From 9898f4b3aef4e82ffc6b1512f7044b8246a64ba1 Mon Sep 17 00:00:00 2001 From: zhangruochu Date: Sun, 29 Nov 2026 17:49:28 +0800 Subject: [PATCH] Verify RDP server certificates instead of ignoring them The bridge used to set FreeRDP_IgnoreCertificate and AutoAcceptCertificate to TRUE and answered every certificate hook with "accept", so a self-signed certificate from anyone on the path was accepted without a word. It now asks the host through cxrdp_set_certificate_callback (API 16) and answers with the host's decision, which aborts the connection when the fingerprint is rejected. FreeRDP keeps accepted certificates in its own store and answers a matching host from there without calling the hook at all, which made the second connection to a host skip every check - including a rotated fingerprint. Declaring the certificate management as external keeps each connection going through the callback, and the store entry for the endpoint is dropped before connecting as a fallback for builds that ignore that flag. The managed side pins the SHA-256 fingerprint per host:port in the rdp_certificates collection, prompts on first use and blocks a changed fingerprint until the operator removes the entry in Settings -> Trusted hosts, mirroring the SSH host key model. Sessions through a tunnel or proxy relay key the store on the real target instead of 127.0.0.1. --- AGENTS.md | 2 + .../RdpCertificateTrustServiceTests.cs | 233 ++++++++++++++ Models/RdpCertificateModels.cs | 38 +++ Models/SessionInfo.cs | 2 + Services/LocalizationService.cs | 45 +++ Services/RdpBridgeClient.cs | 92 ++++++ Services/RdpCertificatePromptService.cs | 104 +++++++ Services/RdpCertificateTrustService.cs | 284 ++++++++++++++++++ ViewModels/ApplicationSettingsViewModel.cs | 95 ++++++ ViewModels/MainWindowViewModel.cs | 2 + ViewModels/RdpCertificatePromptViewModel.cs | 57 ++++ Views/ApplicationSettingsPage.axaml | 19 ++ Views/RdpCertificatePromptWindow.axaml | 96 ++++++ Views/RdpCertificatePromptWindow.axaml.cs | 48 +++ Views/SettingsCenterWindow.axaml.cs | 5 + Views/TrustedHostsPage.axaml | 60 ++++ native/CxRdpBridge/cxrdp_bridge.cpp | 253 ++++++++++++++-- native/CxRdpBridge/cxrdp_bridge.h | 32 +- 18 files changed, 1439 insertions(+), 28 deletions(-) create mode 100644 CxShell.Tests/RdpCertificateTrustServiceTests.cs create mode 100644 Models/RdpCertificateModels.cs create mode 100644 Services/RdpCertificatePromptService.cs create mode 100644 Services/RdpCertificateTrustService.cs create mode 100644 ViewModels/RdpCertificatePromptViewModel.cs create mode 100644 Views/RdpCertificatePromptWindow.axaml create mode 100644 Views/RdpCertificatePromptWindow.axaml.cs diff --git a/AGENTS.md b/AGENTS.md index cbce11b..3b928c6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -55,6 +55,8 @@ SSH X11 forwarding currently uses `ForwardedPortRemote` plus an automatic `DISPL RDP sessions stay alive across idle periods and network drops: the bridge enables TCP keepalive (`FreeRDP_TcpKeepAliveDelay/Interval/Retries`), waits on `freerdp_get_event_handles` with a bounded 25 ms timeout so transport errors surface immediately and queued work is serviced promptly, and reconnects through FreeRDP ARC (`freerdp_disconnect_before_reconnect_context` + `freerdp_reconnect`) with its own retry loop: an escalating 1/2/3/5/10 second backoff, a 20 minute budget, and a user-cancellable "stop trying" path. The SSH tunnel that carries RDP sets `KeepAliveInterval` so NAT devices do not idle it out. Reconnect progress is reported through bridge status lines prefixed `RDP connection lost`, `RDP reconnecting (attempt N)`, `RDP reconnected` and `RDP reconnect failed`; `ViewModels/RdpReconnectStatus.cs` maps them to the localized overlay in `Views/RdpView.axaml`, and the prefixes must stay in sync with `native/CxRdpBridge/cxrdp_bridge.cpp`. When the budget runs out or the user cancels, the view shows a Reconnect button instead of retrying forever. +RDP certificate verification: the bridge no longer ignores the server certificate. `cxrdp_set_certificate_callback` (API 16, `CX_RDP_CAPABILITY_CERTIFICATE_VERIFICATION`) registers `RdpBridgeClient.OnCertificateVerification`, which runs on the native connect thread and blocks while `Services/RdpCertificateTrustService` asks the user, because the answer must exist before the handshake continues; the bridge calls it outside `callback_mutex` on purpose, so never take that lock around a prompt. The native side switches `FreeRDP_IgnoreCertificate`/`AutoAcceptCertificate` to FALSE only when a callback is registered (an older host keeps the accept-all behaviour), normalises the digest to lower-case hex, and caches one decision per fingerprint so a TLS + NLA/CredSSP exchange prompts once. The trust store (`rdp_certificates` collection in `SqliteAppDataStore`) is keyed on the real target `_profileCacheHost/_profileCachePort`, never the loopback endpoint a tunnel or proxy relay substitutes. First-use prompting and changed-certificate blocking mirror SSH (`ConfirmRdpCertificateOnFirstConnection`, `BlockChangedRdpCertificates`, both default true); a changed certificate is rejected without a prompt and the operator removes the entry in Settings → Trusted hosts, and `RdpCertificatePromptService.CancelPending()` closes a pending prompt when the tab is disconnected. + RDP DPI policy (`SessionInfo.RdpDpiPolicy`, edited in `Views/SessionEditDialog.axaml`): `FollowLocal` (default) maps the local render scaling to a quantized RDP scale (100/125/150/175/200) via `Services/RdpDpiScale.cs`; `Fixed100` forces 100%; `KeepRemote` advertises no scale. At connect time `RdpBridgeClient` calls `cxrdp_set_display_scale`, and the bridge adds the `disp` dynamic channel (registered as `DISP_CHANNEL_NAME` "disp" — the long `DISP_DVC_CHANNEL_NAME` fails to resolve the static addin in freerdp-client3.dll) and sets `FreeRDP_DesktopScaleFactor`/`DeviceScaleFactor`. On resize or a monitored DPI change, `RdpViewModel` calls `cxrdp_update_display`; the bridge queues it on the worker thread, which sends `DispClientContext.SendMonitorLayout` with physical dimensions and then resizes GDI directly (the host's deactivate/reactivate does not emit a Desktop Resize Update). Fall back to the full-reconnect resize path when the bridge lacks API 6 / `CX_RDP_CAPABILITY_RUNTIME_RESIZE`. The C API version is 15 and the smoke tool asserts the runtime-resize capability bit. RDP scale wire format (`Services/RdpDpiScale.cs`, `native/CxRdpBridge/cxrdp_bridge.cpp`): `ResolveScalePercent` may return any of 100/125/150/175/200 for `DesktopScaleFactor`, but `DeviceScaleFactor` is only allowed to be 100, 140 or 180 — any other value makes Windows drop BOTH scale factors silently, which looked like "the DPI setting does nothing" on multi-monitor layouts. Both sides therefore funnel it through `RdpDpiScale.DeviceScaleFactorFromDesktopScale` / `resolve_device_scale_factor`; keep the two in sync. Desktop sizes must be even numbers (`& ~1`) because MS-RDPEDISP rejects an odd width, and `PhysicalWidth`/`PhysicalHeight` are derived from the scale by `compute_physical_mm` so the remote sees a plausible monitor. `cx_post_connect` remembers whether the `disp` capabilities already arrived (`disp_caps_received`) and, when they did, queues the initial monitor layout instead of waiting for the first resize; after `freerdp_connect` the worker resets all of it so ARC reconnects re-send a layout. `RdpViewModel` keeps `_runtimeDisplayScalePercent` next to the runtime width/height: a resize is only sent when the size moved by 2 px or the scale actually changed, and `RequestViewportResize` debounces 250 ms (`_resizeDebounceCts`) because MS-RDPEDISP throttles back-to-back `SendMonitorLayout` PDUs during a window drag. `Views/RdpView.axaml.cs` disables the local Windows IME with `ImmAssociateContext(hwnd, IntPtr.Zero)` while the RDP view holds focus and restores the saved context on `LostFocus`, so a local input method cannot swallow remote keystrokes. diff --git a/CxShell.Tests/RdpCertificateTrustServiceTests.cs b/CxShell.Tests/RdpCertificateTrustServiceTests.cs new file mode 100644 index 0000000..f727861 --- /dev/null +++ b/CxShell.Tests/RdpCertificateTrustServiceTests.cs @@ -0,0 +1,233 @@ +using CxShell.Models; +using CxShell.Services; + +namespace CxShell.Tests; + +public sealed class RdpCertificateTrustServiceTests +{ + [Fact] + public void PermanentTrust_PersistsAndSkipsFuturePrompt() + { + var path = CreateTempPath(); + try + { + var firstPrompt = new StubPrompt(RdpCertificateDecision.TrustPermanently); + Assert.True(CreateService(path, firstPrompt).IsTrusted(CreateObservation("A1B2C3"))); + Assert.Equal(1, firstPrompt.CallCount); + + var secondPrompt = new StubPrompt(RdpCertificateDecision.Reject); + Assert.True(CreateService(path, secondPrompt).IsTrusted(CreateObservation("a1b2c3"))); + Assert.Equal(0, secondPrompt.CallCount); + } + finally + { + DeleteTempPath(path); + } + } + + [Fact] + public void TrustOnce_OnlyLivesForCurrentServiceInstance() + { + var path = CreateTempPath(); + try + { + var prompt = new StubPrompt(RdpCertificateDecision.TrustOnce); + var service = CreateService(path, prompt); + + Assert.True(service.IsTrusted(CreateObservation("d4e5f6"))); + Assert.True(service.IsTrusted(CreateObservation("d4e5f6"))); + Assert.Equal(1, prompt.CallCount); + + var nextPrompt = new StubPrompt(RdpCertificateDecision.Reject); + Assert.False(CreateService(path, nextPrompt).IsTrusted(CreateObservation("d4e5f6"))); + Assert.Equal(1, nextPrompt.CallCount); + } + finally + { + DeleteTempPath(path); + } + } + + [Fact] + public void ChangedFingerprint_IsBlockedWithoutPromptByDefault() + { + var path = CreateTempPath(); + try + { + var service = CreateService(path, new StubPrompt(RdpCertificateDecision.TrustPermanently)); + Assert.True(service.IsTrusted(CreateObservation("original"))); + + var changedPrompt = new StubPrompt(RdpCertificateDecision.TrustPermanently); + var changedService = CreateService(path, changedPrompt); + Assert.False(changedService.IsTrusted(CreateObservation("rotated"))); + Assert.Equal(0, changedPrompt.CallCount); + Assert.Equal("original", Assert.Single(changedService.GetKnownCertificates()).Fingerprint); + } + finally + { + DeleteTempPath(path); + } + } + + [Fact] + public void ChangedFingerprint_CanBeConfirmedWhenBlockingIsDisabled() + { + var path = CreateTempPath(); + try + { + var service = CreateService(path, new StubPrompt(RdpCertificateDecision.TrustPermanently)); + Assert.True(service.IsTrusted(CreateObservation("original"))); + + var changedPrompt = new StubPrompt(RdpCertificateDecision.TrustPermanently); + var changedService = CreateService(path, changedPrompt, blockChanged: false); + Assert.True(changedService.IsTrusted(CreateObservation("rotated"))); + Assert.Equal(RdpCertificateVerification.Changed, changedPrompt.LastRequest?.Verification); + Assert.Equal("original", changedPrompt.LastRequest?.PreviousFingerprint); + Assert.Equal("rotated", Assert.Single(changedService.GetKnownCertificates()).Fingerprint); + } + finally + { + DeleteTempPath(path); + } + } + + [Fact] + public void FirstConnection_PromptsWhenConfirmationIsEnabled() + { + var path = CreateTempPath(); + try + { + var prompt = new StubPrompt(RdpCertificateDecision.Reject); + Assert.False(CreateService(path, prompt).IsTrusted(CreateObservation("new"))); + Assert.Equal(1, prompt.CallCount); + Assert.Equal(RdpCertificateVerification.Unknown, prompt.LastRequest?.Verification); + Assert.Null(prompt.LastRequest?.PreviousFingerprint); + } + finally + { + DeleteTempPath(path); + } + } + + [Fact] + public void FirstConnection_IsTrustedSilentlyWhenConfirmationIsDisabled() + { + var path = CreateTempPath(); + try + { + var prompt = new StubPrompt(RdpCertificateDecision.Reject); + var service = CreateService(path, prompt, confirmFirstUse: false); + Assert.True(service.IsTrusted(CreateObservation("silent"))); + Assert.Equal(0, prompt.CallCount); + Assert.Equal("silent", Assert.Single(service.GetKnownCertificates()).Fingerprint); + } + finally + { + DeleteTempPath(path); + } + } + + [Fact] + public void RemoveKnownCertificate_RequiresConfirmationOnNextConnection() + { + var path = CreateTempPath(); + try + { + var service = CreateService(path, new StubPrompt(RdpCertificateDecision.TrustPermanently)); + Assert.True(service.IsTrusted(CreateObservation("saved"))); + + service.RemoveKnownCertificate("example.test", 3389); + Assert.Empty(service.GetKnownCertificates()); + + var prompt = new StubPrompt(RdpCertificateDecision.Reject); + Assert.False(CreateService(path, prompt).IsTrusted(CreateObservation("saved"))); + Assert.Equal(1, prompt.CallCount); + } + finally + { + DeleteTempPath(path); + } + } + + [Fact] + public void FingerprintSeparatorsAndCase_DoNotTriggerAChange() + { + var path = CreateTempPath(); + try + { + var service = CreateService(path, new StubPrompt(RdpCertificateDecision.TrustPermanently)); + Assert.True(service.IsTrusted(CreateObservation("aabbccdd"))); + + var prompt = new StubPrompt(RdpCertificateDecision.Reject); + Assert.True(CreateService(path, prompt).IsTrusted(CreateObservation("SHA256:AA:BB:CC:DD"))); + Assert.Equal(0, prompt.CallCount); + } + finally + { + DeleteTempPath(path); + } + } + + [Fact] + public void EmptyFingerprint_IsNeverTrusted() + { + var path = CreateTempPath(); + try + { + var prompt = new StubPrompt(RdpCertificateDecision.TrustPermanently); + Assert.False(CreateService(path, prompt).IsTrusted(CreateObservation(string.Empty))); + Assert.Equal(0, prompt.CallCount); + } + finally + { + DeleteTempPath(path); + } + } + + private static RdpCertificateTrustService CreateService( + string path, + StubPrompt prompt, + bool blockChanged = true, + bool confirmFirstUse = true) + { + var service = new RdpCertificateTrustService(path, prompt); + service.Configure(new ApplicationSettings + { + ConfirmRdpCertificateOnFirstConnection = confirmFirstUse, + BlockChangedRdpCertificates = blockChanged + }); + return service; + } + + private static RdpCertificateObservation CreateObservation(string fingerprint) + => new("Example.Test", 3389, "example.test", "Example CA", fingerprint); + + private static string CreateTempPath() + { + return Path.Combine( + Path.GetTempPath(), + "CxShellTests", + Guid.NewGuid().ToString("N"), + "rdp_certificates.json"); + } + + private static void DeleteTempPath(string path) + { + var directory = Path.GetDirectoryName(path); + if (!string.IsNullOrWhiteSpace(directory) && Directory.Exists(directory)) + Directory.Delete(directory, recursive: true); + } + + private sealed class StubPrompt(RdpCertificateDecision decision) : IRdpCertificatePrompt + { + public int CallCount { get; private set; } + public RdpCertificatePromptRequest? LastRequest { get; private set; } + + public Task DecideAsync(RdpCertificatePromptRequest request) + { + CallCount++; + LastRequest = request; + return Task.FromResult(decision); + } + } +} diff --git a/Models/RdpCertificateModels.cs b/Models/RdpCertificateModels.cs new file mode 100644 index 0000000..0d883d5 --- /dev/null +++ b/Models/RdpCertificateModels.cs @@ -0,0 +1,38 @@ +namespace CxShell.Models; + +public enum RdpCertificateVerification +{ + Unknown, + Trusted, + Changed +} + +public enum RdpCertificateDecision +{ + Reject, + TrustOnce, + TrustPermanently +} + +public sealed class KnownRdpCertificate +{ + public string Host { get; set; } = string.Empty; + public int Port { get; set; } = 3389; + public string CommonName { get; set; } = string.Empty; + public string Issuer { get; set; } = string.Empty; + public string Fingerprint { get; set; } = string.Empty; + public DateTimeOffset FirstSeenUtc { get; set; } + public DateTimeOffset LastSeenUtc { get; set; } +} + +public sealed record RdpCertificateObservation( + string Host, + int Port, + string CommonName, + string Issuer, + string Fingerprint); + +public sealed record RdpCertificatePromptRequest( + RdpCertificateObservation Observation, + RdpCertificateVerification Verification, + string? PreviousFingerprint); diff --git a/Models/SessionInfo.cs b/Models/SessionInfo.cs index 6546bf1..e08d924 100644 --- a/Models/SessionInfo.cs +++ b/Models/SessionInfo.cs @@ -342,6 +342,8 @@ public class ApplicationSettings public int BackgroundImageOpacity { get; set; } = 100; public bool ConfirmSshHostKeyOnFirstConnection { get; set; } = true; public bool BlockChangedSshHostKeys { get; set; } = true; + public bool ConfirmRdpCertificateOnFirstConnection { get; set; } = true; + public bool BlockChangedRdpCertificates { get; set; } = true; public bool RecordTerminalSessions { get; set; } private int _recordingRetentionDays = 30; diff --git a/Services/LocalizationService.cs b/Services/LocalizationService.cs index 47a18c6..d5b94b3 100644 --- a/Services/LocalizationService.cs +++ b/Services/LocalizationService.cs @@ -1201,6 +1201,28 @@ static LocalizationService() EnglishTexts["SshHostKey.Cancel"] = "Cancel"; EnglishTexts["SshHostKey.TrustOnce"] = "Trust once"; EnglishTexts["SshHostKey.TrustPermanently"] = "Trust permanently"; + + EnglishTexts["ApplicationSettings.RdpSecurity"] = "RDP certificate security"; + EnglishTexts["ApplicationSettings.ConfirmRdpCertificateOnFirstConnection"] = "Ask before trusting an unknown RDP server certificate"; + EnglishTexts["ApplicationSettings.BlockChangedRdpCertificates"] = "Block RDP connections whose certificate changed"; + EnglishTexts["ApplicationSettings.KnownRdpCertificates"] = "Trusted RDP certificates"; + EnglishTexts["ApplicationSettings.NoKnownRdpCertificates"] = "No RDP certificate has been trusted yet."; + EnglishTexts["ApplicationSettings.RdpRemoveCertificate"] = "Remove trusted certificate"; + EnglishTexts["ApplicationSettings.RdpRemoveCertificateConfirmTitle"] = "Remove trusted certificate"; EnglishTexts["ApplicationSettings.RdpRemoveCertificateConfirmMessage"] = "Remove the trusted certificate for {0}? The next connection will ask again."; + EnglishTexts["ApplicationSettings.RdpCertificateNoCommonName"] = "no common name"; + + EnglishTexts["RdpCertificate.Title"] = "Verify RDP Server Certificate"; + EnglishTexts["RdpCertificate.UnknownWarning"] = "This RDP server presents a certificate that has not been seen before. Compare the fingerprint with the server before trusting it."; + EnglishTexts["RdpCertificate.ChangedWarning"] = "The saved certificate for this server has changed. This may indicate a rebuilt server or a man-in-the-middle attack."; + EnglishTexts["RdpCertificate.Host"] = "Server"; + EnglishTexts["RdpCertificate.CommonName"] = "Common name"; + EnglishTexts["RdpCertificate.Issuer"] = "Issuer"; + EnglishTexts["RdpCertificate.Fingerprint"] = "SHA-256 fingerprint"; + EnglishTexts["RdpCertificate.PreviousFingerprint"] = "Saved fingerprint"; + EnglishTexts["RdpCertificate.NotReported"] = "not reported by the server"; + EnglishTexts["RdpCertificate.Cancel"] = "Cancel"; + EnglishTexts["RdpCertificate.TrustOnce"] = "Trust once"; + EnglishTexts["RdpCertificate.TrustPermanently"] = "Trust permanently"; EnglishTexts["Audit.Title"] = "Connection audit"; EnglishTexts["Audit.Description"] = "Recent connection activity is stored locally. Passwords and private keys are never recorded."; EnglishTexts["Audit.FilterPlaceholder"] = "Filter by session, host, protocol, or detail"; @@ -1779,6 +1801,29 @@ static LocalizationService() ChineseTexts["SshHostKey.Cancel"] = "\u53d6\u6d88"; ChineseTexts["SshHostKey.TrustOnce"] = "\u4ec5\u672c\u6b21\u4fe1\u4efb"; ChineseTexts["SshHostKey.TrustPermanently"] = "\u6c38\u4e45\u4fe1\u4efb"; + + ChineseTexts["ApplicationSettings.RdpSecurity"] = "RDP 证书安全"; + ChineseTexts["ApplicationSettings.ConfirmRdpCertificateOnFirstConnection"] = "首次连接时询问是否信任未知的 RDP 服务器证书"; + ChineseTexts["ApplicationSettings.BlockChangedRdpCertificates"] = "RDP 服务器证书变化时阻止连接"; + ChineseTexts["ApplicationSettings.KnownRdpCertificates"] = "已信任的 RDP 证书"; + ChineseTexts["ApplicationSettings.NoKnownRdpCertificates"] = "还没有信任过任何 RDP 证书。"; + ChineseTexts["ApplicationSettings.RdpRemoveCertificate"] = "移除已信任证书"; + ChineseTexts["ApplicationSettings.RdpRemoveCertificateConfirmTitle"] = "移除已信任证书"; + ChineseTexts["ApplicationSettings.RdpRemoveCertificateConfirmMessage"] = "确定移除 {0} 的已信任证书吗?下次连接将重新询问。"; + ChineseTexts["ApplicationSettings.RdpCertificateNoCommonName"] = "无通用名"; + + ChineseTexts["RdpCertificate.Title"] = "验证 RDP 服务器证书"; + ChineseTexts["RdpCertificate.UnknownWarning"] = "这是首次连接该 RDP 服务器。信任前请核对证书指纹与服务端是否一致。"; + ChineseTexts["RdpCertificate.ChangedWarning"] = "该服务器已保存的证书发生了变化。这可能是服务器重装,也可能存在中间人攻击。"; + ChineseTexts["RdpCertificate.Host"] = "服务器"; + ChineseTexts["RdpCertificate.CommonName"] = "通用名"; + ChineseTexts["RdpCertificate.Issuer"] = "颁发者"; + ChineseTexts["RdpCertificate.Fingerprint"] = "SHA-256 指纹"; + ChineseTexts["RdpCertificate.PreviousFingerprint"] = "已保存指纹"; + ChineseTexts["RdpCertificate.NotReported"] = "服务端未提供"; + ChineseTexts["RdpCertificate.Cancel"] = "取消"; + ChineseTexts["RdpCertificate.TrustOnce"] = "仅本次信任"; + ChineseTexts["RdpCertificate.TrustPermanently"] = "永久信任"; ChineseTexts["Audit.Title"] = "\u8fde\u63a5\u5ba1\u8ba1"; ChineseTexts["Audit.Description"] = "\u6700\u8fd1\u7684\u8fde\u63a5\u6d3b\u52a8\u4ec5\u4fdd\u5b58\u5728\u672c\u673a\u3002\u4e0d\u4f1a\u8bb0\u5f55\u5bc6\u7801\u548c\u79c1\u94a5\u3002"; ChineseTexts["Audit.FilterPlaceholder"] = "\u6309\u4f1a\u8bdd\u3001\u4e3b\u673a\u3001\u534f\u8bae\u6216\u8be6\u7ec6\u4fe1\u606f\u7b5b\u9009"; diff --git a/Services/RdpBridgeClient.cs b/Services/RdpBridgeClient.cs index 5ff111a..26b9a4b 100644 --- a/Services/RdpBridgeClient.cs +++ b/Services/RdpBridgeClient.cs @@ -114,6 +114,10 @@ public sealed class RdpBridgeClient : IDisposable private const uint ClipboardLockCapability = 0x00020000; private const uint MultiMonitorApiVersion = 15; private const uint MultiMonitorCapability = 0x00040000; + private const uint CertificateApiVersion = 16; + private const uint CertificateCapability = 0x00100000; + private const int CertificateDecisionReject = 0; + private const int CertificateDecisionAccept = 1; private static readonly object DebugLogLock = new(); private static readonly object NativeLoadFailureLock = new(); private static readonly bool DetailedDebugLogEnabled = IsEnvironmentFlagEnabled("CXSHELL_RDP_DEBUG_LOG"); @@ -132,10 +136,13 @@ public sealed class RdpBridgeClient : IDisposable private readonly FrameCallback _frameCallback; private readonly StatusCallback _statusCallback; private readonly DisconnectCallback _disconnectCallback; + private readonly CertificateCallback _certificateCallback; private readonly ClipboardTextCallback _clipboardTextCallback; private readonly ClipboardImageCallback _clipboardImageCallback; private readonly ClipboardFilesCallback _clipboardFilesCallback; private readonly PointerCallback _pointerCallback; + private readonly RdpCertificateTrustService _certificateTrust = RdpCertificateTrustService.Shared; + private bool _certificateVerificationEnabled; private bool _supportsClipboardImage; private bool _supportsClipboardFiles; private bool _supportsClipboardRichText; @@ -207,6 +214,7 @@ public RdpBridgeClient() _frameCallback = OnFrame; _statusCallback = OnStatus; _disconnectCallback = OnDisconnected; + _certificateCallback = OnCertificateVerification; _clipboardTextCallback = OnClipboardText; _clipboardImageCallback = OnClipboardImage; _clipboardFilesCallback = OnClipboardFiles; @@ -296,6 +304,19 @@ public void Connect( _frameMarkerSupported = nativeApiVersion >= FrameMarkerApiVersion && (nativeCapabilities & FrameMarkerCapability) != 0; + _certificateVerificationEnabled = nativeApiVersion >= CertificateApiVersion && + (nativeCapabilities & CertificateCapability) != 0; + if (_certificateVerificationEnabled) + { + // The bridge asks this callback before it accepts the server + // certificate and reuses one answer per fingerprint, so a session + // that negotiates TLS twice does not prompt twice. + NativeMethods.cxrdp_set_certificate_callback(_handle, _certificateCallback); + } + else + { + DebugLog("native bridge does not verify RDP certificates (API < 16); the server certificate is accepted unchecked."); + } _supportsSyncLockKeys = nativeApiVersion >= SyncLockKeysApiVersion && (nativeCapabilities & SyncLockKeysCapability) != 0; if (nativeApiVersion >= PointerShapeApiVersion && @@ -954,6 +975,10 @@ public void Disconnect() } DebugLog("disconnect requested"); + // A prompt still waiting for an answer would otherwise keep the native + // worker blocked inside cxrdp_disconnect() until its timeout. + if (_certificateVerificationEnabled) + RdpCertificatePromptService.CancelPending(); NativeMethods.cxrdp_disconnect(_handle); NativeMethods.cxrdp_destroy(_handle); _handle = IntPtr.Zero; @@ -1498,6 +1523,57 @@ private void OnDisconnected(IntPtr userData) Disconnected?.Invoke(); } + /// + /// Runs on the native connect thread while FreeRDP verifies the server + /// certificate. Asking the user blocks that worker, which is why the trust + /// service is consulted here instead of the UI layer: the answer has to be + /// known before the handshake continues. + /// + private int OnCertificateVerification( + IntPtr userData, + IntPtr host, + int port, + IntPtr commonName, + IntPtr issuer, + IntPtr fingerprint, + IntPtr previousFingerprint, + uint flags) + { + try + { + // A tunnel or proxy relay makes the bridge dial 127.0.0.1, but the + // operator recognises the session by its real target, and that is + // also what the trust store is keyed on. + var effectiveHost = string.IsNullOrWhiteSpace(_profileCacheHost) + ? ReadUtf8(host) + : _profileCacheHost; + var effectivePort = _profileCachePort > 0 + ? _profileCachePort + : port > 0 ? port : 3389; + + var observation = new RdpCertificateObservation( + effectiveHost, + effectivePort, + ReadUtf8(commonName), + ReadUtf8(issuer), + ReadUtf8(fingerprint)); + + DebugLog($"certificate verify host={SanitizeLogValue(effectiveHost)} port={effectivePort} cn={SanitizeLogValue(observation.CommonName)} sha256={observation.Fingerprint} previous={ReadUtf8(previousFingerprint)} flags=0x{flags:X}"); + + var trusted = _certificateTrust.IsTrusted(observation); + DebugLog($"certificate decision host={SanitizeLogValue(effectiveHost)} trusted={trusted}"); + return trusted ? CertificateDecisionAccept : CertificateDecisionReject; + } + catch (Exception ex) + { + DebugLog($"certificate verification failed: {ex.GetType().Name}: {ex.Message}"); + return CertificateDecisionReject; + } + } + + private static string ReadUtf8(IntPtr pointer) + => pointer == IntPtr.Zero ? string.Empty : Marshal.PtrToStringUTF8(pointer) ?? string.Empty; + private void OnPointer(IntPtr userData, int kind, int width, int height, int hotX, int hotY, IntPtr bgraPixels) { byte[]? copy = null; @@ -1695,6 +1771,17 @@ private delegate void PointerCallback( int hotY, IntPtr bgraPixels); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate int CertificateCallback( + IntPtr userData, + IntPtr host, + int port, + IntPtr commonName, + IntPtr issuer, + IntPtr fingerprint, + IntPtr previousFingerprint, + uint flags); + private static class NativeMethods { [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl)] @@ -1717,6 +1804,11 @@ public static extern void cxrdp_set_callbacks( DisconnectCallback disconnectCallback, IntPtr userData); + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl)] + public static extern int cxrdp_set_certificate_callback( + IntPtr handle, + CertificateCallback certificateCallback); + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl)] public static extern void cxrdp_set_clipboard_callback( IntPtr handle, diff --git a/Services/RdpCertificatePromptService.cs b/Services/RdpCertificatePromptService.cs new file mode 100644 index 0000000..69b338e --- /dev/null +++ b/Services/RdpCertificatePromptService.cs @@ -0,0 +1,104 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.ApplicationLifetimes; +using Avalonia.Threading; +using CxShell.Models; +using CxShell.ViewModels; +using CxShell.Views; + +namespace CxShell.Services; + +/// +/// Shows the certificate prompt on the UI thread and blocks the RDP connect +/// thread until the user decides. The connect runs on a worker thread, so +/// waiting here never stalls the dispatcher; the timeout and +/// keep a forgotten dialog from pinning that worker. +/// +public sealed class RdpCertificatePromptService : IRdpCertificatePrompt +{ + private static readonly TimeSpan DecisionTimeout = TimeSpan.FromMinutes(2); + private static readonly object ActiveLock = new(); + private static readonly HashSet ActiveWindows = []; + + public async Task DecideAsync(RdpCertificatePromptRequest request) + { + if (Dispatcher.UIThread.CheckAccess()) + return RdpCertificateDecision.Reject; + + try + { + return await Dispatcher.UIThread + .InvokeAsync(() => ShowDialogAsync(request)) + .ConfigureAwait(false); + } + catch + { + return RdpCertificateDecision.Reject; + } + } + + /// Closes any open certificate prompt as a rejection. + public static void CancelPending() + { + Window[] windows; + lock (ActiveLock) + { + windows = [.. ActiveWindows]; + ActiveWindows.Clear(); + } + + foreach (var window in windows) + { + Dispatcher.UIThread.Post(() => + { + try + { + if (window.IsVisible) + window.Close(RdpCertificateDecision.Reject); + } + catch + { + // The window is already gone; nothing to cancel. + } + }); + } + } + + private static async Task ShowDialogAsync(RdpCertificatePromptRequest request) + { + if (Application.Current?.ApplicationLifetime is not IClassicDesktopStyleApplicationLifetime desktop) + return RdpCertificateDecision.Reject; + + var owner = desktop.Windows.FirstOrDefault(window => window.IsActive) ?? desktop.MainWindow; + if (owner == null) + return RdpCertificateDecision.Reject; + + var viewModel = new RdpCertificatePromptViewModel(request); + var window = new RdpCertificatePromptWindow(viewModel); + lock (ActiveLock) + ActiveWindows.Add(window); + + try + { + var dialog = window.ShowDialog(owner); + var completed = await Task.WhenAny(dialog, Task.Delay(DecisionTimeout)).ConfigureAwait(true); + if (completed != dialog) + { + if (window.IsVisible) + window.Close(RdpCertificateDecision.Reject); + return RdpCertificateDecision.Reject; + } + + return await dialog.ConfigureAwait(true); + } + catch + { + return RdpCertificateDecision.Reject; + } + finally + { + lock (ActiveLock) + ActiveWindows.Remove(window); + } + } +} diff --git a/Services/RdpCertificateTrustService.cs b/Services/RdpCertificateTrustService.cs new file mode 100644 index 0000000..0a47de3 --- /dev/null +++ b/Services/RdpCertificateTrustService.cs @@ -0,0 +1,284 @@ +using System.Collections.Concurrent; +using System.Text.Json; +using CxShell.Models; + +namespace CxShell.Services; + +public interface IRdpCertificatePrompt +{ + Task DecideAsync(RdpCertificatePromptRequest request); +} + +/// +/// Trust store for RDP server certificates. Mirrors +/// so both protocols answer the same question the same way: is this endpoint's +/// fingerprint the one we already accepted, a new one, or a changed one? +/// +public sealed class RdpCertificateTrustService +{ + internal sealed class KnownCertificatesFile + { + public int Version { get; set; } = 1; + public List Certificates { get; set; } = []; + } + + private static readonly TimeSpan LastSeenWriteInterval = TimeSpan.FromHours(1); + private readonly object _storageLock = new(); + private readonly SqliteAppDataStore _store; + private readonly IRdpCertificatePrompt _prompt; + private readonly ConcurrentDictionary _temporaryTrust = new(StringComparer.OrdinalIgnoreCase); + private readonly ConcurrentDictionary _endpointLocks = new(StringComparer.OrdinalIgnoreCase); + private ApplicationSettings _settings = new(); + + public static RdpCertificateTrustService Shared { get; } = new( + Path.Combine(SessionStorageService.GetStorageDirectory(), "rdp_certificates.json"), + new RdpCertificatePromptService()); + + public RdpCertificateTrustService(string storagePath, IRdpCertificatePrompt prompt) + { + var fullPath = Path.GetFullPath(storagePath ?? throw new ArgumentNullException(nameof(storagePath))); + _store = new SqliteAppDataStore(Path.GetDirectoryName(fullPath)); + _prompt = prompt ?? throw new ArgumentNullException(nameof(prompt)); + } + + public void Configure(ApplicationSettings settings) + { + _settings = settings ?? throw new ArgumentNullException(nameof(settings)); + } + + public IReadOnlyList GetKnownCertificates() + { + lock (_storageLock) + { + return LoadFile().Certificates + .OrderBy(item => item.Host, StringComparer.OrdinalIgnoreCase) + .ThenBy(item => item.Port) + .Select(Clone) + .ToArray(); + } + } + + public void RemoveKnownCertificate(string host, int port) + { + var normalizedHost = NormalizeHost(host); + var normalizedPort = NormalizePort(port); + lock (_storageLock) + { + var file = LoadFile(); + var removed = file.Certificates.RemoveAll(item => EndpointMatches(item, normalizedHost, normalizedPort)); + if (removed > 0) + SaveFile(file); + } + + var prefix = BuildEndpointKey(normalizedHost, normalizedPort) + "|"; + foreach (var key in _temporaryTrust.Keys.Where(key => key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))) + _temporaryTrust.TryRemove(key, out _); + } + + /// + /// Returns true when the connection may proceed. A rejected change is never + /// prompted: the operator removes the entry from the trusted list instead, + /// which keeps a certificate swap from being rubber-stamped in a hurry. + /// + public bool IsTrusted(RdpCertificateObservation observation, bool automaticallyTrustUnknown = false) + { + var normalized = observation with + { + Host = NormalizeHost(observation.Host), + Port = NormalizePort(observation.Port), + CommonName = observation.CommonName?.Trim() ?? string.Empty, + Issuer = observation.Issuer?.Trim() ?? string.Empty, + Fingerprint = NormalizeFingerprint(observation.Fingerprint) + }; + if (string.IsNullOrWhiteSpace(normalized.Host) || string.IsNullOrWhiteSpace(normalized.Fingerprint)) + return false; + + var endpointKey = BuildEndpointKey(normalized.Host, normalized.Port); + var semaphore = _endpointLocks.GetOrAdd(endpointKey, static _ => new SemaphoreSlim(1, 1)); + semaphore.Wait(); + try + { + if (_temporaryTrust.ContainsKey(BuildTrustKey(normalized))) + return true; + + KnownRdpCertificate? existing; + lock (_storageLock) + { + var file = LoadFile(); + existing = file.Certificates.FirstOrDefault(item => EndpointMatches(item, normalized.Host, normalized.Port)); + if (existing != null && string.Equals(existing.Fingerprint, normalized.Fingerprint, StringComparison.OrdinalIgnoreCase)) + { + TouchLastSeen(file, existing); + return true; + } + } + + var verification = existing == null + ? RdpCertificateVerification.Unknown + : RdpCertificateVerification.Changed; + if (verification == RdpCertificateVerification.Changed && _settings.BlockChangedRdpCertificates) + return false; + + if (verification == RdpCertificateVerification.Unknown && + (automaticallyTrustUnknown || !_settings.ConfirmRdpCertificateOnFirstConnection)) + { + TrustPermanently(normalized); + return true; + } + + var decision = _prompt.DecideAsync(new RdpCertificatePromptRequest( + normalized, + verification, + existing?.Fingerprint)) + .ConfigureAwait(false) + .GetAwaiter() + .GetResult(); + switch (decision) + { + case RdpCertificateDecision.TrustOnce: + _temporaryTrust[BuildTrustKey(normalized)] = 0; + return true; + case RdpCertificateDecision.TrustPermanently: + TrustPermanently(normalized); + return true; + default: + return false; + } + } + catch + { + return false; + } + finally + { + semaphore.Release(); + } + } + + private void TrustPermanently(RdpCertificateObservation observation) + { + lock (_storageLock) + { + var now = DateTimeOffset.UtcNow; + var file = LoadFile(); + var existing = file.Certificates.FirstOrDefault(item => + EndpointMatches(item, observation.Host, observation.Port)); + if (existing == null) + { + file.Certificates.Add(new KnownRdpCertificate + { + Host = observation.Host, + Port = observation.Port, + CommonName = observation.CommonName, + Issuer = observation.Issuer, + Fingerprint = observation.Fingerprint, + FirstSeenUtc = now, + LastSeenUtc = now + }); + } + else + { + existing.CommonName = observation.CommonName; + existing.Issuer = observation.Issuer; + existing.Fingerprint = observation.Fingerprint; + existing.FirstSeenUtc = now; + existing.LastSeenUtc = now; + } + + SaveFile(file); + } + } + + private void TouchLastSeen(KnownCertificatesFile file, KnownRdpCertificate existing) + { + var now = DateTimeOffset.UtcNow; + if (now - existing.LastSeenUtc < LastSeenWriteInterval) + return; + + existing.LastSeenUtc = now; + SaveFile(file); + } + + private KnownCertificatesFile LoadFile() + { + try + { + var payload = _store.Read("rdp_certificates", "trusted_certificates"); + return payload == null + ? new KnownCertificatesFile() + : TryDeserialize(payload) ?? new KnownCertificatesFile(); + } + catch + { + return new KnownCertificatesFile(); + } + } + + private void SaveFile(KnownCertificatesFile file) + { + _store.Write( + "rdp_certificates", + "trusted_certificates", + JsonSerializer.Serialize(file, AppJsonOptions.Default)); + } + + private static KnownCertificatesFile? TryDeserialize(string json) + { + try + { + var file = JsonSerializer.Deserialize(json, AppJsonOptions.Default); + if (file == null) + return null; + file.Certificates ??= []; + return file; + } + catch (JsonException) + { + return null; + } + } + + private static bool EndpointMatches(KnownRdpCertificate item, string host, int port) + { + return string.Equals(NormalizeHost(item.Host), host, StringComparison.OrdinalIgnoreCase) && + NormalizePort(item.Port) == port; + } + + private static string BuildEndpointKey(string host, int port) => $"{host}|{NormalizePort(port)}"; + + private static string BuildTrustKey(RdpCertificateObservation observation) + => $"{BuildEndpointKey(observation.Host, observation.Port)}|{observation.Fingerprint}"; + + private static string NormalizeHost(string? host) + { + var value = host?.Trim() ?? string.Empty; + if (value.Length > 1 && value[0] == '[' && value[^1] == ']') + value = value[1..^1]; + return value.ToLowerInvariant(); + } + + private static int NormalizePort(int port) => port is >= 1 and <= 65535 ? port : 3389; + + private static string NormalizeFingerprint(string? fingerprint) + { + var value = fingerprint?.Trim().ToLowerInvariant() ?? string.Empty; + const string prefix = "sha256:"; + if (value.StartsWith(prefix, StringComparison.Ordinal)) + value = value[prefix.Length..]; + return value.Replace(":", string.Empty, StringComparison.Ordinal); + } + + private static KnownRdpCertificate Clone(KnownRdpCertificate source) + { + return new KnownRdpCertificate + { + Host = source.Host, + Port = source.Port, + CommonName = source.CommonName, + Issuer = source.Issuer, + Fingerprint = source.Fingerprint, + FirstSeenUtc = source.FirstSeenUtc, + LastSeenUtc = source.LastSeenUtc + }; + } +} diff --git a/ViewModels/ApplicationSettingsViewModel.cs b/ViewModels/ApplicationSettingsViewModel.cs index 5186bc1..f990a28 100644 --- a/ViewModels/ApplicationSettingsViewModel.cs +++ b/ViewModels/ApplicationSettingsViewModel.cs @@ -43,6 +43,43 @@ public void NotifyLocalizationChanged() } } +public sealed partial class KnownRdpCertificateItemViewModel : ObservableObject +{ + private readonly Func _remove; + + public KnownRdpCertificateItemViewModel( + KnownRdpCertificate certificate, + Func remove) + { + Certificate = certificate; + _remove = remove; + } + + public KnownRdpCertificate Certificate { get; } + public string EndpointText => $"{Certificate.Host}:{Certificate.Port}"; + public string CommonNameText => string.IsNullOrWhiteSpace(Certificate.CommonName) + ? LocalizationService.Shared.Text("ApplicationSettings.RdpCertificateNoCommonName") + : Certificate.CommonName; + public string FingerprintText => RdpCertificatePromptViewModel.FormatFingerprint(Certificate.Fingerprint); + public string LastSeenText => string.Format( + LocalizationService.Shared.Text("ApplicationSettings.SshLastSeen"), + Certificate.LastSeenUtc.ToLocalTime().ToString("yyyy-MM-dd HH:mm")); + public string RemoveText => LocalizationService.Shared.Text("ApplicationSettings.RdpRemoveCertificate"); + + [RelayCommand] + private async Task Remove() + { + await _remove(this); + } + + public void NotifyLocalizationChanged() + { + OnPropertyChanged(nameof(CommonNameText)); + OnPropertyChanged(nameof(LastSeenText)); + OnPropertyChanged(nameof(RemoveText)); + } +} + public partial class ApplicationSettingsViewModel : ObservableObject { private readonly ApplicationSettings _settings; @@ -51,8 +88,10 @@ public partial class ApplicationSettingsViewModel : ObservableObject private readonly Action _applyTheme; private readonly LocalizationService _localization = LocalizationService.Shared; private readonly SshHostKeyTrustService _hostKeyTrust = SshHostKeyTrustService.Shared; + private readonly RdpCertificateTrustService _certificateTrust = RdpCertificateTrustService.Shared; public Func>? ConfirmRemoveKnownHostAsync { get; set; } + public Func>? ConfirmRemoveRdpCertificateAsync { get; set; } [ObservableProperty] private bool _showSessionManagerOnStartup; [ObservableProperty] private bool _minimizeToTrayOnClose; @@ -68,6 +107,8 @@ public partial class ApplicationSettingsViewModel : ObservableObject [ObservableProperty] private bool _includePrereleaseUpdates; [ObservableProperty] private bool _confirmSshHostKeyOnFirstConnection; [ObservableProperty] private bool _blockChangedSshHostKeys; + [ObservableProperty] private bool _confirmRdpCertificateOnFirstConnection; + [ObservableProperty] private bool _blockChangedRdpCertificates; [ObservableProperty] private bool _allowExternalLaunch; [ObservableProperty] private bool _confirmExternalLaunch; [ObservableProperty] private bool _registerExternalUrlProtocols; @@ -112,6 +153,7 @@ public partial class ApplicationSettingsViewModel : ObservableObject private readonly AgentModelCatalogClient _agentModelCatalogClient; public ObservableCollection KnownHosts { get; } = new(); + public ObservableCollection KnownRdpCertificates { get; } = new(); public ObservableCollection AgentPermissionModeOptions { get; } = new(); public ObservableCollection AgentProviderTypeOptions { get; } = new(); public ObservableCollection AgentModelOptions { get; } = new(); @@ -143,7 +185,16 @@ public partial class ApplicationSettingsViewModel : ObservableObject public string BlockChangedSshHostKeysText => Text("ApplicationSettings.BlockChangedSshHostKeys"); public string KnownHostsText => Text("ApplicationSettings.KnownHosts"); public string NoKnownHostsText => Text("ApplicationSettings.NoKnownHosts"); + public string RdpSecurityText => Text("ApplicationSettings.RdpSecurity"); + public string ConfirmRdpCertificateOnFirstConnectionText => Text("ApplicationSettings.ConfirmRdpCertificateOnFirstConnection"); + public string BlockChangedRdpCertificatesText => Text("ApplicationSettings.BlockChangedRdpCertificates"); + public string KnownRdpCertificatesText => Text("ApplicationSettings.KnownRdpCertificates"); + public string NoKnownRdpCertificatesText => Text("ApplicationSettings.NoKnownRdpCertificates"); + public string BuildRemoveRdpCertificateConfirmMessage(KnownRdpCertificate certificate) => string.Format( + Text("ApplicationSettings.RdpRemoveCertificateConfirmMessage"), + $"{certificate.Host}:{certificate.Port}"); public string RemoveKnownHostConfirmTitleText => Text("ApplicationSettings.SshRemoveKnownHostConfirmTitle"); + public string RemoveRdpCertificateConfirmTitleText => Text("ApplicationSettings.RdpRemoveCertificateConfirmTitle"); public string BuildRemoveKnownHostConfirmMessage(KnownSshHostKey hostKey) => string.Format( Text("ApplicationSettings.SshRemoveKnownHostConfirmMessage"), $"{hostKey.Host}:{hostKey.Port}"); @@ -224,6 +275,7 @@ public string BuildRemoveKnownHostConfirmMessage(KnownSshHostKey hostKey) => str public string EnglishText => Text("Language.English"); public string CloseText => Text("ApplicationSettings.Close"); public bool HasKnownHosts => KnownHosts.Count > 0; + public bool HasKnownRdpCertificates => KnownRdpCertificates.Count > 0; public bool IsDarkThemeSelected { @@ -292,6 +344,8 @@ public ApplicationSettingsViewModel( _includePrereleaseUpdates = settings.IncludePrereleaseUpdates; _confirmSshHostKeyOnFirstConnection = settings.ConfirmSshHostKeyOnFirstConnection; _blockChangedSshHostKeys = settings.BlockChangedSshHostKeys; + _confirmRdpCertificateOnFirstConnection = settings.ConfirmRdpCertificateOnFirstConnection; + _blockChangedRdpCertificates = settings.BlockChangedRdpCertificates; _allowExternalLaunch = settings.AllowExternalLaunch; _confirmExternalLaunch = settings.ConfirmExternalLaunch; _registerExternalUrlProtocols = settings.RegisterExternalUrlProtocols; @@ -341,7 +395,9 @@ public ApplicationSettingsViewModel( _globalProxyPassword = PasswordEncryptionService.DecryptEncrypted(globalProxy.Password); RebuildGlobalProxyTypeOptions(globalProxy.Protocol); _hostKeyTrust.Configure(settings); + _certificateTrust.Configure(settings); ReloadKnownHosts(); + ReloadKnownRdpCertificates(); RefreshAgentProviderStatus(); _localization.LanguageChanged += OnLanguageChanged; } @@ -445,6 +501,18 @@ partial void OnBlockChangedSshHostKeysChanged(bool value) Persist(); } + partial void OnConfirmRdpCertificateOnFirstConnectionChanged(bool value) + { + _settings.ConfirmRdpCertificateOnFirstConnection = value; + Persist(); + } + + partial void OnBlockChangedRdpCertificatesChanged(bool value) + { + _settings.BlockChangedRdpCertificates = value; + Persist(); + } + partial void OnRecordTerminalSessionsChanged(bool value) { _settings.RecordTerminalSessions = value; @@ -976,6 +1044,9 @@ private void OnLanguageChanged(object? sender, EventArgs e) OnPropertyChanged(nameof(SshSecurityText)); OnPropertyChanged(nameof(ConfirmSshHostKeyOnFirstConnectionText)); OnPropertyChanged(nameof(BlockChangedSshHostKeysText)); + OnPropertyChanged(nameof(RdpSecurityText)); + OnPropertyChanged(nameof(ConfirmRdpCertificateOnFirstConnectionText)); + OnPropertyChanged(nameof(BlockChangedRdpCertificatesText)); OnPropertyChanged(nameof(ExternalLaunchText)); OnPropertyChanged(nameof(AllowExternalLaunchText)); OnPropertyChanged(nameof(ConfirmExternalLaunchText)); @@ -984,6 +1055,8 @@ private void OnLanguageChanged(object? sender, EventArgs e) OnPropertyChanged(nameof(ExternalLaunchTrustCountText)); OnPropertyChanged(nameof(KnownHostsText)); OnPropertyChanged(nameof(NoKnownHostsText)); + OnPropertyChanged(nameof(KnownRdpCertificatesText)); + OnPropertyChanged(nameof(NoKnownRdpCertificatesText)); OnPropertyChanged(nameof(RecordingText)); OnPropertyChanged(nameof(RecordTerminalSessionsText)); OnPropertyChanged(nameof(RecordingDescriptionText)); @@ -1057,6 +1130,8 @@ private void OnLanguageChanged(object? sender, EventArgs e) OnPropertyChanged(nameof(IsEnglishSelected)); foreach (var item in KnownHosts) item.NotifyLocalizationChanged(); + foreach (var item in KnownRdpCertificates) + item.NotifyLocalizationChanged(); } private async Task RemoveKnownHostAsync(KnownSshHostKeyItemViewModel item) @@ -1080,6 +1155,26 @@ private void ReloadKnownHosts() OnPropertyChanged(nameof(HasKnownHosts)); } + private async Task RemoveKnownRdpCertificateAsync(KnownRdpCertificateItemViewModel item) + { + if (ConfirmRemoveRdpCertificateAsync == null || + !await ConfirmRemoveRdpCertificateAsync(item.Certificate)) + return; + + _certificateTrust.RemoveKnownCertificate( + item.Certificate.Host, + item.Certificate.Port); + ReloadKnownRdpCertificates(); + } + + private void ReloadKnownRdpCertificates() + { + KnownRdpCertificates.Clear(); + foreach (var certificate in _certificateTrust.GetKnownCertificates()) + KnownRdpCertificates.Add(new KnownRdpCertificateItemViewModel(certificate, RemoveKnownRdpCertificateAsync)); + OnPropertyChanged(nameof(HasKnownRdpCertificates)); + } + private static string NormalizeLanguage(string? language) { return string.Equals(language, LocalizationService.English, StringComparison.OrdinalIgnoreCase) diff --git a/ViewModels/MainWindowViewModel.cs b/ViewModels/MainWindowViewModel.cs index 8f3ea7d..92d5e04 100644 --- a/ViewModels/MainWindowViewModel.cs +++ b/ViewModels/MainWindowViewModel.cs @@ -336,6 +336,7 @@ public MainWindowViewModel() AgentPanel.PropertyChanged += OnAgentPanelPropertyChanged; _localization.SetLanguage(_sessionTreeVm.Settings.UiLanguage); SshHostKeyTrustService.Shared.Configure(_sessionTreeVm.Settings); + RdpCertificateTrustService.Shared.Configure(_sessionTreeVm.Settings); SessionRecordingService.Shared.Configure(_sessionTreeVm.Settings); UrlProtocolRegistrationService.Apply(_sessionTreeVm.Settings.RegisterExternalUrlProtocols); _ = Task.Run(() => SessionRecordingService.Shared.CleanupExpiredAsync()); @@ -915,6 +916,7 @@ private void ApplyApplicationSettings(ApplicationSettings settings) AgentPanel.RefreshPermissionModeFromSettings(settings.AgentPermissionMode); AgentPanel.RefreshProviderStatus(); SshHostKeyTrustService.Shared.Configure(settings); + RdpCertificateTrustService.Shared.Configure(settings); SessionRecordingService.Shared.Configure(settings); foreach (var tab in Tabs.Where(item => item.IsTerminalSession)) { diff --git a/ViewModels/RdpCertificatePromptViewModel.cs b/ViewModels/RdpCertificatePromptViewModel.cs new file mode 100644 index 0000000..ed04881 --- /dev/null +++ b/ViewModels/RdpCertificatePromptViewModel.cs @@ -0,0 +1,57 @@ +using System.Text; +using CxShell.Models; +using CxShell.Services; + +namespace CxShell.ViewModels; + +public sealed class RdpCertificatePromptViewModel +{ + private readonly LocalizationService _localization = LocalizationService.Shared; + + public RdpCertificatePromptViewModel(RdpCertificatePromptRequest request) + { + Request = request; + } + + public RdpCertificatePromptRequest Request { get; } + public bool IsChanged => Request.Verification == RdpCertificateVerification.Changed; + public bool HasPreviousFingerprint => IsChanged && !string.IsNullOrWhiteSpace(Request.PreviousFingerprint); + public string TitleText => _localization.Text("RdpCertificate.Title"); + public string WarningText => _localization.Text(IsChanged ? "RdpCertificate.ChangedWarning" : "RdpCertificate.UnknownWarning"); + public string HostLabelText => _localization.Text("RdpCertificate.Host"); + public string CommonNameLabelText => _localization.Text("RdpCertificate.CommonName"); + public string IssuerLabelText => _localization.Text("RdpCertificate.Issuer"); + public string FingerprintLabelText => _localization.Text("RdpCertificate.Fingerprint"); + public string PreviousFingerprintLabelText => _localization.Text("RdpCertificate.PreviousFingerprint"); + public string HostText => $"{Request.Observation.Host}:{Request.Observation.Port}"; + public string CommonNameText => ValueOrPlaceholder(Request.Observation.CommonName); + public string IssuerText => ValueOrPlaceholder(Request.Observation.Issuer); + public string FingerprintText => FormatFingerprint(Request.Observation.Fingerprint); + public string PreviousFingerprintText => FormatFingerprint(Request.PreviousFingerprint); + public string CancelText => _localization.Text("RdpCertificate.Cancel"); + public string TrustOnceText => _localization.Text("RdpCertificate.TrustOnce"); + public string TrustPermanentlyText => _localization.Text("RdpCertificate.TrustPermanently"); + + private string ValueOrPlaceholder(string? value) + => string.IsNullOrWhiteSpace(value) + ? _localization.Text("RdpCertificate.NotReported") + : value.Trim(); + + /// Groups a bare hex digest the way certificate tooling shows it. + internal static string FormatFingerprint(string? fingerprint) + { + var value = fingerprint?.Trim().Replace(":", string.Empty, StringComparison.Ordinal) ?? string.Empty; + if (value.Length == 0) + return string.Empty; + + var builder = new StringBuilder(value.Length + (value.Length / 2)); + for (var index = 0; index < value.Length; index++) + { + if (index > 0 && index % 2 == 0) + builder.Append(':'); + builder.Append(char.ToUpperInvariant(value[index])); + } + + return builder.ToString(); + } +} diff --git a/Views/ApplicationSettingsPage.axaml b/Views/ApplicationSettingsPage.axaml index 228555f..6d875c5 100644 --- a/Views/ApplicationSettingsPage.axaml +++ b/Views/ApplicationSettingsPage.axaml @@ -279,6 +279,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Views/RdpCertificatePromptWindow.axaml.cs b/Views/RdpCertificatePromptWindow.axaml.cs new file mode 100644 index 0000000..cf8ff40 --- /dev/null +++ b/Views/RdpCertificatePromptWindow.axaml.cs @@ -0,0 +1,48 @@ +using System; +using Avalonia.Interactivity; +using CxShell.Models; +using CxShell.ViewModels; + +namespace CxShell.Views; + +public partial class RdpCertificatePromptWindow : AtomUI.Desktop.Controls.Window +{ + private bool _hasResult; + + protected override Type StyleKeyOverride { get; } = typeof(AtomUI.Desktop.Controls.Window); + + public RdpCertificatePromptWindow() + { + InitializeComponent(); + } + + public RdpCertificatePromptWindow(RdpCertificatePromptViewModel viewModel) + : this() + { + DataContext = viewModel; + } + + private void OnCancelClick(object? sender, RoutedEventArgs e) + { + CloseWithResult(RdpCertificateDecision.Reject); + } + + private void OnTrustOnceClick(object? sender, RoutedEventArgs e) + { + CloseWithResult(RdpCertificateDecision.TrustOnce); + } + + private void OnTrustPermanentlyClick(object? sender, RoutedEventArgs e) + { + CloseWithResult(RdpCertificateDecision.TrustPermanently); + } + + private void CloseWithResult(RdpCertificateDecision decision) + { + if (_hasResult) + return; + + _hasResult = true; + Close(decision); + } +} diff --git a/Views/SettingsCenterWindow.axaml.cs b/Views/SettingsCenterWindow.axaml.cs index c58d740..e6d4f7f 100644 --- a/Views/SettingsCenterWindow.axaml.cs +++ b/Views/SettingsCenterWindow.axaml.cs @@ -23,6 +23,11 @@ public SettingsCenterWindow(SettingsCenterViewModel viewModel) this, viewModel.ApplicationSettings.RemoveKnownHostConfirmTitleText, viewModel.ApplicationSettings.BuildRemoveKnownHostConfirmMessage(hostKey)); + viewModel.ApplicationSettings.ConfirmRemoveRdpCertificateAsync = certificate => + AtomUiDialogService.ShowConfirmAsync( + this, + viewModel.ApplicationSettings.RemoveRdpCertificateConfirmTitleText, + viewModel.ApplicationSettings.BuildRemoveRdpCertificateConfirmMessage(certificate)); Closed += (_, _) => viewModel.Dispose(); } diff --git a/Views/TrustedHostsPage.axaml b/Views/TrustedHostsPage.axaml index e4b9ade..81a966b 100644 --- a/Views/TrustedHostsPage.axaml +++ b/Views/TrustedHostsPage.axaml @@ -65,6 +65,66 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/native/CxRdpBridge/cxrdp_bridge.cpp b/native/CxRdpBridge/cxrdp_bridge.cpp index e209f74..6f7b3df 100644 --- a/native/CxRdpBridge/cxrdp_bridge.cpp +++ b/native/CxRdpBridge/cxrdp_bridge.cpp @@ -33,6 +33,7 @@ #include #include +#include extern "C" { #include @@ -187,6 +188,14 @@ struct CxRdpSession cxrdp_clipboard_image_callback clipboard_image_callback = nullptr; cxrdp_clipboard_files_callback clipboard_files_callback = nullptr; cxrdp_pointer_callback pointer_callback = nullptr; + cxrdp_certificate_callback certificate_callback = nullptr; + // The certificate hooks of one connection may run more than once for the + // same certificate (negotiation TLS, then NLA/CredSSP, then the RDP layer). + // Cache the decision so the host is asked exactly once per fingerprint and + // a user is never shown two identical prompts. + std::mutex certificate_mutex; + std::string certificate_decided_fingerprint; + int certificate_decided_value = -1; void* user_data = nullptr; std::string last_error; std::mutex clipboard_mutex; @@ -324,6 +333,18 @@ UINT activate_pending_cliprdr(CxRdpSession* session); UINT flush_local_clipboard_format_list(CxRdpSession* session); void set_error(CxRdpSession* session, const std::string& message); void disarm_gfx_codec_probe(CxRdpSession* session); +void reset_certificate_decision(CxRdpSession* session); +void forget_cached_certificate(const std::string& host, int port); +std::string sha256_hex(const uint8_t* data, size_t length); +int evaluate_certificate( + CxRdpSession* session, + const char* host, + int port, + const char* common_name, + const char* issuer, + const char* fingerprint, + const char* previous_fingerprint, + uint32_t flags); CxRdpSession* get_session(rdpContext* context) { @@ -513,11 +534,140 @@ void notify_status(CxRdpSession* session, const char* message) session->status_callback(session->user_data, message); } -void notify_clipboard_text(CxRdpSession* session, const std::string& text) +void reset_certificate_decision(CxRdpSession* session) { if (!session) return; + std::lock_guard lock(session->certificate_mutex); + session->certificate_decided_fingerprint.clear(); + session->certificate_decided_value = -1; +} + +// FreeRDP keeps the certificates it accepted in its own store +// (%APPDATA%/FreeRDP/server/_.pem on Windows) and short-circuits +// the verify callback when that copy matches. That would let a stale entry +// bypass the host trust store - including the "certificate changed" rule - so +// the entry for this endpoint is dropped before every connect and the decision +// always goes through evaluate_certificate(). +void forget_cached_certificate(const std::string& host, int port) +{ + if (host.empty() || port <= 0) + return; + + std::vector roots; +#if defined(_WIN32) + if (const char* appData = std::getenv("APPDATA")) + roots.emplace_back(std::filesystem::path(appData) / "FreeRDP" / "server"); +#elif defined(__APPLE__) + if (const char* home = std::getenv("HOME")) + roots.emplace_back(std::filesystem::path(home) / ".config" / "freerdp" / "server"); +#else + if (const char* xdg = std::getenv("XDG_CONFIG_HOME")) + roots.emplace_back(std::filesystem::path(xdg) / "freerdp" / "server"); + if (const char* home = std::getenv("HOME")) + roots.emplace_back(std::filesystem::path(home) / ".config" / "freerdp" / "server"); +#endif + + const std::string fileName = host + "_" + std::to_string(port) + ".pem"; + for (const auto& root : roots) + { + std::error_code error; + const auto candidate = root / fileName; + std::filesystem::remove(candidate, error); + } +} + +std::string sha256_hex(const uint8_t* data, size_t length) +{ + if (!data || length == 0) + return {}; + + unsigned char digest[EVP_MAX_MD_SIZE]; + unsigned int digest_length = 0; + if (!EVP_Digest(data, length, digest, &digest_length, EVP_sha256(), nullptr)) + return {}; + + std::ostringstream text; + text << std::hex << std::setfill('0'); + for (unsigned int i = 0; i < digest_length; i++) + text << std::setw(2) << static_cast(digest[i]); + return text.str(); +} + +int evaluate_certificate( + CxRdpSession* session, + const char* host, + int port, + const char* common_name, + const char* issuer, + const char* fingerprint, + const char* previous_fingerprint, + uint32_t flags) +{ + if (!session) + return CX_RDP_CERTIFICATE_ACCEPT; + + // FreeRDP reports the digest in upper case on some paths and lower case on + // others; normalise so one certificate never produces two prompts. + std::string fingerprint_text = fingerprint ? fingerprint : ""; + std::transform( + fingerprint_text.begin(), + fingerprint_text.end(), + fingerprint_text.begin(), + [](unsigned char value) { return static_cast(std::tolower(value)); }); + + // The decision is cached per fingerprint and the host callback runs outside + // the lock: it may block for as long as the user takes, and holding the + // mutex would deadlock this same thread on the next notify_status(). + { + std::lock_guard lock(session->certificate_mutex); + if (session->certificate_decided_value >= 0 && + session->certificate_decided_fingerprint == fingerprint_text) + { + return session->certificate_decided_value; + } + } + + int decision = CX_RDP_CERTIFICATE_ACCEPT; + if (session->certificate_callback && !fingerprint_text.empty()) + { + decision = session->certificate_callback( + session->user_data, + host, + port, + common_name, + issuer, + fingerprint_text.c_str(), + previous_fingerprint, + flags); + if (decision != CX_RDP_CERTIFICATE_ACCEPT && decision != CX_RDP_CERTIFICATE_ACCEPT_AND_PIN) + decision = CX_RDP_CERTIFICATE_REJECT; + } + + { + std::lock_guard lock(session->certificate_mutex); + session->certificate_decided_fingerprint = fingerprint_text; + session->certificate_decided_value = decision; + } + + std::ostringstream message; + message << "RDP certificate " << (decision == CX_RDP_CERTIFICATE_REJECT ? "rejected" : "accepted") + << " host=" << (host ? host : "") + << " port=" << port + << " commonName=" << (common_name ? common_name : "") + << " sha256=" << fingerprint_text; + if (previous_fingerprint && *previous_fingerprint) + message << " previous=" << previous_fingerprint; + notify_status(session, message.str().c_str()); + + return decision; +} + +void notify_clipboard_text(CxRdpSession* session, const std::string& text) +{ if (!session) + return; + std::lock_guard lock(session->callback_mutex); if (session->clipboard_text_callback) session->clipboard_text_callback(session->user_data, text.c_str()); @@ -1804,18 +1954,19 @@ DWORD cx_verify_certificate( const char* fingerprint, DWORD flags) { - if (instance && instance->context) - { - auto* session = get_session(instance->context); - std::ostringstream message; - message << "RDP certificate accepted host=" << (host ? host : "") - << " port=" << port - << " commonName=" << (common_name ? common_name : "") - << " flags=0x" << std::hex << flags; - notify_status(session, message.str().c_str()); - } + if (!instance || !instance->context) + return 1; - return 2; + const int decision = evaluate_certificate( + get_session(instance->context), + host, + port, + common_name, + issuer, + fingerprint, + nullptr, + static_cast(flags)); + return decision == CX_RDP_CERTIFICATE_REJECT ? 0 : 1; } DWORD cx_verify_changed_certificate( @@ -1831,7 +1982,19 @@ DWORD cx_verify_changed_certificate( const char* old_fingerprint, DWORD flags) { - return cx_verify_certificate(instance, host, port, common_name, subject, issuer, new_fingerprint, flags); + if (!instance || !instance->context) + return 1; + + const int decision = evaluate_certificate( + get_session(instance->context), + host, + port, + common_name, + issuer, + new_fingerprint, + old_fingerprint, + static_cast(flags)); + return decision == CX_RDP_CERTIFICATE_REJECT ? 0 : 1; } int cx_verify_x509_certificate( @@ -1842,18 +2005,22 @@ int cx_verify_x509_certificate( UINT16 port, DWORD flags) { - if (instance && instance->context) - { - auto* session = get_session(instance->context); - std::ostringstream message; - message << "RDP X509 certificate accepted host=" << (hostname ? hostname : "") - << " port=" << port - << " length=" << length - << " flags=0x" << std::hex << flags; - notify_status(session, message.str().c_str()); - } + if (!instance || !instance->context) + return 1; - return 2; + // This path only receives the DER blob, so the digest is computed here. + // The subject and issuer stay unknown; the host shows what it was given. + const std::string fingerprint = sha256_hex(data, length); + const int decision = evaluate_certificate( + get_session(instance->context), + hostname, + port, + nullptr, + nullptr, + fingerprint.c_str(), + nullptr, + static_cast(flags)); + return decision == CX_RDP_CERTIFICATE_REJECT ? 0 : 1; } int cx_logon_error(freerdp* instance, UINT32 data, UINT32 type) @@ -3974,8 +4141,20 @@ void connection_thread(CxRdpSession* session) freerdp_settings_set_uint32(settings, FreeRDP_DesktopWidth, initialWidth); freerdp_settings_set_uint32(settings, FreeRDP_DesktopHeight, initialHeight); freerdp_settings_set_uint32(settings, FreeRDP_ColorDepth, static_cast(session->color_depth)); - freerdp_settings_set_bool(settings, FreeRDP_IgnoreCertificate, TRUE); - freerdp_settings_set_bool(settings, FreeRDP_AutoAcceptCertificate, TRUE); + // With a host certificate callback the server certificate is really + // verified: FreeRDP must neither skip the check nor auto-accept, and + // cx_verify_* maps the host decision onto its return codes. Without + // a callback the old accept-all behaviour is kept so an older host + // keeps working against this bridge. + const BOOL verify_certificate = session->certificate_callback != nullptr ? TRUE : FALSE; + freerdp_settings_set_bool(settings, FreeRDP_IgnoreCertificate, verify_certificate ? FALSE : TRUE); + freerdp_settings_set_bool(settings, FreeRDP_AutoAcceptCertificate, verify_certificate ? FALSE : TRUE); + // FreeRDP keeps accepted certificates in its own store and answers a + // matching host from there without asking anybody. Declaring the + // certificate management as external keeps every connection going + // through the host callback, so the trust store below is the only + // authority that can accept a certificate. + freerdp_settings_set_bool(settings, FreeRDP_ExternalCertificateManagement, verify_certificate); freerdp_settings_set_bool(settings, FreeRDP_Authentication, TRUE); freerdp_settings_set_bool(settings, FreeRDP_AutoLogonEnabled, TRUE); freerdp_settings_set_bool(settings, FreeRDP_LogonNotify, TRUE); @@ -4399,7 +4578,8 @@ CX_RDP_API uint32_t cxrdp_get_capabilities(void) CX_RDP_CAPABILITY_CLIPBOARD_RICH_TEXT | CX_RDP_CAPABILITY_CLIPBOARD_LOCK | CX_RDP_CAPABILITY_MULTI_MONITOR | - CX_RDP_CAPABILITY_GFX_H264; + CX_RDP_CAPABILITY_GFX_H264 | + CX_RDP_CAPABILITY_CERTIFICATE_VERIFICATION; if (has_native_audio_backend()) capabilities |= CX_RDP_CAPABILITY_AUDIO_PLAYBACK | CX_RDP_CAPABILITY_MICROPHONE; return capabilities; @@ -4440,6 +4620,21 @@ CX_RDP_API void cxrdp_set_callbacks( session->user_data = user_data; } +CX_RDP_API int cxrdp_set_certificate_callback(void* handle, cxrdp_certificate_callback callback) +{ + auto* session = static_cast(handle); + if (!session) + return -1; + if (session->running) + { + set_error(session, "RDP certificate callback must be registered before connecting."); + return -2; + } + + session->certificate_callback = callback; + return 0; +} + CX_RDP_API void cxrdp_set_clipboard_callback( void* handle, cxrdp_clipboard_text_callback clipboard_text_callback) @@ -4505,6 +4700,8 @@ CX_RDP_API int cxrdp_connect( if (session->running) return 0; + reset_certificate_decision(session); + #if defined(_WIN32) if (!session->wsa_started) { @@ -4525,6 +4722,8 @@ CX_RDP_API int cxrdp_connect( session->host = host ? host : ""; session->port = port > 0 ? port : 3389; + if (session->certificate_callback) + forget_cached_certificate(session->host, session->port); const auto credentials = parse_rdp_credentials(username); session->username = credentials.username; session->domain = credentials.domain; diff --git a/native/CxRdpBridge/cxrdp_bridge.h b/native/CxRdpBridge/cxrdp_bridge.h index 43016a2..d50fe33 100644 --- a/native/CxRdpBridge/cxrdp_bridge.h +++ b/native/CxRdpBridge/cxrdp_bridge.h @@ -31,7 +31,28 @@ typedef void (*cxrdp_pointer_callback)( int hot_y, const uint8_t* bgra_pixels); -#define CX_RDP_BRIDGE_API_VERSION 15u +/* A certificate decision is owned by the host: the bridge only asks and obeys. */ +#define CX_RDP_CERTIFICATE_REJECT 0 +#define CX_RDP_CERTIFICATE_ACCEPT 1 +#define CX_RDP_CERTIFICATE_ACCEPT_AND_PIN 2 + +/* Called from the connection thread while the RDP server certificate is being + verified, so it may block while the host asks the user. `fingerprint` is the + SHA-256 of the certificate as lowercase hex without separators. + `previous_fingerprint` is non-NULL only when the certificate changed during + the exchange, and the return value is one of the CX_RDP_CERTIFICATE_* codes. + A reject aborts the connection. */ +typedef int (*cxrdp_certificate_callback)( + void* user_data, + const char* host, + int port, + const char* common_name, + const char* issuer, + const char* fingerprint, + const char* previous_fingerprint, + uint32_t flags); + +#define CX_RDP_BRIDGE_API_VERSION 16u #define CX_RDP_CAPABILITY_CLIPBOARD 0x00000001u #define CX_RDP_CAPABILITY_DRIVE_REDIRECTION 0x00000002u #define CX_RDP_CAPABILITY_AUDIO_PLAYBACK 0x00000004u @@ -70,6 +91,10 @@ typedef void (*cxrdp_pointer_callback)( #define CX_RDP_CAPABILITY_CLIPBOARD_LOCK 0x00020000u #define CX_RDP_CAPABILITY_MULTI_MONITOR 0x00040000u #define CX_RDP_CAPABILITY_GFX_H264 0x00080000u +/* The bridge verifies the RDP server certificate through the host callback + instead of ignoring it: the host decides, and a rejection aborts the + connection. Without a registered callback the accept-all behaviour stays. */ +#define CX_RDP_CAPABILITY_CERTIFICATE_VERIFICATION 0x00100000u typedef struct CxRdpMonitorRect { @@ -104,6 +129,11 @@ CX_RDP_API void cxrdp_set_callbacks( cxrdp_status_callback status_callback, cxrdp_disconnect_callback disconnect_callback, void* user_data); + +/* Register the certificate decision callback. Call before cxrdp_connect(). + Returns 0 on success, negative when the session is unusable. + Requires CX_RDP_CAPABILITY_CERTIFICATE_VERIFICATION (API 16). */ +CX_RDP_API int cxrdp_set_certificate_callback(void* handle, cxrdp_certificate_callback callback); CX_RDP_API int cxrdp_connect( void* handle, const char* host,