-
Notifications
You must be signed in to change notification settings - Fork 0
/
block.go
443 lines (348 loc) · 8.76 KB
/
block.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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
// Package example is a CoreDNS plugin that prints "example" to stdout on every packet received.
//
// It serves as an example CoreDNS plugin with numerous code comments.
package block
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"slices"
"sync"
"time"
"github.com/coredns/coredns/plugin"
"github.com/coredns/coredns/plugin/metrics"
clog "github.com/coredns/coredns/plugin/pkg/log"
"github.com/coredns/coredns/request"
"github.com/miekg/dns"
"github.com/spr-networks/sprbus"
)
import bolt "go.etcd.io/bbolt"
var log = clog.NewWithPlugin("block")
var gDomainBucket = "domains"
type BlockMetrics struct {
TotalQueries int64
BlockedQueries int64
BlockedDomains int64
}
var gMetrics = BlockMetrics{}
type DomainValue struct {
List_ids []int
Disabled bool
}
var Dmtx sync.RWMutex
var Stagemtx sync.RWMutex
// Block is the block plugin.
type Block struct {
update map[string]DomainValue
stop chan struct{}
config SPRBlockConfig
superapi_enabled bool
Db *bolt.DB
DbPath string
Next plugin.Handler
}
func New() *Block {
return &Block{
update: make(map[string]DomainValue),
stop: make(chan struct{}),
}
}
type DNSBlockEvent struct {
ClientIP string
Name string
}
type DNSOverrideEvent struct {
ClientIP string
IP string // the new IP response
Name string
}
func (i *DNSBlockEvent) String() string {
x, _ := json.Marshal(i)
return string(x)
}
func (i *DNSOverrideEvent) String() string {
x, _ := json.Marshal(i)
return string(x)
}
// ServeDNS implements the plugin.Handler interface.
func (b *Block) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
state := request.Request{W: w, Req: r}
returnIP := ""
gMetrics.TotalQueries++
if b.blocked(state.IP(), state.Name(), &returnIP) {
gMetrics.BlockedQueries++
blockCount.WithLabelValues(metrics.WithServer(ctx)).Inc()
log.Infof("Blocked %s", state.Name())
resp := new(dns.Msg)
resp.SetRcode(r, dns.RcodeNameError)
w.WriteMsg(resp)
event := DNSBlockEvent{state.IP(), state.Name()}
sprbus.PublishString("dns:block:event", event.String())
return dns.RcodeNameError, nil
}
// Rewrite a predefined typeA or typeAAAA response
if returnIP != "" {
resp := new(dns.Msg)
resp.SetRcode(r, dns.RcodeSuccess)
name := r.Question[0].Name
rrType := r.Question[0].Qtype
event := DNSOverrideEvent{state.IP(), returnIP, name}
sprbus.PublishString("dns:override:event", event.String())
if rrType == dns.TypeA {
ans := &dns.A{
Hdr: dns.RR_Header{
Name: name,
Rrtype: rrType,
Class: dns.ClassINET,
Ttl: 1,
},
A: net.ParseIP(returnIP),
}
resp.Answer = append(resp.Answer, ans)
w.WriteMsg(resp)
return dns.RcodeSuccess, nil
} else if rrType == dns.TypeAAAA {
ans := &dns.AAAA{
Hdr: dns.RR_Header{
Name: name,
Rrtype: rrType,
Class: dns.ClassINET,
Ttl: 1,
},
AAAA: net.ParseIP(returnIP),
}
resp.Answer = append(resp.Answer, ans)
w.WriteMsg(resp)
return dns.RcodeSuccess, nil
}
}
return plugin.NextOrFailure(b.Name(), b.Next, ctx, w, r)
}
// Name implements the Handler interface.
func (b *Block) Name() string { return "block" }
func matchOverride(IP string, fullname string, name string, overrides []DomainOverride, returnIP *string) bool {
cur_time := time.Now().Unix()
for _, entry := range overrides {
if entry.Expiration != 0 {
//this override has expired
if entry.Expiration <= cur_time {
continue
}
}
if entry.ClientIP == "" || entry.ClientIP == "*" || entry.ClientIP == IP {
//match wildcard or match IP
//now check if domain matches name to make a decision
if name == entry.Domain || fullname == entry.Domain {
//got a match -> if there is a returnIP set, carry it over
if entry.ResultIP != "" {
*returnIP = entry.ResultIP
}
if len(entry.Tags) > 0 {
//tags were specified, make sure that the IP has one of those set
return IPHasTags(entry.ClientIP, entry.Tags)
}
return true
}
}
}
return false
}
func (b *Block) dumpEntries(w http.ResponseWriter, r *http.Request) {
domains := []string{}
Dmtx.Lock()
err, items := getItems(b.Db, gDomainBucket)
if err != nil {
for _, v := range items {
domains = append(domains, v.Key)
}
}
Dmtx.Unlock()
if err != nil {
http.Error(w, err.Error(), 400)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(domains)
}
var IPTagMap = make(map[string][]string)
var IPPolicyMap = make(map[string][]string)
var IPTagmtx sync.RWMutex
type DeviceEntry struct {
Name string
MAC string
WGPubKey string
VLANTag string
RecentIP string
PSKEntry PSKEntry
Policies []string //tbd: dns quarantine mode in the future?
Groups []string
DeviceTags []string
}
type PSKEntry struct {
Type string
Psk string
}
var DevicesConfigPath = TEST_PREFIX + "/configs/devices/"
var DevicesPublicConfigFile = TEST_PREFIX + "/state/public/devices-public.json"
func APIDevices() (map[string]DeviceEntry, error) {
devs := map[string]DeviceEntry{}
data, err := ioutil.ReadFile(DevicesPublicConfigFile)
if err == nil {
err = json.Unmarshal(data, &devs)
if err != nil {
fmt.Println(err)
return nil, err
}
} else {
fmt.Println(err)
return nil, err
}
return devs, nil
}
func (b *Block) updateIPTags() {
newMap := make(map[string][]string)
newPolicyMap := make(map[string][]string)
devices, err := APIDevices()
if err != nil {
//something failed, stop processing
return
}
for _, entry := range devices {
if entry.RecentIP != "" {
newMap[entry.RecentIP] = entry.DeviceTags
newPolicyMap[entry.RecentIP] = entry.Policies
}
}
IPTagmtx.Lock()
IPTagMap = newMap
IPPolicyMap = newPolicyMap
IPTagmtx.Unlock()
}
func (b *Block) refreshTags() {
b.updateIPTags()
tick := time.NewTicker(1 * time.Minute)
defer tick.Stop()
for {
select {
case <-tick.C:
b.updateIPTags()
case <-b.stop:
return
}
}
}
func IPQuarantined(IP string) bool {
IPTagmtx.RLock()
policies, policy_exists := IPPolicyMap[IP]
IPTagmtx.RUnlock()
if policy_exists {
return slices.Contains(policies, "quarantine")
}
return false
}
func IPHasTags(IP string, applied_tags []string) bool {
if len(applied_tags) == 0 {
return false
}
IPTagmtx.RLock()
device_tags, exists := IPTagMap[IP]
IPTagmtx.RUnlock()
if !exists {
//IP not mapped as having tags, return false
return false
}
for _, applied_tag := range applied_tags {
for _, device_tag := range device_tags {
if applied_tag == device_tag {
return true
}
}
}
return false
}
func (b *Block) deviceMatchBlockListTags(IP string, entry DomainValue) bool {
// a domain was blocked. Check if the list_id has a group specification.
// return true if there is no group specification, or the device is
// in the specified. If the device is not in a specified group, return false
BLmtx.RLock()
defer BLmtx.RUnlock()
for _, list_id := range entry.List_ids {
if list_id >= 0 && int(list_id) < len(b.config.BlockLists) {
applied_tags := b.config.BlockLists[list_id].Tags
if len(applied_tags) == 0 {
//no tags specified, continue
continue
}
//had tags, return true only if IP has that tag. otherwise false
return IPHasTags(IP, applied_tags)
}
}
//no list
return true
}
func (b *Block) getDomain(name string) (DomainValue, bool) {
err, item := getItem(b.Db, gDomainBucket, name)
if err == nil {
return item.Value, true
}
return DomainValue{}, false
}
func (b *Block) checkBlock(IP string, name string, fullname string, returnIP *string) bool {
if b.superapi_enabled {
// do not block for excluded IPs
for _, excludeIP := range b.config.ClientIPExclusions {
if IP == excludeIP {
//not blocked
return false
}
}
if IPQuarantined(IP) {
target := "0.0.0.0"
if b.config.QuarantineHostIP != "" {
target = b.config.QuarantineHostIP
}
*returnIP = target
return false
}
if matchOverride(IP, fullname, name, b.config.PermitDomains, returnIP) {
//permit this domain
return false
}
if matchOverride(IP, fullname, name, b.config.BlockDomains, returnIP) {
//yes blocked
return true
}
}
Dmtx.RLock()
entry, exists := b.getDomain(name)
Dmtx.RUnlock()
if exists && !entry.Disabled {
if b.superapi_enabled {
return b.deviceMatchBlockListTags(IP, entry)
}
return true
}
return false
}
func (b *Block) blocked(IP string, name string, returnIP *string) bool {
if b.checkBlock(IP, name, name, returnIP) {
return true
}
i, end := dns.NextLabel(name, 0)
for !end {
if b.checkBlock(IP, name[i:], name, returnIP) {
return true
}
i, end = dns.NextLabel(name, i)
}
return false
}
func (b *Block) setupDB(filename string) {
Dmtx.Lock()
defer Dmtx.Unlock()
b.Db = BoltOpen(filename)
b.DbPath = filename
}