1

i'm trying to inject code in a traced process...i'm able to read correctly registers (PTRACE_GETREGS) and also PTRACE_PEEKTEXT works...i've verified with GDB. However if i call ptrace with PTRACE_POKETEXT request it returns 0 but reading again at the same address i don't find the expected bytes:

void print_word(long res) {
    char *datap = (char *)&res;

    if (res == -1)
        //check errno for errors
    else
        printf("%02X %02X %02X %02X\n", datap[0], datap[1], datap[2], datap[3]);
}

....

long res, data = 0xAABBCCDD;

res = ptrace(PTRACE_PEEKTEXT, pid, (void *)regs.eip, NULL);
print_word(res);
res = ptrace(PTRACE_POKETEXT, pid, (void *)regs.eip, (void *)&data);
if (res != 0)
    //error
res = ptrace(PTRACE_PEEKTEXT, pid, (void *)regs.eip, NULL);
print_word(res);

The first print_word prints exactly the four bytes displayed by GDB. The second print_word instead prints strange bytes and not 0xAABBCCDD.

Any ideas?

MirkoBanchi
  • 2,173
  • 5
  • 35
  • 52

1 Answers1

8

Those strange bytes that you get from the second ptrace(PTRACE_PEEKTEXT, ...) should match the address of data - compare them with the value of &data.

Although the manual page of ptrace(2) shows the data argument as void *, for the PTRACE_POKETEXT request data holds the request value. Using the address-of operator you actually poke the address of the value instead of the value itself. The correct invocation is as follows:

res = ptrace(PTRACE_POKETEXT, pid, (void *)regs.eip, (void *)data); // w/o &
if (res != 0)
    //error
Hristo Iliev
  • 72,659
  • 12
  • 135
  • 186
  • Thank you, it works. My fault! The fourth param must be a pointer to support all the other requests, but do you know the reason why that param, with `PTRACE_POKETEXT`, is no treated as a pointer? – MirkoBanchi Aug 05 '12 at 22:33
  • 3
    `ptrace` is a variadic function, i.e. different requests take different arguments. I believe this particular request takes the data directly (and not a pointer to it) in order to save one userspace- to kernel-space copy operation. – Hristo Iliev Aug 06 '12 at 07:48