Skip to content

WAF for curl requests/partial json/libddwaf v2 - #3467

Draft
cataphract wants to merge 19 commits into
masterfrom
glopes/appsec-curl
Draft

cataphract wants to merge 19 commits into
masterfrom
glopes/appsec-curl

Conversation

@cataphract

Copy link
Copy Markdown
Contributor

Description

Reviewer checklist

  • Test coverage seems ok.
  • Appropriate labels assigned.

@cataphract
cataphract requested review from a team as code owners October 31, 2025 14:58
@cataphract
cataphract marked this pull request as draft October 31, 2025 14:58
@pr-commenter

pr-commenter Bot commented Oct 31, 2025 •

Copy link
Copy Markdown

Benchmarks [ tracer ]

Benchmark execution time: 2026-12-04 15:34:50

Comparing candidate commit 4566772 in PR branch glopes/appsec-curl with baseline commit 480d82a in branch master.

📊 Benchmarking dashboard

Found 0 performance improvements and 1 performance regressions! Performance is the same for 217 metrics, 0 unstable metrics.

Explanation

This is an A/B test comparing a candidate commit's performance against that of a baseline commit. Performance changes are noted in the tables below as:

  • 🟩 = significantly better candidate vs. baseline
  • 🟥 = significantly worse candidate vs. baseline

We compute a confidence interval (CI) over the relative difference of means between metrics from the candidate and baseline commits, considering the baseline as the reference.

If the CI is entirely outside the configured SIGNIFICANT_IMPACT_THRESHOLD (or the deprecated UNCONFIDENCE_THRESHOLD), the change is considered significant.

Feel free to reach out to #apm-benchmarking-platform on Slack if you have any questions.

More details about the CI and significant changes

You can imagine this CI as a range of values that is likely to contain the true difference of means between the candidate and baseline commits.

CIs of the difference of means are often centered around 0%, because often changes are not that big:

---------------------------------(------|---^--------)-------------------------------->
                              -0.6%    0%  0.3%     +1.2%
                                 |          |        |
         lower bound of the CI --'          |        |
sample mean (center of the CI) -------------'        |
         upper bound of the CI ----------------------'

As described above, a change is considered significant if the CI is entirely outside the configured SIGNIFICANT_IMPACT_THRESHOLD (or the deprecated UNCONFIDENCE_THRESHOLD).

For instance, for an execution time metric, this confidence interval indicates a significantly worse performance:

----------------------------------------|---------|---(---------^---------)---------->
                                       0%        1%  1.3%      2.2%      3.1%
                                                  |   |         |         |
       significant impact threshold --------------'   |         |         |
                      lower bound of CI --------------'         |         |
       sample mean (center of the CI) --------------------------'         |
                      upper bound of CI ----------------------------------'

scenario:SamplingRuleMatchingBench/benchRegexMatching4-opcache

  • 🟥 execution_time [+89.934ns; +176.866ns] or [+5.244%; +10.313%]

@codecov-commenter

codecov-commenter commented Oct 31, 2025 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 52.32059% with 2332 lines in your changes missing coverage. Please review.
✅ Project coverage is 58.91%. Comparing base (ed3089e) to head (bbc593e).

Files with missing lines Patch % Lines
appsec/helper-rust/src/client.rs 0.00% 564 Missing ⚠️
appsec/helper-rust/src/service.rs 53.15% 215 Missing ⚠️
appsec/helper-rust/src/service/waf_diag.rs 20.58% 189 Missing ⚠️
appsec/helper-rust/src/lib.rs 0.00% 186 Missing ⚠️
appsec/helper-rust/src/client/metrics.rs 0.00% 138 Missing ⚠️
appsec/helper-rust/src/rc.rs 73.73% 125 Missing ⚠️
appsec/helper-rust/src/telemetry/sidecar.rs 0.00% 96 Missing ⚠️
appsec/helper-rust/src/rc_notify.rs 0.00% 86 Missing ⚠️
appsec/helper-rust/src/service/limiter.rs 8.33% 66 Missing ⚠️
appsec/src/extension/json_truncated_parser.cpp 73.72% 47 Missing and 15 partials ⚠️
... and 23 more

❌ Your patch status has failed because the patch coverage (52.32%) is below the target coverage (90.00%). You can increase the patch coverage or adjust the target coverage.

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #3467      +/-   ##
==========================================
- Coverage   62.02%   58.91%   -3.12%     
==========================================
  Files         140      162      +22     
  Lines       13309    17895    +4586     
  Branches     1762     1847      +85     
==========================================
+ Hits         8255    10542    +2287     
- Misses       4265     6521    +2256     
- Partials      789      832      +43     
Flag Coverage Δ
helper-rust-unit 48.81% <48.81%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
appsec/src/extension/commands/request_exec.c 100.00% <100.00%> (ø)
appsec/src/extension/configuration.h 100.00% <ø> (ø)
appsec/src/extension/php_compat.h 100.00% <ø> (ø)
appsec/src/extension/request_abort.c 70.28% <100.00%> (ø)
appsec/src/extension/user_tracking.c 75.00% <100.00%> (+0.08%) ⬆️
appsec/src/helper/client.cpp 75.98% <100.00%> (ø)
appsec/src/helper/client.hpp 94.11% <ø> (ø)
appsec/src/helper/engine.cpp 91.73% <100.00%> (ø)
appsec/src/helper/engine.hpp 100.00% <ø> (ø)
appsec/src/helper/json_helper.hpp 50.00% <ø> (ø)
... and 36 more

... and 2 files with indirect coverage changes


Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update ed3089e...bbc593e. Read the comment docs.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@pr-commenter

pr-commenter Bot commented Oct 31, 2025 •

Copy link
Copy Markdown

Benchmarks [ appsec ]

Benchmark execution time: 2026-12-04 15:26:15

Comparing candidate commit 4566772 in PR branch glopes/appsec-curl with baseline commit 480d82a in branch master.

📊 Benchmarking dashboard

Found 0 performance improvements and 0 performance regressions! Performance is the same for 12 metrics, 0 unstable metrics.

Explanation

This is an A/B test comparing a candidate commit's performance against that of a baseline commit. Performance changes are noted in the tables below as:

  • 🟩 = significantly better candidate vs. baseline
  • 🟥 = significantly worse candidate vs. baseline

We compute a confidence interval (CI) over the relative difference of means between metrics from the candidate and baseline commits, considering the baseline as the reference.

If the CI is entirely outside the configured SIGNIFICANT_IMPACT_THRESHOLD (or the deprecated UNCONFIDENCE_THRESHOLD), the change is considered significant.

Feel free to reach out to #apm-benchmarking-platform on Slack if you have any questions.

More details about the CI and significant changes

You can imagine this CI as a range of values that is likely to contain the true difference of means between the candidate and baseline commits.

CIs of the difference of means are often centered around 0%, because often changes are not that big:

---------------------------------(------|---^--------)-------------------------------->
                              -0.6%    0%  0.3%     +1.2%
                                 |          |        |
         lower bound of the CI --'          |        |
sample mean (center of the CI) -------------'        |
         upper bound of the CI ----------------------'

As described above, a change is considered significant if the CI is entirely outside the configured SIGNIFICANT_IMPACT_THRESHOLD (or the deprecated UNCONFIDENCE_THRESHOLD).

For instance, for an execution time metric, this confidence interval indicates a significantly worse performance:

----------------------------------------|---------|---(---------^---------)---------->
                                       0%        1%  1.3%      2.2%      3.1%
                                                  |   |         |         |
       significant impact threshold --------------'   |         |         |
                      lower bound of CI --------------'         |         |
       sample mean (center of the CI) --------------------------'         |
                      upper bound of CI ----------------------------------'

@cataphract
cataphract force-pushed the glopes/appsec-curl branch 2 times, most recently from 88dbc85 to 2d9bc56 Compare November 21, 2025 11:57
@cataphract
cataphract force-pushed the glopes/appsec-curl branch 2 times, most recently from bb17297 to 947897c Compare December 24, 2025 16:22
@cataphract
cataphract force-pushed the glopes/appsec-curl branch 2 times, most recently from 59377d6 to 55d4bd0 Compare January 5, 2026 16:17
@datadog-official

datadog-official Bot commented Jan 16, 2026 •

Copy link
Copy Markdown

Pipelines  Tests

✨ Unblock PR with BitsAI

❌ Errors

Your PR has failed checks. Please review the issues below and take necessary action before merging.

🚦 4 Pipeline jobs failed

DataDog/apm-reliability/dd-trace-php | framework test: [flow] — 🔧 Needs a code fix, caused by this PR

View more details · View in GitLab

DataDog/apm-reliability/dd-trace-php | framework test: [flow_no_ddtrace] — 🔧 Needs a code fix, caused by this PR

View more details · View in GitLab

DataDog/apm-reliability/dd-trace-php | merge-gate — 🔧 Needs a code fix, caused by this PR

View more details · View in GitLab

View all 4 failed jobs.

ℹ️ Info

No other issues found (see more)

🧪 All tests passed
❄️ No new flaky tests detected

🎯 Code Coverage (details)
• Patch Coverage: 72.96%
• Overall Coverage: 79.39% (-1.50%)

Useful? React with 👍 / 👎

This comment will be updated automatically if new data arrives.
🔗 Commit SHA: 4566772 | Docs | View more details | Give us feedback!

@cataphract
cataphract force-pushed the glopes/appsec-curl branch 3 times, most recently from bbc593e to 192a4a1 Compare January 16, 2026 17:33
cataphract and others added 10 commits November 28, 2026 11:37
A downstream HTTP request (e.g. one made with curl) is evaluated by the
WAF in several steps: the request headers and body, then the response
status and headers, then the response body. Rules can match on data
from several of these steps, so all of them have to be evaluated in the
same WAF subcontext, which is discarded once the response is complete.
Neither the main request context (where the data would leak into later
evaluations) nor the transient subcontext push_addresses uses by default
(which is dropped after each call) fit.

The request_exec message and the helper already support this through
the subctx_id and subctx_last_call options; only push_addresses did not
expose them. Its second argument may now be an array with the keys
rasp_rule, rule_variant, subctx_id and subctx_last_call. An options
array was preferred to more positional parameters because the
combinations are sparse (subcontext calls have no RASP rule, RASP calls
have no subcontext) and named arguments are not available on PHP 7. The
string form keeps working unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
RFC-1062 has AppSec analyse the HTTP requests an application makes to
other services (downstream requests): their URL, headers and bodies are
run through the WAF as server.io.net.* addresses. The interception is
done in the userland curl integration, which needs a few things from
the extension:

- should_send_downstream_bodies(), deciding whether the bodies of a
  given downstream request should be analysed. Parsing and sending
  bodies is expensive, so at most
  DD_API_SECURITY_MAX_DOWNSTREAM_REQUEST_BODY_ANALYSIS requests per
  request (default 1) are picked, sampled at
  DD_API_SECURITY_DOWNSTREAM_BODY_ANALYSIS_SAMPLE_RATE (default 0.5).
  Sampling hashes a per-thread counter (Knuth multiplicative hashing)
  instead of drawing random numbers, so the choice is deterministic and
  spreads evenly over consecutive candidates. When any body was
  analysed, the root span gets the _dd.appsec.downstream_request metric.
- convert_json() and convert_xml() outside of testing, to parse the
  bodies with the same parsers used for the request body.
- fflush_stdiocast(): when a PHP stream is given to curl (e.g. as
  CURLOPT_FILE), curl writes to a FILE* cast from it, whose buffer must
  be flushed before the data can be read back from PHP.

Additionally, a blocking response no longer sets the response code
before checking whether the headers were already sent. A downstream
request is often made after output has started, and blocking then must
not overwrite the status code that was actually sent (and reported on
the span) with one that never reaches the client.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Implement RFC-1062 for curl: requests made with curl_exec() and
curl_multi_exec() are analysed by the WAF as server.io.net.* addresses
(URL, method, headers, and, for the sampled requests, the bodies), so
that rules can detect and block SSRF-like abuse and malicious responses
from other services.

The interception lives in userland (CurlAppSec.php), loaded by the curl
integration unless AppSec is fully disabled. curl gives no single point
where the whole exchange is visible, so the integration tracks each
handle: curl_setopt()/curl_setopt_array() calls are recorded (hence the
new deferred-loading hooks for them, curl_init() and
curl_multi_add_handle()), and on submission the handle is wrapped so
that headers and body can be captured without changing what the
application sees: the configured header/write/read callbacks, files
and streams are wrapped or filtered instead of replaced, and
CURLOPT_RETURNTRANSFER output is read back afterwards. Bodies are
analysed up to DD_APPSEC_MAX_BODY_BUFF_SIZE bytes; a response body that
reaches the limit is analysed right away, together with the response
headers already received, without waiting for the transfer to end.

Every downstream request gets its own WAF subcontext: the request data,
then the response status and headers, then the response body are
pushed into it, and it is released with the last call. Using the main
context would let data of one downstream request influence the
evaluation of later ones; transient subcontexts would not let rules
correlate request and response data.

The groovy WafSubcontext tests run a small HTTP server inside the test
container, which curl_requests.php calls in many variants (easy and
multi handles, callbacks, files, return transfer, redirects), checking
both that the CUSTOM-* test rules block and that the application sees
unchanged behaviour when nothing matches.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The AppSec extension is about to analyse downstream requests made
through ext/curl by calling into libcurl itself: setting options on a
handle, reading its info, asking for its version. That is only sound if
those calls act on the very libcurl instance ext/curl uses. A second
copy of libcurl in the process (libcurl.a linked into curl.so, an
LD_PRELOAD of another build) would receive handles it never created,
and the calls would read or write memory with the wrong layout. So
before anything can call libcurl, the extension must establish which
instance ext/curl is bound to, and stay off whenever it cannot.

The detection runs once, from the zend extension startup hook, which
runs after every module's MINIT. That ordering matters: ext/curl's
MINIT has called curl_global_init by then, so the GOT slot of that
function is bound even under lazy binding. The procedure finds the
object that contains ext/curl's module startup function, locates its
relocation for curl_global_init, and follows the slot to the object it
points into. The verdict is "on" only if that object is a different
one from ext/curl's own and its DT_SONAME is among ext/curl's
DT_NEEDED entries. A libcurl linked into ext/curl binds the slot to
ext/curl itself; one preloaded in place of the real library binds it to
an object ext/curl does not depend on; static builds with hidden
symbols have no relocation at all. All of these end up off, with a
human-readable reason kept for the debug log and for tests. When the
verdict is on, the functions are resolved with dlsym on the handle of
that exact object (opened by path with RTLD_NOLOAD, never by SONAME),
and every resolved pointer must lie inside it.

Several alternatives were rejected. Linking ddtrace.so against libcurl
would add a DT_NEEDED and a build-time dependency the tracer must not
have, and would resolve to whichever libcurl the dynamic linker picks
rather than the one ext/curl uses; hence the few libcurl types and
function signatures are declared by hand, relying on libcurl's stable
ABI. A plain dlsym(RTLD_DEFAULT) has the very problem described
above. Anchoring on the zend_function handlers of the curl_* PHP
functions would point into ddtrace.so for those it replaces, so the
anchor is the module entry's startup function, whose pointer targets
ext/curl. The dynamic section is parsed by hand, tolerating both the
relocated d_ptr values glibc leaves and the unrelocated ones of musl
or of a read-only dynamic section, since ddtrace.so is built against
musl and also loaded by glibc.

The layer is supported on Linux for x86_64 and aarch64, under glibc and
musl; elsewhere detection reports "unsupported platform" and stays off.
The detection core is PHP-agnostic (no Zend or libcurl headers) so it
can be built into a standalone program.

Known limit: a preload that interposes only some curl_* functions with
another libcurl's code, while curl_global_init stays bound normally, is
not detected. The only binding check is the one on curl_global_init.

Testing. The CI PHP builds link ext/curl in one or two ways only, so a
harness (make curl_linkage_test, Linux only, not part of xtest)
builds fake libcurl and fake ext/curl objects without PHP: dynamic with
lazy, now and -fno-plt binding, static with exported and with hidden
symbols, under-linked, preloaded, read-only dynamic sections, and
checks the verdict for each. A phpt checks what the real extension
reports through a testing function, and that the layer is off when
ext/curl is absent or unbound.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
To analyse a downstream request natively we have to talk to libcurl
about the transfer that a PHP curl handle stands for, and for that we
need the `CURL *` inside it. ext/curl keeps it in a private struct
(`php_curl`) whose headers are not available to us, and which we do not
want to compile against: the layer must work with whatever ext/curl the
process loaded, from PHP 7.0 to 8.5. Getting the pointer wrong is not a
bug that shows up as a wrong answer. It is a crash inside the
application, so the lookup has to be able to say no, and to say it
without side effects.

The layout facts we rely on are few. On PHP 8, CurlHandle is final and
its zend_object is the last member of `php_curl`, with the handler
table's `offset` holding the distance, which is how ext/curl itself
gets from the object back to the struct. On PHP 7, the "curl" resource
points directly at `php_curl`. In every release the first member is
`CURL *cp`. The handle type is looked up at startup, after all MINITs
and after the libcurl linkage has been established by the previous
commit; if it is not found, or the linkage is off, the whole feature is
off. We do this lookup ourselves instead of reusing the tracer's
`curl_ce`, which is only filled when the tracer is enabled and, on
PHP 7, only after the first curl_init().

Each candidate is validated on its own, with no process-wide state, so
one bad handle costs one skipped transfer and never turns the feature
off for everybody. The offset must be a plausible one (below a fixed
bound). The `CURL *` must be non-NULL (a NULL one is a live handle
without a transfer, such as a denied server push, and is not an
error), and must point to memory that looks like a live easy handle.
Memory is read only through a fault-safe probe, a
process_vm_readv(2) on our own process, rather than by dereferencing
or by consulting /proc/self/maps: it is one syscall, the kernel itself
refuses non-canonical and kernel-half addresses, and we do no range or
pointer-tag arithmetic of our own, so MTE and HWASan systems keep
working. When libcurl is at least 7.75.0, the first member of
`struct Curl_easy` is CURLEASY_MAGIC_NUMBER and is checked; older
libcurls have it at a build-dependent offset, so there the probe alone
has to do.

Where process_vm_readv is unavailable or refused (ENOSYS or EPERM: an
old kernel, or a seccomp filter of the container runtime), the probe
falls back to write(2) of the range into a pipe. The kernel copies it
with the same fault-safe copy_from_user and fails with EFAULT instead of
faulting, and reading the pipe back yields the bytes. The fallback is
needed because Docker's default seccomp profile only allows
process_vm_readv with CAP_SYS_PTRACE, and the dind runners of our CI
refuse it, so without it every handle there would be unverified. Only
when the pipe probe fails for another reason than EFAULT as well is the
result "unverified", not "invalid", because it says nothing about the
pointer, and the next handle is checked again. The known limit is a
seccomp filter that kills the process on one of these syscalls; we
cannot detect that and accept it.

A skipped transfer is explained by a debug line, and here the logging
needed a new facility. The usual `mlog` goes through PHP's error
reporting by default, which would turn a skip into a warning visible to
the application (error handlers, error_get_last(), display_errors),
and may run PHP code from inside a libcurl callback. `mlog_no_php`
writes only to the log file or syslog and is silent with
php_error_reporting. It is added here as the first user needs it, and
later commits use it for everything that runs where PHP must not.

Nothing calls the new API yet except the testing functions. The
validators are covered by a C harness (`make curl_handle_validate_test`)
that drives them with a fake probe: alignment, EFAULT, refused probe,
the magic number, and the version boundary.

A second harness installs real seccomp filters: with
process_vm_readv refused by EPERM or ENOSYS the pipe probe still tells
valid from invalid addresses, and with write refused as well the probe
reports itself unavailable.

The phpt tests cover
live handles from curl_init() and curl_copy_handle(), closed handles
(not_curl on PHP 7, still valid on PHP 8), and, with injected bad
values, a wrong offset, an unmapped pointer, a pointer without the
magic number and the debug-only logging. In each, only that transfer is
skipped and the following handle is validated afresh.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Analysing the bodies of downstream requests costs memory and WAF time,
so RFC-1062 caps how many requests per incoming request get their
bodies analysed and samples a fraction of the candidates. The native
curl analysis that this series builds decides this per transfer, from
inside libcurl's callbacks, so the decision has to live in C. The
existing one is a PHP function that the userland curl integration
calls, and it deviates from the RFC in ways that matter once the
decision is native.

The new dd_should_send_downstream_bodies() follows Appendix A to the
letter: a transfer is sampled iff (count * 11400714819323199488) %
UINT64_MAX <= round(rate * UINT64_MAX), with the product wrapping at
2^64 and the largest double below 2^64 standing in for UINT64_MAX, as
the Appendix prescribes. The old code used a different multiplier and
a strict comparison without the modulo, which does not reproduce the
reference vectors. Rates 0 and 1 are decided without the formula, so
rate 0 never samples and rate 1 always does.

The counter is per thread and never reset per request, so that
sampling spreads over consecutive requests of a worker. It starts at a
random value drawn on the first decision in the worker rather than in
MINIT: pre-forked FPM workers inherit MINIT state and would otherwise
sample in lockstep. The seed is read from /dev/urandom directly
instead of php_random_bytes(), which can raise warnings or exceptions
visible to PHP and is not something a callback may do; without
/dev/urandom (a chroot) a clock, pid and address mix is good enough to
keep workers apart.

The two configuration values are now read in one place, where an
invalid value is replaced by its default instead of being cast: a
negative limit would have become "unlimited" through the unsigned
conversion, and a rate outside [0, 1] (or NaN) an undefined
double-to-integer conversion. The value readers neither allocate nor
log, so callbacks can use them; the public readers add a warning that
is logged once per process and variable. Limit 0 is valid and means no
bodies.

Two accounting changes go with it. The limit counts slots taken by
picked transfers, and a transfer that ends up sending no body gives
its slot back (dd_downstream_release_slot), so it does not starve
later ones. The _dd.appsec.downstream_request span metric is a
separate count of the transfers that actually sent a body, instead of
the constant 1.0 it used to be. The slot is taken only after the debug
log, because logging allocates and may bail out, which would leak a
slot nobody releases.

The userland function datadog\appsec\should_send_downstream_bodies
stays as a thin wrapper over the C decision, counting a true result as
a body analysed. CurlAppSec.php still calls it until the native
analysis replaces that code, and removing it now would either make
ddtrace.so fail to load or silently stop the sampling of userland
curl. The wrapper is deleted together with its last caller.

The decision is covered by phpt tests that use new testing-only
functions (the decision itself, and a getter and setter of the
counter, since the random start would otherwise make the vectors
untestable): the Appendix A vectors at several rates and the
endpoints, the validation and warn-once behaviour of both settings, and
a pcntl_fork test showing that two children of an unseeded parent draw
different seeds. The existing downstream_bodies tests are adapted to
the testing function and the new metric semantics.

Known limit: the counter is per thread, not per process, so under ZTS
each thread samples its own sequence, which is what the RFC's per
worker model implies.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Evaluating a downstream curl request natively will need two things
from the extension-to-helper protocol that it cannot do today. The
first is to send a response body that the extension has already
parsed. A JSON or XML body is decoded once by the extension, and the
result is already MessagePack when it reaches request_exec. Pushing
it through the zval serialiser would decode it into PHP values, only
to encode it again, and would subject it to the serialiser's depth,
element and string limits. Those limits are tuned for the small
address maps of ordinary calls, and the body has its own, separate
size policy. The second need is to end a subcontext that never got
data. A downstream request that fails or is cut short has no response
to analyse, but the helper still has to drop its subcontext, or it
would live until the end of the request.

This commit adds both, as protocol groundwork that nothing uses yet.

request_exec gains a list of raw entries (an address name plus its
encoded value). They are appended to the data map after the entries
that come from the zend_array, and are counted in the map header.
They go through no limits, which keep applying to the array alone.
The map is always written as a map, even when the array is
sequential, because raw entries are named. To get this the array
writer takes the raw entries as parameters, and a new public entry
point passes them. The existing entry point passes none, so the other
callers are unchanged. I chose to extend that writer rather than to
write a second one, so that the limits, the truncation flag and the
sequential-versus-map decision stay in one place. The extension can
also set the truncation flag, which it can already read. A downstream
call can then save the flag, run, and restore it, so that the
truncation of one hop's data does not leak into the flag reported for
the request.

A call with no data and no raw entries used to be refused with "empty
payload". It is still refused, unless it is the last call of a
subcontext, which is the data-less call described above. It is then
sent as an empty map, so the helper reads it as empty WAF data. In
the helper, a last call that has a subcontext id and no data removes
the subcontext and returns an empty result: no WAF run, no triggers,
no actions, no keep, and no RASP metric. Running the WAF with nothing
to evaluate would only have cost time and counted an evaluation that
did not happen. Using the existing last-call flag, rather than a new
command or a new field, keeps the wire format unchanged: an older
helper would see an empty map, which is what it already handled.

Limits: the raw entries are trusted to be valid MessagePack, since
only the extension builds them, so there is no validation in the
writer. A data-less last call without a subcontext id is still
refused, as before.

Tested with three helper unit tests (cargo test -p helper-rust
subctx_last_call): a data-less last call drops the subcontext with no
WAF run and no RASP metric, it is harmless on an unknown subcontext,
and a last call with data still runs the WAF and drops the subcontext.
The extension side has no test of its own here. It is exercised end to
end once downstream requests use it, in later commits.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
To analyse the response of a downstream request without PHP's help,
the layer has to sit between libcurl and ext/curl: libcurl calls the
write, header and read callbacks of a handle, and the layer needs to
see (and, for the request body, supply) the bytes that flow through
them. ext/curl keeps those callbacks static and libcurl has no getter
for them, so the only way to read what a handle holds, and to put our
function in its place for the duration of a transfer, is to know where
in libcurl's private Curl_easy the slots live. That layout changes
between libcurl builds, and we cannot include its private header.

This commit finds the offsets at startup, right after the linkage
detection. On a throwaway handle that never performs a transfer (after
one, libcurl copies the read slots into its transfer state and they
show up twice), the calibration sets distinct sentinel functions and
data pointers with curl_easy_setopt, scans the block bounded by
malloc_usable_size with pointer stride, and requires each sentinel
exactly once. It then repeats with a second set of sentinels, which
must be found at the same offsets. Anything else is a refusal: the
reason is logged and the layer stays off, since no hook is installed
without accepted offsets.

Scanning was chosen over hardcoding offsets per libcurl version
because the distributions patch and configure libcurl in ways a
version table cannot capture, and over parsing debug info because
none is available on production hosts. The price is a set of
conditions under which the scan is not trustworthy, and those are
refused up front: a libcurl built with CURLDEBUG (its handles are not
allocator blocks), an allocator without malloc_usable_size, or a usable
size that cannot be a handle's. Below libcurl 7.80 only the read slots
are used, so only they must be found and the other offsets stay 0.

The slot primitives are in the same change because they are defined
by the same offsets and are tested against the same libcurl: guard
(each used slot holds the pristine function or ours, and its data is
the handle's own php_curl), install, normalise (a copy made while ours
were installed carries them and gets the pristine function back) and
restore (a slot overwritten since, as curl_reset() does, is left
alone). The pristine functions cannot be looked up, so each is learnt
from the first handle that passes the guard, and then never changes: a
slot that later holds something else is not understood and the handle
is not interposed. Nothing in the extension calls these primitives
yet; later commits do.

Both modules are PHP- and libcurl-header-agnostic, so they are also
built into a standalone harness that runs against the libcurl that
dlopen finds (LD_LIBRARY_PATH selects another build) and against a fake
libcurl whose setopt stores values in ways that must be refused:
duplicated, shifted, truncated or inconsistent between rounds. The
harness, run with `make curl_calibrate_test`, also covers the slot
primitives. Its slot cases follow the libcurl they run against: below
7.80 only the read slot is interposed, so the write and header slots are
expected to stay unused (not OTHER, OURS or PRISTINE), and the case that
feeds the guard a foreign write function is skipped. The linkage info
phpt checks the accepted calibration and its offsets in the real
extension, and a testing-only environment switch forces a refusal so
that the layer-off path can be tested.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
cataphract and others added 9 commits November 30, 2026 17:31
The native analysis of downstream requests has to see what libcurl
exchanges: the response head of every hop of a redirect chain and the
body of the last one. The only place to see it is a pair of callbacks
(header and write) plus the PREREQ callback that libcurl calls when a
hop starts. Their interplay has rules that are easy to get wrong and
hard to exercise through a real transfer: with CURLOPT_HEADER libcurl
hands the head lines to the write function too, always before the
header function; the CONNECT head of a proxy tunnel shows up before hop
0 and, on later hops, inside the body phase of the previous one; 1xx
heads start no hop; trailers follow a complete head; chunks arrive
split anywhere.

This commit adds the part of the collector that implements those rules
and nothing else. It holds the head of the current hop (capped, with
whole lines dropped and a truncation flag rather than cut lines), reads
the status from the first line even if that line was dropped, tracks
the phase (head or body) so that head bytes written under CURLOPT_HEADER
are not taken for body, counts hops at PREREQ with a sanity limit, and
passes body bytes to a sink. The standard sink is a buffer with a cap:
it copies at most the cap and records that the rest was not analysed,
and copies nothing at all unless the transfer was sampled. Only the last
hop's body is kept; the next PREREQ releases the previous one.

The collector is deliberately pure C. It includes neither Zend nor
libcurl headers, and all growth goes through an injected allocator that
may refuse. A refusal (or a sink that refuses a chunk) stops the
collector, releases its buffers and sets oom; the transfer itself is
never touched, and the collector runs no PHP code and needs no
zend_try. Injecting the allocator, instead of calling erealloc
directly, is what lets the same file be compiled into a standalone
program where allocation failures can be forced at every point. The
alternatives, a collector written against PHP's memory manager or one
tied to libcurl types, would have been testable only through full
transfers, which cannot reach the cases above reliably.

Nothing feeds the collector yet; the commits that follow connect it to
the interposed callbacks. Known limits: it cannot tell that the app
replaced our PREREQ mid-transfer, so the caller must stop it
explicitly (dd_curl_collect_stop), and the body of a hop whose CONNECT
head leaked into the previous body phase is simply dropped at the next
PREREQ.

It is tested by a C harness (make curl_collect_test) built with
AddressSanitizer and UndefinedBehaviorSanitizer when available. It
covers the phase rule, split chunks at every offset, 1xx and CONNECT
heads, caps, hop limits and allocation failure injection at each
allocation. There are no phpt tests at this point since nothing in PHP
uses the collector yet.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Before the native layer can ask the WAF about a downstream request, it
has to know what request ext/curl is going to send and when. PHP gives
no way to read that back: libcurl has almost no getters for the options
the analysis needs (method, body, headers, cookies, redirect policy),
and ext/curl keeps them in private structs whose layout changes across
PHP versions. So the layer must record them as the application sets
them, and must model, from the PHP-level calls alone, the moment at
which libcurl starts a transfer.

Hooks on curl_init, curl_copy_handle, curl_reset, curl_setopt,
curl_setopt_array, curl_exec and the curl_multi_* functions feed a
per-handle state. Options are recorded only after ext/curl accepted
them, so a rejected value never leaks into the model, and only the
options that matter are kept: no credentials, no VERBOSE, no debug or
app callbacks. The method is tracked as libcurl derives it from the
interplay of POST, PUT, UPLOAD, NOBODY, HTTPGET and POSTFIELDS, since
the last write does not always win. When the model cannot know what
libcurl will do (an option applied under a conversion we do not
recognise, a curl_setopt that threw halfway, an array body whose
effect on a previous string body is unclear) the state says "unsure"
rather than guessing, and the handle is not observed. Each such case
has a named skip reason, so the later commits and the tests can tell
why a transfer was left alone.

The state lives in weak maps keyed by the handle and holds values
only, never PHP objects passed to curl_setopt. Keeping an object would
delay the application's destructors and could create reference cycles
that keep handles alive. Object values for the URL and, on PHP 8,
POSTFIELDS are converted with __toString once by the hook, because
calling it a second time could show different text than what ext/curl
used. Other objects make the handle unobserved.

A transfer begins at curl_exec, or at the first curl_multi_exec after
curl_multi_add_handle, since libcurl reads the options only then. Adds
make a handle pending in its multi; a failed add, a removal or closing
the multi drops the pending entry without starting anything. Multi
handles get keys that are never reused within a request, so state of a
closed multi cannot be confused with a later one. Completion of a
transfer is also modelled (curl_multi_info_read, removal, or
curl_multi_exec returning with nothing running).

An application callback invoked by libcurl may itself call curl_exec
or curl_setopt on another handle. Those nested hook entries do
nothing: no recording of transfers, no evaluation, nothing to defer.
This needs only a depth counter around the hooks that run libcurl, so
curl_eval.c/h start with just that and grow in later commits. The
nested case is not analysed; that is the deliberate simplification
over tracking an arbitrary stack of transfers.

Observation is off unless linkage and handle validation (the previous
commits) succeeded, and when RASP is disabled. In those cases the
hooks are not even installed.

PHP 8.6 removed zend_exception_save() and zend_exception_restore()
together with EG(prev_exception). Where the hooks set aside an exception
the app left pending, they use dd_exception_save() and
dd_exception_restore() from php_helpers.h, which call those functions up
to PHP 8.5 and from 8.6 keep the exception in a slot owned by the
caller.

Nothing is interposed yet and no WAF call is made: this commit only
observes, so the userland analysis keeps working unchanged. Later
commits install callbacks in libcurl's slots and evaluate the hops.

The tests run a local HTTP server and a harness that dumps the
recorded options and the tracked transfers. They cover recorded
options and the method rules, objects as values, array bodies and
resources as POSTFIELDS, setopt_array that throws, curl_reset, and the
cases where the layer is off (RASP off, calibration refused, handle
probe unavailable).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The earlier commits can see which curl handles exist, what options
they carry and when a transfer starts, but nothing yet looks at what
comes back. The response of a downstream request is what the analysis
needs to tag, and ext/curl gives no way to get it: its write, header
and read functions are static and the app's own callbacks, CURLOPT_FILE
and RETURNTRANSFER all end up behind them. This commit puts our own
functions in libcurl's three callback slots, using the slot locations
the calibration step already learnt, and feeds what passes through
them to the collector added before. It still makes no WAF call; the
collected data is only visible through curl_downstream_dump() in the
testing build.

Installation is per transfer, not per setopt. At every transfer start,
observed or skipped, the handle is first normalised: a slot that
still holds one of our functions (left by a copy, a reset or an
earlier transfer) gets ext/curl's function back, and our PREREQ
function is removed unless the app set its own, in which case the
transfer is skipped rather than overridden. A guard then requires that
each slot holds ext/curl's function or ours and that its data pointer
is the handle's own php_curl *; a handle that fails it is not
observed. Only then are our functions installed, before the first
perform, because libcurl copies the read slot into its transfer state
once, when the transfer starts. At the end only slots that still hold
ours are restored. The rule is that the layer never acts on a handle
whose callbacks it does not understand and leaves the handle as
ext/curl configured it. Hooking setopt to keep our functions installed
permanently was rejected: it would make every later option change a
race with the slots, and it would leave our code on handles that are
never analysed.

Our functions run inside libcurl for any handle that carries them,
including copies, pushed handles and DoH handles that inherited them,
so the user data is never trusted: it is only a key into a table of
the transfers registered in this thread, and a call that finds nothing
is forwarded unchanged. For a registered transfer, every call goes at
once, with the same arguments, to ext/curl's function, and its return
value is returned unmodified. Only then is what that function took
appended to the collector (a short write or a pause is not counted, as
libcurl will redeliver that data), and the transfer is looked up again
because the app's callback may have ended it meanwhile. Nothing is
held back or altered, so output and callbacks are identical with and
without the extension, in every output mode. The callbacks run no PHP
code, no WAF call and no zend_try: the collector only appends to
capped buffers.

Hops are marked with our CURLOPT_PREREQFUNCTION (libcurl 7.80 and
later), which libcurl calls before each request of a transfer is sent.
It has no CURL * argument, so it carries an id that is resolved in a
table of live transfers; ids are never reused, so a copy that kept a
stale PREREQDATA cannot resolve to someone else's state. Each PREREQ
starts a new hop in the collector (new head, previous body dropped).
Copies made with curl_copy_handle() or a PHP 8 clone while ours are
installed are cleaned in the copy by a new call from the copy hook.
Below 7.80 only the read slot is used and hops are not marked.

Memory is the other thing that must not go wrong inside libcurl. The
collector's allocator now checks the request's memory limit and
refuses instead of raising a fatal error, which would longjmp through
libcurl; on refusal the collector stops collecting for that transfer
and the original call is unaffected. The check is the one the body
parser already had, so it moves to php_helpers as dd_emalloc_fits and
body_parser.c uses it from there.

Known limits: a curl_reset() while a transfer is in flight overwrites
our slots, so that transfer is observed only up to that point, without
corruption. Other allocations made inside callbacks are not audited.
With CURLOPT_HEADER on libcurl 8.5 or later, trailers of a chunked
response reach the body copy and are accepted as such. No hook runs
before PREREQ, so the connection to a redirect target already exists
when its hop begins. Without CURLOPT_ACCEPT_ENCODING the compressed
bytes are collected as they are.

The behaviour is pinned by tests that compare, with and without the
extension, what the app sees: output, callbacks and return values in
every write mode, chunked and gzip responses, redirects, 1xx and HTTP/2
push, multi handles, pauses, copies, resets in flight, a freed handle
and handles that must be skipped. Further tests check that the slots
are restored and reusable, that the app's own PREREQ function is left
alone, that the collector refuses cleanly at the allocation limit, and
that the body parser keeps passing its out-of-memory tests with the
shared allocator check. The HTTP/2 push test is skipped on libcurl
8.8.0 to 8.12.x, which fail every pushed transfer with CURLE_HTTP2
with or without the extension.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The previous commits built a native layer that observes the transfers
of PHP curl handles without making a single WAF call: it records the
options, tells when a transfer starts, marks the hops of a redirect
chain through CURLOPT_PREREQFUNCTION and collects each hop's response.
This commit puts that data to use. Downstream requests made with
ext/curl are now sent to the WAF from C, as the server.io.net.*
addresses, one WAF subcontext per hop, and a blocking verdict stops
the request.

The analysis used to live in userland (CurlAppSec.php, about two
thousand lines wrapping curl_setopt/curl_exec and friends). That
approach could only see what PHP code told it, duplicated libcurl's
decisions about redirects and methods, and was easy to bypass or to
disturb with the application's own callbacks. It is removed here
rather than kept as a fallback: with both active, every request would
reach the WAF twice. The PHP stub and arginfo of the helper function
it needed, stdiocast.c and the temporary wrapper in request_lifecycle.c
go with it, as do the public registration of convert_json/convert_xml
(CurlAppSec.php was their only user outside tests) and the hooks that
loaded it from CurlIntegration.php and the tracer.

Hop 0 is evaluated before libcurl runs (W1), in the pre-hook of
curl_exec, or of the first curl_multi_exec after curl_multi_add_handle,
which is when libcurl reads the options. The call is built entirely
from the recorded options: URL, method (CURLOPT_CUSTOMREQUEST verbatim,
else derived, and left out when we are not sure), headers, cookie and,
when sampled, the CURLOPT_POSTFIELDS body, parsed as PHP would parse it
for the same content type: urlencoded (new form_urlencoded.c, with
PHP's separators, nesting and limits), JSON, XML, or a PHP array of
fields, including CURLFile entries and objects that PHP would convert
to a string. Nothing is read back from libcurl for this hop, so the
request is evaluated before any connection is made and a block costs no
traffic at all. A transfer whose URL is unknown or not http(s) is not
evaluated.

Every later hop (a redirect, an authentication retry) is evaluated from
our PREREQ callback (W2), just before its request is sent, from
libcurl's own CURLINFO_EFFECTIVE_URL and _METHOD. Each hop's subcontext
is closed by a last call without data, so that the WAF can release it.

The two stages block differently. W1 runs in a PHP function hook, where
unwinding is safe, so it aborts the request there, before the transfer.
W2 runs inside a libcurl callback, which must not unwind through
libcurl: a blocking verdict is only recorded, further evaluation of
that transfer stops, and the block is carried out once libcurl returns
to the hook. Whether bodies are sent at all
follows the sampling decision of the per-request limit and the raw
bodies that earlier commits made available, decided once at W1 and
given back if the transfer ends up sending none.

Known limits: the response is not analysed yet, and bodies read through
CURLOPT_READFUNCTION/INFILE are not either (the next commits); the
request is evaluated as the options describe it, not as libcurl sends
it, so a header added by libcurl itself is not seen. The Groovy
integration suite still expects the userland behaviour (response
blocking, trace meta written by CurlAppSec.php) and is rewritten later
in the series.

The new phpts cover each piece on its own: the URL, method and body
parsing and its parity with PHP, caps and limits, blocking before and
during a multi transfer, slot accounting, closing calls,
identity and debug-function tests that count the WAF calls, and the
skip reasons.

One test depends on the PHP and libcurl in use: curl_setopt() may fail
for a CURLFile name that is no local file, and the request then has no
body. The CURLFile wrappers test probes that with a curl_setopt() call
instead of checking the PHP version.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Until now a downstream request was analysed only on the way out: W1
before the transfer, W2 for each redirect hop, and a closing call
without data that merely ended the hop's WAF subcontext. Rules that
look at what the other server answered (status, headers, a JSON or XML
body) never saw anything, although the observation layer already
collects exactly that data.

Each hop now gets one response call, made when the hop is over: from
the PREREQ of the next hop, before the collector is told that hop
started, or, for the last hop, when the transfer ends. The call carries
the status as a decimal string and the response headers; for the last
hop only, it also carries the body, if the transfer was sampled and the
Content-Type is one we parse (JSON or XML). It has no URL, because the
request call of the same hop already sent it in the same subcontext,
and it is the last call of that subcontext, so it closes the hop and
the closing call without data is only used for a hop that got no
complete response head.

The WAF is run after the response is complete, not while it arrives.
The interposed header and write functions only feed the collector and
run no WAF or PHP code, since they execute inside libcurl, where a
fatal error or a bailout must not be able to unwind. One evaluation
per hop on the whole response also means a rule that combines status,
headers and body sees them together. The body is what libcurl's write
function delivers: de-chunked, and content-decoded when the app set
CURLOPT_ACCEPT_ENCODING. Content-Encoding is deliberately not looked at;
without that option a compressed body fails to parse and is dropped,
and we did not want to add a decompressor for it. Intermediate hops
send no body, as in the userland implementation this series replaces:
a redirect body is not what the app consumes.

A response match only tags the request (the response rule variant is
passed to the helper); it never blocks. By the time the response is
analysed the app's write, header and progress callbacks have already
run, and curl_exec() has a return value that the app may have acted on.
Reporting a block there would mean altering a transfer that already
happened, and turning the effects of the transfer into a lie. Blocking
remains the privilege of the request calls, which run before anything
is sent. A transfer whose request call blocked is not evaluated any
further, and so gets no response call.

Known limits. libcurl before 7.80 has no PREREQ callback: there, the
response of hop 0 is not analysed (its subcontext is closed by the call
without data) and later hops make no call at all. Only the last hop's
body is analysed, up to the body cap, and a truncated body is flagged
as such. A body is sent only for sampled transfers, with the same
per-request budget as the request body.

This commit also brings the request-stage W2 tests
(curl_eval_block_prereq, curl_eval_redirect and curl_eval_auth_retry),
which test the previous commit's behaviour, because their expected
output contains the response calls.

The tests run each behaviour against a local server: the first and last
hop and redirect chains, proxy CONNECT heads (not hops), interim 1xx
responses, status strings, header handling, gzip with and without
decoding, truncation, the cap and the sampling slot, curl_multi
transfers (pending, completed inside a nested call, rejoined, HTTP/2
pause), failed transfers with partial data, and that app callbacks,
CURLOPT_FILE and the return value are exactly those of an unobserved
transfer even when the response matches. The proxy CONNECT test needs
ext/openssl for its TLS server and is skipped without it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The previous commits analyse the request body of a downstream curl
request from the options the app set: CURLOPT_POSTFIELDS is in the
options, so the request-stage call (W1) can carry it. A body that comes
from CURLOPT_READFUNCTION, or from a file given with CURLOPT_INFILE
(upload, PUT), is in no option. It exists only as the bytes ext/curl's
read function hands to libcurl while the request is being sent. Without
this commit such a request reaches the WAF with its URL, method and
headers but no body, which is a real hole: JSON or XML uploaded through
a read function was the one common way to send a body the layer could
not see.

The design puts a gate in the read function the layer already
interposes in libcurl's read slot. For a sampled transfer, with no
POSTFIELDS and a Content-Type of the CURLOPT_HTTPHEADER lines that a
body is analysed for (JSON, XML or urlencoded), W1 arms the gate. While
it fills, libcurl's read calls are served by calling ext/curl's original
read function (the app's callable, or fread() on the INFILE) into
libcurl's own buffer, and the bytes are held rather than passed on.
Holding goes on until EOF, the body cap
(DD_APPSEC_MAX_BODY_BUFF_SIZE) or the upload size libcurl announces
(CURLINFO_CONTENT_LENGTH_UPLOAD, whose size and type vary with the
libcurl version). The gate then makes one request-stage call (W3b) for
hop 0 with the parsed body, and only after that serves the held bytes,
followed by whatever the original function still returns. The WAF thus
sees the body before a single byte of it reaches the server, which is
what allows a block to keep the request from being sent at all. Bytes
that crossed the cap inside the last read are served but not analysed,
and the server always receives exactly the body the app supplied.

The alternatives were worse. Passing bytes through while copying them
would let the request go out before the verdict, so a match could only
be reported, not stopped. Reading the file or calling the app's
function ahead of time, outside libcurl's read calls, would change how
often and with what arguments the app's callable runs. The gate instead
keeps each call of the original function tied to a libcurl read, with
libcurl's length (or less, never past the upload size). The arming
condition is deliberately narrow: a body that can never be analysed, for
example application/octet-stream, is neither held up to the cap nor read
ahead, so the read function forwards to ext/curl's at once, and an
unsampled transfer never arms it.

Like the other calls made from inside libcurl callbacks, W3b never
blocks in place. A blocking verdict makes the read return
CURL_READFUNC_ABORT and is recorded; the block itself is applied once
libcurl has returned to the PHP function hook, the first point where
raising is safe. The gate is turned off when its transfer is destroyed,
when a later hop starts (a 307/308 resend or an authentication retry is
not gated) and at the end of the transfer.

Known exceptions, all of them cases where holding the body would change
what libcurl or the app observes:

- The original function returns CURL_READFUNC_ABORT or
  CURL_READFUNC_PAUSE: the value is returned at once with no WAF call.
  After PAUSE the gate carries on filling once libcurl resumes.
- It returns another value above what was asked: libcurl would fail
  with CURLE_READ_ERROR, so the value is passed on unchanged and nothing
  is analysed. A value above the gate's ask but within libcurl's buffer,
  after bytes were held, would make libcurl take bytes of its buffer in
  place of the held ones, so a body the gate changed must never be sent.
  What the gate returns then depends on the libcurl. Up to 8.6 libcurl
  would have taken the value, so the gate aborts. From 8.7.0 libcurl
  asks the function for no more than is left of the upload, which is
  what the gate asks after the first read, so libcurl without the gate
  would have refused the value with CURLE_READ_ERROR: the gate makes it
  refuse it too, by returning a value above its length (a distinct
  gate step, DD_CURL_GATE_STEP_ERROR).
- With "Expect: 100-continue", libcurl reads only after the server's
  100 (or the timeout), and not at all if the server answers with a
  final status. The gate then holds nothing and makes no call.
- Without CURLOPT_PREREQFUNCTION the layer installs no PREREQ callback,
  so the request only gets the gate's call for hop 0 and no response
  data. Below libcurl 7.80 a gate block is covered by its own test.
- The gate buffers have no memory guard, like the WAF call's own.

The tests exercise the gate against a real local server: the cap with
small READFUNCTION pieces and a large INFILE, a block, PUT, chunked
bodies, Expect, a later hop, upload size 0, content types and the
unsampled case, ABORT and PAUSE, the exact number of calls the app's
callable sees, and the behaviour without a PREREQ function. The later
hop test expects what libcurl does when it cannot rewind the read
function for a 307 resend, which depends on its version: it ends in
CURLE_SEND_FAIL_REWIND, or, from 8.7.0 to 8.13.x, in CURLE_READ_ERROR at
hop 1, and from 7.80.0 to 7.86.0 the rewind fails in the middle of the
response head, so hop 0 is closed by the call without data. The test
compares the errno with the one libcurl gives and checks the calls of
that hop 1 and the closing call of hop 0 apart, so its expected output
is the same on every libcurl.

From PHP 8.6 ext/curl throws a ValueError for an int returned by the
read function other than 0, ABORT or PAUSE and aborts the transfer
before the gate sees it, so the ABORT/PAUSE test expects that outcome
there.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The native analysis makes WAF calls from inside libcurl: the PREREQ
callback (the request call of a redirect hop and the response call of
the hop that is over) and the wrapped read function that fills the
request-body gate. Those calls allocate, and a WAF call can raise a PHP
fatal error, most simply by hitting memory_limit. A fatal error is a
zend_bailout(), a longjmp, and a longjmp out of one of those callbacks
unwinds through libcurl's frames: the easy handle is left mid-transfer,
locks and buffers of libcurl are never released, and the process is in
an undefined state. Until now that was the situation of every code path
above; this commit closes it.

The callbacks no longer let a bailout escape. The WAF calls made from
them run under zend_try. On a catch the transfer records that a bailout
happened and stops making WAF calls (not even the closing call that a
later hook would make). The callback then returns to libcurl as if
nothing was wrong, so libcurl unwinds normally, and the fatal error is
re-raised by the PHP function hook (curl_exec, curl_multi_exec, ...)
that called libcurl, once libcurl has returned. That is the first place
where raising is safe, which is also where blocking verdicts have always
been acted upon, so the two share one settle step. A read function that
hit a bailout makes the gate abort the upload, so the body is not sent
half analysed.

A bailout that cuts the hook itself short, because the transfer was
interrupted by a longjmp from an app callback or by the request ending,
is handled differently: the transfer is released without calling
libcurl and without further WAF calls, since libcurl's state cannot be
trusted and the request is on its way out.

Re-raising is done only by those hooks. The alternative of a VM
interrupt handler that raises it at the next opportunity was rejected:
it would work on one PHP version and not on others (PHP 7.0 has no
reliable interrupt reset), add a second path to reason about, and buy
little, as the hook returns to the VM right after. The consequence is a
known limit: a tracer sandbox around the hook swallows the re-raised
fatal error as it does any fatal error of a hook closure. The
transfer's analysis is stopped nonetheless.

Two pieces of request state are also protected around each downstream
call. The request's data truncation flag is saved and restored, because
a WAF call for a downstream request must not make the request's own
report claim that its input was truncated, and a fatal error swallowed
by a sandbox can skip the restore; the next curl hook entered puts it
back. Likewise a pending exception of the app, thrown by one of its
callbacks inside libcurl, is saved while the WAF call runs and restored
afterwards, including when a bailout cut the call short, so that the
analysis neither runs with an exception pending nor loses it. After a
fatal error outside zend_try the saved exception is deliberately not
restored: raising during shutdown is riskier than dropping it.

Callbacks that run inside libcurl for another transfer still do
nothing, as before, and the memory used by the body gate and by the
WAF call still has no guard of its own: the fatal at the limit is
caught by the same zend_try rather than prevented.

The behaviour is tested with testing hooks that make the Nth downstream
WAF call (optionally once it has completed, as for an allocation while
handling the reply) or the Nth gate allocation raise a fatal error, and
that expose the truncation flag, the number of calls made with an
exception pending, and the C heap in use (glibc only) so that a torn
transfer can be shown to leak none of libcurl's memory. The phpt tests
cover fatal errors in each callback, for curl_exec and the multi
interface, with and without a sandbox, with the memory limit reached for
real (skipped from libcurl 8.14.0, which refuses heads of more than 5000
lines, too few to cross the limit), with handles freed or multi handles
dropped while a transfer is in flight, and with an app exception
pending, blocking or not.

The tests that free a multi handle without curl_multi_close() do not
let a transfer finish in it first, with one exception: libcurl 8.1.0 to
8.9.x crash, with or without the analysis, when a transfer that had
completed in such a multi handle is used again (rewritten in 8.10.0).
The exception is curl_eval_multi_completed_freed.phpt, which does
exactly that, after the response call of the completed transfer, and
skips those versions. The shutdown function of the fatal-in-callback
test removes the in-flight transfer from its multi handle itself, while
the executor is still active: from libcurl 8.18 removing an in-flight
transfer runs the final progress update, which a PHP callback cannot
serve once the executor is shut down.

Which of those exception tests can run depends on the PHP version. The
test of a throwing header callback is split in two. From PHP 8.2
zend_call_function() returns SUCCESS when an exception is pending, the
callback is skipped and the transfer goes on to hop 1. PHP 8.1 returns
FAILURE, so ext/curl warns and aborts the transfer, which is the other
test. The block test throws on the last line of the head so that it
behaves alike on both. From PHP 8.6 ext/curl aborts the transfer when a
callback throws, so no WAF call is ever made with an exception pending
and these tests are skipped there. The header callback test has its own
variant for 8.6 instead, which checks that the exception comes out of
curl_exec() and that the subcontext of hop 0 is still closed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The native analysis of downstream ext/curl requests is only as good as
the tests that exercise it, and two of its properties cannot be seen
from the unit level of the earlier commits. The first is that behaviour
depends on the libcurl the PHP process is bound to: the hooks and the
closing of a hop work differently below 7.80, where the transfer
callbacks the layer relies on are not all available. The second is that
what the real WAF decides (a 403, the matched rule, the tags, the
metrics) and what the downstream server actually received can only be
asserted against the real helper and a real server. This commit adds
both kinds of coverage and replaces the integration suite that still
described the userland implementation.

Every CI PHP image links the distribution's libcurl.so.4, so testing
other versions would normally mean one image per version and a PHP
rebuild for each. Instead a new image, dockerfiles/ci/libcurl, builds
seven libcurl versions (7.79.1 below the 7.80 line, then 7.80.0, 7.88.1,
8.0.1, 8.1.0, 8.5.0 and 8.18.0) into separate prefixes and keeps only
their lib/ directories. A job selects one with LD_LIBRARY_PATH and PHP
is left untouched, which is exactly the situation the linkage detection
of the first commit has to cope with in production. The builds enable
versioned symbols like Debian's: against an unversioned libcurl ld.so
writes a "no version information" line to the stderr of every php
process, and run-tests merges that into the output of each phpt. The
image tag is read from the .env of the image by the pipeline generator,
so adding a version is one Dockerfile line and a bump of that file.

The extension test job now runs the four C harnesses (linkage,
collector, handle probe and calibration) explicitly on every leg: they
are not dependencies of xtest, and a harness that is not built cannot
fail. The pinned leg also builds and runs the calibration harness, as it
scans the private struct of the libcurl the process is bound to, and
checks that the harness printed the version of the pinned build. A
separate leg runs every curl phpt against the 7.79.1 build and checks
that curl_linkage_info.phpt compares the version the extension resolved
with curl_version(). The libcurl builds are handed to that job as an
artifact from a job running in the libcurl image, because the test job
runs in a different image and the system libcurl is still what the
compilers and cmake need while building. On the zts legs and on the
pinned leg, a skip of curl_linkage_info.phpt fails the job: run-tests
exits 0 on a skip, which would otherwise let a layer that is silently
off pass every other curl test by skipping them too.

The Groovy suite is rewritten rather than amended. Under the userland
implementation a response match produced a 403 and the tests read the
push_call meta written by CurlAppSec.php; neither exists now. The new
tests cover request-stage blocks, W2 checks on each redirect hop,
response rules that only tag, and the SSRF and input_truncated
telemetry (a large downstream response must not mark the main request
as truncated; an SSRF block counts as request_blocked without
rule_triggered). Positive controls accompany every prevention test: the
same request with nothing matching must reach the downstream server,
established with a sentinel request rather than a sleep, so a block is
distinguished from a request that never arrived. The test ruleset
(recommended.json) gains the downstream rules, including CUSTOM-013,
which accepts only strings and so matches the response status only
because it is sent as a string.

Response rules tag and never block: that is the design, since the
response body of a downstream call has already been consumed by the
application when the WAF sees it. The helper's tag_only_response_rules
unit tests load the same ruleset and pin this, including the case that
an integer status is not matched by a string rule, so a change to the
type of the status address fails there before the slower Groovy run.

Several of the phpts depend on the libcurl they run against (the
errno of a failed rewind, the hops that exist, HTTP/2 pushes, which
libcurl 8.8.0 to 8.12.x cannot complete, and the memory-limit test from
8.14.0, which refuses heads of more than 5000 lines); they skip or
compare what that libcurl gives.

Known limits: the matrix covers the versions listed, not every libcurl,
and the pinned leg runs the curl phpts only, not the Groovy suite, which
runs against the system libcurl of its image.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The native analysis of downstream ext/curl requests rests on many
decisions that are not visible in the code: which transfers are
analysed and which are skipped, how the pre-send, PREREQ and
response calls map to libcurl's behaviour, what is measured about
each libcurl release, and what the analysis deliberately does not do.
Reviewing the series without them means rediscovering the reasoning
from the commit messages and the tests.

This adds one self-contained HTML document, appsec/docs/
downstream-curl-analysis-design.html. Every statement has an id (G
for guarantees, R for requirement rows of RFC-1062) and every id in
the text links to its definition, so a guarantee can be followed from
the flow of one transfer to the test that verifies it. The open
points are collected in the last section; one remains (musl is only
partly covered).

It is a generated file kept as HTML, not Markdown, because the flow
diagram and the cross-links are the point of it and GitHub does not
render them from Markdown. The sources and the renderer are not part
of the repository: the document is meant to be read, and changed
together with the behaviour it describes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants