转载:https://bbs.pediy.com/thread-246948.htm
插入的代码
#include <stdio.h>
#include <unistd.h>
int main()
{
__asm__( "jmp forward\n\t"
"backword:popq %rsi\n\t"
"movq $1, %rax\n\t"
"movq $2,%rdi\n\t"
"mov $10, %rdx\n\t"
"syscall \n\t"
"int3\n\t"
"forward:callq backword\n\t"
".string \"It is me\\n\"");
return 0;
}
~
上面的用objdump -S 反汇编后是如下二进制:
注入代码的程序如下:
#include <stdio.h>
#include <stdlib.h>
#include <sys/ptrace.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/user.h>
#include <errno.h>
#include <unistd.h>
#define CODE "\xeb\x19\x5e\x48\xc7\xc0\x01\x00\x00\x00\x48\xc7\xc7\x02\x00\x00\x00\x48\xc7\xc2\x0a\x00\x00\x00\x0f\x05\xcc\xe8\xe2\xff\xff\xff\x49\x74\x20\x69\x73\x20\x6d\x65\x0a\x00"
#define CODE_SIZE (sizeof(CODE)-1)
void putdata(pid_t pid, unsigned long addr, void *vptr, int len)
{
int count = 0;
long word;
while (count < len)
{
memcpy(&word, vptr+count, sizeof(word));
word = ptrace(PTRACE_POKEDATA, pid, addr+count, word);
count += sizeof(word);
if (errno != 0)
printf("putdata failed: %p\n", (void *)(addr+count));
}
}
void getdata(pid_t pid, unsigned long addr, void *vptr, int len)
{
int i = 0, count = 0;
long word;
unsigned long *ptr = (unsigned long*)vptr;
while (count < len)
{
word = ptrace(PTRACE_PEEKDATA, pid, addr+count, NULL);
count += sizeof(word);
ptr[i++] = word;
if (errno != 0)
printf("getdata failed: %p\n", (void *)(addr+count));
}
}
int main(int argc,char *argv[])
{
int pid = 0;
struct user_regs_struct reg;
char backup[CODE_SIZE+1];
if(argc < 2)
return -1;
pid = atoi(argv[1]);
if(pid == 0)
return -1;
printf("pid=%d\n",pid);
if(ptrace(PTRACE_ATTACH,pid,NULL,NULL) < 0)
printf("p trace error\n");
if (errno != 0)
printf("attach failed: %s\n", strerror(errno));
wait(NULL);
ptrace(PTRACE_GETREGS,pid,NULL,®);
printf("%llx\n",reg.rip);
getdata(pid, reg.rip, backup, CODE_SIZE);
putdata(pid,reg.rip, CODE, CODE_SIZE);
ptrace(PTRACE_CONT, pid, NULL, NULL);
wait(NULL);
sleep(2);
putdata(pid, reg.rip, backup, CODE_SIZE);
ptrace(PTRACE_SETREGS, pid, NULL, ®);
ptrace(PTRACE_DETACH, pid, NULL, NULL);
return 0;
}
被注入的程序如下:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
while(1)
{
printf("how are you\n");
sleep(2);
}
return 0;
}
执行效果如下: