Created
March 10, 2020 14:01
-
-
Save fearful-symmetry/42b3dfe86bd006c0851628664c9d9c94 to your computer and use it in GitHub Desktop.
Using Rust and LD_PRELOAD to sniff open() calls
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[package] | |
name = "test-ffi" | |
version = "0.1.0" | |
edition = "2018" | |
[lib] | |
crate-type = ["cdylib"] # Creates dynamic lib | |
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html | |
[dependencies] | |
libc = "0.2.67" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use libc::{c_void, dlsym, RTLD_NEXT}; | |
use std::ffi::{CStr, CString}; | |
use std::mem::transmute; | |
use std::os::raw::c_char; | |
#[no_mangle] | |
pub extern "C" fn open(ptr: *const c_char, flags: i32, mode: u32) -> i32 { | |
let cstr = unsafe { CStr::from_ptr(ptr) }; | |
match cstr.to_str() { | |
Ok(s) => { | |
println!( | |
"Hello From Rust: The target binary tried to open {} with flags {} and mode {:o}", | |
s, flags, mode | |
); | |
} | |
Err(_) => println!("The host failed to open {:?}", ptr), | |
} | |
unsafe { | |
let func_handle = dlsym( | |
RTLD_NEXT, | |
CString::new("open").expect("CString::new failed").as_ptr(), | |
); | |
let cast_func = transmute::<*mut c_void, fn(*const c_char, i32, u32) -> i32>(func_handle); | |
cast_func(ptr, flags, mode) | |
} | |
} | |
/* | |
Build: | |
cargo build --release | |
Run: | |
LD_PRELOAD=$PWD/test-ffi/target/release/libtest_ffi.so cat inject.c | |
Get: | |
Hello From Rust: The target binary tried to open /lib64/libc.so.6 with flags 0 and mode 500 | |
Hello From Rust: The target binary tried to open /lib64/ld-linux-x86-64.so.2 with flags 0 and mode 500 | |
Hello From Rust: The target binary tried to open /usr/lib/gcc/x86_64-redhat-linux/9/libgcc_s.so with flags 0 and mode 500 | |
Hello From Rust: The target binary tried to open /lib64/libgcc_s.so.1 with flags 0 and mode 500 | |
Hello From Rust: The target binary tried to open /usr/lib/gcc/x86_64-redhat-linux/9/crtendS.o with flags 0 and mode 500 | |
Hello From Rust: The target binary tried to open /usr/lib/gcc/x86_64-redhat-linux/9/../../../../lib64/crtn.o with flags 0 and mode 500 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment