Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/omnet/blob/main/docs/design/tailnet-lock.md # omnet aien-dev/omnet Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `omnet / docs / design / tailnet-lock.md` 328 lines · 23706 bytes Raw Blame History Source # Tailnet Lock for self-hosted control servers Status: bounded Omega daemon and pinned Headscale adapter implemented; isolated stock-client control-plane lifecycle verified. Not deployed or production-qualified. See Plan and status. ## Problem A Tailscale control server decides which devices join a tailnet. If that server is compromised, or a join key is stolen, an attacker can add a device that every other device then trusts. Tailnet Lock (the Tailnet Key Authority, TKA) moves that decision to the devices: a new device is trusted only if its node key carries a signature from a key the devices themselves hold. The device side ships in the stock Tailscale client. The self-hosted control server headscale does not implement the server side (headscale#1307 , open since 2023). Without server-side support, a self-hosted tailnet cannot use this client-enforced signature check to constrain device admission by a compromised control server. ## Goal and non-goals Goal: a server-side TKA implementation that a stock Tailscale client (v1.102.x) accepts, with all protocol, encoding and cryptographic logic in Omega. Non-goals for the first release: - Admin UI and key-management commands beyond what the client's `tailscale lock` commands call. - Compatibility with clients older than v1.102. - Upstreaming into headscale. That needs maintainer agreement first: the maintainers have said they are wary of reviewing a cryptographic contribution of this size. ## What the server must do Source: `tailscale/tailscale` tag `v1.102.0`, files `tailcfg/tka.go`, `ipn/ipnlocal/tailnet-lock.go`, `tka/*.go`. ### Remote procedures The client calls these over the existing Noise channel as HTTP `GET` requests with a JSON body. `[]byte` fields are base64 in JSON. AUM hashes are `tka.AUMHash.MarshalText`: base32, standard alphabet, no padding. Node keys are `nodekey:`. Path Request → response Server action `/machine/tka/init/begin` `TKAInitBeginRequest{Version, NodeKey, GenesisAUM}` → `TKAInitBeginResponse{NeedSignatures []TKASignInfo}` Validate the genesis AUM: a checkpoint AUM carrying the initial state. Hold it pending, and list every node that needs a signature. `/machine/tka/init/finish` `TKAInitFinishRequest{Version, NodeKey, Signatures map[NodeID][]byte, SupportDisablement}` → `{}` Verify each node-key signature against the pending genesis keys. Commit genesis and signatures atomically, then announce the new head to every node. `/machine/tka/bootstrap` `TKABootstrapRequest{Version, NodeKey, Head}` → `TKABootstrapResponse{GenesisAUM, DisablementSecret}` Return the genesis AUM to a node without TKA state. Return the disablement secret only after TKA has been disabled. `/machine/tka/sync/offer` `TKASyncOfferRequest{Version, NodeKey, Head, Ancestors}` → `TKASyncOfferResponse{Head, Ancestors, MissingAUMs}` Compute the server's own offer (`tka/sync.go` `SyncOffer`: head plus ancestors, skipping 4, then ×4 each step). Find the intersection with the node's offer and return the AUMs the node lacks. `/machine/tka/sync/send` `TKASyncSendRequest{Version, NodeKey, Head, MissingAUMs, Interactive}` → `TKASyncSendResponse{Head}` Verify and apply the node's AUMs (`Authority.Inform`), persist them, and announce a head change. `/machine/tka/disable` `TKADisableRequest{Version, NodeKey, Head, DisablementSecret}` → `{}` Check the secret against the state's disablement values (`Authority.ValidDisablement`). On a match, mark TKA disabled and keep the secret for bootstrap. `/machine/tka/sign` `TKASubmitSignatureRequest{Version, NodeKey, Signature}` → `{}` Verify the node-key signature under the current authority, store it for the node it names, and push it to peers. `/machine/tka/affected-sigs` `TKASignaturesUsingKeyRequest{Version, NodeKey, KeyID}` → `{Signatures}` List the stored signatures made by `KeyID`. The client uses this when a key is removed. The server also writes into the map stream: - `MapResponse.TKAInfo{Head, Disabled}`. A nil TKAInfo in the first response means TKA is off; in a delta response, nil means no change. Clients sync whenever Head differs from their own. - `Node.KeySignature`, for the node itself and for every peer, on every map path, including peer change deltas. `RegisterRequest.NodeKeySignature` arrives at registration and when a node rotates its key. It must be stored and served as that node's `KeySignature`. `RegisterRequest.NLKey` is the node's tailnet-lock public key. It must be stored too, because `init/begin` returns it as `TKASignInfo.RotationPubkey`. The client copies that value into the signature's `WrappingPubkey` (`tailnet-lock.go` `signNodeKey`), and a later key rotation fails verification without it (`tka/sig.go:260-274`). ### Data formats that must match byte for byte - AUM: a CBOR map with integer keys: `1` MessageKind, `2` PrevAUMHash, `3` Key, `4` KeyID, `5` State, `6` Votes, `7` Meta, `23` Signatures. Unset optional fields are omitted. It is encoded in CTAP2 canonical mode (`fxamacker/cbor` `CTAP2EncOptions`). `Hash = BLAKE2s-256(Serialize(aum))`. `SigHash = BLAKE2s-256(Serialize(aum without Signatures))`. Kinds: 1 AddKey, 2 RemoveKey, 3 NoOp, 4 UpdateKey, 5 Checkpoint. - State: integer keys `1` LastAUMHash, `2` DisablementValues, `3` Keys, `4` StateID1, `5` StateID2. At most 512 keys. - NodeKeySignature: integer keys `1` SigKind, `2` Pubkey, `3` KeyID, `4` Signature, `5` Nested, `6` WrappingPubkey. Kinds are direct, rotation and credential (the wrapped pre-auth key). `SigHash = BLAKE2s-256(Serialize(sig without Signature))`. - Signature rules (tag `v1.102.0`): AUM signatures (`tka/verify.go:28`) and direct and credential node-key signatures (`tka/sig.go:300`) use `ed25519consensus` (ZIP-215, mode 1 in `om/ed25519`). The outer signature of a rotation node-key signature (`tka/sig.go:273`) uses Go's `crypto/ed25519` (strict, mode 0). A server that uses a different rule from the clients splits the tailnet. - Disablement values: `argon2.Key(secret, "tailscale network-lock disablement salt", t=4, m=16 MiB, p=4, len=32)`. That is Argon2i, which hashes with BLAKE2b. - Fork choice: when two AUMs share a parent, `tka/tka.go` `pickNextAUM` decides deterministically: (1) the highest signature weight wins; (2) on equal weight, a RemoveKey AUM wins; (3) otherwise the lowest AUM hash wins. The server must pick the same chain the clients pick. ## Architecture ``` flowchart LR C[Stock Tailscale client] -- Noise HTTP/2 --> H[headscale] H -- "glue: route + identity + raw JSON" --> T[tkad: Omega program] T --> S[(AUM log + state files)] H -- "TKAInfo.Head, KeySignature" --> C ``` tkad is one Omega program and holds all TKA logic: - JSON decode and encode of the eight request and response types. - base64, base32 and hex codecs. - CTAP2 CBOR for AUMs, State and NodeKeySignatures. - AUM validation, state transitions, fork choice, sync offers and intersections. - Signature verification. - Disablement checks (Argon2i). - Storage. It listens on a local socket, using the Omega native host operations from omega-mv `seed/host/`. Storage design for stage four: a single versioned whole-service snapshot, including authority updates in reconstruction-preserving typed form, node records/signatures, pending initialization, and disablement state. A candidate is built in the inactive authority slot. Write a temporary file, fsync it, rename it over the committed snapshot, then fsync the directory before publishing the candidate or acknowledging success. Failure after rename but before directory fsync is an uncertain commit: stop serving, do not attempt a rollback rename. Recovery validates the entire committed snapshot; a missing or corrupt snapshot is not interpreted as disabled TKA. The state directory is provisioned under trusted ancestors, owned by the effective UID, and mode - Open and validate its descriptor, then use fixed relative names after `fchdir`; reject unexpected file types, permissions, ownership and hard links. A separate bind-only abstract Unix socket keyed by directory device/inode provides writer exclusion in one Linux network namespace. Only its holder may remove a stale RPC socket. All writers must use the same network namespace; same-UID processes and root remain trusted. This is not cross-namespace locking. headscale glue (Go, in a headscale fork) holds no protocol logic. It: - Registers the eight `/machine/tka/*` routes on the Noise router. Each passes the authenticated node identity and the raw request body to tkad and returns tkad's reply unchanged. - Supplies tkad with the node list (NodeID, node key, tailnet-lock public key) on request. `init/begin` needs it. - Puts `TKAInfo` (from tkad) and each node's stored `KeySignature` into map responses, and wakes map streams when tkad reports a head change. - Forwards `RegisterRequest.NodeKeySignature` to tkad. Its only decision is which nodes may call admin RPCs: `init/*` and `disable` are restricted to the tailnet owner. It makes that decision from headscale's own user model. Local trust boundary for stage four: the RPC socket lives inside the private state directory. Same-UID local adapters may supply authenticated node identity and administrator assertions; the daemon does not authenticate remote Tailscale clients itself. Before separate-UID Headscale integration, move the RPC socket into a distinct access-controlled directory without granting the adapter access to the state files. Production integration must fail closed on daemon errors. Current unit limits: model and crypto inputs are capped at 64 KiB. The in-memory authority holds 128 AUMs per slot and two slots; capacity exhaustion returns an error without evicting history. These limits are not a claim of full client interoperability: valid large checkpoints and long histories can exceed this implementation profile. Service message limits and durable storage must be resolved and exercised against stock clients before deployment. Some fields have tighter limits, which the request handler checks before calling a unit. A decoded `DisablementSecret` longer than 1024 bytes is rejected, because `om/argon2` `a2tka` traps on longer input. The client sends 32 bytes. The pinned client caps successful responses at 1 MiB or 10 MiB depending on the RPC. It reads non-200 error bodies with an unbounded `io.ReadAll` (`tailnet-lock.go`), so a compromised server can still exhaust client memory that way. That is a client issue outside this project; tkad's error bodies are short fixed strings. ## Components Component Language Status BLAKE2s-256 (`om/blake2s`) Omega done: RFC 7693 vectors, KAT 256/256, 2,266-case differential SHA-512 (`om/sha512`) Omega done: NIST CAVP short, long and Monte Carlo vectors, differential Ed25519 verify, strict and ZIP-215 (`om/ed25519`) Omega done: RFC 8032, ZIP-215 196/196, Wycheproof, Go 1.26 used as oracle BLAKE2b (`om/blake2b`) Omega done: RFC 7693 vectors, KAT 256/256, 2,266-case differential Argon2i, TKA disablement KDF (`om/argon2`) Omega done: RFC 9106 §5.2, 41 Go cases incl. TKA parameters, 200 random Go cases base64, base32, hex, `nodekey:` codecs (`om/codec`) Omega done: RFC 4648 §10, 249 malformed cases, 39,806-case Go differential CTAP2 CBOR encode and decode, bounded (`om/cbor`) Omega done: RFC 8949 App. A, 1,200 `tka` structures byte-identical with matching `AUM.Hash`, 475 hostile cases AUM / State / Key model, validation and authorized transitions (`om/tka`) Omega implemented: typed reconstruction and differential oracle NodeKeySignature model and verification (`om/tkasig`) Omega implemented: direct, credential and rotation, strict/ZIP-215 rules Bounded in-memory chain (`om/tka`): fork choice, state at hash, sync, atomic Inform Omega implemented: two slots, 128 AUMs each; daemon adds persistence JSON (`om/json`) and eight RPC handlers (`cmd/tkad`) Omega implemented: bounded parsing, trusted adapter identity binding Snapshot storage (`om/store`) Omega implemented: descriptor validation, writer exclusion, atomic publication, recovery tkad service (`cmd/tkad`) Omega implemented: private Unix socket, registry/map commands, controlled self-exec headscale glue Go (pinned patch) implemented and exercised with unmodified Tailscale v1.102.0 ## Verification plan Each component is checked against two referees: published vectors where they exist, and the Go `tailscale.com/tka` package at the pinned tag, used as a test oracle only. - Encoding: AUMs, States and signatures generated by `tka` must round-trip byte for byte through the Omega CBOR, and must produce identical hashes. - Chain: generated chains with forks, checkpoints, removed keys and bad signatures. tkad's head, sync offers and missing-AUM sets must equal `tka.Authority`'s. - Negative corpus: truncated CBOR, oversized fields, wrong parents and bad signatures reject without trapping. Non-shortest CBOR and reordered maps are accepted where the client accepts them; hashes use typed canonical reserialization. Unknown AUM kinds follow the upstream signed no-op compatibility contract, not an unconditional rejection rule. Typed duplicates, field-type errors and invalid decoded UTF-8 are rejected by the model layer. - End to end: stock clients in containers against the patched headscale. Run `tailscale lock init`, sign, add a node, remove a key, rotate a node key, and disable. Check that an unsigned node is refused by its peers. ### Stage-three verification The complete `tools/test.sh` run on ARM64 Linux passed all nine unit suites with the pinned compiler (`734f0a39319fbfa930bcc62cb30dbf06d47d78e126372b74f5baf478e6126b61`). Go 1.26.8 supplied the pinned TKA oracle; the existing optional oracle comparisons also ran. - Authority/model: 10,691 differential records matched upstream; a signature-bypass mutant completed all records and differed on four. - Node signatures: 1,135 differential cases matched upstream; nine completed-result mutants were detected, and a trapping mutant was rejected by the harness. - Cross-unit scenario: bootstrap a signed authority, authorize a node, apply a signed removal of its authority key, export the new trusted-key table, then reject the same node signature. The fixture generator asserts the same before/after result using upstream `Authority`. These are bounded in-memory host results, not stock-client end-to-end, durable-storage, constant-time, or production-network qualification. ### Stage-four verification The complete `tools/test.sh` run passed all twelve library/daemon suites on ARM64 Linux. The compiler pin was unchanged. New results: - JSON: 7,706 differential cases and 22 golden vectors; six completed-result mutants detected. - Store: 116 completed native cases, independent BLAKE2s framing referee and checksum mutant. Foreign-UID ownership fixtures were skipped because the runner was not root. - Daemon: 224 real-socket assertions across all eight RPCs and registry/map commands. Additional scenarios exercised two-iteration self-exec with queued clients and continuous writer exclusion, missing/swapped resume descriptors, pre-rename ENOSPC followed by successful mutation without restart, and post-rename fsync failure with no reply and recovery of the renamed candidate. Checksum-valid but semantically corrupt snapshots were rejected. - Separate launch smoke observed an initialized map response, a 403 for a missing admin assertion, and identical state after process termination/restart. These checks do not establish filesystem power-loss durability, cross-namespace writer exclusion, stock-client compatibility beyond the tested profile, or production deployment security. ### Stage-five verification Headscale v0.29.6 (`a2b1d7863926834e94479dcdd91ab344a9356bd0`) plus the committed adapter patch passed the isolated stock Tailscale v1.102.0 lifecycle: - Initialize and sign the initial roster; filter a newly registered unsigned peer. - Sign that peer and propagate signature-only updates. - Rotate its node key through real interactive Headscale authentication; reject signing the retired key. The pending rotation does not change the committed identity. - Remove its signing authority, observe peer rejection, and re-sign under the surviving authority. Both peer and self signatures must refresh without unrelated metadata changes. - Restart daemon, controller and clients; retain authority, signatures and removed-key state. - Reject a non-owner disable request even with a valid secret. - Stop the isolated daemon; reject signing, disablement and fresh registration without disabling protection. Restart it; rejected mutations remain unapplied. - Disable and restart every component; unsigned peers become visible and disablement persists. The run reported 13 PASS records including the artifact-provenance check. It uses a fresh network/PID namespace, loopback and a dummy link with no egress. On the verification host, unprivileged user namespaces were denied; the explicit `--sudo-netns` launcher creates the namespace and drops UID/GID privileges before running any daemon. No live services, interfaces, tailnet state or SSH configuration are used. All twelve Omega suites passed; the later interactive-sync correction passed the daemon suite with 279 socket assertions plus failure/recovery checks. The correction checks interactive Head against pre-update state, matching stock `TailnetLockModify`. Headscale control/state/mapper/types suites and SQLite migration tests passed after review fixes. The final self-signature propagation fix additionally passed upstream self-deduplication regressions and the full stock-client lifecycle. Rebuilding the final patch from a fresh clone produced the identical controller SHA-256: `7e6eeb414dc6fd439425b56c4672e2898f71b667b6528f36a75154d3ce27b138`. The adapter keeps rejected registration signatures from poisoning unrelated nodes, retains upstream interactive authentication, rejects duplicate/zero identities before persistence, and freezes coherent map frames before releasing its publication lock for network writes. Omega remains the only accepted-signature and authority implementation. The local adapter still shares the daemon UID. Its durable revision floor is not authenticated rollback protection. These checks prove control-plane behavior, not packet delivery, power-loss durability, constant-time cryptography, or production security. ### Stage-six readiness review Two independent read-only source reviews covered recovery/deployment hazards and the admission boundary. Both found defects rather than only limitations, and each was fixed and regression tested: - Registry readability. A verified node-key signature was stored as submitted, and typed decoding ignores unknown CBOR fields, so an ordinary registered client could keep padding accepted signatures until the registry no longer fit the 64-KiB map response. Reconciliation then failed for every request and the daemon could not be repaired through normal RPCs. Accepted signatures are now stored in canonical typed form, and any candidate whose registry snapshot would not fit the map response is rejected with 413 before it is persisted. The new suite covers a 30,000-byte padded signature being accepted and stored canonically, surviving restart, and a test-only raw-storage variant proving that an over-limit second signature is refused while the registry stays readable. - Unauthenticated admission. TKA RPCs and map polls took the global publication mutex and performed SQL plus daemon reconciliation before the caller's identity was checked, so an arbitrary Noise client could queue on the barrier. A TKA RPC now resolves the caller against committed SQL first and returns 401 without touching the daemon, and registration and map admission take a bounded slot and answer 503 instead of queueing. - Silent downgrade. Unsetting both adapter variables after activation used to start stock behaviour and publish maps with nil `TKAInfo`. Startup now refuses when the database already records adapter state. The remaining findings were deployment limitations, not defects: one committed node without an NLKey blocks publication for the whole tailnet (since 2026-11-14 only once an authority exists; while it is inactive such nodes are served unsigned and `init` answers 409), SQLite cannot be downgraded in place (since 2026-11-14 `integration/headscale/downgrade.sql` does it after disablement), the revision floor is not authenticated rollback protection, and disablement is permanent for that database. They are recorded as gates in `integration/headscale/README.md` . Re-verification after these changes, on the pinned compiler `734f0a39319fbfa930bcc62cb30dbf06d47d78e126372b74f5baf478e6126b61`: - All twelve Omega suites passed (`tools/test.sh`, exit 0). The daemon suite reported 310 socket assertions and the new failure/recovery checks, including the registry capacity guard, and the JSON differential remained 7,706/7,706. That differential now pins its oracle toolchain in `om/json/test/run.py`: Go 1.27 changes `encoding/json` UTF-8 escaping, so an unpinned oracle fails on byte comparison. - Focused adapter regressions, the complete control/state/mapper/types suites and SQLite migration tests passed, including three new tests: unregistered identity refuses before authority work, saturated admission fails fast, and adapter state without settings refuses startup. The deleted-identity test now drives orphan removal through the watcher instead of relying on an unauthorized request. - The isolated stock-client lifecycle passed all 13 records again with the rebuilt binaries. - The committed patch applied to a fresh clone of the pinned tag and rebuilt to a byte-identical controller: SHA-256 `71ffcb5e6aed6bd6b2ec441b718220e2ad1d70d3fa767c728d104447f8668807` (supersedes the stage-five hash, which predates these fixes). These are host and isolated-namespace results. They do not establish packet delivery, power-loss durability, constant-time cryptography, or production security, and no deployment is approved. ## Plan and status - Crypto primitives: BLAKE2s, SHA-512, Ed25519. Done. - BLAKE2b, Argon2i, codecs, CBOR. Done. - TKA model and bounded in-memory chain logic, differential against `tka`. Implemented. Cross-unit smoke checks node authorization before and after a signed authority-key removal. - tkad service, storage, JSON. Implemented for the bounded same-UID local-adapter profile. See `cmd/tkad/README.md` for invocation, framing, limits and tests. - Headscale glue and end-to-end tests with stock clients. Implemented and verified in isolation. See `integration/headscale/README.md` for reproduction. - Independent readiness review and deployment planning. **Done for source review and rehearsal planning.** Two reviews found three defects, fixed and regression tested in Stage six. Deployment gates and the paired-restore procedure are in `integration/headscale/README.md` . This is not a production audit, and no live deployment is approved.