逆向工程 - Frida - Print Struct Value



參考資訊:
https://github.com/frida/frida
https://frida.re/docs/functions/
https://frida.re/docs/installation/
https://github.com/frida/frida/issues/329

main.c

#include <stdio.h>
#include <stdint.h>
#include <unistd.h>

typedef struct {
    uint32_t v[4];
    double d[2];
} mydata;
 
static void test(mydata *p)
{
    p->v[0] = 0x00;
    p->v[1] = 0x11;
    p->v[2] = 0x22;
    p->v[3] = 0x33;
    p->d[0] = 100.1234;
    p->d[1] = 200.5678;
}
 
int main(int argc, char *argv[])
{
    mydata p = { 0 };

    printf("test()=%p\n", test); 
    usleep(10000000);
    test(&p);
 
    return 0;
}

hook.py

import sys
import frida
 
def on_message(message, data):
    print(message)
 
session = frida.attach("main")
 
script = session.create_script("""
    Interceptor.attach(ptr("%s"), {
        onEnter: function (args) {
            this.saveArg = args[0];
        },
        onLeave: function (retval) {
            var raw = this.saveArg.readByteArray(32);
            var u8 = new Uint8Array(raw);
            var u32 = new Uint32Array(raw);

            send("0x" + u32[0].toString(16));
            send("0x" + u32[1].toString(16));
            send("0x" + u32[2].toString(16));
            send("0x" + u32[3].toString(16));

            var buf = new ArrayBuffer(8);
            var view = new DataView(buf);
            for (var i = 0; i < 8; i++) {
                view.setUint8(i, u8[16 + (7 - i)]);
            }
            var num = view.getFloat64(0);
            send(num.toString());

            for (var i = 0; i < 8; i++) {
                view.setUint8(i, u8[24 + (7 - i)]);
            }
            var num = view.getFloat64(0);
            send(num.toString());
        }
    });
""" % int(sys.argv[1], 16))
 
script.on('message', on_message)
script.load()
sys.stdin.read()

編譯、執行

$ gcc main.c -o main
$ ./main&
    test()=0x55cadeb1e149

$ python3 ./hook.py 0x55cadeb1e149
    {'type': 'send', 'payload': '0x0'}
    {'type': 'send', 'payload': '0x11'}
    {'type': 'send', 'payload': '0x22'}
    {'type': 'send', 'payload': '0x33'}
    {'type': 'send', 'payload': '100.1234'}
    {'type': 'send', 'payload': '200.5678'}