What is ptrace process injection and how it enables red team trade-craft?
Learn what is ptrace process injection technique and how to use it for red team trade-craft.
Imagine you are playing a video game where your friend is controlling a character. Normally, they follow the game's rules and move as expected. But what if you could take control of their character for a moment, make it do something different, and then give control back without them realizing it? This is exactly how process injection works on Linux using ptrace
.
Ptrace is a debugging tool that allows one process to control another. Normally, it is used for debugging programs, but it can also be used to modify a running program’s behavior. By using ptrace
, a red team operator can inject and execute code inside a legitimate process, making it run something it was never designed to.
Follow my journey of 100 Days of Red Team on WhatsApp, Telegram or Discord.
The flow for performing process injection using ptrace
is as follows:
Attach to the target process - The first step is to attach to the target process using
ptrace(PTRACE_ATTACH)
.Stop the process - Once attached, the target process is paused, so its state can be modified safely.
Save the current state - The red team operator retrieves the process’s register values using
PTRACE_GETREGS
. This is important because the process needs to be restored later to prevent crashes.Find a writable memory region - Since
ptrace
itself does not provide a direct way to allocate memory, find an existing writable and executable memory section within the process. This can be done by reading/proc/<pid>/maps
.Write shellcode into memory - Write the shellcode using
PTRACE_POKETEXT
orprocess_vm_writev
, into the selected memory region.Modify the instruction pointer - Change the program’s execution flow by modifying the instruction pointer (e.g.,
RIP
on x86_64) to point to the injected shellcode usingPTRACE_SETREGS
.Resume execution - Resume the process using
PTRACE_CONT
, allowing it to execute the injected code.Restore original instructions - Restore the original memory content is after execution to ensure the process continues running normally.
Detach from the process - Finally, detach from the target process using
PTRACE_DETACH
.
Red Team Notes
- ptrace allows one process to control another, enabling code injection into a running process.
- The process involves attaching, stopping, modifying memory, executing shellcode, restoring state, and detaching.
Follow my journey of 100 Days of Red Team on WhatsApp, Telegram or Discord.
Examples of real-world malware / cyber-attacks where this technique was used include Pacemaker.