The nul byte and PHP stringsThe nul byte and PHP strings

A PHP string used to be one thing: a list of any number of any characters, one after the other: a string of pearls I guess. Nowadays, there are several types of strings. Their difference matters, and it express itself at various places in the PHP sources. There are numeric strings, the ones is_numeric() recognises, where "1e3" is a number and "12abc" is not. There are non-empty strings, because "" is a value that code often forgets to check. And there is a rarer kind: strings without a NUL byte, that is, strings that can be handed to a C function without losing their end.

Only the first of these has a predicate named for it. is_numeric() has been there for ages. For the other two, PHP offers no function that says what it tests. You write $s !== '' and str_contains($s, "\0"), and nothing in the language tells a reader, or a type checker, that this is the property the code depends on.

This post is about the third kind, because that is where I got caught recently.

The one that broke a CLI run

I was running exakat as a command-line script, and, of course, it worked before. Suddenly, while switching to PHP 8.6, it stopped with an uncaught ValueError coming from SQLite3::escapeString():

ValueError: SQLite3::escapeString(): Argument #1 ($string) must not contain any null bytes

The message is clear. I was less clear about the reason why I had not seen it coming. So, I went looking in the PHP release notes, and the PHP 8.6 UPGRADING file, which lists every change an upgrader must know about, has no entry for SQLite3 at all.

The reason is not really related to PHP 8.6, even if it landed there. The hunt for null bytes is an older campaign. In php-src, SQLite3::escapeString() declares its argument with the "P" specifier of the parameter parser, which means “path string”. That specifier rejects NUL bytes with the message “must not contain any null bytes”.

I will come back to the CLI part at the end. And first, the mechanism, because it explains all the other cases.

Why a string can end before its last byte

PHP strings are binary-safe. A zend_string stores its length, and a NUL byte is just another byte:

<?php
echo strlen("report\0.pdf"), "\n";   // 11
?>

The C library does not work that way. A C string ends at the first zero byte. Every function that passes a PHP string down to open(), stat(), execve() or libcurl has to decide what to do when the string contains a nul byte before its end. There are three choices, and PHP has made all three over the years.

One string, two readers: PHP counts eleven bytes, a C function stops at the NUL

The figure shows the problem. report\0.pdf is 11 bytes for PHP and report for C. If PHP checks the suffix on the first view and opens the file with the second, the check and the use see different files.

Three reactions

Over the years, PHP has chosen one of three ways to handle for each function.

1. Throw The function refuses the value with a ValueError. This is now the standard for file and path arguments.

<?php
try {
    var_dump(file_exists("report\0.pdf"));
} catch (ValueError $e) {
    echo get_class($e), ": ", $e->getMessage(), "\n";
}
// ValueError: file_exists(): Argument #1 ($filename) must not contain any null bytes
?>

2. Warn and carry on The function does nothing useful, but does not stop the script either. header() is the classic case. A header value with a NUL byte is dropped, with a warning:

<?php
set_error_handler(function ($no, $str) { echo "warning: $str\n"; return true; });
header("X-Test: a\0b");
echo "headers: ", json_encode(headers_list()), "\n";
// warning: Header may not contain NUL bytes
// headers: []
?>

ini_set("session.cookie_path", "/a\0b") behaves the same way: a warning, false, and the setting stays as it was.

3. Truncate silently This is the dangerous one, because nothing fails and noone tells you. The function keeps the part before the NUL and carries on. proc_open() is the example. In PHP 8.6.0, this runs echo with the rest of the command simply gone:

<?php
$p = proc_open("echo hi\0there", [1 => ['pipe', 'w']], $pipes);
echo "stdout: ", stream_get_contents($pipes[1]);   // stdout: hi
proc_close($p);
?>

The $cwd, the second argument of the same function, is refused in 8.6, with ValueError. The command, the first argument, is not. That difference is the kind of detail that is easy to miss when you read the changelog.

There is also Uri\Rfc3986\Uri::parse(), which returns null on a NUL byte rather than throwing. Returning null is a fourth reaction, though it is the easiest one to ignore.

When each change arrived

Here is an overview of the handling of \0 over a few PHP versions.

PHP Function families that began to refuse NUL How they refuse
5.3.4 (2010) Paths in general: the NEWS entry says “Paths with NULL in them (foo\0bar.txt) are now considered as invalid” Documented, with no error message in this entry
8.0 Arguments that go through the "p" / "P" parser specifiers (for example SQLite3::escapeString()); cURL string options; exec, system, passthru, shell_exec, escapeshellarg, escapeshellcmd; NUL bytes in source code ValueError; ParseErrorfor source code
8.4 mb_http_output(), the encoding of XMLReader and XMLWriter, XSLTProcessor::setParameter() ValueError
8.5 finfo_file() and finfo::file() (previously a TypeError), pcntl_exec(), PDO::quote() on SQLite, Locale:: methods, pg_connect(), pg_close_stmt(), SNMP ValueError, or an exception in PDO
8.6 getenv(), putenv(), parse_str(), setlocale(), openlog(), dl(), the $cwd of proc_open(), the file-information family (file_exists(), is_file(), stat(), …), SimpleXMLElement::__construct(), GMP string parsing, session_module_name(), the session cookie and cache settings ValueError, or a warning for the session settings
8.7 (WIP) pg_query_params(), pg_execute(), the pg_send_*() variants, pg_escape_string(), pg_escape_literal(), pg_escape_identifier() Proposed in PR #24240, still open

The path of the progress is clear. The change started with paths and extended to everything that takes a string and hands it to something written in C. The table also shows some gaps: a few functions are still silently truncating, and one whole family is waiting on a pull request.

Code that breaks

The SQLite3 case is rare, and a NUL byte in a database query is rare too. The breakage most likely to reach real code is in the file-information family in 8.6, and it is quiet in a way that is more dangerous.

The request that changes its answer

<?php
// Written for PHP 8.5 and earlier
$name = $_GET['file'] ?? '';
if (file_exists($name)) {
    readfile($name);
} else {
    http_response_code(404);
}
?>

The $_GET value is decoded before this code sees it, so ?file=report%00.pdf arrives with a real NUL byte in $name. On PHP 8.5, file_exists() accepted the name and answered for the part before the NUL. On PHP 8.6 it throws, nothing catches the ValueError, and the visitor gets a 500 and an entry in the error log. The request has not stopped being suspicious. It has stopped being a 404.

The raw NUL that stops parsing

Encoded NUL bytes in a query string are decoded by parse_str() into the value, and nothing fails:

<?php
parse_str("name=a%00b", $o);
var_dump(bin2hex($o["name"]));   // string(6) "610062"
?>

A raw NUL in the input string is a different case. On PHP 8.6 it throws:

<?php
parse_str("name=a\0b", $o);      // ValueError in 8.6
?>

Anyone who wrapped this in try { } catch (Exception $e) will not catch it, because ValueError extends Error, not Exception.

The no longer matching catch clause

In 8.5, finfo_file() changed its exception from TypeError to ValueError when the file name contains NUL:

<?php
$finfo = new finfo(FILEINFO_MIME_TYPE);
try {
    $type = $finfo->file($name);
} catch (TypeError $e) {          // was the right catch before 8.5
    $type = 'unknown';
}
?>

The catch is now dead code, and the ValueError goes up the stack, in production.

The command that runs shorter

This is the case I would worry about most. Nothing throws, and the command runs with less than you wrote:

<?php
$proc = proc_open("tar -czf backup.tgz " . $dir, $spec, $pipes);
?>

If $dir contains a NUL byte, the shell command is cut at the NUL. In 8.6 the $cwd argument is refused, but the command is not. There is no error and no warning, and the process reports on the shorter command it actually ran.

Security implications

NUL bytes have a long history in PHP security. The best-known case is the 2014 report about cURL, which I found as bug #68089. The shape of the problem is always the same. Code checks one string and uses another, also known as TOCTOU: Time Of Check, Time Of Use. The check passes on the full string, and later, the sink stops at the NUL.

The report’s example was a file URL with a NUL followed by http://. A check like strpos($url, "http://") !== falsepasses, because the substring does exist. libcurl then reads the file named before the NUL. Running the check on PHP 8.6.0 confirms that the check passes, and the cURL call is now refused:

<?php
$url = "file:///etc/passwd\0http://example.test/";
var_dump(strpos($url, "http://") !== false);   // bool(true)
try {
    curl_setopt(curl_init(), CURLOPT_URL, $url);
} catch (ValueError $e) {
    echo $e->getMessage(), "\n";   // cURL option CURLOPT_URL must not contain any null bytes
}
?>

The fix in PHP closes this for cURL. The same shape of bug can still appear in any code that validates a string and then passes it to a function that only refuses NUL in some versions. Four consequences to keep in mind:

  1. The check and the use must see the same string A suffix check such as str_ends_with($name, '.pdf') says nothing about what fopen() will open if the two calls see different bytes. Validate the string you pass on, or reject NUL first with str_contains($name, "\0").
  2. Make the failure path fail closed A ValueError is loud, which is good. Code that catches it and turns it into false, as in try { $ok = file_exists($name); } catch (Throwable) { $ok = false; }, has decided what a NUL byte means. If false leads to the branch that allows something, the attacker picks the branch by sending a NUL byte.
  3. Silent truncation is the worst case A command built from user input and a NUL byte runs with the rest of the string gone, and the code has no way to notice. The shorter command is what the function does, not a bug in the input. Audit every call where user input reaches a command string.
  4. The pending 8.7 change is a security fix, not a convenience PR #24240 covers pg_escape_string(). An escaped string that is cut at a NUL can leave a quote open or closed differently from what the validator approved. Until the PR lands, a PostgreSQL call that receives a user-supplied NUL is working with a shorter string than the one the code checked.

header() is worth a note because it is different. A NUL byte is dropped with a warning, which is safe, but the dangerous header characters are CR and LF, and PHP handles them separately. Do not read the NUL warning as a general protection against header injection.

These cases are good candidates for a static check. A rule that flags a call to one of the functions above, where the argument comes directly from $_GET, $_POST, $_SERVER or $_REQUEST, would find the obvious ones quickly. I have not written that rule, and I am not claiming one exists.

Testing the strings

Coming back to the different string types, what we need is a native test for each of the three strings, with a name that says what it tests. Today we have one of the three:

<?php
// Numeric string: native, named for the property
var_dump(is_numeric("1e3"));     // bool(true)
var_dump(is_numeric("12abc"));   // bool(false)

// Non-empty string: no function, just a comparison
var_dump("" !== '');             // bool(false)

// No NUL byte: native, but only as the negation of a search
var_dump(!str_contains("a\0b", "\0"));   // bool(false)
?>

The third line works, but the developer has to know that str_contains() looks for a zero byte, and nothing in the name says that the NUL-free string is the thing being tested. And empty() has such a bad press that noone wants to use it to check if the string is empty.

PHP already has the internal predicate. In ext/standard/exec.c there are assertions such as ZEND_ASSERT(!zend_str_has_nul_byte(unescaped_cmd)), so the C-level test exists and is used in the core. Exposing it under a name that says what it means would cost very little, yet it would make the concern visible. Until then, the userland sketch of the two missing ones looks like this:

<?php
function is_nul_free(string $s): bool {
    return !str_contains($s, "\0");
}

function is_non_empty_string(string $s): bool {
    return $s !== '';
}
?>

These are very easy, and, quite frankly, a no brainer. But for anyone learning the language, it means combining various features for one single camouflaged problem. So, the the names matter a lot: is_non_empty_string() says what the code means, where $s !== '' only says how it is written.

Note that static analysers already use numeric-string and non-empty-string as types. A NUL-free string is the next candidate, and it is the one that comes with functions that refuse the value.

The bigger picture

Every case in this post is the same question asked of a different function: does this function see the whole string, or only the part before the first zero byte? PHP has moved from silent truncation to errors, and the 8.6 release is the biggest step so far. And it has not finished. proc_open() still truncates its command, the PostgreSQL escape functions are waiting on a pull request, and the database code is at the mercy of whichever function a given extension happens to use. Did anyone check on mysqli_real_escape_string() or PDO?

If string is going to be split into various categories so the type checker can see them, a question arise: is “a string with no NUL byte” a new PHP type? Or is a validator at the boundary enough, as long as every function that matters is checked too?