Skip to content

Instantly share code, notes, and snippets.

@wulfgarpro
Forked from D4stiny/LowUtilities.cpp
Created November 22, 2023 02:32
Show Gist options
  • Save wulfgarpro/6c9d01583eded617fdf91a5e9f1a2ece to your computer and use it in GitHub Desktop.
Save wulfgarpro/6c9d01583eded617fdf91a5e9f1a2ece to your computer and use it in GitHub Desktop.
A dependency-less implementation of GetModuleHandle and GetProcAddress.
//
// 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 <Windows.h>
#include <winternl.h>
#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;
/// <summary>
/// A simple string comparison function to support CRT-less environments.
/// </summary>
/// <typeparam name="T">The type of character pointer (CHAR, WCHAR).</typeparam>
/// <param name="Str1">The first string to compare.</param>
/// <param name="Str2">The second string to compare.</param>
/// <param name="CaseSensitive">TRUE if case sensitive comparison, FALSE otherwise.</param>
/// <param name="StartsWith">FALSE if should enforce that both strings end at same time, TRUE otherwise.</param>
/// <returns>TRUE if equal, FALSE otherwise.</returns>
template <class T>
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<T*>(Str1);
currentStr2 = CCAST<T*>(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;
}
/// <summary>
/// Attempts to find first instance of Str2 in Str1. God I hate writing code for a CRT-less environment :(
/// </summary>
/// <typeparam name="T">The type of character.</typeparam>
/// <param name="Str1">The string to search.</param>
/// <param name="Str2">The string to search for.</param>
/// <param name="CaseSensitive">TRUE if case sensitive comparison, FALSE otherwise.</param>
/// <returns>Pointer to Str2 inside Str1.</returns>
template <class T>
T* StrStr (
_In_ CONST T* Str1,
_In_ CONST T* Str2,
_In_ CONST BOOL CaseSensitive = TRUE
)
{
T* currentStr1;
currentStr1 = CCAST<T*>(Str1);
//
// Enumerate every character until we hit a NULL character.
//
while (*currentStr1 != '\0')
{
if (LowUtilities::CmpString<T>(currentStr1, Str2, CaseSensitive, TRUE))
{
return currentStr1;
}
currentStr1++;
}
return NULL;
}
/// <summary>
/// A bad implementation of converting a string to an integer.
/// </summary>
/// <param name="String">The string to parse.</param>
/// <returns>An integer.</returns>
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;
}
/// <summary>
/// Retrieve the process process environment block. Used for enumerating loaded modules.
/// </summary>
/// <returns>Pointer to process PEB.</returns>
PEB*
GetProcessPeb (
VOID
)
{
return RCAST<PEB*>(__readgsqword(0x60));
}
/// <summary>
/// Find the DLL base of a given Module.
/// </summary>
/// <param name="ModuleName">The name of the module.</param>
/// <returns>If module is loaded, the DLL base of the module. Otherwise, NULL.</returns>
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<WCHAR>(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
);
/// <summary>
/// Retrieve the export of a module.
/// </summary>
/// <param name="ModuleBase">The base address of the module.</param>
/// <param name="ExportName">The export to find.</param>
/// <returns>Pointer to export specified by export name.</returns>
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<ULONG_PTR>(ModuleBase);
//
// Retrieve the module DOS header.
//
dosHeader = RCAST<PIMAGE_DOS_HEADER>(moduleBase);
if (dosHeader->e_magic != 'ZM')
{
return NULL;
}
//
// Retrieve the module NT headers.
//
ntHeaders = RCAST<PIMAGE_NT_HEADERS>(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<PIMAGE_EXPORT_DIRECTORY>(moduleBase + eatDirectoryOffset);
eatFunctions = RCAST<DWORD*>(moduleBase + eatDirectory->AddressOfFunctions);
eatOrdinals = RCAST<WORD*>(moduleBase + eatDirectory->AddressOfNameOrdinals);
eatNames = RCAST<DWORD*>(moduleBase + eatDirectory->AddressOfNames);
//
// Check if the export name is an ordinal.
//
if (RCAST<DWORD>(ExportName) < 0xFFFF)
{
currentExportOrdinal = (WORD)ExportName - eatDirectory->Base;
return RCAST<PVOID>(moduleBase + eatFunctions[currentExportOrdinal]);
}
//
// Iterate over every export with a name.
//
for (i = 0; i < eatDirectory->NumberOfNames; i++)
{
eatNameOffset = eatNames[i];
currentExportName = RCAST<CHAR*>(moduleBase + eatNameOffset);
//
// Check if the export name matches our desired export.
//
if (LowUtilities::CmpString<CHAR>(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<CHAR*>(moduleBase + eatFunctions[eatOrdinals[i]]);
//
// Find the period separating the module name and the export name.
//
forwardedExportName = StrStr<CHAR>(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<CHAR*>(LowUtilities::stoi(forwardedExportName));
}
//
// Recursively retrieve the forwarded export.
//
return LowUtilities::GetProcAddress(wideModuleName, forwardedExportName);
}
return RCAST<PVOID>(moduleBase + eatFunctions[eatOrdinals[i]]);
}
}
return NULL;
}
/// <summary>
/// Retrieve the export of a module.
/// </summary>
/// <param name="ModuleName">The name of the module to search.</param>
/// <param name="ExportName">The export to find.</param>
/// <returns>Pointer to export specified by export name.</returns>
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.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment