-
Notifications
You must be signed in to change notification settings - Fork 1
/
pcdns.go
389 lines (320 loc) · 7.75 KB
/
pcdns.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
package main
import (
"errors"
"flag"
"github.com/boltdb/bolt"
"github.com/miekg/dns"
"log"
"math"
"net"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
)
var (
tsig *string
db_path *string
port *int
bdb *bolt.DB
logfile *string
pid_file *string
)
const rr_bucket = "rr"
const ip_notice = "192.168.200.1"
func isMalicious(name string) bool {
if name == "www.gfxworld.ws." {
return true
}
return false
}
func getGatewayPolicy(mac string) map[string]map[string]bool {
policyMap := map[string]map[string]map[string]bool {
"08:00:27:9f:e2:a1": map[string]map[string]bool {
"56:84:7a:fe:97:99": map[string]bool {
"www.google.com.": true,
"www.yahoo.com.": true,
},
//"12:34:56:78:aa:bb": false,
},
}
return policyMap[mac]
}
func getKey(domain string, rtype uint16) (r string, e error) {
if n, ok := dns.IsDomainName(domain); ok {
labels := dns.SplitDomainName(domain)
// Reverse domain, starting from top-level domain
// eg. ".com.mkaczanowski.test"
var tmp string
for i := 0; i < int(math.Floor(float64(n / 2))); i++ {
tmp = labels[i]
labels[i] = labels[n - 1]
labels[n - 1] = tmp
}
reverse_domain := strings.Join(labels, ".")
r = strings.Join([]string{reverse_domain, strconv.Itoa(int(rtype))}, "_")
} else {
e = errors.New("Invailid domain: " + domain)
log.Println(e.Error())
}
return r, e
}
func createBucket(bucket string) (err error) {
err = bdb.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucketIfNotExists([]byte(bucket))
if err != nil {
e := errors.New("Create bucket: " + bucket)
log.Println(e.Error())
return e
}
return nil
})
return err
}
func deleteRecord(domain string, rtype uint16) (err error) {
key, _ := getKey(domain, rtype)
err = bdb.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(rr_bucket))
err := b.Delete([]byte(key))
if err != nil {
e := errors.New("Delete record failed for domain: " + domain)
log.Println(e.Error())
return e
}
return nil
})
return err
}
func storeRecord(rr dns.RR) (err error) {
key, _ := getKey(rr.Header().Name, rr.Header().Rrtype)
err = bdb.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(rr_bucket))
err := b.Put([]byte(key), []byte(rr.String()))
if err != nil {
e := errors.New("Store record failed: " + rr.String())
log.Println(e.Error())
return e
}
return nil
})
return err
}
func getRecord(domain string, rtype uint16) (rr dns.RR, err error) {
key, _ := getKey(domain, rtype)
var v []byte
err = bdb.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(rr_bucket))
v = b.Get([]byte(key))
if string(v) == "" {
e := errors.New("Record not found, key: " + key)
log.Println(e.Error())
return e
}
return nil
})
if err == nil {
rr, err = dns.NewRR(string(v))
}
return rr, err
}
func updateRecord(r dns.RR, q *dns.Question) {
var (
rr dns.RR
name string
rtype uint16
ttl uint32
ip net.IP
)
header := r.Header()
name = header.Name
rtype = header.Rrtype
ttl = header.Ttl
if _, ok := dns.IsDomainName(name); ok {
if header.Class == dns.ClassANY && header.Rdlength == 0 {
// Delete record
deleteRecord(name, rtype)
} else {
// Add record
rheader := dns.RR_Header{
Name: name,
Rrtype: rtype,
Class: dns.ClassINET,
Ttl: ttl,
}
if a, ok := r.(*dns.A); ok {
rrr, err := getRecord(name, rtype)
if err == nil {
rr = rrr.(*dns.A)
} else {
rr = new(dns.A)
}
ip = a.A
rr.(*dns.A).Hdr = rheader
rr.(*dns.A).A = ip
} else if a, ok := r.(*dns.AAAA); ok {
rrr, err := getRecord(name, rtype)
if err == nil {
rr = rrr.(*dns.AAAA)
} else {
rr = new(dns.AAAA)
}
ip = a.AAAA
rr.(*dns.AAAA).Hdr = rheader
rr.(*dns.AAAA).AAAA = ip
}
storeRecord(rr)
}
}
}
func parseQuery(m *dns.Msg, req *dns.Msg) {
var rr dns.RR
var rgMac, clientMac string
opt := req.IsEdns0();
if opt != nil {
for _, o := range opt.Option {
lo := o.(*dns.EDNS0_LOCAL);
if lo.Option() == 65001 {
rgMac = string(lo.Data)
} else if lo.Option() == 65002 {
clientMac = string(lo.Data)
}
}
if rgMac != "" {
log.Printf("Gateway MAC address >%s", rgMac)
}
if clientMac != "" {
log.Printf("Client MAC address >%s", clientMac)
}
}
policy := getGatewayPolicy(rgMac)
for _, q := range m.Question {
malicious := isMalicious(q.Name)
if (malicious) {
log.Printf("Domain %s is detected malicious and blocked", q.Name)
mr := new(dns.A)
mr.A = net.ParseIP(ip_notice)
mr.Hdr = dns.RR_Header{Name: q.Name, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 86400}
m.Answer = append(m.Answer, mr)
return
}
blocked := policy[clientMac][q.Name]
if blocked {
log.Printf("Domain %s is blocked under Gateway and Client's policy", q.Name)
br := new(dns.A)
br.A = net.ParseIP(ip_notice)
br.Hdr = dns.RR_Header{Name: q.Name, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: 3600}
m.Answer = append(m.Answer, br)
return
}
if read_rr, e := getRecord(q.Name, q.Qtype); e == nil {
rr = read_rr.(dns.RR)
if rr.Header().Name == q.Name {
m.Answer = append(m.Answer, rr)
}
}
}
}
func handleDnsRequest(w dns.ResponseWriter, r *dns.Msg) {
m := new(dns.Msg)
m.SetReply(r)
m.Compress = false
log.Printf("DNS Request >\n%s", r.String())
switch r.Opcode {
case dns.OpcodeQuery:
parseQuery(m, r)
case dns.OpcodeUpdate:
for _, question := range r.Question {
for _, rr := range r.Ns {
updateRecord(rr, &question)
}
}
}
if r.IsTsig() != nil {
if w.TsigStatus() == nil {
m.SetTsig(r.Extra[len(r.Extra) - 1].(*dns.TSIG).Hdr.Name,
dns.HmacMD5, 300, time.Now().Unix())
} else {
log.Println("Status", w.TsigStatus().Error())
}
}
w.WriteMsg(m)
}
func serve(name, secret string, port int) {
server := &dns.Server{Addr: ":" + strconv.Itoa(port), Net: "udp"}
if name != "" {
server.TsigSecret = map[string]string{name: secret}
}
err := server.ListenAndServe()
defer server.Shutdown()
if err != nil {
log.Fatalf("Failed to setup the udp server: %sn", err.Error())
}
}
func main() {
var (
name string // tsig keyname
secret string // tsig base64
fh *os.File // logfile handle
)
// Parse flags
logfile = flag.String("logfile", "", "path to log file")
port = flag.Int("port", 53, "server port")
tsig = flag.String("tsig", "", "use MD5 hmac tsig: keyname:base64")
db_path = flag.String("db_path", "./dyndns.db", "location where db will be stored")
pid_file = flag.String("pid", "./go-dyndns.pid", "pid file location")
flag.Parse()
// Open db
db, err := bolt.Open(*db_path, 0600,
&bolt.Options{Timeout: 10 * time.Second})
if err != nil {
log.Fatal(err)
}
defer db.Close()
bdb = db
// Create dns bucket if doesn't exist
createBucket(rr_bucket)
// Attach request handler func
dns.HandleFunc(".", handleDnsRequest)
// Tsig extract
if *tsig != "" {
a := strings.SplitN(*tsig, ":", 2)
name, secret = dns.Fqdn(a[0]), a[1]
}
// Logger setup
if *logfile != "" {
if _, err := os.Stat(*logfile); os.IsNotExist(err) {
if file, err := os.Create(*logfile); err != nil {
if err != nil {
log.Panic("Couldn't create log file: ", err)
}
fh = file
}
} else {
fh, _ = os.OpenFile(*logfile, os.O_RDWR | os.O_CREATE | os.O_APPEND, 0666)
}
defer fh.Close()
log.SetOutput(fh)
}
// Pidfile
file, err := os.OpenFile(*pid_file, os.O_RDWR | os.O_CREATE, 0666)
if err != nil {
log.Panic("Couldn't create pid file: ", err)
} else {
file.Write([]byte(strconv.Itoa(syscall.Getpid())))
defer file.Close()
}
// Start server
go serve(name, secret, *port)
sig := make(chan os.Signal)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
endless:
for {
select {
case s := <-sig:
log.Printf("Signal (%d) received, stoppingn", s)
break endless
}
}
}