/
dns_test.go
323 lines (283 loc) · 9.06 KB
/
dns_test.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
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
// +build !integration
// Common variables, functions and tests for the dns package tests
package dns
import (
"fmt"
"net"
"strings"
"testing"
"time"
mkdns "github.com/miekg/dns"
"github.com/stretchr/testify/assert"
"github.com/elastic/beats/libbeat/beat"
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/libbeat/logp"
"github.com/elastic/beats/packetbeat/protos"
"github.com/elastic/beats/packetbeat/publish"
)
// Test Constants
const (
serverIP = "192.168.0.1"
serverPort = 53
clientIP = "10.0.0.1"
clientPort = 34898
)
// DnsTestMessage holds the data that is expected to be returned when parsing
// the raw DNS layer payloads for the request and response packet.
type dnsTestMessage struct {
id uint16
opcode string
flags []string
rcode string
qClass string
qType string
qName string
qEtld string
answers []string
authorities []string
additionals []string
request []byte
response []byte
}
// Request and response addresses.
var (
forward = common.NewIPPortTuple(4,
net.ParseIP(serverIP), serverPort,
net.ParseIP(clientIP), clientPort)
reverse = common.NewIPPortTuple(4,
net.ParseIP(clientIP), clientPort,
net.ParseIP(serverIP), serverPort)
)
type eventStore struct {
events []beat.Event
}
func (e *eventStore) publish(event beat.Event) {
publish.MarshalPacketbeatFields(&event, nil)
e.events = append(e.events, event)
}
func (e *eventStore) empty() bool {
return len(e.events) == 0
}
func newDNS(store *eventStore, verbose bool) *dnsPlugin {
level := logp.WarnLevel
if verbose {
level = logp.DebugLevel
}
logp.DevelopmentSetup(
logp.WithLevel(level),
logp.WithSelectors("dns"),
)
callback := func(beat.Event) {}
if store != nil {
callback = store.publish
}
cfg, _ := common.NewConfigFrom(map[string]interface{}{
"ports": []int{serverPort},
"include_authorities": true,
"include_additionals": true,
"send_request": true,
"send_response": true,
})
dns, err := New(false, callback, cfg)
if err != nil {
panic(err)
}
return dns.(*dnsPlugin)
}
func newPacket(t common.IPPortTuple, payload []byte) *protos.Packet {
return &protos.Packet{
Ts: time.Now(),
Tuple: t,
Payload: payload,
}
}
// expectResult returns one MapStr result from the Dns results channel. If
// no result is available then the test fails.
func expectResult(t testing.TB, e *eventStore) common.MapStr {
if len(e.events) == 0 {
t.Error("No transaction")
return nil
}
event := e.events[0]
e.events = e.events[1:]
return event.Fields
}
// Retrieves a map value. The key should be the full dotted path to the element.
func mapValue(t testing.TB, m common.MapStr, key string) interface{} {
t.Helper()
return mapValueHelper(t, m, strings.Split(key, "."))
}
// Retrieves nested MapStr values.
func mapValueHelper(t testing.TB, m common.MapStr, keys []string) interface{} {
t.Helper()
key := keys[0]
if len(keys) == 1 {
return m[key]
}
if len(keys) > 1 {
value, exists := m[key]
if !exists {
return nil
}
switch typ := value.(type) {
default:
t.Fatalf("Expected %s to return a MapStr but got %v.", key, value)
case common.MapStr:
return mapValueHelper(t, typ, keys[1:])
case []common.MapStr:
var values []interface{}
for _, m := range typ {
values = append(values, mapValueHelper(t, m, keys[1:]))
}
return values
}
}
panic("mapValueHelper cannot be called with an empty array of keys")
}
// Assert that the published MapStr data matches the data in the DnsTestMessage.
// The validation provided my this method should only be used on results
// published where the response packet was "sent".
// The following fields are validated by this method:
// type (must be dns)
// src (ip and port)
// dst (ip and port)
// query
// resource
// method
// dns.id
// dns.op_code
// dns.flags
// dns.response_code
// dns.question.class
// dns.question.type
// dns.question.name
// dns.answers_count
// dns.answers.data
// dns.authorities_count
// dns.authorities
// dns.additionals_count
// dns.additionals
func assertMapStrData(t testing.TB, m common.MapStr, q dnsTestMessage) {
t.Helper()
assertRequest(t, m, q)
// Answers
assertFlags(t, m, q.flags)
assert.Equal(t, q.rcode, mapValue(t, m, "dns.response_code"))
assert.Equal(t, len(q.answers), mapValue(t, m, "dns.answers_count"),
"Expected dns.answers_count to be %d", len(q.answers))
if len(q.answers) > 0 {
assert.Len(t, mapValue(t, m, "dns.answers"), len(q.answers),
"Expected dns.answers to be length %d", len(q.answers))
for _, ans := range q.answers {
assert.Contains(t, mapValue(t, m, "dns.answers.data"), ans)
}
} else {
assert.Nil(t, mapValue(t, m, "dns.answers"))
}
// Authorities
assert.Equal(t, len(q.authorities), mapValue(t, m, "dns.authorities_count"),
"Expected dns.authorities_count to be %d", len(q.authorities))
if len(q.authorities) > 0 {
assert.Len(t, mapValue(t, m, "dns.authorities"), len(q.authorities),
"Expected dns.authorities to be length %d", len(q.authorities))
for _, ans := range q.authorities {
assert.Contains(t, mapValue(t, m, "dns.authorities.data"), ans)
}
} else {
assert.Nil(t, mapValue(t, m, "dns.authorities"))
}
// Additionals
assert.Equal(t, len(q.additionals), mapValue(t, m, "dns.additionals_count"),
"Expected dns.additionals_count to be length %d", len(q.additionals))
if len(q.additionals) > 0 {
assert.Len(t, mapValue(t, m, "dns.additionals"), len(q.additionals),
"Expected dns.additionals to be length %d", len(q.additionals))
for _, ans := range q.additionals {
assert.Contains(t, mapValue(t, m, "dns.additionals.data"), ans)
}
} else {
assert.Nil(t, mapValue(t, m, "dns.additionals"))
}
}
func assertRequest(t testing.TB, m common.MapStr, q dnsTestMessage) {
t.Helper()
assert.Equal(t, "dns", mapValue(t, m, "type"))
assert.Equal(t, forward.SrcIP.String(), mapValue(t, m, "source.ip"))
assert.EqualValues(t, forward.SrcPort, mapValue(t, m, "source.port"))
assert.Equal(t, forward.DstIP.String(), mapValue(t, m, "destination.ip"))
assert.EqualValues(t, forward.DstPort, mapValue(t, m, "destination.port"))
assert.Equal(t, fmt.Sprintf("class %s, type %s, %s", q.qClass, q.qType, q.qName), mapValue(t, m, "query"))
assert.Equal(t, q.qName, mapValue(t, m, "resource"))
assert.Equal(t, q.opcode, mapValue(t, m, "method"))
assert.Equal(t, q.id, mapValue(t, m, "dns.id"))
assert.Equal(t, q.opcode, mapValue(t, m, "dns.op_code"))
assert.Equal(t, q.qClass, mapValue(t, m, "dns.question.class"))
assert.Equal(t, q.qType, mapValue(t, m, "dns.question.type"))
assert.Equal(t, q.qName, mapValue(t, m, "dns.question.name"))
assert.Equal(t, q.qEtld, mapValue(t, m, "dns.question.etld_plus_one"))
assert.Equal(t, q.qEtld, mapValue(t, m, "dns.question.registered_domain"))
}
// Assert that the specified flags are set.
func assertFlags(t testing.TB, m common.MapStr, flags []string) {
for _, expected := range flags {
var key string
switch expected {
default:
t.Fatalf("Unknown flag '%s' specified in test.", expected)
case "aa":
key = "dns.flags.authoritative"
case "ad":
key = "dns.flags.authentic_data"
case "cd":
key = "dns.flags.checking_disabled"
case "ra":
key = "dns.flags.recursion_available"
case "rd":
key = "dns.flags.recursion_desired"
case "tc":
key = "dns.flags.truncated_response"
}
f := mapValue(t, m, key)
flag, ok := f.(bool)
if !ok {
t.Fatalf("%s value is not a bool.", key)
}
assert.True(t, flag, "Flag %s should be true.", key)
}
}
func TestRRsToMapStrsWithOPTRecord(t *testing.T) {
o := new(mkdns.OPT)
o.Hdr.Name = "." // MUST be the root zone, per definition.
o.Hdr.Rrtype = mkdns.TypeOPT
r := new(mkdns.MX)
r.Hdr = mkdns.RR_Header{Name: "miek.nl", Rrtype: mkdns.TypeMX,
Class: mkdns.ClassINET, Ttl: 3600}
r.Preference = 10
r.Mx = "mx.miek.nl"
// The OPT record is a pseudo-record so it doesn't become a real record
// in our conversion, and there will be 1 entry instead of 2.
mapStrs, _ := rrsToMapStrs([]mkdns.RR{o, r}, false)
assert.Len(t, mapStrs, 1)
mapStr := mapStrs[0]
assert.Equal(t, "IN", mapStr["class"])
assert.Equal(t, "MX", mapStr["type"])
assert.Equal(t, "mx.miek.nl", mapStr["data"])
assert.Equal(t, "miek.nl", mapStr["name"])
assert.EqualValues(t, 10, mapStr["preference"])
}