Files
DUO-RDP/native/cpp/DuoRdpAuthService.cpp
T

1459 lines
62 KiB
C++

#ifndef UNICODE
#define UNICODE
#endif
#ifndef _UNICODE
#define _UNICODE
#endif
#include <windows.h>
#include <sddl.h>
#include <wincrypt.h>
#include <winhttp.h>
#include <bcrypt.h>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cstdint>
#include <cstring>
#include <cstdio>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <memory>
#include <mutex>
#include <optional>
#include <sstream>
#include <stdexcept>
#include <string>
#include <thread>
#include <unordered_map>
#include <utility>
#include <vector>
#include "mini_json.hpp"
#ifdef _MSC_VER
#pragma comment(lib, "advapi32.lib")
#pragma comment(lib, "bcrypt.lib")
#pragma comment(lib, "crypt32.lib")
#pragma comment(lib, "winhttp.lib")
#endif
namespace {
constexpr wchar_t kServiceName[] = L"DuoRdpAuthService";
constexpr wchar_t kPipeName[] = L"\\\\.\\pipe\\duordp-auth-pipe";
constexpr size_t kMaxPipeMessage = 64U * 1024U;
constexpr char kConfigPrefix[] = "DUORDP_CONFIG_V1:";
constexpr char kDpapiPrefix[] = "ENCdpapi:";
std::mutex g_logMutex;
HANDLE g_stopEvent = nullptr;
SERVICE_STATUS_HANDLE g_serviceHandle = nullptr;
SERVICE_STATUS g_serviceStatus{};
std::wstring g_configPathOverride;
std::string wide_to_utf8(const std::wstring& value) {
if (value.empty()) return {};
const int bytes = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, value.data(), static_cast<int>(value.size()), nullptr, 0, nullptr, nullptr);
if (bytes <= 0) return {};
std::string out(static_cast<size_t>(bytes), '\0');
WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, value.data(), static_cast<int>(value.size()), out.data(), bytes, nullptr, nullptr);
return out;
}
std::wstring utf8_to_wide(const std::string& value) {
if (value.empty()) return {};
const int chars = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, value.data(), static_cast<int>(value.size()), nullptr, 0);
if (chars <= 0) return {};
std::wstring out(static_cast<size_t>(chars), L'\0');
MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, value.data(), static_cast<int>(value.size()), out.data(), chars);
return out;
}
std::wstring trim_wide(std::wstring value) {
const auto first = std::find_if_not(value.begin(), value.end(), [](wchar_t c) { return iswspace(c) != 0; });
const auto last = std::find_if_not(value.rbegin(), value.rend(), [](wchar_t c) { return iswspace(c) != 0; }).base();
return first >= last ? std::wstring{} : std::wstring(first, last);
}
std::string trim_ascii(std::string value) {
const auto first = std::find_if_not(value.begin(), value.end(), [](unsigned char c) { return std::isspace(c) != 0; });
const auto last = std::find_if_not(value.rbegin(), value.rend(), [](unsigned char c) { return std::isspace(c) != 0; }).base();
return first >= last ? std::string{} : std::string(first, last);
}
std::wstring program_data_dir() {
wchar_t buffer[MAX_PATH]{};
const DWORD length = GetEnvironmentVariableW(L"ProgramData", buffer, ARRAYSIZE(buffer));
if (length > 0 && length < ARRAYSIZE(buffer)) return std::wstring(buffer);
return L"C:\\ProgramData";
}
std::wstring program_files_dir() {
wchar_t buffer[MAX_PATH]{};
const DWORD length = GetEnvironmentVariableW(L"ProgramFiles", buffer, ARRAYSIZE(buffer));
if (length > 0 && length < ARRAYSIZE(buffer)) return std::wstring(buffer);
return L"C:\\Program Files";
}
std::wstring module_dir() {
std::vector<wchar_t> path(32768U, L'\0');
const DWORD length = GetModuleFileNameW(nullptr, path.data(), static_cast<DWORD>(path.size()));
if (length == 0 || length >= path.size()) return {};
std::wstring value(path.data(), length);
const size_t slash = value.find_last_of(L"\\/");
return slash == std::wstring::npos ? std::wstring{} : value.substr(0, slash);
}
void ensure_directory(const std::wstring& directory) {
if (directory.empty()) return;
std::wstring current;
size_t start = 0;
if (directory.size() >= 2 && directory[1] == L':') {
current.assign(directory, 0, 2);
start = 2;
if (start < directory.size() && (directory[start] == L'\\' || directory[start] == L'/')) ++start;
}
while (start < directory.size()) {
const size_t end = directory.find_first_of(L"\\/", start);
const std::wstring piece = directory.substr(start, end == std::wstring::npos ? std::wstring::npos : end - start);
if (!piece.empty()) {
if (current.empty()) current = piece;
else if (current.size() == 2 && current[1] == L':') current += L"\\" + piece;
else current += L"\\" + piece;
if (!current.empty() && current.back() != L':') CreateDirectoryW(current.c_str(), nullptr);
}
if (end == std::wstring::npos) break;
start = end + 1;
}
}
std::string timestamp_utc() {
SYSTEMTIME time{};
GetSystemTime(&time);
char out[32]{};
std::snprintf(out, sizeof(out), "%04u-%02u-%02u %02u:%02u:%02u", time.wYear, time.wMonth, time.wDay, time.wHour, time.wMinute, time.wSecond);
return out;
}
void log_line(const std::string& component, const std::string& message) {
std::lock_guard lock(g_logMutex);
const std::wstring directory = program_data_dir() + L"\\DuoRdp";
ensure_directory(directory);
const std::wstring path = directory + L"\\logs.txt";
FILE* file = _wfopen(path.c_str(), L"ab");
if (!file) return;
const std::string line = "[" + timestamp_utc() + "] [" + component + "] [pid=" + std::to_string(GetCurrentProcessId()) + "] " + message + "\r\n";
std::fwrite(line.data(), 1, line.size(), file);
std::fclose(file);
}
bool read_file_utf8(const std::wstring& path, std::string& out) {
out.clear();
FILE* file = _wfopen(path.c_str(), L"rb");
if (!file) return false;
if (std::fseek(file, 0, SEEK_END) != 0) {
std::fclose(file);
return false;
}
const long length = std::ftell(file);
if (length < 0 || length > 16L * 1024L * 1024L) {
std::fclose(file);
return false;
}
std::rewind(file);
out.resize(static_cast<size_t>(length));
const size_t read = out.empty() ? 0 : std::fread(out.data(), 1, out.size(), file);
std::fclose(file);
if (read != out.size()) {
out.clear();
return false;
}
if (out.size() >= 3 && static_cast<unsigned char>(out[0]) == 0xefU && static_cast<unsigned char>(out[1]) == 0xbbU && static_cast<unsigned char>(out[2]) == 0xbfU) {
out.erase(0, 3);
}
return true;
}
bool restrict_config_acl(const std::wstring& path, std::string& error) {
PSECURITY_DESCRIPTOR descriptor = nullptr;
if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(L"D:P(A;;FA;;;SY)(A;;FA;;;BA)", SDDL_REVISION_1, &descriptor, nullptr)) {
error = "cannot create config ACL";
return false;
}
const BOOL protectedFile = SetFileSecurityW(path.c_str(), DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION, descriptor);
LocalFree(descriptor);
if (!protectedFile) {
error = "cannot protect config ACL";
return false;
}
return true;
}
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);
const std::wstring temporary = path + L".new";
FILE* file = _wfopen(temporary.c_str(), L"wb");
if (!file) {
error = "cannot open config for writing";
return false;
}
const bool written = data.empty() || std::fwrite(data.data(), 1, data.size(), file) == data.size();
const bool closed = std::fclose(file) == 0;
if (!written || !closed) {
DeleteFileW(temporary.c_str());
error = "cannot write config";
return false;
}
if (!restrict_config_acl(temporary, error)) {
DeleteFileW(temporary.c_str());
return false;
}
if (!MoveFileExW(temporary.c_str(), path.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) {
DeleteFileW(temporary.c_str());
error = "cannot replace config";
return false;
}
return true;
}
std::wstring configured_config_path() {
if (!g_configPathOverride.empty()) return g_configPathOverride;
wchar_t configured[32768]{};
const DWORD size = GetEnvironmentVariableW(L"DUO_RDP_CONFIG", configured, ARRAYSIZE(configured));
if (size > 0 && size < ARRAYSIZE(configured)) return configured;
const std::wstring beside_exe = module_dir() + L"\\config.json";
if (GetFileAttributesW(beside_exe.c_str()) != INVALID_FILE_ATTRIBUTES) return beside_exe;
return program_files_dir() + L"\\DuoRdp\\config.json";
}
duo::Json default_config() {
duo::Json::Object global;
global["enabled"] = false;
global["admin_2fa_enabled"] = false;
global["require_for_all_users"] = false;
global["fail_closed"] = true;
global["otp_length"] = 6;
global["otp_ttl_sec"] = 90;
global["max_attempts"] = 5;
global["resend_cooldown_sec"] = 30;
duo::Json::Object telegram;
telegram["bot_token"] = "";
telegram["user_id"] = "";
telegram["group_id"] = "";
duo::Json::Object rules;
rules["enabled_users"] = duo::Json::Array{};
rules["enabled_groups"] = duo::Json::Array{};
duo::Json::Object root;
root["version"] = 1;
root["global"] = duo::Json(std::move(global));
root["default_telegram"] = duo::Json(std::move(telegram));
root["rules"] = duo::Json(std::move(rules));
root["per_user"] = duo::Json::Object{};
root["next_user_id"] = 1;
root["admin_auth"] = duo::Json::Object{};
return duo::Json(std::move(root));
}
bool base64_decode(const std::string& encoded, std::vector<BYTE>& bytes) {
DWORD size = 0;
if (!CryptStringToBinaryA(encoded.c_str(), static_cast<DWORD>(encoded.size()), CRYPT_STRING_BASE64, nullptr, &size, nullptr, nullptr) || size == 0) return false;
bytes.resize(size);
return CryptStringToBinaryA(encoded.c_str(), static_cast<DWORD>(encoded.size()), CRYPT_STRING_BASE64, bytes.data(), &size, nullptr, nullptr) != FALSE;
}
bool base64_encode(const BYTE* bytes, DWORD count, std::string& encoded) {
DWORD size = 0;
if (!CryptBinaryToStringA(bytes, count, CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, nullptr, &size)) return false;
encoded.resize(size);
if (!CryptBinaryToStringA(bytes, count, CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, encoded.data(), &size)) return false;
if (!encoded.empty() && encoded.back() == '\0') encoded.pop_back();
return true;
}
bool decrypt_dpapi_config(const std::string& encoded, std::string& plain, std::string& error) {
std::vector<BYTE> encrypted;
if (!base64_decode(encoded, encrypted)) {
error = "DPAPI config base64 decode failed";
return false;
}
DATA_BLOB source{};
source.cbData = static_cast<DWORD>(encrypted.size());
source.pbData = encrypted.data();
DATA_BLOB result{};
if (!CryptUnprotectData(&source, nullptr, nullptr, nullptr, nullptr, 0, &result)) {
error = "DPAPI config decrypt failed";
return false;
}
plain.assign(reinterpret_cast<const char*>(result.pbData), result.cbData);
LocalFree(result.pbData);
return true;
}
bool encrypt_dpapi_config(const std::string& plain, std::string& encoded, std::string& error) {
DATA_BLOB source{};
source.cbData = static_cast<DWORD>(plain.size());
source.pbData = reinterpret_cast<BYTE*>(const_cast<char*>(plain.data()));
DATA_BLOB result{};
if (!CryptProtectData(&source, L"DUO-RDP configuration", nullptr, nullptr, nullptr, CRYPTPROTECT_LOCAL_MACHINE, &result)) {
error = "DPAPI config encrypt failed";
return false;
}
const bool ok = base64_encode(result.pbData, result.cbData, encoded);
LocalFree(result.pbData);
if (!ok) error = "DPAPI config base64 encode failed";
return ok;
}
struct ConfigRead final {
duo::Json value = default_config();
bool exists = false;
std::string error;
};
ConfigRead load_config() {
ConfigRead result;
const std::wstring path = configured_config_path();
std::string raw;
if (!read_file_utf8(path, raw)) {
log_line("Config", "config missing; using disabled defaults");
return result;
}
result.exists = true;
raw = trim_ascii(std::move(raw));
try {
if (raw.rfind(kConfigPrefix, 0) == 0) {
const std::string payload = raw.substr(sizeof(kConfigPrefix) - 1U);
if (payload.rfind(kDpapiPrefix, 0) != 0) {
result.error = "unsupported legacy encrypted config; migrate it with the previous DUO-RDP admin";
return result;
}
std::string plain;
if (!decrypt_dpapi_config(payload.substr(sizeof(kDpapiPrefix) - 1U), plain, result.error)) return result;
result.value = duo::Json::parse(plain);
} else {
result.value = duo::Json::parse(raw.empty() ? "{}" : raw);
}
if (!result.value.is_object()) throw std::runtime_error("root is not an object");
result.error.clear();
} catch (const std::exception& exc) {
result.error = std::string("invalid config: ") + exc.what();
}
return result;
}
[[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;
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);
bool identity_matches(const std::string& configured, const std::string& username);
duo::Json& ensure_object_member(duo::Json& parent, const char* key) {
duo::Json& value = parent[key];
if (!value.is_object()) value = duo::Json::Object{};
return value;
}
void ensure_config_shape(duo::Json& config) {
if (!config.is_object()) config = duo::Json::Object{};
const duo::Json defaults = default_config();
for (const char* key : {"version", "global", "default_telegram", "rules", "per_user", "next_user_id", "admin_auth"}) {
if (!config.find(key)) config[key] = *defaults.find(key);
}
duo::Json& global = ensure_object_member(config, "global");
const duo::Json& defaultGlobal = *defaults.find("global");
for (const char* key : {"enabled", "admin_2fa_enabled", "require_for_all_users", "fail_closed", "otp_length", "otp_ttl_sec", "max_attempts", "resend_cooldown_sec"}) {
if (!global.find(key)) global[key] = *defaultGlobal.find(key);
}
duo::Json& telegram = ensure_object_member(config, "default_telegram");
const duo::Json& defaultTelegram = *defaults.find("default_telegram");
for (const char* key : {"bot_token", "user_id", "group_id"}) {
if (!telegram.find(key)) telegram[key] = *defaultTelegram.find(key);
}
duo::Json& rules = ensure_object_member(config, "rules");
if (!rules.find("enabled_users")) rules["enabled_users"] = duo::Json::Array{};
if (!rules.find("enabled_groups")) rules["enabled_groups"] = duo::Json::Array{};
ensure_object_member(config, "per_user");
ensure_object_member(config, "admin_auth");
}
std::vector<std::string> split_csv(const std::string& value) {
std::vector<std::string> output;
size_t start = 0;
while (start <= value.size()) {
const size_t end = value.find(',', start);
std::string item = trim_ascii(value.substr(start, end == std::string::npos ? std::string::npos : end - start));
if (!item.empty()) output.push_back(std::move(item));
if (end == std::string::npos) break;
start = end + 1;
}
return output;
}
bool parse_bool(const std::string& value, bool& out) {
const std::string lowered = normalize_username(value);
if (lowered == "1" || lowered == "true" || lowered == "yes" || lowered == "on") {
out = true;
return true;
}
if (lowered == "0" || lowered == "false" || lowered == "no" || lowered == "off") {
out = false;
return true;
}
return false;
}
void print_admin_usage() {
std::puts(
"DUO-RDP native admin\n"
" --admin [--config <path>] init [--force]\n"
" --admin [--config <path>] show\n"
" --admin [--config <path>] set-global <name> <true|false|number>\n"
" --admin [--config <path>] upsert-user <login> [--chat-id <id>] [--group-id <id>]\n"
" [--groups group1,group2] [--totp <base32>] [--token-stdin] [--verify]\n"
" --admin [--config <path>] remove-user <login>\n"
"\n"
"--token-stdin reads the Telegram bot token from standard input, so it is not exposed in the command line.\n"
);
}
bool read_next_arg(const std::vector<std::string>& args, size_t& index, std::string& output) {
if (index + 1 >= args.size()) return false;
output = args[++index];
return true;
}
void print_config_summary(const ConfigRead& read) {
const duo::Json& global = object_member_or_empty(read.value, "global");
const duo::Json& users = object_member_or_empty(read.value, "per_user");
std::printf("config: %s\n", wide_to_utf8(configured_config_path()).c_str());
std::printf("encrypted DPAPI config: %s\n", read.exists ? "yes" : "not created");
std::printf("enabled=%s admin_2fa=%s require_all=%s fail_closed=%s users=%zu\n",
duo::json_bool(global, "enabled", false) ? "true" : "false",
duo::json_bool(global, "admin_2fa_enabled", false) ? "true" : "false",
duo::json_bool(global, "require_for_all_users", false) ? "true" : "false",
duo::json_bool(global, "fail_closed", true) ? "true" : "false",
users.object_or_empty().size());
for (const auto& [key, row] : users.object_or_empty()) {
const std::string login = duo::json_string(row, "login", key);
const bool telegram = !duo::json_string(row, "bot_token").empty()
&& (!duo::json_string(row, "user_id").empty() || !duo::json_string(row, "group_id").empty());
const bool totp = !duo::json_string(row, "totp_secret").empty();
std::printf("- %s verified=%s telegram=%s totp=%s groups=%zu\n", login.c_str(),
duo::json_bool(row, "verified", false) ? "true" : "false",
telegram ? "configured" : "none", totp ? "configured" : "none",
row.find("groups") ? row.find("groups")->array_or_empty().size() : 0U);
}
}
int run_admin(const std::vector<std::string>& allArgs) {
std::vector<std::string> args;
for (size_t index = 0; index < allArgs.size(); ++index) {
if (allArgs[index] == "--config") {
if (index + 1 >= allArgs.size()) {
std::fputs("--config needs a path\n", stderr);
return 2;
}
g_configPathOverride = utf8_to_wide(allArgs[++index]);
continue;
}
args.push_back(allArgs[index]);
}
if (args.empty() || args[0] == "help" || args[0] == "--help") {
print_admin_usage();
return 0;
}
const std::string& command = args[0];
if (command == "init") {
const bool force = args.size() > 1 && args[1] == "--force";
ConfigRead current = load_config();
if (current.exists && current.error.empty() && !force) {
std::fputs("config already exists; use init --force to replace it\n", stderr);
return 3;
}
std::string error;
if (!save_config(default_config(), error)) {
std::fprintf(stderr, "cannot initialize config: %s\n", error.c_str());
return 1;
}
std::puts("native DPAPI configuration initialized (2FA remains disabled until configured).");
return 0;
}
ConfigRead current = load_config();
if (!current.error.empty()) {
std::fprintf(stderr, "cannot read config: %s\n", current.error.c_str());
return 1;
}
ensure_config_shape(current.value);
if (command == "show") {
print_config_summary(current);
return 0;
}
if (command == "set-global") {
if (args.size() != 3) {
print_admin_usage();
return 2;
}
const std::string& name = args[1];
const std::string& value = args[2];
duo::Json& global = ensure_object_member(current.value, "global");
if (name == "enabled" || name == "admin_2fa_enabled" || name == "require_for_all_users" || name == "fail_closed") {
bool parsed = false;
if (!parse_bool(value, parsed)) {
std::fputs("global boolean value is invalid\n", stderr);
return 2;
}
global[name] = parsed;
} else if (name == "otp_length" || name == "otp_ttl_sec" || name == "max_attempts" || name == "resend_cooldown_sec") {
char* end = nullptr;
const long parsed = std::strtol(value.c_str(), &end, 10);
if (!end || *end != '\0' || parsed < 0 || parsed > 3600) {
std::fputs("global numeric value is invalid\n", stderr);
return 2;
}
global[name] = static_cast<int>(parsed);
} else {
std::fputs("unsupported global setting\n", stderr);
return 2;
}
std::string error;
if (!save_config(current.value, error)) {
std::fprintf(stderr, "cannot save config: %s\n", error.c_str());
return 1;
}
std::puts("global setting saved.");
return 0;
}
if (command == "remove-user") {
if (args.size() != 2) {
print_admin_usage();
return 2;
}
duo::Json& users = ensure_object_member(current.value, "per_user");
const std::string wanted = normalize_username(args[1]);
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])) {
found = key;
break;
}
}
if (found.empty()) {
std::fputs("user not found\n", stderr);
return 3;
}
// Rebuild rather than exposing mutable map internals through mini_json.
duo::Json::Object rebuilt;
for (const auto& [key, row] : users.object_or_empty()) if (key != found) rebuilt[key] = row;
users = duo::Json(std::move(rebuilt));
std::string error;
if (!save_config(current.value, error)) {
std::fprintf(stderr, "cannot save config: %s\n", error.c_str());
return 1;
}
std::puts("user removed.");
return 0;
}
if (command == "upsert-user") {
if (args.size() < 2) {
print_admin_usage();
return 2;
}
const std::string login = args[1];
const std::string key = normalize_username(login);
if (key.empty()) {
std::fputs("login is empty\n", stderr);
return 2;
}
duo::Json& users = ensure_object_member(current.value, "per_user");
duo::Json& row = users[key];
if (!row.is_object()) row = duo::Json::Object{};
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;
} 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());
return 2;
}
if (flag == "--chat-id") { row["user_id"] = value; credentialsChanged = true; }
else if (flag == "--group-id") { row["group_id"] = value; credentialsChanged = true; }
else if (flag == "--totp") { row["totp_secret"] = value; credentialsChanged = true; }
else {
duo::Json::Array groups;
for (const std::string& group : split_csv(value)) groups.emplace_back(group);
row["groups"] = duo::Json(std::move(groups));
}
} else if (flag == "--token-stdin") {
if (!std::getline(std::cin, value) || value.empty()) {
std::fputs("cannot read a non-empty token from stdin\n", stderr);
return 2;
}
row["bot_token"] = value;
credentialsChanged = true;
} else {
std::fprintf(stderr, "unknown upsert option: %s\n", flag.c_str());
return 2;
}
}
if (credentialsChanged && !verify) row["verified"] = false;
if (verify) row["verified"] = true;
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.");
return 0;
}
print_admin_usage();
return 2;
}
const duo::Json& object_member_or_empty(const duo::Json& parent, const char* key) {
static const duo::Json empty(duo::Json::Object{});
const duo::Json* value = parent.find(key);
return value && value->is_object() ? *value : empty;
}
std::vector<std::string> string_array(const duo::Json& value) {
std::vector<std::string> result;
for (const duo::Json& item : value.array_or_empty()) {
if (item.is_string() && !item.string_or().empty()) result.push_back(item.string_or());
}
return result;
}
std::string normalize_username(const std::string& source) {
std::wstring value = trim_wide(utf8_to_wide(source));
const size_t slash = value.find_last_of(L"\\/");
if (slash != std::wstring::npos && slash + 1 < value.size()) value = value.substr(slash + 1);
const size_t at = value.find(L'@');
if (at != std::wstring::npos) value = value.substr(0, at);
std::transform(value.begin(), value.end(), value.begin(), [](wchar_t c) { return static_cast<wchar_t>(towlower(c)); });
return wide_to_utf8(value);
}
std::string normalize_identity(const std::string& source) {
std::wstring value = trim_wide(utf8_to_wide(source));
std::replace(value.begin(), value.end(), L'/', L'\\');
std::transform(value.begin(), value.end(), value.begin(), [](wchar_t c) { return static_cast<wchar_t>(towlower(c)); });
return wide_to_utf8(value);
}
bool normalize_challenge_id(const std::string& source, std::string& normalized) {
normalized.clear();
if (source.empty()) return true; // Legacy Credential Provider.
if (source.size() != 36) return false;
for (size_t index = 0; index < source.size(); ++index) {
const unsigned char character = static_cast<unsigned char>(source[index]);
const bool separator = index == 8 || index == 13 || index == 18 || index == 23;
if (separator) {
if (character != '-') return false;
normalized.push_back('-');
}
else {
if (!std::isxdigit(character)) return false;
normalized.push_back(static_cast<char>(std::tolower(character)));
}
}
return true;
}
struct OtpSessionKey final {
std::string identity;
std::string challengeId;
bool operator==(const OtpSessionKey&) const noexcept = default;
};
struct OtpSessionKeyHash final {
size_t operator()(const OtpSessionKey& key) const noexcept {
const size_t identityHash = std::hash<std::string>{}(key.identity);
const size_t challengeHash = std::hash<std::string>{}(key.challengeId);
return identityHash ^ (challengeHash + 0x9e3779b9U + (identityHash << 6U) + (identityHash >> 2U));
}
};
OtpSessionKey otp_session_key(const std::string& username, const std::string& challengeId) {
// Empty challengeId is deliberately the legacy namespace so an
// already-loaded older Credential Provider keeps working during a rolling
// DLL/service update. A structured key avoids delimiter collisions.
return OtpSessionKey{normalize_identity(username), challengeId};
}
bool identity_matches(const std::string& configured, const std::string& username) {
return normalize_identity(configured) == normalize_identity(username) || normalize_username(configured) == normalize_username(username);
}
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);
const std::string identity = normalize_identity(username);
for (const auto& [key, row] : users.object_or_empty()) {
if (!row.is_object()) continue;
const std::string login = duo::json_string(row, "login");
if (normalize_identity(key) == identity || normalize_username(key) == normalized || identity_matches(login, username)) return &row;
}
return nullptr;
}
struct Methods final {
std::string token;
std::string userId;
std::string groupId;
std::string totpSecret;
bool verified = false;
[[nodiscard]] bool telegram() const noexcept { return !token.empty() && (!userId.empty() || !groupId.empty()); }
[[nodiscard]] bool totp() const noexcept { return !totpSecret.empty(); }
[[nodiscard]] bool configured() const noexcept { return telegram() || totp(); }
};
Methods resolve_methods(const duo::Json& config, const std::string& username) {
Methods methods;
const duo::Json& defaults = object_member_or_empty(config, "default_telegram");
const duo::Json* node = find_user_node(config, username);
methods.token = node ? duo::json_string(*node, "bot_token") : std::string{};
methods.userId = node ? duo::json_string(*node, "user_id") : std::string{};
methods.groupId = node ? duo::json_string(*node, "group_id") : std::string{};
methods.totpSecret = node ? duo::json_string(*node, "totp_secret") : std::string{};
methods.verified = node && duo::json_bool(*node, "verified", false);
if (methods.token.empty()) methods.token = duo::json_string(defaults, "bot_token");
if (methods.userId.empty() && methods.groupId.empty()) {
methods.userId = duo::json_string(defaults, "user_id");
methods.groupId = duo::json_string(defaults, "group_id");
}
methods.totpSecret.erase(std::remove_if(methods.totpSecret.begin(), methods.totpSecret.end(), [](unsigned char c) { return std::isspace(c) != 0; }), methods.totpSecret.end());
std::transform(methods.totpSecret.begin(), methods.totpSecret.end(), methods.totpSecret.begin(), [](unsigned char c) { return static_cast<char>(std::toupper(c)); });
return methods;
}
bool is_admin_group(const std::string& group) {
const std::string normalized = normalize_identity(group);
return normalized == "administrators" || normalized == "administrator" || normalized == "builtin\\administrators" || normalized == "domain admins" || normalized == "администраторы";
}
bool has_admin_group(const std::vector<std::string>& groups) {
return std::any_of(groups.begin(), groups.end(), [](const std::string& value) { return is_admin_group(value); });
}
bool list_contains_identity(const duo::Json& list, const std::string& username) {
return std::any_of(list.array_or_empty().begin(), list.array_or_empty().end(), [&username](const duo::Json& value) {
return value.is_string() && identity_matches(value.string_or(), username);
});
}
bool list_intersects_groups(const duo::Json& list, const std::vector<std::string>& groups) {
for (const duo::Json& configured : list.array_or_empty()) {
if (!configured.is_string()) continue;
const std::string wanted = normalize_username(configured.string_or());
for (const std::string& group : groups) {
if (wanted == normalize_username(group)) return true;
}
}
return false;
}
bool policy_requires_2fa(const duo::Json& config, const std::string& username, const std::vector<std::string>& groups, const Methods& methods) {
const duo::Json& global = object_member_or_empty(config, "global");
if (!duo::json_bool(global, "enabled", false)) return false;
if (duo::json_bool(global, "require_for_all_users", false)) return true;
if (duo::json_bool(global, "admin_2fa_enabled", false) && has_admin_group(groups)) return true;
if (!methods.verified || !methods.configured()) return false;
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;
}
std::int64_t unix_seconds() {
return std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();
}
std::string computer_name() {
wchar_t buffer[256]{};
DWORD length = ARRAYSIZE(buffer);
if (!GetComputerNameW(buffer, &length)) return "UNKNOWN";
return wide_to_utf8(std::wstring(buffer, length));
}
std::string random_digits(int requestedLength) {
const int length = std::clamp(requestedLength, 4, 12);
std::string code;
code.reserve(static_cast<size_t>(length));
while (static_cast<int>(code.size()) < length) {
BYTE value = 0;
if (BCryptGenRandom(nullptr, &value, sizeof(value), BCRYPT_USE_SYSTEM_PREFERRED_RNG) < 0) throw std::runtime_error("CSPRNG failed");
if (value >= 250U) continue;
code.push_back(static_cast<char>('0' + (value % 10U)));
}
return code;
}
bool base32_decode(const std::string& source, std::vector<BYTE>& output) {
int bits = 0;
unsigned accumulator = 0;
for (unsigned char character : source) {
if (character == '=') break;
if (std::isspace(character)) continue;
character = static_cast<unsigned char>(std::toupper(character));
int value = -1;
if (character >= 'A' && character <= 'Z') value = character - 'A';
else if (character >= '2' && character <= '7') value = character - '2' + 26;
else return false;
accumulator = (accumulator << 5U) | static_cast<unsigned>(value);
bits += 5;
if (bits >= 8) {
bits -= 8;
output.push_back(static_cast<BYTE>((accumulator >> bits) & 0xffU));
}
}
return !output.empty();
}
bool hmac_sha1(const std::vector<BYTE>& key, const BYTE* input, size_t inputSize, BYTE output[20]) {
BCRYPT_ALG_HANDLE algorithm = nullptr;
BCRYPT_HASH_HANDLE hash = nullptr;
DWORD objectSize = 0;
DWORD read = 0;
NTSTATUS status = BCryptOpenAlgorithmProvider(&algorithm, BCRYPT_SHA1_ALGORITHM, nullptr, BCRYPT_ALG_HANDLE_HMAC_FLAG);
if (status < 0) return false;
std::vector<BYTE> object;
status = BCryptGetProperty(algorithm, BCRYPT_OBJECT_LENGTH, reinterpret_cast<PUCHAR>(&objectSize), sizeof(objectSize), &read, 0);
if (status >= 0) object.resize(objectSize);
if (status >= 0) status = BCryptCreateHash(algorithm, &hash, object.data(), objectSize, const_cast<PUCHAR>(key.data()), static_cast<ULONG>(key.size()), 0);
if (status >= 0) status = BCryptHashData(hash, const_cast<PUCHAR>(input), static_cast<ULONG>(inputSize), 0);
if (status >= 0) status = BCryptFinishHash(hash, output, 20, 0);
if (hash) BCryptDestroyHash(hash);
if (algorithm) BCryptCloseAlgorithmProvider(algorithm, 0);
return status >= 0;
}
bool constant_time_equals(const std::string& left, const std::string& right) {
if (left.size() != right.size()) return false;
unsigned char difference = 0;
for (size_t i = 0; i < left.size(); ++i) difference |= static_cast<unsigned char>(left[i] ^ right[i]);
return difference == 0;
}
bool normalize_otp_code(const std::string& source, std::string& normalized) {
normalized.clear();
for (unsigned char character : source) {
if (character >= '0' && character <= '9') {
normalized.push_back(static_cast<char>(character));
}
else if (!std::isspace(character)) {
return false;
}
}
return !normalized.empty();
}
bool verify_totp(const std::string& secret, const std::string& submitted) {
std::string code;
for (unsigned char c : submitted) if (std::isdigit(c)) code.push_back(static_cast<char>(c));
if (code.size() != 6) return false;
std::vector<BYTE> key;
if (!base32_decode(secret, key)) return false;
const std::int64_t now = unix_seconds() / 30;
for (int offset = -1; offset <= 1; ++offset) {
const std::uint64_t counter = static_cast<std::uint64_t>(now + offset);
BYTE packed[8]{};
for (int i = 0; i < 8; ++i) packed[7 - i] = static_cast<BYTE>((counter >> (i * 8)) & 0xffU);
BYTE digest[20]{};
if (!hmac_sha1(key, packed, sizeof(packed), digest)) return false;
const unsigned index = digest[19] & 0x0fU;
if (index + 3 >= sizeof(digest)) return false;
const std::uint32_t number = ((static_cast<std::uint32_t>(digest[index]) & 0x7fU) << 24U)
| (static_cast<std::uint32_t>(digest[index + 1]) << 16U)
| (static_cast<std::uint32_t>(digest[index + 2]) << 8U)
| static_cast<std::uint32_t>(digest[index + 3]);
char expected[7]{};
std::snprintf(expected, sizeof(expected), "%06u", number % 1000000U);
if (constant_time_equals(code, expected)) return true;
}
return false;
}
std::string mask_target(const std::string& value) {
if (value.size() <= 4) return "***";
return "***" + value.substr(value.size() - 4);
}
bool telegram_send(const std::string& token, const std::string& target, const std::string& text, std::string& reason) {
duo::Json::Object body;
body["chat_id"] = target;
body["text"] = text;
const std::string payload = duo::Json(std::move(body)).dump();
const std::wstring path = L"/bot" + utf8_to_wide(token) + L"/sendMessage";
HINTERNET session = WinHttpOpen(L"DuoRdpNative/2.0", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
if (!session) {
reason = "winhttp_open_failed";
return false;
}
HINTERNET connect = WinHttpConnect(session, L"api.telegram.org", INTERNET_DEFAULT_HTTPS_PORT, 0);
if (!connect) {
WinHttpCloseHandle(session);
reason = "winhttp_connect_failed";
return false;
}
HINTERNET request = WinHttpOpenRequest(connect, L"POST", path.c_str(), nullptr, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE);
if (!request) {
WinHttpCloseHandle(connect);
WinHttpCloseHandle(session);
reason = "winhttp_request_failed";
return false;
}
static constexpr wchar_t headers[] = L"Content-Type: application/json\r\n";
bool ok = WinHttpSendRequest(request, headers, static_cast<DWORD>(-1L), const_cast<char*>(payload.data()), static_cast<DWORD>(payload.size()), static_cast<DWORD>(payload.size()), 0) != FALSE;
if (ok) ok = WinHttpReceiveResponse(request, nullptr) != FALSE;
DWORD status = 0;
DWORD statusSize = sizeof(status);
if (ok) ok = WinHttpQueryHeaders(request, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX, &status, &statusSize, WINHTTP_NO_HEADER_INDEX) != FALSE;
std::string response;
if (ok) {
for (;;) {
DWORD available = 0;
if (!WinHttpQueryDataAvailable(request, &available) || available == 0) break;
if (response.size() + available > 32768U) break;
const size_t start = response.size();
response.resize(start + available);
DWORD read = 0;
if (!WinHttpReadData(request, response.data() + start, available, &read) || read == 0) {
response.resize(start);
break;
}
response.resize(start + read);
}
}
WinHttpCloseHandle(request);
WinHttpCloseHandle(connect);
WinHttpCloseHandle(session);
if (!ok || status != 200U) {
reason = "telegram_http_" + std::to_string(status);
return false;
}
try {
const duo::Json decoded = duo::Json::parse(response);
if (!duo::json_bool(decoded, "ok", false)) {
reason = "telegram_rejected";
return false;
}
} catch (...) {
reason = "telegram_invalid_response";
return false;
}
log_line("Telegram", "message delivered target=" + mask_target(target));
return true;
}
struct OtpRecord final {
std::string code;
std::int64_t expiresAt = 0;
int attemptsLeft = 0;
};
class OtpStore final {
public:
void replace(const std::string& username, const std::string& challengeId, std::string code, int ttlSeconds, int attempts) {
std::lock_guard lock(mutex_);
records_[otp_session_key(username, challengeId)] = OtpRecord{std::move(code), unix_seconds() + std::clamp(ttlSeconds, 15, 3600), std::clamp(attempts, 1, 20)};
}
duo::Json verify(const std::string& username, const std::string& challengeId, const std::string& code) {
std::lock_guard lock(mutex_);
const OtpSessionKey key = otp_session_key(username, challengeId);
const auto it = records_.find(key);
if (it == records_.end()) return error("no_session");
OtpRecord& record = it->second;
if (unix_seconds() > record.expiresAt) {
records_.erase(it);
return error("expired");
}
if (record.attemptsLeft <= 0) {
records_.erase(it);
return error("no_attempts");
}
std::string normalizedCode;
if (!normalize_otp_code(code, normalizedCode) || normalizedCode.size() != record.code.size()) {
return error("invalid_format");
}
--record.attemptsLeft;
if (constant_time_equals(record.code, normalizedCode)) {
records_.erase(it);
duo::Json::Object result;
result["ok"] = true;
return duo::Json(std::move(result));
}
const int attemptsLeft = record.attemptsLeft;
if (attemptsLeft <= 0) records_.erase(it);
duo::Json::Object result;
result["ok"] = false;
result["reason"] = "invalid_code";
result["attempts_left"] = attemptsLeft;
return duo::Json(std::move(result));
}
private:
static duo::Json error(const char* reason) {
duo::Json::Object result;
result["ok"] = false;
result["reason"] = reason;
return duo::Json(std::move(result));
}
std::mutex mutex_;
std::unordered_map<OtpSessionKey, OtpRecord, OtpSessionKeyHash> records_;
};
class AuthCore final {
public:
duo::Json dispatch(const duo::Json& request) {
if (!request.is_object()) return error("service_unavailable");
const std::string action = duo::json_string(request, "action");
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<std::string> groups = request.find("groups") ? string_array(*request.find("groups")) : std::vector<std::string>{};
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");
}
private:
duo::Json policy(const std::string& username, const std::vector<std::string>& groups) {
const ConfigRead config = load_config();
if (!config.error.empty()) return error("policy_error");
const Methods methods = resolve_methods(config.value, username);
const duo::Json& global = object_member_or_empty(config.value, "global");
const bool required = policy_requires_2fa(config.value, username, groups, methods);
duo::Json::Object result;
result["required"] = required;
result["failClosed"] = duo::json_bool(global, "fail_closed", true);
result["configured"] = methods.configured();
result["telegramConfigured"] = methods.telegram();
result["totpConfigured"] = methods.totp();
result["verified"] = methods.verified && methods.configured();
result["error"] = duo::Json();
log_line("Policy", "resolved required=" + std::to_string(required ? 1 : 0) + " configured=" + std::to_string(methods.configured() ? 1 : 0));
return duo::Json(std::move(result));
}
duo::Json issue(const std::string& username, const std::vector<std::string>& groups, const std::string& challengeId) {
const ConfigRead config = load_config();
if (!config.error.empty()) return error("service_unavailable");
const Methods methods = resolve_methods(config.value, username);
if (!policy_requires_2fa(config.value, username, groups, methods)) return status("skipped", 0, false);
if (!methods.configured()) return error("2fa_not_configured");
const duo::Json& global = object_member_or_empty(config.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);
const std::string code = random_digits(duo::json_int(global, "otp_length", 6));
// A manual RequestOtp always replaces the previous record. This is the
// resend contract: the old code is invalid immediately, regardless of
// whether it was issued automatically or by a prior button click.
store_.replace(username, challengeId, code, ttl, attempts);
log_line("Otp", "issued replacement code ttl=" + std::to_string(ttl)
+ " attempts=" + std::to_string(attempts)
+ " scope=" + (challengeId.empty() ? "legacy" : "tile"));
if (!methods.telegram()) {
if (methods.totp()) return status("totp_available", ttl);
return error("telegram_not_configured");
}
const std::string text = computer_name() + "\nDUO-RDP code (TTL " + std::to_string(ttl) + "s)\n" + username + "\n" + code;
int sent = 0;
std::vector<std::string> targets;
if (!methods.userId.empty()) targets.push_back(methods.userId);
if (!methods.groupId.empty()) targets.push_back(methods.groupId);
for (const std::string& target : targets) {
std::string reason;
if (telegram_send(methods.token, target, text, reason)) {
++sent;
} else {
log_line("Telegram", "send failed reason=" + reason + " target=" + mask_target(target));
}
}
if (sent > 0) return status("sent", ttl);
if (methods.totp()) return status("totp_available", ttl);
return error("telegram_send_failed");
}
duo::Json verify(const std::string& username, const std::string& code, const std::vector<std::string>& groups, const std::string& challengeId) {
const ConfigRead config = load_config();
if (!config.error.empty()) return error("service_unavailable");
const Methods methods = resolve_methods(config.value, username);
if (!policy_requires_2fa(config.value, username, groups, methods)) {
duo::Json::Object result;
result["ok"] = true;
result["method"] = "not_required";
return duo::Json(std::move(result));
}
if (!methods.configured()) return error("2fa_not_configured");
if (methods.totp() && verify_totp(methods.totpSecret, code)) {
duo::Json::Object result;
result["ok"] = true;
result["method"] = "totp";
return duo::Json(std::move(result));
}
return store_.verify(username, challengeId, code);
}
static duo::Json status(const char* value, int ttl, bool required = true) {
duo::Json::Object result;
result["required"] = required;
result["status"] = value;
if (ttl > 0) result["ttl"] = ttl;
return duo::Json(std::move(result));
}
static duo::Json error(const char* reason) {
duo::Json::Object result;
result["required"] = true;
result["status"] = "error";
result["error"] = reason;
result["reason"] = reason;
return duo::Json(std::move(result));
}
OtpStore store_;
};
bool pipe_overlapped_io(HANDLE pipe, void* buffer, DWORD size, DWORD& transferred, bool write) {
transferred = 0;
HANDLE event = CreateEventW(nullptr, TRUE, FALSE, nullptr);
if (!event) return false;
OVERLAPPED overlap{};
overlap.hEvent = event;
const BOOL started = write
? WriteFile(pipe, buffer, size, &transferred, &overlap)
: ReadFile(pipe, buffer, size, &transferred, &overlap);
bool ok = started != FALSE;
if (!ok && GetLastError() == ERROR_IO_PENDING) {
if (g_stopEvent) {
HANDLE waits[] = {g_stopEvent, event};
const DWORD wait = WaitForMultipleObjects(2, waits, FALSE, INFINITE);
if (wait == WAIT_OBJECT_0) {
CancelIoEx(pipe, &overlap);
WaitForSingleObject(event, INFINITE);
CloseHandle(event);
return false;
}
} else {
WaitForSingleObject(event, INFINITE);
}
ok = GetOverlappedResult(pipe, &overlap, &transferred, FALSE) != FALSE;
}
CloseHandle(event);
return ok;
}
bool read_pipe_line(HANDLE pipe, std::string& line) {
line.clear();
char chunk[4096];
while (line.size() < kMaxPipeMessage) {
DWORD read = 0;
if (!pipe_overlapped_io(pipe, chunk, sizeof(chunk), read, false) || read == 0) return false;
const char* newline = static_cast<const char*>(std::memchr(chunk, '\n', read));
const size_t count = newline ? static_cast<size_t>(newline - chunk) : static_cast<size_t>(read);
line.append(chunk, count);
if (newline) return true;
}
return false;
}
void handle_pipe_client(HANDLE pipe, std::shared_ptr<AuthCore> core) {
std::unique_ptr<void, decltype(&CloseHandle)> closer(pipe, &CloseHandle);
std::string reply;
try {
std::string request;
if (!read_pipe_line(pipe, request)) return;
reply = core->dispatch(duo::Json::parse(request)).dump();
} catch (const std::exception& exc) {
log_line("Pipe", std::string("request rejected: ") + exc.what());
duo::Json::Object error;
error["error"] = "service_unavailable";
reply = duo::Json(std::move(error)).dump();
}
reply.push_back('\n');
DWORD written = 0;
if (pipe_overlapped_io(pipe, reply.data(), static_cast<DWORD>(reply.size()), written, true) && written == reply.size()) {
FlushFileBuffers(pipe);
}
DisconnectNamedPipe(pipe);
}
PSECURITY_DESCRIPTOR pipe_security_descriptor() {
PSECURITY_DESCRIPTOR descriptor = nullptr;
if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(L"D:(A;;GA;;;SY)(A;;GA;;;BA)", SDDL_REVISION_1, &descriptor, nullptr)) return nullptr;
return descriptor;
}
void run_pipe_server(const std::shared_ptr<AuthCore>& core) {
PSECURITY_DESCRIPTOR descriptor = pipe_security_descriptor();
SECURITY_ATTRIBUTES attributes{};
attributes.nLength = sizeof(attributes);
attributes.lpSecurityDescriptor = descriptor;
attributes.bInheritHandle = FALSE;
log_line("AuthService", "native pipe server started");
while (WaitForSingleObject(g_stopEvent, 0) != WAIT_OBJECT_0) {
HANDLE connected = CreateNamedPipeW(kPipeName, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, PIPE_UNLIMITED_INSTANCES, 65536, 65536, 0, descriptor ? &attributes : nullptr);
if (connected == INVALID_HANDLE_VALUE) {
log_line("AuthService", "CreateNamedPipe failed error=" + std::to_string(GetLastError()));
Sleep(250);
continue;
}
HANDLE event = CreateEventW(nullptr, TRUE, FALSE, nullptr);
OVERLAPPED overlap{};
overlap.hEvent = event;
BOOL connectedNow = ConnectNamedPipe(connected, &overlap);
DWORD error = connectedNow ? ERROR_SUCCESS : GetLastError();
if (error == ERROR_IO_PENDING) {
HANDLE waits[] = {g_stopEvent, event};
const DWORD wait = WaitForMultipleObjects(2, waits, FALSE, INFINITE);
if (wait == WAIT_OBJECT_0) {
CancelIoEx(connected, &overlap);
CloseHandle(event);
CloseHandle(connected);
break;
}
DWORD ignored = 0;
if (!GetOverlappedResult(connected, &overlap, &ignored, FALSE)) {
CloseHandle(event);
CloseHandle(connected);
continue;
}
} else if (error != ERROR_SUCCESS && error != ERROR_PIPE_CONNECTED) {
CloseHandle(event);
CloseHandle(connected);
continue;
}
CloseHandle(event);
// The core remains alive until an accepted client has finished even if
// SCM stops the listener while that request is in flight.
std::thread(handle_pipe_client, connected, core).detach();
}
if (descriptor) LocalFree(descriptor);
log_line("AuthService", "native pipe server stopped");
}
bool run_self_test() {
OtpStore store;
constexpr char tileA[] = "8f89b26c-4e77-46bd-b06b-568b2d4290cf";
constexpr char tileB[] = "3111d006-62cf-41ec-8c3e-1de5f0f8e3d4";
constexpr char tileC[] = "36a3e6e1-36dc-4e7b-b4a6-7722ff50b451";
store.replace("DOMAIN\\Alice", tileA, "123456", 90, 5);
store.replace("DOMAIN\\Alice", tileA, "654321", 90, 5);
store.replace("DOMAIN\\Alice", tileB, "111111", 90, 5);
store.replace("DOMAIN\\Alice", tileC, "999999", 90, 1);
store.replace("DOMAIN\\Alice", "", "222222", 90, 5);
store.replace("DOMAIN\\Alice", "", "333333", 90, 5);
const duo::Json oldCode = store.verify("DOMAIN\\Alice", tileA, "123456");
const duo::Json newCode = store.verify("DOMAIN\\Alice", tileA, " 654321\r\n");
const duo::Json otherTileCode = store.verify("DOMAIN\\Alice", tileB, "111111");
const duo::Json malformedTileCode = store.verify("DOMAIN\\Alice", tileC, "99 99");
const duo::Json formattedTileCode = store.verify("DOMAIN\\Alice", tileC, "999999");
const duo::Json legacyOldCode = store.verify("DOMAIN\\Alice", "", "222222");
const duo::Json legacyNewCode = store.verify("DOMAIN\\Alice", "", "333333");
const bool oldRejected = !duo::json_bool(oldCode, "ok", false) && duo::json_string(oldCode, "reason") == "invalid_code";
const bool newAccepted = duo::json_bool(newCode, "ok", false);
const bool otherTileAccepted = duo::json_bool(otherTileCode, "ok", false);
const bool malformedRejected = !duo::json_bool(malformedTileCode, "ok", false) && duo::json_string(malformedTileCode, "reason") == "invalid_format";
const bool formattedAccepted = duo::json_bool(formattedTileCode, "ok", false);
const bool legacyOldRejected = !duo::json_bool(legacyOldCode, "ok", false) && duo::json_string(legacyOldCode, "reason") == "invalid_code";
const bool legacyNewAccepted = duo::json_bool(legacyNewCode, "ok", false);
std::string normalizedChallenge;
const bool challengeValidation = normalize_challenge_id("8F89B26C-4E77-46BD-B06B-568B2D4290CF", normalizedChallenge)
&& normalizedChallenge == tileA
&& !normalize_challenge_id("not-a-guid", normalizedChallenge);
const duo::Json parsed = duo::Json::parse("{\"action\":\"RequestOtp\",\"challenge_id\":\"8f89b26c-4e77-46bd-b06b-568b2d4290cf\",\"groups\":[\"Administrators\"]}");
const bool jsonOk = duo::json_string(parsed, "action") == "RequestOtp"
&& duo::json_string(parsed, "challenge_id") == tileA
&& parsed.find("groups") && parsed.find("groups")->array_or_empty().size() == 1;
if (!oldRejected || !newAccepted || !otherTileAccepted || !malformedRejected || !formattedAccepted || !legacyOldRejected || !legacyNewAccepted || !challengeValidation || !jsonOk) {
std::fputs("SELFTEST FAIL\n", stderr);
return false;
}
std::puts("SELFTEST PASS: resend invalidates only its own tile code; parallel tiles and legacy clients remain independent.");
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) {
pipe = CreateFileW(kPipeName, GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, nullptr);
if (pipe != INVALID_HANDLE_VALUE) break;
if (GetLastError() != ERROR_PIPE_BUSY || !WaitNamedPipeW(kPipeName, 100)) Sleep(20);
}
if (pipe == INVALID_HANDLE_VALUE) return false;
std::unique_ptr<void, decltype(&CloseHandle)> closer(pipe, &CloseHandle);
std::string outbound = request.dump() + "\n";
DWORD written = 0;
if (!WriteFile(pipe, outbound.data(), static_cast<DWORD>(outbound.size()), &written, nullptr) || written != outbound.size()) return false;
std::string inbound;
char chunk[1024];
while (inbound.size() < kMaxPipeMessage) {
DWORD read = 0;
if (!ReadFile(pipe, chunk, sizeof(chunk), &read, nullptr) || read == 0) return false;
const char* newline = static_cast<const char*>(std::memchr(chunk, '\n', read));
inbound.append(chunk, newline ? static_cast<size_t>(newline - chunk) : static_cast<size_t>(read));
if (newline) break;
}
try {
response = duo::Json::parse(inbound);
return true;
} catch (...) {
return false;
}
}
bool run_pipe_self_test() {
g_stopEvent = CreateEventW(nullptr, TRUE, FALSE, nullptr);
if (!g_stopEvent) return false;
auto core = std::make_shared<AuthCore>();
std::thread server([core] { run_pipe_server(core); });
duo::Json::Object policyRequest;
policyRequest["action"] = "GetPolicy";
policyRequest["username"] = "native-pipe-test";
policyRequest["groups"] = duo::Json::Array{};
duo::Json policyResponse;
const bool policyOk = pipe_exchange_for_test(duo::Json(std::move(policyRequest)), policyResponse)
&& !duo::json_bool(policyResponse, "required", true);
duo::Json::Object issueRequest;
issueRequest["action"] = "RequestOtp";
issueRequest["username"] = "native-pipe-test";
issueRequest["groups"] = duo::Json::Array{};
duo::Json issueResponse;
const bool issueOk = pipe_exchange_for_test(duo::Json(std::move(issueRequest)), issueResponse)
&& duo::json_string(issueResponse, "status") == "skipped"
&& !duo::json_bool(issueResponse, "required", true);
SetEvent(g_stopEvent);
server.join();
CloseHandle(g_stopEvent);
g_stopEvent = nullptr;
if (!policyOk || !issueOk) {
std::fputs("PIPE SELFTEST FAIL\n", stderr);
return false;
}
std::puts("PIPE SELFTEST PASS: named-pipe JSONL protocol and native dispatch are healthy.");
return true;
}
void set_service_state(DWORD state, DWORD win32Exit = NO_ERROR) {
if (!g_serviceHandle) return;
g_serviceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
g_serviceStatus.dwCurrentState = state;
g_serviceStatus.dwWin32ExitCode = win32Exit;
g_serviceStatus.dwWaitHint = state == SERVICE_START_PENDING || state == SERVICE_STOP_PENDING ? 5000 : 0;
g_serviceStatus.dwControlsAccepted = state == SERVICE_RUNNING ? SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN : 0;
SetServiceStatus(g_serviceHandle, &g_serviceStatus);
}
DWORD WINAPI service_control(DWORD control, DWORD, LPVOID, LPVOID) {
if (control == SERVICE_CONTROL_STOP || control == SERVICE_CONTROL_SHUTDOWN) {
set_service_state(SERVICE_STOP_PENDING);
if (g_stopEvent) SetEvent(g_stopEvent);
}
return NO_ERROR;
}
void WINAPI service_main(DWORD, LPWSTR*) {
g_serviceHandle = RegisterServiceCtrlHandlerExW(kServiceName, service_control, nullptr);
if (!g_serviceHandle) return;
set_service_state(SERVICE_START_PENDING);
g_stopEvent = CreateEventW(nullptr, TRUE, FALSE, nullptr);
if (!g_stopEvent) {
set_service_state(SERVICE_STOPPED, GetLastError());
return;
}
set_service_state(SERVICE_RUNNING);
auto core = std::make_shared<AuthCore>();
run_pipe_server(core);
CloseHandle(g_stopEvent);
g_stopEvent = nullptr;
set_service_state(SERVICE_STOPPED);
}
BOOL WINAPI console_control(DWORD control) {
if ((control == CTRL_C_EVENT || control == CTRL_BREAK_EVENT || control == CTRL_CLOSE_EVENT) && g_stopEvent) {
SetEvent(g_stopEvent);
return TRUE;
}
return FALSE;
}
int run_console() {
g_stopEvent = CreateEventW(nullptr, TRUE, FALSE, nullptr);
if (!g_stopEvent) return 2;
SetConsoleCtrlHandler(console_control, TRUE);
auto core = std::make_shared<AuthCore>();
std::puts("DUO-RDP native auth service is running in console mode. Press Ctrl+C to stop.");
run_pipe_server(core);
CloseHandle(g_stopEvent);
g_stopEvent = nullptr;
return 0;
}
} // namespace
int wmain(int argc, wchar_t** argv) {
if (argc > 1 && std::wstring_view(argv[1]) == L"--admin") {
std::vector<std::string> args;
for (int index = 2; index < argc; ++index) args.push_back(wide_to_utf8(argv[index]));
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"--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[] = {
{const_cast<LPWSTR>(kServiceName), service_main},
{nullptr, nullptr},
};
if (!StartServiceCtrlDispatcherW(table)) {
const DWORD error = GetLastError();
std::fwprintf(stderr, L"DuoRdpAuthService must run under SCM or with --console (error=%lu).\n", error);
return static_cast<int>(error == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT ? 2 : error);
}
return 0;
}