Aktualizacja: 2025-10-16 23:31:18

This commit is contained in:
wesmar
2025-10-16 23:31:18 +02:00
parent e0db9452e4
commit 6aca506715
3 changed files with 46 additions and 422 deletions

View File

@@ -1,14 +1,4 @@
/** // Implementation of Windows Defender Security Engine management
* @file DefenderManager.cpp
* @brief Implementation of Windows Defender Security Engine management
* @author Marek Wesolowski
* @date 2025
* @copyright KVC Framework
*
* Implements registry-level manipulation of Windows Defender service dependencies.
* Provides atomic operations for enabling/disabling the security engine by modifying
* RPC service dependencies in the Windows registry.
*/
#include "DefenderManager.h" #include "DefenderManager.h"
#include "common.h" #include "common.h"
@@ -26,47 +16,21 @@ extern void SetColor(int color);
// PUBLIC INTERFACE IMPLEMENTATION // PUBLIC INTERFACE IMPLEMENTATION
// ============================================================================ // ============================================================================
/** // Disables Windows Defender security engine by modifying registry dependencies
* @brief Disables Windows Defender security engine
*
* Implementation details:
* 1. Calls ModifySecurityEngine(false) to perform registry manipulation
* 2. Provides user feedback through console output
*
* @return bool true if Defender successfully disabled, false on failure
*/
bool DefenderManager::DisableSecurityEngine() noexcept bool DefenderManager::DisableSecurityEngine() noexcept
{ {
std::wcout << L"Disabling Windows Security Engine...\n"; std::wcout << L"Disabling Windows Security Engine...\n";
return ModifySecurityEngine(false); return ModifySecurityEngine(false);
} }
/** // Enables Windows Defender security engine by modifying registry dependencies
* @brief Enables Windows Defender security engine
*
* Implementation details:
* 1. Calls ModifySecurityEngine(true) to perform registry manipulation
* 2. Provides user feedback through console output
*
* @return bool true if Defender successfully enabled, false on failure
*/
bool DefenderManager::EnableSecurityEngine() noexcept bool DefenderManager::EnableSecurityEngine() noexcept
{ {
std::wcout << L"Enabling Windows Security Engine...\n"; std::wcout << L"Enabling Windows Security Engine...\n";
return ModifySecurityEngine(true); return ModifySecurityEngine(true);
} }
/** // Queries current Windows Defender state by checking RpcSs (enabled) or RpcSt (disabled) in service dependencies
* @brief Queries current Windows Defender security engine state
*
* Detection logic:
* 1. Opens Windows Defender service registry key (read-only)
* 2. Reads DependOnService REG_MULTI_SZ value
* 3. Searches for RpcSs (enabled) or RpcSt (disabled) in dependencies
* 4. Returns ENABLED if RpcSs found, DISABLED if RpcSt found, UNKNOWN otherwise
*
* @return SecurityState Current state of Windows Defender security engine
*/
DefenderManager::SecurityState DefenderManager::GetSecurityEngineStatus() noexcept DefenderManager::SecurityState DefenderManager::GetSecurityEngineStatus() noexcept
{ {
try { try {
@@ -98,21 +62,7 @@ DefenderManager::SecurityState DefenderManager::GetSecurityEngineStatus() noexce
// CORE OPERATIONS IMPLEMENTATION // CORE OPERATIONS IMPLEMENTATION
// ============================================================================ // ============================================================================
/** // Core registry manipulation logic - creates snapshot, modifies dependencies, and restores atomically
* @brief Core registry manipulation logic for enable/disable operations
*
* Atomic operation sequence:
* 1. Enable required privileges (SE_BACKUP_NAME, SE_RESTORE_NAME, SE_LOAD_DRIVER_NAME)
* 2. Create registry snapshot of Services hive to temp file
* 3. Modify Windows Defender dependencies in temp registry
* 4. Restore modified registry snapshot to live system
*
* @param enable true to enable Defender (RpcSt→RpcSs), false to disable (RpcSs→RpcSt)
* @return bool true if all operations successful, false on any failure
*
* @note All operations are atomic - partial failure results in rollback
* @note Provides detailed console feedback for each step
*/
bool DefenderManager::ModifySecurityEngine(bool enable) noexcept bool DefenderManager::ModifySecurityEngine(bool enable) noexcept
{ {
try { try {
@@ -151,23 +101,7 @@ bool DefenderManager::ModifySecurityEngine(bool enable) noexcept
} }
} }
/** // Creates temporary registry snapshot by saving Services hive to temp file and loading as HKLM\Temp
* @brief Creates temporary registry snapshot for atomic modifications
*
* Process:
* 1. Get system temp path (Windows\temp)
* 2. Validate write access to temp directory
* 3. Clean up any existing Services.hiv file
* 4. Unload any existing HKLM\Temp registry hive
* 5. Save HKLM\SYSTEM\CurrentControlSet\Services to Services.hiv
* 6. Load Services.hiv as HKLM\Temp for modification
*
* @param ctx [out] Registry context populated with temp paths and hive file
* @return bool true if snapshot created successfully, false on failure
*
* @note Uses REG_LATEST_FORMAT for maximum compatibility
* @note Cleans up existing temp hives to prevent conflicts
*/
bool DefenderManager::CreateRegistrySnapshot(RegistryContext& ctx) noexcept bool DefenderManager::CreateRegistrySnapshot(RegistryContext& ctx) noexcept
{ {
ctx.tempPath = ::GetSystemTempPath(); ctx.tempPath = ::GetSystemTempPath();
@@ -221,24 +155,7 @@ bool DefenderManager::CreateRegistrySnapshot(RegistryContext& ctx) noexcept
return true; return true;
} }
/** // Modifies Windows Defender service dependencies in temp registry by transforming RpcSs↔RpcSt
* @brief Modifies Windows Defender service dependencies in temp registry
*
* Modification logic:
* 1. Opens HKLM\Temp\WinDefend key (loaded from snapshot)
* 2. Reads DependOnService REG_MULTI_SZ value
* 3. Transforms RPC service dependency:
* - Enable: RpcSt (inactive stub) → RpcSs (active service)
* - Disable: RpcSs (active service) → RpcSt (inactive stub)
* 4. Writes modified dependencies back to temp registry
*
* @param ctx Registry context with loaded temp hive
* @param enable true to enable Defender, false to disable
* @return bool true if dependency modification successful, false on failure
*
* @note Operates only on temp registry (HKLM\Temp), not live system
* @note Automatically closes registry key handle on exit
*/
bool DefenderManager::ModifyDefenderDependencies(const RegistryContext& ctx, bool enable) noexcept bool DefenderManager::ModifyDefenderDependencies(const RegistryContext& ctx, bool enable) noexcept
{ {
HKEY tempKey; HKEY tempKey;
@@ -275,22 +192,7 @@ bool DefenderManager::ModifyDefenderDependencies(const RegistryContext& ctx, boo
return true; return true;
} }
/** // Restores modified registry snapshot to live system by unloading temp hive and forcing restore
* @brief Restores modified registry snapshot to live system registry
*
* Restoration process:
* 1. Unload temporary HKLM\Temp registry hive (modified snapshot)
* 2. Open HKLM\SYSTEM\CurrentControlSet\Services key with write access
* 3. Restore modified hive file using RegRestoreKeyW with force flag
* 4. Close registry key handle
*
* @param ctx Registry context with modified hive file path
* @return bool true if restore successful, false on failure
*
* @warning This operation permanently modifies the live system registry
* @note Uses REG_FORCE_RESTORE to overwrite existing registry data
* @note Warnings about failed unload are informational only (non-critical)
*/
bool DefenderManager::RestoreRegistrySnapshot(const RegistryContext& ctx) noexcept bool DefenderManager::RestoreRegistrySnapshot(const RegistryContext& ctx) noexcept
{ {
// Unload temporary registry hive // Unload temporary registry hive
@@ -320,19 +222,7 @@ bool DefenderManager::RestoreRegistrySnapshot(const RegistryContext& ctx) noexce
// PRIVILEGE MANAGEMENT IMPLEMENTATION // PRIVILEGE MANAGEMENT IMPLEMENTATION
// ============================================================================ // ============================================================================
/** // Enables SE_BACKUP_NAME, SE_RESTORE_NAME and SE_LOAD_DRIVER_NAME privileges required for registry operations
* @brief Enables all required privileges for registry operations
*
* Required privileges:
* - SE_BACKUP_NAME: Allows reading registry hives (RegSaveKeyExW)
* - SE_RESTORE_NAME: Allows writing registry hives (RegRestoreKeyW)
* - SE_LOAD_DRIVER_NAME: Allows loading/unloading registry hives (RegLoadKeyW/RegUnLoadKeyW)
*
* @return bool true if all three privileges enabled successfully, false if any fails
*
* @note All three privileges must be enabled for registry snapshot operations
* @note Failure of any single privilege causes entire operation to fail
*/
bool DefenderManager::EnableRequiredPrivileges() noexcept bool DefenderManager::EnableRequiredPrivileges() noexcept
{ {
return PrivilegeUtils::EnablePrivilege(SE_BACKUP_NAME) && return PrivilegeUtils::EnablePrivilege(SE_BACKUP_NAME) &&
@@ -344,25 +234,7 @@ bool DefenderManager::EnableRequiredPrivileges() noexcept
// HELPER UTILITIES IMPLEMENTATION // HELPER UTILITIES IMPLEMENTATION
// ============================================================================ // ============================================================================
/** // Reads REG_MULTI_SZ registry value as string vector by parsing null-terminated strings
* @brief Reads REG_MULTI_SZ registry value as string vector
*
* Reading process:
* 1. Query value type and size using RegQueryValueExW (initial call)
* 2. Validate value is REG_MULTI_SZ type
* 3. Allocate buffer for value data
* 4. Read value data into buffer
* 5. Parse null-terminated strings from buffer
* 6. Return vector of strings (empty vector on failure)
*
* @param key Open registry key handle with KEY_READ access
* @param valueName Name of REG_MULTI_SZ value to read
* @return std::vector<std::wstring> Vector of strings, empty if value doesn't exist or wrong type
*
* @note Returns empty vector if value is wrong type or doesn't exist
* @note Properly handles null-terminated string array format
* @note Does not close registry key handle (caller's responsibility)
*/
vector<wstring> DefenderManager::ReadMultiString(HKEY key, const wstring& valueName) noexcept vector<wstring> DefenderManager::ReadMultiString(HKEY key, const wstring& valueName) noexcept
{ {
DWORD type, size; DWORD type, size;
@@ -388,23 +260,7 @@ vector<wstring> DefenderManager::ReadMultiString(HKEY key, const wstring& valueN
return result; return result;
} }
/** // Writes string vector to REG_MULTI_SZ registry value with proper double null terminator
* @brief Writes string vector to REG_MULTI_SZ registry value
*
* Writing process:
* 1. Create buffer for null-terminated string array
* 2. Copy each string to buffer with null terminator
* 3. Add final double null terminator
* 4. Write buffer to registry using RegSetValueExW
*
* @param key Open registry key handle with KEY_WRITE access
* @param valueName Name of REG_MULTI_SZ value to write
* @param values Vector of strings to write
* @return bool true if write successful, false on failure
*
* @note Properly formats with double null terminator (REG_MULTI_SZ requirement)
* @note Does not close registry key handle (caller's responsibility)
*/
bool DefenderManager::WriteMultiString(HKEY key, const wstring& valueName, bool DefenderManager::WriteMultiString(HKEY key, const wstring& valueName,
const vector<wstring>& values) noexcept const vector<wstring>& values) noexcept
{ {
@@ -425,19 +281,7 @@ bool DefenderManager::WriteMultiString(HKEY key, const wstring& valueName,
// REGISTRY CONTEXT CLEANUP IMPLEMENTATION // REGISTRY CONTEXT CLEANUP IMPLEMENTATION
// ============================================================================ // ============================================================================
/** // Cleans up temporary registry files including hive, transaction logs and regtrans-ms files
* @brief Cleans up temporary registry files and transaction logs
*
* Cleanup targets:
* 1. Main hive file (Services.hiv)
* 2. Transaction logs (Services.hiv.LOG1, Services.hiv.LOG2)
* 3. Binary log file (Services.hiv.blf)
* 4. Registry transaction files (*.regtrans-ms in temp directory)
*
* @note Safe to call multiple times (idempotent operation)
* @note Ignores errors during cleanup (best-effort cleanup)
* @note Called automatically by RegistryContext destructor
*/
void DefenderManager::RegistryContext::Cleanup() noexcept void DefenderManager::RegistryContext::Cleanup() noexcept
{ {
if (hiveFile.empty()) return; if (hiveFile.empty()) return;

View File

@@ -1,19 +1,4 @@
/** // Kernel Vulnerability Capabilities Framework - Main Application Entry Point
* @file kvc.cpp
* @brief Kernel Vulnerability Capabilities Framework - Main Application Entry Point
* @author Marek Wesolowski
* @date 2025
* @copyright KVC Framework
*
* Main command-line interface for the KVC framework providing:
* - Process protection manipulation (PP/PPL)
* - Memory dumping operations
* - Browser password extraction
* - Windows Defender management
* - Registry operations
* - System service integration
* - TrustedInstaller privilege escalation
*/
#include "common.h" #include "common.h"
#include "Controller.h" #include "Controller.h"
@@ -33,10 +18,10 @@
// GLOBAL STATE // GLOBAL STATE
// ============================================================================ // ============================================================================
/** @brief Global controller instance for driver and system operations */ // Global controller instance for driver and system operations
std::unique_ptr<Controller> g_controller; std::unique_ptr<Controller> g_controller;
/** @brief Signal handler flag for graceful shutdown */ // Signal handler flag for graceful shutdown
volatile bool g_interrupted = false; volatile bool g_interrupted = false;
// ============================================================================ // ============================================================================
@@ -54,13 +39,7 @@ bool InitiateSystemRestart() noexcept;
// SIGNAL HANDLERS // SIGNAL HANDLERS
// ============================================================================ // ============================================================================
/** // Emergency signal handler for Ctrl+C - ensures proper driver cleanup to prevent system instability
* @brief Emergency signal handler for Ctrl+C interruption
*
* Ensures proper driver cleanup on emergency exit to prevent system instability.
*
* @param signum Signal number (SIGINT)
*/
void SignalHandler(int signum) void SignalHandler(int signum)
{ {
if (signum == SIGINT) { if (signum == SIGINT) {
@@ -75,15 +54,7 @@ void SignalHandler(int signum)
// HELPER FUNCTIONS // HELPER FUNCTIONS
// ============================================================================ // ============================================================================
/** // Robust PID parsing with validation using std::from_chars, rejects non-ASCII characters
* @brief Robust PID parsing with comprehensive validation
*
* @param pidStr String view containing PID value
* @return std::optional<DWORD> Parsed PID or nullopt on invalid input
*
* @note Uses std::from_chars for efficient and safe parsing
* @note Rejects non-ASCII characters
*/
std::optional<DWORD> ParsePid(std::wstring_view pidStr) noexcept std::optional<DWORD> ParsePid(std::wstring_view pidStr) noexcept
{ {
if (pidStr.empty()) return std::nullopt; if (pidStr.empty()) return std::nullopt;
@@ -106,12 +77,7 @@ std::optional<DWORD> ParsePid(std::wstring_view pidStr) noexcept
std::make_optional(result) : std::nullopt; std::make_optional(result) : std::nullopt;
} }
/** // Checks if string contains only digits
* @brief Checks if string contains only digits
*
* @param str String to validate
* @return bool true if string is purely numeric
*/
bool IsNumeric(std::wstring_view str) noexcept bool IsNumeric(std::wstring_view str) noexcept
{ {
if (str.empty()) return false; if (str.empty()) return false;
@@ -124,14 +90,7 @@ bool IsNumeric(std::wstring_view str) noexcept
return true; return true;
} }
/** // Recognizes various help flag formats: /?, /help, /h, -?, -help, -h, --help, --h, help, ?
* @brief Recognizes various help flag formats for user convenience
*
* Supports: /?, /help, /h, -?, -help, -h, --help, --h, help, ?
*
* @param arg Argument to check
* @return bool true if argument is a help flag
*/
bool IsHelpFlag(std::wstring_view arg) noexcept bool IsHelpFlag(std::wstring_view arg) noexcept
{ {
if (arg == L"/?" || arg == L"/help" || arg == L"/h") if (arg == L"/?" || arg == L"/help" || arg == L"/h")
@@ -149,11 +108,7 @@ bool IsHelpFlag(std::wstring_view arg) noexcept
return false; return false;
} }
/** // Checks if kvc_pass.exe exists in current directory or System32
* @brief Checks if kvc_pass.exe exists in current directory or System32
*
* @return bool true if kvc_pass.exe is found
*/
bool CheckKvcPassExists() noexcept bool CheckKvcPassExists() noexcept
{ {
// Check current directory // Check current directory
@@ -170,13 +125,7 @@ bool CheckKvcPassExists() noexcept
return false; return false;
} }
/** // Initiates system restart with SE_SHUTDOWN_NAME privilege for security engine changes
* @brief Initiates system restart with proper privilege escalation
*
* Used after security engine changes that require reboot.
*
* @return bool true if restart initiated successfully
*/
bool InitiateSystemRestart() noexcept bool InitiateSystemRestart() noexcept
{ {
HANDLE token; HANDLE token;
@@ -211,11 +160,7 @@ bool InitiateSystemRestart() noexcept
SHTDN_REASON_MAJOR_SOFTWARE | SHTDN_REASON_MINOR_RECONFIGURE) != 0; SHTDN_REASON_MAJOR_SOFTWARE | SHTDN_REASON_MINOR_RECONFIGURE) != 0;
} }
/** // Emergency cleanup for driver resources - called on exit or Ctrl+C
* @brief Emergency cleanup for driver resources
*
* Called on exit or Ctrl+C to prevent system instability.
*/
void CleanupDriver() noexcept void CleanupDriver() noexcept
{ {
if (g_controller) { if (g_controller) {
@@ -227,23 +172,7 @@ void CleanupDriver() noexcept
// MAIN APPLICATION ENTRY POINT // MAIN APPLICATION ENTRY POINT
// ============================================================================ // ============================================================================
/** // Main entry point with comprehensive command handling for service management, process operations, browser extraction, security operations and more
* @brief Main application entry point with comprehensive command handling
*
* Supported commands:
* - Service management: install, uninstall, service
* - Process operations: list, protect, unprotect, set, dump, kill
* - Browser extraction: browser-passwords, bp, export
* - System integration: trusted, install-context, add-exclusion
* - Security operations: shift, unshift, disable-defender, enable-defender
* - Registry: registry backup/restore/defrag
* - Session management: restore, history, cleanup-sessions
* - Advanced: setup, evtclear
*
* @param argc Argument count
* @param argv Argument vector
* @return int Exit code (0=success, 1=error, 2=operation failed, 3=exception)
*/
int wmain(int argc, wchar_t* argv[]) int wmain(int argc, wchar_t* argv[])
{ {
// Install signal handler for emergency cleanup on Ctrl+C // Install signal handler for emergency cleanup on Ctrl+C
@@ -510,7 +439,7 @@ int wmain(int argc, wchar_t* argv[])
} }
} }
else if (command == L"get") { else if (command == L"get") {
if (argc < 3) { if (argc < 3) {
ERROR(L"Missing PID/process name argument"); ERROR(L"Missing PID/process name argument");
return 1; return 1;
@@ -977,7 +906,8 @@ int wmain(int argc, wchar_t* argv[])
return g_controller->AddToDefenderExclusions(path) ? 0 : 2; return g_controller->AddToDefenderExclusions(path) ? 0 : 2;
} }
} }
else if (command == L"remove-exclusion") {
else if (command == L"remove-exclusion") {
// Legacy: no args = remove self // Legacy: no args = remove self
if (argc < 3) { if (argc < 3) {
wchar_t exePath[MAX_PATH]; wchar_t exePath[MAX_PATH];
@@ -1012,6 +942,7 @@ int wmain(int argc, wchar_t* argv[])
return g_controller->RemoveFromDefenderExclusions(path) ? 0 : 2; return g_controller->RemoveFromDefenderExclusions(path) ? 0 : 2;
} }
} }
else if (command == L"disable-defender") { else if (command == L"disable-defender") {
INFO(L"Disabling Windows Defender (requires restart)..."); INFO(L"Disabling Windows Defender (requires restart)...");
bool result = DefenderManager::DisableSecurityEngine(); bool result = DefenderManager::DisableSecurityEngine();

View File

@@ -1,13 +1,4 @@
/** // KVC kernel driver communication implementation- Implements low-level IOCTL communication with the KVC kernel driver
* @file kvcDrv.cpp
* @brief KVC kernel driver communication implementation
* @author Marek Wesolowski
* @date 2025
* @copyright KVC Framework
*
* Implements low-level IOCTL communication with the KVC kernel driver
* for safe memory read/write operations in kernel space.
*/
#include "kvcDrv.h" #include "kvcDrv.h"
#include "common.h" #include "common.h"
@@ -16,24 +7,20 @@
// IOCTL COMMAND CODES (DRIVER-SPECIFIC) // IOCTL COMMAND CODES (DRIVER-SPECIFIC)
// ============================================================================ // ============================================================================
/** @brief IOCTL code for kernel memory read operations */ // IOCTL code for kernel memory read operations
constexpr DWORD RTC_IOCTL_MEMORY_READ = 0x80002048; constexpr DWORD RTC_IOCTL_MEMORY_READ = 0x80002048;
/** @brief IOCTL code for kernel memory write operations */ // IOCTL code for kernel memory write operations
constexpr DWORD RTC_IOCTL_MEMORY_WRITE = 0x8000204c; constexpr DWORD RTC_IOCTL_MEMORY_WRITE = 0x8000204c;
// ============================================================================ // ============================================================================
// CONSTRUCTION AND DESTRUCTION // CONSTRUCTION AND DESTRUCTION
// ============================================================================ // ============================================================================
/** // Default constructor - initializes empty driver object
* @brief Default constructor - initializes empty driver object
*/
kvc::kvc() = default; kvc::kvc() = default;
/** // Destructor - ensures proper resource cleanup
* @brief Destructor - ensures proper resource cleanup
*/
kvc::~kvc() kvc::~kvc()
{ {
Cleanup(); Cleanup();
@@ -43,17 +30,7 @@ kvc::~kvc()
// DRIVER CONNECTION MANAGEMENT // DRIVER CONNECTION MANAGEMENT
// ============================================================================ // ============================================================================
/** // Cleans up driver resources by flushing buffers, closing handle and clearing device name
* @brief Cleans up driver resources with proper flushing
*
* Performs orderly shutdown:
* 1. Flushes file buffers to ensure all pending operations complete
* 2. Resets smart handle (automatically calls CloseHandle)
* 3. Clears device name
*
* @note Safe to call multiple times - idempotent operation
* @note Critical for system stability - prevents hanging IOCTL operations
*/
void kvc::Cleanup() noexcept void kvc::Cleanup() noexcept
{ {
DEBUG(L"kvc::Cleanup() called"); DEBUG(L"kvc::Cleanup() called");
@@ -72,32 +49,13 @@ void kvc::Cleanup() noexcept
DEBUG(L"kvc cleanup completed"); DEBUG(L"kvc cleanup completed");
} }
/** // Checks if driver connection is active
* @brief Checks if driver connection is active
*
* @return bool true if device handle is valid and not INVALID_HANDLE_VALUE
*/
bool kvc::IsConnected() const noexcept bool kvc::IsConnected() const noexcept
{ {
return m_deviceHandle && m_deviceHandle.get() != INVALID_HANDLE_VALUE; return m_deviceHandle && m_deviceHandle.get() != INVALID_HANDLE_VALUE;
} }
/** // Establishes connection to KVC kernel driver by opening device handle with read/write access
* @brief Establishes connection to KVC kernel driver
*
* Connection sequence:
* 1. Checks if already connected (idempotent)
* 2. Constructs device name from service name
* 3. Initializes dynamic APIs for CreateFileW
* 4. Opens device handle with read/write access
* 5. Wraps raw handle in smart pointer for RAII
*
* @return bool true if driver device opened successfully
*
* @note Does NOT perform test operations - just opens device
* @note Silently fails if driver not loaded (expected behavior)
* @note Requires dynamic API initialization for CreateFileW
*/
bool kvc::Initialize() noexcept bool kvc::Initialize() noexcept
{ {
// Idempotent check - return early if already connected // Idempotent check - return early if already connected
@@ -145,14 +103,7 @@ bool kvc::Initialize() noexcept
// MEMORY READ OPERATIONS (TYPE-SAFE WRAPPERS) // MEMORY READ OPERATIONS (TYPE-SAFE WRAPPERS)
// ============================================================================ // ============================================================================
/** // Reads 8-bit value from kernel memory by extracting lowest byte from 32-bit read
* @brief Reads 8-bit value from kernel memory
*
* @param address Target kernel address
* @return std::optional<BYTE> Read value or nullopt on failure
*
* @note Extracts lowest byte from 32-bit read result
*/
std::optional<BYTE> kvc::Read8(ULONG_PTR address) noexcept std::optional<BYTE> kvc::Read8(ULONG_PTR address) noexcept
{ {
auto value = Read32(address); auto value = Read32(address);
@@ -162,14 +113,7 @@ std::optional<BYTE> kvc::Read8(ULONG_PTR address) noexcept
return static_cast<BYTE>(value.value() & 0xFF); return static_cast<BYTE>(value.value() & 0xFF);
} }
/** // Reads 16-bit value from kernel memory by extracting lowest 2 bytes from 32-bit read
* @brief Reads 16-bit value from kernel memory
*
* @param address Target kernel address
* @return std::optional<WORD> Read value or nullopt on failure
*
* @note Extracts lowest 2 bytes from 32-bit read result
*/
std::optional<WORD> kvc::Read16(ULONG_PTR address) noexcept std::optional<WORD> kvc::Read16(ULONG_PTR address) noexcept
{ {
auto value = Read32(address); auto value = Read32(address);
@@ -179,30 +123,13 @@ std::optional<WORD> kvc::Read16(ULONG_PTR address) noexcept
return static_cast<WORD>(value.value() & 0xFFFF); return static_cast<WORD>(value.value() & 0xFFFF);
} }
/** // Reads 32-bit value from kernel memory via direct IOCTL call
* @brief Reads 32-bit value from kernel memory
*
* @param address Target kernel address
* @return std::optional<DWORD> Read value or nullopt on failure
*
* @note Direct call to low-level Read() function
*/
std::optional<DWORD> kvc::Read32(ULONG_PTR address) noexcept std::optional<DWORD> kvc::Read32(ULONG_PTR address) noexcept
{ {
return Read(address, sizeof(DWORD)); return Read(address, sizeof(DWORD));
} }
/** // Reads 64-bit value from kernel memory by performing two 32-bit reads and combining them
* @brief Reads 64-bit value from kernel memory
*
* @param address Target kernel address
* @return std::optional<DWORD64> Read value or nullopt on failure
*
* @note Performs two 32-bit reads and combines them:
* - Low DWORD at address
* - High DWORD at address + 4
* @note Both reads must succeed for operation to succeed
*/
std::optional<DWORD64> kvc::Read64(ULONG_PTR address) noexcept std::optional<DWORD64> kvc::Read64(ULONG_PTR address) noexcept
{ {
auto low = Read32(address); auto low = Read32(address);
@@ -216,16 +143,7 @@ std::optional<DWORD64> kvc::Read64(ULONG_PTR address) noexcept
return (static_cast<DWORD64>(high.value()) << 32) | low.value(); return (static_cast<DWORD64>(high.value()) << 32) | low.value();
} }
/** // Reads pointer-sized value from kernel memory (64-bit on x64, 32-bit on x86)
* @brief Reads pointer-sized value from kernel memory
*
* @param address Target kernel address
* @return std::optional<ULONG_PTR> Read value or nullopt on failure
*
* @note Platform-dependent:
* - x64: Uses Read64
* - x86: Uses Read32
*/
std::optional<ULONG_PTR> kvc::ReadPtr(ULONG_PTR address) noexcept std::optional<ULONG_PTR> kvc::ReadPtr(ULONG_PTR address) noexcept
{ {
#ifdef _WIN64 #ifdef _WIN64
@@ -247,63 +165,25 @@ std::optional<ULONG_PTR> kvc::ReadPtr(ULONG_PTR address) noexcept
// MEMORY WRITE OPERATIONS (TYPE-SAFE WRAPPERS) // MEMORY WRITE OPERATIONS (TYPE-SAFE WRAPPERS)
// ============================================================================ // ============================================================================
/** // Writes 8-bit value to kernel memory (WARNING: can cause system instability)
* @brief Writes 8-bit value to kernel memory
*
* @param address Target kernel address
* @param value Value to write
* @return bool true if write successful
*
* @warning Kernel memory writes can cause system instability
*/
bool kvc::Write8(ULONG_PTR address, BYTE value) noexcept bool kvc::Write8(ULONG_PTR address, BYTE value) noexcept
{ {
return Write(address, sizeof(value), value); return Write(address, sizeof(value), value);
} }
/** // Writes 16-bit value to kernel memory (WARNING: can cause system instability)
* @brief Writes 16-bit value to kernel memory
*
* @param address Target kernel address
* @param value Value to write
* @return bool true if write successful
*
* @warning Kernel memory writes can cause system instability
*/
bool kvc::Write16(ULONG_PTR address, WORD value) noexcept bool kvc::Write16(ULONG_PTR address, WORD value) noexcept
{ {
return Write(address, sizeof(value), value); return Write(address, sizeof(value), value);
} }
/** // Writes 32-bit value to kernel memory (WARNING: can cause system instability)
* @brief Writes 32-bit value to kernel memory
*
* @param address Target kernel address
* @param value Value to write
* @return bool true if write successful
*
* @warning Kernel memory writes can cause system instability
*/
bool kvc::Write32(ULONG_PTR address, DWORD value) noexcept bool kvc::Write32(ULONG_PTR address, DWORD value) noexcept
{ {
return Write(address, sizeof(value), value); return Write(address, sizeof(value), value);
} }
/** // Writes 64-bit value to kernel memory via two 32-bit writes (WARNING: non-atomic, can cause system instability)
* @brief Writes 64-bit value to kernel memory
*
* @param address Target kernel address
* @param value Value to write
* @return bool true if write successful
*
* @note Performs two 32-bit writes:
* - Low DWORD at address
* - High DWORD at address + 4
* @note Both writes must succeed for operation to succeed
*
* @warning Kernel memory writes can cause system instability
* @warning Non-atomic operation - system may observe partial write
*/
bool kvc::Write64(ULONG_PTR address, DWORD64 value) noexcept bool kvc::Write64(ULONG_PTR address, DWORD64 value) noexcept
{ {
DWORD low = static_cast<DWORD>(value & 0xFFFFFFFF); DWORD low = static_cast<DWORD>(value & 0xFFFFFFFF);
@@ -317,22 +197,7 @@ bool kvc::Write64(ULONG_PTR address, DWORD64 value) noexcept
// LOW-LEVEL IOCTL COMMUNICATION // LOW-LEVEL IOCTL COMMUNICATION
// ============================================================================ // ============================================================================
/** // Low-level kernel memory read via IOCTL using aligned RTC_MEMORY_READ structure
* @brief Low-level kernel memory read via IOCTL
*
* Communication sequence:
* 1. Ensures driver connection is initialized
* 2. Constructs RTC_MEMORY_READ request structure
* 3. Sends IOCTL_MEMORY_READ command to driver
* 4. Extracts returned value from response
*
* @param address Kernel address to read from
* @param valueSize Size of value to read (1/2/4 bytes)
* @return std::optional<DWORD> Read value or nullopt on failure
*
* @note Uses aligned structure for IOCTL communication
* @note Driver returns value in response structure
*/
std::optional<DWORD> kvc::Read(ULONG_PTR address, DWORD valueSize) noexcept std::optional<DWORD> kvc::Read(ULONG_PTR address, DWORD valueSize) noexcept
{ {
// Construct read request with proper alignment // Construct read request with proper alignment
@@ -369,23 +234,7 @@ std::optional<DWORD> kvc::Read(ULONG_PTR address, DWORD valueSize) noexcept
return memoryRead.Value; return memoryRead.Value;
} }
/** // Low-level kernel memory write via IOCTL (WARNING: can cause BSOD if address is invalid)
* @brief Low-level kernel memory write via IOCTL
*
* Communication sequence:
* 1. Ensures driver connection is initialized
* 2. Constructs RTC_MEMORY_WRITE request structure
* 3. Sends IOCTL_MEMORY_WRITE command to driver
* 4. Checks for successful completion
*
* @param address Kernel address to write to
* @param valueSize Size of value to write (1/2/4 bytes)
* @param value Value to write
* @return bool true if write successful
*
* @note Uses aligned structure for IOCTL communication
* @warning Kernel writes can cause BSOD if address is invalid
*/
bool kvc::Write(ULONG_PTR address, DWORD valueSize, DWORD value) noexcept bool kvc::Write(ULONG_PTR address, DWORD valueSize, DWORD value) noexcept
{ {
// Construct write request with proper alignment // Construct write request with proper alignment