Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
233 changes: 233 additions & 0 deletions CxShell.Tests/RdpCertificateTrustServiceTests.cs
Original file line number Diff line number Diff line change
@@ -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<RdpCertificateDecision> DecideAsync(RdpCertificatePromptRequest request)
{
CallCount++;
LastRequest = request;
return Task.FromResult(decision);
}
}
}
38 changes: 38 additions & 0 deletions Models/RdpCertificateModels.cs
Original file line number Diff line number Diff line change
@@ -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);
2 changes: 2 additions & 0 deletions Models/SessionInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
45 changes: 45 additions & 0 deletions Services/LocalizationService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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";
Expand Down
Loading
Loading