This article analyzes the cause of CVE-2024-31317, an Android user-mode universal vulnerability, and shares our exploitation research and methods. Through this vulnerability, we can obtain code-execution for any uid, similar to breaking through the Android sandbox to gain permissions for any app. This vulnerability has effects similar to the Mystique vulnerability discovered by the author years ago (which won the Pwnie Award for Best Privilege Escalation Bug), but each has its own merits.
A few months ago, Meta X Red Team published two very interesting Android Framework vulnerabilities that could be used to escalate privileges to any UID. Among them, CVE-2024-0044, due to its simplicity and directness, has already been widely analyzed in the technical community with public exploits available (it's worth mentioning that people were later surprised to find that the first fix for this vulnerability was actually ineffective). Meanwhile, CVE-2024-31317 still lacks a public detailed analysis and exploit, although the latter has greater power than the former (able to obtain system-uid privileges). This vulnerability is also quite surprising, because it's already 2024, and we can still find command injection in Android's core component (Zygote).
This reminds us of the Mystique vulnerability we discovered years ago, which similarly allowed attackers to obtain privileges for any uid. It's worth noting that both vulnerabilities have certain prerequisites. For example, CVE-2024-31317 requires the WRITE_SECURE_SETTINGS
permission. Although this permission is not particularly difficult to obtain, it theoretically still requires an additional vulnerability, as ordinary untrusted_app
s cannot obtain this permission (however, it seems that on some branded phones, regular apps may have some methods to directly obtain this permission). ADB shell natively has this permission, and similarly, some special pre-installed signed apps also have this permission.
However, the exploitation effect and universality of this logical vulnerability are still sufficient to make us believe that it is the most valuable Android user-mode vulnerability in recent years since Mystique. Meta's original article provides an excellent analysis of the cause of this vulnerability, but it only briefly touches on the exploitation process and methods, and is overall rather concise. This article will provide a detailed analysis and introduction to this vulnerability, and introduce some new exploitation methods, which, to our knowledge, are the first of their kind.
Attached is an image demonstrating the exploit effect, successfully obtaining system privilege on major phone brand’s June patch version:
¶Analysis of this vulnerability
Although the core of this vulnerability is command injection, exploiting it requires a considerable understanding of the Android system, especially how Android's cornerstone—the Zygote fork mechanism—works, and how it interacts with the system_server.
¶Zygote and system_server bootstrap process
Every Android developer knows that Zygote forks all processes in Android's Java world, and system_server is no exception, as shown in the figure below.
The Zygote process actually receives instructions from system_server and spawns child processes based on these instructions. This is implemented through the poll mechanism in ZygoteServer.java:
1 | Runnable runSelectLoop(String abiList) { |
Then it enters the processCommand
function, which is the core function for parsing the command buffer and extracting parameters. The specific format is defined in ZygoteArguments
, and much of our subsequent work will need to revolve around this format.
1 | Runnable processCommand(ZygoteServer zygoteServer, boolean multipleOK) { |
This is the top-level entry point for Zygote command processing, but the devil is in the details. After Android 12, Google implemented a fast-path C++ parser in ZygoteCommandBuffer
, namely com_android_internal_os_ZygoteCommandBuffer.cpp. The main idea is that Zygote maintains a new inner loop in nativeForkRepeatly
outside the outer loop in processCommand
, to improve the efficiency of launching apps.
nativeForkRepeatly
also polls on the Command Socket and repeatedly processes what is called a SimpleFork
format parsed from the byte stream. This SimpleFork
actually only processes simple zygote parameters such as runtime-args
, setuid
, setgid
, etc. The discovery of other parameters during the reading process will cause an exit from this loop and return to the outer loop in processCommand
, where a new ZygoteCommandBuffer
will be constructed, the loop will restart, and unrecognized commands will be read and parsed again in the outer loop.
System_server may send various commands to zygote, not only commands to start processes, but also commands to modify some global environment values, such as denylistexemptions
which contains the vulnerable code, which we will explain in more detail later.
As for system_server itself, its startup process is not complicated, as launched by hardcoded parameters in Zygote—obviously because Zygote cannot receive commands from a process that does not yet exist, this is a "chicken or egg" problem, and the solution is to start system_server through hardcoding.
¶The Zygote command format
The command parameters accepted by Zygote are in a format similar to Length-Value pairs, separated by line breaks, as shown below
1 | 8 [command #1 arg count] |
Roughly, the protocol parsing process first reads the number of lines, then reads the content of each line one by one according to the number of lines. However, after Android 12, the exploitation method gets much more complicated due to some buffer pre-reading optimizations, which also led to a significant increase in the length of this article and the difficulty of vulnerability exploitation.
From the previous analysis, we can see that Zygote simply parses the buffer it receives from system_server blindly - without performing any additional secondary checks. This leaves room for command injection: if we can somehow manipulate system_server to write attacker-controlled content into the command socket.
denylistexemptions
provides such a method
1 | private void update() { |
"Regardless of the reason why hidden_api_blacklist_exemptions
is modified, the ContentObserver
's callback will be triggered. The newly written value will be read and, after parsing (mainly based on splitting the string by commas), directly written into the zygote command socket. A typical command injection."
¶Achieving universal exploitation utilizing socket features
¶Difficulty encountered on Android12 and above
The attacker's initial idea was to directly inject new commands that would trigger the process startup, as shown below:
1 | settings put global hidden_api_blacklist_exemptions "LClass1;->method1( |
In Android 11 or earlier versions, this type of payload was simple and effective because in these versions, Zygote reads each line directly through Java's readLine
without any buffer implementation affecting it. However, in Android 12, the situation becomes much more complex. Command parsing is now handled by NativeCommandBuffer
, introducing a key difference: after the content is examined for once, this parser discards all trailing unrecognized content in the buffer and exits, rather than saving it for the next parsing attempt. This means that injected commands will be directly discarded!
1 | NO_STACK_PROTECTOR |
"The nativeForkRepeatedly
function operates roughly as follows: After the socket initialization setup is completed, n_buffer->readLines
will pre-read and buffer all the lines—i.e., all the content that can currently be read from the socket. The subsequent reset
will move the buffer's current read pointer back to the initial position—meaning the subsequent operations on n_buffer
will start parsing this buffer from the beginning, without re-triggering a socket read. After a child process is forked, it will consume this buffer to extract its uid
and gid
and set them by itself. The parent process will continue execution and enter the for
loop below. This for
loop continuously listens to the corresponding socket's file descriptor (fd), receiving and reconstructing incoming connections if they are unexpectedly interrupted.
graph TD A[Socket Initialization and Setup] --> B[n_buffer->readLines Reads and Buffers All Lines] B --> C[reset Moves Buffer Pointer Back to Initial Position] C --> D[n_buffer Re-parses the Buffer] D --> E{Fork Child Process} E --> F[Child Process Consumes Buffer to Extract UID and GID] E --> G[Parent Process Continues Execution] G --> H[Enters for Loop] H --> I[n_buffer->clear Clears Buffer] I --> J[Continuously Listens on Socket FD] J --> K[Receives and Rebuilds Incoming Connections] K --> L[n_buffer->getCount] L --> |Valid Input| O[Check if it is a simpleForkCommand] L --> |Invalid Input| I O --> |Is SimpleFork| B O --> |Not SimpleFork| ZygoteConnection::ProcessCommand
1 | for (;;) { |
But this is where things start to get complex and tricky. The call to n_buffer->clear();
discards all the remaining content in the current buffer (the buffer size is 12,200 on Android 12 and HarmonyOS 4, and 32,768 in later versions). This leads to the previously mentioned issue: the injected content will essentially be discarded and will not enter the next round of parsing.
Thus, the core exploitation method here is figuring out how to split the injected content into different reads so that it gets processed. Theoretically, this relies on the Linux kernel's scheduler. Generally speaking, splitting the content into different write
operations on the other side, with a certain time interval between them, can achieve this goal in most cases. Now, let's take a look back at the vulnerable function in system_server
that triggers the writing to the command socket:
1 | private boolean maybeSetApiDenylistExemptions(ZygoteState state, boolean sendIfEmpty) { |
mZygoteOutputWriter
, which inherits from BufferedWriter
, has a buffer size of 8192.
1 | public void write(int c) throws IOException { |
This means that unless flush
is explicitly called, writes to the socket will only be triggered when the size of accumulated content in the BufferedWriter
reaches the defaultCharBufferSize
.
It’s important to note that separate writes do not necessarily guarantee separate reads on the receiving side, as the kernel might merge socket operations. The author of Meta proposed a method to mitigate this: inserting a large number of commas to extend the time consumption in the for
loop, thereby increasing the time interval between the first socket write and the second socket write (flush). Depending on the device configuration, the number of commas may need to be adjusted, but the overall length must not exceed the maximum size of the CommandBuffer
, or it will cause Zygote to abort. The added commas are parsed as empty lines in an array after the string split
and will first be written by system_server
as a corresponding count, represented by 3001
in the diagram below. However, during Zygote parsing, we must ensure that this count matches the corresponding lines before and after the injection.
Thus, the final payload layout is as shown in the diagram below
We want the first part of the payload, which is the content before 13
(the yellow section in the diagram below), to exactly reach the 8192-character limit of the BufferedWriter
, causing it to trigger a flush and ultimately initiate a socket write.
When Zygote receives this request, it should be in com_android_internal_os_ZygoteCommandBuffer_nativeForkRepeatedly
, having just finished processing the previous simpleFork
, and blocked at n_buffer->getCount
(which is used to read the line count from the buffer). After this request arrives, getline
will read all the contents from the socket into the buffer (note: it doesn't read line by line), and upon reading 3001
(line count), it detects that it is not a isSimpleForkCommand
. This causes the function to exit nativeForkRepeatedly
and return to the processCommand
function in ZygoteConnection
.
1 | ZygoteHooks.preFork(); |
The whole procedure is as follows:
graph TD; A[Zygote Receives Request] --> B[Enter com_android_internal_os_ZygoteCommandBuffer_nativeForkRepeatedly]; B --> C[Finish Processing Previous simpleFork]; C --> D[n_buffer->getCount Reads Line Count]; D --> E[getline Reads Buffer]; E --> F[Reads the 3001 Line Count]; F --> G[Detects it is not isSimpleForkCommand]; G --> H[Exit nativeForkRepeatedly]; H --> I[Return to ZygoteConnection's processCommand Function];
This entire 8192-sized block of content is then passed into ZygoteInit.setApiDenylistExemptions
, after which processing of this block is no longer relevant to this vulnerability. Zygote consumes this, and proceed to receive following parts of commands.
At this point, note that we look from the Zygote side back to the system_server side, where system_server is still within the maybeSetApiDenylistExemptions
function's for loop. The 8192 block just processed by Zygote corresponds to the first write
in this for loop.
1 | try { |
The next writer.write
will write the core command injection payload, and then the for loop will continue iterating 3000 (or another specified linecount - 1) times. This is done to ensure that consecutive socket writes do not get merged by the kernel into a single write, which could result in Zygote exceeding the buffer size limit and causing Zygote to abort during its read operation.
These iterations accumulated do not exceed the 8192-byte limit of the BufferedWriter
, will not trigger an actual socket write within the for loop. Instead, the socket write will only be triggered during the flush
. From Zygote's perspective, it will continue parsing the new buffer in ZygoteArguments.getInstance
, corresponding to the section shown in green in the diagram below.
This green section will be read into the buffer in one go. The first thing to be processed is the line count 13
, followed by the fully controlled Zygote parameters injected by the attacker.
This time, the ZygoteArguments
will only contain the 13 lines from this buffer, while the rest of the buffer (empty lines) will be processed in the next call to ZygoteArguments.getInstance
. When the next new ZygoteArguments
instance is created, ZygoteCommandBuffer
will perform another read, effectively ignoring the remaining empty lines.
"After all the complex work outlined above, we have successfully achieved the goal of reliably controlling the Zygote parameters through this vulnerability. However, we still haven’t addressed a critical question: What can be done with these controlled parameters, or how can they be used to escalate privileges?
At first glance, this question seems obvious, but in reality, it requires deeper exploration.
¶Attempt #1: Can we control Zygote to execute a specific package name with a particular uid
?
This might be our first thought: Can we achieve this by controlling the --package-name
and UID?
Unfortunately, the package name is not of much significance to the attacker or to the entire code loading and execution process. Let's recall the Android App loading process:
And let's continue by examining the relevant code inApplicationThread
1 | public static void main(String[] args) { |
As we can see, the APK code loading process actually depends on startSeq
, a parameter maintained by the ActivityManagerService
, which maps ApplicationRecord
to startSeq
. This mapping tracks the corresponding loadApk
, meaning the specific APK file and its path.
So, let’s take a step back:
¶Method #1: Can we control the execution of arbitrary code under a specific UID?
The answer is yes. By analyzing the parameters in ZygoteArguments
, we discovered that the invokeWith
parameter can be used to achieve this goal:
1 | public static void execApplication(String invokeWith, String niceName, |
This piece of code concatenates mInvokeWith
with the subsequent arguments and executes them via execShell
. We only need to point this parameter to an ELF binary or shell script that the attacker controls, and it must be readable and executable by Zygote.
However, we also need to consider the restrictions imposed by SELinux and the AppData directory permissions. Even if an attacker sets a file in a private directory to be globally readable and executable, Zygote will not be able to access or execute it. To resolve this, we refer to the technique we used in the Mystique vulnerability: using files from the app-lib
directory.
The related method for obtaining a system shell is shown in the figure, with the device running HarmonyOS 4.2.
However, this exploitation method still has a problem: obtaining a shell with a specific UID is not the same as direct in-process code execution. If we want to perform further hooking or code injection, this method would require an additional code execution trampoline, but not every app possesses this characteristic, and Android 14 has further introduced DCL (Dynamic Code Loading) restrictions.
So, is it possible to further achieve this goal?
¶Method #2: Leveraging the jdwp
Flag
Here, we propose a new approach: the runtime-flags
field in ZygoteArguments
can actually be used to enable an application's debuggable attribute.
1 | static void applyDebuggerSystemProperty(ZygoteArguments args) { |
Building on our analysis in Attempt #1, we can borrow a startSeq
that matches an existing record in system_server
to complete the full app startup process.The key advantage here is that the app's process flags have been modified to enable the debuggable attribute, allowing the attacker to use tools like jdb
to gain execution control within the process.
¶The Challenge: Predicting startSeq
The issue, however, lies in predicting the startSeq
parameter. ActivityManagerService enforces strict validation for this parameter, ensuring that only legitimate values associated with active application startup processes are used.
1 | private void attachApplicationLocked(@NonNull IApplicationThread thread, |
If an unmatched or incorrect startSeq
is used, the process will be immediately killed. The startSeq
is incremented by 1 with each app startup. So how can an attacker retrieve or guess the current startSeq
?
Our solution to this issue is to first install an attacker-controlled application, and by searching the stack frames, the current startSeq
can be found.
The overall exploitation process is as follows (for versions 11 and earlier):
graph TD; A["Attacker Installs a Debuggable Stub Application"] --> B["Search Stack Frames to Obtain the Current startSeq"]; B --> C["startSeq+1, Perform Command Injection; Zygote Hangs, Waiting for Next App Start"]; C --> D["Launch the Target App via Intent; Corresponding ApplicationRecord Appears in ActivityManagerService"]; D --> E["Zygote Executes Injected Parameters and Forks a Debuggable Process"]; E --> F["The New Forked Process Attaches to AMS with the stolen startSeq; AMS Checks startSeq"]; F --> G["startSeq Check Passes, AMS Controls the Target Process to Load Its Corresponding APK and Complete the Activity Startup Process"]; G --> H["The Target App Has a jdwp Thread, and the Attacker Can Attach to Perform Code Injection"];
The attack effect on Android 11 is shown in the following image:
As you can see, we successfully launched the settings
process and made it debuggable for injection (with a jdwp
thread present). Note that the method shown in the screenshot has not been adapted for versions 12 and above, and readers are encouraged to explore this on their own.
¶Alternative Exploitation Methods
Currently, Method 1 provides a simple and direct way to obtain a shell with arbitrary uid
, but it doesn't allow for direct code injection or loading. Method 2 achieves code injection and loading, but requires using the jdwp
protocol. Is there a better approach?
Perhaps we can explore modifying the class name of the injected parameters—specifically, the previous android.app.ActivityThread
—and redirect it to another gadget class, such as WrapperInit.wrapperInit
.
1 | protected static Runnable applicationInit(int targetSdkVersion, long[] disabledCompatChanges, |
It seems that by leveraging WrapperInit
, we can control the classLoader
to inject our custom classes, potentially achieving the desired effect of code injection and execution.
1 | private static Runnable wrapperInit(int targetSdkVersion, String[] argv) { |
The specific exploitation method is left for interested readers to further explore.
This article analyzed the cause of the CVE-2024-31317 vulnerability and shared our research and exploitation methods. This vulnerability has effects similar to the Mystique vulnerability we discovered years ago, though with its own strengths and weaknesses. Through this vulnerability, we can obtain arbitrary UID privileges, which is akin to bypassing the Android sandbox and gaining access to any app's permissions.
Thanks to Tom Hebb from the Meta X Team for the technical discussions—Tom is the discoverer of this vulnerability, and I had the pleasure of meeting him at the Meta Researcher Conference.