-
Notifications
You must be signed in to change notification settings - Fork 1
/
ban.go
120 lines (100 loc) · 2.5 KB
/
ban.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package main
import (
"net"
"time"
"gorm.io/gorm"
)
const (
isoDate = "2006-01-02T15:04:05"
)
type Ban struct {
gorm.Model
Address []byte `gorm:"not null"`
Mask int `gorm:"not null"`
Name string
Hash string
Reason string
Start int64
Duration int
}
func (server *Server) GetAllBanList() []Ban {
var bans []Ban
server.db.Model(&Ban{}).Where("start + duration > ? OR duration = 0", time.Now().Unix()).Find(&bans)
return bans
}
func (server *Server) PurgeBanList() {
server.db.Exec("DELETE FROM bans;")
server.db.Exec("UPDATE sqlite_sequence SET seq = 0 WHERE name = 'bans';")
server.db.Exec("VACUUM")
return
}
func (server *Server) OverrideBanList(banList []Ban) {
server.PurgeBanList()
for _, b := range banList {
server.db.Create(&b)
}
return
}
// AppendBan append a ban to the banlist
func (server *Server) AppendBan(ban *Ban) {
server.db.Create(ban)
return
}
// IsCertHashBanned Is the certificate hash banned?
func (server *Server) IsCertHashBanned(hash string) bool {
var count int64
server.db.Model(&Ban{}).Where("hash = ? AND (start + duration > ? OR duration = 0)", hash, time.Now().Unix()).Count(&count)
return count > 0
}
func (ban Ban) IPMask() (mask net.IPMask) {
allbits := ban.Mask
for i := 0; i < 16; i++ {
bits := allbits
if bits > 0 {
if bits > 8 {
bits = 8
}
mask = append(mask, byte((1<<uint(bits))-1))
} else {
mask = append(mask, byte(0))
}
allbits -= 8
}
return
}
// Match checks whether an IP matches a Ban
func (ban Ban) Match(ip net.IP) bool {
bannedIP := net.IP(ban.Address)
banned := bannedIP.Mask(ban.IPMask())
masked := ip.Mask(ban.IPMask())
return banned.Equal(masked)
}
// IsConnectionBanned Is the incoming connection conn banned?
func (server *Server) IsConnectionBanned(IP net.IP) bool {
bans := server.GetAllBanList()
// addr := conn.RemoteAddr().(*net.TCPAddr)
for _, ban := range bans {
if ban.Match(IP) {
return true
}
}
if r, o := server.tempIPBan.Get(IP.String()); o == true && time.Now().Unix()-r.(int64) < 10*60 {
return true
}
return false
}
// SetISOStartDate Set Start date from an ISO 8601 date (in UTC)
func (ban *Ban) SetISOStartDate(isodate string) {
startTime, err := time.Parse(isoDate, isodate)
if err != nil {
ban.Start = 0
} else {
ban.Start = startTime.Unix()
}
}
// ISOStartDate returns the currently set start date as an ISO 8601-formatted
// date (in UTC).
func (ban Ban) ISOStartDate() string {
startTime := time.Unix(ban.Start, 0).UTC()
return startTime.Format(isoDate)
}