forked from pion/dtls
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handshaker_test.go
447 lines (394 loc) · 12.2 KB
/
handshaker_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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package dtls
import (
"bytes"
"context"
"crypto/tls"
"errors"
"sync"
"testing"
"time"
"github.com/pion/dtls/v3/pkg/crypto/selfsign"
"github.com/pion/dtls/v3/pkg/crypto/signaturehash"
"github.com/pion/dtls/v3/pkg/protocol/alert"
"github.com/pion/dtls/v3/pkg/protocol/handshake"
"github.com/pion/dtls/v3/pkg/protocol/recordlayer"
"github.com/pion/logging"
"github.com/pion/transport/v3/test"
)
const nonZeroRetransmitInterval = 100 * time.Millisecond
// Test that writes to the key log are in the correct format and only applies
// when a key log writer is given.
func TestWriteKeyLog(t *testing.T) {
var buf bytes.Buffer
cfg := handshakeConfig{
keyLogWriter: &buf,
}
cfg.writeKeyLog("LABEL", []byte{0xAA, 0xBB, 0xCC}, []byte{0xDD, 0xEE, 0xFF})
// Secrets follow the format <Label> <space> <ClientRandom> <space> <Secret>
// https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format
want := "LABEL aabbcc ddeeff\n"
if buf.String() != want {
t.Fatalf("Got %s want %s", buf.String(), want)
}
// no key log writer = no writes
cfg = handshakeConfig{}
cfg.writeKeyLog("LABEL", []byte{0xAA, 0xBB, 0xCC}, []byte{0xDD, 0xEE, 0xFF})
}
func TestHandshaker(t *testing.T) {
// Check for leaking routines
report := test.CheckRoutines(t)
defer report()
loggerFactory := logging.NewDefaultLoggerFactory()
logger := loggerFactory.NewLogger("dtls")
cipherSuites, err := parseCipherSuites(nil, nil, true, false)
if err != nil {
t.Fatal(err)
}
clientCert, err := selfsign.GenerateSelfSigned()
if err != nil {
t.Fatal(err)
}
genFilters := map[string]func() (TestEndpoint, TestEndpoint, func(t *testing.T)){
"PassThrough": func() (TestEndpoint, TestEndpoint, func(t *testing.T)) {
return TestEndpoint{}, TestEndpoint{}, nil
},
"HelloVerifyRequestLost": func() (TestEndpoint, TestEndpoint, func(t *testing.T)) {
var (
cntHelloVerifyRequest = 0
cntClientHelloNoCookie = 0
)
const helloVerifyDrop = 5
clientEndpoint := TestEndpoint{
Filter: func(p *packet) bool {
h, ok := p.record.Content.(*handshake.Handshake)
if !ok {
return true
}
if hmch, ok := h.Message.(*handshake.MessageClientHello); ok {
if len(hmch.Cookie) == 0 {
cntClientHelloNoCookie++
}
}
return true
},
}
serverEndpoint := TestEndpoint{
Filter: func(p *packet) bool {
h, ok := p.record.Content.(*handshake.Handshake)
if !ok {
return true
}
if _, ok := h.Message.(*handshake.MessageHelloVerifyRequest); ok {
cntHelloVerifyRequest++
return cntHelloVerifyRequest > helloVerifyDrop
}
return true
},
}
report := func(t *testing.T) {
if cntHelloVerifyRequest != helloVerifyDrop+1 {
t.Errorf("Number of HelloVerifyRequest retransmit is wrong, expected: %d times, got: %d times", helloVerifyDrop+1, cntHelloVerifyRequest)
}
if cntClientHelloNoCookie != cntHelloVerifyRequest {
t.Errorf(
"HelloVerifyRequest must be triggered only by ClientHello, but HelloVerifyRequest was sent %d times and ClientHello was sent %d times",
cntHelloVerifyRequest, cntClientHelloNoCookie,
)
}
}
return clientEndpoint, serverEndpoint, report
},
"NoLatencyTest": func() (TestEndpoint, TestEndpoint, func(t *testing.T)) {
var (
cntClientFinished = 0
cntServerFinished = 0
)
clientEndpoint := TestEndpoint{
Filter: func(p *packet) bool {
h, ok := p.record.Content.(*handshake.Handshake)
if !ok {
return true
}
if _, ok := h.Message.(*handshake.MessageFinished); ok {
cntClientFinished++
}
return true
},
}
serverEndpoint := TestEndpoint{
Filter: func(p *packet) bool {
h, ok := p.record.Content.(*handshake.Handshake)
if !ok {
return true
}
if _, ok := h.Message.(*handshake.MessageFinished); ok {
cntServerFinished++
}
return true
},
}
report := func(t *testing.T) {
if cntClientFinished != 1 {
t.Errorf("Number of client finished is wrong, expected: %d times, got: %d times", 1, cntClientFinished)
}
if cntServerFinished != 1 {
t.Errorf("Number of server finished is wrong, expected: %d times, got: %d times", 1, cntServerFinished)
}
}
return clientEndpoint, serverEndpoint, report
},
"SlowServerTest": func() (TestEndpoint, TestEndpoint, func(t *testing.T)) {
var (
cntClientFinished = 0
isClientFinished = false
cntClientFinishedLastRetransmit = 0
cntServerFinished = 0
isServerFinished = false
cntServerFinishedLastRetransmit = 0
)
clientEndpoint := TestEndpoint{
Filter: func(p *packet) bool {
h, ok := p.record.Content.(*handshake.Handshake)
if !ok {
return true
}
if _, ok := h.Message.(*handshake.MessageFinished); ok {
if isClientFinished {
cntClientFinishedLastRetransmit++
} else {
cntClientFinished++
}
}
return true
},
Delay: 0,
OnFinished: func() {
isClientFinished = true
},
FinishWait: 2000 * time.Millisecond,
}
serverEndpoint := TestEndpoint{
Filter: func(p *packet) bool {
h, ok := p.record.Content.(*handshake.Handshake)
if !ok {
return true
}
if _, ok := h.Message.(*handshake.MessageFinished); ok {
if isServerFinished {
cntServerFinishedLastRetransmit++
} else {
cntServerFinished++
}
}
return true
},
Delay: 1000 * time.Millisecond,
OnFinished: func() {
isServerFinished = true
},
FinishWait: 2000 * time.Millisecond,
}
report := func(t *testing.T) {
// with one second server delay and 100 ms retransmit (+ exponential backoff), there should be close to 4 `Finished` from client
// using a range of 3 - 5 for checking
if cntClientFinished < 3 || cntClientFinished > 5 {
t.Errorf("Number of client finished is wrong, expected: %d - %d times, got: %d times", 3, 5, cntClientFinished)
}
if !isClientFinished {
t.Errorf("Client is not finished")
}
// there should be no `Finished` last retransmit from client
if cntClientFinishedLastRetransmit != 4 {
t.Errorf("Number of client finished last retransmit is wrong, expected: %d times, got: %d times", 4, cntClientFinishedLastRetransmit)
}
if cntServerFinished < 1 {
t.Errorf("Number of server finished is wrong, expected: at least %d times, got: %d times", 1, cntServerFinished)
}
if !isServerFinished {
t.Errorf("Server is not finished")
}
// there should be `Finished` last retransmit from server. Because of slow server, client would have sent several `Finished`.
if cntServerFinishedLastRetransmit < 1 {
t.Errorf("Number of server finished last retransmit is wrong, expected: at least %d times, got: %d times", 1, cntServerFinishedLastRetransmit)
}
}
return clientEndpoint, serverEndpoint, report
},
}
for name, filters := range genFilters {
clientEndpoint, serverEndpoint, report := filters()
t.Run(name, func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
if report != nil {
defer report(t)
}
ca, cb := flightTestPipe(ctx, clientEndpoint, serverEndpoint)
ca.state.isClient = true
var wg sync.WaitGroup
wg.Add(2)
ctxCliFinished, cancelCli := context.WithCancel(ctx)
ctxSrvFinished, cancelSrv := context.WithCancel(ctx)
go func() {
defer wg.Done()
cfg := &handshakeConfig{
localCipherSuites: cipherSuites,
localCertificates: []tls.Certificate{clientCert},
ellipticCurves: defaultCurves,
localSignatureSchemes: signaturehash.Algorithms(),
insecureSkipVerify: true,
log: logger,
onFlightState: func(_ flightVal, s handshakeState) {
if s == handshakeFinished {
if clientEndpoint.OnFinished != nil {
clientEndpoint.OnFinished()
}
time.AfterFunc(clientEndpoint.FinishWait, func() {
cancelCli()
})
}
},
initialRetransmitInterval: nonZeroRetransmitInterval,
}
fsm := newHandshakeFSM(&ca.state, ca.handshakeCache, cfg, flight1)
err := fsm.Run(ctx, ca, handshakePreparing)
switch {
case errors.Is(err, context.Canceled):
case errors.Is(err, context.DeadlineExceeded):
t.Error("Timeout")
default:
t.Error(err)
}
}()
go func() {
defer wg.Done()
cfg := &handshakeConfig{
localCipherSuites: cipherSuites,
localCertificates: []tls.Certificate{clientCert},
ellipticCurves: defaultCurves,
localSignatureSchemes: signaturehash.Algorithms(),
insecureSkipVerify: true,
log: logger,
onFlightState: func(_ flightVal, s handshakeState) {
if s == handshakeFinished {
if serverEndpoint.OnFinished != nil {
serverEndpoint.OnFinished()
}
time.AfterFunc(serverEndpoint.FinishWait, func() {
cancelSrv()
})
}
},
initialRetransmitInterval: nonZeroRetransmitInterval,
}
fsm := newHandshakeFSM(&cb.state, cb.handshakeCache, cfg, flight0)
err := fsm.Run(ctx, cb, handshakePreparing)
switch {
case errors.Is(err, context.Canceled):
case errors.Is(err, context.DeadlineExceeded):
t.Error("Timeout")
default:
t.Error(err)
}
}()
<-ctxCliFinished.Done()
<-ctxSrvFinished.Done()
cancel()
wg.Wait()
})
}
}
type packetFilter func(p *packet) bool
type TestEndpoint struct {
Filter packetFilter
Delay time.Duration
OnFinished func()
FinishWait time.Duration
}
func flightTestPipe(ctx context.Context, clientEndpoint TestEndpoint, serverEndpoint TestEndpoint) (*flightTestConn, *flightTestConn) {
ca := newHandshakeCache()
cb := newHandshakeCache()
chA := make(chan recvHandshakeState)
chB := make(chan recvHandshakeState)
return &flightTestConn{
handshakeCache: ca,
otherEndCache: cb,
recv: chA,
otherEndRecv: chB,
done: ctx.Done(),
filter: clientEndpoint.Filter,
delay: clientEndpoint.Delay,
}, &flightTestConn{
handshakeCache: cb,
otherEndCache: ca,
recv: chB,
otherEndRecv: chA,
done: ctx.Done(),
filter: serverEndpoint.Filter,
delay: serverEndpoint.Delay,
}
}
type flightTestConn struct {
state State
handshakeCache *handshakeCache
recv chan recvHandshakeState
done <-chan struct{}
epoch uint16
filter packetFilter
delay time.Duration
otherEndCache *handshakeCache
otherEndRecv chan recvHandshakeState
}
func (c *flightTestConn) recvHandshake() <-chan recvHandshakeState {
return c.recv
}
func (c *flightTestConn) setLocalEpoch(epoch uint16) {
c.epoch = epoch
}
func (c *flightTestConn) notify(context.Context, alert.Level, alert.Description) error {
return nil
}
func (c *flightTestConn) writePackets(_ context.Context, pkts []*packet) error {
time.Sleep(c.delay)
for _, p := range pkts {
if c.filter != nil && !c.filter(p) {
continue
}
if h, ok := p.record.Content.(*handshake.Handshake); ok {
handshakeRaw, err := p.record.Marshal()
if err != nil {
return err
}
c.handshakeCache.push(handshakeRaw[recordlayer.FixedHeaderSize:], p.record.Header.Epoch, h.Header.MessageSequence, h.Header.Type, c.state.isClient)
content, err := h.Message.Marshal()
if err != nil {
return err
}
h.Header.Length = uint32(len(content))
h.Header.FragmentLength = uint32(len(content))
hdr, err := h.Header.Marshal()
if err != nil {
return err
}
c.otherEndCache.push(
append(hdr, content...), p.record.Header.Epoch, h.Header.MessageSequence, h.Header.Type, c.state.isClient)
}
}
go func() {
select {
case c.otherEndRecv <- recvHandshakeState{done: make(chan struct{})}:
case <-c.done:
}
}()
// Avoid deadlock on JS/WASM environment due to context switch problem.
time.Sleep(10 * time.Millisecond)
return nil
}
func (c *flightTestConn) handleQueuedPackets(context.Context) error {
return nil
}
func (c *flightTestConn) sessionKey() []byte {
return nil
}