Delphi中Hook API进行进程保护(不允许进程结束的方法)

减小字体 增大字体 作者:佚名  来源:转载  发布时间:2011-02-18 12:56:54

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

来自:http://blog.csdn.net/aroc_lo/archive/2009/11/27/4878811.aspx

Tags:

作者:佚名
  • 好的评价 如果您觉得此文章好,就请您
      0%(0)
  • 差的评价 如果您觉得此文章差,就请您
      0%(0)

文章评论评论内容只代表网友观点,与本站立场无关!

   评论摘要(共 0 条,得分 0 分,平均 0 分) 查看完整评论

广告位置B