diff --git a/DESIGN.md b/DESIGN.md index 657bb66..538c7f1 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -442,7 +442,8 @@ On receiving ClientHello: the discovery key is non-zero, server_peer_id names this server, and the reserved bytes are zero. 6. Check timestamp/freshness. -7. Apply per-source rate limiting. +7. Check source credit, then charge the global resolution budget before + recording the source debit or creating or evicting a source entry. 8. Resolve client_peer_tag to an authorized PeerID. 9. Reject unresolvable tags. 10. Charge the shared verification budget. @@ -456,16 +457,14 @@ This order is intentional. An unauthenticated Internet/DERP sender should not be able to induce expensive post-quantum work beyond a signature verification. -Blinding replaces the old O(1) map lookup on a raw PeerID with a scan that -recomputes each authorized peer's expected tag under the received nonce. The -authorized set is small and held in memory, and one 48-byte HMAC-SHA-384 per -peer is far cheaper than the ML-DSA verification it gates, so the scan does not -meaningfully change unauthenticated DoS exposure. Two ordering details keep it -that way: the per-source bucket is charged *before* the scan, and the shared -verification budget is charged *after* it, so an unresolvable tag cannot spend -verification capacity. The per-PeerID bucket is still charged only after a -successful signature check, so constructing another peer's tag cannot drain that -peer's quota. +Blinded tag resolution costs one HMAC-SHA-384 per candidate in the in-memory +authorized set. Resolution admits up to four hellos per second per source and +128 per second across all sources, with matching initial burst capacities. +Checking the source allowance first preserves shared credit when an existing +source exceeds its quota. The global check bounds scans, source allocations +and oldest-entry evictions even as source keys change. The separate shared +signature-verification budget admits only resolvable tags. The per-PeerID +budget is charged after signature verification. Comparisons use a constant-time equality check, and resolution never touches the filesystem: authorization state is reloaded into memory out of band. @@ -706,8 +705,9 @@ Client Server │ ML-DSA signed ClientHello │ ├───────────────────────────────────────────►│ │ │ + │ check freshness │ + │ check budgets │ │ resolve peer tag │ - │ check freshness │ │ verify ML-DSA │ │ │ │ encapsulate to │ @@ -1031,7 +1031,9 @@ field/source binding checks ↓ timestamp check ↓ -per-source rate limit +check source credit + ↓ +shared resolution budget, then record source debit ↓ blinded tag -> authorized PeerID ↓ @@ -1056,13 +1058,10 @@ Never perform: for unknown peers. -Rate limits should exist: - -```text -per DERP source/node key -per client PeerID -global -``` +ClientFinish uses its transcript hash for direct lookup and validates its +expiry, source and proof before authorization. It uses neither global hello +budget. Periodic bootstrap cleanup owns full expiry of the pending, replay and +rate tables. Individual packet handlers check the records they use. Do not trust an IP address alone because DERP may hide the original path. diff --git a/PROTOCOL.md b/PROTOCOL.md index eb31059..ab3c344 100644 --- a/PROTOCOL.md +++ b/PROTOCOL.md @@ -148,35 +148,37 @@ The server installs the peer after ClientFinish verification; the client waits for ServerAccepted. Legacy Meow packets never authorize a Quantumcat peer. Failures are silent to unauthenticated senders. -Limits: a 64-packet serialized server queue, four hellos/second per source before -the shared 64-verifications/second budget, and four new handshakes/second per -PeerID only after signature verification. Invalid signatures cannot consume -the claimed identity's quota. Token buckets refill continuously, with initial -burst capacities of 4/64/4 respectively (not strict rolling-window maxima). -Idle rate-table entries can be discarded after one second, when their buckets -would be full again. There are 256 pending handshakes (at most eight per -authenticated identity, shared across its source keys), 19,264 replay -entries, 4096 entries in each separate source/identity rate table, and 4096 -installed sessions. The global budget is a resource bound, not a guarantee -against distributed denial of service. Unknown peers trigger no signature work, -encapsulation, or peer installation, and occupy no state beyond the single -bounded per-source rate entry described below. They also trigger no filesystem -I/O, though that is a requirement on the caller-supplied authorized set, which -must be served from memory, rather than something the protocol layer enforces. - -ClientHello processing runs in this order: framing and exact-size checks, the -cheap field checks above, the timestamp window, the per-source bucket, blinded -tag resolution, the shared verification budget, replay and capacity checks, -ML-DSA verification, then the per-PeerID bucket and encapsulation. Resolution -costs one HMAC-SHA-384 per authorized peer over 48 bytes, so it is far cheaper -than the ML-DSA verification it gates, and the per-source bucket caps how often -an unauthenticated sender can trigger it. Because resolution precedes the shared -budget, an unresolvable tag cannot consume verification capacity. Because the -per-PeerID bucket follows verification, constructing another peer's tag cannot -spend that peer's authenticated quota. A well-formed hello from an unknown -source does now occupy one bounded per-source rate entry before its tag is -resolved; that table is still capped at 4096 with oldest-first eviction, and the -threat model already assumes attackers know authorized PeerIDs. +The server queue holds 64 packets. Four continuously refilled token buckets +bound ClientHello work. Each bucket starts full and its burst capacity equals +its per-second rate. + +| Operation | Rate | +| --- | --- | +| Hello admission per transport source | 4/second | +| Tag resolution across all sources | 128/second | +| Signature verification across all sources | 64/second | +| New handshakes per authenticated PeerID | 4/second | + +After checking framing, field bindings and timestamp, the server checks the +source's available credit. A source already at its limit spends no shared +resolution credit. Admitting a hello charges both the source and global +resolution budgets. Only then may the server create a source entry, evict the +oldest entry if the table is full, or scan the in-memory authorized set. The +scan costs one HMAC-SHA-384 per candidate. A matching tag can proceed to the +shared verification budget, replay and capacity checks, ML-DSA verification, +the per-PeerID budget and encapsulation. Rotating sources still share the +resolution budget and can exhaust it. ClientFinish bypasses the hello budgets. +The server checks the accessed transcript's expiry, source and finish proof +before rechecking authorization. + +The server holds at most 256 unfinished handshakes (eight per authenticated +identity across its sources), 19,264 replay entries, 4,096 entries in each of +the source and identity rate tables, and 4,096 installed sessions. Periodic +cleanup erases expired pending secrets and replay entries, and drops idle rate +entries after their buckets have refilled. Packet processing checks the expiry +of accessed pending and replay records without sweeping the tables. An unknown +tag can occupy a bounded source entry. Authorization lookup uses in-memory +pairing data supplied by the application. Enumeration also makes two authenticated paths linear in the size of the authorized set: ClientFinish re-checks the resolved PeerID against it, and each diff --git a/internal/protocol/blinding_test.go b/internal/protocol/blinding_test.go index 44767e3..5f4053e 100644 --- a/internal/protocol/blinding_test.go +++ b/internal/protocol/blinding_test.go @@ -185,8 +185,7 @@ func TestSourceRateTableStaysBoundedForUnknownTags(t *testing.T) { t.Fatal("initial handshake rejected") } // Fill to the cap with entries older than the genuine sender's, so eviction - // has an unambiguous oldest victim. Keep the whole spread inside one second: - // Handle prunes idle entries older than that before it consults the cap. + // has an unambiguous oldest victim. for i := range 4095 { var key [32]byte binary.BigEndian.PutUint32(key[:], uint32(i)) @@ -205,6 +204,15 @@ func TestSourceRateTableStaysBoundedForUnknownTags(t *testing.T) { } fresh := [32]byte{0xAB} copy(unknown[8+32:8+64], fresh[:]) + s.resolution = bucket{start: now} + s.Handle(ctx, fresh, unknown, now) + if _, ok := s.limits[oldest]; !ok { + t.Fatal("evicted a source before obtaining resolution credit") + } + if _, ok := s.limits[fresh]; ok { + t.Fatal("allocated a source before obtaining resolution credit") + } + s.resolution.tokens = 1 if reply, session := s.Handle(ctx, fresh, unknown, now); reply != nil || session != nil { t.Fatal("accepted an unresolvable tag") } diff --git a/internal/protocol/budget_test.go b/internal/protocol/budget_test.go new file mode 100644 index 0000000..05017e3 --- /dev/null +++ b/internal/protocol/budget_test.go @@ -0,0 +1,107 @@ +package protocol + +import ( + "context" + "testing" + "time" + + "github.com/ekarulf/quantumcat/internal/crypto/provider/software" +) + +func TestRejectedPacketsDoNotSweepTables(t *testing.T) { + s, _, _, src, now := fixture(t) + s.pending = map[[hashSize]byte]*pending{{1}: {expires: now.Add(-time.Second)}} + s.replay = map[[hashSize]byte]time.Time{{1}: now.Add(-time.Second)} + s.limits = map[[32]byte]bucket{{1}: {start: now.Add(-time.Hour)}} + for _, kind := range []byte{ClientFinish, ServerAccepted} { + for n := 0; n < 100; n++ { + s.Handle(context.Background(), src, frame(kind, make([]byte, hashSize+proofSize)), now) + } + } + if len(s.pending) != 1 || len(s.replay) != 1 || len(s.limits) != 1 { + t.Fatal("rejected packet swept shared state") + } + s.Expire(now) + if len(s.pending)+len(s.replay)+len(s.limits) != 0 { + t.Fatal("periodic expiry failed") + } +} + +func TestRotatingSourcesCannotBypassResolutionBudget(t *testing.T) { + s, _, hello, _, now := fixture(t) + visited := 0 + s.Authorized = func(yield func(PeerID, []byte) bool) { visited++; yield(PeerID{1}, nil) } + for n := 0; n < 256; n++ { + src := [32]byte{byte(n), 1} + packet := append([]byte(nil), hello...) + copy(packet[8+32:8+64], src[:]) + s.Handle(context.Background(), src, packet, now) + } + if visited != 128 { + t.Fatalf("resolution scans=%d want 128", visited) + } + if len(s.limits) != 128 { + t.Fatalf("allocated source records=%d", len(s.limits)) + } +} + +func TestInvalidFinishDoesNotEnumerateAuthority(t *testing.T) { + s, c, hello, src, now := fixture(t) + reply, _ := s.Handle(context.Background(), src, hello, now) + _, finish, err := c.Complete(context.Background(), reply) + if err != nil { + t.Fatal(err) + } + finish[len(finish)-1] ^= 1 + s.Authorized = func(func(PeerID, []byte) bool) { t.Fatal("unauthenticated finish enumerated peers") } + s.Handle(context.Background(), src, finish, now) +} + +func TestSourceAtLimitLeavesResolutionCreditForRenewal(t *testing.T) { + s, client, hello, src, now := fixture(t) + ctx := t.Context() + reply, _ := s.Handle(ctx, src, hello, now) + _, finish, err := client.Complete(ctx, reply) + if err != nil { + t.Fatal(err) + } + ack, session := s.Handle(ctx, src, finish, now) + if session == nil || !client.Accepted(ack) { + t.Fatal("initial handshake failed") + } + session.Installed(true) + + at := now.Add(time.Second) + otherKeys := session.Keys + otherKeys.WG[0] ^= 1 + other, otherHello, err := NewClient(ctx, client.identity, software.NewKEM, client.serverPublic, otherKeys, s.Keys, at) + if err != nil { + t.Fatal(err) + } + defer other.Close() + s.limits[otherKeys.WG] = bucket{start: at, tokens: 0} + s.resolution = bucket{start: at, tokens: 1} + if reply, _ := s.Handle(ctx, otherKeys.WG, otherHello, at); reply != nil { + t.Fatal("source over its limit was admitted") + } + + renewal, hello, err := NewClient(ctx, client.identity, software.NewKEM, client.serverPublic, session.Keys, s.Keys, at) + if err != nil { + t.Fatal(err) + } + defer renewal.Close() + reply, _ = s.Handle(ctx, src, hello, at) + psk, finish, err := renewal.Complete(ctx, reply) + if err != nil { + t.Fatalf("renewal with one remaining resolution credit: %v", err) + } + ack, renewed := s.Handle(ctx, src, finish, at) + if renewed == nil || renewed.PSK != psk || psk == session.PSK || !renewal.Accepted(ack) { + t.Fatal("renewal did not install the fresh PSK with the resolution bucket exhausted") + } + renewed.Installed(true) + s.Authorized = nil + if ack, _ := s.Handle(ctx, src, finish, at); ack != nil { + t.Fatal("revoked peer received a cached acknowledgement") + } +} diff --git a/internal/protocol/handshake.go b/internal/protocol/handshake.go index 0ae439a..1f2b8dd 100644 --- a/internal/protocol/handshake.go +++ b/internal/protocol/handshake.go @@ -169,6 +169,7 @@ type Server struct { limits map[[32]byte]bucket peerLimits map[[32]byte]bucket global bucket + resolution bucket } // Expire erases pending secrets even when the server receives no traffic. @@ -222,38 +223,18 @@ func allow(b bucket, now time.Time, max int) (bucket, bool) { return b, true } -// Handle is serialized and bounds all caches. No work or state is allocated for -// unknown identities, and encapsulation follows authentication and replay checks. +// Handle is serialized and bounds all caches. Expire owns periodic cleanup. func (s *Server) Handle(ctx context.Context, source [32]byte, packet []byte, now time.Time) ([]byte, *Session) { kind, b, err := Parse(packet) - if err != nil { + if err != nil || (kind != ClientHello && kind != ClientFinish) { return nil, nil } s.mu.Lock() defer s.mu.Unlock() - for h, p := range s.pending { - if !now.Before(p.expires) { - clear(p.hk[:]) - clear(p.session.PSK[:]) - delete(s.pending, h) - } - } - for h, t := range s.replay { - if !now.Before(t) { - delete(s.replay, h) - } - } - for _, limits := range []map[[32]byte]bucket{s.limits, s.peerLimits} { - for h, t := range limits { - if now.Sub(t.start) > time.Second { - delete(limits, h) - } - } - } if kind == ClientFinish { h := [hashSize]byte(b[:hashSize]) p := s.pending[h] - if p == nil || p.source != source || len(Lookup(s.Authorized, p.session.Peer)) == 0 || !hmac.Equal(proof(p.hk, "client-finished", h), b[hashSize:]) { + if p == nil || !now.Before(p.expires) || p.source != source || !hmac.Equal(proof(p.hk, "client-finished", h), b[hashSize:]) || len(Lookup(s.Authorized, p.session.Peer)) == 0 { return nil, nil } ack := frame(ServerAccepted, join(h[:], proof(p.hk, "server-accepted", h))) @@ -267,7 +248,7 @@ func (s *Server) Handle(ctx context.Context, source [32]byte, packet []byte, now // Discard competing transcripts before handing a PSK to the transport; // otherwise a delayed finish could roll back a completed renewal. for _, other := range s.pending { - if other != p && other.source == source && other.installing && !other.accepted { + if other != p && other.source == source && now.Before(other.expires) && other.installing && !other.accepted { return nil, nil } } @@ -315,9 +296,6 @@ func (s *Server) Handle(ctx context.Context, source [32]byte, packet []byte, now } return ack, &session } - if kind != ClientHello { - return nil, nil - } // Version 1 assigns no semantics to the reserved bytes. The complete hello // is transcript-bound, but non-zero extensions still require a new version. if source != [32]byte(b[32:64]) || [32]byte(b[64:96]) == [32]byte{} || PeerID(b[128:160]) != ID(s.Public) || [32]byte(b[160:192]) != [32]byte{} { @@ -327,26 +305,29 @@ func (s *Server) Handle(ctx context.Context, source [32]byte, packet []byte, now if stamp < now.Unix()-120 || stamp > now.Unix()+120 { return nil, nil } - var ok bool + // Check source credit without allocating a record. Only hellos admitted by + // both buckets can create or evict a source record and enumerate peers. + current, known := s.limits[source] + next, ok := allow(current, now, 4) + if !ok { + return nil, nil + } + s.resolution, ok = allow(s.resolution, now, 128) + if !ok { + return nil, nil + } if s.limits == nil { s.limits = make(map[[32]byte]bucket) s.peerLimits = make(map[[32]byte]bucket) } - if _, exists := s.limits[source]; !exists && len(s.limits) >= 4096 { + if !known && len(s.limits) >= 4096 { evictOldest(s.limits) } - // Charge a sender's quota before the identity scan and the shared - // verification budget. Claimed identities must not consume another device's - // quota before authentication. - s.limits[source], ok = allow(s.limits[source], now, 4) - if !ok { - return nil, nil - } + s.limits[source] = next // The first 32 bytes are a nonce-blinded tag, not the client's PeerID, so // recover the real identity by recomputing each authorized peer's tag. One - // HMAC per authorized peer is far cheaper than the ML-DSA verification it - // gates, and the source bucket above bounds how often an unauthenticated - // sender can trigger the scan. Everything downstream uses the real PeerID. + // HMAC per candidate selects the verification key. Both admission buckets + // bound these scans. Everything downstream uses the real PeerID. id, pub := s.resolve(b[:32], b[96:128]) if len(pub) == 0 || ID(pub) != id { return nil, nil @@ -356,10 +337,10 @@ func (s *Server) Handle(ctx context.Context, source [32]byte, packet []byte, now return nil, nil } replay := sha512.Sum384(join(id[:], b[96:128])) - if _, ok := s.replay[replay]; ok { + if expires, ok := s.replay[replay]; ok && now.Before(expires) { digest := sha512.Sum384(packet) for _, p := range s.pending { - if p.source == source && p.helloHash == digest { + if now.Before(p.expires) && p.source == source && p.helloHash == digest { return append([]byte(nil), p.response...), nil } } @@ -383,7 +364,7 @@ func (s *Server) Handle(ctx context.Context, source [32]byte, packet []byte, now } owned := 0 for _, p := range s.pending { - if !p.accepted && p.session.Peer == id { + if !p.accepted && now.Before(p.expires) && p.session.Peer == id { owned++ } }