-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdbcheck.go
444 lines (347 loc) · 9.38 KB
/
dbcheck.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
444
package dbcheck
import (
"database/sql"
"errors"
"fmt"
"net"
"strconv"
"strings"
"math"
"context"
"github.com/coredns/coredns/plugin"
"github.com/coredns/coredns/request"
"github.com/miekg/dns"
_ "github.com/lib/pq"
)
type DbCheck struct {
Next plugin.Handler
Database string
ConnectionString string
Fallthrough bool
Recursion bool
db *sql.DB
}
type Zone struct {
id int64
name string
}
func min(a int, b int) int {
if (a < b) {
return a
}
return b
}
func (check *DbCheck) Init() error {
if check.Database != "" {
fmt.Printf("Connecting to database %s %s\n", check.Database, check.ConnectionString)
con, err := sql.Open(check.Database, check.ConnectionString)
check.db = con
if check.db != nil {
fmt.Printf("Initialized database!")
}
if err != nil {
fmt.Printf("Error while connecting to database: %s", err)
return err
}
}
return nil
}
func (check *DbCheck) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
found := false
state := request.Request{W: w, Req: r}
if check.db == nil {
return check.failOrFallthrough(ctx, w, r, plugin.Error(check.Name(), errors.New("No db connection initialized")))
}
if state.QClass() != dns.ClassINET {
return check.failOrFallthrough(ctx, w, r, plugin.Error(check.Name(), errors.New("can only deal with ClassINET")))
}
if mapTypeToTable(state.QType()) == "" {
return check.failOrFallthrough(ctx, w, r, plugin.Error(check.Name(), errors.New("unsupported query type")))
}
qname := state.Name()
m := new(dns.Msg)
m.SetReply(r)
m.Authoritative, m.RecursionAvailable, m.Compress = true, false, true
/* Explicit support for
NS
SOA
MX
A
AAAA
PTR
CNAME
TXT
SRV
*/
// TODO multiple answers
qnames := dns.SplitDomainName(qname)
param_names := make([]string, len(qnames))
params := make([]interface{}, len(qnames))
for i := range qnames {
param_names[i] = "$" + strconv.Itoa(i+1)
params[i] = strings.Join(qnames[i:], ".") + "."
}
// find most matching zone name in sql:
sql := "SELECT id, name FROM zones WHERE deleted_at is null and disabled = false and name in (" + strings.Join(param_names, ",") + ") ORDER BY length(name) DESC"
// check for zone with that name
zones, err := check.db.QueryContext(ctx, sql, params...)
if err != nil {
fmt.Printf("Error occured when looking up zone: %s\n", err)
return check.failOrFallthrough(ctx, w, r, plugin.Error(check.Name(), errors.New("Error occured when looking up zone")))
}
defer zones.Close()
// handle each zone that matched,
// until we find the first record
// longest match first
for zones.Next() {
zone := Zone{}
err := zones.Scan(&zone.id, &zone.name)
if err != nil {
fmt.Printf("Error while scanning row: %s\n", err)
break
}
fmt.Printf("Checking Zone: %d %s\n", zone.id, zone.name)
var rrs []interface{}
// check for the first record of this type
rrs, err = check.findFirstRecord(state, zone, qname)
if rrs == nil && err == nil {
switch state.QType() {
case dns.TypeA:
// Try to match wildcard
rrs, err = check.findFirstRecord(state, zone, "*."+strings.Join(qnames[1:], "."))
}
}
if err != nil {
fmt.Printf("Error occured when looking up records for zone: %s\n", err)
}
if rrs != nil && len(rrs) > 0 {
for _, rr := range rrs {
m.Answer = append(m.Answer, rr.(dns.RR))
}
found = true
break
}
}
if found {
state.SizeAndDo(m)
w.WriteMsg(m)
return dns.RcodeSuccess, nil
}
return check.failOrFallthrough(ctx, w, r, nil)
}
func (check *DbCheck) failOrFallthrough(ctx context.Context, w dns.ResponseWriter, r *dns.Msg, err error) (int, error) {
if check.Fallthrough {
return plugin.NextOrFailure(check.Name(), check.Next, ctx, w, r)
}
return dns.RcodeServerFailure, err
}
func (check *DbCheck) findFirstRecord(state request.Request, zone Zone, qname string) ([]interface{}, error) {
params_a := make([]interface{}, 2)
params_a[0] = zone.id
if zone.name == qname {
params_a[1] = "@"
} else {
match := strings.TrimRight(qname[:len(qname) - len(zone.name)], ".")
params_a[1] = match
}
records, err := check.db.Query("SELECT id, name, ttl, "+mapTypeToFields(state.QType())+" FROM "+mapTypeToTable(state.QType())+" WHERE deleted_at is null and disabled = false and zone_id = $1 and name = $2", params_a...)
if err != nil {
fmt.Printf("Error occured when looking ip "+mapTypeToTable(state.QType())+" %s\n", err)
return nil, err
}
defer records.Close()
rrs := make([]interface{}, 0)
for records.Next() {
rr, err := mapFieldToRecords(state, zone, records)
if err != nil {
return nil, err
}
fmt.Printf("Found record %+#v\n", rr)
rrs = append(rrs, rr)
}
if len(rrs) > 0 {
return rrs, nil
}
return nil, nil
}
func mapFieldToRecords(state request.Request, zone Zone, records *sql.Rows) (interface{}, error) {
switch state.QType() {
case dns.TypeA:
var id, ttl int64
var name, addr string
records.Scan(&id, &name, &ttl, &addr)
ip := net.ParseIP(addr)
if ip != nil {
rr := &dns.A{
Hdr: dns.RR_Header{Name: state.QName(), Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: uint32(ttl)},
A: ip,
}
return rr, nil
}
case dns.TypeAAAA:
var id, ttl int64
var name, addr string
records.Scan(&id, &name, &ttl, &addr)
ip := net.ParseIP(addr)
if ip != nil {
rr := &dns.AAAA{
Hdr: dns.RR_Header{Name: state.QName(), Rrtype: dns.TypeAAAA, Class: dns.ClassINET, Ttl: uint32(ttl)},
AAAA: ip,
}
return rr, nil
}
case dns.TypeMX:
var id, ttl, preference int64
var name, mx string
records.Scan(&id, &name, &ttl, &preference, &mx)
// append the zone name
if mx[len(mx)-1] != '.' {
mx = mx + "." + zone.name
}
rr := &dns.MX{
Hdr: dns.RR_Header{Name: state.QName(), Rrtype: dns.TypeMX, Class: dns.ClassINET, Ttl: uint32(ttl)},
Preference: uint16(preference),
Mx: mx,
}
return rr, nil
case dns.TypePTR:
var id, ttl int64
var name, ptr string
records.Scan(&id, &name, &ttl, &ptr)
// append the zone name
if ptr[len(ptr)-1] != '.' {
ptr = ptr + "." + zone.name
}
rr := &dns.PTR{
Hdr: dns.RR_Header{Name: state.QName(), Rrtype: dns.TypePTR, Class: dns.ClassINET, Ttl: uint32(ttl)},
Ptr: ptr,
}
return rr, nil
case dns.TypeNS:
var id, ttl int64
var name, ns string
records.Scan(&id, &name, &ttl, &ns)
// append the zone name
if ns[len(ns)-1] != '.' {
ns = ns + "." + zone.name
}
rr := &dns.NS{
Hdr: dns.RR_Header{Name: state.QName(), Rrtype: dns.TypeNS, Class: dns.ClassINET, Ttl: uint32(ttl)},
Ns: ns,
}
return rr, nil
case dns.TypeTXT:
var id, ttl int64
var name, txt string
records.Scan(&id, &name, &ttl, &txt)
var txt_len = int(math.Ceil(float64(len(txt))/float64(255)))
txts := make([]string, txt_len)
// todo test
for i := 0; i < txt_len; i++ {
txts[i] = txt[i * 255:min((i + 1) * 255, len(txt))]
}
rr := &dns.TXT{
Hdr: dns.RR_Header{Name: state.QName(), Rrtype: dns.TypeTXT, Class: dns.ClassINET, Ttl: uint32(ttl)},
Txt: txts,
}
return rr, nil
case dns.TypeSOA:
var id, ttl, serial, refresh, retry, expire, minttl int64
var name, ns, mbox string
records.Scan(&id, &name, &ttl, &ns, &mbox, &serial, &refresh, &retry, &expire, &minttl)
// append the zone name
if ns[len(ns)-1] != '.' {
ns = ns + "." + zone.name
}
rr := &dns.SOA{
Hdr: dns.RR_Header{Name: state.QName(), Rrtype: dns.TypeSOA, Class: dns.ClassINET, Ttl: uint32(ttl)},
Ns: ns,
Mbox: mbox,
Serial: uint32(serial),
Refresh: uint32(refresh),
Retry: uint32(retry),
Expire: uint32(expire),
Minttl: uint32(minttl),
}
return rr, nil
case dns.TypeSRV:
var id, ttl, priority, weight, port int64
var name, target string
records.Scan(&id, &name, &ttl, &priority, &weight, &port, &target)
// append the zone name
if target[len(target)-1] != '.' {
target = target + "." + zone.name
}
rr := &dns.SRV{
Hdr: dns.RR_Header{Name: state.QName(), Rrtype: dns.TypeSRV, Class: dns.ClassINET, Ttl: uint32(ttl)},
Priority: uint16(priority),
Weight: uint16(weight),
Port: uint16(port),
Target: target,
}
return rr, nil
case dns.TypeCNAME:
var id, ttl int64
var name, target string
records.Scan(&id, &name, &ttl, &target)
// append the zone name
if target[len(target)-1] != '.' {
target = target + "." + zone.name
}
rr := &dns.CNAME{
Hdr: dns.RR_Header{Name: state.QName(), Rrtype: dns.TypeCNAME, Class: dns.ClassINET, Ttl: uint32(ttl)},
Target: target,
}
return rr, nil
}
return nil, nil
}
func mapTypeToTable(qtype uint16) string {
switch qtype {
case dns.TypeA:
return "a_records"
case dns.TypeAAAA:
return "aaaa_records"
case dns.TypeMX:
return "mx_records"
case dns.TypePTR:
return "ptr_records"
case dns.TypeNS:
return "ns_records"
case dns.TypeTXT:
return "txt_records"
case dns.TypeSOA:
return "soa_records"
case dns.TypeSRV:
return "srv_records"
case dns.TypeCNAME:
return "cname_records"
}
return ""
}
func mapTypeToFields(qtype uint16) string {
switch qtype {
case dns.TypeA:
return "a"
case dns.TypeAAAA:
return "aaaa"
case dns.TypeMX:
return "preference, mx"
case dns.TypePTR:
return "ptr"
case dns.TypeNS:
return "ns"
case dns.TypeTXT:
return "txt"
case dns.TypeSOA:
return "ns, mbox, serial, refresh, retry, expire, minttl"
case dns.TypeSRV:
return "priority, weight, port, target"
case dns.TypeCNAME:
return "target"
}
return ""
}
func (check *DbCheck) Name() string {
return "dbcheck"
}