]> Cypherpunks.ru repositories - gostls13.git/blob - src/crypto/tls/handshake_server_test.go
crypto/tls: disable RSA-PSS in TLS 1.2
[gostls13.git] / src / crypto / tls / handshake_server_test.go
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package tls
6
7 import (
8         "bytes"
9         "crypto"
10         "crypto/ecdsa"
11         "crypto/elliptic"
12         "crypto/rsa"
13         "crypto/x509"
14         "encoding/hex"
15         "encoding/pem"
16         "errors"
17         "fmt"
18         "io"
19         "io/ioutil"
20         "math/big"
21         "net"
22         "os"
23         "os/exec"
24         "path/filepath"
25         "strings"
26         "testing"
27         "time"
28 )
29
30 // zeroSource is an io.Reader that returns an unlimited number of zero bytes.
31 type zeroSource struct{}
32
33 func (zeroSource) Read(b []byte) (n int, err error) {
34         for i := range b {
35                 b[i] = 0
36         }
37
38         return len(b), nil
39 }
40
41 var testConfig *Config
42
43 func allCipherSuites() []uint16 {
44         ids := make([]uint16, len(cipherSuites))
45         for i, suite := range cipherSuites {
46                 ids[i] = suite.id
47         }
48
49         return ids
50 }
51
52 func init() {
53         testConfig = &Config{
54                 Time:               func() time.Time { return time.Unix(0, 0) },
55                 Rand:               zeroSource{},
56                 Certificates:       make([]Certificate, 2),
57                 InsecureSkipVerify: true,
58                 MinVersion:         VersionSSL30,
59                 MaxVersion:         VersionTLS13,
60                 CipherSuites:       allCipherSuites(),
61         }
62         testConfig.Certificates[0].Certificate = [][]byte{testRSACertificate}
63         testConfig.Certificates[0].PrivateKey = testRSAPrivateKey
64         testConfig.Certificates[1].Certificate = [][]byte{testSNICertificate}
65         testConfig.Certificates[1].PrivateKey = testRSAPrivateKey
66         testConfig.BuildNameToCertificate()
67         if keyFile := os.Getenv("SSLKEYLOGFILE"); keyFile != "" {
68                 f, err := os.OpenFile(keyFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
69                 if err != nil {
70                         panic("failed to open SSLKEYLOGFILE: " + err.Error())
71                 }
72                 testConfig.KeyLogWriter = f
73         }
74 }
75
76 func testClientHello(t *testing.T, serverConfig *Config, m handshakeMessage) {
77         testClientHelloFailure(t, serverConfig, m, "")
78 }
79
80 func testClientHelloFailure(t *testing.T, serverConfig *Config, m handshakeMessage, expectedSubStr string) {
81         c, s := localPipe(t)
82         go func() {
83                 cli := Client(c, testConfig)
84                 if ch, ok := m.(*clientHelloMsg); ok {
85                         cli.vers = ch.vers
86                 }
87                 cli.writeRecord(recordTypeHandshake, m.marshal())
88                 c.Close()
89         }()
90         conn := Server(s, serverConfig)
91         ch, err := conn.readClientHello()
92         hs := serverHandshakeState{
93                 c:           conn,
94                 clientHello: ch,
95         }
96         if err == nil {
97                 err = hs.processClientHello()
98         }
99         if err == nil {
100                 err = hs.pickCipherSuite()
101         }
102         s.Close()
103         if len(expectedSubStr) == 0 {
104                 if err != nil && err != io.EOF {
105                         t.Errorf("Got error: %s; expected to succeed", err)
106                 }
107         } else if err == nil || !strings.Contains(err.Error(), expectedSubStr) {
108                 t.Errorf("Got error: %v; expected to match substring '%s'", err, expectedSubStr)
109         }
110 }
111
112 func TestSimpleError(t *testing.T) {
113         testClientHelloFailure(t, testConfig, &serverHelloDoneMsg{}, "unexpected handshake message")
114 }
115
116 var badProtocolVersions = []uint16{0x0000, 0x0005, 0x0100, 0x0105, 0x0200, 0x0205}
117
118 func TestRejectBadProtocolVersion(t *testing.T) {
119         for _, v := range badProtocolVersions {
120                 testClientHelloFailure(t, testConfig, &clientHelloMsg{
121                         vers:   v,
122                         random: make([]byte, 32),
123                 }, "unsupported versions")
124         }
125         testClientHelloFailure(t, testConfig, &clientHelloMsg{
126                 vers:              VersionTLS12,
127                 supportedVersions: badProtocolVersions,
128                 random:            make([]byte, 32),
129         }, "unsupported versions")
130 }
131
132 func TestNoSuiteOverlap(t *testing.T) {
133         clientHello := &clientHelloMsg{
134                 vers:               VersionTLS10,
135                 random:             make([]byte, 32),
136                 cipherSuites:       []uint16{0xff00},
137                 compressionMethods: []uint8{compressionNone},
138         }
139         testClientHelloFailure(t, testConfig, clientHello, "no cipher suite supported by both client and server")
140 }
141
142 func TestNoCompressionOverlap(t *testing.T) {
143         clientHello := &clientHelloMsg{
144                 vers:               VersionTLS10,
145                 random:             make([]byte, 32),
146                 cipherSuites:       []uint16{TLS_RSA_WITH_RC4_128_SHA},
147                 compressionMethods: []uint8{0xff},
148         }
149         testClientHelloFailure(t, testConfig, clientHello, "client does not support uncompressed connections")
150 }
151
152 func TestNoRC4ByDefault(t *testing.T) {
153         clientHello := &clientHelloMsg{
154                 vers:               VersionTLS10,
155                 random:             make([]byte, 32),
156                 cipherSuites:       []uint16{TLS_RSA_WITH_RC4_128_SHA},
157                 compressionMethods: []uint8{compressionNone},
158         }
159         serverConfig := testConfig.Clone()
160         // Reset the enabled cipher suites to nil in order to test the
161         // defaults.
162         serverConfig.CipherSuites = nil
163         testClientHelloFailure(t, serverConfig, clientHello, "no cipher suite supported by both client and server")
164 }
165
166 func TestRejectSNIWithTrailingDot(t *testing.T) {
167         testClientHelloFailure(t, testConfig, &clientHelloMsg{
168                 vers:       VersionTLS12,
169                 random:     make([]byte, 32),
170                 serverName: "foo.com.",
171         }, "unexpected message")
172 }
173
174 func TestDontSelectECDSAWithRSAKey(t *testing.T) {
175         // Test that, even when both sides support an ECDSA cipher suite, it
176         // won't be selected if the server's private key doesn't support it.
177         clientHello := &clientHelloMsg{
178                 vers:               VersionTLS10,
179                 random:             make([]byte, 32),
180                 cipherSuites:       []uint16{TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA},
181                 compressionMethods: []uint8{compressionNone},
182                 supportedCurves:    []CurveID{CurveP256},
183                 supportedPoints:    []uint8{pointFormatUncompressed},
184         }
185         serverConfig := testConfig.Clone()
186         serverConfig.CipherSuites = clientHello.cipherSuites
187         serverConfig.Certificates = make([]Certificate, 1)
188         serverConfig.Certificates[0].Certificate = [][]byte{testECDSACertificate}
189         serverConfig.Certificates[0].PrivateKey = testECDSAPrivateKey
190         serverConfig.BuildNameToCertificate()
191         // First test that it *does* work when the server's key is ECDSA.
192         testClientHello(t, serverConfig, clientHello)
193
194         // Now test that switching to an RSA key causes the expected error (and
195         // not an internal error about a signing failure).
196         serverConfig.Certificates = testConfig.Certificates
197         testClientHelloFailure(t, serverConfig, clientHello, "no cipher suite supported by both client and server")
198 }
199
200 func TestDontSelectRSAWithECDSAKey(t *testing.T) {
201         // Test that, even when both sides support an RSA cipher suite, it
202         // won't be selected if the server's private key doesn't support it.
203         clientHello := &clientHelloMsg{
204                 vers:               VersionTLS10,
205                 random:             make([]byte, 32),
206                 cipherSuites:       []uint16{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA},
207                 compressionMethods: []uint8{compressionNone},
208                 supportedCurves:    []CurveID{CurveP256},
209                 supportedPoints:    []uint8{pointFormatUncompressed},
210         }
211         serverConfig := testConfig.Clone()
212         serverConfig.CipherSuites = clientHello.cipherSuites
213         // First test that it *does* work when the server's key is RSA.
214         testClientHello(t, serverConfig, clientHello)
215
216         // Now test that switching to an ECDSA key causes the expected error
217         // (and not an internal error about a signing failure).
218         serverConfig.Certificates = make([]Certificate, 1)
219         serverConfig.Certificates[0].Certificate = [][]byte{testECDSACertificate}
220         serverConfig.Certificates[0].PrivateKey = testECDSAPrivateKey
221         serverConfig.BuildNameToCertificate()
222         testClientHelloFailure(t, serverConfig, clientHello, "no cipher suite supported by both client and server")
223 }
224
225 func TestRenegotiationExtension(t *testing.T) {
226         clientHello := &clientHelloMsg{
227                 vers:                         VersionTLS12,
228                 compressionMethods:           []uint8{compressionNone},
229                 random:                       make([]byte, 32),
230                 secureRenegotiationSupported: true,
231                 cipherSuites:                 []uint16{TLS_RSA_WITH_RC4_128_SHA},
232         }
233
234         bufChan := make(chan []byte)
235         c, s := localPipe(t)
236
237         go func() {
238                 cli := Client(c, testConfig)
239                 cli.vers = clientHello.vers
240                 cli.writeRecord(recordTypeHandshake, clientHello.marshal())
241
242                 buf := make([]byte, 1024)
243                 n, err := c.Read(buf)
244                 if err != nil {
245                         t.Errorf("Server read returned error: %s", err)
246                         return
247                 }
248                 c.Close()
249                 bufChan <- buf[:n]
250         }()
251
252         Server(s, testConfig).Handshake()
253         buf := <-bufChan
254
255         if len(buf) < 5+4 {
256                 t.Fatalf("Server returned short message of length %d", len(buf))
257         }
258         // buf contains a TLS record, with a 5 byte record header and a 4 byte
259         // handshake header. The length of the ServerHello is taken from the
260         // handshake header.
261         serverHelloLen := int(buf[6])<<16 | int(buf[7])<<8 | int(buf[8])
262
263         var serverHello serverHelloMsg
264         // unmarshal expects to be given the handshake header, but
265         // serverHelloLen doesn't include it.
266         if !serverHello.unmarshal(buf[5 : 9+serverHelloLen]) {
267                 t.Fatalf("Failed to parse ServerHello")
268         }
269
270         if !serverHello.secureRenegotiationSupported {
271                 t.Errorf("Secure renegotiation extension was not echoed.")
272         }
273 }
274
275 func TestTLS12OnlyCipherSuites(t *testing.T) {
276         // Test that a Server doesn't select a TLS 1.2-only cipher suite when
277         // the client negotiates TLS 1.1.
278         clientHello := &clientHelloMsg{
279                 vers:   VersionTLS11,
280                 random: make([]byte, 32),
281                 cipherSuites: []uint16{
282                         // The Server, by default, will use the client's
283                         // preference order. So the GCM cipher suite
284                         // will be selected unless it's excluded because
285                         // of the version in this ClientHello.
286                         TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
287                         TLS_RSA_WITH_RC4_128_SHA,
288                 },
289                 compressionMethods: []uint8{compressionNone},
290                 supportedCurves:    []CurveID{CurveP256, CurveP384, CurveP521},
291                 supportedPoints:    []uint8{pointFormatUncompressed},
292         }
293
294         c, s := localPipe(t)
295         replyChan := make(chan interface{})
296         go func() {
297                 cli := Client(c, testConfig)
298                 cli.vers = clientHello.vers
299                 cli.writeRecord(recordTypeHandshake, clientHello.marshal())
300                 reply, err := cli.readHandshake()
301                 c.Close()
302                 if err != nil {
303                         replyChan <- err
304                 } else {
305                         replyChan <- reply
306                 }
307         }()
308         config := testConfig.Clone()
309         config.CipherSuites = clientHello.cipherSuites
310         Server(s, config).Handshake()
311         s.Close()
312         reply := <-replyChan
313         if err, ok := reply.(error); ok {
314                 t.Fatal(err)
315         }
316         serverHello, ok := reply.(*serverHelloMsg)
317         if !ok {
318                 t.Fatalf("didn't get ServerHello message in reply. Got %v\n", reply)
319         }
320         if s := serverHello.cipherSuite; s != TLS_RSA_WITH_RC4_128_SHA {
321                 t.Fatalf("bad cipher suite from server: %x", s)
322         }
323 }
324
325 func TestAlertForwarding(t *testing.T) {
326         c, s := localPipe(t)
327         go func() {
328                 Client(c, testConfig).sendAlert(alertUnknownCA)
329                 c.Close()
330         }()
331
332         err := Server(s, testConfig).Handshake()
333         s.Close()
334         if e, ok := err.(*net.OpError); !ok || e.Err != error(alertUnknownCA) {
335                 t.Errorf("Got error: %s; expected: %s", err, error(alertUnknownCA))
336         }
337 }
338
339 func TestClose(t *testing.T) {
340         c, s := localPipe(t)
341         go c.Close()
342
343         err := Server(s, testConfig).Handshake()
344         s.Close()
345         if err != io.EOF {
346                 t.Errorf("Got error: %s; expected: %s", err, io.EOF)
347         }
348 }
349
350 func testHandshake(t *testing.T, clientConfig, serverConfig *Config) (serverState, clientState ConnectionState, err error) {
351         c, s := localPipe(t)
352         errChan := make(chan error)
353         go func() {
354                 cli := Client(c, clientConfig)
355                 err := cli.Handshake()
356                 if err != nil {
357                         errChan <- fmt.Errorf("client: %v", err)
358                         c.Close()
359                         return
360                 }
361                 defer cli.Close()
362                 clientState = cli.ConnectionState()
363                 buf, err := ioutil.ReadAll(cli)
364                 if err != nil {
365                         t.Errorf("failed to call cli.Read: %v", err)
366                 }
367                 if got := string(buf); got != opensslSentinel {
368                         t.Errorf("read %q from TLS connection, but expected %q", got, opensslSentinel)
369                 }
370                 errChan <- nil
371         }()
372         server := Server(s, serverConfig)
373         err = server.Handshake()
374         if err == nil {
375                 serverState = server.ConnectionState()
376                 if _, err := io.WriteString(server, opensslSentinel); err != nil {
377                         t.Errorf("failed to call server.Write: %v", err)
378                 }
379                 if err := server.Close(); err != nil {
380                         t.Errorf("failed to call server.Close: %v", err)
381                 }
382                 err = <-errChan
383         } else {
384                 s.Close()
385                 <-errChan
386         }
387         return
388 }
389
390 func TestVersion(t *testing.T) {
391         serverConfig := &Config{
392                 Certificates: testConfig.Certificates,
393                 MaxVersion:   VersionTLS11,
394         }
395         clientConfig := &Config{
396                 InsecureSkipVerify: true,
397         }
398         state, _, err := testHandshake(t, clientConfig, serverConfig)
399         if err != nil {
400                 t.Fatalf("handshake failed: %s", err)
401         }
402         if state.Version != VersionTLS11 {
403                 t.Fatalf("Incorrect version %x, should be %x", state.Version, VersionTLS11)
404         }
405 }
406
407 func TestCipherSuitePreference(t *testing.T) {
408         serverConfig := &Config{
409                 CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA},
410                 Certificates: testConfig.Certificates,
411                 MaxVersion:   VersionTLS11,
412         }
413         clientConfig := &Config{
414                 CipherSuites:       []uint16{TLS_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_RC4_128_SHA},
415                 InsecureSkipVerify: true,
416         }
417         state, _, err := testHandshake(t, clientConfig, serverConfig)
418         if err != nil {
419                 t.Fatalf("handshake failed: %s", err)
420         }
421         if state.CipherSuite != TLS_RSA_WITH_AES_128_CBC_SHA {
422                 // By default the server should use the client's preference.
423                 t.Fatalf("Client's preference was not used, got %x", state.CipherSuite)
424         }
425
426         serverConfig.PreferServerCipherSuites = true
427         state, _, err = testHandshake(t, clientConfig, serverConfig)
428         if err != nil {
429                 t.Fatalf("handshake failed: %s", err)
430         }
431         if state.CipherSuite != TLS_RSA_WITH_RC4_128_SHA {
432                 t.Fatalf("Server's preference was not used, got %x", state.CipherSuite)
433         }
434 }
435
436 func TestSCTHandshake(t *testing.T) {
437         t.Run("TLSv12", func(t *testing.T) { testSCTHandshake(t, VersionTLS12) })
438         t.Run("TLSv13", func(t *testing.T) { testSCTHandshake(t, VersionTLS13) })
439 }
440
441 func testSCTHandshake(t *testing.T, version uint16) {
442         expected := [][]byte{[]byte("certificate"), []byte("transparency")}
443         serverConfig := &Config{
444                 Certificates: []Certificate{{
445                         Certificate:                 [][]byte{testRSACertificate},
446                         PrivateKey:                  testRSAPrivateKey,
447                         SignedCertificateTimestamps: expected,
448                 }},
449                 MaxVersion: version,
450         }
451         clientConfig := &Config{
452                 InsecureSkipVerify: true,
453         }
454         _, state, err := testHandshake(t, clientConfig, serverConfig)
455         if err != nil {
456                 t.Fatalf("handshake failed: %s", err)
457         }
458         actual := state.SignedCertificateTimestamps
459         if len(actual) != len(expected) {
460                 t.Fatalf("got %d scts, want %d", len(actual), len(expected))
461         }
462         for i, sct := range expected {
463                 if !bytes.Equal(sct, actual[i]) {
464                         t.Fatalf("SCT #%d was %x, but expected %x", i, actual[i], sct)
465                 }
466         }
467 }
468
469 func TestCrossVersionResume(t *testing.T) {
470         t.Run("TLSv12", func(t *testing.T) { testCrossVersionResume(t, VersionTLS12) })
471         t.Run("TLSv13", func(t *testing.T) { testCrossVersionResume(t, VersionTLS13) })
472 }
473
474 func testCrossVersionResume(t *testing.T, version uint16) {
475         serverConfig := &Config{
476                 CipherSuites: []uint16{TLS_RSA_WITH_AES_128_CBC_SHA},
477                 Certificates: testConfig.Certificates,
478         }
479         clientConfig := &Config{
480                 CipherSuites:       []uint16{TLS_RSA_WITH_AES_128_CBC_SHA},
481                 InsecureSkipVerify: true,
482                 ClientSessionCache: NewLRUClientSessionCache(1),
483                 ServerName:         "servername",
484         }
485
486         // Establish a session at TLS 1.1.
487         clientConfig.MaxVersion = VersionTLS11
488         _, _, err := testHandshake(t, clientConfig, serverConfig)
489         if err != nil {
490                 t.Fatalf("handshake failed: %s", err)
491         }
492
493         // The client session cache now contains a TLS 1.1 session.
494         state, _, err := testHandshake(t, clientConfig, serverConfig)
495         if err != nil {
496                 t.Fatalf("handshake failed: %s", err)
497         }
498         if !state.DidResume {
499                 t.Fatalf("handshake did not resume at the same version")
500         }
501
502         // Test that the server will decline to resume at a lower version.
503         clientConfig.MaxVersion = VersionTLS10
504         state, _, err = testHandshake(t, clientConfig, serverConfig)
505         if err != nil {
506                 t.Fatalf("handshake failed: %s", err)
507         }
508         if state.DidResume {
509                 t.Fatalf("handshake resumed at a lower version")
510         }
511
512         // The client session cache now contains a TLS 1.0 session.
513         state, _, err = testHandshake(t, clientConfig, serverConfig)
514         if err != nil {
515                 t.Fatalf("handshake failed: %s", err)
516         }
517         if !state.DidResume {
518                 t.Fatalf("handshake did not resume at the same version")
519         }
520
521         // Test that the server will decline to resume at a higher version.
522         clientConfig.MaxVersion = VersionTLS11
523         state, _, err = testHandshake(t, clientConfig, serverConfig)
524         if err != nil {
525                 t.Fatalf("handshake failed: %s", err)
526         }
527         if state.DidResume {
528                 t.Fatalf("handshake resumed at a higher version")
529         }
530 }
531
532 // Note: see comment in handshake_test.go for details of how the reference
533 // tests work.
534
535 // serverTest represents a test of the TLS server handshake against a reference
536 // implementation.
537 type serverTest struct {
538         // name is a freeform string identifying the test and the file in which
539         // the expected results will be stored.
540         name string
541         // command, if not empty, contains a series of arguments for the
542         // command to run for the reference server.
543         command []string
544         // expectedPeerCerts contains a list of PEM blocks of expected
545         // certificates from the client.
546         expectedPeerCerts []string
547         // config, if not nil, contains a custom Config to use for this test.
548         config *Config
549         // expectHandshakeErrorIncluding, when not empty, contains a string
550         // that must be a substring of the error resulting from the handshake.
551         expectHandshakeErrorIncluding string
552         // validate, if not nil, is a function that will be called with the
553         // ConnectionState of the resulting connection. It returns false if the
554         // ConnectionState is unacceptable.
555         validate func(ConnectionState) error
556         // wait, if true, prevents this subtest from calling t.Parallel.
557         // If false, runServerTest* returns immediately.
558         wait bool
559 }
560
561 var defaultClientCommand = []string{"openssl", "s_client", "-no_ticket"}
562
563 // connFromCommand starts opens a listening socket and starts the reference
564 // client to connect to it. It returns a recordingConn that wraps the resulting
565 // connection.
566 func (test *serverTest) connFromCommand() (conn *recordingConn, child *exec.Cmd, err error) {
567         l, err := net.ListenTCP("tcp", &net.TCPAddr{
568                 IP:   net.IPv4(127, 0, 0, 1),
569                 Port: 0,
570         })
571         if err != nil {
572                 return nil, nil, err
573         }
574         defer l.Close()
575
576         port := l.Addr().(*net.TCPAddr).Port
577
578         var command []string
579         command = append(command, test.command...)
580         if len(command) == 0 {
581                 command = defaultClientCommand
582         }
583         command = append(command, "-connect")
584         command = append(command, fmt.Sprintf("127.0.0.1:%d", port))
585         cmd := exec.Command(command[0], command[1:]...)
586         cmd.Stdin = nil
587         var output bytes.Buffer
588         cmd.Stdout = &output
589         cmd.Stderr = &output
590         if err := cmd.Start(); err != nil {
591                 return nil, nil, err
592         }
593
594         connChan := make(chan interface{})
595         go func() {
596                 tcpConn, err := l.Accept()
597                 if err != nil {
598                         connChan <- err
599                 }
600                 connChan <- tcpConn
601         }()
602
603         var tcpConn net.Conn
604         select {
605         case connOrError := <-connChan:
606                 if err, ok := connOrError.(error); ok {
607                         return nil, nil, err
608                 }
609                 tcpConn = connOrError.(net.Conn)
610         case <-time.After(2 * time.Second):
611                 return nil, nil, errors.New("timed out waiting for connection from child process")
612         }
613
614         record := &recordingConn{
615                 Conn: tcpConn,
616         }
617
618         return record, cmd, nil
619 }
620
621 func (test *serverTest) dataPath() string {
622         return filepath.Join("testdata", "Server-"+test.name)
623 }
624
625 func (test *serverTest) loadData() (flows [][]byte, err error) {
626         in, err := os.Open(test.dataPath())
627         if err != nil {
628                 return nil, err
629         }
630         defer in.Close()
631         return parseTestData(in)
632 }
633
634 func (test *serverTest) run(t *testing.T, write bool) {
635         checkOpenSSLVersion(t)
636
637         var clientConn, serverConn net.Conn
638         var recordingConn *recordingConn
639         var childProcess *exec.Cmd
640
641         if write {
642                 var err error
643                 recordingConn, childProcess, err = test.connFromCommand()
644                 if err != nil {
645                         t.Fatalf("Failed to start subcommand: %s", err)
646                 }
647                 serverConn = recordingConn
648                 defer func() {
649                         if t.Failed() {
650                                 t.Logf("OpenSSL output:\n\n%s", childProcess.Stdout)
651                         }
652                 }()
653         } else {
654                 clientConn, serverConn = localPipe(t)
655         }
656         config := test.config
657         if config == nil {
658                 config = testConfig
659         }
660         server := Server(serverConn, config)
661         connStateChan := make(chan ConnectionState, 1)
662         go func() {
663                 _, err := server.Write([]byte("hello, world\n"))
664                 if len(test.expectHandshakeErrorIncluding) > 0 {
665                         if err == nil {
666                                 t.Errorf("Error expected, but no error returned")
667                         } else if s := err.Error(); !strings.Contains(s, test.expectHandshakeErrorIncluding) {
668                                 t.Errorf("Error expected containing '%s' but got '%s'", test.expectHandshakeErrorIncluding, s)
669                         }
670                 } else {
671                         if err != nil {
672                                 t.Logf("Error from Server.Write: '%s'", err)
673                         }
674                 }
675                 server.Close()
676                 serverConn.Close()
677                 connStateChan <- server.ConnectionState()
678         }()
679
680         if !write {
681                 flows, err := test.loadData()
682                 if err != nil {
683                         t.Fatalf("%s: failed to load data from %s", test.name, test.dataPath())
684                 }
685                 for i, b := range flows {
686                         if i%2 == 0 {
687                                 clientConn.SetWriteDeadline(time.Now().Add(1 * time.Minute))
688                                 clientConn.Write(b)
689                                 continue
690                         }
691                         bb := make([]byte, len(b))
692                         clientConn.SetReadDeadline(time.Now().Add(1 * time.Minute))
693                         n, err := io.ReadFull(clientConn, bb)
694                         if err != nil {
695                                 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)
696                         }
697                         if !bytes.Equal(b, bb) {
698                                 t.Fatalf("%s #%d: mismatch on read: got:%x want:%x", test.name, i+1, bb, b)
699                         }
700                 }
701                 clientConn.Close()
702         }
703
704         connState := <-connStateChan
705         peerCerts := connState.PeerCertificates
706         if len(peerCerts) == len(test.expectedPeerCerts) {
707                 for i, peerCert := range peerCerts {
708                         block, _ := pem.Decode([]byte(test.expectedPeerCerts[i]))
709                         if !bytes.Equal(block.Bytes, peerCert.Raw) {
710                                 t.Fatalf("%s: mismatch on peer cert %d", test.name, i+1)
711                         }
712                 }
713         } else {
714                 t.Fatalf("%s: mismatch on peer list length: %d (wanted) != %d (got)", test.name, len(test.expectedPeerCerts), len(peerCerts))
715         }
716
717         if test.validate != nil {
718                 if err := test.validate(connState); err != nil {
719                         t.Fatalf("validate callback returned error: %s", err)
720                 }
721         }
722
723         if write {
724                 path := test.dataPath()
725                 out, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
726                 if err != nil {
727                         t.Fatalf("Failed to create output file: %s", err)
728                 }
729                 defer out.Close()
730                 recordingConn.Close()
731                 if len(recordingConn.flows) < 3 {
732                         if len(test.expectHandshakeErrorIncluding) == 0 {
733                                 t.Fatalf("Handshake failed")
734                         }
735                 }
736                 recordingConn.WriteTo(out)
737                 t.Logf("Wrote %s\n", path)
738                 childProcess.Wait()
739         }
740 }
741
742 func runServerTestForVersion(t *testing.T, template *serverTest, version, option string) {
743         t.Run(version, func(t *testing.T) {
744                 // Make a deep copy of the template before going parallel.
745                 test := *template
746                 if template.config != nil {
747                         test.config = template.config.Clone()
748                 }
749
750                 if !*update && !template.wait {
751                         t.Parallel()
752                 }
753
754                 test.name = version + "-" + test.name
755                 if len(test.command) == 0 {
756                         test.command = defaultClientCommand
757                 }
758                 test.command = append([]string(nil), test.command...)
759                 test.command = append(test.command, option)
760                 test.run(t, *update)
761         })
762 }
763
764 func runServerTestSSLv3(t *testing.T, template *serverTest) {
765         runServerTestForVersion(t, template, "SSLv3", "-ssl3")
766 }
767
768 func runServerTestTLS10(t *testing.T, template *serverTest) {
769         runServerTestForVersion(t, template, "TLSv10", "-tls1")
770 }
771
772 func runServerTestTLS11(t *testing.T, template *serverTest) {
773         runServerTestForVersion(t, template, "TLSv11", "-tls1_1")
774 }
775
776 func runServerTestTLS12(t *testing.T, template *serverTest) {
777         runServerTestForVersion(t, template, "TLSv12", "-tls1_2")
778 }
779
780 func runServerTestTLS13(t *testing.T, template *serverTest) {
781         runServerTestForVersion(t, template, "TLSv13", "-tls1_3")
782 }
783
784 func TestHandshakeServerRSARC4(t *testing.T) {
785         test := &serverTest{
786                 name:    "RSA-RC4",
787                 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "RC4-SHA"},
788         }
789         runServerTestSSLv3(t, test)
790         runServerTestTLS10(t, test)
791         runServerTestTLS11(t, test)
792         runServerTestTLS12(t, test)
793 }
794
795 func TestHandshakeServerRSA3DES(t *testing.T) {
796         test := &serverTest{
797                 name:    "RSA-3DES",
798                 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "DES-CBC3-SHA"},
799         }
800         runServerTestSSLv3(t, test)
801         runServerTestTLS10(t, test)
802         runServerTestTLS12(t, test)
803 }
804
805 func TestHandshakeServerRSAAES(t *testing.T) {
806         test := &serverTest{
807                 name:    "RSA-AES",
808                 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA"},
809         }
810         runServerTestSSLv3(t, test)
811         runServerTestTLS10(t, test)
812         runServerTestTLS12(t, test)
813 }
814
815 func TestHandshakeServerAESGCM(t *testing.T) {
816         test := &serverTest{
817                 name:    "RSA-AES-GCM",
818                 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-AES128-GCM-SHA256"},
819         }
820         runServerTestTLS12(t, test)
821 }
822
823 func TestHandshakeServerAES256GCMSHA384(t *testing.T) {
824         test := &serverTest{
825                 name:    "RSA-AES256-GCM-SHA384",
826                 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-AES256-GCM-SHA384"},
827         }
828         runServerTestTLS12(t, test)
829 }
830
831 func TestHandshakeServerAES128SHA256(t *testing.T) {
832         test := &serverTest{
833                 name:    "AES128-SHA256",
834                 command: []string{"openssl", "s_client", "-no_ticket", "-ciphersuites", "TLS_AES_128_GCM_SHA256"},
835         }
836         runServerTestTLS13(t, test)
837 }
838 func TestHandshakeServerAES256SHA384(t *testing.T) {
839         test := &serverTest{
840                 name:    "AES256-SHA384",
841                 command: []string{"openssl", "s_client", "-no_ticket", "-ciphersuites", "TLS_AES_256_GCM_SHA384"},
842         }
843         runServerTestTLS13(t, test)
844 }
845 func TestHandshakeServerCHACHA20SHA256(t *testing.T) {
846         test := &serverTest{
847                 name:    "CHACHA20-SHA256",
848                 command: []string{"openssl", "s_client", "-no_ticket", "-ciphersuites", "TLS_CHACHA20_POLY1305_SHA256"},
849         }
850         runServerTestTLS13(t, test)
851 }
852
853 func TestHandshakeServerECDHEECDSAAES(t *testing.T) {
854         config := testConfig.Clone()
855         config.Certificates = make([]Certificate, 1)
856         config.Certificates[0].Certificate = [][]byte{testECDSACertificate}
857         config.Certificates[0].PrivateKey = testECDSAPrivateKey
858         config.BuildNameToCertificate()
859
860         test := &serverTest{
861                 name:    "ECDHE-ECDSA-AES",
862                 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-ECDSA-AES256-SHA", "-ciphersuites", "TLS_AES_128_GCM_SHA256"},
863                 config:  config,
864         }
865         runServerTestTLS10(t, test)
866         runServerTestTLS12(t, test)
867         runServerTestTLS13(t, test)
868 }
869
870 func TestHandshakeServerX25519(t *testing.T) {
871         config := testConfig.Clone()
872         config.CurvePreferences = []CurveID{X25519}
873
874         test := &serverTest{
875                 name:    "X25519",
876                 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-AES128-GCM-SHA256", "-curves", "X25519"},
877                 config:  config,
878         }
879         runServerTestTLS12(t, test)
880         runServerTestTLS13(t, test)
881 }
882
883 func TestHandshakeServerP256(t *testing.T) {
884         config := testConfig.Clone()
885         config.CurvePreferences = []CurveID{CurveP256}
886
887         test := &serverTest{
888                 name:    "P256",
889                 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-AES128-GCM-SHA256", "-curves", "P-256"},
890                 config:  config,
891         }
892         runServerTestTLS12(t, test)
893         runServerTestTLS13(t, test)
894 }
895
896 func TestHandshakeServerHelloRetryRequest(t *testing.T) {
897         config := testConfig.Clone()
898         config.CurvePreferences = []CurveID{CurveP256}
899
900         test := &serverTest{
901                 name:    "HelloRetryRequest",
902                 command: []string{"openssl", "s_client", "-no_ticket", "-curves", "X25519:P-256"},
903                 config:  config,
904         }
905         runServerTestTLS13(t, test)
906 }
907
908 func TestHandshakeServerALPN(t *testing.T) {
909         config := testConfig.Clone()
910         config.NextProtos = []string{"proto1", "proto2"}
911
912         test := &serverTest{
913                 name: "ALPN",
914                 // Note that this needs OpenSSL 1.0.2 because that is the first
915                 // version that supports the -alpn flag.
916                 command: []string{"openssl", "s_client", "-alpn", "proto2,proto1"},
917                 config:  config,
918                 validate: func(state ConnectionState) error {
919                         // The server's preferences should override the client.
920                         if state.NegotiatedProtocol != "proto1" {
921                                 return fmt.Errorf("Got protocol %q, wanted proto1", state.NegotiatedProtocol)
922                         }
923                         return nil
924                 },
925         }
926         runServerTestTLS12(t, test)
927         runServerTestTLS13(t, test)
928 }
929
930 func TestHandshakeServerALPNNoMatch(t *testing.T) {
931         config := testConfig.Clone()
932         config.NextProtos = []string{"proto3"}
933
934         test := &serverTest{
935                 name: "ALPN-NoMatch",
936                 // Note that this needs OpenSSL 1.0.2 because that is the first
937                 // version that supports the -alpn flag.
938                 command: []string{"openssl", "s_client", "-alpn", "proto2,proto1"},
939                 config:  config,
940                 validate: func(state ConnectionState) error {
941                         // Rather than reject the connection, Go doesn't select
942                         // a protocol when there is no overlap.
943                         if state.NegotiatedProtocol != "" {
944                                 return fmt.Errorf("Got protocol %q, wanted ''", state.NegotiatedProtocol)
945                         }
946                         return nil
947                 },
948         }
949         runServerTestTLS12(t, test)
950         runServerTestTLS13(t, test)
951 }
952
953 // TestHandshakeServerSNI involves a client sending an SNI extension of
954 // "snitest.com", which happens to match the CN of testSNICertificate. The test
955 // verifies that the server correctly selects that certificate.
956 func TestHandshakeServerSNI(t *testing.T) {
957         test := &serverTest{
958                 name:    "SNI",
959                 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"},
960         }
961         runServerTestTLS12(t, test)
962 }
963
964 // TestHandshakeServerSNICertForName is similar to TestHandshakeServerSNI, but
965 // tests the dynamic GetCertificate method
966 func TestHandshakeServerSNIGetCertificate(t *testing.T) {
967         config := testConfig.Clone()
968
969         // Replace the NameToCertificate map with a GetCertificate function
970         nameToCert := config.NameToCertificate
971         config.NameToCertificate = nil
972         config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
973                 cert := nameToCert[clientHello.ServerName]
974                 return cert, nil
975         }
976         test := &serverTest{
977                 name:    "SNI-GetCertificate",
978                 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"},
979                 config:  config,
980         }
981         runServerTestTLS12(t, test)
982 }
983
984 // TestHandshakeServerSNICertForNameNotFound is similar to
985 // TestHandshakeServerSNICertForName, but tests to make sure that when the
986 // GetCertificate method doesn't return a cert, we fall back to what's in
987 // the NameToCertificate map.
988 func TestHandshakeServerSNIGetCertificateNotFound(t *testing.T) {
989         config := testConfig.Clone()
990
991         config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
992                 return nil, nil
993         }
994         test := &serverTest{
995                 name:    "SNI-GetCertificateNotFound",
996                 command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"},
997                 config:  config,
998         }
999         runServerTestTLS12(t, test)
1000 }
1001
1002 // TestHandshakeServerSNICertForNameError tests to make sure that errors in
1003 // GetCertificate result in a tls alert.
1004 func TestHandshakeServerSNIGetCertificateError(t *testing.T) {
1005         const errMsg = "TestHandshakeServerSNIGetCertificateError error"
1006
1007         serverConfig := testConfig.Clone()
1008         serverConfig.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
1009                 return nil, errors.New(errMsg)
1010         }
1011
1012         clientHello := &clientHelloMsg{
1013                 vers:               VersionTLS10,
1014                 random:             make([]byte, 32),
1015                 cipherSuites:       []uint16{TLS_RSA_WITH_RC4_128_SHA},
1016                 compressionMethods: []uint8{compressionNone},
1017                 serverName:         "test",
1018         }
1019         testClientHelloFailure(t, serverConfig, clientHello, errMsg)
1020 }
1021
1022 // TestHandshakeServerEmptyCertificates tests that GetCertificates is called in
1023 // the case that Certificates is empty, even without SNI.
1024 func TestHandshakeServerEmptyCertificates(t *testing.T) {
1025         const errMsg = "TestHandshakeServerEmptyCertificates error"
1026
1027         serverConfig := testConfig.Clone()
1028         serverConfig.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
1029                 return nil, errors.New(errMsg)
1030         }
1031         serverConfig.Certificates = nil
1032
1033         clientHello := &clientHelloMsg{
1034                 vers:               VersionTLS10,
1035                 random:             make([]byte, 32),
1036                 cipherSuites:       []uint16{TLS_RSA_WITH_RC4_128_SHA},
1037                 compressionMethods: []uint8{compressionNone},
1038         }
1039         testClientHelloFailure(t, serverConfig, clientHello, errMsg)
1040
1041         // With an empty Certificates and a nil GetCertificate, the server
1042         // should always return a “no certificates” error.
1043         serverConfig.GetCertificate = nil
1044
1045         clientHello = &clientHelloMsg{
1046                 vers:               VersionTLS10,
1047                 random:             make([]byte, 32),
1048                 cipherSuites:       []uint16{TLS_RSA_WITH_RC4_128_SHA},
1049                 compressionMethods: []uint8{compressionNone},
1050         }
1051         testClientHelloFailure(t, serverConfig, clientHello, "no certificates")
1052 }
1053
1054 // TestCipherSuiteCertPreferance ensures that we select an RSA ciphersuite with
1055 // an RSA certificate and an ECDSA ciphersuite with an ECDSA certificate.
1056 func TestCipherSuiteCertPreferenceECDSA(t *testing.T) {
1057         config := testConfig.Clone()
1058         config.CipherSuites = []uint16{TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA}
1059         config.PreferServerCipherSuites = true
1060
1061         test := &serverTest{
1062                 name:   "CipherSuiteCertPreferenceRSA",
1063                 config: config,
1064         }
1065         runServerTestTLS12(t, test)
1066
1067         config = testConfig.Clone()
1068         config.CipherSuites = []uint16{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA}
1069         config.Certificates = []Certificate{
1070                 {
1071                         Certificate: [][]byte{testECDSACertificate},
1072                         PrivateKey:  testECDSAPrivateKey,
1073                 },
1074         }
1075         config.BuildNameToCertificate()
1076         config.PreferServerCipherSuites = true
1077
1078         test = &serverTest{
1079                 name:   "CipherSuiteCertPreferenceECDSA",
1080                 config: config,
1081         }
1082         runServerTestTLS12(t, test)
1083 }
1084
1085 func TestServerResumption(t *testing.T) {
1086         sessionFilePath := tempFile("")
1087         defer os.Remove(sessionFilePath)
1088
1089         testIssue := &serverTest{
1090                 name:    "IssueTicket",
1091                 command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-sess_out", sessionFilePath},
1092                 wait:    true,
1093         }
1094         testResume := &serverTest{
1095                 name:    "Resume",
1096                 command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-sess_in", sessionFilePath},
1097                 validate: func(state ConnectionState) error {
1098                         if !state.DidResume {
1099                                 return errors.New("did not resume")
1100                         }
1101                         return nil
1102                 },
1103         }
1104
1105         runServerTestTLS12(t, testIssue)
1106         runServerTestTLS12(t, testResume)
1107
1108         runServerTestTLS13(t, testIssue)
1109         runServerTestTLS13(t, testResume)
1110
1111         config := testConfig.Clone()
1112         config.CurvePreferences = []CurveID{CurveP256}
1113
1114         testResumeHRR := &serverTest{
1115                 name:    "Resume-HelloRetryRequest",
1116                 command: []string{"openssl", "s_client", "-curves", "X25519:P-256", "-sess_in", sessionFilePath},
1117                 config:  config,
1118                 validate: func(state ConnectionState) error {
1119                         if !state.DidResume {
1120                                 return errors.New("did not resume")
1121                         }
1122                         return nil
1123                 },
1124         }
1125
1126         runServerTestTLS13(t, testResumeHRR)
1127 }
1128
1129 func TestServerResumptionDisabled(t *testing.T) {
1130         sessionFilePath := tempFile("")
1131         defer os.Remove(sessionFilePath)
1132
1133         config := testConfig.Clone()
1134
1135         testIssue := &serverTest{
1136                 name:    "IssueTicketPreDisable",
1137                 command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-sess_out", sessionFilePath},
1138                 config:  config,
1139                 wait:    true,
1140         }
1141         testResume := &serverTest{
1142                 name:    "ResumeDisabled",
1143                 command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-sess_in", sessionFilePath},
1144                 config:  config,
1145                 validate: func(state ConnectionState) error {
1146                         if state.DidResume {
1147                                 return errors.New("resumed with SessionTicketsDisabled")
1148                         }
1149                         return nil
1150                 },
1151         }
1152
1153         config.SessionTicketsDisabled = false
1154         runServerTestTLS12(t, testIssue)
1155         config.SessionTicketsDisabled = true
1156         runServerTestTLS12(t, testResume)
1157
1158         config.SessionTicketsDisabled = false
1159         runServerTestTLS13(t, testIssue)
1160         config.SessionTicketsDisabled = true
1161         runServerTestTLS13(t, testResume)
1162 }
1163
1164 func TestFallbackSCSV(t *testing.T) {
1165         serverConfig := Config{
1166                 Certificates: testConfig.Certificates,
1167         }
1168         test := &serverTest{
1169                 name:   "FallbackSCSV",
1170                 config: &serverConfig,
1171                 // OpenSSL 1.0.1j is needed for the -fallback_scsv option.
1172                 command:                       []string{"openssl", "s_client", "-fallback_scsv"},
1173                 expectHandshakeErrorIncluding: "inappropriate protocol fallback",
1174         }
1175         runServerTestTLS11(t, test)
1176 }
1177
1178 func TestHandshakeServerExportKeyingMaterial(t *testing.T) {
1179         test := &serverTest{
1180                 name:    "ExportKeyingMaterial",
1181                 command: []string{"openssl", "s_client"},
1182                 config:  testConfig.Clone(),
1183                 validate: func(state ConnectionState) error {
1184                         if km, err := state.ExportKeyingMaterial("test", nil, 42); err != nil {
1185                                 return fmt.Errorf("ExportKeyingMaterial failed: %v", err)
1186                         } else if len(km) != 42 {
1187                                 return fmt.Errorf("Got %d bytes from ExportKeyingMaterial, wanted %d", len(km), 42)
1188                         }
1189                         return nil
1190                 },
1191         }
1192         runServerTestTLS10(t, test)
1193         runServerTestTLS12(t, test)
1194         runServerTestTLS13(t, test)
1195 }
1196
1197 func TestHandshakeServerRSAPKCS1v15(t *testing.T) {
1198         test := &serverTest{
1199                 name:    "RSA-RSAPKCS1v15",
1200                 command: []string{"openssl", "s_client", "-no_ticket", "-sigalgs", "rsa_pkcs1_sha256"},
1201         }
1202         runServerTestTLS12(t, test)
1203 }
1204
1205 func TestHandshakeServerRSAPSS(t *testing.T) {
1206         test := &serverTest{
1207                 name:    "RSA-RSAPSS",
1208                 command: []string{"openssl", "s_client", "-no_ticket", "-sigalgs", "rsa_pss_rsae_sha256"},
1209         }
1210         runServerTestTLS12(t, test)
1211         runServerTestTLS13(t, test)
1212 }
1213
1214 func TestHandshakeServerPSSDisabled(t *testing.T) {
1215         test := &serverTest{
1216                 name:    "RSA-PSS-Disabled",
1217                 command: []string{"openssl", "s_client", "-no_ticket"},
1218                 wait:    true,
1219         }
1220
1221         // Restore the default signature algorithms, disabling RSA-PSS in TLS 1.2,
1222         // and check that handshakes still work.
1223         testSupportedSignatureAlgorithmsTLS12 := supportedSignatureAlgorithmsTLS12
1224         defer func() { supportedSignatureAlgorithmsTLS12 = testSupportedSignatureAlgorithmsTLS12 }()
1225         supportedSignatureAlgorithmsTLS12 = savedSupportedSignatureAlgorithmsTLS12
1226
1227         runServerTestTLS12(t, test)
1228         runServerTestTLS13(t, test)
1229
1230         test = &serverTest{
1231                 name:    "RSA-PSS-Disabled-Required",
1232                 command: []string{"openssl", "s_client", "-no_ticket", "-sigalgs", "rsa_pss_rsae_sha256"},
1233                 wait:    true,
1234
1235                 expectHandshakeErrorIncluding: "peer doesn't support any common signature algorithms",
1236         }
1237
1238         runServerTestTLS12(t, test)
1239 }
1240
1241 func benchmarkHandshakeServer(b *testing.B, version uint16, cipherSuite uint16, curve CurveID, cert []byte, key crypto.PrivateKey) {
1242         config := testConfig.Clone()
1243         config.CipherSuites = []uint16{cipherSuite}
1244         config.CurvePreferences = []CurveID{curve}
1245         config.Certificates = make([]Certificate, 1)
1246         config.Certificates[0].Certificate = [][]byte{cert}
1247         config.Certificates[0].PrivateKey = key
1248         config.BuildNameToCertificate()
1249
1250         clientConn, serverConn := localPipe(b)
1251         serverConn = &recordingConn{Conn: serverConn}
1252         go func() {
1253                 config := testConfig.Clone()
1254                 config.MaxVersion = version
1255                 config.CurvePreferences = []CurveID{curve}
1256                 client := Client(clientConn, config)
1257                 client.Handshake()
1258         }()
1259         server := Server(serverConn, config)
1260         if err := server.Handshake(); err != nil {
1261                 b.Fatalf("handshake failed: %v", err)
1262         }
1263         serverConn.Close()
1264         flows := serverConn.(*recordingConn).flows
1265
1266         feeder := make(chan struct{})
1267         clientConn, serverConn = localPipe(b)
1268
1269         go func() {
1270                 for range feeder {
1271                         for i, f := range flows {
1272                                 if i%2 == 0 {
1273                                         clientConn.Write(f)
1274                                         continue
1275                                 }
1276                                 ff := make([]byte, len(f))
1277                                 n, err := io.ReadFull(clientConn, ff)
1278                                 if err != nil {
1279                                         b.Errorf("#%d: %s\nRead %d, wanted %d, got %x, wanted %x\n", i+1, err, n, len(ff), ff[:n], f)
1280                                 }
1281                                 if !bytes.Equal(f, ff) {
1282                                         b.Errorf("#%d: mismatch on read: got:%x want:%x", i+1, ff, f)
1283                                 }
1284                         }
1285                 }
1286         }()
1287
1288         b.ResetTimer()
1289         for i := 0; i < b.N; i++ {
1290                 feeder <- struct{}{}
1291                 server := Server(serverConn, config)
1292                 if err := server.Handshake(); err != nil {
1293                         b.Fatalf("handshake failed: %v", err)
1294                 }
1295         }
1296         close(feeder)
1297 }
1298
1299 func BenchmarkHandshakeServer(b *testing.B) {
1300         b.Run("RSA", func(b *testing.B) {
1301                 benchmarkHandshakeServer(b, VersionTLS12, TLS_RSA_WITH_AES_128_GCM_SHA256,
1302                         0, testRSACertificate, testRSAPrivateKey)
1303         })
1304         b.Run("ECDHE-P256-RSA", func(b *testing.B) {
1305                 b.Run("TLSv13", func(b *testing.B) {
1306                         benchmarkHandshakeServer(b, VersionTLS13, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1307                                 CurveP256, testRSACertificate, testRSAPrivateKey)
1308                 })
1309                 b.Run("TLSv12", func(b *testing.B) {
1310                         benchmarkHandshakeServer(b, VersionTLS12, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
1311                                 CurveP256, testRSACertificate, testRSAPrivateKey)
1312                 })
1313         })
1314         b.Run("ECDHE-P256-ECDSA-P256", func(b *testing.B) {
1315                 b.Run("TLSv13", func(b *testing.B) {
1316                         benchmarkHandshakeServer(b, VersionTLS13, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
1317                                 CurveP256, testP256Certificate, testP256PrivateKey)
1318                 })
1319                 b.Run("TLSv12", func(b *testing.B) {
1320                         benchmarkHandshakeServer(b, VersionTLS12, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
1321                                 CurveP256, testP256Certificate, testP256PrivateKey)
1322                 })
1323         })
1324         b.Run("ECDHE-X25519-ECDSA-P256", func(b *testing.B) {
1325                 b.Run("TLSv13", func(b *testing.B) {
1326                         benchmarkHandshakeServer(b, VersionTLS13, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
1327                                 X25519, testP256Certificate, testP256PrivateKey)
1328                 })
1329                 b.Run("TLSv12", func(b *testing.B) {
1330                         benchmarkHandshakeServer(b, VersionTLS12, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
1331                                 X25519, testP256Certificate, testP256PrivateKey)
1332                 })
1333         })
1334         b.Run("ECDHE-P521-ECDSA-P521", func(b *testing.B) {
1335                 if testECDSAPrivateKey.PublicKey.Curve != elliptic.P521() {
1336                         b.Fatal("test ECDSA key doesn't use curve P-521")
1337                 }
1338                 b.Run("TLSv13", func(b *testing.B) {
1339                         benchmarkHandshakeServer(b, VersionTLS13, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
1340                                 CurveP521, testECDSACertificate, testECDSAPrivateKey)
1341                 })
1342                 b.Run("TLSv12", func(b *testing.B) {
1343                         benchmarkHandshakeServer(b, VersionTLS12, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
1344                                 CurveP521, testECDSACertificate, testECDSAPrivateKey)
1345                 })
1346         })
1347 }
1348
1349 const clientCertificatePEM = `
1350 -----BEGIN CERTIFICATE-----
1351 MIIB7zCCAVigAwIBAgIQXBnBiWWDVW/cC8m5k5/pvDANBgkqhkiG9w0BAQsFADAS
1352 MRAwDgYDVQQKEwdBY21lIENvMB4XDTE2MDgxNzIxNTIzMVoXDTE3MDgxNzIxNTIz
1353 MVowEjEQMA4GA1UEChMHQWNtZSBDbzCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkC
1354 gYEAum+qhr3Pv5/y71yUYHhv6BPy0ZZvzdkybiI3zkH5yl0prOEn2mGi7oHLEMff
1355 NFiVhuk9GeZcJ3NgyI14AvQdpJgJoxlwaTwlYmYqqyIjxXuFOE8uCXMyp70+m63K
1356 hAfmDzr/d8WdQYUAirab7rCkPy1MTOZCPrtRyN1IVPQMjkcCAwEAAaNGMEQwDgYD
1357 VR0PAQH/BAQDAgWgMBMGA1UdJQQMMAoGCCsGAQUFBwMBMAwGA1UdEwEB/wQCMAAw
1358 DwYDVR0RBAgwBocEfwAAATANBgkqhkiG9w0BAQsFAAOBgQBGq0Si+yhU+Fpn+GKU
1359 8ZqyGJ7ysd4dfm92lam6512oFmyc9wnTN+RLKzZ8Aa1B0jLYw9KT+RBrjpW5LBeK
1360 o0RIvFkTgxYEiKSBXCUNmAysEbEoVr4dzWFihAm/1oDGRY2CLLTYg5vbySK3KhIR
1361 e/oCO8HJ/+rJnahJ05XX1Q7lNQ==
1362 -----END CERTIFICATE-----`
1363
1364 const clientKeyPEM = `
1365 -----BEGIN RSA PRIVATE KEY-----
1366 MIICXQIBAAKBgQC6b6qGvc+/n/LvXJRgeG/oE/LRlm/N2TJuIjfOQfnKXSms4Sfa
1367 YaLugcsQx980WJWG6T0Z5lwnc2DIjXgC9B2kmAmjGXBpPCViZiqrIiPFe4U4Ty4J
1368 czKnvT6brcqEB+YPOv93xZ1BhQCKtpvusKQ/LUxM5kI+u1HI3UhU9AyORwIDAQAB
1369 AoGAEJZ03q4uuMb7b26WSQsOMeDsftdatT747LGgs3pNRkMJvTb/O7/qJjxoG+Mc
1370 qeSj0TAZXp+PXXc3ikCECAc+R8rVMfWdmp903XgO/qYtmZGCorxAHEmR80SrfMXv
1371 PJnznLQWc8U9nphQErR+tTESg7xWEzmFcPKwnZd1xg8ERYkCQQDTGtrFczlB2b/Z
1372 9TjNMqUlMnTLIk/a/rPE2fLLmAYhK5sHnJdvDURaH2mF4nso0EGtENnTsh6LATnY
1373 dkrxXGm9AkEA4hXHG2q3MnhgK1Z5hjv+Fnqd+8bcbII9WW4flFs15EKoMgS1w/PJ
1374 zbsySaSy5IVS8XeShmT9+3lrleed4sy+UwJBAJOOAbxhfXP5r4+5R6ql66jES75w
1375 jUCVJzJA5ORJrn8g64u2eGK28z/LFQbv9wXgCwfc72R468BdawFSLa/m2EECQGbZ
1376 rWiFla26IVXV0xcD98VWJsTBZMlgPnSOqoMdM1kSEd4fUmlAYI/dFzV1XYSkOmVr
1377 FhdZnklmpVDeu27P4c0CQQCuCOup0FlJSBpWY1TTfun/KMBkBatMz0VMA3d7FKIU
1378 csPezl677Yjo8u1r/KzeI6zLg87Z8E6r6ZWNc9wBSZK6
1379 -----END RSA PRIVATE KEY-----`
1380
1381 const clientECDSACertificatePEM = `
1382 -----BEGIN CERTIFICATE-----
1383 MIIB/DCCAV4CCQCaMIRsJjXZFzAJBgcqhkjOPQQBMEUxCzAJBgNVBAYTAkFVMRMw
1384 EQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0
1385 eSBMdGQwHhcNMTIxMTE0MTMyNTUzWhcNMjIxMTEyMTMyNTUzWjBBMQswCQYDVQQG
1386 EwJBVTEMMAoGA1UECBMDTlNXMRAwDgYDVQQHEwdQeXJtb250MRIwEAYDVQQDEwlK
1387 b2VsIFNpbmcwgZswEAYHKoZIzj0CAQYFK4EEACMDgYYABACVjJF1FMBexFe01MNv
1388 ja5oHt1vzobhfm6ySD6B5U7ixohLZNz1MLvT/2XMW/TdtWo+PtAd3kfDdq0Z9kUs
1389 jLzYHQFMH3CQRnZIi4+DzEpcj0B22uCJ7B0rxE4wdihBsmKo+1vx+U56jb0JuK7q
1390 ixgnTy5w/hOWusPTQBbNZU6sER7m8TAJBgcqhkjOPQQBA4GMADCBiAJCAOAUxGBg
1391 C3JosDJdYUoCdFzCgbkWqD8pyDbHgf9stlvZcPE4O1BIKJTLCRpS8V3ujfK58PDa
1392 2RU6+b0DeoeiIzXsAkIBo9SKeDUcSpoj0gq+KxAxnZxfvuiRs9oa9V2jI/Umi0Vw
1393 jWVim34BmT0Y9hCaOGGbLlfk+syxis7iI6CH8OFnUes=
1394 -----END CERTIFICATE-----`
1395
1396 const clientECDSAKeyPEM = `
1397 -----BEGIN EC PARAMETERS-----
1398 BgUrgQQAIw==
1399 -----END EC PARAMETERS-----
1400 -----BEGIN EC PRIVATE KEY-----
1401 MIHcAgEBBEIBkJN9X4IqZIguiEVKMqeBUP5xtRsEv4HJEtOpOGLELwO53SD78Ew8
1402 k+wLWoqizS3NpQyMtrU8JFdWfj+C57UNkOugBwYFK4EEACOhgYkDgYYABACVjJF1
1403 FMBexFe01MNvja5oHt1vzobhfm6ySD6B5U7ixohLZNz1MLvT/2XMW/TdtWo+PtAd
1404 3kfDdq0Z9kUsjLzYHQFMH3CQRnZIi4+DzEpcj0B22uCJ7B0rxE4wdihBsmKo+1vx
1405 +U56jb0JuK7qixgnTy5w/hOWusPTQBbNZU6sER7m8Q==
1406 -----END EC PRIVATE KEY-----`
1407
1408 func TestClientAuth(t *testing.T) {
1409         var certPath, keyPath, ecdsaCertPath, ecdsaKeyPath string
1410
1411         if *update {
1412                 certPath = tempFile(clientCertificatePEM)
1413                 defer os.Remove(certPath)
1414                 keyPath = tempFile(clientKeyPEM)
1415                 defer os.Remove(keyPath)
1416                 ecdsaCertPath = tempFile(clientECDSACertificatePEM)
1417                 defer os.Remove(ecdsaCertPath)
1418                 ecdsaKeyPath = tempFile(clientECDSAKeyPEM)
1419                 defer os.Remove(ecdsaKeyPath)
1420         }
1421
1422         t.Run("Normal", func(t *testing.T) {
1423                 config := testConfig.Clone()
1424                 config.ClientAuth = RequestClientCert
1425
1426                 test := &serverTest{
1427                         name:    "ClientAuthRequestedNotGiven",
1428                         command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA"},
1429                         config:  config,
1430                 }
1431                 runServerTestTLS12(t, test)
1432                 runServerTestTLS13(t, test)
1433
1434                 config.ClientAuth = RequireAnyClientCert
1435
1436                 test = &serverTest{
1437                         name: "ClientAuthRequestedAndGiven",
1438                         command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA",
1439                                 "-cert", certPath, "-key", keyPath, "-sigalgs", "rsa_pss_rsae_sha256"},
1440                         config:            config,
1441                         expectedPeerCerts: []string{clientCertificatePEM},
1442                 }
1443                 runServerTestTLS12(t, test)
1444                 runServerTestTLS13(t, test)
1445
1446                 test = &serverTest{
1447                         name: "ClientAuthRequestedAndECDSAGiven",
1448                         command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA",
1449                                 "-cert", ecdsaCertPath, "-key", ecdsaKeyPath},
1450                         config:            config,
1451                         expectedPeerCerts: []string{clientECDSACertificatePEM},
1452                 }
1453                 runServerTestTLS12(t, test)
1454                 runServerTestTLS13(t, test)
1455
1456                 test = &serverTest{
1457                         name: "ClientAuthRequestedAndPKCS1v15Given",
1458                         command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA",
1459                                 "-cert", certPath, "-key", keyPath, "-sigalgs", "rsa_pkcs1_sha256"},
1460                         config:            config,
1461                         expectedPeerCerts: []string{clientCertificatePEM},
1462                 }
1463                 runServerTestTLS12(t, test)
1464         })
1465
1466         // Restore the default signature algorithms, disabling RSA-PSS in TLS 1.2,
1467         // and check that handshakes still work.
1468         testSupportedSignatureAlgorithmsTLS12 := supportedSignatureAlgorithmsTLS12
1469         defer func() { supportedSignatureAlgorithmsTLS12 = testSupportedSignatureAlgorithmsTLS12 }()
1470         supportedSignatureAlgorithmsTLS12 = savedSupportedSignatureAlgorithmsTLS12
1471
1472         t.Run("PSSDisabled", func(t *testing.T) {
1473                 config := testConfig.Clone()
1474                 config.ClientAuth = RequireAnyClientCert
1475
1476                 test := &serverTest{
1477                         name: "ClientAuthRequestedAndGiven-PSS-Disabled",
1478                         command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA",
1479                                 "-cert", certPath, "-key", keyPath},
1480                         config:            config,
1481                         expectedPeerCerts: []string{clientCertificatePEM},
1482                 }
1483                 runServerTestTLS12(t, test)
1484                 runServerTestTLS13(t, test)
1485
1486                 test = &serverTest{
1487                         name: "ClientAuthRequestedAndGiven-PSS-Disabled-Required",
1488                         command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA",
1489                                 "-cert", certPath, "-key", keyPath, "-client_sigalgs", "rsa_pss_rsae_sha256"},
1490                         config: config,
1491
1492                         expectHandshakeErrorIncluding: "client didn't provide a certificate",
1493                 }
1494                 runServerTestTLS12(t, test)
1495         })
1496 }
1497
1498 func TestSNIGivenOnFailure(t *testing.T) {
1499         const expectedServerName = "test.testing"
1500
1501         clientHello := &clientHelloMsg{
1502                 vers:               VersionTLS10,
1503                 random:             make([]byte, 32),
1504                 cipherSuites:       []uint16{TLS_RSA_WITH_RC4_128_SHA},
1505                 compressionMethods: []uint8{compressionNone},
1506                 serverName:         expectedServerName,
1507         }
1508
1509         serverConfig := testConfig.Clone()
1510         // Erase the server's cipher suites to ensure the handshake fails.
1511         serverConfig.CipherSuites = nil
1512
1513         c, s := localPipe(t)
1514         go func() {
1515                 cli := Client(c, testConfig)
1516                 cli.vers = clientHello.vers
1517                 cli.writeRecord(recordTypeHandshake, clientHello.marshal())
1518                 c.Close()
1519         }()
1520         conn := Server(s, serverConfig)
1521         ch, err := conn.readClientHello()
1522         hs := serverHandshakeState{
1523                 c:           conn,
1524                 clientHello: ch,
1525         }
1526         if err == nil {
1527                 err = hs.processClientHello()
1528         }
1529         if err == nil {
1530                 err = hs.pickCipherSuite()
1531         }
1532         defer s.Close()
1533
1534         if err == nil {
1535                 t.Error("No error reported from server")
1536         }
1537
1538         cs := hs.c.ConnectionState()
1539         if cs.HandshakeComplete {
1540                 t.Error("Handshake registered as complete")
1541         }
1542
1543         if cs.ServerName != expectedServerName {
1544                 t.Errorf("Expected ServerName of %q, but got %q", expectedServerName, cs.ServerName)
1545         }
1546 }
1547
1548 var getConfigForClientTests = []struct {
1549         setup          func(config *Config)
1550         callback       func(clientHello *ClientHelloInfo) (*Config, error)
1551         errorSubstring string
1552         verify         func(config *Config) error
1553 }{
1554         {
1555                 nil,
1556                 func(clientHello *ClientHelloInfo) (*Config, error) {
1557                         return nil, nil
1558                 },
1559                 "",
1560                 nil,
1561         },
1562         {
1563                 nil,
1564                 func(clientHello *ClientHelloInfo) (*Config, error) {
1565                         return nil, errors.New("should bubble up")
1566                 },
1567                 "should bubble up",
1568                 nil,
1569         },
1570         {
1571                 nil,
1572                 func(clientHello *ClientHelloInfo) (*Config, error) {
1573                         config := testConfig.Clone()
1574                         // Setting a maximum version of TLS 1.1 should cause
1575                         // the handshake to fail, as the client MinVersion is TLS 1.2.
1576                         config.MaxVersion = VersionTLS11
1577                         return config, nil
1578                 },
1579                 "client offered only unsupported versions",
1580                 nil,
1581         },
1582         {
1583                 func(config *Config) {
1584                         for i := range config.SessionTicketKey {
1585                                 config.SessionTicketKey[i] = byte(i)
1586                         }
1587                         config.sessionTicketKeys = nil
1588                 },
1589                 func(clientHello *ClientHelloInfo) (*Config, error) {
1590                         config := testConfig.Clone()
1591                         for i := range config.SessionTicketKey {
1592                                 config.SessionTicketKey[i] = 0
1593                         }
1594                         config.sessionTicketKeys = nil
1595                         return config, nil
1596                 },
1597                 "",
1598                 func(config *Config) error {
1599                         // The value of SessionTicketKey should have been
1600                         // duplicated into the per-connection Config.
1601                         for i := range config.SessionTicketKey {
1602                                 if b := config.SessionTicketKey[i]; b != byte(i) {
1603                                         return fmt.Errorf("SessionTicketKey was not duplicated from original Config: byte %d has value %d", i, b)
1604                                 }
1605                         }
1606                         return nil
1607                 },
1608         },
1609         {
1610                 func(config *Config) {
1611                         var dummyKey [32]byte
1612                         for i := range dummyKey {
1613                                 dummyKey[i] = byte(i)
1614                         }
1615
1616                         config.SetSessionTicketKeys([][32]byte{dummyKey})
1617                 },
1618                 func(clientHello *ClientHelloInfo) (*Config, error) {
1619                         config := testConfig.Clone()
1620                         config.sessionTicketKeys = nil
1621                         return config, nil
1622                 },
1623                 "",
1624                 func(config *Config) error {
1625                         // The session ticket keys should have been duplicated
1626                         // into the per-connection Config.
1627                         if l := len(config.sessionTicketKeys); l != 1 {
1628                                 return fmt.Errorf("got len(sessionTicketKeys) == %d, wanted 1", l)
1629                         }
1630                         return nil
1631                 },
1632         },
1633 }
1634
1635 func TestGetConfigForClient(t *testing.T) {
1636         serverConfig := testConfig.Clone()
1637         clientConfig := testConfig.Clone()
1638         clientConfig.MinVersion = VersionTLS12
1639
1640         for i, test := range getConfigForClientTests {
1641                 if test.setup != nil {
1642                         test.setup(serverConfig)
1643                 }
1644
1645                 var configReturned *Config
1646                 serverConfig.GetConfigForClient = func(clientHello *ClientHelloInfo) (*Config, error) {
1647                         config, err := test.callback(clientHello)
1648                         configReturned = config
1649                         return config, err
1650                 }
1651                 c, s := localPipe(t)
1652                 done := make(chan error)
1653
1654                 go func() {
1655                         defer s.Close()
1656                         done <- Server(s, serverConfig).Handshake()
1657                 }()
1658
1659                 clientErr := Client(c, clientConfig).Handshake()
1660                 c.Close()
1661
1662                 serverErr := <-done
1663
1664                 if len(test.errorSubstring) == 0 {
1665                         if serverErr != nil || clientErr != nil {
1666                                 t.Errorf("test[%d]: expected no error but got serverErr: %q, clientErr: %q", i, serverErr, clientErr)
1667                         }
1668                         if test.verify != nil {
1669                                 if err := test.verify(configReturned); err != nil {
1670                                         t.Errorf("test[%d]: verify returned error: %v", i, err)
1671                                 }
1672                         }
1673                 } else {
1674                         if serverErr == nil {
1675                                 t.Errorf("test[%d]: expected error containing %q but got no error", i, test.errorSubstring)
1676                         } else if !strings.Contains(serverErr.Error(), test.errorSubstring) {
1677                                 t.Errorf("test[%d]: expected error to contain %q but it was %q", i, test.errorSubstring, serverErr)
1678                         }
1679                 }
1680         }
1681 }
1682
1683 func bigFromString(s string) *big.Int {
1684         ret := new(big.Int)
1685         ret.SetString(s, 10)
1686         return ret
1687 }
1688
1689 func fromHex(s string) []byte {
1690         b, _ := hex.DecodeString(s)
1691         return b
1692 }
1693
1694 var testRSACertificate = fromHex("3082024b308201b4a003020102020900e8f09d3fe25beaa6300d06092a864886f70d01010b0500301f310b3009060355040a1302476f3110300e06035504031307476f20526f6f74301e170d3136303130313030303030305a170d3235303130313030303030305a301a310b3009060355040a1302476f310b300906035504031302476f30819f300d06092a864886f70d010101050003818d0030818902818100db467d932e12270648bc062821ab7ec4b6a25dfe1e5245887a3647a5080d92425bc281c0be97799840fb4f6d14fd2b138bc2a52e67d8d4099ed62238b74a0b74732bc234f1d193e596d9747bf3589f6c613cc0b041d4d92b2b2423775b1c3bbd755dce2054cfa163871d1e24c4f31d1a508baab61443ed97a77562f414c852d70203010001a38193308190300e0603551d0f0101ff0404030205a0301d0603551d250416301406082b0601050507030106082b06010505070302300c0603551d130101ff0402300030190603551d0e041204109f91161f43433e49a6de6db680d79f60301b0603551d230414301280104813494d137e1631bba301d5acab6e7b30190603551d1104123010820e6578616d706c652e676f6c616e67300d06092a864886f70d01010b0500038181009d30cc402b5b50a061cbbae55358e1ed8328a9581aa938a495a1ac315a1a84663d43d32dd90bf297dfd320643892243a00bccf9c7db74020015faad3166109a276fd13c3cce10c5ceeb18782f16c04ed73bbb343778d0c1cf10fa1d8408361c94c722b9daedb4606064df4c1b33ec0d1bd42d4dbfe3d1360845c21d33be9fae7")
1695
1696 var testRSACertificateIssuer = fromHex("3082021930820182a003020102020900ca5e4e811a965964300d06092a864886f70d01010b0500301f310b3009060355040a1302476f3110300e06035504031307476f20526f6f74301e170d3136303130313030303030305a170d3235303130313030303030305a301f310b3009060355040a1302476f3110300e06035504031307476f20526f6f7430819f300d06092a864886f70d010101050003818d0030818902818100d667b378bb22f34143b6cd2008236abefaf2852adf3ab05e01329e2c14834f5105df3f3073f99dab5442d45ee5f8f57b0111c8cb682fbb719a86944eebfffef3406206d898b8c1b1887797c9c5006547bb8f00e694b7a063f10839f269f2c34fff7a1f4b21fbcd6bfdfb13ac792d1d11f277b5c5b48600992203059f2a8f8cc50203010001a35d305b300e0603551d0f0101ff040403020204301d0603551d250416301406082b0601050507030106082b06010505070302300f0603551d130101ff040530030101ff30190603551d0e041204104813494d137e1631bba301d5acab6e7b300d06092a864886f70d01010b050003818100c1154b4bab5266221f293766ae4138899bd4c5e36b13cee670ceeaa4cbdf4f6679017e2fe649765af545749fe4249418a56bd38a04b81e261f5ce86b8d5c65413156a50d12449554748c59a30c515bc36a59d38bddf51173e899820b282e40aa78c806526fd184fb6b4cf186ec728edffa585440d2b3225325f7ab580e87dd76")
1697
1698 // testRSAPSSCertificate has signatureAlgorithm rsassaPss, and subjectPublicKeyInfo
1699 // algorithm rsaEncryption, for use with the rsa_pss_rsae_* SignatureSchemes.
1700 // See also TestRSAPSSKeyError. testRSAPSSCertificate is self-signed.
1701 var testRSAPSSCertificate = fromHex("308202583082018da003020102021100f29926eb87ea8a0db9fcc247347c11b0304106092a864886f70d01010a3034a00f300d06096086480165030402010500a11c301a06092a864886f70d010108300d06096086480165030402010500a20302012030123110300e060355040a130741636d6520436f301e170d3137313132333136313631305a170d3138313132333136313631305a30123110300e060355040a130741636d6520436f30819f300d06092a864886f70d010101050003818d0030818902818100db467d932e12270648bc062821ab7ec4b6a25dfe1e5245887a3647a5080d92425bc281c0be97799840fb4f6d14fd2b138bc2a52e67d8d4099ed62238b74a0b74732bc234f1d193e596d9747bf3589f6c613cc0b041d4d92b2b2423775b1c3bbd755dce2054cfa163871d1e24c4f31d1a508baab61443ed97a77562f414c852d70203010001a3463044300e0603551d0f0101ff0404030205a030130603551d25040c300a06082b06010505070301300c0603551d130101ff04023000300f0603551d110408300687047f000001304106092a864886f70d01010a3034a00f300d06096086480165030402010500a11c301a06092a864886f70d010108300d06096086480165030402010500a20302012003818100cdac4ef2ce5f8d79881042707f7cbf1b5a8a00ef19154b40151771006cd41626e5496d56da0c1a139fd84695593cb67f87765e18aa03ea067522dd78d2a589b8c92364e12838ce346c6e067b51f1a7e6f4b37ffab13f1411896679d18e880e0ba09e302ac067efca460288e9538122692297ad8093d4f7dd701424d7700a46a1")
1702
1703 var testECDSACertificate = fromHex("3082020030820162020900b8bf2d47a0d2ebf4300906072a8648ce3d04013045310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c7464301e170d3132313132323135303633325a170d3232313132303135303633325a3045310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c746430819b301006072a8648ce3d020106052b81040023038186000400c4a1edbe98f90b4873367ec316561122f23d53c33b4d213dcd6b75e6f6b0dc9adf26c1bcb287f072327cb3642f1c90bcea6823107efee325c0483a69e0286dd33700ef0462dd0da09c706283d881d36431aa9e9731bd96b068c09b23de76643f1a5c7fe9120e5858b65f70dd9bd8ead5d7f5d5ccb9b69f30665b669a20e227e5bffe3b300906072a8648ce3d040103818c0030818802420188a24febe245c5487d1bacf5ed989dae4770c05e1bb62fbdf1b64db76140d311a2ceee0b7e927eff769dc33b7ea53fcefa10e259ec472d7cacda4e970e15a06fd00242014dfcbe67139c2d050ebd3fa38c25c13313830d9406bbd4377af6ec7ac9862eddd711697f857c56defb31782be4c7780daecbbe9e4e3624317b6a0f399512078f2a")
1704
1705 var testSNICertificate = fromHex("0441883421114c81480804c430820237308201a0a003020102020900e8f09d3fe25beaa6300d06092a864886f70d01010b0500301f310b3009060355040a1302476f3110300e06035504031307476f20526f6f74301e170d3136303130313030303030305a170d3235303130313030303030305a3023310b3009060355040a1302476f311430120603550403130b736e69746573742e636f6d30819f300d06092a864886f70d010101050003818d0030818902818100db467d932e12270648bc062821ab7ec4b6a25dfe1e5245887a3647a5080d92425bc281c0be97799840fb4f6d14fd2b138bc2a52e67d8d4099ed62238b74a0b74732bc234f1d193e596d9747bf3589f6c613cc0b041d4d92b2b2423775b1c3bbd755dce2054cfa163871d1e24c4f31d1a508baab61443ed97a77562f414c852d70203010001a3773075300e0603551d0f0101ff0404030205a0301d0603551d250416301406082b0601050507030106082b06010505070302300c0603551d130101ff0402300030190603551d0e041204109f91161f43433e49a6de6db680d79f60301b0603551d230414301280104813494d137e1631bba301d5acab6e7b300d06092a864886f70d01010b0500038181007beeecff0230dbb2e7a334af65430b7116e09f327c3bbf918107fc9c66cb497493207ae9b4dbb045cb63d605ec1b5dd485bb69124d68fa298dc776699b47632fd6d73cab57042acb26f083c4087459bc5a3bb3ca4d878d7fe31016b7bc9a627438666566e3389bfaeebe6becc9a0093ceed18d0f9ac79d56f3a73f18188988ed")
1706
1707 var testP256Certificate = fromHex("308201693082010ea00302010202105012dc24e1124ade4f3e153326ff27bf300a06082a8648ce3d04030230123110300e060355040a130741636d6520436f301e170d3137303533313232343934375a170d3138303533313232343934375a30123110300e060355040a130741636d6520436f3059301306072a8648ce3d020106082a8648ce3d03010703420004c02c61c9b16283bbcc14956d886d79b358aa614596975f78cece787146abf74c2d5dc578c0992b4f3c631373479ebf3892efe53d21c4f4f1cc9a11c3536b7f75a3463044300e0603551d0f0101ff0404030205a030130603551d25040c300a06082b06010505070301300c0603551d130101ff04023000300f0603551d1104083006820474657374300a06082a8648ce3d0403020349003046022100963712d6226c7b2bef41512d47e1434131aaca3ba585d666c924df71ac0448b3022100f4d05c725064741aef125f243cdbccaa2a5d485927831f221c43023bd5ae471a")
1708
1709 var testRSAPrivateKey = &rsa.PrivateKey{
1710         PublicKey: rsa.PublicKey{
1711                 N: bigFromString("153980389784927331788354528594524332344709972855165340650588877572729725338415474372475094155672066328274535240275856844648695200875763869073572078279316458648124537905600131008790701752441155668003033945258023841165089852359980273279085783159654751552359397986180318708491098942831252291841441726305535546071"),
1712                 E: 65537,
1713         },
1714         D: bigFromString("7746362285745539358014631136245887418412633787074173796862711588221766398229333338511838891484974940633857861775630560092874987828057333663969469797013996401149696897591265769095952887917296740109742927689053276850469671231961384712725169432413343763989564437170644270643461665184965150423819594083121075825"),
1715         Primes: []*big.Int{
1716                 bigFromString("13299275414352936908236095374926261633419699590839189494995965049151460173257838079863316944311313904000258169883815802963543635820059341150014695560313417"),
1717                 bigFromString("11578103692682951732111718237224894755352163854919244905974423810539077224889290605729035287537520656160688625383765857517518932447378594964220731750802463"),
1718         },
1719 }
1720
1721 var testECDSAPrivateKey = &ecdsa.PrivateKey{
1722         PublicKey: ecdsa.PublicKey{
1723                 Curve: elliptic.P521(),
1724                 X:     bigFromString("2636411247892461147287360222306590634450676461695221912739908880441342231985950069527906976759812296359387337367668045707086543273113073382714101597903639351"),
1725                 Y:     bigFromString("3204695818431246682253994090650952614555094516658732116404513121125038617915183037601737180082382202488628239201196033284060130040574800684774115478859677243"),
1726         },
1727         D: bigFromString("5477294338614160138026852784385529180817726002953041720191098180813046231640184669647735805135001309477695746518160084669446643325196003346204701381388769751"),
1728 }
1729
1730 var testP256PrivateKey, _ = x509.ParseECPrivateKey(fromHex("30770201010420012f3b52bc54c36ba3577ad45034e2e8efe1e6999851284cb848725cfe029991a00a06082a8648ce3d030107a14403420004c02c61c9b16283bbcc14956d886d79b358aa614596975f78cece787146abf74c2d5dc578c0992b4f3c631373479ebf3892efe53d21c4f4f1cc9a11c3536b7f75"))
1731
1732 func TestCloseServerConnectionOnIdleClient(t *testing.T) {
1733         clientConn, serverConn := localPipe(t)
1734         server := Server(serverConn, testConfig.Clone())
1735         go func() {
1736                 clientConn.Write([]byte{'0'})
1737                 server.Close()
1738         }()
1739         server.SetReadDeadline(time.Now().Add(time.Minute))
1740         err := server.Handshake()
1741         if err != nil {
1742                 if err, ok := err.(net.Error); ok && err.Timeout() {
1743                         t.Errorf("Expected a closed network connection error but got '%s'", err.Error())
1744                 }
1745         } else {
1746                 t.Errorf("Error expected, but no error returned")
1747         }
1748 }
1749
1750 func TestCloneHash(t *testing.T) {
1751         h1 := crypto.SHA256.New()
1752         h1.Write([]byte("test"))
1753         s1 := h1.Sum(nil)
1754         h2 := cloneHash(h1, crypto.SHA256)
1755         s2 := h2.Sum(nil)
1756         if !bytes.Equal(s1, s2) {
1757                 t.Error("cloned hash generated a different sum")
1758         }
1759 }
1760
1761 func TestKeyTooSmallForRSAPSS(t *testing.T) {
1762         clientConn, serverConn := localPipe(t)
1763         client := Client(clientConn, testConfig)
1764         cert, err := X509KeyPair([]byte(`-----BEGIN CERTIFICATE-----
1765 MIIBcTCCARugAwIBAgIQGjQnkCFlUqaFlt6ixyz/tDANBgkqhkiG9w0BAQsFADAS
1766 MRAwDgYDVQQKEwdBY21lIENvMB4XDTE5MDExODIzMjMyOFoXDTIwMDExODIzMjMy
1767 OFowEjEQMA4GA1UEChMHQWNtZSBDbzBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQDd
1768 ez1rFUDwax2HTxbcnFUP9AhcgEGMHVV2nn4VVEWFJB6I8C/Nkx0XyyQlrmFYBzEQ
1769 nIPhKls4T0hFoLvjJnXpAgMBAAGjTTBLMA4GA1UdDwEB/wQEAwIFoDATBgNVHSUE
1770 DDAKBggrBgEFBQcDATAMBgNVHRMBAf8EAjAAMBYGA1UdEQQPMA2CC2V4YW1wbGUu
1771 Y29tMA0GCSqGSIb3DQEBCwUAA0EAxDuUS+BrrS3c+h+k+fQPOmOScy6yTX9mHw0Q
1772 KbucGamXYEy0URIwOdO0tQ3LHPc1YGvYSPwkDjkjqECs2Vm/AA==
1773 -----END CERTIFICATE-----`), []byte(`-----BEGIN RSA PRIVATE KEY-----
1774 MIIBOgIBAAJBAN17PWsVQPBrHYdPFtycVQ/0CFyAQYwdVXaefhVURYUkHojwL82T
1775 HRfLJCWuYVgHMRCcg+EqWzhPSEWgu+MmdekCAwEAAQJBALjQYNTdXF4CFBbXwUz/
1776 yt9QFDYT9B5WT/12jeGAe653gtYS6OOi/+eAkGmzg1GlRnw6fOfn+HYNFDORST7z
1777 4j0CIQDn2xz9hVWQEu9ee3vecNT3f60huDGTNoRhtqgweQGX0wIhAPSLj1VcRZEz
1778 nKpbtU22+PbIMSJ+e80fmY9LIPx5N4HTAiAthGSimMR9bloz0EY3GyuUEyqoDgMd
1779 hXxjuno2WesoJQIgemilbcALXpxsLmZLgcQ2KSmaVr7jb5ECx9R+hYKTw1sCIG4s
1780 T+E0J8wlH24pgwQHzy7Ko2qLwn1b5PW8ecrlvP1g
1781 -----END RSA PRIVATE KEY-----`))
1782         if err != nil {
1783                 t.Fatal(err)
1784         }
1785
1786         done := make(chan struct{})
1787         go func() {
1788                 config := testConfig.Clone()
1789                 config.Certificates = []Certificate{cert}
1790                 config.MinVersion = VersionTLS13
1791                 server := Server(serverConn, config)
1792                 err := server.Handshake()
1793                 if !strings.Contains(err.Error(), "key size too small for PSS signature") {
1794                         t.Errorf(`expected "key size too small for PSS signature", got %q`, err)
1795                 }
1796                 close(done)
1797         }()
1798         err = client.Handshake()
1799         if !strings.Contains(err.Error(), "handshake failure") {
1800                 t.Errorf(`expected "handshake failure", got %q`, err)
1801         }
1802         <-done
1803
1804         // With RSA-PSS disabled and TLS 1.2, this should work.
1805
1806         testSupportedSignatureAlgorithmsTLS12 := supportedSignatureAlgorithmsTLS12
1807         defer func() { supportedSignatureAlgorithmsTLS12 = testSupportedSignatureAlgorithmsTLS12 }()
1808         supportedSignatureAlgorithmsTLS12 = savedSupportedSignatureAlgorithmsTLS12
1809
1810         serverConfig := testConfig.Clone()
1811         serverConfig.Certificates = []Certificate{cert}
1812         serverConfig.MaxVersion = VersionTLS12
1813         testHandshake(t, testConfig, serverConfig)
1814 }