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
objdump
will give you the addressgcc -no-pie -o target target.c
works for me