Public Access
A fingerprint approved once is now approved on every machine and survives a
restart, because host key trust is a vault item type rather than a dictionary
that dies with the process. InMemoryKnownHostStore was what shipped, so the user
was asked to verify a fingerprint on every single connection — which is the gap
most likely to train somebody to click through the one warning that actually
matters. A warning that appears when nothing is wrong teaches that nothing is
ever wrong.
The fourth item type, and like the third it cost no sync logic: a row, an EF
configuration, a migration, a server kind; a secret, a codec, a merge, a cipher,
a repository facade and a session property. One row in the client registry. The
reconciler, the mirror, the repository, the outbox and the pull filter were not
touched. SyncEntityType.KnownHostKey and AadResourceType.KnownHostKey were
already reserved, so neither the contract nor docs/crypto.md changed.
One item per (host, port, algorithm), because a server legitimately offers
several host keys and which one gets negotiated is not ours to predict. Pinning
per endpoint would make an algorithm change indistinguishable from an attack.
The label is derived rather than stored, which is the one place this type
departs from the other three. A user never names a pin — there is nothing to
name it after but the three fields it already has — and a stored label is a
second copy of data that can disagree with the first after a merge. Relabel
returns the secret unchanged, and says why.
The store answers the handshake without touching the disk. SshNetConnectionFactory
calls FindAsync from inside SSH.NET's synchronous HostKeyReceived event, over
.GetAwaiter().GetResult(), which cannot be avoided; doing SQLite I/O plus an AEAD
open per lookup there would put the handshake behind the cache. So decryption
happens in OpenAsync and RefreshAsync — on unlock and after each sync pass,
exactly where the host and key lists already reload — and FindAsync is a
dictionary read under a lock with no await inside it.
That snapshot is where the one real bug in this change lived. Install originally
merged the live pins over the freshly loaded snapshot, to protect a TrustAsync
that had landed while the read was in flight. It would also have resurrected
every pin the user had just forgotten, and stopped a withdrawal made on another
machine from ever taking effect — the store would have healed the deletion back
into existence on every refresh. Replacing wholesale and discarding the read
instead is correct because writes are the rare case: every write bumps a
generation counter, and a refresh whose stamp is stale throws itself away rather
than winning. Nothing found this but reading the method again; it is the kind of
mistake that passes every test written before it, because the test that catches
it is the one the bug tells you to write.
Forgetting is new, and persistence is what made it mandatory rather than
convenient. A mismatch is a hard refusal with no way to continue — deliberately,
and that stays — so pinning a key permanently is also a way to make a
legitimately rebuilt server permanently unreachable. Before this change the pin
died at exit and the problem solved itself; now it does not.
ForgetAsync drops every algorithm for an endpoint, and it is reachable from the
host editor rather than from the warning. Putting it on the mismatch banner would
have made it two clicks from "this may be an attack" to "connect anyway", which
is the affordance the hard refusal exists to deny. The banner already promised
the key could be removed in the host's settings; that promise is now true and
points at the button.
Trust recorded on another machine becomes visible at the next sync pass, not
immediately, and that is a decision rather than an oversight. The failure it
produces is a first-contact prompt for a host a colleague approved a minute ago:
answerable, and self-correcting on the next pass. The opposite trade — polling
the vault on the handshake thread to close a one-minute window — buys nothing
and costs the property above. The dangerous direction is not reachable at all: a
pin recorded here enters the snapshot as part of recording it, so a refresh can
never discard a local trust decision.
The server learns nothing, and this is the item type where the temptation was
real. A plaintext host column would let a known-hosts screen sort and page
without decrypting anything, and it would hand the operator the map of every
user's estate — assembled, as these things are, out of facts that are each
individually harmless. A host row concedes an address only when relay is
switched on and the database refuses to store one otherwise (ADR 0004); there is
no equivalent excuse here. The table has no column to put one in, and the EF
configuration says so where somebody adding it would be standing.
Two things about the migration in this commit are worth knowing, because both
came out of getting it wrong.
It was hand-written first, including its .Designer.cs, and that version is not
what is here. Verifying it turned up something that had been quietly assumed:
Migration_AppliedCleanly_WithNoPendingModelChanges does not check the model
snapshot. It asserts that migrations applied and that none are pending, which a
wrong snapshot satisfies perfectly — the snapshot only matters as the diff base
for the *next* migrations add, so an incorrect one passes the whole suite and
corrupts the following migration instead. The real check is to generate a
throwaway migration and confirm its Up and Down come out empty. They did, and
the generated designer was byte-identical to the transcribed one across all 1255
lines, so the hand-written work was in fact correct.
Then dotnet ef migrations remove --no-build deleted the wrong migration. With
--no-build the tool reads the previously compiled assembly rather than the files
on disk, and the probe had just changed which migration was last, so it removed
AddKnownHostKeyItem and reverted the snapshot. That turned out to leave exactly
the right diff base, so the migration here is EF's own output rather than a
transcription — a better outcome than the one that was interrupted, arrived at
by accident. Never pass --no-build to migrations remove.
Mutation tested, all three sabotages detected: dropping the algorithm from
KnownHostIdentity.For, merging instead of replacing in Install, and pointing
KnownHostKeyCipher at PortForward — which is what a cast from the wire enum's 10
would silently produce. Each is caught both by an assertion about the mechanism
and by a behavioural test that never mentions it; the resource-type sabotage is
caught by the table from d10a38d and nothing else, which is what that table is
for.
The end-to-end slice now approves the real sshd's host key through the vault,
pushes it, and reads it back on the second simulated machine — including a check
that the server learned no address, and that the second machine answers null for
an algorithm never offered.
845 tests green. Zero warnings, dotnet format clean.
Three things are deliberately not fixed. A tombstone queued over a create that
was never pushed is refused by the server as Invalid and parked; that is
pre-existing for all four item types, and the fix belongs in
VaultItemRepository.DeleteAsync rather than here. Deleting a host, or changing
its address, orphans its pins — both are correct as trust decisions, since a pin
describes an endpoint and not a bookmark, but nothing surfaces the leftovers.
And there is no interface listing pins at all: trust is created at the connect
prompt and withdrawn in the host editor. A known-hosts list is where the orphans
would become visible, and it wants the vault column rework first, for the same
reason the credential editor does.
198 lines
9.2 KiB
C#
198 lines
9.2 KiB
C#
using System.Globalization;
|
|
|
|
namespace DodoSSH.Client.Ssh;
|
|
|
|
/// <summary>A host key as the server presented it during the handshake.</summary>
|
|
/// <param name="Host">Host as dialled.</param>
|
|
/// <param name="Port">Port as dialled.</param>
|
|
/// <param name="Algorithm">Key algorithm, e.g. <c>ssh-ed25519</c>.</param>
|
|
/// <param name="Fingerprint">OpenSSH-style fingerprint, from <see cref="SshHostKeyFingerprint"/>.</param>
|
|
public sealed record HostKeyPresentation(string Host, int Port, string Algorithm, string Fingerprint);
|
|
|
|
/// <summary>
|
|
/// What makes two pins the same pin.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// <para>
|
|
/// Shared by every <see cref="IKnownHostStore"/> rather than written per implementation, because the two that
|
|
/// exist have to agree: one is what ships and the other is what this project's own SSH tests run against, and
|
|
/// an identity rule that differed between them would mean the tested behaviour was not the shipped behaviour.
|
|
/// </para>
|
|
/// <para>
|
|
/// <b>Case-insensitive, and the host is stored verbatim anyway.</b> DNS names are case-insensitive, so
|
|
/// <c>DB.internal</c> and <c>db.internal</c> are one machine and must be one pin — a store that treated them
|
|
/// as two would ask the user to approve the same server twice. Comparing case-insensitively rather than
|
|
/// lower-casing what gets stored keeps the stored value the one that was actually dialled, which matters for
|
|
/// an internationalised name or an IPv6 literal with a zone id: rewriting those means rewriting a value this
|
|
/// layer does not fully understand. Algorithm names are compared the same way for the same reason, one step
|
|
/// weaker — they are ASCII tokens, and no server has been seen to vary their case.
|
|
/// </para>
|
|
/// </remarks>
|
|
public static class KnownHostIdentity
|
|
{
|
|
/// <summary>The comparer an identity must be compared with.</summary>
|
|
public static StringComparer Comparer => StringComparer.OrdinalIgnoreCase;
|
|
|
|
/// <summary>The identity of one pin, as a single comparable value.</summary>
|
|
public static string For(string host, int port, string algorithm) =>
|
|
string.Create(CultureInfo.InvariantCulture, $"{host}:{port}/{algorithm}");
|
|
}
|
|
|
|
/// <summary>
|
|
/// The trusted host keys a user has accumulated.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// Known hosts live in the end-to-end encrypted vault as a synced entity, not in a local file. Trust
|
|
/// then follows the user to every device, and the server cannot tamper with it — which matters,
|
|
/// because a server that could silently drop a pin could downgrade every connection to first-use.
|
|
/// </remarks>
|
|
public interface IKnownHostStore
|
|
{
|
|
/// <summary>Returns the pinned fingerprint for a host and key algorithm, if there is one.</summary>
|
|
/// <remarks>
|
|
/// <para>
|
|
/// Keyed on algorithm as well as host, because a server legitimately offers several host keys and
|
|
/// which one is negotiated can change between connections. Pinning only one and rejecting the
|
|
/// others would make a normal server look hostile.
|
|
/// </para>
|
|
/// <para>
|
|
/// <b>Implementations must answer this without I/O.</b> It is called from inside SSH.NET's synchronous
|
|
/// host key event — see <c>SshNetConnectionFactory</c> — so the caller has no choice but to block the
|
|
/// thread completing the key exchange on it. Asynchronous in signature because a store may need to be
|
|
/// asynchronous to <em>fill</em> itself; not because this call may go and look something up.
|
|
/// </para>
|
|
/// </remarks>
|
|
ValueTask<string?> FindAsync(string host, int port, string algorithm, CancellationToken cancellationToken);
|
|
|
|
/// <summary>Records a host key as trusted.</summary>
|
|
ValueTask TrustAsync(HostKeyPresentation presentation, CancellationToken cancellationToken);
|
|
|
|
/// <summary>
|
|
/// Withdraws trust from every key pinned for one endpoint, whatever the algorithm.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// The counterpart to a pin that now outlives the process, and not an optional extra: a server that is
|
|
/// legitimately rebuilt gets a new host key, <see cref="SshHostKeyMismatchException"/> is a hard refusal
|
|
/// with no way past it, and without this the host would be unreachable for ever. Every algorithm goes at
|
|
/// once because the user's decision is about the machine, not about one of the keys it happens to offer.
|
|
/// </remarks>
|
|
/// <returns>How many pins were removed, so a caller can say whether there was anything to forget.</returns>
|
|
ValueTask<int> ForgetAsync(string host, int port, CancellationToken cancellationToken);
|
|
}
|
|
|
|
/// <summary>
|
|
/// The host has never been seen, so there is nothing to compare against.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// A distinct exception rather than a prompt inside the handshake, and that is a deliberate design
|
|
/// choice. SSH.NET raises host key verification as a synchronous event, so consulting the user from
|
|
/// inside it would mean blocking the handshake thread on a UI round trip — sync-over-async, and a
|
|
/// deadlock the first time the prompt needs the UI thread. Failing the connection and letting the
|
|
/// caller prompt keeps everything asynchronous, at the cost of a second TCP connection the first
|
|
/// time a host is used.
|
|
/// </remarks>
|
|
public sealed class SshHostKeyUnknownException(HostKeyPresentation presentation)
|
|
: Exception($"The host key for {presentation.Host}:{presentation.Port} is not trusted yet.")
|
|
{
|
|
/// <summary>The key the server offered, to show the user before they trust it.</summary>
|
|
public HostKeyPresentation Presentation { get; } = presentation;
|
|
}
|
|
|
|
/// <summary>
|
|
/// The host presented a different key from the one pinned for it.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// This must stay a hard block with no "continue anyway" in the connect path. A dialog offering to
|
|
/// proceed is how users are trained to click through the one warning that actually indicates an
|
|
/// interception. A legitimate key change — a rebuilt server — is handled by explicitly forgetting the
|
|
/// pin in the host's settings, which is a deliberate act performed away from the moment of
|
|
/// connecting. See <see cref="IKnownHostStore.ForgetAsync"/>.
|
|
/// </remarks>
|
|
public sealed class SshHostKeyMismatchException(HostKeyPresentation presentation, string pinnedFingerprint)
|
|
: Exception(
|
|
$"The host key for {presentation.Host}:{presentation.Port} has changed. "
|
|
+ $"Pinned {pinnedFingerprint}, but the server offered {presentation.Fingerprint}.")
|
|
{
|
|
/// <summary>The key the server offered.</summary>
|
|
public HostKeyPresentation Presentation { get; } = presentation;
|
|
|
|
/// <summary>The key previously trusted for this host.</summary>
|
|
public string PinnedFingerprint { get; } = pinnedFingerprint;
|
|
}
|
|
|
|
/// <summary>
|
|
/// A known-host store held in memory.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// <para>
|
|
/// <b>Not the one that ships.</b> <c>VaultKnownHostStore</c> is: it keeps trust in the vault, so a
|
|
/// fingerprint approved once is approved on every device and survives a restart. This is what a store looks
|
|
/// like with nothing behind it, and it exists because this project deliberately has no project references at
|
|
/// all — that is the seam which keeps connections, authentication and PTY handling testable without a cache,
|
|
/// a keyring or a server, and those tests still need somewhere to put a pin.
|
|
/// </para>
|
|
/// <para>
|
|
/// Trust is lost when the process exits, so a user of this store would be asked about every host on every
|
|
/// launch. Nothing in the application composes it.
|
|
/// </para>
|
|
/// </remarks>
|
|
public sealed class InMemoryKnownHostStore : IKnownHostStore
|
|
{
|
|
private readonly Dictionary<string, HostKeyPresentation> pins = new(KnownHostIdentity.Comparer);
|
|
private readonly Lock gate = new();
|
|
|
|
/// <inheritdoc />
|
|
public ValueTask<string?> FindAsync(
|
|
string host,
|
|
int port,
|
|
string algorithm,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
lock (gate)
|
|
{
|
|
var key = KnownHostIdentity.For(host, port, algorithm);
|
|
|
|
return ValueTask.FromResult(pins.GetValueOrDefault(key)?.Fingerprint);
|
|
}
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public ValueTask TrustAsync(HostKeyPresentation presentation, CancellationToken cancellationToken)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(presentation);
|
|
|
|
lock (gate)
|
|
{
|
|
var key = KnownHostIdentity.For(
|
|
presentation.Host, presentation.Port, presentation.Algorithm);
|
|
|
|
pins[key] = presentation;
|
|
}
|
|
|
|
return ValueTask.CompletedTask;
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public ValueTask<int> ForgetAsync(string host, int port, CancellationToken cancellationToken)
|
|
{
|
|
lock (gate)
|
|
{
|
|
// Matched on the stored values rather than by picking apart the composite key. The key exists to
|
|
// be looked up whole; taking it back apart to find an endpoint would be one parser too many, and
|
|
// a host that is an IPv6 literal is full of colons.
|
|
var doomed = pins
|
|
.Where(pin =>
|
|
KnownHostIdentity.Comparer.Equals(pin.Value.Host, host) && pin.Value.Port == port)
|
|
.Select(pin => pin.Key)
|
|
.ToArray();
|
|
|
|
foreach (var key in doomed)
|
|
{
|
|
pins.Remove(key);
|
|
}
|
|
|
|
return ValueTask.FromResult(doomed.Length);
|
|
}
|
|
}
|
|
}
|