p2p: a per-peer guard drops floods and bans peers that send invalid gossip

Per relaying peer and minute: over 1200 messages are dropped unread (no penalty); 20 invalid ones (bad signature, too little work, garbage) ban the peer for an hour, closing the connection and blacklisting it in gossip. Ignored messages (clock trouble, unknown listing) never count. In the simulator the attacker is cut off from every node it reached and honest listings still arrive 50 of 50; the message-flood scenario now uses a second attacker.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw
This commit is contained in:
2026-11-19 00:21:59 +01:00
co-authored by Claude Sonnet 5.5
parent bcae85b06f
commit daa80a6d56
6 changed files with 305 additions and 12 deletions
+132
View File
@@ -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) }
+140
View File
@@ -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)
}
}
+13 -5
View File
@@ -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
}