1386 lines
55 KiB
C++
1386 lines
55 KiB
C++
#include "DuoCredential.h"
|
|
#include "guid.h"
|
|
#include <combaseapi.h>
|
|
#include <wincred.h>
|
|
#include <ntsecapi.h>
|
|
#ifndef SECURITY_WIN32
|
|
#define SECURITY_WIN32
|
|
#endif
|
|
#include <security.h>
|
|
#include <shlwapi.h>
|
|
#include <propkey.h>
|
|
#include <wincrypt.h>
|
|
#include <fstream>
|
|
#include <cwctype>
|
|
#include <algorithm>
|
|
#include <climits>
|
|
#include <vector>
|
|
#include <lm.h>
|
|
|
|
#ifndef STATUS_SUCCESS
|
|
#define STATUS_SUCCESS ((NTSTATUS)0x00000000L)
|
|
#endif
|
|
|
|
extern "C" IMAGE_DOS_HEADER __ImageBase;
|
|
static std::wstring Utf8ToWide(const std::string& value);
|
|
static void LogLine(const std::wstring& message);
|
|
|
|
static size_t FindJsonValue(const std::wstring& s, const std::wstring& key) {
|
|
const std::wstring p = L"\"" + key + L"\"";
|
|
size_t pos = s.find(p);
|
|
if (pos == std::wstring::npos) return pos;
|
|
pos += p.size();
|
|
while (pos < s.size() && iswspace(s[pos])) ++pos;
|
|
if (pos >= s.size() || s[pos] != L':') return std::wstring::npos;
|
|
++pos;
|
|
while (pos < s.size() && iswspace(s[pos])) ++pos;
|
|
return pos;
|
|
}
|
|
|
|
static bool JsonBool(const std::wstring& s, const std::wstring& key, bool& value) {
|
|
const size_t pos = FindJsonValue(s, key);
|
|
if (pos == std::wstring::npos) return false;
|
|
if (s.compare(pos, 4, L"true") == 0) {
|
|
value = true;
|
|
return true;
|
|
}
|
|
if (s.compare(pos, 5, L"false") == 0) {
|
|
value = false;
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
static bool JsonStringEquals(const std::wstring& s, const std::wstring& key, const std::wstring& value) {
|
|
size_t pos = FindJsonValue(s, key);
|
|
if (pos == std::wstring::npos || pos >= s.size() || s[pos] != L'"') return false;
|
|
++pos;
|
|
std::wstring actual;
|
|
while (pos < s.size()) {
|
|
wchar_t ch = s[pos++];
|
|
if (ch == L'\\' && pos < s.size()) {
|
|
actual.push_back(s[pos++]);
|
|
continue;
|
|
}
|
|
if (ch == L'"') break;
|
|
actual.push_back(ch);
|
|
}
|
|
return actual == value;
|
|
}
|
|
|
|
static std::wstring JsonStringValue(const std::wstring& s, const std::wstring& key) {
|
|
size_t pos = FindJsonValue(s, key);
|
|
if (pos == std::wstring::npos || pos >= s.size() || s[pos] != L'"') return {};
|
|
++pos;
|
|
std::wstring actual;
|
|
while (pos < s.size()) {
|
|
wchar_t ch = s[pos++];
|
|
if (ch == L'\\' && pos < s.size()) {
|
|
actual.push_back(s[pos++]);
|
|
continue;
|
|
}
|
|
if (ch == L'"') break;
|
|
actual.push_back(ch);
|
|
}
|
|
return actual;
|
|
}
|
|
|
|
static std::wstring JsonStringValueFrom(const std::wstring& s, const std::wstring& key, size_t start) {
|
|
const std::wstring p = L"\"" + key + L"\"";
|
|
size_t pos = s.find(p, start);
|
|
if (pos == std::wstring::npos) return {};
|
|
pos += p.size();
|
|
while (pos < s.size() && iswspace(s[pos])) ++pos;
|
|
if (pos >= s.size() || s[pos] != L':') return {};
|
|
++pos;
|
|
while (pos < s.size() && iswspace(s[pos])) ++pos;
|
|
if (pos >= s.size() || s[pos] != L'"') return {};
|
|
++pos;
|
|
std::wstring actual;
|
|
while (pos < s.size()) {
|
|
wchar_t ch = s[pos++];
|
|
if (ch == L'\\' && pos < s.size()) {
|
|
actual.push_back(s[pos++]);
|
|
continue;
|
|
}
|
|
if (ch == L'"') break;
|
|
actual.push_back(ch);
|
|
}
|
|
return actual;
|
|
}
|
|
|
|
static std::wstring ToLower(std::wstring value) {
|
|
std::transform(value.begin(), value.end(), value.begin(), [](wchar_t ch) {
|
|
return (wchar_t)towlower(ch);
|
|
});
|
|
return value;
|
|
}
|
|
|
|
static std::wstring Trim(const std::wstring& value) {
|
|
size_t first = 0;
|
|
while (first < value.size() && iswspace(value[first])) ++first;
|
|
size_t last = value.size();
|
|
while (last > first && iswspace(value[last - 1])) --last;
|
|
return value.substr(first, last - first);
|
|
}
|
|
|
|
static bool StartsWith(const std::wstring& value, const std::wstring& prefix) {
|
|
return value.size() >= prefix.size() && value.compare(0, prefix.size(), prefix) == 0;
|
|
}
|
|
|
|
static std::wstring PolicyUserName(const std::wstring& user) {
|
|
std::wstring value = Trim(user);
|
|
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);
|
|
return ToLower(value);
|
|
}
|
|
|
|
static std::vector<std::wstring> JsonStringArrayValues(const std::wstring& s, const std::wstring& key) {
|
|
std::vector<std::wstring> values;
|
|
size_t pos = FindJsonValue(s, key);
|
|
if (pos == std::wstring::npos || pos >= s.size() || s[pos] != L'[') return values;
|
|
++pos;
|
|
while (pos < s.size()) {
|
|
while (pos < s.size() && (iswspace(s[pos]) || s[pos] == L',')) ++pos;
|
|
if (pos >= s.size() || s[pos] == L']') break;
|
|
if (s[pos] != L'"') {
|
|
++pos;
|
|
continue;
|
|
}
|
|
++pos;
|
|
std::wstring actual;
|
|
while (pos < s.size()) {
|
|
wchar_t ch = s[pos++];
|
|
if (ch == L'\\' && pos < s.size()) {
|
|
actual.push_back(s[pos++]);
|
|
continue;
|
|
}
|
|
if (ch == L'"') break;
|
|
actual.push_back(ch);
|
|
}
|
|
values.push_back(actual);
|
|
}
|
|
return values;
|
|
}
|
|
|
|
static bool JsonStringArrayContains(const std::wstring& s, const std::wstring& key, const std::wstring& value) {
|
|
const std::wstring wanted = PolicyUserName(value);
|
|
for (const auto& actual : JsonStringArrayValues(s, key)) {
|
|
if (PolicyUserName(actual) == wanted) return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
static bool JsonStringArrayIntersects(const std::wstring& s, const std::wstring& key, const std::vector<std::wstring>& values) {
|
|
const auto configured = JsonStringArrayValues(s, key);
|
|
for (const auto& configuredValue : configured) {
|
|
const std::wstring configuredName = PolicyUserName(configuredValue);
|
|
for (const auto& value : values) {
|
|
if (configuredName == PolicyUserName(value)) return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
static bool JsonUserHasVerifiedMethod(const std::wstring& s, const std::wstring& user) {
|
|
const std::wstring wanted = PolicyUserName(user);
|
|
size_t pos = 0;
|
|
while ((pos = s.find(L"\"login\"", pos)) != std::wstring::npos) {
|
|
const std::wstring login = JsonStringValueFrom(s, L"login", pos);
|
|
if (PolicyUserName(login) == wanted) {
|
|
const std::wstring window = s.substr(pos, std::min<size_t>(1600, s.size() - pos));
|
|
bool verified = false;
|
|
if (!JsonBool(window, L"verified", verified) || !verified) return false;
|
|
const std::wstring token = JsonStringValue(window, L"bot_token");
|
|
const std::wstring userId = JsonStringValue(window, L"user_id");
|
|
const std::wstring groupId = JsonStringValue(window, L"group_id");
|
|
const std::wstring secret = JsonStringValue(window, L"totp_secret");
|
|
return (!token.empty() && (!userId.empty() || !groupId.empty())) || !secret.empty();
|
|
}
|
|
++pos;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
static bool JsonDefaultTelegramConfigured(const std::wstring& s, std::wstring& token, std::wstring& userId, std::wstring& groupId) {
|
|
const size_t pos = s.find(L"\"default_telegram\"");
|
|
if (pos == std::wstring::npos) return false;
|
|
const std::wstring window = s.substr(pos, std::min<size_t>(800, s.size() - pos));
|
|
token = JsonStringValue(window, L"bot_token");
|
|
userId = JsonStringValue(window, L"user_id");
|
|
groupId = JsonStringValue(window, L"group_id");
|
|
return !token.empty() && (!userId.empty() || !groupId.empty());
|
|
}
|
|
|
|
static void JsonUserConfiguredMethods(const std::wstring& s, const std::wstring& user, bool& telegram, bool& totp) {
|
|
telegram = false;
|
|
totp = false;
|
|
|
|
std::wstring defaultToken;
|
|
std::wstring defaultUserId;
|
|
std::wstring defaultGroupId;
|
|
const bool defaultTelegram = JsonDefaultTelegramConfigured(s, defaultToken, defaultUserId, defaultGroupId);
|
|
|
|
const std::wstring wanted = PolicyUserName(user);
|
|
size_t pos = 0;
|
|
while ((pos = s.find(L"\"login\"", pos)) != std::wstring::npos) {
|
|
const std::wstring login = JsonStringValueFrom(s, L"login", pos);
|
|
if (PolicyUserName(login) == wanted) {
|
|
const std::wstring window = s.substr(pos, std::min<size_t>(1600, s.size() - pos));
|
|
std::wstring token = JsonStringValue(window, L"bot_token");
|
|
std::wstring userId = JsonStringValue(window, L"user_id");
|
|
std::wstring groupId = JsonStringValue(window, L"group_id");
|
|
if (token.empty()) token = defaultToken;
|
|
if (userId.empty() && groupId.empty()) {
|
|
userId = defaultUserId;
|
|
groupId = defaultGroupId;
|
|
}
|
|
const std::wstring secret = JsonStringValue(window, L"totp_secret");
|
|
telegram = !token.empty() && (!userId.empty() || !groupId.empty());
|
|
totp = !secret.empty();
|
|
return;
|
|
}
|
|
++pos;
|
|
}
|
|
|
|
telegram = defaultTelegram;
|
|
}
|
|
|
|
static bool ReadTextFile(const std::wstring& path, std::wstring& text) {
|
|
// `const wchar_t*` keeps the Windows path Unicode-safe under both MSVC and
|
|
// MinGW cross-builds; passing std::wstring directly is MSVC-specific.
|
|
std::ifstream file(path.c_str(), std::ios::binary);
|
|
if (!file.is_open()) return false;
|
|
std::string bytes((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
|
|
text = Utf8ToWide(bytes);
|
|
return !text.empty() || bytes.empty();
|
|
}
|
|
|
|
static bool TryDecodeDpapiConfig(std::wstring& config) {
|
|
config = Trim(config);
|
|
const std::wstring dpapiPrefix = L"DUORDP_CONFIG_V1:ENCdpapi:";
|
|
if (!StartsWith(config, dpapiPrefix)) {
|
|
return StartsWith(config, L"{");
|
|
}
|
|
|
|
const std::wstring b64 = config.substr(dpapiPrefix.size());
|
|
DWORD protectedSize = 0;
|
|
if (!CryptStringToBinaryW(b64.c_str(), (DWORD)b64.size(), CRYPT_STRING_BASE64, nullptr, &protectedSize, nullptr, nullptr) || protectedSize == 0) {
|
|
LogLine(L"DPAPI config base64 size failed error=" + std::to_wstring(GetLastError()));
|
|
return false;
|
|
}
|
|
|
|
std::vector<BYTE> protectedData(protectedSize);
|
|
if (!CryptStringToBinaryW(b64.c_str(), (DWORD)b64.size(), CRYPT_STRING_BASE64, protectedData.data(), &protectedSize, nullptr, nullptr)) {
|
|
LogLine(L"DPAPI config base64 decode failed error=" + std::to_wstring(GetLastError()));
|
|
return false;
|
|
}
|
|
|
|
DATA_BLOB inBlob{};
|
|
inBlob.cbData = protectedSize;
|
|
inBlob.pbData = protectedData.data();
|
|
DATA_BLOB outBlob{};
|
|
if (!CryptUnprotectData(&inBlob, nullptr, nullptr, nullptr, nullptr, 0, &outBlob)) {
|
|
LogLine(L"DPAPI config decrypt failed error=" + std::to_wstring(GetLastError()));
|
|
return false;
|
|
}
|
|
|
|
std::string plain(reinterpret_cast<char*>(outBlob.pbData), reinterpret_cast<char*>(outBlob.pbData) + outBlob.cbData);
|
|
LocalFree(outBlob.pbData);
|
|
config = Trim(Utf8ToWide(plain));
|
|
return StartsWith(config, L"{");
|
|
}
|
|
|
|
static std::wstring ModuleDirectory() {
|
|
wchar_t path[MAX_PATH] = {};
|
|
DWORD len = GetModuleFileNameW((HMODULE)&__ImageBase, path, ARRAYSIZE(path));
|
|
if (len == 0 || len >= ARRAYSIZE(path)) return {};
|
|
PathRemoveFileSpecW(path);
|
|
return path;
|
|
}
|
|
|
|
static bool LoadLocalConfig(std::wstring& config) {
|
|
config.clear();
|
|
const std::wstring dir = ModuleDirectory();
|
|
if (!dir.empty()) {
|
|
ReadTextFile(dir + L"\\config.json", config);
|
|
}
|
|
if (config.empty()) {
|
|
ReadTextFile(L"C:\\Program Files\\DuoRdp\\config.json", config);
|
|
}
|
|
if (config.empty()) return false;
|
|
return TryDecodeDpapiConfig(config);
|
|
}
|
|
|
|
static bool IsAdminGroup(const std::wstring& group) {
|
|
const std::wstring name = PolicyUserName(group);
|
|
return name == L"administrators"
|
|
|| name == L"administrator"
|
|
|| name == L"domain admins"
|
|
|| name == L"администраторы";
|
|
}
|
|
|
|
static bool HasAdminGroup(const std::vector<std::wstring>& groups) {
|
|
for (const auto& group : groups) {
|
|
if (IsAdminGroup(group)) return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
static bool LocalPolicyRequires2Fa(const std::wstring& user, const std::vector<std::wstring>& groups, bool& required, bool& failClosed, bool& telegram, bool& totp) {
|
|
failClosed = true;
|
|
telegram = false;
|
|
totp = false;
|
|
if (Trim(user).empty()) {
|
|
required = false;
|
|
return true;
|
|
}
|
|
|
|
std::wstring config;
|
|
if (!LoadLocalConfig(config)) return false;
|
|
JsonBool(config, L"fail_closed", failClosed);
|
|
JsonUserConfiguredMethods(config, user, telegram, totp);
|
|
|
|
bool enabled = false;
|
|
if (!JsonBool(config, L"enabled", enabled)) return false;
|
|
if (!enabled) {
|
|
required = false;
|
|
return true;
|
|
}
|
|
|
|
bool allUsers = false;
|
|
JsonBool(config, L"require_for_all_users", allUsers);
|
|
if (allUsers) {
|
|
required = true;
|
|
return true;
|
|
}
|
|
|
|
bool admin2fa = false;
|
|
JsonBool(config, L"admin_2fa_enabled", admin2fa);
|
|
if (admin2fa && HasAdminGroup(groups)) {
|
|
required = true;
|
|
return true;
|
|
}
|
|
|
|
if (!JsonUserHasVerifiedMethod(config, user)) {
|
|
required = false;
|
|
return true;
|
|
}
|
|
|
|
required = JsonStringArrayContains(config, L"enabled_users", user)
|
|
|| JsonStringArrayIntersects(config, L"enabled_groups", groups);
|
|
return true;
|
|
}
|
|
|
|
static bool LocalFallbackRequires2Fa(const std::wstring& user, const std::vector<std::wstring>& groups, const std::wstring& reason) {
|
|
bool localRequired = false;
|
|
bool localFailClosed = true;
|
|
bool localTelegram = false;
|
|
bool localTotp = false;
|
|
if (LocalPolicyRequires2Fa(user, groups, localRequired, localFailClosed, localTelegram, localTotp)) {
|
|
const bool effectiveRequired = localRequired && localFailClosed;
|
|
LogLine(L"Policy " + reason + L"; local fallback for " + user
|
|
+ L" required=" + std::to_wstring(localRequired ? 1 : 0)
|
|
+ L" fail_closed=" + std::to_wstring(localFailClosed ? 1 : 0)
|
|
+ L" telegram=" + std::to_wstring(localTelegram ? 1 : 0)
|
|
+ L" totp=" + std::to_wstring(localTotp ? 1 : 0)
|
|
+ L" effective_required=" + std::to_wstring(effectiveRequired ? 1 : 0));
|
|
return effectiveRequired;
|
|
}
|
|
|
|
LogLine(L"Policy " + reason + L"; local fallback unavailable for " + user + L", fail closed");
|
|
return true;
|
|
}
|
|
|
|
static std::wstring JsonEscape(const std::wstring& value) {
|
|
std::wstring out;
|
|
out.reserve(value.size() + 8);
|
|
for (wchar_t ch : value) {
|
|
if (ch == L'\\' || ch == L'"') {
|
|
out.push_back(L'\\');
|
|
out.push_back(ch);
|
|
}
|
|
else if (ch == L'\r') out += L"\\r";
|
|
else if (ch == L'\n') out += L"\\n";
|
|
else out.push_back(ch);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
static std::wstring NewOtpChallengeId() {
|
|
GUID guid = {};
|
|
if (FAILED(CoCreateGuid(&guid))) return {};
|
|
wchar_t value[40] = {};
|
|
const int length = StringFromGUID2(guid, value, ARRAYSIZE(value));
|
|
// StringFromGUID2 returns a braced GUID. The wire protocol deliberately
|
|
// uses only its canonical 36-character form so the service can validate
|
|
// it without accepting arbitrary unbounded client input.
|
|
return length == 39 ? std::wstring(value + 1, 36) : std::wstring{};
|
|
}
|
|
|
|
static std::wstring UserNameOnly(const std::wstring& user) {
|
|
std::wstring value = Trim(user);
|
|
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);
|
|
return value;
|
|
}
|
|
|
|
static std::vector<std::wstring> UserGroups(const std::wstring& user) {
|
|
std::vector<std::wstring> groups;
|
|
const std::wstring account = UserNameOnly(user);
|
|
if (!account.empty()) {
|
|
LPBYTE buffer = nullptr;
|
|
DWORD entriesRead = 0;
|
|
DWORD totalEntries = 0;
|
|
NET_API_STATUS status = NetUserGetLocalGroups(
|
|
nullptr,
|
|
account.c_str(),
|
|
0,
|
|
LG_INCLUDE_INDIRECT,
|
|
&buffer,
|
|
MAX_PREFERRED_LENGTH,
|
|
&entriesRead,
|
|
&totalEntries);
|
|
if (status == NERR_Success && buffer) {
|
|
auto* rows = reinterpret_cast<LOCALGROUP_USERS_INFO_0*>(buffer);
|
|
for (DWORD i = 0; i < entriesRead; ++i) {
|
|
if (rows[i].lgrui0_name) groups.emplace_back(rows[i].lgrui0_name);
|
|
}
|
|
}
|
|
if (buffer) NetApiBufferFree(buffer);
|
|
if (status != NERR_Success) {
|
|
LogLine(L"NetUserGetLocalGroups failed user=" + account + L" status=" + std::to_wstring(status));
|
|
}
|
|
}
|
|
return groups;
|
|
}
|
|
|
|
static std::wstring GroupsJson(const std::vector<std::wstring>& groups) {
|
|
std::wstring json = L"[";
|
|
for (size_t i = 0; i < groups.size(); ++i) {
|
|
if (i) json += L",";
|
|
json += L"\"" + JsonEscape(groups[i]) + L"\"";
|
|
}
|
|
json += L"]";
|
|
return json;
|
|
}
|
|
|
|
static std::wstring UserGroupsJson(const std::wstring& user) {
|
|
return GroupsJson(UserGroups(user));
|
|
}
|
|
|
|
static std::string WideToUtf8(const std::wstring& value) {
|
|
if (value.empty()) return {};
|
|
int bytes = WideCharToMultiByte(CP_UTF8, 0, value.c_str(), (int)value.size(), nullptr, 0, nullptr, nullptr);
|
|
if (bytes <= 0) return {};
|
|
std::string out(bytes, '\0');
|
|
WideCharToMultiByte(CP_UTF8, 0, value.c_str(), (int)value.size(), out.data(), bytes, nullptr, nullptr);
|
|
return out;
|
|
}
|
|
|
|
static std::wstring Utf8ToWide(const std::string& value) {
|
|
if (value.empty()) return {};
|
|
int chars = MultiByteToWideChar(CP_UTF8, 0, value.c_str(), (int)value.size(), nullptr, 0);
|
|
if (chars <= 0) return {};
|
|
std::wstring out(chars, L'\0');
|
|
MultiByteToWideChar(CP_UTF8, 0, value.c_str(), (int)value.size(), out.data(), chars);
|
|
return out;
|
|
}
|
|
|
|
static void LogLine(const std::wstring& message) {
|
|
CreateDirectoryW(L"C:\\ProgramData\\DuoRdp", nullptr);
|
|
std::wofstream log(L"C:\\ProgramData\\DuoRdp\\logs.txt", std::ios::app);
|
|
if (!log.is_open()) {
|
|
CreateDirectoryW(L"C:\\Program Files\\DuoRdp", nullptr);
|
|
log.open(L"C:\\Program Files\\DuoRdp\\logs.txt", std::ios::app);
|
|
}
|
|
if (!log.is_open()) return;
|
|
SYSTEMTIME st = {};
|
|
GetLocalTime(&st);
|
|
log << L"[" << st.wYear << L"-" << st.wMonth << L"-" << st.wDay
|
|
<< L" " << st.wHour << L":" << st.wMinute << L":" << st.wSecond
|
|
<< L"] [CredentialProvider] [pid=" << GetCurrentProcessId() << L"] " << message << std::endl;
|
|
}
|
|
|
|
static HRESULT RetrieveNegotiateAuthPackage(ULONG* pulAuthPackage) {
|
|
if (!pulAuthPackage) return E_INVALIDARG;
|
|
HANDLE hLsa = nullptr;
|
|
NTSTATUS status = LsaConnectUntrusted(&hLsa);
|
|
if (status != STATUS_SUCCESS) return HRESULT_FROM_WIN32(LsaNtStatusToWinError(status));
|
|
|
|
const char* name = NEGOSSP_NAME_A;
|
|
LSA_STRING lsasz;
|
|
lsasz.Buffer = const_cast<PCHAR>(name);
|
|
lsasz.Length = (USHORT)strlen(name);
|
|
lsasz.MaximumLength = lsasz.Length + 1;
|
|
|
|
status = LsaLookupAuthenticationPackage(hLsa, &lsasz, pulAuthPackage);
|
|
LsaDeregisterLogonProcess(hLsa);
|
|
if (status != STATUS_SUCCESS) return HRESULT_FROM_WIN32(LsaNtStatusToWinError(status));
|
|
return S_OK;
|
|
}
|
|
|
|
static void InitUnicodeString(UNICODE_STRING& target, const std::wstring& value) {
|
|
const size_t byteLength = value.size() * sizeof(wchar_t);
|
|
const size_t maxLength = (size_t)USHRT_MAX;
|
|
const size_t clampedLength = byteLength < maxLength ? byteLength : maxLength;
|
|
target.Length = (USHORT)clampedLength;
|
|
target.MaximumLength = (USHORT)std::min<size_t>(target.Length + sizeof(wchar_t), maxLength);
|
|
target.Buffer = const_cast<PWSTR>(value.c_str());
|
|
}
|
|
|
|
static void SplitDomainAndUser(const std::wstring& account, std::wstring& domain, std::wstring& user) {
|
|
std::wstring value = Trim(account);
|
|
const size_t slash = value.find_last_of(L"\\/");
|
|
if (slash != std::wstring::npos) {
|
|
domain = value.substr(0, slash);
|
|
user = slash + 1 < value.size() ? value.substr(slash + 1) : L"";
|
|
return;
|
|
}
|
|
|
|
domain.clear();
|
|
user = value;
|
|
}
|
|
|
|
static std::wstring HexStatus(NTSTATUS status) {
|
|
wchar_t buffer[16] = {};
|
|
swprintf_s(buffer, L"0x%08lX", static_cast<unsigned long>(status));
|
|
return buffer;
|
|
}
|
|
|
|
static HRESULT InitKerbInteractiveUnlockLogon(
|
|
const std::wstring& domain,
|
|
const std::wstring& user,
|
|
const std::wstring& password,
|
|
CREDENTIAL_PROVIDER_USAGE_SCENARIO scenario,
|
|
KERB_INTERACTIVE_UNLOCK_LOGON& logon) {
|
|
ZeroMemory(&logon, sizeof(logon));
|
|
logon.Logon.MessageType = scenario == CPUS_UNLOCK_WORKSTATION
|
|
? KerbWorkstationUnlockLogon
|
|
: KerbInteractiveLogon;
|
|
InitUnicodeString(logon.Logon.LogonDomainName, domain);
|
|
InitUnicodeString(logon.Logon.UserName, user);
|
|
InitUnicodeString(logon.Logon.Password, password);
|
|
return S_OK;
|
|
}
|
|
|
|
static std::wstring TrimNullTerminator(std::wstring value) {
|
|
if (!value.empty() && value.back() == L'\0') value.pop_back();
|
|
return value;
|
|
}
|
|
|
|
static std::wstring PasswordForSerialization(const std::wstring& password, CREDENTIAL_PROVIDER_USAGE_SCENARIO scenario) {
|
|
if (password.empty() || scenario == CPUS_CREDUI) return password;
|
|
|
|
std::wstring mutablePassword = password;
|
|
CRED_PROTECTION_TYPE protectionType = CredUnprotected;
|
|
if (CredIsProtectedW(mutablePassword.data(), &protectionType) && protectionType != CredUnprotected) {
|
|
return password;
|
|
}
|
|
|
|
DWORD protectedChars = 0;
|
|
std::wstring passwordWithTerminator = password;
|
|
passwordWithTerminator.push_back(L'\0');
|
|
if (CredProtectW(FALSE, passwordWithTerminator.data(), (DWORD)passwordWithTerminator.size(), nullptr, &protectedChars, nullptr) ||
|
|
GetLastError() != ERROR_INSUFFICIENT_BUFFER || protectedChars == 0) {
|
|
LogLine(L"CredProtect size failed error=" + std::to_wstring(GetLastError()) + L"; using raw password");
|
|
return password;
|
|
}
|
|
|
|
std::wstring protectedPassword(protectedChars, L'\0');
|
|
if (!CredProtectW(FALSE, passwordWithTerminator.data(), (DWORD)passwordWithTerminator.size(), protectedPassword.data(), &protectedChars, nullptr)) {
|
|
LogLine(L"CredProtect failed error=" + std::to_wstring(GetLastError()) + L"; using raw password");
|
|
return password;
|
|
}
|
|
protectedPassword.resize(protectedChars);
|
|
return TrimNullTerminator(protectedPassword);
|
|
}
|
|
|
|
static HRESULT PackKerbInteractiveUnlockLogon(
|
|
const KERB_INTERACTIVE_UNLOCK_LOGON& logon,
|
|
BYTE** packed,
|
|
DWORD* packedSize) {
|
|
if (!packed || !packedSize) return E_INVALIDARG;
|
|
*packed = nullptr;
|
|
*packedSize = 0;
|
|
|
|
const DWORD domainSize = logon.Logon.LogonDomainName.MaximumLength;
|
|
const DWORD userSize = logon.Logon.UserName.MaximumLength;
|
|
const DWORD passwordSize = logon.Logon.Password.MaximumLength;
|
|
const DWORD totalSize = sizeof(KERB_INTERACTIVE_UNLOCK_LOGON) + domainSize + userSize + passwordSize;
|
|
|
|
BYTE* buffer = (BYTE*)CoTaskMemAlloc(totalSize);
|
|
if (!buffer) return E_OUTOFMEMORY;
|
|
ZeroMemory(buffer, totalSize);
|
|
|
|
auto* packedLogon = reinterpret_cast<KERB_INTERACTIVE_UNLOCK_LOGON*>(buffer);
|
|
CopyMemory(packedLogon, &logon, sizeof(KERB_INTERACTIVE_UNLOCK_LOGON));
|
|
|
|
BYTE* next = buffer + sizeof(KERB_INTERACTIVE_UNLOCK_LOGON);
|
|
auto packString = [&](UNICODE_STRING& target, const UNICODE_STRING& source) {
|
|
target.Length = source.Length;
|
|
target.MaximumLength = source.MaximumLength;
|
|
if (source.MaximumLength && source.Buffer) {
|
|
target.Buffer = reinterpret_cast<PWSTR>(next - buffer);
|
|
CopyMemory(next, source.Buffer, source.MaximumLength);
|
|
next += source.MaximumLength;
|
|
}
|
|
else {
|
|
target.Buffer = nullptr;
|
|
}
|
|
};
|
|
|
|
packString(packedLogon->Logon.LogonDomainName, logon.Logon.LogonDomainName);
|
|
packString(packedLogon->Logon.UserName, logon.Logon.UserName);
|
|
packString(packedLogon->Logon.Password, logon.Logon.Password);
|
|
|
|
*packed = buffer;
|
|
*packedSize = totalSize;
|
|
return S_OK;
|
|
}
|
|
|
|
DuoCredential::DuoCredential()
|
|
: _cRef(1), _events(nullptr), _statusText(L"Enter username and password"), _scenario(CPUS_LOGON),
|
|
_policyKnown(false), _requires2fa(false), _twoFactorStep(false),
|
|
_telegramAvailable(false), _totpAvailable(false), _serializedCredential(false), _fixedUser(false), _showPassword(false),
|
|
_otpMethod(0) {
|
|
LogLine(L"credential created");
|
|
}
|
|
|
|
void DuoCredential::SetUsageScenario(CREDENTIAL_PROVIDER_USAGE_SCENARIO scenario) {
|
|
_scenario = scenario;
|
|
}
|
|
|
|
void DuoCredential::Initialize(ICredentialProviderUser* user) {
|
|
_serializedCredential = false;
|
|
if (!user) return;
|
|
_fixedUser = true;
|
|
|
|
PWSTR value = nullptr;
|
|
if (SUCCEEDED(user->GetStringValue(PKEY_Identity_UserName, &value)) && value) {
|
|
_username = value;
|
|
CoTaskMemFree(value);
|
|
value = nullptr;
|
|
}
|
|
if (SUCCEEDED(user->GetStringValue(PKEY_Identity_QualifiedUserName, &value)) && value) {
|
|
_qualifiedUsername = value;
|
|
CoTaskMemFree(value);
|
|
value = nullptr;
|
|
}
|
|
if (SUCCEEDED(user->GetStringValue(PKEY_Identity_DisplayName, &value)) && value) {
|
|
_displayName = value;
|
|
CoTaskMemFree(value);
|
|
value = nullptr;
|
|
}
|
|
|
|
if (_username.empty()) _username = _qualifiedUsername;
|
|
if (_displayName.empty()) _displayName = _username;
|
|
ResetTwoFactorState();
|
|
RefreshPolicyState();
|
|
_statusText = L"Enter password";
|
|
LogLine(L"initialized username=" + _username
|
|
+ L" qualified=" + _qualifiedUsername
|
|
+ L" display=" + _displayName
|
|
+ L" requires2fa=" + std::to_wstring(_requires2fa ? 1 : 0));
|
|
}
|
|
|
|
void DuoCredential::InitializeSerialized(const std::wstring& username, const std::wstring& password) {
|
|
_serializedCredential = true;
|
|
_fixedUser = false;
|
|
if (!_username.empty() && username.empty()) {
|
|
_password = password;
|
|
}
|
|
else {
|
|
_username = username;
|
|
_qualifiedUsername = username;
|
|
_displayName = username;
|
|
_password = password;
|
|
}
|
|
|
|
ResetTwoFactorState();
|
|
RefreshPolicyState();
|
|
_twoFactorStep = _requires2fa;
|
|
_statusText = _twoFactorStep ? L"Enter one-time code" : L"Signing in";
|
|
LogLine(L"serialized credentials initialized username=" + _username
|
|
+ L" password_len=" + std::to_wstring(_password.size())
|
|
+ L" requires2fa=" + std::to_wstring(_requires2fa ? 1 : 0));
|
|
}
|
|
|
|
IFACEMETHODIMP DuoCredential::QueryInterface(REFIID riid, void** ppv) {
|
|
if (!ppv) return E_INVALIDARG;
|
|
*ppv = nullptr;
|
|
if (riid == IID_IUnknown || riid == IID_ICredentialProviderCredential) {
|
|
*ppv = static_cast<ICredentialProviderCredential*>(this);
|
|
AddRef();
|
|
return S_OK;
|
|
}
|
|
return E_NOINTERFACE;
|
|
}
|
|
|
|
IFACEMETHODIMP_(ULONG) DuoCredential::AddRef() { return InterlockedIncrement(&_cRef); }
|
|
IFACEMETHODIMP_(ULONG) DuoCredential::Release() { long cRef = InterlockedDecrement(&_cRef); if (!cRef) delete this; return cRef; }
|
|
|
|
IFACEMETHODIMP DuoCredential::Advise(ICredentialProviderCredentialEvents* pcpce) { _events = pcpce; if (_events) _events->AddRef(); return S_OK; }
|
|
IFACEMETHODIMP DuoCredential::UnAdvise() { if (_events) { _events->Release(); _events = nullptr; } return S_OK; }
|
|
IFACEMETHODIMP DuoCredential::SetSelected(BOOL* pbAutoLogon) {
|
|
if (pbAutoLogon) {
|
|
if (!_policyKnown) RefreshPolicyState();
|
|
*pbAutoLogon = (_serializedCredential && !_requires2fa) ? TRUE : FALSE;
|
|
}
|
|
return S_OK;
|
|
}
|
|
IFACEMETHODIMP DuoCredential::SetDeselected() { return S_OK; }
|
|
|
|
IFACEMETHODIMP DuoCredential::GetFieldState(DWORD dwFieldID, CREDENTIAL_PROVIDER_FIELD_STATE* pcpfs, CREDENTIAL_PROVIDER_FIELD_INTERACTIVE_STATE* pcpfis) {
|
|
if (!pcpfs || !pcpfis) return E_INVALIDARG;
|
|
*pcpfis = CPFIS_NONE;
|
|
|
|
const bool fixedUser = _fixedUser && !_username.empty();
|
|
if (!_policyKnown) RefreshPolicyState();
|
|
const bool inTwoFactorStep = IsTwoFactorStep();
|
|
|
|
switch (dwFieldID) {
|
|
case FID_TITLE:
|
|
*pcpfs = CPFS_DISPLAY_IN_BOTH;
|
|
return S_OK;
|
|
case FID_USERNAME:
|
|
*pcpfs = (fixedUser || inTwoFactorStep) ? CPFS_HIDDEN : CPFS_DISPLAY_IN_SELECTED_TILE;
|
|
return S_OK;
|
|
case FID_PASSWORD:
|
|
*pcpfs = (inTwoFactorStep || _showPassword) ? CPFS_HIDDEN : CPFS_DISPLAY_IN_SELECTED_TILE;
|
|
return S_OK;
|
|
case FID_PASSWORD_VISIBLE:
|
|
*pcpfs = (!inTwoFactorStep && _showPassword) ? CPFS_DISPLAY_IN_SELECTED_TILE : CPFS_HIDDEN;
|
|
return S_OK;
|
|
case FID_SHOW_PASSWORD:
|
|
*pcpfs = inTwoFactorStep ? CPFS_HIDDEN : CPFS_DISPLAY_IN_SELECTED_TILE;
|
|
return S_OK;
|
|
case FID_SUBMIT:
|
|
*pcpfs = (!inTwoFactorStep || HasConfigured2FaMethod()) ? CPFS_DISPLAY_IN_SELECTED_TILE : CPFS_HIDDEN;
|
|
return S_OK;
|
|
case FID_STATUS:
|
|
*pcpfs = CPFS_DISPLAY_IN_SELECTED_TILE;
|
|
return S_OK;
|
|
case FID_OTP_METHOD:
|
|
*pcpfs = inTwoFactorStep ? CPFS_DISPLAY_IN_SELECTED_TILE : CPFS_HIDDEN;
|
|
return S_OK;
|
|
case FID_OTP_LABEL:
|
|
*pcpfs = (inTwoFactorStep && !HasConfigured2FaMethod()) ? CPFS_DISPLAY_IN_SELECTED_TILE : CPFS_HIDDEN;
|
|
return S_OK;
|
|
case FID_OTP:
|
|
*pcpfs = (inTwoFactorStep && HasConfigured2FaMethod()) ? CPFS_DISPLAY_IN_SELECTED_TILE : CPFS_HIDDEN;
|
|
return S_OK;
|
|
case FID_GET_OTP:
|
|
*pcpfs = (inTwoFactorStep && _telegramAvailable) ? CPFS_DISPLAY_IN_SELECTED_TILE : CPFS_HIDDEN;
|
|
return S_OK;
|
|
default:
|
|
return E_INVALIDARG;
|
|
}
|
|
}
|
|
|
|
IFACEMETHODIMP DuoCredential::GetStringValue(DWORD dwFieldID, PWSTR* ppwsz) {
|
|
if (!ppwsz) return E_INVALIDARG;
|
|
*ppwsz = nullptr;
|
|
std::wstring value;
|
|
const bool fixedUser = _fixedUser && !_username.empty();
|
|
switch (dwFieldID) {
|
|
case FID_TITLE:
|
|
value = IsTwoFactorStep() && !_username.empty()
|
|
? _username
|
|
: (fixedUser && !_displayName.empty() ? _displayName : L"Other user");
|
|
break;
|
|
case FID_USERNAME: value = _username; break;
|
|
case FID_PASSWORD: value = _password; break;
|
|
case FID_PASSWORD_VISIBLE: value = _password; break;
|
|
case FID_OTP_LABEL: value = L"В аккаунте не настроена 2FA авторизация"; break;
|
|
case FID_OTP: value = _otp; break;
|
|
case FID_GET_OTP: value = OtpButtonText(); break;
|
|
case FID_STATUS: value = _statusText; break;
|
|
default: return E_INVALIDARG;
|
|
}
|
|
return SHStrDupW(value.c_str(), ppwsz);
|
|
}
|
|
|
|
IFACEMETHODIMP DuoCredential::GetBitmapValue(DWORD, HBITMAP*) { return E_NOTIMPL; }
|
|
IFACEMETHODIMP DuoCredential::GetCheckboxValue(DWORD dwFieldID, BOOL* pbChecked, PWSTR* ppwszLabel) {
|
|
if (dwFieldID != FID_SHOW_PASSWORD || !pbChecked || !ppwszLabel) return E_INVALIDARG;
|
|
*pbChecked = _showPassword ? TRUE : FALSE;
|
|
return SHStrDupW(L"Show password", ppwszLabel);
|
|
}
|
|
IFACEMETHODIMP DuoCredential::GetSubmitButtonValue(DWORD dwFieldID, DWORD* pdwAdjacentTo) {
|
|
if (dwFieldID != FID_SUBMIT || !pdwAdjacentTo) return E_INVALIDARG;
|
|
if (!_policyKnown) RefreshPolicyState();
|
|
*pdwAdjacentTo = IsTwoFactorStep() ? FID_OTP : (_showPassword ? FID_PASSWORD_VISIBLE : FID_PASSWORD);
|
|
return S_OK;
|
|
}
|
|
IFACEMETHODIMP DuoCredential::GetComboBoxValueCount(DWORD dwFieldID, DWORD* pcItems, DWORD* pdwSelectedItem) {
|
|
if (dwFieldID != FID_OTP_METHOD || !pcItems || !pdwSelectedItem) return E_INVALIDARG;
|
|
if (!_policyKnown) RefreshPolicyState();
|
|
*pcItems = AvailableMethodCount();
|
|
*pdwSelectedItem = 0;
|
|
if (*pcItems > 0 && _otpMethod == 1 && _telegramAvailable && _totpAvailable) {
|
|
*pdwSelectedItem = 1;
|
|
}
|
|
return S_OK;
|
|
}
|
|
IFACEMETHODIMP DuoCredential::GetComboBoxValueAt(DWORD dwFieldID, DWORD dwItem, PWSTR* ppwszItem) {
|
|
if (dwFieldID != FID_OTP_METHOD || !ppwszItem) return E_INVALIDARG;
|
|
if (!_policyKnown) RefreshPolicyState();
|
|
DWORD method = 0;
|
|
if (!ComboIndexToMethod(dwItem, method)) return E_INVALIDARG;
|
|
return SHStrDupW(method == 0 ? L"телеграмм" : L"гугл код", ppwszItem);
|
|
}
|
|
|
|
IFACEMETHODIMP DuoCredential::SetStringValue(DWORD dwFieldID, PCWSTR pwz) {
|
|
std::wstring v = pwz ? pwz : L"";
|
|
if (dwFieldID == FID_USERNAME) {
|
|
// As with the password field below, LogonUI may flush a hidden
|
|
// control during a redraw. At the OTP step username is hidden and
|
|
// cannot be intentionally edited, so preserve this tile's binding.
|
|
if (IsTwoFactorStep() && v.empty() && !_username.empty()) {
|
|
LogLine(L"ignored empty hidden-username update during 2FA username=" + _username);
|
|
return S_OK;
|
|
}
|
|
if (_username != v) {
|
|
_otp.clear();
|
|
_otpRequestedFor.clear();
|
|
_policyKnown = false;
|
|
ResetTwoFactorState();
|
|
}
|
|
_username = v;
|
|
if (!_fixedUser) {
|
|
_qualifiedUsername = v;
|
|
_displayName.clear();
|
|
}
|
|
RefreshPolicyState();
|
|
_statusText = L"Enter password";
|
|
LogLine(L"username changed username=" + _username
|
|
+ L" requires2fa=" + std::to_wstring(_requires2fa ? 1 : 0));
|
|
RefreshDynamicFields();
|
|
}
|
|
else if (dwFieldID == FID_PASSWORD || dwFieldID == FID_PASSWORD_VISIBLE) {
|
|
// LogonUI can flush a field while it is being hidden. Once the tile
|
|
// has entered the OTP step, that empty callback is not a user edit:
|
|
// treating it as one erases the saved primary password, resets the
|
|
// OTP marker, and lets the submit handler issue a second code.
|
|
// Preserve the credential captured before entering 2FA. A real
|
|
// password edit is impossible while these fields are hidden.
|
|
if (IsTwoFactorStep() && v.empty() && !_password.empty()) {
|
|
LogLine(L"ignored empty hidden-password update during 2FA username=" + _username);
|
|
return S_OK;
|
|
}
|
|
if (_password != v) {
|
|
_otp.clear();
|
|
_otpRequestedFor.clear();
|
|
ResetTwoFactorState();
|
|
_statusText = L"Enter password";
|
|
}
|
|
_password = v;
|
|
LogLine(L"password updated username=" + _username + L" length=" + std::to_wstring(_password.size()));
|
|
RefreshDynamicFields();
|
|
}
|
|
else if (dwFieldID == FID_OTP) {
|
|
_otp = v;
|
|
LogLine(L"otp updated username=" + _username + L" length=" + std::to_wstring(_otp.size()));
|
|
}
|
|
else return E_INVALIDARG;
|
|
return S_OK;
|
|
}
|
|
|
|
IFACEMETHODIMP DuoCredential::SetCheckboxValue(DWORD dwFieldID, BOOL bChecked) {
|
|
if (dwFieldID != FID_SHOW_PASSWORD) return E_INVALIDARG;
|
|
_showPassword = bChecked ? true : false;
|
|
LogLine(L"show password changed username=" + _username + L" show=" + std::to_wstring(_showPassword ? 1 : 0));
|
|
if (_events) {
|
|
const bool inTwoFactorStep = IsTwoFactorStep();
|
|
_events->SetFieldString(this, FID_PASSWORD, _password.c_str());
|
|
_events->SetFieldString(this, FID_PASSWORD_VISIBLE, _password.c_str());
|
|
_events->SetFieldState(this, FID_PASSWORD, (inTwoFactorStep || _showPassword) ? CPFS_HIDDEN : CPFS_DISPLAY_IN_SELECTED_TILE);
|
|
_events->SetFieldState(this, FID_PASSWORD_VISIBLE, (!inTwoFactorStep && _showPassword) ? CPFS_DISPLAY_IN_SELECTED_TILE : CPFS_HIDDEN);
|
|
_events->SetFieldState(this, FID_SHOW_PASSWORD, inTwoFactorStep ? CPFS_HIDDEN : CPFS_DISPLAY_IN_SELECTED_TILE);
|
|
_events->SetFieldSubmitButton(this, FID_SUBMIT, inTwoFactorStep ? FID_OTP : (_showPassword ? FID_PASSWORD_VISIBLE : FID_PASSWORD));
|
|
}
|
|
return S_OK;
|
|
}
|
|
IFACEMETHODIMP DuoCredential::SetComboBoxSelectedValue(DWORD dwFieldID, DWORD dwSelectedItem) {
|
|
if (dwFieldID != FID_OTP_METHOD) return E_INVALIDARG;
|
|
if (!_policyKnown) RefreshPolicyState();
|
|
DWORD method = 0;
|
|
if (!ComboIndexToMethod(dwSelectedItem, method)) return E_INVALIDARG;
|
|
_otpMethod = method;
|
|
_otp.clear();
|
|
if (_otpMethod != 0) {
|
|
_otpRequestedFor.clear();
|
|
}
|
|
_statusText = _otpMethod == 0 ? L"Нажмите Отправить одноразовый код" : L"Введите код из Google Authenticator";
|
|
LogLine(L"otp method changed username=" + _username + L" method=" + std::to_wstring(_otpMethod));
|
|
if (_events) {
|
|
_events->SetFieldString(this, FID_OTP, L"");
|
|
RefreshDynamicFields();
|
|
}
|
|
return S_OK;
|
|
}
|
|
IFACEMETHODIMP DuoCredential::CommandLinkClicked(DWORD dwFieldID) {
|
|
if (dwFieldID != FID_GET_OTP) return E_INVALIDARG;
|
|
LogLine(L"send otp clicked username=" + _username);
|
|
if (_username.empty()) {
|
|
_statusText = L"Enter username first";
|
|
}
|
|
else if (_otpMethod != 0) {
|
|
EnterTwoFactorStep();
|
|
_statusText = _totpAvailable ? L"Введите код из Google Authenticator" : L"В аккаунте не настроена 2FA авторизация";
|
|
}
|
|
else if (_password.empty()) {
|
|
// A resend needs a password entered, but must not perform a second
|
|
// Windows logon here. LogonUserW with a network logon type rejects
|
|
// valid interactive/AAD credentials in a Credential Provider and was
|
|
// preventing this command from ever reaching the OTP service.
|
|
_statusText = L"Enter password first";
|
|
}
|
|
else {
|
|
if (!ShouldRequire2Fa(_username)) {
|
|
RefreshPolicyState();
|
|
_statusText = L"2FA is not required for this user";
|
|
RefreshDynamicFields();
|
|
}
|
|
else if (!HasConfigured2FaMethod()) {
|
|
EnterTwoFactorStep();
|
|
_statusText.clear();
|
|
LogLine(L"Send code blocked: no 2FA method configured for " + _username);
|
|
}
|
|
else {
|
|
// This is the sole code-issuing path. Every explicit click asks
|
|
// the service for a fresh replacement code for this tile.
|
|
const bool isResend = _otpRequestedFor == _username;
|
|
if (RequestOtp(_username)) {
|
|
EnterTwoFactorStep();
|
|
_otp.clear();
|
|
_otpRequestedFor = _username;
|
|
if (_statusText.empty() || _statusText == L"Enter one-time code") {
|
|
_statusText = isResend
|
|
? L"Отправлен новый код. Предыдущий код больше не действует."
|
|
: L"Код отправлен. Введите его и нажмите Login.";
|
|
}
|
|
LogLine((isResend ? L"OTP resent by user action for " : L"OTP sent by user action for ") + _username);
|
|
}
|
|
else {
|
|
EnterTwoFactorStep();
|
|
if (_statusText.empty() || _statusText == L"Enter one-time code") {
|
|
_statusText = L"Code request failed";
|
|
}
|
|
LogLine(L"Send one-time code failed for " + _username);
|
|
}
|
|
}
|
|
}
|
|
|
|
if (_events) {
|
|
RefreshDynamicFields();
|
|
}
|
|
return S_OK;
|
|
}
|
|
|
|
bool DuoCredential::PipeRequest(const std::wstring& requestJson, std::wstring& responseJson) {
|
|
HANDLE hPipe = CreateFileW(L"\\\\.\\pipe\\duordp-auth-pipe", GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, nullptr);
|
|
if (hPipe == INVALID_HANDLE_VALUE) {
|
|
LogLine(L"Pipe open failed, error=" + std::to_wstring(GetLastError()) + L", request=" + requestJson);
|
|
return false;
|
|
}
|
|
|
|
std::string req = WideToUtf8(requestJson);
|
|
req.push_back('\n');
|
|
DWORD written = 0;
|
|
BOOL ok = WriteFile(hPipe, req.data(), (DWORD)req.size(), &written, nullptr);
|
|
if (!ok) {
|
|
LogLine(L"Pipe write failed, error=" + std::to_wstring(GetLastError()));
|
|
CloseHandle(hPipe);
|
|
return false;
|
|
}
|
|
|
|
char buf[4096] = {};
|
|
DWORD read = 0;
|
|
ok = ReadFile(hPipe, buf, sizeof(buf) - 1, &read, nullptr);
|
|
CloseHandle(hPipe);
|
|
if (!ok || read == 0) {
|
|
LogLine(L"Pipe read failed, error=" + std::to_wstring(GetLastError()));
|
|
return false;
|
|
}
|
|
std::string resp(buf, buf + read);
|
|
responseJson = Utf8ToWide(resp);
|
|
LogLine(L"Pipe response=" + responseJson);
|
|
return true;
|
|
}
|
|
|
|
bool DuoCredential::ShouldRequire2Fa(const std::wstring& user) {
|
|
_telegramAvailable = false;
|
|
_totpAvailable = false;
|
|
if (Trim(user).empty()) return false;
|
|
|
|
const auto groups = UserGroups(user);
|
|
std::wstring req = L"{\"action\":\"GetPolicy\",\"username\":\"" + JsonEscape(user) + L"\",\"groups\":" + GroupsJson(groups) + L"}";
|
|
std::wstring resp;
|
|
if (!PipeRequest(req, resp)) {
|
|
bool localRequired = false;
|
|
bool localFailClosed = true;
|
|
if (LocalPolicyRequires2Fa(user, groups, localRequired, localFailClosed, _telegramAvailable, _totpAvailable)) {
|
|
return localRequired && localFailClosed;
|
|
}
|
|
return LocalFallbackRequires2Fa(user, groups, L"pipe unavailable");
|
|
}
|
|
if (JsonStringEquals(resp, L"error", L"policy_error") || JsonStringEquals(resp, L"error", L"service_unavailable")) {
|
|
bool localRequired = false;
|
|
bool localFailClosed = true;
|
|
if (LocalPolicyRequires2Fa(user, groups, localRequired, localFailClosed, _telegramAvailable, _totpAvailable)) {
|
|
return localRequired && localFailClosed;
|
|
}
|
|
return LocalFallbackRequires2Fa(user, groups, L"backend unavailable");
|
|
}
|
|
bool required = false;
|
|
bool haveRequired = JsonBool(resp, L"required", required);
|
|
if (!haveRequired) {
|
|
bool localRequired = false;
|
|
bool localFailClosed = true;
|
|
if (LocalPolicyRequires2Fa(user, groups, localRequired, localFailClosed, _telegramAvailable, _totpAvailable)) {
|
|
return localRequired && localFailClosed;
|
|
}
|
|
return LocalFallbackRequires2Fa(user, groups, L"malformed policy response");
|
|
}
|
|
JsonBool(resp, L"telegramConfigured", _telegramAvailable);
|
|
JsonBool(resp, L"totpConfigured", _totpAvailable);
|
|
return required;
|
|
}
|
|
|
|
void DuoCredential::RefreshPolicyState() {
|
|
_requires2fa = !_username.empty() && ShouldRequire2Fa(_username);
|
|
if (!_requires2fa) {
|
|
_twoFactorStep = false;
|
|
}
|
|
RefreshSelectedMethod();
|
|
_policyKnown = true;
|
|
LogLine(L"policy refreshed username=" + _username
|
|
+ L" requires2fa=" + std::to_wstring(_requires2fa ? 1 : 0)
|
|
+ L" telegram=" + std::to_wstring(_telegramAvailable ? 1 : 0)
|
|
+ L" totp=" + std::to_wstring(_totpAvailable ? 1 : 0));
|
|
}
|
|
|
|
void DuoCredential::RefreshDynamicFields() {
|
|
if (!_events) return;
|
|
const bool fixedUser = _fixedUser && !_username.empty();
|
|
const bool inTwoFactorStep = IsTwoFactorStep();
|
|
const bool hasMethods = HasConfigured2FaMethod();
|
|
const auto methodState = inTwoFactorStep ? CPFS_DISPLAY_IN_SELECTED_TILE : CPFS_HIDDEN;
|
|
const auto sendState = (inTwoFactorStep && _telegramAvailable) ? CPFS_DISPLAY_IN_SELECTED_TILE : CPFS_HIDDEN;
|
|
const auto noMethodState = (inTwoFactorStep && !hasMethods) ? CPFS_DISPLAY_IN_SELECTED_TILE : CPFS_HIDDEN;
|
|
const auto otpState = (inTwoFactorStep && hasMethods) ? CPFS_DISPLAY_IN_SELECTED_TILE : CPFS_HIDDEN;
|
|
LogLine(L"refresh fields username=" + _username
|
|
+ L" two_factor_step=" + std::to_wstring(inTwoFactorStep ? 1 : 0)
|
|
+ L" telegram=" + std::to_wstring(_telegramAvailable ? 1 : 0)
|
|
+ L" totp=" + std::to_wstring(_totpAvailable ? 1 : 0)
|
|
+ L" otp_visible=" + std::to_wstring(otpState == CPFS_DISPLAY_IN_SELECTED_TILE ? 1 : 0));
|
|
_events->SetFieldState(this, FID_USERNAME, (fixedUser || inTwoFactorStep) ? CPFS_HIDDEN : CPFS_DISPLAY_IN_SELECTED_TILE);
|
|
_events->SetFieldState(this, FID_PASSWORD, (inTwoFactorStep || _showPassword) ? CPFS_HIDDEN : CPFS_DISPLAY_IN_SELECTED_TILE);
|
|
_events->SetFieldState(this, FID_PASSWORD_VISIBLE, (!inTwoFactorStep && _showPassword) ? CPFS_DISPLAY_IN_SELECTED_TILE : CPFS_HIDDEN);
|
|
_events->SetFieldState(this, FID_SHOW_PASSWORD, inTwoFactorStep ? CPFS_HIDDEN : CPFS_DISPLAY_IN_SELECTED_TILE);
|
|
_events->SetFieldState(this, FID_OTP_METHOD, methodState);
|
|
_events->SetFieldState(this, FID_OTP_LABEL, noMethodState);
|
|
_events->SetFieldState(this, FID_OTP, otpState);
|
|
_events->SetFieldState(this, FID_GET_OTP, sendState);
|
|
_events->SetFieldState(this, FID_SUBMIT, (!inTwoFactorStep || hasMethods) ? CPFS_DISPLAY_IN_SELECTED_TILE : CPFS_HIDDEN);
|
|
_events->SetFieldString(this, FID_PASSWORD, _password.c_str());
|
|
_events->SetFieldString(this, FID_PASSWORD_VISIBLE, _password.c_str());
|
|
_events->SetFieldString(this, FID_GET_OTP, OtpButtonText().c_str());
|
|
_events->SetFieldString(this, FID_OTP_LABEL, L"В аккаунте не настроена 2FA авторизация");
|
|
_events->SetFieldString(this, FID_OTP, _otp.c_str());
|
|
_events->SetFieldString(this, FID_STATUS, _statusText.c_str());
|
|
_events->SetFieldSubmitButton(this, FID_SUBMIT, inTwoFactorStep ? FID_OTP : (_showPassword ? FID_PASSWORD_VISIBLE : FID_PASSWORD));
|
|
}
|
|
|
|
void DuoCredential::ResetTwoFactorState() {
|
|
_twoFactorStep = false;
|
|
_otpChallengeId.clear();
|
|
}
|
|
|
|
bool DuoCredential::IsTwoFactorStep() const {
|
|
return _requires2fa && _twoFactorStep;
|
|
}
|
|
|
|
bool DuoCredential::HasConfigured2FaMethod() const {
|
|
return _telegramAvailable || _totpAvailable;
|
|
}
|
|
|
|
DWORD DuoCredential::AvailableMethodCount() const {
|
|
return (_telegramAvailable ? 1u : 0u) + (_totpAvailable ? 1u : 0u);
|
|
}
|
|
|
|
bool DuoCredential::ComboIndexToMethod(DWORD item, DWORD& method) const {
|
|
DWORD index = 0;
|
|
if (_telegramAvailable) {
|
|
if (item == index) {
|
|
method = 0;
|
|
return true;
|
|
}
|
|
++index;
|
|
}
|
|
if (_totpAvailable) {
|
|
if (item == index) {
|
|
method = 1;
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
void DuoCredential::RefreshSelectedMethod() {
|
|
if (_otpMethod == 0 && !_telegramAvailable && _totpAvailable) {
|
|
_otpMethod = 1;
|
|
}
|
|
else if (_otpMethod == 1 && !_totpAvailable && _telegramAvailable) {
|
|
_otpMethod = 0;
|
|
}
|
|
else if (!HasConfigured2FaMethod()) {
|
|
_otpMethod = 0;
|
|
}
|
|
}
|
|
|
|
std::wstring DuoCredential::OtpButtonText() const {
|
|
return _otpRequestedFor == _username && !_username.empty()
|
|
? L"Отправить новый одноразовый код"
|
|
: L"Отправить одноразовый код";
|
|
}
|
|
|
|
void DuoCredential::EnterTwoFactorStep() {
|
|
if (!_requires2fa) {
|
|
_twoFactorStep = false;
|
|
return;
|
|
}
|
|
if (!_twoFactorStep) {
|
|
LogLine(L"entering 2FA step username=" + _username);
|
|
}
|
|
_twoFactorStep = true;
|
|
_showPassword = false;
|
|
RefreshSelectedMethod();
|
|
if (!HasConfigured2FaMethod()) {
|
|
_statusText.clear();
|
|
}
|
|
}
|
|
|
|
bool DuoCredential::RequestOtp(const std::wstring& user) {
|
|
if (_otpChallengeId.empty()) {
|
|
_otpChallengeId = NewOtpChallengeId();
|
|
if (_otpChallengeId.empty()) {
|
|
_statusText = L"Could not initialize one-time code session";
|
|
LogLine(L"OTP challenge initialization failed username=" + user);
|
|
return false;
|
|
}
|
|
}
|
|
std::wstring req = L"{\"action\":\"RequestOtp\",\"username\":\"" + JsonEscape(user)
|
|
+ L"\",\"challenge_id\":\"" + JsonEscape(_otpChallengeId)
|
|
+ L"\",\"groups\":" + UserGroupsJson(user) + L"}";
|
|
std::wstring resp;
|
|
if (!PipeRequest(req, resp)) return false;
|
|
if (JsonStringEquals(resp, L"status", L"skipped")) return true;
|
|
if (JsonStringEquals(resp, L"status", L"totp_available")) {
|
|
_telegramAvailable = false;
|
|
_totpAvailable = true;
|
|
RefreshSelectedMethod();
|
|
_statusText = L"Введите код из Google Authenticator";
|
|
return true;
|
|
}
|
|
const std::wstring reason = JsonStringValue(resp, L"reason");
|
|
if (reason == L"2fa_not_configured") {
|
|
_telegramAvailable = false;
|
|
_totpAvailable = false;
|
|
RefreshSelectedMethod();
|
|
_statusText.clear();
|
|
}
|
|
else if (reason == L"telegram_not_configured") {
|
|
_telegramAvailable = false;
|
|
RefreshSelectedMethod();
|
|
_statusText = _totpAvailable ? L"Введите код из Google Authenticator" : L"Telegram is not configured for this user";
|
|
}
|
|
else if (reason == L"telegram_send_failed") {
|
|
_statusText = L"Telegram send failed";
|
|
}
|
|
return JsonStringEquals(resp, L"status", L"sent");
|
|
}
|
|
|
|
bool DuoCredential::VerifyOtp(const std::wstring& user, const std::wstring& otp) {
|
|
std::wstring req = L"{\"action\":\"VerifyOtp\",\"username\":\"" + JsonEscape(user)
|
|
+ L"\",\"code\":\"" + JsonEscape(otp)
|
|
+ L"\",\"challenge_id\":\"" + JsonEscape(_otpChallengeId)
|
|
+ L"\",\"groups\":" + UserGroupsJson(user) + L"}";
|
|
std::wstring resp;
|
|
if (!PipeRequest(req, resp)) return false;
|
|
const std::wstring reason = JsonStringValue(resp, L"reason");
|
|
if (reason == L"2fa_not_configured") {
|
|
_statusText = L"В аккаунте не настроена 2FA авторизация";
|
|
}
|
|
else if (reason == L"no_session") {
|
|
_statusText = L"Request a one-time code first";
|
|
}
|
|
else if (reason == L"expired") {
|
|
_statusText = L"One-time code expired";
|
|
}
|
|
else if (reason == L"no_attempts") {
|
|
_statusText = L"No 2FA attempts left";
|
|
}
|
|
else if (reason == L"invalid_code") {
|
|
// Do not leave the previous "code sent" status on screen after a
|
|
// real VerifyOtp response. It made a rejected code look like another
|
|
// send even when the service had not issued anything.
|
|
_statusText = L"Неверный одноразовый код. Проверьте последний код и повторите.";
|
|
}
|
|
else if (reason == L"invalid_format") {
|
|
_statusText = L"Одноразовый код должен состоять только из цифр.";
|
|
}
|
|
else if (reason == L"invalid_challenge") {
|
|
_statusText = L"One-time code session is invalid. Request a new code.";
|
|
}
|
|
bool ok = false;
|
|
return JsonBool(resp, L"ok", ok) && ok;
|
|
}
|
|
|
|
IFACEMETHODIMP DuoCredential::GetSerialization(CREDENTIAL_PROVIDER_GET_SERIALIZATION_RESPONSE* pcpgsr, CREDENTIAL_PROVIDER_CREDENTIAL_SERIALIZATION* pcpcs, PWSTR* ppwszOptionalStatusText, CREDENTIAL_PROVIDER_STATUS_ICON* pcpsiOptionalStatusIcon) {
|
|
if (pcpgsr) *pcpgsr = CPGSR_NO_CREDENTIAL_NOT_FINISHED;
|
|
if (ppwszOptionalStatusText) *ppwszOptionalStatusText = nullptr;
|
|
if (pcpsiOptionalStatusIcon) *pcpsiOptionalStatusIcon = CPSI_ERROR;
|
|
if (!pcpcs) return E_INVALIDARG;
|
|
|
|
LogLine(L"GetSerialization user_len=" + std::to_wstring(_username.size())
|
|
+ L", password_len=" + std::to_wstring(_password.size())
|
|
+ L", otp_len=" + std::to_wstring(_otp.size())
|
|
+ L", requested_for=" + _otpRequestedFor);
|
|
|
|
if (_username.empty()) {
|
|
LogLine(L"Blocked: username is empty");
|
|
if (ppwszOptionalStatusText) SHStrDupW(L"Username is required", ppwszOptionalStatusText);
|
|
return S_OK;
|
|
}
|
|
|
|
const std::wstring logonUsername = _qualifiedUsername.empty() ? _username : _qualifiedUsername;
|
|
|
|
RefreshPolicyState();
|
|
const bool require2fa = _requires2fa;
|
|
|
|
if (require2fa) {
|
|
// The serialized credential below is the only authoritative Windows
|
|
// password validation. A preflight LogonUserW call is not equivalent
|
|
// to interactive logon and may reject valid credentials before an OTP
|
|
// request is made.
|
|
EnterTwoFactorStep();
|
|
if (!HasConfigured2FaMethod()) {
|
|
_statusText.clear();
|
|
LogLine(L"Blocked: no 2FA method configured for " + _username);
|
|
RefreshDynamicFields();
|
|
if (ppwszOptionalStatusText) SHStrDupW(L"В аккаунте не настроена 2FA авторизация", ppwszOptionalStatusText);
|
|
return S_OK;
|
|
}
|
|
if (_otp.empty()) {
|
|
// Submitting an incomplete 2FA tile must be side-effect free.
|
|
// RequestOtp belongs exclusively to the command-link handler;
|
|
// otherwise a UI refresh or a lost hidden-field value can create
|
|
// a replacement code immediately before verification.
|
|
if (_otpMethod == 1 && _totpAvailable) {
|
|
_statusText = L"Введите код из Google Authenticator";
|
|
}
|
|
else {
|
|
_statusText = _otpMethod == 0 && _telegramAvailable
|
|
? (_otpRequestedFor == _username
|
|
? L"Введите одноразовый пароль или нажмите Отправить новый одноразовый код"
|
|
: L"Нажмите Отправить одноразовый код")
|
|
: L"Введите одноразовый пароль";
|
|
}
|
|
LogLine(L"Blocked: OTP empty for " + _username);
|
|
RefreshDynamicFields();
|
|
if (ppwszOptionalStatusText) SHStrDupW(_statusText.c_str(), ppwszOptionalStatusText);
|
|
return S_OK;
|
|
}
|
|
if (!VerifyOtp(_username, _otp)) {
|
|
if (_statusText.empty() || _statusText == L"Enter one-time code") {
|
|
_statusText = L"Invalid OTP";
|
|
}
|
|
LogLine(L"Blocked: invalid OTP for " + _username);
|
|
_otp.clear();
|
|
RefreshDynamicFields();
|
|
if (ppwszOptionalStatusText) SHStrDupW(_statusText.c_str(), ppwszOptionalStatusText);
|
|
return S_OK;
|
|
}
|
|
}
|
|
|
|
BYTE* packed = nullptr;
|
|
DWORD packedSize = 0;
|
|
|
|
if (_scenario == CPUS_CREDUI) {
|
|
CredPackAuthenticationBufferW(0, const_cast<LPWSTR>(logonUsername.c_str()), const_cast<LPWSTR>(_password.c_str()), nullptr, &packedSize);
|
|
if (GetLastError() != ERROR_INSUFFICIENT_BUFFER || packedSize == 0) {
|
|
LogLine(L"CredUI pack size failed error=" + std::to_wstring(GetLastError()));
|
|
if (ppwszOptionalStatusText) SHStrDupW(L"Credential pack failed", ppwszOptionalStatusText);
|
|
return S_OK;
|
|
}
|
|
|
|
packed = (BYTE*)CoTaskMemAlloc(packedSize);
|
|
if (!packed) return E_OUTOFMEMORY;
|
|
|
|
if (!CredPackAuthenticationBufferW(0, const_cast<LPWSTR>(logonUsername.c_str()), const_cast<LPWSTR>(_password.c_str()), packed, &packedSize)) {
|
|
LogLine(L"CredUI pack failed error=" + std::to_wstring(GetLastError()));
|
|
CoTaskMemFree(packed);
|
|
if (ppwszOptionalStatusText) SHStrDupW(L"Credential pack failed", ppwszOptionalStatusText);
|
|
return S_OK;
|
|
}
|
|
}
|
|
else {
|
|
std::wstring domain;
|
|
std::wstring user;
|
|
SplitDomainAndUser(logonUsername, domain, user);
|
|
if (user.empty()) {
|
|
LogLine(L"Kerberos pack blocked: parsed username is empty");
|
|
if (ppwszOptionalStatusText) SHStrDupW(L"Username is required", ppwszOptionalStatusText);
|
|
return S_OK;
|
|
}
|
|
|
|
const std::wstring serializedPassword = PasswordForSerialization(_password, _scenario);
|
|
KERB_INTERACTIVE_UNLOCK_LOGON logon = {};
|
|
InitKerbInteractiveUnlockLogon(domain, user, serializedPassword, _scenario, logon);
|
|
HRESULT hrPack = PackKerbInteractiveUnlockLogon(logon, &packed, &packedSize);
|
|
if (FAILED(hrPack)) {
|
|
LogLine(L"Kerberos pack failed hr=" + std::to_wstring(hrPack));
|
|
if (ppwszOptionalStatusText) SHStrDupW(L"Credential pack failed", ppwszOptionalStatusText);
|
|
return hrPack == E_OUTOFMEMORY ? E_OUTOFMEMORY : S_OK;
|
|
}
|
|
LogLine(L"Kerberos credential packed user=" + user
|
|
+ L" domain_len=" + std::to_wstring(domain.size())
|
|
+ L" scenario=" + std::to_wstring((DWORD)_scenario));
|
|
}
|
|
|
|
ULONG authPackage = 0;
|
|
if (FAILED(RetrieveNegotiateAuthPackage(&authPackage))) {
|
|
LogLine(L"Auth package resolve failed");
|
|
CoTaskMemFree(packed);
|
|
if (ppwszOptionalStatusText) SHStrDupW(L"Auth package resolve failed", ppwszOptionalStatusText);
|
|
return S_OK;
|
|
}
|
|
|
|
ZeroMemory(pcpcs, sizeof(*pcpcs));
|
|
pcpcs->ulAuthenticationPackage = authPackage;
|
|
pcpcs->clsidCredentialProvider = CLSID_DuoRdpCredentialProvider;
|
|
pcpcs->rgbSerialization = packed;
|
|
pcpcs->cbSerialization = packedSize;
|
|
|
|
if (ppwszOptionalStatusText) SHStrDupW(L"Sign in request accepted", ppwszOptionalStatusText);
|
|
if (pcpsiOptionalStatusIcon) *pcpsiOptionalStatusIcon = CPSI_SUCCESS;
|
|
*pcpgsr = CPGSR_RETURN_CREDENTIAL_FINISHED;
|
|
LogLine(L"Credential serialized for " + _username);
|
|
return S_OK;
|
|
}
|
|
|
|
IFACEMETHODIMP DuoCredential::ReportResult(NTSTATUS ntsStatus, NTSTATUS ntsSubstatus, PWSTR*, CREDENTIAL_PROVIDER_STATUS_ICON*) {
|
|
LogLine(L"ReportResult username=" + _username
|
|
+ L" status=" + HexStatus(ntsStatus)
|
|
+ L" substatus=" + HexStatus(ntsSubstatus));
|
|
ResetTwoFactorState();
|
|
return S_OK;
|
|
}
|