Files
DodoSSH/tests/DodoSSH.Client.Ssh.Tests/SshServerFixture.cs
T
jaap-jan 82966af37b
ci / build and test (push) Successful in 2m8s
ci / android head (push) Successful in 3m20s
ci / desktop nightly (push) Successful in 46s
ci / api image (push) Successful in 23s
Let a connection be reached through a proxy on this machine's loopback
Step 1 of docs/reaching-a-host-you-cannot-dial.md, and it is not the step that document said it was.

SshConnectionRequest carries an optional SshLoopbackProxy and BuildConnectionInfo hands SSH.NET its proxy
ConnectionInfo when there is one. Nothing passes one yet: the callers are jump hosts and the relay, which
are steps 2 and 3.

◆ THE BRIDGE WAS THE WRONG FIRST STEP, AND BUILDING IT WOULD HAVE BEEN THE MISTAKE THIS DOCUMENT IS ABOUT.
ADR 0004 says the relay's loopback bridge "also provides ProxyJump via a SOCKS5 dynamic forward — one
mechanism, two features", and the plan took that to mean the bridge was the shared foundation. It is not:
ForwardedPortDynamic *is* the listener for a jump host — SSH.NET accepts on it, speaks SOCKS5 on it and
tunnels through the bastion — so nothing is left for a bridge of ours to do on that path. The relay is the
case with no SshClient to hang a forward off, so it is the bridge's only consumer, and the bridge belongs in
the commit that uses it. What the two actually share is one level down and a tenth of the size: being told
to reach a target through a loopback proxy while staying about the target. That is what this is.

Three properties, one test each.

A port and nothing else, so a proxy anywhere but loopback cannot be expressed. The failure that shape rules
out is an open SOCKS proxy on the user's network for the life of a shell, which nothing would report — so it
is made unrepresentable rather than validated, on the same grounds AuthenticationChoice carries a kind.

SOCKS5 rather than a dumb pipe, which is what keeps host key pinning honest. The target's own name and port
stay in the request, travel to the proxy in the CONNECT, and are what the gate pins — so a machine reached
through a bastion is pinned under its own name instead of under 127.0.0.1 on whatever ephemeral port that
day's forward got, which is not an identity at all. A pipe would have meant handing SSH.NET a stand-in and
remembering everywhere else that it was one.

And a proxy that is not listening fails as a connection error rather than as an unknown host key. The gate
turns "no host key seen" into a fingerprint prompt, and a connection that never reached a server has seen
none either; the prompt would offer to fix the wrong thing, with no fingerprint to show.

TWO THINGS THE TESTS MEASURED RATHER THAN ASSUMED, both found by the first run failing.

The target is resolved at the *bastion*, not here — a SOCKS CONNECT names it and the far end looks it up. So
the test asks for localhost:2222, the address inside the container, and the published port this host would
use means nothing there. That is not a quirk of the fixture; it is what ProxyJump means, and it is why an
ssh_config writes the target's internal address beside its jump host. Getting it wrong is a SOCKS "general
failure" that names neither end.

And the test server refuses forwarding. linuxserver/openssh-server ships AllowTcpForwarding no, which a
dynamic forward does not notice — opening one asks the server nothing — so every connection through it is
refused at channel-open and reported as the same general failure. The fixture patches it and HUPs sshd.
There are two sshd_config files in that image and the running server uses /config/sshd/sshd_config; the
first attempt patched /etc/ssh/sshd_config, which is the one a search finds first, changed the text and
nothing else, and left the failure exactly where it was.

VERIFIED. Build clean with no new warnings, 85 tests in Client.Ssh.Tests against the real sshd, and the
solution builds. The proxy test was seen to fail — proxy.Port + 1 in BuildConnectionInfo — and seen green
again. An earlier mutation attempt did not compile, and the log said 85 passing because the run never
started and the previous log was still on disk; the second attempt deletes the log first, which is worth
copying whenever a mutation "passes".

dotnet format reports one pre-existing IDE1006 in DodoSSH.Api/Features/Events/EventsEndpoint.cs, in a
project nothing here touches. Left alone.
2026-08-07 13:48:15 +02:00

288 lines
12 KiB
C#

using System.Security.Cryptography;
using DotNet.Testcontainers.Builders;
using DotNet.Testcontainers.Containers;
using Xunit;
namespace DodoSSH.Client.Ssh.Tests;
/// <summary>
/// A real OpenSSH server in a container, with password and public-key auth both enabled.
/// </summary>
/// <remarks>
/// <para>
/// One container per assembly. Everything the SSH layer needs to be right about — PTY
/// allocation, window-change requests, host key encoding, key formats — is behaviour of a real
/// sshd, and none of it can be established against a mock.
/// </para>
/// <para>
/// The image is Alpine-based, so <c>stty</c> comes from busybox. Its <c>stty size</c> prints
/// "rows cols", which is what the resize assertions read.
/// </para>
/// </remarks>
public sealed class SshServerFixture : IAsyncLifetime
{
/// <summary>The account tests authenticate as.</summary>
public const string Username = "dodo";
/// <summary>Password for password authentication.</summary>
public const string Password = "correct-horse-battery-staple";
/// <summary>
/// The port sshd listens on <em>inside</em> the container, rather than the one it is published on.
/// </summary>
/// <remarks>
/// What anything reaching this server from within the container's own network namespace has to use —
/// which includes a forward opened on a connection to it. <see cref="Port"/> is the mapped port on the
/// host and is not listening in there. See <c>LoopbackProxyTests</c>, where the difference is the whole
/// shape of the test.
/// </remarks>
public const int InternalPort = SshPort;
private const int SshPort = 2222;
private readonly SemaphoreSlim sftpGate = new(1, 1);
private IContainer? container;
private ISftpSession? sftp;
/// <summary>Host port the container's sshd is published on.</summary>
public ushort Port => container!.GetMappedPublicPort(SshPort);
/// <summary>Host the container is reachable at.</summary>
public string Host => container!.Hostname;
/// <summary>An RSA key pair whose public half is authorized on the server.</summary>
public RSA ClientKey { get; } = RSA.Create(3072);
/// <inheritdoc />
public async ValueTask InitializeAsync()
{
container = new ContainerBuilder("linuxserver/openssh-server:latest")
.WithEnvironment("PUID", "1000")
.WithEnvironment("PGID", "1000")
.WithEnvironment("USER_NAME", Username)
.WithEnvironment("USER_PASSWORD", Password)
.WithEnvironment("PASSWORD_ACCESS", "true")
.WithEnvironment("SUDO_ACCESS", "false")
.WithEnvironment("PUBLIC_KEY", ExportOpenSshPublicKey(ClientKey))
.WithPortBinding(SshPort, assignRandomHostPort: true)
// The entrypoint generates host keys, rewrites sshd_config and installs the authorized
// key before sshd is usable, so a published port is not readiness. Both conditions are
// needed: the log line proves the authorized key was installed (a connection accepted
// before that fails public-key auth), and the port check proves sshd is actually
// accepting. The message is this image's own wording — "Server listening on" is
// OpenSSH's and never appears here, which is a wait that hangs rather than fails.
.WithWaitStrategy(Wait.ForUnixContainer()
.UntilMessageIsLogged("Public key from env variable added")
.UntilCommandIsCompleted("sh", "-c", $"netstat -ltn | grep -q ':{SshPort}'"))
.Build();
await container.StartAsync();
await AllowTcpForwardingAsync();
}
/// <summary>
/// Lets this server open the direct-tcpip channels a forward is made of.
/// </summary>
/// <remarks>
/// <para>
/// ◆ <b>The image ships <c>AllowTcpForwarding no</c>, and nothing says so at the point it bites.</b> A
/// dynamic forward starts perfectly happily — it is a local listener, and opening it asks the server
/// nothing — and then every connection through it is refused when the channel is opened. SSH.NET
/// reports that as <c>SOCKS5: General failure</c> from the proxy, which names neither the server nor
/// the setting, and is what the first run of <c>LoopbackProxyTests</c> collected.
/// </para>
/// <para>
/// Patched after start rather than baked in, because the image's entrypoint writes its configuration
/// itself on every boot — a mounted file would be overwritten before sshd read it. sshd re-reads on
/// <c>SIGHUP</c> and applies the result to connections made after that, and the readiness wait has
/// already run, so nothing here races the boot.
/// </para>
/// <para>
/// ◆ <b><c>/config/sshd/sshd_config</c>, and there are two.</b> The image also carries
/// <c>/etc/ssh/sshd_config</c>, which looks like the file to patch, reads identically, and is not the
/// one the running server was started with — patching it changes the text and nothing else, which is a
/// fix that appears to work and leaves the failure exactly where it was. Measured with <c>find</c>
/// rather than assumed, after the first version of this method did precisely that.
/// </para>
/// <para>
/// It is on for the whole assembly rather than for the one test that needs it. Forwarding is off in
/// this image as hardening, not as a behaviour worth reproducing: nothing else here opens a channel of
/// any kind, so allowing it changes what exactly one suite can do and what none of the others see.
/// </para>
/// </remarks>
private async Task AllowTcpForwardingAsync()
{
var result = await container!.ExecAsync([
"sh",
"-c",
"sed -i 's/^AllowTcpForwarding no/AllowTcpForwarding yes/' /config/sshd/sshd_config"
+ " && pkill -HUP sshd",
]);
if (result.ExitCode != 0)
{
throw new InvalidOperationException(
$"Could not enable TCP forwarding on the test server: {result.Stderr}");
}
}
/// <summary>
/// Adds one <c>authorized_keys</c> line to the account tests authenticate as.
/// </summary>
/// <remarks>
/// <para>
/// The fixture's own key arrives through the image's <c>PUBLIC_KEY</c> variable, which takes one. This
/// is for the case that needs a second: proving a key <em>this client generated</em> authenticates
/// against a real sshd, which is the only test that can establish the hand-written
/// <c>openssh-key-v1</c> encoding is right. A parser accepting the file is weaker — SSH.NET could be
/// forgiving about something OpenSSH is not.
/// </para>
/// <para>
/// sshd re-reads <c>authorized_keys</c> on each authentication attempt, so nothing has to be restarted.
/// </para>
/// </remarks>
public async ValueTask AuthorizeAsync(string publicKeyLine, CancellationToken cancellationToken)
{
ArgumentException.ThrowIfNullOrWhiteSpace(publicKeyLine);
// Single-quoted in the shell and the line is base64 plus an algorithm name and a comment, so there
// is nothing in it a quote could end. Asserted rather than assumed all the same: a silent failure
// here would show up as an authentication error in a test whose subject is the key encoding, which
// is the most misleading way for this to break.
var result = await container!.ExecAsync(
["sh", "-c", $"echo '{publicKeyLine.Trim()}' >> /config/.ssh/authorized_keys"],
cancellationToken);
if (result.ExitCode != 0)
{
throw new InvalidOperationException(
$"Could not install the public key in the container: {result.Stderr}");
}
}
/// <summary>
/// One file-transfer session, opened on first use and shared by every test that wants one.
/// </summary>
/// <remarks>
/// <para>
/// Shared rather than opened per test, and that is a limit of the server rather than an optimisation.
/// sshd's <c>MaxStartups</c> drops connections at random once enough are part-way through a handshake,
/// and this client's first contact with an unknown host is a connection deliberately <em>refused</em> at
/// the host key — so a suite that opened its own session per test made two handshakes per test and
/// pushed the whole assembly over the threshold. What that looks like is unrelated tests failing with
/// "the connection was closed by the remote host", a different few each run.
/// </para>
/// <para>
/// Safe to share because an SFTP session holds no per-test state: every test here works in a directory
/// named after itself. See <c>ISftpSession</c>, which is one channel and is used by one caller at a
/// time.
/// </para>
/// </remarks>
public async ValueTask<ISftpSession> SftpAsync(CancellationToken cancellationToken)
{
await sftpGate.WaitAsync(cancellationToken);
try
{
if (sftp is not null)
{
return sftp;
}
var knownHosts = new InMemoryKnownHostStore();
var factory = new SshNetConnectionFactory(knownHosts);
var request = new SshConnectionRequest(
Host, Port, Username, new SshPasswordCredential(Password));
try
{
// Learned by being refused, which is the only way this client learns a host key.
return sftp = await factory.OpenSftpAsync(request, cancellationToken);
}
catch (SshHostKeyUnknownException unknown)
{
await knownHosts.TrustAsync(unknown.Presentation, cancellationToken);
}
return sftp = await factory.OpenSftpAsync(request, cancellationToken);
}
finally
{
sftpGate.Release();
}
}
/// <inheritdoc />
public async ValueTask DisposeAsync()
{
if (sftp is not null)
{
await sftp.DisposeAsync();
}
sftpGate.Dispose();
if (container is not null)
{
await container.DisposeAsync();
}
ClientKey.Dispose();
}
/// <summary>
/// Renders an RSA public key in the single-line <c>authorized_keys</c> format.
/// </summary>
/// <remarks>
/// Hand-encoded because there is no BCL helper. The SSH wire format is a sequence of
/// length-prefixed strings: the algorithm name, then the exponent, then the modulus — both
/// as signed big-endian integers, which is why a leading zero byte is prepended when the
/// high bit is set. Getting that wrong yields a key sshd silently ignores.
/// </remarks>
private static string ExportOpenSshPublicKey(RSA rsa)
{
var parameters = rsa.ExportParameters(includePrivateParameters: false);
using var blob = new MemoryStream();
WriteSshString(blob, "ssh-rsa"u8.ToArray());
WriteSshMpint(blob, parameters.Exponent!);
WriteSshMpint(blob, parameters.Modulus!);
return $"ssh-rsa {Convert.ToBase64String(blob.ToArray())} dodossh-test";
}
private static void WriteSshString(Stream destination, byte[] value)
{
Span<byte> length = stackalloc byte[4];
System.Buffers.Binary.BinaryPrimitives.WriteUInt32BigEndian(length, (uint)value.Length);
destination.Write(length);
destination.Write(value);
}
private static void WriteSshMpint(Stream destination, byte[] value)
{
// Signed big-endian: a high bit set would otherwise read as negative.
if (value.Length > 0 && (value[0] & 0x80) != 0)
{
var padded = new byte[value.Length + 1];
value.CopyTo(padded, 1);
WriteSshString(destination, padded);
return;
}
WriteSshString(destination, value);
}
}
/// <summary>Shares one SSH server across every test class in the assembly.</summary>
[CollectionDefinition(Name)]
public sealed class SshCollection : ICollectionFixture<SshServerFixture>
{
/// <summary>Collection name.</summary>
public const string Name = "ssh";
}