用 dd 修改 process 的變量內容

源碼如下

/* test.c */
#include <stdio.h>
#include <stdlib.h>

int global_var = 0x12345678;

int main(int argc, char *args[])
{
    printf("waiting...\n");

    sleep(2);

    printf("hello %s, global_var = 0x%x\n", "world", global_var);

    return 0;
}

Build

$ gcc -o test test.c

確認 global_var 的 address

$ readelf -s test | grep global_var
    52: 0000000000600a04     4 OBJECT  GLOBAL DEFAULT   25 global_var

可用以下方式一行取得 address

$ addr=($(readelf -s test | grep global_var)); addr=0x${addr[1]}

先試試取值

$ ./test & sleep 1; addr=($(readelf -s test | grep global_var)); addr=0x${addr[1]}; dd if=/proc/$!/mem bs=4 count=1 skip=$(($addr/4)) | xxd
[1] 10127
waiting...
dd: ‘/proc/10127/mem’: cannot skip to specified offset
1+0 records in
1+0 records out
4 bytes (4 B) copied, 5.6876e-05 s, 70.3 kB/s
0000000: 7856 3412                                xV4.
hello world, global_var = 0x12345678

Cool, 接下來試寫入

$ ./test & sleep 1; addr=($(readelf -s test | grep global_var)); addr=0x${addr[1]}; echo 0x87654321 | xxd -r | dd of=/proc/$!/mem bs=4 count=1 seek=$(($addr/4)) 
[1] 10885
waiting...
1+0 records in
1+0 records out
4 bytes (4 B) copied, 4.2595e-05 s, 93.9 kB/s
hello world, global_var = 0x21436587

參考資料