forked from oftn-oswg/zerodrop
/
blacklist.go
349 lines (295 loc) · 7.44 KB
/
blacklist.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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
package main
import (
"fmt"
"log"
"net"
"regexp"
"strconv"
"strings"
"github.com/oschwald/geoip2-golang"
)
type ZerodropBlacklistItem struct {
Comment string
Negation bool
All bool
Network *net.IPNet
IP net.IP
Hostname string
Regexp *regexp.Regexp
Geofence *ZerodropGeofence
}
func (i ZerodropBlacklistItem) String() (value string) {
if i.Negation {
value += "!"
}
if i.All {
value += "* # Wildcard"
return
}
if i.Network != nil {
value += i.Network.String() + " # Network"
return
}
if i.IP != nil {
value += i.IP.String() + " # IP Address"
return
}
if i.Hostname != "" {
value += i.Hostname + " # Hostname"
return
}
if i.Regexp != nil {
value += "~"
value += i.Regexp.String() + " # Regular Expression"
return
}
if i.Geofence != nil {
value += "@ " +
strconv.FormatFloat(i.Geofence.Latitude, 'f', -1, 64) + ", " +
strconv.FormatFloat(i.Geofence.Longitude, 'f', -1, 64) + " (" +
strconv.FormatFloat(i.Geofence.Radius, 'f', -1, 64) + "m) # Geofence"
return
}
if i.Comment != "" {
value += "# " + i.Comment
}
return
}
type ZerodropBlacklist struct {
List []*ZerodropBlacklistItem
}
func (b ZerodropBlacklist) String() string {
itemCount := 0
// Stringify items
items := make([]string, len(b.List)+1)
for index, item := range b.List {
if item.Comment == "" {
itemCount++
}
items[index+1] = item.String()
}
// Blacklist comment header
switch itemCount {
case 0:
items[0] = "# Empty blacklist"
case 1:
items[0] = "# Blacklist with 1 item"
default:
items[0] = "# Blacklist with " + strconv.Itoa(itemCount) + " items"
}
return strings.Join(items, "\n")
}
var geofenceRegexp = regexp.MustCompile(`^([-+]?[0-9]*\.?[0-9]+)[^-+0-9]+([-+]?[0-9]*\.?[0-9]+)(?:[^0-9]+([0-9]*\.?[0-9]+)([A-Za-z]*)[^0-9]*)?$`)
var geofenceUnits = map[string]float64{
"": 1.0,
"m": 1.0,
"km": 1000.0,
"mi": 1609.0,
"ft": 1609.0 / 5280.0,
}
func ParseBlacklist(text string) ZerodropBlacklist {
lines := strings.Split(text, "\n")
blacklist := ZerodropBlacklist{List: []*ZerodropBlacklistItem{}}
for _, line := range lines {
// A line with # serves as a comment.
if commentStart := strings.IndexByte(line, '#'); commentStart >= 0 {
line = line[:commentStart]
}
// A blank line matches no files,
// so it can serve as a separator for readability.
line = strings.TrimSpace(line)
if line == "" {
continue
}
item := &ZerodropBlacklistItem{}
// An optional prefix "!" which negates the pattern;
// any matching address/host excluded by a previous pattern
// will become included again.
if line[0] == '!' {
item.Negation = true
line = strings.TrimSpace(line[1:])
}
// A line with only "*" matches everything,
// allowing the creation of a whitelist.
if line == "*" {
item.All = true
blacklist.Add(item)
continue
}
switch line[0] {
case '@':
// An optional prefix "@" indicates a geofencing target.
var lat, lng, radius float64 = 0, 0, 25
line = strings.TrimSpace(line[1:])
matches := geofenceRegexp.FindStringSubmatch(line)
if len(matches) == 5 {
var err error
latString, lngString, radiusString, units :=
matches[1], matches[2], matches[3], strings.ToLower(matches[4])
// Parse latitude
if lat, err = strconv.ParseFloat(latString, 64); err != nil {
item.Comment = fmt.Sprintf(
"Error: %s: could not parse latitude: %s",
line, err.Error())
blacklist.Add(item)
continue
}
// Parse longitude
if lng, err = strconv.ParseFloat(lngString, 64); err != nil {
item.Comment = fmt.Sprintf(
"Error: %s: could not parse longitude: %s",
line, err.Error())
blacklist.Add(item)
continue
}
// Parse optional radius
if radiusString != "" {
if radius, err = strconv.ParseFloat(radiusString, 64); err != nil {
item.Comment = fmt.Sprintf(
"Error: %s: could not parse radius: %s",
line, err.Error())
blacklist.Add(item)
continue
}
}
// Parse units
factor, ok := geofenceUnits[units]
if !ok {
item.Comment = fmt.Sprintf(
"Error: %s: invalid radial units: %s",
line, strconv.Quote(units))
blacklist.Add(item)
continue
}
radius *= factor
} else {
item.Comment = fmt.Sprintf(
"Error: %s: invalid format: must be <lng>, <lng> (<radius><unit>)?",
line)
blacklist.Add(item)
continue
}
item.Geofence = &ZerodropGeofence{
Latitude: lat,
Longitude: lng,
Radius: radius,
}
blacklist.Add(item)
continue
case '~':
// An optional prefix "~" indicates a hostname regular expression match.
line = strings.TrimSpace(line[1:])
reg, err := regexp.Compile(line)
if err != nil {
item.Comment = fmt.Sprintf(
"Error: %s: malformed regular expression: %s",
line, err.Error())
blacklist.Add(item)
continue
}
item.Regexp = reg
blacklist.Add(item)
continue
}
// If a CIDR notation is given, then parse that as an IP network.
_, network, err := net.ParseCIDR(line)
if err == nil {
item.Network = network
blacklist.Add(item)
continue
}
// If an IP address is given, parse as unique IP.
if ip := net.ParseIP(line); ip != nil {
item.IP = ip
blacklist.Add(item)
continue
}
// Otherwise, treat the pattern as a hostname.
item.Hostname = strings.ToLower(line)
blacklist.Add(item)
}
return blacklist
}
func (b *ZerodropBlacklist) Add(item *ZerodropBlacklistItem) {
b.List = append(b.List, item)
}
func (b *ZerodropBlacklist) Allow(ip net.IP, geodb *geoip2.Reader) bool {
allow := true
user := (*ZerodropGeofence)(nil)
for _, item := range b.List {
match := false
if item.All {
// Wildcard
match = true
} else if item.Network != nil {
// IP Network
match = item.Network.Contains(ip)
} else if item.IP != nil {
// IP Address
match = item.IP.Equal(ip)
} else if item.Hostname != "" {
// Hostname
addrs, err := net.LookupIP(item.Hostname)
if err != nil {
for _, addr := range addrs {
if addr.Equal(ip) {
match = true
break
}
}
}
names, err := net.LookupAddr(ip.String())
if err != nil {
for _, name := range names {
name = strings.ToLower(name)
if name == item.Hostname {
match = true
break
}
}
}
} else if item.Regexp != nil {
// Regular Expression
names, err := net.LookupAddr(ip.String())
if err != nil {
for _, name := range names {
name = strings.ToLower(name)
if item.Regexp.Match([]byte(name)) {
match = true
break
}
}
}
} else if item.Geofence != nil {
if geodb == nil {
log.Println("Denying access to geofenced blacklist: No GeoDB provided.")
return false
}
if user == nil {
record, err := geodb.City(ip)
if err != nil {
log.Println("Denying access to geofenced blacklist: Error loading IP.")
return false
}
user = &ZerodropGeofence{
Latitude: record.Location.Latitude,
Longitude: record.Location.Longitude,
Radius: float64(record.Location.AccuracyRadius) * 1000.0, // Convert km to m
}
}
bounds := item.Geofence
boundsIntersect := bounds.Intersection(user)
if item.Negation {
// Whitelist if user is completely contained within bounds
match = boundsIntersect&IsSuperset != 0
} else {
// Blacklist if user intersects at all with bounds
match = !(boundsIntersect&IsDisjoint != 0)
}
}
if match {
allow = item.Negation
}
}
return allow
}