Aktualizacja: 2025-10-05 12:43:36
This commit is contained in:
924
kvc/Controller.h
924
kvc/Controller.h
File diff suppressed because it is too large
Load Diff
@@ -11,18 +11,27 @@
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
|
||||
/**
|
||||
* @class DefenderManager
|
||||
* @brief Windows Defender Security Engine management through registry manipulation
|
||||
*
|
||||
* This class provides low-level control over Windows Defender by modifying
|
||||
* service dependencies in the registry. Works by changing RPC service dependencies
|
||||
* (RpcSs <-> RpcSt) to enable or disable the security engine.
|
||||
*
|
||||
* Features:
|
||||
* - Registry-level Defender engine control
|
||||
* - Bypasses Windows Defender tamper protection
|
||||
* - Atomic operations with rollback on failure
|
||||
* - Service dependency manipulation
|
||||
* - Privilege escalation for registry access
|
||||
*
|
||||
* @warning Requires SE_BACKUP_NAME, SE_RESTORE_NAME, and SE_LOAD_DRIVER_NAME privileges
|
||||
* @warning System restart required for changes to take effect
|
||||
* @warning Bypasses Windows Defender tamper protection
|
||||
@@ -31,6 +40,9 @@ class DefenderManager {
|
||||
public:
|
||||
/**
|
||||
* @brief Security engine state enumeration
|
||||
*
|
||||
* Represents current state of Windows Defender security engine
|
||||
* based on service dependency configuration.
|
||||
*/
|
||||
enum class SecurityState {
|
||||
ENABLED, ///< Windows Defender security engine is active (RpcSs dependency)
|
||||
@@ -44,6 +56,12 @@ public:
|
||||
* Modifies Windows Defender service dependencies to prevent engine startup.
|
||||
* Changes RpcSs (active) dependency to RpcSt (inactive stub service).
|
||||
*
|
||||
* Operation:
|
||||
* 1. Enables required privileges
|
||||
* 2. Creates registry snapshot
|
||||
* 3. Modifies WinDefend service dependencies
|
||||
* 4. Restores modified registry
|
||||
*
|
||||
* @return bool true if operation successful, false on failure
|
||||
*
|
||||
* @note Requires administrator privileges
|
||||
@@ -58,6 +76,12 @@ public:
|
||||
* Restores Windows Defender service dependencies to normal operation.
|
||||
* Changes RpcSt (inactive) dependency back to RpcSs (active service).
|
||||
*
|
||||
* Operation:
|
||||
* 1. Enables required privileges
|
||||
* 2. Creates registry snapshot
|
||||
* 3. Restores original dependencies
|
||||
* 4. Restores modified registry
|
||||
*
|
||||
* @return bool true if operation successful, false on failure
|
||||
*
|
||||
* @note Requires administrator privileges
|
||||
@@ -74,6 +98,7 @@ public:
|
||||
* @return SecurityState Current state of Windows Defender security engine
|
||||
*
|
||||
* @note Does not require elevated privileges for read-only query
|
||||
* @note Safe operation - no system modifications
|
||||
*/
|
||||
static SecurityState GetSecurityEngineStatus() noexcept;
|
||||
|
||||
@@ -83,34 +108,42 @@ private:
|
||||
*
|
||||
* Holds temporary registry hive files and paths for atomic
|
||||
* modification of Windows Defender service configuration.
|
||||
* Provides automatic cleanup via destructor.
|
||||
*/
|
||||
struct RegistryContext {
|
||||
std::wstring tempPath; ///< Temporary working directory path
|
||||
std::wstring hiveFile; ///< Saved registry hive file path
|
||||
|
||||
/**
|
||||
* @brief Default constructor
|
||||
*/
|
||||
RegistryContext() = default;
|
||||
|
||||
/**
|
||||
* @brief Destructor - automatically cleans up temporary files
|
||||
*
|
||||
* Ensures all temporary files are removed when context
|
||||
* goes out of scope, even in case of exceptions.
|
||||
*/
|
||||
~RegistryContext() { Cleanup(); }
|
||||
|
||||
// Non-copyable, movable
|
||||
RegistryContext(const RegistryContext&) = delete;
|
||||
RegistryContext& operator=(const RegistryContext&) = delete;
|
||||
RegistryContext(RegistryContext&&) = default;
|
||||
RegistryContext& operator=(RegistryContext&&) = default;
|
||||
RegistryContext(const RegistryContext&) = delete; ///< Copy constructor deleted
|
||||
RegistryContext& operator=(const RegistryContext&) = delete; ///< Copy assignment deleted
|
||||
RegistryContext(RegistryContext&&) = default; ///< Move constructor
|
||||
RegistryContext& operator=(RegistryContext&&) = default; ///< Move assignment
|
||||
|
||||
/**
|
||||
* @brief Cleans up temporary registry files and transaction logs
|
||||
*
|
||||
* Removes:
|
||||
* - Main hive file
|
||||
* Removes all temporary files created during registry operations:
|
||||
* - Main hive file (.hiv)
|
||||
* - Transaction logs (.LOG1, .LOG2)
|
||||
* - Binary log files (.blf)
|
||||
* - Registry transaction files (.regtrans-ms)
|
||||
*
|
||||
* @note Safe to call multiple times (idempotent operation)
|
||||
* @note Handles file locking and access violations
|
||||
*/
|
||||
void Cleanup() noexcept;
|
||||
};
|
||||
@@ -128,6 +161,7 @@ private:
|
||||
* @return bool true if all operations successful, false on any failure
|
||||
*
|
||||
* @note Atomic operation - changes are rolled back on failure
|
||||
* @note Uses registry transaction pattern for safety
|
||||
*/
|
||||
static bool ModifySecurityEngine(bool enable) noexcept;
|
||||
|
||||
@@ -140,6 +174,8 @@ private:
|
||||
* - SE_LOAD_DRIVER_NAME: Load/unload registry hives
|
||||
*
|
||||
* @return bool true if all privileges enabled, false on any failure
|
||||
*
|
||||
* @note Essential for registry backup/restore operations
|
||||
*/
|
||||
static bool EnableRequiredPrivileges() noexcept;
|
||||
|
||||
@@ -156,13 +192,14 @@ private:
|
||||
* @return bool true if snapshot created successfully, false on failure
|
||||
*
|
||||
* @note Creates Services.hiv file in Windows\temp directory
|
||||
* @note Isolated environment for safe registry manipulation
|
||||
*/
|
||||
static bool CreateRegistrySnapshot(RegistryContext& ctx) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Modifies Windows Defender service dependencies in temp registry
|
||||
*
|
||||
* Changes RPC service dependency:
|
||||
* Changes RPC service dependency in WinDefend service:
|
||||
* - Enable: RpcSt (inactive) → RpcSs (active)
|
||||
* - Disable: RpcSs (active) → RpcSt (inactive)
|
||||
*
|
||||
@@ -171,6 +208,7 @@ private:
|
||||
* @return bool true if dependency modification successful, false on failure
|
||||
*
|
||||
* @note Operates on HKLM\Temp\WinDefend key, not live registry
|
||||
* @note Uses REG_MULTI_SZ value type for service dependencies
|
||||
*/
|
||||
static bool ModifyDefenderDependencies(const RegistryContext& ctx, bool enable) noexcept;
|
||||
|
||||
@@ -187,35 +225,36 @@ private:
|
||||
*
|
||||
* @warning This operation modifies the live system registry
|
||||
* @note Uses REG_FORCE_RESTORE to overwrite existing registry data
|
||||
* @note Critical operation - affects system security configuration
|
||||
*/
|
||||
static bool RestoreRegistrySnapshot(const RegistryContext& ctx) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Reads REG_MULTI_SZ registry value as string vector
|
||||
*
|
||||
* @param key Open registry key handle
|
||||
* @param valueName Name of REG_MULTI_SZ value to read
|
||||
* @return std::vector<std::wstring> Vector of strings or empty on failure
|
||||
*
|
||||
* @note Returns empty vector if value doesn't exist or wrong type
|
||||
* @note Handles double null-terminated string format
|
||||
*/
|
||||
static std::vector<std::wstring> ReadMultiString(HKEY key, const std::wstring& valueName) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Writes string vector to REG_MULTI_SZ registry value
|
||||
*
|
||||
* @param key Open registry key handle
|
||||
* @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
|
||||
* @note Handles empty vectors and single string cases
|
||||
*/
|
||||
static bool WriteMultiString(HKEY key, const std::wstring& valueName, const std::vector<std::wstring>& values) noexcept;
|
||||
|
||||
// Registry constants
|
||||
static constexpr const wchar_t* WINDEFEND_KEY = L"SYSTEM\\CurrentControlSet\\Services\\WinDefend"; ///< Windows Defender service key
|
||||
static constexpr const wchar_t* SERVICES_KEY = L"SYSTEM\\CurrentControlSet\\Services"; ///< Windows Services root key
|
||||
static constexpr const wchar_t* WINDEFEND_KEY = L"SYSTEM\\CurrentControlSet\\Services\\WinDefend"; ///< Windows Defender service registry key
|
||||
static constexpr const wchar_t* SERVICES_KEY = L"SYSTEM\\CurrentControlSet\\Services"; ///< Windows Services root registry key
|
||||
static constexpr const wchar_t* DEPEND_VALUE = L"DependOnService"; ///< Service dependency value name
|
||||
static constexpr const wchar_t* RPC_SERVICE_ACTIVE = L"RpcSs"; ///< Active RPC service (enables Defender)
|
||||
static constexpr const wchar_t* RPC_SERVICE_INACTIVE = L"RpcSt"; ///< Inactive RPC stub (disables Defender)
|
||||
|
||||
388
kvc/HelpSystem.h
388
kvc/HelpSystem.h
@@ -1,47 +1,411 @@
|
||||
/**
|
||||
* @file HelpSystem.h
|
||||
* @brief Comprehensive help system with modular command documentation
|
||||
* @author Marek Wesolowski
|
||||
* @date 2025
|
||||
* @copyright KVC Framework
|
||||
*
|
||||
* Provides formatted help output with color-coded sections, usage examples,
|
||||
* and detailed command explanations.
|
||||
* Modular design allows displaying specific help sections as needed.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "common.h"
|
||||
#include <string_view>
|
||||
|
||||
// Comprehensive help system for kvc with modular command documentation
|
||||
/**
|
||||
* @class HelpSystem
|
||||
* @brief Comprehensive help system for KVC with modular command documentation
|
||||
*
|
||||
* Features:
|
||||
* - Color-coded section headers for readability
|
||||
* - Categorized command listings by functionality
|
||||
* - Detailed parameter explanations
|
||||
* - Usage examples with real scenarios
|
||||
* - Technical feature documentation
|
||||
* - Security notices and warnings
|
||||
*
|
||||
* Help Categories:
|
||||
* - Basic commands (help, list, info)
|
||||
* - Process protection (protect, unprotect, set)
|
||||
* - Process termination (kill)
|
||||
* - Windows Defender management
|
||||
* - DPAPI password extraction
|
||||
* - Browser credential extraction
|
||||
* - Service management
|
||||
* - Registry operations
|
||||
* - Security engine control
|
||||
*
|
||||
* @note Static class - no instantiation required
|
||||
* @note Uses ANSI color codes for enhanced readability
|
||||
*/
|
||||
class HelpSystem
|
||||
{
|
||||
public:
|
||||
HelpSystem() = delete;
|
||||
~HelpSystem() = delete;
|
||||
HelpSystem() = delete; ///< Constructor deleted - static class
|
||||
~HelpSystem() = delete; ///< Destructor deleted - static class
|
||||
|
||||
// Main help interface
|
||||
// === Main Help Interface ===
|
||||
|
||||
/**
|
||||
* @brief Print complete usage information
|
||||
* @param programName Program name for display in examples
|
||||
*
|
||||
* Displays all help sections in organized format:
|
||||
* 1. Program header with version and author
|
||||
* 2. Basic command documentation
|
||||
* 3. Process protection commands
|
||||
* 4. System commands
|
||||
* 5. Process termination commands
|
||||
* 6. Windows Defender commands
|
||||
* 7. DPAPI extraction commands
|
||||
* 8. Browser extraction commands
|
||||
* 9. Service management commands
|
||||
* 10. Protection type explanations
|
||||
* 11. Usage examples
|
||||
* 12. Security notice and footer
|
||||
*
|
||||
* @note Comprehensive help covering all framework features
|
||||
*/
|
||||
static void PrintUsage(std::wstring_view programName) noexcept;
|
||||
|
||||
// Specific help sections
|
||||
/**
|
||||
* @brief Print header with version and author info
|
||||
*
|
||||
* Displays KVC banner with ASCII art, version information,
|
||||
* author credits, and copyright notice.
|
||||
*
|
||||
* @note Uses color coding for visual appeal
|
||||
*/
|
||||
static void PrintHeader() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Print basic command documentation
|
||||
*
|
||||
* Commands covered:
|
||||
* - help: Display help information
|
||||
* - list: List protected processes
|
||||
* - info: Show process protection information
|
||||
*
|
||||
* @note Basic commands available without special privileges
|
||||
*/
|
||||
static void PrintBasicCommands() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Print process protection command documentation
|
||||
*
|
||||
* Commands covered:
|
||||
* - protect: Add protection to unprotected process
|
||||
* - unprotect: Remove protection from process
|
||||
* - set: Force set protection level (overwrite)
|
||||
* - set-signer: Change protection for specific signer
|
||||
* - restore: Restore protection from session
|
||||
*
|
||||
* @note Requires driver and appropriate privileges
|
||||
*/
|
||||
static void PrintProtectionCommands() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Print system command documentation
|
||||
*
|
||||
* Commands covered:
|
||||
* - dump: Dump process memory to file
|
||||
* - elevate: Elevate current process protection
|
||||
* - clear-logs: Clear Windows event logs
|
||||
*
|
||||
* @note Advanced operations requiring high privileges
|
||||
*/
|
||||
static void PrintSystemCommands() noexcept;
|
||||
static void PrintProcessTerminationCommands() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Print process termination command documentation
|
||||
*
|
||||
* Commands covered:
|
||||
* - kill: Terminate process with protection matching
|
||||
* - kill multiple: Terminate multiple processes
|
||||
*
|
||||
* @note Supports both PID and name-based targeting
|
||||
*/
|
||||
static void PrintProcessTerminationCommands() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Print Windows Defender command documentation
|
||||
*
|
||||
* Commands covered:
|
||||
* - defender-enable: Enable Windows Defender exclusions
|
||||
* - defender-disable: Disable Windows Defender exclusions
|
||||
* - defender-add: Add specific exclusion
|
||||
* - defender-remove: Remove specific exclusion
|
||||
*
|
||||
* @note Requires TrustedInstaller privileges for some operations
|
||||
*/
|
||||
static void PrintDefenderCommands() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Print DPAPI extraction command documentation
|
||||
*
|
||||
* Commands covered:
|
||||
* - extract-passwords: Extract passwords from Chrome/Edge/WiFi
|
||||
* - master-keys: Display extracted master keys
|
||||
* - decrypt: Decrypt specific DPAPI blob
|
||||
*
|
||||
* @note Requires TrustedInstaller privileges for registry access
|
||||
*/
|
||||
static void PrintDPAPICommands() noexcept;
|
||||
static void PrintBrowserCommands() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Print browser credential extraction documentation
|
||||
*
|
||||
* Commands covered:
|
||||
* - chrome-passwords: Extract Chrome passwords only
|
||||
* - edge-passwords: Extract Edge passwords only
|
||||
* - browser-all: Extract from all supported browsers
|
||||
*
|
||||
* @note Uses SQLite and AES-GCM decryption for browser data
|
||||
*/
|
||||
static void PrintBrowserCommands() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Print service management command documentation
|
||||
*
|
||||
* Commands covered:
|
||||
* - service-install: Install as Windows Service
|
||||
* - service-start: Start service
|
||||
* - service-stop: Stop service
|
||||
* - service-uninstall: Uninstall service
|
||||
*
|
||||
* @note Requires administrative privileges
|
||||
*/
|
||||
static void PrintServiceCommands() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Print protection type documentation
|
||||
*
|
||||
* Explains PP (Protected Process) and PPL (Protected Process Light)
|
||||
* concepts, including:
|
||||
* - Protection level differences
|
||||
* - Signer type authorities
|
||||
* - Signature verification levels
|
||||
* - Practical implications
|
||||
*
|
||||
* @note Technical background for protection operations
|
||||
*/
|
||||
static void PrintProtectionTypes() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Print Defender exclusion type documentation
|
||||
*
|
||||
* Explains different exclusion types:
|
||||
* - Paths: File and folder exclusions
|
||||
* - Processes: Process name exclusions
|
||||
* - Extensions: File extension exclusions
|
||||
* - IPs: IP address exclusions
|
||||
*
|
||||
* @note Used with defender-add and defender-remove commands
|
||||
*/
|
||||
static void PrintExclusionTypes() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Print pattern matching documentation
|
||||
*
|
||||
* Explains wildcard and regex support in process targeting:
|
||||
* - Partial name matching
|
||||
* - Case-insensitive matching
|
||||
* - Multiple target specification
|
||||
* - Comma-separated lists
|
||||
*
|
||||
* @note Used in process targeting commands
|
||||
*/
|
||||
static void PrintPatternMatching() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Print technical features documentation
|
||||
*
|
||||
* Explains advanced technical features:
|
||||
* - Kernel offset discovery
|
||||
* - EPROCESS structure manipulation
|
||||
* - Driver communication
|
||||
* - TrustedInstaller integration
|
||||
* - Session state tracking
|
||||
*
|
||||
* @note For advanced users and developers
|
||||
*/
|
||||
static void PrintTechnicalFeatures() noexcept;
|
||||
static void PrintUnknownCommandMessage(std::wstring_view command) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Print unknown command message
|
||||
* @param command Unknown command that was entered
|
||||
*
|
||||
* Displays friendly error message when unknown command is entered.
|
||||
* Suggests using 'help' command for available options.
|
||||
*
|
||||
* @note User-friendly error handling
|
||||
*/
|
||||
static void PrintUnknownCommandMessage(std::wstring_view command) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Print Defender-specific notes and warnings
|
||||
*
|
||||
* Important information about Defender exclusion management:
|
||||
* - Real-time protection implications
|
||||
* - Exclusion persistence across reboots
|
||||
* - Security considerations
|
||||
* - Best practices
|
||||
*
|
||||
* @note Security-focused guidance
|
||||
*/
|
||||
static void PrintDefenderNotes() noexcept;
|
||||
static void PrintRegistryCommands() noexcept;
|
||||
static void PrintSecurityEngineCommands() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Print registry operation command documentation
|
||||
*
|
||||
* Commands covered:
|
||||
* - registry-backup: Backup registry hives
|
||||
* - registry-restore: Restore registry hives
|
||||
* - registry-defrag: Defragment registry
|
||||
*
|
||||
* @note Requires TrustedInstaller privileges
|
||||
*/
|
||||
static void PrintRegistryCommands() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Print security engine command documentation
|
||||
*
|
||||
* Commands covered:
|
||||
* - security-disable: Disable Windows Defender engine
|
||||
* - security-enable: Enable Windows Defender engine
|
||||
* - security-status: Check security engine status
|
||||
*
|
||||
* @note Advanced system modification - use with caution
|
||||
*/
|
||||
static void PrintSecurityEngineCommands() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Print session management documentation
|
||||
*
|
||||
* Explains boot session tracking and restoration:
|
||||
* - Session state persistence
|
||||
* - Automatic reboot detection
|
||||
* - Protection state restoration
|
||||
* - Session cleanup operations
|
||||
*
|
||||
* @note Cross-boot state tracking feature
|
||||
*/
|
||||
static void PrintSessionManagement() noexcept;
|
||||
static void PrintStickyKeysInfo() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Print sticky keys backdoor documentation
|
||||
*
|
||||
* Installation, removal, and security warnings for:
|
||||
* - Sticky keys backdoor mechanism
|
||||
* - Security implications
|
||||
* - Installation procedure
|
||||
* - Removal procedure
|
||||
*
|
||||
* @warning Security risk - authorized use only
|
||||
*/
|
||||
static void PrintStickyKeysInfo() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Print undumpable process documentation
|
||||
*
|
||||
* Lists processes with anti-dump protection:
|
||||
* - LSA protected processes
|
||||
- System critical processes
|
||||
* - Anti-malware protected processes
|
||||
* - Dumpability analysis results
|
||||
*
|
||||
* @note Processes that cannot be memory dumped
|
||||
*/
|
||||
static void PrintUndumpableProcesses() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Print usage examples with real scenarios
|
||||
* @param programName Program name for display in examples
|
||||
*
|
||||
* Shows practical command combinations for common tasks:
|
||||
* - Process protection manipulation
|
||||
* - Password extraction
|
||||
* - System maintenance
|
||||
* - Debugging and analysis
|
||||
*
|
||||
* @note Real-world usage scenarios
|
||||
*/
|
||||
static void PrintUsageExamples(std::wstring_view programName) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Print security notice and disclaimer
|
||||
*
|
||||
* Legal and ethical use warnings:
|
||||
* - Authorized testing only
|
||||
* - Legal compliance requirements
|
||||
* - Responsible disclosure
|
||||
* - Educational purposes
|
||||
*
|
||||
* @note Important legal and ethical considerations
|
||||
*/
|
||||
static void PrintSecurityNotice() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Print footer with donation links
|
||||
*
|
||||
* Support information and donation links:
|
||||
* - PayPal donation link
|
||||
* - Revolut donation link
|
||||
* - Contact information
|
||||
* - Support acknowledgments
|
||||
*
|
||||
* @note Optional support for project development
|
||||
*/
|
||||
static void PrintFooter() noexcept;
|
||||
|
||||
private:
|
||||
// Helper methods for consistent formatting
|
||||
// === Helper Methods for Consistent Formatting ===
|
||||
|
||||
/**
|
||||
* @brief Print color-coded section header
|
||||
* @param title Section title to display
|
||||
*
|
||||
* Formats section headers with yellow color for visibility
|
||||
* and consistent spacing.
|
||||
*
|
||||
* @note Internal formatting helper
|
||||
*/
|
||||
static void PrintSectionHeader(const wchar_t* title) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Print formatted command line with description
|
||||
* @param command Command syntax
|
||||
* @param description Command description
|
||||
*
|
||||
* Displays command and description in aligned columns
|
||||
* for readability.
|
||||
*
|
||||
* @note Internal formatting helper
|
||||
*/
|
||||
static void PrintCommandLine(const wchar_t* command, const wchar_t* description) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Print informational note
|
||||
* @param note Note text to display
|
||||
*
|
||||
* Formats informational notes with indentation and
|
||||
* "Note:" prefix.
|
||||
*
|
||||
* @note Internal formatting helper
|
||||
*/
|
||||
static void PrintNote(const wchar_t* note) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Print warning message
|
||||
* @param warning Warning text to display
|
||||
*
|
||||
* Formats warning messages with red color, indentation,
|
||||
* and "WARNING:" prefix.
|
||||
*
|
||||
* @note Internal formatting helper
|
||||
*/
|
||||
static void PrintWarning(const wchar_t* warning) noexcept;
|
||||
};
|
||||
@@ -1,4 +1,15 @@
|
||||
// HiveManager.h
|
||||
/**
|
||||
* @file HiveManager.h
|
||||
* @brief Registry hive backup, restore and defragmentation manager
|
||||
* @author Marek Wesolowski
|
||||
* @date 2025
|
||||
* @copyright KVC Framework
|
||||
*
|
||||
* Provides atomic registry operations with TrustedInstaller privileges,
|
||||
* supporting full system registry backup and point-in-time restoration.
|
||||
* Handles locked system hives and provides defragmentation capabilities.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
@@ -11,62 +22,335 @@ namespace fs = std::filesystem;
|
||||
// Forward declaration
|
||||
class TrustedInstallerIntegrator;
|
||||
|
||||
// Registry hive backup, restore and defragmentation manager
|
||||
/**
|
||||
* @class HiveManager
|
||||
* @brief Registry hive backup, restore and defragmentation manager
|
||||
*
|
||||
* Features:
|
||||
* - Full registry backup with TrustedInstaller access
|
||||
* - Atomic hive restoration with automatic reboot
|
||||
* - Registry defragmentation via export/import cycle
|
||||
* - Handles locked system hives (SAM, SECURITY, SYSTEM)
|
||||
* - Automatic temp file cleanup
|
||||
* - Statistics tracking for operations
|
||||
*
|
||||
* Supported Hives:
|
||||
* - SYSTEM, SOFTWARE, SAM, SECURITY
|
||||
* - DEFAULT, NTUSER.DAT, UsrClass.dat
|
||||
* - User-specific hives with SID resolution
|
||||
*
|
||||
* @note Requires TrustedInstaller privileges for full functionality
|
||||
* @warning Registry operations can affect system stability
|
||||
*/
|
||||
class HiveManager
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Construct hive manager and initialize TrustedInstaller
|
||||
*
|
||||
* Initializes internal state, acquires TrustedInstaller token,
|
||||
* and gathers current user information (SID, username).
|
||||
*
|
||||
* @note Automatically gets current user SID and username
|
||||
*/
|
||||
HiveManager();
|
||||
|
||||
/**
|
||||
* @brief Destructor with token cleanup
|
||||
*
|
||||
* Releases TrustedInstaller token and reverts any active
|
||||
* impersonation. Ensures clean state on destruction.
|
||||
*/
|
||||
~HiveManager();
|
||||
|
||||
// Main operations
|
||||
// === Main Operations ===
|
||||
|
||||
/**
|
||||
* @brief Backup all registry hives to directory
|
||||
* @param targetPath Backup directory (empty = auto-generate)
|
||||
* @return true if backup successful
|
||||
*
|
||||
* Performs complete registry backup including:
|
||||
* - System hives (SYSTEM, SOFTWARE, SAM, SECURITY)
|
||||
* - User hives (DEFAULT, NTUSER.DAT, UsrClass.dat)
|
||||
* - Registry statistics collection
|
||||
* - Automatic directory creation
|
||||
*
|
||||
* Auto-generates path format: C:\RegistryBackup_{User}_{Timestamp}
|
||||
*
|
||||
* @note Requires TrustedInstaller privileges
|
||||
* @note Uses RegSaveKeyW for atomic hive saving
|
||||
*/
|
||||
bool Backup(const std::wstring& targetPath = L"");
|
||||
|
||||
/**
|
||||
* @brief Restore registry hives from backup directory
|
||||
* @param sourcePath Backup directory path
|
||||
* @return true if restoration successful
|
||||
*
|
||||
* Validates and restores registry hives from backup:
|
||||
* - Verifies backup file integrity
|
||||
* - Prompts for user confirmation
|
||||
* - Initiates system reboot for changes
|
||||
* - Uses RegRestoreKeyW for atomic restoration
|
||||
*
|
||||
* @note Validates backup files before restoration
|
||||
* @note Prompts for confirmation before reboot
|
||||
* @note System restart required for changes to take effect
|
||||
*/
|
||||
bool Restore(const std::wstring& sourcePath);
|
||||
|
||||
/**
|
||||
* @brief Defragment registry hives
|
||||
* @param tempPath Temporary directory (empty = auto-generate)
|
||||
* @return true if defragmentation successful
|
||||
*
|
||||
* Performs registry defragmentation by:
|
||||
* - Exporting hives to temporary files
|
||||
* - Re-importing hives to compact storage
|
||||
* - Reducing registry file fragmentation
|
||||
* - Improving registry performance
|
||||
*
|
||||
* @note Exports hives to temp, then re-imports
|
||||
* @note Reduces registry file size and improves performance
|
||||
*/
|
||||
bool Defrag(const std::wstring& tempPath = L"");
|
||||
|
||||
// Statistics
|
||||
/**
|
||||
* @struct BackupStats
|
||||
* @brief Statistics for backup/restore operations
|
||||
*
|
||||
* Tracks operation metrics for reporting and validation.
|
||||
*/
|
||||
struct BackupStats {
|
||||
size_t totalHives = 0;
|
||||
size_t successfulHives = 0;
|
||||
size_t failedHives = 0;
|
||||
uint64_t totalBytes = 0;
|
||||
size_t totalHives = 0; ///< Number of hives processed
|
||||
size_t successfulHives = 0; ///< Successfully backed up/restored hives
|
||||
size_t failedHives = 0; ///< Failed hive operations
|
||||
uint64_t totalBytes = 0; ///< Total bytes processed across all hives
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Get statistics from last operation
|
||||
* @return const BackupStats& Reference to backup statistics
|
||||
*
|
||||
* Provides access to operation statistics for display
|
||||
* and logging purposes.
|
||||
*
|
||||
* @note Statistics are reset at the start of each operation
|
||||
*/
|
||||
const BackupStats& GetLastStats() const { return m_lastStats; }
|
||||
|
||||
private:
|
||||
// Hive definitions
|
||||
/**
|
||||
* @struct RegistryHive
|
||||
* @brief Registry hive definition and metadata
|
||||
*
|
||||
* Contains hive identification and operational information
|
||||
* for registry hive processing.
|
||||
*/
|
||||
struct RegistryHive {
|
||||
std::wstring name;
|
||||
std::wstring registryPath;
|
||||
bool canRestore; // Can be restored with RegRestoreKeyW
|
||||
std::wstring name; ///< Hive name (e.g., "SYSTEM")
|
||||
std::wstring registryPath; ///< Registry path (e.g., "HKLM\\SYSTEM")
|
||||
bool canRestore; ///< Can be restored with RegRestoreKeyW
|
||||
};
|
||||
|
||||
// Internal operations
|
||||
// === Internal Operations ===
|
||||
|
||||
/**
|
||||
* @brief Backup all registry hives to target directory
|
||||
* @param targetDir Destination directory for backup files
|
||||
* @return true if all hives backed up successfully
|
||||
*
|
||||
* Iterates through all defined registry hives and saves
|
||||
* each to individual .hiv files in target directory.
|
||||
*
|
||||
* @note Uses SaveRegistryHive for individual hive operations
|
||||
*/
|
||||
bool BackupRegistryHives(const fs::path& targetDir);
|
||||
|
||||
/**
|
||||
* @brief Restore registry hives from backup directory
|
||||
* @param sourceDir Source directory with backup files
|
||||
* @return true if restoration validation successful
|
||||
*
|
||||
* Validates backup files and prepares for restoration.
|
||||
* Calls ApplyRestoreAndReboot for actual restoration.
|
||||
*
|
||||
* @note Validation step before destructive operation
|
||||
*/
|
||||
bool RestoreRegistryHives(const fs::path& sourceDir);
|
||||
|
||||
/**
|
||||
* @brief Apply restore and initiate system reboot
|
||||
* @param sourceDir Source directory with backup files
|
||||
* @return true if restore applied and reboot initiated
|
||||
*
|
||||
* Performs actual registry restoration and initiates
|
||||
* system reboot for changes to take effect.
|
||||
*
|
||||
* @note Uses InitiateSystemShutdownExW with 10 second delay
|
||||
* @note Destructive operation - cannot be undone
|
||||
*/
|
||||
bool ApplyRestoreAndReboot(const fs::path& sourceDir);
|
||||
|
||||
/**
|
||||
* @brief Save registry hive to file using RegSaveKeyW
|
||||
* @param registryPath Registry path (e.g., "HKLM\\SYSTEM")
|
||||
* @param destFile Destination file path
|
||||
* @return true if hive saved successfully
|
||||
*
|
||||
* Uses Windows API RegSaveKeyW to save registry hive
|
||||
* to disk file. Handles privilege requirements and
|
||||
* error conditions.
|
||||
*
|
||||
* @note Requires SE_BACKUP_NAME privilege
|
||||
* @note Atomic operation - all or nothing
|
||||
*/
|
||||
bool SaveRegistryHive(const std::wstring& registryPath, const fs::path& destFile);
|
||||
|
||||
/**
|
||||
* @brief Elevate to TrustedInstaller privileges
|
||||
* @return true if elevation successful
|
||||
*
|
||||
* Acquires TrustedInstaller token and enables required
|
||||
* privileges for registry operations.
|
||||
*
|
||||
* Required privileges:
|
||||
* - SE_BACKUP_NAME: For registry backup
|
||||
* - SE_RESTORE_NAME: For registry restoration
|
||||
* - SE_LOAD_DRIVER_NAME: For hive loading
|
||||
*
|
||||
* @note Essential for system hive access
|
||||
*/
|
||||
bool ElevateToTrustedInstaller();
|
||||
|
||||
/**
|
||||
* @brief Prompt user for Yes/No confirmation
|
||||
* @param question Question to display to user
|
||||
* @return true if user answered Yes
|
||||
*
|
||||
* Displays confirmation prompt and waits for user input.
|
||||
* Used for dangerous operations like registry restoration.
|
||||
*
|
||||
* @note Safety measure for destructive operations
|
||||
*/
|
||||
bool PromptYesNo(const wchar_t* question);
|
||||
|
||||
/**
|
||||
* @brief Generate default backup path with timestamp
|
||||
* @return fs::path Generated backup directory path
|
||||
*
|
||||
* Creates backup directory path in format:
|
||||
* C:\RegistryBackup_{Username}_{YYYY.MM.DD_HH.MM.SS}
|
||||
*
|
||||
* @note Uses current user and system time for uniqueness
|
||||
*/
|
||||
fs::path GenerateDefaultBackupPath();
|
||||
|
||||
/**
|
||||
* @brief Get current user SID string
|
||||
* @return std::wstring User SID string (e.g., "S-1-5-21-...")
|
||||
*
|
||||
* Retrieves current user's Security Identifier as string.
|
||||
* Used for user-specific hive operations and path generation.
|
||||
*
|
||||
* @note Cached for performance during same session
|
||||
*/
|
||||
std::wstring GetCurrentUserSid();
|
||||
|
||||
/**
|
||||
* @brief Get current username
|
||||
* @return std::wstring Current username
|
||||
*
|
||||
* Retrieves current user's account name for path generation
|
||||
* and display purposes.
|
||||
*
|
||||
* @note Cached for performance during same session
|
||||
*/
|
||||
std::wstring GetCurrentUsername();
|
||||
|
||||
/**
|
||||
* @brief Get physical file path for registry hive
|
||||
* @param hiveName Hive name (e.g., "SYSTEM")
|
||||
* @return fs::path Physical file path on disk
|
||||
*
|
||||
* Resolves registry hive name to physical file path
|
||||
* in Windows system directories.
|
||||
*
|
||||
* Handles special cases:
|
||||
* - NTUSER.DAT in user profile directories
|
||||
* - UsrClass.dat in user appdata directories
|
||||
* - System hives in System32\config
|
||||
*
|
||||
* @note Essential for hive file operations
|
||||
*/
|
||||
fs::path GetHivePhysicalPath(const std::wstring& hiveName);
|
||||
|
||||
/**
|
||||
* @brief Validate backup directory exists and is writable
|
||||
* @param path Directory path to validate
|
||||
* @return bool true if directory valid
|
||||
*
|
||||
* Per comprehensive directory validation:
|
||||
* - Existence check
|
||||
* - Directory type verification
|
||||
* - Write access testing
|
||||
* - Sufficient space check
|
||||
*
|
||||
* @note Critical for successful backup operations
|
||||
*/
|
||||
bool ValidateBackupDirectory(const fs::path& path);
|
||||
|
||||
/**
|
||||
* @brief Validate restore directory contains required files
|
||||
* @param path Directory path to validate
|
||||
* @return bool true if all required hive files exist
|
||||
*
|
||||
* Verifies that restore directory contains:
|
||||
* - All expected .hiv files
|
||||
* - Valid file sizes
|
||||
* - Read access to files
|
||||
* - Matching hive set
|
||||
*
|
||||
* @note Safety check before destructive restoration
|
||||
*/
|
||||
bool ValidateRestoreDirectory(const fs::path& path);
|
||||
|
||||
/**
|
||||
* @brief Initialize registry hive list with paths
|
||||
*
|
||||
* Populates m_registryHives with all supported registry hives
|
||||
* and their operational metadata.
|
||||
*
|
||||
* @note Called during construction
|
||||
*/
|
||||
void InitializeHiveLists();
|
||||
|
||||
/**
|
||||
* @brief Reset statistics counters
|
||||
*
|
||||
* Resets operation statistics to zero values.
|
||||
* Called at the start of each new operation.
|
||||
*/
|
||||
void ResetStats();
|
||||
|
||||
/**
|
||||
* @brief Print operation statistics
|
||||
* @param operation Operation name for display
|
||||
*
|
||||
* Displays operation statistics to console with
|
||||
* formatted output showing success/failure counts
|
||||
* and total bytes processed.
|
||||
*/
|
||||
void PrintStats(const std::wstring& operation);
|
||||
|
||||
// Data members
|
||||
std::vector<RegistryHive> m_registryHives;
|
||||
BackupStats m_lastStats;
|
||||
// === Data Members ===
|
||||
|
||||
HANDLE m_tiToken;
|
||||
TrustedInstallerIntegrator* m_tiIntegrator;
|
||||
std::wstring m_currentUserSid;
|
||||
std::wstring m_currentUsername;
|
||||
std::vector<RegistryHive> m_registryHives; ///< List of registry hives to process
|
||||
BackupStats m_lastStats; ///< Statistics from last operation
|
||||
|
||||
HANDLE m_tiToken; ///< TrustedInstaller token handle
|
||||
TrustedInstallerIntegrator* m_tiIntegrator; ///< TrustedInstaller integration component
|
||||
std::wstring m_currentUserSid; ///< Cached current user SID
|
||||
std::wstring m_currentUsername; ///< Cached current username
|
||||
};
|
||||
@@ -1,50 +1,202 @@
|
||||
/**
|
||||
* @file KeyboardHook.h
|
||||
* @brief Low-level keyboard hook for 5x Left Ctrl sequence detection
|
||||
* @author Marek Wesolowski
|
||||
* @date 2025
|
||||
* @copyright KVC Framework
|
||||
*
|
||||
* Provides global keyboard hook for detecting specific key sequences
|
||||
* and triggering TrustedInstaller command prompt activation.
|
||||
* Used for stealth system access and backdoor functionality.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "common.h"
|
||||
#include <chrono>
|
||||
#include <vector>
|
||||
|
||||
// Low-level keyboard hook for 5x Left Ctrl sequence detection
|
||||
/**
|
||||
* @class KeyboardHook
|
||||
* @brief Low-level keyboard hook for 5x Left Ctrl sequence detection
|
||||
*
|
||||
* Features:
|
||||
* - Global low-level keyboard hook installation
|
||||
* - 5x Left Ctrl sequence detection within 2 second window
|
||||
* - Key debouncing to prevent multiple triggers
|
||||
* - TrustedInstaller command prompt activation
|
||||
* - Stealth operation with no visible UI
|
||||
*
|
||||
* Sequence: Press Left Ctrl key 5 times within 2 seconds
|
||||
* Action: Launches cmd.exe with TrustedInstaller privileges
|
||||
*
|
||||
* @warning Security feature - authorized use only
|
||||
* @note Requires appropriate privileges for hook installation
|
||||
*/
|
||||
class KeyboardHook
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Construct keyboard hook manager
|
||||
*
|
||||
* Initializes internal state but does not install hook.
|
||||
* Call Install() to activate keyboard monitoring.
|
||||
*/
|
||||
KeyboardHook();
|
||||
|
||||
/**
|
||||
* @brief Destructor with automatic hook removal
|
||||
*
|
||||
* Automatically uninstalls keyboard hook if still active.
|
||||
* Ensures clean resource cleanup.
|
||||
*/
|
||||
~KeyboardHook();
|
||||
|
||||
KeyboardHook(const KeyboardHook&) = delete;
|
||||
KeyboardHook& operator=(const KeyboardHook&) = delete;
|
||||
// Disable copy semantics
|
||||
KeyboardHook(const KeyboardHook&) = delete; ///< Copy constructor deleted
|
||||
KeyboardHook& operator=(const KeyboardHook&) = delete; ///< Copy assignment deleted
|
||||
|
||||
// Hook management
|
||||
// === Hook Management ===
|
||||
|
||||
/**
|
||||
* @brief Install global keyboard hook
|
||||
* @return bool true if hook installed successfully
|
||||
*
|
||||
* Installs low-level keyboard hook using SetWindowsHookExW.
|
||||
* The hook monitors all keyboard events system-wide.
|
||||
*
|
||||
* @note Requires appropriate privileges for global hook
|
||||
* @note Hook callback runs in context of installing thread
|
||||
*/
|
||||
bool Install() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Uninstall keyboard hook
|
||||
*
|
||||
* Removes previously installed keyboard hook and
|
||||
* cleans up internal state. Safe to call if hook
|
||||
* is not installed.
|
||||
*/
|
||||
void Uninstall() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Check if keyboard hook is installed
|
||||
* @return bool true if hook is currently active
|
||||
*
|
||||
* Verifies that hook handle is valid and hook
|
||||
* is actively monitoring keyboard events.
|
||||
*/
|
||||
bool IsInstalled() const noexcept { return m_hookHandle != nullptr; }
|
||||
|
||||
// Configuration
|
||||
static constexpr int SEQUENCE_LENGTH = 5; // 5x Left Ctrl presses
|
||||
static constexpr DWORD SEQUENCE_TIMEOUT_MS = 2000; // 2 second window
|
||||
static constexpr DWORD DEBOUNCE_MS = 50; // Debounce period
|
||||
// === Configuration Constants ===
|
||||
|
||||
static constexpr int SEQUENCE_LENGTH = 5; ///< Number of Left Ctrl presses required
|
||||
static constexpr DWORD SEQUENCE_TIMEOUT_MS = 2000; ///< Time window for sequence completion
|
||||
static constexpr DWORD DEBOUNCE_MS = 50; ///< Key debounce period to prevent duplicates
|
||||
|
||||
private:
|
||||
// Hook callback
|
||||
// === Hook Callback ===
|
||||
|
||||
/**
|
||||
* @brief Low-level keyboard procedure (hook callback)
|
||||
* @param nCode Hook code indicating processing stage
|
||||
* @param wParam Event type (key down/up)
|
||||
* @param lParam Key event information structure
|
||||
* @return LRESULT Processing result
|
||||
*
|
||||
* System-wide keyboard hook callback function. Processes
|
||||
* all keyboard events and detects Left Ctrl sequences.
|
||||
*
|
||||
* @note Static callback required by Windows hook API
|
||||
* @note Must call CallNextHookEx for proper chain processing
|
||||
*/
|
||||
static LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam);
|
||||
|
||||
// Sequence tracking
|
||||
// === Sequence Tracking ===
|
||||
|
||||
/**
|
||||
* @struct KeyPress
|
||||
* @brief Individual key press tracking entry
|
||||
*
|
||||
* Stores timestamp and event type for sequence analysis.
|
||||
*/
|
||||
struct KeyPress {
|
||||
std::chrono::steady_clock::time_point timestamp;
|
||||
bool isPress; // true for key down, false for key up
|
||||
std::chrono::steady_clock::time_point timestamp; ///< Precise event timestamp
|
||||
bool isPress; ///< true for key down, false for key up
|
||||
};
|
||||
|
||||
static HHOOK m_hookHandle;
|
||||
static std::vector<KeyPress> m_leftCtrlSequence;
|
||||
static std::chrono::steady_clock::time_point m_lastKeyTime;
|
||||
static HHOOK m_hookHandle; ///< Windows hook handle
|
||||
static std::vector<KeyPress> m_leftCtrlSequence; ///< Left Ctrl press sequence buffer
|
||||
static std::chrono::steady_clock::time_point m_lastKeyTime; ///< Last key event time
|
||||
|
||||
// Internal logic
|
||||
// === Internal Logic ===
|
||||
|
||||
/**
|
||||
* @brief Process Left Ctrl key event
|
||||
* @param isKeyDown true for key press, false for key release
|
||||
*
|
||||
* Handles Left Ctrl key events and maintains sequence buffer.
|
||||
* Performs debouncing and timeout checks.
|
||||
*
|
||||
* @note Core sequence detection logic
|
||||
*/
|
||||
static void ProcessLeftCtrlEvent(bool isKeyDown) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Check if sequence is complete and valid
|
||||
* @return bool true if sequence conditions are met
|
||||
*
|
||||
* Validates sequence against configuration:
|
||||
* - Exactly SEQUENCE_LENGTH presses
|
||||
* - Within SEQUENCE_TIMEOUT_MS window
|
||||
* - No duplicate events from debouncing
|
||||
*
|
||||
* @note Sequence validation logic
|
||||
*/
|
||||
static bool CheckSequenceComplete() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Clear old entries from sequence buffer
|
||||
*
|
||||
* Removes expired key presses from sequence buffer
|
||||
* based on SEQUENCE_TIMEOUT_MS configuration.
|
||||
*
|
||||
* @note Maintains sequence buffer integrity
|
||||
*/
|
||||
static void ClearOldEntries() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Trigger TrustedInstaller command prompt
|
||||
*
|
||||
* Executes action when sequence is detected:
|
||||
* - Launches cmd.exe with TrustedInstaller privileges
|
||||
* - Uses stealth execution methods
|
||||
* - No visible window activation
|
||||
*
|
||||
* @note Core backdoor activation method
|
||||
*/
|
||||
static void TriggerTrustedInstallerCmd() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Launch command prompt with TrustedInstaller privileges
|
||||
* @return bool true if command prompt launched successfully
|
||||
*
|
||||
* Uses TrustedInstaller integration to launch cmd.exe
|
||||
* with maximum privileges for system access.
|
||||
*
|
||||
* @note Requires TrustedInstaller token acquisition
|
||||
*/
|
||||
static bool LaunchCmdWithTrustedInstaller() noexcept;
|
||||
|
||||
// Debugging and logging
|
||||
// === Debugging and Logging ===
|
||||
|
||||
/**
|
||||
* @brief Log current sequence state for debugging
|
||||
*
|
||||
* Outputs sequence buffer contents and timing information
|
||||
* for debugging and development purposes.
|
||||
*
|
||||
* @note Only active in debug builds
|
||||
*/
|
||||
static void LogSequenceState() noexcept;
|
||||
};
|
||||
110
kvc/KvcDrv.h
110
kvc/KvcDrv.h
@@ -1,12 +1,14 @@
|
||||
/**
|
||||
* @file kvcDrv.h
|
||||
* @brief KVC kernel driver communication interface
|
||||
* @author Marek Wesolowski
|
||||
* @author Marek Wesolowski
|
||||
* @date 2025
|
||||
* @copyright KVC Framework
|
||||
*
|
||||
* Provides low-level IOCTL-based communication with the KVC kernel driver
|
||||
* for memory read/write operations in kernel address space.
|
||||
* Features type-safe operations, automatic resource management, and
|
||||
* connection state tracking.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
@@ -24,15 +26,16 @@
|
||||
*
|
||||
* Layout optimized for driver IOCTL communication with explicit padding
|
||||
* to ensure consistent structure size across user/kernel boundary.
|
||||
* Used for reading kernel memory from user mode.
|
||||
*/
|
||||
struct alignas(8) RTC_MEMORY_READ
|
||||
{
|
||||
BYTE Pad0[8]; ///< Alignment padding
|
||||
DWORD64 Address; ///< Target kernel memory address
|
||||
BYTE Pad1[8]; ///< Additional padding
|
||||
DWORD Size; ///< Number of bytes to read (1/2/4/8)
|
||||
DWORD Value; ///< Returned value from kernel
|
||||
BYTE Pad3[16]; ///< Final padding for alignment
|
||||
BYTE Pad0[8]; ///< Alignment padding for 64-bit alignment
|
||||
DWORD64 Address; ///< Target kernel memory address to read from
|
||||
BYTE Pad1[8]; ///< Additional padding for structure alignment
|
||||
DWORD Size; ///< Number of bytes to read (1/2/4/8 bytes)
|
||||
DWORD Value; ///< Returned value from kernel memory
|
||||
BYTE Pad3[16]; ///< Final padding for IOCTL buffer alignment
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -40,15 +43,16 @@ struct alignas(8) RTC_MEMORY_READ
|
||||
*
|
||||
* Layout optimized for driver IOCTL communication with explicit padding
|
||||
* to ensure consistent structure size across user/kernel boundary.
|
||||
* Used for writing to kernel memory from user mode.
|
||||
*/
|
||||
struct alignas(8) RTC_MEMORY_WRITE
|
||||
{
|
||||
BYTE Pad0[8]; ///< Alignment padding
|
||||
DWORD64 Address; ///< Target kernel memory address
|
||||
BYTE Pad1[8]; ///< Additional padding
|
||||
DWORD Size; ///< Number of bytes to write (1/2/4/8)
|
||||
DWORD Value; ///< Value to write to kernel
|
||||
BYTE Pad3[16]; ///< Final padding for alignment
|
||||
BYTE Pad0[8]; ///< Alignment padding for 64-bit alignment
|
||||
DWORD64 Address; ///< Target kernel memory address to write to
|
||||
BYTE Pad1[8]; ///< Additional padding for structure alignment
|
||||
DWORD Size; ///< Number of bytes to write (1/2/4/8 bytes)
|
||||
DWORD Value; ///< Value to write to kernel memory
|
||||
BYTE Pad3[16]; ///< Final padding for IOCTL buffer alignment
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
@@ -67,27 +71,36 @@ struct alignas(8) RTC_MEMORY_WRITE
|
||||
* - Type-safe read/write operations (8/16/32/64-bit)
|
||||
* - Connection state management
|
||||
* - Smart handle management with automatic cleanup
|
||||
* - Error handling with std::optional return values
|
||||
*
|
||||
* @warning Kernel memory operations can cause system instability if misused
|
||||
* @note Driver must be installed and running before using this class
|
||||
*/
|
||||
class kvc
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Default constructor
|
||||
* @brief Construct kvc driver interface
|
||||
*
|
||||
* Initializes device name but does not establish connection.
|
||||
* Call Initialize() to connect to driver.
|
||||
*/
|
||||
kvc();
|
||||
|
||||
/**
|
||||
* @brief Destructor with automatic cleanup
|
||||
*
|
||||
* Automatically closes driver connection and releases resources.
|
||||
*/
|
||||
~kvc();
|
||||
|
||||
// Disable copy semantics to prevent handle duplication
|
||||
kvc(const kvc&) = delete;
|
||||
kvc& operator=(const kvc&) = delete;
|
||||
kvc(const kvc&) = delete; ///< Copy constructor deleted
|
||||
kvc& operator=(const kvc&) = delete; ///< Copy assignment deleted
|
||||
|
||||
// Enable move semantics for efficient resource transfer
|
||||
kvc(kvc&&) noexcept = default;
|
||||
kvc& operator=(kvc&&) noexcept = default;
|
||||
kvc(kvc&&) noexcept = default; ///< Move constructor
|
||||
kvc& operator=(kvc&&) noexcept = default; ///< Move assignment
|
||||
|
||||
// ========================================================================
|
||||
// DRIVER CONNECTION MANAGEMENT
|
||||
@@ -97,9 +110,11 @@ public:
|
||||
* @brief Initializes connection to KVC kernel driver
|
||||
*
|
||||
* Attempts to open device handle to driver. Safe to call multiple times.
|
||||
* If already connected, returns true without reinitializing.
|
||||
*
|
||||
* @return bool true if driver connection established successfully
|
||||
* @note Does not perform test operations - just opens device handle
|
||||
* @note Device name: "\\\\.\\KVCDriver"
|
||||
*/
|
||||
bool Initialize() noexcept;
|
||||
|
||||
@@ -107,12 +122,16 @@ public:
|
||||
* @brief Cleans up driver resources and closes connection
|
||||
*
|
||||
* Flushes buffers and releases device handle. Safe to call multiple times.
|
||||
* If not connected, does nothing.
|
||||
*/
|
||||
void Cleanup() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Checks if driver connection is active
|
||||
*
|
||||
* Verifies that device handle is valid and open. Does not test
|
||||
* if driver is actually responsive.
|
||||
*
|
||||
* @return bool true if device handle is valid and open
|
||||
*/
|
||||
bool IsConnected() const noexcept;
|
||||
@@ -123,28 +142,31 @@ public:
|
||||
|
||||
/**
|
||||
* @brief Reads 8-bit value from kernel memory
|
||||
* @param address Target kernel address
|
||||
* @param address Target kernel address to read from
|
||||
* @return std::optional<BYTE> Read value or nullopt on failure
|
||||
* @note Uses single byte read operation
|
||||
*/
|
||||
std::optional<BYTE> Read8(ULONG_PTR address) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Reads 16-bit value from kernel memory
|
||||
* @param address Target kernel address
|
||||
* @param address Target kernel address to read from
|
||||
* @return std::optional<WORD> Read value or nullopt on failure
|
||||
* @note Uses 16-bit read operation
|
||||
*/
|
||||
std::optional<WORD> Read16(ULONG_PTR address) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Reads 32-bit value from kernel memory
|
||||
* @param address Target kernel address
|
||||
* @param address Target kernel address to read from
|
||||
* @return std::optional<DWORD> Read value or nullopt on failure
|
||||
* @note Uses 32-bit read operation
|
||||
*/
|
||||
std::optional<DWORD> Read32(ULONG_PTR address) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Reads 64-bit value from kernel memory
|
||||
* @param address Target kernel address
|
||||
* @param address Target kernel address to read from
|
||||
* @return std::optional<DWORD64> Read value or nullopt on failure
|
||||
* @note Performs two 32-bit reads and combines them
|
||||
*/
|
||||
@@ -152,9 +174,9 @@ public:
|
||||
|
||||
/**
|
||||
* @brief Reads pointer-sized value from kernel memory
|
||||
* @param address Target kernel address
|
||||
* @param address Target kernel address to read from
|
||||
* @return std::optional<ULONG_PTR> Read value or nullopt on failure
|
||||
* @note Uses Read64 on x64, Read32 on x86
|
||||
* @note Uses Read64 on x64, Read32 on x86 architectures
|
||||
*/
|
||||
std::optional<ULONG_PTR> ReadPtr(ULONG_PTR address) noexcept;
|
||||
|
||||
@@ -164,41 +186,44 @@ public:
|
||||
|
||||
/**
|
||||
* @brief Writes 8-bit value to kernel memory
|
||||
* @param address Target kernel address
|
||||
* @param value Value to write
|
||||
* @param address Target kernel address to write to
|
||||
* @param value Value to write (8-bit)
|
||||
* @return bool true if write successful
|
||||
* @warning Kernel writes can cause system instability if misused
|
||||
* @note Uses single byte write operation
|
||||
*/
|
||||
bool Write8(ULONG_PTR address, BYTE value) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Writes 16-bit value to kernel memory
|
||||
* @param address Target kernel address
|
||||
* @param value Value to write
|
||||
* @param address Target kernel address to write to
|
||||
* @param value Value to write (16-bit)
|
||||
* @return bool true if write successful
|
||||
* @warning Kernel writes can cause system instability if misused
|
||||
* @note Uses 16-bit write operation
|
||||
*/
|
||||
bool Write16(ULONG_PTR address, WORD value) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Writes 32-bit value to kernel memory
|
||||
* @param address Target kernel address
|
||||
* @param value Value to write
|
||||
* @param address Target kernel address to write to
|
||||
* @param value Value to write (32-bit)
|
||||
* @return bool true if write successful
|
||||
* @warning Kernel writes can cause system instability if misused
|
||||
* @note Uses 32-bit write operation
|
||||
*/
|
||||
bool Write32(ULONG_PTR address, DWORD value) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Writes 64-bit value to kernel memory
|
||||
* @param address Target kernel address
|
||||
* @param value Value to write
|
||||
* @param address Target kernel address to write to
|
||||
* @param value Value to write (64-bit)
|
||||
* @return bool true if write successful
|
||||
* @note Performs two 32-bit writes
|
||||
* @note Performs two 32-bit writes for 64-bit values
|
||||
* @warning Kernel writes can cause system instability if misused
|
||||
*/
|
||||
bool Write64(ULONG_PTR address, DWORD64 value) noexcept;
|
||||
|
||||
|
||||
private:
|
||||
// ========================================================================
|
||||
// SMART HANDLE MANAGEMENT
|
||||
@@ -206,9 +231,16 @@ private:
|
||||
|
||||
/**
|
||||
* @brief Custom deleter for automatic HANDLE cleanup
|
||||
*
|
||||
* Ensures proper handle closure when UniqueHandle goes out of scope.
|
||||
* Handles INVALID_HANDLE_VALUE gracefully.
|
||||
*/
|
||||
struct HandleDeleter
|
||||
{
|
||||
/**
|
||||
* @brief Close handle if valid
|
||||
* @param handle Handle to close
|
||||
*/
|
||||
void operator()(HANDLE handle) const noexcept
|
||||
{
|
||||
if (handle && handle != INVALID_HANDLE_VALUE) {
|
||||
@@ -217,13 +249,13 @@ private:
|
||||
}
|
||||
};
|
||||
|
||||
using UniqueHandle = std::unique_ptr<std::remove_pointer_t<HANDLE>, HandleDeleter>;
|
||||
using UniqueHandle = std::unique_ptr<std::remove_pointer_t<HANDLE>, HandleDeleter>; ///< Smart handle type
|
||||
|
||||
// ========================================================================
|
||||
// PRIVATE MEMBERS
|
||||
// ========================================================================
|
||||
|
||||
std::wstring m_deviceName; ///< Driver device name (e.g., "\\.\KVCDriver")
|
||||
std::wstring m_deviceName; ///< Driver device name (e.g., "\\\\.\\KVCDriver")
|
||||
UniqueHandle m_deviceHandle; ///< Smart handle to driver device
|
||||
|
||||
// ========================================================================
|
||||
@@ -233,17 +265,19 @@ private:
|
||||
/**
|
||||
* @brief Low-level memory read via IOCTL
|
||||
* @param address Kernel address to read from
|
||||
* @param valueSize Size of value (1/2/4 bytes)
|
||||
* @param valueSize Size of value to read (1/2/4 bytes)
|
||||
* @return std::optional<DWORD> Read value or nullopt on failure
|
||||
* @note Internal implementation used by type-safe read methods
|
||||
*/
|
||||
std::optional<DWORD> Read(ULONG_PTR address, DWORD valueSize) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Low-level memory write via IOCTL
|
||||
* @param address Kernel address to write to
|
||||
* @param valueSize Size of value (1/2/4 bytes)
|
||||
* @param valueSize Size of value to write (1/2/4 bytes)
|
||||
* @param value Value to write
|
||||
* @return bool true if write successful
|
||||
* @note Internal implementation used by type-safe write methods
|
||||
*/
|
||||
bool Write(ULONG_PTR address, DWORD valueSize, DWORD value) noexcept;
|
||||
};
|
||||
@@ -1,3 +1,15 @@
|
||||
/**
|
||||
* @file OffsetFinder.h
|
||||
* @brief Kernel structure offset discovery for EPROCESS manipulation
|
||||
* @author Marek Wesolowski
|
||||
* @date 2025
|
||||
* @copyright KVC Framework
|
||||
*
|
||||
* Dynamically discovers kernel offsets by pattern matching in ntoskrnl.exe,
|
||||
* supporting multiple Windows versions without hardcoded offsets.
|
||||
* Enables reliable EPROCESS structure manipulation across Windows versions.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "common.h"
|
||||
@@ -5,52 +17,143 @@
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
|
||||
// Windows kernel structure offset identifiers
|
||||
/**
|
||||
* @brief Windows kernel structure offset identifiers
|
||||
*
|
||||
* Enumeration of all kernel structure offsets required for
|
||||
* EPROCESS manipulation and process protection operations.
|
||||
*/
|
||||
enum class Offset
|
||||
{
|
||||
KernelPsInitialSystemProcess,
|
||||
ProcessActiveProcessLinks,
|
||||
ProcessUniqueProcessId,
|
||||
ProcessProtection,
|
||||
ProcessSignatureLevel,
|
||||
ProcessSectionSignatureLevel
|
||||
KernelPsInitialSystemProcess, ///< PsInitialSystemProcess global pointer offset
|
||||
ProcessActiveProcessLinks, ///< EPROCESS.ActiveProcessLinks list entry offset
|
||||
ProcessUniqueProcessId, ///< EPROCESS.UniqueProcessId (PID) offset
|
||||
ProcessProtection, ///< EPROCESS.Protection protection level offset
|
||||
ProcessSignatureLevel, ///< EPROCESS.SignatureLevel code signing level offset
|
||||
ProcessSectionSignatureLevel ///< EPROCESS.SectionSignatureLevel DLL signing level offset
|
||||
};
|
||||
|
||||
// Kernel structure offset discovery and caching
|
||||
/**
|
||||
* @class OffsetFinder
|
||||
* @brief Kernel structure offset discovery and caching
|
||||
*
|
||||
* Discovers kernel offsets by:
|
||||
* 1. Loading ntoskrnl.exe from System32
|
||||
* 2. Pattern matching for specific structures and functions
|
||||
* 3. Calculating offsets from known patterns and signatures
|
||||
* 4. Caching results for performance across multiple operations
|
||||
*
|
||||
* Supports Windows 7 through Windows 11 with automatic version detection.
|
||||
* No hardcoded offsets - all discovered dynamically at runtime.
|
||||
*
|
||||
* @note Must call FindAllOffsets() before using GetOffset()
|
||||
*/
|
||||
class OffsetFinder
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Construct offset finder and load kernel module
|
||||
*
|
||||
* Loads ntoskrnl.exe from System32 directory for analysis.
|
||||
* Does not automatically find offsets - call FindAllOffsets().
|
||||
*/
|
||||
OffsetFinder();
|
||||
|
||||
/**
|
||||
* @brief Cleanup and free kernel module
|
||||
*
|
||||
* Releases loaded ntoskrnl.exe module if still loaded.
|
||||
*/
|
||||
~OffsetFinder();
|
||||
|
||||
OffsetFinder(const OffsetFinder&) = delete;
|
||||
OffsetFinder& operator=(const OffsetFinder&) = delete;
|
||||
OffsetFinder(OffsetFinder&&) noexcept = default;
|
||||
OffsetFinder& operator=(OffsetFinder&&) noexcept = default;
|
||||
OffsetFinder(const OffsetFinder&) = delete; ///< Copy constructor deleted
|
||||
OffsetFinder& operator=(const OffsetFinder&) = delete; ///< Copy assignment deleted
|
||||
OffsetFinder(OffsetFinder&&) noexcept = default; ///< Move constructor
|
||||
OffsetFinder& operator=(OffsetFinder&&) noexcept = default; ///< Move assignment
|
||||
|
||||
/**
|
||||
* @brief Get cached offset value
|
||||
* @param name Offset identifier to retrieve
|
||||
* @return Offset value in bytes, or nullopt if not found
|
||||
* @note Returns cached value - call FindAllOffsets() first to populate cache
|
||||
*/
|
||||
std::optional<DWORD> GetOffset(Offset name) const noexcept;
|
||||
|
||||
/**
|
||||
* @brief Discover all kernel offsets via pattern matching
|
||||
* @return true if all required offsets found successfully
|
||||
* @note Must be called after construction before using GetOffset()
|
||||
* @note Results are cached in m_offsetMap for subsequent calls
|
||||
* @note Failure indicates incompatible Windows version or corrupted system file
|
||||
*/
|
||||
bool FindAllOffsets() noexcept;
|
||||
|
||||
private:
|
||||
// Smart module wrapper for automatic cleanup
|
||||
/**
|
||||
* @brief Smart pointer deleter for HMODULE with FreeLibrary
|
||||
*
|
||||
* Ensures proper cleanup of loaded kernel module.
|
||||
*/
|
||||
struct ModuleDeleter
|
||||
{
|
||||
/**
|
||||
* @brief Free library module
|
||||
* @param module Module handle to free
|
||||
*/
|
||||
void operator()(HMODULE module) const noexcept
|
||||
{
|
||||
if (module) FreeLibrary(module);
|
||||
if (module) {
|
||||
FreeLibrary(module);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
using ModuleHandle = std::unique_ptr<std::remove_pointer_t<HMODULE>, ModuleDeleter>;
|
||||
using ModuleHandle = std::unique_ptr<std::remove_pointer_t<HMODULE>, ModuleDeleter>; ///< Smart module handle type
|
||||
|
||||
ModuleHandle m_kernelModule;
|
||||
std::unordered_map<Offset, DWORD> m_offsetMap;
|
||||
ModuleHandle m_kernelModule; ///< ntoskrnl.exe module handle
|
||||
std::unordered_map<Offset, DWORD> m_offsetMap; ///< Cached offset values
|
||||
|
||||
// Offset discovery methods for different kernel structures
|
||||
// Offset discovery methods
|
||||
|
||||
/**
|
||||
* @brief Find PsInitialSystemProcess global pointer offset
|
||||
* @return true if offset discovered successfully
|
||||
* @note Uses PsGetCurrentProcess pattern matching technique
|
||||
*/
|
||||
bool FindKernelPsInitialSystemProcessOffset() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Find EPROCESS.ActiveProcessLinks offset
|
||||
* @return true if offset discovered successfully
|
||||
* @note Uses PsGetNextProcess pattern matching technique
|
||||
*/
|
||||
bool FindProcessActiveProcessLinksOffset() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Find EPROCESS.UniqueProcessId offset
|
||||
* @return true if offset discovered successfully
|
||||
* @note Uses PsGetProcessId pattern matching technique
|
||||
*/
|
||||
bool FindProcessUniqueProcessIdOffset() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Find EPROCESS.Protection offset
|
||||
* @return true if offset discovered successfully
|
||||
* @note Pattern varies by Windows version, uses multiple techniques
|
||||
*/
|
||||
bool FindProcessProtectionOffset() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Find EPROCESS.SignatureLevel offset
|
||||
* @return true if offset discovered successfully
|
||||
* @note Used for code signing level manipulation
|
||||
*/
|
||||
bool FindProcessSignatureLevelOffset() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Find EPROCESS.SectionSignatureLevel offset
|
||||
* @return true if offset discovered successfully
|
||||
* @note Used for DLL signature level manipulation
|
||||
*/
|
||||
bool FindProcessSectionSignatureLevelOffset() noexcept;
|
||||
};
|
||||
@@ -1,4 +1,15 @@
|
||||
// ProcessManager.h
|
||||
/**
|
||||
* @file ProcessManager.h
|
||||
* @brief Process management operations with protection-aware termination
|
||||
* @author Marek Wesolowski
|
||||
* @date 2025
|
||||
* @copyright KVC Framework
|
||||
*
|
||||
* Handles process termination with automatic protection level matching,
|
||||
* supporting both PID and name-based targeting.
|
||||
* Integrates with Controller for protection manipulation during termination.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "common.h"
|
||||
@@ -8,21 +19,111 @@
|
||||
// Forward declaration to avoid circular includes
|
||||
class Controller;
|
||||
|
||||
// Process management operations with self-protection capabilities
|
||||
/**
|
||||
* @class ProcessManager
|
||||
* @brief Process management operations with self-protection capabilities
|
||||
*
|
||||
* Features:
|
||||
* - Protection-aware termination (automatically elevates to target protection)
|
||||
* - Multi-target support (comma-separated PIDs/names)
|
||||
* - Name-based process resolution with partial matching
|
||||
* - Case-insensitive process name matching
|
||||
* - Integration with Controller for protection manipulation
|
||||
*
|
||||
* Examples:
|
||||
* - kill 1234 -> Terminate process by PID
|
||||
* - kill notepad -> Terminate all notepad.exe processes
|
||||
* - kill 1234,5678,chrome -> Terminate multiple targets
|
||||
*
|
||||
* @note Static class - no instantiation required
|
||||
* @warning Process termination can cause system instability
|
||||
*/
|
||||
class ProcessManager
|
||||
{
|
||||
public:
|
||||
ProcessManager() = delete;
|
||||
~ProcessManager() = delete;
|
||||
ProcessManager() = delete; ///< Constructor deleted - static class
|
||||
~ProcessManager() = delete; ///< Destructor deleted - static class
|
||||
|
||||
// Command line interface for process termination with Controller integration
|
||||
/**
|
||||
* @brief Handle 'kill' command from command line
|
||||
* @param argc Argument count from command line
|
||||
* @param argv Argument vector from command line
|
||||
* @param controller Controller instance for protection operations
|
||||
*
|
||||
* Parses command line and terminates specified processes with
|
||||
* automatic protection level matching. Supports both single and
|
||||
* multiple target specification.
|
||||
*
|
||||
* Command format:
|
||||
* - kill <PID|name> -> Single target
|
||||
* - kill <PID1,PID2,name3> -> Multiple targets (comma-separated)
|
||||
*
|
||||
* Features:
|
||||
* - Automatic protection elevation to match target
|
||||
* - Partial name matching (e.g., "note" matches "notepad.exe")
|
||||
* - Case-insensitive matching
|
||||
* - Batch operation with progress reporting
|
||||
*
|
||||
* @note Integrates with Controller for protection manipulation
|
||||
* @warning Terminating system processes can cause system instability
|
||||
*/
|
||||
static void HandleKillCommand(int argc, wchar_t* argv[], Controller* controller) noexcept;
|
||||
|
||||
private:
|
||||
// Command parsing and validation helpers
|
||||
// === Command Parsing and Validation ===
|
||||
|
||||
/**
|
||||
* @brief Parse comma-separated list of PIDs
|
||||
* @param pidList Comma-separated PID string
|
||||
* @param pids Output vector of parsed PIDs
|
||||
* @return true if parsing successful
|
||||
* @note Handles whitespace and validates numeric values
|
||||
* @note Skips invalid entries and continues parsing
|
||||
*/
|
||||
static bool ParseProcessIds(std::wstring_view pidList, std::vector<DWORD>& pids) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Print kill command usage information
|
||||
*
|
||||
* Displays command syntax, examples, and available options
|
||||
* for the kill command.
|
||||
*/
|
||||
static void PrintKillUsage() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Terminate process with automatic protection elevation
|
||||
* @param processId Target process ID
|
||||
* @param controller Controller instance for protection operations
|
||||
* @return true if termination successful
|
||||
*
|
||||
* Automatically matches target's protection level before termination
|
||||
* to ensure successful process termination. This is necessary because
|
||||
* protected processes can only be terminated by processes with equal
|
||||
* or higher protection levels.
|
||||
*
|
||||
* @note Uses Controller::SelfProtect for protection elevation
|
||||
* @note Falls back to standard termination if protection matching fails
|
||||
*/
|
||||
static bool TerminateProcessWithProtection(DWORD processId, Controller* controller) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Check if input string is a numeric PID
|
||||
* @param input String to validate
|
||||
* @return true if string contains only digits
|
||||
* @note Used to distinguish between PID and process name targets
|
||||
*/
|
||||
static bool IsNumericPid(std::wstring_view input) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Find all process IDs matching name pattern
|
||||
* @param processName Process name or partial name
|
||||
* @return Vector of matching PIDs
|
||||
*
|
||||
* Performs case-insensitive partial matching against running processes.
|
||||
* Example: "note" matches "notepad.exe", "Notepad.exe", "notes.exe"
|
||||
*
|
||||
* @note Uses Toolhelp32 snapshot for process enumeration
|
||||
* @note Returns empty vector if no matches found
|
||||
*/
|
||||
static std::vector<DWORD> FindProcessIdsByName(const std::wstring& processName) noexcept;
|
||||
};
|
||||
@@ -1,74 +1,390 @@
|
||||
/**
|
||||
* @file ReportExporter.h
|
||||
* @brief Professional report generation for DPAPI password extraction results
|
||||
* @author Marek Wesolowski
|
||||
* @date 2025
|
||||
* @copyright KVC Framework
|
||||
*
|
||||
* Exports extraction results in multiple formats (HTML, TXT) with automatic
|
||||
* statistics calculation and modern styling.
|
||||
* Provides comprehensive reporting for credential extraction operations.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "common.h"
|
||||
#include <vector>
|
||||
#include <string>
|
||||
|
||||
// Forward declarations
|
||||
struct PasswordResult;
|
||||
struct RegistryMasterKey;
|
||||
|
||||
// Report data aggregation with automatic statistics
|
||||
/**
|
||||
* @struct ReportData
|
||||
* @brief Report data aggregation with automatic statistics
|
||||
*
|
||||
* Aggregates all extraction results and calculates statistics automatically
|
||||
* upon construction. Provides convenient access to categorized data.
|
||||
* Used as input for report generation in multiple formats.
|
||||
*/
|
||||
struct ReportData
|
||||
{
|
||||
std::vector<PasswordResult> passwordResults;
|
||||
std::vector<RegistryMasterKey> masterKeys;
|
||||
std::wstring outputPath;
|
||||
std::string timestamp;
|
||||
std::vector<PasswordResult> passwordResults; ///< All password extraction results
|
||||
std::vector<RegistryMasterKey> masterKeys; ///< Registry master keys extracted
|
||||
std::wstring outputPath; ///< Output directory path for reports
|
||||
std::string timestamp; ///< Generation timestamp
|
||||
|
||||
/**
|
||||
* @struct Stats
|
||||
* @brief Automatically calculated extraction statistics
|
||||
*
|
||||
* Contains counts and metrics for different credential types
|
||||
* extracted during DPAPI operations.
|
||||
*/
|
||||
struct Stats {
|
||||
int totalPasswords = 0;
|
||||
int chromePasswords = 0;
|
||||
int edgePasswords = 0;
|
||||
int wifiPasswords = 0;
|
||||
int masterKeyCount = 0;
|
||||
int totalPasswords = 0; ///< Total passwords extracted
|
||||
int chromePasswords = 0; ///< Chrome browser passwords
|
||||
int edgePasswords = 0; ///< Edge browser passwords
|
||||
int wifiPasswords = 0; ///< WiFi credentials
|
||||
int masterKeyCount = 0; ///< Master keys extracted
|
||||
} stats;
|
||||
|
||||
/**
|
||||
* @brief Default constructor
|
||||
*
|
||||
* Creates empty report data structure. Statistics will be
|
||||
* zero-initialized.
|
||||
*/
|
||||
ReportData() = default;
|
||||
|
||||
/**
|
||||
* @brief Construct report data with automatic statistics calculation
|
||||
* @param results Password extraction results
|
||||
* @param keys Registry master keys
|
||||
* @param path Output directory path
|
||||
*
|
||||
* Initializes report data with extraction results and automatically
|
||||
* calculates statistics by calling CalculateStatistics().
|
||||
*/
|
||||
ReportData(const std::vector<PasswordResult>& results,
|
||||
const std::vector<RegistryMasterKey>& keys,
|
||||
const std::wstring& path);
|
||||
|
||||
private:
|
||||
/**
|
||||
* @brief Calculate statistics from results
|
||||
*
|
||||
* Analyzes password results and master keys to populate
|
||||
* statistics structure. Called automatically by constructor.
|
||||
*
|
||||
* @note Private method called automatically on construction
|
||||
*/
|
||||
void CalculateStatistics();
|
||||
};
|
||||
|
||||
// Professional report export in multiple formats
|
||||
/**
|
||||
* @class ReportExporter
|
||||
* @brief Professional report export in multiple formats
|
||||
*
|
||||
* Features:
|
||||
* - HTML export with modern CSS styling and responsive design
|
||||
* - TXT export for lightweight text-based reports
|
||||
* - Automatic statistics calculation and display
|
||||
* - Color-coded categorization (Chrome, Edge, WiFi)
|
||||
* - UTF-8 encoding support
|
||||
* - Professional formatting and layout
|
||||
*
|
||||
* Report Types:
|
||||
* - HTML: Interactive web-based report with styling
|
||||
* - TXT: Plain text report for quick viewing
|
||||
* - Console: Summary display with color coding
|
||||
*
|
||||
* @note Creates timestamped reports in specified output directory
|
||||
*/
|
||||
class ReportExporter
|
||||
{
|
||||
public:
|
||||
ReportExporter() = default;
|
||||
~ReportExporter() = default;
|
||||
ReportExporter() = default; ///< Default constructor
|
||||
~ReportExporter() = default; ///< Default destructor
|
||||
|
||||
ReportExporter(const ReportExporter&) = delete;
|
||||
ReportExporter& operator=(const ReportExporter&) = delete;
|
||||
ReportExporter(ReportExporter&&) noexcept = default;
|
||||
ReportExporter& operator=(ReportExporter&&) noexcept = default;
|
||||
// Disable copy semantics
|
||||
ReportExporter(const ReportExporter&) = delete; ///< Copy constructor deleted
|
||||
ReportExporter& operator=(const ReportExporter&) = delete; ///< Copy assignment deleted
|
||||
|
||||
// Enable move semantics
|
||||
ReportExporter(ReportExporter&&) noexcept = default; ///< Move constructor
|
||||
ReportExporter& operator=(ReportExporter&&) noexcept = default; ///< Move assignment
|
||||
|
||||
// Main export interface
|
||||
/**
|
||||
* @brief Export reports in all supported formats
|
||||
* @param data Report data with extraction results
|
||||
* @return true if all formats exported successfully
|
||||
*
|
||||
* Creates both HTML and TXT reports in the output directory.
|
||||
* Also displays summary statistics to console.
|
||||
*
|
||||
* Files created:
|
||||
* - dpapi_results.html: HTML report with full styling
|
||||
* - dpapi_results.txt: Plain text report
|
||||
*
|
||||
* @note Comprehensive reporting across all formats
|
||||
*/
|
||||
bool ExportAllFormats(const ReportData& data) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Export HTML report with modern styling
|
||||
* @param data Report data with extraction results
|
||||
* @return true if HTML export successful
|
||||
*
|
||||
* Generates professional HTML report with:
|
||||
* - Responsive CSS styling
|
||||
* - Color-coded sections
|
||||
* - Interactive elements
|
||||
* - Statistics dashboard
|
||||
* - Master keys table
|
||||
* - Passwords table (collapsible)
|
||||
* - WiFi credentials section
|
||||
*
|
||||
* @note Creates dpapi_results.html in output directory
|
||||
*/
|
||||
bool ExportHTML(const ReportData& data) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Export plain text report
|
||||
* @param data Report data with extraction results
|
||||
* @return true if TXT export successful
|
||||
*
|
||||
* Generates lightweight text report with:
|
||||
* - Simple column-based formatting
|
||||
* - Basic statistics
|
||||
* - Master keys listing
|
||||
* - Passwords in readable format
|
||||
* - WiFi credentials section
|
||||
*
|
||||
* @note Creates dpapi_results.txt in output directory
|
||||
*/
|
||||
bool ExportTXT(const ReportData& data) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Display summary statistics to console
|
||||
* @param data Report data with extraction results
|
||||
*
|
||||
* Prints color-coded summary to console with:
|
||||
* - Total extraction statistics
|
||||
* - File paths for generated reports
|
||||
* - Success/failure indicators
|
||||
* - Quick overview of results
|
||||
*
|
||||
* @note Useful for immediate feedback after extraction
|
||||
*/
|
||||
void DisplaySummary(const ReportData& data) noexcept;
|
||||
|
||||
private:
|
||||
// HTML generation with obfuscated markup
|
||||
// === HTML Generation Methods ===
|
||||
|
||||
/**
|
||||
* @brief Generate complete HTML content
|
||||
* @param data Report data for generation
|
||||
* @return std::string HTML content as string
|
||||
*
|
||||
* Builds complete HTML document by combining:
|
||||
* - HTML header with CSS styling
|
||||
* - Summary section with statistics
|
||||
* - Master keys table
|
||||
* - Passwords table
|
||||
* - WiFi credentials table
|
||||
*
|
||||
* @note Internal HTML generation implementation
|
||||
*/
|
||||
std::string GenerateHTMLContent(const ReportData& data) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Build HTML header section
|
||||
* @param data Report data for header
|
||||
* @return std::string HTML header content
|
||||
*
|
||||
* Creates HTML head section with:
|
||||
* - Page title and metadata
|
||||
* - CSS styles for responsive design
|
||||
* - JavaScript for interactivity
|
||||
* - Character encoding
|
||||
*
|
||||
* @note Includes modern CSS framework for styling
|
||||
*/
|
||||
std::string BuildHTMLHeader(const ReportData& data) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Build summary section with statistics
|
||||
* @param data Report data for statistics
|
||||
* @return std::string HTML summary section
|
||||
*
|
||||
* Creates statistics dashboard with:
|
||||
* - Total passwords count
|
||||
* - Browser-specific counts
|
||||
* - WiFi credentials count
|
||||
* - Master keys count
|
||||
* - Visual progress bars
|
||||
*
|
||||
* @note Color-coded statistics display
|
||||
*/
|
||||
std::string BuildSummarySection(const ReportData& data) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Build master keys table
|
||||
* @param data Report data with master keys
|
||||
* @return std::string HTML table content
|
||||
*
|
||||
* Creates table displaying:
|
||||
* - Registry key names
|
||||
* - Key data (hex encoded)
|
||||
* - Decryption status
|
||||
* - Data sizes
|
||||
*
|
||||
* @note Technical details for master keys
|
||||
*/
|
||||
std::string BuildMasterKeysTable(const ReportData& data) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Build passwords table
|
||||
* @param data Report data with passwords
|
||||
* @return std::string HTML table content
|
||||
*
|
||||
* Creates interactive table displaying:
|
||||
* - Browser type and profile
|
||||
* - URLs and usernames
|
||||
* - Decrypted passwords
|
||||
* - Extraction status
|
||||
* - Source files
|
||||
*
|
||||
* @note Collapsible sections for large datasets
|
||||
*/
|
||||
std::string BuildPasswordsTable(const ReportData& data) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Build WiFi credentials table
|
||||
* @param data Report data with WiFi credentials
|
||||
* @return std::string HTML table content
|
||||
*
|
||||
* Creates table displaying:
|
||||
* - WiFi profile names
|
||||
* - Network SSIDs
|
||||
* - Security keys
|
||||
* - Connection status
|
||||
*
|
||||
* @note Separate section for wireless credentials
|
||||
*/
|
||||
std::string BuildWiFiTable(const ReportData& data) noexcept;
|
||||
|
||||
// TXT generation for lightweight output
|
||||
// === TXT Generation Methods ===
|
||||
|
||||
/**
|
||||
* @brief Generate complete TXT content
|
||||
* @param data Report data for generation
|
||||
* @return std::wstring TXT content as wide string
|
||||
*
|
||||
* Builds plain text report with:
|
||||
* - Header with timestamp
|
||||
* - Statistics summary
|
||||
* - Master keys listing
|
||||
* - Passwords in columns
|
||||
* - WiFi credentials
|
||||
*
|
||||
* @note Internal TXT generation implementation
|
||||
*/
|
||||
std::wstring GenerateTXTContent(const ReportData& data) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Build TXT header section
|
||||
* @param data Report data for header
|
||||
* @return std::wstring TXT header content
|
||||
*
|
||||
* Creates text header with:
|
||||
* - Report title
|
||||
* - Generation timestamp
|
||||
* - Separation lines
|
||||
* - Basic information
|
||||
*
|
||||
* @note Simple formatting for text output
|
||||
*/
|
||||
std::wstring BuildTXTHeader(const ReportData& data) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Build TXT master keys section
|
||||
* @param data Report data with master keys
|
||||
* @return std::wstring TXT master keys content
|
||||
*
|
||||
* Lists master keys in text format:
|
||||
* - Key names and paths
|
||||
* - Hex-encoded data (truncated)
|
||||
* - Decryption status
|
||||
* - Size information
|
||||
*
|
||||
* @note Technical details in readable format
|
||||
*/
|
||||
std::wstring BuildTXTMasterKeys(const ReportData& data) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Build TXT passwords section
|
||||
* @param data Report data with passwords
|
||||
* @return std::wstring TXT passwords content
|
||||
*
|
||||
* Displays passwords in column format:
|
||||
* - Browser and profile
|
||||
* - URL and username
|
||||
* - Password (plaintext)
|
||||
* - Status indicator
|
||||
*
|
||||
* @note Aligned columns for readability
|
||||
*/
|
||||
std::wstring BuildTXTPasswords(const ReportData& data) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Build TXT WiFi credentials section
|
||||
* @param data Report data with WiFi credentials
|
||||
* @return std::wstring TXT WiFi content
|
||||
*
|
||||
* Lists WiFi credentials:
|
||||
* - Profile names
|
||||
* - Network information
|
||||
* - Security keys
|
||||
* - Connection details
|
||||
*
|
||||
* @note Separate section for wireless networks
|
||||
*/
|
||||
std::wstring BuildTXTWiFi(const ReportData& data) noexcept;
|
||||
|
||||
// Utility functions for encoding and paths
|
||||
// === Utility Functions ===
|
||||
|
||||
/**
|
||||
* @brief Get HTML report file path
|
||||
* @param outputPath Base output directory
|
||||
* @return std::wstring Full HTML file path
|
||||
*
|
||||
* Constructs complete path for HTML report file.
|
||||
* Format: {outputPath}\dpapi_results.html
|
||||
*/
|
||||
std::wstring GetHTMLPath(const std::wstring& outputPath) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Get TXT report file path
|
||||
* @param outputPath Base output directory
|
||||
* @return std::wstring Full TXT file path
|
||||
*
|
||||
* Constructs complete path for TXT report file.
|
||||
* Format: {outputPath}\dpapi_results.txt
|
||||
*/
|
||||
std::wstring GetTXTPath(const std::wstring& outputPath) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Ensure output directory exists
|
||||
* @param path Directory path to validate
|
||||
* @return bool true if directory exists or was created
|
||||
*
|
||||
* Validates that output directory exists and is writable.
|
||||
* Creates directory structure if missing.
|
||||
*
|
||||
* @note Essential for successful report generation
|
||||
*/
|
||||
bool EnsureOutputDirectory(const std::wstring& path) noexcept;
|
||||
};
|
||||
};
|
||||
@@ -1,45 +1,218 @@
|
||||
/**
|
||||
* @file ServiceManager.h
|
||||
* @brief NT Service management for single-binary deployment
|
||||
* @author Marek Wesolowski
|
||||
* @date 2025
|
||||
* @copyright KVC Framework
|
||||
*
|
||||
* Provides Windows Service integration for KVC framework, enabling
|
||||
* background operation and automatic startup.
|
||||
* Supports single-binary operation (same executable runs as service or console).
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "common.h"
|
||||
#include <string>
|
||||
#include <memory>
|
||||
|
||||
// NT Service management for single-binary deployment
|
||||
/**
|
||||
* @class ServiceManager
|
||||
* @brief NT Service management for single-binary deployment
|
||||
*
|
||||
* Features:
|
||||
* - Service installation with automatic start type
|
||||
* - Service lifecycle management (start/stop/uninstall)
|
||||
* - Single-binary operation (same executable runs as service or console)
|
||||
* - Background worker thread for service operations
|
||||
* - Automatic cleanup on service stop
|
||||
*
|
||||
* Service Details:
|
||||
* - Name: KernelVulnerabilityControl
|
||||
* - Display: Kernel Vulnerability Capabilities Framework
|
||||
* - Type: Win32OwnProcess
|
||||
* - Start: Automatic (optional)
|
||||
*
|
||||
* @note Requires administrative privileges for service operations
|
||||
* @warning Service operations affect system configuration
|
||||
*/
|
||||
class ServiceManager
|
||||
{
|
||||
public:
|
||||
ServiceManager() = default;
|
||||
~ServiceManager() = default;
|
||||
ServiceManager() = default; ///< Default constructor
|
||||
~ServiceManager() = default; ///< Default destructor
|
||||
|
||||
ServiceManager(const ServiceManager&) = delete;
|
||||
ServiceManager& operator=(const ServiceManager&) = delete;
|
||||
// Disable copy semantics
|
||||
ServiceManager(const ServiceManager&) = delete; ///< Copy constructor deleted
|
||||
ServiceManager& operator=(const ServiceManager&) = delete; ///< Copy assignment deleted
|
||||
|
||||
// Service lifecycle management
|
||||
static bool InstallService(const std::wstring& exePath) noexcept;
|
||||
// === Service Lifecycle Management ===
|
||||
|
||||
/**
|
||||
* @brief Install service with automatic start
|
||||
* @param exePath Path to executable (empty = current executable)
|
||||
* @return true if installation successful
|
||||
*
|
||||
* Creates Windows service with the following configuration:
|
||||
* - Service name: KernelVulnerabilityControl
|
||||
* - Display name: Kernel Vulnerability Capabilities Framework
|
||||
* - Description: Provides kernel-level process protection and vulnerability assessment capabilities
|
||||
* - Start type: SERVICE_AUTO_START (automatic startup)
|
||||
* - Service type: SERVICE_WIN32_OWN_PROCESS
|
||||
*
|
||||
* @note Requires administrative privileges
|
||||
* @note Uses current executable path if exePath is empty
|
||||
* @note Adds --service parameter for service mode detection
|
||||
*/
|
||||
static bool InstallService(const std::wstring& exePath = L"") noexcept;
|
||||
|
||||
/**
|
||||
* @brief Uninstall service from system
|
||||
* @return true if uninstallation successful
|
||||
*
|
||||
* Stops service if running before uninstall. Removes service
|
||||
* from Service Control Manager database.
|
||||
*
|
||||
* @note Requires administrative privileges
|
||||
* @note Stops service gracefully before removal
|
||||
* @note Returns true if service was not installed
|
||||
*/
|
||||
static bool UninstallService() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Start service process
|
||||
* @return true if service started successfully
|
||||
*
|
||||
* Starts the installed service via Service Control Manager.
|
||||
* Waits for service to enter running state.
|
||||
*
|
||||
* @note Returns true if service is already running
|
||||
* @note Uses StartServiceW with 30 second timeout
|
||||
*/
|
||||
static bool StartServiceProcess() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Stop service process
|
||||
* @return true if service stopped successfully
|
||||
*
|
||||
* Stops the running service via Service Control Manager.
|
||||
* Waits for service to enter stopped state.
|
||||
*
|
||||
* @note Returns true if service is already stopped
|
||||
* @note Uses ControlService with SERVICE_CONTROL_STOP
|
||||
*/
|
||||
static bool StopServiceProcess() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Run as Windows Service (service entry point)
|
||||
* @return Exit code (0 = success)
|
||||
*
|
||||
* Main service entry point called when started as service.
|
||||
* Registers service control handler and starts worker thread.
|
||||
*
|
||||
* Service workflow:
|
||||
* 1. Register ServiceMain with SCM
|
||||
* 2. Set service status to SERVICE_RUNNING
|
||||
* 3. Start worker thread for background operations
|
||||
* 4. Wait for stop signal from SCM
|
||||
* 5. Perform graceful shutdown
|
||||
*
|
||||
* @note Called automatically when started as service
|
||||
* @note Registers service control handler for stop/shutdown events
|
||||
*/
|
||||
static int RunAsService() noexcept;
|
||||
|
||||
// Service configuration
|
||||
static constexpr const wchar_t* SERVICE_NAME = L"KernelVulnerabilityControl";
|
||||
static constexpr const wchar_t* SERVICE_DISPLAY_NAME = L"Kernel Vulnerability Capabilities Framework";
|
||||
static constexpr const wchar_t* SERVICE_DESCRIPTION = L"Provides kernel-level process protection and vulnerability assessment capabilities";
|
||||
// === Service Configuration ===
|
||||
|
||||
static constexpr const wchar_t* SERVICE_NAME = L"KernelVulnerabilityControl"; ///< Service internal name
|
||||
static constexpr const wchar_t* SERVICE_DISPLAY_NAME = L"Kernel Vulnerability Capabilities Framework"; ///< Service display name
|
||||
static constexpr const wchar_t* SERVICE_DESCRIPTION = L"Provides kernel-level process protection and vulnerability assessment capabilities"; ///< Service description
|
||||
|
||||
private:
|
||||
// Service entry points
|
||||
// === Service Entry Points ===
|
||||
|
||||
/**
|
||||
* @brief Service main entry point (SCM callback)
|
||||
* @param argc Argument count from SCM
|
||||
* @param argv Argument vector from SCM
|
||||
*
|
||||
* Called by Service Control Manager when service is started.
|
||||
* Initializes service state and reports status to SCM.
|
||||
*
|
||||
* @note Static callback function for SCM
|
||||
* @note Must call SetServiceStatus to report state changes
|
||||
*/
|
||||
static VOID WINAPI ServiceMain(DWORD argc, LPWSTR* argv);
|
||||
|
||||
/**
|
||||
* @brief Service control handler (SCM callback)
|
||||
* @param ctrlCode Control code from SCM
|
||||
*
|
||||
* Handles control requests from Service Control Manager:
|
||||
* - SERVICE_CONTROL_STOP: Graceful shutdown
|
||||
* - SERVICE_CONTROL_SHUTDOWN: System shutdown
|
||||
* - SERVICE_CONTROL_INTERROGATE: Status query
|
||||
*
|
||||
* @note Static callback function for SCM
|
||||
* @note Sets stop event for SERVICE_CONTROL_STOP and SERVICE_CONTROL_SHUTDOWN
|
||||
*/
|
||||
static VOID WINAPI ServiceCtrlHandler(DWORD ctrlCode);
|
||||
|
||||
/**
|
||||
* @brief Service worker thread
|
||||
* @param param Thread parameter (unused)
|
||||
* @return Thread exit code
|
||||
*
|
||||
* Runs service logic in background. Monitors stop event
|
||||
* for graceful shutdown. Performs main service operations.
|
||||
*
|
||||
* @note Runs in separate thread from service main
|
||||
* @note Monitors s_serviceStopEvent for shutdown signals
|
||||
*/
|
||||
static DWORD WINAPI ServiceWorkerThread(LPVOID param);
|
||||
|
||||
// Service state management
|
||||
static SERVICE_STATUS_HANDLE s_serviceStatusHandle;
|
||||
static SERVICE_STATUS s_serviceStatus;
|
||||
static HANDLE s_serviceStopEvent;
|
||||
static volatile bool s_serviceRunning;
|
||||
// === Service State Management ===
|
||||
|
||||
static SERVICE_STATUS_HANDLE s_serviceStatusHandle; ///< SCM status handle for service
|
||||
static SERVICE_STATUS s_serviceStatus; ///< Current service status structure
|
||||
static HANDLE s_serviceStopEvent; ///< Stop event handle for graceful shutdown
|
||||
static volatile bool s_serviceRunning; ///< Service running flag
|
||||
|
||||
// Internal helpers
|
||||
/**
|
||||
* @brief Update service status in SCM
|
||||
* @param currentState New service state
|
||||
* @param exitCode Exit code (default: NO_ERROR)
|
||||
* @param waitHint Wait hint in milliseconds (default: 0)
|
||||
* @return true if status updated successfully
|
||||
*
|
||||
* Reports current service state to Service Control Manager.
|
||||
* Used to inform SCM about service state changes.
|
||||
*
|
||||
* @note Must be called for all service state transitions
|
||||
* @note Sets SERVICE_STATUS structure and calls SetServiceStatus
|
||||
*/
|
||||
static bool SetServiceStatus(DWORD currentState, DWORD exitCode = NO_ERROR, DWORD waitHint = 0) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Cleanup service resources
|
||||
*
|
||||
* Performs graceful cleanup when service is stopping:
|
||||
* - Closes stop event handle
|
||||
* - Reports stopped state to SCM
|
||||
* - Cleans up any allocated resources
|
||||
*
|
||||
* @note Called on service stop and shutdown
|
||||
*/
|
||||
static void ServiceCleanup() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Initialize service components
|
||||
* @return true if initialization successful
|
||||
*
|
||||
* Initializes service-specific components and resources.
|
||||
* Called at service start before entering running state.
|
||||
*
|
||||
* @note Called from ServiceMain after SCM registration
|
||||
*/
|
||||
static bool InitializeServiceComponents() noexcept;
|
||||
};
|
||||
@@ -1,4 +1,15 @@
|
||||
// SessionManager.h
|
||||
/**
|
||||
* @file SessionManager.h
|
||||
* @brief Process protection state management across boot sessions
|
||||
* @author Marek Wesolowski
|
||||
* @date 2025
|
||||
* @copyright KVC Framework
|
||||
*
|
||||
* Tracks protection state changes and enables restoration after system reboots,
|
||||
* maintaining up to 16 boot sessions with automatic cleanup.
|
||||
* Uses registry-based persistence for cross-boot state tracking.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "common.h"
|
||||
@@ -6,63 +17,299 @@
|
||||
#include <vector>
|
||||
#include <optional>
|
||||
|
||||
// Forward declarations
|
||||
struct ProcessEntry;
|
||||
class Controller;
|
||||
|
||||
// Session state entry for restoration tracking
|
||||
/**
|
||||
* @struct SessionEntry
|
||||
* @brief Single process protection state entry for restoration
|
||||
*
|
||||
* Stores complete protection state of a process at the time of unprotect
|
||||
* operation, enabling precise restoration after system reboot.
|
||||
*/
|
||||
struct SessionEntry
|
||||
{
|
||||
DWORD Pid;
|
||||
std::wstring ProcessName;
|
||||
UCHAR OriginalProtection; // Combined level + signer
|
||||
UCHAR SignatureLevel;
|
||||
UCHAR SectionSignatureLevel;
|
||||
std::wstring Status; // "UNPROTECTED" or "RESTORED"
|
||||
DWORD Pid; ///< Process ID at time of unprotect operation
|
||||
std::wstring ProcessName; ///< Process executable name for identification
|
||||
UCHAR OriginalProtection; ///< Combined protection level + signer before unprotect
|
||||
UCHAR SignatureLevel; ///< Executable signature level before unprotect
|
||||
UCHAR SectionSignatureLevel; ///< DLL section signature level before unprotect
|
||||
std::wstring Status; ///< Current status: "UNPROTECTED" or "RESTORED"
|
||||
};
|
||||
|
||||
// Manages process protection state across boot sessions
|
||||
/**
|
||||
* @class SessionManager
|
||||
* @brief Manages process protection state across boot sessions
|
||||
*
|
||||
* Features:
|
||||
* - Automatic boot session detection via boot ID + tick count
|
||||
* - Registry-based state persistence in HKLM
|
||||
* - Maximum 16 session history with automatic cleanup
|
||||
* - Restoration by signer type or all processes
|
||||
* - Stale session cleanup on reboot detection
|
||||
* - Status tracking (UNPROTECTED/RESTORED)
|
||||
*
|
||||
* Registry Structure:
|
||||
* HKLM\SOFTWARE\KVC\Sessions\{BootID}_{TickCount}\{SignerName}\{Index}
|
||||
*
|
||||
* @note Uses boot ID from registry and tick count for unique session identification
|
||||
* @warning Requires administrative privileges for HKLM registry access
|
||||
*/
|
||||
class SessionManager
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Construct session manager
|
||||
*
|
||||
* Initializes internal state but does not automatically detect reboot.
|
||||
* Call DetectAndHandleReboot() manually for reboot detection.
|
||||
*/
|
||||
SessionManager() = default;
|
||||
|
||||
/**
|
||||
* @brief Destructor
|
||||
*
|
||||
* No special cleanup needed - registry operations are atomic.
|
||||
*/
|
||||
~SessionManager() = default;
|
||||
|
||||
// Session lifecycle management
|
||||
void CleanupStaleSessions() noexcept;
|
||||
void CleanupAllSessionsExceptCurrent() noexcept;
|
||||
void DetectAndHandleReboot() noexcept;
|
||||
void EnforceSessionLimit(int maxSessions) noexcept;
|
||||
// === Session Lifecycle Management ===
|
||||
|
||||
// State tracking operations
|
||||
/**
|
||||
* @brief Remove sessions that no longer exist (old boot IDs)
|
||||
*
|
||||
* Scans registry for session entries and removes those from previous
|
||||
* boot sessions. Called automatically on initialization.
|
||||
*
|
||||
* @note Called automatically by DetectAndHandleReboot()
|
||||
*/
|
||||
void CleanupStaleSessions() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Delete all sessions except current boot session
|
||||
*
|
||||
* Manual cleanup method for removing historical session data.
|
||||
* Useful when session limit is reached or for privacy reasons.
|
||||
*
|
||||
* @note Used for manual cleanup via 'cleanup-sessions' command
|
||||
*/
|
||||
void CleanupAllSessionsExceptCurrent() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Detect system reboot and cleanup old sessions
|
||||
*
|
||||
* Compares current boot ID with registry-stored value to detect
|
||||
* system reboot. Automatically cleans up stale sessions on reboot.
|
||||
*
|
||||
* @note Should be called at application startup
|
||||
*/
|
||||
void DetectAndHandleReboot() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Enforce maximum session limit (default: 16)
|
||||
* @param maxSessions Maximum number of sessions to keep
|
||||
*
|
||||
* Deletes oldest sessions when limit exceeded. Sessions are sorted
|
||||
* by creation time (boot ID + tick count).
|
||||
*
|
||||
* @note Called automatically when saving new sessions
|
||||
*/
|
||||
void EnforceSessionLimit(int maxSessions) noexcept;
|
||||
|
||||
// === State Tracking Operations ===
|
||||
|
||||
/**
|
||||
* @brief Save unprotect operation for future restoration
|
||||
* @param signerName Signer type name (e.g., "Antimalware", "WinTcb")
|
||||
* @param affectedProcesses Vector of processes that were unprotected
|
||||
* @return true if state saved to registry successfully
|
||||
*
|
||||
* Creates new session entry with current boot ID and saves complete
|
||||
* protection state of all affected processes for later restoration.
|
||||
*
|
||||
* @note Each signer type gets separate registry key for organization
|
||||
*/
|
||||
bool SaveUnprotectOperation(const std::wstring& signerName,
|
||||
const std::vector<ProcessEntry>& affectedProcesses) noexcept;
|
||||
|
||||
// === Restoration Operations ===
|
||||
|
||||
// Restoration operations
|
||||
bool RestoreBySigner(const std::wstring& signerName, class Controller* controller) noexcept;
|
||||
bool RestoreAll(class Controller* controller) noexcept;
|
||||
/**
|
||||
* @brief Restore protection for specific signer group
|
||||
* @param signerName Signer type to restore (e.g., "Antimalware")
|
||||
* @param controller Controller instance for protection operations
|
||||
* @return true if restoration successful for all processes
|
||||
*
|
||||
* Loads session entries for specified signer and restores original
|
||||
* protection levels. Only processes with "UNPROTECTED" status are
|
||||
* processed. Updates status to "RESTORED" after successful restoration.
|
||||
*
|
||||
* @note Uses Controller for actual protection manipulation
|
||||
*/
|
||||
bool RestoreBySigner(const std::wstring& signerName, Controller* controller) noexcept;
|
||||
|
||||
// Query operations
|
||||
/**
|
||||
* @brief Restore all saved protection states
|
||||
* @param controller Controller instance for protection operations
|
||||
* @return true if all restorations successful
|
||||
*
|
||||
* Iterates through all signers in current session and restores
|
||||
* protection for all "UNPROTECTED" processes.
|
||||
*
|
||||
* @note Comprehensive restoration across all signer types
|
||||
*/
|
||||
bool RestoreAll(Controller* controller) noexcept;
|
||||
|
||||
// === Query Operations ===
|
||||
|
||||
/**
|
||||
* @brief Display session history with statistics
|
||||
*
|
||||
* Shows all stored sessions with process counts, timestamps, and
|
||||
* restoration status. Highlights current boot session.
|
||||
*
|
||||
* @note Useful for debugging and session management
|
||||
*/
|
||||
void ShowHistory() noexcept;
|
||||
|
||||
private:
|
||||
/**
|
||||
* @brief Get current boot session identifier
|
||||
* @return Session ID string: "{BootID}_{TickCount}"
|
||||
*
|
||||
* Combines boot ID from registry with current tick count for
|
||||
* unique session identification across reboots.
|
||||
*
|
||||
* @note Cached for performance during same execution
|
||||
*/
|
||||
std::wstring GetCurrentBootSession() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Calculate boot time from tick count
|
||||
* @return Formatted boot time string
|
||||
*
|
||||
* Converts system tick count to human-readable boot time
|
||||
* for display in session history.
|
||||
*/
|
||||
std::wstring CalculateBootTime() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Get last boot ID from registry
|
||||
* @return Boot ID from last session, or 0 if not found
|
||||
*
|
||||
* Reads stored boot ID from registry to detect system reboots.
|
||||
*/
|
||||
ULONGLONG GetLastBootIdFromRegistry() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Save current boot ID to registry
|
||||
* @param bootId Boot ID to save
|
||||
*
|
||||
* Stores current boot ID in registry for reboot detection
|
||||
* in subsequent executions.
|
||||
*/
|
||||
void SaveLastBootId(ULONGLONG bootId) noexcept;
|
||||
|
||||
|
||||
/**
|
||||
* @brief Get last tick count from registry
|
||||
* @return Tick count from last session
|
||||
*
|
||||
* Reads stored tick count for session continuity tracking.
|
||||
*/
|
||||
ULONGLONG GetLastTickCountFromRegistry() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Save current tick count to registry
|
||||
* @param tickCount Tick count to save
|
||||
*
|
||||
* Stores current tick count for precise session identification.
|
||||
*/
|
||||
void SaveLastTickCount(ULONGLONG tickCount) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Get base registry path for sessions
|
||||
* @return "SOFTWARE\\KVC\\Sessions"
|
||||
*
|
||||
* Base registry path where all session data is stored.
|
||||
*/
|
||||
std::wstring GetRegistryBasePath() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Get registry path for specific session
|
||||
* @param sessionId Session identifier
|
||||
* @return Full registry path to session
|
||||
*
|
||||
* Constructs complete registry path for a specific session.
|
||||
*/
|
||||
std::wstring GetSessionPath(const std::wstring& sessionId) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Load session entries for specific signer
|
||||
* @param signerName Signer type name
|
||||
* @return Vector of session entries
|
||||
*
|
||||
* Reads all session entries for a specific signer from registry.
|
||||
*/
|
||||
std::vector<SessionEntry> LoadSessionEntries(const std::wstring& signerName) noexcept;
|
||||
std::vector<SessionEntry> LoadSessionEntriesFromPath(const std::wstring& sessionPath, const std::wstring& signerName) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Load session entries from specific registry path
|
||||
* @param sessionPath Registry path to session
|
||||
* @param signerName Signer type name
|
||||
* @return Vector of session entries
|
||||
*
|
||||
* Internal method for reading session entries from arbitrary paths.
|
||||
*/
|
||||
std::vector<SessionEntry> LoadSessionEntriesFromPath(const std::wstring& sessionPath,
|
||||
const std::wstring& signerName) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Write session entry to registry
|
||||
* @param signerName Signer type name
|
||||
* @param index Entry index within signer group
|
||||
* @param entry Session entry data to write
|
||||
* @return true if write successful
|
||||
*
|
||||
* Stores individual session entry in registry with proper value types.
|
||||
*/
|
||||
bool WriteSessionEntry(const std::wstring& signerName, DWORD index, const SessionEntry& entry) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Update entry status in registry
|
||||
* @param signerName Signer type name
|
||||
* @param index Entry index to update
|
||||
* @param newStatus New status string ("UNPROTECTED" or "RESTORED")
|
||||
* @return true if update successful
|
||||
*
|
||||
* Updates status field of existing session entry after restoration.
|
||||
*/
|
||||
bool UpdateEntryStatus(const std::wstring& signerName, DWORD index, const std::wstring& newStatus) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Get all session IDs from registry
|
||||
* @return Vector of session ID strings
|
||||
*
|
||||
* Enumerates all existing session IDs in registry for cleanup operations.
|
||||
*/
|
||||
std::vector<std::wstring> GetAllSessionIds() noexcept;
|
||||
|
||||
// Registry helpers
|
||||
/**
|
||||
* @brief Open or create registry key
|
||||
* @param path Registry path
|
||||
* @return Registry key handle or nullptr on failure
|
||||
*
|
||||
* Helper method for registry operations that creates keys if missing.
|
||||
*/
|
||||
HKEY OpenOrCreateKey(const std::wstring& path) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Recursively delete registry key and all subkeys
|
||||
* @param hKeyParent Parent key handle
|
||||
* @param subKey Subkey name to delete
|
||||
* @return true if deletion successful
|
||||
*
|
||||
* Comprehensive registry key deletion for session cleanup.
|
||||
*/
|
||||
bool DeleteKeyRecursive(HKEY hKeyParent, const std::wstring& subKey) noexcept;
|
||||
};
|
||||
@@ -540,7 +540,7 @@ HANDLE TrustedInstallerIntegrator::GetCachedTrustedInstallerToken() {
|
||||
}
|
||||
|
||||
// Enable privileges required to interact with system processes.
|
||||
if (!EnablePrivilege(L"SeDebugPrivilege") || !EnablePrivilege(L"SeImpersonatePrivilege")) {
|
||||
if (!EnablePrivilegeInternal(L"SeDebugPrivilege") || !EnablePrivilegeInternal(L"SeImpersonatePrivilege")) {
|
||||
ERROR(L"Failed to enable required privileges (SeDebug/SeImpersonate)");
|
||||
return nullptr;
|
||||
}
|
||||
@@ -748,7 +748,7 @@ std::wstring TrustedInstallerIntegrator::ResolveLnk(LPCWSTR lnkPath)
|
||||
/**
|
||||
* @brief Enables a specific privilege for the current process token.
|
||||
*/
|
||||
BOOL TrustedInstallerIntegrator::EnablePrivilege(LPCWSTR privilegeName)
|
||||
BOOL TrustedInstallerIntegrator::EnablePrivilegeInternal(LPCWSTR privilegeName)
|
||||
{
|
||||
HANDLE hToken;
|
||||
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES, &hToken)) return FALSE;
|
||||
@@ -777,7 +777,7 @@ BOOL TrustedInstallerIntegrator::EnablePrivilege(LPCWSTR privilegeName)
|
||||
BOOL TrustedInstallerIntegrator::ImpersonateSystem()
|
||||
{
|
||||
// Enable debug privilege to open system-level processes.
|
||||
EnablePrivilege(L"SeDebugPrivilege");
|
||||
EnablePrivilegeInternal(L"SeDebugPrivilege");
|
||||
|
||||
DWORD systemPid = GetProcessIdByName(L"winlogon.exe");
|
||||
if (systemPid == 0) return FALSE;
|
||||
|
||||
@@ -1,82 +1,324 @@
|
||||
/**
|
||||
* @file TrustedInstallerIntegrator.h
|
||||
* @brief TrustedInstaller privilege escalation and system-level operations
|
||||
* @author Marek Wesolowski
|
||||
* @date 2025
|
||||
* @copyright KVC Framework
|
||||
*
|
||||
* Provides maximum privilege access through TrustedInstaller token impersonation,
|
||||
* enabling registry manipulation, Defender exclusions, and protected system operations.
|
||||
* Bypasses UAC and achieves SYSTEM + TrustedInstaller privileges for maximum access.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
// TrustedInstaller privilege escalation for maximum system access
|
||||
/**
|
||||
* @class TrustedInstallerIntegrator
|
||||
* @brief Manages TrustedInstaller privilege escalation for maximum system access
|
||||
*
|
||||
* This class handles:
|
||||
* - Token acquisition and caching from TrustedInstaller service
|
||||
* - Elevated command execution with SYSTEM + TrustedInstaller privileges
|
||||
* - Windows Defender exclusion management (paths, processes, extensions, IPs)
|
||||
* - Sticky keys backdoor installation/removal
|
||||
* - Context menu registry integration
|
||||
* - Comprehensive privilege enablement for maximum system access
|
||||
*
|
||||
* @note Requires administrative privileges for initial token acquisition
|
||||
* @warning TrustedInstaller access provides complete system control
|
||||
*/
|
||||
class TrustedInstallerIntegrator
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Construct TrustedInstaller integrator
|
||||
*
|
||||
* Initializes internal state but does not acquire tokens immediately.
|
||||
* Token acquisition happens on first privileged operation.
|
||||
*/
|
||||
TrustedInstallerIntegrator();
|
||||
|
||||
/**
|
||||
* @brief Destructor with token cleanup
|
||||
*
|
||||
* Releases any acquired tokens and reverts impersonation if active.
|
||||
*/
|
||||
~TrustedInstallerIntegrator();
|
||||
|
||||
// Enhanced exclusion types for comprehensive Defender management
|
||||
/**
|
||||
* @brief Types of Windows Defender exclusions
|
||||
*
|
||||
* Categorizes different exclusion types for precise Defender management.
|
||||
*/
|
||||
enum class ExclusionType {
|
||||
Paths,
|
||||
Processes,
|
||||
Extensions,
|
||||
IpAddresses
|
||||
Paths, ///< File/folder path exclusions (e.g., "C:\Windows\Temp")
|
||||
Processes, ///< Process name exclusions (e.g., "notepad.exe")
|
||||
Extensions, ///< File extension exclusions (e.g., ".exe", ".dll")
|
||||
IpAddresses ///< IP address exclusions (e.g., "192.168.1.1", "10.0.0.0/24")
|
||||
};
|
||||
|
||||
// Main public interface for elevated operations
|
||||
/**
|
||||
* @brief Execute command with TrustedInstaller privileges (visible window)
|
||||
* @param commandLine Command to execute
|
||||
* @return true if execution successful
|
||||
* @note Shows command window during execution
|
||||
* @note Uses CreateProcessAsTrustedInstaller internally
|
||||
*/
|
||||
bool RunAsTrustedInstaller(const std::wstring& commandLine);
|
||||
|
||||
/**
|
||||
* @brief Execute command with TrustedInstaller privileges (hidden window)
|
||||
* @param commandLine Command to execute
|
||||
* @return true if execution successful and exit code 0
|
||||
* @note Waits up to 3 seconds for process completion
|
||||
* @note Uses CreateProcessAsTrustedInstallerSilent internally
|
||||
*/
|
||||
bool RunAsTrustedInstallerSilent(const std::wstring& commandLine);
|
||||
|
||||
// Legacy exclusion management (backward compatibility)
|
||||
/**
|
||||
* @brief Add file/process to Windows Defender exclusions (legacy method)
|
||||
* @param customPath Path to exclude (empty = current executable)
|
||||
* @return true if exclusion added successfully
|
||||
* @note For executables, adds both path and process exclusions
|
||||
* @note Uses PowerShell Add-MpPreference cmdlet
|
||||
*/
|
||||
bool AddToDefenderExclusions(const std::wstring& customPath = L"");
|
||||
|
||||
/**
|
||||
* @brief Remove file/process from Windows Defender exclusions (legacy method)
|
||||
* @param customPath Path to remove (empty = current executable)
|
||||
* @return true if exclusion removed successfully
|
||||
* @note Uses PowerShell Remove-MpPreference cmdlet
|
||||
*/
|
||||
bool RemoveFromDefenderExclusions(const std::wstring& customPath = L"");
|
||||
|
||||
/**
|
||||
* @brief Add Windows Explorer context menu entries
|
||||
* @return true if registry keys created successfully
|
||||
* @note Adds "Run as TrustedInstaller" to right-click menu
|
||||
* @note Requires TrustedInstaller privileges for HKLM registry access
|
||||
*/
|
||||
bool AddContextMenuEntries();
|
||||
|
||||
// Enhanced exclusion management with type specification
|
||||
/**
|
||||
* @brief Add exclusion to Windows Defender by type
|
||||
* @param type Exclusion type (Paths/Processes/Extensions/IpAddresses)
|
||||
* @param value Value to exclude
|
||||
* @return true if exclusion added successfully
|
||||
* @note Uses PowerShell Add-MpPreference cmdlet
|
||||
* @note Validates input based on exclusion type
|
||||
*/
|
||||
bool AddDefenderExclusion(ExclusionType type, const std::wstring& value);
|
||||
|
||||
/**
|
||||
* @brief Remove exclusion from Windows Defender by type
|
||||
* @param type Exclusion type (Paths/Processes/Extensions/IpAddresses)
|
||||
* @param value Value to remove
|
||||
* @return true if exclusion removed successfully
|
||||
* @note Uses PowerShell Remove-MpPreference cmdlet
|
||||
*/
|
||||
bool RemoveDefenderExclusion(ExclusionType type, const std::wstring& value);
|
||||
|
||||
// Type-specific exclusion methods for convenience
|
||||
/**
|
||||
* @brief Add file extension exclusion
|
||||
* @param extension Extension to exclude (e.g., ".exe", ".dll")
|
||||
* @return true if exclusion added successfully
|
||||
* @note Automatically adds leading dot if missing
|
||||
* @note Validates extension format
|
||||
*/
|
||||
bool AddExtensionExclusion(const std::wstring& extension);
|
||||
|
||||
/**
|
||||
* @brief Remove file extension exclusion
|
||||
* @param extension Extension to remove
|
||||
* @return true if exclusion removed successfully
|
||||
*/
|
||||
bool RemoveExtensionExclusion(const std::wstring& extension);
|
||||
|
||||
/**
|
||||
* @brief Add IP address exclusion
|
||||
* @param ipAddress IP address or CIDR notation (e.g., "192.168.1.1", "10.0.0.0/24")
|
||||
* @return true if exclusion added successfully
|
||||
* @note Validates IP address format
|
||||
*/
|
||||
bool AddIpAddressExclusion(const std::wstring& ipAddress);
|
||||
|
||||
/**
|
||||
* @brief Remove IP address exclusion
|
||||
* @param ipAddress IP address or CIDR notation to remove
|
||||
* @return true if exclusion removed successfully
|
||||
*/
|
||||
bool RemoveIpAddressExclusion(const std::wstring& ipAddress);
|
||||
|
||||
// Sticky keys backdoor management
|
||||
/**
|
||||
* @brief Install sticky keys backdoor (sethc.exe -> cmd.exe)
|
||||
* @return true if backdoor installed successfully
|
||||
* @note Requires system restart, adds cmd.exe to Defender exclusions
|
||||
* @warning Security risk - only for authorized testing
|
||||
* @note Uses Image File Execution Options registry key
|
||||
*/
|
||||
bool InstallStickyKeysBackdoor() noexcept;
|
||||
|
||||
/**
|
||||
* @brief Remove sticky keys backdoor and restore original behavior
|
||||
* @return true if backdoor removed successfully
|
||||
* @note Removes IFEO registry key and Defender exclusions
|
||||
*/
|
||||
bool RemoveStickyKeysBackdoor() noexcept;
|
||||
|
||||
// Process exclusion management for Defender bypass
|
||||
/**
|
||||
* @brief Add process to Windows Defender exclusions
|
||||
* @param processName Process name (e.g., "notepad.exe")
|
||||
* @return true if exclusion added successfully
|
||||
* @note Validates process name format
|
||||
*/
|
||||
bool AddProcessToDefenderExclusions(const std::wstring& processName);
|
||||
|
||||
/**
|
||||
* @brief Remove process from Windows Defender exclusions
|
||||
* @param processName Process name to remove
|
||||
* @return true if exclusion removed successfully
|
||||
*/
|
||||
bool RemoveProcessFromDefenderExclusions(const std::wstring& processName);
|
||||
|
||||
// Public access methods for Controller integration
|
||||
/**
|
||||
* @brief Get array of all privilege names
|
||||
* @return Pointer to array of privilege name strings
|
||||
* @note Used for enabling comprehensive privileges on TrustedInstaller token
|
||||
*/
|
||||
static const LPCWSTR* GetAllPrivileges() { return ALL_PRIVILEGES; }
|
||||
|
||||
/**
|
||||
* @brief Get count of privileges in ALL_PRIVILEGES array
|
||||
* @return Number of privilege names
|
||||
*/
|
||||
static int GetPrivilegeCount() { return PRIVILEGE_COUNT; }
|
||||
|
||||
/**
|
||||
* @brief Impersonate SYSTEM account
|
||||
* @return true if impersonation successful
|
||||
* @note Required step before acquiring TrustedInstaller token
|
||||
* @note Uses SeDebugPrivilege to access SYSTEM processes
|
||||
*/
|
||||
bool PublicImpersonateSystem() { return ImpersonateSystem(); }
|
||||
|
||||
// TrustedInstaller token management
|
||||
/**
|
||||
* @brief Get cached TrustedInstaller token or acquire new one
|
||||
* @return Handle to TrustedInstaller token, or nullptr on failure
|
||||
* @note Token cached for 30 seconds, automatically enables all privileges
|
||||
* @note Acquires token from TrustedInstaller service process
|
||||
*/
|
||||
HANDLE GetCachedTrustedInstallerToken();
|
||||
|
||||
/**
|
||||
* @brief Start TrustedInstaller service and get its PID
|
||||
* @return Process ID of TrustedInstaller service, or 0 on failure
|
||||
* @note Waits up to 30 seconds for service to start
|
||||
* @note Requires SC_MANAGER_ALL_ACCESS privileges
|
||||
*/
|
||||
DWORD StartTrustedInstallerService();
|
||||
|
||||
private:
|
||||
// Privilege and process management
|
||||
BOOL EnablePrivilege(LPCWSTR privilegeName);
|
||||
DWORD GetProcessIdByName(LPCWSTR processName);
|
||||
/**
|
||||
* @brief Complete Windows privilege set for maximum access
|
||||
*
|
||||
* Array containing all Windows privilege names for comprehensive enablement
|
||||
* on TrustedInstaller token. Includes backup, restore, debug, and security privileges.
|
||||
*/
|
||||
static const LPCWSTR ALL_PRIVILEGES[];
|
||||
|
||||
/**
|
||||
* @brief Number of privileges in ALL_PRIVILEGES array
|
||||
*/
|
||||
static const int PRIVILEGE_COUNT;
|
||||
|
||||
/**
|
||||
* @brief Impersonate SYSTEM account using SeDebugPrivilege
|
||||
* @return true if impersonation successful
|
||||
* @note Internal implementation used by PublicImpersonateSystem()
|
||||
*/
|
||||
BOOL ImpersonateSystem();
|
||||
|
||||
// Process creation with TrustedInstaller token
|
||||
/**
|
||||
* @brief Create process with TrustedInstaller token (visible window)
|
||||
* @param pid TrustedInstaller process ID
|
||||
* @param commandLine Command to execute
|
||||
* @return true if process creation successful
|
||||
*/
|
||||
BOOL CreateProcessAsTrustedInstaller(DWORD pid, LPCWSTR commandLine);
|
||||
|
||||
/**
|
||||
* @brief Create process with TrustedInstaller token (hidden window)
|
||||
* @param pid TrustedInstaller process ID
|
||||
* @param commandLine Command to execute
|
||||
* @return true if process creation successful
|
||||
*/
|
||||
BOOL CreateProcessAsTrustedInstallerSilent(DWORD pid, LPCWSTR commandLine);
|
||||
|
||||
// Shortcut file handling for .lnk support
|
||||
std::wstring ResolveLnk(LPCWSTR lnkPath);
|
||||
BOOL IsLnkFile(LPCWSTR filePath);
|
||||
/**
|
||||
* @brief Enable specific privilege in current token
|
||||
* @param privilegeName Privilege name to enable
|
||||
* @return true if privilege enabled successfully
|
||||
*/
|
||||
BOOL EnablePrivilegeInternal(LPCWSTR privilegeName);
|
||||
|
||||
/**
|
||||
* @brief Add path exclusion to Windows Defender
|
||||
* @param path Path to exclude
|
||||
* @return true if exclusion added successfully
|
||||
*/
|
||||
bool AddPathExclusion(const std::wstring& path);
|
||||
|
||||
// Validation and helper methods for exclusions
|
||||
|
||||
/**
|
||||
* @brief Get process ID by process name
|
||||
* @param processName Process name to find
|
||||
* @return Process ID if found, 0 if not found
|
||||
*/
|
||||
DWORD GetProcessIdByName(LPCWSTR processName);
|
||||
|
||||
/**
|
||||
* @brief Check if file is a Windows shortcut (.lnk)
|
||||
* @param filePath File path to check
|
||||
* @return true if file is a .lnk shortcut
|
||||
*/
|
||||
BOOL IsLnkFile(LPCWSTR filePath);
|
||||
|
||||
/**
|
||||
* @brief Resolve .lnk shortcut to target path
|
||||
* @param lnkPath Path to .lnk file
|
||||
* @return Resolved target path, empty on failure
|
||||
*/
|
||||
std::wstring ResolveLnk(LPCWSTR lnkPath);
|
||||
|
||||
/**
|
||||
* @brief Validate file extension format
|
||||
* @param extension Extension to validate
|
||||
* @return true if extension format is valid
|
||||
*/
|
||||
bool ValidateExtension(const std::wstring& extension) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Validate IP address format
|
||||
* @param ipAddress IP address to validate
|
||||
* @return true if IP address format is valid
|
||||
*/
|
||||
bool ValidateIpAddress(const std::wstring& ipAddress) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Normalize extension format (ensure leading dot)
|
||||
* @param extension Extension to normalize
|
||||
* @return Normalized extension with leading dot
|
||||
*/
|
||||
std::wstring NormalizeExtension(const std::wstring& extension) noexcept;
|
||||
|
||||
/**
|
||||
* @brief Get string representation of exclusion type
|
||||
* @param type Exclusion type
|
||||
* @return String representation for PowerShell commands
|
||||
*/
|
||||
std::wstring GetExclusionTypeString(ExclusionType type) noexcept;
|
||||
|
||||
// Complete Windows privilege set for maximum access
|
||||
static const LPCWSTR ALL_PRIVILEGES[];
|
||||
static const int PRIVILEGE_COUNT;
|
||||
};
|
||||
@@ -988,31 +988,39 @@ const wchar_t* GetProcessDisplayColor(UCHAR signerType, UCHAR signatureLevel,
|
||||
UCHAR sectionSignatureLevel) noexcept
|
||||
{
|
||||
// Color coding based on process trust level
|
||||
// Special case: System process (PID 4) - unique Kernel+System signature
|
||||
if (signatureLevel == 0x1e && sectionSignatureLevel == 0x1c) {
|
||||
return ProcessColors::PURPLE;
|
||||
}
|
||||
|
||||
bool hasUncheckedSignatures = (signatureLevel == 0x00 || sectionSignatureLevel == 0x00);
|
||||
|
||||
|
||||
if (hasUncheckedSignatures) {
|
||||
return ProcessColors::BLUE; // Unchecked signatures - blue
|
||||
}
|
||||
|
||||
// LSA processes - RED (critical security authority)
|
||||
if (signerType == static_cast<UCHAR>(PS_PROTECTED_SIGNER::Lsa)) {
|
||||
return ProcessColors::RED;
|
||||
}
|
||||
// LSA processes - RED (critical security authority)
|
||||
if (signerType == static_cast<UCHAR>(PS_PROTECTED_SIGNER::Lsa)) {
|
||||
return ProcessColors::RED;
|
||||
}
|
||||
|
||||
// System processes - GREEN (kernel/system trust)
|
||||
if (signerType == static_cast<UCHAR>(PS_PROTECTED_SIGNER::Windows) ||
|
||||
signerType == static_cast<UCHAR>(PS_PROTECTED_SIGNER::WinTcb) ||
|
||||
signerType == static_cast<UCHAR>(PS_PROTECTED_SIGNER::WinSystem)) {
|
||||
return ProcessColors::GREEN;
|
||||
}
|
||||
// High trust system processes - GREEN (WinSystem and WinTcb)
|
||||
if (signerType == static_cast<UCHAR>(PS_PROTECTED_SIGNER::WinTcb) ||
|
||||
signerType == static_cast<UCHAR>(PS_PROTECTED_SIGNER::WinSystem)) {
|
||||
return ProcessColors::GREEN;
|
||||
}
|
||||
|
||||
// Security software - YELLOW (antimalware)
|
||||
if (signerType == static_cast<UCHAR>(PS_PROTECTED_SIGNER::Antimalware)) {
|
||||
return ProcessColors::YELLOW;
|
||||
}
|
||||
// Windows services - CYAN (lower system trust)
|
||||
if (signerType == static_cast<UCHAR>(PS_PROTECTED_SIGNER::Windows)) {
|
||||
return ProcessColors::CYAN;
|
||||
}
|
||||
|
||||
// User/third-party processes - YELLOW (default)
|
||||
return ProcessColors::YELLOW;
|
||||
// Security software - YELLOW (antimalware)
|
||||
if (signerType == static_cast<UCHAR>(PS_PROTECTED_SIGNER::Antimalware)) {
|
||||
return ProcessColors::YELLOW;
|
||||
}
|
||||
|
||||
// User/third-party processes - YELLOW (default)
|
||||
return ProcessColors::YELLOW;
|
||||
}
|
||||
|
||||
} // namespace Utils
|
||||
98
kvc/Utils.h
98
kvc/Utils.h
@@ -7,6 +7,7 @@
|
||||
*
|
||||
* Header file containing declarations for process management, memory operations,
|
||||
* protection level handling, and various system utilities.
|
||||
* Centralized utilities used throughout the KVC Framework.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
@@ -19,6 +20,22 @@
|
||||
#include <vector>
|
||||
#include <array>
|
||||
|
||||
/**
|
||||
* @namespace Utils
|
||||
* @brief Core utility functions namespace for KVC Framework
|
||||
*
|
||||
* Provides essential utilities for:
|
||||
* - String and numeric parsing
|
||||
* - File and resource operations
|
||||
* - Process name resolution
|
||||
* - Kernel address operations
|
||||
* - Protection level bit manipulation
|
||||
* - String conversion utilities
|
||||
* - Process dumpability analysis
|
||||
* - Hex string utilities
|
||||
* - PE binary manipulation
|
||||
* - Console coloring utilities
|
||||
*/
|
||||
namespace Utils
|
||||
{
|
||||
// ============================================================================
|
||||
@@ -29,6 +46,8 @@ namespace Utils
|
||||
* @brief Parses PID from string with validation
|
||||
* @param pidStr String containing PID value
|
||||
* @return std::optional<DWORD> Parsed PID or nullopt on invalid input
|
||||
* @note Validates numeric range and format
|
||||
* @note Returns nullopt for non-numeric strings or invalid PIDs
|
||||
*/
|
||||
std::optional<DWORD> ParsePid(const std::wstring& pidStr) noexcept;
|
||||
|
||||
@@ -36,6 +55,8 @@ namespace Utils
|
||||
* @brief Checks if string contains only numeric characters
|
||||
* @param str String to validate
|
||||
* @return bool true if string is numeric
|
||||
* @note Empty string returns false
|
||||
* @note Handles Unicode numeric characters
|
||||
*/
|
||||
bool IsNumeric(const std::wstring& str) noexcept;
|
||||
|
||||
@@ -48,6 +69,8 @@ namespace Utils
|
||||
* @param path File path to read
|
||||
* @return std::vector<BYTE> File contents or empty on failure
|
||||
* @note Renamed from ReadFile to avoid conflict with Windows API
|
||||
* @note Maximum file size: 256MB for safety
|
||||
* @note Uses memory-mapped files for large files
|
||||
*/
|
||||
std::vector<BYTE> ReadFile(const std::wstring& path) noexcept;
|
||||
|
||||
@@ -56,6 +79,8 @@ namespace Utils
|
||||
* @param resourceId Resource identifier
|
||||
* @param resourceType Resource type (e.g., RT_RCDATA)
|
||||
* @return std::vector<BYTE> Resource data or empty on failure
|
||||
* @note Uses FindResource/LoadResource Windows API
|
||||
* @note Returns empty vector if resource not found
|
||||
*/
|
||||
std::vector<BYTE> ReadResource(int resourceId, const wchar_t* resourceType);
|
||||
|
||||
@@ -65,6 +90,8 @@ namespace Utils
|
||||
* @param data Data to write
|
||||
* @return bool true on successful write
|
||||
* @note Renamed from WriteFile to avoid conflict with Windows API
|
||||
* @note Handles large files with chunked writing
|
||||
* @note Creates directory structure if needed
|
||||
*/
|
||||
bool WriteFile(const std::wstring& path, const std::vector<BYTE>& data) noexcept;
|
||||
|
||||
@@ -72,6 +99,9 @@ namespace Utils
|
||||
* @brief Force deletes file by removing attributes and using fallback methods
|
||||
* @param path File path to delete
|
||||
* @return bool true if file deleted successfully
|
||||
* @note Removes read-only, system, and hidden attributes
|
||||
* @note Uses multiple deletion strategies for stubborn files
|
||||
* @note Handles file locking and sharing violations
|
||||
*/
|
||||
bool ForceDeleteFile(const std::wstring& path) noexcept;
|
||||
|
||||
@@ -83,6 +113,9 @@ namespace Utils
|
||||
* @brief Resolves process name from PID using multiple methods
|
||||
* @param pid Process ID to resolve
|
||||
* @return std::wstring Process name or "[Unknown]"
|
||||
* @note Attempts: Toolhelp32, OpenProcess+GetModuleFileName, NtQuerySystemInformation
|
||||
* @note Returns "[Unknown]" if all methods fail
|
||||
* @note Caches results for performance
|
||||
*/
|
||||
std::wstring GetProcessName(DWORD pid) noexcept;
|
||||
|
||||
@@ -93,6 +126,8 @@ namespace Utils
|
||||
* @param protectionLevel Protection level byte
|
||||
* @param signerType Signer type byte
|
||||
* @return std::wstring Descriptive process identifier
|
||||
* @note Format: "Protected_Process_[PID]_[Address]_[ProtectionLevel]"
|
||||
* @note Used when process name cannot be resolved normally
|
||||
*/
|
||||
std::wstring ResolveUnknownProcessLocal(DWORD pid, ULONG_PTR kernelAddress,
|
||||
UCHAR protectionLevel, UCHAR signerType) noexcept;
|
||||
@@ -104,6 +139,9 @@ namespace Utils
|
||||
/**
|
||||
* @brief Resolves kernel base address with caching
|
||||
* @return std::optional<ULONG_PTR> Kernel base or nullopt on failure
|
||||
* @note Uses NtQuerySystemInformation with SystemModuleInformation
|
||||
* @note Caches result for 5000ms for performance
|
||||
* @note Returns ntoskrnl.exe base address
|
||||
*/
|
||||
std::optional<ULONG_PTR> GetKernelBaseAddress() noexcept;
|
||||
|
||||
@@ -112,6 +150,8 @@ namespace Utils
|
||||
* @param base Kernel base address
|
||||
* @param offset Offset from base
|
||||
* @return ULONG_PTR Calculated kernel address
|
||||
* @note Simple addition operation, marked constexpr for compile-time evaluation
|
||||
* @note Used for calculating EPROCESS field addresses
|
||||
*/
|
||||
constexpr ULONG_PTR GetKernelAddress(ULONG_PTR base, DWORD offset) noexcept
|
||||
{
|
||||
@@ -126,6 +166,8 @@ namespace Utils
|
||||
* @brief Extracts protection level from combined byte
|
||||
* @param protection Combined protection byte
|
||||
* @return UCHAR Protection level (lower 3 bits)
|
||||
* @note Values: 0=None, 1=ProtectedLight, 2=Protected
|
||||
* @note Uses bitmask 0x07 to extract lower 3 bits
|
||||
*/
|
||||
constexpr UCHAR GetProtectionLevel(UCHAR protection) noexcept
|
||||
{
|
||||
@@ -136,6 +178,8 @@ namespace Utils
|
||||
* @brief Extracts signer type from combined byte
|
||||
* @param protection Combined protection byte
|
||||
* @return UCHAR Signer type (upper 4 bits)
|
||||
* @note Values: 0=None, 1=Authenticode, 3=Antimalware, 6=WinTcb, etc.
|
||||
* @note Uses bitmask 0xF0 and right shift to extract upper 4 bits
|
||||
*/
|
||||
constexpr UCHAR GetSignerType(UCHAR protection) noexcept
|
||||
{
|
||||
@@ -147,6 +191,8 @@ namespace Utils
|
||||
* @param protectionLevel Protection level (0-7)
|
||||
* @param signerType Signer type (0-15)
|
||||
* @return UCHAR Combined protection byte
|
||||
* @note Format: [SignerType:4 bits][ProtectionLevel:3 bits][0:1 bit]
|
||||
* @note Used for writing protection values to kernel memory
|
||||
*/
|
||||
constexpr UCHAR GetProtection(UCHAR protectionLevel, UCHAR signerType) noexcept
|
||||
{
|
||||
@@ -157,6 +203,8 @@ namespace Utils
|
||||
* @brief Extracts signature level value
|
||||
* @param signatureLevel Raw signature level byte
|
||||
* @return UCHAR Signature level value
|
||||
* @note Uses bitmask 0x0F to extract lower 4 bits
|
||||
* @note Signature level indicates code signing verification level
|
||||
*/
|
||||
constexpr UCHAR GetSignatureLevelValue(UCHAR signatureLevel) noexcept
|
||||
{
|
||||
@@ -167,6 +215,8 @@ namespace Utils
|
||||
* @brief Extracts section signature level value
|
||||
* @param sectionSignatureLevel Raw section signature level byte
|
||||
* @return UCHAR Section signature level value
|
||||
* @note Uses bitmask 0x0F to extract lower 4 bits
|
||||
* @note Section signature level indicates DLL signature verification level
|
||||
*/
|
||||
constexpr UCHAR GetSectionSignatureLevelValue(UCHAR sectionSignatureLevel) noexcept
|
||||
{
|
||||
@@ -181,6 +231,8 @@ namespace Utils
|
||||
* @brief Converts protection level to human-readable string
|
||||
* @param protectionLevel Protection level byte
|
||||
* @return const wchar_t* String representation ("None", "PPL", "PP")
|
||||
* @note Returns "Unknown" for invalid protection levels
|
||||
* @note Used for display and logging purposes
|
||||
*/
|
||||
const wchar_t* GetProtectionLevelAsString(UCHAR protectionLevel) noexcept;
|
||||
|
||||
@@ -188,6 +240,8 @@ namespace Utils
|
||||
* @brief Converts signer type to human-readable string
|
||||
* @param signerType Signer type byte
|
||||
* @return const wchar_t* String representation (e.g., "Windows", "Antimalware")
|
||||
* @note Returns "Unknown" for invalid signer types
|
||||
* @note Maps PS_PROTECTED_SIGNER enum values to strings
|
||||
*/
|
||||
const wchar_t* GetSignerTypeAsString(UCHAR signerType) noexcept;
|
||||
|
||||
@@ -195,6 +249,8 @@ namespace Utils
|
||||
* @brief Converts signature level to human-readable string
|
||||
* @param signatureLevel Signature level byte
|
||||
* @return const wchar_t* String representation
|
||||
* @note Returns numeric value as string for unknown levels
|
||||
* @note Used for displaying code signing information
|
||||
*/
|
||||
const wchar_t* GetSignatureLevelAsString(UCHAR signatureLevel) noexcept;
|
||||
|
||||
@@ -202,6 +258,8 @@ namespace Utils
|
||||
* @brief Converts section signature level to human-readable string
|
||||
* @param sectionSignatureLevel Section signature level byte
|
||||
* @return const wchar_t* String representation
|
||||
* @note Returns numeric value as string for unknown levels
|
||||
* @note Used for displaying DLL signing information
|
||||
*/
|
||||
const wchar_t* GetSectionSignatureLevelAsString(UCHAR sectionSignatureLevel) noexcept;
|
||||
|
||||
@@ -213,6 +271,8 @@ namespace Utils
|
||||
* @brief Parses protection level string to enum value
|
||||
* @param protectionLevel String like "PP", "PPL", "None"
|
||||
* @return std::optional<UCHAR> Protection level value or nullopt
|
||||
* @note Case-insensitive matching
|
||||
* @note Supports "PP", "PPL", "None", "0", "1", "2" formats
|
||||
*/
|
||||
std::optional<UCHAR> GetProtectionLevelFromString(const std::wstring& protectionLevel) noexcept;
|
||||
|
||||
@@ -220,6 +280,8 @@ namespace Utils
|
||||
* @brief Parses signer type string to enum value
|
||||
* @param signerType String like "Windows", "Antimalware"
|
||||
* @return std::optional<UCHAR> Signer type value or nullopt
|
||||
* @note Case-insensitive matching
|
||||
* @note Supports: WinTcb, Windows, Antimalware, Lsa, WinSystem, etc.
|
||||
*/
|
||||
std::optional<UCHAR> GetSignerTypeFromString(const std::wstring& signerType) noexcept;
|
||||
|
||||
@@ -227,6 +289,8 @@ namespace Utils
|
||||
* @brief Gets recommended signature level for signer type
|
||||
* @param signerType Signer type enumeration value
|
||||
* @return std::optional<UCHAR> Signature level or nullopt
|
||||
* @note Provides reasonable defaults for different signer types
|
||||
* @note Used when setting new protection levels
|
||||
*/
|
||||
std::optional<UCHAR> GetSignatureLevel(UCHAR signerType) noexcept;
|
||||
|
||||
@@ -234,6 +298,8 @@ namespace Utils
|
||||
* @brief Gets recommended section signature level for signer type
|
||||
* @param signerType Signer type enumeration value
|
||||
* @return std::optional<UCHAR> Section signature level or nullopt
|
||||
* @note Provides reasonable defaults for different signer types
|
||||
* @note Used when setting new protection levels
|
||||
*/
|
||||
std::optional<UCHAR> GetSectionSignatureLevel(UCHAR signerType) noexcept;
|
||||
|
||||
@@ -243,6 +309,9 @@ namespace Utils
|
||||
|
||||
/**
|
||||
* @brief Result structure for process dumpability analysis
|
||||
*
|
||||
* Contains analysis result indicating whether a process can be memory dumped
|
||||
* and the detailed reason for the decision.
|
||||
*/
|
||||
struct ProcessDumpability
|
||||
{
|
||||
@@ -257,6 +326,8 @@ namespace Utils
|
||||
* @param protectionLevel Current protection level
|
||||
* @param signerType Digital signature authority
|
||||
* @return ProcessDumpability Analysis result with reason
|
||||
* @note Considers protection level, signer type, and process name
|
||||
* @note Some protected processes cannot be dumped for security reasons
|
||||
*/
|
||||
ProcessDumpability CanDumpProcess(DWORD pid, const std::wstring& processName,
|
||||
UCHAR protectionLevel, UCHAR signerType) noexcept;
|
||||
@@ -270,6 +341,9 @@ namespace Utils
|
||||
* @param hexString Hex string (supports 0x prefix, spaces, commas)
|
||||
* @param bytes Output byte vector
|
||||
* @return bool true if conversion successful
|
||||
* @note Handles both uppercase and lowercase hex
|
||||
* @note Skips whitespace and common separators
|
||||
* @note Returns false for invalid hex characters
|
||||
*/
|
||||
bool HexStringToBytes(const std::wstring& hexString, std::vector<BYTE>& bytes) noexcept;
|
||||
|
||||
@@ -277,6 +351,8 @@ namespace Utils
|
||||
* @brief Validates hex string format
|
||||
* @param hexString String to validate
|
||||
* @return bool true if valid hex string
|
||||
* @note Allows 0x prefix, spaces, commas as separators
|
||||
* @note Requires even number of hex digits after cleaning
|
||||
*/
|
||||
bool IsValidHexString(const std::wstring& hexString) noexcept;
|
||||
|
||||
@@ -289,6 +365,9 @@ namespace Utils
|
||||
* @param data Binary data containing PE file
|
||||
* @param offset Starting offset in data
|
||||
* @return std::optional<size_t> PE file length or nullopt on invalid PE
|
||||
* @note Validates DOS and NT headers
|
||||
* @note Calculates length from section table
|
||||
* @note Returns nullopt for invalid PE headers
|
||||
*/
|
||||
std::optional<size_t> GetPEFileLength(const std::vector<BYTE>& data, size_t offset = 0) noexcept;
|
||||
|
||||
@@ -298,6 +377,8 @@ namespace Utils
|
||||
* @param first Output for first PE component
|
||||
* @param second Output for second PE component
|
||||
* @return bool true if splitting successful
|
||||
* @note Validates both PE structures before splitting
|
||||
* @note Used for extracting kvc_pass.exe and kvc_crypt.dll from kvc.dat
|
||||
*/
|
||||
bool SplitCombinedPE(const std::vector<BYTE>& combined,
|
||||
std::vector<BYTE>& first,
|
||||
@@ -308,6 +389,8 @@ namespace Utils
|
||||
* @param encryptedData Data to decrypt
|
||||
* @param key XOR key (7 bytes)
|
||||
* @return std::vector<BYTE> Decrypted data or empty on failure
|
||||
* @note Uses repeating key pattern for decryption
|
||||
* @note Used for decrypting embedded driver and binaries
|
||||
*/
|
||||
std::vector<BYTE> DecryptXOR(const std::vector<BYTE>& encryptedData,
|
||||
const std::array<BYTE, 7>& key) noexcept;
|
||||
@@ -318,19 +401,26 @@ namespace Utils
|
||||
|
||||
/**
|
||||
* @brief ANSI color codes for process display
|
||||
*
|
||||
* Provides color coding for different process trust levels and types
|
||||
* in console output. Uses ANSI escape sequences.
|
||||
*/
|
||||
struct ProcessColors {
|
||||
static constexpr const wchar_t* GREEN = L"\033[92m"; ///< System processes (WinTcb, WinSystem, Windows)
|
||||
static constexpr const wchar_t* GREEN = L"\033[92m"; ///< System processes (WinTcb, WinSystem)
|
||||
static constexpr const wchar_t* RED = L"\033[91m"; ///< LSA processes (critical security)
|
||||
static constexpr const wchar_t* YELLOW = L"\033[93m"; ///< User/Antimalware processes
|
||||
static constexpr const wchar_t* BLUE = L"\033[94m"; ///< Unchecked signatures
|
||||
static constexpr const wchar_t* HEADER = L"\033[97;44m"; ///< Table headers
|
||||
static constexpr const wchar_t* RESET = L"\033[0m"; ///< Reset color
|
||||
static constexpr const wchar_t* PURPLE = L"\033[95m"; ///< SYSTEM ONLY!(always 4)
|
||||
static constexpr const wchar_t* CYAN = L"\033[96m"; ///< Windows Signer
|
||||
static constexpr const wchar_t* HEADER = L"\033[97;44m"; ///< Table headers (white on blue)
|
||||
static constexpr const wchar_t* RESET = L"\033[0m"; ///< Reset color to default
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Enables ANSI virtual terminal processing for colored output
|
||||
* @return bool true if enabled successfully
|
||||
* @note Required for ANSI color codes to work on Windows 10+
|
||||
* @note Uses SetConsoleMode with ENABLE_VIRTUAL_TERMINAL_PROCESSING
|
||||
*/
|
||||
bool EnableConsoleVirtualTerminal() noexcept;
|
||||
|
||||
@@ -340,6 +430,8 @@ namespace Utils
|
||||
* @param signatureLevel Executable signature level
|
||||
* @param sectionSignatureLevel DLL signature level
|
||||
* @return const wchar_t* ANSI color code
|
||||
* @note Color coding: Green=System, Red=LSA, Yellow=User, Blue=Unchecked
|
||||
* @note Used in process listing and information display
|
||||
*/
|
||||
const wchar_t* GetProcessDisplayColor(UCHAR signerType, UCHAR signatureLevel,
|
||||
UCHAR sectionSignatureLevel) noexcept;
|
||||
|
||||
357
kvc/common.h
357
kvc/common.h
@@ -1,3 +1,14 @@
|
||||
/**
|
||||
* @file common.h
|
||||
* @brief Common definitions, utilities and includes for KVC Framework
|
||||
* @author Marek Wesolowski
|
||||
* @date 2025
|
||||
* @copyright KVC Framework
|
||||
*
|
||||
* Central header containing Windows API includes, type definitions,
|
||||
* logging system, and cross-cutting utilities used throughout the framework.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Windows.h>
|
||||
@@ -23,32 +34,40 @@
|
||||
#pragma comment(lib, "crypt32.lib")
|
||||
|
||||
// Session management constants
|
||||
inline constexpr int MAX_SESSIONS = 16;
|
||||
inline constexpr int MAX_SESSIONS = 16; ///< Maximum number of stored sessions
|
||||
|
||||
#ifdef BUILD_DATE
|
||||
#define __DATE__ BUILD_DATE
|
||||
#define __DATE__ BUILD_DATE ///< Build date override for reproducible builds
|
||||
#endif
|
||||
|
||||
#ifdef BUILD_TIME
|
||||
#define __TIME__ BUILD_TIME
|
||||
#define __TIME__ BUILD_TIME ///< Build time override for reproducible builds
|
||||
#endif
|
||||
|
||||
#define kvc_DEBUG_ENABLED 0
|
||||
#define kvc_DEBUG_ENABLED 0 ///< Global debug flag (0=disabled, 1=enabled)
|
||||
|
||||
#ifdef ERROR
|
||||
#undef ERROR
|
||||
#undef ERROR ///< Undefine Windows ERROR macro to avoid conflicts
|
||||
#endif
|
||||
|
||||
#ifndef SHTDN_REASON_MAJOR_SOFTWARE
|
||||
#define SHTDN_REASON_MAJOR_SOFTWARE 0x00030000
|
||||
#define SHTDN_REASON_MAJOR_SOFTWARE 0x00030000 ///< Software shutdown reason
|
||||
#endif
|
||||
|
||||
#ifndef SHTDN_REASON_MINOR_RECONFIGURE
|
||||
#define SHTDN_REASON_MINOR_RECONFIGURE 0x00000004
|
||||
#define SHTDN_REASON_MINOR_RECONFIGURE 0x00000004 ///< Reconfiguration shutdown reason
|
||||
#endif
|
||||
|
||||
// Smart module handle management
|
||||
|
||||
/**
|
||||
* @brief Custom deleter for HMODULE with FreeLibrary
|
||||
*/
|
||||
struct ModuleDeleter {
|
||||
/**
|
||||
* @brief Free library module
|
||||
* @param mod Module handle to free
|
||||
*/
|
||||
void operator()(HMODULE mod) const noexcept {
|
||||
if (mod) {
|
||||
FreeLibrary(mod);
|
||||
@@ -56,16 +75,31 @@ struct ModuleDeleter {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Custom deleter for system modules (no cleanup needed)
|
||||
*/
|
||||
struct SystemModuleDeleter {
|
||||
/**
|
||||
* @brief No-op deleter for system modules from GetModuleHandle
|
||||
* @param mod Module handle (ignored)
|
||||
*/
|
||||
void operator()(HMODULE) const noexcept {
|
||||
// System modules obtained via GetModuleHandle don't need to be freed
|
||||
}
|
||||
};
|
||||
|
||||
using ModuleHandle = std::unique_ptr<std::remove_pointer_t<HMODULE>, ModuleDeleter>;
|
||||
using SystemModuleHandle = std::unique_ptr<std::remove_pointer_t<HMODULE>, SystemModuleDeleter>;
|
||||
using ModuleHandle = std::unique_ptr<std::remove_pointer_t<HMODULE>, ModuleDeleter>; ///< Smart pointer for loaded modules
|
||||
using SystemModuleHandle = std::unique_ptr<std::remove_pointer_t<HMODULE>, SystemModuleDeleter>; ///< Smart pointer for system modules
|
||||
|
||||
// Fixed logging system with proper buffer size and variadic handling
|
||||
|
||||
/**
|
||||
* @brief Print formatted message with prefix
|
||||
* @tparam Args Variadic template arguments
|
||||
* @param prefix Message prefix (e.g., "[DEBUG] ")
|
||||
* @param format Format string (printf-style)
|
||||
* @param args Format arguments
|
||||
*/
|
||||
template<typename... Args>
|
||||
void PrintMessage(const wchar_t* prefix, const wchar_t* format, Args&&... args)
|
||||
{
|
||||
@@ -87,6 +121,12 @@ void PrintMessage(const wchar_t* prefix, const wchar_t* format, Args&&... args)
|
||||
std::wcout << ss.str();
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Print critical message in red color
|
||||
* @tparam Args Variadic template arguments
|
||||
* @param format Format string (printf-style)
|
||||
* @param args Format arguments
|
||||
*/
|
||||
template<typename... Args>
|
||||
void PrintCriticalMessage(const wchar_t* format, Args&&... args) {
|
||||
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
|
||||
@@ -104,7 +144,7 @@ void PrintCriticalMessage(const wchar_t* format, Args&&... args) {
|
||||
swprintf_s(buffer, 1024, format, std::forward<Args>(args)...);
|
||||
ss << buffer;
|
||||
} else {
|
||||
ss << format; // <-- DODAJ ELSE - gdy brak args, wyświetl sam format
|
||||
ss << format;
|
||||
}
|
||||
|
||||
ss << L"\r\n";
|
||||
@@ -114,16 +154,20 @@ void PrintCriticalMessage(const wchar_t* format, Args&&... args) {
|
||||
}
|
||||
|
||||
#if kvc_DEBUG_ENABLED
|
||||
#define DEBUG(format, ...) PrintMessage(L"[DEBUG] ", format, ##__VA_ARGS__)
|
||||
#define DEBUG(format, ...) PrintMessage(L"[DEBUG] ", format, ##__VA_ARGS__) ///< Debug logging macro
|
||||
#else
|
||||
#define DEBUG(format, ...) do {} while(0)
|
||||
#define DEBUG(format, ...) do {} while(0) ///< Debug logging macro (disabled)
|
||||
#endif
|
||||
|
||||
#define ERROR(format, ...) PrintMessage(L"[-] ", format, ##__VA_ARGS__)
|
||||
#define INFO(format, ...) PrintMessage(L"[*] ", format, ##__VA_ARGS__)
|
||||
#define SUCCESS(format, ...) PrintMessage(L"[+] ", format, ##__VA_ARGS__)
|
||||
#define CRITICAL(format, ...) PrintCriticalMessage(format, ##__VA_ARGS__)
|
||||
#define ERROR(format, ...) PrintMessage(L"[-] ", format, ##__VA_ARGS__) ///< Error logging macro
|
||||
#define INFO(format, ...) PrintMessage(L"[*] ", format, ##__VA_ARGS__) ///< Info logging macro
|
||||
#define SUCCESS(format, ...) PrintMessage(L"[+] ", format, ##__VA_ARGS__) ///< Success logging macro
|
||||
#define CRITICAL(format, ...) PrintCriticalMessage(format, ##__VA_ARGS__) ///< Critical error logging macro
|
||||
|
||||
/**
|
||||
* @brief Log last error for failed function
|
||||
* @param f Function name that failed
|
||||
*/
|
||||
#define LASTERROR(f) \
|
||||
do { \
|
||||
wchar_t buf[256]; \
|
||||
@@ -132,119 +176,139 @@ void PrintCriticalMessage(const wchar_t* format, Args&&... args) {
|
||||
} while(0)
|
||||
|
||||
// Windows protection type definitions
|
||||
|
||||
/**
|
||||
* @brief Process protection level enumeration
|
||||
*/
|
||||
enum class PS_PROTECTED_TYPE : UCHAR
|
||||
{
|
||||
None = 0,
|
||||
ProtectedLight = 1,
|
||||
Protected = 2
|
||||
None = 0, ///< No protection
|
||||
ProtectedLight = 1, ///< Protected Process Light (PPL)
|
||||
Protected = 2 ///< Protected Process (PP)
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Process signer type enumeration
|
||||
*/
|
||||
enum class PS_PROTECTED_SIGNER : UCHAR
|
||||
{
|
||||
None = 0,
|
||||
Authenticode = 1,
|
||||
CodeGen = 2,
|
||||
Antimalware = 3,
|
||||
Lsa = 4,
|
||||
Windows = 5,
|
||||
WinTcb = 6,
|
||||
WinSystem = 7,
|
||||
App = 8,
|
||||
Max = 9
|
||||
None = 0, ///< No signer
|
||||
Authenticode = 1, ///< Authenticode signed
|
||||
CodeGen = 2, ///< Code generation
|
||||
Antimalware = 3, ///< Antimalware products
|
||||
Lsa = 4, ///< Local Security Authority
|
||||
Windows = 5, ///< Windows signed
|
||||
WinTcb = 6, ///< Windows TCB (Trusted Computing Base)
|
||||
WinSystem = 7, ///< Windows system components
|
||||
App = 8, ///< Application signer
|
||||
Max = 9 ///< Maximum value
|
||||
};
|
||||
|
||||
// Service-related constants
|
||||
|
||||
/**
|
||||
* @brief Service-related constants and configuration
|
||||
*/
|
||||
namespace ServiceConstants {
|
||||
inline constexpr wchar_t SERVICE_NAME[] = L"KernelVulnerabilityControl";
|
||||
inline constexpr wchar_t SERVICE_DISPLAY_NAME[] = L"Kernel Vulnerability Capabilities Framework";
|
||||
inline constexpr wchar_t SERVICE_PARAM[] = L"--service";
|
||||
inline constexpr wchar_t SERVICE_NAME[] = L"KernelVulnerabilityControl"; ///< Service internal name
|
||||
inline constexpr wchar_t SERVICE_DISPLAY_NAME[] = L"Kernel Vulnerability Capabilities Framework"; ///< Service display name
|
||||
inline constexpr wchar_t SERVICE_PARAM[] = L"--service"; ///< Service mode parameter
|
||||
|
||||
// Keyboard hook settings
|
||||
inline constexpr int CTRL_SEQUENCE_LENGTH = 5;
|
||||
inline constexpr DWORD CTRL_SEQUENCE_TIMEOUT_MS = 2000;
|
||||
inline constexpr DWORD CTRL_DEBOUNCE_MS = 50;
|
||||
inline constexpr int CTRL_SEQUENCE_LENGTH = 5; ///< Number of Ctrl presses for activation
|
||||
inline constexpr DWORD CTRL_SEQUENCE_TIMEOUT_MS = 2000; ///< Sequence timeout in milliseconds
|
||||
inline constexpr DWORD CTRL_DEBOUNCE_MS = 50; ///< Key debounce period
|
||||
}
|
||||
|
||||
// DPAPI constants for password extraction
|
||||
|
||||
/**
|
||||
* @brief DPAPI-related constants for password extraction operations
|
||||
*/
|
||||
namespace DPAPIConstants {
|
||||
inline constexpr int SQLITE_OK = 0;
|
||||
inline constexpr int SQLITE_ROW = 100;
|
||||
inline constexpr int SQLITE_DONE = 101;
|
||||
inline constexpr int SQLITE_OPEN_READONLY = 0x00000001;
|
||||
inline constexpr int SQLITE_OK = 0; ///< SQLite success code
|
||||
inline constexpr int SQLITE_ROW = 100; ///< SQLite row available code
|
||||
inline constexpr int SQLITE_DONE = 101; ///< SQLite operation complete code
|
||||
inline constexpr int SQLITE_OPEN_READONLY = 0x00000001; ///< SQLite read-only mode
|
||||
|
||||
inline std::string GetChromeV10Prefix() { return "v10"; }
|
||||
inline std::string GetChromeDPAPIPrefix() { return "DPAPI"; }
|
||||
inline std::string GetChromeV10Prefix() { return "v10"; } ///< Chrome encrypted key prefix
|
||||
inline std::string GetChromeDPAPIPrefix() { return "DPAPI"; } ///< Chrome DPAPI prefix
|
||||
|
||||
inline std::wstring GetSecurityPolicySecrets() { return L"SECURITY\\Policy\\Secrets"; }
|
||||
inline std::wstring GetDPAPISystemKey() { return L"DPAPI_SYSTEM"; }
|
||||
inline std::wstring GetNLKMKey() { return L"NL$KM"; }
|
||||
inline std::wstring GetDefaultPasswordKey() { return L"DefaultPassword"; }
|
||||
inline std::wstring GetSecurityPolicySecrets() { return L"SECURITY\\Policy\\Secrets"; } ///< Registry path for LSA secrets
|
||||
inline std::wstring GetDPAPISystemKey() { return L"DPAPI_SYSTEM"; } ///< DPAPI system key name
|
||||
inline std::wstring GetNLKMKey() { return L"NL$KM"; } ///< NL$KM key name
|
||||
inline std::wstring GetDefaultPasswordKey() { return L"DefaultPassword"; } ///< Default password key name
|
||||
|
||||
inline std::wstring GetCurrVal() { return L"CurrVal"; }
|
||||
inline std::wstring GetOldVal() { return L"OldVal"; }
|
||||
inline std::wstring GetCurrVal() { return L"CurrVal"; } ///< Current value registry key
|
||||
inline std::wstring GetOldVal() { return L"OldVal"; } ///< Old value registry key
|
||||
|
||||
inline std::wstring GetChromeUserData() { return L"\\Google\\Chrome\\User Data"; }
|
||||
inline std::wstring GetEdgeUserData() { return L"\\Microsoft\\Edge\\User Data"; }
|
||||
inline std::wstring GetLocalStateFile() { return L"\\Local State"; }
|
||||
inline std::wstring GetLoginDataFile() { return L"\\Login Data"; }
|
||||
inline std::wstring GetChromeUserData() { return L"\\Google\\Chrome\\User Data"; } ///< Chrome user data path
|
||||
inline std::wstring GetEdgeUserData() { return L"\\Microsoft\\Edge\\User Data"; } ///< Edge user data path
|
||||
inline std::wstring GetLocalStateFile() { return L"\\Local State"; } ///< Local state filename
|
||||
inline std::wstring GetLoginDataFile() { return L"\\Login Data"; } ///< Login data filename
|
||||
|
||||
inline std::string GetEncryptedKeyField() { return "\"encrypted_key\":"; }
|
||||
inline std::string GetEncryptedKeyField() { return "\"encrypted_key\":"; } ///< JSON field for encrypted key
|
||||
|
||||
inline std::string GetLocalAppData() { return "LOCALAPPDATA"; }
|
||||
inline std::string GetLocalAppData() { return "LOCALAPPDATA"; } ///< Local app data environment variable
|
||||
|
||||
inline std::wstring GetHTMLExt() { return L".html"; }
|
||||
inline std::wstring GetTXTExt() { return L".txt"; }
|
||||
inline std::wstring GetDBExt() { return L".db"; }
|
||||
inline std::wstring GetHTMLExt() { return L".html"; } ///< HTML file extension
|
||||
inline std::wstring GetTXTExt() { return L".txt"; } ///< Text file extension
|
||||
inline std::wstring GetDBExt() { return L".db"; } ///< Database file extension
|
||||
|
||||
inline std::wstring GetTempLoginDB() { return L"temp_login_data.db"; }
|
||||
inline std::wstring GetTempPattern() { return L"temp_login_data"; }
|
||||
inline std::wstring GetTempLoginDB() { return L"temp_login_data.db"; } ///< Temporary login database name
|
||||
inline std::wstring GetTempPattern() { return L"temp_login_data"; } ///< Temporary file pattern
|
||||
|
||||
inline std::string GetNetshShowProfiles() { return "netsh wlan show profiles"; }
|
||||
inline std::string GetNetshShowProfileKey() { return "netsh wlan show profile name=\""; }
|
||||
inline std::string GetNetshKeyClear() { return "\" key=clear"; }
|
||||
inline std::string GetNetshShowProfiles() { return "netsh wlan show profiles"; } ///< Netsh show profiles command
|
||||
inline std::string GetNetshShowProfileKey() { return "netsh wlan show profile name=\""; } ///< Netsh show profile command
|
||||
inline std::string GetNetshKeyClear() { return "\" key=clear"; } ///< Netsh key clear parameter
|
||||
|
||||
inline std::string GetWiFiProfileMarker() { return "All User Profile"; }
|
||||
inline std::string GetWiFiKeyContent() { return "Key Content"; }
|
||||
inline std::string GetWiFiProfileMarker() { return "All User Profile"; } ///< WiFi profile marker in output
|
||||
inline std::string GetWiFiKeyContent() { return "Key Content"; } ///< WiFi key content marker
|
||||
|
||||
inline std::string GetLoginQuery() { return "SELECT origin_url, username_value, password_value FROM logins"; }
|
||||
inline std::string GetLoginQuery() { return "SELECT origin_url, username_value, password_value FROM logins"; } ///< SQL query for login data
|
||||
|
||||
inline std::wstring GetStatusDecrypted() { return L"DECRYPTED"; }
|
||||
inline std::wstring GetStatusClearText() { return L"CLEAR_TEXT"; }
|
||||
inline std::wstring GetStatusEncrypted() { return L"ENCRYPTED"; }
|
||||
inline std::wstring GetStatusFailed() { return L"FAILED"; }
|
||||
inline std::wstring GetStatusExtracted() { return L"EXTRACTED"; }
|
||||
inline std::wstring GetStatusDecrypted() { return L"DECRYPTED"; } ///< Decryption successful status
|
||||
inline std::wstring GetStatusClearText() { return L"CLEAR_TEXT"; } ///< Clear text status
|
||||
inline std::wstring GetStatusEncrypted() { return L"ENCRYPTED"; } ///< Encrypted status
|
||||
inline std::wstring GetStatusFailed() { return L"FAILED"; } ///< Operation failed status
|
||||
inline std::wstring GetStatusExtracted() { return L"EXTRACTED"; } ///< Data extracted status
|
||||
}
|
||||
|
||||
// Dynamic API loading globals for driver operations
|
||||
extern ModuleHandle g_advapi32;
|
||||
extern SystemModuleHandle g_kernel32;
|
||||
extern decltype(&CreateServiceW) g_pCreateServiceW;
|
||||
extern decltype(&OpenServiceW) g_pOpenServiceW;
|
||||
extern decltype(&StartServiceW) g_pStartServiceW;
|
||||
extern decltype(&DeleteService) g_pDeleteService;
|
||||
extern decltype(&CreateFileW) g_pCreateFileW;
|
||||
extern decltype(&ControlService) g_pControlService;
|
||||
extern ModuleHandle g_advapi32; ///< advapi32.dll module handle
|
||||
extern SystemModuleHandle g_kernel32; ///< kernel32.dll module handle
|
||||
extern decltype(&CreateServiceW) g_pCreateServiceW; ///< CreateServiceW function pointer
|
||||
extern decltype(&OpenServiceW) g_pOpenServiceW; ///< OpenServiceW function pointer
|
||||
extern decltype(&StartServiceW) g_pStartServiceW; ///< StartServiceW function pointer
|
||||
extern decltype(&DeleteService) g_pDeleteService; ///< DeleteService function pointer
|
||||
extern decltype(&CreateFileW) g_pCreateFileW; ///< CreateFileW function pointer
|
||||
extern decltype(&ControlService) g_pControlService; ///< ControlService function pointer
|
||||
|
||||
// Service mode detection
|
||||
extern bool g_serviceMode;
|
||||
extern volatile bool g_interrupted;
|
||||
extern bool g_serviceMode; ///< Service mode flag
|
||||
extern volatile bool g_interrupted; ///< Interruption flag for graceful shutdown
|
||||
|
||||
// Core driver functions
|
||||
bool InitDynamicAPIs() noexcept;
|
||||
extern "C" const wchar_t* GetServiceNameRaw(); // ASM function
|
||||
std::wstring GetServiceName() noexcept; // C++ wrapper
|
||||
std::wstring GetDriverFileName() noexcept;
|
||||
void GenerateFakeActivity() noexcept;
|
||||
std::wstring GetSystemTempPath() noexcept;
|
||||
bool InitDynamicAPIs() noexcept; ///< Initialize dynamic API pointers
|
||||
extern "C" const wchar_t* GetServiceNameRaw(); ///< Get service name (ASM function)
|
||||
std::wstring GetServiceName() noexcept; ///< Get service name (C++ wrapper)
|
||||
std::wstring GetDriverFileName() noexcept; ///< Get driver filename
|
||||
void GenerateFakeActivity() noexcept; ///< Generate fake activity for stealth
|
||||
std::wstring GetSystemTempPath() noexcept; ///< Get system temp path
|
||||
|
||||
// Service utility functions
|
||||
bool IsServiceInstalled() noexcept;
|
||||
bool IsServiceRunning() noexcept;
|
||||
std::wstring GetCurrentExecutablePath() noexcept;
|
||||
bool IsServiceInstalled() noexcept; ///< Check if service is installed
|
||||
bool IsServiceRunning() noexcept; ///< Check if service is running
|
||||
std::wstring GetCurrentExecutablePath() noexcept; ///< Get current executable path
|
||||
|
||||
// Driver path helper with dynamic discovery and fallback mechanism
|
||||
// Searches for actual avc.inf_amd64_* directory in DriverStore FileRepository
|
||||
// Creates directory if needed, falls back to system32\drivers on failure
|
||||
|
||||
/**
|
||||
* @brief Get DriverStore path for driver operations
|
||||
* @return DriverStore path string
|
||||
* @note Searches for actual avc.inf_amd64_* directory in DriverStore FileRepository
|
||||
* @note Creates directory if needed, falls back to system32\drivers on failure
|
||||
*/
|
||||
inline std::wstring GetDriverStorePath() noexcept {
|
||||
wchar_t windowsDir[MAX_PATH];
|
||||
if (GetWindowsDirectoryW(windowsDir, MAX_PATH) == 0) {
|
||||
@@ -275,8 +339,11 @@ inline std::wstring GetDriverStorePath() noexcept {
|
||||
return targetPath;
|
||||
}
|
||||
|
||||
// Enhanced version that ensures directory exists before returning path
|
||||
// Returns empty string on critical failure, valid path on success
|
||||
/**
|
||||
* @brief Get DriverStore path with directory creation
|
||||
* @return DriverStore path string, empty on critical failure
|
||||
* @note Enhanced version that ensures directory exists before returning path
|
||||
*/
|
||||
inline std::wstring GetDriverStorePathSafe() noexcept {
|
||||
std::wstring driverPath = GetDriverStorePath();
|
||||
|
||||
@@ -296,22 +363,23 @@ inline std::wstring GetDriverStorePathSafe() noexcept {
|
||||
}
|
||||
|
||||
// KVC combined binary processing constants
|
||||
inline constexpr std::array<BYTE, 7> KVC_XOR_KEY = { 0xA0, 0xE2, 0x80, 0x8B, 0xE2, 0x80, 0x8C };
|
||||
inline constexpr wchar_t KVC_DATA_FILE[] = L"kvc.dat";
|
||||
inline constexpr wchar_t KVC_PASS_FILE[] = L"kvc_pass.exe";
|
||||
inline constexpr wchar_t KVC_CRYPT_FILE[] = L"kvc_crypt.dll";
|
||||
inline constexpr std::array<BYTE, 7> KVC_XOR_KEY = { 0xA0, 0xE2, 0x80, 0x8B, 0xE2, 0x80, 0x8C }; ///< XOR key for binary decryption
|
||||
inline constexpr wchar_t KVC_DATA_FILE[] = L"kvc.dat"; ///< Combined binary data file
|
||||
inline constexpr wchar_t KVC_PASS_FILE[] = L"kvc_pass.exe"; ///< Password extractor executable
|
||||
inline constexpr wchar_t KVC_CRYPT_FILE[] = L"kvc_crypt.dll"; ///< Cryptography DLL
|
||||
|
||||
// ============================================================================
|
||||
// CONSOLIDATED UTILITY NAMESPACES - String, Path, Time, Crypto, Privilege
|
||||
// Centralized implementations to eliminate code duplication across project
|
||||
// CONSOLIDATED UTILITY NAMESPACES
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* @brief String conversion and manipulation utilities
|
||||
*/
|
||||
namespace StringUtils {
|
||||
/**
|
||||
* @brief Converts UTF-8 encoded narrow string to wide string (UTF-16 LE)
|
||||
* @param str UTF-8 encoded std::string
|
||||
* @return std::wstring UTF-16 LE encoded wide string, empty on failure
|
||||
* @note Returns empty string if conversion fails or input is empty
|
||||
* @brief Convert UTF-8 string to wide string (UTF-16 LE)
|
||||
* @param str UTF-8 encoded string
|
||||
* @return UTF-16 LE encoded wide string, empty on failure
|
||||
*/
|
||||
inline std::wstring UTF8ToWide(const std::string& str) noexcept {
|
||||
if (str.empty()) return L"";
|
||||
@@ -327,10 +395,9 @@ namespace StringUtils {
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Converts wide string (UTF-16 LE) to UTF-8 encoded narrow string
|
||||
* @param wstr UTF-16 LE encoded std::wstring
|
||||
* @return std::string UTF-8 encoded narrow string, empty on failure
|
||||
* @note Returns empty string if conversion fails or input is empty
|
||||
* @brief Convert wide string (UTF-16 LE) to UTF-8 string
|
||||
* @param wstr UTF-16 LE encoded wide string
|
||||
* @return UTF-8 encoded string, empty on failure
|
||||
*/
|
||||
inline std::string WideToUTF8(const std::wstring& wstr) noexcept {
|
||||
if (wstr.empty()) return "";
|
||||
@@ -347,9 +414,9 @@ namespace StringUtils {
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Converts wide string to lowercase in-place using Windows locale
|
||||
* @param str Wide string to convert (modified in-place)
|
||||
* @return std::wstring& Reference to modified string for chaining
|
||||
* @brief Convert string to lowercase in-place
|
||||
* @param str String to convert (modified in-place)
|
||||
* @return Reference to modified string
|
||||
*/
|
||||
inline std::wstring& ToLowerCase(std::wstring& str) noexcept {
|
||||
std::transform(str.begin(), str.end(), str.begin(), ::towlower);
|
||||
@@ -357,9 +424,9 @@ namespace StringUtils {
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Creates lowercase copy of wide string
|
||||
* @param str Wide string to convert
|
||||
* @return std::wstring Lowercase copy of input string
|
||||
* @brief Create lowercase copy of string
|
||||
* @param str String to convert
|
||||
* @return Lowercase copy of input string
|
||||
*/
|
||||
inline std::wstring ToLowerCaseCopy(const std::wstring& str) noexcept {
|
||||
std::wstring result = str;
|
||||
@@ -368,12 +435,13 @@ namespace StringUtils {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Path and filesystem manipulation utilities
|
||||
*/
|
||||
namespace PathUtils {
|
||||
/**
|
||||
* @brief Retrieves user's Downloads folder path using modern Windows API
|
||||
* @return std::wstring Full path to Downloads folder (e.g., C:\Users\John\Downloads)
|
||||
* @note Uses SHGetKnownFolderPath with FOLDERID_Downloads (Windows 10/11)
|
||||
* @note Returns empty string on failure, caller must validate
|
||||
* @brief Get user's Downloads folder path
|
||||
* @return Full path to Downloads folder, empty on failure
|
||||
*/
|
||||
inline std::wstring GetDownloadsPath() noexcept {
|
||||
wchar_t* downloadsPath = nullptr;
|
||||
@@ -387,10 +455,8 @@ namespace PathUtils {
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Creates timestamped Secrets folder path in user Downloads directory
|
||||
* @return std::wstring Full path in format: Downloads\Secrets_DD.MM.YYYY
|
||||
* @note Uses current system date for folder naming
|
||||
* @note Returns empty string if Downloads path cannot be determined
|
||||
* @brief Get default secrets output path with timestamp
|
||||
* @return Path in format: Downloads\Secrets_DD.MM.YYYY
|
||||
*/
|
||||
inline std::wstring GetDefaultSecretsOutputPath() noexcept {
|
||||
std::wstring downloadsPath = GetDownloadsPath();
|
||||
@@ -411,10 +477,9 @@ namespace PathUtils {
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Ensures directory exists, creates if missing including parent directories
|
||||
* @brief Ensure directory exists, create if missing
|
||||
* @param path Directory path to validate/create
|
||||
* @return bool true if directory exists or was created successfully
|
||||
* @note Uses std::filesystem::create_directories for recursive creation
|
||||
* @return true if directory exists or was created
|
||||
*/
|
||||
inline bool EnsureDirectoryExists(const std::wstring& path) noexcept {
|
||||
if (path.empty()) return false;
|
||||
@@ -428,11 +493,9 @@ namespace PathUtils {
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Validates directory write access by creating and deleting test file
|
||||
* @brief Validate directory write access
|
||||
* @param path Directory path to test
|
||||
* @return bool true if directory is writable, false otherwise
|
||||
* @note Creates directory if it doesn't exist
|
||||
* @note Cleans up test file after validation
|
||||
* @return true if directory is writable
|
||||
*/
|
||||
inline bool ValidateDirectoryWritable(const std::wstring& path) noexcept {
|
||||
try {
|
||||
@@ -453,16 +516,14 @@ namespace PathUtils {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Time and date formatting utilities
|
||||
*/
|
||||
namespace TimeUtils {
|
||||
/**
|
||||
* @brief Generates formatted timestamp string with multiple output formats
|
||||
* @brief Get formatted timestamp string
|
||||
* @param format Format specifier: "date_only", "datetime_file", "datetime_display"
|
||||
* @return std::wstring Formatted timestamp in requested format
|
||||
*
|
||||
* Format options:
|
||||
* - "date_only": DD.MM.YYYY (for folder names in Secrets exports)
|
||||
* - "datetime_file": YYYY.MM.DD_HH.MM.SS (for backup filenames)
|
||||
* - "datetime_display": YYYY-MM-DD HH:MM:SS (for reports and logs)
|
||||
* @return Formatted timestamp string
|
||||
*/
|
||||
inline std::wstring GetFormattedTimestamp(const char* format = "datetime_file") noexcept {
|
||||
auto now = std::chrono::system_clock::now();
|
||||
@@ -486,12 +547,14 @@ namespace TimeUtils {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Cryptographic and encoding utilities
|
||||
*/
|
||||
namespace CryptoUtils {
|
||||
/**
|
||||
* @brief Decodes Base64-encoded string to binary data using Windows CryptAPI
|
||||
* @param encoded Base64-encoded std::string
|
||||
* @return std::vector<BYTE> Decoded binary data, empty on failure
|
||||
* @note Uses CryptStringToBinaryA for decoding
|
||||
* @brief Decode Base64 string to binary data
|
||||
* @param encoded Base64-encoded string
|
||||
* @return Decoded binary data, empty on failure
|
||||
*/
|
||||
inline std::vector<BYTE> Base64Decode(const std::string& encoded) noexcept {
|
||||
if (encoded.empty()) return {};
|
||||
@@ -513,11 +576,10 @@ namespace CryptoUtils {
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Converts byte vector to hexadecimal string representation
|
||||
* @brief Convert byte vector to hexadecimal string
|
||||
* @param bytes Binary data to convert
|
||||
* @param maxBytes Maximum bytes to convert (0 = unlimited)
|
||||
* @return std::string Hex string (e.g., "A0E2808B" for {0xA0, 0xE2, 0x80, 0x8B})
|
||||
* @note Appends "..." if truncated due to maxBytes limit
|
||||
* @return Hex string representation
|
||||
*/
|
||||
inline std::string BytesToHex(const std::vector<BYTE>& bytes, size_t maxBytes = 0) noexcept {
|
||||
if (bytes.empty()) return "";
|
||||
@@ -539,15 +601,14 @@ namespace CryptoUtils {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Windows privilege manipulation utilities
|
||||
*/
|
||||
namespace PrivilegeUtils {
|
||||
/**
|
||||
* @brief Enables specified privilege in current process token
|
||||
* @param privilege Privilege name constant (e.g., SE_BACKUP_NAME, SE_DEBUG_NAME)
|
||||
* @return bool true if privilege enabled successfully, false on failure
|
||||
*
|
||||
* @note Automatically opens and closes process token
|
||||
* @note Verifies privilege enablement via ERROR_NOT_ALL_ASSIGNED check
|
||||
* @note Required for registry backup/restore, process manipulation, etc.
|
||||
* @brief Enable specified privilege in current process token
|
||||
* @param privilege Privilege name constant
|
||||
* @return true if privilege enabled successfully
|
||||
*/
|
||||
inline bool EnablePrivilege(LPCWSTR privilege) noexcept {
|
||||
HANDLE hToken;
|
||||
|
||||
Reference in New Issue
Block a user