From 406600f4092fccac86fa06569d239b5bb20a3784 Mon Sep 17 00:00:00 2001 From: Marco Munizaga Date: Fri, 17 Jun 2022 09:09:23 -0700 Subject: [PATCH] Add canonical log for misbehaving peers (#258) * Add canonical logging for misbehaving peers * Add component and use manet.FromNetAddr * Fix log test --- core/canonicallog/canonicallog.go | 31 ++++++++++++++++++++++++++ core/canonicallog/canonicallog_test.go | 19 ++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 core/canonicallog/canonicallog.go create mode 100644 core/canonicallog/canonicallog_test.go diff --git a/core/canonicallog/canonicallog.go b/core/canonicallog/canonicallog.go new file mode 100644 index 000000000..40de00ed1 --- /dev/null +++ b/core/canonicallog/canonicallog.go @@ -0,0 +1,31 @@ +package canonicallog + +import ( + "net" + + logging "github.com/ipfs/go-log/v2" + "github.com/libp2p/go-libp2p-core/peer" + "github.com/multiformats/go-multiaddr" + manet "github.com/multiformats/go-multiaddr/net" +) + +var log = logging.WithSkip(logging.Logger("canonical-log"), 1) + +// LogMisbehavingPeer is the canonical way to log a misbehaving peer. +// Protocols should use this to identify a misbehaving peer to allow the end +// user to easily identify these nodes across protocols and libp2p. +func LogMisbehavingPeer(p peer.ID, peerAddr multiaddr.Multiaddr, component string, err error, msg string) { + log.Errorf("CANONICAL_MISBEHAVING_PEER: peer=%s addr=%s component=%s err=%v msg=%s", p, peerAddr.String(), component, err, msg) +} + +// LogMisbehavingPeer is the canonical way to log a misbehaving peer. +// Protocols should use this to identify a misbehaving peer to allow the end +// user to easily identify these nodes across protocols and libp2p. +func LogMisbehavingPeerNetAddr(p peer.ID, peerAddr net.Addr, component string, originalErr error, msg string) { + ma, err := manet.FromNetAddr(peerAddr) + if err != nil { + log.Errorf("CANONICAL_MISBEHAVING_PEER: peer=%s netAddr=%s component=%s err=%v msg=%s", p, peerAddr.String(), component, originalErr, msg) + } + + log.Errorf("CANONICAL_MISBEHAVING_PEER: peer=%s addr=%s component=%s err=%v msg=%s", p, ma, component, originalErr, msg) +} diff --git a/core/canonicallog/canonicallog_test.go b/core/canonicallog/canonicallog_test.go new file mode 100644 index 000000000..9332ee4a9 --- /dev/null +++ b/core/canonicallog/canonicallog_test.go @@ -0,0 +1,19 @@ +package canonicallog + +import ( + "fmt" + "testing" + + "github.com/libp2p/go-libp2p-core/test" + "github.com/multiformats/go-multiaddr" +) + +func TestLogs(t *testing.T) { + LogMisbehavingPeer(test.RandPeerIDFatal(t), multiaddr.StringCast("/ip4/1.2.3.4"), "somecomponent", fmt.Errorf("something"), "hi") + LogMisbehavingPeerNetAddr(test.RandPeerIDFatal(t), dummyNetAddr{}, "somecomponent", fmt.Errorf("something"), "hi") +} + +type dummyNetAddr struct{} + +func (d dummyNetAddr) Network() string { return "tcp" } +func (d dummyNetAddr) String() string { return "127.0.0.1:80" }