try catch on reflective loaded dll - c++

I was testing this injection technique (Reflective dll injection) and found that any try/catch on the code rise an unhandle windows error (KERNELBASE.dll, code error e06d7363) and the host process dies.
I was injecting a test dll with a basic function.
the work flow is:
print "starting..." and then dies.
My dll.
bool WINAPI DllMain(HINSTANCE hinstDLL, DWORD dwReason, LPVOID lpReserved)
{
bool bReturnValue = TRUE;
switch (dwReason)
{
case DLL_PROCESS_ATTACH:
function();
break;
}
return bReturnValue;
}
void function()
{
cout << "starting..." << std::endl;
try
{
throw std::exception();
}
catch (...)
{
cout << " exception... " << std::endl;
}
}
any technical explanation?

This is likely because the exception handling is not properly set up when you do the injection. See https://hackmag.com/uncategorized/exceptions-for-hardcore-users/.
What library are you using for injection? Does it support SEH? Or are you registering the handlers properly if you are doing it yourself?
I suspect however the issue is more complexe as I am having a similar issue with standard in-memory DLL loading with a lib (SimplePELoader) that supports SEH in my standard test case.

Related

Prevent exit from DllMain with dll hijacking in c++

Hi i'm testing dll hijacking scenario for the educational purpose and i have problem when DllMain loaded i want to create something that keeps my method (Thread) running but the problem is even if i create a new thread still when DllMain reaches at the end my thread killed with it !
if i do something like WaitForSingleObject or while (1) {} it causes the deadlock of course
Also i want to prevent the Main Process (executable file) to exit ! because when the applications loads all modules after that it close him self ! and that's not what i want ! i want to keep the application running . as long as the application is running my thread is live
any thoughts or advise ?
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
if (ul_reason_for_call == DLL_PROCESS_ATTACH)
{
CreateThread(0, 0, (LPTHREAD_START_ROUTINE)LiveBackgroundListenerFunction, 0, 0, 0);
}
//while (1) {} #DeadLock !!!
//WaitForSingleObject(hdl, 100); #DeadLock !!!
return TRUE;
void LiveBackgroundListenerFunction()
{
While(1)
{
Sleep(5000);
//Do Somthing......
}
}
thanks in advance

detours vs MinHook for DLL injection

I have succefully hooked a gog game (DRM free) with this code:
bool WINAPI DllMain(HMODULE hModule, DWORD dwReason, LPVOID lpReserved)
{
static HMODULE libogg_ori = nullptr;
int FFBInitDelayInMillliseconds;
char* DLLFileName;
std::string DLLFile = "libogg_ori.dll";
switch (dwReason)
{
case DLL_PROCESS_ATTACH:
// Load dll
// Initialize config File
Local_InitConfigComplete = Init_Config();
// Delay for timer that initialize the Force Feedback
FFBInitDelayInMillliseconds = Config.FFBDelayBeforeInit * 1000;
DLLFileName = R"(libogg_ori.dll)";
if (FS::File_Exist(DLLFileName))
{
LF::Log_Update("File DLL exit");
// Load the System DLL
d3d9dll = LoadLibraryA(DLLFileName);
if (d3d9dll == NULL)
LF::Log_Update("Load DLL error");
}
else
{
LF::Log_Update("File DLL not exist");
}
// Initilize Detour
if (Local_InitConfigComplete)
Local_InitConfigComplete = Init_Detour();
break;
case DLL_PROCESS_DETACH:
// Close the DLL
LF::Log_Update("Closing session ...");
LF::Log_Update("Release hook in progress ...");
// unhook
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
// this will hook the sound function
DetourDetach(&(LPVOID&)AddressOfHookSoundFunction, &HookSoundFileSub);
// this will hook the damage function (if present in configuration)
if (AddressOfHookDamageFunction>0)
DetourDetach(&(LPVOID&)AddressOfHookDamageFunction, &HookDamageSub);
if (DetourTransactionCommit() == NO_ERROR)
LF::Log_Update(LOG_FLAG_DONE);
else
LF::Log_Update(LOG_FLAG_ERROR, "Warning Hooking not relased.");
LF::Log_Update("Session closed.");
break;
}
return true;
}
bool Init_Detour()
{
// Initialize Detours
// we will find the function/s to hook with IDA pro.
try
{
LF::Log_Update("Initialize Hooking ...");
AddressOfHookSoundFunction = std::strtoul(Config.GameFileSoundOffsetPos.c_str() ,NULL,16); // BattleZoneRedux 0x43AA30
if (Config.GameFileDamageOffsetPos.size() > 1)
AddressOfHookDamageFunction = std::strtoul(Config.GameFileDamageOffsetPos.c_str(), NULL, 16); // BattleZoneRedux 0x49B430
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
// this will hook the sound function
DetourAttach(&(LPVOID&)AddressOfHookSoundFunction, &HookSoundFileSub);
// If is present a offset for hook the damage
if (AddressOfHookDamageFunction!=0)
DetourAttach(&(LPVOID&)AddressOfHookDamageFunction, &HookDamageSub);
if (DetourTransactionCommit() == NO_ERROR)
{
LF::Log_Update(LOG_FLAG_DONE);
return true;
}
else
{
LF::Log_Update(LOG_FLAG_ERROR, "Hooking not initilizing.");
return false;
}
}
catch (const std::exception&)
{
LF::Log_Update(LOG_FLAG_ERROR, "Error while initialize Detour.");
return false;
}
}
to do it I have found a custom version of libogg.dll and d3d9.dll (DLL injection). Both work perfectly.
But when I used the some code to another GOG game with DRM free, to inject it with libogg.dll the game crash always on this row:
DetourDetach(&(LPVOID&)AddressOfHookSoundFunction, &HookSoundFileSub);
In all my test with the game that work, never crash in this row even if AddressOfHookSoundFunction is relative to a non-existent address.
In short independently by AddressOfHookSoundFunction and HookSoundFileSub that second game crash always.
Here the difference between the two games:
The first was made in 2017 and the second was made in 2018 by the some software house.
If I disassambly with IDA the first game I see always sub_xxxxxx , but in the second game sometimes I see the real name of the functions and not the address. So I suppose it was done by a more recent visual c++ version, and for this reason it may not work.
On many forums the people suggest to use MinHook becouse is better than detours, but I don't known why and if this is true for all cases.
Can someone have the some experience in situations like this ?
If the solution is use minhook, can someone help me to re-write this code:
AddressOfHookSoundFunction = std::strtoul(Config.GameFileSoundOffsetPos.c_str() ,NULL,16); // BattleZoneRedux 0x43AA30
if (Config.GameFileDamageOffsetPos.size() > 1)
AddressOfHookDamageFunction = std::strtoul(Config.GameFileDamageOffsetPos.c_str(), NULL, 16); // BattleZoneRedux 0x49B430
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
// this will hook the sound function
DetourAttach(&(LPVOID&)AddressOfHookSoundFunction, &HookSoundFileSub);
// If is present a offset for hook the damage
if (AddressOfHookDamageFunction!=0)
DetourAttach(&(LPVOID&)AddressOfHookDamageFunction, &HookDamageSub);
if (DetourTransactionCommit() == NO_ERROR)
{
LF::Log_Update(LOG_FLAG_DONE);
return true;
}
else
{
LF::Log_Update(LOG_FLAG_ERROR, "Hooking not initilizing.");
return false;
}
with MinHook ?
Thank you !

Windows DLL Backwards Compatibility

I am using MS detours 3.0 Express to create a DLL that detours a function of an application.
I have used StudPE to enter the dll API and hook it to the application.
Everything works fine except for it won't work on windows XP.
Windows 7 works fine though. And I'm running out of idea's as to why it just won't work on windows XP.
I compiled it on a Windows 7 x64 machine with Microsoft Visual Studio 2012.
I'm calling the DllMain My code is: (just the relevant code - incomplete)
extern "C" __declspec(dllexport) INT APIENTRY DllMain(HMODULE hDLL, DWORD Reason, LPVOID Reserved)
{
switch(Reason) {
case DLL_PROCESS_ATTACH: //Do standard detouring
DisableThreadLibraryCalls(hDLL);
//AllocConsole();
//
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourAttach(&(PVOID&)pSend, MySend);
if(DetourTransactionCommit() == NO_ERROR) {
cout << "[" << MySend << "] successfully detoured." << endl;
}
break;
case DLL_PROCESS_DETACH:
DetourTransactionBegin(); //Detach
DetourUpdateThread(GetCurrentThread());
DetourDetach(&(PVOID&)pSend, MySend);
DetourTransactionCommit();
break;
}
return TRUE;
}
On WinXP nothing happens when I try to run the hooked application.

Calling a COM dll from c++, "Class Not Registered"

I have created a COM dll in Microsoft Visual Basic 2008. I am trying to call this dll from a C++ project. In the C++ I used "#import U:\path...\MyComDll.tlb" I then used the following code to the DisplayMessage() method.
FB::variant CmdAccessAPI::filePSV(std::string file)
{
CoInitialize(NULL);
try
{
_MyComClassPtr spIMyComClass;
HRESULT hr = spIMyComClass.CreateInstance(__uuidof(_MyComClass));
if (FAILED(hr)) throw _com_error(hr);
spIMyComClass->DisplayMessage();
}
catch (std::exception& e)
{
CString strMsg(e.what());
MessageBox(NULL, strMsg, L"Error", MB_OK);
}
catch (_com_error& e)
{
CString strMsg;
strMsg = (TCHAR*) e.Description();
strMsg += _T("\n");
strMsg += (TCHAR*) e.ErrorMessage();
MessageBox(NULL, strMsg, L"COM Error", MB_OK);
}
CoUninitialize();
return "test";
}
When I call this function I get a Class Not Registered error. I have tried to register the dll using regsvr32 and I get the message "MyComDll.dll was loaded, but the DLLREgeisterServer entry point was not found. This file can not be registered."
How do I register the class and get this to work?
Try registering it using admin privileges,
Right click on the Command prompt and choose run as administrator, and give the systems 32 path.
Then use regsvr32 xyz.dll
If you can't register it, there are two possibilities
You are missing a dependent library. Download dependency walker and see what's missing. Some of the ones that are marked missing are red herrings (ieshims.dll for example), but one of them may be yours
Something went way off the rails in your COM setup. You can debug your dll as its being registered and dig into the ATL code where its failing.
You need to use regsvr32 to register the DLL, as you suspect.
However, the error its giving suggests that either the DLL doesn't have the stub included (and so cannot register itself) or you're trying to register the library, not the stub.
Make sure your VS project and the code is set up to include the proxy/stub functions in your DLL, or make sure you register the proxy DLL.
**include the below code** and export these functions with .def file
wchar_t *convertCharArrayToLPCWSTR(const char* charArray)
{
wchar_t* wString=new wchar_t[4096];
MultiByteToWideChar(CP_ACP, 0, charArray, -1, wString, 4096);
return wString;
}
BOOL Register( HKEY mainKey,const char *subKey,LPCTSTR val_name, DWORD dwType,char * chardata,DWORD dwDataSize)
{
HKEY hk;
if (ERROR_SUCCESS != RegCreateKey(mainKey,convertCharArrayToLPCWSTR(subKey),&hk) )
return FALSE;
LPCTSTR data=convertCharArrayToLPCWSTR(chardata);
if (ERROR_SUCCESS != RegSetValueEx(hk,val_name,0,dwType,(CONST BYTE *)data,2*dwDataSize))
return FALSE;
if (ERROR_SUCCESS != RegCloseKey(hk))
return FALSE;
return TRUE;
}
HRESULT __stdcall DllRegisterServer(void)
{
WCHAR *lpwszClsid;
char szBuff[MAX_PATH]="new multiplication Algorithm";
char szClsid[MAX_PATH]="", szInproc[MAX_PATH]="",szProgId[MAX_PATH];
char szDescriptionVal[256]="";
StringFromCLSID(CLSID_MultiplicationObject,&lpwszClsid);
sprintf(szClsid,"%S",lpwszClsid);
sprintf(szInproc,"%s\\%s\\%s","clsid",szClsid,"InprocServer32");
sprintf(szProgId,"%s\\%s\\%s","clsid",szClsid,"ProgId");
sprintf(szDescriptionVal,"%s\\%s","clsid",szClsid);
Register (HKEY_CLASSES_ROOT,szDescriptionVal,NULL,REG_SZ,szBuff,strlen(szBuff));
//InprocServer32
GetModuleFileNameA(g_hModule,szBuff,sizeof(szBuff));
Register (HKEY_CLASSES_ROOT,szInproc,NULL,REG_SZ,szBuff,strlen((szBuff)));
//ProgId
strcpy(szBuff,multiplicationObjProgId);
Register (HKEY_CLASSES_ROOT,szProgId,NULL,REG_SZ,szBuff,strlen(szBuff));
return 1;
}
HRESULT __stdcall DllUnregisterServer(void)
{
WCHAR *lpwszClsid;
char szBuff[MAX_PATH]="new multiplication Algorithm";
char szClsid[MAX_PATH]="", szInproc[MAX_PATH]="",szProgId[MAX_PATH];
char szDescriptionVal[256]="";
StringFromCLSID(CLSID_MultiplicationObject,&lpwszClsid);
sprintf(szClsid,"%S",lpwszClsid);
sprintf(szInproc,"%s\\%s\\%s","clsid",szClsid,"InprocServer32");
sprintf(szProgId,"%s\\%s\\%s","clsid",szClsid,"ProgId");
sprintf(szDescriptionVal,"%s\\%s","clsid",szClsid);
RegDeleteKey(HKEY_CLASSES_ROOT,convertCharArrayToLPCWSTR(szInproc));
RegDeleteKey(HKEY_CLASSES_ROOT,convertCharArrayToLPCWSTR(szProgId));
RegDeleteKey(HKEY_CLASSES_ROOT,convertCharArrayToLPCWSTR(szDescriptionVal));
return 1;
}
This kind of dependency problem can happen when there is a mismatch in vendor architecture.
For example, you may have registered the 32bit DLL but your program is 64bit or vice-versa.

Get path of current module after using RemoteThread

I need to get the current path of the module where my code executed (dll). I've made a dll injection from .NET into a native process and used RemoteThread.
I have tried getcwd, GetCurrentDirectory, GetModuleHandle.
Also tried this solution. But it doesn't work either. I get an empty string with the length of MAX_PATH.
https://stackoverflow.com/questions/6719140/get-path-of-current-module-after-using-remotethread/6719210#6719210
I already opened a thread but I can not login to my email to get the id.
Sorry but anyway thanks for your answer. I will rate this time!
C# Injection
public static IntPtr InjectLibrary(
Process targetProcess,
string libraryPath)
{
var libaryPathBytes = Encoding.GetBytes();
var hProc = NativeMethods.OpenProcess()
var hMemory = NativeMethods.VirtualAllocEx()
NativeMethods.WriteProcessMemory()
var hLoadLib = NativeMethods.GetProcAddress()
var hThread = NativeMethods.CreateRemoteThread()
return hThread;
}
Native Library
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
{
DWORD threadId;
CreateThread( NULL, 0, Bootstrap, NULL, 0, &threadId);
break;
}
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
DWORD WINAPI Bootstrap(LPVOID arg) {
DWORD currentProcessID = GetCurrentProcessId();
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, currentProcessID);
MODULEENTRY32 entry;
Module32First(snapshot, &entry);
MessageBox(NULL, entry.szLibPath, L"", MB_OK);//entry.szLibPath is empty string with the length if MAX_PATH like □□□□□□□□□□□□□□□□□□□□□□□....
HMODULE module = entry.hModule;
wchar_t currentPath[MAX_PATH];
GetModuleFileName(module, currentPath, MAX_PATH);
MessageBox(NULL, currentPath, L"", MB_OK);//currentPath isempty string with the length if MAX_PATH like □□□□□□□□□□□□□□□□□□□□□□□....
//all other options give me the same string or the executable path
return 0;
}
There's a "hidden" tool helper library mentionned by Raymond Chen that gets around several quirks in the Win32 APi. It seems you can use that to fetch the handle to the first module associated to a process (presumably the original executable). You can use that handle to get the path to the executable.
Looks something like:
// Get a listing of modules loaded in the process.
DWORD process = ...;
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, process);
// Get the handle to the first module loaded by that process.
MODULEENTRY32 entry;
Module32First(snapshot, &entry);
HANDLE module = entry.hModule;
// Get the path to the executable/DLL file containing the module.
GetModuleFileName(module, ...);
Edit: I've tried a complete example. You get an empty string using GetModuleFileName() because the module handle was not loaded using the LoadLibrary() function call.
However, it seems the MODULEENTRY32 structure already provides the full path to the module in its szExePath member. The following example works for me:
#include <Windows.h>
#include <TlHelp32.h>
#include <iostream>
int main ( int, char ** )
{
// Substitute `process` with appropriate process ID.
const ::DWORD process = ::GetCurrentProcessId();
const ::HANDLE snapshot =
::CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, process);
if ( snapshot == INVALID_HANDLE_VALUE ) {
std::cerr << "Couldn't get snapshot!" << std::endl;
return (EXIT_FAILURE);
}
// Get 1st module info.
::MODULEENTRY32W module;
::ZeroMemory(&module, sizeof(module));
module.dwSize = sizeof(module);
const ::BOOL result = Module32FirstW(snapshot, &module);
if ( result == FALSE )
{
// Handle errors.
const ::DWORD error = ::GetLastError();
std::cerr
<< "Couldn't get 1st module (" << error << ")."
<< std::endl;
return (EXIT_FAILURE);
}
std::wcout
<< module.szExePath << std::endl;
// Cleanup.
::CloseHandle(snapshot);
return (EXIT_SUCCESS);
}