Repository navigation
Expand file tree
/
Copy pathlib.rs
More file actions
executable file
·374 lines (326 loc) · 12.7 KB
/
Copy pathlib.rs
File metadata and controls
executable file
·374 lines (326 loc) · 12.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
#![no_std]
#![no_main]
#[cfg(not(feature = "shellcode_compat"))]
extern crate alloc;
#[cfg(feature = "shellcode_compat")]
extern crate compiler_builtins;
pub mod pelib;
pub mod test;
pub mod utils;
pub mod windows;
use pelib::fix_base_relocations;
use pelib::fix_section_permissions;
use pelib::get_dos_header;
use pelib::get_headers_size;
use pelib::get_image_size;
use pelib::get_nt_header;
use pelib::patch_cli_args;
use pelib::patch_ldr_data;
use pelib::patch_peb;
use pelib::write_import_table;
use pelib::write_sections;
use shellcode_utils::prelude::CreateThreadFn;
use shellcode_utils::prelude::GetModuleHandleAFn;
use shellcode_utils::prelude::GetProcAddressFn;
use shellcode_utils::prelude::ImageTlsCallbackFn;
use shellcode_utils::prelude::LoadLibraryAFn;
use shellcode_utils::prelude::RtlAddFunctionTableFn;
use shellcode_utils::prelude::VirtualAllocFn;
use shellcode_utils::prelude::VirtualProtectFn;
use utils::detect_platform;
#[cfg(not(feature = "shellcode_compat"))]
use windows_sys::Win32::System::LibraryLoader::GetModuleHandleA;
#[cfg(not(feature = "shellcode_compat"))]
use windows_sys::Win32::System::LibraryLoader::GetProcAddress;
#[cfg(not(feature = "shellcode_compat"))]
use windows_sys::Win32::System::LibraryLoader::LoadLibraryA;
#[cfg(not(feature = "shellcode_compat"))]
use windows_sys::Win32::System::Memory::VirtualAlloc;
#[cfg(not(feature = "shellcode_compat"))]
use windows_sys::Win32::System::Memory::VirtualProtect;
use windows_sys::Win32::System::Diagnostics::Debug::IMAGE_DIRECTORY_ENTRY_EXCEPTION;
use windows_sys::Win32::System::Diagnostics::Debug::IMAGE_DIRECTORY_ENTRY_TLS;
use windows_sys::Win32::System::Diagnostics::Debug::IMAGE_NT_HEADERS64;
use windows_sys::Win32::System::Diagnostics::Debug::IMAGE_RUNTIME_FUNCTION_ENTRY;
use windows_sys::Win32::System::Memory::MEM_COMMIT;
use windows_sys::Win32::System::Memory::PAGE_READWRITE;
use windows_sys::Win32::System::SystemServices::DLL_PROCESS_ATTACH;
use windows_sys::Win32::System::SystemServices::DLL_THREAD_ATTACH;
use windows_sys::Win32::System::SystemServices::IMAGE_TLS_DIRECTORY64;
use core::ffi::c_void;
use core::ptr;
#[used]
#[no_mangle]
#[cfg(feature = "shellcode_compat")]
// Required because compiler_builtins expects this symbol to be present
// and they only define it for UEFI environments
pub static _fltused: i32 = 0;
pub struct DependentModules {
pub kernelbase: *mut u8,
}
pub struct RuntimeFns {
pub virtual_alloc: VirtualAllocFn,
pub virtual_protect: VirtualProtectFn,
pub get_proc_address_fn: GetProcAddressFn,
pub load_library_fn: LoadLibraryAFn,
pub create_thread_fn: CreateThreadFn,
pub rtl_add_function_table_fn: Option<RtlAddFunctionTableFn>,
pub get_module_handle_fn: GetModuleHandleAFn,
}
pub struct LoaderContext<'a, 'b> {
pub buffer: &'a [u8],
pub image_name: Option<&'b [u16]>,
pub args: Option<&'b [u16]>,
pub modules: DependentModules,
pub fns: RuntimeFns,
}
/// Compares the platform of the imported Portable Executable (PE) file with the platform of the compiled binary.
/// Panic if not same platforms
///
/// # Arguments
///
/// * `data` - A vector containing the bytes of the PE file to be loaded.
fn is_platforms_same(data: &[u8]) {
let platform = detect_platform(&data).unwrap();
let target_arch = if cfg!(target_arch = "x86_64") { 64 } else { 32 };
if platform != target_arch {
panic!("The platform not the same as the imported pe.")
}
}
unsafe fn reflective_loader_impl(context: LoaderContext) {
unsafe { core::arch::asm!("and rsp, ~0xf") };
is_platforms_same(context.buffer);
// Get the size of the headers and the image
let headerssize = get_headers_size(context.buffer);
let imagesize = get_image_size(context.buffer);
// Get the DOS header
let dosheader = get_dos_header(context.buffer.as_ptr() as *const c_void);
// Get the NT header IMAGE_NT_HEADERS64|IMAGE_NT_HEADERS32
let ntheader = get_nt_header(context.buffer.as_ptr() as *const c_void, dosheader);
#[cfg(target_arch = "x86_64")]
let ntheader_ref: &IMAGE_NT_HEADERS64 = unsafe { core::mem::transmute(ntheader) };
#[cfg(target_arch = "x86")]
let ntheader_ref: &IMAGE_NT_HEADERS32 = unsafe { core::mem::transmute(ntheader) };
// Allocate memory for the image
let preferred_load_addr = ntheader_ref.OptionalHeader.ImageBase as *mut c_void;
let baseptr = (context.fns.virtual_alloc)(
preferred_load_addr, // lpAddress: A pointer to the starting address of the region to allocate.
imagesize, // dwSize: The size of the region, in bytes.
MEM_COMMIT, // flAllocationType: The type of memory allocation.
PAGE_READWRITE, // flProtect: The memory protection for the region of pages to be allocated.
);
// If we failed to get our preferred address, allocate anywhere
let baseptr = if baseptr.is_null() {
(context.fns.virtual_alloc)(
ptr::null_mut(), // lpAddress: A pointer to the starting address of the region to allocate.
imagesize, // dwSize: The size of the region, in bytes.
MEM_COMMIT, // flAllocationType: The type of memory allocation.
PAGE_READWRITE, // flProtect: The memory protection for the region of pages to be allocated.
)
} else {
baseptr
};
let base_offset = baseptr.offset_from(preferred_load_addr);
// Write the headers to the allocated memory
core::ptr::copy_nonoverlapping(
context.buffer.as_ptr() as *const c_void,
baseptr,
headerssize,
);
// Write each section to the allocated memory
write_sections(
baseptr, // The base address of the image.
context.buffer, // The buffer containing the image.
ntheader, // The NT header of the image.
dosheader, // The DOS header of the image.
);
// Write the import table to the allocated memory
write_import_table(
baseptr,
ntheader,
context.fns.get_proc_address_fn,
context.fns.load_library_fn,
context.fns.get_module_handle_fn,
);
// Fix the base relocations
if base_offset != 0 {
fix_base_relocations(baseptr, ntheader);
}
// Ensure each section has the proper permissions set
fix_section_permissions(baseptr, ntheader, dosheader, context.fns.virtual_protect);
// Patch data in kernelbase
patch_cli_args(context.args.clone(), context.modules.kernelbase);
// Patch the PEB
patch_peb(context.args, context.image_name);
#[cfg(target_arch = "x86_64")]
let entrypoint = (baseptr as usize
+ (*(ntheader as *const IMAGE_NT_HEADERS64))
.OptionalHeader
.AddressOfEntryPoint as usize) as *const c_void;
#[cfg(target_arch = "x86")]
let entrypoint = (baseptr as usize
+ (*(ntheader as *const IMAGE_NT_HEADERS32))
.OptionalHeader
.AddressOfEntryPoint as usize) as *const c_void;
let tls_directory =
&ntheader_ref.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS as usize];
// Grab the TLS data from the PE we're loading
let tls_data_addr = if tls_directory.Size == 0 {
core::ptr::null()
} else {
baseptr.offset(tls_directory.VirtualAddress as isize) as *mut IMAGE_TLS_DIRECTORY64
};
patch_ldr_data(
baseptr,
imagesize,
context.fns.get_module_handle_fn,
tls_data_addr,
entrypoint,
);
// Set exception handler
#[cfg(target_arch = "x86_64")]
{
if let Some(rtl_add_function_table_fn) = context.fns.rtl_add_function_table_fn {
let exception_dir = &ntheader_ref.OptionalHeader.DataDirectory
[IMAGE_DIRECTORY_ENTRY_EXCEPTION as usize];
if exception_dir.Size != 0 {
let runtime_functions: *const IMAGE_RUNTIME_FUNCTION_ENTRY =
core::mem::transmute(baseptr.offset(exception_dir.VirtualAddress as isize));
(rtl_add_function_table_fn)(
runtime_functions as *const _,
((exception_dir.Size as usize)
/ core::mem::size_of::<IMAGE_RUNTIME_FUNCTION_ENTRY>())
as u32,
baseptr as u64,
);
}
}
}
// Create a new thread to execute the image
execute_image(baseptr, entrypoint, context.fns.create_thread_fn);
// Free the allocated memory of baseptr
let _ = baseptr;
}
/// Loads a Portable Executable (PE) file into memory using reflective loading.
///
/// # Arguments
///
/// * `buffer` - A vector containing the bytes of the PE file to be loaded.
///
/// # Safety
///
/// This function is unsafe because it directly interacts with the Windows API and modifies memory
/// in the target process.
#[cfg(not(feature = "shellcode_compat"))]
pub unsafe fn reflective_loader(buffer: &[u8], image_name: Option<&[u16]>, args: Option<&[u16]>) {
let context = LoaderContext {
buffer,
image_name,
args,
modules: DependentModules {
// TODO
kernelbase: core::ptr::null_mut(),
},
fns: RuntimeFns {
virtual_alloc: VirtualAlloc,
virtual_protect: VirtualProtect,
get_proc_address_fn: unsafe {
core::mem::transmute(GetProcAddress as unsafe extern "system" fn(_, _) -> _)
},
load_library_fn: unsafe {
core::mem::transmute(LoadLibraryA as unsafe extern "system" fn(_) -> _)
},
// TODO
create_thread_fn: unsafe { core::mem::transmute(core::ptr::null::<CreateThreadFn>()) },
get_module_handle_fn: unsafe {
core::mem::transmute(GetModuleHandleA as unsafe extern "system" fn(_) -> _)
},
rtl_add_function_table_fn: None,
},
};
reflective_loader_impl(context);
}
/// Loads a Portable Executable (PE) file into memory using reflective loading.
///
/// # Arguments
///
/// * `buffer` - A vector containing the bytes of the PE file to be loaded.
///
/// # Safety
///
/// This function is unsafe because it directly interacts with the Windows API and modifies memory
/// in the target process.
#[cfg(feature = "shellcode_compat")]
pub unsafe fn reflective_loader(context: LoaderContext) {
reflective_loader_impl(context);
}
struct EntrypointData {
dll_base: *const c_void,
entrypoint: *const c_void,
}
/// Executes the image by calling its entry point and waiting for the thread to finish executing.
///
/// # Arguments
///
/// * `entrypoint` - A pointer to the PE file entrypoint.
///
/// # Safety
///
/// This function is unsafe because it directly interacts with the Windows API and modifies memory
/// in the target process.
unsafe fn execute_image(
dll_base: *const c_void,
entrypoint: *const c_void,
create_thread_fn: CreateThreadFn,
) {
let args = EntrypointData {
dll_base,
entrypoint,
};
unsafe {
let _handle = (create_thread_fn)(
ptr::null(), // default security attributes
0, // default stack size
core::mem::transmute(execute_image_entrypoint as unsafe extern "system" fn(_)), // thread start fn
core::mem::transmute(&args), // args
0, // default creation flags
ptr::null_mut(), // thread id
);
}
// Hang this thread forever
loop {}
}
unsafe extern "system" fn execute_image_entrypoint(args: *const EntrypointData) {
let func: extern "system" fn(*const c_void, u32, *const c_void) -> u32 =
core::mem::transmute((*args).entrypoint);
func((*args).dll_base, DLL_PROCESS_ATTACH, ptr::null());
}
/// Executes the image by calling its entry point and waiting for the thread to finish executing.
///
/// # Arguments
///
/// * `entrypoint` - A pointer to the PE file entrypoint.
///
/// # Safety
///
/// This function is unsafe because it directly interacts with the Windows API and modifies memory
/// in the target process.
unsafe fn execute_tls_callback(baseptr: *const c_void, entrypoint: *const c_void) {
// if let Some(create_thread_fn) = create_thread_fn {
// unsafe {
// let handle = (create_thread_fn)(
// ptr::null(), // default security n
// 0, // default stack size
// entrypoint, // thread start fn
// ptr::null(), // args
// 0, // default creation flags
// ptr::null_mut(), // thread id
// );
// core::arch::asm!("int 3");
// }
// } else {
// Call the entry point of the image
let func: ImageTlsCallbackFn = core::mem::transmute(entrypoint);
func(baseptr, DLL_THREAD_ATTACH, ptr::null_mut());
//}
}