Code injection in running process using ptrace

shashank Jain
2 min readJul 26, 2018

--

Extending the story of shell code injection (https://medium.com/@jain.sm/shell-code-exploit-with-buffer-overflow-8d78cc11f89b), we showcase a simple example of using ptrace to exploit a running process. Shell code is binary code injected into a running process using ptrace system calls.

Ptrace is a system call which can be used to debug/modify another process. We need specific privileges to run ptrace though.

The exploit is explained as below

1. We create a program which takes as input a pid of the running process and uses PTRACE_ATTACH to attach to a running process. The callee is stopped and caller now is in control.

2. After attaching we get the registers of the running process using PTRACE_GETREGS. This will also return the instruction pointer, so we know where the callee is in terms of instruction execution.

3. We inject the shell code at the point the RIP (instruction pointer) is. So if we see the inject_code method above , we see usage of PTRACE_POKETEXT call which takes as input pid of the callee, target location (will be RIP of callee process), source (shell code)

In this example we are not giving control back to the callee.

Code of the caller is shown below

Dynamic code injection is an activity which can be used for debugging or also for malware injections, as long as we have privileges to run ptrace.

The target process

Executing the caller to do attach to target and inject code

Now see the callee

You can see the shell .

Thanks to https://0x00sec.org/t/linux-infecting-running-processes/1097 for presenting this excellent article on using ptrace for shell code injection.

Disclaimer : The views expressed above are personal and not of the company I work for.

--

--