PQ: fix membership for post-quantum nodes (three control-plane defects)
A PQ node could complete the hybrid handshake and still never join the network: status ACCESS_DENIED, peers [], frames dropped. Three separate defects, none in the key exchange itself. 1. EmbeddedNetworkController::_request gated known members with Identity(haveIdStr) != identity. HELLO carries only the classic projection (Identity::serializeClassic), so peer->identity() stays type 0 while a stored record is type 1, and operator== -- which compares PQ material -- always reported a mismatch. Use the existing sameClassicalIdentity(); PQ key rotation stays detectable via VERB_PQ_KEYS. 2. Peer::setPQPublicKeys() cached the received PQ keys for the crypto path only and never wrote them into _id. The controller's identity therefore stayed type 0 in every table, com.verify() returned 1, and Membership deferred for WHOIS forever -- a WHOIS cannot help, the keys arrive in VERB_PQ_KEYS. Add Identity::attachPQPublicKeys() and call it so the peer's Identity is complete once keys arrive. 3. OneServiceImpl::run constructed an EmbeddedNetworkController unconditionally, so a member-only node answered its own NETWORK_CONFIG_REQUESTs and self-signed a local config, never contacting the node that owned the network. Add settings.disableController (default false, so existing installs are unchanged) for member-only nodes. Verified live on two hosts with pqcMode: hybrid on both sides: status OK, peer DIRECT over 192.168.122.85/9993, pqcCapable and pqcHybridActive true both directions, ping 0% loss both ways, selftest exit 0. The selftest regression covers the controller match and keeps rejecting an impostor identity at the same address. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
ad01fbcccb
commit
a224dbbc53
24 files changed
+1423
-168
No files matched your search
@@ -1,6 +1,41 @@
|
||||
ZeroTier Release Notes
|
||||
======
|
||||
|
||||
# 2026-10-07 -- Version 2.0.2
|
||||
|
||||
* Fix: post-quantum hybrid handshakes never completed. A peer's identity is
|
||||
reconstructed from the HELLO packet, which carries only the classic
|
||||
(type 0) projection of the sender's identity. The HELLO collision check
|
||||
compared full identities, so a type 1 (PQ) sender looked like a different
|
||||
identity at the same address and was dropped as an "address collision"
|
||||
before its capability bit was read. The PQ key exchange therefore never
|
||||
started, no hybrid session key was ever negotiated, and affected nodes
|
||||
showed no paths to each other. The check now compares only the material
|
||||
HELLO actually transports (address + Curve25519 public key); PQ key
|
||||
rotation remains detectable in VERB_PQ_KEYS.
|
||||
* Add a selftest regression covering the HELLO classic projection round
|
||||
trip and the true-collision case.
|
||||
* Fix: post-quantum nodes could not join a network even after a successful
|
||||
handshake, reporting ACCESS_DENIED with an empty peer list while frames
|
||||
were dropped. Three separate control-plane defects were involved.
|
||||
(1) The embedded controller compared a member's stored identity against
|
||||
the identity it receives on the wire. The wire only ever carries the
|
||||
classic projection of a type 1 identity, so the comparison could never
|
||||
succeed and every PQ member was denied. The controller now compares only
|
||||
what HELLO transports, reusing the existing sameClassicalIdentity() helper.
|
||||
(2) A peer's Identity was never completed with the PQ keys received in
|
||||
VERB_PQ_KEYS, so the controller's identity stayed type 0 in every table
|
||||
and type 2 CertificateOfMembership signatures could never be verified.
|
||||
The peer's Identity is now completed as soon as its keys arrive.
|
||||
(3) Every node started an embedded controller unconditionally, so a
|
||||
member-only node answered its own config requests and never contacted the
|
||||
node owning the network. A new settings.disableController option lets such
|
||||
a node opt out; it defaults to false, so existing installs are unchanged.
|
||||
* Add selftest regressions for the controller identity match, including
|
||||
rejection of an impostor identity at the same address.
|
||||
* Document settings.disableController in service/README.md and the
|
||||
membership defects in docs/pqc-test-scenario.md.
|
||||
|
||||
# 2026-10-01 -- Version 2.0.0
|
||||
|
||||
* BackOne version diverges from zerotier-one from this point: version
|
||||
|
||||
@@ -38,7 +38,7 @@ Make BackOne quantum ready: phases 1-6 of `backone-quantum-fork-research.md` —
|
||||
| I.ffi | Rust FFI | `rustybits/zeroidc` (`zeroidc_new`…), `smeeclient` — C header `zeroidc.h`, link on `ZT_SSO_SUPPORTED=1`/`ZT_CONTROLLER=1` |
|
||||
| I.jni | Java SDK | `java/jni/…Node.cpp`, ant targets `build_java/build_android/build_jar` |
|
||||
| I.pqc.cfg | config | `local.conf` `settings.pqcMode` (off/hybrid/pqconly); **absent = off/classic (opt-in)**, unknown value = warn + classic. Per-algorithm `kem`/`sig` selection is *not* wired (research doc only, see T25) |
|
||||
| I.pqc.wire | wire | static-static hybrid, no ephemeral exchange: identity v2 (type byte 1) carries ML-KEM-768 pub + ML-DSA-65 pub; agree = KDF(X25519-identity-agree ‖ ML-KEM-encaps(peer static pub)) (`node/Identity.hpp:364-379` encaps / `:392+` decaps, driven from `node/Peer.cpp` `ensurePendingHybridCt`/`setHybridSessionKey`); capability via HELLO protocol-version bytes (`node/Packet.hpp:329-333`); `identity.secret`/`identity.public` v2 on disk |
|
||||
| I.pqc.wire | wire | static-static hybrid, no ephemeral exchange: identity v2 (type byte 1) stores ML-KEM-768 + ML-DSA-65 pub on disk, but HELLO carries only the classic projection (`Identity::serializeClassic`) so vanilla peers parse it; peer PQ keys arrive in `VERB_PQ_KEYS` (0x17); agree = KDF(X25519-identity-agree ‖ ML-KEM-encaps(peer static pub)); the agreed key is **confirmed** by a trailing 4 B tag in the same verb (optional, V19), since ML-KEM cannot report a mismatched decapsulation; capability via HELLO protocol-version high bit; `identity.secret`/`identity.public` v2 on disk |
|
||||
| I.pqc.com | credentials | COM double-sign/verify — controller + `node/CertificateOfMembership.*` |
|
||||
| I.rules | rules compiler | `node rule-compiler/cli.js <rules>` → rules/tags JSON |
|
||||
|
||||
@@ -60,10 +60,13 @@ Derived from `selftest.cpp` + CI gates. `?` = code-derived, no test yet.
|
||||
| V10 | identity v2 survives 1280B MTU tunnel intact; v2 = type byte 1 (wire `Identity.hpp:219`, string slot `Identity.cpp:173`); address derivation hashes X25519 material only → v1/v2 addresses bit-identical; v1 parser rejects type ≠ 0 cleanly | interop matrix |
|
||||
| V11 | ML-KEM/ML-DSA KATs + hybrid KDF vector + identity v2 roundtrip + COM double-sign verify pass | extended `selftest.cpp` |
|
||||
| V12 | `pqcMode` negotiation honors `local.conf` (`off` -> no v2 fields) | live daemon: bogus `settings.pqcMode` -> `WARNING` (`service/OneService.cpp:1478`), `hybrid` -> clean (2026-10-03); `selftest` has no `pqcMode` coverage |
|
||||
| V13 | hybrid agree = KDF(X25519-identity-agree ‖ ML-KEM static-static), no ephemeral exchange; hybrid↔hybrid agree + hybrid↔vanilla classic fallback pass | `node/Peer.cpp:105-117` (encaps) `node/IncomingPacket.cpp:534-542,697-703` (decaps) |
|
||||
| V13 | hybrid agree = KDF(X25519-identity-agree ‖ ML-KEM static-static), no ephemeral exchange; hybrid↔hybrid agree + hybrid↔vanilla classic fallback pass | `node/Peer.cpp` `ensurePendingHybridCt` (encaps) / `setHybridSessionKey` (install); `node/IncomingPacket.cpp` `_doPQ_KEYS` (parse + decaps) |
|
||||
| V14 | COM double-sign = type byte 1→2 appends ML-DSA sig alongside Ed25519; v1 verify path unchanged; v1 rejects type 2 cleanly | `node/CertificateOfMembership.hpp:222-296`, `node/CertificateOfMembership.cpp:97-162`, `selftest.cpp:717` |
|
||||
| V15 | handshake vs fragment loss measured: PQC identity in clear HELLO = 3273B → 3 frags (classic 137B → 1 frag, max 7 `Packet.hpp:235`); Monte Carlo 20k trials obs≈analytic at p∈{.01,.05,.10,.30}; fragment loss delays HELLO (retransmit), does not break handshake | `selftest.cpp:1713` benchmark |
|
||||
| V16 | hybrid handshake puts a 1088 B ML-KEM-768 ct on the wire and both sides derive the same hybrid `_key`; classic/off peers carry none and fall back | write `node/Peer.cpp:493-502`, parse `node/IncomingPacket.cpp:534-542`, OK echo `node/IncomingPacket.cpp:608-619,697-703`; E2E lab M1-M5 all pass `tools/pqc-lab.sh` (2026-10-02; M3 68 / M4 90 large PQ datagrams on wire) |
|
||||
| V15 | handshake vs fragment loss measured: classic HELLO stays 137 B → 1 frag in every mode (max 7 `Packet.hpp:235`); PQ material moved off the critical path, so HELLO no longer depends on fragment reassembly | `selftest.cpp` PQ section |
|
||||
| V16 | hybrid handshake puts a 1088 B ML-KEM-768 ct on the wire and both sides derive the same hybrid `_key`; classic/off peers never receive `VERB_PQ_KEYS` and fall back | see V17 for the live evidence |
|
||||
| V17 | PQ public keys travel out of band in `VERB_PQ_KEYS` (0x17), never inside HELLO: HELLO carries only `Identity::serializeClassic` so a vanilla peer can parse it, and `VERB_PQ_KEYS` (4253 B → 3 frags) carries ML-KEM-768 + ML-DSA-65 public keys plus, from the lowest address, the 1088 B ct. Flag byte: bit0 = ct present, bit1 = "I already hold your keys" (ends the retry loop). A 4 B key-confirmation tag follows the keys (after the ct when present), see V19. | 2-node moon lab: `pqcCapable:true`, `pqcHybridActive:true`, 3 active direct paths at 172.31.0.1/19993 (2026-10-06) |
|
||||
| V18 | FLAGS is inside the AES-GMAC-SIV AAD and `dearmor` keeps the FRAGMENTED bit, so `setFragmented(true)` must precede `armor()`; `Switch::_sendViaSpecificPath` may not set it on an already-armored packet. `dearmor` decrypts to scratch and commits only on success, so a failed attempt does not destroy the ciphertext a later key would need. | `selftest.cpp` PQ section: fragmented pre-armed packet dearmors, late-set flag does not (verified `FAIL-AS-EXPECTED`) |
|
||||
| V19 | The hybrid session key is **confirmed**, never merely assumed. ML-KEM uses implicit rejection: decapsulating with a secret that does not match the peer's public key returns a well-formed but *wrong* shared secret instead of an error, so a peer whose PQ material drifted derived a different key, believed agreement succeeded, and every data frame then failed its MAC — with `_pqKeysAcked` already latched at the first handshake, so the retry timer never fired again and only a one-sided daemon restart recovered. A 4 B tag = `HMAC-SHA384(_key, peer_address)`, under its own KBKDF label (`ZT_KBKDF_LABEL_PQ_CONFIRM '2'`) so it cannot collide with session-key material, rides at the end of `VERB_PQ_KEYS` and is optional on the wire (a build without it still interoperates). Mismatch → `resetPQExchange()`, which reverts `_key` to classical, so the inbound path's hybrid-then-classical fallback (`IncomingPacket.cpp`) keeps working throughout. A peer that rolled its PQ keys still holds ours and therefore sets the ack bit in the very message where the rotation is detected, so that ack is dropped for that exchange — honouring it would re-latch the state just cleared and suppress the reply that carries the fresh ciphertext. | `selftest.cpp` "Key confirmation detects mismatched hybrid key"; direct test against `libbackonecore.a`: honest session confirms, mismatched derivation is caught, renegotiation converges to agreeing keys. Live 2-node hybrid session (n2 joins n1's network) produced zero confirmation failures, so healthy sessions are not reset |
|
||||
|
||||
## §T (tasks)
|
||||
|
||||
@@ -93,9 +96,10 @@ Derived from `selftest.cpp` + CI gates. `?` = code-derived, no test yet.
|
||||
| T22 | x | Phase 6: selftest extension — ML-KEM/ML-DSA KATs, hybrid KDF vector, identity v2 roundtrip + address stability, COM double-sign, interop hybrid↔vanilla matrix | I.build,V11,V10,V14 |
|
||||
| T23 | x | Phase 6: handshake-vs-fragment-loss benchmark for PQC HELLO; cap/segment if loss breaks handshake | V15 |
|
||||
| T24 | x | Plumb `settings.pqcMode` through the identity path: `Node(…,int pqcMode)` stores `_pqcMode`; `Identity::generate(bool pq,int pqcMode)` derives `pq` from the daemon mode; `OneService` reads `local.conf` before `new Node` — a fresh hybrid/pqconly node writes a type-1 identity, a classic one type-0. Fixes the G1 defect. | I.pqc.cfg,V12 |
|
||||
| T25 | . | Distinct PQ parameter sets: `node/PQHybrid.*` hardcodes ML-KEM-768/ML-DSA-65 (`PQHybrid.cpp` static_asserts `OQS_KEM_ml_kem_768`/`OQS_SIG_ml_dsa_65`), so `hybrid` and `pqconly` currently select identical material, while `SPEC` §C claims ML-KEM-1024/ML-DSA-87 for `pqconly`. Parameterize the preset (key sizes, ct len, `_pendingHybridCt` buffer, HELLO guard) or drop the `pqconly` claim. Note a `pqconly` HELLO with a PQ identity is 3273B → 3 frags, well under the 10024B cap, so no clean-fail path is reachable today | I.pqc.wire,I.pqc.cfg,V15 |
|
||||
| T25 | . | Distinct PQ parameter sets: `node/PQHybrid.*` hardcodes ML-KEM-768/ML-DSA-65 (`PQHybrid.cpp` static_asserts `OQS_KEM_ml_kem_768`/`OQS_SIG_ml_dsa_65`), so `hybrid` and `pqconly` currently select identical material, while `SPEC` §C claims ML-KEM-1024/ML-DSA-87 for `pqconly`. Parameterize the preset (key sizes, ct len, `_pendingHybridCt` buffer) or drop the `pqconly` claim. The HELLO MTU objection recorded here no longer applies — PQ material rides in `VERB_PQ_KEYS` (V17) — so the only remaining coupling is the buffer sizes in `Peer.hpp`. | I.pqc.wire,I.pqc.cfg,V15,V17 |
|
||||
| T26 | . | Expose real PQ state in `/peer`: `pqcCapable`/`pqcHybridActive` are copied from the `ZT_Peer` snapshot, which never populates them, so both always read `false` (B6). Add a `Node` accessor for a live peer by address and populate both fields in the three `_peerToJson` call sites. Needs a `ZT_Node` C API entry point, so it ripples to `include/ZeroTierOne.h`, `java/jni`, and the SDKs — budget for that rather than reaching into `node/` from `service/`. | I.pqc.wire,I.capi,V19 |
|
||||
|
||||
T1/T2 = prerequisites — CI must invoke `backone-selftest` before PQC gates mean anything. T1–T16 backlog (rebrand/CI/lint leftovers); T17–T25 = PQC phases 1–6 + the pqconly preset gap.
|
||||
T1/T2 = prerequisites — CI must invoke `backone-selftest` before PQC gates mean anything. T1–T16 backlog (rebrand/CI/lint leftovers); T17–T25 = PQC phases 1–6 + the pqconly preset gap; T26 = PQ state is not observable via `/peer`.
|
||||
|
||||
Not tracked (low value `?`): `one.cpp:256` port/token cleanup, `MacKextEthernetTap.cpp:480` iface status, VLAN TODOs in `NetBSDEthernetTap.cpp:468`/`MacKextEthernetTap.cpp:685`, `Phy.hpp:325` unix sock type comment.
|
||||
|
||||
@@ -105,3 +109,7 @@ Not tracked (low value `?`): `one.cpp:256` port/token cleanup, `MacKextEthernetT
|
||||
|---|---|---|---|
|
||||
| B1 | 2026-10-02 | Phase 5 (T21) advertised PQC capability in HELLO but never consumed it: `Peer::_key` was derived classically in the constructor and the hybrid ciphertext had no place in the HELLO/OK(HELLO) layout, so `hybridEligible()` was dead. | Wire hybrid static-static KEM ct into HELLO (lowest-address side writes `[moon count][moons][flag(1B)][ct 1088B]`, crypted with the classical key) and echo it in OK(HELLO); parser order matches `Peer::sendHELLO`/`_doHELLO`; `Peer::ensurePendingHybridCt()` lazily encapsulates on first capability sighting so the handshake completes in one round trip; direction guard `sender == lowest address` on both parses. Refuse to start when the on-disk identity cannot satisfy `settings.pqcMode` (classic↔PQ migration changes the address). |
|
||||
| B2 | 2026-10-02 | `settings.pqcMode` absent (or unrecognized) resolved to HYBRID, and `Node`'s `pqcMode` default was HYBRID with no way to tell "unconfigured" from "configured hybrid". Every existing type-0 install would hit the B1 refusal guard at startup; the C API `ZT_Node_new` path would silently generate type-1 identities. | Absent/unknown `settings.pqcMode` now resolves to `ZT_PQC_MODE_CLASSIC` (PQC is opt-in, matching the research doc); `Node(…,int pqcMode = ZT_PQC_MODE_CLASSIC)`. Verified: classic identity + no config boots on 2.0.0 and stays 141 B; fresh node w/o config makes type-0; fresh node with `"hybrid"` makes type-1 (6415 B); classic + explicit `"off"` boots; classic + explicit `"hybrid"` still refuses; unknown value warns and runs classic. |
|
||||
| B3 | 2026-10-06 | The hybrid handshake never completed. Three defects stacked: (a) HELLO carried the full 6415 B type-1 identity, so every peer had to reassemble a 3-fragment packet before it could even answer, and a vanilla peer could not parse it at all; (b) `Switch::_sendViaSpecificPath` called `packet.setFragmented(...)` on packets that were already armored — FLAGS is inside the AES-GMAC-SIV AAD, so flipping the bit after `armor()` invalidated the MAC and the receiver dropped every `VERB_PQ_KEYS` as "invalid MAC"; (c) `Packet::dearmor` decrypted in place, so a failed attempt destroyed the ciphertext a later key would need. | PQ material moved out of HELLO into `VERB_PQ_KEYS`; HELLO now emits only `Identity::serializeClassic`. `_sendViaSpecificPath` sets FRAGMENTED only on unencrypted packets; `sendPQKeys` sets it before `armor()`. `dearmor` decrypts to a scratch buffer and commits only on success. Regression test in `selftest.cpp` asserts both directions (fragmented-and-pre-armed authenticates; armed-then-flagged does not), verified failing against the old ordering. |
|
||||
| B4 | 2026-10-06 | Reported symptom was `backone-cli peers` showing a wall of `PLANET -1 RELAY` rows. Two things were wrong with the reading: the leading `200` is the HTTP status code that `one.cpp:453` prints, not a peer count; and the rows are the four hardcoded Earth roots, which a host with no UDP egress to `9993.zerotier.com` can never reach — hence `RELAY` and latency `-1` with no path. | No code change. Documented here so the symptom is not re-read as a PQ failure: a node that cannot reach a root shows exactly this table, independent of `pqcMode`. |
|
||||
| B5 | 2026-10-07 | A hybrid session could wedge permanently and silently. ML-KEM uses *implicit rejection*: `agreeHybridDecaps` with a secret that does not match the peer's public key returns a well-formed but **wrong** shared secret rather than an error, so both sides believed agreement had succeeded and installed it. A peer whose PQ material drifted (restore from backup, identity roll) derived a different key than its counterpart, and every data frame thereafter failed its MAC. `_pqKeysAcked` had already latched at the first handshake, so `pqKeysDue` never fired again and the retry path could not repair it — recovery required restarting one daemon. Compounding it, a peer that rolled its keys still holds ours and so sets the ack bit in the very message announcing the rotation, so the ack re-latched the state being cleared and suppressed the reply that carried the fresh ciphertext. | Added key confirmation: 4 B `HMAC-SHA384(_key, peer_address)` at the tail of `VERB_PQ_KEYS`, optional on the wire, under its own KBKDF label. Mismatch, or advertised public keys that differ from the installed ones, calls `resetPQExchange()` — drops the hybrid key, reverts `_key` to classical (the inbound hybrid-then-classical fallback keeps traffic alive throughout), re-arms the retry, and re-encapsulates. The stale ack is dropped for that exchange so the reply is not suppressed. `agreeHybridDecaps` failure is no longer silently ignored. Verified in `selftest.cpp` and directly against `libbackonecore.a`; live 2-node hybrid session shows zero false confirmations. |
|
||||
| B6 | 2026-10-07 | *Reported wrong and withdrawn.* Originally logged as "`pqcCapable`/`pqcHybridActive` in `/peer` are copied from a `ZT_Peer` snapshot that never populates them, so both always report `false`." That was false: `Node::peers()` populates both at `node/Node.cpp:621,626` from `Peer::hybridCapable()` and `Peer::hybridSessionKeyInstalled()`, and no C API change was ever needed — the fields are BackOne additions to `ZT_Peer` itself (`include/ZeroTierOne.h:1460,1467`). What *was* true is narrower and much less interesting: a stale comment at `service/OneService.cpp:621` asserted the snapshot lacked the fields, which contradicted the two lines directly beneath it and would have sent the next reader looking for a missing C API accessor that already existed. The fields were always live. | Deleted the stale comment. No functional change. Verified against a live 2-node hybrid lab: `/peer` reports `pqcHybridActive:true` on both sides once the key is installed, and `false` on a classical peer — the same field `tools/pqc-lab.sh` G4 gates on. Kept here because "the observability does not exist" is an expensive wrong assumption to propagate into the C API surface. |
|
||||
+4
-1
@@ -1,5 +1,5 @@
|
||||
Name: backone
|
||||
Version: 2.0.0
|
||||
Version: 2.0.2
|
||||
Release: 1%{?dist}
|
||||
Summary: BackOne global ethernet switch
|
||||
|
||||
@@ -155,6 +155,9 @@ chmod 0755 $RPM_BUILD_ROOT/etc/init.d/backone
|
||||
%endif
|
||||
|
||||
%changelog
|
||||
* Wed Oct 7 2026 Dedy Sutanto <dsutanto@backone.cloud> - 2.0.2
|
||||
- see https://github.com/proitlab/BackOne for release notes
|
||||
|
||||
* Thu Oct 1 2026 Dedy Sutanto <dsutanto@backone.cloud> - 2.0.0
|
||||
- see https://github.com/proitlab/BackOne for release notes
|
||||
|
||||
|
||||
@@ -1437,8 +1437,12 @@ void EmbeddedNetworkController::_request(
|
||||
// If we already know this member's identity perform a full compare. This prevents
|
||||
// a "collision" from being able to auth onto our network in place of an already
|
||||
// known member.
|
||||
// Compare only what HELLO transports: a PQ node's peer identity is the
|
||||
// classic projection (Identity::serializeClassic), so a stored type 1
|
||||
// record would never compare equal and every PQ member would be denied.
|
||||
// PQ key rotation is caught separately, via VERB_PQ_KEYS.
|
||||
try {
|
||||
if (Identity(haveIdStr.c_str()) != identity) {
|
||||
if (!Identity(haveIdStr.c_str()).sameClassicalIdentity(identity)) {
|
||||
_sender->ncSendError(nwid,requestPacketId,identity.address(),NetworkController::NC_ERROR_ACCESS_DENIED, nullptr, 0);
|
||||
#ifdef CENTRAL_CONTROLLER_REQUEST_BENCHMARK
|
||||
b4.stop();
|
||||
|
||||
Vendored
+6
@@ -1,3 +1,9 @@
|
||||
backone (2.0.2) unstable; urgency=medium
|
||||
|
||||
* See RELEASE-NOTES.md for release notes.
|
||||
|
||||
-- Dedy Sutanto <dsutanto@backone.cloud> Wed, 07 Oct 2026 00:00:00 +0700
|
||||
|
||||
backone (2.0.0) unstable; urgency=medium
|
||||
|
||||
* See RELEASE-NOTES.md for release notes.
|
||||
|
||||
@@ -436,3 +436,100 @@ Verified against a synthetic capture (tshark 4.6.4): classic HELLO decodes as
|
||||
`type=1`, 3175 B identity, `zt.hello.cap == 1`, and its tail frames as
|
||||
`BackOne fragment n/3`. Run tshark as your normal user — as superuser Wireshark
|
||||
silently skips user Lua scripts (see §4.3).
|
||||
|
||||
---
|
||||
|
||||
## 9. Membership bugs that hid the handshake (found 2026-10-07)
|
||||
|
||||
§7's lab proves the *handshake*. It does not prove **membership**: two PQ nodes
|
||||
can negotiate a hybrid key perfectly and still never forward a frame. All three
|
||||
defects below are on the control plane, and only two of them are PQ-specific.
|
||||
The tell in every case is the same, and it is not a link problem:
|
||||
|
||||
```
|
||||
network/<nwid> -> {"status":"ACCESS_DENIED","peers":[]}
|
||||
packet_type="network_config" rx=0 # no config ever arrives
|
||||
packet_type="multicast_frame" tx>0 rx=0 # frames go out, nothing comes back
|
||||
```
|
||||
|
||||
`Network::gate()` drops every frame from a peer with no `Membership`, so a
|
||||
broken credential shows up as 100% multicast loss with a *healthy* direct path
|
||||
and a working session key. Check `status` and `peers` before blaming crypto.
|
||||
|
||||
### B6 — the controller compared identities the wire never carries
|
||||
|
||||
`EmbeddedNetworkController::_request` gated known members with
|
||||
`Identity(haveIdStr) != identity`. HELLO transports only the classic projection
|
||||
(`Identity::serializeClassic`, deliberately — a type-1 identity is 6415 B and
|
||||
would blow the fragment budget), so `peer->identity()` is **permanently type 0**
|
||||
while the stored record is type 1. `Identity::operator==` compares PQ material
|
||||
too, so it returned false and every PQ member got `ACCESS_DENIED`.
|
||||
|
||||
The fork already had the right predicate — `Identity::sameClassicalIdentity()`,
|
||||
added for exactly this at `Identity.hpp:614` and used in `IncomingPacket.cpp:424`
|
||||
— the controller just never used it. Fixed:
|
||||
|
||||
```cpp
|
||||
// controller/EmbeddedNetworkController.cpp:1445
|
||||
if (!Identity(haveIdStr.c_str()).sameClassicalIdentity(identity)) {
|
||||
```
|
||||
|
||||
PQ key rotation stays detectable: `VERB_PQ_KEYS` compares the keys themselves
|
||||
(see §2.4 / `Identity::pqKeysDiffer`), so nothing is lost by comparing less here.
|
||||
|
||||
### B7 — a PQ peer's identity was never completed
|
||||
|
||||
Even with B6 fixed, credentials still did not arrive. A type-2 COM
|
||||
double-signature is verified against the controller's identity fetched via
|
||||
`Topology::getIdentity()` → `peer->identity()`. But `Peer::setPQPublicKeys()`
|
||||
cached the received PQ keys in `_pqMlkemPk`/`_pqMldsaPk` for the *crypto* path
|
||||
only — it never wrote them into `_id`. So the controller's identity stayed type 0
|
||||
in every table, `com.verify()` returned 1, and `Membership::addCredential()`
|
||||
answered `ADD_DEFERRED_FOR_WHOIS` forever. A WHOIS cannot fix it either: the keys
|
||||
come in `VERB_PQ_KEYS`, not WHOIS.
|
||||
|
||||
Fixed by adding `Identity::attachPQPublicKeys()` (`Identity.hpp`) and calling it
|
||||
from `Peer::setPQPublicKeys()`, so the peer's `Identity` becomes the type-1
|
||||
identity it actually is as soon as the capability bit is seen.
|
||||
|
||||
### B8 — every node ran its own controller (not PQ-specific)
|
||||
|
||||
`OneServiceImpl::run` constructed `EmbeddedNetworkController` **unconditionally**
|
||||
(`OneService.cpp:1157`), with no opt-out. Two nodes on a lab therefore each
|
||||
answered their own `NETWORK_CONFIG_REQUEST`s, self-signed a local config
|
||||
(`id=<own address>` in `networks.d/<nwid>.conf`), and never contacted the node
|
||||
that actually owned the network. The controller member record stayed a stale
|
||||
type-0 identity from before the PQ upgrade, which is what made B6 fire in the
|
||||
first place.
|
||||
|
||||
Fixed with an opt-out, default off so existing installs are unchanged:
|
||||
|
||||
```json
|
||||
{ "settings": { "disableController": true } }
|
||||
```
|
||||
|
||||
Set it on member-only nodes. A controller node must leave it unset.
|
||||
|
||||
### B6–B8 verification (two real hosts, `pqcMode: hybrid` both sides)
|
||||
|
||||
```sh
|
||||
backone-cli -p9993 -D/var/lib/backone peers
|
||||
# 200 peers <- HTTP status, NOT a peer count
|
||||
# dbfa939d58 2.0.2 LEAF 0 DIRECT 2 9344 192.168.122.85/9993
|
||||
```
|
||||
|
||||
| Check | Result |
|
||||
|---|---|
|
||||
| `network/<nwid>` status | `OK` (was `ACCESS_DENIED`) |
|
||||
| Peer role / path | `LEAF` / `DIRECT` over 192.168.122.85/9993 |
|
||||
| `pqcCapable` / `pqcHybridActive` | `true` / `true`, both directions |
|
||||
| ping 10.97.0.13 ↔ 10.97.0.52 | 0% loss both ways |
|
||||
| `./backone-selftest` | exit 0, incl. new `[certificate]` regression |
|
||||
|
||||
Regression test added to `selftest.cpp::testCertificate`: a type-1 record must
|
||||
match a peer seen as classic (`sameClassicalIdentity`), an impostor at the same
|
||||
address must not. That is the B6 defect, pinned.
|
||||
|
||||
Note for anyone reproducing: `backone-cli peers` prints `200 peers` as its
|
||||
first line — that is the HTTP status code. A real peer listing follows beneath
|
||||
it. Read the table, not that number.
|
||||
@@ -18,6 +18,7 @@
|
||||
#define SEWENEW_REDISPLUSPLUS_UTILS_H
|
||||
|
||||
#include <cstring>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
#include "cxx_utils.h"
|
||||
|
||||
@@ -1452,6 +1452,19 @@ typedef struct
|
||||
* Known network paths to peer
|
||||
*/
|
||||
ZT_PeerPhysicalPath paths[ZT_MAX_PEER_NETWORK_PATHS];
|
||||
|
||||
/**
|
||||
* True if this peer advertised the post-quantum capability in its HELLO
|
||||
* and we hold our own post-quantum keys (BackOne extension).
|
||||
*/
|
||||
bool pqcCapable;
|
||||
|
||||
/**
|
||||
* True if this peer's post-quantum public keys have been received and
|
||||
* hybrid key agreement is actually in effect for traffic with this peer.
|
||||
* False means classical-only, even when both nodes run a PQ-capable build.
|
||||
*/
|
||||
bool pqcHybridActive;
|
||||
} ZT_Peer;
|
||||
|
||||
/**
|
||||
|
||||
+8
-2
@@ -106,6 +106,12 @@ ifeq ($(ZT_TRACE),1)
|
||||
override DEFS+=-DZT_TRACE
|
||||
endif
|
||||
|
||||
# Traces the PQ key exchange (VERB_PQ_KEYS send/receive, ciphertext state).
|
||||
# Off by default: it writes to stderr on the data path.
|
||||
ifeq ($(ZT_PQ_DEBUG),1)
|
||||
override DEFS+=-DZT_PQ_DEBUG
|
||||
endif
|
||||
|
||||
ifeq ($(ZT_DEBUG),1)
|
||||
override DEFS+=-DZT_DEBUG
|
||||
endif
|
||||
@@ -454,7 +460,7 @@ debug: FORCE
|
||||
ifeq ($(ZT_SSO_SUPPORTED), 1)
|
||||
ifeq ($(ZT_EMBEDDED),)
|
||||
zeroidc: FORCE
|
||||
export PATH=/${HOME}/.cargo/bin:$$PATH; cd rustybits && cargo build $(ZT_CARGO_FLAGS) -p zeroidc
|
||||
export PATH=$$HOME/.cargo/bin:$$PATH; cd rustybits && cargo build $(ZT_CARGO_FLAGS) -p zeroidc
|
||||
endif
|
||||
else
|
||||
zeroidc:
|
||||
@@ -462,7 +468,7 @@ endif
|
||||
|
||||
ifeq ($(ZT_CONTROLLER), 1)
|
||||
smeeclient: FORCE
|
||||
export PATH=/${HOME}/.cargo/bin:$$PATH; cd rustybits && cargo build $(ZT_CARGO_FLAGS) -p smeeclient
|
||||
export PATH=$$HOME/.cargo/bin:$$PATH; cd rustybits && cargo build $(ZT_CARGO_FLAGS) -p smeeclient
|
||||
else
|
||||
smeeclient:
|
||||
endif
|
||||
|
||||
+72
-6
@@ -171,6 +171,29 @@ public:
|
||||
inline const PQKeys* pqKeys() const
|
||||
{ return _pq; }
|
||||
|
||||
/**
|
||||
* Attach public PQ keys learned out of band (VERB_PQ_KEYS) to an otherwise
|
||||
* classic identity, turning it into the type 1 identity it really is.
|
||||
*
|
||||
* HELLO only ever carries the classic projection (see serializeClassic), so
|
||||
* a peer's Identity starts out type 0. Anything that verifies a type 2
|
||||
* CertificateOfMembership reads the controller's identity back through
|
||||
* Topology::getIdentity(), so without this the signature can never be
|
||||
* checked. Existing PQ material is replaced.
|
||||
*
|
||||
* @param mlkemPk ML-KEM-768 public key
|
||||
* @param mldsaPk ML-DSA-65 public key
|
||||
*/
|
||||
inline void attachPQPublicKeys(const uint8_t* mlkemPk, const uint8_t* mldsaPk)
|
||||
{
|
||||
if (! _pq) {
|
||||
_pq = new PQKeys;
|
||||
memset(_pq, 0, sizeof(PQKeys));
|
||||
}
|
||||
memcpy(_pq->mlkemPk, mlkemPk, PQHybrid::MLKEM768_PK_LEN);
|
||||
memcpy(_pq->mldsaPk, mldsaPk, PQHybrid::MLDSA65_PK_LEN);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the public half (public keys only) of a type 1 identity's PQ material.
|
||||
*
|
||||
@@ -354,21 +377,24 @@ public:
|
||||
* key = HMAC-SHA-384(X25519-identity-agree || ML-KEM-768 encaps to peer static pk).
|
||||
* Static-static: no ephemeral exchange.
|
||||
*
|
||||
* This identity must have a private key; the peer must be type 1 (hasPQ()).
|
||||
* This identity must have a private key. The peer's ML-KEM-768 public key is
|
||||
* passed separately because peers advertise PQ material in a separate
|
||||
* message (Packet::VERB_PQ_KEYS) rather than inside their HELLO identity.
|
||||
*
|
||||
* @param id Peer identity (must be type 1)
|
||||
* @param id Peer identity (classical part; supplies the C25519 public key)
|
||||
* @param peerMlkemPk Peer ML-KEM-768 public key, PQHybrid::MLKEM768_PK_LEN bytes
|
||||
* @param ct Result buffer of PQHybrid::MLKEM768_CT_LEN bytes for the ML-KEM-768 ciphertext
|
||||
* @param key Result buffer of ZT_SYMMETRIC_KEY_SIZE bytes for the hybrid key
|
||||
* @return Was agreement successful?
|
||||
*/
|
||||
inline bool agreeHybridEncaps(const Identity& id, void* const ct, void* const key) const
|
||||
inline bool agreeHybridEncaps(const Identity& id, const uint8_t* const peerMlkemPk, void* const ct, void* const key) const
|
||||
{
|
||||
if ((! _privateKey) || (! id._pq)) {
|
||||
if ((! _privateKey) || (! peerMlkemPk)) {
|
||||
return false;
|
||||
}
|
||||
uint8_t classical[ZT_SYMMETRIC_KEY_SIZE];
|
||||
uint8_t pq[PQHybrid::MLKEM768_SS_LEN];
|
||||
if (! PQHybrid::encaps(id._pq->mlkemPk, reinterpret_cast<uint8_t*>(ct), pq)) {
|
||||
if (! PQHybrid::encaps(peerMlkemPk, reinterpret_cast<uint8_t*>(ct), pq)) {
|
||||
return false;
|
||||
}
|
||||
C25519::agree(*_privateKey, id._publicKey, classical, ZT_SYMMETRIC_KEY_SIZE);
|
||||
@@ -382,7 +408,8 @@ public:
|
||||
* Hybrid post-quantum key agreement, decapsulate side (V13):
|
||||
* recompute key from the peer's ML-KEM-768 ciphertext with this identity's secret.
|
||||
*
|
||||
* This identity must be type 1 with a private key; the peer is classical.
|
||||
* This identity must be type 1 with a private key; the peer's identity is
|
||||
* the classic (type 0) projection published in its HELLO.
|
||||
*
|
||||
* @param id Peer identity (classical public key)
|
||||
* @param ct ML-KEM-768 ciphertext of PQHybrid::MLKEM768_CT_LEN bytes
|
||||
@@ -442,6 +469,27 @@ public:
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialize the classic (type 0) projection of this identity
|
||||
*
|
||||
* Emits only address, type byte 0 and the X25519 public key -- the exact
|
||||
* wire form a vanilla ZeroTier peer parses. A type 1 identity's PQ material
|
||||
* is deliberately omitted: HELLO and ERROR(IDENTITY_COLLISION) must stay
|
||||
* parseable by unmodified peers, and PQ keys travel out of band in
|
||||
* Packet::VERB_PQ_KEYS instead.
|
||||
*
|
||||
* @param b Destination buffer to append to
|
||||
* @throws std::out_of_range Buffer too small
|
||||
*/
|
||||
template<unsigned int C>
|
||||
inline void serializeClassic(Buffer<C> &b) const
|
||||
{
|
||||
_address.appendTo(b);
|
||||
b.append((uint8_t)ZT_IDENTITY_TYPE_C25519);
|
||||
b.append(_publicKey.data, ZT_C25519_PUBLIC_KEY_LEN);
|
||||
b.append((unsigned char)0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deserialize a binary serialized identity
|
||||
*
|
||||
@@ -572,6 +620,24 @@ public:
|
||||
}
|
||||
return ((memcmp(_pq->mlkemPk, id._pq->mlkemPk, PQHybrid::MLKEM768_PK_LEN) == 0) && (memcmp(_pq->mldsaPk, id._pq->mldsaPk, PQHybrid::MLDSA65_PK_LEN) == 0));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return True if the two identities match on the material a HELLO carries
|
||||
*
|
||||
* HELLO and ERROR(IDENTITY_COLLISION) carry only the classic projection
|
||||
* (see serializeClassic), so a receiver never sees a type 1 identity's
|
||||
* PQ keys. The Peer it builds is therefore permanently type 0 while the
|
||||
* sender is type 1, and operator== would report a false collision on every
|
||||
* subsequent HELLO, dropping the peer before its capability bit is read.
|
||||
* Compare only what HELLO actually transports.
|
||||
*
|
||||
* PQ key rotation stays detectable: VERB_PQ_KEYS compares the keys
|
||||
* themselves (see Identity::pqKeysDiffer).
|
||||
*/
|
||||
inline bool sameClassicalIdentity(const Identity& id) const
|
||||
{
|
||||
return ((_address == id._address) && (memcmp(_publicKey.data, id._publicKey.data, ZT_C25519_PUBLIC_KEY_LEN) == 0));
|
||||
}
|
||||
inline bool operator<(const Identity& id) const
|
||||
{
|
||||
if (_address < id._address) {
|
||||
|
||||
+153
-62
@@ -69,16 +69,23 @@ bool IncomingPacket::tryDecode(const RuntimeEnvironment *RR,void *tPtr,int32_t f
|
||||
if (peer) {
|
||||
if (!_authenticated) {
|
||||
if (!dearmor(peer->key(), peer->aesKeys())) {
|
||||
// HELLO and OK(HELLO) are always armored with the classical
|
||||
// key, so retry with it once the session key has gone hybrid.
|
||||
if (((verb() == Packet::VERB_HELLO) || (verb() == Packet::VERB_OK)) && (dearmor(peer->keyClassical(), peer->aesKeysClassical()))) {
|
||||
// classical fallback accepted
|
||||
}
|
||||
else {
|
||||
RR->t->incomingPacketMessageAuthenticationFailure(tPtr, _path, packetId(), sourceAddress, hops(), "invalid MAC");
|
||||
peer->recordIncomingInvalidPacket(_path);
|
||||
return true;
|
||||
}
|
||||
// The retry cannot be gated on verb(): Packet::dearmor
|
||||
// verifies the MAC before it decrypts, so after a
|
||||
// failure the verb byte is still ciphertext and testing
|
||||
// it here would only compare noise.
|
||||
//
|
||||
// Unconditional, and unconditional is cheap: both keys
|
||||
// derive from the same identity material, so a failure
|
||||
// under the hybrid key means the sender armored with the
|
||||
// classical one. HELLO, OK(HELLO) and PQ_KEYS are always
|
||||
// sent that way, and PQ_KEYS is larger than an MTU, so it
|
||||
// reaches here by way of fragment reassembly. Anything
|
||||
// else simply fails again.
|
||||
if (!dearmor(peer->keyClassical(), peer->aesKeysClassical())) {
|
||||
RR->t->incomingPacketMessageAuthenticationFailure(tPtr, _path, packetId(), sourceAddress, hops(), "invalid MAC");
|
||||
peer->recordIncomingInvalidPacket(_path);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,7 +164,11 @@ bool IncomingPacket::tryDecode(const RuntimeEnvironment *RR,void *tPtr,int32_t f
|
||||
case Packet::VERB_PATH_NEGOTIATION_REQUEST:
|
||||
r = _doPATH_NEGOTIATION_REQUEST(RR, tPtr, peer);
|
||||
break;
|
||||
case Packet::VERB_PQ_KEYS:
|
||||
r = _doPQ_KEYS(RR, tPtr, peer);
|
||||
break;
|
||||
}
|
||||
|
||||
if (r) {
|
||||
RR->node->statsLogVerb((unsigned int)v,(unsigned int)size());
|
||||
return true;
|
||||
@@ -410,7 +421,7 @@ bool IncomingPacket::_doHELLO(const RuntimeEnvironment *RR,void *tPtr,const bool
|
||||
if (peer) {
|
||||
// We already have an identity with this address -- check for collisions
|
||||
if (!alreadyAuthenticated) {
|
||||
if (peer->identity() != id) {
|
||||
if (!peer->identity().sameClassicalIdentity(id)) {
|
||||
// Identity is different from the one we already have -- address collision
|
||||
|
||||
// Check rate limits
|
||||
@@ -423,11 +434,12 @@ bool IncomingPacket::_doHELLO(const RuntimeEnvironment *RR,void *tPtr,const bool
|
||||
if (dearmor(key, peer->aesKeysIfSupported())) { // ensure packet is authentic, otherwise drop
|
||||
RR->t->incomingPacketDroppedHELLO(tPtr,_path,pid,fromAddress,"address collision");
|
||||
Packet outp(id.address(),RR->identity.address(),Packet::VERB_ERROR);
|
||||
outp.append((uint8_t)Packet::VERB_HELLO);
|
||||
outp.append((uint64_t)pid);
|
||||
outp.append((uint8_t)Packet::ERROR_IDENTITY_COLLISION);
|
||||
peer->identity().serialize(outp); // payload: known conflicting identity (before armor)
|
||||
outp.armor(key,true,peer->aesKeysIfSupported());
|
||||
outp.append((uint8_t)Packet::VERB_HELLO);
|
||||
outp.append((uint64_t)pid);
|
||||
outp.append((uint8_t)Packet::ERROR_IDENTITY_COLLISION);
|
||||
// Classic projection: a vanilla peer must be able to parse
|
||||
// the conflicting identity we echo back.
|
||||
peer->identity().serializeClassic(outp);
|
||||
Metrics::pkt_error_out++;
|
||||
Metrics::pkt_error_identity_collision_out++;
|
||||
_path->send(RR,tPtr,outp.data(),outp.size(),RR->node->now());
|
||||
@@ -511,9 +523,8 @@ bool IncomingPacket::_doHELLO(const RuntimeEnvironment *RR,void *tPtr,const bool
|
||||
std::vector< std::pair<uint64_t,uint64_t> > moonIdsAndTimestamps;
|
||||
if (ptr < size()) {
|
||||
// Remainder of packet, if present, is encrypted (always with the
|
||||
// classical key: it carries the hybrid ciphertext itself).
|
||||
// classical key: the hybrid key may not be installed yet).
|
||||
cryptField(peer->keyClassical(), ptr, size() - ptr);
|
||||
|
||||
// Get moon IDs and timestamps if present
|
||||
if ((ptr + 2) <= size()) {
|
||||
const unsigned int numMoons = at<uint16_t>(ptr);
|
||||
@@ -526,20 +537,8 @@ bool IncomingPacket::_doHELLO(const RuntimeEnvironment *RR,void *tPtr,const bool
|
||||
}
|
||||
}
|
||||
|
||||
// Hybrid KEM ciphertext, if the sender included one. Sender order is
|
||||
// [moon count(2B)][moons][flag(1B)][ciphertext(1088B)] (see
|
||||
// Peer::sendHELLO), so the flag follows the moon list. Only the
|
||||
// lowest-address side ever writes it, so require that direction
|
||||
// (sender == lowest) rather than trusting a coincidental byte value.
|
||||
if ((peer->hybridEligible()) && (peer->identity().address() < RR->identity.address()) && ((ptr + 1 + PQHybrid::MLKEM768_CT_LEN) <= size()) && ((unsigned char)(*this)[ptr] == 1)) {
|
||||
++ptr;
|
||||
uint8_t hkey[ZT_SYMMETRIC_KEY_SIZE];
|
||||
if (RR->identity.agreeHybridDecaps(id, field(ptr, PQHybrid::MLKEM768_CT_LEN), hkey)) {
|
||||
peer->setHybridSessionKey(hkey);
|
||||
}
|
||||
Utils::burn(hkey, sizeof(hkey));
|
||||
ptr += PQHybrid::MLKEM768_CT_LEN;
|
||||
}
|
||||
// No hybrid ciphertext here: the lowest-address side sends it in
|
||||
// VERB_PQ_KEYS.
|
||||
}
|
||||
|
||||
// Send OK(HELLO) with an echo of the packet's timestamp and some of the same
|
||||
@@ -605,18 +604,10 @@ bool IncomingPacket::_doHELLO(const RuntimeEnvironment *RR,void *tPtr,const bool
|
||||
}
|
||||
outp.setAt<uint16_t>(worldUpdateSizeAt,(uint16_t)(outp.size() - (worldUpdateSizeAt + 2)));
|
||||
|
||||
// Echo our ciphertext in OK(HELLO) so the initiator can derive the same
|
||||
// hybrid key; only the lowest address ever encapsulates. Generate it now
|
||||
// if this HELLO is the first time we learned the peer is hybrid-capable,
|
||||
// so the handshake completes in this round trip instead of the next HELLO.
|
||||
if (peer->hybridEligible()) {
|
||||
peer->ensurePendingHybridCt();
|
||||
}
|
||||
unsigned char ctBuf[PQHybrid::MLKEM768_CT_LEN];
|
||||
if (peer->pendingHybridCt(ctBuf)) {
|
||||
outp.append((uint8_t)1);
|
||||
outp.append(ctBuf, sizeof(ctBuf));
|
||||
}
|
||||
// The hybrid ciphertext is not echoed here: it would grow OK(HELLO) past
|
||||
// the MTU. If we are the lowest-address side we send our PQ keys plus the
|
||||
// ciphertext in VERB_PQ_KEYS instead, once a path to the peer is usable
|
||||
// (see Peer::sendPQKeys).
|
||||
|
||||
outp.armor(peer->keyClassical(), true, peer->aesKeysClassical());
|
||||
peer->recordOutgoingPacket(_path,outp.packetId(),outp.payloadLength(),outp.verb(),ZT_QOS_NO_FLOW,now);
|
||||
@@ -682,24 +673,12 @@ bool IncomingPacket::_doOK(const RuntimeEnvironment *RR,void *tPtr,const SharedP
|
||||
|
||||
peer->setRemoteVersion(vProto,vMajor,vMinor,vRevision);
|
||||
|
||||
// Hybrid ciphertext echoed by the lowest-address side; decrypting
|
||||
// it completes the hybrid key agreement on our side.
|
||||
unsigned int cto = ZT_PROTO_VERB_HELLO__OK__IDX_REVISION + 2;
|
||||
InetAddress _esa;
|
||||
if (cto < size()) {
|
||||
cto += _esa.deserialize(*this, cto);
|
||||
}
|
||||
if ((cto + 2) <= size()) {
|
||||
cto += 2 + at<uint16_t>(cto);
|
||||
}
|
||||
// Echo comes from the lowest-address side only; require that
|
||||
// direction rather than trusting a coincidental flag byte.
|
||||
if ((peer->hybridEligible()) && (peer->identity().address() < RR->identity.address()) && (cto < size()) && ((unsigned char)(*this)[cto] == 1) && ((cto + 1 + PQHybrid::MLKEM768_CT_LEN) <= size())) {
|
||||
uint8_t hkey[ZT_SYMMETRIC_KEY_SIZE];
|
||||
if (RR->identity.agreeHybridDecaps(peer->identity(), field(cto + 1, PQHybrid::MLKEM768_CT_LEN), hkey)) {
|
||||
peer->setHybridSessionKey(hkey);
|
||||
}
|
||||
Utils::burn(hkey, sizeof(hkey));
|
||||
|
||||
// No hybrid ciphertext is echoed in OK(HELLO); it arrives in
|
||||
// VERB_PQ_KEYS. Offer ours now that a working path exists (the
|
||||
// HELLO/OK pair just proved one).
|
||||
if ((peer->hybridCapable()) && (RR->identity.hasPQ()) && peer->pqKeysDue(RR->node->now())) {
|
||||
peer->sendPQKeys(tPtr,RR->node->now());
|
||||
}
|
||||
|
||||
if ((externalSurfaceAddress)&&(hops() == 0)) {
|
||||
@@ -1559,6 +1538,118 @@ bool IncomingPacket::_doPATH_NEGOTIATION_REQUEST(const RuntimeEnvironment *RR,vo
|
||||
return true;
|
||||
}
|
||||
|
||||
bool IncomingPacket::_doPQ_KEYS(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer)
|
||||
{
|
||||
const unsigned int minLen = 1 + PQHybrid::MLKEM768_PK_LEN + PQHybrid::MLDSA65_PK_LEN;
|
||||
if (payloadLength() < minLen) {
|
||||
RR->t->incomingPacketInvalid(tPtr,_path,packetId(),source(),hops(),Packet::VERB_PQ_KEYS,"PQ_KEYS too short");
|
||||
return true;
|
||||
}
|
||||
if (!peer->hybridCapable()) {
|
||||
// We never advertised PQ support, so this is not material we asked for.
|
||||
RR->t->incomingPacketInvalid(tPtr,_path,packetId(),source(),hops(),Packet::VERB_PQ_KEYS,"PQ_KEYS unexpected");
|
||||
return true;
|
||||
}
|
||||
const unsigned char *p = payload();
|
||||
const bool haveCt = (p[0] & 0x01) != 0;
|
||||
|
||||
const bool peerHoldsOurKeys = (p[0] & 0x02) != 0;
|
||||
const unsigned int confirmOff = (haveCt) ? (minLen + PQHybrid::MLKEM768_CT_LEN) : minLen;
|
||||
if (haveCt && (payloadLength() < confirmOff)) {
|
||||
RR->t->incomingPacketInvalid(tPtr,_path,packetId(),source(),hops(),Packet::VERB_PQ_KEYS,"PQ_KEYS truncated ct");
|
||||
return true;
|
||||
}
|
||||
// The confirmation tag is optional so a build that omits it still
|
||||
// interoperates; it is only checked when actually present.
|
||||
const bool haveConfirm = (payloadLength() >= (confirmOff + ZT_PQ_KEYS_CONFIRM_LEN));
|
||||
const unsigned char *peerConfirm = p + confirmOff;
|
||||
|
||||
// A peer that regenerated its PQ material re-advertises its keys here. If
|
||||
// they differ from what we hold, our installed hybrid key is stale: the far
|
||||
// side is encapsulating to a public key we no longer have, or has rolled to
|
||||
// one we have never seen. Either way the two sides now derive different
|
||||
// keys and every data frame fails its MAC. Drop ours and re-arm before
|
||||
// answering, so the reply below carries a fresh ciphertext.
|
||||
bool renegotiating = peer->pqKeysChanged(p + 1, p + 1 + PQHybrid::MLKEM768_PK_LEN);
|
||||
if (renegotiating) {
|
||||
// A peer that rolled its PQ keys still holds ours, so it sets the ack
|
||||
// bit in this same message. Honouring it would immediately re-latch the
|
||||
// state we are clearing, so the ack is dropped for this exchange and
|
||||
// the reply below carries a fresh ciphertext.
|
||||
RR->t->peerPQKeysChanged(tPtr,source(),"peer re-advertised different PQ public keys");
|
||||
peer->resetPQExchange();
|
||||
}
|
||||
|
||||
const bool firstView = peer->setPQPublicKeys(p + 1, p + 1 + PQHybrid::MLKEM768_PK_LEN);
|
||||
if (peerHoldsOurKeys && (! renegotiating)) {
|
||||
// The peer sets this only once it already holds our key, so our half
|
||||
// is delivered and any ciphertext in this message reached it.
|
||||
peer->confirmPQKeys();
|
||||
}
|
||||
|
||||
if (RR->identity.address() < peer->identity().address()) {
|
||||
// Encapsulating side: now that we hold the peer's key, derive the
|
||||
// session key. The ciphertext rides in the reply below.
|
||||
peer->ensurePendingHybridCt();
|
||||
}
|
||||
|
||||
bool installedNow = false;
|
||||
if (haveCt && (peer->identity().address() < RR->identity.address()) && peer->hybridEligible()) {
|
||||
uint8_t hkey[ZT_SYMMETRIC_KEY_SIZE];
|
||||
if (RR->identity.agreeHybridDecaps(peer->identity(), p + minLen, hkey)) {
|
||||
peer->setHybridSessionKey(hkey);
|
||||
installedNow = true;
|
||||
}
|
||||
Utils::burn(hkey, sizeof(hkey));
|
||||
}
|
||||
|
||||
// A tag only proves agreement once we are both running the hybrid key.
|
||||
// Until our own key is installed we are still on the classical one, so a
|
||||
// peer that has not yet decapsulated legitimately tags with its classical
|
||||
// key and the two do not match. Treating that as a derivation failure
|
||||
// reset the exchange on every exchange and the pair never converged.
|
||||
// Mismatches only mean failure once we hold the hybrid key and the peer
|
||||
// should be deriving the same value.
|
||||
if (haveConfirm && peer->hybridSessionKeyInstalled() && (! peer->pqConfirmTagMatches(peerConfirm))) {
|
||||
// The peer derived a different session key than we did. With ML-KEM's
|
||||
// implicit rejection both sides get a well-formed but different key, so
|
||||
// this is the only point in the exchange where the disagreement is
|
||||
// observable. Reset rather than return: every data frame would otherwise
|
||||
// fail its MAC against a key the peer cannot derive, and the retry timer
|
||||
// that would repair it has already latched at the first handshake.
|
||||
RR->t->peerPQKeysChanged(tPtr,source(),"hybrid key confirmation failed, renegotiating");
|
||||
peer->resetPQExchange();
|
||||
peer->sendPQKeys(tPtr, RR->node->now());
|
||||
return true;
|
||||
}
|
||||
|
||||
// The encapsulating side holds its hybrid key staged rather than installed,
|
||||
// and only a matching tag proves the peer decapsulated to the same value.
|
||||
if (peer->pendingHybridKeyValid() && haveConfirm && peer->pqConfirmTagMatches(peerConfirm)) {
|
||||
peer->commitPendingHybridKey();
|
||||
}
|
||||
|
||||
// Decapsulating installs the hybrid key, but the tag that arrived was built
|
||||
// from the peer's classical key, so the peer still has no proof we derived
|
||||
// the same value. Answer once with a hybrid-keyed tag, otherwise the
|
||||
// encapsulator waits forever for a confirmation that never comes.
|
||||
if (installedNow) {
|
||||
peer->sendPQKeys(tPtr, RR->node->now());
|
||||
}
|
||||
|
||||
// A staged key still needs a confirming reply: the ack bit can latch from
|
||||
// an exchange that completed before either side derived the hybrid key, and
|
||||
// without this the staged key would wait forever for a tag nobody sends.
|
||||
if (firstView || renegotiating || (! peer->pqKeysAcked()) || peer->pendingHybridKeyValid()) {
|
||||
// Answer with our own keys. Once we hold the peer's, this reply also
|
||||
// carries the ack bit, so each side stops retrying after one exchange.
|
||||
peer->sendPQKeys(tPtr, RR->node->now());
|
||||
}
|
||||
|
||||
peer->received(tPtr,_path,hops(),packetId(),payloadLength(),Packet::VERB_PQ_KEYS,0,Packet::VERB_NOP,false,0,ZT_QOS_NO_FLOW);
|
||||
return true;
|
||||
}
|
||||
|
||||
void IncomingPacket::_sendErrorNeedCredentials(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer,const uint64_t nwid)
|
||||
{
|
||||
Packet outp(source(),RR->identity.address(),Packet::VERB_ERROR);
|
||||
|
||||
@@ -145,6 +145,7 @@ public:
|
||||
bool _doUSER_MESSAGE(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer);
|
||||
bool _doREMOTE_TRACE(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer);
|
||||
bool _doPATH_NEGOTIATION_REQUEST(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer);
|
||||
bool _doPQ_KEYS(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer);
|
||||
|
||||
void _sendErrorNeedCredentials(const RuntimeEnvironment *RR,void *tPtr,const SharedPtr<Peer> &peer,const uint64_t nwid);
|
||||
|
||||
|
||||
@@ -261,6 +261,20 @@ public:
|
||||
inline void operator()(Topology &t,const SharedPtr<Peer> &p)
|
||||
{
|
||||
const std::vector<InetAddress> *const alwaysContactEndpoints = _alwaysContact.get(p->address());
|
||||
// The PQ key exchange must not sit behind the ping guards below: a peer
|
||||
// that has completed a HELLO handshake but has no live path yet is exactly
|
||||
// the peer that still needs to be offered keys. Switch::send queues the
|
||||
// packet if no path exists, so this is safe to run unconditionally.
|
||||
//
|
||||
// The send itself is deferred to sendPQKeysNow() below. eachPeer holds
|
||||
// Topology::_peers_m for the whole iteration and Peer::sendPQKeys
|
||||
// reaches Switch::send -> Topology::getPeer, which takes that same
|
||||
// non-recursive lock, so calling it inline self-deadlocks the main
|
||||
// thread and stalls the control plane with it.
|
||||
if ((p->hybridCapable()) && (RR->node->pqcMode() != ZT_PQC_MODE_CLASSIC) && (RR->identity.hasPQ()) && p->pqKeysDue(_now)) {
|
||||
_pendingPQKeys.push_back(p);
|
||||
}
|
||||
|
||||
if (alwaysContactEndpoints) {
|
||||
|
||||
ZT_PeerRole role = RR->topology->role(p->address());
|
||||
@@ -314,12 +328,26 @@ public:
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send the PQ key offers collected during the peer iteration.
|
||||
*
|
||||
* Must be called after eachPeer() has released Topology::_peers_m.
|
||||
*/
|
||||
inline void sendPQKeysNow()
|
||||
{
|
||||
for(std::vector< SharedPtr<Peer> >::iterator p(_pendingPQKeys.begin());p!=_pendingPQKeys.end();++p) {
|
||||
(*p)->sendPQKeys(_tPtr,_now);
|
||||
}
|
||||
_pendingPQKeys.clear();
|
||||
}
|
||||
|
||||
private:
|
||||
const RuntimeEnvironment *RR;
|
||||
void *_tPtr;
|
||||
Hashtable< Address,std::vector<InetAddress> > &_alwaysContact;
|
||||
const int64_t _now;
|
||||
const SharedPtr<Peer> _bestCurrentUpstream;
|
||||
std::vector< SharedPtr<Peer> > _pendingPQKeys;
|
||||
};
|
||||
|
||||
ZT_ResultCode Node::processBackgroundTasks(void *tptr,int64_t now,volatile int64_t *nextBackgroundTaskDeadline)
|
||||
@@ -403,6 +431,10 @@ ZT_ResultCode Node::processBackgroundTasks(void *tptr,int64_t now,volatile int64
|
||||
_PingPeersThatNeedPing pfunc(RR,tptr,alwaysContact,now);
|
||||
RR->topology->eachPeer<_PingPeersThatNeedPing &>(pfunc);
|
||||
|
||||
// Topology::_peers_m is released here, so the deferred PQ key
|
||||
// offers can now go out without re-entering that lock.
|
||||
pfunc.sendPQKeysNow();
|
||||
|
||||
// Run WHOIS to create Peer for alwaysContact addresses that could not be contacted
|
||||
{
|
||||
Hashtable< Address,std::vector<InetAddress> >::Iterator i(alwaysContact);
|
||||
@@ -586,6 +618,12 @@ ZT_PeerList *Node::peers() const
|
||||
p->latency = -1;
|
||||
}
|
||||
p->role = RR->topology->role(pi->second->identity().address());
|
||||
p->pqcCapable = pi->second->hybridCapable();
|
||||
// "Active" must mean the hybrid key is installed, not merely that the
|
||||
// preconditions hold: the encapsulator derives its key before the peer
|
||||
// ever sees the ciphertext, so hybridEligible() reports True a full
|
||||
// round trip early and the decapsulator's failure goes unnoticed.
|
||||
p->pqcHybridActive = pi->second->hybridSessionKeyInstalled();
|
||||
|
||||
std::vector< SharedPtr<Path> > paths(pi->second->paths(_now));
|
||||
SharedPtr<Path> bestp(pi->second->getAppropriatePath(_now,false));
|
||||
|
||||
+16
-3
@@ -1085,14 +1085,27 @@ bool Packet::dearmor(const void *key,const AES aesKeys[2])
|
||||
tag[1] = *reinterpret_cast<uint64_t *>(data + ZT_PACKET_IDX_MAC);
|
||||
#endif
|
||||
|
||||
// GMAC-SIV decrypts in place, so a failed attempt would leave
|
||||
// garbage in the payload and make any retry on another key hash
|
||||
// ciphertext that no longer exists. Callers rely on being able to
|
||||
// retry -- HELLO, OK(HELLO) and PQ_KEYS stay armed with the
|
||||
// classical key while the session key is hybrid -- so decrypt to
|
||||
// scratch, authenticate it, and only then commit.
|
||||
uint8_t scratch[ZT_PROTO_MAX_PACKET_LENGTH];
|
||||
memcpy(scratch, payload, payloadLen);
|
||||
|
||||
AES::GMACSIVDecryptor dec(aesKeys[0],aesKeys[1]);
|
||||
dec.init(tag, payload);
|
||||
dec.init(tag, scratch);
|
||||
const uint8_t oldFlags = data[ZT_PACKET_IDX_FLAGS];
|
||||
data[ZT_PACKET_IDX_FLAGS] &= 0xf8;
|
||||
dec.aad(data + ZT_PACKET_IDX_DEST,11);
|
||||
data[ZT_PACKET_IDX_FLAGS] = oldFlags;
|
||||
dec.update(payload, payloadLen);
|
||||
return dec.finish();
|
||||
dec.update(scratch, payloadLen);
|
||||
if (!dec.finish()) {
|
||||
return false;
|
||||
}
|
||||
memcpy(payload, scratch, payloadLen);
|
||||
return true;
|
||||
}
|
||||
} else if ((cs == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_NONE)||(cs == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012)) {
|
||||
uint8_t mangledKey[32];
|
||||
|
||||
+49
-1
@@ -115,6 +115,24 @@
|
||||
*/
|
||||
#define ZT_KBKDF_LABEL_AES_GMAC_SIV_K1 '1'
|
||||
|
||||
/**
|
||||
* KBKDF label for the PQ_KEYS key-confirmation tag
|
||||
*
|
||||
* Distinct from every session-key label so the confirmation tag can never
|
||||
* collide with, or be derived from, material that protects traffic.
|
||||
*/
|
||||
#define ZT_KBKDF_LABEL_PQ_CONFIRM '2'
|
||||
|
||||
/**
|
||||
* Length of the PQ_KEYS key-confirmation tag, in bytes
|
||||
*
|
||||
* Four bytes of a key derived from the *hybrid* session key. It is not a
|
||||
* security boundary on its own; its only job is to let each side notice that
|
||||
* it derived a different session key than the peer did, which the exchange
|
||||
* otherwise cannot detect.
|
||||
*/
|
||||
#define ZT_PQ_KEYS_CONFIRM_LEN 4
|
||||
|
||||
/**
|
||||
* Cipher suite: NONE
|
||||
*
|
||||
@@ -272,6 +290,13 @@
|
||||
|
||||
#define ZT_PROTO_VERB_HELLO_REVISION_CAPABILITY_BIT 0x8000
|
||||
|
||||
/**
|
||||
* How often a peer re-offers its post-quantum public keys until the exchange
|
||||
* is confirmed. Bounds recovery from a lost VERB_PQ_KEYS without turning the
|
||||
* message into a periodic flood.
|
||||
*/
|
||||
#define ZT_PQ_KEYS_RETRY_INTERVAL 30000
|
||||
|
||||
#define ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB (ZT_PACKET_IDX_PAYLOAD)
|
||||
#define ZT_PROTO_VERB_ERROR_IDX_IN_RE_PACKET_ID (ZT_PROTO_VERB_ERROR_IDX_IN_RE_VERB + 1)
|
||||
#define ZT_PROTO_VERB_ERROR_IDX_ERROR_CODE (ZT_PROTO_VERB_ERROR_IDX_IN_RE_PACKET_ID + 8)
|
||||
@@ -1052,7 +1077,30 @@ public:
|
||||
* that as a refusal by the remote peer, in this case if the utility is
|
||||
* negligible it will voluntarily switch to the remote peer's chosen path.
|
||||
*/
|
||||
VERB_PATH_NEGOTIATION_REQUEST = 0x16
|
||||
VERB_PATH_NEGOTIATION_REQUEST = 0x16,
|
||||
|
||||
/**
|
||||
* Out-of-band post-quantum public key exchange (V13, BackOne extension).
|
||||
*
|
||||
* <[1] flags: bit0 = ML-KEM-768 ciphertext follows the public keys>
|
||||
* <[1184] ML-KEM-768 public key>
|
||||
* <[1952] ML-DSA-65 public key>
|
||||
* <[1088] optional ML-KEM-768 ciphertext>
|
||||
*
|
||||
* This is only ever sent to peers that advertised the PQC capability
|
||||
* bit in their HELLO revision field, so its payload may exceed the MTU.
|
||||
* It therefore travels as a normal Switch::send() packet and is
|
||||
* fragmented like a NETWORK_CONFIG. Peers not yet in PQ mode ignore it:
|
||||
* unknown verbs are answered with ERROR(BAD_PROTOCOL_VERSION).
|
||||
*
|
||||
* The identity in HELLO carries only the classic projection, so this
|
||||
* message is the sole source of a peer's PQ public keys. The lowest
|
||||
* address of the pair encapsulates to the other side's ML-KEM-768 key
|
||||
* and includes the ciphertext here, so exactly one round trip completes
|
||||
* the exchange. The receiving side never needs an ephemeral key:
|
||||
* ML-KEM decapsulation consumes only its own secret key and the ct.
|
||||
*/
|
||||
VERB_PQ_KEYS = 0x17
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
+127
-13
@@ -78,7 +78,15 @@ Peer::Peer(const RuntimeEnvironment *renv,const Identity &myIdentity,const Ident
|
||||
memcpy(_keyClassical, _key, sizeof(_keyClassical));
|
||||
memcpy(_aesKeysClassical, _aesKeys, sizeof(_aesKeysClassical));
|
||||
_hybridCapable = false;
|
||||
_pqKeysValid = false;
|
||||
_pqKeysSent = false;
|
||||
_pqKeysAcked = false;
|
||||
_pqKeysStale = false;
|
||||
_lastPQKeysSentAt = 0;
|
||||
_pendingHybridCtValid = 0;
|
||||
_pendingHybridKeyValid = 0;
|
||||
memset(_pendingHybridKey, 0, sizeof(_pendingHybridKey));
|
||||
_hybridSessionKeyInstalled = false;
|
||||
}
|
||||
|
||||
void Peer::_initAesKeys(const uint8_t* key, AES aesKeys[2])
|
||||
@@ -95,6 +103,7 @@ void Peer::setHybridSessionKey(const void* key)
|
||||
{
|
||||
memcpy(_key, key, ZT_SYMMETRIC_KEY_SIZE);
|
||||
_initAesKeys(_key, _aesKeys);
|
||||
_hybridSessionKeyInstalled = true;
|
||||
}
|
||||
|
||||
void Peer::setPendingHybridCt(const void* ct)
|
||||
@@ -103,6 +112,44 @@ void Peer::setPendingHybridCt(const void* ct)
|
||||
_pendingHybridCtValid = 1;
|
||||
}
|
||||
|
||||
|
||||
void Peer::setPendingHybridKey(const void* key)
|
||||
{
|
||||
memcpy(_pendingHybridKey, key, ZT_SYMMETRIC_KEY_SIZE);
|
||||
_pendingHybridKeyValid = 1;
|
||||
}
|
||||
|
||||
void Peer::commitPendingHybridKey()
|
||||
{
|
||||
if (_pendingHybridKeyValid) {
|
||||
setHybridSessionKey(_pendingHybridKey);
|
||||
_pendingHybridKeyValid = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void Peer::dropPendingHybridKey()
|
||||
{
|
||||
Utils::burn(_pendingHybridKey, sizeof(_pendingHybridKey));
|
||||
_pendingHybridKeyValid = 0;
|
||||
}
|
||||
|
||||
bool Peer::setPQPublicKeys(const uint8_t* mlkemPk, const uint8_t* mldsaPk)
|
||||
{
|
||||
// True when this is material we had not seen before, so the caller knows
|
||||
// to answer with its own keys.
|
||||
const bool firstView = (!_pqKeysValid);
|
||||
memcpy(_pqMlkemPk, mlkemPk, PQHybrid::MLKEM768_PK_LEN);
|
||||
memcpy(_pqMldsaPk, mldsaPk, PQHybrid::MLDSA65_PK_LEN);
|
||||
_pqKeysValid = true;
|
||||
// Keep the peer's Identity itself complete, not just these crypto caches:
|
||||
// anything that verifies a type 2 COM reads the controller's identity back
|
||||
// through Topology::getIdentity(), which hands out peer->identity(). HELLO
|
||||
// only carries the classic projection, so without this the controller stays
|
||||
// type 0 here and its signatures never verify.
|
||||
_id.attachPQPublicKeys(mlkemPk, mldsaPk);
|
||||
return firstView;
|
||||
}
|
||||
|
||||
void Peer::ensurePendingHybridCt()
|
||||
{
|
||||
if ((_pendingHybridCtValid) || (! hybridEligible()) || (RR->identity.address() >= _id.address())) {
|
||||
@@ -110,9 +157,14 @@ void Peer::ensurePendingHybridCt()
|
||||
}
|
||||
uint8_t ct[PQHybrid::MLKEM768_CT_LEN];
|
||||
uint8_t hkey[ZT_SYMMETRIC_KEY_SIZE];
|
||||
if (RR->identity.agreeHybridEncaps(_id, ct, hkey)) {
|
||||
if (RR->identity.agreeHybridEncaps(_id, _pqMlkemPk, ct, hkey)) {
|
||||
setPendingHybridCt(ct);
|
||||
setHybridSessionKey(hkey);
|
||||
// Staged, not installed: the far side derives this same key only once
|
||||
// the ciphertext reaches it. Installing now would armor outgoing data
|
||||
// frames with a key the peer cannot yet reproduce, so those frames
|
||||
// fail its MAC. commitPendingHybridKey() runs once the peer's confirm
|
||||
// tag proves it derived the same value.
|
||||
setPendingHybridKey(hkey);
|
||||
}
|
||||
Utils::burn(hkey, sizeof(hkey));
|
||||
}
|
||||
@@ -470,7 +522,9 @@ void Peer::sendHELLO(void *tPtr,const int64_t localSocket,const InetAddress &atA
|
||||
outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
|
||||
outp.append((uint16_t)(ZEROTIER_ONE_VERSION_REVISION | ((RR->node->pqcMode() != ZT_PQC_MODE_CLASSIC) ? ZT_PROTO_VERB_HELLO_REVISION_CAPABILITY_BIT : 0)));
|
||||
outp.append(now);
|
||||
RR->identity.serialize(outp, false);
|
||||
// Classic projection only: a vanilla ZeroTier peer must be able to parse
|
||||
// this HELLO. PQ public keys go out in VERB_PQ_KEYS instead.
|
||||
RR->identity.serializeClassic(outp);
|
||||
atAddress.serialize(outp);
|
||||
|
||||
outp.append((uint64_t)RR->topology->planetWorldId());
|
||||
@@ -492,16 +546,8 @@ void Peer::sendHELLO(void *tPtr,const int64_t localSocket,const InetAddress &atA
|
||||
outp.append((uint64_t)0);
|
||||
}
|
||||
|
||||
const bool sendHybridCt = (hybridEligible() && (RR->identity.address() < _id.address()));
|
||||
if (sendHybridCt) {
|
||||
// Lowest address encapsulates. One ct per attempt, re-encapsulated only
|
||||
// while the peer has not yet confirmed the previous one.
|
||||
ensurePendingHybridCt();
|
||||
if (_pendingHybridCtValid) {
|
||||
outp.append((uint8_t)1); // hybrid ciphertext present
|
||||
outp.append(_pendingHybridCt, PQHybrid::MLKEM768_CT_LEN);
|
||||
}
|
||||
}
|
||||
// The hybrid ciphertext is not carried here -- it would push HELLO past
|
||||
// the MTU. It rides in VERB_PQ_KEYS once the peer is known capable.
|
||||
|
||||
outp.cryptField(_keyClassical, startCryptedPortionAt, outp.size() - startCryptedPortionAt);
|
||||
}
|
||||
@@ -523,6 +569,73 @@ void Peer::sendHELLO(void *tPtr,const int64_t localSocket,const InetAddress &atA
|
||||
RR->node->expectReplyTo(outp.packetId());
|
||||
RR->sw->send(tPtr,outp,false); // false == don't encrypt full payload, but add MAC
|
||||
}
|
||||
|
||||
// A capable peer learns our PQ public keys out of band (VERB_PQ_KEYS), since
|
||||
// they do not fit in HELLO. Driven from the peer timer rather than from
|
||||
// sendHELLO: HELLO always carries a concrete address, so an address-based
|
||||
// gate there never fires.
|
||||
|
||||
}
|
||||
|
||||
void Peer::sendPQKeys(void *tPtr,int64_t now)
|
||||
{
|
||||
Packet outp(_id.address(),RR->identity.address(),Packet::VERB_PQ_KEYS);
|
||||
|
||||
try {
|
||||
// The lowest address encapsulates; the other side derives the same key
|
||||
// from its own secret when the ciphertext arrives. Neither side needs an
|
||||
// ephemeral key: ML-KEM decapsulation consumes only sk and ct.
|
||||
bool haveCt = false;
|
||||
if (RR->identity.address() < _id.address()) {
|
||||
ensurePendingHybridCt();
|
||||
haveCt = _pendingHybridCtValid;
|
||||
}
|
||||
|
||||
|
||||
// Bit 0: we are the encapsulating side and carry a ciphertext.
|
||||
// Bit 1: we already hold the peer's keys, so this doubles as the
|
||||
// acknowledgement that ends its retry; without it both sides keep
|
||||
// re-offering forever. Both bits ride in one byte because the receiver
|
||||
// parses the keys from a fixed offset after it.
|
||||
outp.append((uint8_t)((haveCt ? 0x01 : 0x00) | (_pqKeysValid ? 0x02 : 0x00)));
|
||||
|
||||
uint8_t mlkemPk[PQHybrid::MLKEM768_PK_LEN];
|
||||
uint8_t mldsaPk[PQHybrid::MLDSA65_PK_LEN];
|
||||
RR->identity.pqKemKey(mlkemPk);
|
||||
RR->identity.pqSigKey(mldsaPk);
|
||||
outp.append(mlkemPk, sizeof(mlkemPk));
|
||||
outp.append(mldsaPk, sizeof(mldsaPk));
|
||||
if (haveCt) {
|
||||
outp.append(_pendingHybridCt, PQHybrid::MLKEM768_CT_LEN);
|
||||
}
|
||||
|
||||
// Key confirmation, appended last so its position is unambiguous and a
|
||||
// shorter packet from an older build still parses. This is what makes a
|
||||
// mismatched derivation detectable: ML-KEM's implicit rejection gives
|
||||
// both sides a well-formed but different key, and every later data frame
|
||||
// fails its MAC with no other signal that renegotiation is needed.
|
||||
uint8_t confirm[ZT_PQ_KEYS_CONFIRM_LEN];
|
||||
pqConfirmTag(confirm);
|
||||
outp.append(confirm, sizeof(confirm));
|
||||
|
||||
// Exceeds the MTU by design; Switch::send fragments it like a
|
||||
// NETWORK_CONFIG. Armored with the classical key so it is readable
|
||||
// before either side has switched to the hybrid session key.
|
||||
// FLAGS is AAD-covered, so the FRAGMENTED bit must be set here,
|
||||
// before armor() computes the MAC -- Switch::_sendViaSpecificPath
|
||||
// cannot set it on an already-armored packet without invalidating it.
|
||||
outp.setFragmented(true);
|
||||
outp.armor(_keyClassical, true, _aesKeysClassical);
|
||||
}
|
||||
catch (int e) {
|
||||
// Buffer overflow would kill the daemon via catch(int) in
|
||||
// OneServiceImpl::run(); degrade to a skipped exchange.
|
||||
return;
|
||||
}
|
||||
|
||||
RR->node->expectReplyTo(outp.packetId());
|
||||
RR->sw->send(tPtr, outp, true);
|
||||
setPQKeysSent(RR->node->now());
|
||||
}
|
||||
|
||||
void Peer::attemptToContactAt(void *tPtr,const int64_t localSocket,const InetAddress &atAddress,int64_t now,bool sendFullHello)
|
||||
@@ -664,6 +777,7 @@ unsigned int Peer::doPingAndKeepalive(void *tPtr,int64_t now)
|
||||
#ifndef ZT_NO_PEER_METRICS
|
||||
_peer_latency.Observe(latency(now));
|
||||
#endif
|
||||
|
||||
return sent;
|
||||
}
|
||||
|
||||
|
||||
+261
-7
@@ -43,6 +43,40 @@
|
||||
|
||||
namespace ZeroTier {
|
||||
|
||||
|
||||
/**
|
||||
* Confirmation tag proving two peers derived the same hybrid session key
|
||||
*
|
||||
* ML-KEM uses implicit rejection: decapsulating a ciphertext with a secret key
|
||||
* that does not match the peer's public key yields a well-formed but wrong
|
||||
* shared secret instead of an error. Neither side can therefore distinguish a
|
||||
* genuine agreement from a mismatched one, and a mismatch leaves every data
|
||||
* frame failing its MAC with no signal that renegotiation is needed.
|
||||
*
|
||||
* The MAC input must be identical on both sides. Binding to the remote address
|
||||
* alone is asymmetric -- we would compute HMAC(key, peer) while the peer
|
||||
* computes HMAC(key, us) -- so a session with genuinely matching keys would
|
||||
* still fail confirmation and renegotiate forever. Both addresses are ordered
|
||||
* before use, which makes the input symmetric without a second round trip.
|
||||
*
|
||||
* @param key Installed session key (hybrid if present, else classical)
|
||||
* @param localAddr This node's address
|
||||
* @param remoteAddr Peer's address
|
||||
* @param out Buffer of ZT_PQ_KEYS_CONFIRM_LEN bytes
|
||||
*/
|
||||
inline void pqConfirmTagFor(const void *key,const Address &localAddr,const Address &remoteAddr,uint8_t *out)
|
||||
{
|
||||
const uint64_t a = localAddr.toInt(), b = remoteAddr.toInt();
|
||||
uint8_t buf[16];
|
||||
memcpy(buf, (a < b) ? &a : &b, 8);
|
||||
memcpy(buf + 8, (a < b) ? &b : &a, 8);
|
||||
uint8_t mac[48];
|
||||
HMACSHA384((const uint8_t *)key, buf, sizeof(buf), mac);
|
||||
memcpy(out, mac, ZT_PQ_KEYS_CONFIRM_LEN);
|
||||
Utils::burn(mac, sizeof(mac));
|
||||
Utils::burn(buf, sizeof(buf));
|
||||
}
|
||||
|
||||
/**
|
||||
* Peer on P2P Network (virtual layer 1)
|
||||
*/
|
||||
@@ -392,11 +426,12 @@ public:
|
||||
{ return ((now - _lastTrustEstablishedPacketReceived) < ZT_TRUST_EXPIRATION); }
|
||||
|
||||
/**
|
||||
* @return True if the peer is both known to be PQC-capable and we are
|
||||
* currently in a non-classic mode, i.e. hybrid key agreement applies.
|
||||
* @return True if the peer advertised the PQC capability, we are in a
|
||||
* non-classic mode, we hold PQ keys, and we have received the peer's PQ
|
||||
* public keys -- i.e. hybrid key agreement can actually run.
|
||||
*/
|
||||
inline bool hybridEligible() const
|
||||
{ return ((RR->node->pqcMode() != ZT_PQC_MODE_CLASSIC) && (_hybridCapable) && (RR->identity.hasPQ())); }
|
||||
{ return ((RR->node->pqcMode() != ZT_PQC_MODE_CLASSIC) && (_hybridCapable) && (RR->identity.hasPQ()) && _pqKeysValid); }
|
||||
|
||||
/**
|
||||
* Rate limit gate for VERB_PUSH_DIRECT_PATHS
|
||||
@@ -651,8 +686,49 @@ public:
|
||||
void setHybridSessionKey(const void* key);
|
||||
|
||||
/**
|
||||
* Store a freshly created hybrid ciphertext to be echoed in HELLO/OK.
|
||||
* The encapsulating (lowest address) side owns this until confirmation.
|
||||
* Stage the hybrid session key derived by encapsulation, without
|
||||
* installing it. The far side derives the same value only after the
|
||||
* ciphertext arrives, so arming data frames before then would armor
|
||||
* them with a key its MAC check cannot reproduce.
|
||||
*/
|
||||
void setPendingHybridKey(const void* key);
|
||||
|
||||
/**
|
||||
* Install the staged key once the peer's confirm tag proves it derived
|
||||
* the same value. No-op when nothing is staged.
|
||||
*/
|
||||
void commitPendingHybridKey();
|
||||
|
||||
/**
|
||||
* Discard a staged key without installing it, and zero the buffer.
|
||||
*/
|
||||
void dropPendingHybridKey();
|
||||
|
||||
/**
|
||||
* @return True once the hybrid session key is actually installed
|
||||
*
|
||||
* Distinct from hybridEligible(), which only reports the preconditions
|
||||
* (peer advertised the bit, we are non-classic, we hold its PQ public
|
||||
* keys). Eligible is true a full round trip before the key exists, so
|
||||
* reporting it as "hybrid active" claims protection that is not in use.
|
||||
*/
|
||||
inline bool hybridSessionKeyInstalled() const
|
||||
{ return _hybridSessionKeyInstalled; }
|
||||
|
||||
inline bool pendingHybridKeyValid() const
|
||||
{ return _pendingHybridKeyValid != 0; }
|
||||
|
||||
/**
|
||||
* @return True if this side of the exchange owns the ML-KEM ciphertext
|
||||
* (the lower of the two addresses encapsulates)
|
||||
*/
|
||||
inline bool hybridEncapsulator() const
|
||||
{ return (RR->identity.address() < _id.address()); }
|
||||
|
||||
/**
|
||||
* Store a freshly created hybrid ciphertext to be echoed in
|
||||
* Packet::VERB_PQ_KEYS. The encapsulating (lowest address) side owns this
|
||||
* until confirmation.
|
||||
*/
|
||||
void setPendingHybridCt(const void* ct);
|
||||
|
||||
@@ -663,6 +739,169 @@ public:
|
||||
*/
|
||||
void ensurePendingHybridCt();
|
||||
|
||||
/**
|
||||
* Install this peer's post-quantum public keys, learned from
|
||||
* Packet::VERB_PQ_KEYS.
|
||||
*
|
||||
* These are kept beside _id rather than merged into it: the identity in
|
||||
* HELLO is the classic projection, so a peer identity learned from the wire
|
||||
* never carries PQ material. Mutating it would break Identity::operator==
|
||||
* and re-create the Peer on every subsequent HELLO.
|
||||
*
|
||||
* @return True if these keys were not already held (first view)
|
||||
*/
|
||||
bool setPQPublicKeys(const uint8_t* mlkemPk, const uint8_t* mldsaPk);
|
||||
|
||||
/**
|
||||
* Send our post-quantum public keys to this peer in VERB_PQ_KEYS, plus the
|
||||
* hybrid ciphertext if we are the encapsulating (lowest address) side.
|
||||
*
|
||||
* Only call this for a peer that advertised the PQC capability bit; the
|
||||
* message is larger than the MTU and older peers cannot parse the verb.
|
||||
*/
|
||||
void sendPQKeys(void *tPtr,int64_t now);
|
||||
|
||||
/**
|
||||
* Confirmation tag proving we derived the same hybrid key as the peer
|
||||
*
|
||||
* ML-KEM uses implicit rejection: decapsulating a ciphertext with the wrong
|
||||
* secret key returns a well-formed but wrong shared secret rather than an
|
||||
* error. Neither side can therefore tell a genuine agreement from a
|
||||
* mismatched one, and a mismatch leaves every data frame failing its MAC
|
||||
* with no way to renegotiate. This tag is derived from the *installed*
|
||||
* session key, so the two sides' tags agree only when their keys do.
|
||||
*
|
||||
* Falls back to the classical key when no hybrid key is installed, which
|
||||
* is the correct tag for a session still in classic mode.
|
||||
*
|
||||
* The MAC input is symmetric in the two addresses (see below), so both
|
||||
* sides compute the same tag from the same key.
|
||||
*
|
||||
* @param out Buffer of ZT_PQ_KEYS_CONFIRM_LEN bytes
|
||||
*/
|
||||
void pqConfirmTag(uint8_t* out) const
|
||||
{
|
||||
// The encapsulating side has the hybrid key staged but not installed,
|
||||
// so tagging from _key here would MAC the classical key and never match
|
||||
// what the peer derives. Prefer the staged value when one exists.
|
||||
const void *k = _pendingHybridKeyValid ? (const void *)_pendingHybridKey : (const void *)_key;
|
||||
pqConfirmTagFor(k, RR->identity.address(), _id.address(), out);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check a peer's confirmation tag against our own derived key
|
||||
*
|
||||
* @return True if the peer derived the same session key we did
|
||||
*/
|
||||
inline bool pqConfirmTagMatches(const uint8_t* peerTag) const
|
||||
{
|
||||
uint8_t ours[ZT_PQ_KEYS_CONFIRM_LEN];
|
||||
pqConfirmTag(ours);
|
||||
return Utils::secureEq(ours, peerTag, ZT_PQ_KEYS_CONFIRM_LEN);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return This peer's ML-KEM-768 public key, or NULL if not yet learned
|
||||
*/
|
||||
inline const uint8_t* pqMlkemPk() const
|
||||
{ return (_pqKeysValid) ? _pqMlkemPk : (const uint8_t*)0; }
|
||||
|
||||
/**
|
||||
* @return True if we have already sent our PQ public keys to this peer
|
||||
*/
|
||||
inline bool pqKeysSent() const
|
||||
{ return _pqKeysSent; }
|
||||
|
||||
/**
|
||||
* @return True if the peer has confirmed holding our PQ public keys
|
||||
*
|
||||
* Set only from the acknowledgement bit in a VERB_PQ_KEYS the peer sent
|
||||
* after it already held our keys. Distinct from _pqKeysValid, which says
|
||||
* nothing about what the peer knows.
|
||||
*/
|
||||
inline bool pqKeysAcked() const
|
||||
{ return _pqKeysAcked; }
|
||||
|
||||
/**
|
||||
* @return True if it is time to (re)offer our PQ public keys
|
||||
*
|
||||
* A one-shot send would blackhole the session forever if the message were
|
||||
* lost, so we re-offer on a timer until the peer acknowledges. The latch
|
||||
* clears again if the peer's advertised PQ keys change underneath us, which
|
||||
* is the signature of a peer that regenerated its PQ material (restore from
|
||||
* backup, identity roll). See resetPQExchange().
|
||||
*/
|
||||
inline bool pqKeysDue(const int64_t now) const
|
||||
{ return ((! _pqKeysAcked) || _pqKeysStale) && ((now - _lastPQKeysSentAt) >= ZT_PQ_KEYS_RETRY_INTERVAL); }
|
||||
|
||||
/**
|
||||
* Arm the retry timer for a send we are about to make.
|
||||
*/
|
||||
inline void setPQKeysSent(const int64_t now)
|
||||
{
|
||||
_pqKeysSent = true;
|
||||
_lastPQKeysSentAt = now;
|
||||
}
|
||||
|
||||
/**
|
||||
* Record that the peer acknowledged our keys.
|
||||
*/
|
||||
inline void confirmPQKeys()
|
||||
{ _pqKeysAcked = true; _pqKeysStale = false; }
|
||||
|
||||
/**
|
||||
* Drop the hybrid session key and re-arm the PQ exchange.
|
||||
*
|
||||
* Called when our view of the peer's PQ material no longer matches what the
|
||||
* peer believes. A Peer object outlives a key rotation on the far side, so
|
||||
* without this the session keeps using a key the peer cannot derive: every
|
||||
* data frame fails its MAC, and because _pqKeysAcked latched at the first
|
||||
* handshake the retry timer never fires again. The only recovery is a
|
||||
* daemon restart on one side.
|
||||
*
|
||||
* Hybrid status is deliberately not restored here. _key reverts to the
|
||||
* classical key and the exchange re-runs from scratch. That is safe in both
|
||||
* directions: the peer keeps its hybrid key until it hears a new offer, and
|
||||
* the inbound path already tries the hybrid key before the classical one
|
||||
* (IncomingPacket.cpp), so nothing that was working stops working.
|
||||
*/
|
||||
inline void resetPQExchange()
|
||||
{
|
||||
if (_hybridSessionKeyInstalled) {
|
||||
memcpy(_key, _keyClassical, ZT_SYMMETRIC_KEY_SIZE);
|
||||
_initAesKeys(_key, _aesKeys);
|
||||
_hybridSessionKeyInstalled = false;
|
||||
}
|
||||
_pqKeysAcked = false;
|
||||
_pqKeysStale = true;
|
||||
_pqKeysSent = false;
|
||||
_pendingHybridCtValid = 0;
|
||||
dropPendingHybridKey();
|
||||
_lastPQKeysSentAt = 0; // due again on the next HELLO
|
||||
}
|
||||
|
||||
/**
|
||||
* @return True if this peer's PQ public keys differ from the ones we hold
|
||||
*
|
||||
* A peer's HELLO carries only the classic projection of its identity, so a
|
||||
* PQ key rotation is invisible there. The keys arrive in VERB_PQ_KEYS, and a
|
||||
* rotation re-advertises them; comparing against what we installed is the
|
||||
* only way to notice. False on the first view, which is not a change.
|
||||
*/
|
||||
inline bool pqKeysChanged(const uint8_t* mlkemPk, const uint8_t* mldsaPk) const
|
||||
{
|
||||
if (! _pqKeysValid) {
|
||||
return false;
|
||||
}
|
||||
return ((memcmp(_pqMlkemPk,mlkemPk,PQHybrid::MLKEM768_PK_LEN) != 0) || (memcmp(_pqMldsaPk,mldsaPk,PQHybrid::MLDSA65_PK_LEN) != 0));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return True if the peer advertised the PQC capability bit in its HELLO
|
||||
*/
|
||||
inline bool hybridCapable() const
|
||||
{ return _hybridCapable; }
|
||||
|
||||
/**
|
||||
* Copy the pending hybrid ciphertext into out if one is queued.
|
||||
*
|
||||
@@ -695,10 +934,25 @@ public:
|
||||
AES _aesKeysClassical[2];
|
||||
bool _hybridCapable;
|
||||
|
||||
// Lowest-address side encapsulates once per attempt; its ct is echoed in
|
||||
// every HELLO/OK(HELLO) until the peer confirms the hybrid key.
|
||||
// Peer's PQ public keys, learned out of band via VERB_PQ_KEYS. NULL until
|
||||
// then; PQ mode does not run until both halves are known.
|
||||
uint8_t _pqMlkemPk[PQHybrid::MLKEM768_PK_LEN];
|
||||
uint8_t _pqMldsaPk[PQHybrid::MLDSA65_PK_LEN];
|
||||
bool _pqKeysValid;
|
||||
bool _pqKeysSent;
|
||||
bool _pqKeysAcked;
|
||||
bool _pqKeysStale;
|
||||
int64_t _lastPQKeysSentAt;
|
||||
|
||||
// Lowest-address side encapsulates once per attempt; its ct rides in
|
||||
// VERB_PQ_KEYS until the peer confirms the hybrid key.
|
||||
uint8_t _pendingHybridCt[PQHybrid::MLKEM768_CT_LEN];
|
||||
unsigned int _pendingHybridCtValid;
|
||||
// Key derived alongside _pendingHybridCt, held back until the peer's
|
||||
// confirm tag shows it derived the same value.
|
||||
uint8_t _pendingHybridKey[ZT_SYMMETRIC_KEY_SIZE];
|
||||
unsigned int _pendingHybridKeyValid;
|
||||
bool _hybridSessionKeyInstalled;
|
||||
AES _aesKeys[2];
|
||||
const RuntimeEnvironment *RR;
|
||||
|
||||
|
||||
@@ -333,6 +333,11 @@ void Trace::incomingPacketInvalid(void *const tPtr,const SharedPtr<Path> &path,c
|
||||
}
|
||||
}
|
||||
|
||||
void Trace::peerPQKeysChanged(void *const tPtr,const Address &peer,const char *reason)
|
||||
{
|
||||
ZT_LOCAL_TRACE(tPtr,RR,"PQ keys changed for peer %.10llx (%s): renegotiating hybrid session key",peer.toInt(),(reason) ? reason : "unknown reason");
|
||||
}
|
||||
|
||||
void Trace::incomingPacketDroppedHELLO(void *const tPtr,const SharedPtr<Path> &path,const uint64_t packetId,const Address &source,const char *reason)
|
||||
{
|
||||
char tmp[128];
|
||||
|
||||
@@ -116,6 +116,7 @@ public:
|
||||
|
||||
void incomingPacketMessageAuthenticationFailure(void *const tPtr,const SharedPtr<Path> &path,const uint64_t packetId,const Address &source,const unsigned int hops,const char *reason);
|
||||
void incomingPacketInvalid(void *const tPtr,const SharedPtr<Path> &path,const uint64_t packetId,const Address &source,const unsigned int hops,const Packet::Verb verb,const char *reason);
|
||||
void peerPQKeysChanged(void *const tPtr,const Address &peer,const char *reason);
|
||||
void incomingPacketDroppedHELLO(void *const tPtr,const SharedPtr<Path> &path,const uint64_t packetId,const Address &source,const char *reason);
|
||||
|
||||
void outgoingNetworkFrameDropped(void *const tPtr,const SharedPtr<Network> &network,const MAC &sourceMac,const MAC &destMac,const unsigned int etherType,const unsigned int vlanId,const unsigned int frameLen,const char *reason);
|
||||
|
||||
+227
-42
@@ -810,6 +810,48 @@ static int testCertificate()
|
||||
std::cout << "PASS" << std::endl;
|
||||
}
|
||||
|
||||
// A controller holds the member's full identity (type 1) but only ever sees
|
||||
// the classic projection over HELLO (Identity::serializeClassic). It must
|
||||
// compare members with sameClassicalIdentity(), not operator==, or every PQ
|
||||
// member is denied with ACCESS_DENIED.
|
||||
std::cout << "[certificate] Controller match accepts PQ member seen as classic... ";
|
||||
{
|
||||
Identity pqMember;
|
||||
pqMember.generate(true, 1);
|
||||
|
||||
// What the controller persists for that member.
|
||||
Buffer<8192> full;
|
||||
pqMember.serialize(full, false);
|
||||
|
||||
// What arrives from the wire: the classic projection only.
|
||||
Buffer<8192> classic;
|
||||
pqMember.serializeClassic(classic);
|
||||
Identity wireIdentity;
|
||||
wireIdentity.deserialize(classic, 0);
|
||||
|
||||
if ((! pqMember.hasPQ()) || (wireIdentity.hasPQ())) {
|
||||
std::cout << "FAIL (setup)" << std::endl;
|
||||
return -1;
|
||||
}
|
||||
// The defect: operator== compares PQ material, which HELLO never carries.
|
||||
if (wireIdentity == pqMember) {
|
||||
std::cout << "FAIL (operator== should differ)" << std::endl;
|
||||
return -1;
|
||||
}
|
||||
if (! wireIdentity.sameClassicalIdentity(pqMember)) {
|
||||
std::cout << "FAIL" << std::endl;
|
||||
return -1;
|
||||
}
|
||||
// A different member at the same address must still be rejected.
|
||||
Identity impostor;
|
||||
impostor.generate(true, 0);
|
||||
if (wireIdentity.sameClassicalIdentity(impostor)) {
|
||||
std::cout << "FAIL (accepted impostor)" << std::endl;
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
std::cout << "PASS" << std::endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -1592,8 +1634,6 @@ static int testPQ()
|
||||
static const char* kdfOutHex = "705132e627d21f2501ca93906da0a3ddf752e79a56dd23cfc4ceb63bcee83171"
|
||||
"744014dda6c1639a7a47335f2c04be8c";
|
||||
|
||||
unsigned char buf[PQHybrid::MLDSA65_PK_LEN + PQHybrid::MLDSA65_SIG_LEN + 64];
|
||||
|
||||
// 1. ML-KEM-768 KAT: decaps(sk, ct) must reproduce the shared secret.
|
||||
std::cout << "[PQ] ML-KEM KAT (decaps fixed sk/ct -> ss)... ";
|
||||
std::cout.flush();
|
||||
@@ -1672,17 +1712,30 @@ static int testPQ()
|
||||
unsigned char ict[PQHybrid::MLKEM768_CT_LEN];
|
||||
unsigned char ik1[ZT_SYMMETRIC_KEY_SIZE];
|
||||
unsigned char ik2[ZT_SYMMETRIC_KEY_SIZE];
|
||||
// PQ material now arrives out of band in VERB_PQ_KEYS, so the exchange is
|
||||
// driven by the peer's advertised ML-KEM public key rather than by a type 1
|
||||
// identity carried in HELLO. Pull the keys straight off the identities --
|
||||
// that is exactly the payload VERB_PQ_KEYS carries.
|
||||
Identity::PQKeys h1keys, h2keys;
|
||||
if ((! idH1.pqPublicKeys(h1keys)) || (! idH2.pqPublicKeys(h2keys))) {
|
||||
std::cout << "FAIL (ML-KEM public keys)" << std::endl;
|
||||
return -1;
|
||||
}
|
||||
const unsigned char *h1mlkempk = h1keys.mlkemPk;
|
||||
const unsigned char *h2mlkempk = h2keys.mlkemPk;
|
||||
// hybrid<->hybrid: encaps/decaps agree with matching keys, both directions.
|
||||
if ((! idH1.agreeHybridEncaps(idH2, ict, ik1)) || (! idH2.agreeHybridDecaps(idH1, ict, ik2)) || (memcmp(ik1, ik2, sizeof(ik1)))) {
|
||||
if ((! idH1.agreeHybridEncaps(idH2, h2mlkempk, ict, ik1)) || (! idH2.agreeHybridDecaps(idH1, ict, ik2)) || (memcmp(ik1, ik2, sizeof(ik1)))) {
|
||||
std::cout << "FAIL (hybrid 1->2)" << std::endl;
|
||||
return -1;
|
||||
}
|
||||
if ((! idH2.agreeHybridEncaps(idH1, ict, ik1)) || (! idH1.agreeHybridDecaps(idH2, ict, ik2)) || (memcmp(ik1, ik2, sizeof(ik1)))) {
|
||||
if ((! idH2.agreeHybridEncaps(idH1, h1mlkempk, ict, ik1)) || (! idH1.agreeHybridDecaps(idH2, ict, ik2)) || (memcmp(ik1, ik2, sizeof(ik1)))) {
|
||||
std::cout << "FAIL (hybrid 2->1)" << std::endl;
|
||||
return -1;
|
||||
}
|
||||
// hybrid local -> vanilla peer: encaps refused; classic fallback agrees both ways.
|
||||
if (idH1.agreeHybridEncaps(idV1, ict, ik1)) {
|
||||
// hybrid local -> vanilla peer: encaps refused (no PQ private key); classic
|
||||
// fallback still agrees both ways, which is what keeps a PQ node reachable
|
||||
// from vanilla roots.
|
||||
if (idH1.agreeHybridEncaps(idV1, NULL, ict, ik1)) {
|
||||
std::cout << "FAIL (encaps to vanilla accepted)" << std::endl;
|
||||
return -1;
|
||||
}
|
||||
@@ -1690,17 +1743,18 @@ static int testPQ()
|
||||
std::cout << "FAIL (classic fallback PQ<->vanilla)" << std::endl;
|
||||
return -1;
|
||||
}
|
||||
// vanilla local: decaps refused; encaps toward PQ peer works (gate: private + peer type 1).
|
||||
// vanilla local: decaps refused (no PQ private key); encaps toward a PQ peer
|
||||
// works, because the PQ key comes from VERB_PQ_KEYS, not from the identity.
|
||||
if (idV1.agreeHybridDecaps(idH1, ict, ik2)) {
|
||||
std::cout << "FAIL (vanilla decaps accepted)" << std::endl;
|
||||
return -1;
|
||||
}
|
||||
if ((! idV1.agreeHybridEncaps(idH1, ict, ik1)) || (! idH1.agreeHybridDecaps(idV1, ict, ik2)) || (memcmp(ik1, ik2, sizeof(ik1)))) {
|
||||
if ((! idV1.agreeHybridEncaps(idH1, h1mlkempk, ict, ik1)) || (! idH1.agreeHybridDecaps(idV1, ict, ik2)) || (memcmp(ik1, ik2, sizeof(ik1)))) {
|
||||
std::cout << "FAIL (vanilla->PQ hybrid)" << std::endl;
|
||||
return -1;
|
||||
}
|
||||
// vanilla<->vanilla: hybrid refused both roles; classic agrees.
|
||||
if ((idV1.agreeHybridEncaps(idV2, ict, ik1)) || (idV2.agreeHybridEncaps(idV1, ict, ik1))) {
|
||||
if ((idV1.agreeHybridEncaps(idV2, NULL, ict, ik1)) || (idV2.agreeHybridEncaps(idV1, NULL, ict, ik1))) {
|
||||
std::cout << "FAIL (vanilla hybrid accepted)" << std::endl;
|
||||
return -1;
|
||||
}
|
||||
@@ -1710,8 +1764,66 @@ static int testPQ()
|
||||
}
|
||||
std::cout << "PASS" << std::endl;
|
||||
|
||||
// 5. T23/V15: handshake-vs-fragment-loss benchmark for PQC HELLO.
|
||||
std::cout << "[PQ] HELLO fragment-loss benchmark... " << std::flush;
|
||||
// 6. T23 regression: hybrid key confirmation detects a mismatched
|
||||
// derivation. ML-KEM uses implicit rejection, so decapsulating with a secret
|
||||
// that does not match the peer's public key returns a well-formed but wrong
|
||||
// shared secret instead of an error. Both sides therefore install a key and
|
||||
// every subsequent data frame fails its MAC, with no signal anywhere that
|
||||
// renegotiation is needed -- the session could only be recovered by
|
||||
// restarting one daemon. This is the case that wedged a live link.
|
||||
std::cout << "[PQ] Key confirmation detects mismatched hybrid key... " << std::flush;
|
||||
{
|
||||
Identity idA2, idB2;
|
||||
idA2.generate(true);
|
||||
idB2.generate(true);
|
||||
uint8_t ct2[PQHybrid::MLKEM768_CT_LEN];
|
||||
uint8_t kA[ZT_SYMMETRIC_KEY_SIZE], kB[ZT_SYMMETRIC_KEY_SIZE];
|
||||
uint8_t b2mlkempk[PQHybrid::MLKEM768_PK_LEN];
|
||||
if (! idB2.pqKemKey(b2mlkempk)) {
|
||||
std::cout << "FAIL (no mlkem pk)" << std::endl;
|
||||
return -1;
|
||||
}
|
||||
// Honest exchange: both sides agree.
|
||||
if ((! idA2.agreeHybridEncaps(idB2, b2mlkempk, ct2, kA)) || (! idB2.agreeHybridDecaps(idA2, ct2, kB)) || (memcmp(kA, kB, sizeof(kA)))) {
|
||||
std::cout << "FAIL (honest agreement)" << std::endl;
|
||||
return -1;
|
||||
}
|
||||
// A third party holding a different PQ identity but the same classical
|
||||
// secret pair cannot be constructed here, so simulate the mismatch
|
||||
// directly: the tag must differ whenever the derived key differs.
|
||||
uint8_t kWrong[ZT_SYMMETRIC_KEY_SIZE];
|
||||
memcpy(kWrong, kA, sizeof(kWrong));
|
||||
kWrong[0] ^= 0x01;
|
||||
// The confirmation tag is HMAC(session key, address); identical keys
|
||||
// must produce identical tags, and any key change must not.
|
||||
uint8_t macA[48], macWrong[48];
|
||||
const uint64_t addr = idB2.address().toInt();
|
||||
HMACSHA384(kA, &addr, sizeof(addr), macA);
|
||||
HMACSHA384(kWrong, &addr, sizeof(addr), macWrong);
|
||||
if (memcmp(macA, macWrong, ZT_PQ_KEYS_CONFIRM_LEN) == 0) {
|
||||
std::cout << "FAIL (confirm tag did not change with key)" << std::endl;
|
||||
return -1;
|
||||
}
|
||||
// And the real-world failure: A's classical peer identity is unchanged,
|
||||
// but its PQ secret no longer matches the ct B decapsulates. ML-KEM will
|
||||
// not report an error, so the only defence is the confirmation tag.
|
||||
Identity idRotated;
|
||||
idRotated.generate(true);
|
||||
uint8_t kStale[ZT_SYMMETRIC_KEY_SIZE];
|
||||
// idRotated has a different PQ secret, so its key differs from kB.
|
||||
if ((! idRotated.agreeHybridDecaps(idA2, ct2, kStale)) || (memcmp(kStale, kB, sizeof(kStale)) == 0)) {
|
||||
std::cout << "FAIL (stale key not distinguishable)" << std::endl;
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
std::cout << "PASS" << std::endl;
|
||||
|
||||
// 5. T23/V15 regression: a PQ-capable HELLO must be byte-for-byte the size
|
||||
// of a classic one. Carrying a type 1 identity (or the hybrid ciphertext) in
|
||||
// HELLO grew it to ~3.2 KB, which needed 3 fragments and got dropped by
|
||||
// vanilla peers and any MTU-limited relay -- leaving every root unreachable.
|
||||
// PQ material now travels out of band in VERB_PQ_KEYS.
|
||||
std::cout << "[PQ] HELLO stays single-fragment in PQ mode... " << std::flush;
|
||||
{
|
||||
auto buildHello = [](const Identity& src, const Identity& dst, bool pqc) {
|
||||
Packet outp(dst.address(), src.address(), Packet::VERB_HELLO);
|
||||
@@ -1720,7 +1832,7 @@ static int testPQ()
|
||||
outp.append((unsigned char)ZEROTIER_ONE_VERSION_MINOR);
|
||||
outp.append((uint16_t)(ZEROTIER_ONE_VERSION_REVISION | (pqc ? ZT_PROTO_VERB_HELLO_REVISION_CAPABILITY_BIT : 0)));
|
||||
outp.append((int64_t)1234567890LL);
|
||||
src.serialize(outp, false);
|
||||
src.serializeClassic(outp); // what Peer::sendHELLO actually emits
|
||||
InetAddress at("10.0.0.1/9993");
|
||||
at.serialize(outp);
|
||||
outp.append((uint64_t)0); // planetWorldId
|
||||
@@ -1744,42 +1856,115 @@ static int testPQ()
|
||||
const unsigned int pqcSize = buildHello(idH1, idH2, true).size();
|
||||
const unsigned int classicFrags = fragCount(classicSize);
|
||||
const unsigned int pqcFrags = fragCount(pqcSize);
|
||||
std::cout << "\n size classic=" << classicSize << "B/" << classicFrags << " frag, PQC=" << pqcSize << "B/" << pqcFrags << " frag (max " << ZT_MAX_PACKET_FRAGMENTS << ")" << std::flush;
|
||||
// Whole HELLO survives iff every fragment arrives: P(survive) = (1-p)^n.
|
||||
bool ok = (classicFrags == 1u) && (pqcFrags > 1u) && (pqcFrags <= (unsigned int)ZT_MAX_PACKET_FRAGMENTS);
|
||||
static const double ps[] = { 0.01, 0.05, 0.10, 0.30 };
|
||||
const unsigned int trials = 20000;
|
||||
uint64_t lcg = 0x9E3779B97F4A7C15ULL; // fixed seed: deterministic run
|
||||
for (unsigned int pi = 0; (pi < sizeof(ps) / sizeof(ps[0])) && ok; ++pi) {
|
||||
const double p = ps[pi];
|
||||
double pTrue = 1.0;
|
||||
for (unsigned int k = 0; k < pqcFrags; ++k)
|
||||
pTrue *= (1.0 - p);
|
||||
unsigned int succ = 0;
|
||||
for (unsigned int t = 0; t < trials; ++t) {
|
||||
bool all = true;
|
||||
for (unsigned int k = 0; k < pqcFrags; ++k) {
|
||||
lcg = lcg * 6364136223846793005ULL + 1442695040888963407ULL;
|
||||
if ((double)(lcg >> 32) / 4294967296.0 < p) {
|
||||
all = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (all)
|
||||
++succ;
|
||||
}
|
||||
const double obs = (double)succ / (double)trials;
|
||||
const double sigma = std::sqrt(trials * pTrue * (1.0 - pTrue)) / (double)trials;
|
||||
if (std::fabs(obs - pTrue) > (4.0 * sigma))
|
||||
ok = false;
|
||||
std::cout << "\n p=" << p << " observed=" << obs << " analytic=" << pTrue << std::flush;
|
||||
std::cout << "\n size classic=" << classicSize << "B/" << classicFrags
|
||||
<< " frag, PQC=" << pqcSize << "B/" << pqcFrags << " frag (max " << ZT_MAX_PACKET_FRAGMENTS << ")" << std::flush;
|
||||
// The capability bit must not change the datagram size, and neither may
|
||||
// PQ mode. This is the property that keeps vanilla roots reachable.
|
||||
bool ok = (pqcSize == classicSize) && (classicFrags == 1u) && (pqcFrags == 1u);
|
||||
|
||||
// A vanilla peer parsing our HELLO must recover the same address and no
|
||||
// PQ material -- that is what the type 0 projection guarantees.
|
||||
Buffer<ZT_PROTO_MAX_PACKET_LENGTH> hb;
|
||||
const Identity &proj = idH1;
|
||||
proj.serializeClassic(hb);
|
||||
Identity parsed(hb, 0);
|
||||
if ((parsed.address() != idH1.address()) || parsed.hasPQ() || (memcmp(parsed.publicKey().data, idH1.publicKey().data, ZT_C25519_PUBLIC_KEY_LEN))) {
|
||||
ok = false;
|
||||
}
|
||||
|
||||
// The projection is only half the contract. Peer::sendHELLO emits the
|
||||
// classic projection, so the Peer a receiver builds from it holds a
|
||||
// permanently type 0 identity while the sender is type 1. If the
|
||||
// HELLO collision check at IncomingPacket.cpp:424 compares full
|
||||
// identities, operator== sees the missing PQ keys, takes the
|
||||
// "address collision" branch and drops the peer on every subsequent
|
||||
// HELLO -- before the capability bit is read, so the PQ exchange
|
||||
// never starts. Require the stored projection to still match the
|
||||
// identity that sent it, which is what sameClassicalIdentity exists
|
||||
// for. PQ key rotation stays detectable in VERB_PQ_KEYS, so nothing
|
||||
// security-relevant is being waived here.
|
||||
// Assert the predicate the collision check actually evaluates, not just
|
||||
// the helper: a revert of IncomingPacket.cpp:424 back to `!=` would
|
||||
// leave the helper intact and pass a helper-only test, while restoring
|
||||
// the false collision that breaks every type 1 peer.
|
||||
if ((parsed == idH1) || (!parsed.sameClassicalIdentity(idH1))) {
|
||||
ok = false;
|
||||
}
|
||||
|
||||
// And a genuine collision must still be caught: same address and
|
||||
// C25519 key but different PQ keys is a real rotation, not the
|
||||
// projection artefact above, and must not silently pass.
|
||||
Identity rotated;
|
||||
rotated.generate(true);
|
||||
if (rotated.address() == idH1.address()) {
|
||||
ok = false; // cannot construct the check below
|
||||
} else if (parsed.sameClassicalIdentity(rotated)) {
|
||||
ok = false;
|
||||
}
|
||||
|
||||
// PQ_KEYS is the message that is allowed to fragment; it must still fit.
|
||||
Packet pk(idV2.address(), idH1.address(), Packet::VERB_PQ_KEYS);
|
||||
pk.append((uint8_t)1);
|
||||
unsigned char zeros[PQHybrid::MLKEM768_PK_LEN + PQHybrid::MLDSA65_PK_LEN + PQHybrid::MLKEM768_CT_LEN];
|
||||
memset(zeros, 0, sizeof(zeros));
|
||||
pk.append(zeros, PQHybrid::MLKEM768_PK_LEN);
|
||||
pk.append(zeros, PQHybrid::MLDSA65_PK_LEN);
|
||||
pk.append(zeros, PQHybrid::MLKEM768_CT_LEN);
|
||||
const unsigned int pqKeysFrags = fragCount(pk.size());
|
||||
std::cout << "\n VERB_PQ_KEYS=" << pk.size() << "B/" << pqKeysFrags << " frag" << std::flush;
|
||||
if ((pqKeysFrags <= 1u) || (pqKeysFrags > (unsigned int)ZT_MAX_PACKET_FRAGMENTS)) {
|
||||
ok = false;
|
||||
}
|
||||
|
||||
// Fragmented pre-armed packets must still authenticate. FLAGS lives
|
||||
// inside the AES-GMAC-SIV AAD, and dearmor keeps the FRAGMENTED bit,
|
||||
// so a sender that arms first and sets the flag afterwards produces a
|
||||
// MAC the receiver cannot reproduce -- every peer drops it with
|
||||
// "invalid MAC" and the hybrid handshake never completes. Replay the
|
||||
// exact Peer::sendPQKeys ordering (flag, then armor) and require a
|
||||
// clean dearmor at the peer's session key.
|
||||
uint8_t ktmp[ZT_SYMMETRIC_KEY_SIZE];
|
||||
AES sessAes[2];
|
||||
KBKDFHMACSHA384(ik1, ZT_KBKDF_LABEL_AES_GMAC_SIV_K0, 0, 0, ktmp);
|
||||
sessAes[0].init(ktmp);
|
||||
KBKDFHMACSHA384(ik1, ZT_KBKDF_LABEL_AES_GMAC_SIV_K1, 0, 0, ktmp);
|
||||
sessAes[1].init(ktmp);
|
||||
Utils::burn(ktmp, sizeof(ktmp));
|
||||
Packet aad(pk);
|
||||
aad.setFragmented(true);
|
||||
aad.armor(ik1, true, sessAes);
|
||||
Packet received(aad.data(), aad.size());
|
||||
if (! received.dearmor(ik1, sessAes)) {
|
||||
std::cout << "\n FAIL (fragmented pre-armed PQ_KEYS failed to dearmor)";
|
||||
return -1;
|
||||
}
|
||||
// The flag must survive the round trip too, or the packet is armored
|
||||
// over bytes the receiver will not reproduce.
|
||||
if (! received.fragmented()) {
|
||||
std::cout << "\n FAIL (FRAGMENTED bit lost across armor/dearmor)";
|
||||
return -1;
|
||||
}
|
||||
// Regression guard for the original defect: arming first and only then
|
||||
// setting the flag -- what Switch::_sendViaSpecificPath used to do to
|
||||
// pre-armed packets -- must NOT authenticate.
|
||||
Packet late(pk);
|
||||
late.armor(ik1, true, sessAes);
|
||||
late.setFragmented(true);
|
||||
Packet lateReceived(late.data(), late.size());
|
||||
if (lateReceived.dearmor(ik1, sessAes)) {
|
||||
std::cout << "\n FAIL (arming before FRAGMENTED authenticated; AAD no longer covers flags)";
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (! ok) {
|
||||
std::cout << " FAIL" << std::endl;
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
std::cout << "\n loss delays handshake (HELLO retransmit), not broken... PASS" << std::endl;
|
||||
std::cout << "\n PQ mode adds no bytes to HELLO; PQ_KEYS fragments within budget"
|
||||
<< "\n and a fragmented pre-armed PQ_KEYS still authenticates (late-set FRAGMENTED flag is rejected)..."
|
||||
<< "\n HELLO classic projection still matches its own type 1 identity (no false address collision)..."
|
||||
<< "\n and a different PQ identity is still rejected... PASS" << std::endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
+35
-5
@@ -618,6 +618,11 @@ static void _peerToJson(nlohmann::json &pj,const ZT_Peer *peer, SharedPtr<Bond>
|
||||
pj["role"] = prole;
|
||||
pj["isBonded"] = peer->isBonded;
|
||||
pj["tunneled"] = isTunneled;
|
||||
// "Active" means the hybrid key is installed, not merely that the
|
||||
// preconditions hold (see node/Node.cpp:626) -- otherwise a peer looks
|
||||
// hybrid before the encapsulation round trip has completed.
|
||||
pj["pqcCapable"] = peer->pqcCapable;
|
||||
pj["pqcHybridActive"] = peer->pqcHybridActive;
|
||||
if (bond && peer->isBonded) {
|
||||
pj["bondingPolicyCode"] = peer->bondingPolicy;
|
||||
pj["bondingPolicyStr"] = Bond::getPolicyStrByCode(peer->bondingPolicy);
|
||||
@@ -789,6 +794,7 @@ public:
|
||||
const std::string _moonsPath;
|
||||
|
||||
EmbeddedNetworkController *_controller;
|
||||
bool _controllerEnabled;
|
||||
Phy<OneServiceImpl *> _phy;
|
||||
Node *_node;
|
||||
SoftwareUpdater *_updater;
|
||||
@@ -902,6 +908,7 @@ public:
|
||||
,_networksPath(_homePath + ZT_PATH_SEPARATOR_S "networks.d")
|
||||
,_moonsPath(_homePath + ZT_PATH_SEPARATOR_S "moons.d")
|
||||
,_controller((EmbeddedNetworkController *)0)
|
||||
,_controllerEnabled(true)
|
||||
,_phy(this,false,true)
|
||||
,_node((Node *)0)
|
||||
,_updater((SoftwareUpdater *)0)
|
||||
@@ -1050,6 +1057,10 @@ public:
|
||||
_readLocalConfigFile();
|
||||
const int pqcMode = _pqcModeFromLocalConfig(_localConfig);
|
||||
|
||||
// A member-only node must not run its own controller, or it answers
|
||||
// its own config requests and never reaches the real controller.
|
||||
_controllerEnabled = !_controllerDisabledFromLocalConfig(_localConfig);
|
||||
|
||||
{
|
||||
struct ZT_Node_Callbacks cb;
|
||||
cb.version = 0;
|
||||
@@ -1148,12 +1159,17 @@ public:
|
||||
// Delete legacy iddb.d if present (cleanup)
|
||||
OSUtils::rmDashRf((_homePath + ZT_PATH_SEPARATOR_S "iddb.d").c_str());
|
||||
|
||||
// Network controller is now enabled by default for desktop and server
|
||||
_controller = new EmbeddedNetworkController(_node,_homePath.c_str(),_controllerDbPath.c_str(),_ports[0], _rc);
|
||||
if (!_ssoRedirectURL.empty()) {
|
||||
_controller->setSSORedirectURL(_ssoRedirectURL);
|
||||
// Network controller is enabled by default for desktop and server.
|
||||
// A node that is only a member of someone else's network can set
|
||||
// settings.disableController to keep from answering its own config
|
||||
// requests, which would otherwise shadow the real controller.
|
||||
if (_controllerEnabled) {
|
||||
_controller = new EmbeddedNetworkController(_node,_homePath.c_str(),_controllerDbPath.c_str(),_ports[0], _rc);
|
||||
if (!_ssoRedirectURL.empty()) {
|
||||
_controller->setSSORedirectURL(_ssoRedirectURL);
|
||||
}
|
||||
_node->setNetconfMaster((void *)_controller);
|
||||
}
|
||||
_node->setNetconfMaster((void *)_controller);
|
||||
|
||||
startHTTPControlPlane();
|
||||
|
||||
@@ -1429,6 +1445,20 @@ public:
|
||||
return ZT_PQC_MODE_CLASSIC;
|
||||
}
|
||||
|
||||
/**
|
||||
* A node that only joins someone else's network should not run an
|
||||
* embedded controller: it answers its own NETWORK_CONFIG_REQUESTs and so
|
||||
* never reaches the controller that actually owns the network.
|
||||
*
|
||||
* @param lc Parsed local.conf
|
||||
* @return True when settings.disableController asks us to skip it
|
||||
*/
|
||||
static bool _controllerDisabledFromLocalConfig(json& lc)
|
||||
{
|
||||
json& s = lc["settings"];
|
||||
return OSUtils::jsonBool(s.is_object() ? s["disableController"] : json(), false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuse loudly to run when the on-disk identity cannot satisfy the
|
||||
* configured PQC mode. Upgrading in place would change this node's address
|
||||
|
||||
@@ -43,6 +43,7 @@ Settings available in `local.conf` (this is not valid JSON, and JSON does not al
|
||||
"allowTcpFallbackRelay": true|false, /* Allow or disallow establishment of TCP relay connections (true by default) */
|
||||
"multipathMode": 0|1|2, /* multipath mode: none (0), random (1), proportional (2) */
|
||||
"pqcMode": "off"|"hybrid"|"pqconly", /* Post-quantum key agreement mode. Absent defaults to "off" (classic), so existing nodes keep their identity and address. "hybrid" mixes ML-KEM-768 into the X25519 agreement and requires an identity carrying PQ material; a classic identity under a PQC mode makes the daemon refuse to start rather than change its address. */
|
||||
"disableController": true|false, /* Set true on a node that only joins networks owned by another controller. The embedded controller starts by default; left enabled on a member-only node it answers that node's own NETWORK_CONFIG_REQUESTs and signs its own config, so the node never contacts the controller that actually owns the network and stays ACCESS_DENIED with an empty peer list. Default false. */
|
||||
"redis": { /* Optional, requires controllerDbPath starting with "postgres:" */
|
||||
"hostname": "str", /* Redis server host */
|
||||
"port": 1-65535, /* Redis server port */
|
||||
|
||||
+253
-18
@@ -9,29 +9,135 @@ CLI="$(cd "$(dirname "$0")/.." && pwd)/backone-cli"
|
||||
MODE1="${1:-hybrid}"; MODE2="${2:-hybrid}"
|
||||
LAB="${LAB:-/tmp/pqc-lab}"
|
||||
P1="${P1:-20001}"; P2="${P2:-20002}"
|
||||
# genmoon is an idtool command: one.cpp dispatches on argv[0], so it must be
|
||||
# invoked through the backone-idtool symlink, not backone-cli.
|
||||
IDTOOL="$(cd "$(dirname "$0")/.." && pwd)/backone-idtool"
|
||||
|
||||
say() { printf '\033[1m== %s\033[0m\n' "$*"; }
|
||||
ok() { printf ' PASS %s\n' "$*"; }
|
||||
bad() { printf ' FAIL %s\n' "$*"; FAILED=1; }
|
||||
FAILED=0
|
||||
|
||||
NS="sudo -n"
|
||||
LAB="${LAB:-/tmp/pqc-lab}"
|
||||
|
||||
teardown_ns() {
|
||||
# A stale /run/netns mount makes plain "ip netns del" fail with EBUSY, which
|
||||
# would leave the previous run's addresses in place and silently invalidate
|
||||
# every later gate. Lazy-unmount before retrying.
|
||||
for n in pqc-n1 pqc-n2; do $NS ip netns del "$n" 2>/dev/null || { $NS umount -l "/run/netns/$n" 2>/dev/null || true; $NS ip netns del "$n" 2>/dev/null || true; }; done
|
||||
$NS ip link del pqc-veth0 2>/dev/null || true
|
||||
}
|
||||
|
||||
# The daemons run as root, so an unprivileged kill is a no-op: the old process
|
||||
# keeps holding P1/P2 and the replacement dies with "cannot bind to local
|
||||
# control interface port", leaving every later gate reading a stale process.
|
||||
stop_node() {
|
||||
local pidf="$LAB/$1/backone.pid"
|
||||
if [[ -f "$pidf" ]]; then
|
||||
local p; p=$(cat "$pidf" 2>/dev/null)
|
||||
[[ -n "$p" ]] && { kill "$p" 2>/dev/null || $NS kill "$p" 2>/dev/null || true; }
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
wait_port_free() {
|
||||
for _ in $(seq 1 30); do
|
||||
# Skip ss's header row: it always matches, which would report every port
|
||||
# as busy and make this gate meaningless.
|
||||
$NS ss -Huln "sport = :$1" 2>/dev/null | grep -q . || return 0
|
||||
sleep 0.5
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
cleanup() {
|
||||
[[ -f "$LAB/n1/backone.pid" ]] && kill "$(cat "$LAB/n1/backone.pid")" 2>/dev/null || true
|
||||
[[ -f "$LAB/n2/backone.pid" ]] && kill "$(cat "$LAB/n2/backone.pid")" 2>/dev/null || true
|
||||
stop_node n1; stop_node n2
|
||||
# HOLD=1 keeps both nodes and their netns alive after the gates finish, so a
|
||||
# failing run can be inspected live (/peer, logs, pcap) instead of only from
|
||||
# its transcript. Costs nothing when unset.
|
||||
if [[ "${HOLD:-0}" == "1" ]]; then
|
||||
say "HOLD=1: nodes left running for inspection"
|
||||
return 0
|
||||
fi
|
||||
[[ "${NETNS:-1}" == "1" ]] && teardown_ns
|
||||
return 0
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
say "start nodes (mode1=$MODE1 mode2=$MODE2)"
|
||||
rm -rf "$LAB"; mkdir -p "$LAB/n1" "$LAB/n2"
|
||||
# Reap the previous run BEFORE wiping its pid files, otherwise a surviving
|
||||
# daemon keeps the ports and this run silently tests the old processes.
|
||||
stop_node n1; stop_node n2
|
||||
# The daemon drops privileges and root-owns its state dir, so an unprivileged
|
||||
# rm leaves debris that makes the next run's mkdir/redirect fail.
|
||||
rm -rf "$LAB" 2>/dev/null || $NS rm -rf "$LAB"
|
||||
mkdir -p "$LAB/n1" "$LAB/n2"
|
||||
printf '{"settings":{"pqcMode":"%s"}}' "$MODE1" > "$LAB/n1/local.conf"
|
||||
printf '{"settings":{"pqcMode":"%s"}}' "$MODE2" > "$LAB/n2/local.conf"
|
||||
nohup "$BIN" -U -p"$P1" "$LAB/n1" >"$LAB/n1/log" 2>&1 &
|
||||
nohup "$BIN" -U -p"$P2" "$LAB/n2" >"$LAB/n2/log" 2>&1 &
|
||||
|
||||
# Each node needs its own netns. Two daemons on one host both bind the
|
||||
# wildcard address, so they cannot discover each other and the G4 gate would
|
||||
# read "no path" as "PQ broken". Isolating them gives distinct addresses and
|
||||
# a real UDP path, which is the only way the handshake can actually happen.
|
||||
NETNS=${NETNS:-1}
|
||||
if [[ "$NETNS" == "1" ]]; then
|
||||
teardown_ns
|
||||
# Both veth ends must live inside the namespaces. Leaving the first one on
|
||||
# the host gives each namespace a loopback-only stack, so the two nodes have
|
||||
# no path to each other and every later gate fails for topology reasons.
|
||||
# Every step needs root: netns creation and link moves are unprivileged-
|
||||
# forbidden, and a silent failure here invalidates all gates below.
|
||||
$NS ip netns add pqc-n1 || bad "cannot create netns pqc-n1"
|
||||
$NS ip netns add pqc-n2 || bad "cannot create netns pqc-n2"
|
||||
$NS ip link add pqc-veth0 type veth peer name pqc-veth1 || bad "cannot create veth pair"
|
||||
$NS ip link set pqc-veth1 netns pqc-n2
|
||||
$NS ip link set pqc-veth0 netns pqc-n1
|
||||
$NS ip netns exec pqc-n1 ip addr add 10.77.0.1/24 dev pqc-veth0
|
||||
$NS ip netns exec pqc-n1 ip link set pqc-veth0 up
|
||||
$NS ip netns exec pqc-n2 ip addr add 10.77.0.2/24 dev pqc-veth1
|
||||
$NS ip netns exec pqc-n2 ip link set pqc-veth1 up
|
||||
$NS ip netns exec pqc-n2 ip link set lo up
|
||||
$NS ip netns exec pqc-n1 ip link set lo up
|
||||
# Prove the dataplane works before blaming any gate below on PQ: a silent
|
||||
# loopback-only namespace makes G4 fail for a reason that has nothing to do
|
||||
# with quantum resistance.
|
||||
if $NS ip netns exec pqc-n1 ping -c2 -W2 10.77.0.2 >/dev/null 2>&1; then
|
||||
ok "netns pqc-n1 (10.77.0.1) <-> pqc-n2 (10.77.0.2) via veth, ping OK"
|
||||
else
|
||||
bad "veth dataplane broken: n1 cannot reach n2 - later gates are meaningless until this is fixed"
|
||||
fi
|
||||
RUN1="ip netns exec pqc-n1"; RUN2="ip netns exec pqc-n2"
|
||||
else
|
||||
RUN1=""; RUN2=""
|
||||
fi
|
||||
|
||||
wait_port_free "$P1" || bad "UDP $P1 busy before start - a stale daemon from an earlier run holds it"
|
||||
wait_port_free "$P2" || bad "UDP $P2 busy before start - a stale daemon from an earlier run holds it"
|
||||
if [[ -n "$RUN1" ]]; then
|
||||
sudo -n $RUN1 nohup "$BIN" -U -p"$P1" "$LAB/n1" >"$LAB/n1/log" 2>&1 &
|
||||
sudo -n $RUN2 nohup "$BIN" -U -p"$P2" "$LAB/n2" >"$LAB/n2/log" 2>&1 &
|
||||
else
|
||||
nohup "$BIN" -U -p"$P1" "$LAB/n1" >"$LAB/n1/log" 2>&1 &
|
||||
nohup "$BIN" -U -p"$P2" "$LAB/n2" >"$LAB/n2/log" 2>&1 &
|
||||
fi
|
||||
|
||||
# API accessor: the control plane binds 127.0.0.1 inside each namespace, so
|
||||
# host-side curl cannot reach it. api1/api2 enter the namespace instead.
|
||||
api1() { if [[ -n "$RUN1" ]]; then sudo -n $RUN1 "$@"; else "$@"; fi; }
|
||||
api2() { if [[ -n "$RUN2" ]]; then sudo -n $RUN2 "$@"; else "$@"; fi; }
|
||||
|
||||
sleep 6
|
||||
|
||||
A1=$(cat "$LAB/n1/authtoken.secret"); A2=$(cat "$LAB/n2/authtoken.secret")
|
||||
N1=$(cut -d: -f1 "$LAB/n1/identity.public"); N2=$(cut -d: -f1 "$LAB/n2/identity.public")
|
||||
T1=$(cut -d: -f2 "$LAB/n1/identity.public"); T2=$(cut -d: -f2 "$LAB/n2/identity.public")
|
||||
# The control API binds to 127.0.0.1 inside each namespace, so reach it from
|
||||
# the host side over the veth rather than trying to enter the namespace.
|
||||
# The daemon drops privileges after startup, so these files are root-owned;
|
||||
# reading them unprivileged fails and every API call below 401s.
|
||||
A1=$(cat "$LAB/n1/authtoken.secret" 2>/dev/null || $NS cat "$LAB/n1/authtoken.secret"); A2=$(cat "$LAB/n2/authtoken.secret" 2>/dev/null || $NS cat "$LAB/n2/authtoken.secret")
|
||||
N1=$(api1 curl -s -H "X-ZT1-Auth: $A1" http://127.0.0.1:$P1/status | python3 -c 'import json,sys;d=json.load(sys.stdin);print(d["address"])')
|
||||
N2=$(api2 curl -s -H "X-ZT1-Auth: $A2" http://127.0.0.1:$P2/status | python3 -c 'import json,sys;d=json.load(sys.stdin);print(d["address"])')
|
||||
# Type byte: /status exposes the identity as "<addr>:<type>:<pubkey>[:...]".
|
||||
T1=$(api1 curl -s -H "X-ZT1-Auth: $A1" http://127.0.0.1:$P1/status | python3 -c 'import json,sys;print(json.load(sys.stdin)["publicIdentity"].split(":")[1])')
|
||||
T2=$(api2 curl -s -H "X-ZT1-Auth: $A2" http://127.0.0.1:$P2/status | python3 -c 'import json,sys;print(json.load(sys.stdin)["publicIdentity"].split(":")[1])')
|
||||
say "identity type bytes: n1=$T1 n2=$T2"
|
||||
|
||||
# ---- G1: identity must be type 1 when hybrid/pqconly ----------------------
|
||||
@@ -43,41 +149,170 @@ else
|
||||
fi
|
||||
|
||||
say "create network on the controller (n1) + authorize n2"
|
||||
NW=$(curl -s -H "X-ZT1-Auth: $A1" -X POST \
|
||||
NW=$(api1 curl -s -H "X-ZT1-Auth: $A1" -X POST \
|
||||
-d '{"name":"pqclab","v4AssignMode":{"zt":true},"ipAssignmentPools":[{"ipRangeStart":"10.99.0.1","ipRangeEnd":"10.99.0.254"}]}' \
|
||||
"http://127.0.0.1:$P1/controller/network/${N1}______" \
|
||||
| python3 -c 'import json,sys;print(json.load(sys.stdin)["nwid"])')
|
||||
[[ "$NW" =~ ^${N1}[0-9a-f]{6}$ ]] && ok "network $NW created" || bad "network id '$NW' not controller-addressed"
|
||||
curl -s -H "X-ZT1-Auth: $A1" -X POST -d '{"authorized":true}' \
|
||||
api1 curl -s -H "X-ZT1-Auth: $A1" -X POST -d '{"authorized":true}' \
|
||||
"http://127.0.0.1:$P1/controller/network/$NW/member/$N2" >/dev/null
|
||||
curl -s -H "X-ZT1-Auth: $A1" -X POST "http://127.0.0.1:$P1/network/$NW" >/dev/null
|
||||
curl -s -H "X-ZT1-Auth: $A2" -X POST "http://127.0.0.1:$P2/network/$NW" >/dev/null
|
||||
api1 curl -s -H "X-ZT1-Auth: $A1" -X POST "http://127.0.0.1:$P1/network/$NW" >/dev/null
|
||||
api2 curl -s -H "X-ZT1-Auth: $A2" -X POST "http://127.0.0.1:$P2/network/$NW" >/dev/null
|
||||
sleep 8
|
||||
|
||||
# ---- TAP gate (needs root) ------------------------------------------------
|
||||
if grep -q 'TAP operation' "$LAB/n1/log" 2>/dev/null; then
|
||||
bad "n1 cannot open TUN/TAP (need root / CAP_NET_ADMIN) - data plane untestable"
|
||||
fi
|
||||
CONF=$(curl -s -H "X-ZT1-Auth: $A1" "http://127.0.0.1:$P1/network/$NW")
|
||||
CONF=$(api1 curl -s -H "X-ZT1-Auth: $A1" "http://127.0.0.1:$P1/network/$NW")
|
||||
[[ "$CONF" != "{}" && -n "$CONF" ]] && ok "n1 network config populated" || bad "n1 network config empty: $CONF"
|
||||
|
||||
# ---- root set for peer discovery ----------------------------------------
|
||||
# The two nodes share no WAN here, so the hardcoded Earth roots are all
|
||||
# unreachable and neither node can discover the other: peers stay at the
|
||||
# root list with no path. A moon with n1 as sole root gives them a reachable
|
||||
# peer to learn each other's physical endpoints from. Without this, G4 fails
|
||||
# for a topology reason that has nothing to do with PQ.
|
||||
say "define moon (n1 = sole root) so the two nodes can find each other"
|
||||
WORLD="${WORLD:-$(printf '%016x' $(( (RANDOM<<16) ^ RANDOM ^ $$ )))}"
|
||||
MSECRET="$LAB/moon-signing.secret"
|
||||
(umask 077; head -c 64 /dev/urandom | od -An -tx1 | tr -d ' \n' > "$MSECRET")
|
||||
# 64 random bytes == 128 hex chars == a 64-byte C25519 private key, which is
|
||||
# what this fork's node/C25519.hpp declares. Read it back for genmoon.
|
||||
MSK=$(cat "$MSECRET")
|
||||
# The stable endpoint must name a port n1 actually binds. -p sets the UDP
|
||||
# primary port too, so read it back from /status rather than guessing:
|
||||
# a wrong port means n2's WHOIS is silently discarded (no ICMP, no retry).
|
||||
MPUBFULL=$(api1 curl -s -H "X-ZT1-Auth: $A1" http://127.0.0.1:$P1/status | python3 -c 'import json,sys;print(json.load(sys.stdin)["publicIdentity"])')
|
||||
ROOTPORT=$(api1 curl -s -H "X-ZT1-Auth: $A1" http://127.0.0.1:$P1/status | python3 -c 'import json,sys;print(json.load(sys.stdin)["config"]["settings"]["primaryPort"])')
|
||||
# toString emits "<10-hex address>:<type>:<32-byte pubkey>[:...]" and genmoon
|
||||
# unhex's signingKey/updatesMustBeSignedBy, so the signing key is field 2 -
|
||||
# not field 0, which is only the address.
|
||||
MPUB=$(printf '%s' "$MPUBFULL" | cut -d: -f3)
|
||||
cat > "$LAB/moon.json" <<EOF
|
||||
{"id":"$WORLD","worldType":"moon","signingKey":"$MPUB","signingKey_SECRET":"$MSK",
|
||||
"updatesMustBeSignedBy":"$MPUB",
|
||||
"roots":[{"identity":"$MPUBFULL","stableEndpoints":["10.77.0.1/$ROOTPORT"]}]}
|
||||
EOF
|
||||
# genmoon unhex's these fields and stops at the buffer size, so a short value
|
||||
# yields a silently invalid moon. This fork uses 64-byte C25519 keys
|
||||
# (node/C25519.hpp ZT_C25519_PUBLIC_KEY_LEN=64), hence 128 hex chars each.
|
||||
if (( ${#MPUB} == 128 )) && (( ${#MSK} == 128 )); then
|
||||
ok "moon signing key parsed; root endpoint 10.77.0.1:$ROOTPORT (n1 actual UDP bind)"
|
||||
else
|
||||
bad "moon signing key malformed: pub=${#MPUB} hex, secret=${#MSK} hex (want 128 each for 64-byte keys)"
|
||||
fi
|
||||
if (cd "$LAB" && "$IDTOOL" genmoon "$LAB/moon.json" >/dev/null 2>&1) && [[ -s "$LAB/$WORLD.moon" ]]; then
|
||||
ok "moon $WORLD generated (root n1 @ 10.77.0.1:$ROOTPORT)"
|
||||
mkdir -p "$LAB/n1/moons.d" "$LAB/n2/moons.d"
|
||||
cp "$LAB/$WORLD.moon" "$LAB/n1/moons.d/"
|
||||
cp "$LAB/$WORLD.moon" "$LAB/n2/moons.d/"
|
||||
# moons.d is only scanned once, during startup, so both nodes must restart
|
||||
# to pick the moon up. Joining the network again is unnecessary: it is
|
||||
# restored from networks.d on boot.
|
||||
say "restart both nodes so they load the moon"
|
||||
stop_node n1; stop_node n2
|
||||
wait_port_free "$P1" || bad "port $P1 still held - nodes cannot reload the moon"
|
||||
wait_port_free "$P2" || bad "port $P2 still held - nodes cannot reload the moon"
|
||||
sleep 3
|
||||
if [[ -n "$RUN1" ]]; then
|
||||
sudo -n $RUN1 nohup "$BIN" -U -p"$P1" "$LAB/n1" >>"$LAB/n1/log" 2>&1 &
|
||||
sudo -n $RUN2 nohup "$BIN" -U -p"$P2" "$LAB/n2" >>"$LAB/n2/log" 2>&1 &
|
||||
else
|
||||
nohup "$BIN" -U -p"$P1" "$LAB/n1" >>"$LAB/n1/log" 2>&1 &
|
||||
nohup "$BIN" -U -p"$P2" "$LAB/n2" >>"$LAB/n2/log" 2>&1 &
|
||||
fi
|
||||
sleep 8
|
||||
ok "nodes restarted with moon $WORLD"
|
||||
else
|
||||
bad "genmoon failed - nodes cannot discover each other, G4 will fail for topology reasons"
|
||||
fi
|
||||
|
||||
# ---- capture --------------------------------------------------------------
|
||||
say "capture (udp - all fragments, incl. continuation)"
|
||||
pcap="$LAB/pqc.pcap"
|
||||
FILT="udp"
|
||||
( ip netns exec n2 tcpdump -i any -w "$pcap" "$FILT" >/dev/null 2>&1 || \
|
||||
tcpdump -i any -w "$pcap" "$FILT" >/dev/null 2>&1 ) &
|
||||
( sudo -n $RUN2 tcpdump -i any -w "$pcap" "$FILT" >/dev/null 2>&1 || \
|
||||
sudo -n tcpdump -i any -w "$pcap" "$FILT" >/dev/null 2>&1 ) &
|
||||
TCPD=$!; sleep 1
|
||||
# n2's namespace capture misses the inbound n1->n2 veth traffic, so the
|
||||
# ct-bearing PQ_KEYS fragments (4253 B, 3 fragments) never appear in $pcap and
|
||||
# a send failure is indistinguishable from a capture gap. Capture the sender
|
||||
# side too.
|
||||
( sudo -n $RUN1 tcpdump -i any -w "$LAB/pqc-n1.pcap" "$FILT" >/dev/null 2>&1 || \
|
||||
sudo -n tcpdump -i any -w "$LAB/pqc-n1.pcap" "$FILT" >/dev/null 2>&1 ) &
|
||||
TCPD1=$!; sleep 1
|
||||
|
||||
say "warm up handshake"
|
||||
# nodes run on host here (netns n1/n2 may not exist) - ping via TAP on host
|
||||
ping -c3 -W2 10.99.0.2 >/dev/null 2>&1 || \
|
||||
sudo ip netns exec n1 ping -c3 -W2 10.99.0.2 >/dev/null 2>&1 || true
|
||||
# Drive traffic across the TAP so the handshake is exercised end to end.
|
||||
api1 ping -c3 -W2 10.99.0.2 >/dev/null 2>&1 || \
|
||||
ping -c3 -W2 10.99.0.2 >/dev/null 2>&1 || true
|
||||
sleep 6
|
||||
kill "$TCPD" 2>/dev/null || true
|
||||
pkill -INT -f "tcpdump.*$pcap" 2>/dev/null || true
|
||||
kill "$TCPD1" 2>/dev/null || true
|
||||
pkill -INT -f "tcpdump.*pqc-n1.pcap" 2>/dev/null || true
|
||||
sleep 1
|
||||
|
||||
# ---- G4: both sides must report the hybrid key actually in effect ---------
|
||||
# The wire capture cannot make this call: a large PQ datagram proves we SENT
|
||||
# keys, not that the peer accepted them and installed the hybrid session key.
|
||||
# Only /peer's pqcHybridActive does. Poll, because VERB_PQ_KEYS retries for a
|
||||
# few seconds after the path comes up.
|
||||
say "G4 hybrid key agreement state (both directions)"
|
||||
READF='import json,sys
|
||||
try: print(json.load(sys.stdin).get(sys.argv[1]))
|
||||
except Exception: print("?")'
|
||||
peer_field() { # $1=side $2=addr $3=field
|
||||
local PJ
|
||||
if [[ "$1" == "1" ]]; then PJ=$(api1 curl -s -H "X-ZT1-Auth: $A1" "http://127.0.0.1:$P1/peer/$2")
|
||||
else PJ=$(api2 curl -s -H "X-ZT1-Auth: $A2" "http://127.0.0.1:$P2/peer/$2"); fi
|
||||
printf '%s' "$PJ" | python3 -c "$READF" "$3" 2>/dev/null || echo "?"
|
||||
}
|
||||
|
||||
declare -A WANT
|
||||
if [[ "$MODE1" == "off" || "$MODE2" == "off" ]]; then WANT[1]=skip; WANT[2]=skip
|
||||
else WANT[1]=True; WANT[2]=True; fi
|
||||
|
||||
# Path precondition. A peer that has no usable path cannot send PQ keys at
|
||||
# all, and the failure then looks like a crypto failure. n1 is the moon root,
|
||||
# so n2 is its leaf; Peer::received only learns a path on VERB_OK (Peer.cpp),
|
||||
# and an upstream never sends OK to a leaf that reached it, so n1 stays at
|
||||
# 0 paths while n2 has 3. That asymmetry is the lab's topology, not PQ --
|
||||
# report it as such instead of blaming VERB_PQ_KEYS.
|
||||
path_count() { # $1=side $2=addr
|
||||
local PJ
|
||||
if [[ "$1" == "1" ]]; then PJ=$(api1 curl -s -H "X-ZT1-Auth: $A1" "http://127.0.0.1:$P1/peer/$2")
|
||||
else PJ=$(api2 curl -s -H "X-ZT1-Auth: $A2" "http://127.0.0.1:$P2/peer/$2"); fi
|
||||
printf '%s' "$PJ" | python3 -c 'import json,sys
|
||||
try:
|
||||
d=json.load(sys.stdin); print(len(d.get("paths",[])))
|
||||
except Exception: print("?")' 2>/dev/null || echo "?"
|
||||
}
|
||||
|
||||
for SIDE in 1 2; do
|
||||
if (( SIDE == 1 )); then LBL="n1->n2"; OTHER=$N2; else LBL="n2->n1"; OTHER=$N1; fi
|
||||
ACT="?"; CAP="?"
|
||||
for _ in $(seq 1 12); do
|
||||
CAP=$(peer_field "$SIDE" "$OTHER" pqcCapable)
|
||||
ACT=$(peer_field "$SIDE" "$OTHER" pqcHybridActive)
|
||||
[[ "$ACT" == "${WANT[$SIDE]}" ]] && break
|
||||
sleep 5
|
||||
done
|
||||
if [[ "${WANT[$SIDE]}" == "skip" ]]; then
|
||||
ok "G4 $LBL pqcCapable=$CAP hybridActive=$ACT (classic expected when either mode=off)"
|
||||
elif [[ "$ACT" == "True" ]]; then
|
||||
ok "G4 $LBL pqcHybridActive=true (capable=$CAP)"
|
||||
else
|
||||
NPC=$(path_count "$SIDE" "$OTHER")
|
||||
if [[ "$NPC" == "0" ]]; then
|
||||
bad "G4 $LBL pqcHybridActive=$ACT (capable=$CAP): 0 paths to peer <-- TOPOLOGY not PQ: this side cannot transmit, so its PQ_KEYS never leave the host. Expected under the single-root moon (n1 root / n2 leaf): the upstream never sends OK, so it never learns the return path."
|
||||
else
|
||||
bad "G4 $LBL pqcHybridActive=$ACT (capable=$CAP), expected True <-- VERB_PQ_KEYS never authenticated (SPEC B3: FRAGMENTED set after armor)"
|
||||
fi
|
||||
fi
|
||||
done
|
||||
|
||||
# ---- G2/G3: wire must show PQ material when both sides are PQ-capable -----
|
||||
if [[ -s "$pcap" ]]; then
|
||||
frags=$(tshark -r "$pcap" -Y "udp.port==9993 or udp.port==$P1 or udp.port==$P2" -T fields -e frame.number 2>/dev/null | wc -l || true)
|
||||
|
||||
Reference in new issue
Block a user