interplane.Get Omega
Read in your language

omnet

aien-dev/omnet

Brought by drakestapleton

branch main Branches Tags History

omnet / integration / headscale / README.md

321 lines · 20061 bytes Raw Blame History Rendered
1# Headscale adapter
2
3`headscale.patch` applies to Headscale **v0.29.6**, commit
4`a2b1d7863926834e94479dcdd91ab344a9356bd0` (see `headscale.pin`). No fork is
5vendored. The patch adds Go transport/authentication glue to the existing
6Headscale server. TKA parsing, signatures, authority transitions and durable
7accepted signatures remain in the Omega daemon.
8
9## Build
10
11From the Omnet checkout, with Git, a Go launcher supporting automatic toolchain
12selection, and network access to GitHub and the Go module proxy:
13
14```sh
15GO=/path/to/go sh integration/headscale/build.sh
16# output: build/headscale (override with HEADSCALE_OUTPUT)
17sh tools/build-tkad.sh
18```
19
20The builder clones the pinned tag into a disposable directory, verifies its
21commit, applies the patch, and builds using `go1.27.3` and the patched module
22checksums. It removes only its own temporary checkout. Dependencies are not
23vendored. Headscale requires Go 1.27.3. Its original x/tools v0.49.0 cannot read
24that compiler's V5 export data, so the patch pins x/tools (now v0.51.0) and includes
25regenerated Node views/clones. Re-generation requires Go on `PATH`:
26`go generate ./hscontrol/types` in the patched source.
27
28The patch also moves `tailscale.com` from v1.102.0 to **v1.104.5**. Headscale's
29embedded DERP server links `tailscale.com/derp/derpserver`; before v1.104 its
30`noteClientActivity` only appended to `sendHistory`, so two connections sharing
31one node key could grow it without bound (omnet#8). v1.104 removes the earlier
32entry before appending, which bounds the slice by the duplicate-set size. The
33bump changes DERP region IDs from `int` to `tailcfg.DERPRegionID`; the patch
34carries the matching Headscale type changes, ported from upstream Headscale
35commit `3aece650`. It adds no database migration.
36
37## Isolated operation
38
39Provision tkad exactly as described in `cmd/tkad/README.md`, then start both
40processes as the **same UID**, in the same network namespace. Use private state,
41private sockets and an isolated Headscale configuration, not an existing tailnet.
42The two required adapter settings are environment variables, not YAML keys:
43
44```sh
45OMNET_TKAD_SOCKET=/absolute/private/tkad/tkad.sock \
46OMNET_TKAD_ADMIN_USER_ID=1 \
47 build/headscale --config /absolute/private/headscale.yaml serve
48```
49
50`OMNET_TKAD_ADMIN_USER_ID` must be the explicitly selected numeric Headscale user
51ID. The example value `1` is not a default. It may be configured before that user
52is created; the isolated E2E harness creates the user and checks the returned ID.
53Only currently unexpired, untagged nodes owned by that user receive the admin
54assertion. Noise machine identity and the current unique node key must both match. A body
55cannot assert a user, NodeID or administrator status. Setting only one variable
56is an error. Setting neither leaves ordinary upstream Headscale behavior **only on
57a database that has never used this adapter**; once adapter state exists (a
58checkpoint row or any node with a tailnet-lock key), the server refuses to start
59instead of publishing maps without TKA state.
60
61Headscale still needs a nonempty DERP map, even in isolation. The E2E harness
62supplies a private region and private client sockets; it never uses the live
63Tailscale socket. See `integration/e2e/` for the runnable stock-client scenario.
64
65## Persistence and failure behavior
66
67The patch adds `nodes.tka_key`, `nodes.tka_signature` and a one-row
68`omnet_checkpoints` table through an append-only migration. NLKey and the pending
69submitted NKS are committed with Headscale's desired registration tuple, including
70interactive auth callbacks. The pending signature is an outbox, **not** a trusted
71map signature. Only a tkad snapshot supplies map signatures.
72
73A shared publication barrier serializes identity changes, reconciliation,
74Noise/admin resolution and map-frame construction. Reconciliation reads committed
75SQL, rejects ambiguous or speculative identities, removes daemon orphans and
76vacates obsolete keys before claiming desired keys, including key-reuse cycles
77after an outage. Accepted-signature readback resolves an ambiguous IPC outcome
78without replaying a historical signature after key removal. An unchanged registry
79causes no upsert, including after adapter restart, so it does not cancel pending
80initialization.
81
82A definitively rejected pending signature is retried without a signature. Only
83after that unsigned tuple succeeds is the rejected outbox cleared. A new key is
84then unsigned; an unchanged key retains its existing Omega-accepted signature.
85The submitting registration gets an explicit signature error, but unrelated
86nodes keep working. IPC authentication failures, failed unsigned retries, 5xx
87and lost replies remain fail-closed and retain the outbox for recovery.
88
89All eight raw GET RPC bodies and replies are forwarded without re-encoding.
90Initial, self, peer, changed-peer, non-streaming and queued map responses use one
91fresh daemon snapshot. Key-only patches become full maps so an unsigned new key
92cannot retain an old signature through JSON omission. Stale sessions cannot
93restore an old node key through MapRequest. Revision changes wake streams even
94when the authority head is unchanged (for example, signing a node).
95Non-key patches never carry signatures. Each stream writes its frozen frames in
96order after releasing the global barrier, with bounded writes and a stop deadline
97that cannot be lengthened by a queued frame. Client cancellation does not mark
98the daemon unhealthy. Interactive reauthentication retains the signature challenge
99and then requires upstream authentication; the old Noise identity never silently
100rotates the key or replaces an AuthURL.
101
102Daemon connection/read/shape failures block publication and close existing map
103streams; no stale-cache, empty-signature, disabled-state or nil-TKAInfo fallback
104is used. An absent daemon refuses server startup. A reachable daemon plus a
105pending registration permits authenticated retries and administrative repair while
106unresolved transport/registry failures block map/TKA publication. Older Headscale
107nodes without NLKey must re-register before `init`; there is no invented rotation key. A committed
108identity whose outbox cannot be reconciled is not reported as successful registration.
109Post-commit policy refresh runs even when reconciliation will reject registration.
110
111The durable observed-revision floor rejects an empty/older daemon snapshot after
112adapter restart. It is **not authenticated rollback protection**, and cannot
113identify an arbitrary different authority with a higher revision. Back up and
114restore the Headscale database and tkad directory together. Same-UID processes
115and root are trusted and can alter either store. Outages do not revoke already
116installed peer connectivity. This is not a separate-UID deployment profile or a
117production security audit.
118
119Limits remain one tailnet, 64 nodes, 128 AUMs and 64-KiB IPC JSON messages. Every
120committed mutation must still be servable through the 64-KiB registry response:
121an accepted node signature is stored in canonical form, so ignored CBOR fields
122cannot pad it, and a candidate that would exceed the response limit is rejected
123with 413 before it is persisted. A saturated registration or map admission
124answers 503 instead of queueing on the publication barrier, and a TKA RPC from
125an unregistered Noise identity is refused before any daemon work. IPC and
126raw RPC read/write phases have absolute deadlines; a bounded serial daemon and
127publication barrier trade throughput for simple ordering. New registrations beyond
12864, zero node keys, duplicate keys even across users on one machine, and signatures
129above 48,768 raw bytes are rejected before persistence.
130
131## Validation
132
133Focused adapter regressions, upstream control/state/mapper/types suites, SQLite
134migration tests and the isolated stock-client lifecycle passed. Reproduce focused tests
135in a checkout at the pinned commit with `headscale.patch` applied:
136
137```sh
138GOTOOLCHAIN=go1.27.3 go test -count=1 -run '^TestOmnet' ./hscontrol ./hscontrol/state
139GOTOOLCHAIN=go1.27.3 go test -count=1 -run '^TestSQLite' ./hscontrol/db
140```
141
142Build and run the stock clients separately from the library suite:
143
144```sh
145GO=/path/to/go sh integration/e2e/build-clients.sh
146GO=/path/to/go sh integration/headscale/build.sh
147sh tools/build-tkad.sh
148sh integration/e2e/run.sh --result /tmp/omnet-e2e-result.json
149# If user namespaces are prohibited, explicitly request privileged namespace setup:
150sh integration/e2e/run.sh --sudo-netns --result /tmp/omnet-e2e-result.json
151```
152
153The launcher requires Linux `unshare`, `ip` and Python3. It creates a fresh network
154namespace with loopback and a dummy link, no egress or host interfaces. Privileged
155setup drops UID/GID privileges before starting the daemons. Clients use private state
156and explicit sockets. Default cleanup removes the invocation's disposable state;
157`--keep` retains it, including private test keys, for debugging. Do not publish those logs.
158The receipt includes only scenario verdicts and public artifact hashes.
159
160The successful lifecycle reports 13 PASS records including provenance. It covers
161initialization, unsigned-peer filtering, signing, authenticated rotation, authority
162removal and re-signing, restart recovery, non-owner denial, daemon outage/recovery,
163disablement and disabled restart. This is netmap admission evidence, not packet delivery.
164
165The tests exercise durable outbox/revision persistence, committed identity
166refusal, same-machine cross-user duplicate-key prevention, expired-owner denial,
167historical-signature readback, definitive rejection isolation, ambiguous replies,
168unchanged restart reconciliation, interactive authentication, old-map rollback
169refusal, full-node signature clearing, signature-free non-key patches, cancelled
170requests, stopped/slow writers, key-reuse recovery cycles, policy refresh after
171reconciliation failure, and map outage closure. Transport fixtures do not replace
172the real Omega suite or stock-client E2E. The parent integration run supplies those
173receipts. For broader upstream regression coverage run the normal Headscale unit
174suites separately; Docker-based Headscale integration tests are not required by
175this adapter's isolated stock-client harness.
176
177## Deployment gate and recovery plan
178
179The [Tailworm disclosure](https://tailworm.com/) also describes SSH forwarding,
180app connectors, unauthenticated control-server exhaustion, hostile DERP responses
181and Serve exposure. This adapter does not patch those components. Signature-based
182node admission does not stop an already authorized compromised device from using
183its existing permissions, or protect signing keys on a compromised endpoint.
184Qualify upstream fixes and feature-specific hardening separately; passing this
185suite must never be reported as “Tailworm fixed” or “the network is secure.”
186
187**Not approved for live deployment.** The isolated lifecycle is a control-plane
188receipt, not a production security audit or proof of packet delivery. Keep this
189adapter off the live controller until the following gates have evidence:
190
191- **Every committed node must carry an NLKey before the lock starts, and the roster
192 must fit the profile (at most 64 nodes, unique node keys, no ambiguous
193 identity).** Nodes created before this migration have a null NLKey. While the
194 authority is inactive they are left out of the registry and served unsigned,
195 as upstream would serve them, so starting the adapter over an existing database
196 does not black out control; the owner's `init/begin` and `init/finish` answer 409 until
197 each of them re-registers (`tailscale up --force-reauth`) or is deleted. Once an
198 authority exists, a node without an NLKey still fails reconciliation as a whole
199 (map streams close, new map polls answer 503) until it re-registers. Verify with
200 `SELECT` on `nodes` that no row has a null `tka_key` and that the count is within
201 64 before `init`. [`docs/runbook.md`](../../docs/runbook.md) gives the order, and
202 `integration/e2e/run.sh --scenario runbook` rehearses it.
203- Inventory the actual clients, registered nodes (including offline nodes), NLKeys,
204 authority history and expected message sizes against this bounded profile.
205 The tested client is v1.102.0; other versions need their own qualification.
206 Every accepted node signature occupies part of one 64-KiB registry response.
207 A mutation that would not fit is now rejected with 413 instead of being
208 committed unreadable, so qualification must show the real roster plus signature
209 history stays below that response limit for the operational horizon. The 128-AUM
210 authority limit has no compaction path; plan for it before exhaustion.
211- Establish and test an administration path independent of this tailnet, including
212 console or direct SSH access. An existing tailnet SSH session is not a recovery
213 path: controller loss, key rotation or signature rejection can prevent reconnect.
214- Select the owner user by numeric ID and enumerate every unexpired, untagged
215 device that will receive administrator privileges. Ownership is user-wide, not
216 restricted to one operator device; a newly enrolled unsigned owner device also
217 qualifies, so its enrollment credentials are part of the administration boundary.
218- Keep at least two separately held signing keys and protect the disablement
219 secret offline. Do not store signing private keys or recovery secrets on the
220 controller. Test operator recovery using disposable keys first. A nonempty
221 `SupportDisablement` value submitted at `init/finish` is stored in the tkad
222 snapshot, so a same-UID controller compromise can read and use it: either
223 accept that, or never submit it and keep the secret off the controller
224 entirely (the client then needs its own copy for `tailscale lock disable`).
225- Rehearse the database migration, paired backup/restore, client reconnect and
226 packet-level signed/unsigned-peer behavior in a separate representative network.
227 Include the phone and the actual SSH path before scheduling a live change.
228- Review the same-UID trust boundary and untrusted-client availability limits.
229 Controller compromise grants access to tkad state; Omega is not a sandbox for
230 the controller. Source review does not establish constant-time behavior.
231 Registration and map admission are bounded (a saturated adapter answers 503
232 "busy" instead of queueing), and a TKA RPC from an unregistered Noise identity
233 is refused before any shared persistence work. That bounds amplification; it
234 does not make the control plane immune to load.
235- On SQLite, a stock v0.29.6 binary refuses a migrated database at its schema
236 check, and the migration has no rollback. Treat the adapter as a one-way
237 migration for that database: keep the original binary and pre-migration
238 database together, and rebase and re-qualify the patch for every Headscale
239 upgrade. PostgreSQL is unqualified and does not perform that schema check, so
240 it would start stock and silently drop Tailnet Lock state.
241- Run tkad and Headscale as separate units under the same UID, in the same
242 network namespace, with tkad started first. Never put `--init` in a unit file.
243 Handle the daemon's exit codes distinctly: 73 is a refused start (do not
244 restart in a loop), 74 is a deliberate storage fail-stop, 76 is a failed
245 rollover or exec. Restored state directories must be 0700/0600, owned by the
246 service UID, without hard links or a symlinked final component, and no tkad
247 process may be running while the directory is copied.
248
249### Quiescent backup and restore
250
251This is the required ordering for a rehearsal, not a claim that a live restore
252has been tested:
253
2541. Stop Headscale and prevent its automatic restart so no registry or TKA request
255 can be submitted. Stop tkad and prevent its automatic restart.
2562. Capture a consistent Headscale database using the database's supported backup
257 mechanism, plus the tkad state directory, controller configuration, policy,
258 artifact hashes and both adapter settings. Keep SQLite WAL/journal consistency;
259 copying a live main database file alone is not a backup.
2603. Keep the pair together, access-restricted and labelled with one capture ID.
261 The snapshot includes secrets. Do not put it in this public repository.
2624. Restore both stores into an isolated environment under trusted ancestors and
263 the intended UID/modes. Never restore one store alone, decrement the observed
264 revision floor, or use `--init` to bypass missing/corrupt state.
2655. Start tkad without `--init`, then Headscale with both adapter settings. Check
266 the authority head, roster and accepted signatures, then reconnect clients.
267 A checksum-valid backup is not proof that clients accept its authority history.
268
269The revision floor detects some stale restores; it is not authentication of the
270backup. Rolling both stores back can evade that floor and conflict with client
271state. If a rehearsal cannot reconcile the saved authority with current clients,
272keep publication stopped and recover the correct stores rather than resetting
273the authority.
274
275### Change window and interruption
276
277Before enabling Tailnet Lock, preserve the pre-migration database and original
278controller binary/configuration. A pre-activation rollback restores that original
279set, not an older binary against the migrated database.
280
281After activation, there is **no transparent downgrade** to ordinary Headscale:
282removing the adapter variables does not safely undo the authority already stored
283by clients. On SQLite a stock binary refuses the migrated database outright; on
284PostgreSQL it would start and silently drop Tailnet Lock state. To make that
285failure explicit, the adapter now refuses to start when both settings are absent
286and the database already records adapter state (a checkpoint row or any node with
287a tailnet-lock key). Prefer repair/roll-forward using the paired stores.
288After the lock has been disabled, [`downgrade.sql`](downgrade.sql) returns a SQLite
289database to the exact v0.29.6 schema (it removes the two columns, the checkpoint
290table and the migration row) so the stock binary starts on it with every node's
291current key; the runbook rehearsal checks the stock refusal first, then the
292downgrade and reconnection. Restoring the pre-activation backup instead loses every
293node key changed since (each re-registration); in one rehearsal run stock Headscale then
294answered "node not found" to those nodes (observed once, not asserted by the test).
295Disabling Tailnet Lock is an explicit security downgrade requiring the owner's
296approval, a valid recovery secret and verified client convergence. Disablement is
297permanent for that database: a disabled authority cannot be reinitialized, and a
298fresh `--init` directory starts at revision 0, which the durable floor rejects.
299Re-enabling Tailnet Lock therefore needs a new Headscale database. Run `disable`
300only while the adapter is active, so clients can fetch the stored disablement
301secret; a client that misses it needs `tailscale lock local-disable` locally.
302Do not present disablement as a reversible toggle.
303
304The revision floor catches a lower daemon revision, not an arbitrary different
305authority at an equal or higher revision, and it advances before reconciliation.
306Restoring an older database beside a newer tkad therefore removes the nodes and
307signatures the older database lacks. That is why the stores must always be
308restored together from one capture.
309
310A controller restart interrupts control-plane requests and map streams. Existing
311peer paths may continue, but new connections, relay-dependent paths, registration,
312rotation and SSH reconnect are not guaranteed. A tkad outage blocks publication;
313it does not revoke existing data-plane connectivity. No live-service interruption
314is part of the isolated build/review workflow.
315
316## Third-party notices
317
318The patch includes context from Headscale and regenerated Tailscale-derived view
319code. Their BSD-3-Clause notices are `headscale.LICENSE` and `tailscale.LICENSE`.
320New Omnet glue is covered by the repository license. No upstream cryptographic
321implementation is added to Headscale by this patch.