HyperDbg/hyperdbg/hyperhv/code/memory/Layout.c

98 lines
2.2 KiB
C
Raw Permalink Normal View History

/**
* @file Layout.c
* @author Sina Karvandi (sina@hyperdbg.org)
2023-04-27 18:21:55 +09:00
* @brief Functions for working with memory layouts
*
* @version 0.2
* @date 2023-04-27
*
* @copyright This project is released under the GNU Public License v3.
*
*/
#include "pch.h"
/**
2023-04-27 18:21:55 +09:00
* @brief Converts pid to kernel cr3
*
2023-04-27 18:21:55 +09:00
* @details this function should NOT be called from vmx-root
*
* @param ProcessId ProcessId to switch
2023-04-27 18:21:55 +09:00
* @return CR3_TYPE The cr3 of the target process
*/
_Use_decl_annotations_
CR3_TYPE
2023-04-27 18:21:55 +09:00
LayoutGetCr3ByProcessId(UINT32 ProcessId)
{
PEPROCESS TargetEprocess;
2023-04-27 18:21:55 +09:00
CR3_TYPE ProcessCr3 = {0};
2024-03-02 23:58:00 +09:00
if (PsLookupProcessByProcessId((HANDLE)ProcessId, &TargetEprocess) != STATUS_SUCCESS)
{
//
// There was an error, probably the process id was not found
//
2023-04-27 18:21:55 +09:00
return ProcessCr3;
}
//
// Due to KVA Shadowing, we need to switch to a different directory table base
// if the PCID indicates this is a user mode directory table base.
//
NT_KPROCESS * CurrentProcess = (NT_KPROCESS *)(TargetEprocess);
2023-04-27 18:21:55 +09:00
ProcessCr3.Flags = CurrentProcess->DirectoryTableBase;
ObDereferenceObject(TargetEprocess);
2023-04-27 18:21:55 +09:00
return ProcessCr3;
}
/**
2023-04-27 18:21:55 +09:00
* @brief Get cr3 of the target running process
*
2023-04-27 18:21:55 +09:00
* @return CR3_TYPE Returns the cr3 of running process
*/
CR3_TYPE
2023-04-27 18:21:55 +09:00
LayoutGetCurrentProcessCr3()
{
CR3_TYPE GuestCr3;
//
2023-04-27 18:21:55 +09:00
// Due to KVA Shadowing, we need to switch to a different directory table base
// if the PCID indicates this is a user mode directory table base.
//
2023-04-27 18:21:55 +09:00
NT_KPROCESS * CurrentProcess = (NT_KPROCESS *)(PsGetCurrentProcess());
GuestCr3.Flags = CurrentProcess->DirectoryTableBase;
2023-04-27 18:21:55 +09:00
return GuestCr3;
}
/**
* @brief Get cr3 of the target running process
*
* @return CR3_TYPE Returns the cr3 of running process
*/
CR3_TYPE
LayoutGetExactGuestProcessCr3()
{
CR3_TYPE GuestCr3 = {0};
2026-04-19 15:57:52 +02:00
VmxVmread64P(VMCS_GUEST_CR3, &GuestCr3.Flags);
return GuestCr3;
}
/**
2023-04-27 18:21:55 +09:00
* @brief Find cr3 of system process
*
2023-04-27 18:21:55 +09:00
* @return UINT64 Returns cr3 of System process (pid=4)
*/
2023-04-27 18:21:55 +09:00
UINT64
LayoutGetSystemDirectoryTableBase()
{
//
2023-04-27 18:21:55 +09:00
// Return CR3 of the system process.
//
2023-04-27 18:21:55 +09:00
NT_KPROCESS * SystemProcess = (NT_KPROCESS *)(PsInitialSystemProcess);
return SystemProcess->DirectoryTableBase;
}