MinHook-rs
A Rust implementation of the MinHook library for Windows x64 function hooking.
Installation
[]
= "2.1"
= { = "0.61", = [
"Win32_UI_WindowsAndMessaging",
"Win32_Foundation"
] }
Quick Start
//! Basic MessageBox Hook Example
//!
//! Simple MessageBoxA Hook demonstration showing before/after comparison
use *;
use c_void;
use ptr;
use *;
use UI*;
use PCSTR;
// MessageBoxA function signature
type MessageBoxAFn = unsafe extern "system" fn ;
// Store original function pointer
static mut ORIGINAL_MESSAGEBOX: = None;
// Hook function - modify message content
pub unsafe extern "system"
// Test MessageBox call
Expected output:
MinHook-rs MessageBox Hook Demo
================================
[PHASE 1] Testing original MessageBox behavior
Showing original MessageBox...
[PHASE 2] Installing hook
Initializing MinHook...
Creating MessageBoxA hook...
Enabling hook...
Hook activated successfully!
[PHASE 3] Testing hook effect
Showing hooked MessageBox...
[HOOK] MessageBoxA intercepted!
[PHASE 4] Testing hook stability
Second hook test...
[HOOK] MessageBoxA intercepted!
Third hook test...
[HOOK] MessageBoxA intercepted!
[PHASE 5] Disabling hook
Hook disabled
[PHASE 6] Verifying hook is disabled
Showing normal MessageBox after disable...
[PHASE 7] Cleanup
Cleanup completed
Demo completed successfully!
Summary:
- Original behavior: Normal MessageBox
- Hook active: Message intercepted and modified
- Hook disabled: Normal behavior restored
- Complete cleanup: System returned to initial state
Examples
Basic Hook Example
Run the comprehensive demonstration example:
This example demonstrates all MinHook-rs features including basic hooks, multiple simultaneous hooks, dynamic enable/disable cycles, queued operations, error handling, and performance testing with detailed output.
DLL Hook Examples
Complete DLL hooking workflow with injector and target programs:
# Build hook DLL and test programs
# Start test program (displays several MessageBox dialogs)
# Find process ID and inject hook DLL
|
Notepad Hook Example
Real-world application hooking - intercepts Notepad's exit confirmation dialog:
# Build Notepad hook DLL and injector
# Start Notepad and inject hook
&
|
# Test: Type text in Notepad, try to close without saving
# You'll see a custom hook message instead of normal save dialog
API Reference
Library Management
initialize // Initialize once at startup
uninitialize // Cleanup at shutdown
is_supported // Check platform compatibility
Hook Creation
// Hook by function address
create_hook // Hook by API name (returns trampoline and target)
create_hook_api
// Remove hook
remove_hook
Hook Control
enable_hook // Use ALL_HOOKS for all
disable_hook // Use ALL_HOOKS for all
// Queued (deferred) operations
queue_enable_hook // Apply all queued enable/disable requests in one step
Note: Queued operations do not take effect until you call
apply_queued(). This allows you to schedule multiple enable/disable changes and apply them atomically and safely.
Instruction Analysis
decode_instruction
Usage Patterns
Hook by Address
use *;
use c_void;
unsafe extern "system"
Multiple Hooks
unsafe extern "system"
unsafe extern "system"
Queued Operations
Error Handling
match create_hook_api
x86_64 Instruction Structure
x86_64 instructions use variable-length encoding (1-15 bytes):
[Prefixes] [REX] [Opcode] [ModR/M] [SIB] [Displacement] [Immediate]
0-4 0-1 1-3 0-1 0-1 0-8 0-8 (bytes)
Instruction Components
Legacy Prefixes (0-4 bytes):
F0- LOCK prefixF2/F3- REP/REPE/REPNE prefixes2E/36/3E/26/64/65- Segment override66- Operand size override (16-bit)67- Address size override
REX Prefix (0-1 byte, x64 only):
4 3 2 1 0
W R X B
- W: 64-bit operand size
- R: Extension of ModR/M reg field
- X: Extension of SIB index field
- B: Extension of ModR/M r/m or SIB base field
ModR/M Byte:
7 6 5 3 2 0
mod reg r/m
mod: Addressing mode (00/01/10/11)reg: Register or opcode extensionr/m: Register or memory operand
SIB Byte (if ModR/M indicates):
7 6 5 3 2 0
scale index base
scale: 1, 2, 4, or 8 times multiplierindex: Index registerbase: Base register
Critical Instructions for Hooking
RIP-relative addressing (requires relocation):
mov rax, [rip + offset] ; 48 8B 05 xx xx xx xx
lea rax, [rip + offset] ; 48 8D 05 xx xx xx xx
call [rip + offset] ; FF 15 xx xx xx xx
Direct relative jumps/calls:
call rel32 ; E8 xx xx xx xx
jmp rel32 ; E9 xx xx xx xx
jz rel32 ; 0F 84 xx xx xx xx
Instruction Analysis Example
let code = &;
let inst = decode_instruction;
println!; // 7
println!; // true
println!; // 0x78563412
Hook Implementation
Function hooking replaces the target function's prologue with a jump to the detour:
Original: [Function Prologue] -> [Function Body] -> [Return]
Hooked: [JMP to Relay] -> [Detour] -> [Trampoline] -> [Original Body] -> [Return]
Process Steps
- Disassemble: Decode instructions at target location
- Relocate: Fix RIP-relative addresses in copied instructions
- Trampoline: Create executable memory with original code + jump back
- Relay: Create x64 absolute jump to detour function
- Patch: Atomically replace target prologue with jump to relay
- Thread Safety: Suspend/resume threads during patching
Memory Layout
Target Function: [E9 xx xx xx xx] -> Jump to Relay
[Original bytes backed up]
Trampoline Buffer: [Relocated original instructions]
[JMP back to Target+5]
[Relay: JMP to Detour]
Error Types
| Error | Description |
|---|---|
NotInitialized |
Call initialize() first |
AlreadyCreated |
Hook already exists for target |
NotCreated |
Hook doesn't exist for target |
Enabled/Disabled |
Hook already in requested state |
ModuleNotFound |
Specified module not loaded |
FunctionNotFound |
Function not exported by module |
UnsupportedFunction |
Cannot hook this function safely |
MemoryAlloc/MemoryProtect |
Memory operation failed |
Best Practices
Function Signatures
- Match exact calling conventions (
extern "system"for Windows APIs) - Use proper parameter types and return values
- Handle edge cases and error conditions
Memory Management
Safety Guidelines
- Run as Administrator for system-level hooks
- Validate function addresses before hooking
- Use thread-safe access patterns for hook data
- Proper cleanup prevents crashes and memory leaks
Requirements
- Architecture: x86_64 only
- Operating System: Windows
- Rust Version: 1.85.0+
- Privileges: Administrator for system hooks
License
MIT License - see LICENSE file for details.