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
Related
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);
}
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
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;
}
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
I'm using WinInet and InternetOpenUrl to download a file... which is working. But I want to monitor the progress so I tried to add a Callback function but for some reason it's never called...
The code:
void CALLBACK DownloadProgress(HINTERNET hInternet, DWORD_PTR dwContext, DWORD dwInternetStatus, LPVOID lpvStatusInformation, DWORD dwStatusInformationLength)
{
// this function never gets called
MessageBox(NULL, L"test", L"test", MB_OK);
}
void Download()
{
HINTERNET hOpen = InternetOpen(0, INTERNET_OPEN_TYPE_DIRECT, 0, 0, 0);
InternetSetStatusCallback(hOpen, DownloadProgress);
HINTERNET hOpenUrl = InternetOpenUrl(hOpen, L"http://www.website.com/test.txt", 0, 0, 0, 0);
// small edit
InternetReadFile(hOpenUrl, data, SIZE, &size);
}
What am I doing wrong here?
From the MSDN:
INTERNET_STATUS_CALLBACK InternetSetStatusCallback(
_In_ HINTERNET hInternet,
_In_ INTERNET_STATUS_CALLBACK lpfnInternetCallback
);
Note The callback function specified in the lpfnInternetCallback
parameter will not be called on asynchronous operations for the
request handle when the dwContext parameter of HttpOpenRequest is set
to zero (INTERNET_NO_CALLBACK), or the connection handle when the
dwContext handle of InternetConnect is set to zero
(INTERNET_NO_CALLBACK).
In your case, you are using InternetOpenUrl (after calling InternetOpen) which is an easy alternative to work with URLs when you not need to access the particulars of the protocol. Syntax:
HINTERNET InternetOpenUrl(
_In_ HINTERNET hInternet,
_In_ LPCTSTR lpszUrl,
_In_ LPCTSTR lpszHeaders,
_In_ DWORD dwHeadersLength,
_In_ DWORD dwFlags,
_In_ DWORD_PTR dwContext
);
dwContext is an application-defined value that's passed to the callback function registered with InternetSetStatusCallback. Is used to identify the application context.
Now, note that you are passing dwContext=0 to this function in your code. If you change that, your code will work as you expect.