利用ptrace进行注入

转载: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,&reg);
    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, &reg);

    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;
}

执行效果如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值