Skip to content

Instantly share code, notes, and snippets.

@mrexodia
Forked from D4stiny/LowUtilities.cpp
Last active September 20, 2023 08:09
Show Gist options
  • Save mrexodia/f2ed348456b4a17202be33fce8c90e3e to your computer and use it in GitHub Desktop.
Save mrexodia/f2ed348456b4a17202be33fce8c90e3e 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>
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_t_t).</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 <bool CaseSensitive = true, bool StartsWith = false, class T = char>
bool
CmpString(
_In_ const T* Str1,
_In_ const T* Str2
)
{
//
// Enumerate every character until we hit a nullptr character.
//
while (*Str1 != '\0' && *Str2 != '\0')
{
auto currentchar1 = *Str1;
auto currentchar2 = *Str2;
if (!CaseSensitive)
{
if (currentchar1 >= 'A' && currentchar1 <= 'Z')
{
currentchar1 = currentchar1 + ('a' - 'A');
}
if (currentchar2 >= 'A' && currentchar2 <= 'Z')
{
currentchar2 = currentchar2 + ('a' - 'A');
}
}
if (currentchar1 != currentchar2)
{
return false;
}
Str1++;
Str2++;
}
//
// Make sure both strings are ending at the same time.
//
if (!StartsWith && (*Str1 != '\0' || *Str2 != '\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 <bool CaseSensitive = true, class T = char>
const T*
StrStr(
_In_ const T* Str1,
_In_ const T* Str2
)
{
//
// Enumerate every character until we hit a null terminator.
//
while (*Str1 != '\0')
{
if (CmpString<CaseSensitive, true>(Str1, Str2))
{
return Str1;
}
Str1++;
}
return nullptr;
}
/// <summary>
/// Retrieve the process process environment block. Used for enumerating loaded modules.
/// </summary>
/// <returns>Pointer to process PEB.</returns>
PEB*
GetProcessPeb()
{
return reinterpret_cast<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, nullptr.</returns>
inline PVOID
GetModuleBase(
_In_ const wchar_t* ModuleName
)
{
//
// Grab the current process's PEB.
//
auto processPeb = GetProcessPeb();
if (processPeb == nullptr)
{
return nullptr;
}
auto processLdr = processPeb->Ldr;
//
// Enumerate the module list.
//
auto headModuleEntry = &processLdr->InMemoryOrderModuleList;
auto currentModuleEntry = headModuleEntry->Flink;
while (currentModuleEntry != headModuleEntry)
{
//
// Retrieve the contained LDR_DATA_TABLE_ENTRY structure.
//
auto currentLdrEntry = CONTAINING_RECORD(currentModuleEntry, FULL_LDR_DATA_TABLE_ENTRY, InMemoryOrderModuleList);
//
// Determine if current entry has the DLL name we're looking for.
//
if (StrStr<false>(currentLdrEntry->BaseDllName.Buffer, ModuleName))
{
//
// Return the base of the module.
//
return currentLdrEntry->DllBase;
}
currentModuleEntry = currentModuleEntry->Flink;
}
return nullptr;
}
/// <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>
inline PVOID
GetProcAddress(
_In_ PVOID ModuleBase,
_In_ const char* ExportName
)
{
auto moduleBase = reinterpret_cast<char*>(ModuleBase);
//
// Retrieve the module DOS header.
//
auto dosHeader = reinterpret_cast<PIMAGE_DOS_HEADER>(moduleBase);
if (dosHeader->e_magic != IMAGE_DOS_SIGNATURE)
{
return nullptr;
}
//
// Retrieve the module NT headers.
//
auto ntHeaders = reinterpret_cast<PIMAGE_NT_HEADERS>(moduleBase + dosHeader->e_lfanew);
if (ntHeaders->Signature != IMAGE_NT_SIGNATURE)
{
return nullptr;
}
if (ntHeaders->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR_MAGIC)
{
return nullptr;
}
//
// Get the EAT data directory.
//
auto eatDirectoryOffset = ntHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
auto eatDirectorySize = ntHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
auto eatDirectory = reinterpret_cast<PIMAGE_EXPORT_DIRECTORY>(moduleBase + eatDirectoryOffset);
auto eatFunctions = reinterpret_cast<DWORD*>(moduleBase + eatDirectory->AddressOfFunctions);
auto eatOrdinals = reinterpret_cast<WORD*>(moduleBase + eatDirectory->AddressOfNameOrdinals);
auto eatNames = reinterpret_cast<DWORD*>(moduleBase + eatDirectory->AddressOfNames);
//
// Iterate over every export with a name.
//
for (DWORD i = 0; i < eatDirectory->NumberOfNames; i++)
{
auto eatNameOffset = eatNames[i];
auto currentExportName = moduleBase + eatNameOffset;
//
// Check if the export name matches our desired export.
//
if (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))
{
auto forwardedExport = moduleBase + eatFunctions[eatOrdinals[i]];
//
// Find the period separating the module name and the export name.
//
auto forwardedExportName = StrStr<false>(forwardedExport, ".");
//
// Skip the period.
//
forwardedExportName++;
//
// Convert the module name to a wide string.
//
auto c = 0;
wchar_t wideModuleName[MAX_PATH]; // UNICODE_STRING was invented for exactly this reason
while (*forwardedExport != '.')
{
wideModuleName[c] = (wchar_t)forwardedExport[0];
forwardedExport++;
c++;
}
wideModuleName[c] = '\0';
//
// Recursively retrieve the forwarded export.
//
return GetProcAddress(wideModuleName, forwardedExportName);
}
return moduleBase + eatFunctions[eatOrdinals[i]];
}
}
return nullptr;
}
/// <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>
inline PVOID
GetProcAddress(
_In_ const wchar_t* ModuleName,
_In_ const char* ExportName
)
{
//
// Retrieve the base of the module.
//
auto moduleBase = GetModuleBase(ModuleName);
if (moduleBase == nullptr)
{
return nullptr;
}
return 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