Debian Codegraph @

tsig_test.go

raw symbols SCIP
1 package dns
2
3 import (
4 "encoding/binary"
5 "encoding/hex"
6 "errors"
7 "fmt"
8 "strings"
9 "testing"
10 "time"
11 )
12
13 func newTsig(algo string) *Msg {
14 m := new(Msg)
15 m.SetQuestion("example.org.", TypeA)
16 m.SetTsig("example.", algo, 300, time.Now().Unix())
17 return m
18 }
19
20 func TestTsig(t *testing.T) {
21 m := newTsig(HmacSHA256)
22 buf, _, err := TsigGenerate(m, "pRZgBrBvI4NAHZYhxmhs/Q==", "", false)
23 if err != nil {
24 t.Fatal(err)
25 }
26 err = TsigVerify(buf, "pRZgBrBvI4NAHZYhxmhs/Q==", "", false)
27 if err != nil {
28 t.Fatal(err)
29 }
30
31 // TSIG accounts for ID substitution. This means if the message ID is
32 // changed by a forwarder, we should still be able to verify the TSIG.
33 m = newTsig(HmacSHA256)
34 buf, _, err = TsigGenerate(m, "pRZgBrBvI4NAHZYhxmhs/Q==", "", false)
35 if err != nil {
36 t.Fatal(err)
37 }
38
39 binary.BigEndian.PutUint16(buf[0:2], 42)
40 err = TsigVerify(buf, "pRZgBrBvI4NAHZYhxmhs/Q==", "", false)
41 if err != nil {
42 t.Fatal(err)
43 }
44 }
45
46 func TestTsigCase(t *testing.T) {
47 m := newTsig(strings.ToUpper(HmacSHA256))
48 buf, _, err := TsigGenerate(m, "pRZgBrBvI4NAHZYhxmhs/Q==", "", false)
49 if err != nil {
50 t.Fatal(err)
51 }
52 err = TsigVerify(buf, "pRZgBrBvI4NAHZYhxmhs/Q==", "", false)
53 if err != nil {
54 t.Fatal(err)
55 }
56 }
57
58 func TestTsigErrorResponse(t *testing.T) {
59 for _, rcode := range []uint16{RcodeBadSig, RcodeBadKey} {
60 m := newTsig(strings.ToUpper(HmacSHA256))
61 m.IsTsig().Error = rcode
62 buf, _, err := TsigGenerate(m, "pRZgBrBvI4NAHZYhxmhs/Q==", "", false)
63 if err != nil {
64 t.Fatal(err)
65 }
66
67 err = m.Unpack(buf)
68 if err != nil {
69 t.Fatal(err)
70 }
71
72 mTsig := m.IsTsig()
73 if mTsig.MAC != "" {
74 t.Error("Expected empty MAC")
75 }
76 if mTsig.MACSize != 0 {
77 t.Error("Expected 0 MACSize")
78 }
79 if mTsig.TimeSigned != 0 {
80 t.Errorf("Expected TimeSigned to be 0, got %v", mTsig.TimeSigned)
81 }
82 }
83 }
84
85 func TestTsigBadTimeResponse(t *testing.T) {
86 clientTime := uint64(time.Now().Unix()) - 3600
87 m := newTsig(strings.ToUpper(HmacSHA256))
88 m.IsTsig().Error = RcodeBadTime
89 m.IsTsig().TimeSigned = clientTime
90
91 buf, _, err := TsigGenerate(m, "pRZgBrBvI4NAHZYhxmhs/Q==", "", false)
92 if err != nil {
93 t.Fatal(err)
94 }
95
96 err = m.Unpack(buf)
97 if err != nil {
98 t.Fatal(err)
99 }
100
101 mTsig := m.IsTsig()
102 if mTsig.MAC == "" {
103 t.Error("Expected non-empty MAC")
104 }
105 if int(mTsig.MACSize) != len(mTsig.MAC)/2 {
106 t.Errorf("Expected MACSize %v, got %v", len(mTsig.MAC)/2, mTsig.MACSize)
107 }
108
109 if mTsig.TimeSigned != clientTime {
110 t.Errorf("Expected TimeSigned %v to be retained, got %v", clientTime, mTsig.TimeSigned)
111 }
112 }
113
114 const (
115 // A template wire-format DNS message (in hex form) containing a TSIG RR.
116 // Its time signed field will be filled by tests.
117 wireMsg = "c60028000001000000010001076578616d706c6503636f6d00000600010161c00c0001000100000e100004c0000201077465" +
118 "73746b65790000fa00ff00000000003d0b686d61632d73686132353600" +
119 "%012x" + // placeholder for the "time signed" field
120 "012c00208cf23e0081d915478a182edcea7ff48ad102948e6c7ef8e887536957d1fa5616c60000000000"
121 // A secret (in base64 format) with which the TSIG in wireMsg will be validated
122 testSecret = "NoTCJU+DMqFWywaPyxSijrDEA/eC3nK0xi3AMEZuPVk="
123 // the 'time signed' field value that would make the TSIG RR valid with testSecret
124 timeSigned uint64 = 1594855491
125 )
126
127 func TestTsigErrors(t *testing.T) {
128 // Helper shortcut to build wire-format test message.
129 // TsigVerify can modify the slice, so we need to create a new one for each test case below.
130 buildMsgData := func(tm uint64) []byte {
131 msgData, err := hex.DecodeString(fmt.Sprintf(wireMsg, tm))
132 if err != nil {
133 t.Fatal(err)
134 }
135 return msgData
136 }
137
138 // the signature is valid but 'time signed' is too far from the "current time".
139 if err := tsigVerify(buildMsgData(timeSigned), tsigHMACProvider(testSecret), "", false, timeSigned+301); err != ErrTime {
140 t.Fatalf("expected an error '%v' but got '%v'", ErrTime, err)
141 }
142 if err := tsigVerify(buildMsgData(timeSigned), tsigHMACProvider(testSecret), "", false, timeSigned-301); err != ErrTime {
143 t.Fatalf("expected an error '%v' but got '%v'", ErrTime, err)
144 }
145
146 // the signature is invalid and 'time signed' is too far.
147 // the signature should be checked first, so we should see ErrSig.
148 if err := tsigVerify(buildMsgData(timeSigned+301), tsigHMACProvider(testSecret), "", false, timeSigned); err != ErrSig {
149 t.Fatalf("expected an error '%v' but got '%v'", ErrSig, err)
150 }
151
152 // tweak the algorithm name in the wire data, resulting in the "unknown algorithm" error.
153 msgData := buildMsgData(timeSigned)
154 copy(msgData[67:], "bogus")
155 if err := tsigVerify(msgData, tsigHMACProvider(testSecret), "", false, timeSigned); err != ErrKeyAlg {
156 t.Fatalf("expected an error '%v' but got '%v'", ErrKeyAlg, err)
157 }
158
159 // call TsigVerify with a message that doesn't contain a TSIG
160 msgData, tsig, err := stripTsig(buildMsgData(timeSigned))
161 if err != nil {
162 t.Fatal(err)
163 }
164 if err := tsigVerify(msgData, tsigHMACProvider(testSecret), "", false, timeSigned); err != ErrNoSig {
165 t.Fatalf("expected an error '%v' but got '%v'", ErrNoSig, err)
166 }
167
168 // replace the test TSIG with a bogus one with large "other data", which would cause overflow in TsigVerify.
169 // The overflow should be caught without disruption.
170 tsig.OtherData = strings.Repeat("00", 4096)
171 tsig.OtherLen = uint16(len(tsig.OtherData) / 2)
172 msg := new(Msg)
173 if err = msg.Unpack(msgData); err != nil {
174 t.Fatal(err)
175 }
176 msg.Extra = append(msg.Extra, tsig)
177 if msgData, err = msg.Pack(); err != nil {
178 t.Fatal(err)
179 }
180 err = tsigVerify(msgData, tsigHMACProvider(testSecret), "", false, timeSigned)
181 if err == nil || !strings.Contains(err.Error(), "overflow") {
182 t.Errorf("expected error to contain %q, but got %v", "overflow", err)
183 }
184 }
185
186 // This test exercises some more corner cases for TsigGenerate.
187 func TestTsigGenerate(t *testing.T) {
188 // This is a template TSIG to be used for signing.
189 tsig := TSIG{
190 Hdr: RR_Header{Name: "testkey.", Rrtype: TypeTSIG, Class: ClassANY, Ttl: 0},
191 Algorithm: HmacSHA256,
192 TimeSigned: timeSigned,
193 Fudge: 300,
194 OrigId: 42,
195 Error: RcodeBadTime, // use a non-0 value to make sure it's indeed used
196 }
197
198 tests := []struct {
199 desc string // test description
200 requestMAC string // request MAC to be passed to TsigGenerate (arbitrary choice)
201 otherData string // other data specified in the TSIG (arbitrary choice)
202 expectedMAC string // pre-computed expected (correct) MAC in hex form
203 }{
204 {"with request MAC", "3684c225", "",
205 "c110e3f62694755c10761dc8717462431ee34340b7c9d1eee09449150757c5b1"},
206 {"no request MAC", "", "",
207 "385449a425c6d52b9bf2c65c0726eefa0ad8084cdaf488f24547e686605b9610"},
208 {"with other data", "3684c225", "666f6f",
209 "15b91571ca80b3b410a77e2b44f8cc4f35ace22b26020138439dd94803e23b5d"},
210 }
211 for _, tc := range tests {
212 tc := tc
213 t.Run(tc.desc, func(t *testing.T) {
214 // Build TSIG for signing from the template
215 testTSIG := tsig
216 testTSIG.OtherLen = uint16(len(tc.otherData) / 2)
217 testTSIG.OtherData = tc.otherData
218 req := &Msg{
219 MsgHdr: MsgHdr{Opcode: OpcodeUpdate},
220 Question: []Question{{Name: "example.com.", Qtype: TypeSOA, Qclass: ClassINET}},
221 Extra: []RR{&testTSIG},
222 }
223
224 // Call generate, and check the returned MAC against the expected value
225 msgData, mac, err := TsigGenerate(req, testSecret, tc.requestMAC, false)
226 if err != nil {
227 t.Error(err)
228 }
229 if mac != tc.expectedMAC {
230 t.Fatalf("MAC doesn't match: expected '%s', but got '%s'", tc.expectedMAC, mac)
231 }
232
233 // Retrieve the TSIG to be sent out, confirm the MAC in it
234 _, outTSIG, err := stripTsig(msgData)
235 if err != nil {
236 t.Error(err)
237 }
238 if outTSIG.MAC != tc.expectedMAC {
239 t.Fatalf("MAC doesn't match: expected '%s', but got '%s'", tc.expectedMAC, outTSIG.MAC)
240 }
241 // Confirm other fields of MAC.
242 // RDLENGTH should be valid as stripTsig succeeded, so we exclude it from comparison
243 outTSIG.MACSize = 0
244 outTSIG.MAC = ""
245 testTSIG.Hdr.Rdlength = outTSIG.Hdr.Rdlength
246 if *outTSIG != testTSIG {
247 t.Fatalf("TSIG RR doesn't match: expected '%v', but got '%v'", *outTSIG, testTSIG)
248 }
249 })
250 }
251 }
252
253 func TestTSIGHMAC224And384(t *testing.T) {
254 tests := []struct {
255 algorithm string // TSIG algorithm, also used as test description
256 secret string // (arbitrarily chosen) secret suitable for the algorithm in base64 format
257 expectedMAC string // pre-computed expected (correct) MAC in hex form
258 }{
259 {HmacSHA224, "hVEkQuAqnTmBuRrT9KF1Udr91gOMGWPw9LaTtw==",
260 "d6daf9ea189e48bc38f9aed63d6cc4140cdfa38a7a333ee2eefdbd31",
261 },
262 {HmacSHA384, "Qjer2TL2lAdpq9w6Gjs98/ClCQx/L3vtgVHCmrZ8l/oKEPjqUUMFO18gMCRwd5H4",
263 "89a48936d29187870c325cbdba5ad71609bd038d0459d6010c844d659c570e881d3650e4fe7310be53ebe5178d0d1001",
264 },
265 }
266 for _, tc := range tests {
267 tc := tc
268 t.Run(tc.algorithm, func(t *testing.T) {
269 // Build a DNS message with TSIG for the test scenario
270 tsig := TSIG{
271 Hdr: RR_Header{Name: "testkey.", Rrtype: TypeTSIG, Class: ClassANY, Ttl: 0},
272 Algorithm: tc.algorithm,
273 TimeSigned: timeSigned,
274 Fudge: 300,
275 OrigId: 42,
276 }
277 req := &Msg{
278 MsgHdr: MsgHdr{Opcode: OpcodeUpdate},
279 Question: []Question{{Name: "example.com.", Qtype: TypeSOA, Qclass: ClassINET}},
280 Extra: []RR{&tsig},
281 }
282
283 // Confirm both Generate and Verify recognize the algorithm and handle it correctly
284 msgData, mac, err := TsigGenerate(req, tc.secret, "", false)
285 if err != nil {
286 t.Error(err)
287 }
288 if mac != tc.expectedMAC {
289 t.Fatalf("MAC doesn't match: expected '%s' but got '%s'", tc.expectedMAC, mac)
290 }
291 if err = tsigVerify(msgData, tsigHMACProvider(tc.secret), "", false, timeSigned); err != nil {
292 t.Error(err)
293 }
294 })
295 }
296 }
297
298 const testGoodKeyName = "goodkey."
299
300 var (
301 errBadKey = errors.New("this is an intentional error")
302 testGoodMAC = []byte{0, 1, 2, 3}
303 )
304
305 // testProvider always generates the same MAC and only accepts the one signature
306 type testProvider struct {
307 GenerateAllKeys bool
308 }
309
310 func (provider *testProvider) Generate(_ []byte, t *TSIG) ([]byte, error) {
311 if t.Hdr.Name == testGoodKeyName || provider.GenerateAllKeys {
312 return testGoodMAC, nil
313 }
314 return nil, errBadKey
315 }
316
317 func (*testProvider) Verify(_ []byte, t *TSIG) error {
318 if t.Hdr.Name == testGoodKeyName {
319 return nil
320 }
321 return errBadKey
322 }
323
324 func TestTsigGenerateProvider(t *testing.T) {
325 tables := []struct {
326 keyname string
327 mac []byte
328 err error
329 }{
330 {
331 testGoodKeyName,
332 testGoodMAC,
333 nil,
334 },
335 {
336 "badkey.",
337 nil,
338 errBadKey,
339 },
340 }
341
342 for _, table := range tables {
343 t.Run(table.keyname, func(t *testing.T) {
344 tsig := TSIG{
345 Hdr: RR_Header{Name: table.keyname, Rrtype: TypeTSIG, Class: ClassANY, Ttl: 0},
346 Algorithm: HmacSHA1,
347 TimeSigned: timeSigned,
348 Fudge: 300,
349 OrigId: 42,
350 }
351 req := &Msg{
352 MsgHdr: MsgHdr{Opcode: OpcodeUpdate},
353 Question: []Question{{Name: "example.com.", Qtype: TypeSOA, Qclass: ClassINET}},
354 Extra: []RR{&tsig},
355 }
356
357 _, mac, err := TsigGenerateWithProvider(req, new(testProvider), "", false)
358 if err != table.err {
359 t.Fatalf("error doesn't match: expected '%s' but got '%s'", table.err, err)
360 }
361 expectedMAC := hex.EncodeToString(table.mac)
362 if mac != expectedMAC {
363 t.Fatalf("MAC doesn't match: expected '%s' but got '%s'", table.mac, expectedMAC)
364 }
365 })
366 }
367 }
368
369 func TestTsigVerifyProvider(t *testing.T) {
370 tables := []struct {
371 keyname string
372 err error
373 }{
374 {
375 testGoodKeyName,
376 nil,
377 },
378 {
379 "badkey.",
380 errBadKey,
381 },
382 }
383
384 for _, table := range tables {
385 t.Run(table.keyname, func(t *testing.T) {
386 tsig := TSIG{
387 Hdr: RR_Header{Name: table.keyname, Rrtype: TypeTSIG, Class: ClassANY, Ttl: 0},
388 Algorithm: HmacSHA1,
389 TimeSigned: timeSigned,
390 Fudge: 300,
391 OrigId: 42,
392 }
393 req := &Msg{
394 MsgHdr: MsgHdr{Opcode: OpcodeUpdate},
395 Question: []Question{{Name: "example.com.", Qtype: TypeSOA, Qclass: ClassINET}},
396 Extra: []RR{&tsig},
397 }
398
399 provider := &testProvider{true}
400 msgData, _, err := TsigGenerateWithProvider(req, provider, "", false)
401 if err != nil {
402 t.Error(err)
403 }
404 if err = tsigVerify(msgData, provider, "", false, timeSigned); err != table.err {
405 t.Fatalf("error doesn't match: expected '%s' but got '%s'", table.err, err)
406 }
407 })
408 }
409 }