procedure TForm1.btn2Click(Sender: TObject);
begin
API_Hookup;
end;
procedure TForm1.btn4Click(Sender: TObject);
begin
MessageBoxA(Form1.Handle,'NO HOOK UP A','MessageBoxA',MB_OK);
MessageBoxW(Form1.Handle,'NO HOOK UP W','MessageBoxW',MB_OK);
MessageBox (Form1.Handle,'NO HOOK UP BOX','MessageBox',MB_OK);
end;
procedure TForm1.btn3Click(Sender: TObject);
begin
Un_API_Hook;
end;
var
OldMessageBoxA: TmessageA;
OldMessageBoxW: TmessageW;
function GetFunctionAddress(PFunction: PImportCode): Pointer;
begin
Result:= PFunction;
if PFunction = nil then exit;
if (PFunction.JumpInstruction = $25FF) then
Result:= PFunction.AddressOfPointerToFunction^;
end;
function RepointFunction(OldFunc, NewFunc: Pointer): Integer;
var
ProcessList: TList;
function RepointAddrInModule(hModule: THandle; OldFunc, NewFunc: Pointer): Integer;
var
f: Pointer;
RVA: DWORD;
InportDLL: string;
written: DWORD;
Func: ^Pointer;
NT: PImageNTHeaders;
Dos: PImageDosHeader;
ImportDesc: PImage_Import_Entry;
begin
//HOOK的数量
Result:= 0;
//判断当前Module是否已经处理过
Dos:= Pointer(hModule);
if ProcessList.IndexOf(Dos) >= 0 then exit;
ProcessList.Add(Dos);
if IsBadReadPtr(Dos, SizeOf(TImageDosHeader)) then exit;
if Dos.e_magic <> IMAGE_DOS_SIGNATURE then exit;
NT:= Pointer(Integer(Dos) + dos._lfanew);
RVA:= NT^.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress;
if RVA = 0 then exit;
ImportDesc:= Pointer(Integer(Dos) + Integer(RVA));
//取旧的函数地址
OldFunc:= GetFunctionAddress(OldFunc);
while (ImportDesc^.Name <> 0) do
begin
//递归处理函数包含的所有InprotDll
InportDLL:= PChar(Integer(Dos) + Integer(ImportDesc^.Name));
RepointAddrInModule(GetModuleHandle(PChar(InportDLL)), OldFunc, NewFunc);
//处理当前Dll导入的函数
Func:= Pointer(Integer(DOS) + Integer(ImportDesc.LookupTable));
while Func^ <> nil do
begin
f:= GetFunctionAddress(Func^);
if f = OldFunc then
begin
WriteProcessMemory(GetCurrentProcess, Func, @NewFunc, 4, written);
if Written > 0 then Inc(Result);
end;
Inc(Func);
end;
Inc(ImportDesc);
end;
end;
procedure API_Hookup;
begin
if @OldMessageBoxA = nil then
@OldMessageBoxA:= GetFunctionAddress(@MessageBoxA);
RepointFunction(@OldMessageBoxA, @MyBoxA);
if @OldMessageBoxW = nil then
@OldMessageBoxW:= GetFunctionAddress(@MessageBoxW);
RepointFunction(@OldMessageBoxW, @MyBoxW);
end;
procedure Un_API_Hook;
begin
if @OldMessageBoxA <> nil then
RepointFunction(@MyBoxA, @OldMessageBoxA);
if @OldMessageBoxW <> nil then
RepointFunction(@MyBoxW, @OldMessageBoxW);
end;