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 Rendered 1 # Tailnet Lock for self-hosted control servers 2 3 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](#plan-and-status). 4 5 ## Problem 6 7 A Tailscale control server decides which devices join a tailnet. If that server is compromised, or a 8 join key is stolen, an attacker can add a device that every other device then trusts. Tailnet Lock 9 (the Tailnet Key Authority, TKA) moves that decision to the devices: a new device is trusted only if 10 its node key carries a signature from a key the devices themselves hold. 11 12 The device side ships in the stock Tailscale client. The self-hosted control server headscale does 13 not implement the server side ([headscale#1307](https://github.com/juanfont/headscale/issues/1307), 14 open since 2023). Without server-side support, a self-hosted tailnet cannot use this client-enforced 15 signature check to constrain device admission by a compromised control server. 16 17 ## Goal and non-goals 18 19 Goal: a server-side TKA implementation that a stock Tailscale client (v1.102.x) accepts, with all 20 protocol, encoding and cryptographic logic in Omega. 21 22 Non-goals for the first release: 23 - Admin UI and key-management commands beyond what the client's `tailscale lock` commands call. 24 - Compatibility with clients older than v1.102. 25 - Upstreaming into headscale. That needs maintainer agreement first: the maintainers have said they 26 are wary of reviewing a cryptographic contribution of this size. 27 28 ## What the server must do 29 30 Source: `tailscale/tailscale` tag `v1.102.0`, files `tailcfg/tka.go`, `ipn/ipnlocal/tailnet-lock.go`, 31 `tka/*.go`. 32 33 ### Remote procedures 34 35 The client calls these over the existing Noise channel as HTTP `GET` requests with a JSON body. 36 `[]byte` fields are base64 in JSON. AUM hashes are `tka.AUMHash.MarshalText`: base32, standard 37 alphabet, no padding. Node keys are `nodekey:`. 38 39 | Path | Request → response | Server action | 40 |---|---|---| 41 | `/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. | 42 | `/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. | 43 | `/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. | 44 | `/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. | 45 | `/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. | 46 | `/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. | 47 | `/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. | 48 | `/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. | 49 50 The server also writes into the map stream: 51 - `MapResponse.TKAInfo{Head, Disabled}`. A nil TKAInfo in the first response means TKA is off; in a 52 delta response, nil means no change. Clients sync whenever Head differs from their own. 53 - `Node.KeySignature`, for the node itself and for every peer, on every map path, including peer 54 change deltas. 55 56 `RegisterRequest.NodeKeySignature` arrives at registration and when a node rotates its key. It must be 57 stored and served as that node's `KeySignature`. `RegisterRequest.NLKey` is the node's tailnet-lock 58 public key. It must be stored too, because `init/begin` returns it as `TKASignInfo.RotationPubkey`. The 59 client copies that value into the signature's `WrappingPubkey` (`tailnet-lock.go` `signNodeKey`), and 60 a later key rotation fails verification without it (`tka/sig.go:260-274`). 61 62 ### Data formats that must match byte for byte 63 64 - **AUM**: a CBOR map with integer keys: `1` MessageKind, `2` PrevAUMHash, `3` Key, `4` KeyID, 65 `5` State, `6` Votes, `7` Meta, `23` Signatures. Unset optional fields are omitted. It is encoded in 66 CTAP2 canonical mode (`fxamacker/cbor` `CTAP2EncOptions`). 67 `Hash = BLAKE2s-256(Serialize(aum))`. `SigHash = BLAKE2s-256(Serialize(aum without Signatures))`. 68 Kinds: 1 AddKey, 2 RemoveKey, 3 NoOp, 4 UpdateKey, 5 Checkpoint. 69 - **State**: integer keys `1` LastAUMHash, `2` DisablementValues, `3` Keys, `4` StateID1, 70 `5` StateID2. At most 512 keys. 71 - **NodeKeySignature**: integer keys `1` SigKind, `2` Pubkey, `3` KeyID, `4` Signature, `5` Nested, 72 `6` WrappingPubkey. Kinds are direct, rotation and credential (the wrapped pre-auth key). 73 `SigHash = BLAKE2s-256(Serialize(sig without Signature))`. 74 - **Signature rules** (tag `v1.102.0`): AUM signatures (`tka/verify.go:28`) and direct and credential 75 node-key signatures (`tka/sig.go:300`) use `ed25519consensus` (ZIP-215, mode 1 in `om/`ed25519``). 76 The outer signature of a rotation node-key signature (`tka/sig.go:273`) uses Go's `crypto/`ed25519`` 77 (strict, mode 0). A server that uses a different rule from the clients splits the tailnet. 78 - **Disablement values**: `argon2.Key(secret, "tailscale network-lock disablement salt", t=4, 79 m=16 MiB, p=4, len=32)`. That is **Argon2i**, which hashes with BLAKE2b. 80 - **Fork choice**: when two AUMs share a parent, `tka/tka.go` `pickNextAUM` decides deterministically: 81 (1) the highest signature weight wins; (2) on equal weight, a RemoveKey AUM wins; (3) otherwise the 82 lowest AUM hash wins. The server must pick the same chain the clients pick. 83 84 ## Architecture 85 86 ```mermaid 87 flowchart LR 88 C[Stock Tailscale client] -- Noise HTTP/2 --> H[headscale] 89 H -- "glue: route + identity + raw JSON" --> T[tkad: Omega program] 90 T --> S[(AUM log + state files)] 91 H -- "TKAInfo.Head, KeySignature" --> C 92 ``` 93 94 **tkad** is one Omega program and holds all TKA logic: 95 - JSON decode and encode of the eight request and response types. 96 - base64, base32 and hex codecs. 97 - CTAP2 CBOR for AUMs, State and NodeKeySignatures. 98 - AUM validation, state transitions, fork choice, sync offers and intersections. 99 - Signature verification. 100 - Disablement checks (Argon2i). 101 - Storage. 102 103 It listens on a local socket, using the Omega native host operations from omega-mv `seed/host/`. 104 105 **Storage design for stage four**: a single versioned whole-service snapshot, including authority 106 updates in reconstruction-preserving typed form, node records/signatures, pending initialization, 107 and disablement state. A candidate is built in the inactive authority slot. Write a temporary file, 108 fsync it, rename it over the committed snapshot, then fsync the directory before publishing the 109 candidate or acknowledging success. Failure after rename but before directory fsync is an uncertain 110 commit: stop serving, do not attempt a rollback rename. Recovery validates the entire committed 111 snapshot; a missing or corrupt snapshot is not interpreted as disabled TKA. 112 113 The state directory is provisioned under trusted ancestors, owned by the effective UID, and mode 114 0700. Open and validate its descriptor, then use fixed relative names after `fchdir`; reject 115 unexpected file types, permissions, ownership and hard links. A separate bind-only abstract Unix 116 socket keyed by directory device/inode provides writer exclusion in one Linux network namespace. 117 Only its holder may remove a stale RPC socket. All writers must use the same network namespace; 118 same-UID processes and root remain trusted. This is not cross-namespace locking. 119 120 **headscale glue** (Go, in a headscale fork) holds no protocol logic. It: 121 1. Registers the eight `/machine/tka/*` routes on the Noise router. Each passes the authenticated 122 node identity and the raw request body to tkad and returns tkad's reply unchanged. 123 2. Supplies tkad with the node list (NodeID, node key, tailnet-lock public key) on request. 124 `init/begin` needs it. 125 3. Puts `TKAInfo` (from tkad) and each node's stored `KeySignature` into map responses, and wakes 126 map streams when tkad reports a head change. 127 4. Forwards `RegisterRequest.NodeKeySignature` to tkad. 128 129 Its only decision is which nodes may call admin RPCs: `init/*` and `disable` are restricted to the 130 tailnet owner. It makes that decision from headscale's own user model. 131 132 **Local trust boundary for stage four**: the RPC socket lives inside the private state directory. 133 Same-UID local adapters may supply authenticated node identity and administrator assertions; 134 the daemon does not authenticate remote Tailscale clients itself. Before separate-UID Headscale 135 integration, move the RPC socket into a distinct access-controlled directory without granting the 136 adapter access to the state files. Production integration must fail closed on daemon errors. 137 138 **Current unit limits**: model and crypto inputs are capped at 64 KiB. The in-memory authority holds 139 128 AUMs per slot and two slots; capacity exhaustion returns an error without evicting history. 140 These limits are not a claim of full client interoperability: valid large checkpoints and long 141 histories can exceed this implementation profile. Service message limits and durable storage must 142 be resolved and exercised against stock clients before deployment. Some fields have tighter 143 limits, which the request handler checks before calling a unit. A decoded `DisablementSecret` longer 144 than 1024 bytes is rejected, because `om/argon2` `a2tka` traps on longer input. The client sends 145 32 bytes. The pinned client caps 146 successful responses at 1 MiB or 10 MiB depending on the RPC. It reads non-200 error bodies with an 147 unbounded `io.ReadAll` (`tailnet-lock.go`), so a compromised server can still exhaust client memory 148 that way. That is a client issue outside this project; tkad's error bodies are short fixed strings. 149 150 ## Components 151 152 | Component | Language | Status | 153 |---|---|---| 154 | BLAKE2s-256 (`om/blake2s`) | Omega | done: RFC 7693 vectors, KAT 256/256, 2,266-case differential | 155 | SHA-512 (`om/sha512`) | Omega | done: NIST CAVP short, long and Monte Carlo vectors, differential | 156 | Ed25519 verify, strict and ZIP-215 (`om/`ed25519``) | Omega | done: RFC 8032, ZIP-215 196/196, Wycheproof, Go 1.26 used as oracle | 157 | BLAKE2b (`om/blake2b`) | Omega | done: RFC 7693 vectors, KAT 256/256, 2,266-case differential | 158 | Argon2i, TKA disablement KDF (`om/argon2`) | Omega | done: RFC 9106 §5.2, 41 Go cases incl. TKA parameters, 200 random Go cases | 159 | base64, base32, hex, `nodekey:` codecs (`om/codec`) | Omega | done: RFC 4648 §10, 249 malformed cases, 39,806-case Go differential | 160 | 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 | 161 | AUM / State / Key model, validation and authorized transitions (`om/tka`) | Omega | implemented: typed reconstruction and differential oracle | 162 | NodeKeySignature model and verification (`om/tkasig`) | Omega | implemented: direct, credential and rotation, strict/ZIP-215 rules | 163 | Bounded in-memory chain (`om/tka`): fork choice, state at hash, sync, atomic Inform | Omega | implemented: two slots, 128 AUMs each; daemon adds persistence | 164 | JSON (`om/json`) and eight RPC handlers (`cmd/tkad`) | Omega | implemented: bounded parsing, trusted adapter identity binding | 165 | Snapshot storage (`om/store`) | Omega | implemented: descriptor validation, writer exclusion, atomic publication, recovery | 166 | tkad service (`cmd/tkad`) | Omega | implemented: private Unix socket, registry/map commands, controlled self-exec | 167 | headscale glue | Go (pinned patch) | implemented and exercised with unmodified Tailscale v1.102.0 | 168 169 ## Verification plan 170 171 Each component is checked against two referees: published vectors where they exist, and the Go 172 `tailscale.com/tka` package at the pinned tag, used as a test oracle only. 173 - **Encoding**: AUMs, States and signatures generated by `tka` must round-trip byte for byte through 174 the Omega CBOR, and must produce identical hashes. 175 - **Chain**: generated chains with forks, checkpoints, removed keys and bad signatures. tkad's head, 176 sync offers and missing-AUM sets must equal `tka.Authority`'s. 177 - **Negative corpus**: truncated CBOR, oversized fields, wrong parents and bad signatures reject 178 without trapping. Non-shortest CBOR and reordered maps are accepted where the client accepts 179 them; hashes use typed canonical reserialization. Unknown AUM kinds follow the upstream signed 180 no-op compatibility contract, not an unconditional rejection rule. Typed duplicates, field-type 181 errors and invalid decoded UTF-8 are rejected by the model layer. 182 - **End to end**: stock clients in containers against the patched headscale. Run `tailscale lock 183 init`, sign, add a node, remove a key, rotate a node key, and disable. Check that an unsigned node is 184 refused by its peers. 185 186 ### Stage-three verification 187 188 The complete `tools/test.sh` run on ARM64 Linux passed all nine unit suites with the pinned 189 compiler (``734f0a39319fbfa930bcc62cb30dbf06d47d78e126372b74f5baf478e6126b61``). 190 Go 1.26.8 supplied the pinned TKA oracle; the existing optional oracle comparisons also ran. 191 192 - Authority/model: 10,691 differential records matched upstream; a signature-bypass mutant 193 completed all records and differed on four. 194 - Node signatures: 1,135 differential cases matched upstream; nine completed-result mutants 195 were detected, and a trapping mutant was rejected by the harness. 196 - Cross-unit scenario: bootstrap a signed authority, authorize a node, apply a signed removal 197 of its authority key, export the new trusted-key table, then reject the same node signature. 198 The fixture generator asserts the same before/after result using upstream `Authority`. 199 200 These are bounded in-memory host results, not stock-client end-to-end, durable-storage, 201 constant-time, or production-network qualification. 202 203 ### Stage-four verification 204 205 The complete `tools/test.sh` run passed all twelve library/daemon suites on ARM64 Linux. 206 The compiler pin was unchanged. New results: 207 208 - JSON: 7,706 differential cases and 22 golden vectors; six completed-result mutants detected. 209 - Store: 116 completed native cases, independent BLAKE2s framing referee and checksum mutant. 210 Foreign-UID ownership fixtures were skipped because the runner was not root. 211 - Daemon: 224 real-socket assertions across all eight RPCs and registry/map commands. 212 Additional scenarios exercised two-iteration self-exec with queued clients and continuous 213 writer exclusion, missing/swapped resume descriptors, pre-rename ENOSPC followed by successful 214 mutation without restart, and post-rename fsync failure with no reply and recovery of the 215 renamed candidate. Checksum-valid but semantically corrupt snapshots were rejected. 216 - Separate launch smoke observed an initialized map response, a 403 for a missing admin assertion, 217 and identical state after process termination/restart. 218 219 These checks do not establish filesystem power-loss durability, cross-namespace writer exclusion, 220 stock-client compatibility beyond the tested profile, or production deployment security. 221 222 ### Stage-five verification 223 224 Headscale v0.29.6 (``a2b1d7863926834e94479dcdd91ab344a9356bd0``) plus the committed 225 adapter patch passed the isolated stock Tailscale v1.102.0 lifecycle: 226 227 - Initialize and sign the initial roster; filter a newly registered unsigned peer. 228 - Sign that peer and propagate signature-only updates. 229 - Rotate its node key through real interactive Headscale authentication; reject signing 230 the retired key. The pending rotation does not change the committed identity. 231 - Remove its signing authority, observe peer rejection, and re-sign under the surviving 232 authority. Both peer and self signatures must refresh without unrelated metadata changes. 233 - Restart daemon, controller and clients; retain authority, signatures and removed-key state. 234 - Reject a non-owner disable request even with a valid secret. 235 - Stop the isolated daemon; reject signing, disablement and fresh registration without 236 disabling protection. Restart it; rejected mutations remain unapplied. 237 - Disable and restart every component; unsigned peers become visible and disablement persists. 238 239 The run reported 13 PASS records including the artifact-provenance check. It uses a fresh 240 network/PID namespace, loopback and a dummy link with no egress. On the verification host, 241 unprivileged user namespaces were denied; the explicit `--sudo-netns` launcher creates 242 the namespace and drops UID/GID privileges before running any daemon. No live services, 243 interfaces, tailnet state or SSH configuration are used. 244 245 All twelve Omega suites passed; the later interactive-sync correction passed the daemon suite 246 with 279 socket assertions plus failure/recovery checks. The correction checks interactive 247 Head against pre-update state, matching stock `TailnetLockModify`. 248 Headscale control/state/mapper/types suites and SQLite migration tests passed after review 249 fixes. The final self-signature propagation fix additionally passed upstream self-deduplication 250 regressions and the full stock-client lifecycle. Rebuilding the final patch from a fresh clone 251 produced the identical controller SHA-256: 252 ``7e6eeb414dc6fd439425b56c4672e2898f71b667b6528f36a75154d3ce27b138``. 253 254 The adapter keeps rejected registration signatures from poisoning unrelated nodes, retains 255 upstream interactive authentication, rejects duplicate/zero identities before persistence, 256 and freezes coherent map frames before releasing its publication lock for network writes. 257 Omega remains the only accepted-signature and authority implementation. The local adapter 258 still shares the daemon UID. Its durable revision floor is not authenticated rollback protection. 259 These checks prove control-plane behavior, not packet delivery, power-loss durability, 260 constant-time cryptography, or production security. 261 262 ### Stage-six readiness review 263 264 Two independent read-only source reviews covered recovery/deployment hazards and the admission 265 boundary. Both found defects rather than only limitations, and each was fixed and regression 266 tested: 267 268 - **Registry readability.** A verified node-key signature was stored as submitted, and typed 269 decoding ignores unknown CBOR fields, so an ordinary registered client could keep padding 270 accepted signatures until the registry no longer fit the 64-KiB map response. Reconciliation 271 then failed for every request and the daemon could not be repaired through normal RPCs. 272 Accepted signatures are now stored in canonical typed form, and any candidate whose registry 273 snapshot would not fit the map response is rejected with 413 before it is persisted. The new 274 suite covers a 30,000-byte padded signature being accepted and stored canonically, surviving 275 restart, and a test-only raw-storage variant proving that an over-limit second signature is 276 refused while the registry stays readable. 277 - **Unauthenticated admission.** TKA RPCs and map polls took the global publication mutex and 278 performed SQL plus daemon reconciliation before the caller's identity was checked, so an 279 arbitrary Noise client could queue on the barrier. A TKA RPC now resolves the caller against 280 committed SQL first and returns 401 without touching the daemon, and registration and map 281 admission take a bounded slot and answer 503 instead of queueing. 282 - **Silent downgrade.** Unsetting both adapter variables after activation used to start stock 283 behaviour and publish maps with nil `TKAInfo`. Startup now refuses when the database already 284 records adapter state. 285 286 The remaining findings were deployment limitations, not defects: one committed node without an 287 NLKey blocks publication for the whole tailnet (since 2026-11-14 only once an authority exists; while 288 it is inactive such nodes are served unsigned and `init` answers 409), SQLite cannot be downgraded in 289 place (since 2026-11-14 `integration/headscale/downgrade.sql` does it after disablement), the 290 revision floor is not authenticated rollback protection, and disablement is permanent for that 291 database. They are recorded as gates in 292 [`integration/headscale/README.md`](../../integration/headscale/README.md). 293 294 Re-verification after these changes, on the pinned compiler 295 ``734f0a39319fbfa930bcc62cb30dbf06d47d78e126372b74f5baf478e6126b61``: 296 297 - All twelve Omega suites passed (`tools/test.sh`, exit 0). The daemon suite reported 310 298 socket assertions and the new failure/recovery checks, including the registry capacity guard, 299 and the JSON differential remained 7,706/7,706. That differential now pins its oracle 300 toolchain in `om/json/test/run.py`: Go 1.27 changes `encoding/json` UTF-8 escaping, so an 301 unpinned oracle fails on byte comparison. 302 - Focused adapter regressions, the complete control/state/mapper/types suites and SQLite 303 migration tests passed, including three new tests: unregistered identity refuses before 304 authority work, saturated admission fails fast, and adapter state without settings refuses 305 startup. The deleted-identity test now drives orphan removal through the watcher instead of 306 relying on an unauthorized request. 307 - The isolated stock-client lifecycle passed all 13 records again with the rebuilt binaries. 308 - The committed patch applied to a fresh clone of the pinned tag and rebuilt to a byte-identical 309 controller: SHA-256 ``71ffcb5e6aed6bd6b2ec441b718220e2ad1d70d3fa767c728d104447f8668807`` 310 (supersedes the stage-five hash, which predates these fixes). 311 312 These are host and isolated-namespace results. They do not establish packet delivery, power-loss 313 durability, constant-time cryptography, or production security, and no deployment is approved. 314 315 ## Plan and status 316 1. Crypto primitives: BLAKE2s, SHA-512, Ed25519. **Done.** 317 2. BLAKE2b, Argon2i, codecs, CBOR. **Done.** 318 3. TKA model and bounded in-memory chain logic, differential against `tka`. **Implemented.** 319 Cross-unit smoke checks node authorization before and after a signed authority-key removal. 320 4. tkad service, storage, JSON. **Implemented for the bounded same-UID local-adapter profile.** 321 See [`cmd/tkad/README.md`](../../cmd/tkad/README.md) for invocation, framing, limits and tests. 322 5. Headscale glue and end-to-end tests with stock clients. **Implemented and verified in isolation.** 323 See [`integration/headscale/README.md`](../../integration/headscale/README.md) for reproduction. 324 6. Independent readiness review and deployment planning. **Done for source review and 325 rehearsal planning.** Two reviews found three defects, fixed and regression tested in 326 [Stage six](#stage-six-readiness-review). Deployment gates and the paired-restore 327 procedure are in [`integration/headscale/README.md`](../../integration/headscale/README.md). 328 This is not a production audit, and no live deployment is approved.