Alternative TLS implementation in Go
Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

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