Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 19 additions & 20 deletions DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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.
Expand Down Expand Up @@ -706,8 +705,9 @@ Client Server
│ ML-DSA signed ClientHello │
├───────────────────────────────────────────►│
│ │
│ check freshness │
│ check budgets │
│ resolve peer tag │
│ check freshness │
│ verify ML-DSA │
│ │
│ encapsulate to │
Expand Down Expand Up @@ -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
↓
Expand All @@ -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.

Expand Down
60 changes: 31 additions & 29 deletions PROTOCOL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 10 additions & 2 deletions internal/protocol/blinding_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand All @@ -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")
}
Expand Down
107 changes: 107 additions & 0 deletions internal/protocol/budget_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
}
Loading
Loading