Traversing through the PEB and Export Directory for Position Independency ft. WinDbg
Walking through Windows internals to achieve position independent code, using WinDbg and C to traverse the PEB and resolve exports dynamically.
This blog post attempts to explain internal structures within Windows that allow for Position Independent Code, through the usage of WinDbg and C. It was mostly created to help increase my knowledge of WinDbg and this overall process.
Process Environment Block (PEB)
The Process Environment Block is a user-mode structure which documents various properties of the associated process, such as the computer name or if it is currently being debugged. The PEB is contained within every process, and as such is seen as a gold-mine for offensive tooling due to the reliability of its fixed position. The PEB can be found at GS:[0x60] for x64 architecture and FS:[0x30] for x86. A common method to obtain the offset is through the following code:
__readgsqword(0x60); //x64
__readfsdword(0x30); //x86
WinDbg allows for easy enumeration of the PEB through the !peb command:
2:004> !peb
PEB at 000000c5d41f2000
InheritedAddressSpace: No
ReadImageFileExecOptions: No
BeingDebugged: Yes
ImageBaseAddress: 00007ff702750000
NtGlobalFlag: 70
NtGlobalFlag2: 0
Ldr 00007ff8944dc4c0
Ldr.Initialized: Yes
Ldr.InInitializationOrderModuleList: 0000023ab0422860 . 0000023ab0422f80
Ldr.InLoadOrderModuleList: 0000023ab0422a10 . 0000023ab0423640
Ldr.InMemoryOrderModuleList: 0000023ab0422a20 . 0000023ab0423650
Base TimeStamp Module
7ff702750000 634d3885 Oct 17 04:12:05 2022 C:\Users\Shinji.NERV\Downloads\main.exe
7ff894370000 fe96c48e May 08 23:26:22 2105 C:\Windows\SYSTEM32\ntdll.dll
7ff8940a0000 4d6d72d1 Mar 01 14:27:29 2011 C:\Windows\System32\KERNEL32.DLL
7ff891b10000 cb12e58e Dec 17 16:34:22 2077 C:\Windows\System32\KERNELBASE.dll
SubSystemData: 0000000000000000
ProcessHeap: 0000023ab0420000
ProcessParameters: 0000023ab0421f40
CurrentDirectory: 'C:\Windows\system32\'
WindowTitle: 'C:\Users\Shinji.NERV\Downloads\main.exe'
ImageFile: 'C:\Users\Shinji.NERV\Downloads\main.exe'
CommandLine: 'C:\Users\Shinji.NERV\Downloads\main.exe'
DllPath: '< Name not readable >'
Environment: 0000023ab0421130
ALLUSERSPROFILE=C:\ProgramData
APPDATA=C:\Users\Shinji.NERV\AppData\Roaming
CommonProgramFiles=C:\Program Files\Common Files
CommonProgramFiles(x86)=C:\Program Files (x86)\Common Files
CommonProgramW6432=C:\Program Files\Common Files
COMPUTERNAME=EVA01
ComSpec=C:\Windows\system32\cmd.exe
DBGENG_OVERRIDE_DBGSRV_PATH=C:\Users\Shinji.NERV\AppData\Local\Microsoft\WindowsApps\Microsoft.WinDbg_8wekyb3d8bbwe\dbgsrvX64.exe
DBGHELP_HOMEDIR=C:\ProgramData\Dbg
DriverData=C:\Windows\System32\Drivers\DriverData
HOMEDRIVE=C:
HOMEPATH=\Users\Shinji.NERV
LOCALAPPDATA=C:\Users\Shinji.NERV\AppData\Local
LOGONSERVER=\\GEOFRONT
NUMBER_OF_PROCESSORS=2
OneDrive=C:\Users\Shinji.NERV\OneDrive
OS=Windows_NT
Path=C:\Program Files\WindowsApps\Microsoft.WinDbg_1.2210.3001.0_x64__8wekyb3d8bbwe\amd64;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files\PuTTY\;C:\Program Files\dotnet\;C:\Users\Shinji.NERV\AppData\Local\Microsoft\WindowsApps
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
PROCESSOR_ARCHITECTURE=AMD64
PROCESSOR_IDENTIFIER=AMD64 Family 25 Model 33 Stepping 0, AuthenticAMD
PROCESSOR_LEVEL=25
PROCESSOR_REVISION=2100
ProgramData=C:\ProgramData
ProgramFiles=C:\Program Files
ProgramFiles(x86)=C:\Program Files (x86)
ProgramW6432=C:\Program Files
PSModulePath=C:\Program Files\WindowsPowerShell\Modules;C:\Windows\system32\WindowsPowerShell\v1.0\Modules
PUBLIC=C:\Users\Public
SRCSRV_SHOW_TF_PROMPT=1
SystemDrive=C:
SystemRoot=C:\Windows
TEMP=C:\Users\SHINJI~1.NER\AppData\Local\Temp
TMP=C:\Users\SHINJI~1.NER\AppData\Local\Temp
USERDNSDOMAIN=NERV.LOCAL
USERDOMAIN=NERV
USERDOMAIN_ROAMINGPROFILE=NERV
USERNAME=Shinji
USERPROFILE=C:\Users\Shinji.NERV
windir=C:\Windows
As we can see, the PEB offers a treasure trove of information. For the purpose of this blog, however, we will solely focus on the Ldr attribute. Windows has kindly offered some documentation on the PEB structure[1] that will help us understand this property. According to Microsoft, Ldr is a pointer to the PEB_LDR_DATA structure which contains information about the loaded modules for the process. This makes sense, given in our WinDbg text above we clearly see kernel22.dll and ntdll.dll alongside their relevant base address.
If we dig more into PEB_LDR_DATA[2], we can see that Microsoft have also partially given documentation for its purpose. Whilst two functions are declared “Reserved”, and their purpose kept withdrawn (more to this later), they have listed the InMemoryOrderModuleList function. This is a LIST_ENTRY that contains the loaded modules for the process. Each item within this list is a pointer to a LDR_DATA-TABLE_ENTRY. This entry looks as follows:
typedef struct _LDR_DATA_TABLE_ENTRY {
PVOID Reserved1[2];
LIST_ENTRY InMemoryOrderLinks;
PVOID Reserved2[2];
PVOID DllBase;
PVOID EntryPoint;
PVOID Reserved3;
UNICODE_STRING FullDllName;
BYTE Reserved4[8];
PVOID Reserved5[3];
union {
ULONG CheckSum;
PVOID Reserved6;
};
ULONG TimeDateStamp;
} LDR_DATA_TABLE_ENTRY, *PLDR_DATA_TABLE_ENTRY;
Here we can see the DllBase function, which points to the Dll’s base address, and FullDllName, which would allow us to enumerate the name of its loaded module. Lets go back to WinDbg and enumerate this structure some more. We’ll first take the address value found in Ldr.InMemoryOrderModuleList (0000023ab0422a20) and display _LDR_DATA_TABLE_ENTRY:
2:004> dt _LDR_DATA_TABLE_ENTRY 0000023ab0422a20
ntdll!_LDR_DATA_TABLE_ENTRY
+0x000 InLoadOrderLinks : _LIST_ENTRY [ 0x0000023a`b0422850 - 0x00007ff8`944dc4e0 ]
+0x010 InMemoryOrderLinks : _LIST_ENTRY [ 0x00000000`00000000 - 0x00000000`00000000 ]
+0x020 InInitializationOrderLinks : _LIST_ENTRY [ 0x00007ff7`02750000 - 0x00007ff7`02751000 ]
+0x030 DllBase : 0x00000000`00003000 Void
+0x038 EntryPoint : 0x00000000`0050004e Void
+0x040 SizeOfImage : 0xb0422588
+0x048 FullDllName : _UNICODE_STRING "main.exe"
+0x058 BaseDllName : _UNICODE_STRING "???"
+0x068 FlagGroup : [4] "???"
+0x068 Flags : 0x944dc310
+0x068 PackagedBinary : 0y0
+0x068 MarkedForRemoval : 0y0
+0x068 ImageDll : 0y0
+0x068 LoadNotificationsSent : 0y0
+0x068 TelemetryEntryProcessed : 0y1
+0x068 ProcessStaticImport : 0y0
+0x068 InLegacyLists : 0y0
+0x068 InIndexes : 0y0
+0x068 ShimDll : 0y1
+0x068 InExceptionTable : 0y1
+0x068 ReservedFlags1 : 0y00
+0x068 LoadInProgress : 0y0
+0x068 LoadConfigProcessed : 0y0
+0x068 EntryProcessed : 0y1
+0x068 ProtectDelayLoad : 0y1
+0x068 ReservedFlags3 : 0y01
+0x068 DontCallForThreads : 0y1
+0x068 ProcessAttachCalled : 0y1
+0x068 ProcessAttachFailed : 0y0
+0x068 CorDeferredValidate : 0y0
+0x068 CorImage : 0y1
+0x068 DontRelocate : 0y0
+0x068 CorILOnly : 0y0
+0x068 ChpeImage : 0y0
+0x068 ReservedFlags5 : 0y01
+0x068 Redirected : 0y1
+0x068 ReservedFlags6 : 0y00
+0x068 CompatDatabaseProcessed : 0y1
+0x06c ObsoleteLoadCount : 0x7ff8
+0x06e TlsIndex : 0
+0x070 HashLinks : _LIST_ENTRY [ 0x00000000`634d3885 - 0x00000000`00000000 ]
+0x080 TimeDateStamp : 0
+0x088 EntryPointActivationContext : 0x0000023a`b0422b60 _ACTIVATION_CONTEXT
+0x090 Lock : 0x0000023a`b0422b60 Void
+0x098 DdagNode : 0x0000023a`b0422b60 _LDR_DDAG_NODE
+0x0a0 NodeModuleLink : _LIST_ENTRY [ 0x000000c5`d43ff430 - 0x00000000`00000000 ]
+0x0b0 LoadContext : 0x00007ff8`9448d2f4 _LDRP_LOAD_CONTEXT
+0x0b8 ParentDllBase : (null)
+0x0c0 SwitchBackContext : 0x0000023a`b0423708 Void
+0x0c8 BaseAddressIndexNode : _RTL_BALANCED_NODE
+0x0e0 MappingInfoIndexNode : _RTL_BALANCED_NODE
+0x0f8 OriginalBase : 0x00000004`f071787d
+0x100 LoadTime : _LARGE_INTEGER 0x00000002`00000000
+0x108 BaseNameHashValue : 0
+0x10c LoadReason : 0 ( LoadReasonStaticDependency )
+0x110 ImplicitPathOptions : 0xabababab
+0x114 ReferenceCount : 0xabababab
+0x118 DependentLoadFlags : 0xabababab
+0x11c SigningLevel : 0xab ''
We can see from the FullDllName value that this is currently within the main.exe module. To enumerate through another process, we can use the InLoadOrderLinks pointer:
dt _LDR_DATA_TABLE_ENTRY 0x0000023a`b0422850
ntdll!_LDR_DATA_TABLE_ENTRY
+0x000 InLoadOrderLinks : _LIST_ENTRY [ 0x0000023a`b0422f70 - 0x0000023a`b0422a20 ]
+0x010 InMemoryOrderLinks : _LIST_ENTRY [ 0x0000023a`b0423660 - 0x00007ff8`944dc4f0 ]
+0x020 InInitializationOrderLinks : _LIST_ENTRY [ 0x00007ff8`94370000 - 0x00000000`00000000 ]
+0x030 DllBase : 0x00000000`001f8000 Void
+0x038 EntryPoint : 0x00000000`003c003a Void
+0x040 SizeOfImage : 0xb04226d0
+0x048 FullDllName : _UNICODE_STRING "ntdll.dll"
+0x058 BaseDllName : _UNICODE_STRING "???"
+0x068 FlagGroup : [4] "???"
<SNIP>
So far we have gone over enough of the structure to build a simple example concept, where we will loop through the PEB and list all module names. Lets go over the code for this:
#include <windows>
#include <stdio.h>
#include <winternl.h>
int main(){
PPEB pebAddress;
PPEB_LDR_DATA pLoader;
PLDR_DATA_TABLE_ENTRY pFirstModule;
PLDR_DATA_TABLE_ENTRY pNextModule;
pebAddress = (PPEB) __readgsqword(0x60);
pLoader = pebAddress->Ldr;
pFirstModule = (PLDR_DATA_TABLE_ENTRY)pLoader->InMemoryOrderModuleList.Flink;
pNextModule = pFirstModule;
do{
wprintf(L"Current module is %S\n", pNextModule->FullDllName.Buffer);
pNextModule = pNextModule->Reserved1[0];
} while(pNextModule != pFirstModule);
return 0;
}
This will go through every instance of InMemoryOrderModuleList, returning the FullDllName value. After the FullDllName value is printed, pNextModule is set to Reserved1 (known also as InLoadOrderLinks) which points to the next module instance. This will continue until the value of pNextModule is the same as pFirst Module (as LIST_ENTRY is loopable). Lets run the program and see what happens:
PS C:\Users\Shinji.NERV\Downloads> ./Modules.exe
Current module is Modules.exe
Current module is ntdll.dll
Current module is KERNEL32.DLL
Current module is KERNELBASE.dll
Current module is msvcrt.dll
Current module is (null)
Awesome! We’ve successfully parsed data from the PEB with concepts taken from our enumeration of WinDbg. Similar to the WinDbg example, the first module loaded is itself, followed by ntdll.dll and kernel32.dll. This is the first step we need to take to obtain position independency. Our next step in this journey is to obtain the address to LoadLibrary within kernel32. This will require us to know the base address of kernel32, which we can clearly obtain from everything we have learnt thus far. Instead of merely grabbing the FullDllName value for every module, we will specifically search for the name of kernel32, and when found give us its base address.
We’ll first need to delineate a tiny bit to talk about hashing algorithms. We are quite limited with position independent code, and can’t use any imported functions (such as strcmp). While we could transfer the code line-by-line into our program, I think it looks rather ugly. To avoid this inconvienance, we will be using the djb2 hashing algorithm[3] to compare the value of FullDllName:
UINT_PTR hashAlgorithm(PWSTR input){
long hash = 7777;
int i;
while (i = *input++)
hash = ((hash << 5) + hash) + i;
return hash;
We’ll define kernel32’s hash within our program as so:
#define HASH_KERNEL32 0x4b5888b1
With this completed, lets return to our PEB parser and add the additions previously mentioned:
PVOID resolveDllBase(DWORD dllName){
PPEB pPebAddress;
PPEB_LDR_DATA pLoader;
PLDR_DATA_TABLE_ENTRY pFirstModule;
PLDR_DATA_TABLE_ENTRY pNextModule;
DWORD moduleHash;
pPebAddress = (PPEB) __readgsqword(0x60);
pLoader = pPebAddress->Ldr;
pFirstModule = (PLDR_DATA_TABLE_ENTRY)pLoader->InMemoryOrderModuleList.Flink;
pNextModule = pFirstModule;
do{
moduleHash = hashAlgorithm(pNextModule->FullDllName.Buffer);
if(moduleHash == dllName){
return pNextModule->Reserved2[0];
}
pNextModule = pNextModule->Reserved1[0];
} while(pNextModule != pFirstModule);
return 0;
};
The concept is mostly the same, except we have included a conditional check through the hashing algorithm. This conditional check, if it results in true, returns Reserved2 (InInitializationOrderLinks). This would be the base address of kernel32!
Export Directory
So, we now have a handle to the base address of kernel32, what do we do from here? Our goal is to obtain the address of LoadLibrary, which we’ll have to traverse the PE file itself for, more specifically the data directory. We’ll first define the DOS and NT headers which will grant us a pointer to the data directory:
ntHeaders = dllName + ((PIMAGE_DOS_HEADER)dllName)->e_lfanew;
exportDirectory = dllName + ntHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
Sadly there isn’t much documentation on PIMAGE_DOS_HEADER. the e_lfanew attribute points to the modern NT header (otherwise known simply as PE header). Once this is instaniated, we use the OptionalHeader[4] function to obtain a pointer for the export directories virtual address. Let us once again journey into the miasma that is WinDbg to understand and uncover the theory behind this code.
We can display the headers for kernel32 by obtaining the address from InInitializationOrderLinks and providing it alongside !dh:
2:004> !dh 0x00007ff8`940a0000 -f
File Type: DLL
FILE HEADER VALUES
8664 machine (X64)
7 number of sections
4D6D72D1 time date stamp Tue Mar 1 14:27:29 2011
0 file pointer to symbol table
0 number of symbols
F0 size of optional header
2022 characteristics
Executable
App can handle >2gb addresses
DLL
OPTIONAL HEADER VALUES
20B magic #
14.20 linker version
7D400 size of code
3A600 size of initialized data
0 size of uninitialized data
170D0 address of entry point
1000 base of code
----- new -----
00007ff8940a0000 image base
1000 section alignment
200 file alignment
3 subsystem (Windows CUI)
10.00 operating system version
10.00 image version
10.00 subsystem version
BD000 size of image
400 size of headers
BC204 checksum
0000000000040000 size of stack reserve
0000000000001000 size of stack commit
0000000000100000 size of heap reserve
0000000000001000 size of heap commit
4160 DLL characteristics
High entropy VA supported
Dynamic base
NX compatible
Guard
99080 [ DF0C] address [size] of Export Directory
A6F8C [ 794] address [size] of Import Directory
BB000 [ 520] address [size] of Resource Directory
B4000 [ 5550] address [size] of Exception Directory
B7000 [ 4030] address [size] of Security Directory
BC000 [ 300] address [size] of Base Relocation Directory
86930 [ 70] address [size] of Debug Directory
0 [ 0] address [size] of Description Directory
0 [ 0] address [size] of Special Directory
0 [ 0] address [size] of Thread Storage Directory
7F7F0 [ 118] address [size] of Load Configuration Directory
0 [ 0] address [size] of Bound Import Directory
807C0 [ 2A58] address [size] of Import Address Table Directory
98E40 [ 60] address [size] of Delay Import Directory
0 [ 0] address [size] of COR20 Header Directory
0 [ 0] address [size] of Reserved Directory
We can see the image base and additionally all optional header values. Lets dump addresses with the offset of Export Directory using the dd command:
2:004> dd 0x00007ff8940a0000+99080
00007ff8`94139080 00000000 4d6d72d1 00000000 0009d072
00007ff8`94139090 00000001 00000661 00000661 000990a8
00007ff8`941390a0 0009aa2c 0009c3b0 0009d097 0009d0cd
00007ff8`941390b0 00020080 0001b700 00059170 000128f0
00007ff8`941390c0 00025640 00025650 0009d153 0003bd10
00007ff8`941390d0 000592b0 00059310 00022270 0001e2c0
00007ff8`941390e0 00039650 000208a0 00039670 00037a70
00007ff8`941390f0 0009d28c 0009d2cc 00007200 00025290
We can correlate this dump with the below structure from pinvoke.net. An UInt32 type will belong to its own space (e.g 4d6d72d1 - TimeDateStamp), however UInt16 will be halved (e.g 00000000 - MajorVersion, MinorVersion):
public struct IMAGE_EXPORT_DIRECTORY
{
public UInt32 Characteristics;
public UInt32 TimeDateStamp;
public UInt16 MajorVersion;
public UInt16 MinorVersion;
public UInt32 Name;
public UInt32 Base;
public UInt32 NumberOfFunctions;
public UInt32 NumberOfNames;
public UInt32 AddressOfFunctions; // RVA from base of image
public UInt32 AddressOfNames; // RVA from base of image
public UInt32 AddressOfNameOrdinals; // RVA from base of image
}
For instance, lets look up the Name attribute using the WinDbg da command. This will print out ASCII characters:
0:000> da 00007ff8940a0000+0009d072
00007ffc`58d7d072 "KERNEL32.dll"
Perfect! As we can see, we’re at the correct address and we can successfully enumerate values from Kernel32’s export directory. Lets go a step further, and attempt to enumerate the names of functions contained here. Our goal being to identify LoadLibrary. We’ll start by going through the AddressOfNames pointer, with the same da command as the Name pointer:
0:000> dc 0x00007ff8940a0000+0009aa2c
00007ffc`58d7aa2c 0009d07f 0009d0b8 0009d0eb 0009d0fa ................
00007ffc`58d7aa3c 0009d10f 0009d118 0009d121 0009d132 ........!...2...
00007ffc`58d7aa4c 0009d143 0009d188 0009d1ae 0009d1cd C...............
00007ffc`58d7aa5c 0009d1ec 0009d1f9 0009d20c 0009d224 ............$...
00007ffc`58d7aa6c 0009d23f 0009d254 0009d271 0009d2b0 ?...T...q.......
00007ffc`58d7aa7c 0009d2f1 0009d304 0009d311 0009d32b ............+...
00007ffc`58d7aa8c 0009d349 0009d380 0009d3c5 0009d410 I...............
00007ffc`58d7aa9c 0009d46b 0009d4c0 0009d513 0009d568 k...........h...
0:000> da 00007ff8940a0000+0009d07f
00007ffd`9f30d07f "AcquireSRWLockExclusive"
0:000> da 00007ff8940a0000+0009d0b8
00007ffd`9f30d07f "AcquireSRWLockShared"
We’re now at the AddressOfNames attribute and can clearly see the function names stored here. Lets make an addition to our program to include recursion logic, so we parse everything stored within AddressOfNames. We can use the NumberOfNames pointer to help us in this endevour:
PVOID lookupExport(PBYTE dllName){
PIMAGE_NT_HEADERS ntHeaders;
PIMAGE_EXPORT_DIRECTORY exportDirectory;
PDWORD addressNames;
PCHAR functionName;
ntHeaders = dllName + ((PIMAGE_DOS_HEADER)dllName)->e_lfanew;
exportDirectory = dllName + ntHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
addressNames = (PDWORD)(dllName + (DWORD)exportDirectory->AddressOfNames);
for(DWORD i = 0; i < exportDirectory->NumberOfNames; i++){
functionName = dllName + addressNames[i];
printf("Function Name is: %s\n", functionName);
}
return 0;
}
This function of ours takes in the dllName from our PEB traversal function from before, and looks up the export directory from this. Once we have the address for this directory, we’ll declare an AddressOfNames pointer and create a for loop around the number of names. The rest should be pretty self-explanatory. Due to the sheer length of the output, I’ve lessened it to around 10~ entries. Clearly it is working as intended!
Function Name is: AcquireSRWLockExclusive
Function Name is: AcquireSRWLockShared
Function Name is: ActivateActCtx
Function Name is: ActivateActCtxWorker
Function Name is: AddAtomA
Function Name is: AddAtomW
Function Name is: AddConsoleAliasA
Function Name is: AddConsoleAliasW
Function Name is: AddDllDirectory
Function Name is: AddIntegrityLabelToBoundaryDescriptor
Function Name is: AddLocalAlternateComputerNameA
Function Name is: AddLocalAlternateComputerNameW
<SNIP>
Function Name is: LoadLibraryA
So, we now have a way to find the name of LoadLibrary. Akin to the PEB traversal, we need to find the base address of LoadLibrary. We’ll be applying the same principals of hash comparing, so lets focus on how to find the base address and create the function out of this. If we harken back to the IMAGE_EXPORT_DIRECTORY structure, there are three commented pointers:
- AddressOfFunctions
- AddressOfNames
- AddressOfNameOrdinals
We’ve already uncovered the purpose of AddressOfNames, but what about the other two? AddressOfFunctions is similar to AddressOfNames conceptually, however we must additionally call AddressOfNameOrdinals with an integer to correctly locate its base address. Dejan Lukan has written a terrific blog post here detailing the intricacies, to which I wouldn’t be able to adequately explain as well. Let’s change our export directory proof of concept to now return the address of a function instead of names themselves. We can do the same hash comparasion process as with the PEB.
PVOID lookupExport(PBYTE dllName, DWORD functionNameHash){
PIMAGE_NT_HEADERS ntHeaders;
PIMAGE_EXPORT_DIRECTORY exportDirectory;
PDWORD addressNames;
PDWORD addressFunctions;
PUSHORT addressOrdinals;
PCHAR functionName;
DWORD functionHash;
ntHeaders = dllName + ((PIMAGE_DOS_HEADER)dllName)->e_lfanew;
exportDirectory = dllName + ntHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
addressNames = (PDWORD)(dllName + (DWORD)exportDirectory->AddressOfNames);
addressFunctions = (PDWORD)(dllName + (DWORD)exportDirectory->AddressOfFunctions);
addressOrdinals = (PUSHORT)(dllName + (DWORD)exportDirectory->AddressOfNameOrdinals);
for(DWORD i = 0; i < exportDirectory->NumberOfNames; i++){
functionName = dllName + addressNames[i];
functionHash = hashAlgorithm((PWSTR)functionName);
if(functionHash == functionNameHash){
printf("Found Function Name.");
printf("addr of loadLibrary: 0x%p\n", dllName + addressFunctions[addressOrdinals[i]]);
return (PVOID)(dllName + addressFunctions[addressOrdinals[i]]);
}
}
return 0;
}
With this completed, we’re pretty much finished with the C implementation. We’ll need to also define the functions themselves, but that is pretty simple. I’ve created a header file which defines them as so:
typedef HMODULE(WINAPI* LOADLIBRARYA)(LPCSTR);
Custom Entrypoint
We’re nearing the end of the blog now, however you would notice that we are still not at position independency quite yet. Sure, we can traverse the PEB and dynamically find functions, but all our code currently compiles into a standard executable with bits and pieces in various PE sections. How do we fix this? Well, we can do this through ensuring that only the .text section will compile and that we don’t go through the standard entrypoint mainCRTStartup. This can be done with two files, the first written in assembly:
extern pic
global alignstack
segment .text
align:
push rdi
mov rdi, rsp
and rsp, byte -0x10
sub rsp, byte +0x20
call pic
mov rsp, rdi
pop rdi
ret
This assembly code will fulfill the pre-requisites before we call our custom entrypoint, which is ensuring that the only section will be .text and the stack is alligned by 16-bytes. We’ll need to align the stack by 16-bytes due to SIMD (SSE) instructions, which perform parallel operations for performancy. This is a requirement as certain WINAPI calls use these instructions under the hood (for example, CreateProcessInternalW) and failure to do this will result in an exception.
Now we’ll create a linker file which will specify our custom entrypoint:
ENTRY(alignstack)
SECTIONS
{
.text :
{
*(.text.alignstack)
*(.text.pic)
}
}
As you can see, we are first calling the alignstack stub, then our custom PIC C code all within the .text section. The compilation process can be seen as follows:
_______________ __________________ _______________
/ \ / \ / \
| | | Compile pic.c | | Link asm.o |
| Compile | --> | with | --> | and |
| asm.asm | | linker script | | pic.o |
| | | | |
\______________/ \________________/ \_______________/
Which can be condensed into the following Makefile (again, kudos to paranoidninja):
make:
nasm -f win64 adjuststack.asm -o adjuststack.o
x86_64-w64-mingw32-gcc pic.c -Wall -m64 -ffunction-sections -fno-asynchronous-unwind-tables -nostdlib -fno-ident -O2 -c -o pic.o -Wl,-Tlinker.ld,--no-seh
x86_64-w64-mingw32-ld -s adjuststack.o pic.o -o pic.exe
And thats it! If all goes well, you should now be able to extract the shellcode from the exe’s .text section. Thanks for reading!