hooking-rs
======
[![github-badge]][github-link]
[![crates-hooking-badge]][crates-hooking]
[![docs-hooking-badge]][docs-hooking]
![License][license-badge]
[license-badge]:https://img.shields.io/crates/l/hooking.svg?style=for-the-badge
[github-badge]: https://img.shields.io/badge/github-pigeonhands/hooking-8da0cb?style=for-the-badge&labelColor=555555&logo=github
[github-link]: https://github.com/pigeonhands/hooking
[actions-badge]: https://img.shields.io/github/actions/workflow/status/pigeonhands/hooking/ci.yml?branch=master&style=for-the-badge
[actions-url]: https://github.com/pigeonhands/hooking/actions
[crates-hooking-badge]: https://img.shields.io/crates/v/hooking.svg?style=for-the-badge&color=fc8d62&logo=rust
[crates-hooking]: https://crates.io/crates/hooking
[docs-hooking-badge]: https://img.shields.io/badge/docs.rs-hooking-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs
[docs-hooking]: https://docs.rs/hooking
Function hooking in rust
-----
A library for hooking and intercepting functions in rust for windows and linux, on x86_64 and x86.
- **Hook by name or address**: `Hook::by_name` finds a symbol in a loaded module, `Hook::create` takes a function pointer.
- **Call the original**: the overwritten instructions are relocated, so the original function still works while hooked.
- **Attribute macros**: `#[hook]` and `#[mini_hook]` create the hook when the program starts and generate `enable_hook`/`disable_hook`.
- **`original_function_ptr`** (x86_64): a hook can get its original function from registers, with no global state.
- **Mini hooks**: hooks without a trampoline, which jump straight to the destination and leave r10/r11 untouched.
- **`HookKind` trait**: create and manage any kind of hook generically, or keep mixed hooks as `Box<dyn HookKind>`.
- **Save-registers hooks** (x86_64): one dispatch function reads and rewrites any hooked function's arguments, without knowing its signature.
- **Pluggable memory handling**: choose where hook code lives and how targets are patched.
```toml
[dependencies]
hooking = "0.6"
```
## Quick start
```rust
use hooking::hook;
#[hook(method = "puts")]
unsafe extern "C" fn hooked_puts(s: *const i8) -> std::ffi::c_int {
let original_puts = unsafe { hooked_puts::original_function().expect("the hook was created") };
original_puts(c"Yes, im hooked!".as_ptr())
}
fn main() {
unsafe { hooked_puts::enable_hook().unwrap() };
unsafe { libc::puts(c"Am i hooked?".as_ptr()) }; // prints "Yes, im hooked!"
unsafe { hooked_puts::disable_hook().unwrap() };
}
```
Types in a hooked function's signature are copied into a generated module, so write them as
full paths (`std::ffi::c_int`, not `c_int`).
## Examples
### Hook a function by address, and call the original
On x86_64, `hooking::original_function_ptr()` returns the original function from inside the
hook. Call it first, before anything else in the hook can overwrite the registers it reads.
On x86, store `hook.original_function()` somewhere the hook can read it, such as a `OnceLock`.
```rust
extern "C" fn hooked_multiply(a: u64, b: u64) -> u64 {
let original = hooking::original_function_ptr().expect("called from the hook");
let original: extern "C" fn(u64, u64) -> u64 = unsafe { std::mem::transmute(original.as_ptr()) };
original(a, b) + 1
}
let mut hook = unsafe { Hook::create(multiply as *mut u8, hooked_multiply as *mut u8)? };
unsafe { hook.apply_hook()? };
assert_eq!(multiply(6, 7), 43);
unsafe { hook.remove_hook()? };
```
### Hook without a trampoline
A `MiniHook` is a `Hook` without the trampoline: the target jumps straight to the
destination, and r10/r11 are left untouched. `original_function_ptr` isn't available in the
destination, but `original_function()` still calls the original.
Use a `MiniHook` over a `Hook` when:
- **The caller passes values in r10 or r11.** A `Hook`'s trampoline overwrites them (on x86_64)
to pass the original function along, so the hook, and the original it calls, never see
them. Some code does pass hidden values there, such as GCC's static chain pointer for nested
functions (r10) and hidden arguments to stubs in JIT runtimes like .NET's CoreCLR.
- **You don't need `original_function_ptr`.** Without the trampoline each call makes one jump
fewer, and the hook takes up less memory.
```rust
#[mini_hook(method = "getpid")]
extern "C" fn offset_getpid() -> std::ffi::c_int {
let original = unsafe { offset_getpid::original_function().expect("the hook was created") };
original() + 1_000_000
}
unsafe { offset_getpid::enable_hook()? };
// std::process::id() now reports the real pid plus a million.
```
Or without the macro:
```rust
let mut hook = unsafe { MiniHook::create(roll_dice as *mut u8, loaded_dice as *mut u8)? };
let original = hook.original_function(); // store it where loaded_dice can read it
unsafe { hook.apply_hook()? };
```
### Work with any kind of hook
`Hook` and `MiniHook` both implement `HookKind`, which has their constructors and their
operations (`apply_hook`, `remove_hook`, `original_function`, `is_applied`, `target`).
```rust
fn create<H: HookKind>(target: GreetFn, detour: GreetFn) -> H {
unsafe { H::create(target as *mut u8, detour as *mut u8).unwrap() }
}
let mut hooks: Vec<Box<dyn HookKind>> = vec![
Box::new(create::<Hook>(hello, loud_hello)),
Box::new(create::<MiniHook>(goodbye, loud_goodbye)),
];
for hook in &mut hooks {
unsafe { hook.apply_hook()? };
}
```
### Inspect and rewrite arguments without knowing the signature (x86_64)
Arguments are saved in the platform's argument order: `[rdi, rsi, rdx, rcx, r8, r9]` and
`xmm0-7` on linux, `[rcx, rdx, r8, r9]` and `xmm0-3` on windows, where the Nth argument uses
slot N of whichever set matches its type.
```rust
extern "C" fn dispatch(
original: usize,
int_regs: *mut u64,
sse_regs: *mut [u8; 16],
result: *mut DispatchResult,
) {
let regs = SavedRegs { int_regs, sse_regs };
let outcome = match regs.read_int(0) {
// Return a value of our own, without calling the original.
0 => DispatchResult::override_float(-1.0),
// Rewrite the first argument, then let the original run.
13 => {
regs.write_int(0, 12);
DispatchResult::passthrough()
}
// Call the original ourselves and change its result.
_ => {
let returned = unsafe { call_with_saved_regs(original, int_regs, sse_regs) };
DispatchResult::override_float(returned.float_val + 0.5)
}
};
unsafe { *result = outcome };
}
let mut hook = unsafe { Hook::create_save_registers(scale as *mut u8, dispatch)? };
```
## How it works
Applying a hook writes a jump over the start of the target: a 5 byte `jmp rel32`, or a 14
byte `jmp [rip+0]` on x86_64 when the hook's code couldn't be placed within 2GB of the target.
A `Hook` places this in an arena:
| Original function address | Where the relocated original is, read by the trampoline on x86_64 |
| Trampoline | Jumps to the hook. On x86_64 it first passes the original function in r10, with a checksum in r11, for `original_function_ptr` |
| Original function | The instructions the jump overwrote, relocated to run here, then a jump back to the rest of the target |
A `MiniHook` has no trampoline: the target jumps straight to the destination, through a small
thunk in the arena only when the destination is more than 2GB away. Its arena code is just
that thunk and the relocated original.
## Arenas and patchers
Creating or applying a hook never makes code that may be running non-executable, so hooks
can be added and removed while hooked functions are being called on other threads.
Where the generated hook code lives is chosen by a `CodeArena`:
| `DualMappedArena` (default) | Maps memory twice, writable and executable. Hooks are written through the writable view, so executable memory never changes protection and hooks share pages. |
| `SealedArena` | Each hook gets fresh memory that is made executable once and never written again. Uses at least a page per hook. |
How the jump is written into the hooked function is chosen by a `PatchWriter`:
| `AliasPatcher` (default on linux) | Swaps the target's pages for an identical memfd-backed copy with a writable alias, then patches through the alias. Protection never changes. |
| `ProtectPatcher` (default on windows) | Makes the target's pages read/write/execute while patching, then restores their original protection. |
```rust
use hooking::{HookWriter, arena::SealedArena, patch::ProtectPatcher};
static ARENA: SealedArena = SealedArena::new();
static PATCHER: ProtectPatcher = ProtectPatcher::new();
let writer = HookWriter::new(&ARENA).with_patcher(&PATCHER);
let mut hook = unsafe { writer.create_hook(target, destination)? };
unsafe { hook.apply_hook()? };
```
## More examples
The [examples](https://github.com/pigeonhands/hooking-rs/tree/master/hooking/examples) directory
has runnable examples (`cargo run -p hooking --example <name>`):
| `hook_puts` | linux | `Hook::by_name` on libc's `puts`, keeping the original in a `OnceLock` |
| `hook_msgboxa` | windows | Hooking `MessageBoxA` in user32.dll, keeping the original in a `OnceLock` |
| `macros` | linux | `#[hook]`, with the macro's `original_function()` and `enable_hook`/`disable_hook` |
| `macro_original_function_ptr` | linux x86_64 | `#[hook]` reaching the original with `original_function_ptr` instead |
| `original_function_ptr` | x86_64 | `Hook::create` on a local function, reaching the original with no stored state |
| `skip_original` | linux | A hook on `getenv` that answers some calls itself instead of calling the original |
| `mini_hook` | all | `MiniHook::create`, calling the original through `original_function()` |
| `mini_hook_macro` | linux | `#[mini_hook]` on libc's `getpid`, calling the original |
| `hook_kind` | all | Creating a `Hook` and a `MiniHook` generically, and managing them together as `Box<dyn HookKind>` |
| `custom_arena` | all | `HookWriter` with `SealedArena` and `ProtectPatcher` |
| `write_hook_table` | all | Writing a hook's code without applying it, and calling its trampoline directly |
| `save_registers` | x86_64 | `create_save_registers`: rewriting arguments, overriding the return value, and `call_with_saved_regs` |
## Testing the Windows build on linux
The Windows build can be tested on linux with [mingw-w64](https://www.mingw-w64.org/) and
[Wine](https://www.winehq.org/). Install mingw-w64's gcc (`mingw-w64-gcc` on Arch,
`gcc-mingw-w64-x86-64` on Debian/Ubuntu) and Wine, then add the target:
```sh
rustup target add x86_64-pc-windows-gnu
```
Run the tests or an example through Wine with cargo's runner setting:
```sh
export CARGO_TARGET_X86_64_PC_WINDOWS_GNU_RUNNER=wine
cargo test --target x86_64-pc-windows-gnu
cargo run --target x86_64-pc-windows-gnu --example save_registers
```
`WINEDEBUG=-all` hides Wine's own logging. Wine isn't Windows, so check anything that depends on
the details of memory protection or loaded modules on real Windows too.