Skip to content

Instantly share code, notes, and snippets.

@marmistrz
Created July 14, 2017 12:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marmistrz/56eac71d3cb65fb22caa5de1c95300e3 to your computer and use it in GitHub Desktop.
Save marmistrz/56eac71d3cb65fb22caa5de1c95300e3 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <sys/ptrace.h>
#include <sys/reg.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <unistd.h>
void wait_sigtrap() {
int status;
wait(&status);
if (WIFEXITED(status)) exit(0);
}
int main() {
pid_t child = fork();
if (child == 0) {
ptrace(PTRACE_TRACEME, 0, NULL, NULL);
const char* file = "./pi.py";
if (execl(file, file, "1000", NULL) < 0) {
perror("execl");
return 1;
};
} else {
pid_t pid = child;
wait_sigtrap(); // there will be an initial stop after traceme, ignore
// it
ptrace(PTRACE_SYSCALL, pid, 0, 0); // wait for another
for (;;) {
// detect enter, get syscall no
wait_sigtrap();
long no = ptrace(PTRACE_PEEKUSER, pid, 8 * ORIG_RAX, 0);
if (no != SYS_getrandom) {
ptrace(PTRACE_SYSCALL, pid, 0, 0); // wait for another
wait_sigtrap(); // wait for exit
} else {
// getrandom
long bufptr = ptrace(PTRACE_PEEKUSER, pid, 8 * RDI, 0);
long buflen = ptrace(PTRACE_PEEKUSER, pid, 8 * RSI, 0);
printf("getrandom request: 0x%016lx 0x%016lx\n", bufptr,
buflen);
fflush(stdout);
ptrace(PTRACE_SYSCALL, pid, 0, 0); // wait for another
wait_sigtrap(); // wait for exit
long ret = ptrace(PTRACE_PEEKUSER, pid, 8 * ORIG_RAX, 0);
if (ret < 0) {
printf("Syscall %ld exited with an error code %ld, not touching it",
no, ret);
fflush(stdout);
} else {
long ind = 0;
while (ind < buflen) {
ptrace(PTRACE_POKEDATA, pid, bufptr + ind, 0);
ind += sizeof(long);
}
}
}
ptrace(PTRACE_SYSCALL, pid, 0, 0); // wait for another
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment