// // An implementation of GetModuleHandle and GetProcAddress that works with manually mapped modules, forwarded exports, // without a CRT standard library, and uses no Windows API or dependencies. // // Author: Bill Demirkapi // License: MIT, appended at the bottom of this document if you care about licensing and want to credit me in your own project. // #include #include #define RCAST reinterpret_cast #define SCAST static_cast #define CCAST const_cast struct FULL_LDR_DATA_TABLE_ENTRY; namespace LowUtilities { typedef struct _FULL_LDR_DATA_TABLE_ENTRY { LIST_ENTRY InLoadOrderLinks; LIST_ENTRY InMemoryOrderModuleList; LIST_ENTRY InInitializationOrderModuleList; PVOID DllBase; PVOID EntryPoint; ULONG SizeOfImage; UNICODE_STRING FullDllName; UNICODE_STRING BaseDllName; ULONG Flags; USHORT LoadCount; USHORT TlsIndex; union { LIST_ENTRY HashLinks; struct { PVOID SectionPointer; ULONG CheckSum; }; }; union { ULONG TimeDateStamp; PVOID LoadedImports; }; PVOID EntryPointActivationContext; PVOID PatchInformation; } FULL_LDR_DATA_TABLE_ENTRY, * PFULL_LDR_DATA_TABLE_ENTRY; /// /// A simple string comparison function to support CRT-less environments. /// /// The type of character pointer (CHAR, WCHAR). /// The first string to compare. /// The second string to compare. /// TRUE if case sensitive comparison, FALSE otherwise. /// FALSE if should enforce that both strings end at same time, TRUE otherwise. /// TRUE if equal, FALSE otherwise. template BOOL CmpString ( _In_ CONST T* Str1, _In_ CONST T* Str2, _In_ CONST BOOL CaseSensitive = TRUE, _In_ CONST BOOL StartsWith = FALSE ) { T* currentStr1; T* currentStr2; T currentChar1; T currentChar2; currentStr1 = CCAST(Str1); currentStr2 = CCAST(Str2); // // Enumerate every character until we hit a NULL character. // while (*currentStr1 != '\0' && *currentStr2 != '\0') { currentChar1 = *currentStr1; currentChar2 = *currentStr2; if (CaseSensitive == FALSE) { if (currentChar1 >= 65 && currentChar1 <= 90) { currentChar1 = currentChar1 + 32; } if (currentChar2 >= 65 && currentChar2 <= 90) { currentChar2 = currentChar2 + 32; } } if (currentChar1 != currentChar2) { return FALSE; } currentStr1++; currentStr2++; } // // Make sure both strings are ending at the same time. // if (StartsWith == FALSE && (*currentStr1 != '\0' || *currentStr2 != '\0')) { return FALSE; } return TRUE; } /// /// Attempts to find first instance of Str2 in Str1. God I hate writing code for a CRT-less environment :( /// /// The type of character. /// The string to search. /// The string to search for. /// TRUE if case sensitive comparison, FALSE otherwise. /// Pointer to Str2 inside Str1. template T* StrStr ( _In_ CONST T* Str1, _In_ CONST T* Str2, _In_ CONST BOOL CaseSensitive = TRUE ) { T* currentStr1; currentStr1 = CCAST(Str1); // // Enumerate every character until we hit a NULL character. // while (*currentStr1 != '\0') { if (LowUtilities::CmpString(currentStr1, Str2, CaseSensitive, TRUE)) { return currentStr1; } currentStr1++; } return NULL; } /// /// A bad implementation of converting a string to an integer. /// /// The string to parse. /// An integer. int stoi ( _In_ CHAR* String ) { CHAR* originalString; int result; ULONG digitBase; SIZE_T stringLength; int currentDigit; result = 0; stringLength = 0; digitBase = 1; originalString = String; // // Start by counting how many characters are in String. // while (*String != '\x00') { // // Sanity check to make sure what we have is a string of digits. // if (*String < '0') { return 0; } String++; stringLength++; } // // Before we can parse the digits, we need to figure out the exponent of 10 // we need to start at given the length of the string. // while (stringLength != 1) { digitBase *= 10; stringLength--; } // // Next, iterate each digit and add it to the result. // String = originalString; while (*String != '\x00') { // // Get the integer representation of the digit by subtracting the 0 ascii digit. // currentDigit = *String - '0'; result += digitBase * currentDigit; digitBase /= 10; String++; } return result; } /// /// Retrieve the process process environment block. Used for enumerating loaded modules. /// /// Pointer to process PEB. PEB* GetProcessPeb ( VOID ) { return RCAST(__readgsqword(0x60)); } /// /// Find the DLL base of a given Module. /// /// The name of the module. /// If module is loaded, the DLL base of the module. Otherwise, NULL. PVOID GetModuleBase ( _In_ CONST WCHAR* ModuleName ) { PEB* processPeb; PPEB_LDR_DATA processLdr; PLIST_ENTRY headModuleEntry; PLIST_ENTRY currentModuleEntry; PFULL_LDR_DATA_TABLE_ENTRY currentLdrEntry; // // Grab the current process's PEB. // processPeb = LowUtilities::GetProcessPeb(); if (processPeb == NULL) { return NULL; } processLdr = processPeb->Ldr; // // Enumerate the module list. // headModuleEntry = &processLdr->InMemoryOrderModuleList; currentModuleEntry = headModuleEntry->Flink; while (currentModuleEntry != headModuleEntry) { // // Retrieve the contained LDR_DATA_TABLE_ENTRY structure. // currentLdrEntry = CONTAINING_RECORD(currentModuleEntry, FULL_LDR_DATA_TABLE_ENTRY, InMemoryOrderModuleList); // // Determine if current entry has the DLL name we're looking for. // if (StrStr(currentLdrEntry->BaseDllName.Buffer, ModuleName, FALSE)) { // // Return the base of the module. // return currentLdrEntry->DllBase; } currentModuleEntry = currentModuleEntry->Flink; } return NULL; } // // Forward declaration for the overload of GetProcAddress. // PVOID GetProcAddress ( _In_ CONST WCHAR* ModuleName, _In_ CONST CHAR* ExportName ); /// /// Retrieve the export of a module. /// /// The base address of the module. /// The export to find. /// Pointer to export specified by export name. PVOID GetProcAddress ( _In_ PVOID ModuleBase, _In_ CONST CHAR* ExportName ) { ULONG_PTR moduleBase; PIMAGE_DOS_HEADER dosHeader; PIMAGE_NT_HEADERS ntHeaders; ULONG eatDirectoryOffset; ULONG eatDirectorySize; PIMAGE_EXPORT_DIRECTORY eatDirectory; DWORD* eatFunctions; WORD* eatOrdinals; DWORD* eatNames; ULONG i; CHAR* currentExportName; WORD currentExportOrdinal; DWORD eatNameOffset; CHAR* forwardedExport; WCHAR wideModuleName[MAX_PATH]; ULONG c; CHAR* forwardedExportName; moduleBase = RCAST(ModuleBase); // // Retrieve the module DOS header. // dosHeader = RCAST(moduleBase); if (dosHeader->e_magic != 'ZM') { return NULL; } // // Retrieve the module NT headers. // ntHeaders = RCAST(moduleBase + dosHeader->e_lfanew); if (ntHeaders->Signature != 'EP') { return NULL; } // // Get the EAT data directory. // eatDirectoryOffset = ntHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress; eatDirectorySize = ntHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size; eatDirectory = RCAST(moduleBase + eatDirectoryOffset); eatFunctions = RCAST(moduleBase + eatDirectory->AddressOfFunctions); eatOrdinals = RCAST(moduleBase + eatDirectory->AddressOfNameOrdinals); eatNames = RCAST(moduleBase + eatDirectory->AddressOfNames); // // Check if the export name is an ordinal. // if (RCAST(ExportName) < 0xFFFF) { currentExportOrdinal = (WORD)ExportName - eatDirectory->Base; return RCAST(moduleBase + eatFunctions[currentExportOrdinal]); } // // Iterate over every export with a name. // for (i = 0; i < eatDirectory->NumberOfNames; i++) { eatNameOffset = eatNames[i]; currentExportName = RCAST(moduleBase + eatNameOffset); // // Check if the export name matches our desired export. // if (LowUtilities::CmpString(currentExportName, ExportName)) { // // If the function offset lies in the EAT virtual range, it's a forwarded export. // if (eatFunctions[eatOrdinals[i]] > eatDirectoryOffset && eatFunctions[eatOrdinals[i]] < (eatDirectoryOffset + eatDirectorySize)) { forwardedExport = RCAST(moduleBase + eatFunctions[eatOrdinals[i]]); // // Find the period separating the module name and the export name. // forwardedExportName = StrStr(forwardedExport, ".", FALSE); // // Skip the period. // forwardedExportName++; // // Convert the module name to a wide string. // c = 0; while (*forwardedExport != '.') { wideModuleName[c] = (WCHAR)forwardedExport[0]; forwardedExport++; c++; } wideModuleName[c] = '\0'; // // If the remaining function name starts with a #, attempt to convert it to an ordinal number. // if (forwardedExportName[0] == '#') { // // Move the cursor to the next character which should be a digit. // forwardedExportName++; // // Convert the remaining string to a number. // forwardedExportName = RCAST(LowUtilities::stoi(forwardedExportName)); } // // Recursively retrieve the forwarded export. // return LowUtilities::GetProcAddress(wideModuleName, forwardedExportName); } return RCAST(moduleBase + eatFunctions[eatOrdinals[i]]); } } return NULL; } /// /// Retrieve the export of a module. /// /// The name of the module to search. /// The export to find. /// Pointer to export specified by export name. PVOID GetProcAddress ( _In_ CONST WCHAR* ModuleName, _In_ CONST CHAR* ExportName ) { PVOID moduleBase; // // Retrieve the base of the module. // moduleBase = LowUtilities::GetModuleBase(ModuleName); if (moduleBase == NULL) { return NULL; } return LowUtilities::GetProcAddress(moduleBase, ExportName); } } /* MIT License Copyright (c) 2021 Bill Demirkapi Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */