首页 > 解决方案 > 复杂铸造

问题描述

在学习了 C 和操作系统的理论知识后,我决定分析一个用于 linux 的内核 rootkit,但是我无法理解一行代码,我不知道如何阅读该行:

*(void **)&((char *)h->original_function)[ASM_HOOK_CODE_OFFSET] = h->modified_function;

完整的上下文:

#if defined __i386__
    // push 0x00000000, ret
    #define ASM_HOOK_CODE "\x68\x00\x00\x00\x00\xc3"
    #define ASM_HOOK_CODE_OFFSET 1
    // alternativly we could do `mov eax 0x00000000, jmp eax`, but it's a byte longer
    //#define ASM_HOOK_CODE "\xb8\x00\x00\x00\x00\xff\xe0"
#elif defined __x86_64__
    // there is no push that pushes a 64-bit immidiate in x86_64,
    // so we do things a bit differently:
    // mov rax 0x0000000000000000, jmp rax
    #define ASM_HOOK_CODE "\x48\xb8\x00\x00\x00\x00\x00\x00\x00\x00\xff\xe0"
    #define ASM_HOOK_CODE_OFFSET 2
#else
    #error ARCH_ERROR_MESSAGE
#endif

struct asm_hook {
    void *original_function;
    void *modified_function;
    char original_asm[sizeof(ASM_HOOK_CODE)-1];
    struct list_head list;
};


/**
 * Patches machine code of the original function to call another function.
 * This function should not be called directly.
 */
void _asm_hook_patch(struct asm_hook *h)
{
    DISABLE_W_PROTECTED_MEMORY
    memcpy(h->original_function, ASM_HOOK_CODE, sizeof(ASM_HOOK_CODE)-1);
    *(void **)&((char *)h->original_function)[ASM_HOOK_CODE_OFFSET] = h->modified_function;
    ENABLE_W_PROTECTED_MEMORY
}

Rootkit链接: https ://github.com/nurupo/rootkit/blob/master/rootkit.c (rootkit.c第314行)

我不想解释rootkit是如何被解释的,只想了解如何阅读那行代码,这行的第一部分让我头晕目眩。

标签: ccastinglinux-kernelkernel-module

解决方案


如果我没记错的话:你从最里面开始,也就是

h->original_function

然后我们在右边看到一个大括号,所以现在我们扫描左边的匹配大括号。但是等一下,我们看到了一个强制转换,(char *)所以它是一个指向 char 的指针,现在大括号关闭了。

在右边我们现在看到一个数组索引来获取元素[ASM_HOOK_CODE_OFFSET],在左边我们现在看到&获取它的地址。所以我们现在有了一个字符的地址。

现在我们只能向左看*(void **),这会将这个地址转换为指向空指针的指针,然后取消引用它并将右侧部分分配给该地址。


推荐阅读