Skip to content

Instantly share code, notes, and snippets.

@avagin
Created December 20, 2019 01:20
Show Gist options
  • Save avagin/53d5d980264d153e207427612fe62e7e to your computer and use it in GitHub Desktop.
Save avagin/53d5d980264d153e207427612fe62e7e to your computer and use it in GitHub Desktop.
ptrace: syscall
#define _GNU_SOURCE
#include <sys/ptrace.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/user.h>
#include <stdlib.h>
#include <stdio.h>
#define SYSTRAP
int main(int argc, char **argv)
{
struct user_regs_struct regs;
long i, n = atoi(argv[1]), sigtrap = atoi(argv[2]);
int status;
pid_t pid = fork();
if (pid < 0)
return 1;
if (pid == 0) {
long sysno = __NR_kill;
long signo = SIGSTOP;
long p = getpid();
asm volatile(
"movq %0, %%rax \n"
"movq %1, %%rdi \n"
"movq %2, %%rsi \n"
"syscall \n"
"int3; \n"
:
: "g" (sysno), "g" (signo), "g" (p)
: "rax" , "rdi", "rsi", "memory");
return 1;
}
if (ptrace(PTRACE_ATTACH, pid, 0, 0))
return 1;
while (1) {
if (waitpid(pid, &status, 0) != pid)
return 1;
printf("%x\n", status);
if (WIFSTOPPED(status) && WSTOPSIG(status) == SIGTRAP)
break;
if (ptrace(PTRACE_CONT, pid, 0, 0))
return 1;
}
if (ptrace(PTRACE_SETOPTIONS, pid, NULL, PTRACE_O_TRACESYSGOOD))
return 1;
if (ptrace(PTRACE_GETREGS, pid, NULL, &regs))
return 1;
regs.rip -= 3;
regs.rax = __NR_getpid;
printf("rip %llx\n", regs.rip);
for (i = 0; i < n; i++) {
if (ptrace(PTRACE_SETREGS, pid, NULL, &regs))
return 1;
if (sigtrap) {
if (ptrace(PTRACE_CONT, pid, 0, 0))
return 1;
if (waitpid(pid, &status, 0) != pid)
return 1;
if (!WIFSTOPPED(status) || WSTOPSIG(status) != SIGTRAP) {
printf("%x\n", status);
return 1;
}
} else {
if (ptrace(PTRACE_SYSCALL, pid, 0, 0))
return 1;
if (wait4(pid, &status, __WALL, NULL) != pid)
return 1;
if (status != 0x857f) {
printf("%x\n", status);
return 1;
}
if (ptrace(PTRACE_SYSCALL, pid, 0, 0))
return 1;
if (wait4(pid, &status, __WALL, NULL) != pid)
return 1;
if (status != 0x857f) {
printf("%x\n", status);
return 1;
}
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment