#ifndef UNICODE #define UNICODE #endif #ifndef _UNICODE #define _UNICODE #endif #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 { 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::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); } 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 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; } 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; } 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); }