#include <windows.h>
#include <stdio.h>
typedef
NTSTATUS(WINAPI* PNT_QUERY_INFORMATION_PROCESS)(
HANDLE
ProcessHandle,
PROCESSINFOCLASS ProcessInformationClass,
PVOID
ProcessInformation,
ULONG
ProcessInformationLength,
PULONG
ReturnLength
);
void
PrintLastError(
DWORD
error) {
LPVOID
lpMsgBuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL, error,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(
LPTSTR
)& lpMsgBuf, 0, NULL);
printf
(
"Error: %s"
, (
LPCTSTR
)lpMsgBuf);
LocalFree(lpMsgBuf);
}
DWORD_PTR
GetPebAddress(
DWORD
PID) {
DWORD_PTR
pebAddress = 0;
HMODULE
ntdll = LoadLibraryA(
"ntdll.dll"
);
PNT_QUERY_INFORMATION_PROCESS NtQueryInformationProcess =
(PNT_QUERY_INFORMATION_PROCESS)GetProcAddress(ntdll,
"NtQueryInformationProcess"
);
HANDLE
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, PID);
if
(hProcess != NULL) {
PROCESS_BASIC_INFORMATION pbi;
ULONG
returnLength;
NTSTATUS status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, (
PVOID
)& pbi,
sizeof
(PROCESS_BASIC_INFORMATION), & returnLength);
if
(status == STATUS_SUCCESS) {
pebAddress = (
DWORD_PTR
)pbi.PebBaseAddress;
}
else
{
PrintLastError(status);
}
CloseHandle(hProcess);
}
FreeLibrary(ntdll);
return
pebAddress;
}
int
main() {
DWORD
PID = 1234;
DWORD_PTR
pebAddress = GetPebAddress(PID);
if
(pebAddress == 0) {
printf
(
"Failed to get PEB address for process %ld"
, PID);
}
else
{
printf
(
"PEB address for process %ld: 0x%p"
, PID, (
LPVOID
)pebAddress);
}
return
0;
}