bester 发表于 2019-8-26 22:49

实现Win10下Delphi 10.3.1 inline hook DLL过滤之LoadLibraryExW

本帖最后由 bester 于 2019-8-26 22:51 编辑

易语言调用LoadLibraryExW载入1234.dll图:

DLL源码以及EXE调用源码:



易语言调用宽字节函数,由于易语言的文本型是窄字节类型,故需要用精益模块的Ansi转unicode,然后他这个命令是字节集类型,故我们在声明API的时候也要定义为字节集
library Project1;

{ Important note about DLL memory management: ShareMem must be the
first unit in your library's USES clause AND your project's (select
Project-View Source) USES clause if your DLL exports any procedures or
functions that pass strings as parameters or function results. This
applies to all strings passed to and from your DLL--even those that
are nested in records and classes. ShareMem is the interface unit to
the BORLNDMM.DLL shared memory manager, which must be deployed along
with your DLL. To avoid using BORLNDMM.DLL, pass string information
using PChar or ShortString parameters. }

uses
System.SysUtils,
System.Classes,
Winapi.Windows,
Vcl.Dialogs;

{$R *.res}
var
read: array of Byte=(0,0,0,0,0);
apiaddr: Integer;
rd: NativeUInt;
jmps: Integer;
tiaoshi, tiaoshi1: Integer;
function lens(x,y:Integer):Integer;
begin
Result:=x-y-5;
end;
function MyLoad(lpLibFileName: LPCWSTR; hFile: THandle; dwFlags: DWORD): HMODULE; stdcall;
var
I: Integer;   //循环次数变量,每次都要写入1个字节,还原API头
reads: byte;   //取出我们保存的5个字节,然后循环写入
begin
for I := 1 to 5 do    //先恢复HOOK,怕出现安全问题,因为我们不知道这个DLL是否是拦截还是放行,故先恢复HOOK再说,等下面再做判断,如果是需要拦截的,我们之间返回为0,剩下的就是不需要拦截的DLL,就可以不用HOOK了
begin
    reads := read;
    WriteProcessMemory(GetCurrentProcess, Pointer(apiaddr + I - 1), Pointer(@reads), 1, rd);
end;
   if lpLibFileName='C:\Users\Administrator\Desktop\1234.dll' then   //判断是否为我们不想让程序载入的DLL,如果是不想载入的DLL,返回为0,表示拦截,返回为0就会导致函数载入DLL失败
   begin
    Result := 0   //返回为0,表示拦截,如果是需要判断多个DLL 拦截,在下面的else,改成elseif 表示再判断一个DLL。
   end
   else
   begin
    Result:=LoadLibraryExW(lpLibFileName, hFile, dwFlags);    //如果是别的DLL,我就放行,让他正常调用一次,然后进行HOOK,等待下一次拦截,下面5句代码就是继续HOOK API 的头部5个字节
    jmps := 233;
    WriteProcessMemory(GetCurrentProcess, Pointer(apiaddr), Pointer(@jmps), 1, rd);
    tiaoshi := Integer(@MyLoad);
    tiaoshi1 := lens(Integer(@MyLoad), apiaddr);
    WriteProcessMemory(GetCurrentProcess, Pointer(apiaddr + 1), Pointer(@tiaoshi1), 4, rd);

   end;

end;


procedure MyMain();

begin
apiaddr := Integer(GetProcAddress(LoadLibrary('Kernel32.dll'), 'LoadLibraryExW'));
ReadProcessMemory(GetCurrentProcess, Pointer(apiaddr), Pointer(@read), 5, rd);
jmps := 233;
WriteProcessMemory(GetCurrentProcess, Pointer(apiaddr), Pointer(@jmps), 1, rd);
tiaoshi := Integer(@MyLoad);
tiaoshi1 := lens(Integer(@MyLoad), apiaddr);
WriteProcessMemory(GetCurrentProcess, Pointer(apiaddr + 1), Pointer(@tiaoshi1), 4, rd);
end;

begin
   MyMain();   //DllMain,调用HOOK 过程
end.

bester 发表于 2019-8-26 22:51

jiale625 发表于 2021-5-14 18:13

页: [1]
查看完整版本: 实现Win10下Delphi 10.3.1 inline hook DLL过滤之LoadLibraryExW