Huawei Security Hypervisor Vulnerability
The security hypervisor's logging system uses shared memory control structures whose fields are not validated, allowing the kernel to write a single non-zero byte to an arbitrary address in the hypervisor's address space. This primitive was used to force an integer underflow in the heap allocator, leading to a stage 2 page table being allocated outside the heap and writable by the kernel, enabling arbitrary code execution at EL2.
blog.impalabs.com
Published on blog.impalabs.com
Alexandre Adamski](https://blog.impalabs.com/authors/alexandre-adamski.html) [{{media:2}}
The full write-up lives on its author's site
It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.
Huawei's security hypervisor runs at EL2 and supervises the kernel at runtime. It enforces access permissions on physical memory through a second stage of address translation and traps modifications of system registers. The kernel calls into it with the HVC instruction, and as a rule of thumb the hypervisor should distrust anything the kernel passes in. During an assessment of this component, that rule held almost everywhere except in one place: the logging system.
This advisory covers CVE-2021-39979, an out-of-bounds access reachable through the logging system; the researchers developed an exploit that achieves arbitrary code execution at EL2 from the kernel.
Context
The logging system uses several buffers of shared memory that both the kernel and the hypervisor can access. On the kernel side, the hhee_logger_init function of the "hisi hhee exception" driver retrieves the physical addresses of these log buffers by invoking the HHEE_LOGBUF_INFO, HHEE_CRASHLOG_INFO and HHEE_PMFBUFLOG_INFO HVCs.
▸ drivers/hisi/hhee/hhee_log.c
int hhee_logger_init(void)
{
// ...
/* get logging information */
/* normal buffer */
ret_res = hhee_fn_hvc((unsigned long)HHEE_LOGBUF_INFO, 0ul, 0ul, 0ul);
ret = cb_init(ret_res.a0, ret_res.a1, &normal_cb, NORMAL_LOG);
// ...
/* crash buffer */
ret_res = hhee_fn_hvc((unsigned long)HHEE_CRASHLOG_INFO, 0ul, 0ul, 0ul);
ret = cb_init(ret_res.a0, ret_res.a1, &crash_cb, CRASH_LOG);
// ...
/* monitor buffer */
ret_res = hhee_fn_hvc((unsigned long)HHEE_PMFBUFLOG_INFO, 0ul, 0ul, 0ul);
ret = cb_init(ret_res.a0, ret_res.a1, &monitor_cb, MONITOR_LOG);
// ...
}
Each log buffer is mapped by cb_init and is then ready to be accessed by the kernel.
▸ drivers/hisi/hhee/hhee_log.c
int cb_init(uint64_t inlog_addr, uint64_t inlog_size,
struct circular_buffer **incb, unsigned int logtype)
{
// ...
log_addr = (uint64_t)(uintptr_t)ioremap_cache(inlog_addr, inlog_size);
// ...
tmp_cb = (struct circular_buffer *) kzalloc(sizeof(struct circular_buffer),
GFP_KERNEL);
// ...
tmp_cb->virt_log_addr = log_addr;
tmp_cb->virt_log_size = inlog_size;
tmp_cb->logtype = logtype;
*incb = tmp_cb;
return 0;
}
On the hypervisor side, the log buffers are initialised from init_log_buffers.
void init_log_buffers(saved_regs_t *regs) {
// ...
init_irq_infobuf();
init_logbuf_info(0x134e0000, 0x10000);
init_crashlog_info(0x134f0000, 0x1000);
init_monitorlog_info(0x134f1000, 0xf000);
init_pmfbuflog_info(0x134d4000, 0xc000);
// ...
}
For example, the LOGBUF_INFO buffer, which spans the region 0x134E0000-0x134F0000, is initialised by init_logbuf_info.
void init_logbuf_info(log_buffer_t *buf, int64_t size) {
buf->data_size = size - 0x28;
buf->head_size = 0x28;
buf->total_off = 0x28;
buf->field_18 = 0;
buf->data_ptr = (char *)buf + 0x28;
g_logbuf_info = buf;
}
Every log buffer region starts with a control structure, log_buffer_t:
typedef struct log_buffer {
int64_t data_size; /* Size of the data section */
int64_t head_size; /* Size of the header section */
int64_t curr_off; /* Current offset in the buffer */
// ...
void* data_ptr; /* Pointer to the data section */
} log_buffer_t;
This control structure holds a pointer, an offset and two size fields, as shown in the figure below.
Strings are written to the log buffer by the hypervisor through write_str_to_logbuf_info. After formatting the arguments of the string, this function writes into the log buffer one character at a time by calling write_chr_to_logbuf_info.
int write_str_to_logbuf_info(const char *fmt, ...) {
char buf[0x88];
// Format the log string arguments.
// ...
hvc_log_lock();
int count = 0;
char *buf_ptr = buf;
// Iterate over the characters of `buf`.
for (char c = *buf_ptr; c; buf_ptr++) {
// Increment the count of written characters.
count++;
// Append the character to the log buffer.
write_chr_to_logbuf_info(c);
}
hvc_log_unlock();
return count;
}
write_chr_to_logbuf_info writes the character into the circular buffer and updates the control structure fields.
int write_chr_to_logbuf_info(char c) {
uint64_t head_size;
uint64_t curr_offset;
uint64_t data_off;
// ...
// Ensure the log buffer is initialized.
if (!g_logbuf_info)
return -1;
// Get the `head_size` and `curr_offset` fields of the control structure.
head_size = g_logbuf_info->head_size;
curr_offset = g_logbuf_info->curr_offset;
// Check if the circular buffer needs to wrap around.
if (curr_offset >= head_size + g_logbuf_info->data_size) {
// Reset the current offset to the beginning of the buffer.
g_logbuf_info->curr_offset = head_size;
data_off = 0;
} else {
// Compute the offset of the next character.
data_off = curr_offset - head_size;
}
// Write the character at the current offset.
*(char *)(g_logbuf_info->data_ptr + data_off) = c;
// Increment the current offset.
++g_logbuf_info->curr_offset;
return c;
}
Finding it
The control structure sits in shared memory, and the hypervisor does not verify the values of its fields. The kernel can therefore change them so that the log string is written at a chosen address in the hypervisor's address space. The logging functions for the other buffers initialised by init_crashlog_info and init_pmfbuflog_info are similar.
Exploitation
This section describes the exploit developed to get arbitrary code execution in the security hypervisor from the kernel.
Constrained write primitive
When a string is logged, each of its characters is written at address data_ptr - head_size + curr_off, where curr_off ranges:
- from offset
head_size, the end of the header and start of the data section; - to
head_size + data_size, the end of the data section and thus of the log buffer.
The log buffers are circular, so when curr_off reaches the end it is reset to head_size.
Modifying the data_ptr field is enough to write the string at an arbitrary address, but the string that is logged is not controlled by the kernel. In this exploit only a single non-zero byte was needed, for the forced integer underflow described in the next section. The primitive was constructed as follows.
The handler of the ARM_STD_HVC_VERSION (0x8400FF03) HVC calls a function that logs the "PMF:cpu %lu\ttid %u\tts %llu\n" string into the LOGBUF_INFO buffer. Setting the data_size field of the control structure to 1 means only one character is needed to fill the buffer and circle back to the beginning. Each character overwrites the previous one, leaving only the last byte of the string in memory, which in this case is the new line character ('\n', i.e. 0x0A). The figure below shows the log buffer in this configuration.
Forcing an integer underflow
The constrained write primitive was used to bump the heap offset, which in turn led to targeting the stage 2 page tables. They are allocated by the hypervisor using a simple heap allocator. The heap region spans the addresses 0x12F14C00-0x134D1000, and the allocation function is alloc_memory_inner.
#define HEAP_START 0x12F14C00
#define HEAP_SIZE 0x5BA400
uint64_t alloc_memory_inner(uint64_t alignment, uint64_t size) {
uint64_t alignment_mask = alignment - 1;
uint64_t heap_current_ptr = HEAP_START + g_heap_offset;
uint64_t padding = -heap_current_ptr & alignment_mask;
// Return if the remaining size is too small to make the allocation.
if (HEAP_SIZE - g_heap_offset < padding + size)
return 0;
// Update the global heap offset.
g_heap_offset += size + padding;
// Log the global heap offset in another log buffer.
if (snprintf(buf, 0x18, 0x17, "heap_offset 0x%lx.\n", g_heap_offset) >= 0)
write_str_to_pmfbuflog_info(buf, 0x18);
return heap_current_ptr + padding;
}
During normal use the check HEAP_SIZE - g_heap_offset < padding + size is not vulnerable and correctly prevents the allocator from returning memory outside the heap region. If the offset is made greater than the heap size, for example with the write primitive, the check passes because of an integer overflow on HEAP_SIZE - g_heap_offset, and the allocator returns memory outside the heap region.
Allocations have a size of 0x1000 bytes, so the first allocation made outside the heap region lands at 0x134D0000 (not 0x134CF000, because of the padding). That region is located in the log buffer, which is mapped by both the hypervisor and the kernel.
To trigger the allocation of a stage 2 page table, the [redacted] function has to be reached through an HVC. It takes an intermediate physical address range as an argument and changes the permissions of that range. If the range is unmapped in the second stage, or currently mapped as a block, changing its permissions requires the allocation of new page tables.
Step 0: The initial state (assuming no allocation has been made).
Step 1: The heap is filled until g_heap_offset equals HEAP_SIZE, by mapping and changing the permissions of physical memory regions located after 0x10000000000. The heap offset can be monitored through the log message written by alloc_memory_inner.
Step 2: g_heap_offset is bumped past HEAP_SIZE with the write primitive, changing its value from 0x5BA400 to 0x5BA40A. As a result, HEAP_SIZE - g_heap_offset is now equal to 0xfffffffffffffff6, which is bigger than padding + size.
Step 3: The allocation that will be made at 0x134D0000, outside the heap region and accessible by the kernel, is triggered by mapping and changing the permissions of the memory block starting at 0x10000000.
Double-mapping the hypervisor
After these three steps, the result is a stage 2 page table that is writable from the kernel. By changing the descriptors contained in this page, the hypervisor's physical address range can be mapped a second time, and this mapping made writable. All that is left is to patch the hypervisor's code and call the modified function to get arbitrary code execution at EL2.
Step 0: The initial content of the kernel-accessible stage 2 page table.
Step 1: The output addresses of the descriptors are modified to map the IPA range 0x10000000 to 0x10200000 to the PA range 0x12F00000 to 0x13100000. The attributes are also changed to make the mapping read-write.
Step 2: Using the writable mapping, the HHEE_HVC_LIVEPATCH (0xC6001088) HVC handler is patched with a simple shellcode that returns the current exception level.
Root cause
The hypervisor trusts the contents of the log buffer control structures, which live in memory shared with the kernel. write_chr_to_logbuf_info reads head_size, curr_offset and data_ptr straight from that shared structure and uses them to compute the write destination, without validating them. A kernel that rewrites those fields redirects the hypervisor's own writes to an address of its choosing.
The same write primitive feeds the second bug: g_heap_offset is bumped past HEAP_SIZE with the constrained write, and alloc_memory_inner performs its bounds check with a subtraction that wraps once the offset exceeds HEAP_SIZE. The check that should keep allocations inside the heap region therefore passes, and the allocator hands out memory outside it.
Impact
An attacker who controls the kernel can escalate to the security hypervisor at EL2: the exploit achieves arbitrary code execution there. The vulnerability was verified on the following devices:
| SoC | Device |
|---|---|
| Kirin 710 | P30 Lite (MAR) |
| Kirin 810 | P40 Lite (JNY) |
Other models might have been affected.
Fix
This vulnerability was assigned CVE-2021-39979 and patched in the October 2021 security update.
Timeline
- Jul. 09, 2021 - A vulnerability report is sent to Huawei PSIRT.
- Jul. 22, 2021 - Huawei PSIRT acknowledges the vulnerability report.
- Oct. 01, 2021 - The issue is fixed in the October 2021 update.
Variants to test
- Other shared log buffers. The logging functions for the buffers initialised by
init_crashlog_infoandinit_pmfbuflog_infoare similar to theLOGBUF_INFOpath. On a related target, look for any hypervisor log buffer whose control structure is mapped into the kernel and check whether its fields are validated before use. A positive result is a kernel write to the control structure that changes where the hypervisor's next log character lands. - Other HVC handlers that log. The constrained write primitive relied on the
ARM_STD_HVC_VERSION(0x8400FF03) handler logging a fixed string. Enumerate HVC handlers that log and check whether any of them can be driven with adata_sizeof 1 to leave a single chosen byte in memory. A positive result is a log buffer whose contents after the call are a single byte at a location you selected. - Heap offset reachability. The underflow depended on
g_heap_offsetbeing writable through the shared log buffer. On another hypervisor, check whether allocator bookkeeping variables are reachable from kernel-shared memory, then set the offset just past the heap size and trigger an allocation. A positive result is an allocation returned outside the documented heap region, at an address the kernel can map. - Allocator bounds checks. Review other size checks of the form
SIZE - offset < padding + sizefor unsigned wraparound. A positive result is a check that passes when the offset exceeds the size, letting the allocator return memory beyond its region. - Permission-change HVCs. The page table allocation was triggered through
[redacted]. Test other HVCs that change stage 2 permissions on unmapped or block-mapped ranges and observe whether they allocate page tables at attacker-influenced addresses. A positive result is a new page table placed in memory the kernel can write.
What happened, in plain words
Huawei phones run a small piece of software called a security hypervisor. Think of it as a security guard standing behind the normal operating system: the operating system (the kernel) does the everyday work, and the guard watches over it, checking that it does not touch memory it is not allowed to touch. The guard is supposed to be more privileged than the kernel, running at EL2 while the kernel runs at a lower level.
This advisory describes a bug that breaks that promise. The guard and the kernel share a small area of memory used for writing log messages (a diary of what happened). The guard reads some bookkeeping numbers from that shared area and trusts them without checking. Because the kernel can also write to that shared area, an attacker who controls the kernel can change those numbers and trick the guard into writing to a place of the attacker's choosing. From there, the researchers built a chain that lets them run their own code inside the guard itself.
The bug is tracked as CVE-2021-39979. The advisory was written by Alexandre Adamski and Maxime Peterlin and published on 1 December 2022. It was fixed in Huawei's October 2021 security update.
Background: the pieces involved
Before walking through the bug, here are the ideas you need. Each one is explained from scratch.
The kernel and the hypervisor
A phone's main processor runs several layers of software. The kernel is the core of the operating system: it manages memory, decides which app can use which resource, and talks to the hardware. Above the kernel sit the apps you actually see.
A hypervisor is a layer that runs below the kernel and watches it. On Huawei devices the security hypervisor is a privileged component that supervises the kernel while it runs. It does two jobs described in the advisory:
- it enforces access permissions on physical memory using a second stage of address translation;
- it traps modifications of system registers, meaning it intercepts attempts to change certain low-level settings.
Exception levels (EL2)
ARM processors, which Huawei phones use, number their privilege levels. The higher the number, the more power the code at that level has. The advisory says the security hypervisor executes at EL2, while the kernel runs at a lower level. Code at EL2 can do things code at the kernel level cannot, which is exactly why taking over EL2 matters: it is a step up in power, not down.
The HVC instruction
The kernel cannot simply call a function inside the hypervisor the way one program calls another. Instead it uses a special processor instruction called HVC (Hypervisor Call). Think of it as ringing a doorbell at the guard's office: the kernel passes a number identifying which service it wants, plus some arguments, and the hypervisor handles the request.
The advisory states a rule of thumb: the hypervisor should distrust any information coming from the kernel. The kernel is the less privileged side, so anything it hands over could be malicious. During the assessment, the researchers found this rule held almost everywhere, except in one place: the logging system.
Physical and virtual addresses
Programs do not use raw hardware addresses directly. The processor translates a virtual address (what the program sees) into a physical address (where the data really sits in the memory chips). This translation is done through tables, and the hypervisor adds a second stage on top, so there are two rounds of translation. That second stage is how the hypervisor controls which physical memory the kernel is allowed to reach.
Shared memory
Normally the kernel and the hypervisor are kept apart. But sometimes they need to exchange data, and the simplest way is a region of memory that both can read and write. The logging system uses exactly this: several buffers (chunks of memory) of shared memory that can be accessed both by the kernel and the hypervisor. Shared memory is convenient, but it is also a trust boundary: whatever one side writes, the other side must treat with suspicion.
What a log buffer is
A log buffer is a place where software writes messages about what it is doing, so that later someone can read them back for debugging. The advisory describes these buffers as circular: when the writer reaches the end, it wraps around to the beginning and starts overwriting the oldest entries. This keeps the buffer a fixed size forever.
Context: how the logging system is set up
The kernel side
On the kernel side, a driver called "hisi hhee exception" contains a function named hhee_logger_init. Its job is to ask the hypervisor where the log buffers live. It does this by making three HVC calls, one for each buffer: HHEE_LOGBUF_INFO, HHEE_CRASHLOG_INFO and HHEE_PMFBUFLOG_INFO.
▸ drivers/hisi/hhee/hhee_log.c
This line is just a label telling you which file in the kernel source tree the following code comes from: drivers/hisi/hhee/hhee_log.c.
int hhee_logger_init(void)
{
// ...
/* get logging information */
/* normal buffer */
ret_res = hhee_fn_hvc((unsigned long)HHEE_LOGBUF_INFO, 0ul, 0ul, 0ul);
ret = cb_init(ret_res.a0, ret_res.a1, &normal_cb, NORMAL_LOG);
// ...
/* crash buffer */
ret_res = hhee_fn_hvc((unsigned long)HHEE_CRASHLOG_INFO, 0ul, 0ul, 0ul);
ret = cb_init(ret_res.a0, ret_res.a1, &crash_cb, CRASH_LOG);
// ...
/* monitor buffer */
ret_res = hhee_fn_hvc((unsigned long)HHEE_PMFBUFLOG_INFO, 0ul, 0ul, 0ul);
ret = cb_init(ret_res.a0, ret_res.a1, &monitor_cb, MONITOR_LOG);
// ...
}
Line by line:
int hhee_logger_init(void)declares a function that takes no arguments and returns an integer (a success or error code).- The
// ...and/* ... */lines are comments, notes for humans that the processor ignores. ret_res = hhee_fn_hvc((unsigned long)HHEE_LOGBUF_INFO, 0ul, 0ul, 0ul);rings the hypervisor's doorbell asking for the normal log buffer.HHEE_LOGBUF_INFOis the service number. The three0ularguments are placeholders (zero, as an unsigned long). The answer comes back inret_res.ret = cb_init(ret_res.a0, ret_res.a1, &normal_cb, NORMAL_LOG);takes two values from the answer,a0anda1(the address and the size of the buffer), and passes them tocb_init, which prepares the buffer for use. The result is stored innormal_cband tagged asNORMAL_LOG.- The same pattern repeats for the crash buffer (
HHEE_CRASHLOG_INFO, stored incrash_cb, taggedCRASH_LOG) and the monitor buffer (HHEE_PMFBUFLOG_INFO, stored inmonitor_cb, taggedMONITOR_LOG).
Why this matters: the kernel is asking the hypervisor for the addresses of memory the two of them will share. Those addresses are the first link in the chain.
Mapping the buffers
Each log buffer is then mapped by a function called cb_init. Mapping means making a region of physical memory visible to the kernel under a virtual address, so the kernel can read and write it.
▸ drivers/hisi/hhee/hhee_log.c
int cb_init(uint64_t inlog_addr, uint64_t inlog_size,
struct circular_buffer **incb, unsigned int logtype)
{
// ...
log_addr = (uint64_t)(uintptr_t)ioremap_cache(inlog_addr, inlog_size);
// ...
tmp_cb = (struct circular_buffer *) kzalloc(sizeof(struct circular_buffer),
GFP_KERNEL);
// ...
tmp_cb->virt_log_addr = log_addr;
tmp_cb->virt_log_size = inlog_size;
tmp_cb->logtype = logtype;
*incb = tmp_cb;
return 0;
}
Line by line:
- The function takes four things:
inlog_addr(the physical address of the buffer),inlog_size(its size),incb(where to store the resulting bookkeeping object) andlogtype(a label saying which buffer this is). ioremap_cache(inlog_addr, inlog_size)makes that physical region visible to the kernel and returns a virtual address, stored inlog_addr.kzalloc(...)allocates a small block of kernel memory to hold astruct circular_buffer, a bookkeeping record.kzalloczeroes the memory as it allocates it.- The next three lines fill in that record: the virtual address of the buffer, its size, and its type label.
*incb = tmp_cb;hands the record back to the caller through the pointer it supplied.return 0;signals success.
Why this matters: after this step the kernel has a working handle on the shared log buffer, and can read and write it freely.
The hypervisor side
On the hypervisor side, the buffers are set up by a function called init_log_buffers.
void init_log_buffers(saved_regs_t *regs) {
// ...
init_irq_infobuf();
init_logbuf_info(0x134e0000, 0x10000);
init_crashlog_info(0x134f0000, 0x1000);
init_monitorlog_info(0x134f1000, 0xf000);
init_pmfbuflog_info(0x134d4000, 0xc000);
// ...
}
Line by line:
init_irq_infobuf();sets up an interrupt-related buffer (the advisory does not go into detail on this one).init_logbuf_info(0x134e0000, 0x10000);sets up the normal log buffer at physical address0x134e0000with a size of0x10000bytes.init_crashlog_info(0x134f0000, 0x1000);sets up the crash log buffer at0x134f0000, size0x1000.init_monitorlog_info(0x134f1000, 0xf000);sets up the monitor log buffer at0x134f1000, size0xf000.init_pmfbuflog_info(0x134d4000, 0xc000);sets up the PMF buffer log at0x134d4000, size0xc000.
Why this matters: these are the exact memory locations the two sides will share. The numbers are hexadecimal (base 16), which programmers use because they line up neatly with memory sizes.
Inside one buffer
Take the LOGBUF_INFO buffer, which spans the region 0x134E0000-0x134F0000. It is initialised by init_logbuf_info.
void init_logbuf_info(log_buffer_t *buf, int64_t size) {
buf->data_size = size - 0x28;
buf->head_size = 0x28;
buf->total_off = 0x28;
buf->field_18 = 0;
buf->data_ptr = (char *)buf + 0x28;
g_logbuf_info = buf;
}
Line by line:
- The function receives
buf, a pointer to the start of the buffer, andsize, its total size. buf->data_size = size - 0x28;reserves the first0x28bytes (40 in decimal) for a header, and records how much space is left for actual log data.buf->head_size = 0x28;records the header size.buf->total_off = 0x28;sets the starting offset to the end of the header.buf->field_18 = 0;zeroes another field (the advisory does not say what it is for).buf->data_ptr = (char *)buf + 0x28;computes a pointer to where the data section begins, just past the header.g_logbuf_info = buf;stores the buffer's address in a global variable so the rest of the hypervisor can find it.
Why this matters: the first 40 bytes of every log buffer are a control structure, a small block of bookkeeping numbers that describe how the rest of the buffer should be used.
The control structure
Every log buffer region starts with a control structure, log_buffer_t, defined as follows.
typedef struct log_buffer {
int64_t data_size; /* Size of the data section */
int64_t head_size; /* Size of the header section */
int64_t curr_off; /* Current offset in the buffer */
// ...
void* data_ptr; /* Pointer to the data section */
} log_buffer_t;
Line by line:
typedef struct log_buffer { ... } log_buffer_t;defines a new named type. A struct is a bundle of related values stored together in memory, like a form with several fields.int64_t data_size;is the size of the data section, a 64-bit integer.int64_t head_size;is the size of the header section.int64_t curr_off;is the current position in the buffer, i.e. where the next character will go.void* data_ptr;is a pointer (a memory address) to the start of the data section.
This control structure contains a pointer, an offset and two size fields, as shown in the following figure.
Why this matters: these four values decide where the hypervisor writes each log character. If an attacker can change them, the attacker can change the destination.
Writing a string to the log
Strings are written to the log buffer by the hypervisor using write_str_to_logbuf_info. After formatting the arguments of the string, this function writes into the log buffer one character at a time by calling write_chr_to_logbuf_info.
int write_str_to_logbuf_info(const char *fmt, ...) {
char buf[0x88];
// Format the log string arguments.
// ...
hvc_log_lock();
int count = 0;
char *buf_ptr = buf;
// Iterate over the characters of `buf`.
for (char c = *buf_ptr; c; buf_ptr++) {
// Increment the count of written characters.
count++;
// Append the character to the log buffer.
write_chr_to_logbuf_info(c);
}
hvc_log_unlock();
return count;
}
Line by line:
- The function takes a format string
fmtand a variable number of extra arguments (...), likeprintfin everyday programming. char buf[0x88];reserves a small local scratch area of0x88bytes to hold the formatted message.- The commented-out lines would format the arguments into
buf. hvc_log_lock();takes a lock so two writers cannot interleave their characters.int count = 0;starts a counter of written characters.char *buf_ptr = buf;points at the start of the formatted message.- The
forloop walks through the message one character at a time.char c = *buf_ptrreads the current character;cbeing non-zero means "not the end of the string yet";buf_ptr++moves to the next character. - Inside the loop,
count++increments the counter andwrite_chr_to_logbuf_info(c)appends the character to the log buffer. hvc_log_unlock();releases the lock.return count;reports how many characters were written.
Why this matters: the string is written one character at a time, and each character's destination is computed from the control structure. That is the point where the bug lives.
The per-character write
write_chr_to_logbuf_info writes the character into the circular buffer and updates the control structure fields.
int write_chr_to_logbuf_info(char c) {
uint64_t head_size;
uint64_t curr_offset;
uint64_t data_off;
// ...
// Ensure the log buffer is initialized.
if (!g_logbuf_info)
return -1;
// Get the `head_size` and `curr_offset` fields of the control structure.
head_size = g_logbuf_info->head_size;
curr_offset = g_logbuf_info->curr_offset;
// Check if the circular buffer needs to wrap around.
if (curr_offset >= head_size + g_logbuf_info->data_size) {
// Reset the current offset to the beginning of the buffer.
g_logbuf_info->curr_offset = head_size;
data_off = 0;
} else {
// Compute the offset of the next character.
data_off = curr_offset - head_size;
}
// Write the character at the current offset.
*(char *)(g_logbuf_info->data_ptr + data_off) = c;
// Increment the current offset.
++g_logbuf_info->curr_offset;
return c;
}
Line by line:
- The function takes one character
cand declares three 64-bit unsigned integers:head_size,curr_offsetanddata_off. if (!g_logbuf_info) return -1;bails out if the buffer has not been initialised yet.head_size = g_logbuf_info->head_size;andcurr_offset = g_logbuf_info->curr_offset;read two fields straight out of the shared control structure. No check is made on their values.- The
ifchecks whether the current offset has reached the end of the data section (head_size + data_size). If so, it resets the offset tohead_sizeand setsdata_offto 0, wrapping around to the start. - Otherwise,
data_off = curr_offset - head_size;computes how far into the data section the character should go. *(char *)(g_logbuf_info->data_ptr + data_off) = c;is the actual write: it takesdata_ptrfrom the shared structure, addsdata_off, and stores the character at that address.++g_logbuf_info->curr_offset;advances the offset for the next character.return c;returns the character written.
Why this matters: data_ptr, head_size and curr_offset all come from memory the kernel can write. The hypervisor uses them to compute a destination address and writes there without validating anything. That is the whole vulnerability in one sentence.
Finding it
The control structure sits in shared memory, and the hypervisor does not verify the values of its fields. The kernel can therefore change them so that the log string is written at a chosen address in the hypervisor's address space. The logging functions for the other buffers initialised by init_crashlog_info and init_pmfbuflog_info are similar.
In plain terms: the guard keeps a notebook in a drawer that both the guard and the kernel can open. The guard reads the notebook to decide where to write the next line, and never checks whether the notebook has been tampered with. The kernel can rewrite the notebook to say "write the next line over there instead", and the guard will obediently do it.
Exploitation
This section describes the exploit developed to get arbitrary code execution in the security hypervisor from the kernel. Arbitrary code execution means the attacker gets to run their own instructions on the target, rather than just reading or writing data.
Constrained write primitive
A primitive in exploitation is a small, reliable capability that you build up and then combine with others. This one is constrained because it can only write certain bytes to certain places, not anything anywhere.
When a string is logged, each of its characters is written at address data_ptr - head_size + curr_off, where curr_off ranges:
- from offset
head_size, the end of the header and start of the data section; - to
head_size + data_size, the end of the data section and thus of the log buffer.
The log buffers are circular, so when curr_off reaches the end it is reset to head_size.
Modifying the data_ptr field is enough to write the string at an arbitrary address, but the string that is logged is not controlled by the kernel. In this exploit only a single non-zero byte was needed, for the forced integer underflow described in the next section. The primitive was constructed as follows.
The handler of the ARM_STD_HVC_VERSION (0x8400FF03) HVC calls a function that logs the "PMF:cpu %lu\ttid %u\tts %llu\n" string into the LOGBUF_INFO buffer. Setting the data_size field of the control structure to 1 means only one character is needed to fill the buffer and circle back to the beginning. Each character overwrites the previous one, leaving only the last byte of the string in memory, which in this case is the new line character ('\n', i.e. 0x0A). The figure below shows the log buffer in this configuration.
Why this step was taken: the attacker needs to change one specific number in memory (the heap offset, explained next) by a small amount. Writing a single 0x0A byte at a chosen address is enough for that. The trick of setting data_size to 1 turns a fixed log message into a one-byte write at an address the attacker chooses by editing data_ptr.
Forcing an integer underflow
The constrained write primitive was used to bump the heap offset, which in turn led to targeting the stage 2 page tables. Page tables are the data structures the processor uses to translate virtual addresses into physical ones; the stage 2 tables are the hypervisor's own layer of that translation. If the attacker can edit those tables, they can change which physical memory the kernel is allowed to reach.
The page tables are allocated by the hypervisor using a simple heap allocator. A heap allocator is a piece of software that hands out chunks of memory on request and keeps track of what has been used. The heap region spans the addresses 0x12F14C00-0x134D1000, and the allocation function is alloc_memory_inner.
#define HEAP_START 0x12F14C00
#define HEAP_SIZE 0x5BA400
uint64_t alloc_memory_inner(uint64_t alignment, uint64_t size) {
uint64_t alignment_mask = alignment - 1;
uint64_t heap_current_ptr = HEAP_START + g_heap_offset;
uint64_t padding = -heap_current_ptr & alignment_mask;
// Return if the remaining size is too small to make the allocation.
if (HEAP_SIZE - g_heap_offset < padding + size)
return 0;
// Update the global heap offset.
g_heap_offset += size + padding;
// Log the global heap offset in another log buffer.
if (snprintf(buf, 0x18, 0x17, "heap_offset 0x%lx.\n", g_heap_offset) >= 0)
write_str_to_pmfbuflog_info(buf, 0x18);
return heap_current_ptr + padding;
}
Line by line:
#define HEAP_START 0x12F14C00and#define HEAP_SIZE 0x5BA400give names to two constants: where the heap begins and how big it is.uint64_t alignment_mask = alignment - 1;prepares a mask used to round the allocation up to a required alignment (for example, starting on a 4096-byte boundary).uint64_t heap_current_ptr = HEAP_START + g_heap_offset;computes the current position in the heap by adding the running offsetg_heap_offsetto the start.uint64_t padding = -heap_current_ptr & alignment_mask;computes how many bytes of padding are needed to reach the next aligned address.if (HEAP_SIZE - g_heap_offset < padding + size) return 0;is the bounds check: if the remaining space is too small for this allocation, refuse and return 0. This is the line that is supposed to keep allocations inside the heap.g_heap_offset += size + padding;advances the running offset past the newly allocated block.- The
snprintfline formats a message"heap_offset 0x%lx.\n"containing the new offset, andwrite_str_to_pmfbuflog_infowrites it to another log buffer. This is a debugging aid, and it also lets the attacker watch the offset change. return heap_current_ptr + padding;returns the address of the allocated block.
During normal use the check HEAP_SIZE - g_heap_offset < padding + size is not vulnerable and correctly prevents the allocator from returning memory outside the heap region. If the offset is made greater than the heap size, for example with the write primitive, the check passes because of an integer overflow on HEAP_SIZE - g_heap_offset, and the allocator returns memory outside the heap region.
An integer overflow here is really an underflow: the numbers are unsigned (they cannot go negative), so subtracting a larger number from a smaller one wraps around to a huge value. If g_heap_offset is slightly bigger than HEAP_SIZE, then HEAP_SIZE - g_heap_offset becomes a number close to the maximum possible, which is certainly bigger than padding + size, so the check passes when it should fail.
Allocations have a size of 0x1000 bytes, so the first allocation made outside the heap region lands at 0x134D0000 (not 0x134CF000, because of the padding). That region is located in the log buffer, which is mapped by both the hypervisor and the kernel. In other words, the allocator hands out a page table that sits inside memory the kernel can already write to.
To trigger the allocation of a stage 2 page table, the [redacted] function has to be reached through an HVC. It takes an intermediate physical address range as an argument and changes the permissions of that range. If the range is unmapped in the second stage, or currently mapped as a block, changing its permissions requires the allocation of new page tables.
The exploit proceeds in four steps, illustrated below.
Step 0: The initial state (assuming no allocation has been made).
Step 1: The heap is filled until g_heap_offset equals HEAP_SIZE, by mapping and changing the permissions of physical memory regions located after 0x10000000000. The heap offset can be monitored through the log message written by alloc_memory_inner.
Why this step was taken: the underflow only works if the offset is already at or near the end of the heap. Filling the heap first brings the offset to exactly HEAP_SIZE, so a tiny nudge is enough to push it over.
Step 2: g_heap_offset is bumped past HEAP_SIZE with the write primitive, changing its value from 0x5BA400 to 0x5BA40A. As a result, HEAP_SIZE - g_heap_offset is now equal to 0xfffffffffffffff6, which is bigger than padding + size.
Why this step was taken: this is where the one-byte write from the previous section is used. The offset is nudged just past the limit, so the bounds check wraps around and passes.
Step 3: The allocation that will be made at 0x134D0000, outside the heap region and accessible by the kernel, is triggered by mapping and changing the permissions of the memory block starting at 0x10000000.
Why this step was taken: the attacker needs the hypervisor to actually allocate a page table now, so that the out-of-bounds allocation happens. Asking for a permission change on a range that needs new page tables does exactly that.
Double-mapping the hypervisor
After these three steps, the result is a stage 2 page table that is writable from the kernel. By changing the descriptors contained in this page, the hypervisor's physical address range can be mapped a second time, and this mapping made writable. All that is left is to patch the hypervisor's code and call the modified function to get arbitrary code execution at EL2.
A descriptor here is an entry in a page table that says "this virtual range points to that physical range, with these permissions". Editing descriptors lets the attacker create a second view of the hypervisor's own memory, this time writable from the kernel side.
Step 0: The initial content of the kernel-accessible stage 2 page table.
Step 1: The output addresses of the descriptors are modified to map the IPA range 0x10000000 to 0x10200000 to the PA range 0x12F00000 to 0x13100000. The attributes are also changed to make the mapping read-write.
Why this step was taken: the attacker points a range they can reach from the kernel at the hypervisor's own physical memory, and marks it writable. IPA here means intermediate physical address, the address as seen before the second stage of translation; PA means physical address, the real location in memory.
Step 2: Using the writable mapping, the HHEE_HVC_LIVEPATCH (0xC6001088) HVC handler is patched with a simple shellcode that returns the current exception level.
Why this step was taken: this proves the escalation. Shellcode is a small piece of attacker-written machine code. Patching the handler means replacing the hypervisor's own instructions with the attacker's. Returning the current exception level is a simple way to show that the code is now running at EL2, the hypervisor's level.
Root cause
The hypervisor trusts the contents of the log buffer control structures, which live in memory shared with the kernel. write_chr_to_logbuf_info reads head_size, curr_offset and data_ptr straight from that shared structure and uses them to compute the write destination, without validating them. A kernel that rewrites those fields redirects the hypervisor's own writes to an address of its choosing.
The same write primitive feeds the second bug: g_heap_offset is bumped past HEAP_SIZE with the constrained write, and alloc_memory_inner performs its bounds check with a subtraction that wraps once the offset exceeds HEAP_SIZE. The check that should keep allocations inside the heap region therefore passes, and the allocator hands out memory outside it.
In everyday terms: the guard trusts the notebook, and the notebook also contains the guard's own tally of how much storage is left. Rewriting the tally makes the guard believe there is plenty of room when there is none, so it hands out a storage box that is actually outside the storeroom, in a place the kernel can reach.
Impact
An attacker who controls the kernel can escalate to the security hypervisor at EL2: the exploit achieves arbitrary code execution there. The vulnerability was verified on the following devices:
| SoC | Device |
|---|---|
| Kirin 710 | P30 Lite (MAR) |
| Kirin 810 | P40 Lite (JNY) |
Other models might have been affected.
An SoC (system on a chip) is the main processor chip inside a phone, which bundles several processing units together. The table lists the chip and a phone model that uses it.
Fix
This vulnerability was assigned CVE-2021-39979 and patched in the October 2021 security update.
Timeline
- Jul. 09, 2021 - A vulnerability report is sent to Huawei PSIRT.
- Jul. 22, 2021 - Huawei PSIRT acknowledges the vulnerability report.
- Oct. 01, 2021 - The issue is fixed in the October 2021 update.
PSIRT stands for Product Security Incident Response Team: the group inside a company that receives reports of security bugs and coordinates fixing them.
Variants to test
- Other shared log buffers. The logging functions for the buffers initialised by
init_crashlog_infoandinit_pmfbuflog_infoare similar to theLOGBUF_INFOpath. On a related target, look for any hypervisor log buffer whose control structure is mapped into the kernel and check whether its fields are validated before use. A positive result is a kernel write to the control structure that changes where the hypervisor's next log character lands. - Other HVC handlers that log. The constrained write primitive relied on the
ARM_STD_HVC_VERSION(0x8400FF03) handler logging a fixed string. Enumerate HVC handlers that log and check whether any of them can be driven with adata_sizeof 1 to leave a single chosen byte in memory. A positive result is a log buffer whose contents after the call are a single byte at a location you selected. - Heap offset reachability. The underflow depended on
g_heap_offsetbeing writable through the shared log buffer. On another hypervisor, check whether allocator bookkeeping variables are reachable from kernel-shared memory, then set the offset just past the heap size and trigger an allocation. A positive result is an allocation returned outside the documented heap region, at an address the kernel can map. - Allocator bounds checks. Review other size checks of the form
SIZE - offset < padding + sizefor unsigned wraparound. A positive result is a check that passes when the offset exceeds the size, letting the allocator return memory beyond its region. - Permission-change HVCs. The page table allocation was triggered through
[redacted]. Test other HVCs that change stage 2 permissions on unmapped or block-mapped ranges and observe whether they allocate page tables at attacker-influenced addresses. A positive result is a new page table placed in memory the kernel can write.
Glossary
- Arbitrary code execution: the ability for an attacker to run their own instructions on a target system.
- Buffer: a chunk of memory used to hold data temporarily.
- Circular buffer: a fixed-size buffer that wraps around to the beginning when full, overwriting the oldest data.
- Control structure: a small block of bookkeeping values that describes how a larger structure should be used.
- CVE: Common Vulnerabilities and Exposures, a public identifier assigned to a specific security bug.
- Descriptor: an entry in a page table that maps a virtual range to a physical range with given permissions.
- EL2: Exception Level 2, a privilege level on ARM processors higher than the kernel's, used by hypervisors.
- Heap allocator: software that hands out chunks of memory on request and tracks what has been used.
- HVC: Hypervisor Call, a processor instruction the kernel uses to request a service from the hypervisor.
- Hypervisor: a privileged software layer that runs below the kernel and supervises it.
- Integer overflow / underflow: when an arithmetic result does not fit in the number of bits available and wraps around to an unexpected value.
- IPA: intermediate physical address, the address as seen before the second stage of translation.
- Kernel: the core of an operating system, managing memory, resources and hardware.
- Log buffer: a region of memory where software writes messages about what it is doing.
- Mapping: making a region of physical memory visible at a virtual address.
- PA: physical address, the real location of data in memory.
- Page table: a data structure the processor uses to translate virtual addresses into physical ones.
- Primitive: a small, reliable exploitation capability that is combined with others.
- PSIRT: Product Security Incident Response Team, the group inside a company that handles security reports.
- Shellcode: a small piece of attacker-written machine code.
- SoC: system on a chip, the main processor chip inside a device.
- Stage 2 page table: the hypervisor's own layer of address translation, controlling which physical memory the kernel can reach.
- Struct: a bundle of related values stored together in memory.
- Virtual address: the address a program sees, translated by the processor into a physical address.