-
Notifications
You must be signed in to change notification settings - Fork 158
/
conn_test.go
3715 lines (3317 loc) · 100 KB
/
conn_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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package dtls
import (
"bytes"
"context"
"crypto"
"crypto/ecdsa"
cryptoElliptic "crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"encoding/hex"
"errors"
"fmt"
"io"
"net"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/pion/dtls/v3/internal/ciphersuite"
"github.com/pion/dtls/v3/pkg/crypto/elliptic"
"github.com/pion/dtls/v3/pkg/crypto/hash"
"github.com/pion/dtls/v3/pkg/crypto/selfsign"
"github.com/pion/dtls/v3/pkg/crypto/signature"
"github.com/pion/dtls/v3/pkg/crypto/signaturehash"
dtlsnet "github.com/pion/dtls/v3/pkg/net"
"github.com/pion/dtls/v3/pkg/protocol"
"github.com/pion/dtls/v3/pkg/protocol/alert"
"github.com/pion/dtls/v3/pkg/protocol/extension"
"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/dpipe"
"github.com/pion/transport/v3/test"
)
var (
errTestPSKInvalidIdentity = errors.New("TestPSK: Server got invalid identity")
errPSKRejected = errors.New("PSK Rejected")
errNotExpectedChain = errors.New("not expected chain")
errExpecedChain = errors.New("expected chain")
errWrongCert = errors.New("wrong cert")
)
func TestStressDuplex(t *testing.T) {
// Limit runtime in case of deadlocks
lim := test.TimeOut(time.Second * 20)
defer lim.Stop()
// Check for leaking routines
report := test.CheckRoutines(t)
defer report()
// Run the test
stressDuplex(t)
}
func stressDuplex(t *testing.T) {
ca, cb, err := pipeMemory()
if err != nil {
t.Fatal(err)
}
defer func() {
err = ca.Close()
if err != nil {
t.Fatal(err)
}
err = cb.Close()
if err != nil {
t.Fatal(err)
}
}()
opt := test.Options{
MsgSize: 2048,
MsgCount: 100,
}
err = test.StressDuplex(ca, cb, opt)
if err != nil {
t.Fatal(err)
}
}
func TestRoutineLeakOnClose(t *testing.T) {
// Limit runtime in case of deadlocks
lim := test.TimeOut(5 * time.Second)
defer lim.Stop()
// Check for leaking routines
report := test.CheckRoutines(t)
defer report()
ca, cb, err := pipeMemory()
if err != nil {
t.Fatal(err)
}
if _, err := ca.Write(make([]byte, 100)); err != nil {
t.Fatal(err)
}
if err := cb.Close(); err != nil {
t.Fatal(err)
}
if err := ca.Close(); err != nil {
t.Fatal(err)
}
// Packet is sent, but not read.
// inboundLoop routine should not be leaked.
}
func TestReadWriteDeadline(t *testing.T) {
// Limit runtime in case of deadlocks
lim := test.TimeOut(5 * time.Second)
defer lim.Stop()
// Check for leaking routines
report := test.CheckRoutines(t)
defer report()
var e net.Error
ca, cb, err := pipeMemory()
if err != nil {
t.Fatal(err)
}
if err := ca.SetDeadline(time.Unix(0, 1)); err != nil {
t.Fatal(err)
}
_, werr := ca.Write(make([]byte, 100))
if errors.As(werr, &e) {
if !e.Timeout() {
t.Error("Deadline exceeded Write must return Timeout error")
}
if !e.Temporary() { //nolint:staticcheck
t.Error("Deadline exceeded Write must return Temporary error")
}
} else {
t.Error("Write must return net.Error error")
}
_, rerr := ca.Read(make([]byte, 100))
if errors.As(rerr, &e) {
if !e.Timeout() {
t.Error("Deadline exceeded Read must return Timeout error")
}
if !e.Temporary() { //nolint:staticcheck
t.Error("Deadline exceeded Read must return Temporary error")
}
} else {
t.Error("Read must return net.Error error")
}
if err := ca.SetDeadline(time.Time{}); err != nil {
t.Error(err)
}
if err := ca.Close(); err != nil {
t.Error(err)
}
if err := cb.Close(); err != nil {
t.Error(err)
}
if _, err := ca.Write(make([]byte, 100)); !errors.Is(err, ErrConnClosed) {
t.Errorf("Write must return %v after close, got %v", ErrConnClosed, err)
}
if _, err := ca.Read(make([]byte, 100)); !errors.Is(err, io.EOF) {
t.Errorf("Read must return %v after close, got %v", io.EOF, err)
}
}
func TestSequenceNumberOverflow(t *testing.T) {
// Limit runtime in case of deadlocks
lim := test.TimeOut(5 * time.Second)
defer lim.Stop()
// Check for leaking routines
report := test.CheckRoutines(t)
defer report()
t.Run("ApplicationData", func(t *testing.T) {
ca, cb, err := pipeMemory()
if err != nil {
t.Fatal(err)
}
atomic.StoreUint64(&ca.state.localSequenceNumber[1], recordlayer.MaxSequenceNumber)
if _, werr := ca.Write(make([]byte, 100)); werr != nil {
t.Errorf("Write must send message with maximum sequence number, but errord: %v", werr)
}
if _, werr := ca.Write(make([]byte, 100)); !errors.Is(werr, errSequenceNumberOverflow) {
t.Errorf("Write must abandonsend message with maximum sequence number, but errord: %v", werr)
}
if err := ca.Close(); err != nil {
t.Error(err)
}
if err := cb.Close(); err != nil {
t.Error(err)
}
})
t.Run("Handshake", func(t *testing.T) {
ca, cb, err := pipeMemory()
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
atomic.StoreUint64(&ca.state.localSequenceNumber[0], recordlayer.MaxSequenceNumber+1)
// Try to send handshake packet.
if werr := ca.writePackets(ctx, []*packet{
{
record: &recordlayer.RecordLayer{
Header: recordlayer.Header{
Version: protocol.Version1_2,
},
Content: &handshake.Handshake{
Message: &handshake.MessageClientHello{
Version: protocol.Version1_2,
Cookie: make([]byte, 64),
CipherSuiteIDs: cipherSuiteIDs(defaultCipherSuites()),
CompressionMethods: defaultCompressionMethods(),
},
},
},
},
}); !errors.Is(werr, errSequenceNumberOverflow) {
t.Errorf("Connection must fail on handshake packet reaches maximum sequence number")
}
if err := ca.Close(); err != nil {
t.Error(err)
}
if err := cb.Close(); err != nil {
t.Error(err)
}
})
}
func pipeMemory() (*Conn, *Conn, error) {
// In memory pipe
ca, cb := dpipe.Pipe()
return pipeConn(ca, cb)
}
func pipeConn(ca, cb net.Conn) (*Conn, *Conn, error) {
type result struct {
c *Conn
err error
}
c := make(chan result)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// Setup client
go func() {
client, err := testClient(ctx, dtlsnet.PacketConnFromConn(ca), ca.RemoteAddr(), &Config{SRTPProtectionProfiles: []SRTPProtectionProfile{SRTP_AES128_CM_HMAC_SHA1_80}}, true)
c <- result{client, err}
}()
// Setup server
server, err := testServer(ctx, dtlsnet.PacketConnFromConn(cb), cb.RemoteAddr(), &Config{SRTPProtectionProfiles: []SRTPProtectionProfile{SRTP_AES128_CM_HMAC_SHA1_80}}, true)
if err != nil {
return nil, nil, err
}
// Receive client
res := <-c
if res.err != nil {
_ = server.Close()
return nil, nil, res.err
}
return res.c, server, nil
}
func testClient(ctx context.Context, c net.PacketConn, rAddr net.Addr, cfg *Config, generateCertificate bool) (*Conn, error) {
if generateCertificate {
clientCert, err := selfsign.GenerateSelfSigned()
if err != nil {
return nil, err
}
cfg.Certificates = []tls.Certificate{clientCert}
}
cfg.InsecureSkipVerify = true
conn, err := Client(c, rAddr, cfg)
if err != nil {
return nil, err
}
return conn, conn.HandshakeContext(ctx)
}
func testServer(ctx context.Context, c net.PacketConn, rAddr net.Addr, cfg *Config, generateCertificate bool) (*Conn, error) {
if generateCertificate {
serverCert, err := selfsign.GenerateSelfSigned()
if err != nil {
return nil, err
}
cfg.Certificates = []tls.Certificate{serverCert}
}
conn, err := Server(c, rAddr, cfg)
if err != nil {
return nil, err
}
return conn, conn.HandshakeContext(ctx)
}
func sendClientHello(cookie []byte, ca net.Conn, sequenceNumber uint64, extensions []extension.Extension) error {
packet, err := (&recordlayer.RecordLayer{
Header: recordlayer.Header{
Version: protocol.Version1_2,
SequenceNumber: sequenceNumber,
},
Content: &handshake.Handshake{
Header: handshake.Header{
MessageSequence: uint16(sequenceNumber),
},
Message: &handshake.MessageClientHello{
Version: protocol.Version1_2,
Cookie: cookie,
CipherSuiteIDs: cipherSuiteIDs(defaultCipherSuites()),
CompressionMethods: defaultCompressionMethods(),
Extensions: extensions,
},
},
}).Marshal()
if err != nil {
return err
}
if _, err = ca.Write(packet); err != nil {
return err
}
return nil
}
func TestHandshakeWithAlert(t *testing.T) {
// Limit runtime in case of deadlocks
lim := test.TimeOut(time.Second * 20)
defer lim.Stop()
// Check for leaking routines
report := test.CheckRoutines(t)
defer report()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
cases := map[string]struct {
configServer, configClient *Config
errServer, errClient error
}{
"CipherSuiteNoIntersection": {
configServer: &Config{
CipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
},
configClient: &Config{
CipherSuites: []CipherSuiteID{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
},
errServer: errCipherSuiteNoIntersection,
errClient: &alertError{&alert.Alert{Level: alert.Fatal, Description: alert.InsufficientSecurity}},
},
"SignatureSchemesNoIntersection": {
configServer: &Config{
CipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
SignatureSchemes: []tls.SignatureScheme{tls.ECDSAWithP256AndSHA256},
},
configClient: &Config{
CipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
SignatureSchemes: []tls.SignatureScheme{tls.ECDSAWithP521AndSHA512},
},
errServer: &alertError{&alert.Alert{Level: alert.Fatal, Description: alert.InsufficientSecurity}},
errClient: errNoAvailableSignatureSchemes,
},
}
for name, testCase := range cases {
testCase := testCase
t.Run(name, func(t *testing.T) {
clientErr := make(chan error, 1)
ca, cb := dpipe.Pipe()
go func() {
_, err := testClient(ctx, dtlsnet.PacketConnFromConn(ca), ca.RemoteAddr(), testCase.configClient, true)
clientErr <- err
}()
_, errServer := testServer(ctx, dtlsnet.PacketConnFromConn(cb), cb.RemoteAddr(), testCase.configServer, true)
if !errors.Is(errServer, testCase.errServer) {
t.Fatalf("Server error exp(%v) failed(%v)", testCase.errServer, errServer)
}
errClient := <-clientErr
if !errors.Is(errClient, testCase.errClient) {
t.Fatalf("Client error exp(%v) failed(%v)", testCase.errClient, errClient)
}
})
}
}
func TestHandshakeWithInvalidRecord(t *testing.T) {
// Limit runtime in case of deadlocks
lim := test.TimeOut(time.Second * 20)
defer lim.Stop()
// Check for leaking routines
report := test.CheckRoutines(t)
defer report()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
type result struct {
c *Conn
err error
}
clientErr := make(chan result, 1)
ca, cb := dpipe.Pipe()
caWithInvalidRecord := &connWithCallback{Conn: ca}
var msgSeq atomic.Int32
// Send invalid record after first message
caWithInvalidRecord.onWrite = func([]byte) {
if msgSeq.Add(1) == 2 {
if _, err := ca.Write([]byte{0x01, 0x02}); err != nil {
t.Fatal(err)
}
}
}
go func() {
client, err := testClient(ctx, dtlsnet.PacketConnFromConn(caWithInvalidRecord), caWithInvalidRecord.RemoteAddr(), &Config{
CipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
}, true)
clientErr <- result{client, err}
}()
server, errServer := testServer(ctx, dtlsnet.PacketConnFromConn(cb), cb.RemoteAddr(), &Config{
CipherSuites: []CipherSuiteID{TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
}, true)
errClient := <-clientErr
defer func() {
if server != nil {
if err := server.Close(); err != nil {
t.Fatal(err)
}
}
if errClient.c != nil {
if err := errClient.c.Close(); err != nil {
t.Fatal(err)
}
}
}()
if errServer != nil {
t.Fatalf("Server failed(%v)", errServer)
}
if errClient.err != nil {
t.Fatalf("Client failed(%v)", errClient.err)
}
}
func TestExportKeyingMaterial(t *testing.T) {
// Check for leaking routines
report := test.CheckRoutines(t)
defer report()
var rand [28]byte
exportLabel := "EXTRACTOR-dtls_srtp"
expectedServerKey := []byte{0x61, 0x09, 0x9d, 0x7d, 0xcb, 0x08, 0x52, 0x2c, 0xe7, 0x7b}
expectedClientKey := []byte{0x87, 0xf0, 0x40, 0x02, 0xf6, 0x1c, 0xf1, 0xfe, 0x8c, 0x77}
c := &Conn{
state: State{
localRandom: handshake.Random{GMTUnixTime: time.Unix(500, 0), RandomBytes: rand},
remoteRandom: handshake.Random{GMTUnixTime: time.Unix(1000, 0), RandomBytes: rand},
localSequenceNumber: []uint64{0, 0},
cipherSuite: &ciphersuite.TLSEcdheEcdsaWithAes128GcmSha256{},
},
}
c.setLocalEpoch(0)
c.setRemoteEpoch(0)
state, ok := c.ConnectionState()
if !ok {
t.Fatal("ConnectionState failed")
}
_, err := state.ExportKeyingMaterial(exportLabel, nil, 0)
if !errors.Is(err, errHandshakeInProgress) {
t.Errorf("ExportKeyingMaterial when epoch == 0: expected '%s' actual '%s'", errHandshakeInProgress, err)
}
c.setLocalEpoch(1)
state, ok = c.ConnectionState()
if !ok {
t.Fatal("ConnectionState failed")
}
_, err = state.ExportKeyingMaterial(exportLabel, []byte{0x00}, 0)
if !errors.Is(err, errContextUnsupported) {
t.Errorf("ExportKeyingMaterial with context: expected '%s' actual '%s'", errContextUnsupported, err)
}
for k := range invalidKeyingLabels() {
state, ok = c.ConnectionState()
if !ok {
t.Fatal("ConnectionState failed")
}
_, err = state.ExportKeyingMaterial(k, nil, 0)
if !errors.Is(err, errReservedExportKeyingMaterial) {
t.Errorf("ExportKeyingMaterial reserved label: expected '%s' actual '%s'", errReservedExportKeyingMaterial, err)
}
}
state, ok = c.ConnectionState()
if !ok {
t.Fatal("ConnectionState failed")
}
keyingMaterial, err := state.ExportKeyingMaterial(exportLabel, nil, 10)
if err != nil {
t.Errorf("ExportKeyingMaterial as server: unexpected error '%s'", err)
} else if !bytes.Equal(keyingMaterial, expectedServerKey) {
t.Errorf("ExportKeyingMaterial client export: expected (% 02x) actual (% 02x)", expectedServerKey, keyingMaterial)
}
c.state.isClient = true
state, ok = c.ConnectionState()
if !ok {
t.Fatal("ConnectionState failed")
}
keyingMaterial, err = state.ExportKeyingMaterial(exportLabel, nil, 10)
if err != nil {
t.Errorf("ExportKeyingMaterial as server: unexpected error '%s'", err)
} else if !bytes.Equal(keyingMaterial, expectedClientKey) {
t.Errorf("ExportKeyingMaterial client export: expected (% 02x) actual (% 02x)", expectedClientKey, keyingMaterial)
}
}
func TestPSK(t *testing.T) {
// Limit runtime in case of deadlocks
lim := test.TimeOut(time.Second * 20)
defer lim.Stop()
// Check for leaking routines
report := test.CheckRoutines(t)
defer report()
for _, test := range []struct {
Name string
ClientIdentity []byte
ServerIdentity []byte
CipherSuites []CipherSuiteID
ClientVerifyConnection func(*State) error
ServerVerifyConnection func(*State) error
WantFail bool
ExpectedServerErr string
ExpectedClientErr string
}{
{
Name: "Server identity specified",
ServerIdentity: []byte("Test Identity"),
ClientIdentity: []byte("Client Identity"),
CipherSuites: []CipherSuiteID{TLS_PSK_WITH_AES_128_CCM_8},
},
{
Name: "Server identity specified - Server verify connection fails",
ServerIdentity: []byte("Test Identity"),
ClientIdentity: []byte("Client Identity"),
CipherSuites: []CipherSuiteID{TLS_PSK_WITH_AES_128_CCM_8},
ServerVerifyConnection: func(*State) error {
return errExample
},
WantFail: true,
ExpectedServerErr: errExample.Error(),
ExpectedClientErr: alert.BadCertificate.String(),
},
{
Name: "Server identity specified - Client verify connection fails",
ServerIdentity: []byte("Test Identity"),
ClientIdentity: []byte("Client Identity"),
CipherSuites: []CipherSuiteID{TLS_PSK_WITH_AES_128_CCM_8},
ClientVerifyConnection: func(*State) error {
return errExample
},
WantFail: true,
ExpectedServerErr: alert.BadCertificate.String(),
ExpectedClientErr: errExample.Error(),
},
{
Name: "Server identity nil",
ServerIdentity: nil,
ClientIdentity: []byte("Client Identity"),
CipherSuites: []CipherSuiteID{TLS_PSK_WITH_AES_128_CCM_8},
},
{
Name: "TLS_PSK_WITH_AES_128_CBC_SHA256",
ServerIdentity: nil,
ClientIdentity: []byte("Client Identity"),
CipherSuites: []CipherSuiteID{TLS_PSK_WITH_AES_128_CBC_SHA256},
},
{
Name: "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256",
ServerIdentity: nil,
ClientIdentity: []byte("Client Identity"),
CipherSuites: []CipherSuiteID{TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256},
},
{
Name: "Client identity empty",
ServerIdentity: nil,
ClientIdentity: []byte{},
CipherSuites: []CipherSuiteID{TLS_PSK_WITH_AES_128_CCM_8},
},
} {
test := test
t.Run(test.Name, func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
type result struct {
c *Conn
err error
}
clientRes := make(chan result, 1)
ca, cb := dpipe.Pipe()
go func() {
conf := &Config{
PSK: func(hint []byte) ([]byte, error) {
if !bytes.Equal(test.ServerIdentity, hint) {
return nil, fmt.Errorf("TestPSK: Client got invalid identity expected(% 02x) actual(% 02x)", test.ServerIdentity, hint) //nolint:goerr113
}
return []byte{0xAB, 0xC1, 0x23}, nil
},
PSKIdentityHint: test.ClientIdentity,
CipherSuites: test.CipherSuites,
VerifyConnection: test.ClientVerifyConnection,
}
c, err := testClient(ctx, dtlsnet.PacketConnFromConn(ca), ca.RemoteAddr(), conf, false)
clientRes <- result{c, err}
}()
config := &Config{
PSK: func(hint []byte) ([]byte, error) {
fmt.Println(hint)
if !bytes.Equal(test.ClientIdentity, hint) {
return nil, fmt.Errorf("%w: expected(% 02x) actual(% 02x)", errTestPSKInvalidIdentity, test.ClientIdentity, hint)
}
return []byte{0xAB, 0xC1, 0x23}, nil
},
PSKIdentityHint: test.ServerIdentity,
CipherSuites: test.CipherSuites,
VerifyConnection: test.ServerVerifyConnection,
}
server, err := testServer(ctx, dtlsnet.PacketConnFromConn(cb), cb.RemoteAddr(), config, false)
if test.WantFail {
res := <-clientRes
if err == nil || !strings.Contains(err.Error(), test.ExpectedServerErr) {
t.Fatalf("TestPSK: Server expected(%v) actual(%v)", test.ExpectedServerErr, err)
}
if res.err == nil || !strings.Contains(res.err.Error(), test.ExpectedClientErr) {
t.Fatalf("TestPSK: Client expected(%v) actual(%v)", test.ExpectedClientErr, res.err)
}
return
}
if err != nil {
t.Fatalf("TestPSK: Server failed(%v)", err)
}
state, ok := server.ConnectionState()
if !ok {
t.Fatalf("TestPSK: Server ConnectionState failed")
}
actualPSKIdentityHint := state.IdentityHint
if !bytes.Equal(actualPSKIdentityHint, test.ClientIdentity) {
t.Errorf("TestPSK: Server ClientPSKIdentity Mismatch '%s': expected(%v) actual(%v)", test.Name, test.ClientIdentity, actualPSKIdentityHint)
}
defer func() {
_ = server.Close()
}()
res := <-clientRes
if res.err != nil {
t.Fatal(res.err)
}
_ = res.c.Close()
})
}
}
func TestPSKHintFail(t *testing.T) {
// Check for leaking routines
report := test.CheckRoutines(t)
defer report()
serverAlertError := &alertError{&alert.Alert{Level: alert.Fatal, Description: alert.InternalError}}
pskRejected := errPSKRejected
// Limit runtime in case of deadlocks
lim := test.TimeOut(time.Second * 20)
defer lim.Stop()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
clientErr := make(chan error, 1)
ca, cb := dpipe.Pipe()
go func() {
conf := &Config{
PSK: func([]byte) ([]byte, error) {
return nil, pskRejected
},
PSKIdentityHint: []byte{},
CipherSuites: []CipherSuiteID{TLS_PSK_WITH_AES_128_CCM_8},
}
_, err := testClient(ctx, dtlsnet.PacketConnFromConn(ca), ca.RemoteAddr(), conf, false)
clientErr <- err
}()
config := &Config{
PSK: func([]byte) ([]byte, error) {
return nil, pskRejected
},
PSKIdentityHint: []byte{},
CipherSuites: []CipherSuiteID{TLS_PSK_WITH_AES_128_CCM_8},
}
if _, err := testServer(ctx, dtlsnet.PacketConnFromConn(cb), cb.RemoteAddr(), config, false); !errors.Is(err, serverAlertError) {
t.Fatalf("TestPSK: Server error exp(%v) failed(%v)", serverAlertError, err)
}
if err := <-clientErr; !errors.Is(err, pskRejected) {
t.Fatalf("TestPSK: Client error exp(%v) failed(%v)", pskRejected, err)
}
}
// Assert that ServerKeyExchange is only sent if Identity is set on server side
func TestPSKServerKeyExchange(t *testing.T) {
// Limit runtime in case of deadlocks
lim := test.TimeOut(time.Second * 20)
defer lim.Stop()
// Check for leaking routines
report := test.CheckRoutines(t)
defer report()
for _, test := range []struct {
Name string
SetIdentity bool
}{
{
Name: "Server Identity Set",
SetIdentity: true,
},
{
Name: "Server Not Identity Set",
SetIdentity: false,
},
} {
test := test
t.Run(test.Name, func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
gotServerKeyExchange := false
clientErr := make(chan error, 1)
ca, cb := dpipe.Pipe()
cbAnalyzer := &connWithCallback{Conn: cb}
cbAnalyzer.onWrite = func(in []byte) {
messages, err := recordlayer.UnpackDatagram(in)
if err != nil {
t.Fatal(err)
}
for i := range messages {
h := &handshake.Handshake{}
_ = h.Unmarshal(messages[i][recordlayer.FixedHeaderSize:])
if h.Header.Type == handshake.TypeServerKeyExchange {
gotServerKeyExchange = true
}
}
}
go func() {
conf := &Config{
PSK: func([]byte) ([]byte, error) {
return []byte{0xAB, 0xC1, 0x23}, nil
},
PSKIdentityHint: []byte{0xAB, 0xC1, 0x23},
CipherSuites: []CipherSuiteID{TLS_PSK_WITH_AES_128_CCM_8},
}
if client, err := testClient(ctx, dtlsnet.PacketConnFromConn(ca), ca.RemoteAddr(), conf, false); err != nil {
clientErr <- err
} else {
clientErr <- client.Close() //nolint
}
}()
config := &Config{
PSK: func([]byte) ([]byte, error) {
return []byte{0xAB, 0xC1, 0x23}, nil
},
CipherSuites: []CipherSuiteID{TLS_PSK_WITH_AES_128_CCM_8},
}
if test.SetIdentity {
config.PSKIdentityHint = []byte{0xAB, 0xC1, 0x23}
}
if server, err := testServer(ctx, dtlsnet.PacketConnFromConn(cbAnalyzer), cbAnalyzer.RemoteAddr(), config, false); err != nil {
t.Fatalf("TestPSK: Server error %v", err)
} else {
if err = server.Close(); err != nil {
t.Fatal(err)
}
}
if err := <-clientErr; err != nil {
t.Fatalf("TestPSK: Client error %v", err)
}
if gotServerKeyExchange != test.SetIdentity {
t.Fatalf("Mismatch between setting Identity and getting a ServerKeyExchange exp(%t) actual(%t)", test.SetIdentity, gotServerKeyExchange)
}
})
}
}
func TestClientTimeout(t *testing.T) {
// Limit runtime in case of deadlocks
lim := test.TimeOut(time.Second * 20)
defer lim.Stop()
// Check for leaking routines
report := test.CheckRoutines(t)
defer report()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
clientErr := make(chan error, 1)
ca, _ := dpipe.Pipe()
go func() {
conf := &Config{}
c, err := testClient(ctx, dtlsnet.PacketConnFromConn(ca), ca.RemoteAddr(), conf, true)
if err == nil {
_ = c.Close() //nolint:contextcheck
}
clientErr <- err
}()
// no server!
err := <-clientErr
var netErr net.Error
if !errors.As(err, &netErr) || !netErr.Timeout() {
t.Fatalf("Client error exp(Temporary network error) failed(%v)", err)
}
}
func TestSRTPConfiguration(t *testing.T) {
// Check for leaking routines
report := test.CheckRoutines(t)
defer report()
for _, test := range []struct {
Name string
ClientSRTP []SRTPProtectionProfile
ServerSRTP []SRTPProtectionProfile
ClientSRTPMasterKeyIdentifier []byte
ServerSRTPMasterKeyIdentifier []byte
ExpectedProfile SRTPProtectionProfile
WantClientError error
WantServerError error
}{
{
Name: "No SRTP in use",
ClientSRTP: nil,
ServerSRTP: nil,
ExpectedProfile: 0,
WantClientError: nil,
WantServerError: nil,
},
{
Name: "SRTP both ends",
ClientSRTP: []SRTPProtectionProfile{SRTP_AES128_CM_HMAC_SHA1_80},
ServerSRTP: []SRTPProtectionProfile{SRTP_AES128_CM_HMAC_SHA1_80},
ExpectedProfile: SRTP_AES128_CM_HMAC_SHA1_80,
ClientSRTPMasterKeyIdentifier: []byte("ClientSRTPMKI"),
ServerSRTPMasterKeyIdentifier: []byte("ServerSRTPMKI"),
WantClientError: nil,
WantServerError: nil,
},
{
Name: "SRTP client only",
ClientSRTP: []SRTPProtectionProfile{SRTP_AES128_CM_HMAC_SHA1_80},
ServerSRTP: nil,
ExpectedProfile: 0,
WantClientError: &alertError{&alert.Alert{Level: alert.Fatal, Description: alert.InsufficientSecurity}},
WantServerError: errServerNoMatchingSRTPProfile,
},
{
Name: "SRTP server only",
ClientSRTP: nil,
ServerSRTP: []SRTPProtectionProfile{SRTP_AES128_CM_HMAC_SHA1_80},
ExpectedProfile: 0,
WantClientError: nil,
WantServerError: nil,
},
{
Name: "Multiple Suites",
ClientSRTP: []SRTPProtectionProfile{SRTP_AES128_CM_HMAC_SHA1_80, SRTP_AES128_CM_HMAC_SHA1_32},
ServerSRTP: []SRTPProtectionProfile{SRTP_AES128_CM_HMAC_SHA1_80, SRTP_AES128_CM_HMAC_SHA1_32},
ExpectedProfile: SRTP_AES128_CM_HMAC_SHA1_80,
WantClientError: nil,
WantServerError: nil,
},
{
Name: "Multiple Suites, Client Chooses",
ClientSRTP: []SRTPProtectionProfile{SRTP_AES128_CM_HMAC_SHA1_80, SRTP_AES128_CM_HMAC_SHA1_32},
ServerSRTP: []SRTPProtectionProfile{SRTP_AES128_CM_HMAC_SHA1_32, SRTP_AES128_CM_HMAC_SHA1_80},
ExpectedProfile: SRTP_AES128_CM_HMAC_SHA1_80,
WantClientError: nil,
WantServerError: nil,
},
} {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
ca, cb := dpipe.Pipe()
type result struct {
c *Conn
err error
}
c := make(chan result)
go func() {
client, err := testClient(ctx, dtlsnet.PacketConnFromConn(ca), ca.RemoteAddr(), &Config{SRTPProtectionProfiles: test.ClientSRTP, SRTPMasterKeyIdentifier: test.ServerSRTPMasterKeyIdentifier}, true)
c <- result{client, err}
}()
server, err := testServer(ctx, dtlsnet.PacketConnFromConn(cb), cb.RemoteAddr(), &Config{SRTPProtectionProfiles: test.ServerSRTP, SRTPMasterKeyIdentifier: test.ClientSRTPMasterKeyIdentifier}, true)
if !errors.Is(err, test.WantServerError) {
t.Errorf("TestSRTPConfiguration: Server Error Mismatch '%s': expected(%v) actual(%v)", test.Name, test.WantServerError, err)
}
if err == nil {
defer func() {
_ = server.Close()
}()
}
res := <-c
if res.err == nil {
defer func() {
_ = res.c.Close()
}()
}
if !errors.Is(res.err, test.WantClientError) {
t.Fatalf("TestSRTPConfiguration: Client Error Mismatch '%s': expected(%v) actual(%v)", test.Name, test.WantClientError, res.err)
}
if res.c == nil {
return
}
actualClientSRTP, _ := res.c.SelectedSRTPProtectionProfile()
if actualClientSRTP != test.ExpectedProfile {
t.Errorf("TestSRTPConfiguration: Client SRTPProtectionProfile Mismatch '%s': expected(%v) actual(%v)", test.Name, test.ExpectedProfile, actualClientSRTP)
}
actualServerSRTP, _ := server.SelectedSRTPProtectionProfile()
if actualServerSRTP != test.ExpectedProfile {
t.Errorf("TestSRTPConfiguration: Server SRTPProtectionProfile Mismatch '%s': expected(%v) actual(%v)", test.Name, test.ExpectedProfile, actualServerSRTP)
}
actualServerMKI, _ := server.RemoteSRTPMasterKeyIdentifier()
if !bytes.Equal(actualServerMKI, test.ServerSRTPMasterKeyIdentifier) {
t.Errorf("TestSRTPConfiguration: Server SRTPMKI Mismatch '%s': expected(%v) actual(%v)", test.Name, test.ServerSRTPMasterKeyIdentifier, actualServerMKI)
}