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

Configurable User Agent Filtering for IBD #11

Open
wants to merge 3 commits into
base: master
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
9 changes: 7 additions & 2 deletions btcd.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"runtime"
"runtime/debug"
"runtime/pprof"
"strings"

"github.com/roasbeef/btcd/blockchain/indexers"
"github.com/roasbeef/btcd/database"
Expand Down Expand Up @@ -144,9 +145,13 @@ func btcdMain(serverChan chan<- *server) error {
return nil
}

// Parse the black and whitelists as comma separated lists.
agentBlacklist := strings.Split(cfg.AgentBlacklist, ",")
agentWhitelist := strings.Split(cfg.AgentWhitelist, ",")

// Create server and start it.
server, err := newServer(cfg.Listeners, db, activeNetParams.Params,
interrupt)
server, err := newServer(cfg.Listeners, agentBlacklist, agentWhitelist,
db, activeNetParams.Params, interrupt)
if err != nil {
// TODO: this logging could do with some beautifying.
btcdLog.Errorf("Unable to start server on %v: %v",
Expand Down
6 changes: 4 additions & 2 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ import (
"strings"
"time"

"github.com/btcsuite/go-socks/socks"
flags "github.com/jessevdk/go-flags"
"github.com/roasbeef/btcd/blockchain"
"github.com/roasbeef/btcd/chaincfg"
"github.com/roasbeef/btcd/chaincfg/chainhash"
Expand All @@ -28,8 +30,6 @@ import (
_ "github.com/roasbeef/btcd/database/ffldb"
"github.com/roasbeef/btcd/mempool"
"github.com/roasbeef/btcutil"
"github.com/btcsuite/go-socks/socks"
flags "github.com/jessevdk/go-flags"
)

const (
Expand Down Expand Up @@ -104,6 +104,8 @@ type config struct {
BanDuration time.Duration `long:"banduration" description:"How long to ban misbehaving peers. Valid time units are {s, m, h}. Minimum 1 second"`
BanThreshold uint32 `long:"banthreshold" description:"Maximum allowed ban score before disconnecting and banning misbehaving peers."`
Whitelists []string `long:"whitelist" description:"Add an IP network or IP that will not be banned. (eg. 192.168.1.0/24 or ::1)"`
AgentBlacklist string `long:"agentblacklist" description:"A comma separated list of user agents substrings to which btcd will not allow connections."`
AgentWhitelist string `long:"agentwhitelist" description:"A comma separated list of user agent substrings to which must be present before allowing a particular connection, the whitelist is applied after the blacklist. An empty whitelist will allow all agents that do not fail the blacklist."`
RPCUser string `short:"u" long:"rpcuser" description:"Username for RPC connections"`
RPCPass string `short:"P" long:"rpcpass" default-mask:"-" description:"Password for RPC connections"`
RPCLimitUser string `long:"rpclimituser" description:"Username for limited RPC connections"`
Expand Down
68 changes: 67 additions & 1 deletion server.go
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,14 @@ type server struct {
// messages for each filter type.
cfCheckptCaches map[wire.FilterType][]cfHeaderKV
cfCheckptCachesMtx sync.RWMutex

// agentBlacklist is a list of blacklisted substrings by which to filter
// user agents.
agentBlacklist []string

// agentWhitelist is a list of whitelisted user agent substrings, no
// whitelisting will be applied if the list is empty or nil.
agentWhitelist []string
}

// serverPeer extends the peer to maintain state shared by the server and
Expand Down Expand Up @@ -1470,6 +1478,12 @@ func (s *server) handleAddPeerMsg(state *peerState, sp *serverPeer) bool {
return false
}

// Disconnect peers with unwanted user agents.
if sp.HasUndesiredUserAgent(s.agentBlacklist, s.agentWhitelist) {
sp.Disconnect()
return false
}

// Ignore new peers if we're shutting down.
if atomic.LoadInt32(&s.shutdown) != 0 {
srvrLog.Infof("New peer %s ignored - server is shutting down", sp)
Expand Down Expand Up @@ -2421,7 +2435,10 @@ func setupRPCListeners() ([]net.Listener, error) {
// newServer returns a new btcd server configured to listen on addr for the
// bitcoin network type specified by chainParams. Use start to begin accepting
// connections from peers.
func newServer(listenAddrs []string, db database.DB, chainParams *chaincfg.Params, interrupt <-chan struct{}) (*server, error) {
func newServer(listenAddrs, agentBlacklist, agentWhitelist []string,
db database.DB, chainParams *chaincfg.Params,
interrupt <-chan struct{}) (*server, error) {

services := defaultServices
if cfg.NoPeerBloomFilters {
services &^= wire.SFNodeBloom
Expand All @@ -2445,6 +2462,9 @@ func newServer(listenAddrs []string, db database.DB, chainParams *chaincfg.Param
}
}

srvrLog.Infof("Using agent blacklist: %s and whitelist: %s",
agentBlacklist, agentWhitelist)

s := server{
chainParams: chainParams,
addrManager: amgr,
Expand All @@ -2464,6 +2484,8 @@ func newServer(listenAddrs []string, db database.DB, chainParams *chaincfg.Param
sigCache: txscript.NewSigCache(cfg.SigCacheMaxSize),
hashCache: txscript.NewHashCache(cfg.SigCacheMaxSize),
cfCheckptCaches: make(map[wire.FilterType][]cfHeaderKV),
agentBlacklist: agentBlacklist,
agentWhitelist: agentWhitelist,
}

// Create the transaction and address indexes if needed.
Expand Down Expand Up @@ -3016,3 +3038,47 @@ func mergeCheckpoints(defaultCheckpoints, additional []chaincfg.Checkpoint) []ch
sort.Sort(checkpointSorter(checkpoints))
return checkpoints
}

// HasUndesiredUserAgent determines whether the server should continue to pursue
// a connection with this peer based on its advertised user agent. It performs
// the following steps:
// 1) Reject the peer if it contains a blacklisted agent.
// 2) If no whitelist is provided, accept all user agents.
// 3) Accept the peer if it contains a whitelisted agent.
// 4) Reject all other peers.
func (sp *serverPeer) HasUndesiredUserAgent(blacklistedAgents,
whitelistedAgents []string) bool {

agent := sp.UserAgent()

// First, if peer's user agent contains any blacklisted substring, we
// will ignore the connection request.
for _, blacklistedAgent := range blacklistedAgents {
if strings.Contains(agent, blacklistedAgent) {
srvrLog.Debugf("Ignoring peer %s, user agent "+
"contains blacklisted user agent: %s", sp,
agent)
return true
}
}

// If no whitelist is provided, we will accept all user agents.
if len(whitelistedAgents) == 0 {
return false
}

// Peer's user agent passed blacklist. Now check to see if it contains
// one of our whitelisted user agents, if so accept.
for _, whitelistedAgent := range whitelistedAgents {
if strings.Contains(agent, whitelistedAgent) {
return false
}
}

// Otherwise, the peer's user agent was not included in our whitelist.
// Ignore just in case it could stall the initial block download.
srvrLog.Debugf("Ignoring peer %s, user agent: %s not found in "+
"whitelist", sp, agent)

return true
}