forked from refraction-networking/utls
-
Notifications
You must be signed in to change notification settings - Fork 2
/
handshake_server_test.go
2059 lines (1887 loc) · 63 KB
/
handshake_server_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
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tls
import (
"bytes"
"context"
"crypto"
"crypto/ecdh"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"io"
"net"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
)
func testClientHello(t *testing.T, serverConfig *Config, m handshakeMessage) {
t.Helper()
testClientHelloFailure(t, serverConfig, m, "")
}
// testFatal is a hack to prevent the compiler from complaining that there is a
// call to t.Fatal from a non-test goroutine
func testFatal(t *testing.T, err error) {
t.Helper()
t.Fatal(err)
}
func testClientHelloFailure(t *testing.T, serverConfig *Config, m handshakeMessage, expectedSubStr string) {
c, s := localPipe(t)
go func() {
cli := Client(c, testConfig)
if ch, ok := m.(*clientHelloMsg); ok {
cli.vers = ch.vers
}
if _, err := cli.writeHandshakeRecord(m, nil); err != nil {
testFatal(t, err)
}
c.Close()
}()
ctx := context.Background()
conn := Server(s, serverConfig)
ch, err := conn.readClientHello(ctx)
if err == nil && conn.vers == VersionTLS13 {
hs := serverHandshakeStateTLS13{
c: conn,
ctx: ctx,
clientHello: ch,
}
err = hs.processClientHello()
} else if err == nil {
hs := serverHandshakeState{
c: conn,
ctx: ctx,
clientHello: ch,
}
err = hs.processClientHello()
if err == nil {
err = hs.pickCipherSuite()
}
}
s.Close()
if len(expectedSubStr) == 0 {
if err != nil && err != io.EOF {
t.Helper()
t.Errorf("Got error: %s; expected to succeed", err)
}
} else if err == nil || !strings.Contains(err.Error(), expectedSubStr) {
t.Helper()
t.Errorf("Got error: %v; expected to match substring '%s'", err, expectedSubStr)
}
}
func TestSimpleError(t *testing.T) {
testClientHelloFailure(t, testConfig, &serverHelloDoneMsg{}, "unexpected handshake message")
}
var badProtocolVersions = []uint16{0x0000, 0x0005, 0x0100, 0x0105, 0x0200, 0x0205, VersionSSL30}
func TestRejectBadProtocolVersion(t *testing.T) {
config := testConfig.Clone()
config.MinVersion = VersionSSL30
for _, v := range badProtocolVersions {
testClientHelloFailure(t, config, &clientHelloMsg{
vers: v,
random: make([]byte, 32),
}, "unsupported versions")
}
testClientHelloFailure(t, config, &clientHelloMsg{
vers: VersionTLS12,
supportedVersions: badProtocolVersions,
random: make([]byte, 32),
}, "unsupported versions")
}
func TestNoSuiteOverlap(t *testing.T) {
clientHello := &clientHelloMsg{
vers: VersionTLS10,
random: make([]byte, 32),
cipherSuites: []uint16{0xff00},
compressionMethods: []uint8{compressionNone},
}
testClientHelloFailure(t, testConfig, clientHello, "no cipher suite supported by both client and server")
}
func TestNoCompressionOverlap(t *testing.T) {
clientHello := &clientHelloMsg{
vers: VersionTLS10,
random: make([]byte, 32),
cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
compressionMethods: []uint8{0xff},
}
testClientHelloFailure(t, testConfig, clientHello, "client does not support uncompressed connections")
}
func TestNoRC4ByDefault(t *testing.T) {
clientHello := &clientHelloMsg{
vers: VersionTLS10,
random: make([]byte, 32),
cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
compressionMethods: []uint8{compressionNone},
}
serverConfig := testConfig.Clone()
// Reset the enabled cipher suites to nil in order to test the
// defaults.
serverConfig.CipherSuites = nil
testClientHelloFailure(t, serverConfig, clientHello, "no cipher suite supported by both client and server")
}
func TestRejectSNIWithTrailingDot(t *testing.T) {
testClientHelloFailure(t, testConfig, &clientHelloMsg{
vers: VersionTLS12,
random: make([]byte, 32),
serverName: "foo.com.",
}, "unexpected message")
}
func TestDontSelectECDSAWithRSAKey(t *testing.T) {
// Test that, even when both sides support an ECDSA cipher suite, it
// won't be selected if the server's private key doesn't support it.
clientHello := &clientHelloMsg{
vers: VersionTLS10,
random: make([]byte, 32),
cipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA},
compressionMethods: []uint8{compressionNone},
supportedCurves: []CurveID{CurveP256},
supportedPoints: []uint8{pointFormatUncompressed},
}
serverConfig := testConfig.Clone()
serverConfig.CipherSuites = clientHello.cipherSuites
serverConfig.Certificates = make([]Certificate, 1)
serverConfig.Certificates[0].Certificate = [][]byte{testECDSACertificate}
serverConfig.Certificates[0].PrivateKey = testECDSAPrivateKey
serverConfig.BuildNameToCertificate()
// First test that it *does* work when the server's key is ECDSA.
testClientHello(t, serverConfig, clientHello)
// Now test that switching to an RSA key causes the expected error (and
// not an internal error about a signing failure).
serverConfig.Certificates = testConfig.Certificates
testClientHelloFailure(t, serverConfig, clientHello, "no cipher suite supported by both client and server")
}
func TestDontSelectRSAWithECDSAKey(t *testing.T) {
// Test that, even when both sides support an RSA cipher suite, it
// won't be selected if the server's private key doesn't support it.
clientHello := &clientHelloMsg{
vers: VersionTLS10,
random: make([]byte, 32),
cipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA},
compressionMethods: []uint8{compressionNone},
supportedCurves: []CurveID{CurveP256},
supportedPoints: []uint8{pointFormatUncompressed},
}
serverConfig := testConfig.Clone()
serverConfig.CipherSuites = clientHello.cipherSuites
// First test that it *does* work when the server's key is RSA.
testClientHello(t, serverConfig, clientHello)
// Now test that switching to an ECDSA key causes the expected error
// (and not an internal error about a signing failure).
serverConfig.Certificates = make([]Certificate, 1)
serverConfig.Certificates[0].Certificate = [][]byte{testECDSACertificate}
serverConfig.Certificates[0].PrivateKey = testECDSAPrivateKey
serverConfig.BuildNameToCertificate()
testClientHelloFailure(t, serverConfig, clientHello, "no cipher suite supported by both client and server")
}
func TestRenegotiationExtension(t *testing.T) {
clientHello := &clientHelloMsg{
vers: VersionTLS12,
compressionMethods: []uint8{compressionNone},
random: make([]byte, 32),
secureRenegotiationSupported: true,
cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
}
bufChan := make(chan []byte, 1)
c, s := localPipe(t)
go func() {
cli := Client(c, testConfig)
cli.vers = clientHello.vers
if _, err := cli.writeHandshakeRecord(clientHello, nil); err != nil {
testFatal(t, err)
}
buf := make([]byte, 1024)
n, err := c.Read(buf)
if err != nil {
t.Errorf("Server read returned error: %s", err)
return
}
c.Close()
bufChan <- buf[:n]
}()
Server(s, testConfig).Handshake()
buf := <-bufChan
if len(buf) < 5+4 {
t.Fatalf("Server returned short message of length %d", len(buf))
}
// buf contains a TLS record, with a 5 byte record header and a 4 byte
// handshake header. The length of the ServerHello is taken from the
// handshake header.
serverHelloLen := int(buf[6])<<16 | int(buf[7])<<8 | int(buf[8])
var serverHello serverHelloMsg
// unmarshal expects to be given the handshake header, but
// serverHelloLen doesn't include it.
if !serverHello.unmarshal(buf[5 : 9+serverHelloLen]) {
t.Fatalf("Failed to parse ServerHello")
}
if !serverHello.secureRenegotiationSupported {
t.Errorf("Secure renegotiation extension was not echoed.")
}
}
func TestTLS12OnlyCipherSuites(t *testing.T) {
// Test that a Server doesn't select a TLS 1.2-only cipher suite when
// the client negotiates TLS 1.1.
clientHello := &clientHelloMsg{
vers: VersionTLS11,
random: make([]byte, 32),
cipherSuites: []uint16{
// The Server, by default, will use the client's
// preference order. So the GCM cipher suite
// will be selected unless it's excluded because
// of the version in this ClientHello.
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
TLS_RSA_WITH_RC4_128_SHA,
},
compressionMethods: []uint8{compressionNone},
supportedCurves: []CurveID{CurveP256, CurveP384, CurveP521},
supportedPoints: []uint8{pointFormatUncompressed},
}
c, s := localPipe(t)
replyChan := make(chan any)
go func() {
cli := Client(c, testConfig)
cli.vers = clientHello.vers
if _, err := cli.writeHandshakeRecord(clientHello, nil); err != nil {
testFatal(t, err)
}
reply, err := cli.readHandshake(nil)
c.Close()
if err != nil {
replyChan <- err
} else {
replyChan <- reply
}
}()
config := testConfig.Clone()
config.CipherSuites = clientHello.cipherSuites
Server(s, config).Handshake()
s.Close()
reply := <-replyChan
if err, ok := reply.(error); ok {
t.Fatal(err)
}
serverHello, ok := reply.(*serverHelloMsg)
if !ok {
t.Fatalf("didn't get ServerHello message in reply. Got %v\n", reply)
}
if s := serverHello.cipherSuite; s != TLS_RSA_WITH_RC4_128_SHA {
t.Fatalf("bad cipher suite from server: %x", s)
}
}
func TestTLSPointFormats(t *testing.T) {
// Test that a Server returns the ec_point_format extension when ECC is
// negotiated, and not on a RSA handshake or if ec_point_format is missing.
tests := []struct {
name string
cipherSuites []uint16
supportedCurves []CurveID
supportedPoints []uint8
wantSupportedPoints bool
}{
{"ECC", []uint16{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA}, []CurveID{CurveP256}, []uint8{pointFormatUncompressed}, true},
{"ECC without ec_point_format", []uint16{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA}, []CurveID{CurveP256}, nil, false},
{"ECC with extra values", []uint16{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA}, []CurveID{CurveP256}, []uint8{13, 37, pointFormatUncompressed, 42}, true},
{"RSA", []uint16{TLS_RSA_WITH_AES_256_GCM_SHA384}, nil, nil, false},
{"RSA with ec_point_format", []uint16{TLS_RSA_WITH_AES_256_GCM_SHA384}, nil, []uint8{pointFormatUncompressed}, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
clientHello := &clientHelloMsg{
vers: VersionTLS12,
random: make([]byte, 32),
cipherSuites: tt.cipherSuites,
compressionMethods: []uint8{compressionNone},
supportedCurves: tt.supportedCurves,
supportedPoints: tt.supportedPoints,
}
c, s := localPipe(t)
replyChan := make(chan any)
go func() {
cli := Client(c, testConfig)
cli.vers = clientHello.vers
if _, err := cli.writeHandshakeRecord(clientHello, nil); err != nil {
testFatal(t, err)
}
reply, err := cli.readHandshake(nil)
c.Close()
if err != nil {
replyChan <- err
} else {
replyChan <- reply
}
}()
config := testConfig.Clone()
config.CipherSuites = clientHello.cipherSuites
Server(s, config).Handshake()
s.Close()
reply := <-replyChan
if err, ok := reply.(error); ok {
t.Fatal(err)
}
serverHello, ok := reply.(*serverHelloMsg)
if !ok {
t.Fatalf("didn't get ServerHello message in reply. Got %v\n", reply)
}
if tt.wantSupportedPoints {
if !bytes.Equal(serverHello.supportedPoints, []uint8{pointFormatUncompressed}) {
t.Fatal("incorrect ec_point_format extension from server")
}
} else {
if len(serverHello.supportedPoints) != 0 {
t.Fatalf("unexpected ec_point_format extension from server: %v", serverHello.supportedPoints)
}
}
})
}
}
func TestAlertForwarding(t *testing.T) {
c, s := localPipe(t)
go func() {
Client(c, testConfig).sendAlert(alertUnknownCA)
c.Close()
}()
err := Server(s, testConfig).Handshake()
s.Close()
var opErr *net.OpError
if !errors.As(err, &opErr) || opErr.Err != error(alertUnknownCA) {
t.Errorf("Got error: %s; expected: %s", err, error(alertUnknownCA))
}
}
func TestClose(t *testing.T) {
c, s := localPipe(t)
go c.Close()
err := Server(s, testConfig).Handshake()
s.Close()
if err != io.EOF {
t.Errorf("Got error: %s; expected: %s", err, io.EOF)
}
}
func TestVersion(t *testing.T) {
serverConfig := &Config{
Certificates: testConfig.Certificates,
MaxVersion: VersionTLS13,
}
clientConfig := &Config{
InsecureSkipVerify: true,
MinVersion: VersionTLS12,
}
state, _, err := testHandshake(t, clientConfig, serverConfig)
if err != nil {
t.Fatalf("handshake failed: %s", err)
}
if state.Version != VersionTLS13 {
t.Fatalf("incorrect version %x, should be %x", state.Version, VersionTLS11)
}
clientConfig.MinVersion = 0
serverConfig.MaxVersion = VersionTLS11
_, _, err = testHandshake(t, clientConfig, serverConfig)
if err == nil {
t.Fatalf("expected failure to connect with TLS 1.0/1.1")
}
}
func TestCipherSuitePreference(t *testing.T) {
serverConfig := &Config{
CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA, TLS_AES_128_GCM_SHA256,
TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256},
Certificates: testConfig.Certificates,
MaxVersion: VersionTLS12,
GetConfigForClient: func(chi *ClientHelloInfo) (*Config, error) {
if chi.CipherSuites[0] != TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 {
t.Error("the advertised order should not depend on Config.CipherSuites")
}
if len(chi.CipherSuites) != 2+len(defaultCipherSuitesTLS13) {
t.Error("the advertised TLS 1.2 suites should be filtered by Config.CipherSuites")
}
return nil, nil
},
}
clientConfig := &Config{
CipherSuites: []uint16{TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256},
InsecureSkipVerify: true,
}
state, _, err := testHandshake(t, clientConfig, serverConfig)
if err != nil {
t.Fatalf("handshake failed: %s", err)
}
if state.CipherSuite != TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 {
t.Error("the preference order should not depend on Config.CipherSuites")
}
}
func TestSCTHandshake(t *testing.T) {
t.Run("TLSv12", func(t *testing.T) { testSCTHandshake(t, VersionTLS12) })
t.Run("TLSv13", func(t *testing.T) { testSCTHandshake(t, VersionTLS13) })
}
func testSCTHandshake(t *testing.T, version uint16) {
expected := [][]byte{[]byte("certificate"), []byte("transparency")}
serverConfig := &Config{
Certificates: []Certificate{{
Certificate: [][]byte{testRSACertificate},
PrivateKey: testRSAPrivateKey,
SignedCertificateTimestamps: expected,
}},
MaxVersion: version,
}
clientConfig := &Config{
InsecureSkipVerify: true,
}
_, state, err := testHandshake(t, clientConfig, serverConfig)
if err != nil {
t.Fatalf("handshake failed: %s", err)
}
actual := state.SignedCertificateTimestamps
if len(actual) != len(expected) {
t.Fatalf("got %d scts, want %d", len(actual), len(expected))
}
for i, sct := range expected {
if !bytes.Equal(sct, actual[i]) {
t.Fatalf("SCT #%d was %x, but expected %x", i, actual[i], sct)
}
}
}
func TestCrossVersionResume(t *testing.T) {
t.Run("TLSv12", func(t *testing.T) { testCrossVersionResume(t, VersionTLS12) })
t.Run("TLSv13", func(t *testing.T) { testCrossVersionResume(t, VersionTLS13) })
}
func testCrossVersionResume(t *testing.T, version uint16) {
serverConfig := &Config{
CipherSuites: []uint16{TLS_RSA_WITH_AES_128_CBC_SHA},
Certificates: testConfig.Certificates,
}
clientConfig := &Config{
CipherSuites: []uint16{TLS_RSA_WITH_AES_128_CBC_SHA},
InsecureSkipVerify: true,
ClientSessionCache: NewLRUClientSessionCache(1),
ServerName: "servername",
MinVersion: VersionTLS12,
}
// Establish a session at TLS 1.3.
clientConfig.MaxVersion = VersionTLS13
_, _, err := testHandshake(t, clientConfig, serverConfig)
if err != nil {
t.Fatalf("handshake failed: %s", err)
}
// The client session cache now contains a TLS 1.3 session.
state, _, err := testHandshake(t, clientConfig, serverConfig)
if err != nil {
t.Fatalf("handshake failed: %s", err)
}
if !state.DidResume {
t.Fatalf("handshake did not resume at the same version")
}
// Test that the server will decline to resume at a lower version.
clientConfig.MaxVersion = VersionTLS12
state, _, err = testHandshake(t, clientConfig, serverConfig)
if err != nil {
t.Fatalf("handshake failed: %s", err)
}
if state.DidResume {
t.Fatalf("handshake resumed at a lower version")
}
// The client session cache now contains a TLS 1.2 session.
state, _, err = testHandshake(t, clientConfig, serverConfig)
if err != nil {
t.Fatalf("handshake failed: %s", err)
}
if !state.DidResume {
t.Fatalf("handshake did not resume at the same version")
}
// Test that the server will decline to resume at a higher version.
clientConfig.MaxVersion = VersionTLS13
state, _, err = testHandshake(t, clientConfig, serverConfig)
if err != nil {
t.Fatalf("handshake failed: %s", err)
}
if state.DidResume {
t.Fatalf("handshake resumed at a higher version")
}
}
// Note: see comment in handshake_test.go for details of how the reference
// tests work.
// serverTest represents a test of the TLS server handshake against a reference
// implementation.
type serverTest struct {
// name is a freeform string identifying the test and the file in which
// the expected results will be stored.
name string
// command, if not empty, contains a series of arguments for the
// command to run for the reference server.
command []string
// expectedPeerCerts contains a list of PEM blocks of expected
// certificates from the client.
expectedPeerCerts []string
// config, if not nil, contains a custom Config to use for this test.
config *Config
// expectHandshakeErrorIncluding, when not empty, contains a string
// that must be a substring of the error resulting from the handshake.
expectHandshakeErrorIncluding string
// validate, if not nil, is a function that will be called with the
// ConnectionState of the resulting connection. It returns false if the
// ConnectionState is unacceptable.
validate func(ConnectionState) error
// wait, if true, prevents this subtest from calling t.Parallel.
// If false, runServerTest* returns immediately.
wait bool
}
var defaultClientCommand = []string{"openssl", "s_client", "-no_ticket"}
// connFromCommand starts opens a listening socket and starts the reference
// client to connect to it. It returns a recordingConn that wraps the resulting
// connection.
func (test *serverTest) connFromCommand() (conn *recordingConn, child *exec.Cmd, err error) {
l, err := net.ListenTCP("tcp", &net.TCPAddr{
IP: net.IPv4(127, 0, 0, 1),
Port: 0,
})
if err != nil {
return nil, nil, err
}
defer l.Close()
port := l.Addr().(*net.TCPAddr).Port
var command []string
command = append(command, test.command...)
if len(command) == 0 {
command = defaultClientCommand
}
command = append(command, "-connect")
command = append(command, fmt.Sprintf("127.0.0.1:%d", port))
cmd := exec.Command(command[0], command[1:]...)
cmd.Stdin = nil
var output bytes.Buffer
cmd.Stdout = &output
cmd.Stderr = &output
if err := cmd.Start(); err != nil {
return nil, nil, err
}
connChan := make(chan any, 1)
go func() {
tcpConn, err := l.Accept()
if err != nil {
connChan <- err
return
}
connChan <- tcpConn
}()
var tcpConn net.Conn
select {
case connOrError := <-connChan:
if err, ok := connOrError.(error); ok {
return nil, nil, err
}
tcpConn = connOrError.(net.Conn)
case <-time.After(2 * time.Second):
return nil, nil, errors.New("timed out waiting for connection from child process")
}
record := &recordingConn{
Conn: tcpConn,
}
return record, cmd, nil
}
func (test *serverTest) dataPath() string {
return filepath.Join("testdata", "Server-"+test.name)
}
func (test *serverTest) loadData() (flows [][]byte, err error) {
in, err := os.Open(test.dataPath())
if err != nil {
return nil, err
}
defer in.Close()
return parseTestData(in)
}
func (test *serverTest) run(t *testing.T, write bool) {
var clientConn, serverConn net.Conn
var recordingConn *recordingConn
var childProcess *exec.Cmd
if write {
var err error
recordingConn, childProcess, err = test.connFromCommand()
if err != nil {
t.Fatalf("Failed to start subcommand: %s", err)
}
serverConn = recordingConn
defer func() {
if t.Failed() {
t.Logf("OpenSSL output:\n\n%s", childProcess.Stdout)
}
}()
} else {
clientConn, serverConn = localPipe(t)
}
config := test.config
if config == nil {
config = testConfig
}
server := Server(serverConn, config)
connStateChan := make(chan ConnectionState, 1)
go func() {
_, err := server.Write([]byte("hello, world\n"))
if len(test.expectHandshakeErrorIncluding) > 0 {
if err == nil {
t.Errorf("Error expected, but no error returned")
} else if s := err.Error(); !strings.Contains(s, test.expectHandshakeErrorIncluding) {
t.Errorf("Error expected containing '%s' but got '%s'", test.expectHandshakeErrorIncluding, s)
}
} else {
if err != nil {
t.Logf("Error from Server.Write: '%s'", err)
}
}
server.Close()
serverConn.Close()
connStateChan <- server.ConnectionState()
}()
if !write {
flows, err := test.loadData()
if err != nil {
t.Fatalf("%s: failed to load data from %s", test.name, test.dataPath())
}
for i, b := range flows {
if i%2 == 0 {
if *fast {
clientConn.SetWriteDeadline(time.Now().Add(1 * time.Second))
} else {
clientConn.SetWriteDeadline(time.Now().Add(1 * time.Minute))
}
clientConn.Write(b)
continue
}
bb := make([]byte, len(b))
if *fast {
clientConn.SetReadDeadline(time.Now().Add(1 * time.Second))
} else {
clientConn.SetReadDeadline(time.Now().Add(1 * time.Minute))
}
n, err := io.ReadFull(clientConn, bb)
if err != nil {
t.Fatalf("%s #%d: %s\nRead %d, wanted %d, got %x, wanted %x\n", test.name, i+1, err, n, len(bb), bb[:n], b)
}
if !bytes.Equal(b, bb) {
t.Fatalf("%s #%d: mismatch on read: got:%x want:%x", test.name, i+1, bb, b)
}
}
clientConn.Close()
}
connState := <-connStateChan
peerCerts := connState.PeerCertificates
if len(peerCerts) == len(test.expectedPeerCerts) {
for i, peerCert := range peerCerts {
block, _ := pem.Decode([]byte(test.expectedPeerCerts[i]))
if !bytes.Equal(block.Bytes, peerCert.Raw) {
t.Fatalf("%s: mismatch on peer cert %d", test.name, i+1)
}
}
} else {
t.Fatalf("%s: mismatch on peer list length: %d (wanted) != %d (got)", test.name, len(test.expectedPeerCerts), len(peerCerts))
}
if test.validate != nil {
if err := test.validate(connState); err != nil {
t.Fatalf("validate callback returned error: %s", err)
}
}
if write {
path := test.dataPath()
out, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
t.Fatalf("Failed to create output file: %s", err)
}
defer out.Close()
recordingConn.Close()
if len(recordingConn.flows) < 3 {
if len(test.expectHandshakeErrorIncluding) == 0 {
t.Fatalf("Handshake failed")
}
}
recordingConn.WriteTo(out)
t.Logf("Wrote %s\n", path)
childProcess.Wait()
}
}
func runServerTestForVersion(t *testing.T, template *serverTest, version, option string) {
// Make a deep copy of the template before going parallel.
test := *template
if template.config != nil {
test.config = template.config.Clone()
}
test.name = version + "-" + test.name
if len(test.command) == 0 {
test.command = defaultClientCommand
}
test.command = append([]string(nil), test.command...)
test.command = append(test.command, option)
runTestAndUpdateIfNeeded(t, version, test.run, test.wait)
}
func runServerTestTLS10(t *testing.T, template *serverTest) {
runServerTestForVersion(t, template, "TLSv10", "-tls1")
}
func runServerTestTLS11(t *testing.T, template *serverTest) {
runServerTestForVersion(t, template, "TLSv11", "-tls1_1")
}
func runServerTestTLS12(t *testing.T, template *serverTest) {
runServerTestForVersion(t, template, "TLSv12", "-tls1_2")
}
func runServerTestTLS13(t *testing.T, template *serverTest) {
runServerTestForVersion(t, template, "TLSv13", "-tls1_3")
}
func TestHandshakeServerRSARC4(t *testing.T) {
test := &serverTest{
name: "RSA-RC4",
command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "RC4-SHA"},
}
runServerTestTLS10(t, test)
runServerTestTLS11(t, test)
runServerTestTLS12(t, test)
}
func TestHandshakeServerRSA3DES(t *testing.T) {
test := &serverTest{
name: "RSA-3DES",
command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "DES-CBC3-SHA"},
}
runServerTestTLS10(t, test)
runServerTestTLS12(t, test)
}
func TestHandshakeServerRSAAES(t *testing.T) {
test := &serverTest{
name: "RSA-AES",
command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA"},
}
runServerTestTLS10(t, test)
runServerTestTLS12(t, test)
}
func TestHandshakeServerAESGCM(t *testing.T) {
test := &serverTest{
name: "RSA-AES-GCM",
command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-AES128-GCM-SHA256"},
}
runServerTestTLS12(t, test)
}
func TestHandshakeServerAES256GCMSHA384(t *testing.T) {
test := &serverTest{
name: "RSA-AES256-GCM-SHA384",
command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-AES256-GCM-SHA384"},
}
runServerTestTLS12(t, test)
}
func TestHandshakeServerAES128SHA256(t *testing.T) {
test := &serverTest{
name: "AES128-SHA256",
command: []string{"openssl", "s_client", "-no_ticket", "-ciphersuites", "TLS_AES_128_GCM_SHA256"},
}
runServerTestTLS13(t, test)
}
func TestHandshakeServerAES256SHA384(t *testing.T) {
test := &serverTest{
name: "AES256-SHA384",
command: []string{"openssl", "s_client", "-no_ticket", "-ciphersuites", "TLS_AES_256_GCM_SHA384"},
}
runServerTestTLS13(t, test)
}
func TestHandshakeServerCHACHA20SHA256(t *testing.T) {
test := &serverTest{
name: "CHACHA20-SHA256",
command: []string{"openssl", "s_client", "-no_ticket", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"},
}
runServerTestTLS13(t, test)
}
func TestHandshakeServerECDHEECDSAAES(t *testing.T) {
config := testConfig.Clone()
config.Certificates = make([]Certificate, 1)
config.Certificates[0].Certificate = [][]byte{testECDSACertificate}
config.Certificates[0].PrivateKey = testECDSAPrivateKey
config.BuildNameToCertificate()
test := &serverTest{
name: "ECDHE-ECDSA-AES",
command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-ECDSA-AES256-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256"},
config: config,
}
runServerTestTLS10(t, test)
runServerTestTLS12(t, test)
runServerTestTLS13(t, test)
}
func TestHandshakeServerX25519(t *testing.T) {
config := testConfig.Clone()
config.CurvePreferences = []CurveID{X25519}
test := &serverTest{
name: "X25519",
command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256", "-curves", "X25519"},
config: config,
}
runServerTestTLS12(t, test)
runServerTestTLS13(t, test)
}
func TestHandshakeServerP256(t *testing.T) {
config := testConfig.Clone()
config.CurvePreferences = []CurveID{CurveP256}
test := &serverTest{
name: "P256",
command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256", "-curves", "P-256"},
config: config,
}
runServerTestTLS12(t, test)
runServerTestTLS13(t, test)
}
func TestHandshakeServerHelloRetryRequest(t *testing.T) {
config := testConfig.Clone()
config.CurvePreferences = []CurveID{CurveP256}
test := &serverTest{
name: "HelloRetryRequest",
command: []string{"openssl", "s_client", "-no_ticket", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256", "-curves", "X25519:P-256"},
config: config,
}
runServerTestTLS13(t, test)
}
func TestHandshakeServerALPN(t *testing.T) {
config := testConfig.Clone()
config.NextProtos = []string{"proto1", "proto2"}
test := &serverTest{
name: "ALPN",
// Note that this needs OpenSSL 1.0.2 because that is the first
// version that supports the -alpn flag.
command: []string{"openssl", "s_client", "-alpn", "proto2,proto1", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"},
config: config,
validate: func(state ConnectionState) error {
// The server's preferences should override the client.
if state.NegotiatedProtocol != "proto1" {
return fmt.Errorf("Got protocol %q, wanted proto1", state.NegotiatedProtocol)
}
return nil
},
}
runServerTestTLS12(t, test)
runServerTestTLS13(t, test)
}
func TestHandshakeServerALPNNoMatch(t *testing.T) {
config := testConfig.Clone()
config.NextProtos = []string{"proto3"}
test := &serverTest{
name: "ALPN-NoMatch",
// Note that this needs OpenSSL 1.0.2 because that is the first
// version that supports the -alpn flag.
command: []string{"openssl", "s_client", "-alpn", "proto2,proto1", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"},
config: config,
expectHandshakeErrorIncluding: "client requested unsupported application protocol",
}
runServerTestTLS12(t, test)
runServerTestTLS13(t, test)
}
func TestHandshakeServerALPNNotConfigured(t *testing.T) {
config := testConfig.Clone()
config.NextProtos = nil
test := &serverTest{
name: "ALPN-NotConfigured",
// Note that this needs OpenSSL 1.0.2 because that is the first
// version that supports the -alpn flag.
command: []string{"openssl", "s_client", "-alpn", "proto2,proto1", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"},
config: config,
validate: func(state ConnectionState) error {
if state.NegotiatedProtocol != "" {
return fmt.Errorf("Got protocol %q, wanted nothing", state.NegotiatedProtocol)
}
return nil
},
}
runServerTestTLS12(t, test)
runServerTestTLS13(t, test)
}
func TestHandshakeServerALPNFallback(t *testing.T) {
config := testConfig.Clone()
config.NextProtos = []string{"proto1", "h2", "proto2"}
test := &serverTest{
name: "ALPN-Fallback",
// Note that this needs OpenSSL 1.0.2 because that is the first
// version that supports the -alpn flag.
command: []string{"openssl", "s_client", "-alpn", "proto3,http/1.1,proto4", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"},
config: config,
validate: func(state ConnectionState) error {
if state.NegotiatedProtocol != "" {
return fmt.Errorf("Got protocol %q, wanted nothing", state.NegotiatedProtocol)
}
return nil
},
}
runServerTestTLS12(t, test)
runServerTestTLS13(t, test)
}
// TestHandshakeServerSNI involves a client sending an SNI extension of