選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 
 

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