Fully automatic Windows API hashing in C
Existing Windows API hashing implementations typically require use of C++ (consteval is very useful), and the manual definitions of function declarations. Which is very troublesome. Especially for large existing projects.
Using this method, we automate everything. On first run, the exe will read its IAT, and replace every name with its hash (and some metadata) (prefixed with a null byte to prevent anything from showing up in PE analysis tools). Then we replace the u1.AddressOfData
of the first thunk with a null, and save the original value elsewhere, this is required so the Windows PE loader does not see the hash and refuse to load the PE because it cannot find the hash in the DLLs. Then we dump to disk, write to output.exe
Then, on subsequent runs, we will walk the IAT and find our hashed functions, then replace and resolve them manually. This gives you basically all the benefits of API hashing, with basically none of the drawbacks (manual function declaration, manual hashing if no C++ consteval).
Step 1: Run x86_64-w64-mingw32-gcc self.c -Wl,-emain2 -s -Os
(we change main function for convenience)
Step 2: Run a.exe
to perform the actual hashing
Step 3: Run output.exe
to run your actual code
- The DLL imports are not removed, unlike the standard
LoadLibraryA
+GetProcAddress
methods. But usually we don't hash the dll name anyways, so it's not too bad
To https://www.ired.team/offensive-security/defense-evasion/windows-api-hashing-in-malware for the skeleton code
Note that hash collisions ARE possible, and may occur. I have already checked through kernel32, user32, and ntdll for collisions and have not found any, but it is definitely possible.