Hook APIs that imported to program by LoadLibrary/GetProcAddress - c++

I know how I can hook functions from the IAT table, but I have a problem with APIs which were imported by calling LoadLibrary/GetProcAddress functions. I want to know exactly how someone could hook those functions. I realize that I should hook the GetProcAddress function but how can I check the parameters that were passsed to that function?
For example, consider a program which is going to include MessageBoxW via LoadLibrary/GetProcAddress, how can I hook that MessageBoxW and then check the parameters that have been passed to it?
I have searched a lot in StackOverflow and Google, but I couldn't find a step-by-step tutorial about this. So, if you have such a tutorial or article, I would be really grateful to read them.

In order to hook APIs that they are loaded into a binary dynamically with help of LoadLibrary/GetProcAddress, you should intercept return address of the GetProcAddress and name of the functions that passed to it (for example, consider a program try to load MessageBoxA in this way).
In the second step, you should save that original address of MessageBoxA API in a variable like OriginalMessageBoxA.
In the third and final step, you should return address of your modified API (HookedMessageBoxA) to the callee of the GetProcAddress so when the program try to call that address, program redirected to your function. Something like the following one:
VOID* HookedGetProcAddress(HMODULE hModule, LPCSTR lpProcName)
{
if (std::string(lpProcName).compare("MessageBoxA") == 0)
{
OMessageBoxA = (PMessageBoxA)GetProcAddress(hModule, lpProcName);
return HookedMessageBoxA;
}
else
{
return OGetProcAddress(hModule, lpProcName);
}
}
In that moment, caller will go through your HookedMessageBoxA and you can check parameters that passed to MessageBoxA. As folks said, it is kinda same like normal IAT hook with a minor changes and tricks.

Related

Access method's parameter with dll injection

I have a 64bit process, I figured out one of its statically linked library methods.
Source of this method:
int SSL_connect(SSL *s)
{
if (s->handshake_func == 0)
/* Not properly initialized yet */
SSL_set_connect_state(s);
return (s->method->ssl_connect(s));
}
Actual assembly image: click here.
What I want to do is using dll injection in order to access SSL parameter. I'm using x64dbg + ScyllaHide plugin to inject dlls, so any custom injection tools shouldn't be needed. I successfully injected a simple dll into this process, so I think it's enough for this case.
Is there any chance to access the variable from here without any modification of assembly?
Could anyone throw me some bone, please? (I don't ask for code, I just need some hint as I'm rather a newbie to C++ and dll injection world than an expert).
If you can find out the address of the SSL_connect function you can detour it. This means that you can write a JMP instruction at the begin of the method to your patched-method.
If your jumped-to method has the same calling convention and signature you can simply access SSL* and do what you want with it afterwards you can jump back...
To let the jump back work you would need to restore the org code or create a copy of the org method...
Another way would be a Hardware-Break-Point: read for example here.

How to hook an exe function?

I need to get something from a program. And with the help of ollydbg and IDA, I found the "thing" I can get is in a function called sub_HEXHEX.
Now I know how to hook a function from Dll like DrawTextA or other one.
I need to get function address with
HMODULE hmod = LoadLibrary(L"User32.dll");
GetProcAddress(hmod, "DrawTextA")
But when I need to hook this sub_HEXHEX, I confused. I can get that exe's HANDLE, I know the function's Address (that 0x00HEXHEX), but there's no GetProcAddress I can use. I tried use HANDLE + 0x00HEXHEX as function's address, but I think im wrong with 'offset' things.
Here is what I did
DWORD dwPid = GetCurrentProcessId();
hProcess = OpenProcess(PROCESS_ALL_ACCESS, 0, dwPid);
OldA2ECB0 = (sub_A2ECB0)((HMODULE)hProcess + 0xA2ECB0);
pfOldA2ECB0 = (FARPROC)OldA2ECB0;
And sub_A2ECB0
typedef int(*sub_A2ECB0)(LPCSTR param1, int param2);
But pfOldA2ECB0 will be NULL.
My knowledge is poor with C++ and Win32 (English, too), so its toooooo difficult for me.
From what I understand, and I do believe I understand correctly what you want is internal hooking.
I can show you how to do this in 3 simple steps.
These are the things you must understand:
The function shown in IDA is not exported, thus you cannot use GetProcAddress()
You must be within the context of the remote process to hook internal functions
You cannot use libraries like Detours, you must have your own method/function for hooking
These are the steps you must do:
Be withing the context of the remote process, simplest method: inject your dll.
Get the address offset from IDA, in your case is 00A2ECB0.
Simply apply the hook once inside the remote process:
//0xE8 instruction is a relative call instruction
SetCompleteHook(0xE8,0x00A2ECB0,&YOUR_OWN_FUNCTION);
Helper:
void SetCompleteHook(BYTE head,DWORD offset,...)
{
DWORD OldProtect;
VirtualProtect((void*)offset,5,PAGE_EXECUTE_READWRITE,&OldProtect);
if(head != 0xFF)
{
*(BYTE*)(offset) = head;
}
DWORD* function = &offset+1;
*(DWORD*)(offset+1) = (*function)-(offset+5);
VirtualProtect((void*)offset,5,OldProtect,&OldProtect);
}
And that's it really, it's as simple and straightforward as possible in your scenario.
You can go further of course and perform much more complex internal hooking, but for your learning purpose this is a massive step ahead and starting point.
Enjoy!

Which module called my DLL exported function?

Background
I'm developing a C++ windows DLL module that exports a single function
__declspec(dllexport) void Run()
Motivation
I would like to implement some sort of accessing rights to my function. I wish to prevent unauthorized modules from activating my DLL proc.
I don't need a robust/bullet proof mechanism. I only like to "defend" this proc from other modules running under my own app.
Approach
Get the calling module name and decide based on the name if access is granted.
Question
Would this approach suffice?
if so, how do I get the name of the calling module?
if so, how do I get the name of the calling module?
get return address by call _ReturnAddress
get base address of the image that contains this return address -
RtlPcToFileHeader
finally call GetModuleFileName function
so code can be like this
HMODULE hmod;
if (RtlPcToFileHeader(_ReturnAddress(), (void**)&hmod))
{
WCHAR sz[MAX_PATH];
if (GetModuleFileName(hmod, sz, MAX_PATH))
{
DbgPrint("%p %S\n", hmod, sz);
}
}
about - are this work in XP ? yes, but with one note. _ReturnAddress is CL intrinsic - so not depended from os version (for say gcc exist __builtin_return_address (0) ) GetModuleFileName also very old api function and exist in win2000, xp, everywhere. about RtlPcToFileHeader
- it exported (and implemented) in ntdll.dll in all windows versions from xp to latest. also begin from win2003 it also exported from kernel32.dll but implementation here - simply jump to ntdll.RtlPcToFileHeader - so if want use this on xp also - link with ntdll.lib and place it before kernel32.lib in libs order or can get it it runtime by GetProcAddress(GetModuleHandle(L"ntdll"), "RtlPcToFileHeader");
or even if somebody afraid that RtlPcToFileHeader will be removed from ntdll (this is of course no) can use this
GetProcAddress(GetModuleHandle(g_xp ? L"ntdll" : L"kernel32"), "RtlPcToFileHeader");

Using GetProcAddress and EasyHook to hook class methods and constructors

I've had plenty of success using EasyHook to hook system API routines (in C++) out of libraries. These libraries have always been flat and basically filled with globally callable routines. Here is a small sample using MessageBeep() out of the User32.dll library (minus setup code):
HMODULE hUser32 = GetModuleHandle ( L"User32" );
FARPROC TrampolineMethod; // This would have been set to my new replacement trampoline method.
TRACED_HOOK_HANDLE hHook = new HOOK_TRACE_INFO();
NTSTATUS status;
status = LhInstallHook(
GetProcAddress(hUser32, "MessageBeep"),
TrampolineMethod,
(PVOID)0x12345678,
hHook);
This is all works great. The problem is, I now have a need to hook methods out of a class, not just a global function. I don't really care about the object itself, I'm really more interested in examining the parameters of the method and that's it. I don't know how to syntactically identify the routine in the function name parameter for GetProcAddress(), and I'm not even sure if GetProcAddress() supports it. For example, I'd like to hook the Pen::SetColor() method out of the gdiplus.dll library:
HMODULE hGDIPlus = GetModuleHandle ( L"Gdiplus" );
FARPROC TrampolineMethod; // This would have been set to my new replacement trampoline method.
TRACED_HOOK_HANDLE hHook = new HOOK_TRACE_INFO();
NTSTATUS status;
status = LhInstallHook(
GetProcAddress(hGDIPlus, "Pen.SetColor"), // this is probably wrong or not possible here
TrampolineMethod,
(PVOID)0x12345678,
hHook);
This doesn't work of course and I don't think the GetProcAddress(hGDIPlus, "Pen.SetColor") is correct. How do I specify a member function of a class to GetProcAddress()? Is this even possible? Also, how would this look if I wanted to hook a constructor such as Pen::Pen()?
The Portable Executable (PE) format that Windows uses doesn't really supports exporting or importing objects or their methods, so that's not what GdiPlus (or any other DLL) uses internally. The object notation is probably an abstraction implemented in the import library for the DLL.
If you take a look at GdiPlus's export table with the Dependency Walker tool (Windows SDK), or similar, you will see
GdipGetPenColor
GdipSetPenColor
etc.
So it is basically no different than the legacy exports, like MessageBeep.

How does one read a localized name from the registry?

Consider the following registry export:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\WinSock2\Parameters\Protocol_Catalog9\Catalog_Entries\000000000001]
;...
"ProtocolName"="#%SystemRoot%\\System32\\wshtcpip.dll,-60100"
The intention here appears to be for someone to load the DLL in question, and use some form of API retrieve the actual name. But I don't know what that API is :/
I'd like to avoid loading the DLL into my address space (and thus call DLL_PROCESS_ATTACH) if at all possible; can't really trust third party DLLs to be trustworthy.
RegLoadMUIString will do the necessary for you. Note however, that it was introduced in Vista so won't help if you need to support XP.
If you want to avoid code in the DLL running whilst you extract resources, use LoadLibraryEx passing LOAD_LIBRARY_AS_IMAGE_RESOURCE | LOAD_LIBRARY_AS_DATAFILE, or possibly LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE. Once you have done that, you can call LoadString to extract the MUI value.
This is going to help:
HMODULE hModule = LoadLibrary(_T("wshtcpip.dll")); // LoadLibraryEx is even better
TCHAR pszValue[1024] = { 0 };
INT nResult = LoadString(hModule, 60100, pszValue, _countof(pszValue));
LoadString will take care of downloading resource from MUI, if needed. LoadString uses thread locale, which you might want to override prior to the call.
Also: Loading Language Resources on MSDN.