2

I learning usage of ptrace.
I tried following simple example but raises a I/O Error.

I would like to overwrite "Hello, world" (printing string) from other process.
A target program prints "Hello, world" string until stop then I want to change this prints string from another program that use ptrace.

However the ptrace program failed to POKEDATA with I/O Error.
I have no idea why it failed.

I have tried on:
x86_64 Linux 5.11.
AMD Ryzen 7 4750U

ptrace code: (This ptrace code refer from http://0xcc.net/blog/archives/000077.html (Japanese))

#include <assert.h>
#include <sys/ptrace.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>

int
main (int argc, char **argv)
{
    assert(argc == 4);
    pid_t pid = atoi(argv[1]);
    void *addr = (void *)strtol(argv[2], NULL, 0);
    void *word = (void *)strtol(argv[3], NULL, 0);

    assert(ptrace(PTRACE_ATTACH, pid, NULL, NULL) == 0);
    wait(NULL);
    if (ptrace(PTRACE_POKEDATA, pid, addr, word) != 0) {
        printf("Error: %s\n", strerror(errno));
        return 0;

    }
    assert(ptrace(PTRACE_DETACH, pid, NULL, NULL) == 0);
    return 0;
}

target code:

#include <stdio.h>
#include <stdbool.h>

int main() {
    while (true) {
        printf("%s\n", "Hello, world");
    }
}

A address of target string in target binary (in my environment):

Contents of section .rodata:
 2000 01000200 48656c6c 6f2c2077 6f726c64  ....Hello, world

exection (shell):

./ptrace target_process_id 0x2004 0x60616263   //try to replace from Hell to abcdl 
8
  • you need an actual address of this string in the process' memory Apr 18, 2021 at 14:49
  • @PawełŁukasik How to get it? Apr 18, 2021 at 14:51
  • 1
    one way is, you can compile w/o PIE and the objdump will give you the address Apr 18, 2021 at 15:37
  • 2
    gcc -no-pie -o target target.c works for me Apr 18, 2021 at 16:13
  • 1
    Oops I was misunderstandeding that pie and pic! It works fine for me. ありがとうございました😀 Apr 18, 2021 at 16:32

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.