Initial native C++ DUO-RDP release source and documentation

This commit is contained in:
SoGi committed 2026-10-21 13:38:44 +02:00
commit 65b2145791
42 files changed
+5506

No files matched your search

+457
View File
@@ -0,0 +1,457 @@
#ifndef UNICODE
#define UNICODE
#endif
#ifndef _UNICODE
#define _UNICODE
#endif
#include <windows.h>
#include <winsvc.h>
#include <sddl.h>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <string>
#include <string_view>
#include <vector>
namespace {
constexpr wchar_t kServiceName[] = L"DuoRdpAuthService";
constexpr wchar_t kPipeName[] = L"\\\\.\\pipe\\duordp-auth-pipe";
constexpr wchar_t kProviderClsid[] = L"{8F04B2A1-7C4C-4E47-9D26-9B8E744B2501}";
constexpr wchar_t kFilterClsid[] = L"{D6E4A825-8E89-49D8-A5B2-F30B7E681A39}";
std::wstring module_directory() {
std::vector<wchar_t> buffer(32768U, L'\0');
const DWORD length = GetModuleFileNameW(nullptr, buffer.data(), static_cast<DWORD>(buffer.size()));
if (length == 0 || length >= buffer.size()) return {};
std::wstring path(buffer.data(), length);
const size_t slash = path.find_last_of(L"\\/");
return slash == std::wstring::npos ? std::wstring{} : path.substr(0, slash);
}
std::wstring program_files_directory() {
wchar_t buffer[MAX_PATH]{};
const DWORD length = GetEnvironmentVariableW(L"ProgramFiles", buffer, ARRAYSIZE(buffer));
return length > 0 && length < ARRAYSIZE(buffer) ? std::wstring(buffer) : L"C:\\Program Files";
}
std::wstring program_data_directory() {
wchar_t buffer[MAX_PATH]{};
const DWORD length = GetEnvironmentVariableW(L"ProgramData", buffer, ARRAYSIZE(buffer));
return length > 0 && length < ARRAYSIZE(buffer) ? std::wstring(buffer) : L"C:\\ProgramData";
}
void ensure_directory(const std::wstring& directory) {
std::wstring current;
size_t start = 0;
if (directory.size() >= 2 && directory[1] == L':') {
current.assign(directory, 0, 2);
start = 2;
if (start < directory.size() && (directory[start] == L'\\' || directory[start] == L'/')) ++start;
}
while (start < directory.size()) {
const size_t end = directory.find_first_of(L"\\/", start);
const std::wstring part = directory.substr(start, end == std::wstring::npos ? std::wstring::npos : end - start);
if (!part.empty()) {
if (current.empty()) current = part;
else if (current.size() == 2 && current[1] == L':') current += L"\\" + part;
else current += L"\\" + part;
if (current.size() != 2 || current[1] != L':') CreateDirectoryW(current.c_str(), nullptr);
}
if (end == std::wstring::npos) break;
start = end + 1;
}
}
std::wstring timestamp() {
SYSTEMTIME now{};
GetLocalTime(&now);
wchar_t value[32]{};
std::swprintf(value, ARRAYSIZE(value), L"%04u%02u%02u-%02u%02u%02u", now.wYear, now.wMonth, now.wDay, now.wHour, now.wMinute, now.wSecond);
return value;
}
bool is_elevated() {
HANDLE token = nullptr;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) return false;
TOKEN_ELEVATION elevation{};
DWORD read = 0;
const bool result = GetTokenInformation(token, TokenElevation, &elevation, sizeof(elevation), &read) != FALSE && elevation.TokenIsElevated != 0;
CloseHandle(token);
return result;
}
bool exists(const std::wstring& path) {
return GetFileAttributesW(path.c_str()) != INVALID_FILE_ATTRIBUTES;
}
bool config_is_safe_to_migrate(const std::wstring& configPath, std::wstring& error) {
if (!exists(configPath)) return true;
FILE* file = _wfopen(configPath.c_str(), L"rb");
if (!file) {
error = L"cannot read existing configuration";
return false;
}
char prefix[64]{};
const size_t count = std::fread(prefix, 1, sizeof(prefix) - 1U, file);
std::fclose(file);
std::string head(prefix, count);
if (head.size() >= 3 && static_cast<unsigned char>(head[0]) == 0xefU && static_cast<unsigned char>(head[1]) == 0xbbU && static_cast<unsigned char>(head[2]) == 0xbfU) head.erase(0, 3);
if (head.rfind("DUORDP_CONFIG_V1:ENCv1:", 0) == 0) {
error = L"existing ENCv1 configuration must be migrated with the legacy DUO-RDP admin before installing the native release";
return false;
}
return true;
}
bool restrict_config_acl(const std::wstring& configPath, std::wstring& error) {
PSECURITY_DESCRIPTOR descriptor = nullptr;
if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(L"D:P(A;;FA;;;SY)(A;;FA;;;BA)", SDDL_REVISION_1, &descriptor, nullptr)) {
error = L"cannot create restrictive config ACL";
return false;
}
const BOOL applied = SetFileSecurityW(configPath.c_str(), DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION, descriptor);
LocalFree(descriptor);
if (!applied) {
error = L"cannot protect config ACL";
return false;
}
return true;
}
bool copy_file_with_backup(const std::wstring& source, const std::wstring& destination, const std::wstring& backupDirectory, std::wstring& error) {
if (!exists(source)) {
error = L"payload missing: " + source;
return false;
}
if (exists(destination)) {
ensure_directory(backupDirectory);
const size_t slash = destination.find_last_of(L"\\/");
const std::wstring name = slash == std::wstring::npos ? destination : destination.substr(slash + 1);
if (!CopyFileW(destination.c_str(), (backupDirectory + L"\\" + name).c_str(), TRUE)) {
error = L"cannot back up existing file: " + destination;
return false;
}
}
if (!CopyFileW(source.c_str(), destination.c_str(), FALSE)) {
error = L"cannot copy payload: " + source;
return false;
}
return true;
}
bool set_default_reg_value(HKEY root, const std::wstring& key, const wchar_t* value, std::wstring& error) {
HKEY handle = nullptr;
if (RegCreateKeyExW(root, key.c_str(), 0, nullptr, 0, KEY_SET_VALUE, nullptr, &handle, nullptr) != ERROR_SUCCESS) {
error = L"registry key creation failed: " + key;
return false;
}
const DWORD bytes = static_cast<DWORD>((std::wcslen(value) + 1U) * sizeof(wchar_t));
const LONG result = RegSetValueExW(handle, nullptr, 0, REG_SZ, reinterpret_cast<const BYTE*>(value), bytes);
RegCloseKey(handle);
if (result != ERROR_SUCCESS) {
error = L"registry value write failed: " + key;
return false;
}
return true;
}
void delete_reg_tree(const std::wstring& key) {
RegDeleteTreeW(HKEY_LOCAL_MACHINE, key.c_str());
}
bool invoke_registration(const std::wstring& dllPath, bool registerServer, std::wstring& error) {
HMODULE module = LoadLibraryExW(dllPath.c_str(), nullptr, LOAD_WITH_ALTERED_SEARCH_PATH);
if (!module) {
error = L"Credential Provider DLL cannot be loaded, error=" + std::to_wstring(GetLastError());
return false;
}
using RegistrationFn = HRESULT(STDAPICALLTYPE*)();
const char* functionName = registerServer ? "DllRegisterServer" : "DllUnregisterServer";
const FARPROC rawRegistration = GetProcAddress(module, functionName);
RegistrationFn registration = nullptr;
static_assert(sizeof(rawRegistration) == sizeof(registration));
std::memcpy(&registration, &rawRegistration, sizeof(registration));
if (!registration) {
FreeLibrary(module);
error = L"Credential Provider export missing";
return false;
}
const HRESULT result = registration();
FreeLibrary(module);
if (FAILED(result)) {
error = L"Credential Provider registration failed, HRESULT=" + std::to_wstring(result);
return false;
}
return true;
}
bool validate_dll_load(const std::wstring& dllPath, std::wstring& error) {
HMODULE module = LoadLibraryExW(dllPath.c_str(), nullptr, LOAD_WITH_ALTERED_SEARCH_PATH);
if (!module) {
error = L"Credential Provider DLL cannot be loaded, error=" + std::to_wstring(GetLastError());
return false;
}
FreeLibrary(module);
return true;
}
void stop_delete_service() {
SC_HANDLE manager = OpenSCManagerW(nullptr, nullptr, SC_MANAGER_CONNECT);
if (!manager) return;
SC_HANDLE service = OpenServiceW(manager, kServiceName, SERVICE_STOP | SERVICE_QUERY_STATUS | DELETE);
if (!service) {
CloseServiceHandle(manager);
return;
}
SERVICE_STATUS status{};
ControlService(service, SERVICE_CONTROL_STOP, &status);
for (int i = 0; i < 50; ++i) {
SERVICE_STATUS_PROCESS process{};
DWORD needed = 0;
if (!QueryServiceStatusEx(service, SC_STATUS_PROCESS_INFO, reinterpret_cast<BYTE*>(&process), sizeof(process), &needed) || process.dwCurrentState == SERVICE_STOPPED) break;
Sleep(100);
}
DeleteService(service);
CloseServiceHandle(service);
CloseServiceHandle(manager);
}
bool create_start_service(const std::wstring& executable, std::wstring& error) {
stop_delete_service();
SC_HANDLE manager = OpenSCManagerW(nullptr, nullptr, SC_MANAGER_CREATE_SERVICE);
if (!manager) {
error = L"cannot open Service Control Manager";
return false;
}
const std::wstring quoted = L"\"" + executable + L"\"";
SC_HANDLE service = CreateServiceW(manager, kServiceName, L"DUO-RDP native 2FA service", SERVICE_ALL_ACCESS,
SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, quoted.c_str(), nullptr, nullptr, nullptr,
L"LocalSystem", nullptr);
if (!service) {
error = L"cannot create native service, error=" + std::to_wstring(GetLastError());
CloseServiceHandle(manager);
return false;
}
SERVICE_FAILURE_ACTIONSW failure{};
SC_ACTION actions[3]{};
for (SC_ACTION& action : actions) {
action.Type = SC_ACTION_RESTART;
action.Delay = 5000;
}
failure.dwResetPeriod = 86400;
failure.cActions = ARRAYSIZE(actions);
failure.lpsaActions = actions;
ChangeServiceConfig2W(service, SERVICE_CONFIG_FAILURE_ACTIONS, &failure);
if (!StartServiceW(service, 0, nullptr)) {
error = L"cannot start native service, error=" + std::to_wstring(GetLastError());
CloseServiceHandle(service);
CloseServiceHandle(manager);
return false;
}
CloseServiceHandle(service);
CloseServiceHandle(manager);
return true;
}
bool pipe_health(std::wstring& error) {
for (int attempt = 0; attempt < 60; ++attempt) {
if (!WaitNamedPipeW(kPipeName, 250)) {
Sleep(100);
continue;
}
HANDLE pipe = CreateFileW(kPipeName, GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, nullptr);
if (pipe == INVALID_HANDLE_VALUE) continue;
static constexpr char request[] = "{\"action\":\"GetPolicy\",\"username\":\"installer-health\",\"groups\":[]}\n";
DWORD written = 0;
char response[4096]{};
DWORD read = 0;
const bool ok = WriteFile(pipe, request, sizeof(request) - 1U, &written, nullptr) != FALSE
&& ReadFile(pipe, response, sizeof(response) - 1U, &read, nullptr) != FALSE
&& read > 0;
CloseHandle(pipe);
const std::string body(response, read);
if (ok && body.find("\"required\"") != std::string::npos && body.find("\"status\":\"error\"") == std::string::npos) return true;
Sleep(100);
}
error = L"native service did not pass the named-pipe health check";
return false;
}
int install(const std::wstring& payloadDirectory) {
if (!is_elevated()) {
std::fputs("Installer requires an elevated administrator token.\n", stderr);
return 2;
}
const std::wstring installDirectory = program_files_directory() + L"\\DuoRdp";
const std::wstring backupDirectory = installDirectory + L"\\backup\\" + timestamp();
const std::wstring serviceSource = payloadDirectory + L"\\DuoRdpAuthService.exe";
const std::wstring adminSource = payloadDirectory + L"\\DuoRdpAdmin.exe";
const std::wstring providerSource = payloadDirectory + L"\\DuoRdpCredentialProvider.dll";
const std::wstring uninstallerSource = payloadDirectory + L"\\DUOUnIstall.exe";
std::wstring error;
if (!exists(serviceSource) || !exists(adminSource) || !exists(providerSource) || !exists(uninstallerSource)) {
std::fputs("Payload must contain DuoRdpAuthService.exe, DuoRdpAdmin.exe, DuoRdpCredentialProvider.dll and DUOUnIstall.exe.\n", stderr);
return 2;
}
if (!config_is_safe_to_migrate(installDirectory + L"\\config.json", error)) {
std::fwprintf(stderr, L"Install blocked before service/filter changes: %s\n", error.c_str());
return 1;
}
if (!validate_dll_load(providerSource, error)) {
std::fwprintf(stderr, L"Preflight failed: %s\n", error.c_str());
return 1;
}
ensure_directory(installDirectory);
if (!copy_file_with_backup(serviceSource, installDirectory + L"\\DuoRdpAuthService.exe", backupDirectory, error)
|| !copy_file_with_backup(adminSource, installDirectory + L"\\DuoRdpAdmin.exe", backupDirectory, error)
|| !copy_file_with_backup(providerSource, installDirectory + L"\\DuoRdpCredentialProvider.dll", backupDirectory, error)
|| !copy_file_with_backup(uninstallerSource, installDirectory + L"\\DUOUnIstall.exe", backupDirectory, error)) {
std::fwprintf(stderr, L"Install failed: %s\n", error.c_str());
return 1;
}
const std::wstring installedService = installDirectory + L"\\DuoRdpAuthService.exe";
const std::wstring installedProvider = installDirectory + L"\\DuoRdpCredentialProvider.dll";
if (!exists(installDirectory + L"\\config.json")) {
std::wstring command = L"\"" + installedService + L"\" --admin init";
STARTUPINFOW startup{};
startup.cb = sizeof(startup);
PROCESS_INFORMATION process{};
std::vector<wchar_t> mutableCommand(command.begin(), command.end());
mutableCommand.push_back(L'\0');
if (!CreateProcessW(nullptr, mutableCommand.data(), nullptr, nullptr, FALSE, 0, nullptr, installDirectory.c_str(), &startup, &process)) {
std::fputs("Install failed: cannot initialize native configuration.\n", stderr);
return 1;
}
WaitForSingleObject(process.hProcess, INFINITE);
DWORD exitCode = 1;
GetExitCodeProcess(process.hProcess, &exitCode);
CloseHandle(process.hThread);
CloseHandle(process.hProcess);
if (exitCode != 0) return 1;
}
if (!restrict_config_acl(installDirectory + L"\\config.json", error)) {
std::fwprintf(stderr, L"Install failed before service/filter changes: %s\n", error.c_str());
return 1;
}
if (!invoke_registration(installedProvider, true, error)
|| !set_default_reg_value(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Authentication\\Credential Providers\\" + std::wstring(kProviderClsid), L"DuoRdp Credential Provider", error)
|| !create_start_service(installedService, error)
|| !pipe_health(error)) {
std::fwprintf(stderr, L"Install failed before filter activation: %s\n", error.c_str());
return 1;
}
// The filter can hide the stock password provider. It is enabled last,
// after the service and pipe have proved healthy.
if (!set_default_reg_value(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Authentication\\Credential Provider Filters\\" + std::wstring(kFilterClsid), L"DuoRdp Credential Filter", error)) {
std::fwprintf(stderr, L"Install failed while enabling filter: %s\n", error.c_str());
return 1;
}
std::wprintf(L"DUO-RDP native C++ installation complete: %s\n", installDirectory.c_str());
return 0;
}
int uninstall(bool purgeData) {
if (!is_elevated()) {
std::fputs("Uninstaller requires an elevated administrator token.\n", stderr);
return 2;
}
const std::wstring installDirectory = program_files_directory() + L"\\DuoRdp";
const std::wstring backupDirectory = installDirectory + L"\\backup\\uninstall-" + timestamp();
const std::wstring provider = installDirectory + L"\\DuoRdpCredentialProvider.dll";
// Recovery ordering: make the stock password provider visible first.
delete_reg_tree(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Authentication\\Credential Provider Filters\\" + std::wstring(kFilterClsid));
delete_reg_tree(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Authentication\\Credential Providers\\" + std::wstring(kProviderClsid));
stop_delete_service();
std::wstring ignored;
if (exists(provider)) invoke_registration(provider, false, ignored);
for (const wchar_t* name : {L"DuoRdpAuthService.exe", L"DuoRdpAdmin.exe", L"DuoRdpCredentialProvider.dll"}) {
const std::wstring source = installDirectory + L"\\" + name;
if (!exists(source)) continue;
ensure_directory(backupDirectory);
CopyFileW(source.c_str(), (backupDirectory + L"\\" + name).c_str(), TRUE);
DeleteFileW(source.c_str());
}
if (purgeData) {
DeleteFileW((installDirectory + L"\\config.json").c_str());
DeleteFileW((installDirectory + L"\\logs.txt").c_str());
const std::wstring logDirectory = program_data_directory() + L"\\DuoRdp";
DeleteFileW((logDirectory + L"\\logs.txt").c_str());
RemoveDirectoryW(logDirectory.c_str());
}
std::puts("DUO-RDP native uninstall complete. Config and logs were kept unless --purge-data was supplied.");
return 0;
}
void usage() {
std::puts("DuoRdpInstaller.exe --install [--payload <directory>] | --uninstall [--purge-data] | --self-test");
}
bool run_self_test() {
const bool constantsOk = std::wstring_view(kPipeName) == L"\\\\.\\pipe\\duordp-auth-pipe" && std::wstring_view(kServiceName) == L"DuoRdpAuthService";
wchar_t temporary[MAX_PATH]{};
if (!GetTempPathW(ARRAYSIZE(temporary), temporary)) return false;
const std::wstring directory = std::wstring(temporary) + L"DuoRdpNativeInstallerSelfTest";
ensure_directory(directory);
const std::wstring config = directory + L"\\config.json";
{
FILE* file = _wfopen(config.c_str(), L"wb");
if (!file) return false;
static constexpr char legacy[] = "DUORDP_CONFIG_V1:ENCv1:test";
std::fwrite(legacy, 1, sizeof(legacy) - 1U, file);
std::fclose(file);
}
std::wstring migrationError;
const bool legacyBlocked = !config_is_safe_to_migrate(config, migrationError) && !migrationError.empty();
{
FILE* file = _wfopen(config.c_str(), L"wb");
if (!file) return false;
static constexpr char plain[] = "{\"version\":1}";
std::fwrite(plain, 1, sizeof(plain) - 1U, file);
std::fclose(file);
}
migrationError.clear();
const bool plainAccepted = config_is_safe_to_migrate(config, migrationError);
DeleteFileW(config.c_str());
RemoveDirectoryW(directory.c_str());
return constantsOk && legacyBlocked && plainAccepted;
}
} // namespace
int wmain(int argc, wchar_t** argv) {
#ifdef DUO_RDP_UNINSTALL_DEFAULT
if (argc == 1) return uninstall(false);
#endif
if (argc == 2 && std::wstring_view(argv[1]) == L"--self-test") {
const bool passed = run_self_test();
std::puts(passed ? "INSTALLER SELFTEST PASS" : "INSTALLER SELFTEST FAIL");
return passed ? 0 : 1;
}
if (argc < 2) {
usage();
return 2;
}
const std::wstring_view command = argv[1];
if (command == L"--install") {
std::wstring payload = module_directory() + L"\\payload";
if (argc == 4 && std::wstring_view(argv[2]) == L"--payload") payload = argv[3];
else if (argc != 2) {
usage();
return 2;
}
return install(payload);
}
if (command == L"--uninstall") {
if (argc > 3 || (argc == 3 && std::wstring_view(argv[2]) != L"--purge-data")) {
usage();
return 2;
}
return uninstall(argc == 3);
}
usage();
return 2;
}