Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux技術

Linux 系統呼叫 Hook 完全指南:從 Ring3 到 Ring0 的監控技術

1. 系統呼叫 Hook 簡介

系統呼叫本質上是一種軟中斷(中斷陷阱)機制,它由作業系統提供的功能入口(sys_call)與 CPU 提供的硬體支援(int 3 trap)共同完成。Hook 是一個相當寬泛的技術主題,因為作業系統從 ring3 到 ring0 是分層的結構,在每一個層次上都可以進行相應的 Hook,而它們採用的方法與達到的效果也不盡相同。本文以「系統呼叫的 Hook」為目標,盡量涵蓋從 ring3 到 ring0 所涉及的方法,藉此實現對系統呼叫的監控,這也是主動防禦與動態入侵檢測的基礎。

2. Ring3 中的 Hook 技術

0x1:LD_PRELOAD 動態連結 .so 函式劫持

在 Linux 的動態連結庫體系中,LD_PRELOAD 是一個能影響程式執行期連結(runtime linker)的環境變數,它允許你指定在程式啟動前優先載入的動態連結庫。載入器進行動態連結時,會把同名的符號覆蓋成 LD_PRELOAD 指定 so 檔中的符號。換句話說,我們可以用自訂 so 庫裡的函式去取代原本函式庫中的同名函式,藉此達成 hook。這與 Windows 下修改 import table 來 hook API、或 PHP 中修改 functions_table 來 hook function 的原理十分類似。

Linux 使用 C 函式庫多為 glibc,也就是幾乎所有 Linux 命令都會動態連結的 libc.so.6。預設情況下,編譯出的程式對標準 C 函式的連結都是透過動態方式指向 libc.so.6。這也意味著,當我們用注入的 .so 完成函式覆蓋劫持後,還需要從 libc.so.6 取回原本正常的函式指標,讓程式能繼續正確執行。

正常程式 main.c:

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{
    if( strcmp(argv[1], 'test') )
    {
        printf('Incorrect password ');
    }
    else
    {
        printf('Correct password ');
    }
    return 0;
}

用於劫持函式的 .so 程式 hook.c:

#include <stdio.h>
#include <string.h>
#include <dlfcn.h>

/* hook 的目標是 strcmp,因此 typedef 一個 STRCMP 函式指標
   hook 的目的是控制函式行為,從原庫 libc.so.6 取得 strcmp 指標,
   保存成 old_strcmp 以備呼叫 */
typedef int(*STRCMP)(const char*, const char*);

int strcmp(const char *s1, const char *s2)
{
    static void *handle = NULL;
    static STRCMP old_strcmp = NULL;

    if( !handle )
    {
        handle = dlopen('libc.so.6', RTLD_LAZY);
        old_strcmp = (STRCMP)dlsym(handle, 'strcmp');
    }
    printf('oops!!! hack function invoked. s1=<%s> s2=<%s> ', s1, s2);
    return old_strcmp(s1, s2);
}

編譯與執行:

gcc -o test main.c
gcc -fPIC -shared -o hook.so hook.c -ldl
LD_PRELOAD=./hook.so ./test 123

3. Ring0 中的 Hook 技術

0x1:Kernel Inline Hook

傳統的 kernel inline hook 做法是修改內核函式的 opcode,寫入 jmp 或 push ret 等指令,使流程跳轉到新的內核函式,藉此達成劫持。對於這類攻擊,常見的防禦手段是 fireeye 提出的「函式返回位址污點檢測」,透過對原有指令返回位置的組語作污點標記,並搜尋 jmp、push ret 等指令來防禦。

一個系統呼叫函式往往會遞迴嵌套呼叫許多子函式。從組語角度來看,對子函式的呼叫採用「段內相對短跳轉 jmp offset」實作,CPU 依 offset 做偏移跳轉。如果我們把下層函式在上層函式中的 offset 替換成「Hook 函式」的 offset,那麼上層呼叫下層時就會跳到我們的 Hook 函式,我們便能在其中做過濾與劫持。

以 sys_read 為例(linux-2.6.32.63 read_write.c):

asmlinkage ssize_t sys_read(unsigned int fd, char __user * buf, size_t count)
{
    struct file *file;
    ssize_t ret = -EBADF;
    int fput_needed;

    file = fget_light(fd, &fput_needed);
    if (file)
    {
        loff_t pos = file_pos_read(file);
        ret = vfs_read(file, buf, count, &pos);
        file_pos_write(file, pos);
        fput_light(file, fput_needed);
    }
    return ret;
}
EXPORT_SYMBOL_GPL(sys_read);

在 sys_read() 中,會呼叫子函式 vfs_read() 完成讀取資料的動作,其組語指令為 call 0xc106d75c <vfs_read>,等同於 jmp offset(相對於 sys_read() 的基底偏移)。因此思路很明確:找到這條 call 指令,把其中的 offset 改成我們 Hook 函式對應的 offset 即可。

整體流程為:

1. 搜尋 sys_read 的 opcode
2. 若發現是 call 指令,根據後面的 offset 計算跳轉位址是否為要 hook 的函式位址
   1) 若「不是」,就重新計算 Hook 函式的 offset 並替換原本的 offset
   2) 若「已經是」Hook 函式的 offset,代表函式已處於被劫持狀態,Hook 引擎應直接跳過,避免重複劫持

概念性範例(patch_kernel_func):

/* 參數:
   1. handler 是上層函式位址,這裡是 sys_read 的位址
   2. old_func 是要替換的函式位址,這裡是 vfs_read
   3. new_func 是新函式位址,這裡是 new_vfs_read 的位址 */
unsigned int patch_kernel_func(unsigned int handler, unsigned int old_func,
                               unsigned int new_func)
{
    unsigned char *p = (unsigned char *)handler;
    unsigned char buf[4] = '';
    unsigned int offset = 0, orig = 0;
    int i = 0;

    while (1) {
        if (i > 512) return 0;
        if (p[0] == 0xe8) {              // 找到 call 指令
            buf[0] = p[1]; buf[1] = p[2]; buf[2] = p[3]; buf[3] = p[4];
            offset = *(unsigned int *)buf;
            orig = offset + (unsigned int)p + 5;
            if (orig == old_func) break; // 找到目標函式
        }
        p++; i++;
    }

    offset = new_func - (unsigned int)p - 5;
    p[1] = (offset & 0x000000ff);
    p[2] = (offset & 0x0000ff00) >> 8;
    p[3] = (offset & 0x00ff0000) >> 16;
    p[4] = (offset & 0xff000000) >> 24;
    return orig;
}

0x2:利用 0x80 中斷劫持 system_call → sys_call_table

要替換系統呼叫表(sys_call_table),前提是先取得它的位址。但出於安全考量,Linux 2.6 之後的內核並未導出 sys_call_table 這個符號,因此需要一些取巧方式來取得。由於系統呼叫都透過 0x80 中斷進行,我們可以從 0x80 中斷的處理程式反推 sys_call_table 的位址,基本步驟如下:

1. 取得中斷描述符表(IDT)的位址(以 C / ASM 組語實作)
2. 從中找出 0x80 中斷(系統呼叫中斷)的服務例程(8 * 0x80 偏移)
3. 搜尋該例程的記憶體空間
4. 從中取得 sys_call_table(保存所有系統呼叫例程入口位址)的位址

程式範例 find_sys_call_table.c:

#include <linux/module.h>
#include <linux/kernel.h>

struct { unsigned short limit; unsigned int base; } __attribute__((packed)) idtr;
struct { unsigned short off1; unsigned short sel; unsigned char none, flags;
         unsigned short off2; } __attribute__((packed)) idt;

void disp_sys_call_table(void)
{
    unsigned int sys_call_off, sys_call_table;
    char* p; int i;

    asm('sidt %0':'=m'(idtr));                 // 取得 IDTR 位址
    memcpy(&idt, idtr.base + 8 * 0x80, sizeof(idt));
    sys_call_off = ((idt.off2 << 16) | idt.off1);

    p = sys_call_off;                          // 搜尋 sys_call_table
    for (i = 0; i < 100; i++) {
        if (p == 'ÿ' && p[i+1] == '' && p[i+2] == '?') {
            sys_call_table = *(unsigned int*)(p + i + 3);
            printk('addr of sys_call_table: %x ', sys_call_table);
            return;
        }
    }
}
module_init(init_get_sys_call_table);
MODULE_LICENSE('GPL2.0');

取得 sys_call_table 基底位址後,就能修改指定 offset 對應的系統呼叫,達到劫持目的。

0x3:取得 sys_call_table 的其他方法

方法一:模擬出一段 call *sys_call_table(,%eax,4),觀察其機器碼,再在 system_call 附近依此特徵搜尋。方法二:直接從 /boot/System.map-<版本> 檔中 grep sys_call_table 取得位址。

0x4:利用 kprobe 機制進行系統呼叫 Hook

kprobe 是一個能動態收集偵錯與效能資訊的工具,由 Dprobe 專案衍生而來,幾乎能追蹤任何函式或被執行的指令。它的運作機制是:註冊探測點時,將被探測函式的指令碼替換為 int 3 斷點指令;執行到斷點時觸發 trap,透過通知鏈呼叫 kprobe 的異常處理函式,判斷是否存在 pre_handler 鉤子並執行;接著進入單步除錯執行原始指令,最後執行 post_handler 並恢復正常流程。整體順序為:pre_handler → 被 Hook 的原函式 → post_handler。

kprobe 實現三種探測點:kprobes(可插入任何指令位置)、jprobes(只能插入函式入口,可無縫取得參數)、kretprobes(在函式返回時才執行)。核心 API 包括 register_kprobe、register_jprobe、register_kretprobe 及對應的 unregister 系列。

kprobe 編程範例(do_fork.c,追蹤新進程建立):

static struct kprobe kp = { .symbol_name = 'do_fork', };

static int handler_pre(struct kprobe *p, struct pt_regs *regs)
{
    struct thread_info *thread = current_thread_info();
    printk(KERN_INFO 'pre-handler: pid = %d ', thread->task->pid);
    return 0;
}
static void handler_post(struct kprobe *p, struct pt_regs *regs, unsigned long flags)
{
    /* 於此記錄 fork 後的資訊 */
}
static int __init kprobe_init(void)
{
    kp.pre_handler = handler_pre;
    kp.post_handler = handler_post;
    return register_kprobe(&kp);
}
module_init(kprobe_init);

4. 後記

Hook 技術是主動防禦與動態入侵檢測的關鍵。目前許多 Hook 手法都偏向「劫持」關鍵流程上函式的執行位址,執行完再跳回原函式(並做好現場保護),或透過注入提前取得 CPU 執行權。但隨著 Windows PatchGuard 的出現,這類出於「安全性」考量的內核 patch 會被視為對內核完整性的威脅。更優雅穩健的方向,是採用系統提供的標準回調機制,例如 kprobe、netfilter 的鏈式處理流程,以及進程、線程、模組建立與卸載的標準回調函式。

Copyright © Linux教程網 All Rights Reserved