├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md ├── config.yaml ├── examples ├── README.md ├── fuzz_example_unix.rs ├── fuzz_target │ ├── .gitignore │ ├── Cargo.toml │ ├── build.rs │ └── src │ │ ├── main.rs │ │ └── to_fuzz.c ├── hook_example_windows.rs ├── run_example.rs └── selffuzz │ ├── .gitignore │ ├── Cargo.toml │ ├── README.md │ ├── build.rs │ ├── setup_nyx_linux.sh │ └── src │ ├── main.rs │ ├── unix_to_fuzz.c │ └── win_to_fuzz.c └── src ├── config.rs ├── hooking.rs ├── lib.rs ├── misc.rs ├── modules.rs ├── modules_unix.rs ├── modules_windows.rs └── nyx.rs /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | debug/ 4 | target/ 5 | 6 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 7 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 8 | Cargo.lock 9 | 10 | # These are backup files generated by rustfmt 11 | **/*.rs.bk 12 | 13 | # MSVC Windows builds of rustc generate these, which store debugging information 14 | *.pdb -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "hyperhook" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [target.'cfg(windows)'.dependencies] 7 | winapi = { version = "0.3", features = ["winuser", "psapi", "libloaderapi", "errhandlingapi", "winbase", "processthreadsapi"] } 8 | 9 | [dependencies] 10 | config = { version="0.13.1", features = ["yaml"] } 11 | once_cell = "1.18.0" 12 | serde = "1.0.164" 13 | log = "0.4.19" 14 | simplelog = { version = "0.12.1", features = ["termcolor"] } 15 | retour = { git = "https://github.com/Hpmason/retour-rs" } 16 | document-features = "0.2" 17 | 18 | [target.'cfg(unix)'.dependencies] 19 | redhook = "2.0.0" 20 | phdrs = { git = "https://github.com/softdevteam/phdrs" } 21 | goblin = "0.8.0" 22 | libc = "*" 23 | nix = "0.26.2" 24 | 25 | [dev-dependencies] 26 | clap = { version = "4.0", features = ["derive"] } 27 | 28 | [lib] 29 | name = "hyperhook" 30 | crate_type = ["dylib", "lib"] 31 | 32 | [[example]] 33 | name = "hook_example_windows" 34 | crate-type = ["cdylib"] 35 | 36 | [[example]] 37 | name = "fuzz_example_unix" 38 | crate-type = ["cdylib"] 39 | 40 | [features] 41 | default = ["pt", "kafl"] 42 | #! # Feature Flags 43 | 44 | ## If set, HyperHook assumes the host supports Intel-PT 45 | pt = [] 46 | ## If set, HyperHook assumes that the host runs kAFL Kernel 47 | kafl = [] 48 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # HyperHook 2 | 3 | Hyperhook is a cross-platform harnessing framework designed for Nyx-based fuzzers. 4 | 5 | It provides essential functionalities such as issuing hypercalls, managing function hooks and detours, setting up resident memory pages, and enabling custom signal and exception handlers. Currently, it supports userspace targets on both Linux and Windows. 6 | 7 | ## Features 8 | 9 | - Function detours by address or name 10 | - Module and function resolving 11 | - Signal and exception handling 12 | - Nyx guest-to-host communication via hypercalls 13 | - Config file for PT trace modules 14 | - Malloc resident pages for fuzz input 15 | - Debug logging to host via hypercalls 16 | 17 | ## Resources 18 | 19 | - [HyperHook example usage with Nyx and LibAFL](https://neodyme.io/blog/hyperhook) 20 | - [kAFL's documentation for Nyx setup](https://intellabs.github.io/kAFL/) 21 | - [Generic LibAFL fuzzer for Nyx](https://github.com/AFLplusplus/LibAFL/tree/main/fuzzers/full_system/nyx_launcher) 22 | 23 | ## Getting Started 24 | 25 | We provide [examples](https://github.com/neodyme-labs/hyperhook/tree/main/examples) for both Windows and Linux. 26 | 27 | There is also a [selffuzz](https://github.com/neodyme-labs/hyperhook/tree/main/examples/selffuzz) example for testing purposes. 28 | 29 | For a detailed setup instructions check out our [blog post](https://neodyme.io/blog/hyperhook). 30 | 31 | ## Known Issues 32 | 33 | When building HyperHook for Windows targets in release mode, [the hooking seems to be unstable](https://github.com/Hpmason/retour-rs/issues/59). -------------------------------------------------------------------------------- /config.yaml: -------------------------------------------------------------------------------- 1 | mode: "fuzz" 2 | tracing: 3 | libs: 4 | - libc.so.6 5 | - somelib -------------------------------------------------------------------------------- /examples/README.md: -------------------------------------------------------------------------------- 1 | # Examples 2 | 3 | ## fuzz_example_unix 4 | 5 | Requires target `x86_64-unknown-linux-gnu`: `rustup target add x86_64-unknown-linux-gnu` 6 | 7 | Build: 8 | ``` 9 | RUSTFLAGS="-C target-feature=-crt-static" cargo build --example fuzz_example_unix --target x86_64-unknown-linux-gnu 10 | ``` 11 | 12 | ## hook_example_windows 13 | 14 | Requires target `x86_64-pc-windows-gnu` and `gcc-mingw-w64`: 15 | ``` 16 | sudo apt install gcc-mingw-w64 17 | rustup target add x86_64-pc-windows-gnu 18 | ``` 19 | 20 | Build: 21 | ``` 22 | RUSTFLAGS="-C target-feature=-crt-static" cargo build --example hook_example_windows --target x86_64-pc-windows-gnu 23 | ``` -------------------------------------------------------------------------------- /examples/fuzz_example_unix.rs: -------------------------------------------------------------------------------- 1 | use log::trace; 2 | use std::mem; 3 | use std::sync::OnceLock; 4 | 5 | #[cfg(not(feature = "pt"))] 6 | use simplelog::*; 7 | 8 | use hyperhook::*; 9 | 10 | use redhook::*; 11 | 12 | type FuzzCase = extern "C" fn(usize, i32) -> i32; 13 | static PAYLOAD: OnceLock = OnceLock::new(); 14 | 15 | extern "C" fn fuzz_case_detour(_p_data: usize, _len: i32) -> i32 { 16 | trace!("In fuzz_case_detour"); 17 | 18 | // Generates pre-snapshot if run with ./qemu_tool.sh create_snapshot 19 | nyx::lock(); 20 | 21 | trace!("Initialize agent"); 22 | nyx::agent_init(true); 23 | 24 | trace!("Register default signal handlers"); 25 | misc::register_sighandlers_default(); 26 | 27 | let hook_manager: std::sync::MutexGuard<'_, hooking::HookManager> = 28 | hooking::HOOK_MANAGER.lock().unwrap(); 29 | 30 | // trace!( 31 | // "Initializing PT ranges for libs: {:?}", 32 | // crate::config::get_pt_trace_libs() 33 | // ); 34 | // misc::setup_pt_ranges(crate::config::get_pt_trace_libs()); 35 | 36 | trace!("Setup Intel-PT ranges for main module"); 37 | misc::setup_pt_ranges(vec!["".to_string()]); 38 | 39 | let orig_fn: FuzzCase = unsafe { 40 | mem::transmute( 41 | hook_manager 42 | .get_trampoline("fuzz_case") 43 | .expect("Failed to get trampoline"), 44 | ) 45 | }; 46 | trace!("Got trampoline to original fuzz_case at {:016x}", orig_fn as usize); 47 | 48 | trace!("Allocate resident pages"); 49 | let pages = misc::malloc_resident_pages(256).expect("Failed allocating memory"); 50 | let payload = PAYLOAD.get_or_init(|| pages); 51 | trace!("Got payload pages at {:x}", payload); 52 | 53 | trace!("Send payload address to Nyx"); 54 | nyx::get_payload(*payload); 55 | 56 | trace!("Starting fuzzing loop"); 57 | 58 | trace!("Get next fuzz input"); 59 | // Nyx takes snapshot on first NextPayload hypercall. 60 | nyx::next_payload(); 61 | 62 | trace!("Enable feedback collection"); 63 | nyx::user_acquire(); 64 | 65 | let kafl_payload = unsafe { nyx::KAFLPayload::from_raw(payload) }; 66 | trace!("Got fuzz payload of size {:x} at {:?}", kafl_payload.size, kafl_payload.data); 67 | 68 | trace!("Call original fuzz_case"); 69 | orig_fn(kafl_payload.data as usize, kafl_payload.size as i32); 70 | 71 | trace!("Done. Disable feedbalc collection"); 72 | nyx::release(); 73 | 0 74 | } 75 | 76 | hook! { 77 | unsafe fn __libc_start_main( 78 | main: usize, 79 | argc: libc::c_int, 80 | argv: *const *const libc::c_char, 81 | init: usize, 82 | fini: usize, 83 | rtld_fini: usize, 84 | stack_end: *const libc::c_void 85 | ) -> libc::c_int => my_libc_start_main { 86 | 87 | #[cfg(not(feature = "pt"))] 88 | TermLogger::init( 89 | LevelFilter::Trace, 90 | Config::default(), 91 | TerminalMode::Stdout, 92 | ColorChoice::Auto, 93 | ).unwrap(); 94 | 95 | trace!("In hooked __libc_start_main. Argc: {argc} Main: {:016x}", main as usize); 96 | 97 | trace!("Get symbol address of target function"); 98 | let fuzz_case_addr = modules::get_symbol_address("", "fuzz_case").expect("Failed to get symbol address"); 99 | trace!("Got fuzz_case base address: {:016x}", fuzz_case_addr); 100 | 101 | unsafe { 102 | let mut hook_manager = hooking::HOOK_MANAGER.lock().unwrap(); 103 | 104 | trace!("Place hook at target function"); 105 | hook_manager.add_raw_detour( 106 | "fuzz_case", 107 | (fuzz_case_addr) as *const (), 108 | fuzz_case_detour as *const (), 109 | ); 110 | 111 | trace!("Enable hook for target function"); 112 | hook_manager.enable_detour("fuzz_case"); 113 | } 114 | 115 | let exit_code = real!(__libc_start_main)(main as *const () as usize, argc, argv, init, fini, rtld_fini, stack_end); 116 | 117 | return exit_code; 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /examples/fuzz_target/.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | debug/ 4 | target/ 5 | 6 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 7 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 8 | Cargo.lock 9 | 10 | # These are backup files generated by rustfmt 11 | **/*.rs.bk 12 | 13 | # MSVC Windows builds of rustc generate these, which store debugging information 14 | *.pdb -------------------------------------------------------------------------------- /examples/fuzz_target/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "fuzz_target" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | 10 | [build-dependencies] 11 | cc = "1.0" -------------------------------------------------------------------------------- /examples/fuzz_target/build.rs: -------------------------------------------------------------------------------- 1 | use std::process::Command; 2 | 3 | fn main() { 4 | // If run in Kernel mode, libgcc_s.so.1 need to be loaded as a dependency 5 | Command::new("gcc") 6 | .args(["src/to_fuzz.c", "-o", "target/debug/to_fuzz", "-g"]) 7 | .spawn() 8 | .expect("command failed to start"); 9 | 10 | println!("cargo:rerun-if-changed=src/to_fuzz.c"); 11 | } 12 | -------------------------------------------------------------------------------- /examples/fuzz_target/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | println!("Hello, world!"); 3 | } 4 | -------------------------------------------------------------------------------- /examples/fuzz_target/src/to_fuzz.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int hook_me_1(int arg1) { 5 | printf("Hook me called with arg1: %d\n", arg1); 6 | return 1; 7 | } 8 | 9 | int fuzz_case(char* data, int len) { 10 | if(len < 4) return -1; 11 | if(data[0] == 'N') { 12 | if(data[1] == 'E') { 13 | if(data[2] == '0') { 14 | if(data[3] == 'D') { 15 | if(data[4] == 'y') { 16 | if(data[5] == 'M') { 17 | if(data[6] == 'E') { 18 | int* myPTR = NULL; 19 | *myPTR = 0x13371338; 20 | } 21 | } 22 | } 23 | } 24 | } 25 | } 26 | } 27 | return 0; 28 | } 29 | 30 | 31 | int main() { 32 | printf("Program startup\n"); 33 | 34 | int res = hook_me_1(1338); 35 | printf("Hook me returned: %d\n", res); 36 | 37 | char* buf_input = (char*)malloc(0x1000); 38 | fuzz_case(buf_input, 0x10); 39 | 40 | return 0; 41 | } -------------------------------------------------------------------------------- /examples/hook_example_windows.rs: -------------------------------------------------------------------------------- 1 | #![cfg(windows)] 2 | use winapi::shared::minwindef; 3 | use winapi::shared::minwindef::{BOOL, DWORD, HINSTANCE, LPVOID}; 4 | extern crate hyperhook; 5 | use std::mem; 6 | 7 | use hyperhook::hooking; 8 | use hyperhook::misc; 9 | use hyperhook::modules; 10 | 11 | use log::{error, info}; 12 | use simplelog::*; 13 | 14 | const OFFSET_HOOK_ME: usize = 0x11900; 15 | type FnHookMe1 = extern "C" fn(i32) -> i32; 16 | 17 | #[inline(never)] 18 | extern "C" fn hook_me_1_detour(x: i32) -> i32 { 19 | info!("In detour. Arg Original: {}", x); 20 | let mut hook_manager: std::sync::MutexGuard<'_, hooking::HookManager> = 21 | hooking::HOOK_MANAGER.lock().unwrap(); 22 | info!("Calling original function with arg: 69420"); 23 | unsafe { 24 | let orig_fn: FnHookMe1 = mem::transmute(hook_manager.get_trampoline("hook_me_1").unwrap()); 25 | orig_fn(69420); 26 | 694201337 27 | } 28 | } 29 | 30 | /// Entry point which will be called by the system once the DLL has been loaded 31 | /// in the target process. Declaring this function is optional. 32 | /// 33 | /// # Safety 34 | /// 35 | /// What you can safely do inside here is very limited, see the Microsoft documentation 36 | /// about "DllMain". Rust also doesn't officially support a "life before main()", 37 | /// though it is unclear what that that means exactly for DllMain. 38 | #[no_mangle] 39 | #[allow(non_snake_case, unused_variables)] 40 | extern "system" fn DllMain(dll_module: HINSTANCE, call_reason: DWORD, reserved: LPVOID) -> BOOL { 41 | const DLL_PROCESS_ATTACH: DWORD = 1; 42 | const DLL_PROCESS_DETACH: DWORD = 0; 43 | 44 | match call_reason { 45 | DLL_PROCESS_ATTACH => demo_init(), // Maybe: Start in thread 46 | DLL_PROCESS_DETACH => (), 47 | _ => (), 48 | } 49 | minwindef::TRUE 50 | } 51 | 52 | fn demo_init() { 53 | TermLogger::init( 54 | LevelFilter::Trace, 55 | ConfigBuilder::new() 56 | .set_level_padding(LevelPadding::Right) 57 | .build(), 58 | TerminalMode::Stdout, 59 | ColorChoice::Auto, 60 | ) 61 | .unwrap(); 62 | 63 | let module_entry_point = modules::get_program_entry_point(); 64 | if module_entry_point.is_none() { 65 | error!("Could not find module entry point"); 66 | return; 67 | } 68 | 69 | let module_entry_point = module_entry_point.unwrap(); 70 | 71 | println!("Module EP VA: {:016x}", module_entry_point); 72 | let to_fuzz_base = modules::get_main_module_address().unwrap(); 73 | unsafe { 74 | let mut hook_manager: std::sync::MutexGuard<'_, hooking::HookManager> = 75 | hooking::HOOK_MANAGER.lock().unwrap(); 76 | hook_manager.add_raw_detour( 77 | "hook_me_1", 78 | (to_fuzz_base + OFFSET_HOOK_ME) as *const (), 79 | hook_me_1_detour as *const (), 80 | ); 81 | hook_manager.enable_detour("hook_me_1"); 82 | } 83 | 84 | misc::register_sighandlers_default(); 85 | println!("Done!"); 86 | } 87 | -------------------------------------------------------------------------------- /examples/run_example.rs: -------------------------------------------------------------------------------- 1 | use std::{path::Path, process::Command}; 2 | 3 | use clap::Parser; 4 | 5 | /// Search for a pattern in a file and display the lines that contain it. 6 | #[derive(Parser)] 7 | struct Cli { 8 | /// Path to executable that should be started and injected into 9 | program_to_inject: String, 10 | /// Path of the library, relative to target/debug/examples/ 11 | library_name: String, 12 | } 13 | fn main() { 14 | let args = Cli::parse(); 15 | let libary_fullpath: std::path::PathBuf = Path::new(".") 16 | .join("target/debug/examples/") 17 | .join(args.library_name); 18 | 19 | if !libary_fullpath.exists() { 20 | println!("Library path not found: {:?}", libary_fullpath); 21 | return; 22 | } 23 | 24 | Command::new(args.program_to_inject) 25 | .env("LD_PRELOAD", libary_fullpath.to_str().unwrap()) 26 | .spawn() 27 | .expect("command failed to start"); 28 | } 29 | -------------------------------------------------------------------------------- /examples/selffuzz/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | -------------------------------------------------------------------------------- /examples/selffuzz/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "selffuzz" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | hyperhook = { path = "../../", features = ["kafl", "pt"]} 8 | log = "0.4.19" 9 | simplelog = { version = "0.12.1", features = ["termcolor"] } 10 | libc = "*" 11 | lazy_static = "1.4.0" 12 | 13 | [build-dependencies] 14 | cc = "1.0" -------------------------------------------------------------------------------- /examples/selffuzz/README.md: -------------------------------------------------------------------------------- 1 | # selffuzz 2 | 3 | ## Linux 4 | 5 | Build: 6 | 7 | `RUSTFLAGS='-C target-feature=+crt-static' cargo build --target x86_64-unknown-linux-gnu` 8 | 9 | Setup Nyx directory for kernel mode fuzzing: 10 | 11 | `./setup_nyx_linux.sh` 12 | 13 | ## Windows 14 | 15 | Build: 16 | 17 | `RUSTFLAGS='-C target-feature=+crt-static' cargo build --target x86_64-pc-windows-gnu` 18 | 19 | -------------------------------------------------------------------------------- /examples/selffuzz/build.rs: -------------------------------------------------------------------------------- 1 | extern crate cc; 2 | 3 | fn main() { 4 | if std::env::var_os("CARGO_CFG_WINDOWS").is_some() { 5 | cc::Build::new() 6 | .file("src/win_to_fuzz.c") 7 | .compile("fuzz_case"); 8 | } else { 9 | cc::Build::new() 10 | .file("src/unix_to_fuzz.c") 11 | .compile("fuzz_case"); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /examples/selffuzz/setup_nyx_linux.sh: -------------------------------------------------------------------------------- 1 | mode=$1 2 | 3 | python3 "../../../LibAFL/libafl_nyx/packer/packer/nyx_packer.py" \ 4 | ./target/x86_64-unknown-linux-gnu/$mode/selffuzz \ 5 | /tmp/selffuzz_linux \ 6 | afl \ 7 | processor_trace \ 8 | -args "/tmp/input" \ 9 | -file "/tmp/input" \ 10 | --fast_reload_mode \ 11 | --purge || exit 12 | 13 | python3 ../../../LibAFL/libafl_nyx/packer/packer/nyx_config_gen.py /tmp/selffuzz_linux/ Kernel || exit -------------------------------------------------------------------------------- /examples/selffuzz/src/main.rs: -------------------------------------------------------------------------------- 1 | extern crate core; 2 | use log::trace; 3 | use std::mem; 4 | 5 | use std::sync::OnceLock; 6 | 7 | use hyperhook::*; 8 | 9 | type FuzzCase = extern "C" fn(*const u8, i32) -> i32; 10 | 11 | static PAYLOAD: OnceLock = OnceLock::new(); 12 | static INPUT_SIZE: usize = 1; 13 | 14 | #[link(name = "fuzz_case", kind = "static")] 15 | extern "C" { 16 | fn fuzz_case(data: *const u8, len: i32) -> i32; 17 | } 18 | 19 | extern "C" fn fuzz_case_detour(_p_data: *const u8, _len: i32) -> i32 { 20 | trace!("In fuzz_case detour"); 21 | let hook_manager: std::sync::MutexGuard<'_, hooking::HookManager> = 22 | hooking::HOOK_MANAGER.lock().unwrap(); 23 | 24 | trace!("Locked HOOK_MANAGER"); 25 | 26 | let trampoline = hook_manager.get_trampoline("fuzz_case").unwrap(); 27 | let orig_fn: FuzzCase = unsafe { std::mem::transmute::<_, FuzzCase>(trampoline) }; 28 | 29 | trace!("fuzz_case address: {:x}", orig_fn as usize); 30 | 31 | trace!("Placed trampoline"); 32 | 33 | let payload = PAYLOAD.get_or_init(|| { 34 | misc::malloc_resident_pages(INPUT_SIZE).expect("Failed to get payload address") 35 | }); 36 | 37 | trace!("Payload pages {:x}", payload); 38 | 39 | trace!("Starting fuzzing loop"); 40 | nyx::next_payload(); 41 | nyx::user_acquire(); 42 | 43 | let kafl_payload = unsafe { nyx::KAFLPayload::from_raw(payload) }; 44 | 45 | trace!("payload size {:x}", kafl_payload.size); 46 | trace!("payload ptr {:x}", kafl_payload.data as usize); 47 | 48 | trace!("Calling orig fn"); 49 | orig_fn(kafl_payload.data as *const u8, kafl_payload.size as i32); 50 | 51 | trace!("Called orig fn"); 52 | nyx::release(); 53 | 54 | trace!("Release"); 55 | 0 56 | } 57 | 58 | fn main() { 59 | trace!("Starting selffuzz"); 60 | nyx::lock(); 61 | 62 | nyx::agent_init(false); 63 | 64 | trace!("Finished Agent Init"); 65 | 66 | misc::register_sighandlers_default(); 67 | 68 | trace!("Get module base address"); 69 | 70 | trace!("Get symbol address"); 71 | let to_fuzz_addr = 72 | modules::get_symbol_address("", "fuzz_case").expect("Failed to get symbol address"); 73 | 74 | misc::setup_pt_ranges(vec!["".to_string()]); 75 | 76 | trace!("Hooking target function"); 77 | unsafe { 78 | let mut hook_manager: std::sync::MutexGuard<'_, hooking::HookManager> = 79 | hooking::HOOK_MANAGER.lock().unwrap(); 80 | hook_manager.add_raw_detour( 81 | "fuzz_case", 82 | (to_fuzz_addr) as *const (), 83 | fuzz_case_detour as *const (), 84 | ); 85 | hook_manager.enable_detour("fuzz_case"); 86 | } 87 | 88 | trace!("Allocating resident pages"); 89 | 90 | let pages = misc::malloc_resident_pages(INPUT_SIZE).expect("Failed allocating memory"); 91 | 92 | let payload = PAYLOAD.get_or_init(|| pages); 93 | 94 | trace!("Allocated memory at address: {:x}", *payload); 95 | 96 | trace!("Mmap shared buffer between QEMU and fuzzer"); 97 | nyx::get_payload(*payload); 98 | 99 | trace!("Calling fuzzcase"); 100 | unsafe { fuzz_case(0 as *const u8, 0) }; 101 | } 102 | -------------------------------------------------------------------------------- /examples/selffuzz/src/unix_to_fuzz.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | 6 | int fuzz_case(char* data, int len) { 7 | if(len < 7) return -1; 8 | if(data[0] == 'N') { 9 | if(data[1] == 'E') { 10 | if(data[2] == '0') { 11 | if(data[3] == 'D') { 12 | if(data[4] == 'y') { 13 | if(data[5] == 'M') { 14 | if(data[6] == 'E') { 15 | *((uint32_t*)0x00) = 0x13371338; 16 | } 17 | } 18 | } 19 | } 20 | } 21 | } 22 | } 23 | 24 | if(data[0] == 'T') { 25 | if(data[1] == '1') { 26 | if(data[2] == 'M') { 27 | if(data[3] == 'e') { 28 | if(data[4] == 'O') { 29 | if(data[5] == 'U') { 30 | if(data[6] == 'T') { 31 | while (1) { 32 | 33 | } 34 | } 35 | } 36 | } 37 | } 38 | } 39 | } 40 | } 41 | return 0; 42 | } 43 | 44 | -------------------------------------------------------------------------------- /examples/selffuzz/src/win_to_fuzz.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | 6 | __declspec( dllexport ) int fuzz_case(char* data, int len) { 7 | if(len < 7) return -1; 8 | if(data[0] == 'N') { 9 | if(data[1] == 'E') { 10 | if(data[2] == '0') { 11 | if(data[3] == 'D') { 12 | if(data[4] == 'y') { 13 | if(data[5] == 'M') { 14 | if(data[6] == 'E') { 15 | *((uint32_t*)0x00) = 0x13371338; 16 | } 17 | } 18 | } 19 | } 20 | } 21 | } 22 | } 23 | 24 | if(data[0] == 'T') { 25 | if(data[1] == '1') { 26 | if(data[2] == 'M') { 27 | if(data[3] == 'e') { 28 | if(data[4] == 'O') { 29 | if(data[5] == 'U') { 30 | if(data[6] == 'T') { 31 | while (1) { 32 | 33 | } 34 | } 35 | } 36 | } 37 | } 38 | } 39 | } 40 | } 41 | return 0; 42 | } 43 | 44 | -------------------------------------------------------------------------------- /src/config.rs: -------------------------------------------------------------------------------- 1 | //! Module for handling configuration settings for HyperHook. 2 | 3 | use config::Config; 4 | use once_cell::sync::Lazy; 5 | 6 | use serde::Deserialize; 7 | 8 | #[derive(Debug, Deserialize)] 9 | struct HyperhookConfig { 10 | mode: String, 11 | tracing: TraceOptions, 12 | } 13 | 14 | #[derive(Debug, Deserialize)] 15 | struct TraceOptions { 16 | libs: Vec, 17 | } 18 | 19 | /// Not used for now. Could be used to dump core in reproduction mode or e.g. backtrace in trace mode 20 | pub enum HyerhookMode { 21 | /// Default operation 22 | Fuzz, 23 | /// Reproduction run 24 | Reproduce, 25 | /// Trace run 26 | Trace, 27 | } 28 | 29 | static CONFIG: Lazy = Lazy::new(|| { 30 | let settings = Config::builder() 31 | .add_source(config::File::with_name("config.yaml")) 32 | // Add in settings from the environment (with a prefix of APP) 33 | // Eg.. `APP_DEBUG=1 ./target/app` would set the `debug` key 34 | .add_source(config::Environment::with_prefix("HYPERHOOK")) 35 | .build() 36 | .unwrap(); 37 | settings.try_deserialize::().unwrap() 38 | }); 39 | 40 | /// Returns a `HyerhookMode` enum value, based on the mode specified in the configuration. 41 | pub fn get_hyperhook_mode() -> HyerhookMode { 42 | let mode = CONFIG.mode.as_str(); 43 | match mode { 44 | "fuzz" => HyerhookMode::Fuzz, 45 | "reproduce" => HyerhookMode::Reproduce, 46 | "trace" => HyerhookMode::Trace, 47 | _ => panic!("Invalid mode set: {}", mode), 48 | } 49 | } 50 | 51 | /// Returns a vector of strings containing the library names to be traced during execution. 52 | pub fn get_pt_trace_libs() -> Vec { 53 | CONFIG.tracing.libs.to_vec() 54 | } 55 | -------------------------------------------------------------------------------- /src/hooking.rs: -------------------------------------------------------------------------------- 1 | //! Provides functionality for hooking and detouring function calls in HyperHook. 2 | //! 3 | //! It allows adding raw detours for specific functions, enabling and disabling detours, and retrieving the trampoline pointer for a detour. 4 | 5 | use std::{collections::HashMap, sync::Mutex}; 6 | 7 | use once_cell::sync::Lazy; 8 | 9 | use retour::RawDetour; 10 | 11 | /// A thread-safe global Lazy static instance of `HookManager`. 12 | pub static HOOK_MANAGER: Lazy> = Lazy::new(|| Mutex::new(HookManager::new())); 13 | 14 | /// A function pointer type representing the signature of the `main` function in C. 15 | #[cfg(target_os = "linux")] 16 | pub type MainFcnPtr = 17 | unsafe extern "C" fn(libc::c_int, *const *const libc::c_char, *const *const libc::c_char); 18 | 19 | /// The original function pointer for the `main` function. 20 | pub static mut MAIN_PTR_ORIGINAL: usize = 0; 21 | 22 | /// Manages the raw detour hooks for function calls. 23 | pub struct HookManager { 24 | raw_detours: HashMap, 25 | } 26 | 27 | impl HookManager { 28 | /// Adds a raw detour for a specified function by name, target, and detour addresses. 29 | /// # Safety 30 | /// TODO 31 | pub unsafe fn add_raw_detour(&mut self, name: &str, target: *const (), detour: *const ()) { 32 | unsafe { 33 | let hook = RawDetour::new(target, detour) 34 | .expect("target or source is not usable for detouring"); 35 | self.raw_detours.insert(name.to_string(), hook); 36 | } 37 | } 38 | 39 | /// Enables a detour for a specified function. 40 | /// # Safety 41 | /// TODO 42 | pub unsafe fn enable_detour(&mut self, name: &str) -> bool { 43 | unsafe { 44 | let hook = self.raw_detours.get(name); 45 | if hook.is_none() { 46 | return false; 47 | } 48 | 49 | hook.unwrap().enable().is_ok() 50 | } 51 | } 52 | 53 | /// Disables a detour for a specified function. 54 | pub fn disable_detour(&mut self, name: &str) -> bool { 55 | let hook = self.raw_detours.get(name); 56 | if hook.is_none() { 57 | return false; 58 | } 59 | unsafe { hook.unwrap().disable().is_ok() } 60 | } 61 | 62 | // TODO: How to do generics and mem::transmute to get directly a nice trampoline pointer? 63 | // REF: https://github.com/darfink/detour-rs/blob/3b6f17a8b51ba5b37addc8c4361e5cfbe2875243/tests/lib.rs#L34C33-L34C48 64 | /// Returns the trampoline pointer for a detour. 65 | pub fn get_trampoline(&self, name: &str) -> Option<*const ()> { 66 | self.raw_detours 67 | .get(name) 68 | .map(|hook| hook.trampoline() as *const ()) 69 | } 70 | 71 | fn new() -> HookManager { 72 | HookManager { 73 | raw_detours: HashMap::new(), 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Hyperhook is a cross-platform harnessing framework designed for Nyx-based fuzzers. 2 | //! 3 | //! It provides essential functionalities for fuzzing, triaging, and tracing/debugging executions, 4 | //! offering platform-specific support for issuing hypercalls, managing detours with raw detour patches, 5 | //! setting up resident memory pages, and enabling custom signal and exception handlers. 6 | #![doc = document_features::document_features!()] 7 | 8 | pub mod config; 9 | pub mod hooking; 10 | pub mod misc; 11 | pub mod modules; 12 | pub mod nyx; 13 | -------------------------------------------------------------------------------- /src/misc.rs: -------------------------------------------------------------------------------- 1 | //! A collection of miscellaneous utility functions and error handling code used in various parts of the HyperHook library. 2 | 3 | #[cfg(unix)] 4 | use libc::*; 5 | #[cfg(unix)] 6 | use nix::sys::signal; 7 | #[cfg(unix)] 8 | use phdrs::objects; 9 | #[cfg(unix)] 10 | use std::alloc::{alloc, Layout}; 11 | 12 | 13 | #[cfg(windows)] 14 | use winapi::shared::minwindef::HMODULE; 15 | 16 | #[cfg(windows)] 17 | use winapi::um::{ 18 | processthreadsapi::GetCurrentProcess, 19 | errhandlingapi::GetLastError, 20 | winbase::SetProcessWorkingSetSize, 21 | memoryapi::{VirtualAlloc, VirtualLock}, 22 | psapi::MODULEINFO, 23 | }; 24 | 25 | use std::panic; 26 | 27 | use log::*; 28 | 29 | use crate::modules; 30 | use crate::nyx; 31 | 32 | /// Allocates memory pages and locks them in memory to make them resident 33 | #[cfg(all(target_arch = "x86_64", target_os = "linux"))] 34 | pub fn malloc_resident_pages(num_pages: usize) -> Option { 35 | // Get pagesize 36 | let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) as usize }; 37 | 38 | let data_size = page_size * num_pages; 39 | 40 | // Allocate a page-aligned memory block 41 | let layout = Layout::from_size_align(data_size, page_size).unwrap(); 42 | let aligned_ptr = unsafe { alloc(layout) }; 43 | 44 | if aligned_ptr.is_null() { 45 | error!("Failed to allocate memory"); 46 | return None; 47 | } 48 | 49 | info!("Allocated memory at address: {:?}", aligned_ptr); 50 | 51 | // Lock the pages in memory to prevent swapping (resident pages) 52 | let result = unsafe { libc::mlock(aligned_ptr as *const libc::c_void, data_size) }; 53 | if result != 0 { 54 | error!("Failed to lock pages in memory"); 55 | return None; 56 | } 57 | 58 | info!("Locked memory at address: {:?}", aligned_ptr); 59 | 60 | Some(aligned_ptr as uintptr_t) 61 | } 62 | 63 | #[cfg(target_os = "windows")] 64 | #[inline(never)] 65 | pub fn malloc_resident_pages(num_pages: usize) -> Option { 66 | use std::ptr::null_mut; 67 | 68 | use winapi::ctypes::c_void; 69 | // Get pagesize 70 | let page_size = 0x1000; // Hardcoded for now. Windows supports 4k (small) and 2MB pages 71 | let dw_min = 1 << 25; // min: 64MB 72 | let dw_max = 1 << 31; // max: 2GB 73 | 74 | let data_size = page_size * num_pages; 75 | 76 | // Allocate actual memory as RW 77 | // 0x3000 = MEM_RESERVE | MEM_COMMIT 0x04 = PAGE_READWRITE 78 | let alloc = unsafe { 79 | VirtualAlloc(null_mut(), data_size, 0x3000, 0x04) as *mut c_void 80 | }; 81 | 82 | if alloc.is_null() { 83 | let last_error = unsafe { GetLastError() }; 84 | error!("Failed to allocate memory. Last Error: {}", last_error); 85 | return None; 86 | } 87 | 88 | let h_process; 89 | unsafe { 90 | h_process = GetCurrentProcess(); 91 | } 92 | 93 | if h_process.is_null() { 94 | let last_error = unsafe { GetLastError() }; 95 | error!("Failed to open own process. Last Error: {}", last_error); 96 | return None; 97 | } 98 | 99 | 100 | /* 101 | let mut dw_min: SIZE_T = 0; 102 | let mut dw_max: SIZE_T = 0; 103 | unsafe { 104 | if GetProcessWorkingSetSize(h_process, &mut dw_min, &mut dw_max) == 0 { 105 | let last_error = GetLastError(); 106 | error!("Failed to get process working set size. Last Error: {}", last_error); 107 | return None; 108 | } 109 | } 110 | */ 111 | 112 | unsafe { 113 | if SetProcessWorkingSetSize(h_process, dw_min, dw_max) == 0 { 114 | let last_error = GetLastError(); 115 | error!("Failed to set process working set size. Last Error: {}", last_error); 116 | return None; 117 | } 118 | } 119 | 120 | unsafe { 121 | if VirtualLock(alloc as *mut c_void, data_size) == 0 { 122 | let last_error = GetLastError(); 123 | error!( 124 | "[+] WARNING: Virtuallock failed to lock payload buffer. Last Error: {}", 125 | last_error 126 | ); 127 | return None; 128 | } 129 | } 130 | 131 | Some(alloc as usize) 132 | } 133 | 134 | #[cfg(all(target_arch = "x86", target_os = "linux"))] 135 | extern "C" fn sighandler_default( 136 | signo: libc::c_int, 137 | info: *mut libc::siginfo_t, 138 | extra: *mut libc::c_void, 139 | ) { 140 | let ucontext_ptr: *mut ucontext_t = extra as *mut libc::ucontext_t; 141 | let ucontext: &mut libc::ucontext_t = unsafe { &mut *ucontext_ptr }; 142 | 143 | let signinfo_ptr: *mut siginfo_t = info as *mut libc::siginfo_t; 144 | let siginfo: &mut siginfo_t = unsafe { &mut *signinfo_ptr }; 145 | 146 | let reason: u64 = 0x8000000000000000u64 147 | | ucontext.uc_mcontext.gregs[libc::REG_EIP as usize] as u64 148 | | ((siginfo.si_signo as u64) << 47); 149 | 150 | nyx::hypercall(nyx::KAFLHypercalls::Panic, reason as usize); 151 | 152 | panic!("Caught fatal signal: {signo}") 153 | } 154 | 155 | #[cfg(all(target_arch = "x86_64", target_os = "linux"))] 156 | extern "C" fn sighandler_default( 157 | signo: libc::c_int, 158 | info: *mut libc::siginfo_t, 159 | extra: *mut libc::c_void, 160 | ) { 161 | let ucontext_ptr: *mut ucontext_t = extra as *mut libc::ucontext_t; 162 | let ucontext: &mut libc::ucontext_t = unsafe { &mut *ucontext_ptr }; 163 | 164 | let signinfo_ptr: *mut siginfo_t = info; 165 | let siginfo: &mut siginfo_t = unsafe { &mut *signinfo_ptr }; 166 | 167 | let reason: u64 = 0x8000000000000000u64 168 | | ucontext.uc_mcontext.gregs[libc::REG_RIP as usize] as u64 169 | | ((siginfo.si_signo as u64) << 47); 170 | 171 | nyx::hypercall(nyx::KAFLHypercalls::Panic, reason as usize); 172 | 173 | panic!("Caught fatal signal: {signo}") 174 | } 175 | 176 | #[cfg(all(target_arch = "x86_64", target_os = "linux"))] 177 | pub extern "C" fn sighandler_backtrace( 178 | signo: libc::c_int, 179 | _info: *mut libc::siginfo_t, 180 | _extra: *mut libc::c_void, 181 | ) { 182 | use std::backtrace::Backtrace; 183 | let bp = Backtrace::force_capture().to_string(); 184 | nyx::panic_extended(bp); 185 | 186 | panic!("Caught fatal signal: {signo}") 187 | } 188 | 189 | #[cfg(all(target_arch = "x86", target_os = "windows"))] 190 | #[inline(never)] 191 | unsafe extern "system" fn exception_handler_default( 192 | exception: *mut winapi::um::winnt::EXCEPTION_POINTERS, 193 | ) -> winapi::um::winnt::LONG { 194 | let exception_data = *exception; 195 | let exception_record = *exception_data.ExceptionRecord; 196 | let exception_context = *exception_data.ContextRecord; 197 | 198 | let reason: u64 = 0x8000000000000000u64 199 | | exception_context.Eip as u64 200 | | ((exception_record.ExceptionCode as u64) << 47); 201 | 202 | nyx::hypercall(nyx::KAFLHypercalls::Panic, reason as usize); 203 | 204 | let exception_code = exception_record.ExceptionCode; 205 | let addr = exception_record.ExceptionAddress as usize; 206 | 207 | panic!("Caught fatal, unhanlded exception: {exception_code:016x} Addr: {addr:016x}") 208 | } 209 | 210 | #[cfg(all(target_arch = "x86_64", target_os = "windows"))] 211 | #[inline(never)] 212 | unsafe extern "system" fn exception_handler_default( 213 | exception: *mut winapi::um::winnt::EXCEPTION_POINTERS, 214 | ) -> winapi::um::winnt::LONG { 215 | use winapi::um::errhandlingapi::GetLastError; 216 | 217 | let last_error = GetLastError(); 218 | error!("Exception Handler Error: {last_error}"); 219 | let exception_data = *exception; 220 | let exception_record = *exception_data.ExceptionRecord; 221 | let exception_context = *exception_data.ContextRecord; 222 | 223 | let reason: u64 = 0x8000000000000000u64 224 | | exception_context.Rip 225 | | ((exception_record.ExceptionCode as u64) << 47); 226 | 227 | nyx::hypercall(nyx::KAFLHypercalls::Panic, reason as usize); 228 | 229 | let exception_code = exception_record.ExceptionCode; 230 | let addr = exception_record.ExceptionAddress as usize; 231 | 232 | panic!("Caught fatal, unhanlded exception: {exception_code:016x} Addr: {addr:016x}") 233 | } 234 | 235 | /// Register custom signal handlers on Unix systems and exception handlers on Windows systems. 236 | #[cfg(unix)] 237 | pub fn register_sighandlers_custom( 238 | handler: extern "C" fn(libc::c_int, *mut libc::siginfo_t, *mut libc::c_void), 239 | ) { 240 | unsafe { 241 | let sig_action: signal::SigAction = signal::SigAction::new( 242 | signal::SigHandler::SigAction(handler), 243 | signal::SaFlags::empty(), 244 | signal::SigSet::empty(), 245 | ); 246 | if signal::sigaction(signal::SIGSEGV, &sig_action).is_err() 247 | || signal::sigaction(signal::SIGFPE, &sig_action).is_err() 248 | || signal::sigaction(signal::SIGBUS, &sig_action).is_err() 249 | || signal::sigaction(signal::SIGILL, &sig_action).is_err() 250 | || signal::sigaction(signal::SIGABRT, &sig_action).is_err() 251 | || signal::sigaction(signal::SIGIOT, &sig_action).is_err() 252 | || signal::sigaction(signal::SIGTRAP, &sig_action).is_err() 253 | || signal::sigaction(signal::SIGSYS, &sig_action).is_err() 254 | { 255 | panic!("Failed to installed at least one signal handler. Aborting..."); 256 | } 257 | }; 258 | } 259 | 260 | #[cfg(windows)] 261 | #[inline(never)] 262 | pub fn register_sighandlers_custom( 263 | handler: winapi::um::errhandlingapi::LPTOP_LEVEL_EXCEPTION_FILTER, 264 | ) { 265 | use winapi::um::errhandlingapi::SetUnhandledExceptionFilter; 266 | unsafe { 267 | SetUnhandledExceptionFilter(handler); 268 | }; 269 | } 270 | 271 | /// Gets memory range for n modules by name and sets them as PT ranges. 272 | #[inline(never)] 273 | pub fn setup_pt_ranges(modules: Vec) { 274 | for m in modules { 275 | let range = get_address_range_for_module(m.as_str()); 276 | match range { 277 | Some(address_range) => nyx::send_pt_range_to_hypervisor(address_range), 278 | None => warn!("[!] Module not found for tracing: {m}"), 279 | } 280 | } 281 | } 282 | 283 | #[cfg(windows)] 284 | pub fn get_module_info(h_module: HMODULE) -> Option { 285 | use std::mem; 286 | 287 | use winapi::um::{ 288 | psapi::{GetModuleInformation, MODULEINFO}, 289 | winnt::HANDLE, 290 | }; 291 | 292 | let mut mod_info: MODULEINFO = MODULEINFO { 293 | lpBaseOfDll: std::ptr::null_mut(), 294 | SizeOfImage: 0, 295 | EntryPoint: std::ptr::null_mut(), 296 | }; 297 | let own_process_handle = usize::MAX as HANDLE; // -1 is the own process pseudo handle 298 | unsafe { 299 | if GetModuleInformation( 300 | own_process_handle, 301 | h_module, 302 | &mut mod_info, 303 | mem::size_of::() as u32, 304 | ) == 0 305 | { 306 | return None; 307 | } 308 | } 309 | 310 | Some(mod_info) 311 | } 312 | 313 | #[cfg(windows)] 314 | pub fn get_address_range_for_module(module: &str) -> Option { 315 | use std::mem; 316 | 317 | use winapi::{ 318 | shared::{ 319 | minwindef::{DWORD, HINSTANCE, HMODULE, MAX_PATH}, 320 | ntdef::NULL, 321 | }, 322 | um::{ 323 | errhandlingapi::GetLastError, 324 | psapi::GetModuleBaseNameA, 325 | winnt::HANDLE, 326 | }, 327 | }; 328 | 329 | trace!("Searching for module: {}", module); 330 | 331 | let mut mods = [NULL as HINSTANCE; 1024]; 332 | let own_process_handle = usize::MAX as HANDLE; // -1 is the own process pseudo handle 333 | let mut space_needed: DWORD = 0; 334 | 335 | { 336 | unsafe { 337 | let res = winapi::um::psapi::EnumProcessModules( 338 | own_process_handle, 339 | mods.as_mut_ptr(), 340 | mem::size_of::<[HMODULE; 1024]>() as u32, 341 | &mut space_needed, 342 | ); 343 | 344 | if res == 0 { 345 | let last_error = GetLastError(); 346 | 347 | error!("EnumProcessModules failed. Res: {res} Error: {last_error}"); 348 | } 349 | trace!( 350 | "EnumProcessModules returned {} elements", 351 | space_needed / std::mem::size_of::() as u32 352 | ) 353 | } 354 | } 355 | 356 | for i in 0..space_needed / mem::size_of::() as u32 { 357 | //Get module names 358 | let mut mod_name: [u8; 260] = [0; MAX_PATH]; 359 | let res: DWORD; 360 | unsafe { 361 | res = GetModuleBaseNameA( 362 | own_process_handle, 363 | mods[i as usize], 364 | mod_name.as_mut_ptr() as *mut i8, 365 | MAX_PATH as u32, 366 | ); 367 | trace!("GetModuleBaseNameA res: {}", res); 368 | if res != 0 { 369 | let mod_name_len = mod_name.iter().position(|&r| r == 0).unwrap(); 370 | let mod_name_str = std::str::from_utf8(&mod_name[0..mod_name_len]).unwrap(); 371 | 372 | trace!("Found loaded module: {}", mod_name_str); 373 | 374 | if mod_name_str.contains(module) { 375 | let mod_info = get_module_info(mods[i as usize]); 376 | mod_info?; 377 | let mod_info = mod_info.unwrap(); 378 | 379 | let addr_range = modules::AddressRange { 380 | start: mod_info.lpBaseOfDll as u64, 381 | end: (mod_info.lpBaseOfDll as u64 + mod_info.SizeOfImage as u64) as u64, 382 | ..Default::default() 383 | }; 384 | 385 | trace!( 386 | "Found matching module. Base: {:016x} End: {:016x}", 387 | addr_range.start, 388 | addr_range.end 389 | ); 390 | return Some(addr_range); 391 | } 392 | } 393 | } 394 | } 395 | 396 | None 397 | } 398 | 399 | #[cfg(unix)] 400 | #[inline(never)] 401 | pub fn get_address_range_for_module(module: &str) -> Option { 402 | trace!("Searching for module: {}", module); 403 | 404 | for o in objects() { 405 | let obj_name_str = String::from_utf8_lossy(o.name().to_bytes()).to_string(); 406 | 407 | if obj_name_str.contains(module) { 408 | let base_addr = o.addr(); 409 | 410 | for h in o.iter_phdrs() { 411 | if (h.type_() & PT_LOAD) != 0 && (h.flags() & PF_X) != 0 { 412 | let range = modules::AddressRange { 413 | start: (base_addr + h.vaddr()), 414 | end: (base_addr + h.offset() + h.memsz()), 415 | ..Default::default() 416 | }; 417 | trace!("Module found: \n\tRange: {:x?}", range); 418 | return Some(range); 419 | } 420 | } 421 | } 422 | } 423 | 424 | info!("Module {} not found!", module); 425 | None 426 | } 427 | 428 | /// The `sighandler_default`/`exception_handler_default` methods as the default custom handlers. 429 | #[cfg(unix)] 430 | pub fn register_sighandlers_default() { 431 | register_sighandlers_custom(sighandler_default) 432 | } 433 | 434 | #[cfg(windows)] 435 | pub fn register_sighandlers_default() { 436 | register_sighandlers_custom(Some(exception_handler_default)) 437 | } 438 | -------------------------------------------------------------------------------- /src/modules.rs: -------------------------------------------------------------------------------- 1 | /// Defines the start and end addresses of a memory range and is used for representing memory address ranges in the library. 2 | #[derive(Debug, Default)] 3 | pub struct AddressRange { 4 | pub start: u64, 5 | pub end: u64, 6 | pub index: u64, 7 | } 8 | 9 | #[cfg(unix)] 10 | #[path = "modules_unix.rs"] 11 | pub mod modules_impl; 12 | 13 | #[cfg(windows)] 14 | #[path = "modules_windows.rs"] 15 | pub mod modules_impl; 16 | 17 | pub use modules_impl::*; 18 | -------------------------------------------------------------------------------- /src/modules_unix.rs: -------------------------------------------------------------------------------- 1 | //! Module containing platform-specific functions for handling modules on Unix systems. 2 | 3 | use goblin::elf; 4 | use log::{trace, warn}; 5 | use phdrs::objects; 6 | 7 | // use std::{collections::HashMap, path::PathBuf, sync::Mutex}; 8 | // use once_cell::sync::Lazy; 9 | 10 | // static MODULE_CACHE: Lazy>> = Lazy::new(|| Mutex::new(HashMap::new())); 11 | 12 | /// Represents a loaded object and provides methods to get symbol addresses and other information from the module. 13 | struct Module { 14 | object: phdrs::Object, 15 | path: std::path::PathBuf, 16 | } 17 | 18 | impl Module { 19 | /// Get a loaded Object by name. Use an empty string "" to get the main module. 20 | fn new(module_name: &str) -> Option { 21 | for object in objects() { 22 | let obj_name_str = String::from_utf8_lossy(object.name().to_bytes()).to_string(); 23 | trace!("Got module name via phdr: {}", obj_name_str.as_str()); 24 | 25 | if obj_name_str.contains(module_name) { 26 | let path = match module_name.is_empty() { 27 | true => std::env::current_exe().unwrap(), 28 | false => std::path::PathBuf::from(obj_name_str), 29 | }; 30 | 31 | return Some(Module { object, path }); 32 | } 33 | } 34 | None 35 | } 36 | 37 | /// Get the address of a symbol in a module. 38 | fn get_symbol_address(self, symbol: &str) -> Option { 39 | trace!("Reading module {} from disk", self.path.display()); 40 | let buffer = std::fs::read(self.path).expect("Failed to read module from disk"); 41 | let elf = elf::Elf::parse(&buffer).expect("Failed to parse module"); 42 | 43 | if let Some(offset) = get_offset(&elf.dynsyms, &elf.dynstrtab, symbol) { 44 | trace!( 45 | "Found function {symbol} at 0x{:016x}", 46 | offset + self.object.addr() as usize 47 | ); 48 | return Some(offset + self.object.addr() as usize); 49 | } 50 | 51 | if let Some(offset) = get_offset(&elf.syms, &elf.strtab, symbol) { 52 | trace!( 53 | "Found function {symbol} at 0x{:016x}", 54 | offset + self.object.addr() as usize 55 | ); 56 | return Some(offset + self.object.addr() as usize); 57 | } 58 | warn!("Symbol {symbol} not found"); 59 | None 60 | } 61 | } 62 | 63 | fn get_offset( 64 | symtab: &goblin::elf::Symtab, 65 | strtab: &goblin::strtab::Strtab, 66 | function_name: &str, 67 | ) -> Option { 68 | symtab 69 | .iter() 70 | .find(|sym| { 71 | if let Some(name_bytes) = strtab.get_at(sym.st_name) { 72 | if let Ok(name) = std::str::from_utf8(name_bytes.as_bytes()) { 73 | return name.trim_end_matches('\0') == function_name; 74 | } 75 | } 76 | false 77 | }) 78 | .map(|sym| sym.st_value as usize) 79 | } 80 | 81 | /// Get the address of a symbol in a module. Use "" for the main module. 82 | pub fn get_symbol_address(module_name: &str, function_name: &str) -> Option { 83 | trace!("Searching for function {function_name} in module {module_name}"); 84 | 85 | if let Some(module) = Module::new(module_name) { 86 | module.get_symbol_address(function_name) 87 | } else { 88 | warn!("Module {module_name} not found"); 89 | None 90 | } 91 | } 92 | 93 | /// Get the address of a module. Use "" for the main module. 94 | pub fn get_module_address(module_name: &str) -> Option { 95 | let main_module = Module::new(module_name); 96 | match main_module { 97 | Some(module) => Some(module.object.addr() as usize), 98 | _ => None, 99 | } 100 | } 101 | 102 | /// Get the address of the main module. 103 | pub fn get_main_module_address() -> Option { 104 | get_module_address("") 105 | } 106 | -------------------------------------------------------------------------------- /src/modules_windows.rs: -------------------------------------------------------------------------------- 1 | //! Module for handling modules on Windows systems. 2 | 3 | use log::*; 4 | 5 | use std::ptr::null_mut; 6 | use winapi::{ 7 | shared::minwindef::MAX_PATH, 8 | um::{libloaderapi::GetModuleHandleA, psapi::GetModuleBaseNameA, winnt::HANDLE}, 9 | }; 10 | 11 | /// Get the address of a symbol in a module. 12 | #[cfg(target_os = "windows")] 13 | pub fn get_symbol_address(module_name: &str, function_name: &str) -> Option { 14 | use std::{ffi::CString, ptr}; 15 | #[cfg(target_os = "windows")] 16 | use winapi::um::libloaderapi::{GetProcAddress, LoadLibraryA}; 17 | unsafe { 18 | let module_name: CString = CString::new(module_name).expect("Failed to create CString"); 19 | let mut module = LoadLibraryA(module_name.as_ptr()); 20 | 21 | if module_name.is_empty() { 22 | let mut mod_name: [u8; 260] = [0; MAX_PATH]; 23 | let own_process_handle = usize::MAX as HANDLE; 24 | let res = GetModuleBaseNameA( 25 | own_process_handle, 26 | null_mut(), 27 | mod_name.as_mut_ptr() as *mut i8, 28 | MAX_PATH as u32, 29 | ); 30 | if res == 0 { 31 | error!("Failed to GetModuleBaseNameA"); 32 | return None; 33 | } 34 | 35 | let mod_name_len = mod_name.iter().position(|&r| r == 0).unwrap(); 36 | let mod_name_str = std::str::from_utf8(&mod_name[0..mod_name_len]).unwrap(); 37 | 38 | let mod_name_str: CString = 39 | CString::new(mod_name_str).expect("Failed to create CString"); 40 | module = GetModuleHandleA(mod_name_str.as_ptr()); 41 | } 42 | 43 | if module == ptr::null_mut() { 44 | return None; 45 | } 46 | 47 | let function_name: CString = CString::new(function_name).expect("Failed to create CString"); 48 | 49 | let addr = GetProcAddress(module, function_name.as_ptr()) as usize; 50 | if addr == 0 { 51 | return None; 52 | } 53 | 54 | Some(addr as usize) 55 | } 56 | } 57 | 58 | /// Get the address of a module. 59 | #[cfg(target_os = "windows")] 60 | pub fn get_module_address(module_name: &str) -> Option { 61 | use crate::misc::get_address_range_for_module; 62 | use crate::modules::AddressRange; 63 | 64 | let module_range: Option = get_address_range_for_module(module_name); 65 | 66 | if module_range.is_some() { 67 | return Some(module_range.unwrap().start as usize); 68 | } 69 | 70 | None 71 | } 72 | 73 | /// Get the address of the main module. 74 | #[cfg(target_os = "windows")] 75 | pub fn get_main_module_address() -> Option { 76 | let mut mod_name: [u8; 260] = [0; MAX_PATH]; 77 | let own_process_handle = usize::MAX as HANDLE; 78 | unsafe { 79 | let res = GetModuleBaseNameA( 80 | own_process_handle, 81 | null_mut(), 82 | mod_name.as_mut_ptr() as *mut i8, 83 | MAX_PATH as u32, 84 | ); 85 | if res == 0 { 86 | error!("Failed to GetModuleBaseNameA"); 87 | return None; 88 | } 89 | 90 | let mod_name_len = mod_name.iter().position(|&r| r == 0).unwrap(); 91 | let mod_name_str = std::str::from_utf8(&mod_name[0..mod_name_len]).unwrap(); 92 | 93 | get_module_address(mod_name_str) 94 | } 95 | } 96 | 97 | /// Gets the entry point of the program from the main module. 98 | #[cfg(target_os = "windows")] 99 | pub fn get_program_entry_point() -> Option { 100 | use std::{ffi::CString, ptr::null_mut}; 101 | 102 | use winapi::{ 103 | shared::minwindef::MAX_PATH, 104 | um::{ 105 | libloaderapi::GetModuleHandleA, 106 | psapi::{GetModuleBaseNameA, MODULEINFO}, 107 | winnt::HANDLE, 108 | }, 109 | }; 110 | 111 | use crate::misc::get_module_info; 112 | 113 | let mut mod_name: [u8; 260] = [0; MAX_PATH]; 114 | let own_process_handle = usize::MAX as HANDLE; 115 | unsafe { 116 | let res = GetModuleBaseNameA( 117 | own_process_handle, 118 | null_mut(), 119 | mod_name.as_mut_ptr() as *mut i8, 120 | MAX_PATH as u32, 121 | ); 122 | if res == 0 { 123 | error!("Failed to GetModuleBaseNameA"); 124 | return None; 125 | } 126 | 127 | let mod_name_len = mod_name.iter().position(|&r| r == 0).unwrap(); 128 | let mod_name_str = std::str::from_utf8(&mod_name[0..mod_name_len]).unwrap(); 129 | 130 | let mod_name_str: CString = CString::new(mod_name_str).expect("Failed to create CString"); 131 | 132 | let module = GetModuleHandleA(mod_name_str.as_ptr()); 133 | 134 | let module_info: Option = get_module_info(module); 135 | module_info?; 136 | 137 | let module_info = module_info.unwrap(); 138 | 139 | Some(module_info.EntryPoint as usize) 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /src/nyx.rs: -------------------------------------------------------------------------------- 1 | //! Module containing Nyx-related definitions, constants, and functions. 2 | 3 | #[cfg(target_arch = "x86")] 4 | use core::arch::x86::__cpuid_count; 5 | 6 | #[cfg(target_arch = "x86_64")] 7 | use core::arch::x86_64::__cpuid_count; 8 | 9 | #[cfg(target_arch = "x86_64")] 10 | use std::arch::x86_64::CpuidResult; 11 | 12 | #[cfg(target_arch = "x86")] 13 | use std::arch::x86::CpuidResult; 14 | 15 | #[cfg(all(feature = "pt", feature = "kafl"))] 16 | use std::arch::asm; 17 | 18 | use crate::modules; 19 | use log::*; 20 | use std::ffi::CString; 21 | 22 | const HYPERTRASH_HYPERCALL_MASK: u32 = 0xAA000000; 23 | 24 | #[cfg(all(feature = "pt", feature = "kafl"))] 25 | const HYPERCALL_RAX_PT: u32 = 0x01f; 26 | 27 | #[cfg(not(feature = "pt"))] 28 | const HYPERCALL_RAX_VMWARE: u32 = 0x8080801f; 29 | const CPU_ID_VENDOR: u32 = 0x80000004; 30 | 31 | /// Magic bytes that identify Nyx-QEMU 32 | pub const NYX_HOST_MAGIC: u32 = 0x4878794e; 33 | /// Magic bytes that identify Nyx agents 34 | pub const NYX_AGENT_MAGIC: u32 = 0x4178794e; 35 | 36 | /// Expected Nyx host version 37 | pub const NYX_HOST_VERSION: u32 = 2; 38 | /// Nyx agent version sent to the host 39 | pub const NYX_AGENT_VERSION: u32 = 1; 40 | 41 | #[cfg(not(feature = "pt"))] 42 | const VMWARE_PORT: u32 = 0x5658; 43 | 44 | /// Defines the maximum payload size 45 | pub const PAYLOAD_MAX_SIZE: u32 = 1024 * 1024; 46 | 47 | /// Implements the `log::Log` trait, providing logging functionality using the `log` crate. 48 | /// It formats log records and sends them to Nyx via `hprintf`. 49 | #[repr(packed)] 50 | pub struct NyxLogger; 51 | 52 | impl log::Log for NyxLogger { 53 | fn enabled(&self, metadata: &Metadata) -> bool { 54 | metadata.level() <= log::max_level() 55 | } 56 | 57 | fn log(&self, record: &Record) { 58 | if self.enabled(record.metadata()) { 59 | hprintf(format!("{} - {} \n", record.level(), record.args())); 60 | } 61 | } 62 | 63 | fn flush(&self) {} 64 | } 65 | 66 | /// Holds the size and a pointer to a payload. 67 | #[repr(C)] 68 | pub struct KAFLPayload { 69 | pub size: u32, 70 | pub data: *const u8, 71 | } 72 | 73 | impl KAFLPayload { 74 | /// Creates a `KAFLPayload` reference from a raw pointer 75 | /// # Safety 76 | /// This function is unsafe because it assumes the pointer is valid and properly aligned. 77 | pub unsafe fn from_raw(raw_ptr: *const usize) -> KAFLPayload { 78 | let size = unsafe { std::ptr::read(*raw_ptr as *const u32) }; 79 | let data: *const u8 = (*raw_ptr + std::mem::size_of::()) as *const u8; 80 | 81 | KAFLPayload { size, data } 82 | } 83 | } 84 | 85 | // #[repr(C)] 86 | // pub struct KAFLRanges { 87 | // pub ip: [u64; 4], 88 | // pub size: [u64; 4], 89 | // pub enabled: [u8; 4], 90 | // } 91 | 92 | /// Nyx host configuration. 93 | #[derive(Default)] 94 | #[repr(packed)] 95 | pub struct HostConfig { 96 | pub host_magic: u32, 97 | pub host_version: u32, 98 | pub bitmap_size: u32, 99 | pub ijon_bitmap_size: u32, 100 | pub payload_buffer_size: u32, 101 | pub worker_id: u32, 102 | } 103 | 104 | /// Nyx agent configuration. 105 | #[derive(Default)] 106 | #[repr(packed)] 107 | pub struct AgentConfig { 108 | pub agent_magic: u32, 109 | pub agent_version: u32, 110 | pub agent_timeout_detection: u8, 111 | pub agent_tracing: u8, 112 | pub agent_ijon_tracing: u8, 113 | pub agent_non_reload_mode: u8, 114 | pub trace_buffer_vaddr: u64, 115 | pub ijon_trace_buffer_vaddr: u64, 116 | pub coverage_bitmap_size: u32, 117 | pub input_buffer_size: u32, 118 | pub dump_payloads: u8, 119 | } 120 | 121 | /// Represents a dump file which can be send to the Nyx host. 122 | #[repr(C)] 123 | pub struct DumpFile { 124 | pub file_name_str_ptr: u64, 125 | pub data_ptr: u64, 126 | pub bytes: u64, 127 | pub append: u8, 128 | } 129 | 130 | /// Nyx CPU types. 131 | pub enum NxyCpuType { 132 | Unknown = 0, 133 | NyxCpuV1 = 1, /* Nyx CPU used by KVM-PT */ 134 | NyxCpuV2 = 2, /* Nyx CPU used by vanilla KVM + VMWare backdoor */ 135 | } 136 | 137 | /// Nyx hypercalls to communicate with the Nyx host 138 | #[repr(u32)] 139 | #[derive(Debug)] 140 | pub enum KAFLHypercalls { 141 | Acquire = 0, 142 | GetPayload = 1, 143 | /* deprecated */ 144 | GetProgram = 2, 145 | /* deprecated */ 146 | GetArgv = 3, 147 | 148 | Release = 4, 149 | SubmitCR3 = 5, 150 | SubmitPanic = 6, 151 | 152 | /* deprecated */ 153 | SubmitKASAN = 7, 154 | Panic = 8, 155 | /* deprecated */ 156 | KASAN = 9, 157 | Lock = 10, 158 | 159 | /* deprecated */ 160 | Info = 11, 161 | 162 | NextPayload = 12, 163 | Printf = 13, 164 | /* deprecated */ 165 | PrintkAddr = 14, 166 | /* deprecated */ 167 | Printk = 15, 168 | 169 | /* user space only hypercalls */ 170 | UserRangeAdvise = 16, 171 | UserSubmitMode = 17, 172 | UserFastAcquire = 18, 173 | 174 | /* 19 is already used for exit reason KVM_EXIT_KAFL_TOPA_MAIN_FULL */ 175 | UserAbort = 20, 176 | RangeSubmit = 29, 177 | ReqStreamData = 30, 178 | PanicExtended = 32, 179 | 180 | CreateTmpSnapshot = 33, 181 | /* hypercall for debugging / development purposes */ 182 | DebugTmpSnapshot = 34, 183 | GetHostConfig = 35, 184 | SetAgentConfig = 36, 185 | DumpFile = 37, 186 | ReqStreamDataBulk = 38, 187 | PersistPagePastSnapshot = 39, 188 | } 189 | 190 | #[repr(u32)] 191 | pub enum KAFLHypertrashCalls { 192 | Prepare = HYPERTRASH_HYPERCALL_MASK, 193 | Config = (1u32 | HYPERTRASH_HYPERCALL_MASK), 194 | Acquire = (2u32 | HYPERTRASH_HYPERCALL_MASK), 195 | Release = (3u32 | HYPERTRASH_HYPERCALL_MASK), 196 | HPrintf = (4u32 | HYPERTRASH_HYPERCALL_MASK), 197 | } 198 | 199 | /// Represents different modes (64-bit, 32-bit, 16-bit) available in Nyx. 200 | #[repr(u32)] 201 | pub enum KAFLMode { 202 | Bits64 = 0, 203 | Bits32 = 1, 204 | Bits16 = 2, 205 | } 206 | 207 | /// Explicitly tell the host if the target is 32 or 64 bit code. 208 | #[cfg(target_arch = "x86_64")] 209 | pub fn submit_mode() { 210 | hypercall(KAFLHypercalls::UserSubmitMode, KAFLMode::Bits64 as usize); 211 | } 212 | 213 | #[cfg(target_arch = "x86")] 214 | pub fn submit_mode() { 215 | hypercall(KAFLHypercalls::UserSubmitMode, KAFLMode::Bits32 as usize); 216 | } 217 | 218 | /// Like printf, but using the KAFL_HYPERCALL_PRINTF as printing backend. 219 | pub fn hprintf(data: String) { 220 | let c_string: &'static CString = Box::leak(Box::new( 221 | CString::new(data).expect("Failed to create CString"), 222 | )); 223 | hypercall(KAFLHypercalls::Printf, c_string.as_ptr() as usize); 224 | } 225 | 226 | /// Signal a fatal error to Nyx. 227 | pub fn habort(data: String) { 228 | hypercall(KAFLHypercalls::UserAbort, data.as_ptr() as usize); 229 | } 230 | 231 | /// Tell Nyx where to write the payload by providing it the payload’s guest address. 232 | pub fn get_payload(address: usize) { 233 | hypercall(KAFLHypercalls::GetPayload, address); 234 | } 235 | 236 | /// Mark the start and stop of a single execution. 237 | pub fn user_acquire() { 238 | hypercall(KAFLHypercalls::Acquire, 0usize); 239 | } 240 | 241 | /// Signal that the execution is done with no errors. 242 | pub fn release() { 243 | hypercall(KAFLHypercalls::Release, 0usize); 244 | } 245 | 246 | /// Trigger the actual write of the next payload into the previously registered buffer. 247 | pub fn next_payload() { 248 | hypercall(KAFLHypercalls::NextPayload, 0usize); 249 | } 250 | 251 | /// Generate a VM pre-snapshot for the fuzzer. 252 | pub fn lock() { 253 | hypercall(KAFLHypercalls::Lock, 0usize); 254 | } 255 | 256 | /// Initialize PT (Page Table) tracing ranges and notify the hypervisor about the address ranges to be traced. 257 | #[inline(never)] 258 | pub fn send_pt_range_to_hypervisor(range: modules::AddressRange) { 259 | // prevent compiler optimizations 260 | core::hint::black_box(&range); 261 | let range_box = Box::new(range); 262 | let range_ptr = Box::into_raw(range_box) as usize; 263 | 264 | hypercall(KAFLHypercalls::RangeSubmit, range_ptr); 265 | } 266 | 267 | /// Sends binary buffers that will be stored as files in $WORK_DIR/dump/. 268 | pub fn dump_payload(buf: Vec, filename: String) { 269 | let dump_file = DumpFile { 270 | file_name_str_ptr: filename.as_ptr() as u64, 271 | data_ptr: buf.as_ptr() as u64, 272 | bytes: buf.len() as u64, 273 | append: 0, 274 | }; 275 | 276 | hypercall( 277 | KAFLHypercalls::DumpFile, 278 | std::ptr::addr_of!(dump_file) as usize, 279 | ); 280 | } 281 | 282 | /// Like KAFLHypercalls::Panic but with additional data 283 | /// Use libnyx::NyxProcess aux_string() to receive the string on the host side 284 | pub fn panic_extended(data: String) { 285 | let c_string: &'static CString = Box::leak(Box::new( 286 | CString::new(data).expect("Failed to create CString"), 287 | )); 288 | hypercall(KAFLHypercalls::PanicExtended, c_string.as_ptr() as usize); 289 | } 290 | 291 | /// Initialize the Nyx agent, sets up panic handlers, and sets up the NyxLogger based on the verbosity level specified. 292 | pub fn agent_init(verbose: bool) { 293 | // Register panic handler in case something crashes in the harness (only PT and kafl) 294 | #[cfg(all(feature = "pt", feature = "kafl"))] 295 | std::panic::set_hook(Box::new(|panic_info| { 296 | hprintf(format!("Panic in harness: {}", panic_info)); 297 | habort(format!("Panic in harness: {}", panic_info)); 298 | 299 | loop {} 300 | })); 301 | 302 | // Initial handshake 303 | hypercall(KAFLHypercalls::Acquire, 0usize); 304 | hypercall(KAFLHypercalls::Release, 0usize); 305 | 306 | let mut host_config = HostConfig { 307 | ..Default::default() 308 | }; 309 | 310 | hypercall( 311 | KAFLHypercalls::GetHostConfig, 312 | std::ptr::addr_of_mut!(host_config) as usize, 313 | ); 314 | 315 | if host_config.host_magic != NYX_HOST_MAGIC { 316 | habort(format!( 317 | "HOST_MAGIC mismatch! {:016x} != {:016x}", 318 | unsafe { std::ptr::read_unaligned(std::ptr::addr_of!(host_config.host_magic)) }, 319 | NYX_HOST_MAGIC 320 | )); 321 | } 322 | 323 | if unsafe { std::ptr::read_unaligned(std::ptr::addr_of!(host_config.host_version)) } 324 | != NYX_HOST_VERSION 325 | { 326 | habort(format!( 327 | "HOST_VERSION mismatch! {:016x} != {:016x}", 328 | unsafe { std::ptr::read_unaligned(std::ptr::addr_of!(host_config.host_version)) }, 329 | NYX_HOST_VERSION 330 | )); 331 | } 332 | 333 | if host_config.payload_buffer_size > PAYLOAD_MAX_SIZE { 334 | habort(format!( 335 | "Payload size to large! {:016x} > {:016x}", 336 | unsafe { 337 | std::ptr::read_unaligned(std::ptr::addr_of!(host_config.payload_buffer_size)) 338 | }, 339 | PAYLOAD_MAX_SIZE 340 | )); 341 | } 342 | 343 | let mut agent_config = AgentConfig { 344 | agent_magic: NYX_AGENT_MAGIC, 345 | agent_version: NYX_AGENT_VERSION, 346 | coverage_bitmap_size: host_config.bitmap_size, 347 | ..Default::default() 348 | }; 349 | 350 | hypercall( 351 | KAFLHypercalls::SetAgentConfig, 352 | std::ptr::addr_of_mut!(agent_config.agent_magic) as usize, 353 | ); 354 | 355 | hypercall(KAFLHypercalls::SubmitCR3, 0usize); 356 | submit_mode(); 357 | 358 | // Initialize NyxLogger 359 | // hprints before agent initialization would result in segfault 360 | if verbose { 361 | let _ = log::set_boxed_logger(Box::new(NyxLogger)) 362 | .map(|()| log::set_max_level(LevelFilter::Trace)); 363 | } else { 364 | let _ = log::set_boxed_logger(Box::new(NyxLogger)) 365 | .map(|()| log::set_max_level(LevelFilter::Warn)); 366 | } 367 | 368 | trace!("Agent initialized"); 369 | } 370 | 371 | /// Send a hypercall to the host. 372 | #[cfg(not(feature = "kafl"))] 373 | pub fn hypercall(hypercall: KAFLHypercalls, argument: usize) -> usize { 374 | warn!("Would do hypercall, but no kAFL Kernel: {hypercall:?} Arg: {argument:x?}"); 375 | 0 376 | } 377 | 378 | #[inline(never)] 379 | #[cfg(all(target_arch = "x86_64", feature = "pt", feature = "kafl"))] 380 | pub fn hypercall(hypercall: KAFLHypercalls, argument: usize) -> usize { 381 | let result: usize = 0; 382 | unsafe { 383 | asm!( 384 | "mov rax, {HYPERCALL_RAX:r}", 385 | "mov rbx, {hypercall:r}", 386 | "mov rcx, {argument:r}", 387 | "vmcall;", 388 | "mov {result}, rax", 389 | HYPERCALL_RAX = in(reg) HYPERCALL_RAX_PT, 390 | hypercall = in(reg) hypercall as u32, 391 | argument = in(reg) argument, 392 | result = out(reg) _, 393 | ) 394 | } 395 | result 396 | } 397 | 398 | #[inline(never)] 399 | #[cfg(all(target_arch = "x86_64", not(feature = "pt"), feature = "kafl"))] 400 | pub fn hypercall(hypercall: KAFLHypercalls, argument: usize) -> usize { 401 | let result: usize = 0; 402 | unsafe { 403 | asm!( 404 | "mov rax, {HYPERCALL_RAX:r}", 405 | "mov rbx, {hypercall:r}", 406 | "mov rcx, {argument:r}", 407 | "mov dx, {VMWARE_PORT}", 408 | "out dx, rax", 409 | "mov {result}, rax", 410 | HYPERCALL_RAX = in(reg) HYPERCALL_RAX_VMWARE, 411 | hypercall = in(reg) hypercall as u32, 412 | argument = in(reg) argument, 413 | VMWARE_PORT = in(reg) VMWARE_PORT, 414 | result = out(reg) _, 415 | ) 416 | } 417 | result 418 | } 419 | 420 | #[inline(never)] 421 | #[cfg(all(target_arch = "x86", feature = "pt", feature = "kafl"))] 422 | pub fn hypercall(hypercall: KAFLHypercalls, argument: usize) -> usize { 423 | let result: usize = 0; 424 | unsafe { 425 | asm!( 426 | "mov eax, {HYPERCALL_RAX}", 427 | "mov ebx, {hypercall}", 428 | "mov ecx, {argument}", 429 | "vmcall;", 430 | "mov {result}, eax", 431 | HYPERCALL_RAX = in(reg) HYPERCALL_RAX_PT, 432 | hypercall = in(reg) hypercall as u32, 433 | argument = in(reg) argument, 434 | result = out(reg) _, 435 | ) 436 | } 437 | result 438 | } 439 | 440 | #[inline(never)] 441 | #[cfg(all(target_arch = "x86", not(feature = "pt"), feature = "kafl"))] 442 | pub fn hypercall(hypercall: KAFLHypercalls, argument: usize) -> usize { 443 | let result: usize = 0; 444 | unsafe { 445 | asm!( 446 | "mov eax, {HYPERCALL_RAX:r}", 447 | "mov ebx, {hypercall:r}", 448 | "mov ecx, {argument:r}", 449 | "mov dx, {VMWARE_PORT}", 450 | "out dx, eax", 451 | "mov {result}, eax", 452 | HYPERCALL_RAX = in(reg) HYPERCALL_RAX_VMWARE, 453 | hypercall = in(reg) hypercall as u32, 454 | argument = in(reg) argument, 455 | VMWARE_PORT = in(reg) VMWARE_PORT, 456 | result = out(reg) _, 457 | ) 458 | } 459 | result 460 | } 461 | 462 | /// Check if the current CPU is a Nyx vCPU. 463 | pub fn is_nyx_vcpu() -> bool { 464 | unsafe { 465 | let result = __cpuid_count(CPU_ID_VENDOR, 0); 466 | let eax: u32 = result.eax; 467 | let ebx = result.ebx; 468 | 469 | eax == 0x2058594e && ebx == 0x55504376 // = "NYX vCPU" in hex 470 | } 471 | } 472 | 473 | /// Get the type of the Nyx CPU. 474 | pub fn get_nyx_cpu_type() -> NxyCpuType { 475 | unsafe { 476 | let result: CpuidResult = __cpuid_count(CPU_ID_VENDOR, 0); 477 | let eax: u32 = result.eax; 478 | let ebx: u32 = result.ebx; 479 | let ecx: u32 = result.ecx; 480 | let edx: u32 = result.edx; 481 | 482 | if eax != 0x2058594e || ebx != 0x55504376 { 483 | // = "NYX vCPU" in hex 484 | NxyCpuType::Unknown 485 | } else if ecx == 0x4f4e2820 && edx == 0x2954502d { 486 | // = " (NO-PT)" in hex 487 | NxyCpuType::NyxCpuV1 488 | } else { 489 | NxyCpuType::NyxCpuV2 490 | } 491 | } 492 | } 493 | --------------------------------------------------------------------------------