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的进程就无法关闭了,杀的时候会弹出一个消息框提示拒绝访问。

Posted in 软件开发 by 傻猫 at September 11, 2015.
Tags: 进程, API

添加新评论