Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Peer CIDR based filtering #2387

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
10 changes: 9 additions & 1 deletion cmd/juno/juno.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ const (
p2pPeersF = "p2p-peers"
p2pFeederNodeF = "p2p-feeder-node"
p2pPrivateKey = "p2p-private-key"
p2pDenyList = "p2p-deny-list"
p2pAllowList = "p2p-allow-list"
metricsF = "metrics"
metricsHostF = "metrics-host"
metricsPortF = "metrics-port"
Expand Down Expand Up @@ -157,7 +159,11 @@ const (
"These peers can be either Feeder or regular nodes."
p2pFeederNodeUsage = "EXPERIMENTAL: Run juno as a feeder node which will only sync from feeder gateway and gossip the new" +
" blocks to the network."
p2pPrivateKeyUsage = "EXPERIMENTAL: Hexadecimal representation of a private key on the Ed25519 elliptic curve."
p2pPrivateKeyUsage = "EXPERIMENTAL: Hexadecimal representation of a private key on the Ed25519 elliptic curve."
p2pDenyListUsage = "CIDR subnets to block peer connections. " +
"For example, '192.168.0.0/16' blocks local network peers. By default, all connections are accepted."
p2pAllowListUsage = "CIDR subnets to allow peer connections. " +
"For example, '192.168.0.0/16' allows local network peers. By default, all connections are accepted."
metricsUsage = "Enables the Prometheus metrics endpoint on the default port."
metricsHostUsage = "The interface on which the Prometheus endpoint will listen for requests."
metricsPortUsage = "The port on which the Prometheus endpoint will listen for requests."
Expand Down Expand Up @@ -344,6 +350,8 @@ func NewCmd(config *node.Config, run func(*cobra.Command, []string) error) *cobr
junoCmd.Flags().String(p2pPeersF, defaultP2pPeers, p2pPeersUsage)
junoCmd.Flags().Bool(p2pFeederNodeF, defaultP2pFeederNode, p2pFeederNodeUsage)
junoCmd.Flags().String(p2pPrivateKey, defaultP2pPrivateKey, p2pPrivateKeyUsage)
junoCmd.Flags().StringArray(p2pDenyList, make([]string, 0), p2pDenyListUsage)
junoCmd.Flags().StringArray(p2pAllowList, make([]string, 0), p2pAllowListUsage)
junoCmd.Flags().Bool(metricsF, defaultMetrics, metricsUsage)
junoCmd.Flags().String(metricsHostF, defaulHost, metricsHostUsage)
junoCmd.Flags().Uint16(metricsPortF, defaultMetricsPort, metricsPortUsage)
Expand Down
4 changes: 4 additions & 0 deletions cmd/juno/juno_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -638,6 +638,10 @@ network: sepolia
junoEnv := unsetJunoPrefixedEnv(t)

for name, tc := range tests {
if tc.expectedConfig != nil {
tc.expectedConfig.P2PAllowList = make([]string, 0)
tc.expectedConfig.P2PDenyList = make([]string, 0)
}
t.Run(name, func(t *testing.T) {
if tc.cfgFile {
fileN := tempCfgFile(t, tc.cfgFileContents)
Expand Down
16 changes: 9 additions & 7 deletions node/node.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,12 +73,14 @@ type Config struct {
MetricsHost string `mapstructure:"metrics-host"`
MetricsPort uint16 `mapstructure:"metrics-port"`

P2P bool `mapstructure:"p2p"`
P2PAddr string `mapstructure:"p2p-addr"`
P2PPublicAddr string `mapstructure:"p2p-public-addr"`
P2PPeers string `mapstructure:"p2p-peers"`
P2PFeederNode bool `mapstructure:"p2p-feeder-node"`
P2PPrivateKey string `mapstructure:"p2p-private-key"`
P2P bool `mapstructure:"p2p"`
P2PAddr string `mapstructure:"p2p-addr"`
P2PPublicAddr string `mapstructure:"p2p-public-addr"`
P2PPeers string `mapstructure:"p2p-peers"`
P2PFeederNode bool `mapstructure:"p2p-feeder-node"`
P2PPrivateKey string `mapstructure:"p2p-private-key"`
P2PDenyList []string `mapstructure:"p2p-deny-list"`
P2PAllowList []string `mapstructure:"p2p-allow-list"`

MaxVMs uint `mapstructure:"max-vms"`
MaxVMQueue uint `mapstructure:"max-vm-queue"`
Expand Down Expand Up @@ -182,7 +184,7 @@ func New(cfg *Config, version string) (*Node, error) { //nolint:gocyclo,funlen
synchronizer = nil
}
p2pService, err = p2p.New(cfg.P2PAddr, cfg.P2PPublicAddr, version, cfg.P2PPeers, cfg.P2PPrivateKey, cfg.P2PFeederNode,
chain, &cfg.Network, log, database)
chain, &cfg.Network, log, database, cfg.P2PDenyList, cfg.P2PAllowList)
if err != nil {
return nil, fmt.Errorf("set up p2p service: %w", err)
}
Expand Down
116 changes: 116 additions & 0 deletions p2p/connection_gater.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
package p2p

import (
"fmt"
"net"

"github.com/NethermindEth/juno/utils"
"github.com/libp2p/go-libp2p/core/control"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/multiformats/go-multiaddr"
multinet "github.com/multiformats/go-multiaddr/net"
)

// connectionGater manages connection filtering based on multiaddr rules.
type connectionGater struct {
addrFilter *multiaddr.Filters
log utils.SimpleLogger
}

func newConnectionGater(denyListCIDR, allowListCIDR []string, log utils.SimpleLogger) (*connectionGater, error) {
addrFilter, err := configureFilter(denyListCIDR, allowListCIDR, log)
if err != nil {
return nil, fmt.Errorf("configure address filter: %w", err)
}

return &connectionGater{
addrFilter: addrFilter,
log: log,
}, nil
}

// InterceptPeerDial always allows dialling a peer.
func (*connectionGater) InterceptPeerDial(_ peer.ID) (allow bool) {
return true
}

// InterceptAddrDial checks if dialling a specific multiaddr for a given peer is allowed.
func (s *connectionGater) InterceptAddrDial(pid peer.ID, m multiaddr.Multiaddr) (allow bool) {
return filterMultiAddr(s.addrFilter, m, s.log)
}

// InterceptAccept checks if an inbound connection is allowed based on its remote address.
func (s *connectionGater) InterceptAccept(n network.ConnMultiaddrs) (allow bool) {
return filterMultiAddr(s.addrFilter, n.RemoteMultiaddr(), s.log)
}

// InterceptSecured allows all authenticated connections.
func (*connectionGater) InterceptSecured(_ network.Direction, _ peer.ID, _ network.ConnMultiaddrs) (allow bool) {
return true
}

// InterceptUpgraded allows all fully capable connections.
func (*connectionGater) InterceptUpgraded(_ network.Conn) (allow bool, reason control.DisconnectReason) {
// A zero value stands for "no reason" / NA.
return true, 0
}

// configureFilter sets up a filter using deny and allow lists of CIDRs.
// The deny list takes priority: CIDRs in both lists will be blocked.
func configureFilter(denyListCIDR, allowListCIDR []string, log utils.SimpleLogger) (*multiaddr.Filters, error) {
filter := multiaddr.NewFilters()

for _, cidr := range allowListCIDR {
if err := addCIDRToFilter(filter, cidr, multiaddr.ActionAccept, log); err != nil {
return nil, err
}
}

for _, cidr := range denyListCIDR {
if err := addCIDRToFilter(filter, cidr, multiaddr.ActionDeny, log); err != nil {
return nil, err
}
}

return filter, nil
}

// addCIDRToFilter adds a single CIDR to the filter with the specified action.
func addCIDRToFilter(filter *multiaddr.Filters, cidr string, action multiaddr.Action, log utils.SimpleLogger) error {
_, ipNet, err := net.ParseCIDR(cidr)
if err != nil {
return err
}

existingAction, _ := filter.ActionForFilter(*ipNet)
if existingAction != action && existingAction != multiaddr.ActionNone {
log.Warnw("Conflicting filter rule", "address", ipNet.String(), "current_action", existingAction, "new_action", action)
}
filter.AddFilter(*ipNet, action)
return nil
}

// filterMultiAddr checks the IP subnets in the filter.
// By default libp2p accepts all incoming dials.
func filterMultiAddr(filter *multiaddr.Filters, addr multiaddr.Multiaddr, log utils.SimpleLogger) bool {
acceptIPNets := filter.FiltersForAction(multiaddr.ActionAccept)

// If an allow list exists, only connections from specified subnets are permitted, all others are rejected.
if len(acceptIPNets) > 0 {
ip, err := multinet.ToIP(addr)
if err != nil {
log.Tracew("Multiaddress invalid ip", "error", err)
return false
}

for _, ipnet := range acceptIPNets {
if ipnet.Contains(ip) {
return true
}
}
return false
}

return !filter.AddrBlocked(addr)
}
171 changes: 171 additions & 0 deletions p2p/connection_gater_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
package p2p

import (
"context"
"fmt"
"net"
"testing"

"github.com/NethermindEth/juno/utils"
"github.com/libp2p/go-libp2p"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/multiformats/go-multiaddr"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

type multiaddrEndpoints struct {
local multiaddr.Multiaddr
remote multiaddr.Multiaddr
}

func (c *multiaddrEndpoints) LocalMultiaddr() multiaddr.Multiaddr {
return c.local
}

func (c *multiaddrEndpoints) RemoteMultiaddr() multiaddr.Multiaddr {
return c.remote
}

func TestConnectionGater_AllowAll(t *testing.T) {
ipAddr := net.ParseIP("127.0.0.1")

listen, err := multiaddr.NewMultiaddr(fmt.Sprintf("/ip4/%s/tcp/%d", ipAddr.String(), 12345))
require.NoError(t, err)

connGater, err := newConnectionGater([]string{}, []string{}, utils.NewNopZapLogger())
require.NoError(t, err)

h1, err := libp2p.New([]libp2p.Option{libp2p.ListenAddrs(listen), libp2p.ConnectionGater(connGater)}...)
require.NoError(t, err)
defer func() {
err := h1.Close()
require.NoError(t, err)
}()

listen, err = multiaddr.NewMultiaddr(fmt.Sprintf("/ip4/%s/tcp/%d", ipAddr.String(), 12345))
require.NoError(t, err)

h2, err := libp2p.New([]libp2p.Option{libp2p.ListenAddrs(listen)}...)
require.NoError(t, err)
defer func() {
err := h2.Close()
require.NoError(t, err)
}()

multiAddress, err := multiaddr.NewMultiaddr(fmt.Sprintf("/ip4/%s/tcp/%d/p2p/%s", ipAddr, 12345, h2.ID()))
require.NoError(t, err)
addrInfo, err := peer.AddrInfoFromP2pAddr(multiAddress)
require.NoError(t, err)
err = h1.Connect(context.Background(), *addrInfo)
assert.NotNil(t, err, "Connection shouldn't be forbidden by connection gater")
}

func TestConnectionGater_DenyPeer(t *testing.T) {
var (
ipAddr = net.ParseIP("127.0.0.1")
cidr = "127.0.0.0/8"
)

listen, err := multiaddr.NewMultiaddr(fmt.Sprintf("/ip4/%s/tcp/%d", ipAddr.String(), 12345))
require.NoError(t, err)

connGater, err := newConnectionGater([]string{cidr}, []string{}, utils.NewNopZapLogger())
require.NoError(t, err)

h1, err := libp2p.New([]libp2p.Option{libp2p.ListenAddrs(listen), libp2p.ConnectionGater(connGater)}...)
require.NoError(t, err)
defer func() {
err := h1.Close()
require.NoError(t, err)
}()

listen, err = multiaddr.NewMultiaddr(fmt.Sprintf("/ip4/%s/tcp/%d", ipAddr.String(), 12345))
require.NoError(t, err)

h2, err := libp2p.New([]libp2p.Option{libp2p.ListenAddrs(listen)}...)
require.NoError(t, err)
defer func() {
err := h2.Close()
require.NoError(t, err)
}()

multiAddress, err := multiaddr.NewMultiaddr(fmt.Sprintf("/ip4/%s/tcp/%d/p2p/%s", ipAddr, 12345, h2.ID()))
require.NoError(t, err)
addrInfo, err := peer.AddrInfoFromP2pAddr(multiAddress)
require.NoError(t, err)
err = h1.Connect(context.Background(), *addrInfo)
assert.NotNil(t, err, "Connection should be forbidden by connection gater")
}

func TestConnectionGater(t *testing.T) {
tests := []struct {
name string
denyCIDR []string
allowCIDR []string
addr string
expectDial bool
expectAccept bool
}{
{
name: "Default",
denyCIDR: []string{},
addr: "/ip4/127.0.0.1/tcp/1234",
expectDial: true,
expectAccept: true,
},
{
name: "DenyCIDR_SameCidr",
denyCIDR: []string{"127.0.0.0/8"},
addr: "/ip4/127.0.0.1/tcp/1234",
expectDial: false,
expectAccept: false,
},
{
name: "DenyCIDR_DifferentCidr",
denyCIDR: []string{"192.168.0.0/16"},
addr: "/ip4/127.0.0.1/tcp/1234",
expectDial: true,
expectAccept: true,
},
{
name: "AllowCIDR_SameCIDR",
allowCIDR: []string{"127.0.0.0/8"},
addr: "/ip4/127.0.0.1/tcp/1234",
expectDial: true,
expectAccept: true,
},
{
name: "AllowCIDR_DifferentCidr",
allowCIDR: []string{"192.168.0.0/16"},
addr: "/ip4/127.0.0.1/tcp/1234",
expectDial: false,
expectAccept: false,
},
{
name: "Collision",
allowCIDR: []string{"127.0.0.0/8"},
denyCIDR: []string{"127.0.0.0/8"},
addr: "/ip4/127.0.0.1/tcp/1234",
expectDial: false,
expectAccept: false,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
connGater, err := newConnectionGater(tt.denyCIDR, tt.allowCIDR, utils.NewNopZapLogger())
require.NoError(t, err)

// Test InterceptAddrDial
addr, err := multiaddr.NewMultiaddr(tt.addr)
require.NoError(t, err)
resultDial := connGater.InterceptAddrDial("", addr)
require.Equal(t, tt.expectDial, resultDial)

// Test InterceptAccept
resultAccept := connGater.InterceptAccept(&multiaddrEndpoints{remote: addr})
require.Equal(t, tt.expectAccept, resultAccept)
})
}
}
9 changes: 8 additions & 1 deletion p2p/p2p.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ type Service struct {
}

func New(addr, publicAddr, version, peers, privKeyStr string, feederNode bool, bc *blockchain.Blockchain, snNetwork *utils.Network,
log utils.SimpleLogger, database db.DB,
log utils.SimpleLogger, database db.DB, denyListCIDR []string, allowListCIDR []string,
) (*Service, error) {
if addr == "" {
// 0.0.0.0/tcp/0 will listen on any interface device and assing a free port.
Expand Down Expand Up @@ -89,6 +89,11 @@ func New(addr, publicAddr, version, peers, privKeyStr string, feederNode bool, b
return addrs
}

connGater, err := newConnectionGater(denyListCIDR, allowListCIDR, log)
if err != nil {
return nil, err
}

p2pHost, err := libp2p.New(
libp2p.ListenAddrs(sourceMultiAddr),
libp2p.Identity(prvKey),
Expand All @@ -103,6 +108,8 @@ func New(addr, publicAddr, version, peers, privKeyStr string, feederNode bool, b
libp2p.EnableHolePunching(),
// Try to open a port in the NAT router to accept incoming connections.
libp2p.NATPortMap(),
// Manage inbound / outbound connections.
libp2p.ConnectionGater(connGater),
)
if err != nil {
return nil, err
Expand Down
Loading