Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 
 
 

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