Let the Linux head check for updates, and seal its device key in the TPM
ci / build and test (push) Successful in 2m55s
ci / android head (push) Successful in 3m28s
ci / desktop nightly (push) Successful in 1m10s
ci / api image (push) Successful in 49s

Two things the RPM shipped without, and the reason they arrive together is
that both are the same question — what may this platform ask of the machine,
and what must it not ask of the user.

◆ UPDATES: THIS CLIENT CHECKS AND FETCHES, AND PACKAGEKIT INSTALLS.

ADR 0013 rule 11 said there was no updater at all, and that went too far. It
conflated noticing that a newer build exists with installing it: the second is
what the trust argument is about, and the first is not — a client that checks
a fixed address and tells you what it found has taken no capability from
anybody. Written as a flat refusal, the rule bought its safety by paying a cost
that was avoidable, and the ADR now says so in its own words.

So LinuxUpdateChannel reads the rolling nightly release, compares versions the
way rpm compares them, downloads the package, verifies its digest and hands the
file to PackageKit over gdbus. Polkit asks; the user may say no; nothing is
torn down before the answer, because ApplyingEndsTheProcess is false and the
shell already knows what that means — it is the phone's shape, and declining an
update must not cost somebody their open shells.

Three details that are load-bearing rather than incidental:

  - The comparison is rpmvercmp and not SemVer, because rpm is what will accept
    or refuse the install. Same argument ADR 0014 makes for versionCode. The
    installed side is read out of the rpm database rather than derived from the
    assembly, so the SemVer-to-rpm translation exists in exactly one place. All
    28 expected values in RpmVersionTests came out of rpm itself rather than out
    of a reading of the algorithm.

  - The digest is checked and is not a signature. Velopack verifies its own
    downloads and Android checks a signature; an RPM over HTTPS has neither. The
    manifest names a SHA-256 and a mismatch deletes the file rather than leaving
    something installable-by-hand in the profile directory.

  - ONLY_TRUSTED is cleared, which is what routes the request to polkit's
    package-install-untrusted action. The package is unsigned, so requiring
    trust would fail every update at the last step.

◆ THE DEVICE KEY: SEALED IN THE TPM, BEHIND A PIN THE TPM CHECKS.

ADR 0007's amendment is the bar: a gate inside the process is not a gate. The
key is sealed into a TPM 2.0 keyedhash object whose userAuth comes from a PIN,
so unsealing is a command the chip refuses; the blob is encrypted to the storage
hierarchy and is useless on any other machine; nothing here ever compares a PIN.

The sealed object deliberately carries no NoDA attribute, and that one omission
is the whole reason four digits is enough: every wrong answer advances the TPM's
dictionary-attack counter and the chip stops answering entirely once it trips.
Measured at four wrong tries against a software TPM, after which the correct PIN
gets nothing either. It is asserted by a test rather than left to a reading of
the template, because removing the attribute leaves every other assertion
passing.

This is weaker than Hello and Touch ID and the difference is invisible, so it is
written down in three places rather than smoothed over: those raise their prompt
from inside the platform and this one is a window we draw. The prompt is
deliberately plain for that reason — teaching people that a convincing DodoSSH
PIN box is a system dialog is the one thing this design must not do.

Rejected, each for failing the amendment: the Secret Service API, which has no
per-use consent and is DPAPI's shape exactly; fprintd, which answers a question
and holds nothing, so skipping the call skips the gate; and a polkit-gated root
helper, which would work and puts a privileged component in a package that
installs nothing setuid.

Availability is narrower than "has a TPM": on Fedora /dev/tpmrm0 is root:tss and
desktop users are not in tss, so the ordinary case reports unavailable and keeps
asking for the passphrase. Shipping a udev rule to widen that is refused — it is
the administrator's decision, not an application package's.

◆ WHAT IS ACTUALLY VERIFIED, SINCE THAT IS THE PART THAT USUALLY ISN'T.

This is the only device key store in the repository with real coverage, and it
is only possible because the PIN is a delegate and the TPM is a device: seal,
unseal, wrong PIN, lockout, decline and a foreign blob all run unattended
against a software TPM. Windows and macOS cannot be tested at all — their
prompts block a suite forever, which WindowsDeviceKeyStoreTests records.

TSS.Net's own TcpTpmDevice cannot reach swtpm: it opens the platform socket too
and exchanges a handshake only the Microsoft reference simulator answers, so
Connect() blocks with no error and no timeout. SoftwareTpm speaks the data
channel and nothing else.

The suite also lied once and was fixed: the lockout test trips shared state, and
without a DictionaryAttackLockReset in Dispose every later test got null from a
correct PIN — six of them assert null and passed for entirely the wrong reason.

End to end on a real Fedora 44: a genuine linux-x64 publish packages, installs,
and every DT_NEEDED in the installed tree resolves except liblttng-ust, which is
the one this spec deliberately excludes. What no runner covers is /dev/tpmrm0,
PackageKit and polkit, and Phase 19 grew five checks for exactly those.

Also fixed: the magic-bytes literal picked up raw control characters, which made
LinuxDeviceKeyStore.cs binary to git — no diffs and no line-ending normalisation.
This commit is contained in:
jaap-jan committed 2026-08-22 20:02:30 +02:00
1 parent 1bf79c7c26
commit 4552538533
25 files changed
+2646 -105

No files matched your search

@@ -0,0 +1,223 @@
using System.Security.Cryptography;
using DodoSSH.Client.App.Platform;
using DodoSSH.Client.Session;
using Tpm2Lib;
namespace DodoSSH.Client.App.Tests;
/// <summary>
/// The TPM-backed store, driven end to end against a software TPM.
/// </summary>
/// <remarks>
/// <para>
/// <b>This is the only device key store in the repository with real coverage, and the reason is worth
/// knowing.</b> <c>WindowsDeviceKeyStoreTests</c> records that the Windows store cannot be exercised at
/// all: the consent policy prompts at creation as well as at use, so anything calling <c>SaveAsync</c>
/// blocks the suite forever waiting for a person. macOS is the same shape with a Touch ID sheet. Here the
/// PIN arrives through a delegate and the TPM through a device, so both can be supplied and the whole path
/// — seal, unseal, wrong PIN, lockout — runs unattended.
/// </para>
/// <para>
/// <b>Skipped unless a software TPM is running, which CI does not start.</b> The same arrangement the
/// Windows tests have on a machine with no TPM, and for the same reason: a suite that fails because the
/// hardware is absent is a suite people learn to ignore. Start one and they run:
/// </para>
/// <code>
/// docker run --rm -p 2321:2321 debian:bookworm-slim sh -c \
/// 'apt-get update -qq &amp;&amp; apt-get install -y -qq swtpm &gt;/dev/null &amp;&amp; \
/// swtpm socket --tpm2 --tpmstate dir=/tmp --server type=tcp,port=2321,bindaddr=0.0.0.0 \
/// --ctrl type=tcp,port=2322 --flags not-need-init,startup-clear'
/// DODOSSH_TPM_TCP=127.0.0.1 dotnet test tests/DodoSSH.Client.App.Tests
/// </code>
/// <para>
/// <b>What this cannot cover is the transport.</b> Production opens <c>/dev/tpmrm0</c> through TSS.Net's
/// <c>LinuxTpmDevice</c> and these tests open a socket, so everything above the device is proved here and
/// the device itself is proved by Phase 19 of <c>docs/manual-checks.md</c> on a machine with a real chip.
/// The split is deliberate: the commands, the templates and the attributes are where the security argument
/// lives, and they are identical either way.
/// </para>
/// </remarks>
public sealed class LinuxDeviceKeyStoreTests : IDisposable
{
private readonly string directory =
Path.Combine(Path.GetTempPath(), $"dodossh-tpm-{Guid.CreateVersion7():N}");
private static CancellationToken Token => TestContext.Current.CancellationToken;
/// <summary>Where a software TPM is listening, if the person running this started one.</summary>
private static string? Simulator => Environment.GetEnvironmentVariable("DODOSSH_TPM_TCP");
/// <summary>
/// Clears the profile directory, and clears the TPM's lockout counter behind it.
/// </summary>
/// <remarks>
/// ◆ <b>The second half is not tidiness, and leaving it out made this suite lie.</b> A software TPM is
/// one piece of shared mutable state and its dictionary-attack counter is the most global thing in it:
/// <see cref="WrongPinsEventuallyLockTheTpmOut"/> deliberately trips it, and every test that ran
/// afterwards then got null from a correct PIN. Six of them assert null and passed for entirely the
/// wrong reason; the one that asserts a successful unseal failed, which is the only reason this was
/// noticed at all.
/// </remarks>
public void Dispose()
{
if (Directory.Exists(directory))
{
Directory.Delete(directory, recursive: true);
}
if (string.IsNullOrEmpty(Simulator))
{
return;
}
try
{
using var device = new SoftwareTpm(Simulator, 2321);
device.Connect();
// The lockout hierarchy has no auth value on a fresh simulator, which is exactly the state a
// real machine is not in — there, recovery is a timer measured in hours and an administrator.
// That difference is the point of Phase 19 rather than of this file.
new Tpm2(device).DictionaryAttackLockReset(TpmRh.Lockout);
}
catch (Exception exception) when (exception is not OutOfMemoryException)
{
// A simulator that has gone away between the test and here. The next test's own connect will
// report it far more clearly than a throw out of Dispose would.
}
}
[Fact]
public async Task WithNothingSaved_LoadingReturnsNullWithoutAsking()
{
// No TPM needed and no prompt allowed: a machine that has never registered must not raise a PIN
// box on the unlock screen. The delegate fails the test rather than answering, which is the only
// way to assert "was not asked" — see the ordering this depends on in TryLoadAsync.
var store = new LinuxDeviceKeyStore(
new ClientPaths(directory),
(_, _) => throw new InvalidOperationException("A PIN was asked for with nothing stored."),
() => throw new InvalidOperationException("The TPM was opened with nothing stored."));
(await store.TryLoadAsync(Token)).ShouldBeNull();
}
[Fact]
public async Task ARoundTripReturnsTheSameKey()
{
SkipUnlessSimulated();
var key = RandomNumberGenerator.GetBytes(32);
var store = Store("1234");
await store.SaveAsync(key, Token);
// A second store over the same directory, because the point is that nothing survives in memory:
// the blob on disk and the TPM are between these two lines, and nothing else.
var loaded = await Store("1234").TryLoadAsync(Token);
loaded.ShouldNotBeNull();
loaded.ShouldBe(key);
}
[Fact]
public async Task TheWrongPinGetsNothing()
{
SkipUnlessSimulated();
await Store("1234").SaveAsync(RandomNumberGenerator.GetBytes(32), Token);
// Null rather than an exception, and rather than the key. This is the assertion the whole design
// exists for: the blob is readable by anyone who has the file, and it opens for nobody without the
// PIN, because the TPM and not this process is what checks it.
(await Store("9999").TryLoadAsync(Token)).ShouldBeNull();
}
[Fact]
public async Task DecliningThePromptFallsBackWithoutTouchingTheTpm()
{
SkipUnlessSimulated();
await Store("1234").SaveAsync(RandomNumberGenerator.GetBytes(32), Token);
// Cancelling is ordinary — IDeviceKeyStore says so — and it must not spend one of the TPM's
// lockout attempts. The device factory throwing is what proves the TPM was never opened.
var declined = new LinuxDeviceKeyStore(
new ClientPaths(directory),
(_, _) => ValueTask.FromResult<string?>(null),
() => throw new InvalidOperationException("The TPM was opened after the prompt was declined."));
(await declined.TryLoadAsync(Token)).ShouldBeNull();
}
[Fact]
public async Task WrongPinsEventuallyLockTheTpmOut()
{
SkipUnlessSimulated();
var key = RandomNumberGenerator.GetBytes(32);
await Store("1234").SaveAsync(key, Token);
// ◆ The property that makes a four-digit PIN safe here, asserted rather than assumed.
//
// The sealed object deliberately carries no NoDA attribute, so every wrong answer advances the
// TPM's dictionary-attack counter. Remove that one attribute and this test still passes every
// other assertion in this file while the PIN becomes guessable at full speed by anything holding
// the blob — which is why the lockout is asserted by observing the *correct* PIN stop working.
for (var attempt = 0; attempt < 8; attempt++)
{
(await Store("9999").TryLoadAsync(Token)).ShouldBeNull();
}
(await Store("1234").TryLoadAsync(Token)).ShouldBeNull(
"the TPM should have stopped answering, so even the right PIN gets nothing");
}
[Fact]
public async Task ForgettingLeavesNothingThatCanBeOpened()
{
SkipUnlessSimulated();
var store = Store("1234");
await store.SaveAsync(RandomNumberGenerator.GetBytes(32), Token);
await store.ForgetAsync(Token);
// Deleting the blob is the whole of it: the sealed object was never made persistent inside the
// TPM, so there is no chip state left to clean up and nothing for a later install to trip over.
File.Exists(new ClientPaths(directory).DeviceKeyFile).ShouldBeFalse();
(await Store("1234").TryLoadAsync(Token)).ShouldBeNull();
}
[Fact]
public async Task ABlobFromSomewhereElseIsRefusedRatherThanParsed()
{
var paths = new ClientPaths(directory);
paths.EnsureCreated();
// What the Windows store writes is a bare RSA ciphertext with no header, and a dual-boot machine
// or a copied profile directory can put one here. Feeding it to the TPM as a marshalled structure
// is the failure this refuses; answering null lands on the passphrase, which works.
await File.WriteAllBytesAsync(paths.DeviceKeyFile, RandomNumberGenerator.GetBytes(256), Token);
var store = new LinuxDeviceKeyStore(
paths,
(_, _) => throw new InvalidOperationException("A PIN was asked for over an unusable blob."),
() => throw new InvalidOperationException("The TPM was opened for an unusable blob."));
(await store.TryLoadAsync(Token)).ShouldBeNull();
}
private LinuxDeviceKeyStore Store(string pin) =>
new(
new ClientPaths(directory),
(_, _) => ValueTask.FromResult<string?>(pin),
() => new SoftwareTpm(Simulator ?? "127.0.0.1", 2321));
private static void SkipUnlessSimulated() =>
Assert.SkipWhen(
string.IsNullOrEmpty(Simulator),
"No software TPM. See the remarks on this class for the one command that starts one.");
}