Public Access
Add the client's SSH key model, codec, merge and cipher
The client can now seal and open an SSH key item. Nothing consumes it yet — the repository, the sync engine's per-type handling and the UI come next — but this is the layer everything above it depends on, and it is the layer where the crypto has to be right. SshKeySecret holds the private key as an ordinary string, deliberately, and says so: a .NET string cannot be wiped, so the material lives until the GC reuses the memory. libsodium's guarded memory was considered and rejected because the passphrase protecting the key, the password on the next item and the JSON the codec just parsed are all strings on the same heap — protecting one field among them reads as security and buys nothing. What the design does give is that the key never reaches the disk in plaintext, never reaches the server at all, and is handed to SSH.NET through a MemoryStream so there is no temporary key file to leak. Validation refuses a public key by name. ssh-keygen writes two files whose names differ by four characters, and pasting the wrong one otherwise produces a vault item that looks fine and fails at connection time with an authentication error that says nothing about which file you chose. The merge redacts the private key and its passphrase from the conflict log. A host conflict shows both values so the loser can be put back; doing that for a private key would write the discarded key into a log that is designed to be read rather than used and is deliberately retained after acknowledgement. Two different private keys are not something anyone reconciles by reading them side by side. And the lesson worth recording, because it nearly shipped: the first version of AadResourceTypeTests proved nothing. It checked that a key payload does not open as a host and vice versa — true however both ciphers are misconfigured, because Seal and TryOpen share one constant, so changing it changes both and the round trip still works. Sealing every private key as if it were a vault passed all twelve tests. The tests now open a sealed payload independently through ItemKeys with the resource type named out of band, and that does fail under the same sabotage. A test that only compares an implementation against itself cannot catch a self-consistent mistake. The trap it defends: SyncEntityType.SshKey is 3, AadResourceType.SshKey is 6, because the crypto enum also carries None, User, Device and Vault ahead of the item types. A cast between them is a specification violation that encrypts cleanly and would only surface when another implementation refused the item.
This commit is contained in:
@@ -0,0 +1,113 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
|
||||
namespace DodoSSH.Client.Domain;
|
||||
|
||||
/// <summary>
|
||||
/// An SSH key pair as the user sees it, decrypted.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// The private key is the most valuable thing this product stores, and it is held here as an ordinary
|
||||
/// string, in managed memory, exactly like <see cref="HostSecret.Notes"/> and every passphrase in the
|
||||
/// client. That is a deliberate choice rather than an oversight, and it is worth being plain about what it
|
||||
/// does and does not give you.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// It does not give you a zeroable buffer. A .NET string cannot be wiped, so the key material lives until
|
||||
/// the garbage collector reuses the memory, and a process dump taken in the meantime contains it. The
|
||||
/// alternative — libsodium's guarded memory, which <c>DodoSSH.Crypto</c> uses for the vault keys — was
|
||||
/// considered and rejected here for one reason: the passphrase protecting this key, the password on the next
|
||||
/// item, and the decoded JSON the codec produced are all strings on the same heap. Protecting one field
|
||||
/// among them would be a measure that reads as security and buys nothing, and the honest place for that
|
||||
/// effort is the threat this design actually addresses, which is the server and the disk rather than another
|
||||
/// process running as the same user. See <c>LocalCacheProtector</c>, which says the same thing about the
|
||||
/// cache.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// What it does give you: the key never reaches the disk in plaintext and never reaches the server at all.
|
||||
/// It is sealed under the vault key before it leaves this type, and SSH.NET is handed it through a
|
||||
/// <c>MemoryStream</c> rather than a file, so there is no temporary key file to leak or forget.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed record SshKeySecret
|
||||
{
|
||||
/// <summary>What the user calls this key.</summary>
|
||||
public required string Label { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The private key, in the armoured form <c>ssh-keygen</c> writes.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Stored verbatim, including its header and trailer. Not reformatted, not re-encoded, not normalised:
|
||||
/// OpenSSH, PKCS#1 and PKCS#8 all round-trip through here untouched, and a client that rewrote them
|
||||
/// would eventually rewrite one it did not fully understand.
|
||||
/// </remarks>
|
||||
public required string PrivateKeyPem { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The passphrase protecting the private key, when it has one.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Kept with the key rather than typed per connection, which is the entire point of a vault: the
|
||||
/// passphrase defends the key file on a disk, and inside a vault the key is not on a disk. Storing both
|
||||
/// together means the vault passphrase is what protects them, which is the guarantee this product is
|
||||
/// built to make. A user who wants the second factor can leave this null and be prompted.
|
||||
/// </remarks>
|
||||
public string? Passphrase { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The public half, in <c>authorized_keys</c> form, when it is known.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Not derived from the private key, and deliberately optional. Deriving it means parsing every key
|
||||
/// format this type accepts verbatim, which is the thing above that it declines to do. It is worth
|
||||
/// keeping because installing a key on a host needs exactly this line, and a user who imported only a
|
||||
/// private key should be told the public half is missing rather than have one silently reconstructed.
|
||||
/// </remarks>
|
||||
public string? PublicKey { get; init; }
|
||||
|
||||
/// <summary>Free text.</summary>
|
||||
public string? Notes { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Whether this key is storable, and why not if it is not.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The public-key mix-up is checked explicitly because it is the mistake a person actually makes:
|
||||
/// <c>ssh-keygen</c> writes two files whose names differ by four characters, and pasting the wrong one
|
||||
/// produces a vault item that looks fine and fails at connection time with an authentication error that
|
||||
/// says nothing about which file you chose.
|
||||
/// </remarks>
|
||||
public bool TryValidate([NotNullWhen(false)] out string? error)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(Label))
|
||||
{
|
||||
error = "A key needs a name.";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(PrivateKeyPem))
|
||||
{
|
||||
error = "A key needs its private key material.";
|
||||
return false;
|
||||
}
|
||||
|
||||
var material = PrivateKeyPem.TrimStart();
|
||||
|
||||
if (material.StartsWith("ssh-", StringComparison.Ordinal)
|
||||
|| material.StartsWith("ecdsa-", StringComparison.Ordinal))
|
||||
{
|
||||
error = "That is a public key. Paste the private key — the file without the .pub extension.";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!material.StartsWith("-----BEGIN", StringComparison.Ordinal))
|
||||
{
|
||||
error = "That does not look like a private key; it should begin with \"-----BEGIN\".";
|
||||
return false;
|
||||
}
|
||||
|
||||
error = null;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace DodoSSH.Client.Domain;
|
||||
|
||||
/// <summary>A decoded SSH key payload, together with the schema version it was written at.</summary>
|
||||
/// <param name="Key">The key.</param>
|
||||
/// <param name="SchemaVersion">The version the writing client used.</param>
|
||||
public sealed record SshKeySecretDocument(SshKeySecret Key, int SchemaVersion)
|
||||
{
|
||||
/// <inheritdoc cref="HostSecretDocument.IsReadOnly" />
|
||||
/// <remarks>
|
||||
/// The consequence is sharper for a key than for a host. Re-encoding an item written by a newer client
|
||||
/// drops the fields this build has no concept of — and if one of those fields were, say, a certificate
|
||||
/// or a second key format, the item would still decrypt, still look complete, and no longer
|
||||
/// authenticate. Refusing to write is the only safe answer.
|
||||
/// </remarks>
|
||||
public bool IsReadOnly => SchemaVersion > SshKeySecretCodec.CurrentSchemaVersion;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Encodes and decodes the plaintext inside an SSH key item's encrypted payload.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Mirrors <see cref="HostSecretCodec"/>, for the same reasons and with the same guarantees: JSON so a field
|
||||
/// can be added without a migration, deterministic property order so an unchanged key does not look like a
|
||||
/// change to the sync engine, and a separate mutable document type so a decode failure cannot produce a
|
||||
/// half-built key that looks valid downstream.
|
||||
/// </remarks>
|
||||
public static class SshKeySecretCodec
|
||||
{
|
||||
/// <summary>The schema version this build writes.</summary>
|
||||
public const int CurrentSchemaVersion = 1;
|
||||
|
||||
/// <summary>Serialises a key to the bytes that get sealed.</summary>
|
||||
/// <exception cref="ArgumentException">The key is not valid for storage.</exception>
|
||||
public static byte[] Encode(SshKeySecret key)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(key);
|
||||
|
||||
if (!key.TryValidate(out var error))
|
||||
{
|
||||
throw new ArgumentException(error, nameof(key));
|
||||
}
|
||||
|
||||
var document = new SshKeyPayloadDocument
|
||||
{
|
||||
SchemaVersion = CurrentSchemaVersion,
|
||||
Label = key.Label,
|
||||
PrivateKeyPem = key.PrivateKeyPem,
|
||||
Passphrase = key.Passphrase,
|
||||
PublicKey = key.PublicKey,
|
||||
Notes = key.Notes,
|
||||
};
|
||||
|
||||
return JsonSerializer.SerializeToUtf8Bytes(
|
||||
document, SshKeyPayloadJsonContext.Default.SshKeyPayloadDocument);
|
||||
}
|
||||
|
||||
/// <summary>Parses a decrypted payload.</summary>
|
||||
/// <inheritdoc cref="HostSecretCodec.TryDecode" path="/remarks" />
|
||||
public static bool TryDecode(
|
||||
ReadOnlySpan<byte> payload,
|
||||
[NotNullWhen(true)] out SshKeySecretDocument? document)
|
||||
{
|
||||
document = null;
|
||||
|
||||
SshKeyPayloadDocument? parsed;
|
||||
try
|
||||
{
|
||||
parsed = JsonSerializer.Deserialize(
|
||||
payload, SshKeyPayloadJsonContext.Default.SshKeyPayloadDocument);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (parsed is null || parsed.SchemaVersion < 1)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var candidate = new SshKeySecret
|
||||
{
|
||||
Label = parsed.Label ?? string.Empty,
|
||||
PrivateKeyPem = parsed.PrivateKeyPem ?? string.Empty,
|
||||
Passphrase = parsed.Passphrase,
|
||||
PublicKey = parsed.PublicKey,
|
||||
Notes = parsed.Notes,
|
||||
};
|
||||
|
||||
if (!candidate.TryValidate(out _))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
document = new SshKeySecretDocument(candidate, parsed.SchemaVersion);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The serialised shape. Mutable and nullable because it models untrusted input.</summary>
|
||||
/// <inheritdoc cref="HostPayloadDocument" path="/remarks" />
|
||||
internal sealed class SshKeyPayloadDocument
|
||||
{
|
||||
public int SchemaVersion { get; set; }
|
||||
|
||||
public string? Label { get; set; }
|
||||
|
||||
public string? PrivateKeyPem { get; set; }
|
||||
|
||||
public string? Passphrase { get; set; }
|
||||
|
||||
public string? PublicKey { get; set; }
|
||||
|
||||
public string? Notes { get; set; }
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(
|
||||
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
|
||||
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
||||
UnmappedMemberHandling = JsonUnmappedMemberHandling.Skip)]
|
||||
[JsonSerializable(typeof(SshKeyPayloadDocument))]
|
||||
internal sealed partial class SshKeyPayloadJsonContext : JsonSerializerContext;
|
||||
@@ -0,0 +1,120 @@
|
||||
namespace DodoSSH.Client.Domain;
|
||||
|
||||
/// <summary>The merged key, and everything that had to be overridden to produce it.</summary>
|
||||
/// <param name="Merged">The key to store and push.</param>
|
||||
/// <param name="Conflicts">Empty when the two sides were reconcilable field by field.</param>
|
||||
public sealed record SshKeyMergeResult(
|
||||
SshKeySecret Merged,
|
||||
IReadOnlyList<HostFieldConflict> Conflicts)
|
||||
{
|
||||
/// <summary>Whether anything had to be overridden.</summary>
|
||||
public bool HasConflicts => Conflicts.Count > 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Merges two divergent versions of an SSH key against the version they both started from.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Every field is a scalar, so this is simpler than the host merge — there is no per-name map to reconcile
|
||||
/// and no ordered list whose order is its meaning. It reuses <see cref="HostFieldConflict"/> rather than
|
||||
/// declaring a parallel type: the conflict log, the storage that persists it and the interface that shows it
|
||||
/// are all shared, and a second record with identical members would have to be mapped to the first at every
|
||||
/// boundary.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>The conflict detail never carries key material.</b> A host conflict shows both values so the user can
|
||||
/// put back the one that lost; doing that for a private key would write the discarded key into the conflict
|
||||
/// log, which is a copy of a secret in a place designed to be read rather than used — and the log is
|
||||
/// deliberately retained after acknowledgement. So the private key and its passphrase report only
|
||||
/// <em>that</em> they differed. This is the one place where showing less is the safer answer, and it costs
|
||||
/// the user nothing they can act on: two different private keys are not something anyone reconciles by
|
||||
/// reading them side by side.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public static class SshKeySecretMerge
|
||||
{
|
||||
/// <summary>Produces the merged key.</summary>
|
||||
/// <param name="ancestor">The version both sides branched from.</param>
|
||||
/// <param name="local">The pending local version.</param>
|
||||
/// <param name="remote">The server's current version.</param>
|
||||
public static SshKeyMergeResult Merge(SshKeySecret ancestor, SshKeySecret local, SshKeySecret remote)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(ancestor);
|
||||
ArgumentNullException.ThrowIfNull(local);
|
||||
ArgumentNullException.ThrowIfNull(remote);
|
||||
|
||||
var conflicts = new List<HostFieldConflict>();
|
||||
|
||||
var merged = new SshKeySecret
|
||||
{
|
||||
// Null-forgiving on the two required fields, as HostSecretMerge does for the same reason: the
|
||||
// merge returns one of the three inputs, and all three are non-null here by construction.
|
||||
Label = Shown(
|
||||
nameof(SshKeySecret.Label), ancestor.Label, local.Label, remote.Label, conflicts)!,
|
||||
PrivateKeyPem = Redacted(
|
||||
nameof(SshKeySecret.PrivateKeyPem),
|
||||
ancestor.PrivateKeyPem,
|
||||
local.PrivateKeyPem,
|
||||
remote.PrivateKeyPem,
|
||||
conflicts)!,
|
||||
Passphrase = Redacted(
|
||||
nameof(SshKeySecret.Passphrase),
|
||||
ancestor.Passphrase,
|
||||
local.Passphrase,
|
||||
remote.Passphrase,
|
||||
conflicts),
|
||||
PublicKey = Shown(
|
||||
nameof(SshKeySecret.PublicKey),
|
||||
ancestor.PublicKey,
|
||||
local.PublicKey,
|
||||
remote.PublicKey,
|
||||
conflicts),
|
||||
Notes = Shown(
|
||||
nameof(SshKeySecret.Notes), ancestor.Notes, local.Notes, remote.Notes, conflicts),
|
||||
};
|
||||
|
||||
return new SshKeyMergeResult(merged, conflicts);
|
||||
}
|
||||
|
||||
/// <summary>A field whose overridden value is safe to show.</summary>
|
||||
private static string? Shown(
|
||||
string name,
|
||||
string? ancestor,
|
||||
string? local,
|
||||
string? remote,
|
||||
List<HostFieldConflict> conflicts) =>
|
||||
Resolve(name, ancestor, local, remote, conflicts, redact: false);
|
||||
|
||||
/// <summary>A field whose overridden value must not be written to the conflict log.</summary>
|
||||
private static string? Redacted(
|
||||
string name,
|
||||
string? ancestor,
|
||||
string? local,
|
||||
string? remote,
|
||||
List<HostFieldConflict> conflicts) =>
|
||||
Resolve(name, ancestor, local, remote, conflicts, redact: true);
|
||||
|
||||
private static string? Resolve(
|
||||
string name,
|
||||
string? ancestor,
|
||||
string? local,
|
||||
string? remote,
|
||||
List<HostFieldConflict> conflicts,
|
||||
bool redact)
|
||||
{
|
||||
var merge = ThreeWayMerge.Scalar(ancestor, local, remote, StringComparer.Ordinal);
|
||||
|
||||
if (merge.IsConflicted)
|
||||
{
|
||||
conflicts.Add(new HostFieldConflict(
|
||||
name,
|
||||
MergeSide.Local,
|
||||
redact ? "(kept the server's value)" : merge.Value,
|
||||
redact ? "(a different value was discarded)" : merge.Discarded,
|
||||
DiscardedWasRemoval: false));
|
||||
}
|
||||
|
||||
return merge.Value;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user