Apache HTTP [2.4.17-2.4.38] Local Root Privilege Escalation
Apache HTTP server versions 2.4.17 to 2.4.38 have an out-of-bounds array access in the shared memory scoreboard, allowing a low-privilege worker process to call an arbitrary function as root during a graceful restart. An attacker with code execution as the web server user could escalate to root.
- Triaged in 47 hours
- Fixed in 5 months
- Paid in 5 months
- Disclosed after 5 months
Hello,
I reported a Local Root privilege escalation vulnerability on Apache HTTPd at the beginning of the year. Apache has now patched it, as you can see here. The vulnerability affects mod_prefork, mod_event, and mod_worker, the most used mods on Linux. Basically, this is an arbitrary function call as root triggered whenever the server gracefully restarts, which is generally once a day.
Here is the article I plan to publish soon, as MarkDown (careful, wall of text):
Introduction
From version 2.4.17 (Oct 9, 2015) to version 2.4.38 (Apr 1, 2019), Apache HTTP suffers from a local root privilege escalation vulnerability due to an out-of-bounds array access leading to an arbitrary function call.
The vulnerability is triggered when Apache gracefully restarts (apache2ctl graceful).
In standard Linux configurations, the logrotate utility runs this command once a day, at 6:25AM, in order to reset log file handles.
The vulnerability affects mod_prefork, mod_worker and mod_event. The following bug description, code walkthrough and exploit target mod_prefork.
Bug description
In MPM prefork, the main server process, running as root, manages a pool of single-threaded, low-privilege (www-data) worker processes, meant to handle HTTP requests.
In order to get feedback from its workers, Apache maintains a shared-memory area (SHM), scoreboard, which contains various informations such as the workers PIDs and the last request they handled.
Each worker is meant to maintain a process_score structure associated with its PID, and has full read/write access to the SHM.
ap_scoreboard_image: pointers to the shared memory block
(gdb) p *ap_scoreboard_image
$3 = {
global = 0x7f4a9323e008,
parent = 0x7f4a9323e020,
servers = 0x55835eddea78
}
(gdb) p ap_scoreboard_image->servers[0]
$5 = (worker_score *) 0x7f4a93240820
Example of shared memory associated with worker PID 19447
(gdb) p ap_scoreboard_image->parent[0]
$6 = {
pid = 19447,
generation = 0,
quiescing = 0 '\000',
not_accepting = 0 '\000',
connections = 0,
write_completion = 0,
lingering_close = 0,
keep_alive = 0,
suspended = 0,
bucket = 0 <- index for all_buckets
}
(gdb) ptype *ap_scoreboard_image->parent
type = struct process_score {
pid_t pid;
ap_generation_t generation;
char quiescing;
char not_accepting;
apr_uint32_t connections;
apr_uint32_t write_completion;
apr_uint32_t lingering_close;
apr_uint32_t keep_alive;
apr_uint32_t suspended;
int bucket; <- index for all_buckets
}
When Apache gracefully restarts, its main process kills old workers and replaces them by new ones.
At this point, every old worker's bucket value will be used by the main process to access an array of his, all_buckets.
all_buckets
(gdb) p $index = ap_scoreboard_image->parent[0]->bucket
(gdb) p all_buckets[$index]
$7 = {
pod = 0x7f19db2c7408,
listeners = 0x7f19db35e9d0,
mutex = 0x7f19db2c7550
}
(gdb) ptype all_buckets[$index]
type = struct prefork_child_bucket {
ap_pod_t *pod;
ap_listen_rec *listeners;
apr_proc_mutex_t *mutex; <--
}
(gdb) ptype apr_proc_mutex_t
apr_proc_mutex_t {
apr_pool_t *pool;
const apr_proc_mutex_unix_lock_methods_t *meth; <--
int curr_locked;
char *fname;
...
}
(gdb) ptype apr_proc_mutex_unix_lock_methods_t
apr_proc_mutex_unix_lock_methods_t {
...
apr_status_t (*child_init)(apr_proc_mutex_t **, apr_pool_t *, const char *); <--
...
}
No bound checks happen. Therefore, a rogue worker can change its bucket index and make it point to the shared memory, in order to control the prefork_child_bucket structure upon restart. Eventually, and before privileges are dropped, mutex->meth->child_init() is called.
This results in an arbitrary function call as root.
Vulnerable code
We'll go through server/mpm/prefork/prefork.c to find out where and how the bug happens.
- A rogue worker changes its
bucketindex in shared memory to make it point to a structure of his, also in SHM. - At 06:25AM the next day,
logrotaterequests a graceful restart from Apache. - Upon this, the main Apache process will first kill workers, and then spawn new ones.
- The killing is done by sending
SIGUSR1to workers. They are expected to exit ASAP. - Then,
prefork_run()(L853) is called to spawn new workers. Sinceretained->mpm->was_gracefulistrue(L861), workers are not restarted straight away. - Instead, we enter the main loop (L933) and monitor dead workers' PIDs. When an old worker dies,
ap_wait_or_timeout()returns its PID (L940). - The index of the
process_scorestructure associated with this PID is stored inchild_slot(L948). - If the death of this worker was not fatal (L969),
make_child()is called withap_get_scoreboard_process(child_slot)->bucketas a third argument (L985). As previously said,bucket's value has been changed by a rogue worker. make_child()creates a new child,fork()ing (L671) the main process.- The OOB read happens (L691), and
my_bucketis therefore under the control of an attacker. child_main()is called (L722), and the function call happens a bit further (L433).SAFE_ACCEPT(<code>)will only execute<code>if Apache listens on two ports or more, which is often the case since a server listens over HTTP (80) and HTTPS (443).- Assuming
<code>is executed,apr_proc_mutex_child_init()is called, which results in a call to(*mutex)->meth->child_init(mutex, pool, fname)with mutex under control. - Privileges are dropped a bit later in the execution (L446).
Exploitation
The exploitation is a four step process:
- Obtain R/W access on a worker process
- Write a fake
prefork_child_bucketstructure in the SHM - Make
all_buckets[bucket]point to the structure - Await 6:25AM to get an arbitrary function call
Advantages:
- The main process never exits, so we know where everything is mapped by reading
/proc/self/maps(ASLR/PIE useless) - When a worker dies (or segfaults), it is automatically restarted by the main process, so there is no risk of DOSing Apache
Problems:
- PHP does not allow to read/write
/proc/self/mem, which blocks us from simply editing the SHM all_bucketsis reallocated after a graceful restart (!)
1. Obtain R/W access on a worker process
PHP UAF 0-day
Since mod_prefork is often used in combination with mod_php, it seems natural to exploit the vulnerability through PHP. CVE-2019-6977 would be a perfect candidate, but it was not out when I started writing the exploit. I went with a 0day UAF in PHP 7.x (which seems to work in PHP5.x as well):
PHP UAF
<?php
class X extends DateInterval implements JsonSerializable
{
public function jsonSerialize()
{
global $y, $p;
unset($y[0]);
$p = $this->y;
return $this;
}
}
function get_aslr()
{
global $p, $y;
$p = 0;
$y = [new X('PT1S')];
json_encode([1234 => &$y]);
print("ADDRESS: 0x" . dechex($p) . "\n");
return $p;
}
get_aslr();
This is an UAF on a PHP object: we unset $y[0] (an instance of X), but it is still usable using $this.
UAF to Read/Write
We want to achieve two things:
- Read memory to find
all_buckets' address - Edit the SHM to change
bucketindex and add our custom mutex structure
Luckily for us, PHP's heap is located before those two in memory.
Memory addresses of PHP's heap, ap_scoreboard_image->* and all_buckets
root@apaubuntu:~# cat /proc/6318/maps | grep libphp | grep rw-p
7f4a8f9f3000-7f4a8fa0a000 rw-p 00471000 08:02 542265 /usr/lib/apache2/modules/libphp7.2.so
(gdb) p *ap_scoreboard_image
$14 = {
global = 0x7f4a9323e008,
parent = 0x7f4a9323e020,
servers = 0x55835eddea78
}
(gdb) p all_buckets
$15 = (prefork_child_bucket *) 0x7f4a9336b3f0
Since we're triggering the UAF on a PHP object, any property of this object will be UAF'd too; we can convert this zend_object UAF into a zend_string one.
This is useful because of zend_string's structure:
(gdb) ptype zend_string
type = struct _zend_string {
zend_refcounted_h gc;
zend_ulong h;
size_t len;
char val[1];
}
The len property contains the length of the string. By incrementing it, we can read and write further in memory, and therefore access the two memory regions we're interested in: the SHM and Apache's all_buckets.
Locating bucket indexes and all_buckets
We want to change ap_scoreboard_image->parent[worker_id]->bucket for a certain worker_id. Luckily, the structure always starts at the beginning of the shared memory block, so it is easy to locate.
Shared memory location and targeted process_score structures
root@apaubuntu:~# cat /proc/6318/maps | grep rw-s
7f4a9323e000-7f4a93252000 rw-s 00000000 00:05 57052 /dev/zero (deleted)
(gdb) p &ap_scoreboard_image->parent[0]
$18 = (process_score *) 0x7f4a9323e020
(gdb) p &ap_scoreboard_image->parent[1]
$19 = (process_score *) 0x7f4a9323e044
To locate all_buckets, we can make use of our knowledge of the prefork_child_bucket structure. We have:
Important structures of bucket items
prefork_child_bucket {
ap_pod_t *pod;
ap_listen_rec *listeners;
apr_proc_mutex_t *mutex; <--
}
apr_proc_mutex_t {
apr_pool_t *pool;
const apr_proc_mutex_unix_lock_methods_t *meth; <--
int curr_locked;
char *fname;
...
}
apr_proc_mutex_unix_lock_methods_t {
unsigned int flags;
apr_status_t (*create)(apr_proc_mutex_t *, const char *);
apr_status_t (*acquire)(apr_proc_mutex_t *);
apr_status_t (*tryacquire)(apr_proc_mutex_t *);
apr_status_t (*release)(apr_proc_mutex_t *);
apr_status_t (*cleanup)(void *);
apr_status_t (*child_init)(apr_proc_mutex_t **, apr_pool_t *, const char *); <--
apr_status_t (*perms_set)(apr_proc_mutex_t *, apr_fileperms_t, apr_uid_t, apr_gid_t);
apr_lockmech_e mech;
const char *name;
}
all_buckets[0]->mutex will be located in the same memory region as all_buckets[0]. Since meth is a static structure, it will be located in libapr's .data. Since meth points to functions defined in libapr, each of the function pointers will be located in libapr's .text.
Since we have knowledge of those region's addresses through /proc/self/maps, we can go through every pointer in Apache's memory and find one that matches the structure. It will be all_buckets[0].
As I mentioned, all_buckets's address changes at every graceful restart. This means that when our exploit triggers, all_buckets's address will be different than the one we found. This has to be taken into account; we'll talk about this later.
2. Write a fake prefork_child_bucket structure in the SHM
Reaching the function call
The code path to the arbitrary function call is the following:
bucket_id = ap_scoreboard_image->parent[id]->bucket
my_bucket = all_buckets[bucket_id]
mutex = &my_bucket->mutex
apr_proc_mutex_child_init(mutex)
(*mutex)->meth->child_init(mutex, pool, fname)
Calling something proper
To exploit, we make (*mutex)->meth->child_init point to zend_object_std_dtor(zend_object *object), which yields the following chain:
mutex = &my_bucket->mutex
[object = mutex]
zend_object_std_dtor(object)
ht = object->properties
zend_array_destroy(ht)
zend_hash_destroy(ht)
val = &ht->arData[0]->val
ht->pDestructor(val)
pDestructor is set to system, and &ht->arData[0]->val is a string.
As you can see, both leftmost structures are superimposed.
3. Make all_buckets[bucket] point to the structure
Problem and solution
Right now, if all_buckets' address was unchanged in between restarts, our exploit would be over:
- Get R/W over all memory after PHP's heap
- Find
all_bucketsby matching its structure - Put our structure in the SHM
- Change one of the
process_score.bucketin the SHM so thatall_bucket[bucket]->mutexpoints to our payload
As all_buckets' address changes, we can do two things to improve reliability: spray the SHM and use every process_score structure - one for each PID.
Spraying the shared memory
If all_buckets' new address is not far from the old one, my_bucket will point close to our structure. Therefore, instead of having our prefork_child_bucket structure at a precise point in the SHM, we can spray it all over unused parts of the SHM. The problem is that the
structure is also used as a zend_object, and therefore it has a size of (5 * 8 =) 40 bytes to include zend_object.properties.
Spraying a structure that big over a space this small won't help us much.
To solve this problem, we superimpose the two center structures, apr_proc_mutex_t and zend_array, and spray their address in the rest of the shared memory.
The impact will be that prefork_child_bucket.mutex and zend_object.properties point to the same address.
Now, if all_bucket is relocated not too far from its original address, my_bucket will be in the sprayed area.
Using every process_score
Each Apache worker has an associated process_score structure, and with it a bucket index.
Instead of changing one process_score.bucket value, we can change every one of them, so that they cover another part of memory. For instance:
ap_scoreboard_image->parent[0]->bucket = -10000 -> 0x7faabbcc00 <= all_buckets <= 0x7faabbdd00
ap_scoreboard_image->parent[1]->bucket = -20000 -> 0x7faabbdd00 <= all_buckets <= 0x7faabbff00
ap_scoreboard_image->parent[2]->bucket = -30000 -> 0x7faabbff00 <= all_buckets <= 0x7faabc0000
This multiplies our success rate by the number of apache workers. Upon respawn, only one worker have a valid bucket number, but this is not a problem because the others will crash, and immediately respawn.
Success rate
Different Apache servers have different number of workers. Having more workers mean we can spray the address of our mutex over less memory, but it also means we can specify more index for all_buckets. This means that having more workers improves our success rate. After a few tries on my test Apache server of 4 workers (default), I had ~80% success rate.
Again, if the exploit fails, it can be restarted the next day as Apache will still restart properly. Apache's error.log will nevertheless contain notifications about its workers segfaulting.
4. Await 6:25AM for the exploit to trigger
Well, that's the easy step.
Vulnerability timeline
- 2019-02-22 Initial contact email to
security[at]apache[dot]org, with description and POC - 2019-02-25 Acknowledgment of the vulnerability, working on a fix
- 2019-03-07 Apache's security team sends a patch for I to review, CVE assigned
- 2019-03-10 I approve the patch
- 2019-04-01 Apache HTTP version 2.4.39 released
Apache's team has been prompt to respond and patch, and nice as hell. Really good experience. PHP never answered regarding the UAF.
Exploit
I'm not releasing it just yet !
Impact
You generally obtain root privileges from www-data privileges.
Context
Apache HTTP Server, from version 2.4.17 (9 October 2015) to version 2.4.38 (1 April 2019), suffered from a local root privilege escalation vulnerability caused by an out-of-bounds array access that leads to an arbitrary function call. The vulnerability is triggered when Apache gracefully restarts (apache2ctl graceful). In standard Linux configurations, the logrotate utility runs this command once a day, at 6:25AM, in order to reset log file handles.
The vulnerability affects mod_prefork, mod_worker and mod_event. The bug description, code walkthrough and exploit in this write-up target mod_prefork.
In MPM prefork, the main server process, running as root, manages a pool of single-threaded, low-privilege (www-data) worker processes, meant to handle HTTP requests. In order to get feedback from its workers, Apache maintains a shared-memory area (SHM), scoreboard, which contains various pieces of information such as the workers' PIDs and the last request they handled. Each worker is meant to maintain a process_score structure associated with its PID, and has full read/write access to the SHM.
Setup
Since mod_prefork is often used in combination with mod_php, exploiting the vulnerability through PHP is natural. The researcher's test server ran the default of 4 workers. The main process never exits, so the layout of its memory can be read from /proc/self/maps, which makes ASLR and PIE irrelevant. When a worker dies or segfaults, it is automatically restarted by the main process, so there is no risk of denial of service against Apache.
Two obstacles are noted up front: PHP does not allow reading or writing /proc/self/mem, which blocks simply editing the SHM, and all_buckets is reallocated after a graceful restart.
Finding it
The starting point is the scoreboard shared memory. ap_scoreboard_image holds pointers into the shared memory block:
(gdb) p *ap_scoreboard_image
$3 = {
global = 0x7f4a9323e008,
parent = 0x7f4a9323e020,
servers = 0x55835eddea78
}
(gdb) p ap_scoreboard_image->servers[0]
$5 = (worker_score *) 0x7f4a93240820
Each worker's process_score structure lives in that block. For worker PID 19447:
(gdb) p ap_scoreboard_image->parent[0]
$6 = {
pid = 19447,
generation = 0,
quiescing = 0 '\000',
not_accepting = 0 '\000',
connections = 0,
write_completion = 0,
lingering_close = 0,
keep_alive = 0,
suspended = 0,
bucket = 0 <- index for all_buckets
}
(gdb) ptype *ap_scoreboard_image->parent
type = struct process_score {
pid_t pid;
ap_generation_t generation;
char quiescing;
char not_accepting;
apr_uint32_t connections;
apr_uint32_t write_completion;
apr_uint32_t lingering_close;
apr_uint32_t keep_alive;
apr_uint32_t suspended;
int bucket; <- index for all_buckets
}
The bucket field is the interesting one. When Apache gracefully restarts, its main process kills old workers and replaces them with new ones. At this point, every old worker's bucket value is used by the main process to access an array of its own, all_buckets:
(gdb) p $index = ap_scoreboard_image->parent[0]->bucket
(gdb) p all_buckets[$index]
$7 = {
pod = 0x7f19db2c7408,
listeners = 0x7f19db35e9d0,
mutex = 0x7f19db2c7550
}
(gdb) ptype all_buckets[$index]
type = struct prefork_child_bucket {
ap_pod_t *pod;
ap_listen_rec *listeners;
apr_proc_mutex_t *mutex; <--
}
(gdb) ptype apr_proc_mutex_t
apr_proc_mutex_t {
apr_pool_t *pool;
const apr_proc_mutex_unix_lock_methods_t *meth; <--
int curr_locked;
char *fname;
...
}
(gdb) ptype apr_proc_mutex_unix_lock_methods_t
apr_proc_mutex_unix_lock_methods_t {
...
apr_status_t (*child_init)(apr_proc_mutex_t **, apr_pool_t *, const char *); <--
...
}
No bound checks happen. A rogue worker can therefore change its bucket index and make it point into the shared memory, in order to control the prefork_child_bucket structure upon restart. Eventually, and before privileges are dropped, mutex->meth->child_init() is called. This results in an arbitrary function call as root.
Exploitation
The exploitation is a four step process:
- Obtain R/W access on a worker process
- Write a fake
prefork_child_bucketstructure in the SHM - Make
all_buckets[bucket]point to the structure - Await 6:25AM to get an arbitrary function call
Step 1: obtain R/W access on a worker process
CVE-2019-6977 would have been a perfect candidate, but it was not out when the exploit was started, so the researcher went with a 0day use-after-free in PHP 7.x, which seems to work in PHP 5.x as well:
<?php
class X extends DateInterval implements JsonSerializable
{
public function jsonSerialize()
{
global $y, $p;
unset($y[0]);
$p = $this->y;
return $this;
}
}
function get_aslr()
{
global $p, $y;
$p = 0;
$y = [new X('PT1S')];
json_encode([1234 => &$y]);
print("ADDRESS: 0x" . dechex($p) . "\n");
return $p;
}
get_aslr();
This is a use-after-free on a PHP object: $y[0], an instance of X, is unset, but the object is still usable through $this.
The goal is twofold: read memory to find the address of all_buckets, and edit the SHM to change the bucket index and add the custom mutex structure. PHP's heap is conveniently located before those two in memory:
root@apaubuntu:~# cat /proc/6318/maps | grep libphp | grep rw-p
7f4a8f9f3000-7f4a8fa0a000 rw-p 00471000 08:02 542265 /usr/lib/apache2/modules/libphp7.2.so
(gdb) p *ap_scoreboard_image
$14 = {
global = 0x7f4a9323e008,
parent = 0x7f4a9323e020,
servers = 0x55835eddea78
}
(gdb) p all_buckets
$15 = (prefork_child_bucket *) 0x7f4a9336b3f0
Since the UAF is triggered on a PHP object, any property of that object is UAF'd too, which allows converting the zend_object UAF into a zend_string one. That is useful because of the layout of zend_string:
(gdb) ptype zend_string
type = struct _zend_string {
zend_refcounted_h gc;
zend_ulong h;
size_t len;
char val[1];
}
The len property contains the length of the string. By incrementing it, it becomes possible to read and write further in memory, and therefore reach the two regions of interest: the SHM and Apache's all_buckets.
To change ap_scoreboard_image->parent[worker_id]->bucket for a given worker_id, note that the structure always starts at the beginning of the shared memory block, so it is easy to locate:
root@apaubuntu:~# cat /proc/6318/maps | grep rw-s
7f4a9323e000-7f4a93252000 rw-s 00000000 00:05 57052 /dev/zero (deleted)
(gdb) p &ap_scoreboard_image->parent[0]
$18 = (process_score *) 0x7f4a9323e020
(gdb) p &ap_scoreboard_image->parent[1]
$19 = (process_score *) 0x7f4a9323e044
To locate all_buckets, the knowledge of the prefork_child_bucket structure is used:
prefork_child_bucket {
ap_pod_t *pod;
ap_listen_rec *listeners;
apr_proc_mutex_t *mutex; <--
}
apr_proc_mutex_t {
apr_pool_t *pool;
const apr_proc_mutex_unix_lock_methods_t *meth; <--
int curr_locked;
char *fname;
...
}
apr_proc_mutex_unix_lock_methods_t {
unsigned int flags;
apr_status_t (*create)(apr_proc_mutex_t *, const char *);
apr_status_t (*acquire)(apr_proc_mutex_t *);
apr_status_t (*tryacquire)(apr_proc_mutex_t *);
apr_status_t (*release)(apr_proc_mutex_t *);
apr_status_t (*cleanup)(void *);
apr_status_t (*child_init)(apr_proc_mutex_t **, apr_pool_t *, const char *); <--
apr_status_t (*perms_set)(apr_proc_mutex_t *, apr_fileperms_t, apr_uid_t, apr_gid_t);
apr_lockmech_e mech;
const char *name;
}
all_buckets[0]->mutex is located in the same memory region as all_buckets[0]. Since meth is a static structure, it is located in libapr's .data. Since meth points to functions defined in libapr, each of the function pointers is located in libapr's .text. With knowledge of those regions' addresses from /proc/self/maps, it is possible to go through every pointer in Apache's memory and find one that matches the structure. It will be all_buckets[0].
As mentioned, the address of all_buckets changes at every graceful restart, so when the exploit triggers, its address will differ from the one found. This has to be taken into account later.
Step 2: write a fake prefork_child_bucket structure in the SHM
The code path to the arbitrary function call is the following:
bucket_id = ap_scoreboard_image->parent[id]->bucket
my_bucket = all_buckets[bucket_id]
mutex = &my_bucket->mutex
apr_proc_mutex_child_init(mutex)
(*mutex)->meth->child_init(mutex, pool, fname)
To exploit, (*mutex)->meth->child_init is made to point to zend_object_std_dtor(zend_object *object), which yields the following chain:
mutex = &my_bucket->mutex
[object = mutex]
zend_object_std_dtor(object)
ht = object->properties
zend_array_destroy(ht)
zend_hash_destroy(ht)
val = &ht->arData[0]->val
ht->pDestructor(val)
pDestructor is set to system, and &ht->arData[0]->val is a string. Both leftmost structures are superimposed.
Step 3: make all_buckets[bucket] point to the structure
If the address of all_buckets were unchanged between restarts, the exploit would be over: get R/W over all memory after PHP's heap, find all_buckets by matching its structure, put the structure in the SHM, and change one of the process_score.bucket values in the SHM so that all_bucket[bucket]->mutex points to the payload.
Because the address of all_buckets changes, two things improve reliability: spray the SHM and use every process_score structure, one for each PID.
If the new address of all_buckets is not far from the old one, my_bucket will point close to the structure. Instead of having the prefork_child_bucket structure at a precise point in the SHM, it can be sprayed all over unused parts of the SHM. The problem is that the structure is also used as a zend_object, and therefore has a size of (5 * 8 =) 40 bytes to include zend_object.properties. Spraying a structure that big over a space this small will not help much. To solve this, the two centre structures, apr_proc_mutex_t and zend_array, are superimposed, and their address is sprayed in the rest of the shared memory. The impact is that prefork_child_bucket.mutex and zend_object.properties point to the same address. Now, if all_bucket is relocated not too far from its original address, my_bucket will be in the sprayed area.
Each Apache worker has an associated process_score structure, and with it a bucket index. Instead of changing one process_score.bucket value, every one of them can be changed so that they cover another part of memory. For instance:
ap_scoreboard_image->parent[0]->bucket = -10000 -> 0x7faabbcc00 <= all_buckets <= 0x7faabbdd00
ap_scoreboard_image->parent[1]->bucket = -20000 -> 0x7faabbdd00 <= all_buckets <= 0x7faabbff00
ap_scoreboard_image->parent[2]->bucket = -30000 -> 0x7faabbff00 <= all_buckets <= 0x7faabc0000
This multiplies the success rate by the number of Apache workers. Upon respawn, only one worker has a valid bucket number, but this is not a problem because the others will crash and immediately respawn.
Different Apache servers have different numbers of workers. Having more workers means the address of the mutex can be sprayed over less memory, but it also means more index values can be specified for all_buckets. More workers therefore improve the success rate. After a few tries on a test Apache server of 4 workers (the default), the researcher had ~80% success rate. If the exploit fails, it can be restarted the next day, as Apache will still restart properly. Apache's error.log will nevertheless contain notifications about its workers segfaulting.
Step 4: await 6:25AM for the exploit to trigger
That is the easy step.
Root cause
The bug is in server/mpm/prefork/prefork.c. The sequence is:
- A rogue worker changes its
bucketindex in shared memory to make it point to a structure of its own, also in SHM. - At 06:25AM the next day,
logrotaterequests a graceful restart from Apache. - Upon this, the main Apache process first kills workers, and then spawns new ones.
- The killing is done by sending
SIGUSR1to workers, which are expected to exit ASAP. - Then,
prefork_run()(L853) is called to spawn new workers. Sinceretained->mpm->was_gracefulistrue(L861), workers are not restarted straight away. - Instead, the main loop (L933) is entered and dead workers' PIDs are monitored. When an old worker dies,
ap_wait_or_timeout()returns its PID (L940). - The index of the
process_scorestructure associated with this PID is stored inchild_slot(L948). - If the death of this worker was not fatal (L969),
make_child()is called withap_get_scoreboard_process(child_slot)->bucketas a third argument (L985). As previously said,bucket's value has been changed by a rogue worker. make_child()creates a new child,fork()ing (L671) the main process.- The OOB read happens (L691), and
my_bucketis therefore under the control of an attacker. child_main()is called (L722), and the function call happens a bit further (L433).SAFE_ACCEPT(<code>)will only execute<code>if Apache listens on two ports or more, which is often the case since a server listens over HTTP (80) and HTTPS (443).- Assuming
<code>is executed,apr_proc_mutex_child_init()is called, which results in a call to(*mutex)->meth->child_init(mutex, pool, fname)withmutexunder control. - Privileges are dropped a bit later in the execution (L446).
No bound checks happen on the bucket index, which allows the out-of-bounds read of all_buckets and the subsequent function pointer call before privileges are dropped.
Impact
You generally obtain root privileges from www-data privileges. The trigger is a graceful restart, which in standard Linux configurations happens once a day at 6:25AM via logrotate. The SAFE_ACCEPT condition means the call path requires Apache to listen on two ports or more, which is often the case with HTTP and HTTPS.
Fix
Apache patched the vulnerability and released version 2.4.39 on 1 April 2019. The report links to the Apache HTTP Server 2.4 vulnerabilities page for CVE-2019-0211. The patch was sent by Apache's security team on 7 March 2019 for review, and approved on 10 March 2019.
Variants to test
The report targets mod_prefork; it states that mod_worker and mod_event are also affected, so the same bucket/all_buckets reasoning is worth checking in those MPMs. The exploit also depends on a worker process that can read and write the SHM, so any deployment where mod_prefork runs alongside an in-process scripting runtime such as mod_php is a candidate.
Hunting notes
This kind of bug hides in shared-memory structures that low-privilege workers can write and that the privileged parent later trusts, especially where an index from the shared area is used to address a parent-side array. The exploit was not released at the time of writing.
Vulnerability timeline
- 2019-02-22 Initial contact email to
security[at]apache[dot]org, with description and POC - 2019-02-25 Acknowledgment of the vulnerability, working on a fix
- 2019-03-07 Apache's security team sends a patch for review, CVE assigned
- 2019-03-10 The patch is approved
- 2019-04-01 Apache HTTP version 2.4.39 released
PHP never answered regarding the UAF.
What happened, in plain words
A security researcher found a way for an ordinary web server user to become the most powerful user on a Linux machine, the administrator account called root. The software involved is the Apache HTTP Server, the program that many websites use to answer visitors' requests. The flaw existed in versions 2.4.17 (released 9 October 2015) through 2.4.38 (released 1 April 2019).
The trick works like this. Apache runs one powerful parent process as root and a group of weaker helper processes, called workers, that actually talk to visitors. The workers run as a low-privilege account, typically www-data. The parent and the workers share a small patch of memory, a noticeboard where each worker writes down things like its process ID and the last request it handled. Once a day, a housekeeping tool called logrotate asks Apache to restart gently, without dropping connections, and during that restart the parent reads a number from the noticeboard and uses it to look up an entry in a list of its own. Nobody checks whether that number makes sense. A worker that has been taken over can write a silly number there, and the parent will then read from the wrong place in memory and, a moment later, call a function whose address the attacker controls. That call happens while the parent is still root, so the attacker's code runs with full power.
The exploit uses a separate bug in PHP (the language many Apache setups run inside the workers) to gain read and write access to the worker's memory in the first place. Apache fixed the problem and released version 2.4.39 on 1 April 2019.
The pieces you need to know
Before the details, a few everyday ideas. You can skip nothing here; each one comes back later.
- Process: a running program. Your browser is a process, and so is each copy of Apache. Each has a number, the PID (process ID), so the operating system can tell them apart.
- root: the superuser on Linux. It can do anything: read any file, change any setting, install software. Ordinary accounts, like
www-data, cannot. - Privilege escalation: any bug that lets a weaker account gain the powers of a stronger one. Here, from
www-datatoroot. The word "local" means the attacker already has a foothold on the machine; they are not breaking in from the internet in this step. - Apache HTTP Server: the web server program. It receives requests from browsers and sends back pages.
- MPM (Multi-Processing Module): the part of Apache that decides how to spread the work across processes.
mod_preforkuses one process per connection at a time;mod_workerandmod_eventuse threads. All three were affected; the write-up focuses onmod_prefork. - Graceful restart: asking the server to reload without cutting off visitors mid-page. Old workers finish what they are doing and exit; new ones take over. The command is
apache2ctl graceful. - logrotate: a Linux housekeeping tool that rotates log files (renames the old one, starts a fresh one) on a schedule. To let Apache reopen its log files, it sends the graceful restart command. On standard setups this happens once a day at 6:25AM.
- Shared memory (SHM): a patch of memory that several processes can read and write. Think of a whiteboard in an office that everyone can see and scribble on. Apache's whiteboard is called the
scoreboard. - Out-of-bounds (OOB) access: reading or writing past the end of a list or array, into memory that belongs to something else. Like reading past the last name in a printed address book and getting whatever is printed on the next page.
- Arbitrary function call: making a program jump to a function of the attacker's choosing. If that happens while the program is
root, the attacker's chosen function runs asroot. - ASLR and PIE: techniques that shuffle where things sit in memory each time a program starts, to make attackers' lives harder. They are useless here because the main Apache process never exits, so its layout stays put and can simply be read.
/proc/self/maps: a file on Linux that lists which parts of memory a process has mapped and where. Reading it tells you the addresses of the program's code, its data, and its shared memory./proc/self/mem: a file that lets a process read and write its own memory directly. Handy for an attacker, but PHP blocks access to it, which is one of the obstacles described below.- PHP and
mod_php: PHP is a programming language used to build web pages.mod_phpruns PHP inside the Apache worker process, so a bug in PHP can be used to take over that worker. - Use-after-free (UAF): a bug where a program frees an object (gives its memory back) but keeps a reference to it and later uses it. Like throwing away a key, then finding a copy still opens the door.
- Heap: the area of memory a program uses for objects it creates while running.
- Spraying: filling memory with many copies of the same data so that, wherever the program happens to look, it finds a copy. Like scattering identical leaflets over a whole field instead of placing one on a specific bench.
- Segfault: a crash caused by a program touching memory it should not. Apache notices a dead worker and starts a new one, so crashes are survivable.
- CVE: a public identifier for a known vulnerability, so people can refer to it unambiguously.
The setup the researcher used
Since mod_prefork is often used in combination with mod_php, exploiting the vulnerability through PHP is natural. The test server ran the default of 4 workers.
Two facts make life easier for the attacker:
- The main process never exits, so its memory layout can be read from
/proc/self/maps. ASLR and PIE, the usual defences against guessing addresses, do not help here. - When a worker dies or segfaults, the main process automatically starts a new one. So crashing workers does not take the site down; there is no risk of denial of service against Apache.
Two obstacles are noted up front:
- PHP does not allow reading or writing
/proc/self/mem, which blocks the simple approach of directly editing the shared memory. all_buckets(the parent's list, explained below) is reallocated after a graceful restart, so its address changes.
Finding the bug
The starting point is the scoreboard shared memory. The variable ap_scoreboard_image holds pointers into that block:
(gdb) p *ap_scoreboard_image
$3 = {
global = 0x7f4a9323e008,
parent = 0x7f4a9323e020,
servers = 0x55835eddea78
}
(gdb) p ap_scoreboard_image->servers[0]
$5 = (worker_score *) 0x7f4a93240820
Line by line: gdb is the GNU debugger, a tool that lets you pause a running program and inspect it. p means print. *ap_scoreboard_image prints the contents of the structure that describes the scoreboard. The three fields, global, parent and servers, are addresses inside the shared memory block. The second command prints the first entry of the servers array, which is a worker_score structure at address 0x7f4a93240820. In plain terms: the scoreboard is a block of memory, and these commands show where its parts live.
Each worker's process_score structure lives in that block. For worker PID 19447:
(gdb) p ap_scoreboard_image->parent[0]
$6 = {
pid = 19447,
generation = 0,
quiescing = 0 '\000',
not_accepting = 0 '\000',
connections = 0,
write_completion = 0,
lingering_close = 0,
keep_alive = 0,
suspended = 0,
bucket = 0 <- index for all_buckets
}
(gdb) ptype *ap_scoreboard_image->parent
type = struct process_score {
pid_t pid;
ap_generation_t generation;
char quiescing;
char not_accepting;
apr_uint32_t connections;
apr_uint32_t write_completion;
apr_uint32_t lingering_close;
apr_uint32_t keep_alive;
apr_uint32_t suspended;
int bucket; <- index for all_buckets
}
Line by line: the first command prints the first process_score entry, the one belonging to worker PID 19447. The fields are bookkeeping values: pid is the process ID, generation counts restarts, quiescing and not_accepting are flags, and the connections, write_completion, lingering_close, keep_alive and suspended fields are counters. The last field, bucket, is the interesting one: it is an index into the parent's all_buckets array. The second command, ptype, prints the definition of the structure, confirming the same fields and their types. The comment <- index for all_buckets marks the field that matters.
When Apache gracefully restarts, its main process kills old workers and replaces them with new ones. At this point, every old worker's bucket value is used by the main process to access an array of its own, all_buckets:
(gdb) p $index = ap_scoreboard_image->parent[0]->bucket
(gdb) p all_buckets[$index]
$7 = {
pod = 0x7f19db2c7408,
listeners = 0x7f19db35e9d0,
mutex = 0x7f19db2c7550
}
(gdb) ptype all_buckets[$index]
type = struct prefork_child_bucket {
ap_pod_t *pod;
ap_listen_rec *listeners;
apr_proc_mutex_t *mutex; <--
}
(gdb) ptype apr_proc_mutex_t
apr_proc_mutex_t {
apr_pool_t *pool;
const apr_proc_mutex_unix_lock_methods_t *meth; <--
int curr_locked;
char *fname;
...
}
(gdb) ptype apr_proc_mutex_unix_lock_methods_t
apr_proc_mutex_unix_lock_methods_t {
...
apr_status_t (*child_init)(apr_proc_mutex_t **, apr_pool_t *, const char *); <--
...
}
Line by line: the first command stores the bucket value of worker 0 in a convenience variable $index. The second prints the entry of all_buckets at that index, showing three pointers: pod, listeners and mutex. The third command prints the type of that entry, prefork_child_bucket, with the same three fields; the arrow marks mutex. The fourth prints the type of the mutex structure, apr_proc_mutex_t, which contains a pointer meth to a table of lock methods; the arrow marks meth. The fifth prints that table's type, apr_proc_mutex_unix_lock_methods_t, a list of function pointers, one of which is child_init; the arrow marks it.
No bound checks happen. A rogue worker can therefore change its bucket index and make it point into the shared memory, in order to control the prefork_child_bucket structure upon restart. Eventually, and before privileges are dropped, mutex->meth->child_init() is called. This results in an arbitrary function call as root.
In plain words: the parent trusts a number written by a weaker process. If the weaker process writes a number that points somewhere else, the parent follows it, reads a fake structure, and then calls a function address taken from that fake structure, all while still holding root power.
The four steps of the exploit
The exploitation is a four step process:
- Obtain R/W access on a worker process
- Write a fake
prefork_child_bucketstructure in the SHM - Make
all_buckets[bucket]point to the structure - Await 6:25AM to get an arbitrary function call
R/W means read and write. The attacker first needs the ability to read and change the worker's memory, then uses that ability to plant fake data, then arranges for the parent to follow a pointer to that fake data, and finally waits for the daily restart to trigger the call.
Step 1: obtain R/W access on a worker process
CVE-2019-6977 would have been a perfect candidate, but it was not out when the exploit was started, so the researcher went with a 0day use-after-free in PHP 7.x, which seems to work in PHP 5.x as well:
<?php
class X extends DateInterval implements JsonSerializable
{
public function jsonSerialize()
{
global $y, $p;
unset($y[0]);
$p = $this->y;
return $this;
}
}
function get_aslr()
{
global $p, $y;
$p = 0;
$y = [new X('PT1S')];
json_encode([1234 => &$y]);
print("ADDRESS: 0x" . dechex($p) . "\n");
return $p;
}
get_aslr();
Line by line: <?php starts a PHP script. class X extends DateInterval implements JsonSerializable declares a class X that inherits from PHP's built-in DateInterval and promises to provide a jsonSerialize method. The method jsonSerialize() is called automatically when the object is converted to JSON. Inside it, global $y, $p; makes the two outer variables visible. unset($y[0]); removes the first element of the array $y, which is the object itself, freeing its memory. $p = $this->y; then reads a property from the object that has just been freed: this is the use-after-free. return $this; returns the object. The function get_aslr() sets $p to 0, creates an array $y containing one new X object, calls json_encode on an array that references $y, which triggers jsonSerialize, and then prints the value now stored in $p as a hexadecimal address. In plain words: the script frees an object, keeps using it, and prints an address that leaks where memory lives.
This is a use-after-free on a PHP object: $y[0], an instance of X, is unset, but the object is still usable through $this.
The goal is twofold: read memory to find the address of all_buckets, and edit the SHM to change the bucket index and add the custom mutex structure. PHP's heap is conveniently located before those two in memory:
root@apaubuntu:~# cat /proc/6318/maps | grep libphp | grep rw-p
7f4a8f9f3000-7f4a8fa0a000 rw-p 00471000 08:02 542265 /usr/lib/apache2/modules/libphp7.2.so
(gdb) p *ap_scoreboard_image
$14 = {
global = 0x7f4a9323e008,
parent = 0x7f4a9323e020,
servers = 0x55835eddea78
}
(gdb) p all_buckets
$15 = (prefork_child_bucket *) 0x7f4a9336b3f0
Line by line: the shell command reads the memory map of process 6318 and filters for the PHP module and for writable memory, showing the range where libphp7.2.so is loaded. The two gdb commands print the scoreboard pointers and the address of all_buckets. Comparing the numbers shows that the PHP heap sits at a lower address than the scoreboard and all_buckets, which is why growing a PHP string can reach them.
Since the UAF is triggered on a PHP object, any property of that object is UAF'd too, which allows converting the zend_object UAF into a zend_string one. That is useful because of the layout of zend_string:
(gdb) ptype zend_string
type = struct _zend_string {
zend_refcounted_h gc;
zend_ulong h;
size_t len;
char val[1];
}
Line by line: zend_string is PHP's internal string type. gc is bookkeeping for memory management, h is a cached hash, len is the length of the string, and val is the first character of the text. The len field is the lever: if the attacker can increase it, PHP will believe the string is longer than it really is.
The len property contains the length of the string. By incrementing it, it becomes possible to read and write further in memory, and therefore reach the two regions of interest: the SHM and Apache's all_buckets.
To change ap_scoreboard_image->parent[worker_id]->bucket for a given worker_id, note that the structure always starts at the beginning of the shared memory block, so it is easy to locate:
root@apaubuntu:~# cat /proc/6318/maps | grep rw-s
7f4a9323e000-7f4a93252000 rw-s 00000000 00:05 57052 /dev/zero (deleted)
(gdb) p &ap_scoreboard_image->parent[0]
$18 = (process_score *) 0x7f4a9323e020
(gdb) p &ap_scoreboard_image->parent[1]
$19 = (process_score *) 0x7f4a9323e044
Line by line: the shell command filters the memory map for shared memory (rw-s), showing the block that backs the scoreboard. The two gdb commands print the addresses of the first two process_score entries, which are close together and inside that block. In plain words: the attacker knows exactly where the bucket fields are, because they always start at the beginning of the shared block.
To locate all_buckets, the knowledge of the prefork_child_bucket structure is used:
prefork_child_bucket {
ap_pod_t *pod;
ap_listen_rec *listeners;
apr_proc_mutex_t *mutex; <--
}
apr_proc_mutex_t {
apr_pool_t *pool;
const apr_proc_mutex_unix_lock_methods_t *meth; <--
int curr_locked;
char *fname;
...
}
apr_proc_mutex_unix_lock_methods_t {
unsigned int flags;
apr_status_t (*create)(apr_proc_mutex_t *, const char *);
apr_status_t (*acquire)(apr_proc_mutex_t *);
apr_status_t (*tryacquire)(apr_proc_mutex_t *);
apr_status_t (*release)(apr_proc_mutex_t *);
apr_status_t (*cleanup)(void *);
apr_status_t (*child_init)(apr_proc_mutex_t **, apr_pool_t *, const char *); <--
apr_status_t (*perms_set)(apr_proc_mutex_t *, apr_fileperms_t, apr_uid_t, apr_gid_t);
apr_lockmech_e mech;
const char *name;
}
Line by line: the first block is the shape of one entry of all_buckets, with a pointer to a mutex. The second block is the shape of that mutex, with a pointer meth to a table of methods. The third block is that table: a set of function pointers, including child_init. The arrows mark the chain the attacker follows: bucket, then mutex, then method table, then function.
all_buckets[0]->mutex is located in the same memory region as all_buckets[0]. Since meth is a static structure, it is located in libapr's .data. Since meth points to functions defined in libapr, each of the function pointers is located in libapr's .text. With knowledge of those regions' addresses from /proc/self/maps, it is possible to go through every pointer in Apache's memory and find one that matches the structure. It will be all_buckets[0].
In plain words: the attacker knows what a real bucket entry looks like, and knows roughly where the library's code and data live, so they can scan memory for a pointer that fits the pattern. The first match is the start of the array.
As mentioned, the address of all_buckets changes at every graceful restart, so when the exploit triggers, its address will differ from the one found. This has to be taken into account later.
Step 2: write a fake prefork_child_bucket structure in the SHM
The code path to the arbitrary function call is the following:
bucket_id = ap_scoreboard_image->parent[id]->bucket
my_bucket = all_buckets[bucket_id]
mutex = &my_bucket->mutex
apr_proc_mutex_child_init(mutex)
(*mutex)->meth->child_init(mutex, pool, fname)
Line by line: the parent reads the bucket value for a worker, uses it to pick an entry from all_buckets, takes the address of that entry's mutex field, calls apr_proc_mutex_child_init on it, and that function calls the child_init function pointer found through the mutex's method table. Each line is one hop in a chain of pointers. If the attacker controls the first number, they control the last call.
To exploit, (*mutex)->meth->child_init is made to point to zend_object_std_dtor(zend_object *object), which yields the following chain:
mutex = &my_bucket->mutex
[object = mutex]
zend_object_std_dtor(object)
ht = object->properties
zend_array_destroy(ht)
zend_hash_destroy(ht)
val = &ht->arData[0]->val
ht->pDestructor(val)
pDestructor is set to system, and &ht->arData[0]->val is a string. Both leftmost structures are superimposed.
Line by line: the attacker arranges for the fake mutex to also look like a PHP object. When the parent calls zend_object_std_dtor (a normal PHP cleanup function) on it, that function reads the object's properties field, treats it as a PHP array, destroys it, and finally calls a destructor function pointer stored in the array, pDestructor, passing it a string. The attacker sets pDestructor to system, the C library function that runs a shell command, and makes the string a command of their choice. So the chain ends with a shell command running as root. "Superimposed" means the same bytes are interpreted as two different structures at once, which is how the attacker makes one fake blob satisfy both the mutex and the PHP object expectations.
Step 3: make all_buckets[bucket] point to the structure
If the address of all_buckets were unchanged between restarts, the exploit would be over: get R/W over all memory after PHP's heap, find all_buckets by matching its structure, put the structure in the SHM, and change one of the process_score.bucket values in the SHM so that all_bucket[bucket]->mutex points to the payload.
Because the address of all_buckets changes, two things improve reliability: spray the SHM and use every process_score structure, one for each PID.
If the new address of all_buckets is not far from the old one, my_bucket will point close to the structure. Instead of having the prefork_child_bucket structure at a precise point in the SHM, it can be sprayed all over unused parts of the SHM. The problem is that the structure is also used as a zend_object, and therefore has a size of (5 * 8 =) 40 bytes to include zend_object.properties. Spraying a structure that big over a space this small will not help much. To solve this, the two centre structures, apr_proc_mutex_t and zend_array, are superimposed, and their address is sprayed in the rest of the shared memory. The impact is that prefork_child_bucket.mutex and zend_object.properties point to the same address. Now, if all_bucket is relocated not too far from its original address, my_bucket will be in the sprayed area.
In plain words: the attacker does not know exactly where the parent will look after the restart, so they fill the shared memory with many copies of a small fake structure. Because the fake structure must serve two purposes at once, they overlap the two shapes so that a single copy works for both. Then, wherever the parent lands nearby, it finds a usable copy.
Each Apache worker has an associated process_score structure, and with it a bucket index. Instead of changing one process_score.bucket value, every one of them can be changed so that they cover another part of memory. For instance:
ap_scoreboard_image->parent[0]->bucket = -10000 -> 0x7faabbcc00 <= all_buckets <= 0x7faabbdd00
ap_scoreboard_image->parent[1]->bucket = -20000 -> 0x7faabbdd00 <= all_buckets <= 0x7faabbff00
ap_scoreboard_image->parent[2]->bucket = -30000 -> 0x7faabbff00 <= all_buckets <= 0x7faabc0000
Line by line: each line sets one worker's bucket to a different negative number. A negative index makes the parent look before the start of its array, into a different range of memory. The comment after the arrow shows which range of addresses that index would reach if all_buckets happened to sit there. By using several workers, the attacker covers several ranges at once.
This multiplies the success rate by the number of Apache workers. Upon respawn, only one worker has a valid bucket number, but this is not a problem because the others will crash and immediately respawn.
Different Apache servers have different numbers of workers. Having more workers means the address of the mutex can be sprayed over less memory, but it also means more index values can be specified for all_buckets. More workers therefore improve the success rate. After a few tries on a test Apache server of 4 workers (the default), the researcher had ~80% success rate. If the exploit fails, it can be restarted the next day, as Apache will still restart properly. Apache's error.log will nevertheless contain notifications about its workers segfaulting.
In plain words: the attacker hedges their bets. Each worker gets a different guess, so if one guess is right, the trick works; the workers whose guesses are wrong simply crash and are replaced. The cost of a wrong guess is a line in the error log, not a broken website.
Step 4: await 6:25AM for the exploit to trigger
That is the easy step. That is the easy step: the daily logrotate job sends the graceful restart.
Where the bug lives in the code
The bug is in server/mpm/prefork/prefork.c. The sequence is:
- A rogue worker changes its
bucketindex in shared memory to make it point to a structure of its own, also in SHM. - At 06:25AM the next day,
logrotaterequests a graceful restart from Apache. - Upon this, the main Apache process first kills workers, and then spawns new ones.
- The killing is done by sending
SIGUSR1to workers, which are expected to exit ASAP.SIGUSR1is a signal, a short message the operating system delivers to a process; here it means "please stop". - Then,
prefork_run()(L853) is called to spawn new workers. Sinceretained->mpm->was_gracefulistrue(L861), workers are not restarted straight away. - Instead, the main loop (L933) is entered and dead workers' PIDs are monitored. When an old worker dies,
ap_wait_or_timeout()returns its PID (L940). - The index of the
process_scorestructure associated with this PID is stored inchild_slot(L948). - If the death of this worker was not fatal (L969),
make_child()is called withap_get_scoreboard_process(child_slot)->bucketas a third argument (L985). As previously said,bucket's value has been changed by a rogue worker. make_child()creates a new child,fork()ing (L671) the main process.fork()makes a copy of the current process; the copy inherits the parent's memory and privileges.- The OOB read happens (L691), and
my_bucketis therefore under the control of an attacker. child_main()is called (L722), and the function call happens a bit further (L433).SAFE_ACCEPT(<code>)will only execute<code>if Apache listens on two ports or more, which is often the case since a server listens over HTTP (80) and HTTPS (443).- Assuming
<code>is executed,apr_proc_mutex_child_init()is called, which results in a call to(*mutex)->meth->child_init(mutex, pool, fname)withmutexunder control. - Privileges are dropped a bit later in the execution (L446).
No bound checks happen on the bucket index, which allows the out-of-bounds read of all_buckets and the subsequent function pointer call before privileges are dropped. In plain words: the parent reads a number from the shared whiteboard, uses it without checking, and only afterwards lowers its own privileges. The window between the read and the drop is where the attacker's code runs.
Impact
You generally obtain root privileges from www-data privileges. The trigger is a graceful restart, which in standard Linux configurations happens once a day at 6:25AM via logrotate. The SAFE_ACCEPT condition means the call path requires Apache to listen on two ports or more, which is often the case with HTTP and HTTPS.
The fix
Apache patched the vulnerability and released version 2.4.39 on 1 April 2019. The report links to the Apache HTTP Server 2.4 vulnerabilities page for CVE-2019-0211. The patch was sent by Apache's security team on 7 March 2019 for review, and approved on 10 March 2019.
Variants to test
The report targets mod_prefork; it states that mod_worker and mod_event are also affected, so the same bucket/all_buckets reasoning is worth checking in those MPMs. The exploit also depends on a worker process that can read and write the SHM, so any deployment where mod_prefork runs alongside an in-process scripting runtime such as mod_php is a candidate.
Hunting notes
This kind of bug hides in shared-memory structures that low-privilege workers can write and that the privileged parent later trusts, especially where an index from the shared area is used to address a parent-side array. The exploit was not released at the time of writing.
Vulnerability timeline
- 2019-02-22 Initial contact email to
security[at]apache[dot]org, with description and POC - 2019-02-25 Acknowledgment of the vulnerability, working on a fix
- 2019-03-07 Apache's security team sends a patch for review, CVE assigned
- 2019-03-10 The patch is approved
- 2019-04-01 Apache HTTP version 2.4.39 released
PHP never answered regarding the UAF.
Glossary
- Apache HTTP Server: the web server program that answers browser requests; the product affected here.
- Arbitrary function call: making a program jump to a function chosen by the attacker.
- ASLR: Address Space Layout Randomisation; a defence that shuffles memory addresses each time a program starts.
- Bounty: a payment made by a programme to a researcher who reports a valid vulnerability.
bucket: an index field in the shared scoreboard that the parent uses to pick an entry fromall_buckets.- CVE: a public identifier for a known vulnerability.
- Denial of service (DoS): making a service unavailable to its users.
fork(): a system call that creates a copy of the current process.- Graceful restart: reloading a server without cutting off ongoing connections; triggered here by
apache2ctl graceful. - Heap: the memory area a program uses for objects created while running.
libapr: the Apache Portable Runtime library; its.dataand.textsections hold static structures and code used by Apache.logrotate: a Linux tool that rotates log files on a schedule and, in this setup, triggers the daily graceful restart at 6:25AM.mod_event,mod_prefork,mod_worker: Apache's Multi-Processing Modules, which decide how work is spread across processes and threads; all three were affected.mod_php: the module that runs PHP inside Apache worker processes.- MPM: Multi-Processing Module; the part of Apache that manages processes and threads.
- Out-of-bounds (OOB) access: reading or writing past the end of an array, into unrelated memory.
- PIE: Position Independent Executable; a defence that lets a program be loaded at a random address.
- PID: process ID; the number the operating system uses to identify a running process.
- Privilege escalation: a bug that lets a weaker account gain a stronger account's powers.
/proc/self/maps: a Linux file listing the memory regions of the current process./proc/self/mem: a Linux file that allows a process to read and write its own memory.root: the superuser account on Linux, with unrestricted power.- R/W: read and write access.
SAFE_ACCEPT: a macro in Apache that only runs its argument when the server listens on two or more ports.- Scoreboard / SHM: the shared-memory area where workers record their state and which the parent reads.
- Segfault: a crash caused by touching invalid memory.
SIGUSR1: a signal sent to a process, used here to tell workers to exit.- Spraying: filling memory with many copies of the same data so that a copy is found wherever the program looks.
system: the C library function that runs a shell command.- Use-after-free (UAF): using an object after its memory has been freed.
www-data: the low-privilege account Apache workers typically run as.zend_object,zend_string,zend_array: PHP's internal types for objects, strings and arrays, used here as building blocks for the fake structures.- 0day: a vulnerability that is not yet publicly known or patched when it is used.