diff --git a/SPECS.md b/SPECS.md index 32fb608..24b4da5 100644 --- a/SPECS.md +++ b/SPECS.md @@ -147,8 +147,10 @@ starting a design-heavy item; see "Working with the owner". - **Check a public node's memory under load.** `--public` nodes now accept 1000 inbound connections (`--max-conns`); nobody has measured a node holding that many against the 512 MiB pod limit. -- **Peer scoring and rate limits** beyond what the validators do now. The - simulator's attacker stays connected after 500 bad messages. +- **Peer scoring beyond the guard.** `internal/p2p/guard.go` drops a peer + relaying over 1200 messages a minute and bans one that sends 20 invalid ones + for an hour (gossip only). Not covered: throwaway peer IDs, rate limits on + the sync protocol and the HTTP API, sharing bans between nodes. - **Joining without the seeds.** A newcomer whose remembered peers are all in another region cannot find its region when no DHT server is up (sim: 0 of 114 listings). Remember region peers separately, or ask connected peers. diff --git a/cmd/allmende-sim/scenarios.go b/cmd/allmende-sim/scenarios.go index 94ad2e7..4b5a2df 100644 --- a/cmd/allmende-sim/scenarios.go +++ b/cmd/allmende-sim/scenarios.go @@ -153,7 +153,7 @@ func (s *sim) hostile(regions []string, rep *reportTable) { lt := "/allmende/1/listings/" + region mt := "/allmende/1/messages/" + region atk := s.newAttacker(targets, lt, mt) - defer atk.close() + defer func() { atk.close() }() // atk is replaced before the flood // 1. listings that must never be stored ident := &simNode{} @@ -221,7 +221,7 @@ func (s *sim) hostile(regions []string, rep *reportTable) { poll(pairs, 100*time.Millisecond) } rep.latency("attack 1b", "honest listings published while the attacker is connected", await(pairs, s.timeout)) - rep.row("attack 1c", fmt.Sprintf("the attacker is still connected to %d of %d nodes it dialed (there is no peer scoring: nobody cuts it off)", + rep.row("attack 1c", fmt.Sprintf("the attacker is still connected to %d of %d nodes it dialed (a node bans a peer after 20 invalid messages in a minute and cuts it off)", len(atk.h.Network().Peers()), len(targets))) // 2. a message flood at one listing, with real (cheap) proof-of-work @@ -249,6 +249,10 @@ func (s *sim) hostile(regions []string, rep *reportTable) { } return c } + // The first attacker has been banned by now; the flood comes from a new + // peer, whose messages are all valid (the point is the queue, not a ban). + atk.close() + atk = s.newAttacker(targets, lt, mt) const flood = 400 for i := 0; i < flood; i++ { tk, err := message.NewThreadKey() diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index b7a0c79..d8347ea 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -696,9 +696,16 @@ Findings (see "What is left" in SPECS.md for the open ones): changes it; `-1` restores libp2p's default), and the table above shows the result. Not measured: the memory of a seed holding 1000 connections against the 512 MiB limit in `k8s/base/statefulset.yaml`. -2. **No peer scoring.** The attacker stayed connected to all 10 nodes it - dialed after sending 500 bad messages. Nothing was stored, but each message - still cost every node its validation work. +2. **Peer limits are crude.** The first run had no peer scoring: the attacker + stayed connected to all 10 nodes it dialed after 500 bad messages. Now every + node counts, per relaying peer and minute, the messages it gets (over 1200 + are dropped unread, without penalty) and the invalid ones (20 get the peer + banned for an hour: closed connection, gossip blacklist; `internal/p2p/guard.go`). + In the sim the attacker was cut off from all 6 nodes it reached and honest + listings still arrived 50 of 50. What it does not stop: an attacker with many + peer IDs (a ban costs it nothing but a new key), a peer that sends only + valid but unwanted records, or one that stays under the limits. The ban is + per node, not shared, and covers gossip only, not the sync protocol. 3. **The DHT is only as good as its servers.** Only publicly reachable nodes serve it. With every seed gone, a newcomer whose remembered peers are all in another region found nobody (0 of 114 listings), and one that remembers no diff --git a/internal/p2p/guard.go b/internal/p2p/guard.go new file mode 100644 index 0000000..d9fa459 --- /dev/null +++ b/internal/p2p/guard.go @@ -0,0 +1,132 @@ +package p2p + +import ( + "context" + "log/slog" + "sync" + "time" + + pubsub "github.com/libp2p/go-libp2p-pubsub" + "github.com/libp2p/go-libp2p/core/peer" +) + +// Limits on what one peer may send us. They are generous for an honest peer +// (a node relaying a busy region) and cheap for us to enforce: the rate check +// runs before a message is parsed or its signature verified. +const ( + // guardWindow is the span over which a peer's messages and bad messages are counted. + guardWindow = time.Minute + // maxPerWindow is how many messages one peer may relay to us per window; + // more are dropped unread (and not passed on), without penalty. + maxPerWindow = 1200 + // maxBadPerWindow is how many invalid messages (bad signature, too little + // proof-of-work, garbage) one peer may send per window before it is banned. + // Honest peers send none: clock trouble and unknown listings are ignored, + // not counted as bad. + maxBadPerWindow = 20 + // banFor is how long a banned peer stays disconnected and ignored. + banFor = time.Hour +) + +// peerGuard counts, per peer, the messages it relays to us and how many were +// invalid, drops floods and bans peers that keep sending invalid ones. A ban +// is a pubsub blacklist entry plus a closed connection; it expires by itself. +type peerGuard struct { + now func() time.Time + log *slog.Logger + bl pubsub.Blacklist + disconnect func(peer.ID) + self peer.ID + + mu sync.Mutex + peers map[peer.ID]*peerCount +} + +type peerCount struct { + start time.Time // of the current window + total int + bad int + noted bool // the flood was already logged this window +} + +func newPeerGuard(self peer.ID, now func() time.Time, log *slog.Logger, disconnect func(peer.ID)) (*peerGuard, error) { + bl, err := pubsub.NewTimeCachedBlacklist(banFor) + if err != nil { + return nil, err + } + return &peerGuard{now: now, log: log, bl: bl, disconnect: disconnect, self: self, peers: map[peer.ID]*peerCount{}}, nil +} + +// wrap puts the guard around a topic validator. Messages we published +// ourselves are not counted. +func (g *peerGuard) wrap(v pubsub.ValidatorEx) pubsub.ValidatorEx { + return func(ctx context.Context, from peer.ID, msg *pubsub.Message) pubsub.ValidationResult { + if from == g.self { + return v(ctx, from, msg) + } + if !g.admit(from) { + return pubsub.ValidationIgnore + } + res := v(ctx, from, msg) + if res == pubsub.ValidationReject { + g.bad(from) + } + return res + } +} + +// count returns p's counters for the current window. g.mu must be held. +func (g *peerGuard) count(p peer.ID) *peerCount { + now := g.now() + c := g.peers[p] + if c == nil || now.Sub(c.start) >= guardWindow { + if len(g.peers) > 4096 { // forget peers whose windows ended + for k, v := range g.peers { + if now.Sub(v.start) >= guardWindow { + delete(g.peers, k) + } + } + } + c = &peerCount{start: now} + g.peers[p] = c + } + return c +} + +// admit counts one message from p and reports whether it is within the rate. +func (g *peerGuard) admit(p peer.ID) bool { + g.mu.Lock() + defer g.mu.Unlock() + c := g.count(p) + c.total++ + if c.total <= maxPerWindow { + return true + } + if !c.noted { + c.noted = true + g.log.Warn("peer sends too much; dropping its messages until the minute is over", + "peer", p, "limit_per_minute", maxPerWindow) + } + return false +} + +// bad counts an invalid message from p and bans it past the limit. +func (g *peerGuard) bad(p peer.ID) { + g.mu.Lock() + c := g.count(p) + c.bad++ + ban := c.bad == maxBadPerWindow + g.mu.Unlock() + if !ban { + return + } + g.bl.Add(p) + g.log.Warn("banned a peer that kept sending invalid messages", "peer", p, + "invalid_in_a_minute", maxBadPerWindow, "for", banFor) + if g.disconnect != nil { + g.disconnect(p) + } +} + +// banned reports whether p is currently banned. +func (g *peerGuard) banned(p peer.ID) bool { return g.bl.Contains(p) } diff --git a/internal/p2p/guard_test.go b/internal/p2p/guard_test.go new file mode 100644 index 0000000..4612593 --- /dev/null +++ b/internal/p2p/guard_test.go @@ -0,0 +1,140 @@ +package p2p + +import ( + "context" + "io" + "log/slog" + "testing" + "time" + + pubsub "github.com/libp2p/go-libp2p-pubsub" + "github.com/libp2p/go-libp2p/core/peer" +) + +type guardFixture struct { + g *peerGuard + now time.Time + verdict pubsub.ValidationResult + ran int + dropped []peer.ID + v pubsub.ValidatorEx +} + +func newGuardFixture(t *testing.T) *guardFixture { + t.Helper() + f := &guardFixture{now: time.Unix(1_800_000_000, 0), verdict: pubsub.ValidationAccept} + g, err := newPeerGuard("self", func() time.Time { return f.now }, + slog.New(slog.NewTextHandler(io.Discard, nil)), func(p peer.ID) { f.dropped = append(f.dropped, p) }) + if err != nil { + t.Fatal(err) + } + f.g = g + f.v = g.wrap(func(context.Context, peer.ID, *pubsub.Message) pubsub.ValidationResult { + f.ran++ + return f.verdict + }) + return f +} + +func (f *guardFixture) send(from peer.ID) pubsub.ValidationResult { + return f.v(context.Background(), from, &pubsub.Message{}) +} + +func TestAPeerThatSendsInvalidMessagesIsBannedAndDisconnected(t *testing.T) { + f := newGuardFixture(t) + f.verdict = pubsub.ValidationReject + for i := 0; i < maxBadPerWindow-1; i++ { + f.send("mallory") + } + if f.g.banned("mallory") || len(f.dropped) != 0 { + t.Fatal("banned before the limit") + } + f.send("mallory") + if !f.g.banned("mallory") { + t.Fatalf("not banned after %d invalid messages", maxBadPerWindow) + } + if len(f.dropped) != 1 || f.dropped[0] != "mallory" { + t.Fatalf("disconnected %v, want mallory once", f.dropped) + } + f.send("mallory") // more invalid ones must not disconnect again and again + if len(f.dropped) != 1 { + t.Fatalf("disconnected %d times", len(f.dropped)) + } + if f.g.banned("alice") { + t.Fatal("an innocent peer is banned") + } +} + +func TestInvalidMessagesSpreadOverTimeDoNotBan(t *testing.T) { + f := newGuardFixture(t) + f.verdict = pubsub.ValidationReject + for i := 0; i < 5*maxBadPerWindow; i++ { + f.send("slow") + f.now = f.now.Add(guardWindow / (maxBadPerWindow / 2)) // half the limit per window + } + if f.g.banned("slow") { + t.Fatal("banned for a rate below the limit") + } +} + +func TestIgnoredMessagesAreNotHeldAgainstThePeer(t *testing.T) { + f := newGuardFixture(t) + f.verdict = pubsub.ValidationIgnore // clock trouble, unknown listing + for i := 0; i < 10*maxBadPerWindow; i++ { + f.send("honest") + } + if f.g.banned("honest") { + t.Fatal("ignored messages must not count as bad") + } +} + +func TestAFloodIsDroppedUnreadAndTheNextMinuteStartsFresh(t *testing.T) { + f := newGuardFixture(t) + for i := 0; i < maxPerWindow; i++ { + if res := f.send("busy"); res != pubsub.ValidationAccept { + t.Fatalf("message %d within the limit got %v", i, res) + } + } + ran := f.ran + if res := f.send("busy"); res != pubsub.ValidationIgnore { + t.Fatalf("over the limit got %v, want Ignore", res) + } + if f.ran != ran { + t.Fatal("a message over the limit was still validated") + } + if f.g.banned("busy") { + t.Fatal("a flood of valid messages is dropped, not banned") + } + if res := f.send("calm"); res != pubsub.ValidationAccept { + t.Fatal("one peer's flood must not limit another") + } + f.now = f.now.Add(guardWindow) + if res := f.send("busy"); res != pubsub.ValidationAccept { + t.Fatalf("after the window the peer got %v", res) + } +} + +func TestOurOwnMessagesAreNeverLimited(t *testing.T) { + f := newGuardFixture(t) + f.verdict = pubsub.ValidationReject + for i := 0; i < 3*maxPerWindow; i++ { + if f.send("self") == pubsub.ValidationIgnore { + t.Fatal("limited our own publish") + } + } + if f.g.banned("self") { + t.Fatal("banned ourselves") + } +} + +func TestFinishedWindowsAreForgotten(t *testing.T) { + f := newGuardFixture(t) + for i := 0; i < 5000; i++ { + f.send(peer.ID("p" + string(rune('a'+i%26)) + time.Duration(i).String())) + } + f.now = f.now.Add(2 * guardWindow) + f.send("fresh") + if n := len(f.g.peers); n > 10 { + t.Fatalf("%d peers still tracked after their windows ended", n) + } +} diff --git a/internal/p2p/node.go b/internal/p2p/node.go index 3c4143e..8e14999 100644 --- a/internal/p2p/node.go +++ b/internal/p2p/node.go @@ -128,6 +128,8 @@ type Node struct { ps *pubsub.PubSub clock func() time.Time log *slog.Logger + // guard rate-limits and bans the peers that relay to us. + guard *peerGuard // gossipIn counts listings that arrived by gossip since the last summary. gossipIn tally @@ -267,9 +269,15 @@ func New(ctx context.Context, cfg Config) (*Node, error) { // Flood-publish: the origin sends to every subscribed peer instead of only // its mesh. Regional topics are small, and without it a listing published // in the first second after connecting (before the mesh forms) is lost. + n.guard, err = newPeerGuard(h.ID(), n.clock, log, func(p peer.ID) { _ = h.Network().ClosePeer(p) }) + if err != nil { + n.Close() + return nil, err + } n.ps, err = pubsub.NewGossipSub(nctx, h, pubsub.WithMaxMessageSize(listing.MaxSize+4096), - pubsub.WithFloodPublish(true)) + pubsub.WithFloodPublish(true), + pubsub.WithBlacklist(n.guard.bl)) if err != nil { n.Close() return nil, err @@ -431,7 +439,7 @@ func (n *Node) Close() error { // --- topics --------------------------------------------------------------- func (n *Node) startRevocations() error { - if err := n.ps.RegisterTopicValidator(RevocationTopic, n.revocationValidator, + if err := n.ps.RegisterTopicValidator(RevocationTopic, n.guard.wrap(n.revocationValidator), pubsub.WithValidatorTimeout(5*time.Second)); err != nil { return err } @@ -461,7 +469,7 @@ func (n *Node) startRevocations() error { } func (n *Node) startReports() error { - if err := n.ps.RegisterTopicValidator(ReportTopic, n.reportValidator, + if err := n.ps.RegisterTopicValidator(ReportTopic, n.guard.wrap(n.reportValidator), pubsub.WithValidatorTimeout(5*time.Second)); err != nil { return err } @@ -651,7 +659,7 @@ func (n *Node) messageTopic(region string) (*pubsub.Topic, error) { return t, nil } name := messageTopicPrefix + region - if err := n.ps.RegisterTopicValidator(name, n.messageValidator(region), + if err := n.ps.RegisterTopicValidator(name, n.guard.wrap(n.messageValidator(region)), pubsub.WithValidatorTimeout(5*time.Second)); err != nil { return nil, err } @@ -674,7 +682,7 @@ func (n *Node) regionTopic(region string) (*pubsub.Topic, error) { return t, nil } name := listingTopicPrefix + region - if err := n.ps.RegisterTopicValidator(name, n.listingValidator(region), + if err := n.ps.RegisterTopicValidator(name, n.guard.wrap(n.listingValidator(region)), pubsub.WithValidatorTimeout(5*time.Second)); err != nil { return nil, err }