#syscalls #intercept

libsyscall-intercept

用户空间系统调用拦截库

3个版本

0.1.2 2023年7月23日
0.1.1 2023年7月23日
0.1.0 2023年7月22日

#13 in #系统调用

MIT 协议

475KB
11K SLoC

C 5.5K SLoC // 0.3% comments GNU Style Assembly 3.5K SLoC // 0.1% comments Perl 1K SLoC // 0.2% comments Shell 491 SLoC // 0.6% comments RPM Specfile 68 SLoC Rust 39 SLoC // 0.3% comments C++ 7 SLoC // 0.8% comments

syscall-intercept-rs

要求

在Ubuntu上安装依赖。

sudo apt install cmake libcapstone-dev

还需要syscall_intercept库。[FIXME] syscall_intercept的GitHub地址

https://github.com/pmem/syscall_intercept

将以下行添加到您的Cargo.toml中

[dependencies]
libsyscall-intercept = "0.1.1"

用法

将lib.rs添加到您的代码中

use std::cell::Cell;
#[macro_use]
extern crate ctor;
use libsyscall_intercept::{set_hook_fn,InterceptResult};


#[ctor]
fn init_preload() {
    unsafe { set_hook_fn(hook) };
}

extern "C" fn hook(
    num: i64,
    _a0: i64,
    _a1: i64,
    _a2: i64,
    _a3: i64,
    _a4: i64,
    _a5: i64,
    result: *mut i64,
) -> i32 {
    // detect and avoid recursive interception
    let _guard = match InterceptGuard::try_lock() {
        Some(g) => g,
        None => return InterceptResult::Forward as i32,
    };
    if num == libc::SYS_getdents64 || num == libc::SYS_getdents {
        unsafe {
            *result =  -libc::ENOTSUP as i64;
        } 
        return InterceptResult::Hook as i32;
    }
    InterceptResult::Forward as i32
}

thread_local! {
    static INTERCEPTED: Cell<bool> = Cell::new(false);
}

struct InterceptGuard;

impl InterceptGuard {
    fn try_lock() -> Option<Self> {
        INTERCEPTED.with(|x| {
            if x.get() {
                None
            } else {
                x.set(true);
                Some(InterceptGuard)
            }
        })
    }
}

impl Drop for InterceptGuard {
    fn drop(&mut self) {
        INTERCEPTED.with(|x| x.set(false));
    }
}

Cargo.toml如下所示

[package]
name = "my-lib-test"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.net.cn/cargo/reference/manifest.html


[dependencies]
ctor = "0.2.0"
libc = "0.2"
libsyscall-intercept = "0.1.1"


[lib]
name = "rintercept"
crate-type = ["dylib"]

然后运行命令

cargo build
LD_PRELOAD=./target/debug/librintercept.so ls

将看到命令 ls不支持

依赖项

~0–2MB
~41K SLoC