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
|
package main
import (
"flag"
"fmt"
"log"
"net"
"os"
"os/signal"
"strings"
"sync"
"syscall"
"time"
"golang.org/x/net/dns/dnsmessage"
)
type DNSForwarder struct {
upstreamDNS string
listenAddresses []ListenAddress
nat64Prefix *net.IPNet
}
type ListenAddress struct {
IP string
Port int
}
func NewDNSForwarder(upstreamDNS string, listenAddresses []ListenAddress) *DNSForwarder {
_, nat64Network, _ := net.ParseCIDR("64:ff9b::/96")
return &DNSForwarder{
upstreamDNS: upstreamDNS,
listenAddresses: listenAddresses,
nat64Prefix: nat64Network,
}
}
func (df *DNSForwarder) createSocket(listenIP string, listenPort int) (*net.UDPConn, error) {
addr := &net.UDPAddr{
Port: listenPort,
}
if listenIP == "::" {
addr.IP = net.IPv6zero
} else {
addr.IP = net.ParseIP(listenIP)
}
conn, err := net.ListenUDP("udp", addr)
if err != nil {
return nil, err
}
log.Printf("DNS forwarder listening on %s:%d", listenIP, listenPort)
return conn, nil
}
func (df *DNSForwarder) handleSocket(conn *net.UDPConn) {
buffer := make([]byte, 4096)
for {
n, remoteAddr, err := conn.ReadFromUDP(buffer)
if err != nil {
log.Printf("Error reading from socket: %v", err)
continue
}
go func(data []byte, addr *net.UDPAddr) {
response := df.processQuery(data[:n])
if response != nil {
_, err := conn.WriteToUDP(response, addr)
if err != nil {
log.Printf("Error sending response: %v", err)
}
}
}(buffer[:n], remoteAddr)
}
}
func (df *DNSForwarder) processQuery(queryData []byte) []byte {
// Check minimum DNS message size
if len(queryData) < 12 {
log.Printf("Query too short to be valid DNS message")
return nil
}
var msg dnsmessage.Message
if err := msg.Unpack(queryData); err != nil {
log.Printf("Error unpacking DNS message: %v", err)
errorMsg := &dnsmessage.Message{
Header: dnsmessage.Header{
ID: msg.Header.ID,
Response: true,
RCode: dnsmessage.RCodeFormatError,
},
}
response, packErr := errorMsg.Pack()
if packErr != nil {
log.Printf("Error packing error response: %v", packErr)
return nil
}
return response
}
if len(msg.Questions) == 0 {
log.Printf("DNS query contains no questions")
return nil
}
upstreamConn, err := net.Dial("udp", df.upstreamDNS)
if err != nil {
log.Printf("Error connecting to upstream DNS: %v", err)
return nil
}
defer upstreamConn.Close()
// Set a reasonable timeout for upstream queries (5 seconds)
upstreamConn.SetDeadline(time.Now().Add(5 * time.Second))
_, err = upstreamConn.Write(queryData)
if err != nil {
log.Printf("Error sending query to upstream: %v", err)
return nil
}
responseBuffer := make([]byte, 4096)
n, err := upstreamConn.Read(responseBuffer)
if err != nil {
log.Printf("Error reading response from upstream: %v", err)
return nil
}
if n < 12 {
log.Printf("Response too short to be valid DNS message")
return nil
}
return df.filterDNS64Responses(responseBuffer[:n])
}
func (df *DNSForwarder) filterDNS64Responses(responseData []byte) []byte {
var msg dnsmessage.Message
if err := msg.Unpack(responseData); err != nil {
log.Printf("Error unpacking response: %v", err)
return responseData
}
var filteredAnswers []dnsmessage.Resource
for _, answer := range msg.Answers {
if answer.Header.Type == dnsmessage.TypeAAAA {
aaaa, ok := answer.Body.(*dnsmessage.AAAAResource)
if ok {
ip := net.IP(aaaa.AAAA[:])
if !df.nat64Prefix.Contains(ip) {
filteredAnswers = append(filteredAnswers, answer)
}
}
} else {
filteredAnswers = append(filteredAnswers, answer)
}
}
msg.Answers = filteredAnswers
response, err := msg.Pack()
if err != nil {
log.Printf("Error packing filtered response: %v", err)
return responseData
}
return response
}
func (df *DNSForwarder) Start() error {
var wg sync.WaitGroup
for _, addr := range df.listenAddresses {
conn, err := df.createSocket(addr.IP, addr.Port)
if err != nil {
return fmt.Errorf("failed to create socket for %s:%d: %v", addr.IP, addr.Port, err)
}
wg.Add(1)
go func() {
defer wg.Done()
df.handleSocket(conn)
}()
}
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
<-sigChan
log.Println("Shutting down...")
return nil
}
func parseListenAddress(addr string) ListenAddress {
parts := strings.Split(addr, ":")
if len(parts) < 2 {
return ListenAddress{IP: "::", Port: 53}
}
port := 53
fmt.Sscanf(parts[len(parts)-1], "%d", &port)
ip := strings.Join(parts[:len(parts)-1], ":")
if ip == "" {
ip = "::"
}
return ListenAddress{IP: ip, Port: port}
}
func main() {
upstreamDNS := flag.String("upstream", "[2606:4700:4700::1111]:53", "Upstream DNS server (format: ip:port or [ipv6]:port)")
listenAddrs := flag.String("listen", "[::]:53", "Comma-separated list of IP:PORT to listen on")
flag.Parse()
var addresses []ListenAddress
for _, addr := range strings.Split(*listenAddrs, ",") {
addresses = append(addresses, parseListenAddress(addr))
}
forwarder := NewDNSForwarder(*upstreamDNS, addresses)
if err := forwarder.Start(); err != nil {
log.Fatal(err)
}
}
|