├── .gitignore ├── .gitmodules ├── Cargo.toml ├── LICENSE.txt ├── dll ├── Cargo.toml ├── build.rs ├── c_src │ └── c_entry.c └── src │ ├── ffi.rs │ ├── lib.rs │ ├── pipe.rs │ └── windows.rs ├── exe ├── Cargo.toml └── src │ └── main.rs ├── img.png ├── img_1.png ├── rdll-rs.cna ├── readme.md ├── rust-toolchain.toml └── xtask ├── Cargo.toml └── src └── main.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /build-deps/pe_to_shellcode/ 3 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "build-deps/pe_to_shellcode"] 2 | path = build-deps/pe_to_shellcode 3 | url = https://github.com/hasherezade/pe_to_shellcode 4 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = ["dll", "exe", "xtask"] 3 | resolver = "3" 4 | 5 | [profile.release] 6 | strip = "symbols" 7 | panic = "abort" 8 | opt-level = "z" 9 | codegen-units = 1 10 | lto = true 11 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2025 Steve S. 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | 204 | To the maximum extent possible, the contents of this repository may also be used under MIT licensing. 205 | 206 | MIT License 207 | 208 | Copyright (c) 2025 Steve S. 209 | 210 | Permission is hereby granted, free of charge, to any person obtaining a copy 211 | of this software and associated documentation files (the "Software"), to deal 212 | in the Software without restriction, including without limitation the rights 213 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 214 | copies of the Software, and to permit persons to whom the Software is 215 | furnished to do so, subject to the following conditions: 216 | 217 | The above copyright notice and this permission notice shall be included in all 218 | copies or substantial portions of the Software. 219 | 220 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 221 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 222 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 223 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 224 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 225 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 226 | SOFTWARE. -------------------------------------------------------------------------------- /dll/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "dll-rs" 3 | version = "0.1.0" 4 | edition = "2024" 5 | 6 | [lib] 7 | name = "dll_rs" 8 | crate-type = ["cdylib", "rlib"] 9 | path = "src/lib.rs" 10 | 11 | [build-dependencies] 12 | cc = "1.2.22" -------------------------------------------------------------------------------- /dll/build.rs: -------------------------------------------------------------------------------- 1 | use std::fs; 2 | 3 | fn main() { 4 | let c_src_dir = "c_src"; 5 | let mut c_files = Vec::new(); 6 | 7 | // Read the c_src directory 8 | if let Ok(entries) = fs::read_dir(c_src_dir) { 9 | for entry in entries { 10 | if let Ok(entry) = entry { 11 | let path = entry.path(); 12 | // Check if it's a file and has a .c extension 13 | if path.is_file() { 14 | if let Some(extension) = path.extension() { 15 | if extension == "c" { 16 | #[cfg(debug_assertions)] 17 | println!("cargo:warning=Found C file: {}", path.display()); 18 | 19 | c_files.push(path); 20 | } 21 | } 22 | } 23 | } 24 | } 25 | } else { 26 | // Handle the case where c_src directory might not exist, 27 | // though in the temaplte it's expected. 28 | eprintln!( 29 | "cargo:warning=Directory {} not found or could not be read.", 30 | c_src_dir 31 | ); 32 | } 33 | 34 | if !c_files.is_empty() { 35 | cc::Build::new() 36 | .files(c_files) // Use .files() for multiple files 37 | .compile("c_code"); // The name of the static library to be generated 38 | } else { 39 | // If no C files are found, print a warning. 40 | println!( 41 | "cargo:warning=No .c files found in {} directory. Skipping C code compilation.", 42 | c_src_dir 43 | ); 44 | } 45 | 46 | // Ensure Cargo reruns the build script if any file in c_src changes. 47 | // This is important so that adding/removing/modifying C files triggers a recompile. 48 | println!("cargo:rerun-if-changed={}", c_src_dir); 49 | } 50 | -------------------------------------------------------------------------------- /dll/c_src/c_entry.c: -------------------------------------------------------------------------------- 1 | #include 2 | void c_entry(){ 3 | CHAR msg[] = "Hello from FFI C code!"; 4 | MessageBoxA(NULL, msg, msg, 0); 5 | } -------------------------------------------------------------------------------- /dll/src/ffi.rs: -------------------------------------------------------------------------------- 1 | // Rust definitions for C functions 2 | unsafe extern "C" { 3 | /// Rust definition of the c_entry C function. 4 | pub fn c_entry(); 5 | } 6 | -------------------------------------------------------------------------------- /dll/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![no_main] 2 | #![allow(dead_code)] 3 | #![crate_type = "cdylib"] 4 | 5 | mod ffi; 6 | mod pipe; 7 | mod windows; 8 | 9 | use crate::ffi::*; 10 | use crate::pipe::*; 11 | 12 | use std::os::raw::c_void; 13 | use windows::*; 14 | 15 | /// Entry point for the custom Rust-based DLL. 16 | /// 17 | /// This function serves as the main entry point for invoking functionality 18 | /// via the Reflective DLL template. As examples, it performs the following operations: 19 | /// 20 | /// 1. Displays a message box with a greeting message using the `MessageBoxA` Windows API call. 21 | /// 2. Delegates execution to an external C entry point function (`c_entry`) for further processing. 22 | /// 3. Outputs a message using a named pipe or standard output, depending on the build configuration. 23 | #[unsafe(no_mangle)] 24 | #[allow(named_asm_labels)] 25 | #[allow(non_snake_case, unused_variables)] 26 | pub fn dll_main() { 27 | let msg = b"Hello from Rust Reflective DLL!\0"; 28 | unsafe { 29 | MessageBoxA( 30 | std::ptr::null_mut(), 31 | msg.as_ptr() as LPVOID, 32 | msg.as_ptr() as LPVOID, 33 | 0, 34 | ); 35 | } 36 | 37 | // Call the C entry point 38 | unsafe { 39 | c_entry(); 40 | } 41 | 42 | // Write output to the pipe 43 | write_output("Hello from the Rust Reflective DLL via output!"); 44 | } 45 | 46 | /// Retrieves the instruction pointer (IP) on the `x86_64` architecture. 47 | /// 48 | /// This function obtains the current value of the instruction pointer (RIP register) 49 | /// using inline assembly. It can be used to determine the memory address of the 50 | /// currently executing instruction, which is helpful for low-level debugging, 51 | /// locating code regions, or working with reflective APIs. 52 | /// 53 | /// # Returns 54 | /// A `usize` representing the value of the instruction pointer (RIP). 55 | /// 56 | /// # Safety 57 | /// - This function uses inline assembly, which is inherently unsafe. 58 | #[cfg(target_arch = "x86_64")] 59 | unsafe fn get_ip() -> usize { 60 | let rip: usize; 61 | unsafe { std::arch::asm!("lea {}, [rip]", out(reg) rip) }; 62 | rip 63 | } 64 | 65 | /// Retrieves the instruction pointer (IP) on the `x86` architecture. 66 | /// 67 | /// This function obtains the current value of the instruction pointer (EIP register) 68 | /// using inline assembly. It is useful for determining the memory address of the 69 | /// next executing instruction, which aids in low-level debugging, reflective APIs, 70 | /// and locating code regions. 71 | /// 72 | /// # Returns 73 | /// A `usize` representing the value of the instruction pointer (EIP). 74 | /// 75 | /// # Safety 76 | /// - This function uses inline assembly, which is inherently unsafe. 77 | #[cfg(target_arch = "x86")] 78 | unsafe fn get_ip() -> usize { 79 | let eip: usize; 80 | unsafe { 81 | std::arch::asm!( 82 | "call 1f", 83 | "1: pop {}", 84 | out(reg) eip, 85 | ); 86 | } 87 | 88 | eip 89 | } 90 | 91 | #[unsafe(no_mangle)] 92 | #[allow(named_asm_labels)] 93 | #[allow(non_snake_case, unused_variables, unreachable_patterns)] 94 | pub unsafe extern "system" fn DllMain( 95 | dll_module: HANDLE, 96 | call_reason: u32, 97 | reserved: *mut c_void, 98 | ) -> BOOL { 99 | match call_reason { 100 | DLL_PROCESS_ATTACH => { 101 | // Code to run when the DLL is loaded into a process 102 | // Initialize resources, etc. 103 | dll_main(); 104 | } 105 | DLL_THREAD_ATTACH => { 106 | // Code to run when a new thread is created in the process 107 | } 108 | DLL_THREAD_DETACH => { 109 | // Code to run when a thread exits cleanly 110 | } 111 | DLL_PROCESS_DETACH => { 112 | // Code to run when the DLL is unloaded from the process 113 | // Clean up resources, etc. 114 | } 115 | _ => {} 116 | } 117 | return 1; 118 | } 119 | -------------------------------------------------------------------------------- /dll/src/pipe.rs: -------------------------------------------------------------------------------- 1 | #![allow(unused_imports)] 2 | use crate::windows::*; 3 | use std::ffi::CString; 4 | use std::ptr::null_mut; 5 | 6 | pub static PIPE_NAME: &[u8; 42] = b"\\\\.\\pipe\\RDLL_PIPE_NAME_NO_CHANGE_PLS\0\0\0\0\0"; 7 | 8 | /// Writes output data to a named pipe for external consumption in release builds. 9 | /// 10 | /// This function creates a named pipe, waits for a connection, and writes the provided 11 | /// data to the pipe. It is useful for transmitting output from a reflective DLL 12 | /// or other processes to another application via inter-process communication (IPC). 13 | /// 14 | /// # Parameters 15 | /// - `data`: A string slice containing the data to be written to the named pipe. 16 | /// 17 | /// # Behavior 18 | /// 1. Creates a named pipe with specific access and buffer configurations. 19 | /// 2. Waits for a client to connect to the pipe. 20 | /// 3. Writes the provided data to the pipe once a connection is established. 21 | /// 4. Cleans up resources and closes the pipe upon completion. 22 | /// 23 | /// # Safety 24 | /// - This function uses unsafe blocks due to its interaction with the Windows API, 25 | /// including raw pointers and function calls. 26 | /// - Proper error checking is performed, but misuse or unexpected system behavior could 27 | /// result in crashes or undefined behavior. 28 | #[cfg(not(debug_assertions))] 29 | pub(crate) fn write_output(data: &str) { 30 | let pipe_name = String::from_utf8_lossy(&*PIPE_NAME); 31 | let message = data.as_bytes(); 32 | let mut bytes_written: u32 = 0; 33 | 34 | let h_pipe = unsafe { 35 | CreateNamedPipeA( 36 | pipe_name.as_ptr() as *const u8, 37 | PIPE_ACCESS_DUPLEX, 38 | PIPE_TYPE_BYTE, 39 | 1, 40 | 4096, 41 | 4096, 42 | 0, 43 | std::ptr::null_mut(), 44 | ) 45 | }; 46 | 47 | if h_pipe == INVALID_HANDLE_VALUE { 48 | let err = unsafe { GetLastError() }; 49 | dbg!("CreateNamedPipe failed: {}", err); 50 | return; 51 | } 52 | 53 | dbg!( 54 | "[*] Waiting for Beacon connection on {}", 55 | pipe_name.to_string() 56 | ); 57 | 58 | let connected = unsafe { ConnectNamedPipe(h_pipe, std::ptr::null_mut()) }; 59 | if connected == 0 { 60 | let err = unsafe { GetLastError() }; 61 | if err != ERROR_PIPE_CONNECTED { 62 | dbg!("ConnectNamedPipe failed: {}", err); 63 | unsafe { CloseHandle(h_pipe) }; 64 | return; 65 | } 66 | } 67 | 68 | dbg!("[+] Beacon connected! Sending message..."); 69 | 70 | let success = unsafe { 71 | WriteFile( 72 | h_pipe, 73 | message.as_ptr(), 74 | message.len() as u32, 75 | &mut bytes_written, 76 | std::ptr::null_mut(), 77 | ) 78 | }; 79 | 80 | if success == 0 { 81 | let err = unsafe { GetLastError() }; 82 | dbg!("WriteFile failed: {}", err); 83 | unsafe { CloseHandle(h_pipe) }; 84 | return; 85 | } 86 | 87 | unsafe { 88 | FlushFileBuffers(h_pipe); 89 | CloseHandle(h_pipe); 90 | } 91 | } 92 | 93 | /// Debug implementation of write_output. 94 | #[cfg(debug_assertions)] 95 | pub(crate) fn write_output(data: &str) { 96 | println!("{}", data); 97 | } 98 | -------------------------------------------------------------------------------- /dll/src/windows.rs: -------------------------------------------------------------------------------- 1 | // Basic Windows type aliases using Rust primitives 2 | pub(crate) type DWORD = u32; 3 | pub(crate) type BOOL = i32; // Windows BOOL is typically defined as int 4 | pub(crate) type HANDLE = *mut std::ffi::c_void; // Treat handles as opaque pointers 5 | pub(crate) type LPVOID = *mut std::ffi::c_void; 6 | 7 | pub(crate) const PIPE_ACCESS_DUPLEX: u32 = 0x00000003; 8 | pub(crate) const PIPE_TYPE_BYTE: u32 = 0x00000000; 9 | pub(crate) const INVALID_HANDLE_VALUE: HANDLE = -1isize as HANDLE; 10 | pub(crate) const ERROR_PIPE_CONNECTED: u32 = 535; 11 | // Constants for DllMain call_reason 12 | pub(crate) const DLL_PROCESS_ATTACH: DWORD = 1; 13 | pub(crate) const DLL_PROCESS_DETACH: DWORD = 0; 14 | pub(crate) const DLL_THREAD_ATTACH: DWORD = 2; 15 | pub(crate) const DLL_THREAD_DETACH: DWORD = 3; 16 | 17 | #[allow(non_snake_case)] 18 | #[link(name = "kernel32")] 19 | unsafe extern "system" { 20 | pub(crate) fn WinExec(lpCmdLine: LPVOID, uCmdShow: DWORD) -> DWORD; 21 | pub(crate) fn GetModuleHandleA(lpModuleName: LPVOID) -> HANDLE; 22 | pub(crate) fn GetProcAddress(hmodule: HANDLE, lpProcName: LPVOID) -> LPVOID; 23 | pub(crate) fn GetLastError() -> u32; 24 | pub(crate) fn CreateNamedPipeA( 25 | lpName: *const u8, // LPCSTR 26 | dwOpenMode: u32, // DWORD 27 | dwPipeMode: u32, // DWORD 28 | nMaxInstances: u32, // DWORD 29 | nOutBufferSize: u32, // DWORD 30 | nInBufferSize: u32, // DWORD 31 | nDefaultTimeOut: u32, // DWORD 32 | lpSecurityAttributes: *const core::ffi::c_void, // opaque pointer, fix in future...maybe 33 | ) -> HANDLE; 34 | 35 | pub(crate) fn ConnectNamedPipe( 36 | hNamedPipe: HANDLE, 37 | lpOverLapped: *const core::ffi::c_void, // opaque pointer, fix in future...maybe 38 | ) -> BOOL; 39 | 40 | pub(crate) fn CloseHandle(handle: HANDLE) -> BOOL; 41 | 42 | pub(crate) fn WriteFile( 43 | hFile: HANDLE, 44 | lpBuffer: *const u8, 45 | nNumberOfBytesToWrite: u32, 46 | lpNumberOfBytesWritten: *mut u32, 47 | lpOverlapped: *const core::ffi::c_void, 48 | ) -> BOOL; 49 | 50 | pub(crate) fn FlushFileBuffers(handle: HANDLE) -> BOOL; 51 | } 52 | 53 | #[allow(non_snake_case)] 54 | #[link(name = "user32")] 55 | unsafe extern "system" { 56 | pub fn MessageBoxA(hWnd: HANDLE, lpText: LPVOID, lpCaption: LPVOID, uType: DWORD); 57 | } 58 | 59 | #[repr(C)] 60 | pub(crate) struct ImageDosHeader { 61 | pub(crate) e_magic: u16, 62 | e_cblp: u16, 63 | e_cp: u16, 64 | e_crlc: u16, 65 | e_cparhdr: u16, 66 | e_minalloc: u16, 67 | e_maxalloc: u16, 68 | e_ss: u16, 69 | e_sp: u16, 70 | e_csum: u16, 71 | e_ip: u16, 72 | e_cs: u16, 73 | e_lfarlc: u16, 74 | e_ovno: u16, 75 | e_res: [u16; 4], 76 | e_oemid: u16, 77 | e_oeminfo: u16, 78 | e_res2: [u16; 10], 79 | pub(crate) e_lfanew: i32, 80 | } 81 | 82 | #[repr(C)] 83 | pub(crate) struct ImageNtHeaders { 84 | pub(crate) signature: u32, 85 | } 86 | 87 | pub(crate) const IMAGE_DOS_SIGNATURE: u16 = 0x5A4D; // 'MZ' 88 | pub(crate) const IMAGE_NT_SIGNATURE: u32 = 0x00004550; // 'PE\0\0' 89 | -------------------------------------------------------------------------------- /exe/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "debug-executable" 3 | version = "0.1.0" 4 | edition = "2024" 5 | 6 | [dependencies] 7 | dll-rs = { path = "../dll"} -------------------------------------------------------------------------------- /exe/src/main.rs: -------------------------------------------------------------------------------- 1 | #![allow(unused_imports)] 2 | use dll_rs::dll_main; 3 | 4 | /// Executable wrapper for functionality in dll_rs 5 | fn main() { 6 | #[cfg(not(debug_assertions))] 7 | println!("[!] RELEASE DEBUGGING EXECUTABLE [!]"); 8 | 9 | dll_main(); 10 | } 11 | -------------------------------------------------------------------------------- /img.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/0xTriboulet/rdll-rs/44c077c4d38fa12399f15f43c51d804815287b87/img.png -------------------------------------------------------------------------------- /img_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/0xTriboulet/rdll-rs/44c077c4d38fa12399f15f43c51d804815287b87/img_1.png -------------------------------------------------------------------------------- /rdll-rs.cna: -------------------------------------------------------------------------------- 1 | # bpsinject($1, 1234, x64, "[System.Diagnostics.Process]::GetCurrentProcess()"); 2 | # powerpick $pipe = New-Object IO.Pipes.NamedPipeClientStream('.', 'macrohard_updates', [IO.Pipes.PipeDirection]::In); $pipe.Connect(10000); $reader = New-Object IO.StreamReader($pipe); while(($line = $reader.ReadLine()) -ne $null){Write-Output $line}; $reader.Close(); $pipe.Close() 3 | 4 | import beacon.CommandBuilder; 5 | 6 | global('$pipe_wait $pipe_name_generic $pipe_stomp_me_name'); 7 | $pipe_name_generic = "macrohard_updates"; # Change the pipe name an reload the CNA for 'opsec', 28-bytes MAX 8 | $pipe_wait = 30000; # Custom timeout 9 | $pipe_stomp_me_name = "RDLL_PIPE_NAME_NO_CHANGE_PLS"; 10 | 11 | # $1 - beacon id 12 | # $2 - process id of injection target (optional) 13 | alias rdll-exec { 14 | local('$barch $beacon_id $pid $rdll_path $rdll $handle $actual_pipe_name $desired_length $null_padding $padding_needed $padded_pipe_name'); 15 | $beacon_id = $1; 16 | $pid = $2; # Optional pid 17 | # Get current beacon info 18 | $barch = beacon_info($beacon_id, "barch"); 19 | 20 | if ($barch != "x64") { 21 | berror($1, "This script only supports x64 processes"); 22 | return; 23 | } 24 | 25 | # If pid was not passed in, local injection 26 | if ($pid == $null){ 27 | $pid = beacon_info($beacon_id, "pid"); 28 | } 29 | 30 | # Build rdll path; This needs rework if you want to support x86 for whatever reason 31 | $rdll_path = getFileProper(script_resource("."), "target", "release", "dll_rs.shc.dll"); 32 | 33 | # Get rdll contents 34 | $handle = openf($rdll_path); 35 | $rdll = readb($handle, -1); 36 | 37 | # Close handle 38 | closef($handle); 39 | 40 | $padded_pipe_name = $pipe_name_generic; # 28 bytes by initial design 41 | $desired_length = "28"; # per DLL design 42 | $padding_needed = $desired_length - strlen($actual_pipe_name); 43 | $padded_pipe_name = $actual_pipe_name; 44 | 45 | if ($padding_needed > 0) { 46 | $null_padding = ""; 47 | $i = 0; 48 | while ($i < $padding_needed) { 49 | $null_padding = $null_padding . chr(0); # Append an actual null byte 50 | $i = $i + 1; 51 | } 52 | $padded_pipe_name = $actual_pipe_name . $null_padding; 53 | } else if ($padding_needed < 0) { 54 | berror($beacon_id, "Pipe name '" . $padded_pipe_name . "' is longer than max " . $max_pipe_name_len . " bytes!"); 55 | return; # Important to return if name is too long 56 | } 57 | println("ORIGINAL PIPENAME: " . $pipe_stomp_me_name); 58 | println("NEW PIPENAME: " . $padded_pipe_name); 59 | 60 | # Now use $padded_pipe_name in strrep 61 | $rdll = strrep($rdll, $pipe_stomp_me_name, $padded_pipe_name); 62 | 63 | # Open output handle 64 | $handle = openf(">" . $rdll_path); 65 | 66 | # Write rdll back down 67 | writeb($handle, $rdll); 68 | 69 | # Close handle 70 | closef($handle); 71 | 72 | # self-inject the dll 73 | bshinject($beacon_id, $pid, $barch, $rdll_path); 74 | 75 | } 76 | 77 | # $1 - beacon id 78 | # $2 - process id of injection target (optional) 79 | alias rdll-read { 80 | local('$barch $beacon_id $pid $cmd $builder $job_type $callback_type $description $job'); 81 | $beacon_id = $1; 82 | $pid = $2; # Optional pid 83 | $job_type = 40; 84 | $callback_type = 32; 85 | $description = "pipe read"; 86 | 87 | # Get current beacon info 88 | $barch = beacon_info($beacon_id, "barch"); 89 | 90 | if ($barch != "x64") { 91 | berror($1, "This script only supports x64 processes"); 92 | return; 93 | } 94 | 95 | # If pid was not passed in, local injection 96 | if ($pid == $null){ 97 | $pid = beacon_info($beacon_id, "pid"); 98 | } 99 | 100 | # Use command builder to read from pipe 101 | $builder = [new CommandBuilder]; 102 | [$builder setCommand: $job_type]; 103 | [$builder addInteger: parseNumber($pid)]; 104 | [$builder addShort: $callback_type]; 105 | [$builder addShort: $pipe_wait]; 106 | [$builder addLengthAndString: "\\\\.\\pipe\\" . $pipe_name_generic]; 107 | [$builder addLengthAndString: $description]; 108 | $job = [$builder build]; 109 | call("beacons.task", $null, $beacon_id, cast($job, 'b')); 110 | } 111 | 112 | # -------------------- 113 | # Register the command 114 | # -------------------- 115 | beacon_command_group( 116 | "rdll_dlls", 117 | "User-Defined Reflective DLLs", 118 | "Collection of user-implemented reflective DLLs that enable advanced post-exploitation activities." 119 | ); 120 | 121 | beacon_command_register( 122 | "rdll-exec", 123 | "(64-bit only) Executes user implemented reflective DLL via 'bdllinject' aggressor function in the local process (default).\n Output of the DLL can be read via rdll-read.", 124 | "rdll-exec ", 125 | "rdll_dlls" 126 | ); 127 | 128 | beacon_command_register( 129 | "rdll-read", 130 | "(64-bit only) Reads output of a user implemented reflective DLL via 'bpsinject' aggressor function in the local process (default).", 131 | "rdll-exec ", 132 | "rdll_dlls" 133 | ); -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # rdll-rs 2 | 3 | A Rust DLL template project that integrates [pe2shc](https://github.com/hasherezade/pe_to_shellcode) to facilitate the development of [Reflective DLLs](https://github.com/stephenfewer/ReflectiveDLLInjection). The template presently only supports 64-bit DLL development in most contexts, though with a few tweaks it should support 32-bit. 4 | 5 | ## Overview 6 | 7 | rdll-rs is a Rust template that can be compiled as both a dynamic-link library (DLL), a regular executable, or a Reflective DLL. It provides an example of how to create Windows DLLs using Rust, including proper exports and Windows API integration. 8 | 9 | This project is broken down into "main" branches `master` and `master-legacy`. 10 | 11 | - `master` is intended for use with modern prepend loaders. 12 | - `master-legacy` retains the necessary symbols for compatibility with stomp-style reflective loaders. 13 | 14 | ## Features 15 | 16 | - Dual compilation modes (DLL and executable) 17 | - Windows API integration through FFI 18 | - Example exported functions 19 | - DLL lifecycle management 20 | 21 | ## Project Structure 22 | 23 | - `dll/src/lib.rs` - Library entry point 24 | - `dll/c_src/c_entry.c` - Entry point for C code via FFI 25 | - `exe/src/main.rs` - Executable implementation 26 | - `build-deps/pe_to_shellcode` - Post-build stomp reflective loader 27 | - Supporting Rust source files 28 | 29 | ## Building 30 | 31 | To build the project, use Cargo: 32 | ```bash 33 | cargo build 34 | ``` 35 | Or to build in release: 36 | ```bash 37 | cargo build --release 38 | ``` 39 | Or to build a Reflective DLL: 40 | ```bash 41 | cargo run --bin xtask --release 42 | ``` 43 | 44 | ## Usage 45 | 46 | The project can be used in three ways: 47 | 48 | 1. As a DLL (**dll-rs.dll**): 49 | - Build in release mode to generate the DLL 50 | - The DLL exports a `DllMain` function and example functionality 51 | 2. As an executable (**debug-executable.exe**): 52 | - Run in debug mode to test DLL functionality without DLL debugging gymnastics 53 | - Running in release mode will display a warning message 54 | - **NOTE: For maximum compatability with this template, all functionality should be called from `dll_main` in `dll/src/lib.rs`** 55 | 3. As a Reflective DLL (**dll_rs.shc.dll**) using [@hasherezade's](https://github.com/hasherezade) [pe_to_shellcode](https://github.com/hasherezade/pe_to_shellcode) 56 | - Resolve submodules with `git submodule update --init --recursive` 57 | - `cd .\build-deps\pe_to_shellcode\` 58 | - `cmake .` 59 | - `cmake --build . --config Release` 60 | - `cd ..\..` 61 | - `cargo run --bin xtask --release` 62 | - Use your Reflective DLL in `target/release/dll_rs.shc.dll` 63 | - **NOTE: If the build process above is too complicated/broken for your taste, simply placing the [`pe2shc.exe`](https://github.com/hasherezade/pe_to_shellcode/releases/download/v1.2/pe2shc.exe) executable in the proper folder structure (`build-deps/pe_to_shellcode/pe2shc/Release/pe2shc.exe`) will work.** 64 | 65 | ## Getting Reflective DLL Output to Beacon Console 66 | This template includes a `write_output` function which allows for output via named pipes to the Beacon console (in a very hacky way). 67 | This works by loading the `rdll-rs.cna` which registers two commands: `rdll-exec` and `rdll-read`. 68 | - `rdll-exec` stomps the pipe name specified in the `.cna` into the `dll_rs.shc.dll`, then injects the DLL via the `bdllinject` aggressor function. 69 | - `rdll-read` uses `CommandBuilder` to build a custom task to read from the pipe and output the contents to the Beacon console. 70 | - **NOTE: `write_output` is **BLOCKING** so it should only be used to write output to the Beacon console all at once (ie once your intended functionality is entirely complete).** 71 | 72 | ![img_1.png](img_1.png) 73 | 74 | ## Using Other Reflective Loaders 75 | The `master` branch of this repository abandoned compatability with stomp loaders in favor of more generic prepend-style (sRDI) reflective loaders. For stomp-style support see the `master-legacy` branch. Some implementations of reflective loaders obfuscate the DLL. This can be helpful in some contexts but applying the obfuscation on the DLL before execution of the `.cna` results in a failure to stomp the appropriate pipe name into the DLL, breaking `write_output` functionality. To mitigate the risk of this, it's recommended that a manual stomp step be applied before the reflective loader is applied to the DLL. An example workflow that uses a PowerShell one-liner is below: 76 | - `cargo build --release` 77 | - `cd target/release` 78 | - ```$path = "dll_rs.dll"; $bytes = [System.IO.File]::ReadAllBytes($path); $search = [System.Text.Encoding]::ASCII.GetBytes("RDLL_PIPE_NAME_NO_CHANGE_PLS"); $replace = [System.Text.Encoding]::ASCII.GetBytes("macrohard_updates`0".PadRight($search.Length, "`0")); for ($i = 0; $i -le $bytes.Length - $search.Length; $i++) { $match = $true; for ($j = 0; $j -lt $search.Length; $j++) { if ($bytes[$i + $j] -ne $search[$j]) { $match = $false; break } } if ($match) { $replace.CopyTo($bytes, $i); break } }; [System.IO.File]::WriteAllBytes($path, $bytes)``` 79 | - **Note that `macrohard_updates` should match the pipe name in the `.cna` and has the same length limitation (28-bytes).** 80 | - `donut --input:dll_rs.dll -o dll_rs.shc.dll` 81 | 82 | ## I don't want to learn Rust 83 | I encourage you to try it sometime. However, to support the integration of C code a [Foreign Function Interface (FFI)](https://doc.rust-lang.org/nomicon/ffi.html) entry point (`dll/c_src/c_entry.c`) has been added to the template to allow you to call into C code from Rust. 84 | ![img.png](img.png) 85 | 86 | If you want to add more `.c` files, be sure to add them to the `dll/c_src` directory because that's the intended convention, and define desired FFI functions in `dll/ffi.rs` if you want to call them from Rust. The build script `dll/build.rs` builds all `.c` files in the `c_src` directory into a single 87 | static library (`c_code`) that is linked into the Rust DLL. 88 | 89 | ## Technical Details 90 | 91 | - Uses `cdylib` and `rlib` crate types 92 | - Implements Windows API bindings 93 | - Provides internal FFI declarations for Windows types 94 | - Includes DLL entry point handling 95 | - Remember: For maximum compatability with this template, all functionality should be called from `dll_main` in `dll/src/lib.rs` 96 | - Supports the command-line ergonomics of the `shinject` in your [favorite C2 Framework](https://www.cobaltstrike.com/). 97 | 98 | ## Comments 99 | This template is significantly more useful than most existing Reflective DLL templates in C/C++ because it provides an organic platform from which third-party libraries can be readily used. This is thanks to Rust's [Cargo](https://github.com/rust-lang/cargo) which allows for easily sharable libraries. 100 | For example, if you were looking for a method of stack spoofing from inside a Reflective DLL in C/C++ you would most likely be stuck implementing that yourself from your preferred template. However, using Cargo, you can quickly add a library like [uwd](https://crates.io/crates/uwd) to 101 | get access to that capability without any of the overhead or additional Git submodule shenanigans that come with setting that up in a C/C++ repository. The entire [Crates](https://crates.io/) ecosystem is now at your fingertips. 102 | 103 | ## Requirements 104 | 105 | - Rust 2024 edition 106 | - Windows operating system 107 | - Cargo build system 108 | - Cmake > 3.0 109 | 110 | ## Licensing 111 | 112 | - MIT or Apache 2.0 -------------------------------------------------------------------------------- /rust-toolchain.toml: -------------------------------------------------------------------------------- 1 | [toolchain] 2 | channel = "stable" 3 | targets = [ "x86_64-pc-windows-gnu" ] 4 | profile = "complete" -------------------------------------------------------------------------------- /xtask/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "xtask" 3 | version = "0.1.0" 4 | edition = "2024" 5 | 6 | [dependencies] 7 | -------------------------------------------------------------------------------- /xtask/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::process::{Command, exit}; 2 | 3 | fn main() { 4 | let path = std::env::current_dir().unwrap(); 5 | println!("[INFO] The current directory is {}", path.display()); 6 | 7 | let status = Command::new("cargo") 8 | .args(&["build", "--release", "--manifest-path", "./Cargo.toml"]) 9 | .current_dir("./dll") 10 | .status() 11 | .expect("Failed to build"); 12 | if !status.success() { 13 | exit(1); 14 | } 15 | 16 | let status = Command::new("build-deps/pe_to_shellcode/pe2shc/Release/pe2shc.exe") 17 | .args(&["dll_rs.dll"]) 18 | .current_dir("./target/release") 19 | .status() 20 | .expect("Failed to run pe2shc.exe"); 21 | if !status.success() { 22 | exit(1); 23 | } 24 | 25 | println!("Done"); 26 | } 27 | --------------------------------------------------------------------------------