http://www.rohitab.com/discuss/topic/36942-hooking-zwopenprocess-to-protect-processes/
I have coded this hook to protect processes by returning a STATUS_ACCESS_DENIED. I have tried to make a function that will get the PID from the process "Server.exe" but it did'nt work. I'm asking for your help here at Rohitab.
#include "ntddk.h"
// Hooking ZwOpenProcess to protect a process by returning a STATUS_ACCESS_DENIED
// The PID of my process
int PID = 1234; // I want to get the PID from the process "SERVER.EXE"
NTSYSAPI
NTSTATUS
NTAPI ZwOpenProcess (OUT PHANDLE ProcessHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, IN PCLIENT_ID ClientId OPTIONAL);
typedef NTSTATUS (*ZWOPENPROCESS)(OUT PHANDLE ProcessHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, IN PCLIENT_ID ClientId OPTIONAL);
// OldZwOpenProcess points to the original function
ZWOPENPROCESS OldZwOpenProcess;
// This is my hook function that will replace the kernel function ZwOpenProcess in the System Service Dispatch Table (SSDT)
NTSTATUS NewZwOpenProcess(OUT PHANDLE ProcessHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, IN PCLIENT_ID ClientId OPTIONAL)
{
HANDLE ProcessId;
__try
{
ProcessId = ClientId->UniqueProcess;
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
return STATUS_INVALID_PARAMETER;
}
if (ProcessId == (HANDLE)PID) // Check if the PID matches my protected process
{
return STATUS_ACCESS_DENIED; // Return a Acess Denied
}
else
return OldZwOpenProcess(ProcessHandle, DesiredAccess,ObjectAttributes, ClientId); // Return the original ZwOpenProcess
}
You can use
CreateToolhelp32Snapshot to create a snapshot of all processes on the system. Then you loop over it with
Process32First and
Process32Next until you find a process that has "server.exe" as main module.
Here is some example code from msdn