I had created this code below where i try prevent a
dll injection that will use
LdrLoadDll function through of a kernel driver.
Now i want know how i can unhook this
api (based in my
Hook() function) when the
dll of protection is unloaded or when protected process is finalized?
Code:
library mydll;
uses
Windows,
SysUtils,
Classes;
{$R *.res}
type
NTSTATUS = UINT;
CONST
STATUS_ACCESS_DENIED = NTSTATUS($C0000022);
type
PUNICODE_STRING = ^UNICODE_STRING;
UNICODE_STRING = packed record
Length: Word;
MaximumLength: Word;
Buffer: PWideChar;
end;
var
Old_LdrLoadDll: function(szcwPath: PWideChar; dwFlags: DWORD;
pUniModuleName: PUNICODE_STRING; pResultInstance: PPointer)
: NTSTATUS; stdcall;
function LdrLoadDll(szcwPath: PWideChar; dwFlags: DWORD;
pUniModuleName: PUNICODE_STRING; pResultInstance: PPointer)
: NTSTATUS; stdcall;
begin
Result := Old_LdrLoadDll(szcwPath, dwFlags, pUniModuleName, pResultInstance);
end;
function NewLdrLoadDll(szcwPath: PWideChar; dwFlags: DWORD;
pUniModuleName: PUNICODE_STRING; pResultInstance: PPointer)
: NTSTATUS; stdcall;
begin
if (CompareStr(pUniModuleName^.Buffer, 'hackdll.dll') = 0) or
(CompareStr(szcwPath, 'Hack') = 0) then
Result := STATUS_ACCESS_DENIED
else
Result := LdrLoadDll(szcwPath, dwFlags, pUniModuleName, pResultInstance);
end;
procedure Hook(target, newfunc: pointer);
var
jmpto: DWORD;
OldProtect: Cardinal;
begin
jmpto := DWORD(newfunc) - DWORD(target) - 5;
VirtualProtect(target, 5, PAGE_EXECUTE_READWRITE, @OldProtect);
pbyte(target)^ := $E9;
pdword(DWORD(target) + 1)^ := jmpto;
end;
procedure DllEntryPoint(Reason: Integer); stdcall;
begin
case Reason of
DLL_PROCESS_ATTACH:
begin
DisableThreadLibraryCalls(HInstance);
Hook(GetProcAddress(GetModuleHandle('ntdll.dll'), 'LdrLoadDll'),
@NewLdrLoadDll);
end;
DLL_THREAD_ATTACH:
; //
DLL_THREAD_DETACH:
; //
DLL_PROCESS_DETACH:
begin
// Unhook();
end;
end;
end;
begin
DllProc := @DllEntryPoint;
DllEntryPoint(DLL_PROCESS_ATTACH);
end.