-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathHookLib.cs
44 lines (40 loc) · 2.33 KB
/
HookLib.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
using System;
namespace HookLib
{
public class HookLib
{
private string LibToHook { get; set; }
private string FunctionToHook { get; set; }
public byte[] NewBytes { get; set; }
private uint SizeOfNewBytes { get; set; }
public bool IsHooked { get; set; }
public byte[] OldBytes { get; set; }
private IntPtr ProcessToHook { get; set; }
public HookLib(IntPtr ProcessToPatch, string LibName, string FunctionName, byte[] BytesToHook)
{
OldBytes = new byte[BytesToHook.Length]; //first we need a buffer to restore old function bytes to unhook it
ProcessToHook = ProcessToPatch;
LibToHook = LibName;//the lib ex kernel32 or ntdll
FunctionToHook = FunctionName;//name of the function you want to hook
NewBytes = BytesToHook;//bytes you want to use as replacement of our function address
SizeOfNewBytes = (uint)BytesToHook.Length;//the size of hooked bytes
}
public bool HookedFunction()
{
IntPtr AddressOfLib = NativeAPI.GetModuleHandle(LibToHook);//getting lib address in our program
IntPtr FunctionAddress = NativeAPI.GetProcAddress(AddressOfLib, FunctionToHook);//getting function address in our program
NativeAPI.ReadProcessMemory(ProcessToHook, FunctionAddress, OldBytes, SizeOfNewBytes, 0);//read the original bytes from our function address and store them if you want to restore
return IsHooked = NativeAPI.WriteProcessMemory(ProcessToHook, FunctionAddress, NewBytes, SizeOfNewBytes, 0);// here we hooked the function : the address of our function is replace by our code (asm or opcode !)
}
public bool UnHookedFunction()
{
IntPtr AddressOfLib = NativeAPI.GetModuleHandle(LibToHook);//getting lib address in our program
IntPtr FunctionAddress = NativeAPI.GetProcAddress(AddressOfLib, FunctionToHook);//getting function address in our program
if (NativeAPI.WriteProcessMemory(ProcessToHook, FunctionAddress, OldBytes, SizeOfNewBytes, 0))//here we unhook the function by setting the original bytes from our buffer
IsHooked = false;
else
IsHooked = true;
return IsHooked;
}
}
}