You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1409 line
48 KiB

  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. package tls
  5. import (
  6. "bytes"
  7. "crypto"
  8. "crypto/ecdsa"
  9. "crypto/elliptic"
  10. "crypto/rsa"
  11. "crypto/x509"
  12. "encoding/hex"
  13. "encoding/pem"
  14. "errors"
  15. "fmt"
  16. "io"
  17. "math/big"
  18. "net"
  19. "os"
  20. "os/exec"
  21. "path/filepath"
  22. "strings"
  23. "testing"
  24. "time"
  25. )
  26. // zeroSource is an io.Reader that returns an unlimited number of zero bytes.
  27. type zeroSource struct{}
  28. func (zeroSource) Read(b []byte) (n int, err error) {
  29. for i := range b {
  30. b[i] = 0
  31. }
  32. return len(b), nil
  33. }
  34. var testConfig *Config
  35. func allCipherSuites() []uint16 {
  36. var ids []uint16
  37. for _, suite := range cipherSuites {
  38. if suite.flags&suiteTLS13 != 0 {
  39. continue
  40. }
  41. ids = append(ids, suite.id)
  42. }
  43. return ids
  44. }
  45. func init() {
  46. testConfig = &Config{
  47. Time: func() time.Time { return time.Unix(0, 0) },
  48. Rand: zeroSource{},
  49. Certificates: make([]Certificate, 2),
  50. InsecureSkipVerify: true,
  51. MinVersion: VersionSSL30,
  52. MaxVersion: VersionTLS12,
  53. CipherSuites: allCipherSuites(),
  54. }
  55. testConfig.Certificates[0].Certificate = [][]byte{testRSACertificate}
  56. testConfig.Certificates[0].PrivateKey = testRSAPrivateKey
  57. testConfig.Certificates[1].Certificate = [][]byte{testSNICertificate}
  58. testConfig.Certificates[1].PrivateKey = testRSAPrivateKey
  59. testConfig.BuildNameToCertificate()
  60. }
  61. func testClientHello(t *testing.T, serverConfig *Config, m handshakeMessage) {
  62. testClientHelloFailure(t, serverConfig, m, "")
  63. }
  64. func testClientHelloFailure(t *testing.T, serverConfig *Config, m handshakeMessage, expectedSubStr string) {
  65. // Create in-memory network connection,
  66. // send message to server. Should return
  67. // expected error.
  68. c, s := net.Pipe()
  69. go func() {
  70. cli := Client(c, testConfig)
  71. if ch, ok := m.(*clientHelloMsg); ok {
  72. cli.vers = ch.vers
  73. }
  74. cli.writeRecord(recordTypeHandshake, m.marshal())
  75. c.Close()
  76. }()
  77. hs := serverHandshakeState{
  78. c: Server(s, serverConfig),
  79. }
  80. _, err := hs.readClientHello()
  81. s.Close()
  82. if len(expectedSubStr) == 0 {
  83. if err != nil && err != io.EOF {
  84. t.Errorf("Got error: %s; expected to succeed", err)
  85. }
  86. } else if err == nil || !strings.Contains(err.Error(), expectedSubStr) {
  87. t.Errorf("Got error: %s; expected to match substring '%s'", err, expectedSubStr)
  88. }
  89. }
  90. func TestSimpleError(t *testing.T) {
  91. testClientHelloFailure(t, testConfig, &serverHelloDoneMsg{}, "unexpected handshake message")
  92. }
  93. var badProtocolVersions = []uint16{0x0000, 0x0005, 0x0100, 0x0105, 0x0200, 0x0205}
  94. func TestRejectBadProtocolVersion(t *testing.T) {
  95. for _, v := range badProtocolVersions {
  96. testClientHelloFailure(t, testConfig, &clientHelloMsg{vers: v}, "unsupported, maximum protocol version")
  97. }
  98. }
  99. func TestNoSuiteOverlap(t *testing.T) {
  100. clientHello := &clientHelloMsg{
  101. vers: VersionTLS10,
  102. cipherSuites: []uint16{0xff00},
  103. compressionMethods: []uint8{compressionNone},
  104. }
  105. testClientHelloFailure(t, testConfig, clientHello, "no cipher suite supported by both client and server")
  106. }
  107. func TestNoCompressionOverlap(t *testing.T) {
  108. clientHello := &clientHelloMsg{
  109. vers: VersionTLS10,
  110. cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
  111. compressionMethods: []uint8{0xff},
  112. }
  113. testClientHelloFailure(t, testConfig, clientHello, "client does not support uncompressed connections")
  114. }
  115. func TestNoRC4ByDefault(t *testing.T) {
  116. clientHello := &clientHelloMsg{
  117. vers: VersionTLS10,
  118. cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
  119. compressionMethods: []uint8{compressionNone},
  120. }
  121. serverConfig := testConfig.Clone()
  122. // Reset the enabled cipher suites to nil in order to test the
  123. // defaults.
  124. serverConfig.CipherSuites = nil
  125. testClientHelloFailure(t, serverConfig, clientHello, "no cipher suite supported by both client and server")
  126. }
  127. func TestRejectSNIWithTrailingDot(t *testing.T) {
  128. testClientHelloFailure(t, testConfig, &clientHelloMsg{vers: VersionTLS12, serverName: "foo.com."}, "unexpected message")
  129. }
  130. func TestDontSelectECDSAWithRSAKey(t *testing.T) {
  131. // Test that, even when both sides support an ECDSA cipher suite, it
  132. // won't be selected if the server's private key doesn't support it.
  133. clientHello := &clientHelloMsg{
  134. vers: VersionTLS10,
  135. cipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA},
  136. compressionMethods: []uint8{compressionNone},
  137. supportedCurves: []CurveID{CurveP256},
  138. supportedPoints: []uint8{pointFormatUncompressed},
  139. }
  140. serverConfig := testConfig.Clone()
  141. serverConfig.CipherSuites = clientHello.cipherSuites
  142. serverConfig.Certificates = make([]Certificate, 1)
  143. serverConfig.Certificates[0].Certificate = [][]byte{testECDSACertificate}
  144. serverConfig.Certificates[0].PrivateKey = testECDSAPrivateKey
  145. serverConfig.BuildNameToCertificate()
  146. // First test that it *does* work when the server's key is ECDSA.
  147. testClientHello(t, serverConfig, clientHello)
  148. // Now test that switching to an RSA key causes the expected error (and
  149. // not an internal error about a signing failure).
  150. serverConfig.Certificates = testConfig.Certificates
  151. testClientHelloFailure(t, serverConfig, clientHello, "no cipher suite supported by both client and server")
  152. }
  153. func TestDontSelectRSAWithECDSAKey(t *testing.T) {
  154. // Test that, even when both sides support an RSA cipher suite, it
  155. // won't be selected if the server's private key doesn't support it.
  156. clientHello := &clientHelloMsg{
  157. vers: VersionTLS10,
  158. cipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA},
  159. compressionMethods: []uint8{compressionNone},
  160. supportedCurves: []CurveID{CurveP256},
  161. supportedPoints: []uint8{pointFormatUncompressed},
  162. }
  163. serverConfig := testConfig.Clone()
  164. serverConfig.CipherSuites = clientHello.cipherSuites
  165. // First test that it *does* work when the server's key is RSA.
  166. testClientHello(t, serverConfig, clientHello)
  167. // Now test that switching to an ECDSA key causes the expected error
  168. // (and not an internal error about a signing failure).
  169. serverConfig.Certificates = make([]Certificate, 1)
  170. serverConfig.Certificates[0].Certificate = [][]byte{testECDSACertificate}
  171. serverConfig.Certificates[0].PrivateKey = testECDSAPrivateKey
  172. serverConfig.BuildNameToCertificate()
  173. testClientHelloFailure(t, serverConfig, clientHello, "no cipher suite supported by both client and server")
  174. }
  175. func TestRenegotiationExtension(t *testing.T) {
  176. clientHello := &clientHelloMsg{
  177. vers: VersionTLS12,
  178. compressionMethods: []uint8{compressionNone},
  179. random: make([]byte, 32),
  180. secureRenegotiationSupported: true,
  181. cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
  182. }
  183. var buf []byte
  184. c, s := net.Pipe()
  185. go func() {
  186. cli := Client(c, testConfig)
  187. cli.vers = clientHello.vers
  188. cli.writeRecord(recordTypeHandshake, clientHello.marshal())
  189. buf = make([]byte, 1024)
  190. n, err := c.Read(buf)
  191. if err != nil {
  192. t.Errorf("Server read returned error: %s", err)
  193. return
  194. }
  195. buf = buf[:n]
  196. c.Close()
  197. }()
  198. Server(s, testConfig).Handshake()
  199. if len(buf) < 5+4 {
  200. t.Fatalf("Server returned short message of length %d", len(buf))
  201. }
  202. // buf contains a TLS record, with a 5 byte record header and a 4 byte
  203. // handshake header. The length of the ServerHello is taken from the
  204. // handshake header.
  205. serverHelloLen := int(buf[6])<<16 | int(buf[7])<<8 | int(buf[8])
  206. var serverHello serverHelloMsg
  207. // unmarshal expects to be given the handshake header, but
  208. // serverHelloLen doesn't include it.
  209. if serverHello.unmarshal(buf[5:9+serverHelloLen]) != alertSuccess {
  210. t.Fatalf("Failed to parse ServerHello")
  211. }
  212. if !serverHello.secureRenegotiationSupported {
  213. t.Errorf("Secure renegotiation extension was not echoed.")
  214. }
  215. }
  216. func TestTLS12OnlyCipherSuites(t *testing.T) {
  217. // Test that a Server doesn't select a TLS 1.2-only cipher suite when
  218. // the client negotiates TLS 1.1.
  219. var zeros [32]byte
  220. clientHello := &clientHelloMsg{
  221. vers: VersionTLS11,
  222. random: zeros[:],
  223. cipherSuites: []uint16{
  224. // The Server, by default, will use the client's
  225. // preference order. So the GCM cipher suite
  226. // will be selected unless it's excluded because
  227. // of the version in this ClientHello.
  228. TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  229. TLS_RSA_WITH_RC4_128_SHA,
  230. },
  231. compressionMethods: []uint8{compressionNone},
  232. supportedCurves: []CurveID{CurveP256, CurveP384, CurveP521},
  233. supportedPoints: []uint8{pointFormatUncompressed},
  234. }
  235. c, s := net.Pipe()
  236. var reply interface{}
  237. var clientErr error
  238. go func() {
  239. cli := Client(c, testConfig)
  240. cli.vers = clientHello.vers
  241. cli.writeRecord(recordTypeHandshake, clientHello.marshal())
  242. reply, clientErr = cli.readHandshake()
  243. c.Close()
  244. }()
  245. config := testConfig.Clone()
  246. config.CipherSuites = clientHello.cipherSuites
  247. Server(s, config).Handshake()
  248. s.Close()
  249. if clientErr != nil {
  250. t.Fatal(clientErr)
  251. }
  252. serverHello, ok := reply.(*serverHelloMsg)
  253. if !ok {
  254. t.Fatalf("didn't get ServerHello message in reply. Got %v\n", reply)
  255. }
  256. if s := serverHello.cipherSuite; s != TLS_RSA_WITH_RC4_128_SHA {
  257. t.Fatalf("bad cipher suite from server: %x", s)
  258. }
  259. }
  260. func TestAlertForwarding(t *testing.T) {
  261. c, s := net.Pipe()
  262. go func() {
  263. Client(c, testConfig).sendAlert(alertUnknownCA)
  264. c.Close()
  265. }()
  266. err := Server(s, testConfig).Handshake()
  267. s.Close()
  268. if e, ok := err.(*net.OpError); !ok || e.Err != error(alertUnknownCA) {
  269. t.Errorf("Got error: %s; expected: %s", err, error(alertUnknownCA))
  270. }
  271. }
  272. func TestClose(t *testing.T) {
  273. c, s := net.Pipe()
  274. go c.Close()
  275. err := Server(s, testConfig).Handshake()
  276. s.Close()
  277. if err != io.EOF {
  278. t.Errorf("Got error: %s; expected: %s", err, io.EOF)
  279. }
  280. }
  281. func testHandshake(clientConfig, serverConfig *Config) (serverState, clientState ConnectionState, err error) {
  282. c, s := net.Pipe()
  283. done := make(chan bool)
  284. go func() {
  285. cli := Client(c, clientConfig)
  286. cli.Handshake()
  287. clientState = cli.ConnectionState()
  288. c.Close()
  289. done <- true
  290. }()
  291. server := Server(s, serverConfig)
  292. err = server.Handshake()
  293. if err == nil {
  294. serverState = server.ConnectionState()
  295. }
  296. s.Close()
  297. <-done
  298. return
  299. }
  300. func TestVersion(t *testing.T) {
  301. serverConfig := &Config{
  302. Certificates: testConfig.Certificates,
  303. MaxVersion: VersionTLS11,
  304. }
  305. clientConfig := &Config{
  306. InsecureSkipVerify: true,
  307. }
  308. state, _, err := testHandshake(clientConfig, serverConfig)
  309. if err != nil {
  310. t.Fatalf("handshake failed: %s", err)
  311. }
  312. if state.Version != VersionTLS11 {
  313. t.Fatalf("Incorrect version %x, should be %x", state.Version, VersionTLS11)
  314. }
  315. }
  316. func TestCipherSuitePreference(t *testing.T) {
  317. serverConfig := &Config{
  318. CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA},
  319. Certificates: testConfig.Certificates,
  320. MaxVersion: VersionTLS11,
  321. }
  322. clientConfig := &Config{
  323. CipherSuites: []uint16{TLS_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_RC4_128_SHA},
  324. InsecureSkipVerify: true,
  325. }
  326. state, _, err := testHandshake(clientConfig, serverConfig)
  327. if err != nil {
  328. t.Fatalf("handshake failed: %s", err)
  329. }
  330. if state.CipherSuite != TLS_RSA_WITH_AES_128_CBC_SHA {
  331. // By default the server should use the client's preference.
  332. t.Fatalf("Client's preference was not used, got %x", state.CipherSuite)
  333. }
  334. serverConfig.PreferServerCipherSuites = true
  335. state, _, err = testHandshake(clientConfig, serverConfig)
  336. if err != nil {
  337. t.Fatalf("handshake failed: %s", err)
  338. }
  339. if state.CipherSuite != TLS_RSA_WITH_RC4_128_SHA {
  340. t.Fatalf("Server's preference was not used, got %x", state.CipherSuite)
  341. }
  342. }
  343. func TestSCTHandshake(t *testing.T) {
  344. expected := [][]byte{[]byte("certificate"), []byte("transparency")}
  345. serverConfig := &Config{
  346. Certificates: []Certificate{{
  347. Certificate: [][]byte{testRSACertificate},
  348. PrivateKey: testRSAPrivateKey,
  349. SignedCertificateTimestamps: expected,
  350. }},
  351. }
  352. clientConfig := &Config{
  353. InsecureSkipVerify: true,
  354. }
  355. _, state, err := testHandshake(clientConfig, serverConfig)
  356. if err != nil {
  357. t.Fatalf("handshake failed: %s", err)
  358. }
  359. actual := state.SignedCertificateTimestamps
  360. if len(actual) != len(expected) {
  361. t.Fatalf("got %d scts, want %d", len(actual), len(expected))
  362. }
  363. for i, sct := range expected {
  364. if !bytes.Equal(sct, actual[i]) {
  365. t.Fatalf("SCT #%d was %x, but expected %x", i, actual[i], sct)
  366. }
  367. }
  368. }
  369. func TestCrossVersionResume(t *testing.T) {
  370. serverConfig := &Config{
  371. CipherSuites: []uint16{TLS_RSA_WITH_AES_128_CBC_SHA},
  372. Certificates: testConfig.Certificates,
  373. }
  374. clientConfig := &Config{
  375. CipherSuites: []uint16{TLS_RSA_WITH_AES_128_CBC_SHA},
  376. InsecureSkipVerify: true,
  377. ClientSessionCache: NewLRUClientSessionCache(1),
  378. ServerName: "servername",
  379. }
  380. // Establish a session at TLS 1.1.
  381. clientConfig.MaxVersion = VersionTLS11
  382. _, _, err := testHandshake(clientConfig, serverConfig)
  383. if err != nil {
  384. t.Fatalf("handshake failed: %s", err)
  385. }
  386. // The client session cache now contains a TLS 1.1 session.
  387. state, _, err := testHandshake(clientConfig, serverConfig)
  388. if err != nil {
  389. t.Fatalf("handshake failed: %s", err)
  390. }
  391. if !state.DidResume {
  392. t.Fatalf("handshake did not resume at the same version")
  393. }
  394. // Test that the server will decline to resume at a lower version.
  395. clientConfig.MaxVersion = VersionTLS10
  396. state, _, err = testHandshake(clientConfig, serverConfig)
  397. if err != nil {
  398. t.Fatalf("handshake failed: %s", err)
  399. }
  400. if state.DidResume {
  401. t.Fatalf("handshake resumed at a lower version")
  402. }
  403. // The client session cache now contains a TLS 1.0 session.
  404. state, _, err = testHandshake(clientConfig, serverConfig)
  405. if err != nil {
  406. t.Fatalf("handshake failed: %s", err)
  407. }
  408. if !state.DidResume {
  409. t.Fatalf("handshake did not resume at the same version")
  410. }
  411. // Test that the server will decline to resume at a higher version.
  412. clientConfig.MaxVersion = VersionTLS11
  413. state, _, err = testHandshake(clientConfig, serverConfig)
  414. if err != nil {
  415. t.Fatalf("handshake failed: %s", err)
  416. }
  417. if state.DidResume {
  418. t.Fatalf("handshake resumed at a higher version")
  419. }
  420. }
  421. // Note: see comment in handshake_test.go for details of how the reference
  422. // tests work.
  423. // serverTest represents a test of the TLS server handshake against a reference
  424. // implementation.
  425. type serverTest struct {
  426. // name is a freeform string identifying the test and the file in which
  427. // the expected results will be stored.
  428. name string
  429. // command, if not empty, contains a series of arguments for the
  430. // command to run for the reference server.
  431. command []string
  432. // expectedPeerCerts contains a list of PEM blocks of expected
  433. // certificates from the client.
  434. expectedPeerCerts []string
  435. // config, if not nil, contains a custom Config to use for this test.
  436. config *Config
  437. // expectHandshakeErrorIncluding, when not empty, contains a string
  438. // that must be a substring of the error resulting from the handshake.
  439. expectHandshakeErrorIncluding string
  440. // validate, if not nil, is a function that will be called with the
  441. // ConnectionState of the resulting connection. It returns false if the
  442. // ConnectionState is unacceptable.
  443. validate func(ConnectionState) error
  444. }
  445. var defaultClientCommand = []string{"openssl", "s_client", "-no_ticket"}
  446. // connFromCommand starts opens a listening socket and starts the reference
  447. // client to connect to it. It returns a recordingConn that wraps the resulting
  448. // connection.
  449. func (test *serverTest) connFromCommand() (conn *recordingConn, child *exec.Cmd, err error) {
  450. l, err := net.ListenTCP("tcp", &net.TCPAddr{
  451. IP: net.IPv4(127, 0, 0, 1),
  452. Port: 0,
  453. })
  454. if err != nil {
  455. return nil, nil, err
  456. }
  457. defer l.Close()
  458. port := l.Addr().(*net.TCPAddr).Port
  459. var command []string
  460. command = append(command, test.command...)
  461. if len(command) == 0 {
  462. command = defaultClientCommand
  463. }
  464. command = append(command, "-connect")
  465. command = append(command, fmt.Sprintf("127.0.0.1:%d", port))
  466. cmd := exec.Command(command[0], command[1:]...)
  467. cmd.Stdin = nil
  468. var output bytes.Buffer
  469. cmd.Stdout = &output
  470. cmd.Stderr = &output
  471. if err := cmd.Start(); err != nil {
  472. return nil, nil, err
  473. }
  474. connChan := make(chan interface{})
  475. go func() {
  476. tcpConn, err := l.Accept()
  477. if err != nil {
  478. connChan <- err
  479. }
  480. connChan <- tcpConn
  481. }()
  482. var tcpConn net.Conn
  483. select {
  484. case connOrError := <-connChan:
  485. if err, ok := connOrError.(error); ok {
  486. return nil, nil, err
  487. }
  488. tcpConn = connOrError.(net.Conn)
  489. case <-time.After(2 * time.Second):
  490. output.WriteTo(os.Stdout)
  491. return nil, nil, errors.New("timed out waiting for connection from child process")
  492. }
  493. record := &recordingConn{
  494. Conn: tcpConn,
  495. }
  496. return record, cmd, nil
  497. }
  498. func (test *serverTest) dataPath() string {
  499. return filepath.Join("testdata", "Server-"+test.name)
  500. }
  501. func (test *serverTest) loadData() (flows [][]byte, err error) {
  502. in, err := os.Open(test.dataPath())
  503. if err != nil {
  504. return nil, err
  505. }
  506. defer in.Close()
  507. return parseTestData(in)
  508. }
  509. func (test *serverTest) run(t *testing.T, write bool) {
  510. checkOpenSSLVersion(t)
  511. var clientConn, serverConn net.Conn
  512. var recordingConn *recordingConn
  513. var childProcess *exec.Cmd
  514. if write {
  515. var err error
  516. recordingConn, childProcess, err = test.connFromCommand()
  517. if err != nil {
  518. t.Fatalf("Failed to start subcommand: %s", err)
  519. }
  520. serverConn = recordingConn
  521. } else {
  522. clientConn, serverConn = net.Pipe()
  523. }
  524. config := test.config
  525. if config == nil {
  526. config = testConfig
  527. }
  528. server := Server(serverConn, config)
  529. connStateChan := make(chan ConnectionState, 1)
  530. go func() {
  531. _, err := server.Write([]byte("hello, world\n"))
  532. if len(test.expectHandshakeErrorIncluding) > 0 {
  533. if err == nil {
  534. t.Errorf("Error expected, but no error returned")
  535. } else if s := err.Error(); !strings.Contains(s, test.expectHandshakeErrorIncluding) {
  536. t.Errorf("Error expected containing '%s' but got '%s'", test.expectHandshakeErrorIncluding, s)
  537. }
  538. } else {
  539. if err != nil {
  540. t.Logf("Error from Server.Write: '%s'", err)
  541. }
  542. }
  543. server.Close()
  544. serverConn.Close()
  545. connStateChan <- server.ConnectionState()
  546. }()
  547. if !write {
  548. flows, err := test.loadData()
  549. if err != nil {
  550. t.Fatalf("%s: failed to load data from %s", test.name, test.dataPath())
  551. }
  552. for i, b := range flows {
  553. if i%2 == 0 {
  554. clientConn.Write(b)
  555. continue
  556. }
  557. bb := make([]byte, len(b))
  558. n, err := io.ReadFull(clientConn, bb)
  559. if err != nil {
  560. 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)
  561. }
  562. if !bytes.Equal(b, bb) {
  563. t.Fatalf("%s #%d: mismatch on read: got:%x want:%x", test.name, i+1, bb, b)
  564. }
  565. }
  566. clientConn.Close()
  567. }
  568. connState := <-connStateChan
  569. peerCerts := connState.PeerCertificates
  570. if len(peerCerts) == len(test.expectedPeerCerts) {
  571. for i, peerCert := range peerCerts {
  572. block, _ := pem.Decode([]byte(test.expectedPeerCerts[i]))
  573. if !bytes.Equal(block.Bytes, peerCert.Raw) {
  574. t.Fatalf("%s: mismatch on peer cert %d", test.name, i+1)
  575. }
  576. }
  577. } else {
  578. t.Fatalf("%s: mismatch on peer list length: %d (wanted) != %d (got)", test.name, len(test.expectedPeerCerts), len(peerCerts))
  579. }
  580. if test.validate != nil {
  581. if err := test.validate(connState); err != nil {
  582. t.Fatalf("validate callback returned error: %s", err)
  583. }
  584. }
  585. if write {
  586. path := test.dataPath()
  587. out, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
  588. if err != nil {
  589. t.Fatalf("Failed to create output file: %s", err)
  590. }
  591. defer out.Close()
  592. recordingConn.Close()
  593. if len(recordingConn.flows) < 3 {
  594. childProcess.Stdout.(*bytes.Buffer).WriteTo(os.Stdout)
  595. if len(test.expectHandshakeErrorIncluding) == 0 {
  596. t.Fatalf("Handshake failed")
  597. }
  598. }
  599. recordingConn.WriteTo(out)
  600. fmt.Printf("Wrote %s\n", path)
  601. childProcess.Wait()
  602. }
  603. }
  604. func runServerTestForVersion(t *testing.T, template *serverTest, prefix, option string) {
  605. setParallel(t)
  606. test := *template
  607. test.name = prefix + test.name
  608. if len(test.command) == 0 {
  609. test.command = defaultClientCommand
  610. }
  611. test.command = append([]string(nil), test.command...)
  612. test.command = append(test.command, option)
  613. test.run(t, *update)
  614. }
  615. func runServerTestSSLv3(t *testing.T, template *serverTest) {
  616. runServerTestForVersion(t, template, "SSLv3-", "-ssl3")
  617. }
  618. func runServerTestTLS10(t *testing.T, template *serverTest) {
  619. runServerTestForVersion(t, template, "TLSv10-", "-tls1")
  620. }
  621. func runServerTestTLS11(t *testing.T, template *serverTest) {
  622. runServerTestForVersion(t, template, "TLSv11-", "-tls1_1")
  623. }
  624. func runServerTestTLS12(t *testing.T, template *serverTest) {
  625. runServerTestForVersion(t, template, "TLSv12-", "-tls1_2")
  626. }
  627. func TestHandshakeServerRSARC4(t *testing.T) {
  628. test := &serverTest{
  629. name: "RSA-RC4",
  630. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "RC4-SHA"},
  631. }
  632. runServerTestSSLv3(t, test)
  633. runServerTestTLS10(t, test)
  634. runServerTestTLS11(t, test)
  635. runServerTestTLS12(t, test)
  636. }
  637. func TestHandshakeServerRSA3DES(t *testing.T) {
  638. test := &serverTest{
  639. name: "RSA-3DES",
  640. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "DES-CBC3-SHA"},
  641. }
  642. runServerTestSSLv3(t, test)
  643. runServerTestTLS10(t, test)
  644. runServerTestTLS12(t, test)
  645. }
  646. func TestHandshakeServerRSAAES(t *testing.T) {
  647. test := &serverTest{
  648. name: "RSA-AES",
  649. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA"},
  650. }
  651. runServerTestSSLv3(t, test)
  652. runServerTestTLS10(t, test)
  653. runServerTestTLS12(t, test)
  654. }
  655. func TestHandshakeServerAESGCM(t *testing.T) {
  656. test := &serverTest{
  657. name: "RSA-AES-GCM",
  658. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-AES128-GCM-SHA256"},
  659. }
  660. runServerTestTLS12(t, test)
  661. }
  662. func TestHandshakeServerAES256GCMSHA384(t *testing.T) {
  663. test := &serverTest{
  664. name: "RSA-AES256-GCM-SHA384",
  665. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-AES256-GCM-SHA384"},
  666. }
  667. runServerTestTLS12(t, test)
  668. }
  669. func TestHandshakeServerECDHEECDSAAES(t *testing.T) {
  670. config := testConfig.Clone()
  671. config.Certificates = make([]Certificate, 1)
  672. config.Certificates[0].Certificate = [][]byte{testECDSACertificate}
  673. config.Certificates[0].PrivateKey = testECDSAPrivateKey
  674. config.BuildNameToCertificate()
  675. test := &serverTest{
  676. name: "ECDHE-ECDSA-AES",
  677. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-ECDSA-AES256-SHA"},
  678. config: config,
  679. }
  680. runServerTestTLS10(t, test)
  681. runServerTestTLS12(t, test)
  682. }
  683. func TestHandshakeServerX25519(t *testing.T) {
  684. config := testConfig.Clone()
  685. config.CurvePreferences = []CurveID{X25519}
  686. test := &serverTest{
  687. name: "X25519-ECDHE-RSA-AES-GCM",
  688. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-AES128-GCM-SHA256"},
  689. config: config,
  690. }
  691. runServerTestTLS12(t, test)
  692. }
  693. func TestHandshakeServerALPN(t *testing.T) {
  694. config := testConfig.Clone()
  695. config.NextProtos = []string{"proto1", "proto2"}
  696. test := &serverTest{
  697. name: "ALPN",
  698. // Note that this needs OpenSSL 1.0.2 because that is the first
  699. // version that supports the -alpn flag.
  700. command: []string{"openssl", "s_client", "-alpn", "proto2,proto1"},
  701. config: config,
  702. validate: func(state ConnectionState) error {
  703. // The server's preferences should override the client.
  704. if state.NegotiatedProtocol != "proto1" {
  705. return fmt.Errorf("Got protocol %q, wanted proto1", state.NegotiatedProtocol)
  706. }
  707. return nil
  708. },
  709. }
  710. runServerTestTLS12(t, test)
  711. }
  712. func TestHandshakeServerALPNNoMatch(t *testing.T) {
  713. config := testConfig.Clone()
  714. config.NextProtos = []string{"proto3"}
  715. test := &serverTest{
  716. name: "ALPN-NoMatch",
  717. // Note that this needs OpenSSL 1.0.2 because that is the first
  718. // version that supports the -alpn flag.
  719. command: []string{"openssl", "s_client", "-alpn", "proto2,proto1"},
  720. config: config,
  721. validate: func(state ConnectionState) error {
  722. // Rather than reject the connection, Go doesn't select
  723. // a protocol when there is no overlap.
  724. if state.NegotiatedProtocol != "" {
  725. return fmt.Errorf("Got protocol %q, wanted ''", state.NegotiatedProtocol)
  726. }
  727. return nil
  728. },
  729. }
  730. runServerTestTLS12(t, test)
  731. }
  732. // TestHandshakeServerSNI involves a client sending an SNI extension of
  733. // "snitest.com", which happens to match the CN of testSNICertificate. The test
  734. // verifies that the server correctly selects that certificate.
  735. func TestHandshakeServerSNI(t *testing.T) {
  736. test := &serverTest{
  737. name: "SNI",
  738. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"},
  739. }
  740. runServerTestTLS12(t, test)
  741. }
  742. // TestHandshakeServerSNICertForName is similar to TestHandshakeServerSNI, but
  743. // tests the dynamic GetCertificate method
  744. func TestHandshakeServerSNIGetCertificate(t *testing.T) {
  745. config := testConfig.Clone()
  746. // Replace the NameToCertificate map with a GetCertificate function
  747. nameToCert := config.NameToCertificate
  748. config.NameToCertificate = nil
  749. config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
  750. cert, _ := nameToCert[clientHello.ServerName]
  751. return cert, nil
  752. }
  753. test := &serverTest{
  754. name: "SNI-GetCertificate",
  755. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"},
  756. config: config,
  757. }
  758. runServerTestTLS12(t, test)
  759. }
  760. // TestHandshakeServerSNICertForNameNotFound is similar to
  761. // TestHandshakeServerSNICertForName, but tests to make sure that when the
  762. // GetCertificate method doesn't return a cert, we fall back to what's in
  763. // the NameToCertificate map.
  764. func TestHandshakeServerSNIGetCertificateNotFound(t *testing.T) {
  765. config := testConfig.Clone()
  766. config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
  767. return nil, nil
  768. }
  769. test := &serverTest{
  770. name: "SNI-GetCertificateNotFound",
  771. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"},
  772. config: config,
  773. }
  774. runServerTestTLS12(t, test)
  775. }
  776. // TestHandshakeServerSNICertForNameError tests to make sure that errors in
  777. // GetCertificate result in a tls alert.
  778. func TestHandshakeServerSNIGetCertificateError(t *testing.T) {
  779. const errMsg = "TestHandshakeServerSNIGetCertificateError error"
  780. serverConfig := testConfig.Clone()
  781. serverConfig.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
  782. return nil, errors.New(errMsg)
  783. }
  784. clientHello := &clientHelloMsg{
  785. vers: VersionTLS10,
  786. cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
  787. compressionMethods: []uint8{compressionNone},
  788. serverName: "test",
  789. }
  790. testClientHelloFailure(t, serverConfig, clientHello, errMsg)
  791. }
  792. // TestHandshakeServerEmptyCertificates tests that GetCertificates is called in
  793. // the case that Certificates is empty, even without SNI.
  794. func TestHandshakeServerEmptyCertificates(t *testing.T) {
  795. const errMsg = "TestHandshakeServerEmptyCertificates error"
  796. serverConfig := testConfig.Clone()
  797. serverConfig.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
  798. return nil, errors.New(errMsg)
  799. }
  800. serverConfig.Certificates = nil
  801. clientHello := &clientHelloMsg{
  802. vers: VersionTLS10,
  803. cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
  804. compressionMethods: []uint8{compressionNone},
  805. }
  806. testClientHelloFailure(t, serverConfig, clientHello, errMsg)
  807. // With an empty Certificates and a nil GetCertificate, the server
  808. // should always return a “no certificates” error.
  809. serverConfig.GetCertificate = nil
  810. clientHello = &clientHelloMsg{
  811. vers: VersionTLS10,
  812. cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
  813. compressionMethods: []uint8{compressionNone},
  814. }
  815. testClientHelloFailure(t, serverConfig, clientHello, "no certificates")
  816. }
  817. // TestCipherSuiteCertPreference ensures that we select an RSA ciphersuite with
  818. // an RSA certificate and an ECDSA ciphersuite with an ECDSA certificate.
  819. func TestCipherSuiteCertPreferenceECDSA(t *testing.T) {
  820. config := testConfig.Clone()
  821. config.CipherSuites = []uint16{TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA}
  822. config.PreferServerCipherSuites = true
  823. test := &serverTest{
  824. name: "CipherSuiteCertPreferenceRSA",
  825. config: config,
  826. }
  827. runServerTestTLS12(t, test)
  828. config = testConfig.Clone()
  829. config.CipherSuites = []uint16{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA}
  830. config.Certificates = []Certificate{
  831. {
  832. Certificate: [][]byte{testECDSACertificate},
  833. PrivateKey: testECDSAPrivateKey,
  834. },
  835. }
  836. config.BuildNameToCertificate()
  837. config.PreferServerCipherSuites = true
  838. test = &serverTest{
  839. name: "CipherSuiteCertPreferenceECDSA",
  840. config: config,
  841. }
  842. runServerTestTLS12(t, test)
  843. }
  844. func TestResumption(t *testing.T) {
  845. sessionFilePath := tempFile("")
  846. defer os.Remove(sessionFilePath)
  847. test := &serverTest{
  848. name: "IssueTicket",
  849. command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-sess_out", sessionFilePath},
  850. }
  851. runServerTestTLS12(t, test)
  852. test = &serverTest{
  853. name: "Resume",
  854. command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-sess_in", sessionFilePath},
  855. }
  856. runServerTestTLS12(t, test)
  857. }
  858. func TestResumptionDisabled(t *testing.T) {
  859. sessionFilePath := tempFile("")
  860. defer os.Remove(sessionFilePath)
  861. config := testConfig.Clone()
  862. test := &serverTest{
  863. name: "IssueTicketPreDisable",
  864. command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-sess_out", sessionFilePath},
  865. config: config,
  866. }
  867. runServerTestTLS12(t, test)
  868. config.SessionTicketsDisabled = true
  869. test = &serverTest{
  870. name: "ResumeDisabled",
  871. command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-sess_in", sessionFilePath},
  872. config: config,
  873. }
  874. runServerTestTLS12(t, test)
  875. // One needs to manually confirm that the handshake in the golden data
  876. // file for ResumeDisabled does not include a resumption handshake.
  877. }
  878. func TestFallbackSCSV(t *testing.T) {
  879. serverConfig := Config{
  880. Certificates: testConfig.Certificates,
  881. }
  882. test := &serverTest{
  883. name: "FallbackSCSV",
  884. config: &serverConfig,
  885. // OpenSSL 1.0.1j is needed for the -fallback_scsv option.
  886. command: []string{"openssl", "s_client", "-fallback_scsv"},
  887. expectHandshakeErrorIncluding: "inappropriate protocol fallback",
  888. }
  889. runServerTestTLS11(t, test)
  890. }
  891. func benchmarkHandshakeServer(b *testing.B, cipherSuite uint16, curve CurveID, cert []byte, key crypto.PrivateKey) {
  892. config := testConfig.Clone()
  893. config.CipherSuites = []uint16{cipherSuite}
  894. config.CurvePreferences = []CurveID{curve}
  895. config.Certificates = make([]Certificate, 1)
  896. config.Certificates[0].Certificate = [][]byte{cert}
  897. config.Certificates[0].PrivateKey = key
  898. config.BuildNameToCertificate()
  899. clientConn, serverConn := net.Pipe()
  900. serverConn = &recordingConn{Conn: serverConn}
  901. go func() {
  902. client := Client(clientConn, testConfig)
  903. client.Handshake()
  904. }()
  905. server := Server(serverConn, config)
  906. if err := server.Handshake(); err != nil {
  907. b.Fatalf("handshake failed: %v", err)
  908. }
  909. serverConn.Close()
  910. flows := serverConn.(*recordingConn).flows
  911. feeder := make(chan struct{})
  912. clientConn, serverConn = net.Pipe()
  913. go func() {
  914. for range feeder {
  915. for i, f := range flows {
  916. if i%2 == 0 {
  917. clientConn.Write(f)
  918. continue
  919. }
  920. ff := make([]byte, len(f))
  921. n, err := io.ReadFull(clientConn, ff)
  922. if err != nil {
  923. b.Fatalf("#%d: %s\nRead %d, wanted %d, got %x, wanted %x\n", i+1, err, n, len(ff), ff[:n], f)
  924. }
  925. if !bytes.Equal(f, ff) {
  926. b.Fatalf("#%d: mismatch on read: got:%x want:%x", i+1, ff, f)
  927. }
  928. }
  929. }
  930. }()
  931. b.ResetTimer()
  932. for i := 0; i < b.N; i++ {
  933. feeder <- struct{}{}
  934. server := Server(serverConn, config)
  935. if err := server.Handshake(); err != nil {
  936. b.Fatalf("handshake failed: %v", err)
  937. }
  938. }
  939. close(feeder)
  940. }
  941. func BenchmarkHandshakeServer(b *testing.B) {
  942. b.Run("RSA", func(b *testing.B) {
  943. benchmarkHandshakeServer(b, TLS_RSA_WITH_AES_128_GCM_SHA256,
  944. 0, testRSACertificate, testRSAPrivateKey)
  945. })
  946. b.Run("ECDHE-P256-RSA", func(b *testing.B) {
  947. benchmarkHandshakeServer(b, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
  948. CurveP256, testRSACertificate, testRSAPrivateKey)
  949. })
  950. b.Run("ECDHE-P256-ECDSA-P256", func(b *testing.B) {
  951. benchmarkHandshakeServer(b, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  952. CurveP256, testP256Certificate, testP256PrivateKey)
  953. })
  954. b.Run("ECDHE-X25519-ECDSA-P256", func(b *testing.B) {
  955. benchmarkHandshakeServer(b, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  956. X25519, testP256Certificate, testP256PrivateKey)
  957. })
  958. b.Run("ECDHE-P521-ECDSA-P521", func(b *testing.B) {
  959. if testECDSAPrivateKey.PublicKey.Curve != elliptic.P521() {
  960. b.Fatal("test ECDSA key doesn't use curve P-521")
  961. }
  962. benchmarkHandshakeServer(b, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  963. CurveP521, testECDSACertificate, testECDSAPrivateKey)
  964. })
  965. }
  966. // clientCertificatePEM and clientKeyPEM were generated with generate_cert.go
  967. // Thus, they have no ExtKeyUsage fields and trigger an error when verification
  968. // is turned on.
  969. const clientCertificatePEM = `
  970. -----BEGIN CERTIFICATE-----
  971. MIIB7zCCAVigAwIBAgIQXBnBiWWDVW/cC8m5k5/pvDANBgkqhkiG9w0BAQsFADAS
  972. MRAwDgYDVQQKEwdBY21lIENvMB4XDTE2MDgxNzIxNTIzMVoXDTE3MDgxNzIxNTIz
  973. MVowEjEQMA4GA1UEChMHQWNtZSBDbzCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkC
  974. gYEAum+qhr3Pv5/y71yUYHhv6BPy0ZZvzdkybiI3zkH5yl0prOEn2mGi7oHLEMff
  975. NFiVhuk9GeZcJ3NgyI14AvQdpJgJoxlwaTwlYmYqqyIjxXuFOE8uCXMyp70+m63K
  976. hAfmDzr/d8WdQYUAirab7rCkPy1MTOZCPrtRyN1IVPQMjkcCAwEAAaNGMEQwDgYD
  977. VR0PAQH/BAQDAgWgMBMGA1UdJQQMMAoGCCsGAQUFBwMBMAwGA1UdEwEB/wQCMAAw
  978. DwYDVR0RBAgwBocEfwAAATANBgkqhkiG9w0BAQsFAAOBgQBGq0Si+yhU+Fpn+GKU
  979. 8ZqyGJ7ysd4dfm92lam6512oFmyc9wnTN+RLKzZ8Aa1B0jLYw9KT+RBrjpW5LBeK
  980. o0RIvFkTgxYEiKSBXCUNmAysEbEoVr4dzWFihAm/1oDGRY2CLLTYg5vbySK3KhIR
  981. e/oCO8HJ/+rJnahJ05XX1Q7lNQ==
  982. -----END CERTIFICATE-----`
  983. const clientKeyPEM = `
  984. -----BEGIN RSA PRIVATE KEY-----
  985. MIICXQIBAAKBgQC6b6qGvc+/n/LvXJRgeG/oE/LRlm/N2TJuIjfOQfnKXSms4Sfa
  986. YaLugcsQx980WJWG6T0Z5lwnc2DIjXgC9B2kmAmjGXBpPCViZiqrIiPFe4U4Ty4J
  987. czKnvT6brcqEB+YPOv93xZ1BhQCKtpvusKQ/LUxM5kI+u1HI3UhU9AyORwIDAQAB
  988. AoGAEJZ03q4uuMb7b26WSQsOMeDsftdatT747LGgs3pNRkMJvTb/O7/qJjxoG+Mc
  989. qeSj0TAZXp+PXXc3ikCECAc+R8rVMfWdmp903XgO/qYtmZGCorxAHEmR80SrfMXv
  990. PJnznLQWc8U9nphQErR+tTESg7xWEzmFcPKwnZd1xg8ERYkCQQDTGtrFczlB2b/Z
  991. 9TjNMqUlMnTLIk/a/rPE2fLLmAYhK5sHnJdvDURaH2mF4nso0EGtENnTsh6LATnY
  992. dkrxXGm9AkEA4hXHG2q3MnhgK1Z5hjv+Fnqd+8bcbII9WW4flFs15EKoMgS1w/PJ
  993. zbsySaSy5IVS8XeShmT9+3lrleed4sy+UwJBAJOOAbxhfXP5r4+5R6ql66jES75w
  994. jUCVJzJA5ORJrn8g64u2eGK28z/LFQbv9wXgCwfc72R468BdawFSLa/m2EECQGbZ
  995. rWiFla26IVXV0xcD98VWJsTBZMlgPnSOqoMdM1kSEd4fUmlAYI/dFzV1XYSkOmVr
  996. FhdZnklmpVDeu27P4c0CQQCuCOup0FlJSBpWY1TTfun/KMBkBatMz0VMA3d7FKIU
  997. csPezl677Yjo8u1r/KzeI6zLg87Z8E6r6ZWNc9wBSZK6
  998. -----END RSA PRIVATE KEY-----`
  999. const clientECDSACertificatePEM = `
  1000. -----BEGIN CERTIFICATE-----
  1001. MIIB/DCCAV4CCQCaMIRsJjXZFzAJBgcqhkjOPQQBMEUxCzAJBgNVBAYTAkFVMRMw
  1002. EQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0
  1003. eSBMdGQwHhcNMTIxMTE0MTMyNTUzWhcNMjIxMTEyMTMyNTUzWjBBMQswCQYDVQQG
  1004. EwJBVTEMMAoGA1UECBMDTlNXMRAwDgYDVQQHEwdQeXJtb250MRIwEAYDVQQDEwlK
  1005. b2VsIFNpbmcwgZswEAYHKoZIzj0CAQYFK4EEACMDgYYABACVjJF1FMBexFe01MNv
  1006. ja5oHt1vzobhfm6ySD6B5U7ixohLZNz1MLvT/2XMW/TdtWo+PtAd3kfDdq0Z9kUs
  1007. jLzYHQFMH3CQRnZIi4+DzEpcj0B22uCJ7B0rxE4wdihBsmKo+1vx+U56jb0JuK7q
  1008. ixgnTy5w/hOWusPTQBbNZU6sER7m8TAJBgcqhkjOPQQBA4GMADCBiAJCAOAUxGBg
  1009. C3JosDJdYUoCdFzCgbkWqD8pyDbHgf9stlvZcPE4O1BIKJTLCRpS8V3ujfK58PDa
  1010. 2RU6+b0DeoeiIzXsAkIBo9SKeDUcSpoj0gq+KxAxnZxfvuiRs9oa9V2jI/Umi0Vw
  1011. jWVim34BmT0Y9hCaOGGbLlfk+syxis7iI6CH8OFnUes=
  1012. -----END CERTIFICATE-----`
  1013. const clientECDSAKeyPEM = `
  1014. -----BEGIN EC PARAMETERS-----
  1015. BgUrgQQAIw==
  1016. -----END EC PARAMETERS-----
  1017. -----BEGIN EC PRIVATE KEY-----
  1018. MIHcAgEBBEIBkJN9X4IqZIguiEVKMqeBUP5xtRsEv4HJEtOpOGLELwO53SD78Ew8
  1019. k+wLWoqizS3NpQyMtrU8JFdWfj+C57UNkOugBwYFK4EEACOhgYkDgYYABACVjJF1
  1020. FMBexFe01MNvja5oHt1vzobhfm6ySD6B5U7ixohLZNz1MLvT/2XMW/TdtWo+PtAd
  1021. 3kfDdq0Z9kUsjLzYHQFMH3CQRnZIi4+DzEpcj0B22uCJ7B0rxE4wdihBsmKo+1vx
  1022. +U56jb0JuK7qixgnTy5w/hOWusPTQBbNZU6sER7m8Q==
  1023. -----END EC PRIVATE KEY-----`
  1024. func TestClientAuth(t *testing.T) {
  1025. setParallel(t)
  1026. var certPath, keyPath, ecdsaCertPath, ecdsaKeyPath string
  1027. if *update {
  1028. certPath = tempFile(clientCertificatePEM)
  1029. defer os.Remove(certPath)
  1030. keyPath = tempFile(clientKeyPEM)
  1031. defer os.Remove(keyPath)
  1032. ecdsaCertPath = tempFile(clientECDSACertificatePEM)
  1033. defer os.Remove(ecdsaCertPath)
  1034. ecdsaKeyPath = tempFile(clientECDSAKeyPEM)
  1035. defer os.Remove(ecdsaKeyPath)
  1036. }
  1037. config := testConfig.Clone()
  1038. config.ClientAuth = RequestClientCert
  1039. test := &serverTest{
  1040. name: "ClientAuthRequestedNotGiven",
  1041. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA"},
  1042. config: config,
  1043. }
  1044. runServerTestTLS12(t, test)
  1045. test = &serverTest{
  1046. name: "ClientAuthRequestedAndGiven",
  1047. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-cert", certPath, "-key", keyPath},
  1048. config: config,
  1049. expectedPeerCerts: []string{clientCertificatePEM},
  1050. }
  1051. runServerTestTLS12(t, test)
  1052. test = &serverTest{
  1053. name: "ClientAuthRequestedAndECDSAGiven",
  1054. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-cert", ecdsaCertPath, "-key", ecdsaKeyPath},
  1055. config: config,
  1056. expectedPeerCerts: []string{clientECDSACertificatePEM},
  1057. }
  1058. runServerTestTLS12(t, test)
  1059. }
  1060. func TestSNIGivenOnFailure(t *testing.T) {
  1061. const expectedServerName = "test.testing"
  1062. clientHello := &clientHelloMsg{
  1063. vers: VersionTLS10,
  1064. cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
  1065. compressionMethods: []uint8{compressionNone},
  1066. serverName: expectedServerName,
  1067. }
  1068. serverConfig := testConfig.Clone()
  1069. // Erase the server's cipher suites to ensure the handshake fails.
  1070. serverConfig.CipherSuites = nil
  1071. c, s := net.Pipe()
  1072. go func() {
  1073. cli := Client(c, testConfig)
  1074. cli.vers = clientHello.vers
  1075. cli.writeRecord(recordTypeHandshake, clientHello.marshal())
  1076. c.Close()
  1077. }()
  1078. hs := serverHandshakeState{
  1079. c: Server(s, serverConfig),
  1080. }
  1081. _, err := hs.readClientHello()
  1082. defer s.Close()
  1083. if err == nil {
  1084. t.Error("No error reported from server")
  1085. }
  1086. cs := hs.c.ConnectionState()
  1087. if cs.HandshakeComplete {
  1088. t.Error("Handshake registered as complete")
  1089. }
  1090. if cs.ServerName != expectedServerName {
  1091. t.Errorf("Expected ServerName of %q, but got %q", expectedServerName, cs.ServerName)
  1092. }
  1093. }
  1094. var getConfigForClientTests = []struct {
  1095. setup func(config *Config)
  1096. callback func(clientHello *ClientHelloInfo) (*Config, error)
  1097. errorSubstring string
  1098. verify func(config *Config) error
  1099. }{
  1100. {
  1101. nil,
  1102. func(clientHello *ClientHelloInfo) (*Config, error) {
  1103. return nil, nil
  1104. },
  1105. "",
  1106. nil,
  1107. },
  1108. {
  1109. nil,
  1110. func(clientHello *ClientHelloInfo) (*Config, error) {
  1111. return nil, errors.New("should bubble up")
  1112. },
  1113. "should bubble up",
  1114. nil,
  1115. },
  1116. {
  1117. nil,
  1118. func(clientHello *ClientHelloInfo) (*Config, error) {
  1119. config := testConfig.Clone()
  1120. // Setting a maximum version of TLS 1.1 should cause
  1121. // the handshake to fail.
  1122. config.MaxVersion = VersionTLS11
  1123. return config, nil
  1124. },
  1125. "protocol version not supported",
  1126. nil,
  1127. },
  1128. {
  1129. func(config *Config) {
  1130. for i := range config.SessionTicketKey {
  1131. config.SessionTicketKey[i] = byte(i)
  1132. }
  1133. config.sessionTicketKeys = nil
  1134. },
  1135. func(clientHello *ClientHelloInfo) (*Config, error) {
  1136. config := testConfig.Clone()
  1137. for i := range config.SessionTicketKey {
  1138. config.SessionTicketKey[i] = 0
  1139. }
  1140. config.sessionTicketKeys = nil
  1141. return config, nil
  1142. },
  1143. "",
  1144. func(config *Config) error {
  1145. // The value of SessionTicketKey should have been
  1146. // duplicated into the per-connection Config.
  1147. for i := range config.SessionTicketKey {
  1148. if b := config.SessionTicketKey[i]; b != byte(i) {
  1149. return fmt.Errorf("SessionTicketKey was not duplicated from original Config: byte %d has value %d", i, b)
  1150. }
  1151. }
  1152. return nil
  1153. },
  1154. },
  1155. {
  1156. func(config *Config) {
  1157. var dummyKey [32]byte
  1158. for i := range dummyKey {
  1159. dummyKey[i] = byte(i)
  1160. }
  1161. config.SetSessionTicketKeys([][32]byte{dummyKey})
  1162. },
  1163. func(clientHello *ClientHelloInfo) (*Config, error) {
  1164. config := testConfig.Clone()
  1165. config.sessionTicketKeys = nil
  1166. return config, nil
  1167. },
  1168. "",
  1169. func(config *Config) error {
  1170. // The session ticket keys should have been duplicated
  1171. // into the per-connection Config.
  1172. if l := len(config.sessionTicketKeys); l != 1 {
  1173. return fmt.Errorf("got len(sessionTicketKeys) == %d, wanted 1", l)
  1174. }
  1175. return nil
  1176. },
  1177. },
  1178. }
  1179. func TestGetConfigForClient(t *testing.T) {
  1180. serverConfig := testConfig.Clone()
  1181. clientConfig := testConfig.Clone()
  1182. clientConfig.MinVersion = VersionTLS12
  1183. for i, test := range getConfigForClientTests {
  1184. if test.setup != nil {
  1185. test.setup(serverConfig)
  1186. }
  1187. var configReturned *Config
  1188. serverConfig.GetConfigForClient = func(clientHello *ClientHelloInfo) (*Config, error) {
  1189. config, err := test.callback(clientHello)
  1190. configReturned = config
  1191. return config, err
  1192. }
  1193. c, s := net.Pipe()
  1194. done := make(chan error)
  1195. go func() {
  1196. defer s.Close()
  1197. done <- Server(s, serverConfig).Handshake()
  1198. }()
  1199. clientErr := Client(c, clientConfig).Handshake()
  1200. c.Close()
  1201. serverErr := <-done
  1202. if len(test.errorSubstring) == 0 {
  1203. if serverErr != nil || clientErr != nil {
  1204. t.Errorf("test[%d]: expected no error but got serverErr: %q, clientErr: %q", i, serverErr, clientErr)
  1205. }
  1206. if test.verify != nil {
  1207. if err := test.verify(configReturned); err != nil {
  1208. t.Errorf("test[%d]: verify returned error: %v", i, err)
  1209. }
  1210. }
  1211. } else {
  1212. if serverErr == nil {
  1213. t.Errorf("test[%d]: expected error containing %q but got no error", i, test.errorSubstring)
  1214. } else if !strings.Contains(serverErr.Error(), test.errorSubstring) {
  1215. t.Errorf("test[%d]: expected error to contain %q but it was %q", i, test.errorSubstring, serverErr)
  1216. }
  1217. }
  1218. }
  1219. }
  1220. func bigFromString(s string) *big.Int {
  1221. ret := new(big.Int)
  1222. ret.SetString(s, 10)
  1223. return ret
  1224. }
  1225. func fromHex(s string) []byte {
  1226. b, _ := hex.DecodeString(s)
  1227. return b
  1228. }
  1229. var testRSACertificate = fromHex("3082024b308201b4a003020102020900e8f09d3fe25beaa6300d06092a864886f70d01010b0500301f310b3009060355040a1302476f3110300e06035504031307476f20526f6f74301e170d3136303130313030303030305a170d3235303130313030303030305a301a310b3009060355040a1302476f310b300906035504031302476f30819f300d06092a864886f70d010101050003818d0030818902818100db467d932e12270648bc062821ab7ec4b6a25dfe1e5245887a3647a5080d92425bc281c0be97799840fb4f6d14fd2b138bc2a52e67d8d4099ed62238b74a0b74732bc234f1d193e596d9747bf3589f6c613cc0b041d4d92b2b2423775b1c3bbd755dce2054cfa163871d1e24c4f31d1a508baab61443ed97a77562f414c852d70203010001a38193308190300e0603551d0f0101ff0404030205a0301d0603551d250416301406082b0601050507030106082b06010505070302300c0603551d130101ff0402300030190603551d0e041204109f91161f43433e49a6de6db680d79f60301b0603551d230414301280104813494d137e1631bba301d5acab6e7b30190603551d1104123010820e6578616d706c652e676f6c616e67300d06092a864886f70d01010b0500038181009d30cc402b5b50a061cbbae55358e1ed8328a9581aa938a495a1ac315a1a84663d43d32dd90bf297dfd320643892243a00bccf9c7db74020015faad3166109a276fd13c3cce10c5ceeb18782f16c04ed73bbb343778d0c1cf10fa1d8408361c94c722b9daedb4606064df4c1b33ec0d1bd42d4dbfe3d1360845c21d33be9fae7")
  1230. var testRSACertificateIssuer = fromHex("3082021930820182a003020102020900ca5e4e811a965964300d06092a864886f70d01010b0500301f310b3009060355040a1302476f3110300e06035504031307476f20526f6f74301e170d3136303130313030303030305a170d3235303130313030303030305a301f310b3009060355040a1302476f3110300e06035504031307476f20526f6f7430819f300d06092a864886f70d010101050003818d0030818902818100d667b378bb22f34143b6cd2008236abefaf2852adf3ab05e01329e2c14834f5105df3f3073f99dab5442d45ee5f8f57b0111c8cb682fbb719a86944eebfffef3406206d898b8c1b1887797c9c5006547bb8f00e694b7a063f10839f269f2c34fff7a1f4b21fbcd6bfdfb13ac792d1d11f277b5c5b48600992203059f2a8f8cc50203010001a35d305b300e0603551d0f0101ff040403020204301d0603551d250416301406082b0601050507030106082b06010505070302300f0603551d130101ff040530030101ff30190603551d0e041204104813494d137e1631bba301d5acab6e7b300d06092a864886f70d01010b050003818100c1154b4bab5266221f293766ae4138899bd4c5e36b13cee670ceeaa4cbdf4f6679017e2fe649765af545749fe4249418a56bd38a04b81e261f5ce86b8d5c65413156a50d12449554748c59a30c515bc36a59d38bddf51173e899820b282e40aa78c806526fd184fb6b4cf186ec728edffa585440d2b3225325f7ab580e87dd76")
  1231. var testECDSACertificate = fromHex("3082020030820162020900b8bf2d47a0d2ebf4300906072a8648ce3d04013045310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c7464301e170d3132313132323135303633325a170d3232313132303135303633325a3045310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c746430819b301006072a8648ce3d020106052b81040023038186000400c4a1edbe98f90b4873367ec316561122f23d53c33b4d213dcd6b75e6f6b0dc9adf26c1bcb287f072327cb3642f1c90bcea6823107efee325c0483a69e0286dd33700ef0462dd0da09c706283d881d36431aa9e9731bd96b068c09b23de76643f1a5c7fe9120e5858b65f70dd9bd8ead5d7f5d5ccb9b69f30665b669a20e227e5bffe3b300906072a8648ce3d040103818c0030818802420188a24febe245c5487d1bacf5ed989dae4770c05e1bb62fbdf1b64db76140d311a2ceee0b7e927eff769dc33b7ea53fcefa10e259ec472d7cacda4e970e15a06fd00242014dfcbe67139c2d050ebd3fa38c25c13313830d9406bbd4377af6ec7ac9862eddd711697f857c56defb31782be4c7780daecbbe9e4e3624317b6a0f399512078f2a")
  1232. var testSNICertificate = fromHex("0441883421114c81480804c430820237308201a0a003020102020900e8f09d3fe25beaa6300d06092a864886f70d01010b0500301f310b3009060355040a1302476f3110300e06035504031307476f20526f6f74301e170d3136303130313030303030305a170d3235303130313030303030305a3023310b3009060355040a1302476f311430120603550403130b736e69746573742e636f6d30819f300d06092a864886f70d010101050003818d0030818902818100db467d932e12270648bc062821ab7ec4b6a25dfe1e5245887a3647a5080d92425bc281c0be97799840fb4f6d14fd2b138bc2a52e67d8d4099ed62238b74a0b74732bc234f1d193e596d9747bf3589f6c613cc0b041d4d92b2b2423775b1c3bbd755dce2054cfa163871d1e24c4f31d1a508baab61443ed97a77562f414c852d70203010001a3773075300e0603551d0f0101ff0404030205a0301d0603551d250416301406082b0601050507030106082b06010505070302300c0603551d130101ff0402300030190603551d0e041204109f91161f43433e49a6de6db680d79f60301b0603551d230414301280104813494d137e1631bba301d5acab6e7b300d06092a864886f70d01010b0500038181007beeecff0230dbb2e7a334af65430b7116e09f327c3bbf918107fc9c66cb497493207ae9b4dbb045cb63d605ec1b5dd485bb69124d68fa298dc776699b47632fd6d73cab57042acb26f083c4087459bc5a3bb3ca4d878d7fe31016b7bc9a627438666566e3389bfaeebe6becc9a0093ceed18d0f9ac79d56f3a73f18188988ed")
  1233. var testP256Certificate = fromHex("308201693082010ea00302010202105012dc24e1124ade4f3e153326ff27bf300a06082a8648ce3d04030230123110300e060355040a130741636d6520436f301e170d3137303533313232343934375a170d3138303533313232343934375a30123110300e060355040a130741636d6520436f3059301306072a8648ce3d020106082a8648ce3d03010703420004c02c61c9b16283bbcc14956d886d79b358aa614596975f78cece787146abf74c2d5dc578c0992b4f3c631373479ebf3892efe53d21c4f4f1cc9a11c3536b7f75a3463044300e0603551d0f0101ff0404030205a030130603551d25040c300a06082b06010505070301300c0603551d130101ff04023000300f0603551d1104083006820474657374300a06082a8648ce3d0403020349003046022100963712d6226c7b2bef41512d47e1434131aaca3ba585d666c924df71ac0448b3022100f4d05c725064741aef125f243cdbccaa2a5d485927831f221c43023bd5ae471a")
  1234. var testRSAPrivateKey = &rsa.PrivateKey{
  1235. PublicKey: rsa.PublicKey{
  1236. N: bigFromString("153980389784927331788354528594524332344709972855165340650588877572729725338415474372475094155672066328274535240275856844648695200875763869073572078279316458648124537905600131008790701752441155668003033945258023841165089852359980273279085783159654751552359397986180318708491098942831252291841441726305535546071"),
  1237. E: 65537,
  1238. },
  1239. D: bigFromString("7746362285745539358014631136245887418412633787074173796862711588221766398229333338511838891484974940633857861775630560092874987828057333663969469797013996401149696897591265769095952887917296740109742927689053276850469671231961384712725169432413343763989564437170644270643461665184965150423819594083121075825"),
  1240. Primes: []*big.Int{
  1241. bigFromString("13299275414352936908236095374926261633419699590839189494995965049151460173257838079863316944311313904000258169883815802963543635820059341150014695560313417"),
  1242. bigFromString("11578103692682951732111718237224894755352163854919244905974423810539077224889290605729035287537520656160688625383765857517518932447378594964220731750802463"),
  1243. },
  1244. }
  1245. var testECDSAPrivateKey = &ecdsa.PrivateKey{
  1246. PublicKey: ecdsa.PublicKey{
  1247. Curve: elliptic.P521(),
  1248. X: bigFromString("2636411247892461147287360222306590634450676461695221912739908880441342231985950069527906976759812296359387337367668045707086543273113073382714101597903639351"),
  1249. Y: bigFromString("3204695818431246682253994090650952614555094516658732116404513121125038617915183037601737180082382202488628239201196033284060130040574800684774115478859677243"),
  1250. },
  1251. D: bigFromString("5477294338614160138026852784385529180817726002953041720191098180813046231640184669647735805135001309477695746518160084669446643325196003346204701381388769751"),
  1252. }
  1253. var testP256PrivateKey, _ = x509.ParseECPrivateKey(fromHex("30770201010420012f3b52bc54c36ba3577ad45034e2e8efe1e6999851284cb848725cfe029991a00a06082a8648ce3d030107a14403420004c02c61c9b16283bbcc14956d886d79b358aa614596975f78cece787146abf74c2d5dc578c0992b4f3c631373479ebf3892efe53d21c4f4f1cc9a11c3536b7f75"))