-
Notifications
You must be signed in to change notification settings - Fork 12
/
dns.go
83 lines (67 loc) · 1.67 KB
/
dns.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
package main
import (
"log"
"strings"
"github.com/miekg/dns"
)
func dnsHandler(w dns.ResponseWriter, r *dns.Msg) {
isDisabledMu.Lock()
isEnabled := !isDisabled
isDisabledMu.Unlock()
if isEnabled {
// Make a copy of the questions (in case we need them for the error response)
qs := make([]dns.Question, len(r.Question))
copy(qs, r.Question)
// If none of the questions are allowed, respond with an error message
if r.Question = filterQuestions(r.Question); len(r.Question) == 0 {
m := &dns.Msg{
MsgHdr: dns.MsgHdr{
Id: r.Id,
Response: true,
Opcode: dns.OpcodeQuery,
Authoritative: true,
RecursionDesired: r.RecursionDesired,
RecursionAvailable: false,
Rcode: dns.RcodeNameError, // NXDOMAIN
},
Question: qs,
}
w.WriteMsg(m)
return
}
}
// Proxy allowed questions upstream
for _, addr := range strings.Split(*dnsProxyTo, ",") {
in, _, err := dnsClient.Exchange(r, addr)
if err != nil {
log.Printf("Exchange(%s) Error: %s\n", addr, err)
continue
}
w.WriteMsg(in)
return
}
dns.HandleFailed(w, r)
}
func filterQuestions(qs []dns.Question) []dns.Question {
var keep []dns.Question
for _, q := range qs {
if isNameAllowed(q.Name) {
keep = append(keep, q)
}
}
return keep
}
func isNameAllowed(n string) bool {
n = strings.TrimSuffix(n, ".")
r, err := db.get(n)
if err != nil {
if err == errRecordNotFound {
// If no record by that name was found, assume it is allowed
return true
}
// For other errors, assume the name is now allowed
log.Printf("db.get(%s) Error: %s\n", n, err)
return false
}
return r.isAllowed()
}