How to share variables between dll functions? - c++

Why does inside of WriteConsole_Hook the code doesn't recognize if (ffmpeg_struct.ffmpeg_console) { as true?
It has been previously set true inside of CreateProcessW_Hook function.
struct ffmpeg {
bool ffmpeg_console;
} ffmpeg_struct;
BOOL __stdcall CreateProcessW_Hook(
LPCWSTR lpApplicationName,
LPWSTR lpCommandLine,
LPSECURITY_ATTRIBUTES lpProcessAttributes,
LPSECURITY_ATTRIBUTES lpThreadAttributes,
BOOL bInheritHandles,
DWORD dwCreationFlags,
LPVOID lpEnvironment,
LPCWSTR lpCurrentDirectory,
LPSTARTUPINFOW lpStartupInfo,
LPPROCESS_INFORMATION lpProcessInformation
)
{
BOOL rt = CreateProcessW(lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo, lpProcessInformation);
if (lpCommandLine)
if(wcsstr(lpCommandLine, L"ffmpeg.exe") != NULL)
{
Sleep(100);
ffmpeg_struct.ffmpeg_console = true;
DWORD pid = lpProcessInformation->dwProcessId;
//........
}
return rt;
}
BOOL __stdcall WriteConsole_Hook(
HANDLE hConsoleOutput,
const VOID* lpBuffer,
DWORD nNumberOfCharsToWrite,
LPDWORD lpNumberOfCharsWritten,
LPVOID lpReserved
)
{
const wchar_t* string = reinterpret_cast<const wchar_t*>(lpBuffer);
if (ffmpeg_struct.ffmpeg_console) {
//....
}
return WriteConsoleW(hConsoleOutput, lpBuffer, nNumberOfCharsToWrite, lpNumberOfCharsWritten, lpReserved);
}

Related

Hooking of CreateFile throw exception: Read Access violation

When i run my program it successfully createfile but when I tried to inject my CreateFile API into my program it shows exception
Exception thrown: read access violation.
pbCode was nullptr.
I have search from various sites but still unable to locate the problem
This is the code for hooked CreateFile
_CreateFile TrueCreateFile =
(_CreateFile)GetProcAddress(GetModuleHandle(L"kernel32"), "CreateFile");
HANDLE WINAPI HookCreateFile(
_In_ LPCTSTR lpFileName,
_In_ DWORD dwDesiredAccess,
_In_ DWORD dwShareMode,
_In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes,
_In_ DWORD dwCreationDisposition,
_In_ DWORD dwFlagsAndAttributes,
_In_opt_ HANDLE hTemplateFile)
{
HANDLE out = TrueCreateFile((LPCTSTR)"C:\\Users\\abc\\bar.txt",
dwDesiredAccess,
dwShareMode,
lpSecurityAttributes,
dwCreationDisposition,
dwFlagsAndAttributes,
hTemplateFile);
return out;
}
To Hook CreateFile
void hook_CreateFile()
{
HANDLE hProc = NULL;
if (Mhook_SetHook((PVOID*)&TrueCreateFile, HookCreateFile)) {
// Now call OpenProcess and observe NtOpenProcess being redirected
// under the hood.
hProc = OpenProcess(PROCESS_ALL_ACCESS,
FALSE, GetCurrentProcessId());
if (hProc) {
printf("Successfully opened CreateFile: %p\n", hProc);
CloseHandle(hProc);
}
else {
printf("Could not open CreateFile: %d\n", GetLastError());
}
}
}
TrueCreateFile is a pointer to the function's address.
You're passing &TrueCreateFile which is the address of the pointer.
You're hooking the pointer instead of the function.
Just pass (void*)TrueCreateFile

How can i suppport both Unicode and Multi-Byte Character Set in Static library (.lib)?

I am using visual studio 2015 and I want to write C++ static library that I can use in Unicode projects and in Multi-Byte projects, how I doing it right?
For example I have this code:
namespace Reg
{
LONG WINAPI CreateKey(
_In_ HKEY hKey,
_In_ LPCTSTR lpSubKey,
_In_ REGSAM samDesired,
_Out_ PHKEY phkResult
)
{
return RegCreateKeyEx(hKey,
lpSubKey,
0, NULL,
REG_OPTION_NON_VOLATILE,
samDesired,
NULL,
phkResult,
NULL);
}
}
Like Raymond Chen suggested in a comment, you can use two separate overloaded functions - one for Ansi, one for Unicode:
namespace Reg
{
LONG WINAPI CreateKey(
_In_ HKEY hKey,
_In_ LPCSTR lpSubKey,
_In_ REGSAM samDesired,
_Out_ PHKEY phkResult
)
{
return RegCreateKeyExA(hKey,
lpSubKey,
0, NULL,
REG_OPTION_NON_VOLATILE,
samDesired,
NULL,
phkResult,
NULL);
}
LONG WINAPI CreateKey(
_In_ HKEY hKey,
_In_ LPCWSTR lpSubKey,
_In_ REGSAM samDesired,
_Out_ PHKEY phkResult
)
{
return RegCreateKeyExW(hKey,
lpSubKey,
0, NULL,
REG_OPTION_NON_VOLATILE,
samDesired,
NULL,
phkResult,
NULL);
}
}
Or, like rubenvb suggested, just forget about the Ansi function altogether, focus on just Unicode by itself:
namespace Reg
{
LONG WINAPI CreateKey(
_In_ HKEY hKey,
_In_ LPCWSTR lpSubKey,
_In_ REGSAM samDesired,
_Out_ PHKEY phkResult
)
{
return RegCreateKeyExW(hKey,
lpSubKey,
0, NULL,
REG_OPTION_NON_VOLATILE,
samDesired,
NULL,
phkResult,
NULL);
}
}
you could do it same way as is usually used for Win32 functions:
CreateKeyW(..) { unicode implementation }
CreateKeyA(..) { byte string implementation }
#ifdef UNICODE
#define CreateKey CreateKeyW
#else
#define CreateKey CreateKeyA
#endif

Hooking GetVolumeInformation to return a custom filesystem type

I've been attempting (and miserably failing!) at learning how to use Easyhook. I'm trying to hook and return a custom filesystem name for all GetVolumeInformation calls. The following code does hook and I get the filesystem name in debugview, but it crashes the app that loads it.
Any help would be massively appreciated
#include "stdafx.h"
#include <string>
#include <iostream>
#include <Windows.h>
#include <easyhook.h>
BOOL WINAPI myhook(LPCTSTR lpRootPathName, LPTSTR lpVolumeNameBuffer, DWORD nVolumeNameSize, LPDWORD lpVolumeSerialNumber, LPDWORD lpMaximumComponentLength, LPDWORD lpFileSystemFlags, LPTSTR lpFileSystemNameBuffer, DWORD nFileSystemNameSize);
BOOL WINAPI myhook(LPCTSTR lpRootPathName, LPTSTR lpVolumeNameBuffer, DWORD nVolumeNameSize, LPDWORD lpVolumeSerialNumber, LPDWORD lpMaximumComponentLength, LPDWORD lpFileSystemFlags, LPTSTR lpFileSystemNameBuffer, DWORD nFileSystemNameSize)
{
BOOL retval = GetVolumeInformationW(lpRootPathName, lpVolumeNameBuffer, nVolumeNameSize, lpVolumeSerialNumber, lpMaximumComponentLength, lpFileSystemFlags, lpFileSystemNameBuffer, nFileSystemNameSize);
if (retval) {
wcscpy_s(lpFileSystemNameBuffer, 8, L"NOTNTFS");
OutputDebugString(lpFileSystemNameBuffer);
}
return retval;
}
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
HOOK_TRACE_INFO hHook = { NULL }; // keep track of our hook
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
{
NTSTATUS result = LhInstallHook(
GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetVolumeInformationW"),
myhook,
NULL,
&hHook);
if (FAILED(result))
{
OutputDebugStringA("FAILED TO HOOK");
}
else {
OutputDebugStringA("HOOKED");
ULONG ACLEntries[1] = { 0 };
LhSetInclusiveACL(ACLEntries, 1, &hHook);
}
}
case DLL_THREAD_DETACH:
{
}
case DLL_PROCESS_DETACH:
{
}
break;
}
return TRUE;
}

Detours Hook: GetVolumeInformation Random Volume Serial

I'm trying to hook GetVolumeInformation, using Detours Express (3.0), to change the volume serial.
The problem is each time the hooked function is called it returns a random volume serial.
#include <fstream>
#include <string>
#include <windows.h>
#include <detours.h>
#include <fcntl.h>
#include <stdio.h>
#include <io.h>
#pragma comment(lib,"detours.lib")
#pragma comment(lib,"ws2_32.lib")
std::string rcvBuf;
HANDLE CreateConsole();
HANDLE CreateConsole()
{
int hConHandle = 0;
HANDLE lStdHandle = 0;
FILE *fp = 0;
// Allocate a console
AllocConsole();
// redirect unbuffered STDOUT to the console
lStdHandle = GetStdHandle(STD_OUTPUT_HANDLE);
hConHandle = _open_osfhandle(PtrToUlong(lStdHandle), _O_TEXT);
fp = _fdopen(hConHandle, "w");
*stdout = *fp;
setvbuf(stdout, NULL, _IONBF, 0);
return lStdHandle;
}
HMODULE hLib = GetModuleHandle("Kernel32.dll");
typedef BOOL (WINAPI *HWIDPtr)(LPCTSTR lpRootPathName, LPTSTR lpVolumeNameBuffer, DWORD nVolumeNameSize, LPDWORD &lpVolumeSerialNumber, LPDWORD lpMaximumComponentLength, LPDWORD lpFileSystemFlags, LPTSTR lpFileSystemNameBuffer, DWORD nFileSystemNameSize);
HWIDPtr pHWID = (HWIDPtr)GetProcAddress(hLib, "GetVolumeInformationW");
BOOL WINAPI MyHWID(LPCTSTR lpRootPathName, LPTSTR lpVolumeNameBuffer, DWORD nVolumeNameSize, LPDWORD lpVolumeSerialNumber, LPDWORD lpMaximumComponentLength, LPDWORD lpFileSystemFlags, LPTSTR lpFileSystemNameBuffer, DWORD nFileSystemNameSize)
{
printf( ("Real : %u"),&lpVolumeSerialNumber);
return pHWID(lpRootPathName, lpVolumeNameBuffer, nVolumeNameSize, lpVolumeSerialNumber, lpMaximumComponentLength, lpFileSystemFlags, lpFileSystemNameBuffer, nFileSystemNameSize);
}
BOOL WINAPI DllMain(HINSTANCE hinst, DWORD dwReason, LPVOID reserved)
{
if (DetourIsHelperProcess()) {
return TRUE;
}
if (dwReason == DLL_PROCESS_ATTACH) {
CreateConsole();
DetourRestoreAfterWith();
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourAttach(&(PVOID&)pHWID, MyHWID);
if(DetourTransactionCommit() == NO_ERROR)
printf("Attached successfuly!#");
}
else if (dwReason == DLL_PROCESS_DETACH) {
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourDetach(&(PVOID&)pHWID, MyHWID);
DetourTransactionCommit();
}
return TRUE;
}
any advise would be appreciated.
If you are referring to the fact that printf() call inside the hook function outputs random garbage - it makes perfect sense, since lpVolumeSerialNumber is an out parameter, and hence it may (and most probably will) contain garbage prior to the original function call. If you want to see the value returned by the original function, you should rewrite your hook function in the following manner:
BOOL WINAPI MyHWID(LPCTSTR lpRootPathName, LPTSTR lpVolumeNameBuffer, DWORD nVolumeNameSize, LPDWORD lpVolumeSerialNumber, LPDWORD lpMaximumComponentLength, LPDWORD lpFileSystemFlags, LPTSTR lpFileSystemNameBuffer, DWORD nFileSystemNameSize)
{
BOOL retval = pHWID(lpRootPathName, lpVolumeNameBuffer, nVolumeNameSize, lpVolumeSerialNumber, lpMaximumComponentLength, lpFileSystemFlags, lpFileSystemNameBuffer, nFileSystemNameSize);
printf( ("Real : %u"), *lpVolumeSerialNumber);
return retval;
}
Please note that I also changed the "&" to "*" - this is what you should use if you want to dereference a pointer rather than get its address.
Hope this helps

Hooking kernel32.dll function stops my program from working

Do you know why I can't run the program when hooking one of kernel32 functions? I'm writing anti cheat and want to optimize it more because currently it's in thread, but something is wrong...
There's written OpenProcess because I've tried before to hook it and the same problem.
typedef HANDLE ( WINAPI * pOpenProcess )( _In_ HANDLE hProcess,
_In_ LPSECURITY_ATTRIBUTES lpThreadAttributes,
_In_ SIZE_T dwStackSize,
_In_ LPTHREAD_START_ROUTINE lpStartAddress,
_In_ LPVOID lpParameter,
_In_ DWORD dwCreationFlags,
_Out_ LPDWORD lpThreadId );
pOpenProcess original;
__declspec(naked) void hOpenProcess()
{
__asm PUSHAD
__asm PUSHFD
//my actions here
__asm POPFD
__asm POPAD
__asm JMP[original]
};
void ZPerformHook()
{
DWORD Address = ( DWORD )GetProcAddress( GetModuleHandle( TEXT( "kernel32.dll" ) ), "CreateRemoteThread" );
original = ( pOpenProcess )DetourFunction( (PBYTE)Address, (PBYTE)hOpenProcess );
}
"//my actions here" would be interesting, maybe you are corrupting the stack.
or maybe the error is in your DetourFunction.
how does your program fail? maybe with a access violation?
also you don´t have to use a naked function. you can just hook to a function that has the exact same signature as your target.
no asm needed.
HANDLE __stdcall hOpenProcess( HANDLE hProcess,
LPSECURITY_ATTRIBUTES lpThreadAttributes,
SIZE_T dwStackSize,
LPTHREAD_START_ROUTINE lpStartAddress,
LPVOID lpParameter,
DWORD dwCreationFlags,
LPDWORD lpThreadId )
{
// do your stuff here
std::cout << "From hook" << std::endl;
return original( hProcess, lpThreadAttributes, dwStackSize, lpStartAddress, lpParameter, dwCreationFlags, lpThreadId);
}
if that doesn´t work, check the return value of GetProcAddress, if that´s correct, something in your DetourFunction may be going wrong.
you could also use a disassembler like beaengine and dump your target function after detouring to see if the hook was applied correctly