4

I am learning to write hooks for Windows API and for exercise I am writing a hook for pDeleteFileA function. When the function will get called, before deleting the file I want to check whether file's name is 'testfile.txt' if yes then instead of deleting it a message will pop up and if its called something else then proceed deleting the file.

I have written some code already and the code compiles without any errors but when I try to delete 'testfile.txt' it is just being deleted. Maybe someone could give me a hint what I am doing wrong or what I am not doing?

Here is my code so far:

#include <Windows.h>

struct hook_t{// a datatype to store information about our hook
    bool isHooked = false;
    void* FunctionAddress = operator new(100);
    void* HookAddress = operator new(100);
    char Jmp[6] = { 0 };
    char OriginalBytes[6] = {0};
    void* OriginalFunction = operator new(100);
};

namespace hook {
    bool InitializeHook(hook_t* Hook, char* Module, char* Function, void* HookFunction) {
        HMODULE hModule;
        DWORD OrigFunc, FuncAddr;
        byte opcodes[] = {0x90, 0x90, 0x90, 0x90, 0x90, 0xe9, 0x00, 0x00, 0x00, 0x00};
        if (Hook->isHooked) {
            return false;
        }

        hModule = GetModuleHandleA(Module);
        if (hModule == INVALID_HANDLE_VALUE) {
            Hook->isHooked = false;
            return false;
        }

        Hook->Jmp[0] = 0xe9;
        *(PULONG)&Hook->Jmp[1] = (ULONG)HookFunction - (ULONG)Hook->FunctionAddress - 5;
        memcpy(Hook->OriginalBytes, Hook->FunctionAddress, 5);
        Hook->OriginalFunction = VirtualAlloc(0, 4096, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
        if (Hook->OriginalFunction == NULL) {
            return false;
        }
        memcpy(Hook->OriginalFunction, Hook->OriginalBytes, 5);
        OrigFunc = (ULONG)Hook->OriginalFunction + 5;
        FuncAddr = (ULONG)Hook->OriginalFunction + 5;
        *(LPBYTE)((LPBYTE)Hook->OriginalFunction + 5) = 0xe9;
        *(PULONG)((LPBYTE)Hook->OriginalFunction + 6) = (ULONG)FuncAddr;
        Hook->isHooked = true;
        return true;

    }//end InitializeHook

    bool InsertHook(hook_t* Hook) {
        DWORD op;
        if (!Hook->isHooked) {
            return false;
        }
        VirtualProtect(Hook->FunctionAddress, 5, PAGE_EXECUTE_READWRITE, &op);
        memcpy(Hook->FunctionAddress, Hook->Jmp, 5);
        VirtualProtect(Hook->FunctionAddress, 5, op, &op);
        return true;
    }

    bool Unhook(hook_t* Hook) {
        DWORD op;
        if (!Hook->isHooked) {
            return false;
        }
        VirtualProtect(Hook->FunctionAddress, 5, PAGE_EXECUTE_READWRITE, &op);
        memcpy(Hook->FunctionAddress, Hook->OriginalBytes, 5);
        VirtualProtect(Hook->FunctionAddress, 5, op, &op);
        Hook->isHooked = false;
        return true;
    }

    bool FreeHook(hook_t* Hook) {
        if (Hook->isHooked) {
            return false;
        }
        VirtualFree(Hook->OriginalFunction, 0, MEM_RELEASE);
        memset(Hook, 0, sizeof(hook_t*));
        return true;
    }

}//end namespase

==========================================================================

#define _CRT_SECURE_NO_WARNINGS

#include "apihook.h"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>

using namespace hook;

//define the function to be hooked
typedef BOOL(WINAPI* pDeleteFileA)(LPCSTR lpFileName);//in this case this will be delete file a

pDeleteFileA pDeleteFile;//instance of it
hook_t* Hook = new hook_t();

//this function will replace the original API function in the process
BOOL WINAPI HookDeleteFileA(LPCSTR lpFileName) {
    //we can do here whatever we want before the original API function is called
    //for example disable deleting of a certain file
    if (strstr(lpFileName, "testfile")) {//checks if parameter contains a string
        //disable deleting of this file
        SetLastError(ERROR_ACCESS_DENIED);
        MessageBoxA(0, "You can't delete this file!", "error", 0);
        return false;
    }
    return pDeleteFile(lpFileName);//if parameter does not contain our string, call the original API function
}

void StartRoutine() {
    pDeleteFile = (pDeleteFileA)&Hook->OriginalFunction;
    //the pDeleteFileA is located in "kernel32.dll"
    InitializeHook(Hook, "kernel32.dll", "DeleteFileA", HookDeleteFileA);
    InsertHook(Hook);//spawn the hook to the current process
}

BOOL WINAPI DllMain(HMODULE hModule, DWORD dwReason, LPVOID lpReserved) {
    switch (dwReason) {
    case DLL_PROCESS_ATTACH:
        printf("API Hook Attached!");//notify
        StartRoutine();
        break;
    case DLL_PROCESS_DETACH:
        Unhook(Hook);//unhook the hook
        FreeHook(Hook);//remove the hook from memory
    }
}

int main() {

    HMODULE hModule = GetModuleHandleA("kernel32.dll");

    //The reason code that indicates why the DLL entry-point function is being called.
    //This parameter can be one of the following values:
    //DLL_PROCESS_ATTACH 1:
    //The DLL is being loaded into the virtual address space of the current process 
    //as a result of the process starting up or as a result of a call to LoadLibrary. 
    //DLL_PROCESS_DETACH 0:
    //The DLL is being unloaded from the virtual address space of the calling process 
    //because it was loaded unsuccessfully or the reference count has reached zero 
    //(the processes has either terminated or called FreeLibrary one time for each time it called LoadLibrary).
    DWORD dwReason = DLL_PROCESS_ATTACH;


    //If fdwReason is DLL_PROCESS_ATTACH, lpvReserved is NULL for dynamic loads and non-NULL for static loads
    //If fdwReason is DLL_PROCESS_DETACH, lpvReserved is NULL if FreeLibrary has been called or the DLL load 
    //failed and non-NULL if the process is terminating.
    LPVOID lpReserved = NULL;

    DllMain(hModule, dwReason, lpReserved);

    return 0;
}
3
  • Are you hooking your own process and deleting file in explorer? Commented Apr 16, 2016 at 13:02
  • Yes, this is my first hook ever so if I am doing it wrong could you give me some advice?
    – Nikolaj
    Commented Apr 16, 2016 at 13:20
  • Yeah, that won't work. You hooked DeleteFileA for your own process, so to have any effect on explorer, explorer itself should have loaded this dll, which won't happen obviously. Also what's going on with DllMain in main() exe entry point?
    – bunglehead
    Commented Apr 17, 2016 at 7:51

1 Answer 1

5

Each process has it's own address space.

Each process loads it's DLLs separately and has separate memory. So if you try to overwrite memory - you're overwriting just a copy of DLL that is loaded into your process. This is done for stability and security reasons.

To owerwrite memory and execute code in another process - you need to use DLL Injection, wiki has good overview of scenarios and methods.

So you need to place your code into DLL, then load this DLL into target's process. Then your DLL in it's DLLMain will overwrite function for this process (the hook code). It also means that hook code will run in context of hooked process, so MessageBox or printf might not work as expected.

Also I highly recommend to use second PC with remote debug or VM, because hooking system processes may cause instability.

Edit: some more notes. You're trying to hook DeleteFileA, which is ASCII version and newer software will use DeleteFileW instead.

Edit2: also you can't load 32 bit DLL into 64 bit process and vice versa.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.