Files
proitlabandClaude Opus 4.8 a224dbbc53
validate.yml / build_ubuntu (push) Canceled after 0s
build.yml / build_ubuntu (push) Canceled after 0s
build.yml / build_macos (push) Canceled after 0s
build.yml / build_windows (push) Canceled after 0s
Lint / clang-format (push) Canceled after 0s
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>
2026-10-07 21:37:05 +00:00

334 lines
17 KiB
Bash
Executable File

#!/usr/bin/env bash
# pqc-lab.sh - hermetic-ish two-node BackOne PQC handshake lab + capture + asserts.
# See docs/pqc-test-scenario.md §4-5. Needs root for TUN/TAP and (optionally) netns.
# Usage: sudo -E tools/pqc-lab.sh [mode1] [mode2] (default: hybrid hybrid)
set -euo pipefail
BIN="$(cd "$(dirname "$0")/.." && pwd)/backone"
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() {
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)"
# 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"
# 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
# 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 ----------------------
if [[ "$MODE1" == "off" ]]; then
[[ "$T1" == "0" ]] && ok "G1 n1 classic identity under mode=off" || bad "G1 n1 expected type 0, got $T1"
else
if [[ "$T1" == "1" ]]; then ok "G1 n1 type-1 identity under mode=$MODE1"
else bad "G1 n1 expected type 1 (PQ) under mode=$MODE1, got $T1 <-- Node.cpp:96 ignores pqcMode"; fi
fi
say "create network on the controller (n1) + authorize n2"
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"
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
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=$(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"
( 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"
# 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)
ok "captured $frags ZT-adjacent UDP frames -> $pcap"
if [[ "$MODE1" != "off" && "$MODE2" != "off" ]]; then
# After the §7 fix a 1088-byte ML-KEM ciphertext (>=2 datagrams) must appear.
big=$(tshark -r "$pcap" -Y 'udp.length>1200' -T fields -e frame.number 2>/dev/null | wc -l || true)
if (( big > 0 )); then ok "G2/G3 large PQ datagrams present ($big) - hybrid material on wire"
else bad "G2/G3 no large datagrams: PQ capability advertised but no ML-KEM ciphertext <-- Identity::agree() is classical"; fi
fi
say "dissect with: tshark -X lua_script:$(dirname "$0")/zt-dissector.lua -r $pcap -Y zt"
else
bad "no packets captured (netns/tcpdump unavailable without root?)"
fi
echo
[[ "$FAILED" == "0" ]] && say "ALL CHECKS PASSED" || say "FAILURES PRESENT (see above; §0/§7 of docs/pqc-test-scenario.md)"
exit "$FAILED"