-
Notifications
You must be signed in to change notification settings - Fork 125
/
dns.go
121 lines (95 loc) · 2.2 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
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
package cachet
import (
"net"
"regexp"
"strings"
"github.com/Sirupsen/logrus"
"github.com/miekg/dns"
)
type DNSAnswer struct {
Regex string
regexp *regexp.Regexp
Exact string
}
type DNSMonitor struct {
AbstractMonitor `mapstructure:",squash"`
// IP:port format or blank to use system defined DNS
DNS string
// A(default), AAAA, MX, ...
Question string
question uint16
Answers []DNSAnswer
}
func (monitor *DNSMonitor) Validate() []string {
errs := monitor.AbstractMonitor.Validate()
if len(monitor.DNS) == 0 {
config, _ := dns.ClientConfigFromFile("/etc/resolv.conf")
if len(config.Servers) > 0 {
monitor.DNS = net.JoinHostPort(config.Servers[0], config.Port)
}
}
if len(monitor.DNS) == 0 {
monitor.DNS = "8.8.8.8:53"
}
if len(monitor.Question) == 0 {
monitor.Question = "A"
}
monitor.Question = strings.ToUpper(monitor.Question)
monitor.question = findDNSType(monitor.Question)
if monitor.question == 0 {
errs = append(errs, "Could not look up DNS question type")
}
for i, a := range monitor.Answers {
if len(a.Regex) > 0 {
monitor.Answers[i].regexp, _ = regexp.Compile(a.Regex)
}
}
return errs
}
func (monitor *DNSMonitor) test() bool {
m := new(dns.Msg)
m.SetQuestion(dns.Fqdn(monitor.Target), monitor.question)
m.RecursionDesired = true
c := new(dns.Client)
r, _, err := c.Exchange(m, monitor.DNS)
if err != nil {
logrus.Warnf("DNS error: %v", err)
return false
}
if r.Rcode != dns.RcodeSuccess {
return false
}
for _, check := range monitor.Answers {
found := false
for _, answer := range r.Answer {
found = matchAnswer(answer, check)
if found {
break
}
}
if !found {
logrus.Warnf("DNS check failed: %v. Not found in any of %v", check, r.Answer)
return false
}
}
return true
}
func findDNSType(t string) uint16 {
for rr, strType := range dns.TypeToString {
if t == strType {
return rr
}
}
return 0
}
func matchAnswer(answer dns.RR, check DNSAnswer) bool {
fields := []string{}
for i := 0; i < dns.NumField(answer); i++ {
fields = append(fields, dns.Field(answer, i+1))
}
str := strings.Join(fields, " ")
if check.regexp != nil {
return check.regexp.Match([]byte(str))
}
return str == check.Exact
}