Application Crashes when hooked with MS Detours and Injected with Withdll.exe - c++

I am hooking FindNextFile() using MS Detours. I have configured the Detours library successfully and wrote a dll named "Detuors.dll" and an application named "FNFSend.exe". The following is the code:
DLL:
#include <cstdio>
#include <stdio.h>
#include <windows.h>
#include "detours.h"
#pragma comment (lib,"detours.lib")
//Prototypes
extern "C" __declspec(dllexport) BOOL (WINAPI *pFNF)(HANDLE hFindFile, LPWIN32_FIND_DATA lpFindFileData) = FindNextFile;
extern "C" __declspec(dllexport) BOOL WINAPI MyFNF(HANDLE hFindFile, LPWIN32_FIND_DATA lpFindFileData);
//Log File
FILE* pFNFLogFile;
int counter = 0;
INT APIENTRY DllMain(HMODULE hDLL, DWORD Reason, LPVOID Reserved)
{
switch(Reason)
{
case DLL_PROCESS_ATTACH:
DisableThreadLibraryCalls(hDLL);
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourAttach(&(PVOID&)pFNF, MyFNF);
if(DetourTransactionCommit() == NO_ERROR)
OutputDebugString("FNF() detoured successfully");
else
OutputDebugString("FNF() not detoured");
break;
case DLL_PROCESS_DETACH:
DetourTransactionBegin(); //Detach
DetourUpdateThread(GetCurrentThread());
DetourDetach(&(PVOID&)pFNF, MyFNF);
DetourTransactionCommit();
break;
case DLL_THREAD_ATTACH:
DisableThreadLibraryCalls(hDLL);
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourAttach(&(PVOID&)pFNF, MyFNF);
if(DetourTransactionCommit() == NO_ERROR)
OutputDebugString("FNF() detoured successfully");
else
OutputDebugString("FNF() not detoured");
break;
case DLL_THREAD_DETACH:
break;
}
return TRUE;
}
//Open file, write contents, close it
extern "C" __declspec(dllexport) int WINAPI MyFNF(HANDLE hFindFile, LPWIN32_FIND_DATA lpFindFileData)
{
counter ++;
fopen_s(&pFNFLogFile, "C:\\FNFLog.txt", "a+");
fprintf(pFNFLogFile, "%s\n", counter);
fclose(pFNFLogFile);
return pFNF(hFindFile, lpFindFileData);
}
Both the codes compiled successfully with no errors. The application calls FindNextFile() recursively and the dll hooks it and write the counter to a file.
I then used the tool named "withdll.exe" that is provided by detours library itself to create a process with a dll injected in it. So I injected my dll into the application using command:
withdll /d:Detuors.dll "C:\FNFSend.exe"
After injection, the function is hooked successfully, i.e. the file is made in the dirctory but suddenly the application crashes. After debugging in visual studio, I saw the exception in "output.c" as follows:
Unhandled exception at 0x6265984f (msvcr90d.dll) in FNFSend.exe: 0xC0000005:
Access violation reading location 0x00000001.
Kindly help in rectifying the problem.

%s is not a valid format string for printing out a number. Use %d instead.
By specifying %s you're telling fprintf to read the memory at address counter as a string. The first value you try calling fprintf with is 1 which is why there is an access violation at address 0x00000001.

Related

Dll not being loaded in Firefox but loads in custom application

I posted a recent question on SO about code injection, this one is similar but not the same. I am injecting dll into Firefox, it injects successfully but the code in the DLL doesn't run. If i inject the same code into a custom application, it works. Why might that be. This is the code that I'm using.
Injector.exe // the file that's injecting the code
#include <stdio.h>
#include <windows.h>
#define procId 2844
#define dllname "dllinject.dll" // located in same directory
int main()
{
HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, false, procId);
LPVOID allocated = (LPVOID)VirtualAllocEx(hProc, NULL, strlen(dllname), MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE);
WriteProcessMemory(hProc, (LPVOID)allocated, dllname, strlen(dllname), NULL);
LPVOID libaddr = (LPVOID)GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");
CreateRemoteThread(hProc, NULL, NULL, (LPTHREAD_START_ROUTINE)libaddr, NULL, NULL);
CloseHandle(hProc);
return 0;
}
Simpleinjected.exe // the file being injected
#include <stdio.h>
int main()
{
printf("Hello");
return 0;
}
dllinject.dll
#include <windows.h>
int message(const char *msg)
{
MessageBox(NULL, msg, "Message from Dll", MB_OK);
return 0;
}
BOOL WINAPI DLLMain(HINSTANCE hInstDll, DWORD ulReason, LPVOID lpReserved)
{
switch(ulReason)
{
case DLL_PROCESS_ATTACH:
message("process attach");
break;
case DLL_THREAD_ATTACH:
message("thread attach");
break;
case DLL_PROCESS_DETACH:
message("process detach");
break;
case DLL_THREAD_DETACH:
message("thread detach");
break;
}
return true;
}
It works when injected into simpleinjected.exe but when injected in Firefox, nothing happens even though the dll is injected successfully.
I cannot reproduce your observations. I was able to inject dllinject.dll into other processes (also firefox) but I've never seen a message box.
After a bit of digging I found that your DLLMain is spelled wrong. Change it into DllMain and you'll see message boxes in Firefox.
By the way: You propably want to change MessageBox into MessageBeep since FireFox creates/destroys a lot of threads... (this is annoying even for a quick test!)

C++ Code Injection crashes injected application

I'm trying to inject a simple executable into another executable that I made, unfortunately, whenever I inject the code into the executable, it says 'simpleinjected.exe has stopped working' then it closes. I'm using CreateRemoteThread to inject the code. This is what I have done so far.
Injector.exe // the file that's injecting the code
#include <stdio.h>
#include <windows.h>
#define procId 2844
#define executable "executable.exe" // located in same directory
int main()
{
HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, false, procId);
LPVOID allocated = (LPVOID)VirtualAllocEx(hProc, NULL, strlen(executable), MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE);
WriteProcessMemory(hProc, (LPVOID)allocated, executable, strlen(executable), NULL);
LPVOID libaddr = (LPVOID)GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");
CreateRemoteThread(hProc, NULL, NULL, (LPTHREAD_START_ROUTINE)libaddr, NULL, NULL);
CloseHandle(hProc);
return 0;
}
Simpleinjected.exe // the file being injected
#include <stdio.h>
int main()
{
printf("Hello");
return 0;
}
executable.exe // the executable being injected into simpleinjected
#include <windows.h>
int main()
{
MessageBox(NULL, "Injected successfully", "Code Injection", MB_OK);
return 0;
}
The message is not displaying and simpleinjected.exe crashes. The crash shows that the code was inserted but I don't understand why it's crashing.
When using DLL and the same technique above, the dll executes in the 'simpleinjected.exe' but doesn't work when injected into Firefox. The dll code is below. It executes in the custom application but not Firefox even though it's injected successfully.
dllinject.dll
#include <windows.h>
int message(const char *msg)
{
MessageBox(NULL, msg, "Message from Dll", MB_OK);
return 0;
}
BOOL WINAPI DLLMain(HINSTANCE hInstDll, DWORD ulReason, LPVOID lpReserved)
{
switch(ulReason)
{
case DLL_PROCESS_ATTACH:
message("process attach");
break;
case DLL_THREAD_ATTACH:
message("thread attach");
break;
case DLL_PROCESS_DETACH:
message("process detach");
break;
case DLL_THREAD_DETACH:
message("thread detach");
break;
}
return true;
}
modified code of Simpleinjected.exe as these below. and then try inject dllinject.dll to Simpleinjected.exe again.
#include <stdio.h>
int main()
{
while(true)
{
printf("Hello");
}
return 0;
}
you should modify the defines below as same as Simpleinjected.exe.
#define procId 2844 //process id of Simpleinjected.exe
#define executable "dllinject.dll" // located in same directory

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.

Cannot implement password filter

I try to implement password filter, so I write a simple password filter.
I followed the document in the MSDN, and make sure that the functions are declared correctly.
I compile in VS 2010.
.def file:
LIBRARY myFilt
EXPORTS
InitializeChangeNotify
PasswordFilter
PasswordChangeNotify
.cpp file:
#include <windows.h>
#include <stdio.h>
#include <ntsecapi.h>
void writeToLog(const char* szString)
{
FILE* pFile = fopen("c:\\work\\logFile.txt", "a+");
if (NULL == pFile)
{
return;
}
fprintf(pFile, "%s\r\n", szString);
fclose(pFile);
return;
}
// Default DllMain implementation
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
OutputDebugString(L"DllMain");
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
BOOLEAN __stdcall InitializeChangeNotify(void)
{
OutputDebugString(L"InitializeChangeNotify");
writeToLog("InitializeChangeNotify()");
return TRUE;
}
BOOLEAN __stdcall PasswordFilter(
PUNICODE_STRING AccountName,
PUNICODE_STRING FullName,
PUNICODE_STRING Password,
BOOLEAN SetOperation
)
{
OutputDebugString(L"PasswordFilter");
return TRUE;
}
NTSTATUS __stdcall PasswordChangeNotify(
PUNICODE_STRING UserName,
ULONG RelativeId,
PUNICODE_STRING NewPassword
)
{
OutputDebugString(L"PasswordChangeNotify");
writeToLog("PasswordChangeNotify()");
return 0;
}
I put myFilt.dll in %windir%\system32, add "myFilt" to "Notification Packages" in the registry, restart the computer, change the password, and nothing happens.
I opened depends.exe and saw that the functions are correctly:
InitializeChangeNotify
PasswordChangeNotify
PasswordFilter
Where is the mistake??
Thanks.
I found the problem! I changed the runtime library from Multi-threaded Debug DLL (/MDd) to Multi-threaded Debug (/MTd) and it works perfect! :)
– user1375970 May 5 at 10:38
Notification Packages
Specifies the dynamic-link libraries (DLLs) that are loaded or called when passwords are set or changed. To specify more than one file, list the file names one above the other by pressing ENTER between each file name.
above the other!

MS Detours 2.1 - Popping out of stack

I wont to detour PlaySoundW function inside Minesweeper.
Game is crashing as soon as it calls PlaySoundW function.
If I uncomment Beep inside my code, game beeps and than crashes.
Now code is calling original function from hooked function so it should't do anything. But it is crashing anyway.
Can you tell me what is wrong?
After debugging app in Olly I found that when detour is active not all rubbish is popped out of stack.
How to fix it?
This is my code:
#include <Windows.h>
#include <tchar.h>
#include <detours.h>
namespace Hooks
{
BOOL(__stdcall *OrgPlaySoundW)(LPCTSTR pszSound, HMODULE hmod, DWORD fdwSound) = &PlaySoundW;
BOOL HookPlaySoundW(LPCTSTR pszSound, HMODULE hmod, DWORD fdwSound)
{
//Beep(1000, 250);
//return TRUE;
return OrgPlaySoundW(pszSound, hmod, fdwSound);
}
void DetourPlaySoundW(BOOL disable)
{
if(!disable)
{
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourAttach(&(PVOID&)OrgPlaySoundW, &HookPlaySoundW);
DetourTransactionCommit();
} else
{
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourDetach(&(PVOID&)OrgPlaySoundW, &HookPlaySoundW);
DetourTransactionCommit();
}
}
}
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
switch(fdwReason)
{
case DLL_PROCESS_ATTACH:
Hooks::DetourPlaySoundW(FALSE);
break;
case DLL_PROCESS_DETACH:
Hooks::DetourPlaySoundW(TRUE);
break;
}
return TRUE;
}
Try setting the calling convention of HookPlaySoundW to __stdcall (because the CC of PlaySoundW is also __stdcall (from Windows.h): WINMMAPI BOOL WINAPI PlaySoundW( __in_opt LPCWSTR pszSound, __in_opt HMODULE hmod, __in DWORD fdwSound);).
I have worked with detours before and after a casual glance everything looks correct except what I mentioned above. If this doesn't resolve your problem I'd be glad to do some further investigation.
The default setting for Visual C++ is __cdecl in which the call*er* cleans up the stack, but in __stdcall the call*ee* cleans up the stack. This is probably (i.e. might possibly be) the reason for all the "rubbish being popped off the stack".