How to hook an exe function? - c++

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!

Related

Hook APIs that imported to program by LoadLibrary/GetProcAddress

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.

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.

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.

System-wide hooks with MHook

I have this project where I hook some Windows functions (GetOpenFileNameA, GetOpenFileNameW, GetSaveFileNameA, GetSaveFileNameW) with MHook library. This is the code I use to install the hooks.
for(size_t i = 0; i < FunctionsCount; ++i)
{
HMODULE hModule = GetModuleHandleA(Function[i].ModuleName);
//[1]
if( !hModule )
return FALSE;
*Function[i].Original = GetProcAddress(hModule, Function[i].Name);
if(*Function[i].Original == NULL)
return FALSE;
if(!Mhook_SetHook(Function[i].Original, Function[i].Hooked))
return FALSE;
}
It is called from DllMain on DLL_PROCESS_ATTACH reason.
Now, when I inject my Dll using the CreateRemoteThread approach it works pretty well, but when I want to set up the system-wide hooks using LoadAppInit_DLLs mechanism my hooks doesn't works. After hours debugging I found that the reason is that my Dll is loaded BEFORE comdlg32.dll (which is the module where these functions are), and then the statement [1] returns false, then my Dll is not loaded.
The solution I've so far is to call LoadLibrary if [1] returns false.
HMODULE hModule = GetModuleHandleA(Function[i].ModuleName);
//[2]
if( !hModule )
{
LoadLibraryA(Function[i].ModuleName);
hModule = GetModuleHandleA(Function[i].ModuleName);
}
I've found many site where is said this is evil and I agree (even when works fine). Also if a process doesn't use common dialogs at all I'm hooking functions that will never be called.
If anybody could help, maybe a workaround or an explanation of another way to set-up global hooks it will be appreciated. Thanks in advance
You need to hook LoadLibraryXXX functions and after successful their execution check whether your module has been loaded (calling GetModuleHandle) and hook it if it is loaded.
Also it is a good idea to pin hooked dlls so they are not unloaded anymore.

Hook ishellfolder enumobjects

I am trying to hook the function enumobjects in Ishellfolder .
I am doing it because I want to display the user non existing files in explorer.
I was success to hook FindNextFile and FindFirstFile but unfortunately this function not always call by explorer according to this question Which APIs are used by explorer.exe in Windows 7 to list files?
Now I try to hook IShellFolder::EnumObjects so I hook
MyCoCreateInstance(REFCLSID rclsid, LPUNKNOWN pUnkOuter, DWORD dwClsContext, REFIID riid, LPVOID *ppv)
And inside this function I have the following code:
if (IsEqualCLSID(rclsid, (REFGUID) __uuidof (IShellFolder)) ||
IsEqualCLSID(rclsid, (REFGUID) __uuidof (IShellFolder2)) ||
IsEqualCLSID(rclsid, (REFGUID) CLSID_ShellDesktop) ||
IsEqualCLSID(rclsid, (REFGUID) IID_IShellFolder) )
{
PDEBUG(L"IID_IShellFolder.2");
IShellFolderCast *shellFolder = (IShellFolderCast *) *ppv;
orig_EnumObjects = (type_EnumObjects) GetInterfaceMethod(shellFolder->lpVtbl, 4);
if (!Mhook_SetHook((void **) &orig_EnumObjects, MyEnumObjects))
{
PDEBUG(L". CoCreateInstance. Failed to set EnumObjects!");
}else
{
PDEBUG(L". CoCreateInstance. success to set EnumObjects!");
}
}
but it never go inside that if
anyone know why?
The following lays out how the windows API enumerates files in a directory. Look here.
[EDIT]
Missed the intent of your question on my first entry. You want to know how to trap an event when iShellFolder is accessed? You have probably already Looked Here?. It has some example code, and discusses topics around what I think may be useful.
Just change to
if (IsEqualCLSID(rclsid, (REFGUID) CLSID_ShellFSFolder) )
and now it works