Skip to content
Memory corruption Write-up Advanced

CVE-2018-9411: New critical vulnerability in multiple high-privileged Android services

A 64-bit size field in the HIDL hidl_memory structure is truncated to 32 bits when mapped by a 32-bit process, so bounds checks based on the full size pass while the actual mapped region is much smaller. An attacker could use this to gain out-of-bounds read and write in a vulnerable HAL service, and the author demonstrated hijacking a thread to run a ROP chain and access the TEE device.

Tamir Zahavi-Brunner Follow

Published on blog.zimperium.com

{{media:0}}As part of our platform research in Zimperium zLabs, I have recently disclosed a critical vulnerability affecting multiple high-privileged Android services to Google. Google designated it as CVE-2018-9411 and patched it in the July security update (2018-07-01 patch level), including additional patches in…

Tamir Zahavi-Brunner, on blog.zimperium.com

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

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

Context

Project Treble split many Android system services that previously mixed AOSP (Android Open Source Project) code and vendor code into one AOSP service and one or more vendor services, called HAL services. That split increases the amount of inter-process communication, because data that used to move inside a single process between AOSP and vendor code now has to cross a process boundary. Most IPC in Android goes through Binder, so Google made the new IPC use Binder as well, with two changes: multiple Binder domains to separate this new IPC from other IPC, and HIDL, a new format for the data passed through Binder IPC, supported by a new set of libraries and dedicated to the new Binder domain used between AOSP and HAL services. Other Binder domains still use the old format.

The two stacks are layered similarly: the Binder kernel driver underneath, a different library set on top. The new HIDL libraries contain code very similar to the old ones, to the point that some original code was copied into them. Both sets represent data transferred in Binder transactions as C++ objects, from simple ones such as strings to more complex ones such as file descriptors or references to other services.

Binder limits each transaction to a maximum size of 1MB, so processes that want to share larger amounts of data use shared memory. They do this through Binder's file descriptor sharing: a file descriptor can be mapped with mmap, so sharing the descriptor shares the memory region. Because regular Linux file descriptors are normally backed by files, Android provides ashmem, which lets processes allocate memory to back file descriptors without an actual file involved. In both the HIDL and the old libraries the eventual actions are the same: one process maps an ashmem file descriptor, transfers it through Binder, and the other process maps it in its own memory space. The implementations differ.

In HIDL the object that handles this is hidl_memory, described in the source as "a structure that can be used to transfer pieces of shared memory between processes".

From the original on blog.zimperium.com

Setup

The source links in the write-up point at the android-8.1.0_r29 tags. The proof-of-concept exploit targets one specific device and build: a Pixel 2 with the May 2018 security update, build fingerprint google/walleye/walleye:8.1.0/OPM2.171019.029.B1/4720900:user/release-keys. A link to the full exploit code is available at the end of the blog post.

The vulnerability was reported to Google, designated CVE-2018-9411, and patched in the July 2018 security update (2018-07-01 patch level), with additional patches in the September 2018 security update (2018-09-01 patch level).

Finding it

hidl_memory has three members:

From the original on blog.zimperium.com
  • mHandle: a handle, a HIDL object that holds file descriptors (only one in this case).
  • mSize: the size of the memory to be shared.
  • mName: supposed to represent the type of memory, but only the ashmem type is really relevant here.

When such a structure crosses Binder in HIDL, complex objects (like hidl_handle or hidl_string) have their own custom code for writing and reading the data, while simple types such as integers are transferred as is. The size is therefore transferred as a 64 bit integer. In the old set of libraries a 32 bit integer is used for the same purpose.

That raised two questions: why use 64 bit at all, and, more importantly, how would a 32 bit process handle it? The code that maps a hidl_memory object for the ashmem type says nothing about 32 bit processes and does not even mention that the size is 64 bit:

From the original on blog.zimperium.com

The length field in mmap's signature is a size_t, so its width matches the process. In a 64 bit process everything is 64 bit and there is no issue. In a 32 bit process the size is truncated to 32 bits, so only the lower 32 bits are used. A 32 bit process that receives a hidl_memory whose size is larger than UINT32_MAX (0xFFFFFFFF) maps a much smaller region than the size claims: a hidl_memory of size 0x100001000 results in a mapped region of only 0x1000. If that process then performs bounds checks against the hidl_memory size, the checks pass for offsets far outside the real mapping, because the size falsely indicates that the region spans more than the entire memory space. That is the vulnerability.

Exploitation

Step 1: pick a target

The requirements for a target HAL service were:

  1. It compiles to 32 bit.
  2. It receives shared memory as input.
  3. When performing bounds checks on the shared memory, it does not truncate the size as well. Code that checks a truncated size_t is not vulnerable:
From the original on blog.zimperium.com

Two further, optional criteria made a target more interesting. First, having a default implementation in AOSP: vendors are in charge of all HAL services, but when an AOSP default implementation exists, vendors are often reluctant to modify it and use it as is, so the bug can be relevant across multiple vendors rather than in one vendor-specific service. Second, being directly accessible from an unprivileged app: HAL services are supposed to be reachable only by other system services, but a select few are in fact accessible by regular unprivileged apps, each for its own reason. Without that, the whole exercise stays hypothetical unless another service is already compromised.

One HAL service met all of these: android.hardware.cas, also known as MediaCasService.

Step 2: understand the target

CAS stands for Conditional Access System. It is similar to DRM, so much so that the differences are not always clear; simplistically it works the same way, with encrypted data that needs to be decrypted. MediaCasService allows apps to decrypt encrypted data, and it is extremely similar to MediaDrmServer, the service in charge of decrypting DRM media, both in its API and in how it operates internally. The terminology differs: the API is called descramble rather than decrypt, although internally it ends up calling it decrypt as well.

The descramble method works like this (some minor parts are omitted to simplify):

From the original on blog.zimperium.com

Data is shared over shared memory. A buffer, srcBuffer, indicates where the relevant part of the shared memory is and is used for both source and destination; it carries offsets to where the service reads the source data from and where it writes the destination data to. The caller can indicate that the source data is clear rather than encrypted, in which case the service simply copies from source to destination without modifying it.

If the service verified that everything fits inside the shared memory using only the hidl_memory size and not other parameters, then making it believe that a small region spans its entire memory space would bypass the bounds checks and allow arbitrary source and destination offsets: full read and write access to the service memory, reading from anywhere into the shared memory and writing from the shared memory to anywhere. Negative offsets should work too, since even 0xFFFFFFFF (-1) is less than the hidl_memory size.

The descramble code confirms it. The helper validateRangeForSize simply checks that "first_param + second_param <= third_param" while minding possible overflows:

From the original on blog.zimperium.com

The code checks that srcBuffer lies inside the shared memory based on the hidl_memory size. After that the hidl_memory is not used any more and the remaining checks are performed against srcBuffer itself. So the only thing needed for full read and write access is to use the vulnerability and then set srcBuffer's size to more than 0xFFFFFFFF, which makes any value for the source and destination offsets valid.

From the original on blog.zimperium.com

Step 3: decide what the exploit should achieve

The SELinux rules for this service show that it is heavily restricted and does not have many permissions. It does have one permission a regular unprivileged app does not: access to the TEE (Trusted Execution Environment) device. That permission is interesting because it gives access to a wide variety of things: different device drivers for different vendors, different TrustZone operating systems and a large number of trustlets. To prove the access, the objective was kept simple: perform an operation that requires the TEE device. The Qualcomm TEE device driver has a fairly simple ioctl that queries the version of the QSEOS running on the device, so the goal of the exploit was to run that ioctl and get its result.

Step 4: deal with ASLR and mapping placement

Full read and write over the target process memory is a strong primitive, but two issues had to be solved:

  • ASLR: the read access is only relative to where the shared memory was mapped, and the address of the shared memory compared to other data in memory is unknown. Ideally the address of the shared memory and of other interesting data would be known.
  • For each execution of the vulnerability the shared memory is mapped and then unmapped after the operation, with no guarantee that it lands in the same place each time; another memory region may take its place between executions.

The memory maps of the linker in the service memory space for this build show the way out:

From the original on blog.zimperium.com

The linker creates a small gap of 2 memory pages (0x2000) between linker_alloc_small_objects and linker_alloc. These mappings are at relatively high addresses, and all libraries loaded by the process are mapped lower, so this is the highest gap in memory. Since mmap tries high addresses before low ones, any mapping of 2 pages or less should land in this gap, and the service does not normally map anything so small, so the gap should stay. That solves the second issue: the shared memory always lands at a deterministic location.

The data in linker_alloc straight after the gap is helpful:

From the original on blog.zimperium.com

It contains addresses that easily indicate the address of the linker_alloc region. Since the vulnerability gives relative read and the shared memory is mapped straight before linker_alloc, taking the address at offset 0x40 and reducing it by 0x10 gives the linker_alloc address; reducing that by the size of the shared memory gives the shared memory address. The first issue is now partly solved: the shared memory address is known, but not the addresses of other interesting data.

Step 5: hijack a blocked thread

One part of the MediaCasService API lets clients provide listeners to events. A client that provides a listener is notified when CAS events occur, and a client can also trigger events itself, which are then sent back to the listener. Through Binder and HIDL, when the service sends an event to the listener it waits until the listener has finished processing it, so a thread is blocked waiting for the listener:

From the original on blog.zimperium.com

That is useful: a thread in the service can be made to block waiting for us, in a known pre-determined thread. Once a thread is in that state its stack can be modified to hijack it, and the thread is resumed only after the event processing is finished. The problem is finding the thread stack in memory. The deterministic shared memory address is high, so the distance to possible locations of the blocked thread stack is large, and ASLR makes it too unreliable to find the stack relatively from that address. The approach instead is to use a bigger shared memory and have it mapped before the blocked thread stack, so the stack can be reached relatively through the vulnerability.

Rather than getting one thread into the blocked state, the exploit gets multiple (5) threads there. That causes more threads to be created and more thread stacks to be allocated, so if there are a few thread-stack-sized gaps in memory they should be filled, and at least one blocked thread stack should be mapped at a low address with no library mapped before it (mmap maps regions at high addresses before low addresses). Then a large shared memory should ideally be mapped before that stack.

From the original on blog.zimperium.com

One drawback is that other unexpected things, such as the jemalloc heap, may get mapped in the middle, so the blocked thread stack is not where expected. The chosen solution is to crash the service using the vulnerability, by writing to an unmapped address, and try again, since the service simply restarts when it crashes. This scenario normally does not happen, and even when it does, one retry is usually enough.

Step 6: read the thread stack

Once the shared memory is mapped before the blocked thread stack, the vulnerability reads two things from the stack:

  • The thread stack address, from pthread metadata that lies in the same memory region after the stack itself.
  • The address where libc is mapped, needed later to build a ROP chain from gadgets and symbols in libc (libc has enough gadgets). This is obtained by reading a return address to a specific point in libc that is in the thread stack.
From the original on blog.zimperium.com

From then on the thread stack can be read and written through the vulnerability. With both the deterministic shared memory address and the thread stack address known, the difference between them lets the exploit reach the thread stack from the small shared memory at the deterministic location.

Step 7: run a ROP chain

With full access to a blocked thread stack that can be resumed, the next step is to execute a ROP chain. The exact part of the stack to overwrite is known because the exact state the thread is blocked at is known; after overwriting, the thread is resumed and the chain runs.

SELinux limitations on the process prevent turning this into full arbitrary code execution: there is no execmem permission, so anonymous memory cannot be mapped executable, and there is no control over file types that can be mapped executable. Since the objective is simple (a single ioctl), the ROP chain does just that. For more complex work the primitive is strong enough in theory; for example, multi-stage ROP could run a function and write its result somewhere, read that result, do the complex logic in the attacker's own process, and then run another ROP chain based on it.

The code essentially performed by the ROP chain to obtain the QSEOS version:

From the original on blog.zimperium.com

stack_addr is the address of the memory region of the stack, an address known to be writable and not to be overwritten (the stack begins from the bottom and is not close to the top), so the result can be written there and read back through the vulnerability. The sleep at the end keeps the thread from crashing immediately after the ROP chain runs, so the result can be read.

Building the chain is straightforward: there are enough gadgets in libc, all the symbols are in libc as well, and libc's address is already known.

Afterwards the process is left in a somewhat unstable state because a thread was hijacked to run the ROP chain. To leave everything clean, the service is crashed using the vulnerability, by writing to an unmapped address, so that it restarts.

Root cause

The mistake is the mismatch between the 64 bit size carried by hidl_memory and the 32 bit size_t used by mmap in a 32 bit process. The HIDL libraries transfer mSize as a 64 bit integer, unlike the old libraries, which use a 32 bit integer. When a 32 bit process maps the ashmem region, the size is silently truncated to its lower 32 bits, so the mapping is smaller than the size the object reports. Consumers that validate offsets against the hidl_memory size, as MediaCasService's descramble does before switching to checks against srcBuffer, accept offsets outside the real mapping. The vulnerability exists in a library introduced specifically as part of Project Treble and does not exist in the previous library that does pretty much the same thing; because it is in a commonly used library, it affects many high-privileged services.

Impact

An unprivileged app can reach MediaCasService directly and use the truncated mapping to obtain full read and write access to the service's memory, relative to the shared memory. From there the exploit determines the shared memory address through the linker gap, blocks threads with listener events, locates a thread stack, reads the stack address and libc's address, and hijacks the blocked thread with a ROP chain. The service's SELinux policy is heavily restricted, so the chain cannot become arbitrary code execution, but the service holds access to the TEE device, which an unprivileged app does not have; the demonstrated result is running the Qualcomm TEE driver ioctl that queries the QSEOS version. The exploit is specific to one device and build, and the write-up presents the TEE access as a proof of concept rather than a full attack chain.

Fix

Google distributed an initial set of patches on 02.07.2018 and an additional set on 04.09.2018, both in system/libhidl, and the issue was assigned CVE-2018-9411.

Variants to test

  • Other 32 bit HAL services that receive shared memory and validate offsets against the hidl_memory size rather than a truncated size_t. A positive result is a bounds check that passes for an offset beyond the real mapping, as with srcBuffer set above 0xFFFFFFFF.
  • Services with an AOSP default implementation that vendors use unmodified, since the same library code is shared across vendors.
  • Services directly reachable from an unprivileged app, which makes the primitive usable without a prior compromise.
  • Services whose SELinux policy grants access to sensitive devices such as the TEE, where a single ioctl is enough to demonstrate impact.
  • Any code path that maps a 64 bit size through a 32 bit size_t and then trusts the original size for later checks; a positive result is a mapping smaller than the reported size with checks still passing.

Timeline

  • 03.05.2018: vulnerability discovered
  • 07.05.2018: vulnerability details and PoC sent to Google
  • 02.07.2018: Google distributed the initial set of patches
  • 13.07.2018: Google asked to delay blog post publication
  • 04.09.2018: Google distributed an additional set of patches

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

What happened, in plain words

A security researcher at Zimperium zLabs found a serious flaw in Android, the operating system that runs on most phones. The flaw lived in a piece of Android that lets different parts of the system talk to each other. Because of a small mismatch in how a number (a size) was handled, a normal, unprivileged app could trick a powerful system service into reading and writing memory it should never touch. Google gave the flaw the identifier CVE-2018-9411 and fixed it in the July 2018 security update, with more fixes in September 2018.

The researcher also wrote a proof-of-concept exploit, and full exploit code is available on GitHub for educational or defensive purposes. The exploit was built for one specific phone and software version: a Pixel 2 running the May 2018 security update.

This article walks through the whole story from zero. It explains the background (how Android is put together after a change called Project Treble), the bug itself, why one particular service was chosen as the target, how the exploit worked around the protections that normally make such attacks hard, and what the exploit finally achieved. Every technical term is explained the first time it appears, and every code snippet is followed by a plain-words explanation.

From the original on blog.zimperium.com

Background: what Project Treble changed

To understand the bug, you first need a little picture of how Android is built.

Android is made of two kinds of code. One kind is AOSP, the Android Open Source Project: the public, open code that Google maintains and that anyone can download. The other kind is vendor code: code written by the phone manufacturer (Samsung, Google, Qualcomm and so on) to make the hardware in a specific phone work.

Before Project Treble, a single system service could contain both AOSP code and vendor code mixed together. A service here means a background program that runs with high privileges and does jobs on behalf of other programs. Project Treble, introduced by Google, split these mixed services into two: one pure AOSP service, and one or more vendor services. The vendor services are called HAL services. HAL stands for Hardware Abstraction Layer: a layer that hides the details of specific hardware behind a standard interface.

Why does this matter for security? Because splitting a service in two means the two halves can no longer simply call each other's functions inside one program. They now live in separate processes, and separate processes can only talk by sending messages to each other. This message passing is called IPC, inter-process communication. Project Treble therefore increased the total amount of IPC in Android: data that used to move inside a single process now has to cross a process boundary.

Background: Binder and HIDL

Most IPC in Android goes through a component called Binder. You can think of Binder as the postal system inside the phone: one process puts a message in an envelope, addresses it to another process, and Binder delivers it. Binder is part of the Android kernel, the core of the operating system.

When Google needed the new AOSP-to-HAL communication to use Binder too, they did not just reuse the existing Binder code unchanged. They made two changes:

  1. They introduced multiple Binder domains. A domain is like a separate postal district: messages in one district are kept apart from messages in another. This separates the new kind of IPC from the older kinds.
  2. They introduced HIDL, which stands for HAL Interface Definition Language. HIDL is a whole new format for the data that travels through Binder. It comes with a new set of libraries (pre-written code that programs link against) and is dedicated to the new Binder domain used between AOSP and HAL services. Other Binder domains still use the old format.

A library here is a collection of reusable code that many programs can use, so a bug in a library can affect every program that uses it.

The old and new systems are layered in a similar way. At the bottom, in both cases, sits the Binder kernel driver. On top sits a different set of libraries. The new HIDL libraries contain code that is very similar to the old ones, so similar that some of the original code was literally copied into them. The researcher notes that he could not find a good reason for copy-pasting code here, since copying code is generally not good practice: when you fix a bug in one copy, the other copy stays broken.

Both sets of libraries represent the data travelling in Binder transactions as C++ objects. C++ is a programming language; an object is a bundle of data plus the operations on that data. The objects range from simple ones, like objects that represent text strings, to more complex ones, like objects that represent file descriptors or references to other services.

Background: sharing memory

Binder has a size limit: each transaction can carry at most 1MB of data. That is fine for small messages, but sometimes two processes want to share something much bigger, like a video buffer. For that, they use shared memory: a region of memory that both processes can see and use at the same time.

How do you share memory through Binder? Binder has a feature for sharing file descriptors. A file descriptor is a small number that the operating system uses as a handle to an open file or similar resource. The key fact is that a file descriptor can be mapped into memory with a system call called mmap. Mapping means telling the operating system: "make this file's contents appear at this address in my memory, so I can read and write it like ordinary memory." If two processes map the same file descriptor, they are looking at the same memory, and that is how sharing works.

There is a catch on regular Linux (the non-Android kind). File descriptors are normally backed by actual files on disk. What if two processes want to share a chunk of anonymous memory, with no file involved? Android solves this with ashmem, a feature that lets a process allocate memory and attach a file descriptor to it without any real file existing. The descriptor is just a handle to that chunk of memory.

Sharing memory through Binder is one place where HIDL and the old libraries differ in implementation, even though the end result is the same. In both cases, one process maps an ashmem file descriptor into its memory, sends the descriptor to the other process through Binder, and the other process maps it into its own memory. But the code that handles the objects involved is different.

In HIDL, the important object for this is called hidl_memory. The Android source code describes it as "a structure that can be used to transfer pieces of shared memory between processes". A structure is simply a bundle of named fields, like a form with a few boxes to fill in.

The vulnerability

Let's look inside hidl_memory. It has three members (fields):

From the original on blog.zimperium.com
  • mHandle: a handle, which is a HIDL object that holds file descriptors. In this case it holds exactly one file descriptor.
  • mSize: the size of the memory to be shared.
  • mName: supposed to represent the type of memory, but only the ashmem type is really relevant here.

Now, when a structure like this travels through Binder in HIDL, different fields are handled differently. Complex objects (like hidl_handle or hidl_string) have their own custom code for writing and reading the data. Simple types, such as integers, are transferred "as is", meaning their raw bytes are copied. The consequence is that the size, mSize, is transferred as a 64 bit integer. A bit is a binary digit, 0 or 1; 64 bits can represent numbers up to about 18 quintillion. In the old set of libraries, the same kind of size is stored as a 32 bit integer, which tops out at about 4.3 billion.

This raised two questions for the researcher. First, why use 64 bits at all, when the old libraries used 32? Second, and more importantly: how would a 32 bit process handle a 64 bit size? A 32 bit process is a program compiled to work with 32 bit numbers and addresses; many Android services are still 32 bit even on 64 bit phones.

The code that maps a hidl_memory object (for the ashmem type) says nothing about 32 bit processes, and does not even mention that the size is 64 bit:

From the original on blog.zimperium.com

Here is what happens. The length field in mmap's signature is of type size_t. size_t is a special integer type whose width matches the process: 64 bits in a 64 bit process, 32 bits in a 32 bit process. In a 64 bit process, everything is 64 bit and there is no problem. In a 32 bit process, the 64 bit size is truncated to 32 bits: only the lower 32 bits are kept, and the upper bits are silently thrown away.

This has a dramatic effect. Suppose a 32 bit process receives a hidl_memory whose size is larger than UINT32_MAX, which is 0xFFFFFFFF (the largest number a 32 bit unsigned integer can hold, about 4.3 billion). The actual mapped region will be much smaller than the size claims. For example, a hidl_memory with size 0x100001000 (about 4.3 billion plus 4096) results in a mapped region of only 0x1000 (4096 bytes), because the upper part of the number is cut off.

Now suppose the 32 bit process then performs bounds checks against the hidl_memory size. A bounds check is a safety test that asks: "is this offset inside the region I am allowed to touch?" An offset is a distance from the start of the region, like "12 steps from the door". If the process believes the region is enormous (because it trusts the 64 bit size), the checks will pass for offsets that are far outside the real, tiny mapping. The checks "hopelessly fail", as the researcher puts it, because they falsely indicate that the region spans more than the entire memory space. That is the vulnerability.

Finding a target

Having a vulnerability is not the same as having an attack. The researcher needed a real program that would be fooled by it. He looked for a HAL service meeting these criteria:

  1. It compiles to 32 bit (so the truncation happens).
  2. It receives shared memory as input (so the fake size can be delivered).
  3. When performing bounds checks on the shared memory, it does not truncate the size as well. For example, the following code is not vulnerable, because it performs the bounds check on a truncated size_t:
From the original on blog.zimperium.com

In plain words: if the service itself also cuts the size down to 32 bits before checking, then the size it checks against matches the real mapping, and the trick does not work. The bug only bites when the service trusts the big 64 bit number for its checks.

Two further, optional criteria made a target more interesting:

  1. It has a default implementation in AOSP. Vendors are ultimately in charge of all HAL services, but AOSP contains default implementations for some of them, which vendors can use. The researcher found that when such an implementation exists, vendors are often reluctant to modify it and simply use it as is. That makes the target relevant across multiple vendors, rather than being a one-vendor curiosity.
  2. It is directly accessible from an unprivileged app. HAL services are supposed to be reachable only by other system services, but that is not really the truth: a select few HAL services are in fact accessible by regular unprivileged apps, each for its own reason. Without this, the whole exercise stays hypothetical, because you would first need to compromise another service to reach the target.

Luckily, one HAL service met all of these requirements: android.hardware.cas, also known as MediaCasService.

Understanding the target: CAS and MediaCasService

CAS stands for Conditional Access System. The researcher notes that CAS is mostly out of scope for the post, but in general it is similar to DRM (Digital Rights Management), so much so that the differences are not always clear. Simplistically, it works the same way as DRM: there is encrypted data that needs to be decrypted. Think of a pay-TV box: the broadcast is scrambled, and the box holds the keys and the logic to unscramble it for a paying subscriber.

MediaCasService allows apps to decrypt encrypted data. If you have read the researcher's previous blog post about a vulnerability in a service called MediaDrmServer (the service in charge of decrypting DRM media), you might notice why the comparison with DRM comes up: MediaCasService is extremely similar to MediaDrmServer, from its API to the way it operates internally. An API is an Application Programming Interface: the set of commands and data formats a program offers to other programs, like a restaurant menu that lists what you can order and how to order it.

One slight change from MediaDrmServer is the terminology. Instead of "decrypt", the API is called descramble, although internally the code ends up calling it decrypt as well.

Here is how the descramble method operates (some minor parts are omitted to simplify):

From the original on blog.zimperium.com

What this code does, in plain words: the data to be processed is shared over shared memory. A buffer called srcBuffer indicates where the relevant part of the shared memory is. Despite the "src" in its name, it is used for both the source and the destination. On this buffer there are offsets: where the service should read the source data from, and where it should write the destination data to. The caller can also indicate that the source data is in fact clear (not encrypted), in which case the service simply copies data from source to destination without modifying it.

This looked very promising for the vulnerability. If the service verified that everything fits inside the shared memory using only the hidl_memory size, and not other parameters, then the attack would work like this: make the service believe that a small memory region spans its entire memory space. That would bypass the bounds checks and allow the source and destination offsets to be anywhere. The result would be full read and write access to the service's memory: read from anywhere into the shared memory, and write from the shared memory to anywhere. Negative offsets should work too, because even 0xFFFFFFFF (which is -1 in signed 32 bit arithmetic) is less than the enormous hidl_memory size.

So the researcher checked descramble's code to confirm. A quick note first: the helper function validateRangeForSize simply checks that "first_param + second_param <= third_param" while minding possible overflows. In plain words, it checks that a start plus a length stays within a limit, and it is careful about the case where the addition wraps around.

From the original on blog.zimperium.com

As the code shows, the check that srcBuffer lies inside the shared memory is based on the hidl_memory size. After that, the hidl_memory is not used any more, and the rest of the checks are performed against srcBuffer itself. Perfect: all that is needed for full read and write access is to use the vulnerability and then set srcBuffer's size to more than 0xFFFFFFFF. That way, any value for the source and destination offsets is considered valid.

From the original on blog.zimperium.com

The two images above illustrate the two directions of the attack: using the vulnerability for an out-of-bounds read (pulling data from outside the shared memory into it) and for an out-of-bounds write (pushing data from the shared memory to somewhere outside it). "Out-of-bounds" simply means outside the region the program was supposed to touch.

Deciding what the exploit should achieve

Before writing the exploit, the researcher asked: what should it actually accomplish? A look at the SELinux rules for this service shows that it is heavily restricted and does not have many permissions. SELinux, Security-Enhanced Linux, is an extra layer of access control in Android: even a powerful process is only allowed to do the specific things its policy lists, like a strict building pass that opens only certain doors.

Still, the service has one interesting permission that a regular unprivileged app does not have: access to the TEE device. TEE stands for Trusted Execution Environment: a separate, isolated processor mode (often backed by ARM TrustZone hardware) that runs small security-critical programs called trustlets, away from the normal operating system. The TEE handles things like key storage and payment secrets.

This permission is extremely interesting because it lets an attacker access a wide variety of things: different device drivers for different vendors, different TrustZone operating systems, and a large number of trustlets. The researcher had already discussed in his previous blog post how dangerous this permission can be.

While there are many things one could do with TEE access, at this point he merely wanted to prove that he could get it. So the objective was kept simple: perform a simple operation that requires access to the TEE device. In the Qualcomm TEE device driver there is a fairly simple ioctl that queries the version of the QSEOS running on the device. An ioctl is a special system call used to send a command to a device driver; QSEOS is the operating system running on Qualcomm's secure side. The goal of the exploit was therefore to run this ioctl and get its result.

The exploit: setup and the two problems

A note on the setup: the exploit is for a specific device and build, a Pixel 2 with the May 2018 security update. The build fingerprint is:

Text
google/walleye/walleye:8.1.0/OPM2.171019.029.B1/4720900:user/release-keys

A build fingerprint is a string that identifies exactly which software version a phone is running. A link to the full exploit code is available at the end of the blog post.

At this point the researcher had full read and write over the target process's memory. That is a great primitive: in security jargon, a primitive is a basic capability you have obtained, which you then build on. But two issues had to be solved first:

  • ASLR. ASLR stands for Address Space Layout Randomisation: the operating system deliberately places programs and their data at random addresses each time they start, so an attacker cannot hard-code addresses. The researcher had full read access, but only relative to where the shared memory was mapped; he did not know where that was compared to other data in memory. Ideally he would know the address of the shared memory and the addresses of other interesting data.
  • Mapping placement. For each execution of the vulnerability, the shared memory gets mapped and then unmapped after the operation. There is no guarantee that it will be mapped in the same location each time; another memory region may take its place between executions.

Solving the placement problem: the linker gap

To solve the second problem, the researcher looked at the memory maps of the linker in the service's memory space for this specific build. The linker is the part of the system that loads libraries into a process. A memory map is the operating system's list of which regions of memory are used for what.

From the original on blog.zimperium.com

As the map shows, the linker happens to create a small gap of 2 memory pages (0x2000 bytes) between two of its regions, linker_alloc_small_objects and linker_alloc. A memory page is the basic unit of memory the operating system manages, typically 4096 bytes.

The addresses of these mappings are relatively high, and all libraries loaded by the process are mapped at lower addresses. That means this gap is the highest gap in memory. Since mmap's behaviour is to try to map at high addresses before low addresses, any attempt to map a region of 2 pages or less should land in this gap. And luckily, the service does not normally map anything so small, so the gap should stay there. This solves the second problem: the shared memory will always be mapped at a deterministic location in memory.

Next, the researcher looked at the data in linker_alloc straight after the gap:

From the original on blog.zimperium.com

The linker data there turned out to be extremely helpful. It contains addresses that can easily indicate the address of the linker_alloc memory region. Since the vulnerability gives relative read, and the shared memory is mapped straight before this linker_alloc, the address of the shared memory can be computed: take the address at offset 0x40 and reduce it by 0x10, and you get the linker_alloc address; reduce that by the size of the shared memory itself, and you get the shared memory address.

So the second problem is solved, and the first is partly solved: the address of the shared memory is now known, but not the addresses of other interesting data. The question becomes: what other data is interesting?

Hijacking a blocked thread

One part of the MediaCasService API is the ability for clients to provide listeners to events. A listener is a piece of code that says "tell me when something happens". If a client provides a listener, it will be notified when different CAS events occur. A client can also trigger events by itself, which are then sent back to the listener.

The way this works through Binder and HIDL is that when the service sends an event to the listener, it waits until the listener has finished processing the event. In other words, a thread in the service is blocked, waiting for the listener. A thread is one sequence of instructions running inside a process; a process can have several threads running at once, each with its own stack. The stack is the region of memory where a thread keeps its local variables and the return addresses that tell it where to go back to when a function finishes.

From the original on blog.zimperium.com

This is great for the attacker: a thread in the service can be made to block waiting for us, in a known, pre-determined thread. Once a thread is in that state, its stack can be modified to hijack it; the thread is resumed only after the event processing is finished. But how do you find the thread stack in memory?

The deterministic shared memory address is very high, so the distance between it and possible locations of the blocked thread stack is large. ASLR makes it too unreliable to try to find the thread stack relatively from that address. So the researcher used another approach: use a bigger shared memory and have it mapped before the blocked thread stack, so the stack can be reached relatively through the vulnerability.

Instead of getting only one thread into the blocked state, the exploit gets multiple (5) threads there. This causes more threads to be created, with more thread stacks allocated. By doing this, if there are a few thread-stack-sized gaps in memory, they should be filled, and at least one thread stack in a blocked thread should be mapped at a low address, without any library mapped before it (remember, mmap maps regions at high addresses before low addresses). Then, ideally, a large shared memory should be mapped before that stack.

From the original on blog.zimperium.com

One drawback: there is a chance that other unexpected things, such as the jemalloc heap, will get mapped in the middle, so the blocked thread stack will not be where expected. jemalloc is a memory allocator, the component that hands out chunks of memory to programs. The chosen solution was simple: crash the service using the vulnerability, by writing to an unmapped address, and try again, because every time the service crashes it simply restarts. This scenario normally does not happen, and even when it does, one retry is usually enough.

Reading the thread stack

Once the shared memory is mapped before the blocked thread stack, the vulnerability is used to read two things from the thread stack:

  • The thread stack address, using pthread metadata that lies in the same memory region after the stack itself. pthread is the standard threading library; its metadata is bookkeeping data about the thread.
  • The address where libc is mapped, needed later to build a ROP chain using both gadgets and symbols in libc (libc has enough gadgets). libc is the standard C library, full of useful functions. A symbol is the name and address of a function inside a library. A gadget is a short sequence of instructions already present in the code that ends in a return instruction, which an attacker can chain together; a ROP chain (Return-Oriented Programming) is a sequence of such gadgets that, executed one after another, makes the program do what the attacker wants without injecting any new code. The libc address is obtained by reading a return address to a specific point in libc that is in the thread stack.
From the original on blog.zimperium.com

From this point on, the thread stack can be read and written through the vulnerability. With both the deterministic shared memory address and the thread stack address known, the difference between them lets the exploit reach the thread stack from the small shared memory at the deterministic location.

Running a ROP chain

With full access to a blocked thread stack that can be resumed, the next step is to execute a ROP chain. The exact part of the stack to overwrite is known, because the exact state the thread is blocked at is known. After overwriting part of the stack, the thread is resumed, and the ROP chain runs.

Unfortunately, the SELinux limitations on this process prevent turning this ROP chain into full arbitrary code execution. There is no execmem permission, so anonymous memory cannot be mapped as executable, and there is no control over which file types can be mapped as executable. In plain words: the attacker cannot simply write new code into memory and run it, because the policy forbids making memory executable.

Since the objective is simple (running a single ioctl), the researcher simply wrote a ROP chain that does exactly that. In theory, if you want to do more complex things, the primitive is so strong that it should still be possible. For instance, if you want to perform complex logic based on the result of a function, you could do multi-stage ROP: run one ROP chain that calls the function and writes its result somewhere, read that result, do the complex logic in your own process, and then run another ROP chain based on that.

As mentioned, the objective is to obtain the QSEOS version. Here is the code that is essentially performed by the ROP chain to do that:

From the original on blog.zimperium.com

In this code, stack_addr is the address of the memory region of the stack. It is simply an address that is known to be writable and will not be overwritten (the stack begins from the bottom and is not close to the top), so the result can be written there and then read back using the vulnerability. The sleep at the end is there so the thread will not crash immediately after running the ROP chain, which gives the attacker time to read the result.

Building the ROP chain itself is pretty straightforward: there are enough gadgets in libc, all the symbols are in libc as well, and libc's address is already known.

Afterwards, the process is left in a somewhat unstable state, because a thread was hijacked to execute the ROP chain. To leave everything in a clean state, the service is crashed using the vulnerability, by writing to an unmapped address, so that it restarts.

Root cause

The mistake is the mismatch between the 64 bit size carried by hidl_memory and the 32 bit size_t used by mmap in a 32 bit process. The HIDL libraries transfer mSize as a 64 bit integer, unlike the old libraries, which use a 32 bit integer. When a 32 bit process maps the ashmem region, the size is silently truncated to its lower 32 bits, so the mapping is smaller than the size the object reports. Consumers that validate offsets against the hidl_memory size, as MediaCasService's descramble does before switching to checks against srcBuffer, accept offsets outside the real mapping.

The vulnerability exists in a library introduced specifically as part of Project Treble and does not exist in the previous library that does pretty much the same thing. Because it is in a commonly used library, it affects many high-privileged services.

Impact

An unprivileged app can reach MediaCasService directly and use the truncated mapping to obtain full read and write access to the service's memory, relative to the shared memory. From there, the exploit determines the shared memory address through the linker gap, blocks threads with listener events, locates a thread stack, reads the stack address and libc's address, and hijacks the blocked thread with a ROP chain.

The service's SELinux policy is heavily restricted, so the chain cannot become arbitrary code execution. But the service holds access to the TEE device, which an unprivileged app does not have. The demonstrated result is running the Qualcomm TEE driver ioctl that queries the QSEOS version. The exploit is specific to one device and build, and the write-up presents the TEE access as a proof of concept rather than a full attack chain.

Fix

Google distributed an initial set of patches on 02.07.2018 and an additional set on 04.09.2018, both in system/libhidl, and the issue was assigned CVE-2018-9411.

Variants to test

  • Other 32 bit HAL services that receive shared memory and validate offsets against the hidl_memory size rather than a truncated size_t. A positive result is a bounds check that passes for an offset beyond the real mapping, as with srcBuffer set above 0xFFFFFFFF.
  • Services with an AOSP default implementation that vendors use unmodified, since the same library code is shared across vendors.
  • Services directly reachable from an unprivileged app, which makes the primitive usable without a prior compromise.
  • Services whose SELinux policy grants access to sensitive devices such as the TEE, where a single ioctl is enough to demonstrate impact.
  • Any code path that maps a 64 bit size through a 32 bit size_t and then trusts the original size for later checks; a positive result is a mapping smaller than the reported size with checks still passing.

Timeline

  • 03.05.2018: vulnerability discovered
  • 07.05.2018: vulnerability details and PoC sent to Google
  • 02.07.2018: Google distributed the initial set of patches
  • 13.07.2018: Google asked to delay blog post publication
  • 04.09.2018: Google distributed an additional set of patches

Glossary

  • AOSP: the Android Open Source Project, the public open code that Google maintains.
  • API: Application Programming Interface, the set of commands and data formats a program offers to other programs.
  • ASLR: Address Space Layout Randomisation, the operating system placing programs and data at random addresses to make attacks harder.
  • ashmem: an Android feature that lets a process allocate memory and attach a file descriptor to it without a real file.
  • Binder: the main inter-process communication system in Android, part of the kernel.
  • bit: a binary digit, 0 or 1; 32 bits can hold about 4.3 billion values, 64 bits far more.
  • bounds check: a safety test that asks whether an offset is inside the region a program is allowed to touch.
  • buffer: a region of memory used to hold data temporarily.
  • build fingerprint: a string identifying exactly which software version a phone is running.
  • CAS: Conditional Access System, a system for controlling access to encrypted content, similar to DRM.
  • C++: a programming language; an object in it is a bundle of data plus operations on that data.
  • CVE: Common Vulnerabilities and Exposures, a public identifier for a security flaw.
  • descramble: the MediaCasService API call that decrypts data.
  • deterministic: always the same, not random.
  • DRM: Digital Rights Management, technology for controlling access to protected content.
  • execmem: an SELinux permission that allows memory to be made executable.
  • exploit: a program that demonstrates or carries out an attack using a vulnerability.
  • file descriptor: a small number the operating system uses as a handle to an open file or similar resource.
  • gadget: a short sequence of existing instructions ending in a return, used to build a ROP chain.
  • HAL: Hardware Abstraction Layer, a layer that hides hardware details behind a standard interface; HAL services are the vendor-side services.
  • HIDL: HAL Interface Definition Language, the new format and library set for data passed through Binder between AOSP and HAL services.
  • hidl_memory: the HIDL structure used to transfer shared memory between processes.
  • heap: the area of memory a program uses for dynamically allocated data.
  • integer: a whole number; 32 bit and 64 bit integers differ in how large a value they can hold.
  • ioctl: a system call used to send a command to a device driver.
  • IPC: inter-process communication, the ways separate processes exchange data.
  • jemalloc: a memory allocator, the component that hands out chunks of memory to programs.
  • libc: the standard C library, containing common functions and useful code sequences.
  • library: a collection of reusable code that many programs can use.
  • linker: the part of the system that loads libraries into a process.
  • listener: a piece of code registered to be notified when an event happens.
  • mapping: making a file or memory region appear at an address in a process's memory.
  • memory map: the operating system's list of which memory regions are used for what.
  • memory page: the basic unit of memory the operating system manages, typically 4096 bytes.
  • mmap: the system call that maps a file descriptor or memory region into a process's address space.
  • offset: a distance from the start of a region, like "12 steps from the door".
  • out-of-bounds: outside the region a program was supposed to touch.
  • pthread: the standard threading library; its metadata is bookkeeping data about threads.
  • primitive: in security, a basic capability obtained, which is then built upon.
  • process: a running program with its own memory space.
  • Project Treble: Google's change that split mixed AOSP and vendor services into separate AOSP and HAL services.
  • proof of concept (PoC): a small demonstration that a vulnerability is real and exploitable.
  • QSEOS: the operating system running on Qualcomm's secure side.
  • ROP chain: Return-Oriented Programming chain, a sequence of gadgets executed one after another to make a program do what an attacker wants without injecting new code.
  • SELinux: Security-Enhanced Linux, an extra access-control layer in Android that restricts what each process may do.
  • service: a background program running with high privileges that does jobs for other programs.
  • shared memory: a region of memory that two or more processes can see and use at the same time.
  • size_t: an integer type whose width matches the process, 32 or 64 bits.
  • stack: the region of memory where a thread keeps local variables and return addresses.
  • structure: a bundle of named fields, like a form with boxes to fill in.
  • symbol: the name and address of a function inside a library.
  • TEE: Trusted Execution Environment, a separate isolated processor mode that runs security-critical programs.
  • thread: one sequence of instructions running inside a process; a process can have several at once.
  • transaction: one message sent through Binder from one process to another.
  • truncation: silently cutting off the upper bits of a number when it does not fit in the target type.
  • trustlet: a small security-critical program that runs inside the TEE.
  • TrustZone: ARM's hardware technology for running a separate secure world alongside the normal one.
  • UINT32_MAX: the largest value a 32 bit unsigned integer can hold, 0xFFFFFFFF (about 4.3 billion).
  • unprivileged app: a normal app with no special system permissions.
  • vendor code: code written by the phone manufacturer to make specific hardware work.
  • vulnerability: a flaw in software that can be used to make it behave in unintended ways.

More by Tamir Zahavi-Brunner

View all

4 more disclosed reports, best first.

More from Google

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Memory corruption

The lesson behind this report.

Native code reads or writes memory it should not: overflows, use-after-free, type confusion. The core of browser, kernel and parser bugs.