badmalloc (CVE-2023-32428) - a macOS LPE
A macOS framework that logs memory allocations could be tricked into writing a file to an arbitrary location with root privileges, and because the file descriptor was not closed on execution, an attacker could use a setuid binary like crontab to obtain a writable file descriptor to a root-owned file and escalate privileges.
Published on gergelykalman.com
I recently realised that I still owe you guys some writeups, so since OBTSv7 is around the corner here's the one for badmalloc. I found this back in March 2023, and it got fixed in October.
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.
Not written yet. The AI write-up for this write-up has not been written yet. The Original tab links to the source.
How it worked
Root cause
The MallocStackLogging framework opened log files without the O_CLOEXEC flag, so the file descriptor remained open across exec and could be inherited by a child process controlled by the attacker.
Impact
An attacker could escalate privileges to root on macOS by exploiting the leaked file descriptor to write to a protected file, as demonstrated with crontab and sudoers.
What the attacker needed
Ability to run a setuid binary like crontab; Control over the EDITOR environment variable; Ability to create symlinks and race file operations
The fix
The fix was deployed by Apple and included using O_NOFOLLOW_ANY, realpath(), O_CLOEXEC, and fixing the random generator and truncation bugs.
How it was found
- Set the EDITOR environment variable to point to a script you control.
- Run crontab -e with MallocStackLogging enabled and a directory you control.
- Race the file open by swapping the directory with a symlink to /etc/sudoers.d.
- In your script, detect the leaked file descriptor, truncate the file, and write a sudoers entry granting passwordless root.
- Use sudo to become root without a password.
Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.
Not written yet. The AI write-up for this write-up has not been written yet. The Original tab links to the source.
A logging feature in macOS could be abused to create files in places it shouldn't, even with high permissions. By running a special program that lets you edit files, an attacker could get access to a file that only the administrator should be able to change, and then use it to become the administrator.
What is RCE?
Running the attacker's code on the target's servers: through command or code injection, unsafe deserialisation or template injection.