Repository navigation
Expand file tree
/
Copy pathhandshake_test.go
More file actions
737 lines (646 loc) · 19.7 KB
/
Copy pathhandshake_test.go
File metadata and controls
737 lines (646 loc) · 19.7 KB
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
// Copyright 2013 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 (
"bufio"
"bytes"
"context"
"encoding/hex"
"errors"
"flag"
"fmt"
"io"
"net"
"os"
"os/exec"
"runtime"
"strconv"
"strings"
"sync"
"testing"
"testing/cryptotest"
"time"
"github.com/refraction-networking/utls/internal/boring"
"github.com/refraction-networking/utls/internal/testenv"
)
// TLS reference tests run a connection against a reference implementation
// (OpenSSL) of TLS and record the bytes of the resulting connection. The Go
// code, during a test, is configured with deterministic randomness and so the
// reference test can be reproduced exactly in the future.
//
// In order to save everyone who wishes to run the tests from needing the
// reference implementation installed, the reference connections are saved in
// files in the testdata directory. Thus running the tests involves nothing
// external, but creating and updating them requires the reference
// implementation.
//
// Tests can be updated by running them with the -update flag. This will cause
// the test files for failing tests to be regenerated. Since the reference
// implementation will always generate fresh random numbers, large parts of the
// reference connection will always change.
var (
update = flag.Bool("update", false, "update golden files on failure")
keyFile = flag.String("keylog", "", "destination file for KeyLogWriter")
bogoMode = flag.Bool("bogo-mode", false, "Enabled bogo shim mode, ignore everything else")
bogoFilter = flag.String("bogo-filter", "", "BoGo test filter")
bogoLocalDir = flag.String("bogo-local-dir", "",
"If not-present, checkout BoGo into this dir, or otherwise use it as a pre-existing checkout")
bogoReport = flag.String("bogo-html-report", "", "File path to render an HTML report with BoGo results")
)
func runTestAndUpdateIfNeeded(t *testing.T, name string, run func(t *testing.T, update bool)) {
skipFIPS(t) // FIPS 140-3 mode changes the advertised parameters.
// Go+BoringCrypto's boring.RandReader ignores the testing override set by
// cryptotest.SetGlobalRandom, so e.g. ECDH key generation would be
// non-deterministic. Setting cryptocustomrand=1 makes rand.CustomReader
// pass the caller's reader (the testing source) through instead.
if boring.Enabled {
testenv.SetGODEBUG(t, "cryptocustomrand=1")
}
success := t.Run(name, func(t *testing.T) {
cryptotest.SetGlobalRandom(t, 0)
run(t, false)
})
if !success && *update {
t.Run(name+"#update", func(t *testing.T) {
cryptotest.SetGlobalRandom(t, 0)
run(t, true)
})
}
}
// checkOpenSSLVersion ensures that the version of OpenSSL looks reasonable
// before updating the test data.
func checkOpenSSLVersion() error {
if !*update {
return nil
}
openssl := exec.Command("openssl", "version")
output, err := openssl.CombinedOutput()
if err != nil {
return err
}
version := string(output)
if strings.HasPrefix(version, "OpenSSL 1.1.1") {
return nil
}
println("***********************************************")
println("")
println("You need to build OpenSSL 1.1.1 from source in order")
println("to update the test data.")
println("")
println("Configure it with:")
println("./Configure enable-weak-ssl-ciphers no-shared")
println("and then add the apps/ directory at the front of your PATH.")
println("***********************************************")
return errors.New("version of OpenSSL does not appear to be suitable for updating test data")
}
// recordingConn is a net.Conn that records the traffic that passes through it.
// WriteTo can be used to produce output that can be later be loaded with
// ParseTestData.
type recordingConn struct {
net.Conn
sync.Mutex
flows [][]byte
reading bool
}
func (r *recordingConn) Read(b []byte) (n int, err error) {
if n, err = r.Conn.Read(b); n == 0 {
return
}
b = b[:n]
r.Lock()
defer r.Unlock()
if l := len(r.flows); l == 0 || !r.reading {
buf := make([]byte, len(b))
copy(buf, b)
r.flows = append(r.flows, buf)
} else {
r.flows[l-1] = append(r.flows[l-1], b[:n]...)
}
r.reading = true
return
}
func (r *recordingConn) Write(b []byte) (n int, err error) {
if n, err = r.Conn.Write(b); n == 0 {
return
}
b = b[:n]
r.Lock()
defer r.Unlock()
if l := len(r.flows); l == 0 || r.reading {
buf := make([]byte, len(b))
copy(buf, b)
r.flows = append(r.flows, buf)
} else {
r.flows[l-1] = append(r.flows[l-1], b[:n]...)
}
r.reading = false
return
}
// WriteTo writes Go source code to w that contains the recorded traffic.
func (r *recordingConn) WriteTo(w io.Writer) (int64, error) {
// TLS always starts with a client to server flow.
clientToServer := true
var written int64
for i, flow := range r.flows {
source, dest := "client", "server"
if !clientToServer {
source, dest = dest, source
}
n, err := fmt.Fprintf(w, ">>> Flow %d (%s to %s)\n", i+1, source, dest)
written += int64(n)
if err != nil {
return written, err
}
dumper := hex.Dumper(w)
n, err = dumper.Write(flow)
written += int64(n)
if err != nil {
return written, err
}
err = dumper.Close()
if err != nil {
return written, err
}
clientToServer = !clientToServer
}
return written, nil
}
func parseTestData(r io.Reader) (flows [][]byte, err error) {
var currentFlow []byte
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := scanner.Text()
// If the line starts with ">>> " then it marks the beginning
// of a new flow.
if strings.HasPrefix(line, ">>> ") {
if len(currentFlow) > 0 || len(flows) > 0 {
flows = append(flows, currentFlow)
currentFlow = nil
}
continue
}
// Otherwise the line is a line of hex dump that looks like:
// 00000170 fc f5 06 bf (...) |.....X{&?......!|
// (Some bytes have been omitted from the middle section.)
_, after, ok := strings.Cut(line, " ")
if !ok {
return nil, errors.New("invalid test data")
}
line = after
before, _, ok := strings.Cut(line, "|")
if !ok {
return nil, errors.New("invalid test data")
}
line = before
hexBytes := strings.Fields(line)
for _, hexByte := range hexBytes {
val, err := strconv.ParseUint(hexByte, 16, 8)
if err != nil {
return nil, errors.New("invalid hex byte in test data: " + err.Error())
}
currentFlow = append(currentFlow, byte(val))
}
}
if len(currentFlow) > 0 {
flows = append(flows, currentFlow)
}
return flows, nil
}
// replayingConn is a net.Conn that replays flows recorded by recordingConn.
type replayingConn struct {
t testing.TB
sync.Mutex
flows [][]byte
reading bool
}
var _ net.Conn = (*replayingConn)(nil)
func (r *replayingConn) Read(b []byte) (n int, err error) {
r.Lock()
defer r.Unlock()
if !r.reading {
r.t.Errorf("expected write, got read")
return 0, fmt.Errorf("recording expected write, got read")
}
n = copy(b, r.flows[0])
r.flows[0] = r.flows[0][n:]
if len(r.flows[0]) == 0 {
r.flows = r.flows[1:]
if len(r.flows) == 0 {
return n, io.EOF
} else {
r.reading = false
}
}
return n, nil
}
func (r *replayingConn) Write(b []byte) (n int, err error) {
r.Lock()
defer r.Unlock()
if r.reading {
r.t.Errorf("expected read, got write")
return 0, fmt.Errorf("recording expected read, got write")
}
if !bytes.HasPrefix(r.flows[0], b) {
r.t.Errorf("write mismatch: expected %x, got %x", r.flows[0], b)
return 0, fmt.Errorf("write mismatch")
}
r.flows[0] = r.flows[0][len(b):]
if len(r.flows[0]) == 0 {
r.flows = r.flows[1:]
r.reading = true
}
return len(b), nil
}
func (r *replayingConn) Close() error {
r.Lock()
defer r.Unlock()
if len(r.flows) > 0 {
r.t.Errorf("closed with unfinished flows")
return fmt.Errorf("unexpected close")
}
return nil
}
func (r *replayingConn) LocalAddr() net.Addr { return nil }
func (r *replayingConn) RemoteAddr() net.Addr { return nil }
func (r *replayingConn) SetDeadline(t time.Time) error { return nil }
func (r *replayingConn) SetReadDeadline(t time.Time) error { return nil }
func (r *replayingConn) SetWriteDeadline(t time.Time) error { return nil }
// tempFile creates a temp file containing contents and returns its path.
func tempFile(contents string) string {
file, err := os.CreateTemp("", "go-tls-test")
if err != nil {
panic("failed to create temp file: " + err.Error())
}
path := file.Name()
file.WriteString(contents)
file.Close()
return path
}
// localListener is set up by TestMain and used by localPipe to create Conn
// pairs like net.Pipe, but connected by an actual buffered TCP connection.
var localListener struct {
mu sync.Mutex
addr net.Addr
ch chan net.Conn
}
const localFlakes = 0 // change to 1 or 2 to exercise localServer/localPipe handling of mismatches
func localServer(l net.Listener) {
for n := 0; ; n++ {
c, err := l.Accept()
if err != nil {
return
}
if localFlakes == 1 && n%2 == 0 {
c.Close()
continue
}
localListener.ch <- c
}
}
var isConnRefused = func(err error) bool { return false }
func localPipe(t testing.TB) (net.Conn, net.Conn) {
localListener.mu.Lock()
defer localListener.mu.Unlock()
addr := localListener.addr
var err error
Dialing:
// We expect a rare mismatch, but probably not 5 in a row.
for i := 0; i < 5; i++ {
tooSlow := time.NewTimer(1 * time.Second)
defer tooSlow.Stop()
var c1 net.Conn
c1, err = net.Dial(addr.Network(), addr.String())
if err != nil {
if runtime.GOOS == "dragonfly" && (isConnRefused(err) || os.IsTimeout(err)) {
// golang.org/issue/29583: Dragonfly sometimes returns a spurious
// ECONNREFUSED or ETIMEDOUT.
<-tooSlow.C
continue
}
t.Fatalf("localPipe: %v", err)
}
if localFlakes == 2 && i == 0 {
c1.Close()
continue
}
for {
select {
case <-tooSlow.C:
t.Logf("localPipe: timeout waiting for %v", c1.LocalAddr())
c1.Close()
continue Dialing
case c2 := <-localListener.ch:
if c2.RemoteAddr().String() == c1.LocalAddr().String() {
t.Cleanup(func() { c1.Close() })
t.Cleanup(func() { c2.Close() })
return c1, c2
}
t.Logf("localPipe: unexpected connection: %v != %v", c2.RemoteAddr(), c1.LocalAddr())
c2.Close()
}
}
}
t.Fatalf("localPipe: failed to connect: %v", err)
panic("unreachable")
}
func TestMain(m *testing.M) {
flag.Usage = func() {
fmt.Fprintf(flag.CommandLine.Output(), "Usage of %s:\n", os.Args)
flag.PrintDefaults()
if *bogoMode {
os.Exit(89)
}
}
flag.Parse()
// [uTLS section begin]
// if *bogoMode {
// bogoShim()
// os.Exit(0)
// }
// [uTLS section end]
os.Exit(runMain(m))
}
func runMain(m *testing.M) int {
// Cipher suites preferences change based on the architecture. Force them to
// the version without AES acceleration for test consistency.
hasAESGCMHardwareSupport = false
// Set up localPipe.
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
l, err = net.Listen("tcp6", "[::1]:0")
}
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to open local listener: %v", err)
os.Exit(1)
}
localListener.ch = make(chan net.Conn)
localListener.addr = l.Addr()
defer l.Close()
go localServer(l)
if err := checkOpenSSLVersion(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v", err)
os.Exit(1)
}
rootCAPath := tempFile(testRootCertPEM)
defer os.Remove(rootCAPath)
defaultClientCommand = []string{"openssl", "s_client", "-no_ticket",
"-verify", "1", "-verify_return_error", "-CAfile", rootCAPath,
"-servername", "test.golang.example", "-attime", fmt.Sprint(testTime().Unix())}
clientRootCAPath := tempFile(testClientRootCertPEM)
defer os.Remove(clientRootCAPath)
serverCommand = []string{"openssl", "s_server", "-no_ticket", "-num_tickets", "0",
"-naccept", "1", "-verify_return_error", "-verifyCAfile", clientRootCAPath,
"-attime", fmt.Sprint(testTime().Unix())}
if *keyFile != "" {
f, err := os.OpenFile(*keyFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
panic("failed to open -keylog file: " + err.Error())
}
testConfigClient.KeyLogWriter = f
testConfigServer.KeyLogWriter = f
defer f.Close()
}
return m.Run()
}
func testHandshake(t *testing.T, clientConfig, serverConfig *Config) (serverState, clientState ConnectionState, err error) {
// [uTLS SECTION BEGIN]
return testUtlsHandshake(t, clientConfig, serverConfig, spec)
}
func testUtlsHandshake(t *testing.T, clientConfig, serverConfig *Config, spec *ClientHelloSpec) (serverState, clientState ConnectionState, err error) {
// [uTLS SECTION END]
const sentinel = "SENTINEL\n"
c, s := localPipe(t)
errChan := make(chan error, 1)
go func() {
// [uTLS SECTION BEGIN]
var cli interface {
Handshake() error
ConnectionState() ConnectionState
Close() error
io.Reader
}
if spec != nil {
ucli := UClient(c, clientConfig, HelloCustom)
if err := ucli.ApplyPreset(spec); err != nil {
errChan <- fmt.Errorf("client preset: %v", err)
c.Close()
return
}
cli = ucli
} else {
cli = Client(c, clientConfig)
}
// [uTLS SECTION END]
err := cli.Handshake()
if err != nil {
errChan <- fmt.Errorf("client: %v", err)
c.Close()
return
}
clientState = cli.ConnectionState()
buf, err := io.ReadAll(cli)
if err != nil {
if serverConfig.ClientAuth != NoClientCert && clientState.Version == VersionTLS13 {
// In TLS 1.3, client certificates are sent after the server's
// handshake has completed, and the client only learns about it
// reading the alert after the handshake.
errChan <- fmt.Errorf("client (from Read): %v", err)
c.Close()
return
} else {
t.Errorf("failed to call cli.Read: %v", err)
}
}
defer func() { errChan <- nil }()
if got := string(buf); got != sentinel {
t.Errorf("read %q from TLS connection, but expected %q", got, sentinel)
}
// We discard the error because after ReadAll returns the server must
// have already closed the connection. Sending data (the closeNotify
// alert) can cause a reset, that will make Close return an error.
cli.Close()
}()
server := Server(s, serverConfig)
err = server.Handshake()
if err == nil {
serverState = server.ConnectionState()
if _, err := io.WriteString(server, sentinel); err != nil {
t.Errorf("failed to call server.Write: %v", err)
}
if err := server.Close(); err != nil {
t.Errorf("failed to call server.Close: %v", err)
}
} else {
err = fmt.Errorf("server: %v", err)
s.Close()
}
err = errors.Join(err, <-errChan)
return
}
func fromHex(s string) []byte {
b, _ := hex.DecodeString(s)
return b
}
func TestServerHelloTrailingMessage(t *testing.T) {
// In TLS 1.3 the change cipher spec message is optional. If a CCS message
// is not sent, after reading the ServerHello, the read traffic secret is
// set, and all following messages must be encrypted. If the server sends
// additional unencrypted messages in a record with the ServerHello, the
// client must either fail or ignore the additional messages.
c, s := localPipe(t)
go func() {
ctx := context.Background()
srv := Server(s, testConfigServer.Clone())
clientHello, _, err := srv.readClientHello(ctx)
if err != nil {
testFatal(t, err)
}
hs := serverHandshakeStateTLS13{
c: srv,
ctx: ctx,
clientHello: clientHello,
}
if err := hs.processClientHello(); err != nil {
testFatal(t, err)
}
if err := transcriptMsg(hs.clientHello, hs.transcript); err != nil {
testFatal(t, err)
}
record, err := concatHandshakeMessages(hs.hello, &encryptedExtensionsMsg{alpnProtocol: "h2"})
if err != nil {
testFatal(t, err)
}
if _, err := s.Write(record); err != nil {
testFatal(t, err)
}
srv.Close()
}()
cli := Client(c, testConfigClient.Clone())
expectedErr := "tls: handshake buffer not empty before setting read traffic secret"
if err := cli.Handshake(); err == nil {
t.Fatal("expected error from incomplete handshake, got nil")
} else if err.Error() != expectedErr {
t.Fatalf("expected error %q, got %q", expectedErr, err.Error())
}
}
func TestClientHelloTrailingMessage(t *testing.T) {
// Same as TestServerHelloTrailingMessage but for the client side.
c, s := localPipe(t)
go func() {
cli := Client(c, testConfigClient.Clone())
hello, _, _, err := cli.makeClientHello()
if err != nil {
testFatal(t, err)
}
record, err := concatHandshakeMessages(hello, &certificateMsgTLS13{})
if err != nil {
testFatal(t, err)
}
if _, err := c.Write(record); err != nil {
testFatal(t, err)
}
cli.Close()
}()
srv := Server(s, testConfigServer.Clone())
expectedErr := "tls: handshake buffer not empty before setting read traffic secret"
if err := srv.Handshake(); err == nil {
t.Fatal("expected error from incomplete handshake, got nil")
} else if err.Error() != expectedErr {
t.Fatalf("expected error %q, got %q", expectedErr, err.Error())
}
}
func TestDoubleClientHelloHRR(t *testing.T) {
// If a client sends two ClientHello messages in a single record, and the
// server sends a HRR after reading the first ClientHello, the server must
// either fail or ignore the trailing ClientHello.
c, s := localPipe(t)
go func() {
cli := Client(c, testConfigClient.Clone())
hello, _, _, err := cli.makeClientHello()
if err != nil {
testFatal(t, err)
}
hello.keyShares = nil
record, err := concatHandshakeMessages(hello, hello)
if err != nil {
testFatal(t, err)
}
if _, err := c.Write(record); err != nil {
testFatal(t, err)
}
cli.Close()
}()
srv := Server(s, testConfigServer.Clone())
expectedErr := "tls: handshake buffer not empty before HelloRetryRequest"
if err := srv.Handshake(); err == nil {
t.Fatal("expected error from incomplete handshake, got nil")
} else if err.Error() != expectedErr {
t.Fatalf("expected error %q, got %q", expectedErr, err.Error())
}
}
// concatHandshakeMessages marshals and concatenates the given handshake
// messages into a single record.
func concatHandshakeMessages(msgs ...handshakeMessage) ([]byte, error) {
var marshalled []byte
for _, msg := range msgs {
data, err := msg.marshal()
if err != nil {
return nil, err
}
marshalled = append(marshalled, data...)
}
m := len(marshalled)
outBuf := make([]byte, recordHeaderLen)
outBuf[0] = byte(recordTypeHandshake)
vers := VersionTLS12
outBuf[1] = byte(vers >> 8)
outBuf[2] = byte(vers)
outBuf[3] = byte(m >> 8)
outBuf[4] = byte(m)
outBuf = append(outBuf, marshalled...)
return outBuf, nil
}
func TestMultipleKeyUpdate(t *testing.T) {
for _, requestUpdate := range []bool{true, false} {
t.Run(fmt.Sprintf("requestUpdate=%t", requestUpdate), func(t *testing.T) {
c, s := localPipe(t)
clientConfig := testConfigClient.Clone()
clientConfig.MinVersion = VersionTLS13
clientConfig.MaxVersion = VersionTLS13
serverConfig := testConfigServer.Clone()
serverConfig.MinVersion = VersionTLS13
serverConfig.MaxVersion = VersionTLS13
client := Client(c, clientConfig)
server := Server(s, serverConfig)
clientHandshakeDone := make(chan struct{})
go func() {
if err := client.Handshake(); err != nil {
}
close(clientHandshakeDone)
io.Copy(io.Discard, server)
}()
if err := server.Handshake(); err != nil {
t.Fatalf("server handshake failed: %v\n", err)
}
<-clientHandshakeDone
c.SetReadDeadline(time.Now().Add(1 * time.Second))
s.SetReadDeadline(time.Now().Add(1 * time.Second))
kuMsg, err := (&keyUpdateMsg{updateRequested: requestUpdate}).marshal()
if err != nil {
t.Fatalf("failed to marshal key update message: %v", err)
}
client.out.Lock()
if _, err := client.writeRecordLocked(recordTypeHandshake, append(kuMsg, kuMsg...)); err != nil {
t.Fatalf("failed to write key update messages: %v", err)
}
client.out.Unlock()
_, err = io.Copy(io.Discard, client)
if err == nil {
t.Fatal("expected multiple key update messages to cause an error, got nil")
} else if !strings.HasSuffix(err.Error(), "tls: unexpected message") {
t.Fatalf("unexpected error: %v", err)
}
})
}
}