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:
proitlabandClaude Opus 4.8 committed 2026-10-07 21:37:05 +00:00
1 parent ad01fbcccb
commit a224dbbc53
24 files changed
+1423 -168

No files matched your search

+153 -62
View File
@@ -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);