我正在尝试在 api 挂钩中调用原始函数,以防止按LdrLoadDll()
函数注入 dll,但是每次当我尝试加载不同的被过滤的 dll 时,应用程序崩溃并且不可能调用原始函数。似乎我什么时候会在钩子之前保存“original_function”时做错了。
我正在 Windows 7 x64 上进行测试,在 32 位应用程序中注入 32 位 dll(代码如下)。
如何解决这个问题?
program Project1;
{$APPTYPE CONSOLE}
{$R *.res}
uses
Windows,
SysUtils;
type
NTSTATUS = Cardinal;
PUNICODE_STRING = ^UNICODE_STRING;
UNICODE_STRING = packed record
Length: Word;
MaximumLength: Word;
Buffer: PWideChar;
end;
const
STATUS_ACCESS_DENIED = NTSTATUS($C0000022);
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;
procedure PatchCode(Address: Pointer; const NewCode; Size: Integer);
var
OldProtect: DWORD;
begin
if VirtualProtect(Address, Size, PAGE_EXECUTE_READWRITE, OldProtect) then
begin
Move(NewCode, Address^, Size);
FlushInstructionCache(GetCurrentProcess, Address, Size);
VirtualProtect(Address, Size, OldProtect, @OldProtect);
end;
end;
type
PInstruction = ^TInstruction;
TInstruction = packed record
Opcode: Byte;
Offset: Integer;
end;
procedure RedirectProcedure(OldAddress, NewAddress: Pointer);
var
NewCode: TInstruction;
begin
NewCode.Opcode := $E9;
NewCode.Offset := NativeInt(NewAddress) - NativeInt(OldAddress) -
SizeOf(NewCode);
PatchCode(OldAddress, NewCode, SizeOf(NewCode));
end;
function NewLdrLoadDll(szcwPath: PWideChar; dwFlags: DWORD;
pUniModuleName: PUNICODE_STRING; pResultInstance: PPointer)
: NTSTATUS; stdcall;
begin
if (pos('111', pUniModuleName.Buffer) > 0) or
(pos('222', pUniModuleName.Buffer) > 0) then
Result := STATUS_ACCESS_DENIED
else
Result := LdrLoadDll(szcwPath, dwFlags, pUniModuleName, pResultInstance);
end;
begin
@Old_LdrLoadDll := GetProcAddress(GetModuleHandle('ntdll.dll'), 'LdrLoadDll');
try
RedirectProcedure(GetProcAddress(GetModuleHandle('ntdll.dll'),
'LdrLoadDll'), @NewLdrLoadDll);
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
Readln;
end.