function HookAPIFunction(hFromModule: HMODULE;pszFunctionModule: PAnsiChar; pszFunctionName: PAnsiChar;pfnNewProc: Pointer): Pointer; var pfnOriginalProc: Pointer; pDosHeader: PImageDosHeader; pNTHeader: PImageNtHeaders; pImportDesc: PImageImportDescriptor; pThunk: PImageThunkData; dwProtectionFlags,dwScratch: DWORD; pszModName: PAnsiChar; begin Result := nil; pfnOriginalProc := GetProcAddress(GetModuleHandle(pszFunctionModule), pszFunctionName); pDosHeader := PImageDosHeader(hFromModule); pNTHeader := PImageNTHeaders(DWORD(pDosHeader)+DWORD(pDosHeader^._lfanew)); pImportDesc := PImageImportDescriptor(DWORD(pDosHeader)+ DWORD(pNTHeader^.OptionalHeader. DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]. VirtualAddress)); while pImportDesc^.Name <> 0 do begin pszModName := PAnsiChar(Pointer(DWORD(pDosHeader) + DWORD(pImportDesc^.Name))); if LowerCase(pszModName) = LowerCase(pszFunctionModule) then Break; Inc(pImportDesc); end; if pImportDesc^.Name = 0 then Exit; pThunk := PImageThunkData(DWORD(pDosHeader) + DWORD(pImportDesc^.FirstThunk)); while pThunk^.Function_ <> 0 do begin if (pThunk^.Function_ = DWORD(pfnOriginalProc)) then begin dwProtectionFlags := PAGE_READWRITE; VirtualProtect(@pThunk^.Function_,4096,dwProtectionFlags,@dwScratch); pThunk^.Function_ := DWORD(pfnNewProc); Result := pfnOriginalProc ; Break; end; Inc(pThunk); end; end;
function OpenProcessHandler(dwDesiredAccess: DWORD; bInheritHandle: BOOL; dwProcessId: DWORD): THandle; stdcall; begin Result := OriginalOpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId); if (dwProcessID = PID) and (PID <> 0) then Result := 0; end;
//防杀的进程ID,从注册表中获得 procedure GetHookProcessID; var TempKey: HKEY; DataType,Size: Integer; begin PID := 0; Size := Sizeof(Integer); if RegOpenKeyEx(HKEY_LOCAL_MACHINE,’Software\Vssoft’, 0,KEY_READ, TempKey) = ERROR_SUCCESS then begin RegQueryValueEx(TempKey,’ProcessID’,nil,@DataType,PByte(@PID),@Size); RegCloseKey(TempKey); end; end;
function HookOpenProcess(nCode: Integer;wParam: WPARAM;lParam: LPARAM): LRESULT;stdcall; begin GetHookProcessID; if not Assigned(OriginalOpenProcess) then OriginalOpenProcess := HookAPIFunction(GetModuleHandle(nil), ’KERNEL32.DLL’,’OpenProcess’,@OpenProcessHandler); Result := 0; end;