From d05253ba840d3071bf4cbb51d272cac09ea8b325 Mon Sep 17 00:00:00 2001 From: SoGi Date: Thu, 22 Oct 2026 16:31:51 +0200 Subject: [PATCH] Release native admin final 2.1.0 --- CHANGELOG.md | 8 + CMakeLists.txt | 9 +- README.md | 4 +- artifacts/README.md | 4 +- artifacts/SHA256SUMS.txt | 6 + docs/CONFIGURATION.md | 41 +- docs/INSTALL.md | 2 +- docs/RELEASE.md | 6 +- native/cpp/DuoRdpAdmin.cpp | 753 +++++++++++++++++++++++-- native/cpp/DuoRdpAuthService.cpp | 904 ++++++++++++++++++++++++++++++- native/cpp/DuoRdpInstaller.cpp | 5 + native/cpp/README.md | 94 +++- 12 files changed, 1723 insertions(+), 113 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 94b22ff..378dd37 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 2.1.0-native-admin-final - 2026-10-22 + +- Возвращена быстрая нативная Win32-админка - без HTML, Edge и localhost. +- Первый запуск создаёт login и PBKDF2 password verifier в machine-DPAPI конфиге; следующие запуски требуют эту пару. +- Админка управляет пользователями, группами, Telegram и Google Authenticator/TOTP, показывает значения после авторизации и выполняет реальный Send test/Verify. +- Исправлены выбор пользователя после Save и конфликты legacy numeric/login ключей. +- Service сохраняет timestamped DPAPI backup перед заменой конфигурации. + ## 2.0.0-otp-session-fix - 2026-10-21 - Полная native C++ ветка: service, admin, installer/uninstaller и Credential Provider. diff --git a/CMakeLists.txt b/CMakeLists.txt index c05d2bc..8eb22ba 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -16,16 +16,17 @@ endif() add_executable(DuoRdpAuthService native/cpp/DuoRdpAuthService.cpp ) -target_link_libraries(DuoRdpAuthService PRIVATE advapi32 bcrypt crypt32 winhttp user32) +target_link_libraries(DuoRdpAuthService PRIVATE advapi32 bcrypt crypt32 winhttp user32 netapi32) if(MSVC) target_compile_options(DuoRdpAuthService PRIVATE /MT) else() target_link_options(DuoRdpAuthService PRIVATE -static -static-libgcc -static-libstdc++ -municode) endif() -add_executable(DuoRdpAdmin +add_executable(DuoRdpAdmin WIN32 native/cpp/DuoRdpAdmin.cpp ) +target_link_libraries(DuoRdpAdmin PRIVATE advapi32 bcrypt comctl32 credui gdi32 shell32) if(MSVC) target_compile_options(DuoRdpAdmin PRIVATE /MT) else() @@ -35,7 +36,7 @@ endif() add_executable(DuoRdpInstaller native/cpp/DuoRdpInstaller.cpp ) -target_link_libraries(DuoRdpInstaller PRIVATE advapi32) +target_link_libraries(DuoRdpInstaller PRIVATE advapi32 shell32) if(MSVC) target_compile_options(DuoRdpInstaller PRIVATE /MT) else() @@ -46,7 +47,7 @@ add_executable(DUOUnIstall native/cpp/DuoRdpInstaller.cpp ) target_compile_definitions(DUOUnIstall PRIVATE DUO_RDP_UNINSTALL_DEFAULT=1) -target_link_libraries(DUOUnIstall PRIVATE advapi32) +target_link_libraries(DUOUnIstall PRIVATE advapi32 shell32) if(MSVC) target_compile_options(DUOUnIstall PRIVATE /MT) else() diff --git a/README.md b/README.md index c39ec6b..e83738a 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ - `DuoRdpAuthService.exe` - Windows service, Telegram/TOTP, DPAPI-конфиг и named-pipe API; - `DuoRdpCredentialProvider.dll` - Credential Provider и Filter для экрана входа Windows; -- `DuoRdpAdmin.exe` - безопасный CLI-админ поверх service core; +- `DuoRdpAdmin.exe` - быстрая нативная Win32-админка поверх service core; - `DuoRdpInstaller.exe` и `DUOUnIstall.exe` - установка, backup и восстановление. Главная исправленная механика: Telegram-код создаётся только явной кнопкой в плитке. Каждый resend заменяет код только своей плитки (`username + challenge_id`), предыдущий сразу недействителен. Нажатие `Login` больше не отправляет код само. @@ -16,7 +16,7 @@ 1. Собрать или скачать release asset `DuoRdpNative-otp-session-fix-20261021-1321.zip`. 2. Проверить хеши из [artifacts/SHA256SUMS.txt](artifacts/SHA256SUMS.txt). 3. Прочитать [установку](docs/INSTALL.md) и иметь физическую/console-сессию до активации Filter. -4. Настроить пользователя и политику через [native CLI](docs/CONFIGURATION.md). +4. Настроить пользователя и политику через [native админку](docs/CONFIGURATION.md). 5. Прогнать [приёмку](docs/TESTING.md), включая два подряд resend. ## Документация diff --git a/artifacts/README.md b/artifacts/README.md index 218e487..b9518c3 100644 --- a/artifacts/README.md +++ b/artifacts/README.md @@ -4,7 +4,9 @@ Git хранит исходники и manifests. Готовые EXE/DLL/ZIP п Текущий проверенный package: -- `DuoRdpNative-otp-session-fix-20261021-1321.zip` +- `DuoRdpNative-v2.1.0-native-admin-final-20261022-final.zip` + +Предыдущий OTP-session fix сохранён для rollback-анализа, но для новых установок используйте финальный native-admin release. Его archive hash и hashes payload перечислены в [SHA256SUMS.txt](SHA256SUMS.txt). Перед установкой сверяйте их через `Get-FileHash -Algorithm SHA256`. diff --git a/artifacts/SHA256SUMS.txt b/artifacts/SHA256SUMS.txt index a0c7a35..d44e1f3 100644 --- a/artifacts/SHA256SUMS.txt +++ b/artifacts/SHA256SUMS.txt @@ -3,3 +3,9 @@ a8ea285423978c39a6d231c6adbdd016f448bf7d8f40c14bf01b31a8a3e91227 DuoRdpNative-otp-session-fix-20261021-1321.zip 3186afbe6a11d218829a976a95edecbc17c3b744a74bdbb5d079220e16c96f5d payload/DuoRdpAuthService.exe 1ecb8ed193352eac41263922261f363ced3d6974ba1fd327b52a9bd28f4dba31 payload/DuoRdpCredentialProvider.dll + +# DUO-RDP native admin final - 2026-10-22 +6ae002d6d133c3388d7424ce040cd0911cb29c180be765f665b87f97c1827681 DuoRdpNative-v2.1.0-native-admin-final-20261022-final.zip +e337ba4a7ce8039f363b2aa6b99c468a577e8ca7962f97650ad54625268e1607 payload/DuoRdpAuthService.exe +b5b3502512159737e9c7ffa52677ef7aebda8412cab3a344a3654deff6401dad payload/DuoRdpAdmin.exe +1ecb8ed193352eac41263922261f363ced3d6974ba1fd327b52a9bd28f4dba31 payload/DuoRdpCredentialProvider.dll diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 6dcadbe..9d67a1b 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -1,6 +1,6 @@ # Настройка 2FA -Рабочий конфиг создаётся и перезаписывается только native CLI в machine-DPAPI формате. `config.example.json` - схема для аудита, не файл для ручной подстановки секретов. +Рабочий конфиг читает и сохраняет только service в machine-DPAPI формате. `config.example.json` - схема для аудита, не файл для ручной подстановки секретов. Конфиг ищется в таком порядке: @@ -8,38 +8,11 @@ 2. `config.json` рядом с service EXE; 3. `%ProgramFiles%\DuoRdp\config.json`. -## CLI +## Нативная админка -`DuoRdpAdmin.exe` передаёт аргументы `DuoRdpAuthService.exe --admin` и ждёт его exit code. +Запустите `%ProgramFiles%\DuoRdp\DuoRdpAdmin.exe` от локального Administrator. На первом запуске укажите login и одинаковый пароль дважды. Далее используйте эту пару для входа. Login и PBKDF2 verifier сохраняются в `config.json` внутри machine-DPAPI; plaintext-пароль не хранится. -```text -DuoRdpAdmin.exe init [--force] -DuoRdpAdmin.exe show -DuoRdpAdmin.exe set-global -DuoRdpAdmin.exe upsert-user [--chat-id ] [--group-id ] - [--groups group1,group2] [--totp ] [--token-stdin] [--verify] -DuoRdpAdmin.exe remove-user -``` - -`--token-stdin` читает Telegram bot token из standard input. Не передавайте token в command line, Git, скриншоты или shell history. - -## Первый пользователь - -В elevated terminal: - -```text -"%ProgramFiles%\DuoRdp\DuoRdpAdmin.exe" show -"%ProgramFiles%\DuoRdp\DuoRdpAdmin.exe" upsert-user DOMAIN\alice --chat-id --groups "DOMAIN\Rdp2faUsers" --token-stdin --verify -"%ProgramFiles%\DuoRdp\DuoRdpAdmin.exe" set-global enabled true -``` - -После запуска второй команды введите bot token через stdin и завершите ввод. `--verify` ставит verified только после того, как оператор проверил доставку и назначение метода; не включайте global 2FA раньше такой проверки. - -Для TOTP добавьте base32 secret вместо или вместе с Telegram: - -```text -"%ProgramFiles%\DuoRdp\DuoRdpAdmin.exe" upsert-user DOMAIN\alice --totp --groups "DOMAIN\Rdp2faUsers" --verify -``` +В редакторе выберите или добавьте пользователя, заполните Telegram target/token и/или Google Authenticator secret. `Generate TOTP` создаёт новый Base32 ключ. Нажмите `Apply row`, затем `Save settings`; `Send test` отправляет реальный Telegram код, а `Verify` принимает последний Telegram или текущий TOTP. Изменение token, target, TOTP key или groups снимает Verified до новой проверки. ## Политика @@ -49,11 +22,7 @@ DuoRdpAdmin.exe remove-user - `global.admin_2fa_enabled=true` и пользователь состоит в administrator group; - одна из его Windows groups есть в `--groups` у настроенного пользователя. -Для group-scoped rollout настройте `--groups` и оставьте `require_for_all_users=false`. Для full rollout сначала протестируйте отдельную console-сессию, затем включите: - -```text -"%ProgramFiles%\DuoRdp\DuoRdpAdmin.exe" set-global require_for_all_users true -``` +Для group-scoped rollout заполните groups и оставьте `require_for_all_users=false`. Для full rollout сначала протестируйте отдельную console-сессию, затем включите этот флаг в админке. Поддерживаемые global keys: `enabled`, `admin_2fa_enabled`, `require_for_all_users`, `fail_closed`, `otp_length`, `otp_ttl_sec`, `max_attempts`, `resend_cooldown_sec`. diff --git a/docs/INSTALL.md b/docs/INSTALL.md index b4d69d0..87340c9 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -43,7 +43,7 @@ Installer: ```text sc query DuoRdpAuthService -"%ProgramFiles%\DuoRdp\DuoRdpAdmin.exe" show +"%ProgramFiles%\DuoRdp\DuoRdpAdmin.exe" ``` Затем выполните [настройку](CONFIGURATION.md) и [ручную приёмку](TESTING.md) до закрытия console-сессии. diff --git a/docs/RELEASE.md b/docs/RELEASE.md index 22d9738..026df5c 100644 --- a/docs/RELEASE.md +++ b/docs/RELEASE.md @@ -1,6 +1,8 @@ -# Release: 2.0.0-otp-session-fix (2026-10-21) +# Release: 2.1.0-native-admin-final (2026-10-22) -Canonical binary asset: +Canonical binary asset is published with the `v2.1.0-native-admin-final-20261022` tag. Its SHA-256 is generated during publication. + +Previous 2.0.0 asset: ```text DuoRdpNative-otp-session-fix-20261021-1321.zip diff --git a/native/cpp/DuoRdpAdmin.cpp b/native/cpp/DuoRdpAdmin.cpp index ddec49c..1d202f1 100644 --- a/native/cpp/DuoRdpAdmin.cpp +++ b/native/cpp/DuoRdpAdmin.cpp @@ -6,63 +6,730 @@ #endif #include +#include +#include +#include +#include -#include +#include +#include +#include +#include #include +#include +#include #include +#include "mini_json.hpp" + +#ifdef _MSC_VER +#pragma comment(lib, "advapi32.lib") +#pragma comment(lib, "bcrypt.lib") +#pragma comment(lib, "comctl32.lib") +#pragma comment(lib, "credui.lib") +#pragma comment(lib, "shell32.lib") +#endif + namespace { -std::wstring module_directory() { - std::vector buffer(32768U, L'\0'); - const DWORD length = GetModuleFileNameW(nullptr, buffer.data(), static_cast(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); +constexpr wchar_t kClass[] = L"DuoRdpNativeAdminWindow"; +constexpr wchar_t kTitle[] = L"DUO-RDP - 2FA settings"; +constexpr wchar_t kPipe[] = L"\\\\.\\pipe\\duordp-auth-pipe"; + +enum ControlId : int { + IdEnabled = 100, IdAdmins, IdAll, IdFailClosed, + IdOtpLength, IdOtpTtl, IdAttempts, IdCooldown, + IdDefaultToken, IdDefaultUser, IdDefaultGroup, + IdUsers, IdLogin, IdGroups, IdToken, IdUser, IdGroup, IdTotp, IdCode, + IdNew, IdApply, IdDelete, IdGenerate, IdSave, IdReload, IdSend, IdVerify, IdStatus, + LabelLength = -100, LabelTtl = -101, LabelAttempts = -102, LabelCooldown = -103, + LabelDefaultToken = -104, LabelDefaultUser = -105, LabelDefaultGroup = -106, LabelDefaultInfo = -107, + LabelLogin = -108, LabelGroups = -109, LabelToken = -110, LabelUser = -111, + LabelGroup = -112, LabelTotp = -113, +}; + +struct UserRow final { + int id = 0; + std::wstring login, groups, token, user, group, totp; + bool verified = false; +}; + +struct State final { + HINSTANCE instance = nullptr; + HWND window = nullptr, users = nullptr, status = nullptr; + HWND enabled = nullptr, admins = nullptr, all = nullptr, failClosed = nullptr; + HWND otpLength = nullptr, otpTtl = nullptr, attempts = nullptr, cooldown = nullptr; + HWND defaultToken = nullptr, defaultUser = nullptr, defaultGroup = nullptr; + HWND login = nullptr, groups = nullptr, token = nullptr, user = nullptr, group = nullptr, totp = nullptr, code = nullptr; + std::vector rows; + duo::Json config = duo::Json::Object{}; + std::string adminSession; + int selected = -1; + bool changingList = false; +}; + +std::wstring from_utf8(const std::string& source) { + if (source.empty()) return {}; + const int count = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, source.data(), static_cast(source.size()), nullptr, 0); + if (count <= 0) return {}; + std::wstring result(static_cast(count), L'\0'); + MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, source.data(), static_cast(source.size()), result.data(), count); + return result; } -std::wstring quote(const std::wstring& value) { - std::wstring output = L"\""; - size_t slashCount = 0; - for (wchar_t character : value) { - if (character == L'\\') { - ++slashCount; - continue; - } - if (character == L'\"') output.append(slashCount * 2U + 1U, L'\\'); - else output.append(slashCount, L'\\'); - slashCount = 0; - output.push_back(character); +std::string to_utf8(const std::wstring& source) { + if (source.empty()) return {}; + const int count = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, source.data(), static_cast(source.size()), nullptr, 0, nullptr, nullptr); + if (count <= 0) return {}; + std::string result(static_cast(count), '\0'); + WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, source.data(), static_cast(source.size()), result.data(), count, nullptr, nullptr); + return result; +} + +std::wstring trim(std::wstring value) { + const auto first = std::find_if_not(value.begin(), value.end(), [](wchar_t ch) { return iswspace(ch) != 0; }); + const auto last = std::find_if_not(value.rbegin(), value.rend(), [](wchar_t ch) { return iswspace(ch) != 0; }).base(); + return first >= last ? std::wstring{} : std::wstring(first, last); +} + +std::wstring text_of(HWND control) { + const int length = GetWindowTextLengthW(control); + if (length <= 0) return {}; + std::wstring result(static_cast(length) + 1U, L'\0'); + GetWindowTextW(control, result.data(), length + 1); + result.resize(static_cast(length)); + return result; +} + +void set_text(HWND control, const std::wstring& text) { + SetWindowTextW(control, text.c_str()); +} + +bool checked(HWND control) { + return SendMessageW(control, BM_GETCHECK, 0, 0) == BST_CHECKED; +} + +void set_checked(HWND control, bool value) { + SendMessageW(control, BM_SETCHECK, value ? BST_CHECKED : BST_UNCHECKED, 0); +} + +int int_value(HWND control, int fallback) { + try { return std::stoi(text_of(control)); } catch (...) { return fallback; } +} + +void set_int(HWND control, int value) { + set_text(control, std::to_wstring(value)); +} + +void set_font(HWND control) { + SendMessageW(control, WM_SETFONT, reinterpret_cast(GetStockObject(DEFAULT_GUI_FONT)), TRUE); +} + +HWND child(State& state, const wchar_t* klass, const wchar_t* caption, DWORD style, int id, DWORD ex = 0) { + HWND control = CreateWindowExW(ex, klass, caption, WS_CHILD | WS_VISIBLE | style, 0, 0, 1, 1, state.window, + reinterpret_cast(static_cast(id)), state.instance, nullptr); + set_font(control); + return control; +} + +void status(State& state, const std::wstring& message, bool error = false) { + set_text(state.status, message); + SetWindowLongPtrW(state.status, GWLP_USERDATA, error ? 1 : 0); + InvalidateRect(state.status, nullptr, TRUE); +} + +std::wstring error_text(DWORD code) { + LPWSTR raw = nullptr; + const DWORD length = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + nullptr, code, 0, reinterpret_cast(&raw), 0, nullptr); + std::wstring result = length && raw ? trim(raw) : L"Windows error " + std::to_wstring(code); + if (raw) LocalFree(raw); + return result; +} + +bool pipe_call(const duo::Json& request, duo::Json& response, std::wstring& error) { + HANDLE pipe = INVALID_HANDLE_VALUE; + for (int tryNo = 0; tryNo != 25; ++tryNo) { + pipe = CreateFileW(kPipe, GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, nullptr); + if (pipe != INVALID_HANDLE_VALUE) break; + if (GetLastError() != ERROR_PIPE_BUSY || !WaitNamedPipeW(kPipe, 200)) Sleep(80); } - output.append(slashCount * 2U, L'\\'); - output.push_back(L'\"'); - return output; + if (pipe == INVALID_HANDLE_VALUE) { + error = L"Cannot reach DuoRdpAuthService: " + error_text(GetLastError()); + return false; + } + const std::string outbound = request.dump() + "\n"; + DWORD written = 0; + if (!WriteFile(pipe, outbound.data(), static_cast(outbound.size()), &written, nullptr) || written != outbound.size()) { + error = L"Cannot send request: " + error_text(GetLastError()); + CloseHandle(pipe); + return false; + } + std::string inbound; + char buffer[4096]; + while (inbound.size() < 1024U * 1024U) { + DWORD read = 0; + if (!ReadFile(pipe, buffer, sizeof(buffer), &read, nullptr) || read == 0) { + error = L"Cannot read response: " + error_text(GetLastError()); + CloseHandle(pipe); + return false; + } + const char* newline = static_cast(std::memchr(buffer, '\n', read)); + inbound.append(buffer, newline ? static_cast(newline - buffer) : static_cast(read)); + if (newline) break; + } + CloseHandle(pipe); + try { + response = duo::Json::parse(inbound); + return true; + } catch (...) { + error = L"DuoRdpAuthService returned invalid data."; + return false; + } +} + +bool admin_call(const std::string& action, const duo::Json* config, const std::wstring& username, const std::wstring& code, + const std::wstring& password, const std::string& session, duo::Json& response, std::wstring& error) { + duo::Json::Object request; + request["action"] = action; + if (config) request["config"] = *config; + if (!username.empty()) request["username"] = to_utf8(username); + if (!code.empty()) request["code"] = to_utf8(code); + if (!password.empty()) request["password"] = to_utf8(password); + if (!session.empty()) request["admin_session"] = session; + if (!pipe_call(duo::Json(std::move(request)), response, error)) return false; + if (!duo::json_bool(response, "ok", false)) { + error = from_utf8(duo::json_string(response, "error", "The service rejected this request.")); + return false; + } + return true; +} + +void clear_sensitive(std::wstring& value) { + if (!value.empty()) SecureZeroMemory(value.data(), value.size() * sizeof(wchar_t)); + value.clear(); +} + +bool prompt_credentials(HWND owner, const wchar_t* caption, const wchar_t* message, + std::wstring& username, std::wstring& password, std::wstring& error) { + wchar_t usernameBuffer[CREDUI_MAX_USERNAME_LENGTH + 1]{}; + wchar_t passwordBuffer[CREDUI_MAX_PASSWORD_LENGTH + 1]{}; + CREDUI_INFOW info{}; + info.cbSize = sizeof(info); + info.hwndParent = owner; + info.pszCaptionText = caption; + info.pszMessageText = message; + BOOL save = FALSE; + const DWORD result = CredUIPromptForCredentialsW(&info, L"DUO-RDP administrator", nullptr, 0, + usernameBuffer, ARRAYSIZE(usernameBuffer), passwordBuffer, ARRAYSIZE(passwordBuffer), &save, + CREDUI_FLAGS_GENERIC_CREDENTIALS | CREDUI_FLAGS_ALWAYS_SHOW_UI | CREDUI_FLAGS_DO_NOT_PERSIST); + if (result != ERROR_SUCCESS) { + SecureZeroMemory(passwordBuffer, sizeof(passwordBuffer)); + error = result == ERROR_CANCELLED ? L"Administrator access was cancelled." : L"Cannot read administrator credentials: " + error_text(result); + return false; + } + username = trim(usernameBuffer); + password.assign(passwordBuffer); + SecureZeroMemory(passwordBuffer, sizeof(passwordBuffer)); + if (username.empty() || password.empty()) { + clear_sensitive(password); + error = L"Login and password are required."; + return false; + } + return true; +} + +bool start_admin_session(HINSTANCE instance, HWND owner, std::string& session, std::wstring& error) { + (void)instance; + duo::Json statusResponse; + if (!admin_call("AdminAuthStatus", nullptr, L"", L"", L"", {}, statusResponse, error)) return false; + const bool configured = duo::json_bool(statusResponse, "configured", false); + for (;;) { + std::wstring username, password; + if (!prompt_credentials(owner, + configured ? L"DUO-RDP administrator access" : L"DUO-RDP - create administrator access", + configured ? L"Enter the administrator login and password." : L"First launch: enter the new administrator login and password.", + username, password, error)) { + return false; + } + if (!configured) { + std::wstring repeatedUser, repeatedPassword; + const bool confirmed = prompt_credentials(owner, L"DUO-RDP - confirm administrator access", + L"Enter the same login and password again.", repeatedUser, repeatedPassword, error); + const bool equal = confirmed && username == repeatedUser && password == repeatedPassword; + clear_sensitive(repeatedPassword); + if (!confirmed) { + clear_sensitive(password); + return false; + } + if (!equal) { + clear_sensitive(password); + MessageBoxW(owner, L"The two login/password entries do not match. Try again.", kTitle, MB_ICONWARNING | MB_OK); + continue; + } + } + duo::Json response; + const bool ok = admin_call(configured ? "AdminAuthenticate" : "AdminSetup", nullptr, username, L"", password, {}, response, error); + clear_sensitive(password); + if (ok) { + const std::string returned = duo::json_string(response, "admin_session"); + if (returned.size() == 64U) { + session = returned; + return true; + } + error = L"The service returned an invalid administrator session."; + } + if (configured && error == L"invalid administrator login or password") { + const int reset = MessageBoxW(owner, + L"The saved administrator credentials were rejected.\n\n" + L"Reset administrator login/password now? This requires local Administrator rights. " + L"Users, Telegram settings, Google Authenticator keys and 2FA policy will be preserved.", + kTitle, MB_ICONWARNING | MB_YESNO | MB_DEFBUTTON2); + if (reset == IDYES) { + std::wstring newUser, newPassword, repeatUser, repeatPassword; + const bool first = prompt_credentials(owner, L"DUO-RDP - reset administrator access", + L"Enter the new administrator login and password.", newUser, newPassword, error); + const bool second = first && prompt_credentials(owner, L"DUO-RDP - confirm administrator access", + L"Enter the same new login and password again.", repeatUser, repeatPassword, error); + const bool equal = second && newUser == repeatUser && newPassword == repeatPassword; + clear_sensitive(repeatPassword); + if (!first || !second) { + clear_sensitive(newPassword); + return false; + } + if (!equal) { + clear_sensitive(newPassword); + MessageBoxW(owner, L"The two login/password entries do not match. Try again.", kTitle, MB_ICONWARNING | MB_OK); + continue; + } + duo::Json resetResponse; + const bool resetOk = admin_call("AdminReset", nullptr, newUser, L"", newPassword, {}, resetResponse, error); + clear_sensitive(newPassword); + if (resetOk) { + const std::string resetSession = duo::json_string(resetResponse, "admin_session"); + if (resetSession.size() == 64U) { session = resetSession; return true; } + error = L"The service reset access but returned an invalid session."; + } + } + } + MessageBoxW(owner, error.c_str(), kTitle, MB_ICONERROR | MB_OK); + if (!configured) { + if (!admin_call("AdminAuthStatus", nullptr, L"", L"", L"", {}, statusResponse, error)) return false; + if (duo::json_bool(statusResponse, "configured", false)) return start_admin_session(instance, owner, session, error); + } + } +} + +bool active_admin_call(State& state, const std::string& action, const duo::Json* config, const std::wstring& username, + const std::wstring& code, duo::Json& response, std::wstring& error) { + for (int attempt = 0; attempt != 2; ++attempt) { + if (admin_call(action, config, username, code, L"", state.adminSession, response, error)) return true; + if (error != L"administrator authentication required") return false; + if (!start_admin_session(state.instance, state.window, state.adminSession, error)) return false; + } + error = L"Administrator session could not be renewed."; + return false; +} + +std::vector split_groups(const std::wstring& source) { + std::vector result; + std::unordered_set seen; + size_t begin = 0; + while (begin <= source.size()) { + const size_t end = source.find(L',', begin); + const std::wstring part = trim(source.substr(begin, end == std::wstring::npos ? std::wstring::npos : end - begin)); + if (!part.empty()) { + const std::string value = to_utf8(part); + std::string key = value; + std::transform(key.begin(), key.end(), key.begin(), [](unsigned char ch) { return static_cast(std::tolower(ch)); }); + if (seen.insert(key).second) result.push_back(value); + } + if (end == std::wstring::npos) break; + begin = end + 1; + } + return result; +} + +std::wstring group_text(const duo::Json* groups) { + if (!groups || !groups->is_array()) return {}; + std::wstring result; + for (const duo::Json& value : groups->array_or_empty()) { + if (!value.is_string()) continue; + if (!result.empty()) result += L", "; + result += from_utf8(value.string_or()); + } + return result; +} + +void refresh_rows(State& state) { + state.changingList = true; + ListView_DeleteAllItems(state.users); + for (size_t i = 0; i < state.rows.size(); ++i) { + const UserRow& row = state.rows[i]; + const std::wstring id = std::to_wstring(row.id); + LVITEMW item{}; + item.mask = LVIF_TEXT | LVIF_PARAM; + item.iItem = static_cast(i); + item.pszText = const_cast(id.c_str()); + item.lParam = static_cast(i); + const int inserted = ListView_InsertItem(state.users, &item); + const std::wstring target = row.user.empty() ? row.group : row.user; + const wchar_t* values[] = { + row.login.c_str(), row.groups.c_str(), row.token.c_str(), target.c_str(), + row.totp.c_str(), row.verified ? L"Verified" : L"Not verified" + }; + for (int column = 0; column != 6; ++column) ListView_SetItemText(state.users, inserted, column + 1, const_cast(values[column])); + } + state.changingList = false; +} + +void clear_editor(State& state) { + state.selected = -1; + for (HWND edit : {state.login, state.groups, state.token, state.user, state.group, state.totp, state.code}) set_text(edit, L""); + ListView_SetItemState(state.users, -1, 0, LVIS_SELECTED | LVIS_FOCUSED); + SetFocus(state.login); +} + +void load_editor(State& state, int index) { + if (index < 0 || index >= static_cast(state.rows.size())) { + clear_editor(state); + return; + } + state.selected = index; + const UserRow& row = state.rows[static_cast(index)]; + set_text(state.login, row.login); set_text(state.groups, row.groups); set_text(state.token, row.token); + set_text(state.user, row.user); set_text(state.group, row.group); set_text(state.totp, row.totp); set_text(state.code, L""); +} + +bool apply_row(State& state, bool complain = true) { + UserRow next; + if (state.selected >= 0 && state.selected < static_cast(state.rows.size())) next = state.rows[static_cast(state.selected)]; + next.login = trim(text_of(state.login)); next.groups = trim(text_of(state.groups)); next.token = trim(text_of(state.token)); + next.user = trim(text_of(state.user)); next.group = trim(text_of(state.group)); next.totp = trim(text_of(state.totp)); + if (next.login.empty()) { + if (complain) status(state, L"Login is required for every row.", true); + return false; + } + bool authenticationChanged = false; + if (state.selected >= 0 && state.selected < static_cast(state.rows.size())) { + const UserRow& old = state.rows[static_cast(state.selected)]; + authenticationChanged = old.login != next.login || old.groups != next.groups || old.token != next.token || old.user != next.user + || old.group != next.group || old.totp != next.totp; + } + if (authenticationChanged) next.verified = false; + if (state.selected < 0 || state.selected >= static_cast(state.rows.size())) { + state.rows.push_back(std::move(next)); + state.selected = static_cast(state.rows.size()) - 1; + } else { + state.rows[static_cast(state.selected)] = std::move(next); + } + refresh_rows(state); + ListView_SetItemState(state.users, state.selected, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED); + status(state, authenticationChanged ? L"Changed authentication data requires verification before it becomes active." : L"Row updated. Save settings to apply it."); + return true; +} + +int next_id(const State& state) { + int result = 1; + for (const UserRow& row : state.rows) result = std::max(result, row.id + 1); + if (const duo::Json* configured = state.config.find("next_user_id")) result = std::max(result, configured->int_or(1)); + return result; +} + +duo::Json build_config(State& state) { + duo::Json config = state.config; + if (!config.is_object()) config = duo::Json::Object{}; + duo::Json::Object global; + global["enabled"] = checked(state.enabled); + global["admin_2fa_enabled"] = checked(state.admins); + global["require_for_all_users"] = checked(state.all); + global["fail_closed"] = checked(state.failClosed); + global["otp_length"] = int_value(state.otpLength, 6); + global["otp_ttl_sec"] = int_value(state.otpTtl, 90); + global["max_attempts"] = int_value(state.attempts, 5); + global["resend_cooldown_sec"] = int_value(state.cooldown, 30); + config["global"] = duo::Json(std::move(global)); + duo::Json::Object defaults; + defaults["bot_token"] = to_utf8(trim(text_of(state.defaultToken))); + defaults["user_id"] = to_utf8(trim(text_of(state.defaultUser))); + defaults["group_id"] = to_utf8(trim(text_of(state.defaultGroup))); + config["default_telegram"] = duo::Json(std::move(defaults)); + duo::Json::Object users; + const duo::Json* existingUsers = config.find("per_user"); + std::unordered_set used; + int generated = next_id(state); + for (UserRow& row : state.rows) { + if (row.login.empty()) continue; + if (row.id <= 0 || !used.insert(row.id).second) { + while (used.contains(generated)) ++generated; + row.id = generated++; + used.insert(row.id); + } + duo::Json::Array groups; + for (const std::string& group : split_groups(row.groups)) groups.emplace_back(group); + // Keep fields added by a newer service version. The native editor owns + // the known delivery/policy fields, but must not turn an ordinary + // settings save into data loss for an unrecognised per-user field. + duo::Json user = duo::Json::Object{}; + if (existingUsers && existingUsers->is_object()) { + const duo::Json* prior = existingUsers->find(std::to_string(row.id)); + if (!prior) { + for (const auto& [key, value] : existingUsers->object_or_empty()) { + if (key == std::to_string(row.id) || duo::json_int(value, "id", 0) == row.id) { + prior = &value; + break; + } + } + } + if (prior && prior->is_object()) user = *prior; + } + user["id"] = row.id; user["login"] = to_utf8(row.login); user["groups"] = duo::Json(std::move(groups)); + user["bot_token"] = to_utf8(row.token); user["user_id"] = to_utf8(row.user); user["group_id"] = to_utf8(row.group); + user["totp_secret"] = to_utf8(row.totp); user["verified"] = row.verified; + users[std::to_string(row.id)] = duo::Json(std::move(user)); + } + config["per_user"] = duo::Json(std::move(users)); + config["next_user_id"] = generated; + return config; +} + +void load_config(State& state, const duo::Json& config) { + state.config = config; + const duo::Json blank(duo::Json::Object{}); + const duo::Json& global = config.find("global") ? *config.find("global") : blank; + set_checked(state.enabled, duo::json_bool(global, "enabled", false)); + set_checked(state.admins, duo::json_bool(global, "admin_2fa_enabled", false)); + set_checked(state.all, duo::json_bool(global, "require_for_all_users", false)); + set_checked(state.failClosed, duo::json_bool(global, "fail_closed", true)); + set_int(state.otpLength, duo::json_int(global, "otp_length", 6)); set_int(state.otpTtl, duo::json_int(global, "otp_ttl_sec", 90)); + set_int(state.attempts, duo::json_int(global, "max_attempts", 5)); set_int(state.cooldown, duo::json_int(global, "resend_cooldown_sec", 30)); + const duo::Json* defaults = config.find("default_telegram"); + set_text(state.defaultToken, from_utf8(defaults ? duo::json_string(*defaults, "bot_token") : "")); + set_text(state.defaultUser, from_utf8(defaults ? duo::json_string(*defaults, "user_id") : "")); + set_text(state.defaultGroup, from_utf8(defaults ? duo::json_string(*defaults, "group_id") : "")); + state.rows.clear(); + if (const duo::Json* users = config.find("per_user"); users && users->is_object()) { + for (const auto& [key, source] : users->object_or_empty()) { + if (!source.is_object()) continue; + UserRow row; + row.id = duo::json_int(source, "id", 0); + if (row.id <= 0) { try { row.id = std::stoi(key); } catch (...) { row.id = 0; } } + row.login = from_utf8(duo::json_string(source, "login", key)); row.groups = group_text(source.find("groups")); + row.token = from_utf8(duo::json_string(source, "bot_token")); row.user = from_utf8(duo::json_string(source, "user_id")); + row.group = from_utf8(duo::json_string(source, "group_id")); row.totp = from_utf8(duo::json_string(source, "totp_secret")); + row.verified = duo::json_bool(source, "verified", false); + state.rows.push_back(std::move(row)); + } + } + std::sort(state.rows.begin(), state.rows.end(), [](const UserRow& a, const UserRow& b) { return a.id < b.id; }); + refresh_rows(state); clear_editor(state); +} + +bool reload(State& state) { + duo::Json response; std::wstring error; + if (!active_admin_call(state, "AdminGet", nullptr, L"", L"", response, error)) { status(state, error, true); return false; } + const duo::Json* config = response.find("config"); + if (!config) { status(state, L"DuoRdpAuthService did not return configuration.", true); return false; } + load_config(state, *config); + status(state, from_utf8(duo::json_string(response, "message", "Settings loaded."))); + return true; +} + +bool save(State& state, bool report = true) { + duo::Json candidate = build_config(state), response; std::wstring error; + if (!active_admin_call(state, "AdminSave", &candidate, L"", L"", response, error)) { status(state, error, true); return false; } + if (const duo::Json* config = response.find("config")) load_config(state, *config); + if (report) status(state, from_utf8(duo::json_string(response, "message", "Settings saved."))); + return true; +} + +std::wstring new_totp() { + BYTE bytes[20]{}; + if (BCryptGenRandom(nullptr, bytes, sizeof(bytes), BCRYPT_USE_SYSTEM_PREFERRED_RNG) < 0) return {}; + static constexpr wchar_t alphabet[] = L"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; + std::wstring result; result.reserve(32); + unsigned accumulator = 0; int bits = 0; + for (BYTE byte : bytes) { + accumulator = (accumulator << 8U) | byte; bits += 8; + while (bits >= 5) { bits -= 5; result.push_back(alphabet[(accumulator >> bits) & 31U]); } + } + if (bits > 0) result.push_back(alphabet[(accumulator << (5 - bits)) & 31U]); + return result; +} + +bool local_admin() { + SID_IDENTIFIER_AUTHORITY authority = SECURITY_NT_AUTHORITY; PSID sid = nullptr; BOOL member = FALSE; + const bool ok = AllocateAndInitializeSid(&authority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &sid) + && CheckTokenMembership(nullptr, sid, &member); + if (sid) FreeSid(sid); + return ok && member; +} + +bool elevate() { + wchar_t path[32768]{}; const DWORD length = GetModuleFileNameW(nullptr, path, ARRAYSIZE(path)); + return length > 0 && length < ARRAYSIZE(path) && reinterpret_cast(ShellExecuteW(nullptr, L"runas", path, nullptr, nullptr, SW_SHOWNORMAL)) > 32; +} + +void layout(State& state) { + RECT client{}; GetClientRect(state.window, &client); + const int width = std::max(860, static_cast(client.right)); + const int height = std::max(630, static_cast(client.bottom)); + const int margin = 10; + const int h = 25; + auto put = [](HWND control, int x, int y, int w, int height = 25) { MoveWindow(control, x, y, std::max(1, w), std::max(1, height), TRUE); }; + put(state.enabled, 10, 8, 115); put(state.admins, 130, 8, 180); put(state.all, 315, 8, 150); put(state.failClosed, 470, 8, 100); + const int nx = std::max(700, width - 390); + put(GetDlgItem(state.window, LabelLength), nx, 8, 45); put(state.otpLength, nx + 48, 7, 40); + put(GetDlgItem(state.window, LabelTtl), nx + 92, 8, 25); put(state.otpTtl, nx + 120, 7, 46); + put(GetDlgItem(state.window, LabelAttempts), nx + 170, 8, 50); put(state.attempts, nx + 222, 7, 40); + put(GetDlgItem(state.window, LabelCooldown), nx + 267, 8, 58); put(state.cooldown, nx + 327, 7, 46); + const int half = (width - margin * 3) / 2; + put(GetDlgItem(state.window, LabelDefaultToken), margin, 40, 138); put(state.defaultToken, margin + 140, 39, half - 140); + put(GetDlgItem(state.window, LabelDefaultUser), margin * 2 + half, 40, 105); put(state.defaultUser, margin * 2 + half + 107, 39, half - 107); + put(GetDlgItem(state.window, LabelDefaultGroup), margin, 68, 138); put(state.defaultGroup, margin + 140, 67, half - 140); + put(GetDlgItem(state.window, LabelDefaultInfo), margin * 2 + half, 68, half, 22); + const int listTop = 97, listHeight = std::max(160, height / 3); + put(state.users, margin, listTop, width - margin * 2, listHeight); + const int detail = listTop + listHeight + 12; + put(GetDlgItem(state.window, LabelLogin), margin, detail, 45, 22); put(state.login, margin + 48, detail - 1, half - 48); + put(GetDlgItem(state.window, LabelGroups), margin * 2 + half, detail, 50, 22); put(state.groups, margin * 2 + half + 52, detail - 1, half - 52); + put(GetDlgItem(state.window, LabelToken), margin, detail + h + 7, 92, 22); put(state.token, margin + 94, detail + h + 6, half - 94); + put(GetDlgItem(state.window, LabelUser), margin * 2 + half, detail + h + 7, 72, 22); put(state.user, margin * 2 + half + 74, detail + h + 6, half - 74); + put(GetDlgItem(state.window, LabelGroup), margin, detail + 2 * h + 14, 92, 22); put(state.group, margin + 94, detail + 2 * h + 13, half - 94); + put(GetDlgItem(state.window, LabelTotp), margin * 2 + half, detail + 2 * h + 14, 72, 22); put(state.totp, margin * 2 + half + 74, detail + 2 * h + 13, half - 74); + const int actions = detail + 3 * h + 23; int x = margin; + for (int id : {IdNew, IdApply, IdDelete, IdGenerate, IdSave, IdReload}) { put(GetDlgItem(state.window, id), x, actions, 112); x += 119; } + const int testX = std::max(x + 4, width - 305); + put(state.code, testX, actions, 92); put(GetDlgItem(state.window, IdSend), testX + 98, actions, 96); put(GetDlgItem(state.window, IdVerify), testX + 200, actions, 96); + put(state.status, margin, height - 30, width - margin * 2, 23); +} + +LRESULT CALLBACK proc(HWND window, UINT message, WPARAM wParam, LPARAM lParam) { + State* state = reinterpret_cast(GetWindowLongPtrW(window, GWLP_USERDATA)); + if (message == WM_NCCREATE) { + state = static_cast(reinterpret_cast(lParam)->lpCreateParams); + state->window = window; + SetWindowLongPtrW(window, GWLP_USERDATA, reinterpret_cast(state)); + } + if (!state) return DefWindowProcW(window, message, wParam, lParam); + switch (message) { + case WM_CREATE: { + state->enabled = child(*state, L"BUTTON", L"2FA enabled", BS_AUTOCHECKBOX | WS_TABSTOP, IdEnabled); + state->admins = child(*state, L"BUTTON", L"Administrators require 2FA", BS_AUTOCHECKBOX | WS_TABSTOP, IdAdmins); + state->all = child(*state, L"BUTTON", L"Require for all users", BS_AUTOCHECKBOX | WS_TABSTOP, IdAll); + state->failClosed = child(*state, L"BUTTON", L"Fail closed", BS_AUTOCHECKBOX | WS_TABSTOP, IdFailClosed); + child(*state, L"STATIC", L"Length", 0, LabelLength); state->otpLength = child(*state, L"EDIT", L"6", ES_NUMBER | ES_AUTOHSCROLL | WS_BORDER, IdOtpLength, WS_EX_CLIENTEDGE); + child(*state, L"STATIC", L"TTL", 0, LabelTtl); state->otpTtl = child(*state, L"EDIT", L"90", ES_NUMBER | ES_AUTOHSCROLL | WS_BORDER, IdOtpTtl, WS_EX_CLIENTEDGE); + child(*state, L"STATIC", L"Attempts", 0, LabelAttempts); state->attempts = child(*state, L"EDIT", L"5", ES_NUMBER | ES_AUTOHSCROLL | WS_BORDER, IdAttempts, WS_EX_CLIENTEDGE); + child(*state, L"STATIC", L"Cooldown", 0, LabelCooldown); state->cooldown = child(*state, L"EDIT", L"30", ES_NUMBER | ES_AUTOHSCROLL | WS_BORDER, IdCooldown, WS_EX_CLIENTEDGE); + child(*state, L"STATIC", L"Default Telegram token", 0, LabelDefaultToken); state->defaultToken = child(*state, L"EDIT", L"", ES_AUTOHSCROLL | WS_BORDER, IdDefaultToken, WS_EX_CLIENTEDGE); + child(*state, L"STATIC", L"Default Telegram ID", 0, LabelDefaultUser); state->defaultUser = child(*state, L"EDIT", L"", ES_AUTOHSCROLL | WS_BORDER, IdDefaultUser, WS_EX_CLIENTEDGE); + child(*state, L"STATIC", L"Default group ID", 0, LabelDefaultGroup); state->defaultGroup = child(*state, L"EDIT", L"", ES_AUTOHSCROLL | WS_BORDER, IdDefaultGroup, WS_EX_CLIENTEDGE); + child(*state, L"STATIC", L"Defaults apply only where a user row leaves Telegram fields blank.", 0, LabelDefaultInfo); + state->users = child(*state, WC_LISTVIEWW, L"", LVS_REPORT | LVS_SINGLESEL | LVS_SHOWSELALWAYS | WS_TABSTOP, IdUsers, WS_EX_CLIENTEDGE); + ListView_SetExtendedListViewStyle(state->users, LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES | LVS_EX_DOUBLEBUFFER); + const wchar_t* labels[] = {L"ID", L"Login", L"Groups", L"Telegram token", L"Telegram target", L"Google key", L"State"}; + const int widths[] = {48, 180, 165, 250, 160, 220, 105}; + for (int i = 0; i < 7; ++i) { LVCOLUMNW col{}; col.mask = LVCF_TEXT | LVCF_WIDTH | LVCF_SUBITEM; col.pszText = const_cast(labels[i]); col.cx = widths[i]; col.iSubItem = i; ListView_InsertColumn(state->users, i, &col); } + child(*state, L"STATIC", L"Login", 0, LabelLogin); state->login = child(*state, L"EDIT", L"", ES_AUTOHSCROLL | WS_BORDER, IdLogin, WS_EX_CLIENTEDGE); + child(*state, L"STATIC", L"Groups", 0, LabelGroups); state->groups = child(*state, L"EDIT", L"", ES_AUTOHSCROLL | WS_BORDER, IdGroups, WS_EX_CLIENTEDGE); + child(*state, L"STATIC", L"Telegram token", 0, LabelToken); state->token = child(*state, L"EDIT", L"", ES_AUTOHSCROLL | WS_BORDER, IdToken, WS_EX_CLIENTEDGE); + child(*state, L"STATIC", L"Telegram ID", 0, LabelUser); state->user = child(*state, L"EDIT", L"", ES_AUTOHSCROLL | WS_BORDER, IdUser, WS_EX_CLIENTEDGE); + child(*state, L"STATIC", L"Telegram group", 0, LabelGroup); state->group = child(*state, L"EDIT", L"", ES_AUTOHSCROLL | WS_BORDER, IdGroup, WS_EX_CLIENTEDGE); + child(*state, L"STATIC", L"Google Authenticator key", 0, LabelTotp); state->totp = child(*state, L"EDIT", L"", ES_AUTOHSCROLL | WS_BORDER, IdTotp, WS_EX_CLIENTEDGE); + child(*state, L"BUTTON", L"New row", BS_PUSHBUTTON, IdNew); child(*state, L"BUTTON", L"Apply row", BS_PUSHBUTTON, IdApply); + child(*state, L"BUTTON", L"Delete row", BS_PUSHBUTTON, IdDelete); child(*state, L"BUTTON", L"Generate TOTP", BS_PUSHBUTTON, IdGenerate); + child(*state, L"BUTTON", L"Save settings", BS_DEFPUSHBUTTON, IdSave); child(*state, L"BUTTON", L"Reload", BS_PUSHBUTTON, IdReload); + state->code = child(*state, L"EDIT", L"", ES_NUMBER | ES_AUTOHSCROLL | WS_BORDER, IdCode, WS_EX_CLIENTEDGE); + SendMessageW(state->code, EM_SETCUEBANNER, TRUE, reinterpret_cast(L"test code")); + child(*state, L"BUTTON", L"Send test", BS_PUSHBUTTON, IdSend); child(*state, L"BUTTON", L"Verify", BS_PUSHBUTTON, IdVerify); + state->status = child(*state, L"STATIC", L"Loading settings...", SS_ENDELLIPSIS, IdStatus); + PostMessageW(window, WM_APP + 1, 0, 0); return 0; + } + case WM_APP + 1: reload(*state); return 0; + case WM_SIZE: layout(*state); return 0; + case WM_NOTIFY: + if (reinterpret_cast(lParam)->idFrom == IdUsers && reinterpret_cast(lParam)->code == LVN_ITEMCHANGED && !state->changingList) { + const auto* update = reinterpret_cast(lParam); + if ((update->uChanged & LVIF_STATE) && (update->uNewState & LVIS_SELECTED)) load_editor(*state, update->iItem); + } + return 0; + case WM_COMMAND: { + const int id = LOWORD(wParam); + if (id == IdNew && HIWORD(wParam) == BN_CLICKED) { clear_editor(*state); status(*state, L"Enter settings, then press Apply row."); return 0; } + if (id == IdApply && HIWORD(wParam) == BN_CLICKED) { apply_row(*state); return 0; } + if (id == IdDelete && HIWORD(wParam) == BN_CLICKED) { + if (state->selected < 0 || state->selected >= static_cast(state->rows.size())) { status(*state, L"Select a row first.", true); return 0; } + if (MessageBoxW(window, L"Delete the selected 2FA user row? Save settings to make it permanent.", kTitle, MB_ICONWARNING | MB_YESNO | MB_DEFBUTTON2) == IDYES) { + state->rows.erase(state->rows.begin() + state->selected); refresh_rows(*state); clear_editor(*state); status(*state, L"Row deleted locally. Press Save settings to apply it."); + } + return 0; + } + if (id == IdGenerate && HIWORD(wParam) == BN_CLICKED) { + const std::wstring secret = new_totp(); + if (secret.empty()) status(*state, L"Cannot generate a TOTP secret.", true); + else { set_text(state->totp, secret); status(*state, L"TOTP secret generated. Add it to Google Authenticator, then Apply row, Save, and Verify."); } + return 0; + } + if (id == IdSave && HIWORD(wParam) == BN_CLICKED) { save(*state); return 0; } + if (id == IdReload && HIWORD(wParam) == BN_CLICKED) { reload(*state); return 0; } + if (id == IdSend && HIWORD(wParam) == BN_CLICKED) { + if (!apply_row(*state) || state->selected < 0) return 0; + const std::wstring login = state->rows[static_cast(state->selected)].login; + if (!save(*state, false)) return 0; + duo::Json response; std::wstring error; + if (!active_admin_call(*state, "AdminSendTestOtp", nullptr, login, L"", response, error)) status(*state, error, true); + else status(*state, from_utf8(duo::json_string(response, "message", "Test request completed."))); + return 0; + } + if (id == IdVerify && HIWORD(wParam) == BN_CLICKED) { + if (state->selected < 0 || state->selected >= static_cast(state->rows.size())) { status(*state, L"Select and save a row first.", true); return 0; } + const std::wstring code = trim(text_of(state->code)); + if (code.empty()) { status(*state, L"Enter the verification code.", true); return 0; } + duo::Json response; std::wstring error; + if (!active_admin_call(*state, "AdminVerifyTestOtp", nullptr, state->rows[static_cast(state->selected)].login, code, response, error)) status(*state, error, true); + else { if (const duo::Json* config = response.find("config")) load_config(*state, *config); status(*state, from_utf8(duo::json_string(response, "message", "2FA method verified."))); } + return 0; + } + return 0; + } + case WM_CTLCOLORSTATIC: + if (reinterpret_cast(lParam) == state->status) { + HDC dc = reinterpret_cast(wParam); + SetTextColor(dc, GetWindowLongPtrW(state->status, GWLP_USERDATA) ? RGB(180, 30, 30) : RGB(30, 90, 45)); + SetBkMode(dc, TRANSPARENT); + return reinterpret_cast(GetSysColorBrush(COLOR_WINDOW)); + } + break; + case WM_CLOSE: DestroyWindow(window); return 0; + case WM_DESTROY: state->adminSession.clear(); PostQuitMessage(0); return 0; + default: break; + } + return DefWindowProcW(window, message, wParam, lParam); } } // namespace -int wmain(int argc, wchar_t** argv) { - const std::wstring service = module_directory() + L"\\DuoRdpAuthService.exe"; - if (GetFileAttributesW(service.c_str()) == INVALID_FILE_ATTRIBUTES) { - std::fwprintf(stderr, L"DuoRdpAuthService.exe is missing next to DuoRdpAdmin.exe.\n"); - return 2; +int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) { + if (!local_admin()) { + if (!elevate()) MessageBoxW(nullptr, L"DUO-RDP settings require a local Administrator account. UAC elevation was cancelled or unavailable.", kTitle, MB_ICONERROR | MB_OK); + return 0; } - std::wstring command = quote(service) + L" --admin"; - for (int index = 1; index < argc; ++index) command += L" " + quote(argv[index]); - std::vector mutableCommand(command.begin(), command.end()); - mutableCommand.push_back(L'\0'); - STARTUPINFOW startup{}; - startup.cb = sizeof(startup); - PROCESS_INFORMATION process{}; - if (!CreateProcessW(nullptr, mutableCommand.data(), nullptr, nullptr, TRUE, 0, nullptr, module_directory().c_str(), &startup, &process)) { - std::fwprintf(stderr, L"Cannot launch native admin core, error=%lu.\n", GetLastError()); + INITCOMMONCONTROLSEX common{}; common.dwSize = sizeof(common); common.dwICC = ICC_LISTVIEW_CLASSES; InitCommonControlsEx(&common); + std::string adminSession; + std::wstring accessError; + if (!start_admin_session(instance, nullptr, adminSession, accessError)) { + MessageBoxW(nullptr, accessError.c_str(), kTitle, MB_ICONERROR | MB_OK); return 1; } - CloseHandle(process.hThread); - WaitForSingleObject(process.hProcess, INFINITE); - DWORD exitCode = 1; - GetExitCodeProcess(process.hProcess, &exitCode); - CloseHandle(process.hProcess); - return static_cast(exitCode); + State state; state.instance = instance; state.adminSession = std::move(adminSession); + WNDCLASSEXW klass{}; klass.cbSize = sizeof(klass); klass.hInstance = instance; klass.hCursor = LoadCursorW(nullptr, IDC_ARROW); + klass.hbrBackground = GetSysColorBrush(COLOR_WINDOW); klass.lpszClassName = kClass; klass.lpfnWndProc = proc; klass.hIcon = LoadIconW(nullptr, IDI_SHIELD); + if (!RegisterClassExW(&klass) && GetLastError() != ERROR_CLASS_ALREADY_EXISTS) return 1; + HWND window = CreateWindowExW(0, kClass, kTitle, WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, CW_USEDEFAULT, CW_USEDEFAULT, 1250, 720, nullptr, nullptr, instance, &state); + if (!window) return 1; + ShowWindow(window, show == 0 ? SW_SHOWNORMAL : show); UpdateWindow(window); + MSG message{}; + while (GetMessageW(&message, nullptr, 0, 0) > 0) { TranslateMessage(&message); DispatchMessageW(&message); } + return static_cast(message.wParam); } diff --git a/native/cpp/DuoRdpAuthService.cpp b/native/cpp/DuoRdpAuthService.cpp index 5b1cf4a..ba056be 100644 --- a/native/cpp/DuoRdpAuthService.cpp +++ b/native/cpp/DuoRdpAuthService.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include @@ -29,6 +30,7 @@ #include #include #include +#include #include #include @@ -39,6 +41,7 @@ #pragma comment(lib, "bcrypt.lib") #pragma comment(lib, "crypt32.lib") #pragma comment(lib, "winhttp.lib") +#pragma comment(lib, "netapi32.lib") #endif namespace { @@ -193,6 +196,61 @@ bool restrict_config_acl(const std::wstring& path, std::string& error) { return true; } +std::wstring config_backup_name(const std::wstring& path, unsigned sequence) { + SYSTEMTIME time{}; + GetSystemTime(&time); + wchar_t suffix[48]{}; + std::swprintf(suffix, ARRAYSIZE(suffix), L"_%04u%02u%02u-%02u%02u%02u", time.wYear, time.wMonth, time.wDay, time.wHour, time.wMinute, time.wSecond); + const size_t slash = path.find_last_of(L"\\/"); + const size_t dot = path.find_last_of(L'.'); + const bool hasExtension = dot != std::wstring::npos && (slash == std::wstring::npos || dot > slash); + const std::wstring base = hasExtension ? path.substr(0, dot) : path; + const std::wstring extension = hasExtension ? path.substr(dot) : L""; + return base + suffix + (sequence ? L"-" + std::to_wstring(sequence) : L"") + extension; +} + +bool backup_existing_config(const std::wstring& path, std::string& error) { + const DWORD attributes = GetFileAttributesW(path.c_str()); + if (attributes == INVALID_FILE_ATTRIBUTES) { + if (GetLastError() == ERROR_FILE_NOT_FOUND || GetLastError() == ERROR_PATH_NOT_FOUND) return true; + error = "cannot inspect existing config"; + return false; + } + if ((attributes & FILE_ATTRIBUTE_DIRECTORY) != 0U) { + error = "config path is a directory"; + return false; + } + LARGE_INTEGER originalSize{}; + HANDLE original = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (original == INVALID_HANDLE_VALUE || !GetFileSizeEx(original, &originalSize)) { + if (original != INVALID_HANDLE_VALUE) CloseHandle(original); + error = "cannot inspect existing config size"; + return false; + } + CloseHandle(original); + for (unsigned sequence = 0; sequence < 1000U; ++sequence) { + const std::wstring backup = config_backup_name(path, sequence); + if (!CopyFileW(path.c_str(), backup.c_str(), TRUE)) { + if (GetLastError() == ERROR_FILE_EXISTS) continue; + error = "cannot create config backup"; + return false; + } + LARGE_INTEGER backupSize{}; + HANDLE copied = CreateFileW(backup.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + const bool sameSize = copied != INVALID_HANDLE_VALUE && GetFileSizeEx(copied, &backupSize) && backupSize.QuadPart == originalSize.QuadPart; + if (copied != INVALID_HANDLE_VALUE) CloseHandle(copied); + if (!sameSize || !restrict_config_acl(backup, error)) { + DeleteFileW(backup.c_str()); + if (error.empty()) error = "config backup verification failed"; + return false; + } + log_line("Config", "encrypted config backup created"); + return true; + } + error = "cannot allocate a unique config backup name"; + return false; +} + bool write_file_utf8_atomic(const std::wstring& path, const std::string& data, std::string& error) { const std::wstring directory = path.substr(0, path.find_last_of(L"\\/")); ensure_directory(directory); @@ -353,11 +411,13 @@ ConfigRead load_config() { [[maybe_unused]] bool save_config(const duo::Json& value, std::string& error) { std::string payload; if (!encrypt_dpapi_config(value.dump(), payload, error)) return false; + if (!backup_existing_config(configured_config_path(), error)) return false; return write_file_utf8_atomic(configured_config_path(), std::string(kConfigPrefix) + kDpapiPrefix + payload, error); } const duo::Json& object_member_or_empty(const duo::Json& parent, const char* key); std::string normalize_username(const std::string& source); +std::string normalize_identity(const std::string& source); bool identity_matches(const std::string& configured, const std::string& username); duo::Json& ensure_object_member(duo::Json& parent, const char* key) { @@ -422,7 +482,7 @@ void print_admin_usage() { " --admin [--config ] show\n" " --admin [--config ] set-global \n" " --admin [--config ] upsert-user [--chat-id ] [--group-id ]\n" - " [--groups group1,group2] [--totp ] [--token-stdin] [--verify]\n" + " [--groups group1,group2] [--totp ] [--token-stdin]\n" " --admin [--config ] remove-user \n" "\n" "--token-stdin reads the Telegram bot token from standard input, so it is not exposed in the command line.\n" @@ -480,6 +540,14 @@ int run_admin(const std::vector& allArgs) { if (command == "init") { const bool force = args.size() > 1 && args[1] == "--force"; ConfigRead current = load_config(); + if (current.exists && current.error.empty()) { + ensure_config_shape(current.value); + const duo::Json& auth = object_member_or_empty(current.value, "admin_auth"); + if (!duo::json_string(auth, "username").empty() || !duo::json_string(auth, "password_hash").empty()) { + std::fputs("administrator authentication is configured; use DuoRdpAdmin.exe\n", stderr); + return 5; + } + } if (current.exists && current.error.empty() && !force) { std::fputs("config already exists; use init --force to replace it\n", stderr); return 3; @@ -503,6 +571,11 @@ int run_admin(const std::vector& allArgs) { print_config_summary(current); return 0; } + const duo::Json& adminAuth = object_member_or_empty(current.value, "admin_auth"); + if (!duo::json_string(adminAuth, "username").empty() || !duo::json_string(adminAuth, "password_hash").empty()) { + std::fputs("administrator authentication is configured; use DuoRdpAdmin.exe\n", stderr); + return 5; + } if (command == "set-global") { if (args.size() != 3) { @@ -550,8 +623,11 @@ int run_admin(const std::vector& allArgs) { std::string found; for (const auto& [key, row] : users.object_or_empty()) { if (normalize_username(key) == wanted || identity_matches(duo::json_string(row, "login"), args[1])) { + if (!found.empty()) { + std::fputs("duplicate user records detected; open DuoRdpAdmin.exe to repair them safely\n", stderr); + return 4; + } found = key; - break; } } if (found.empty()) { @@ -577,22 +653,48 @@ int run_admin(const std::vector& allArgs) { return 2; } const std::string login = args[1]; - const std::string key = normalize_username(login); - if (key.empty()) { + if (normalize_identity(login).empty()) { std::fputs("login is empty\n", stderr); return 2; } duo::Json& users = ensure_object_member(current.value, "per_user"); + std::string key; + for (const auto& [candidateKey, candidate] : users.object_or_empty()) { + if (identity_matches(duo::json_string(candidate, "login", candidateKey), login)) { + if (!key.empty()) { + std::fputs("duplicate user records detected; open DuoRdpAdmin.exe to repair them safely\n", stderr); + return 4; + } + key = candidateKey; + } + } + if (key.empty()) { + int nextId = std::max(1, duo::json_int(current.value, "next_user_id", 1)); + for (const auto& [unused, candidate] : users.object_or_empty()) { + (void)unused; + nextId = std::max(nextId, duo::json_int(candidate, "id", 0) + 1); + } + key = std::to_string(nextId); + current.value["next_user_id"] = nextId + 1; + } duo::Json& row = users[key]; if (!row.is_object()) row = duo::Json::Object{}; + if (duo::json_int(row, "id", 0) <= 0) { + int numericId = static_cast(std::strtol(key.c_str(), nullptr, 10)); + if (numericId <= 0) { + numericId = std::max(1, duo::json_int(current.value, "next_user_id", 1)); + current.value["next_user_id"] = numericId + 1; + } + row["id"] = numericId; + } row["login"] = login; bool credentialsChanged = false; - bool verify = false; for (size_t index = 2; index < args.size(); ++index) { const std::string& flag = args[index]; std::string value; if (flag == "--verify") { - verify = true; + std::fputs("--verify is retired; use DuoRdpAdmin.exe and prove Telegram/TOTP possession instead\n", stderr); + return 2; } else if (flag == "--chat-id" || flag == "--group-id" || flag == "--totp" || flag == "--groups") { if (!read_next_arg(args, index, value)) { std::fprintf(stderr, "%s needs a value\n", flag.c_str()); @@ -605,6 +707,7 @@ int run_admin(const std::vector& allArgs) { duo::Json::Array groups; for (const std::string& group : split_csv(value)) groups.emplace_back(group); row["groups"] = duo::Json(std::move(groups)); + credentialsChanged = true; } } else if (flag == "--token-stdin") { if (!std::getline(std::cin, value) || value.empty()) { @@ -618,14 +721,13 @@ int run_admin(const std::vector& allArgs) { return 2; } } - if (credentialsChanged && !verify) row["verified"] = false; - if (verify) row["verified"] = true; + if (credentialsChanged) row["verified"] = false; std::string error; if (!save_config(current.value, error)) { std::fprintf(stderr, "cannot save config: %s\n", error.c_str()); return 1; } - std::puts(verify ? "user saved and verified." : "user saved; verification is required before rule-based 2FA applies."); + std::puts("user saved; verification is required before rule-based 2FA applies."); return 0; } @@ -709,6 +811,56 @@ bool identity_matches(const std::string& configured, const std::string& username return normalize_identity(configured) == normalize_identity(username) || normalize_username(configured) == normalize_username(username); } +void append_group_identity(std::vector& groups, std::unordered_set& seen, const std::wstring& group) { + const std::string value = wide_to_utf8(trim_wide(group)); + const std::string key = normalize_identity(value); + if (!key.empty() && seen.insert(key).second) groups.push_back(value); +} + +std::vector resolve_windows_groups(const std::string& username, const std::vector& supplied) { + std::vector groups; + std::unordered_set seenGroups; + for (const std::string& group : supplied) append_group_identity(groups, seenGroups, utf8_to_wide(group)); + std::vector candidates; + std::unordered_set seenCandidates; + const auto addCandidate = [&](std::wstring value) { + value = trim_wide(std::move(value)); + const std::string key = normalize_identity(wide_to_utf8(value)); + if (!key.empty() && seenCandidates.insert(key).second) candidates.push_back(std::move(value)); + }; + const std::wstring raw = trim_wide(utf8_to_wide(username)); + addCandidate(raw); + const size_t slash = raw.find_last_of(L"\\/"); + if (slash != std::wstring::npos && slash + 1 < raw.size()) addCandidate(raw.substr(slash + 1)); + const size_t at = raw.find(L'@'); + if (at != std::wstring::npos) addCandidate(raw.substr(0, at)); + + for (const std::wstring& account : candidates) { + LPBYTE localBuffer = nullptr; + DWORD localRead = 0; + DWORD localTotal = 0; + const NET_API_STATUS localStatus = NetUserGetLocalGroups(nullptr, account.c_str(), 0, LG_INCLUDE_INDIRECT, &localBuffer, + MAX_PREFERRED_LENGTH, &localRead, &localTotal); + if (localStatus == NERR_Success && localBuffer) { + const auto* rows = reinterpret_cast(localBuffer); + for (DWORD index = 0; index < localRead; ++index) if (rows[index].lgrui0_name) append_group_identity(groups, seenGroups, rows[index].lgrui0_name); + } + if (localBuffer) NetApiBufferFree(localBuffer); + + LPBYTE globalBuffer = nullptr; + DWORD globalRead = 0; + DWORD globalTotal = 0; + const NET_API_STATUS globalStatus = NetUserGetGroups(nullptr, account.c_str(), 0, &globalBuffer, + MAX_PREFERRED_LENGTH, &globalRead, &globalTotal); + if (globalStatus == NERR_Success && globalBuffer) { + const auto* rows = reinterpret_cast(globalBuffer); + for (DWORD index = 0; index < globalRead; ++index) if (rows[index].grui0_name) append_group_identity(groups, seenGroups, rows[index].grui0_name); + } + if (globalBuffer) NetApiBufferFree(globalBuffer); + } + return groups; +} + const duo::Json* find_user_node(const duo::Json& config, const std::string& username) { const duo::Json& users = object_member_or_empty(config, "per_user"); const std::string normalized = normalize_username(username); @@ -788,12 +940,6 @@ bool policy_requires_2fa(const duo::Json& config, const std::string& username, c const duo::Json& rules = object_member_or_empty(config, "rules"); if (const duo::Json* users = rules.find("enabled_users"); users && list_contains_identity(*users, username)) return true; if (const duo::Json* enabledGroups = rules.find("enabled_groups"); enabledGroups && list_intersects_groups(*enabledGroups, groups)) return true; - - const duo::Json& perUser = object_member_or_empty(config, "per_user"); - for (const auto& [unused, row] : perUser.object_or_empty()) { - (void)unused; - if (const duo::Json* rowGroups = row.find("groups"); rowGroups && list_intersects_groups(*rowGroups, groups)) return true; - } return false; } @@ -906,6 +1052,294 @@ bool verify_totp(const std::string& secret, const std::string& submitted) { return false; } +// The first native release kept only a deliberately small command-line admin +// surface. The production administrator is now a native GUI which speaks to +// this service over the existing Administrator/SYSTEM-only pipe. Keeping all +// config IO here matters: the GUI never reads a DPAPI file directly, so the +// machine-encrypted configuration remains writable only by the service. +bool is_single_line_value(const std::string& value, size_t maximum = 4096U) { + return value.size() <= maximum + && value.find('\r') == std::string::npos + && value.find('\n') == std::string::npos; +} + +std::string normalized_totp_secret(std::string value) { + value.erase(std::remove_if(value.begin(), value.end(), [](unsigned char c) { return std::isspace(c) != 0; }), value.end()); + std::transform(value.begin(), value.end(), value.begin(), [](unsigned char c) { return static_cast(std::toupper(c)); }); + return value; +} + +bool base32_decode(const std::string& source, std::vector& output); + +bool valid_totp_secret(const std::string& value) { + if (value.empty()) return true; + std::vector decoded; + return base32_decode(value, decoded) && decoded.size() >= 10U; +} + +bool has_nonempty_array(const duo::Json* value) { + return value && value->is_array() && !value->array_or_empty().empty(); +} + +void merge_admin_user_row(duo::Json& destination, const duo::Json& source, bool sourcePreferred) { + if (!destination.is_object()) destination = duo::Json::Object{}; + if (!source.is_object()) return; + // A legacy numeric row and a short-lived login-keyed row can coexist after + // the old CLI upsert bug. Prefer the explicit login-keyed mutation, while + // retaining fields it did not carry (for example groups on token-only + // changes). This is deterministic and makes the first GUI Save repair + // the duplicate instead of leaving policy lookup map-order dependent. + for (const char* key : {"login", "bot_token", "user_id", "group_id", "totp_secret"}) { + const duo::Json* candidate = source.find(key); + if (!candidate || !candidate->is_string()) continue; + const std::string value = candidate->string_or(); + if (sourcePreferred || (!value.empty() && duo::json_string(destination, key).empty())) destination[key] = value; + } + if (const duo::Json* groups = source.find("groups"); groups && groups->is_array()) { + if (sourcePreferred || !has_nonempty_array(destination.find("groups"))) destination["groups"] = *groups; + } + if (const duo::Json* verified = source.find("verified"); verified && verified->is_bool()) { + if (sourcePreferred || !destination.find("verified")) destination["verified"] = verified->bool_or(false); + } + if (const duo::Json* id = source.find("id"); id && id->is_number() && duo::json_int(destination, "id", 0) <= 0) { + destination["id"] = id->int_or(0); + } +} + +bool normalize_admin_config(duo::Json& config, std::string& error, bool enforceSafety = true) { + if (!config.is_object()) { + error = "configuration must be a JSON object"; + return false; + } + ensure_config_shape(config); + duo::Json& global = ensure_object_member(config, "global"); + global["enabled"] = duo::json_bool(global, "enabled", false); + global["admin_2fa_enabled"] = duo::json_bool(global, "admin_2fa_enabled", false); + global["require_for_all_users"] = duo::json_bool(global, "require_for_all_users", false); + global["fail_closed"] = duo::json_bool(global, "fail_closed", true); + global["otp_length"] = std::clamp(duo::json_int(global, "otp_length", 6), 4, 12); + global["otp_ttl_sec"] = std::clamp(duo::json_int(global, "otp_ttl_sec", 90), 15, 3600); + global["max_attempts"] = std::clamp(duo::json_int(global, "max_attempts", 5), 1, 20); + global["resend_cooldown_sec"] = std::clamp(duo::json_int(global, "resend_cooldown_sec", 30), 0, 3600); + + duo::Json& defaults = ensure_object_member(config, "default_telegram"); + for (const char* key : {"bot_token", "user_id", "group_id"}) { + std::string value = trim_ascii(duo::json_string(defaults, key)); + if (!is_single_line_value(value)) { + error = std::string("default Telegram ") + key + " is invalid"; + return false; + } + defaults[key] = value; + } + + // The administrator UI has its own credential gate. It is deliberately + // part of the protected configuration so an update cannot silently reset + // it. The native web UI never receives password_hash; AdminSave also + // preserves this member from the service-side copy. + duo::Json& adminAuth = ensure_object_member(config, "admin_auth"); + const std::string adminUsername = trim_ascii(duo::json_string(adminAuth, "username")); + const std::string adminPasswordHash = trim_ascii(duo::json_string(adminAuth, "password_hash")); + if ((!adminUsername.empty() || !adminPasswordHash.empty()) + && (adminUsername.empty() || adminPasswordHash.empty() + || !is_single_line_value(adminUsername, 512U) + || !is_single_line_value(adminPasswordHash, 2048U))) { + error = "administrator authentication configuration is invalid"; + return false; + } + adminAuth["username"] = adminUsername; + adminAuth["password_hash"] = adminPasswordHash; + + const duo::Json& sourceUsers = object_member_or_empty(config, "per_user"); + if (!sourceUsers.is_object()) { + error = "per_user must be an object"; + return false; + } + struct Row final { duo::Json data; bool explicitLoginKey = false; }; + std::vector rows; + std::unordered_map indexByIdentity; + for (const auto& [sourceKey, sourceRow] : sourceUsers.object_or_empty()) { + if (!sourceRow.is_object()) { + error = "every user row must be an object"; + return false; + } + duo::Json row = sourceRow; + const std::string login = trim_ascii(duo::json_string(row, "login", sourceKey)); + if (login.empty() || !is_single_line_value(login, 512U)) { + error = "every user row requires a valid login"; + return false; + } + const std::string identity = normalize_identity(login); + if (identity.empty()) { + error = "every user row requires a valid login"; + return false; + } + row["login"] = login; + for (const char* key : {"bot_token", "user_id", "group_id"}) { + const std::string value = trim_ascii(duo::json_string(row, key)); + if (!is_single_line_value(value)) { + error = std::string("invalid user ") + key; + return false; + } + row[key] = value; + } + const std::string totp = normalized_totp_secret(duo::json_string(row, "totp_secret")); + if (!valid_totp_secret(totp)) { + error = "invalid Google Authenticator secret"; + return false; + } + row["totp_secret"] = totp; + duo::Json::Array groups; + std::unordered_set seenGroups; + if (const duo::Json* configuredGroups = row.find("groups"); configuredGroups && configuredGroups->is_array()) { + for (const duo::Json& group : configuredGroups->array_or_empty()) { + if (!group.is_string()) continue; + const std::string name = trim_ascii(group.string_or()); + if (name.empty()) continue; + if (!is_single_line_value(name, 512U)) { + error = "invalid group name"; + return false; + } + const std::string key = normalize_identity(name); + if (!key.empty() && seenGroups.insert(key).second) groups.emplace_back(name); + } + } + row["groups"] = duo::Json(std::move(groups)); + row["verified"] = duo::json_bool(row, "verified", false); + // The former native CLI keyed rows by normalize_username(login), + // while the legacy GUI used numeric keys. Both DOMAIN\\Alice and + // alice therefore identify an explicit CLI mutation; numeric keys do + // not. + const bool explicitLoginKey = normalize_identity(sourceKey) == identity + || normalize_username(sourceKey) == normalize_username(login); + const auto existing = indexByIdentity.find(identity); + if (existing == indexByIdentity.end()) { + indexByIdentity.emplace(identity, rows.size()); + rows.push_back(Row{std::move(row), explicitLoginKey}); + } else { + Row& prior = rows[existing->second]; + const bool preferIncoming = explicitLoginKey && !prior.explicitLoginKey; + if (preferIncoming) { + duo::Json merged = row; + merge_admin_user_row(merged, prior.data, false); + prior.data = std::move(merged); + prior.explicitLoginKey = true; + } else { + merge_admin_user_row(prior.data, row, false); + } + } + } + + int nextId = std::max(1, duo::json_int(config, "next_user_id", 1)); + std::unordered_set knownIds; + for (const Row& row : rows) { + const int id = duo::json_int(row.data, "id", 0); + if (id > 0) { + knownIds.insert(id); + nextId = std::max(nextId, id + 1); + } + } + std::unordered_set assignedIds; + duo::Json::Object rebuilt; + for (Row& row : rows) { + int id = duo::json_int(row.data, "id", 0); + if (id <= 0 || !assignedIds.insert(id).second) { + while (knownIds.contains(nextId) || assignedIds.contains(nextId)) ++nextId; + id = nextId++; + assignedIds.insert(id); + } + row.data["id"] = id; + rebuilt[std::to_string(id)] = std::move(row.data); + } + config["per_user"] = duo::Json(std::move(rebuilt)); + config["next_user_id"] = nextId; + + duo::Json::Array enabledUsers; + duo::Json::Array enabledGroups; + std::unordered_set seenUsers; + std::unordered_set seenGroups; + size_t verifiedUserCount = 0; + for (const auto& [unused, row] : config.find("per_user")->object_or_empty()) { + (void)unused; + if (!duo::json_bool(row, "verified", false)) continue; + ++verifiedUserCount; + const std::string login = duo::json_string(row, "login"); + const std::string identity = normalize_identity(login); + if (!identity.empty() && seenUsers.insert(identity).second) enabledUsers.emplace_back(login); + if (const duo::Json* groups = row.find("groups")) { + for (const duo::Json& group : groups->array_or_empty()) { + const std::string name = group.string_or(); + const std::string key = normalize_identity(name); + if (!key.empty() && seenGroups.insert(key).second) enabledGroups.emplace_back(name); + } + } + } + duo::Json& rules = ensure_object_member(config, "rules"); + rules["enabled_users"] = duo::Json(std::move(enabledUsers)); + rules["enabled_groups"] = duo::Json(std::move(enabledGroups)); + const bool defaultTelegramReady = !duo::json_string(defaults, "bot_token").empty() + && (!duo::json_string(defaults, "user_id").empty() || !duo::json_string(defaults, "group_id").empty()); + // A per-user Telegram/TOTP record is sufficient for an administrator who + // is explicitly configured. Requiring a global Telegram target merely + // because admin-wide 2FA is enabled rejects an existing secure setup and + // prevents its TOTP Verify action from saving. Require-for-all remains a + // different contract: unknown users need a default delivery target. + if (enforceSafety && duo::json_bool(global, "enabled", false) + && duo::json_bool(global, "require_for_all_users", false) + && !defaultTelegramReady) { + error = "Require for all users needs a configured default Telegram target to avoid a sign-in lockout"; + return false; + } + if (enforceSafety && duo::json_bool(global, "enabled", false) && !defaultTelegramReady && verifiedUserCount == 0U) { + error = "enable 2FA only after verifying at least one user, or configure a default Telegram target"; + return false; + } + return true; +} + +bool same_delivery_methods(const Methods& before, const Methods& after) { + return before.token == after.token + && before.userId == after.userId + && before.groupId == after.groupId + && before.totpSecret == after.totpSecret; +} + +void invalidate_unverified_method_changes(const duo::Json& previous, duo::Json& candidate) { + const duo::Json& users = object_member_or_empty(candidate, "per_user"); + duo::Json::Object rebuilt; + for (const auto& [key, source] : users.object_or_empty()) { + duo::Json row = source; + const std::string login = duo::json_string(row, "login"); + const duo::Json* oldRow = find_user_node(previous, login); + const std::string oldGroups = oldRow && oldRow->find("groups") ? oldRow->find("groups")->dump() : "[]"; + const std::string newGroups = row.find("groups") ? row.find("groups")->dump() : "[]"; + if (!oldRow || oldGroups != newGroups || !same_delivery_methods(resolve_methods(previous, login), resolve_methods(candidate, login))) { + row["verified"] = false; + } + rebuilt[key] = std::move(row); + } + candidate["per_user"] = duo::Json(std::move(rebuilt)); +} + +bool set_admin_user_verified(duo::Json& config, const std::string& username, std::string& error) { + const duo::Json& users = object_member_or_empty(config, "per_user"); + duo::Json::Object rebuilt; + bool found = false; + for (const auto& [key, source] : users.object_or_empty()) { + duo::Json row = source; + if (identity_matches(duo::json_string(row, "login"), username)) { + row["verified"] = true; + found = true; + } + rebuilt[key] = std::move(row); + } + if (!found) { + error = "user was not found; save its settings first"; + return false; + } + config["per_user"] = duo::Json(std::move(rebuilt)); + return normalize_admin_config(config, error); +} + std::string mask_target(const std::string& value) { if (value.size() <= 4) return "***"; return "***" + value.substr(value.size() - 4); @@ -1047,14 +1481,373 @@ public: const std::string username = duo::json_string(request, "username"); std::string challengeId; if (!normalize_challenge_id(duo::json_string(request, "challenge_id"), challengeId)) return error("invalid_challenge"); - const std::vector groups = request.find("groups") ? string_array(*request.find("groups")) : std::vector{}; + const std::vector suppliedGroups = request.find("groups") ? string_array(*request.find("groups")) : std::vector{}; + const std::vector groups = resolve_windows_groups(username, suppliedGroups); + // The pipe itself is SYSTEM + local Administrators only. The native + // administrator application adds a credential gate before it can + // read or mutate the protected configuration. The verifier and all + // 2FA settings stay in this one machine-DPAPI protected config. + if (action == "AdminAuthStatus") return admin_auth_status(); + if (action == "AdminAuthenticate") return admin_authenticate(username, duo::json_string(request, "password")); + if (action == "AdminSetup") return admin_setup(username, duo::json_string(request, "password")); + // Recovery is intentionally limited by the pipe DACL to SYSTEM and + // local Administrators. A local Administrator can already replace the + // service/config offline; this gives that same operator a safe path + // which preserves the 2FA policy and all enrolled methods. + if (action == "AdminReset") return admin_reset(username, duo::json_string(request, "password")); + const std::string adminSession = duo::json_string(request, "admin_session"); + if (action == "AdminGet" || action == "AdminSave" || action == "AdminSendTestOtp" || action == "AdminVerifyTestOtp") { + if (!admin_session_valid(adminSession)) return admin_failure("administrator authentication required"); + } + if (action == "AdminGet") return admin_get(); + if (action == "AdminSave") return admin_save(request.find("config")); + if (action == "AdminSendTestOtp") return admin_send_test(username); + if (action == "AdminVerifyTestOtp") return admin_verify_test(username, duo::json_string(request, "code")); if (action == "GetPolicy") return policy(username, groups); if (action == "RequestOtp") return issue(username, groups, challengeId); if (action == "VerifyOtp") return verify(username, duo::json_string(request, "code"), groups, challengeId); return error("service_unavailable"); } + static bool admin_auth_self_test() { + // RFC-compatible Python legacy format: hashlib.pbkdf2_hmac("sha256", + // b"legacy-admin-test", bytes(range(16)), 260000), encoded exactly + // as app/core/security.py did before the native migration. + static constexpr char legacyHash[] = "PBKDF2v1:260000:AAECAwQFBgcICQoLDA0ODw==:Qe5C+2I2PHjLA9JFBSMjBhUzxH7fsRtC39hV6XxORII="; + std::string generated; + return verify_admin_password("legacy-admin-test", legacyHash) + && !verify_admin_password("wrong-password", legacyHash) + && make_admin_password_hash("new-native-admin-password", generated) + && verify_admin_password("new-native-admin-password", generated) + && !verify_admin_password("new-native-admin-password!", generated); + } + private: + static duo::Json admin_failure(const std::string& reason) { + duo::Json::Object result; + result["ok"] = false; + result["error"] = reason; + return duo::Json(std::move(result)); + } + + static bool pbkdf2_sha256(const std::string& password, const std::vector& salt, ULONGLONG iterations, + std::vector& derived) { + if (password.empty() || salt.empty() || iterations < 100000ULL || iterations > 2000000ULL) return false; + BCRYPT_ALG_HANDLE algorithm = nullptr; + const NTSTATUS opened = BCryptOpenAlgorithmProvider(&algorithm, BCRYPT_SHA256_ALGORITHM, nullptr, BCRYPT_ALG_HANDLE_HMAC_FLAG); + if (opened < 0 || !algorithm) return false; + derived.resize(32U); + const NTSTATUS status = BCryptDeriveKeyPBKDF2(algorithm, + reinterpret_cast(const_cast(password.data())), static_cast(password.size()), + const_cast(salt.data()), static_cast(salt.size()), iterations, + derived.data(), static_cast(derived.size()), 0); + BCryptCloseAlgorithmProvider(algorithm, 0); + if (status < 0) { + if (!derived.empty()) SecureZeroMemory(derived.data(), derived.size()); + derived.clear(); + return false; + } + return true; + } + + static bool verify_admin_password(const std::string& password, const std::string& stored) { + static constexpr char prefix[] = "PBKDF2v1:"; + constexpr size_t prefixSize = sizeof(prefix) - 1U; + if (password.empty() || stored.compare(0, prefixSize, prefix) != 0) return false; + const size_t first = stored.find(':', prefixSize); + const size_t second = first == std::string::npos ? std::string::npos : stored.find(':', first + 1U); + if (first == std::string::npos || second == std::string::npos || stored.find(':', second + 1U) != std::string::npos) return false; + const std::string iterationsText = stored.substr(prefixSize, first - prefixSize); + char* end = nullptr; + const unsigned long parsed = std::strtoul(iterationsText.c_str(), &end, 10); + if (!end || *end != '\0' || parsed < 100000UL || parsed > 2000000UL) return false; + std::vector salt; + std::vector expected; + std::vector actual; + if (!base64_decode(stored.substr(first + 1U, second - first - 1U), salt) + || !base64_decode(stored.substr(second + 1U), expected) + || expected.size() != 32U + || !pbkdf2_sha256(password, salt, static_cast(parsed), actual)) { + return false; + } + bool equal = actual.size() == expected.size(); + BYTE difference = 0; + for (size_t index = 0; index < actual.size() && index < expected.size(); ++index) difference |= static_cast(actual[index] ^ expected[index]); + SecureZeroMemory(actual.data(), actual.size()); + SecureZeroMemory(expected.data(), expected.size()); + SecureZeroMemory(salt.data(), salt.size()); + return equal && difference == 0; + } + + static bool make_admin_password_hash(const std::string& password, std::string& stored) { + if (password.size() < 8U || password.size() > 4096U) return false; + std::vector salt(16U); + if (BCryptGenRandom(nullptr, salt.data(), static_cast(salt.size()), BCRYPT_USE_SYSTEM_PREFERRED_RNG) < 0) return false; + std::vector derived; + static constexpr ULONGLONG iterations = 260000ULL; + if (!pbkdf2_sha256(password, salt, iterations, derived)) { + SecureZeroMemory(salt.data(), salt.size()); + return false; + } + std::string salt64; + std::string derived64; + const bool encoded = base64_encode(salt.data(), static_cast(salt.size()), salt64) + && base64_encode(derived.data(), static_cast(derived.size()), derived64); + SecureZeroMemory(salt.data(), salt.size()); + SecureZeroMemory(derived.data(), derived.size()); + if (!encoded) return false; + stored = "PBKDF2v1:" + std::to_string(iterations) + ":" + salt64 + ":" + derived64; + return true; + } + + std::string create_admin_session() { + BYTE bytes[32]{}; + if (BCryptGenRandom(nullptr, bytes, sizeof(bytes), BCRYPT_USE_SYSTEM_PREFERRED_RNG) < 0) return {}; + static constexpr char hex[] = "0123456789abcdef"; + std::string token; + token.reserve(sizeof(bytes) * 2U); + for (BYTE value : bytes) { + token.push_back(hex[(value >> 4U) & 0x0fU]); + token.push_back(hex[value & 0x0fU]); + } + std::lock_guard lock(adminSessionMutex_); + const std::int64_t now = unix_seconds(); + for (auto it = adminSessions_.begin(); it != adminSessions_.end();) { + if (it->second <= now) it = adminSessions_.erase(it); + else ++it; + } + adminSessions_[token] = now + 15 * 60; + return token; + } + + bool admin_session_valid(const std::string& token) { + if (token.size() != 64U) return false; + std::lock_guard lock(adminSessionMutex_); + const std::int64_t now = unix_seconds(); + for (auto it = adminSessions_.begin(); it != adminSessions_.end();) { + if (it->second <= now) it = adminSessions_.erase(it); + else ++it; + } + const auto it = adminSessions_.find(token); + if (it == adminSessions_.end()) return false; + it->second = now + 15 * 60; // idle timeout, refreshed only by an authenticated request + return true; + } + + duo::Json admin_auth_status() { + std::lock_guard lock(adminMutex_); + ConfigRead current = load_config(); + if (!current.error.empty()) return admin_failure(current.error); + std::string error; + if (!normalize_admin_config(current.value, error, false)) return admin_failure(error); + const duo::Json& auth = object_member_or_empty(current.value, "admin_auth"); + duo::Json::Object result; + result["ok"] = true; + result["configured"] = !duo::json_string(auth, "username").empty() && !duo::json_string(auth, "password_hash").empty(); + return duo::Json(std::move(result)); + } + + duo::Json admin_authenticate(const std::string& username, const std::string& password) { + std::lock_guard lock(adminMutex_); + ConfigRead current = load_config(); + if (!current.error.empty()) return admin_failure(current.error); + std::string error; + if (!normalize_admin_config(current.value, error, false)) return admin_failure(error); + const duo::Json& auth = object_member_or_empty(current.value, "admin_auth"); + const std::string expectedUsername = duo::json_string(auth, "username"); + const std::string expectedHash = duo::json_string(auth, "password_hash"); + if (expectedUsername.empty() || expectedHash.empty()) return admin_failure("administrator setup is required"); + if (!identity_matches(expectedUsername, username) || !verify_admin_password(password, expectedHash)) { + log_line("Admin", "administrator authentication rejected"); + return admin_failure("invalid administrator login or password"); + } + const std::string session = create_admin_session(); + if (session.empty()) return admin_failure("cannot create administrator session"); + duo::Json::Object result; + result["ok"] = true; + result["admin_session"] = session; + result["message"] = "Administrator authenticated."; + log_line("Admin", "administrator authenticated"); + return duo::Json(std::move(result)); + } + + duo::Json admin_setup(const std::string& username, const std::string& password) { + const std::string normalizedUsername = trim_ascii(username); + if (normalizedUsername.empty() || !is_single_line_value(normalizedUsername, 512U)) return admin_failure("administrator login is invalid"); + std::string passwordHash; + if (!make_admin_password_hash(password, passwordHash)) return admin_failure("administrator password must be 8 to 4096 characters"); + std::lock_guard lock(adminMutex_); + ConfigRead current = load_config(); + if (!current.error.empty()) return admin_failure(current.error); + std::string error; + if (!normalize_admin_config(current.value, error, false)) return admin_failure(error); + const duo::Json& existing = object_member_or_empty(current.value, "admin_auth"); + if (!duo::json_string(existing, "username").empty() || !duo::json_string(existing, "password_hash").empty()) { + return admin_failure("administrator access is already configured"); + } + duo::Json& auth = ensure_object_member(current.value, "admin_auth"); + auth["username"] = normalizedUsername; + auth["password_hash"] = passwordHash; + if (!save_config(current.value, error)) return admin_failure("cannot save administrator access: " + error); + const std::string session = create_admin_session(); + if (session.empty()) return admin_failure("administrator access saved but session creation failed"); + duo::Json::Object result; + result["ok"] = true; + result["admin_session"] = session; + result["message"] = "Administrator access configured."; + log_line("Admin", "administrator access configured"); + return duo::Json(std::move(result)); + } + + duo::Json admin_reset(const std::string& username, const std::string& password) { + const std::string normalizedUsername = trim_ascii(username); + if (normalizedUsername.empty() || !is_single_line_value(normalizedUsername, 512U)) return admin_failure("administrator login is invalid"); + std::string passwordHash; + if (!make_admin_password_hash(password, passwordHash)) return admin_failure("administrator password must be 8 to 4096 characters"); + std::lock_guard lock(adminMutex_); + ConfigRead current = load_config(); + if (!current.error.empty()) return admin_failure(current.error); + std::string error; + if (!normalize_admin_config(current.value, error, false)) return admin_failure(error); + duo::Json& auth = ensure_object_member(current.value, "admin_auth"); + auth["username"] = normalizedUsername; + auth["password_hash"] = passwordHash; + if (!save_config(current.value, error)) return admin_failure("cannot reset administrator access: " + error); + const std::string session = create_admin_session(); + if (session.empty()) return admin_failure("administrator access reset but session creation failed"); + duo::Json::Object result; + result["ok"] = true; + result["admin_session"] = session; + result["message"] = "Administrator access reset. 2FA settings were preserved."; + log_line("Admin", "administrator access reset by local administrator"); + return duo::Json(std::move(result)); + } + + static duo::Json admin_success(duo::Json config, bool exists, const char* message) { + const duo::Json& auth = object_member_or_empty(config, "admin_auth"); + duo::Json::Object publicAuth; + publicAuth["configured"] = !duo::json_string(auth, "username").empty() + && !duo::json_string(auth, "password_hash").empty(); + // The native GUI only needs to know whether a credential exists. + // Keep the verifier in the service-side config so ordinary setting + // saves can never replace it. + config["admin_auth"] = duo::Json(std::move(publicAuth)); + duo::Json::Object result; + result["ok"] = true; + result["exists"] = exists; + result["message"] = message; + result["config"] = std::move(config); + return duo::Json(std::move(result)); + } + + duo::Json admin_get() { + std::lock_guard lock(adminMutex_); + ConfigRead current = load_config(); + if (!current.error.empty()) return admin_failure(current.error); + std::string error; + if (!normalize_admin_config(current.value, error, false)) return admin_failure(error); + return admin_success(std::move(current.value), current.exists, current.exists ? "Settings loaded." : "No settings file yet - save to create a protected native configuration."); + } + + duo::Json admin_save(const duo::Json* requested) { + if (!requested) return admin_failure("configuration payload is missing"); + std::lock_guard lock(adminMutex_); + ConfigRead previous = load_config(); + if (!previous.error.empty()) return admin_failure(previous.error); + duo::Json config = *requested; + std::string error; + if (previous.exists) { + if (!normalize_admin_config(previous.value, error, false)) return admin_failure(error); + // The UI payload must not reset or replace the login gate. Only + // the first-run AdminSetup operation may create credentials. + if (const duo::Json* adminAuth = previous.value.find("admin_auth")) config["admin_auth"] = *adminAuth; + if (!normalize_admin_config(config, error)) return admin_failure(error); + invalidate_unverified_method_changes(previous.value, config); + if (!normalize_admin_config(config, error)) return admin_failure(error); + } else { + if (!normalize_admin_config(config, error)) return admin_failure(error); + // A newly-created row can never be pre-verified merely by a GUI + // payload. It becomes active only after Telegram/TOTP proof. + invalidate_unverified_method_changes(default_config(), config); + if (!normalize_admin_config(config, error)) return admin_failure(error); + } + if (!save_config(config, error)) return admin_failure("cannot save configuration: " + error); + log_line("Admin", "settings saved by local administrator"); + return admin_success(std::move(config), true, "Settings saved. Changes apply to the next sign-in request."); + } + + duo::Json admin_send_test(const std::string& username) { + if (trim_ascii(username).empty()) return admin_failure("select a user first"); + std::lock_guard lock(adminMutex_); + ConfigRead current = load_config(); + if (!current.error.empty()) return admin_failure(current.error); + std::string shapeError; + if (!normalize_admin_config(current.value, shapeError, false)) return admin_failure(shapeError); + if (!find_user_node(current.value, username)) return admin_failure("user was not found; save its settings first"); + const Methods methods = resolve_methods(current.value, username); + if (!methods.configured()) return admin_failure("configure Telegram or Google Authenticator first"); + const duo::Json& global = object_member_or_empty(current.value, "global"); + const int ttl = std::clamp(duo::json_int(global, "otp_ttl_sec", 90), 15, 3600); + const int attempts = std::clamp(duo::json_int(global, "max_attempts", 5), 1, 20); + if (!methods.telegram()) { + duo::Json::Object result; + result["ok"] = true; + result["status"] = "totp_ready"; + result["message"] = "Enter the current Google Authenticator code, then press Verify."; + return duo::Json(std::move(result)); + } + const std::string code = random_digits(duo::json_int(global, "otp_length", 6)); + const std::string text = computer_name() + "\nDUO-RDP settings verification (TTL " + std::to_string(ttl) + "s)\n" + username + "\n" + code; + int sent = 0; + for (const std::string& target : {methods.userId, methods.groupId}) { + if (target.empty()) continue; + std::string reason; + if (telegram_send(methods.token, target, text, reason)) ++sent; + else log_line("Admin", "Telegram verification send failed reason=" + reason + " target=" + mask_target(target)); + } + if (sent == 0) { + if (methods.totp()) { + duo::Json::Object result; + result["ok"] = true; + result["status"] = "totp_ready"; + result["message"] = "Telegram delivery failed; enter the current Google Authenticator code, then press Verify."; + return duo::Json(std::move(result)); + } + return admin_failure("Telegram did not accept the message"); + } + adminTestStore_.replace(username, "", code, ttl, attempts); + log_line("Admin", "verification code sent ttl=" + std::to_string(ttl)); + duo::Json::Object result; + result["ok"] = true; + result["status"] = "sent"; + result["ttl"] = ttl; + result["message"] = "Verification code sent. Enter it and press Verify."; + return duo::Json(std::move(result)); + } + + duo::Json admin_verify_test(const std::string& username, const std::string& code) { + if (trim_ascii(username).empty()) return admin_failure("select a user first"); + std::lock_guard lock(adminMutex_); + ConfigRead current = load_config(); + if (!current.error.empty()) return admin_failure(current.error); + std::string shapeError; + if (!normalize_admin_config(current.value, shapeError)) return admin_failure(shapeError); + if (!find_user_node(current.value, username)) return admin_failure("user was not found; save its settings first"); + const Methods methods = resolve_methods(current.value, username); + bool verified = methods.totp() && verify_totp(methods.totpSecret, code); + std::string reason; + if (!verified) { + const duo::Json test = adminTestStore_.verify(username, "", code); + verified = duo::json_bool(test, "ok", false); + reason = duo::json_string(test, "reason", "invalid_code"); + } + if (!verified) return admin_failure(reason); + if (!set_admin_user_verified(current.value, username, shapeError)) return admin_failure(shapeError); + if (!save_config(current.value, shapeError)) return admin_failure("cannot save verified settings: " + shapeError); + log_line("Admin", "2FA method verified for configured user"); + return admin_success(std::move(current.value), true, "2FA settings verified and enabled for this user."); + } + duo::Json policy(const std::string& username, const std::vector& groups) { const ConfigRead config = load_config(); if (!config.error.empty()) return error("policy_error"); @@ -1154,6 +1947,10 @@ private: } OtpStore store_; + OtpStore adminTestStore_; + std::mutex adminMutex_; + std::mutex adminSessionMutex_; + std::unordered_map adminSessions_; }; bool pipe_overlapped_io(HANDLE pipe, void* buffer, DWORD size, DWORD& transferred, bool write) { @@ -1315,6 +2112,80 @@ bool run_self_test() { return true; } +bool run_admin_config_self_test() { + duo::Json config = default_config(); + duo::Json::Object legacy; + legacy["id"] = 1; + legacy["login"] = "DOMAIN\\Alice"; + legacy["groups"] = duo::Json::Array{duo::Json("Remote Desktop Users")}; + legacy["bot_token"] = "old-token"; + legacy["user_id"] = "100"; + legacy["group_id"] = ""; + legacy["totp_secret"] = ""; + legacy["verified"] = true; + duo::Json::Object cli; + cli["login"] = "DOMAIN\\Alice"; + cli["bot_token"] = "new-token"; + cli["user_id"] = "100"; + cli["verified"] = false; + duo::Json::Object users; + users["1"] = duo::Json(std::move(legacy)); + users["alice"] = duo::Json(std::move(cli)); + config["per_user"] = duo::Json(std::move(users)); + std::string error; + if (!normalize_admin_config(config, error)) { + std::fprintf(stderr, "ADMIN SELFTEST FAIL: normalize %s\n", error.c_str()); + return false; + } + const duo::Json& normalizedUsers = object_member_or_empty(config, "per_user"); + const duo::Json* row = find_user_node(config, "DOMAIN\\Alice"); + const bool deduplicated = normalizedUsers.object_or_empty().size() == 1U + && row && duo::json_string(*row, "bot_token") == "new-token" + && duo::json_string(*row, "groups").empty() + && !duo::json_bool(*row, "verified", true); + // The group is an array, so check it separately instead of treating it as + // a scalar. It must survive a token-only legacy CLI update. + const bool groupsPreserved = row && row->find("groups") && row->find("groups")->array_or_empty().size() == 1U; + duo::Json changed = config; + if (duo::Json* changedRow = changed.find("per_user")->find("1")) { + (*changedRow)["bot_token"] = "another-token"; + (*changedRow)["verified"] = true; + } + invalidate_unverified_method_changes(config, changed); + const duo::Json* changedRow = find_user_node(changed, "DOMAIN\\Alice"); + const bool invalidated = changedRow && !duo::json_bool(*changedRow, "verified", true); + const std::vector suppliedGroups{"Administrators", "administrators"}; + const std::vector resolvedGroups = resolve_windows_groups("", suppliedGroups); + const bool suppliedGroupsPreserved = resolvedGroups.size() == 1U && is_admin_group(resolvedGroups.front()); + duo::Json perUserAdminOnly = default_config(); + duo::Json& perUserGlobal = ensure_object_member(perUserAdminOnly, "global"); + perUserGlobal["enabled"] = true; + perUserGlobal["admin_2fa_enabled"] = true; + duo::Json::Object perUserRow; + perUserRow["id"] = 1; + perUserRow["login"] = "DOMAIN\\Admin"; + perUserRow["groups"] = duo::Json::Array{}; + perUserRow["bot_token"] = ""; + perUserRow["user_id"] = ""; + perUserRow["group_id"] = ""; + perUserRow["totp_secret"] = "JBSWY3DPEHPK3PXP"; + perUserRow["verified"] = true; + duo::Json::Object perUserRows; + perUserRows["1"] = duo::Json(std::move(perUserRow)); + perUserAdminOnly["per_user"] = duo::Json(std::move(perUserRows)); + std::string perUserError; + const bool perUserAdminAccepted = normalize_admin_config(perUserAdminOnly, perUserError); + ensure_object_member(perUserAdminOnly, "global")["require_for_all_users"] = true; + const bool requireAllRejected = !normalize_admin_config(perUserAdminOnly, perUserError); + const bool adminAuthCompatible = AuthCore::admin_auth_self_test(); + if (!deduplicated || !groupsPreserved || !invalidated || !suppliedGroupsPreserved || !perUserAdminAccepted || !requireAllRejected || !adminAuthCompatible) { + std::fprintf(stderr, "ADMIN SELFTEST FAIL deduplicated=%d groupsPreserved=%d invalidated=%d suppliedGroups=%d perUserAdmin=%d requireAll=%d adminAuth=%d\n", deduplicated ? 1 : 0, groupsPreserved ? 1 : 0, invalidated ? 1 : 0, suppliedGroupsPreserved ? 1 : 0, perUserAdminAccepted ? 1 : 0, requireAllRejected ? 1 : 0, adminAuthCompatible ? 1 : 0); + return false; + } + std::puts("ADMIN SELFTEST PASS: numeric legacy rows are deduplicated, current values win, changed delivery methods lose verification, per-user admin 2FA is accepted, require-all still needs a default target, Windows groups are canonicalized, and legacy PBKDF2 admin credentials remain compatible."); + return true; +} + bool pipe_exchange_for_test(const duo::Json& request, duo::Json& response) { HANDLE pipe = INVALID_HANDLE_VALUE; for (int attempt = 0; attempt < 100; ++attempt) { @@ -1443,6 +2314,7 @@ int wmain(int argc, wchar_t** argv) { return run_admin(args); } if (argc > 1 && std::wstring_view(argv[1]) == L"--self-test") return run_self_test() ? 0 : 1; + if (argc > 1 && std::wstring_view(argv[1]) == L"--admin-self-test") return run_admin_config_self_test() ? 0 : 1; if (argc > 1 && std::wstring_view(argv[1]) == L"--pipe-self-test") return run_pipe_self_test() ? 0 : 1; if (argc > 1 && std::wstring_view(argv[1]) == L"--console") return run_console(); SERVICE_TABLE_ENTRYW table[] = { diff --git a/native/cpp/DuoRdpInstaller.cpp b/native/cpp/DuoRdpInstaller.cpp index 8aceb33..4f278c7 100644 --- a/native/cpp/DuoRdpInstaller.cpp +++ b/native/cpp/DuoRdpInstaller.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include @@ -351,6 +352,10 @@ int install(const std::wstring& payloadDirectory) { return 1; } std::wprintf(L"DUO-RDP native C++ installation complete: %s\n", installDirectory.c_str()); + const HINSTANCE launched = ShellExecuteW(nullptr, L"open", (installDirectory + L"\\DuoRdpAdmin.exe").c_str(), nullptr, installDirectory.c_str(), SW_SHOWNORMAL); + if (reinterpret_cast(launched) <= 32) { + std::fwprintf(stderr, L"Installation is complete, but open DuoRdpAdmin.exe manually (ShellExecute error=%lld).\n", static_cast(reinterpret_cast(launched))); + } return 0; } diff --git a/native/cpp/README.md b/native/cpp/README.md index 3350369..5e60b41 100644 --- a/native/cpp/README.md +++ b/native/cpp/README.md @@ -1,13 +1,91 @@ -# Native C++ runtime +# DUO-RDP native C++ release -Этот каталог - canonical source для текущего DUO-RDP native release. Он заменяет прежний C#/Python broker, HTTP OTP service, PyInstaller GUI-admin и installer chain. +This directory is the native replacement for the former C# pipe broker, Python +OTP HTTP server, Python admin UI and PyInstaller installer chain. -- `DuoRdpAuthService.exe` - Windows service и единственный OTP runtime. Он обслуживает `\\.\pipe\duordp-auth-pipe` по JSONL protocol v2, хранит OTP-сессии в памяти, отправляет Telegram через WinHTTP, проверяет TOTP и читает machine-DPAPI конфиг. -- `DuoRdpAdmin.exe` - launcher для `DuoRdpAuthService.exe --admin`; токен передаётся только через `--token-stdin`. -- `DuoRdpInstaller.exe` и `DUOUnIstall.exe` - native installer/recovery. Installer проверяет DLL, конфиг, service и live pipe до регистрации Filter. Uninstaller сначала снимает Filter и по умолчанию сохраняет config/logs. +- `DuoRdpAuthService.exe` is a Windows service and the sole OTP runtime. + It keeps the existing `\\.\pipe\duordp-auth-pipe` JSONL v1 contract used by + the Credential Provider. It reads the existing machine-DPAPI configuration + format, sends Telegram messages with WinHTTP, verifies TOTP and stores OTP + sessions in-process. +- `DuoRdpAdmin.exe` is a native Win32 settings application. It self-elevates + with UAC, then talks to the service through its Administrator/SYSTEM-only + named pipe. The GUI never reads the DPAPI configuration directly. On its + first launch it asks for an administrator login and the same password twice; + later launches require that login and password before any 2FA value is read. + The password is stored only as a salted PBKDF2 verifier inside the same + machine-DPAPI protected config.json. + It manages users and groups, per-user/default Telegram targets, TOTP + generation, Telegram/TOTP proof, global rules and OTP limits. +- `DuoRdpInstaller.exe` and `DUOUnIstall.exe` are native installer/recovery + tools. The installer validates the DLL, starts and checks the pipe before it + enables the Credential Provider Filter. The uninstaller removes the filter + first and preserves config/logs unless `--purge-data` is explicit. -Каждый явный `RequestOtp` заменяет запись конкретной плитки. Старый код этой плитки перестаёт работать немедленно; коды параллельных плиток не конфликтуют. Login-submit код сам не отправляет. +Manual resend semantics are intentional and testable: every `RequestOtp` from +the explicit Credential Provider button creates a replacement record. The +previous code is invalid immediately. Automatic Login-submit still sends at +most one initial code per user/tile; it tells the user to use the explicit +`Отправить новый одноразовый код` command for a new code. -Legacy `ENCv1` config намеренно блокируется до любых изменений: сначала его нужно мигрировать старым admin tool, затем ставить native release. Это предотвращает fail-closed lockout. +The native release reads plaintext and machine-DPAPI (`ENCdpapi`) configs. An +existing legacy `ENCv1` config is intentionally rejected by the installer +*before* it changes a service or enables the Credential Provider Filter. Migrate +that config once with the old administration tool, then install the native +release; this gate prevents a fail-closed login lockout. -Инструкции: [сборка](../../docs/BUILD.md), [установка](../../docs/INSTALL.md), [проверка](../../docs/TESTING.md), [protocol](../../docs/PROTOCOL.md). +Every native GUI save writes a timestamped encrypted `config_*.json` backup +beside the active configuration before an atomic replacement. Changing a +user's Telegram token/target, TOTP secret or groups invalidates its verified +state; it becomes active again only after a real Telegram or TOTP proof. +Legacy numeric-ID and login-key duplicates are canonicalized into one numeric +row, so a stale token cannot win by map ordering. +When Credential Provider group discovery is incomplete, the service also +resolves local and global Windows group memberships before applying group +rules. + +## Configure + +1. Run `C:\Program Files\DuoRdp\DuoRdpAdmin.exe` as a local Administrator. +2. On the first opening, enter the administrator login and password twice. + On every later opening, enter that login and password once. +3. Add a user row, Telegram token/target and/or a TOTP secret. Use + **Generate TOTP** when needed. +4. Click **Apply row**, then **Save settings**. +5. Click **Send test**, enter the last received Telegram code (or the current + TOTP code), and click **Verify**. +6. Enable global 2FA only after at least one required row shows Verified. + +The native window displays configured Telegram values and Google Authenticator +keys after administrator authentication; it does not mask them with asterisks. + +The old `--admin` CLI remains only for scripted inspection and limited edits. +It no longer has a fake `--verify` switch; verification must happen through +the GUI proof flow. + +## Build + +MSVC 2022 / Windows SDK: + +```powershell +cmake -S . -B build -A x64 +cmake --build build --config Release +``` + +The included `scripts/mingw64-toolchain.cmake` supports a reproducible +cross-build on Linux with `x86_64-w64-mingw32-g++`. + +## Acceptance checks + +Run on Windows before any install: + +```text +DuoRdpAuthService.exe --self-test +DuoRdpAuthService.exe --admin-self-test +DuoRdpAuthService.exe --pipe-self-test +DuoRdpInstaller.exe --self-test +``` + +Do not register the Credential Provider Filter until the service and the pipe +health check pass. A broken filter can remove the normal password tile from the +logon screen.