-
Notifications
You must be signed in to change notification settings - Fork 0
/
handshaker_test.go
277 lines (243 loc) · 7.3 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
package dtls
import (
"bytes"
"context"
"crypto/tls"
"sync"
"testing"
"time"
"github.com/pchaseh/go-dtls/v2/pkg/crypto/selfsign"
"github.com/pchaseh/go-dtls/v2/pkg/crypto/signaturehash"
"github.com/pchaseh/go-dtls/v2/pkg/protocol/alert"
"github.com/pchaseh/go-dtls/v2/pkg/protocol/handshake"
"github.com/pchaseh/go-dtls/v2/pkg/protocol/recordlayer"
"github.com/pion/logging"
"github.com/pion/transport/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() (packetFilter, packetFilter, func(t *testing.T)){
"PassThrough": func() (packetFilter, packetFilter, func(t *testing.T)) {
return nil, nil, nil
},
"HelloVerifyRequestLost": func() (packetFilter, packetFilter, func(t *testing.T)) {
var (
cntHelloVerifyRequest = 0
cntClientHelloNoCookie = 0
)
const helloVerifyDrop = 5
return 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
},
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
},
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,
)
}
}
},
}
for name, filters := range genFilters {
f1, f2, report := filters()
t.Run(name, func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if report != nil {
defer report(t)
}
ca, cb := flightTestPipe(ctx, f1, f2)
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},
localSignatureSchemes: signaturehash.Algorithms(),
insecureSkipVerify: true,
log: logger,
onFlightState: func(f flightVal, s handshakeState) {
if s == handshakeFinished {
cancelCli()
}
},
retransmitInterval: nonZeroRetransmitInterval,
}
fsm := newHandshakeFSM(&ca.state, ca.handshakeCache, cfg, flight1)
switch err := fsm.Run(ctx, ca, handshakePreparing); err {
case context.Canceled:
case context.DeadlineExceeded:
t.Error("Timeout")
default:
t.Error(err)
}
}()
go func() {
defer wg.Done()
cfg := &handshakeConfig{
localCipherSuites: cipherSuites,
localCertificates: []tls.Certificate{clientCert},
localSignatureSchemes: signaturehash.Algorithms(),
insecureSkipVerify: true,
log: logger,
onFlightState: func(f flightVal, s handshakeState) {
if s == handshakeFinished {
cancelSrv()
}
},
retransmitInterval: nonZeroRetransmitInterval,
}
fsm := newHandshakeFSM(&cb.state, cb.handshakeCache, cfg, flight0)
switch err := fsm.Run(ctx, cb, handshakePreparing); err {
case context.Canceled:
case context.DeadlineExceeded:
t.Error("Timeout")
default:
t.Error(err)
}
}()
<-ctxCliFinished.Done()
<-ctxSrvFinished.Done()
cancel()
wg.Wait()
})
}
}
type packetFilter func(*packet) bool
func flightTestPipe(ctx context.Context, filter1 packetFilter, filter2 packetFilter) (*flightTestConn, *flightTestConn) {
ca := newHandshakeCache()
cb := newHandshakeCache()
chA := make(chan chan struct{})
chB := make(chan chan struct{})
return &flightTestConn{
handshakeCache: ca,
otherEndCache: cb,
recv: chA,
otherEndRecv: chB,
done: ctx.Done(),
filter: filter1,
}, &flightTestConn{
handshakeCache: cb,
otherEndCache: ca,
recv: chB,
otherEndRecv: chA,
done: ctx.Done(),
filter: filter2,
}
}
type flightTestConn struct {
state State
handshakeCache *handshakeCache
recv chan chan struct{}
done <-chan struct{}
epoch uint16
filter packetFilter
otherEndCache *handshakeCache
otherEndRecv chan chan struct{}
}
func (c *flightTestConn) recvHandshake() <-chan chan struct{} {
return c.recv
}
func (c *flightTestConn) setLocalEpoch(epoch uint16) {
c.epoch = epoch
}
func (c *flightTestConn) notify(ctx context.Context, level alert.Level, desc alert.Description) error {
return nil
}
func (c *flightTestConn) writePackets(ctx context.Context, pkts []*packet) error {
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.HeaderSize:], 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 <- 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(ctx context.Context) error {
return nil
}