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

1406 lines
48 KiB

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