您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 
 

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