Keep the device key in the TPM, behind a consent Windows enforces

The last of ADR 0007's three pieces, and it does not implement what that ADR
originally decided — because writing it exposed a flaw in the decision.

The ADR said "a Windows Hello gesture gating a protected blob". That does not
deliver what the rest of the document claims for it: a gate inside the process is
not a gate. A store that showed a prompt and then read a DPAPI blob would be
bypassed by malware that skipped the prompt, read the file and called
CryptUnprotectData itself — which is exactly the attacker the whole decision was
made against, and exactly the reason DPAPI alone was rejected. The presence
requirement has to be a condition of using the key, enforced below the
application, or it is decoration.

So the device key is encrypted to an RSA key created in the Microsoft Platform
Crypto Provider — the TPM — under CngUIProtectionLevels.ProtectKey. Windows
requires consent to use that key, so the prompt is not something this code can be
talked out of showing. Malware can ask for the key; it cannot answer the dialog.
That is strictly stronger than the ADR described, and most of what option D was
being saved for: the wrapping key genuinely never leaves hardware. The X25519
device key still lands in memory to open the wrap, because DSH1 fixes that wrap at
a curve the TPM cannot do — the remaining gap, and now a smaller step than it was.

CngKey is in-box, so this needed no WinRT projection and no Windows target
framework. Which is worth stating plainly because the opposite was planned: the
piece was scoped as "where the Windows TFM lands", and it turned out a platform
guard on one class was enough. Client.App and its two test projects stay on
net10.0.

Two things were measured on real hardware rather than assumed, and the second
changed the shape of the work.

The platform provider works here and holds an RSA key — confirmed by creating and
deleting one before writing anything that depended on it.

And ProtectKey prompts at key *creation*, not only at use. The comment in the
first draft of this file said the opposite, with a confident explanation: sealing
uses only the public half, so it should be silent. It is not. CngKey.Create blocks
on a dialog, because the policy means "protect this key with a PIN" and Windows
asks the user to set that up there and then. Found by writing tests around save
and forget and watching the suite hang for ten minutes waiting for somebody to
type one.

That has two consequences worth knowing before touching this file. SaveAsync is
user-facing code — it belongs on a UI thread, behind a button somebody pressed,
never on a background pass. And almost nothing in the store can be covered
automatically: two tests remain, availability and the empty-blob case, both of
which provably reach no dialog. Disabling the UI policy to make the rest testable
would remove the one property worth having.

The interface offers two things and hides both where they cannot work. "Use
Windows Hello" appears on the unlock screen only when this machine has a cached
wrap and a keystore still willing to release the key; "Use Windows Hello here"
appears in the account bar only when the machine can keep a key and has not
already registered one, so it is spent once used. Absent rather than disabled, in
both cases: a greyed-out button on a machine that never had a TPM reads as
something broken, and the passphrase box beside it is not a fallback — it is the
ordinary way in.

Both unlock paths now share AdoptAsync rather than each opening the known-host
store, building the vault and starting auto-sync. The ordering in there is
load-bearing and a second copy would be a second chance to get it wrong.

The shell's tests drive a fake keystore. Not for speed: the real one prompts on
every save and load, so a suite using it would block forever. What the shell has
to get right is which buttons appear and what happens when one is pressed, and a
fake answers exactly that. It is shared from Client.Session.Tests by source link
rather than reimplemented.

882 tests green, 6 of them new. Zero warnings, dotnet format clean.

Not verified, and not verifiable here: the dialogs. Whether the consent prompt
appears at the right moments, reads sensibly, and returns to a usable window when
declined needs the application run by a person on a machine with a TPM. That is
the remaining half of outstanding item #7, and it is now the only thing between
this feature and being finished.
This commit is contained in:
2026-07-30 15:17:30 +02:00
parent 1faea42b94
commit 573f5d5668
12 changed files with 699 additions and 88 deletions
@@ -1,5 +1,9 @@
using DodoSSH.Client.App.ViewModels;
using DodoSSH.Client.Session;
// FakeDeviceKeyStore is compiled into this assembly from a source link and keeps its original namespace;
// see the csproj for why it is shared rather than reimplemented.
using DodoSSH.Client.Session.Tests;
using DodoSSH.Client.Ssh;
using DodoSSH.Client.Storage;
using DodoSSH.Client.Terminal;
@@ -43,6 +47,14 @@ public sealed class ShellFlowTests : IAsyncLifetime
private ClientCacheFactory caches = null!;
private TerminalWorkspace workspace = null!;
private VaultKnownHostStore knownHosts = null!;
/// <remarks>
/// A fake rather than the real TPM-backed store, and not for speed: the real one prompts for a Windows
/// consent dialog on every save and every load, so a suite using it would block forever waiting for
/// somebody to enter a PIN. What the shell has to get right is which buttons appear and what happens when
/// one is pressed, and that is exactly what a fake keystore can answer.
/// </remarks>
private FakeDeviceKeyStore deviceKeys = null!;
private MainWindowViewModel shell = null!;
/// <inheritdoc />
@@ -58,6 +70,7 @@ public sealed class ShellFlowTests : IAsyncLifetime
// shell's business — opened on unlock, closed on lock — and the trust it records goes into the vault
// this suite already has, so substituting one would only stop the wiring being tested.
knownHosts = new VaultKnownHostStore();
deviceKeys = new FakeDeviceKeyStore();
// In-memory assets rather than the application's Avalonia-resource provider, which reads the
// resource system at construction and needs an initialised toolkit. This is what
@@ -94,6 +107,7 @@ public sealed class ShellFlowTests : IAsyncLifetime
caches,
workspace,
knownHosts,
deviceKeys,
SignInAsync,
TimeProvider.System,
CheapProfile);
@@ -276,6 +290,7 @@ public sealed class ShellFlowTests : IAsyncLifetime
caches,
workspace,
new VaultKnownHostStore(),
new UnavailableDeviceKeyStore(),
(_, _) => throw new InvalidOperationException("The shell went to the network to unlock."),
TimeProvider.System,
CheapProfile);
@@ -720,6 +735,7 @@ public sealed class ShellFlowTests : IAsyncLifetime
caches,
workspace,
new VaultKnownHostStore(),
new UnavailableDeviceKeyStore(),
(_, _) => throw new InvalidOperationException("unreachable"),
TimeProvider.System,
CheapProfile);
@@ -1251,6 +1267,73 @@ public sealed class ShellFlowTests : IAsyncLifetime
private Task ReadyToUnlockAsync() => EnrolledAndConfirmedAsync();
// ---- Unlocking with this machine's device key ----
[Fact]
public async Task AnUnlockedVaultOffersToRegisterThisMachine()
{
await UnlockedAsync();
shell.CanRegisterDevice.ShouldBeTrue();
// Not before: a locked machine with nothing registered has nothing to offer, and the unlock screen
// must not show a gesture button for a key it does not have.
shell.CanUnlockWithDevice.ShouldBeFalse();
}
[Fact]
public async Task RegisteringThenRelaunching_UnlocksWithTheGestureAndNoPassphrase()
{
// The shell's half of the feature, end to end through the commands a user actually presses.
await UnlockedAsync();
await shell.RegisterDeviceCommand.ExecuteAsync(null);
shell.CanRegisterDevice.ShouldBeFalse("it is registered now, so the offer is spent");
server.RegisteredDevices.Count.ShouldBe(1);
await shell.LockCommand.ExecuteAsync(null);
await shell.StartAsync(Token);
shell.CanUnlockWithDevice.ShouldBeTrue("the wrap is cached and the keystore still has the key");
await shell.UnlockWithDeviceCommand.ExecuteAsync(null);
shell.State.ShouldBe(ShellState.Unlocked, shell.StatusMessage);
shell.Passphrase.ShouldBeEmpty("nothing was typed");
}
[Fact]
public async Task OnAMachineWithNoKeystore_NeitherAffordanceAppears()
{
deviceKeys.IsAvailable = false;
await UnlockedAsync();
shell.CanRegisterDevice.ShouldBeFalse();
shell.CanUnlockWithDevice.ShouldBeFalse();
}
[Fact]
public async Task ADeclinedGesture_LeavesTheUnlockScreenUsable()
{
// The fallback that makes the whole thing safe to offer: a cancelled prompt changes the message and
// nothing else, and the passphrase still opens the vault.
await UnlockedAsync();
await shell.RegisterDeviceCommand.ExecuteAsync(null);
await shell.LockCommand.ExecuteAsync(null);
await shell.StartAsync(Token);
deviceKeys.Decline = true;
await shell.UnlockWithDeviceCommand.ExecuteAsync(null);
shell.State.ShouldBe(ShellState.Locked);
shell.Passphrase = Passphrase;
await shell.UnlockCommand.ExecuteAsync(null);
shell.State.ShouldBe(ShellState.Unlocked, shell.StatusMessage);
}
private async Task UnlockedAsync()
{
await EnrolledAndConfirmedAsync();