#include <stdio.h>
#include <stdlib.h>
#include <sys/ptrace.h>
#include <stdint.h>
#include <errno.h>
#include <sys/wait.h>
int main(int argc, char* argv[])
{
void *addr1;
void *addr2;
pid_t attack_pid = -1;
if (argc < 4 || argv[1] <= 0)
{
printf("usage: ./main pid addr addr\n");
return 0;
}
attack_pid = strtoul(argv[1], 0, 10);
long val = strtoul(argv[4], 0, 10);
uintptr_t address,address2;
sscanf(argv[2], "%lx", &address);
sscanf(argv[3], "%lx", &address2);
addr1 = (void *)address;
addr2 = (void *)address2;
printf("will replace pid(%d) mem address %p %p val %ld\n", attack_pid, addr1, addr2, val);
if (ptrace(PTRACE_ATTACH, attack_pid, NULL, NULL) < 0)
{
printf("attach failed\n");
return 0;
}
//讀取資料
long data;
errno = 0;
while (1) {
waitpid(attack_pid, NULL, 0);
data = ptrace(PTRACE_PEEKDATA , attack_pid, addr1, NULL);
if (data == -1)
perror("PTRACE_PEEKDATA addr1");
else
printf("read global1 %ld\n", data);
data = ptrace(PTRACE_PEEKDATA , attack_pid, addr2, NULL);
if (data == -1)
perror("PTRACE_PEEKDATA addr2");
else
printf("read stack_var %ld\n", data);
//修改資料
printf("POKEDATA %ld\n", ptrace(PTRACE_POKEDATA , attack_pid, addr1, val));
printf("POKEDATA %ld\n", ptrace(PTRACE_POKEDATA , attack_pid, addr2, val));
if (ptrace(PTRACE_CONT, attack_pid, NULL, NULL) == -1) {
perror("ptrace cont");
ptrace(PTRACE_DETACH, attack_pid, NULL, NULL);
}
scanf("%ld", &val);
if (val == 0) break;
if (kill(attack_pid, SIGSTOP) == -1) {
perror("kill");
}
}
ptrace (PTRACE_DETACH, attack_pid, NULL, NULL);
return 0;
}
#include <stdio.h>
int global1 = 11; //
int main(void)
{
long stack_var = 10;
char c = 'a';
printf("pid: %d\n", getpid());
while(1)
{
printf("global1 addrss 0x%lx, global1=%d\n", &global1, global1);
printf("stack_var addrss 0x%lx, stack_var=%d\n", &stack_var, stack_var);
scanf("%c", &c);
getchar();
if (c != 'c')
{
break;
}
}
return 0;
}
編譯
$ mkdir -p build
$ gcc ptrace.c -o build/ptrace
$ gcc main.c -o main
$ ./build/main
pid: 9414
global1 addrss 0x555a27513010, global1=11
stack_var addrss 0x7ffd67ba46b0, stack_var=10
$ ./build/ptrace 9414 555a27513010 7ffd67ba46b0 88