-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathdnsserver.go
296 lines (234 loc) · 9.39 KB
/
dnsserver.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
package main
/*
Simple DNS Server implemented in Go
BSD 2-Clause License
Copyright (c) 2019, Daniel Lorch
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import (
"bytes"
"encoding/binary"
"fmt"
"net"
"os"
"strings"
)
// DNSHeader describes the request/response DNS header
type DNSHeader struct {
TransactionID uint16
Flags uint16
NumQuestions uint16
NumAnswers uint16
NumAuthorities uint16
NumAdditionals uint16
}
// DNSResourceRecord describes individual records in the request and response of the DNS payload body
type DNSResourceRecord struct {
DomainName string
Type uint16
Class uint16
TimeToLive uint32
ResourceDataLength uint16
ResourceData []byte
}
// Type and Class values for DNSResourceRecord
const (
TypeA uint16 = 1 // a host address
ClassINET uint16 = 1 // the Internet
FlagResponse uint16 = 1 << 15
UDPMaxMessageSizeBytes uint = 512 // RFC1035
)
// Pretend to look up values in a database
func dbLookup(queryResourceRecord DNSResourceRecord) ([]DNSResourceRecord, []DNSResourceRecord, []DNSResourceRecord) {
var answerResourceRecords = make([]DNSResourceRecord, 0)
var authorityResourceRecords = make([]DNSResourceRecord, 0)
var additionalResourceRecords = make([]DNSResourceRecord, 0)
names, err := GetNames()
if err != nil {
return answerResourceRecords, authorityResourceRecords, additionalResourceRecords
}
if queryResourceRecord.Type != TypeA || queryResourceRecord.Class != ClassINET {
return answerResourceRecords, authorityResourceRecords, additionalResourceRecords
}
for _, name := range names {
if strings.Contains(queryResourceRecord.DomainName, name.Name) {
fmt.Println(queryResourceRecord.DomainName, "resolved to", name.Address)
answerResourceRecords = append(answerResourceRecords, DNSResourceRecord{
DomainName: name.Name,
Type: TypeA,
Class: ClassINET,
TimeToLive: 31337,
ResourceData: name.Address[12:16], // ipv4 address
ResourceDataLength: 4,
})
}
}
return answerResourceRecords, authorityResourceRecords, additionalResourceRecords
}
// RFC1035: "Domain names in messages are expressed in terms of a sequence
// of labels. Each label is represented as a one octet length field followed
// by that number of octets. Since every domain name ends with the null label
// of the root, a domain name is terminated by a length byte of zero."
func readDomainName(requestBuffer *bytes.Buffer) (string, error) {
var domainName string
b, err := requestBuffer.ReadByte()
for ; b != 0 && err == nil; b, err = requestBuffer.ReadByte() {
labelLength := int(b)
labelBytes := requestBuffer.Next(labelLength)
labelName := string(labelBytes)
if len(domainName) == 0 {
domainName = labelName
} else {
domainName += "." + labelName
}
}
return domainName, err
}
// RFC1035: "Domain names in messages are expressed in terms of a sequence
// of labels. Each label is represented as a one octet length field followed
// by that number of octets. Since every domain name ends with the null label
// of the root, a domain name is terminated by a length byte of zero."
func writeDomainName(responseBuffer *bytes.Buffer, domainName string) error {
labels := strings.Split(domainName, ".")
for _, label := range labels {
labelLength := len(label)
labelBytes := []byte(label)
responseBuffer.WriteByte(byte(labelLength))
responseBuffer.Write(labelBytes)
}
err := responseBuffer.WriteByte(byte(0))
return err
}
func handleDNSClient(requestBytes []byte, serverConn *net.UDPConn, clientAddr *net.UDPAddr) {
/**
* read request
*/
var requestBuffer = bytes.NewBuffer(requestBytes)
var queryHeader DNSHeader
var queryResourceRecords []DNSResourceRecord
err := binary.Read(requestBuffer, binary.BigEndian, &queryHeader) // network byte order is big endian
if err != nil {
fmt.Println("Error decoding header: ", err.Error())
}
queryResourceRecords = make([]DNSResourceRecord, queryHeader.NumQuestions)
for idx, _ := range queryResourceRecords {
queryResourceRecords[idx].DomainName, err = readDomainName(requestBuffer)
if err != nil {
fmt.Println("Error decoding label: ", err.Error())
}
queryResourceRecords[idx].Type = binary.BigEndian.Uint16(requestBuffer.Next(2))
queryResourceRecords[idx].Class = binary.BigEndian.Uint16(requestBuffer.Next(2))
}
/**
* lookup values
*/
var answerResourceRecords = make([]DNSResourceRecord, 0)
var authorityResourceRecords = make([]DNSResourceRecord, 0)
var additionalResourceRecords = make([]DNSResourceRecord, 0)
for _, queryResourceRecord := range queryResourceRecords {
newAnswerRR, newAuthorityRR, newAdditionalRR := dbLookup(queryResourceRecord)
answerResourceRecords = append(answerResourceRecords, newAnswerRR...) // three dots cause the two lists to be concatenated
authorityResourceRecords = append(authorityResourceRecords, newAuthorityRR...)
additionalResourceRecords = append(additionalResourceRecords, newAdditionalRR...)
}
/**
* write response
*/
var responseBuffer = new(bytes.Buffer)
var responseHeader DNSHeader
responseHeader = DNSHeader{
TransactionID: queryHeader.TransactionID,
Flags: FlagResponse,
NumQuestions: queryHeader.NumQuestions,
NumAnswers: uint16(len(answerResourceRecords)),
NumAuthorities: uint16(len(authorityResourceRecords)),
NumAdditionals: uint16(len(additionalResourceRecords)),
}
err = Write(responseBuffer, &responseHeader)
if err != nil {
fmt.Println("Error writing to buffer: ", err.Error())
}
for _, queryResourceRecord := range queryResourceRecords {
err = writeDomainName(responseBuffer, queryResourceRecord.DomainName)
if err != nil {
fmt.Println("Error writing to buffer: ", err.Error())
}
Write(responseBuffer, queryResourceRecord.Type)
Write(responseBuffer, queryResourceRecord.Class)
}
for _, answerResourceRecord := range answerResourceRecords {
err = writeDomainName(responseBuffer, answerResourceRecord.DomainName)
if err != nil {
fmt.Println("Error writing to buffer: ", err.Error())
}
Write(responseBuffer, answerResourceRecord.Type)
Write(responseBuffer, answerResourceRecord.Class)
Write(responseBuffer, answerResourceRecord.TimeToLive)
Write(responseBuffer, answerResourceRecord.ResourceDataLength)
Write(responseBuffer, answerResourceRecord.ResourceData)
}
for _, authorityResourceRecord := range authorityResourceRecords {
err = writeDomainName(responseBuffer, authorityResourceRecord.DomainName)
if err != nil {
fmt.Println("Error writing to buffer: ", err.Error())
}
Write(responseBuffer, authorityResourceRecord.Type)
Write(responseBuffer, authorityResourceRecord.Class)
Write(responseBuffer, authorityResourceRecord.TimeToLive)
Write(responseBuffer, authorityResourceRecord.ResourceDataLength)
Write(responseBuffer, authorityResourceRecord.ResourceData)
}
for _, additionalResourceRecord := range additionalResourceRecords {
err = writeDomainName(responseBuffer, additionalResourceRecord.DomainName)
if err != nil {
fmt.Println("Error writing to buffer: ", err.Error())
}
Write(responseBuffer, additionalResourceRecord.Type)
Write(responseBuffer, additionalResourceRecord.Class)
Write(responseBuffer, additionalResourceRecord.TimeToLive)
Write(responseBuffer, additionalResourceRecord.ResourceDataLength)
Write(responseBuffer, additionalResourceRecord.ResourceData)
}
serverConn.WriteToUDP(responseBuffer.Bytes(), clientAddr)
}
func main() {
serverAddr, err := net.ResolveUDPAddr("udp", ":1053")
if err != nil {
fmt.Println("Error resolving UDP address: ", err.Error())
os.Exit(1)
}
serverConn, err := net.ListenUDP("udp", serverAddr)
if err != nil {
fmt.Println("Error listening: ", err.Error())
os.Exit(1)
}
fmt.Println("Listening at: ", serverAddr)
defer serverConn.Close()
for {
requestBytes := make([]byte, UDPMaxMessageSizeBytes)
_, clientAddr, err := serverConn.ReadFromUDP(requestBytes)
if err != nil {
fmt.Println("Error receiving: ", err.Error())
} else {
fmt.Println("Received request from ", clientAddr)
go handleDNSClient(requestBytes, serverConn, clientAddr) // array is value type (call-by-value), i.e. copied
}
}
}