/
plugin_ecs.go
80 lines (69 loc) · 1.52 KB
/
plugin_ecs.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
package main
import (
"math/rand"
"net"
"github.com/jedisct1/dlog"
"github.com/miekg/dns"
)
type PluginECS struct {
nets []*net.IPNet
}
func (plugin *PluginECS) Name() string {
return "ecs"
}
func (plugin *PluginECS) Description() string {
return "Set EDNS-client-subnet information in outgoing queries."
}
func (plugin *PluginECS) Init(proxy *Proxy) error {
plugin.nets = proxy.ednsClientSubnets
dlog.Notice("ECS plugin enabled")
return nil
}
func (plugin *PluginECS) Drop() error {
return nil
}
func (plugin *PluginECS) Reload() error {
return nil
}
func (plugin *PluginECS) Eval(pluginsState *PluginsState, msg *dns.Msg) error {
var options *[]dns.EDNS0
for _, extra := range msg.Extra {
if extra.Header().Rrtype == dns.TypeOPT {
options = &extra.(*dns.OPT).Option
for _, option := range *options {
if option.Option() == dns.EDNS0SUBNET {
return nil
}
}
break
}
}
if options == nil {
msg.SetEdns0(uint16(pluginsState.maxPayloadSize), false)
for _, extra := range msg.Extra {
if extra.Header().Rrtype == dns.TypeOPT {
options = &extra.(*dns.OPT).Option
break
}
}
}
if options == nil {
return nil
}
prr := dns.EDNS0_SUBNET{}
prr.Code = dns.EDNS0SUBNET
net := plugin.nets[rand.Intn(len(plugin.nets))]
bits, totalSize := net.Mask.Size()
if totalSize == 32 {
prr.Family = 1
} else if totalSize == 128 {
prr.Family = 2
} else {
return nil
}
prr.SourceNetmask = uint8(bits)
prr.SourceScope = 0
prr.Address = net.IP
*options = append(*options, &prr)
return nil
}