This repository has been archived by the owner on Mar 21, 2024. It is now read-only.
/
score.go
69 lines (58 loc) · 1.6 KB
/
score.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package security
import (
"sync"
log "github.com/sirupsen/logrus"
)
const (
defaultBanThreshold = uint32(100)
defaultWarnThreshold = uint32(50)
LevelMsgIllegal = 0x01
levelMsgIllegalPersistent = uint32(20)
levelMsgIllegalTransient = uint32(0)
LevelConnException = 0x02
levelConnExceptionPersistent = uint32(0)
levelConnExceptionTransient = uint32(20)
)
type PeersBanScore struct {
peers map[string]*DynamicBanScore
mtx sync.Mutex
}
func NewPeersScore() *PeersBanScore {
return &PeersBanScore{
peers: make(map[string]*DynamicBanScore),
}
}
func (ps *PeersBanScore) DelPeer(ip string) {
ps.mtx.Lock()
defer ps.mtx.Unlock()
delete(ps.peers, ip)
}
func (ps *PeersBanScore) Increase(ip string, level byte, reason string) bool {
ps.mtx.Lock()
defer ps.mtx.Unlock()
var persistent, transient uint32
switch level {
case LevelMsgIllegal:
persistent = levelMsgIllegalPersistent
transient = levelMsgIllegalTransient
case LevelConnException:
persistent = levelConnExceptionPersistent
transient = levelConnExceptionTransient
default:
return false
}
banScore, ok := ps.peers[ip]
if !ok {
banScore = &DynamicBanScore{}
ps.peers[ip] = banScore
}
score := banScore.Increase(persistent, transient)
if score > defaultBanThreshold {
log.WithFields(log.Fields{"module": logModule, "address": ip, "score": score, "reason": reason}).Errorf("banning and disconnecting")
return true
}
if score > defaultWarnThreshold {
log.WithFields(log.Fields{"module": logModule, "address": ip, "score": score, "reason": reason}).Warning("ban score increasing")
}
return false
}