I am trying to learn to use ptrace, I wrote a simple assembly stub that 1/ calls ptrace(0,0,0,0) (the syscall, not the libc function). Then displays hello world then spawns a shell. I run my code from a bash shell. Hello world is displayed, however my process is stopped before the execve(/bin/sh) (I get the bash notification of a background process) Is it because of ptrace ? Also when issuing the "fg" command to continue execution, nothing happens and I have to close the terminal since ctrl-c doesn't work... What exactly is happening ?
Asked
Active
Viewed 72 times
1 Answers
1
From the execve man page:
If the current program is being ptraced, a SIGTRAP signal is sent to it after a successful execve().
Using ptrace(PTRACE_TRACEME)
makes your process be a tracee of its parent, so that execve SIGTRAP behaviour applies to your process even if the parent doesn't PTRACE_ATTACH
or make any other ptrace system calls. e.g. if it's a normal shell like bash rather than a debugger like GDB. (I assume PTRACE_TRACEME
is 0
.)
See also How does gdb start an assembly compiled program and step one line at a time? for a more detailed walk-through of how GDB uses ptrace(PTRACE_TRACEME)
after fork but before execve, so the GDB process can trace the new process.

Peter Cordes
- 328,167
- 45
- 605
- 847
-
I assume it's not possible to handle this SIGTRAP in the tracee, in order to run normally even if the parent is not expecting to trace you ? – Aaa Bbb Dec 15 '21 at 11:32
-
@AaaBbb: Probably not, I think it's delivered after the execve replaces the old process including its signal handlers and sigaction settings, and I don't think you can make ignoring SIGTRAP persist across execve. Yeah, `sigaction` says `execve` resets signal dispositions to their defaults. But IDK why you'd ever want to run `PTRACE_TRACEME` in a process that wasn't actively cooperating with a specific parent. Just don't do that in the first place, except after fork, right before execve! If you want to attach to another process, just do it with `PTRACE_ATTACH`. – Peter Cordes Dec 15 '21 at 11:38
-
I see, I simply wanted to implement an anti-debugging security technique, where if ptrace==-1 we exit else we start malware execution (in our case a shell). But I now I understand it's limited to non-sigtrap causing instructions like exec. – Aaa Bbb Dec 15 '21 at 11:47