-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreverter.go
75 lines (67 loc) · 2.04 KB
/
reverter.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
package bogus
import (
"fmt"
"log"
"net"
"strings"
"github.com/miekg/dns"
)
// ResponseReverter reverses the operations done on the question section of a packet.
// This is need because the client will otherwise disregards the response, i.e.
// dig will complain with ';; Question section mismatch: got example.org/HINFO/IN'
type ResponseReverter struct {
dns.ResponseWriter
originalQuestion dns.Question
bogus []net.IP
}
// NewResponseReverter returns a pointer to a new ResponseReverter.
func NewResponseReverter(w dns.ResponseWriter, r *dns.Msg, bogus []net.IP) *ResponseReverter {
return &ResponseReverter{
ResponseWriter: w,
originalQuestion: r.Question[0],
bogus: bogus,
}
}
// WriteMsg records the status code and calls the underlying ResponseWriter's WriteMsg method.
func (r *ResponseReverter) WriteMsg(res *dns.Msg) error {
res.Question[0] = r.originalQuestion
for _, rr := range res.Answer {
if rr.Header().Rrtype != dns.TypeA && rr.Header().Rrtype != dns.TypeAAAA {
continue
}
ss := strings.Split(rr.String(), "\t")
if len(ss) != 5 {
continue
}
ip := net.ParseIP(ss[4])
for _, i := range r.bogus {
if !ip.Equal(i) {
continue
}
rs := &dns.Msg{
MsgHdr: dns.MsgHdr{
Id: res.Id,
Response: true,
RecursionDesired: true,
RecursionAvailable: true,
},
Question: res.Question,
Answer: []dns.RR{soa(r.originalQuestion.Name)},
}
return r.ResponseWriter.WriteMsg(rs)
}
}
return r.ResponseWriter.WriteMsg(res)
}
// Write is a wrapper that records the size of the message that gets written.
func (r *ResponseReverter) Write(buf []byte) (int, error) {
log.Println("bogus write", string(buf))
n, err := r.ResponseWriter.Write(buf)
return n, err
}
func soa(name string) dns.RR {
s := fmt.Sprintf("%s 60 IN SOA ns1.%s postmaster.%s 1524370381 14400 3600 604800 60", name, name, name)
soa, _ := dns.NewRR(s)
HitsCount.WithLabelValues(name).Add(1)
return soa
}