Modify the data being transfered with hooking C's read() function

I'm using ld_preload on linux to hook the C's read() function and I want to modify the data being sent through a socket.‌ Consider the following code:

#[no_mangle] // or #[export_name = "read"]
unsafe fn read(d: c_int, buf: *mut c_void, count: size_t) -> ssize_t {
    let ptr = libc::dlsym(libc::RTLD_NEXT, CString::new("read").unwrap().into_raw());
    let c_read: fn(d: c_int, buf: *const c_void, count: size_t) -> ssize_t = std::mem::transmute(ptr);

    let result = c_read(d, buf, count);
    let cstr = CStr::from_ptr(buf as *const _).to_string_lossy().trim().to_string();
    result
}

As you can see I can read the data and store it in cstr , But how can I modify the data that user receives ?

Instead of treating it as a CStr (which implies that the data is some sort of string), I'd use std::slice::from_raw_parts_mut() to convert buf into a &mut [u8] and from there you can play around with the bytes to your heart's content.

You'll need a couple casts to convert buf and count to the right type though (e.g. std::slice::from_raw_parts_mut(buf as *mut u8, count as usize)).

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.