您现在的位置:首页 >> API >> API >> 内容

Delphi中Hook API进行进程保护

时间:2011/9/3 14:52:13 点击:

  核心提示:const PRG_NAME = 'HA.exe';var TerminateProcessNext : function (processHandle, exitCode: dword) : boo...

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

作者:网络 来源:转载
共有评论 0相关评论
发表我的评论
  • 大名:
  • 内容:
本类推荐
  • 没有
本类固顶
  • 没有
  • 盒子文章(www.2ccc.com) © 2024 版权所有 All Rights Reserved.
  • 沪ICP备05001939号