A Story of mishandling the Chunked Data (CVE-2018-17082)
A flaw in PHP's Apache module caused request body data to be included in the response when chunked transfer encoding was used with an incorrect Content-Length header. An attacker could potentially leak sensitive request data into the response.
Published on github.com
See, Apache didn't upgrade to HTTP/2.0, which means still the Chunked Transfer Encoding exists. When header field has the option as Transfer-Encoding: chunked and improper Content-Length that is more than required.
The full write-up lives on its author's site
It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.
Context
This is a story about how PHP's Apache SAPI module mishandles chunked request data, published as CVE-2018-17082. The affected component is sapi/apache2handler/sapi_apache2.c, the glue between Apache's request handling and PHP's SAPI layer. The bug is classified as XSS: a request body that PHP never intended to read ends up in the response body.
The report opens by defining the mechanism at the centre of it. Chunked transfer encoding is a streaming data transfer mechanism in HTTP/1.1: the data stream is divided into a series of non-overlapping chunks, sent and received independently, and neither sender nor receiver needs knowledge of the stream outside the chunk currently being processed.
The processing rules matter for the rest of the story. When a Transfer-Encoding field with the value chunked is present in an HTTP message, the body consists of an unspecified number of chunks, a terminating chunk, a trailer, and a final CRLF sequence. Each chunk starts with the number of octets it embeds, expressed as a hexadecimal number in ASCII, followed by optional chunk extensions and a terminating CRLF, then the chunk data, terminated by CRLF. If chunk extensions are present, the chunk size is terminated by a semicolon and followed by the parameters, each also delimited by semicolons.
Setup
The report does not describe a specific deployment, version string or test harness. The precondition it names is architectural: Apache has not upgraded to HTTP/2.0, so chunked transfer encoding still exists on the connection. The trigger is a request that carries Transfer-Encoding: chunked together with an improper Content-Length that is larger than required.
Finding it
Under those conditions the request body mysteriously appears in the response body. The input reaches Apache's bucket brigade even though PHP is not sending it there directly. In fact PHP never sees the input, because Apache does not let it read the body: it throws an error in ap_http_filter instead.
The backtrace in the report shows the path. ap_http_filter is reached from php_apache_sapi_read_post in sapi_apache2.c, which is reached from sapi_read_post_block and sapi_deactivate during php_request_shutdown. The error response is then built through the output filter chain (ap_http_header_filter, ap_content_length_filter, ap_byterange_filter, deflate_out_filter, filter_harness) and written with ap_rvputs and buffer_output in protocol.c. The string being written in the trace is:
\n\n<title>
with nbyte=71, which is the request data surfacing inside the error page.
Exploitation
Step 1: send a chunked request with a mismatched Content-Length
Send a request whose header field carries Transfer-Encoding: chunked and a Content-Length larger than the body actually requires. The report does not give a full request, only these two conditions.
Step 2: let Apache fail the read
Apache refuses to hand the body to PHP and raises an error in ap_http_filter. PHP's shutdown path (sapi_deactivate, called from php_request_shutdown) is already running, and the error response is generated through the output filters.
Step 3: observe the body in the response
The request body appears in the response body. The request body appears in the response body, and the trace shows <title> being written into the output.
Root cause
The report explains it in terms of Apache's bucket and brigade model. A bucket is a container for data of any type: usually a block of memory, but it can be a file on disc or a stream from a dynamic source such as a separate program. Different bucket types hold different kinds of data and have different handling methods; in OOP terms apr_bucket is an abstract base class from which the actual bucket types derive, and there are also metadata buckets. Buckets are never freestanding: they live in bucket brigades, ring-structured containers that may hold any number of buckets. The brigade is the unit passed to and from a filter, and it enables flexible, efficient manipulation of data.
The report's summary of the flaw is that bucket memory is initialised well above and waits until the chunked data enters the memory stream before it is destroyed, and the brigade memory is then mishandled into the path of the response brigade memory. In other words, the request-side brigade and the response-side brigade end up sharing memory they should not.
The handler responsible is in sapi_apache2.c:
if (!parent_req) {
php_apache_request_dtor(r);
ctx->request_processed = 1;
bucket = apr_bucket_eos_create(r->connection->bucket_alloc);
APR_BRIGADE_INSERT_TAIL(brigade, bucket);
The patch adds the missing creation step:
if (!parent_req) {
php_apache_request_dtor(r);
ctx->request_processed = 1;
bucket = apr_bucket_eos_create(r->connection->bucket_alloc);
brigade = apr_brigade_create(r->pool, r->connection->bucket_alloc);
APR_BRIGADE_INSERT_TAIL(brigade, bucket);
Impact
A crafted chunked request can get request data into the response body. The report frames the result as XSS and does not go further into what an attacker could achieve with it, nor does it state which clients or configurations are exploitable beyond the HTTP/1.1 chunked condition.
Fix
The fix adds a line creating a fresh brigade with apr_brigade_create(r->pool, r->connection->bucket_alloc) before inserting the end-of-stream bucket. The change was added to the security repository as commit [redacted] and published as a gist at https://gist.github.com/smalyshev/[redacted].
The embedded video accompanies the write-up; the report gives no further description of its contents.
Variants to test
- Send
Transfer-Encoding: chunkedwith aContent-Lengthlarger than the body on other Apache/PHP deployments. A positive result is request data appearing in the response body, especially inside an error page. - Put HTML markup such as
<title>or a script tag in the chunked body. A positive result is that markup being rendered rather than escaped. - Trigger the error path deliberately, for example by making Apache reject the body read in
ap_http_filter. A positive result is the body leaking into the generated error response. - Test other SAPI handlers that build brigades around request shutdown. A positive result is the same cross-contamination between request and response brigade memory.
What happened, in plain words
A web server called Apache and a programming language called PHP were working together in a way that let a visitor's request data leak back out into the page the server sent in reply. If the visitor put HTML code in that request data, it would appear in the page the server sent back. That kind of flaw is called cross-site scripting, or XSS for short: the site ends up delivering code that an attacker chose, and the victim's browser trusts it because it came from the site.
The bug was given the identifier CVE-2018-17082. A CVE is a public catalogue number for a known security flaw, so people can talk about the same bug unambiguously. The affected piece of software is a file inside PHP called sapi/apache2handler/sapi_apache2.c. Think of it as the adapter between Apache and PHP: Apache receives the request, and this file is the part of PHP that talks to Apache about it.
To follow the story you need one idea first: how a web request can be sent in pieces. That idea is chunked transfer encoding, and the whole bug grows out of it.
What chunked data is
The report starts by defining the mechanism at the centre of everything. Chunked transfer encoding is a streaming data transfer mechanism available in version 1.1 of HTTP, the protocol browsers and servers use to exchange pages and data. In chunked transfer encoding, the data stream is divided into a series of non-overlapping chunks. The chunks are sent out and received independently of one another. Neither the sender nor the receiver needs any knowledge of the data stream outside the chunk currently being processed.
An everyday comparison: instead of posting one heavy parcel, you post a series of small numbered boxes. The recipient can start handling box one before box ten has arrived, and each box carries its own label saying how much is inside it. Nobody has to know the total weight in advance.
How a chunk is processed
The report then gives the processing rules, which matter for the rest of the story. If a Transfer-Encoding field with a value of chunked is specified in an HTTP message, whether that is a request sent by a client or the response from the server, the body of the message consists of an unspecified number of chunks, a terminating chunk, a trailer, and a final CRLF sequence. CRLF means carriage return followed by line feed, the pair of characters that marks the end of a line in HTTP.
Each chunk starts with the number of octets of the data it embeds, expressed as a hexadecimal number in ASCII, followed by optional parameters (chunk extension) and a terminating CRLF sequence, followed by the chunk data. The chunk is terminated by CRLF. If chunk extensions are provided, the chunk size is terminated by a semicolon and followed by the parameters, each also delimited by semicolons.
In plain words: every box has a label at the top saying how many bytes are inside, written in a number format computers use (hexadecimal), then a line break, then the bytes themselves, then another line break. Optional extra notes can be attached to the label after a semicolon. A special final chunk says the stream is finished.
The setup: what has to be true for the bug
The report does not describe a specific deployment, version string or test harness. The precondition it names is architectural: Apache has not upgraded to HTTP/2.0, so chunked transfer encoding still exists on the connection. HTTP/2 is a newer version of the protocol with different rules for sending data; on an HTTP/1.1 connection the chunked mechanism described above is still in play.
The trigger is a request that carries Transfer-Encoding: chunked together with an improper Content-Length that is larger than required. Content-Length is the header where a request normally states how many bytes its body contains. Sending both headers, and making the stated length bigger than the body really is, is the unusual combination that starts the trouble.
Finding it
Under those conditions the request body mysteriously appears in the response body. The input reaches Apache's bucket brigade even though PHP is not sending it there directly. In fact PHP never sees the input, because Apache does not let it read the body: it throws an error in ap_http_filter instead.
ap_http_filter is one of Apache's internal filters, the components that inspect and transform data as it flows in or out. A backtrace is a stack trace: a list of the function calls that were active at the moment something happened, like a receipt showing every step that led to the current point. The backtrace in the report shows the path the data took:
#0 apr_brigade_write (b=0x7f5115c18810, flush=0x5574844fcef0 <ap_filter_flush>, ctx=0x7f5115c1a548,
str=0x557484546fc0 "\n\n<title>", nbyte=71) at ./buckets/apr_brigade.c:433
#1 0x00005574844feebc in buffer_output (r=, str=, len=) at protocol.c:1898 #2 0x0000557484500d9e in ap_rvputs (r=r@entry=0x7f5115c190a0) at protocol.c:2022
#3 0x000055748452dde0 in ap_send_error_response (r=0x7f5115c190a0, recursive_error=0) at http_protocol.c:1539
#4 0x0000557484532eb6 in ap_http_header_filter (f=0x7f5115c1a570, b=0x7f5115c186e0) at http_filters.c:1335
#5 0x0000557484500832 in ap_content_length_filter (f=0x7f5115c1a548, b=0x7f5115c186e0) at protocol.c:1769
#6 0x000055748453415a in ap_byterange_filter (f=0x7f5115c1a520, bb=0x7f5115c186e0) at byterange_filter.c:494
#7 0x00007f51130855f4 in deflate_out_filter (f=, bb=0x7f5115c186e0) at mod_deflate.c:831 #8 0x00007f511285f10a in filter_harness (f=0x7f5115c17860, bb=0x7f5115c186e0) at mod_filter.c:323
#9 0x00005574845312df in ap_http_filter (f=, b=0x7f5115c18540, mode=, block=, readbytes=16384)
at http_filters.c:555
#10 0x00007f5111cf941f in php_apache_sapi_read_post (buf=0x7fffa5bf0500 "", count_bytes=16384) at ./sapi/apache2handler/sapi_apache2.c:198 #11 0x00007f5111c09d28 in sapi_read_post_block (buffer=buffer@entry=0x7fffa5bf0500 "", buflen=buflen@entry=16384) at ./main/SAPI.c:248
#12 0x00007f5111c0a77d in sapi_deactivate () at ./main/SAPI.c:513
#13 0x00007f5111c00ab9 in php_request_shutdown (dummy=dummy@entry=0x0) at ./main/main.c:1863
Line by line, reading from the bottom up because that is the order in which the calls happened:
php_request_shutdowninmain/main.cis PHP finishing up a request. Every request has a shutdown phase where PHP cleans up after itself.sapi_deactivateinmain/SAPI.cis part of that cleanup. SAPI stands for Server Application Programming Interface: the layer that lets PHP plug into a web server such as Apache.sapi_read_post_blockandphp_apache_sapi_read_postinsapi_apache2.care PHP asking Apache for the request body, the data the visitor sent.ap_http_filterinhttp_filters.cis where Apache handles that read. This is where the error is thrown: Apache refuses to hand the body over.- The next frames,
filter_harness,deflate_out_filter,ap_byterange_filter,ap_content_length_filterandap_http_header_filter, are Apache's output filters. They build the response, including the error page that is about to be sent back. ap_send_error_responseinhttp_protocol.cis the function that assembles that error response.ap_rvputsandbuffer_outputinprotocol.cwrite the response text out.apr_brigade_writeinbuckets/apr_brigade.cis the lowest frame shown, the point where bytes are actually placed into the output buffer.
The string being written in the trace is:
\n\n<title>
with nbyte=71, which is the request data surfacing inside the error page. In other words, the bytes the visitor sent are being written into the error response as if they were part of the page. The <title> fragment is HTML markup appearing in the error response.
What a bucket brigade is
To understand why this happens, the report explains Apache's internal data model. It starts with buckets.
Buckets
A bucket is a container for data. Buckets can contain any type of data. Although the most common case is a block of memory, a bucket may instead contain a file on disc, or even be fed a data stream from a dynamic source such as a separate program. Different bucket types exist to hold different kinds of data and the methods for handling it. In OOP terms, the apr_bucket is an abstract base class from which actual bucket types are derived. OOP means object-oriented programming, a style where code is organised around types of object; an abstract base class is a template that other types build on. There are several different types of data bucket, as well as metadata buckets, which hold information about data rather than the data itself.
An everyday comparison: a bucket is a labelled tub. The tub can hold sand, water or a note, and each kind of contents is handled differently, but the tub itself is the same idea.
Brigades
In normal use, there is no such thing as a freestanding bucket: they are contained in bucket brigades. A brigade is a container that may hold any number of buckets in a ring structure. The brigade serves to enable flexible and efficient manipulation of data, and is the unit that gets passed to and from your filter.
So a brigade is a chain of tubs, linked in a loop, and it is the whole chain that travels through Apache's filters rather than individual tubs. The report's summary of the flaw is that bucket memory gets initialised way above and waits until the chunked data enters the memory stream before it is destroyed, and the brigade memory is then mishandled into the way of the response brigade memory. In plain terms: the brigade memory is mishandled into the way of the response brigade memory.
The handler responsible for this vulnerability is in sapi_apache2.c:
if (!parent_req) {
php_apache_request_dtor(r);
ctx->request_processed = 1;
bucket = apr_bucket_eos_create(r->connection->bucket_alloc);
APR_BRIGADE_INSERT_TAIL(brigade, bucket);
Line by line:
if (!parent_req) {checks that this is not a sub-request, a request made internally by the server rather than by a visitor. The cleanup below should only run for the main request.php_apache_request_dtor(r);destroys the per-request state, the destructor step of the request's life.ctx->request_processed = 1;records that the request has been handled.bucket = apr_bucket_eos_create(r->connection->bucket_alloc);creates a special bucket that marks end of stream, the signal that there is no more data.APR_BRIGADE_INSERT_TAIL(brigade, bucket);adds that end-of-stream bucket to the end ofbrigade.
The patch adds the missing creation step:
if (!parent_req) {
php_apache_request_dtor(r);
ctx->request_processed = 1;
bucket = apr_bucket_eos_create(r->connection->bucket_alloc);
brigade = apr_brigade_create(r->pool, r->connection->bucket_alloc);
APR_BRIGADE_INSERT_TAIL(brigade, bucket);
The only difference is the added line brigade = apr_brigade_create(r->pool, r->connection->bucket_alloc);. It builds a fresh brigade, using the request's memory pool (r->pool) and the connection's bucket allocator, before the end-of-stream bucket is inserted. The added line creates a fresh brigade before the end-of-stream bucket is inserted.
Why existing defences did not stop it
If your application checks incoming data for dangerous characters, that check only happens when the application actually receives the data. Here the data never reaches the application, so the check is skipped entirely.
Impact
A crafted chunked request can get request data into the response body. The report frames the result as XSS and does not go further into what an attacker could achieve with it, nor does it state which clients or configurations are exploitable beyond the HTTP/1.1 chunked condition.
The fix
The fix adds a line creating a fresh brigade with apr_brigade_create(r->pool, r->connection->bucket_alloc) before inserting the end-of-stream bucket. The change was added to the security repository as commit [redacted] and published as a gist at https://gist.github.com/smalyshev/[redacted].
The embedded video accompanies the write-up; the report gives no further description of its contents.
Variants to test
- Send
Transfer-Encoding: chunkedwith aContent-Lengthlarger than the body on other Apache/PHP deployments. A positive result is request data appearing in the response body, especially inside an error page. - Put HTML markup such as
<title>or a script tag in the chunked body. A positive result is that markup being rendered rather than escaped. - Trigger the error path deliberately, for example by making Apache reject the body read in
ap_http_filter. A positive result is the body leaking into the generated error response. - Test other SAPI handlers that build brigades around request shutdown. A positive result is the same cross-contamination between request and response brigade memory.
Glossary
- Apache: a widely used web server program that receives requests from browsers and passes them to applications.
- PHP: a programming language commonly used to build web pages and web applications.
- SAPI: Server Application Programming Interface, the layer that lets PHP plug into a web server such as Apache.
- CVE: a public catalogue number for a known security flaw, so the same bug can be referred to unambiguously.
- XSS (cross-site scripting): a flaw where a site delivers code chosen by an attacker, and the victim's browser runs it because it trusts the site.
- HTTP: the protocol browsers and servers use to exchange pages and data.
- HTTP/1.1: the version of HTTP in which chunked transfer encoding is used.
- HTTP/2: a newer version of HTTP with different rules for sending data.
- Chunked transfer encoding: a way of sending a body as a series of independently handled pieces, each labelled with its size.
- Chunk: one piece of a chunked body.
- Chunk extension: optional extra parameters attached to a chunk's size label, after a semicolon.
- CRLF: carriage return followed by line feed, the character pair that marks the end of a line in HTTP.
- Header: a named field in an HTTP message carrying information about it, such as
Transfer-EncodingorContent-Length. Transfer-Encoding: chunked: the header value that tells the receiver the body is sent in chunks.Content-Length: the header stating how many bytes a body contains.- Octet: a byte, eight bits of data.
- Hexadecimal: a base-16 number format often used in computing.
- ASCII: a standard way of encoding text characters as numbers.
- Filter: an Apache component that inspects or transforms data as it flows in or out.
ap_http_filter: the Apache filter where the body read is rejected in this bug.- Backtrace (stack trace): a list of the function calls active at a moment, showing the steps that led there.
- Bucket: Apache's container for a piece of data, which can be memory, a file, a stream or metadata.
apr_bucket: the abstract base class from which Apache's bucket types are derived.- Metadata bucket: a bucket that holds information about data rather than the data itself.
- Brigade: a ring-structured container holding any number of buckets, passed to and from Apache filters.
- Bucket allocator: the component that supplies memory for buckets on a connection.
- Memory pool: a region of memory managed together and freed together, used here as
r->pool. - End-of-stream bucket: a special bucket marking that no more data follows.
- Commit: a recorded change in a source code repository.
- Gist: a small snippet of code published on GitHub.
- Validation: checking incoming data for dangerous or unexpected content.
- Application layer: the part of a system made of the application's own code, as opposed to the server's internals.