天天看點

Delphi中Hook API進行程序保護

 const

PRG_NAME = 'HA.exe';

var TerminateProcessNext : function (processHandle, exitCode: dword) : bool; stdcall;

NtTerminateProcessNext : function (processHandle, exitCode: dword) : dword; stdcall;

{$R *.res}

function ThisIsOurProcess(processHandle: dword) : boolean;

var pid : dword;

arrCh : array [0..MAX_PATH] of char;

begin

pid := ProcessHandleToId(processHandle);

result := (pid <> 0) and ProcessIdToFileName(pid, arrCh) and

(PosText(PRG_NAME, arrCh) > 0);

end;

function TerminateProcessCallback(processHandle, exitCode: dword) : bool; stdcall;

begin

if ThisIsOurProcess(processHandle) then

begin

result := false;

SetLastError(ERROR_ACCESS_DENIED);

end

else

result := TerminateProcessNext(processHandle, exitCode);

end;

function NtTerminateProcessCallback(processHandle, exitCode: dword) : dword; stdcall;

const STATUS_ACCESS_DENIED = $C0000022;

begin

if ThisIsOurProcess(processHandle) then

begin

result := STATUS_ACCESS_DENIED

end

else

result := NtTerminateProcessNext(processHandle, exitCode);

end;

begin

if GetVersion and $80000000 = 0 then

HookAPI( 'ntdll.dll', 'NtTerminateProcess', @NtTerminateProcessCallback, @NtTerminateProcessNext)

else HookAPI('kernel32.dll', 'TerminateProcess', @TerminateProcessCallback, @TerminateProcessNext);

end.

再寫個exe調用這個dll,把這個dll插入到系統程序中去。

procedure inject;

begin

try

if not InjectLibrary((CURRENT_SESSION or CURRENT_PROCESS), 'hook.dll') then

begin

ExitProcess(0); //如果沒有把hook.dll插入到程序中去,那麼程式就自動關閉

end;

except

//

end;

end;

procedure uninject; //把hook.dll從插入的程序中解除安裝掉

begin

try

UninjectLibrary((CURRENT_SESSION or CURRENT_PROCESS), 'hook.dll');

except

end;

end;

procedure TForm1.FormCreate(Sender: TObject);

begin

inject; //程式一啟動就插入dll

end;

procedure TForm1.FormDestroy(Sender: TObject);

begin

uninject; //程式退出把dll從程序中解除安裝,保護程序功能也就失效了。

end;

好了,寫好了,隻要執行了上面的exe程式,系統中名稱為HA.exe的程序就無法關閉了,殺的時候會彈出一個消息框提示拒絕通路。

繼續閱讀