Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

1418 lignes
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 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. 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. // See GH#76
  356. MaxVersion: VersionTLS12,
  357. }
  358. clientConfig := &Config{
  359. InsecureSkipVerify: true,
  360. }
  361. _, state, err := testHandshake(clientConfig, serverConfig)
  362. if err != nil {
  363. t.Fatalf("handshake failed: %s", err)
  364. }
  365. actual := state.SignedCertificateTimestamps
  366. if len(actual) != len(expected) {
  367. t.Fatalf("got %d scts, want %d", len(actual), len(expected))
  368. }
  369. for i, sct := range expected {
  370. if !bytes.Equal(sct, actual[i]) {
  371. t.Fatalf("SCT #%d was %x, but expected %x", i, actual[i], sct)
  372. }
  373. }
  374. }
  375. func TestCrossVersionResume(t *testing.T) {
  376. serverConfig := &Config{
  377. CipherSuites: []uint16{TLS_RSA_WITH_AES_128_CBC_SHA},
  378. Certificates: testConfig.Certificates,
  379. MinVersion: VersionTLS10,
  380. }
  381. clientConfig := &Config{
  382. CipherSuites: []uint16{TLS_RSA_WITH_AES_128_CBC_SHA},
  383. InsecureSkipVerify: true,
  384. ClientSessionCache: NewLRUClientSessionCache(1),
  385. ServerName: "servername",
  386. MinVersion: VersionTLS10,
  387. }
  388. // Establish a session at TLS 1.1.
  389. clientConfig.MaxVersion = VersionTLS11
  390. _, _, err := testHandshake(clientConfig, serverConfig)
  391. if err != nil {
  392. t.Fatalf("handshake failed: %s", err)
  393. }
  394. // The client session cache now contains a TLS 1.1 session.
  395. state, _, err := testHandshake(clientConfig, serverConfig)
  396. if err != nil {
  397. t.Fatalf("handshake failed: %s", err)
  398. }
  399. if !state.DidResume {
  400. t.Fatalf("handshake did not resume at the same version")
  401. }
  402. // Test that the server will decline to resume at a lower version.
  403. clientConfig.MaxVersion = VersionTLS10
  404. state, _, err = testHandshake(clientConfig, serverConfig)
  405. if err != nil {
  406. t.Fatalf("handshake failed: %s", err)
  407. }
  408. if state.DidResume {
  409. t.Fatalf("handshake resumed at a lower version")
  410. }
  411. // The client session cache now contains a TLS 1.0 session.
  412. state, _, err = testHandshake(clientConfig, serverConfig)
  413. if err != nil {
  414. t.Fatalf("handshake failed: %s", err)
  415. }
  416. if !state.DidResume {
  417. t.Fatalf("handshake did not resume at the same version")
  418. }
  419. // Test that the server will decline to resume at a higher version.
  420. clientConfig.MaxVersion = VersionTLS11
  421. state, _, err = testHandshake(clientConfig, serverConfig)
  422. if err != nil {
  423. t.Fatalf("handshake failed: %s", err)
  424. }
  425. if state.DidResume {
  426. t.Fatalf("handshake resumed at a higher version")
  427. }
  428. }
  429. // Note: see comment in handshake_test.go for details of how the reference
  430. // tests work.
  431. // serverTest represents a test of the TLS server handshake against a reference
  432. // implementation.
  433. type serverTest struct {
  434. // name is a freeform string identifying the test and the file in which
  435. // the expected results will be stored.
  436. name string
  437. // command, if not empty, contains a series of arguments for the
  438. // command to run for the reference server.
  439. command []string
  440. // expectedPeerCerts contains a list of PEM blocks of expected
  441. // certificates from the client.
  442. expectedPeerCerts []string
  443. // config, if not nil, contains a custom Config to use for this test.
  444. config *Config
  445. // expectHandshakeErrorIncluding, when not empty, contains a string
  446. // that must be a substring of the error resulting from the handshake.
  447. expectHandshakeErrorIncluding string
  448. // validate, if not nil, is a function that will be called with the
  449. // ConnectionState of the resulting connection. It returns false if the
  450. // ConnectionState is unacceptable.
  451. validate func(ConnectionState) error
  452. }
  453. var defaultClientCommand = []string{"openssl", "s_client", "-no_ticket"}
  454. // connFromCommand starts opens a listening socket and starts the reference
  455. // client to connect to it. It returns a recordingConn that wraps the resulting
  456. // connection.
  457. func (test *serverTest) connFromCommand() (conn *recordingConn, child *exec.Cmd, err error) {
  458. l, err := net.ListenTCP("tcp", &net.TCPAddr{
  459. IP: net.IPv4(127, 0, 0, 1),
  460. Port: 0,
  461. })
  462. if err != nil {
  463. return nil, nil, err
  464. }
  465. defer l.Close()
  466. port := l.Addr().(*net.TCPAddr).Port
  467. var command []string
  468. command = append(command, test.command...)
  469. if len(command) == 0 {
  470. command = defaultClientCommand
  471. }
  472. command = append(command, "-connect")
  473. command = append(command, fmt.Sprintf("127.0.0.1:%d", port))
  474. cmd := exec.Command(command[0], command[1:]...)
  475. cmd.Stdin = nil
  476. var output bytes.Buffer
  477. cmd.Stdout = &output
  478. cmd.Stderr = &output
  479. if err := cmd.Start(); err != nil {
  480. return nil, nil, err
  481. }
  482. connChan := make(chan interface{})
  483. go func() {
  484. tcpConn, err := l.Accept()
  485. if err != nil {
  486. connChan <- err
  487. }
  488. connChan <- tcpConn
  489. }()
  490. var tcpConn net.Conn
  491. select {
  492. case connOrError := <-connChan:
  493. if err, ok := connOrError.(error); ok {
  494. return nil, nil, err
  495. }
  496. tcpConn = connOrError.(net.Conn)
  497. case <-time.After(2 * time.Second):
  498. output.WriteTo(os.Stdout)
  499. return nil, nil, errors.New("timed out waiting for connection from child process")
  500. }
  501. record := &recordingConn{
  502. Conn: tcpConn,
  503. }
  504. return record, cmd, nil
  505. }
  506. func (test *serverTest) dataPath() string {
  507. return filepath.Join("testdata", "Server-"+test.name)
  508. }
  509. func (test *serverTest) loadData() (flows [][]byte, err error) {
  510. in, err := os.Open(test.dataPath())
  511. if err != nil {
  512. return nil, err
  513. }
  514. defer in.Close()
  515. return parseTestData(in)
  516. }
  517. func (test *serverTest) run(t *testing.T, write bool) {
  518. checkOpenSSLVersion(t)
  519. var clientConn, serverConn net.Conn
  520. var recordingConn *recordingConn
  521. var childProcess *exec.Cmd
  522. if write {
  523. var err error
  524. recordingConn, childProcess, err = test.connFromCommand()
  525. if err != nil {
  526. t.Fatalf("Failed to start subcommand: %s", err)
  527. }
  528. serverConn = recordingConn
  529. } else {
  530. clientConn, serverConn = net.Pipe()
  531. }
  532. config := test.config
  533. if config == nil {
  534. config = testConfig
  535. }
  536. server := Server(serverConn, config)
  537. connStateChan := make(chan ConnectionState, 1)
  538. go func() {
  539. _, err := server.Write([]byte("hello, world\n"))
  540. if len(test.expectHandshakeErrorIncluding) > 0 {
  541. if err == nil {
  542. t.Errorf("Error expected, but no error returned")
  543. } else if s := err.Error(); !strings.Contains(s, test.expectHandshakeErrorIncluding) {
  544. t.Errorf("Error expected containing '%s' but got '%s'", test.expectHandshakeErrorIncluding, s)
  545. }
  546. } else {
  547. if err != nil {
  548. t.Logf("Error from Server.Write: '%s'", err)
  549. }
  550. }
  551. server.Close()
  552. serverConn.Close()
  553. connStateChan <- server.ConnectionState()
  554. }()
  555. if !write {
  556. flows, err := test.loadData()
  557. if err != nil {
  558. t.Fatalf("%s: failed to load data from %s", test.name, test.dataPath())
  559. }
  560. for i, b := range flows {
  561. if i%2 == 0 {
  562. clientConn.Write(b)
  563. continue
  564. }
  565. bb := make([]byte, len(b))
  566. n, err := io.ReadFull(clientConn, bb)
  567. if err != nil {
  568. 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)
  569. }
  570. if !bytes.Equal(b, bb) {
  571. t.Fatalf("%s #%d: mismatch on read: got:%x want:%x", test.name, i+1, bb, b)
  572. }
  573. }
  574. clientConn.Close()
  575. }
  576. connState := <-connStateChan
  577. peerCerts := connState.PeerCertificates
  578. if len(peerCerts) == len(test.expectedPeerCerts) {
  579. for i, peerCert := range peerCerts {
  580. block, _ := pem.Decode([]byte(test.expectedPeerCerts[i]))
  581. if !bytes.Equal(block.Bytes, peerCert.Raw) {
  582. t.Fatalf("%s: mismatch on peer cert %d", test.name, i+1)
  583. }
  584. }
  585. } else {
  586. t.Fatalf("%s: mismatch on peer list length: %d (wanted) != %d (got)", test.name, len(test.expectedPeerCerts), len(peerCerts))
  587. }
  588. if test.validate != nil {
  589. if err := test.validate(connState); err != nil {
  590. t.Fatalf("validate callback returned error: %s", err)
  591. }
  592. }
  593. if write {
  594. path := test.dataPath()
  595. out, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
  596. if err != nil {
  597. t.Fatalf("Failed to create output file: %s", err)
  598. }
  599. defer out.Close()
  600. recordingConn.Close()
  601. if len(recordingConn.flows) < 3 {
  602. childProcess.Stdout.(*bytes.Buffer).WriteTo(os.Stdout)
  603. if len(test.expectHandshakeErrorIncluding) == 0 {
  604. t.Fatalf("Handshake failed")
  605. }
  606. }
  607. recordingConn.WriteTo(out)
  608. fmt.Printf("Wrote %s\n", path)
  609. childProcess.Wait()
  610. }
  611. }
  612. func runServerTestForVersion(t *testing.T, template *serverTest, prefix, option string) {
  613. setParallel(t)
  614. test := *template
  615. test.name = prefix + test.name
  616. if len(test.command) == 0 {
  617. test.command = defaultClientCommand
  618. }
  619. test.command = append([]string(nil), test.command...)
  620. test.command = append(test.command, option)
  621. test.run(t, *update)
  622. }
  623. func runServerTestSSLv3(t *testing.T, template *serverTest) {
  624. runServerTestForVersion(t, template, "SSLv3-", "-ssl3")
  625. }
  626. func runServerTestTLS10(t *testing.T, template *serverTest) {
  627. runServerTestForVersion(t, template, "TLSv10-", "-tls1")
  628. }
  629. func runServerTestTLS11(t *testing.T, template *serverTest) {
  630. runServerTestForVersion(t, template, "TLSv11-", "-tls1_1")
  631. }
  632. func runServerTestTLS12(t *testing.T, template *serverTest) {
  633. runServerTestForVersion(t, template, "TLSv12-", "-tls1_2")
  634. }
  635. func TestHandshakeServerRSARC4(t *testing.T) {
  636. test := &serverTest{
  637. name: "RSA-RC4",
  638. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "RC4-SHA"},
  639. }
  640. runServerTestSSLv3(t, test)
  641. runServerTestTLS10(t, test)
  642. runServerTestTLS11(t, test)
  643. runServerTestTLS12(t, test)
  644. }
  645. func TestHandshakeServerRSA3DES(t *testing.T) {
  646. test := &serverTest{
  647. name: "RSA-3DES",
  648. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "DES-CBC3-SHA"},
  649. }
  650. runServerTestSSLv3(t, test)
  651. runServerTestTLS10(t, test)
  652. runServerTestTLS12(t, test)
  653. }
  654. func TestHandshakeServerRSAAES(t *testing.T) {
  655. test := &serverTest{
  656. name: "RSA-AES",
  657. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA"},
  658. }
  659. runServerTestSSLv3(t, test)
  660. runServerTestTLS10(t, test)
  661. runServerTestTLS12(t, test)
  662. }
  663. func TestHandshakeServerAESGCM(t *testing.T) {
  664. test := &serverTest{
  665. name: "RSA-AES-GCM",
  666. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-AES128-GCM-SHA256"},
  667. }
  668. runServerTestTLS12(t, test)
  669. }
  670. func TestHandshakeServerAES256GCMSHA384(t *testing.T) {
  671. test := &serverTest{
  672. name: "RSA-AES256-GCM-SHA384",
  673. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-AES256-GCM-SHA384"},
  674. }
  675. runServerTestTLS12(t, test)
  676. }
  677. func TestHandshakeServerECDHEECDSAAES(t *testing.T) {
  678. config := testConfig.Clone()
  679. config.Certificates = make([]Certificate, 1)
  680. config.Certificates[0].Certificate = [][]byte{testECDSACertificate}
  681. config.Certificates[0].PrivateKey = testECDSAPrivateKey
  682. config.BuildNameToCertificate()
  683. test := &serverTest{
  684. name: "ECDHE-ECDSA-AES",
  685. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-ECDSA-AES256-SHA"},
  686. config: config,
  687. }
  688. runServerTestTLS10(t, test)
  689. runServerTestTLS12(t, test)
  690. }
  691. func TestHandshakeServerX25519(t *testing.T) {
  692. config := testConfig.Clone()
  693. config.CurvePreferences = []CurveID{X25519}
  694. test := &serverTest{
  695. name: "X25519-ECDHE-RSA-AES-GCM",
  696. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-AES128-GCM-SHA256"},
  697. config: config,
  698. }
  699. runServerTestTLS12(t, test)
  700. }
  701. func TestHandshakeServerALPN(t *testing.T) {
  702. config := testConfig.Clone()
  703. config.NextProtos = []string{"proto1", "proto2"}
  704. test := &serverTest{
  705. name: "ALPN",
  706. // Note that this needs OpenSSL 1.0.2 because that is the first
  707. // version that supports the -alpn flag.
  708. command: []string{"openssl", "s_client", "-alpn", "proto2,proto1"},
  709. config: config,
  710. validate: func(state ConnectionState) error {
  711. // The server's preferences should override the client.
  712. if state.NegotiatedProtocol != "proto1" {
  713. return fmt.Errorf("Got protocol %q, wanted proto1", state.NegotiatedProtocol)
  714. }
  715. return nil
  716. },
  717. }
  718. runServerTestTLS12(t, test)
  719. }
  720. func TestHandshakeServerALPNNoMatch(t *testing.T) {
  721. config := testConfig.Clone()
  722. config.NextProtos = []string{"proto3"}
  723. test := &serverTest{
  724. name: "ALPN-NoMatch",
  725. // Note that this needs OpenSSL 1.0.2 because that is the first
  726. // version that supports the -alpn flag.
  727. command: []string{"openssl", "s_client", "-alpn", "proto2,proto1"},
  728. config: config,
  729. validate: func(state ConnectionState) error {
  730. // Rather than reject the connection, Go doesn't select
  731. // a protocol when there is no overlap.
  732. if state.NegotiatedProtocol != "" {
  733. return fmt.Errorf("Got protocol %q, wanted ''", state.NegotiatedProtocol)
  734. }
  735. return nil
  736. },
  737. }
  738. runServerTestTLS12(t, test)
  739. }
  740. // TestHandshakeServerSNI involves a client sending an SNI extension of
  741. // "snitest.com", which happens to match the CN of testSNICertificate. The test
  742. // verifies that the server correctly selects that certificate.
  743. func TestHandshakeServerSNI(t *testing.T) {
  744. test := &serverTest{
  745. name: "SNI",
  746. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"},
  747. }
  748. runServerTestTLS12(t, test)
  749. }
  750. // TestHandshakeServerSNICertForName is similar to TestHandshakeServerSNI, but
  751. // tests the dynamic GetCertificate method
  752. func TestHandshakeServerSNIGetCertificate(t *testing.T) {
  753. config := testConfig.Clone()
  754. // Replace the NameToCertificate map with a GetCertificate function
  755. nameToCert := config.NameToCertificate
  756. config.NameToCertificate = nil
  757. config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
  758. cert, _ := nameToCert[clientHello.ServerName]
  759. return cert, nil
  760. }
  761. test := &serverTest{
  762. name: "SNI-GetCertificate",
  763. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"},
  764. config: config,
  765. }
  766. runServerTestTLS12(t, test)
  767. }
  768. // TestHandshakeServerSNICertForNameNotFound is similar to
  769. // TestHandshakeServerSNICertForName, but tests to make sure that when the
  770. // GetCertificate method doesn't return a cert, we fall back to what's in
  771. // the NameToCertificate map.
  772. func TestHandshakeServerSNIGetCertificateNotFound(t *testing.T) {
  773. config := testConfig.Clone()
  774. config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
  775. return nil, nil
  776. }
  777. test := &serverTest{
  778. name: "SNI-GetCertificateNotFound",
  779. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"},
  780. config: config,
  781. }
  782. runServerTestTLS12(t, test)
  783. }
  784. // TestHandshakeServerSNICertForNameError tests to make sure that errors in
  785. // GetCertificate result in a tls alert.
  786. func TestHandshakeServerSNIGetCertificateError(t *testing.T) {
  787. const errMsg = "TestHandshakeServerSNIGetCertificateError error"
  788. serverConfig := testConfig.Clone()
  789. serverConfig.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
  790. return nil, errors.New(errMsg)
  791. }
  792. clientHello := &clientHelloMsg{
  793. vers: VersionTLS10,
  794. cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
  795. compressionMethods: []uint8{compressionNone},
  796. serverName: "test",
  797. }
  798. testClientHelloFailure(t, serverConfig, clientHello, errMsg)
  799. }
  800. // TestHandshakeServerEmptyCertificates tests that GetCertificates is called in
  801. // the case that Certificates is empty, even without SNI.
  802. func TestHandshakeServerEmptyCertificates(t *testing.T) {
  803. const errMsg = "TestHandshakeServerEmptyCertificates error"
  804. serverConfig := testConfig.Clone()
  805. serverConfig.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
  806. return nil, errors.New(errMsg)
  807. }
  808. serverConfig.Certificates = nil
  809. clientHello := &clientHelloMsg{
  810. vers: VersionTLS10,
  811. cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
  812. compressionMethods: []uint8{compressionNone},
  813. }
  814. testClientHelloFailure(t, serverConfig, clientHello, errMsg)
  815. // With an empty Certificates and a nil GetCertificate, the server
  816. // should always return a “no certificates” error.
  817. serverConfig.GetCertificate = nil
  818. clientHello = &clientHelloMsg{
  819. vers: VersionTLS10,
  820. cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
  821. compressionMethods: []uint8{compressionNone},
  822. }
  823. testClientHelloFailure(t, serverConfig, clientHello, "no certificates")
  824. }
  825. // TestCipherSuiteCertPreference ensures that we select an RSA ciphersuite with
  826. // an RSA certificate and an ECDSA ciphersuite with an ECDSA certificate.
  827. func TestCipherSuiteCertPreferenceECDSA(t *testing.T) {
  828. config := testConfig.Clone()
  829. config.CipherSuites = []uint16{TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA}
  830. config.PreferServerCipherSuites = true
  831. test := &serverTest{
  832. name: "CipherSuiteCertPreferenceRSA",
  833. config: config,
  834. }
  835. runServerTestTLS12(t, test)
  836. config = testConfig.Clone()
  837. config.CipherSuites = []uint16{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA}
  838. config.Certificates = []Certificate{
  839. {
  840. Certificate: [][]byte{testECDSACertificate},
  841. PrivateKey: testECDSAPrivateKey,
  842. },
  843. }
  844. config.BuildNameToCertificate()
  845. config.PreferServerCipherSuites = true
  846. test = &serverTest{
  847. name: "CipherSuiteCertPreferenceECDSA",
  848. config: config,
  849. }
  850. runServerTestTLS12(t, test)
  851. }
  852. func TestResumption(t *testing.T) {
  853. sessionFilePath := tempFile("")
  854. defer os.Remove(sessionFilePath)
  855. test := &serverTest{
  856. name: "IssueTicket",
  857. command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-sess_out", sessionFilePath},
  858. }
  859. runServerTestTLS12(t, test)
  860. test = &serverTest{
  861. name: "Resume",
  862. command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-sess_in", sessionFilePath},
  863. }
  864. runServerTestTLS12(t, test)
  865. }
  866. func TestResumptionDisabled(t *testing.T) {
  867. sessionFilePath := tempFile("")
  868. defer os.Remove(sessionFilePath)
  869. config := testConfig.Clone()
  870. test := &serverTest{
  871. name: "IssueTicketPreDisable",
  872. command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-sess_out", sessionFilePath},
  873. config: config,
  874. }
  875. runServerTestTLS12(t, test)
  876. config.SessionTicketsDisabled = true
  877. test = &serverTest{
  878. name: "ResumeDisabled",
  879. command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-sess_in", sessionFilePath},
  880. config: config,
  881. }
  882. runServerTestTLS12(t, test)
  883. // One needs to manually confirm that the handshake in the golden data
  884. // file for ResumeDisabled does not include a resumption handshake.
  885. }
  886. func TestFallbackSCSV(t *testing.T) {
  887. serverConfig := Config{
  888. Certificates: testConfig.Certificates,
  889. MinVersion: VersionTLS10,
  890. }
  891. test := &serverTest{
  892. name: "FallbackSCSV",
  893. config: &serverConfig,
  894. // OpenSSL 1.0.1j is needed for the -fallback_scsv option.
  895. command: []string{"openssl", "s_client", "-fallback_scsv"},
  896. expectHandshakeErrorIncluding: "inappropriate protocol fallback",
  897. }
  898. runServerTestTLS11(t, test)
  899. }
  900. func benchmarkHandshakeServer(b *testing.B, cipherSuite uint16, curve CurveID, cert []byte, key crypto.PrivateKey) {
  901. config := testConfig.Clone()
  902. config.CipherSuites = []uint16{cipherSuite}
  903. config.CurvePreferences = []CurveID{curve}
  904. config.Certificates = make([]Certificate, 1)
  905. config.Certificates[0].Certificate = [][]byte{cert}
  906. config.Certificates[0].PrivateKey = key
  907. config.BuildNameToCertificate()
  908. clientConn, serverConn := net.Pipe()
  909. serverConn = &recordingConn{Conn: serverConn}
  910. go func() {
  911. client := Client(clientConn, testConfig)
  912. client.Handshake()
  913. }()
  914. server := Server(serverConn, config)
  915. if err := server.Handshake(); err != nil {
  916. b.Fatalf("handshake failed: %v", err)
  917. }
  918. serverConn.Close()
  919. flows := serverConn.(*recordingConn).flows
  920. feeder := make(chan struct{})
  921. clientConn, serverConn = net.Pipe()
  922. go func() {
  923. for range feeder {
  924. for i, f := range flows {
  925. if i%2 == 0 {
  926. clientConn.Write(f)
  927. continue
  928. }
  929. ff := make([]byte, len(f))
  930. n, err := io.ReadFull(clientConn, ff)
  931. if err != nil {
  932. b.Fatalf("#%d: %s\nRead %d, wanted %d, got %x, wanted %x\n", i+1, err, n, len(ff), ff[:n], f)
  933. }
  934. if !bytes.Equal(f, ff) {
  935. b.Fatalf("#%d: mismatch on read: got:%x want:%x", i+1, ff, f)
  936. }
  937. }
  938. }
  939. }()
  940. b.ResetTimer()
  941. for i := 0; i < b.N; i++ {
  942. feeder <- struct{}{}
  943. server := Server(serverConn, config)
  944. if err := server.Handshake(); err != nil {
  945. b.Fatalf("handshake failed: %v", err)
  946. }
  947. }
  948. close(feeder)
  949. }
  950. func BenchmarkHandshakeServer(b *testing.B) {
  951. b.Run("RSA", func(b *testing.B) {
  952. benchmarkHandshakeServer(b, TLS_RSA_WITH_AES_128_GCM_SHA256,
  953. 0, testRSACertificate, testRSAPrivateKey)
  954. })
  955. b.Run("ECDHE-P256-RSA", func(b *testing.B) {
  956. benchmarkHandshakeServer(b, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
  957. CurveP256, testRSACertificate, testRSAPrivateKey)
  958. })
  959. b.Run("ECDHE-P256-ECDSA-P256", func(b *testing.B) {
  960. benchmarkHandshakeServer(b, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  961. CurveP256, testP256Certificate, testP256PrivateKey)
  962. })
  963. b.Run("ECDHE-X25519-ECDSA-P256", func(b *testing.B) {
  964. benchmarkHandshakeServer(b, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  965. X25519, testP256Certificate, testP256PrivateKey)
  966. })
  967. b.Run("ECDHE-P521-ECDSA-P521", func(b *testing.B) {
  968. if testECDSAPrivateKey.PublicKey.Curve != elliptic.P521() {
  969. b.Fatal("test ECDSA key doesn't use curve P-521")
  970. }
  971. benchmarkHandshakeServer(b, TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  972. CurveP521, testECDSACertificate, testECDSAPrivateKey)
  973. })
  974. }
  975. // clientCertificatePEM and clientKeyPEM were generated with generate_cert.go
  976. // Thus, they have no ExtKeyUsage fields and trigger an error when verification
  977. // is turned on.
  978. const clientCertificatePEM = `
  979. -----BEGIN CERTIFICATE-----
  980. MIIB7zCCAVigAwIBAgIQXBnBiWWDVW/cC8m5k5/pvDANBgkqhkiG9w0BAQsFADAS
  981. MRAwDgYDVQQKEwdBY21lIENvMB4XDTE2MDgxNzIxNTIzMVoXDTE3MDgxNzIxNTIz
  982. MVowEjEQMA4GA1UEChMHQWNtZSBDbzCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkC
  983. gYEAum+qhr3Pv5/y71yUYHhv6BPy0ZZvzdkybiI3zkH5yl0prOEn2mGi7oHLEMff
  984. NFiVhuk9GeZcJ3NgyI14AvQdpJgJoxlwaTwlYmYqqyIjxXuFOE8uCXMyp70+m63K
  985. hAfmDzr/d8WdQYUAirab7rCkPy1MTOZCPrtRyN1IVPQMjkcCAwEAAaNGMEQwDgYD
  986. VR0PAQH/BAQDAgWgMBMGA1UdJQQMMAoGCCsGAQUFBwMBMAwGA1UdEwEB/wQCMAAw
  987. DwYDVR0RBAgwBocEfwAAATANBgkqhkiG9w0BAQsFAAOBgQBGq0Si+yhU+Fpn+GKU
  988. 8ZqyGJ7ysd4dfm92lam6512oFmyc9wnTN+RLKzZ8Aa1B0jLYw9KT+RBrjpW5LBeK
  989. o0RIvFkTgxYEiKSBXCUNmAysEbEoVr4dzWFihAm/1oDGRY2CLLTYg5vbySK3KhIR
  990. e/oCO8HJ/+rJnahJ05XX1Q7lNQ==
  991. -----END CERTIFICATE-----`
  992. const clientKeyPEM = `
  993. -----BEGIN RSA PRIVATE KEY-----
  994. MIICXQIBAAKBgQC6b6qGvc+/n/LvXJRgeG/oE/LRlm/N2TJuIjfOQfnKXSms4Sfa
  995. YaLugcsQx980WJWG6T0Z5lwnc2DIjXgC9B2kmAmjGXBpPCViZiqrIiPFe4U4Ty4J
  996. czKnvT6brcqEB+YPOv93xZ1BhQCKtpvusKQ/LUxM5kI+u1HI3UhU9AyORwIDAQAB
  997. AoGAEJZ03q4uuMb7b26WSQsOMeDsftdatT747LGgs3pNRkMJvTb/O7/qJjxoG+Mc
  998. qeSj0TAZXp+PXXc3ikCECAc+R8rVMfWdmp903XgO/qYtmZGCorxAHEmR80SrfMXv
  999. PJnznLQWc8U9nphQErR+tTESg7xWEzmFcPKwnZd1xg8ERYkCQQDTGtrFczlB2b/Z
  1000. 9TjNMqUlMnTLIk/a/rPE2fLLmAYhK5sHnJdvDURaH2mF4nso0EGtENnTsh6LATnY
  1001. dkrxXGm9AkEA4hXHG2q3MnhgK1Z5hjv+Fnqd+8bcbII9WW4flFs15EKoMgS1w/PJ
  1002. zbsySaSy5IVS8XeShmT9+3lrleed4sy+UwJBAJOOAbxhfXP5r4+5R6ql66jES75w
  1003. jUCVJzJA5ORJrn8g64u2eGK28z/LFQbv9wXgCwfc72R468BdawFSLa/m2EECQGbZ
  1004. rWiFla26IVXV0xcD98VWJsTBZMlgPnSOqoMdM1kSEd4fUmlAYI/dFzV1XYSkOmVr
  1005. FhdZnklmpVDeu27P4c0CQQCuCOup0FlJSBpWY1TTfun/KMBkBatMz0VMA3d7FKIU
  1006. csPezl677Yjo8u1r/KzeI6zLg87Z8E6r6ZWNc9wBSZK6
  1007. -----END RSA PRIVATE KEY-----`
  1008. const clientECDSACertificatePEM = `
  1009. -----BEGIN CERTIFICATE-----
  1010. MIIB/DCCAV4CCQCaMIRsJjXZFzAJBgcqhkjOPQQBMEUxCzAJBgNVBAYTAkFVMRMw
  1011. EQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0
  1012. eSBMdGQwHhcNMTIxMTE0MTMyNTUzWhcNMjIxMTEyMTMyNTUzWjBBMQswCQYDVQQG
  1013. EwJBVTEMMAoGA1UECBMDTlNXMRAwDgYDVQQHEwdQeXJtb250MRIwEAYDVQQDEwlK
  1014. b2VsIFNpbmcwgZswEAYHKoZIzj0CAQYFK4EEACMDgYYABACVjJF1FMBexFe01MNv
  1015. ja5oHt1vzobhfm6ySD6B5U7ixohLZNz1MLvT/2XMW/TdtWo+PtAd3kfDdq0Z9kUs
  1016. jLzYHQFMH3CQRnZIi4+DzEpcj0B22uCJ7B0rxE4wdihBsmKo+1vx+U56jb0JuK7q
  1017. ixgnTy5w/hOWusPTQBbNZU6sER7m8TAJBgcqhkjOPQQBA4GMADCBiAJCAOAUxGBg
  1018. C3JosDJdYUoCdFzCgbkWqD8pyDbHgf9stlvZcPE4O1BIKJTLCRpS8V3ujfK58PDa
  1019. 2RU6+b0DeoeiIzXsAkIBo9SKeDUcSpoj0gq+KxAxnZxfvuiRs9oa9V2jI/Umi0Vw
  1020. jWVim34BmT0Y9hCaOGGbLlfk+syxis7iI6CH8OFnUes=
  1021. -----END CERTIFICATE-----`
  1022. const clientECDSAKeyPEM = `
  1023. -----BEGIN EC PARAMETERS-----
  1024. BgUrgQQAIw==
  1025. -----END EC PARAMETERS-----
  1026. -----BEGIN EC PRIVATE KEY-----
  1027. MIHcAgEBBEIBkJN9X4IqZIguiEVKMqeBUP5xtRsEv4HJEtOpOGLELwO53SD78Ew8
  1028. k+wLWoqizS3NpQyMtrU8JFdWfj+C57UNkOugBwYFK4EEACOhgYkDgYYABACVjJF1
  1029. FMBexFe01MNvja5oHt1vzobhfm6ySD6B5U7ixohLZNz1MLvT/2XMW/TdtWo+PtAd
  1030. 3kfDdq0Z9kUsjLzYHQFMH3CQRnZIi4+DzEpcj0B22uCJ7B0rxE4wdihBsmKo+1vx
  1031. +U56jb0JuK7qixgnTy5w/hOWusPTQBbNZU6sER7m8Q==
  1032. -----END EC PRIVATE KEY-----`
  1033. func TestClientAuth(t *testing.T) {
  1034. setParallel(t)
  1035. var certPath, keyPath, ecdsaCertPath, ecdsaKeyPath string
  1036. if *update {
  1037. certPath = tempFile(clientCertificatePEM)
  1038. defer os.Remove(certPath)
  1039. keyPath = tempFile(clientKeyPEM)
  1040. defer os.Remove(keyPath)
  1041. ecdsaCertPath = tempFile(clientECDSACertificatePEM)
  1042. defer os.Remove(ecdsaCertPath)
  1043. ecdsaKeyPath = tempFile(clientECDSAKeyPEM)
  1044. defer os.Remove(ecdsaKeyPath)
  1045. }
  1046. config := testConfig.Clone()
  1047. config.ClientAuth = RequestClientCert
  1048. test := &serverTest{
  1049. name: "ClientAuthRequestedNotGiven",
  1050. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA"},
  1051. config: config,
  1052. }
  1053. runServerTestTLS12(t, test)
  1054. test = &serverTest{
  1055. name: "ClientAuthRequestedAndGiven",
  1056. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-cert", certPath, "-key", keyPath},
  1057. config: config,
  1058. expectedPeerCerts: []string{clientCertificatePEM},
  1059. }
  1060. runServerTestTLS12(t, test)
  1061. test = &serverTest{
  1062. name: "ClientAuthRequestedAndECDSAGiven",
  1063. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-cert", ecdsaCertPath, "-key", ecdsaKeyPath},
  1064. config: config,
  1065. expectedPeerCerts: []string{clientECDSACertificatePEM},
  1066. }
  1067. runServerTestTLS12(t, test)
  1068. }
  1069. func TestSNIGivenOnFailure(t *testing.T) {
  1070. const expectedServerName = "test.testing"
  1071. clientHello := &clientHelloMsg{
  1072. vers: VersionTLS10,
  1073. cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
  1074. compressionMethods: []uint8{compressionNone},
  1075. serverName: expectedServerName,
  1076. }
  1077. serverConfig := testConfig.Clone()
  1078. // Erase the server's cipher suites to ensure the handshake fails.
  1079. serverConfig.CipherSuites = nil
  1080. c, s := net.Pipe()
  1081. go func() {
  1082. cli := Client(c, testConfig)
  1083. cli.vers = clientHello.vers
  1084. cli.writeRecord(recordTypeHandshake, clientHello.marshal())
  1085. c.Close()
  1086. }()
  1087. hs := serverHandshakeState{
  1088. c: Server(s, serverConfig),
  1089. }
  1090. _, err := hs.readClientHello()
  1091. defer s.Close()
  1092. if err == nil {
  1093. t.Error("No error reported from server")
  1094. }
  1095. cs := hs.c.ConnectionState()
  1096. if cs.HandshakeComplete {
  1097. t.Error("Handshake registered as complete")
  1098. }
  1099. if cs.ServerName != expectedServerName {
  1100. t.Errorf("Expected ServerName of %q, but got %q", expectedServerName, cs.ServerName)
  1101. }
  1102. }
  1103. var getConfigForClientTests = []struct {
  1104. setup func(config *Config)
  1105. callback func(clientHello *ClientHelloInfo) (*Config, error)
  1106. errorSubstring string
  1107. verify func(config *Config) error
  1108. }{
  1109. {
  1110. nil,
  1111. func(clientHello *ClientHelloInfo) (*Config, error) {
  1112. return nil, nil
  1113. },
  1114. "",
  1115. nil,
  1116. },
  1117. {
  1118. nil,
  1119. func(clientHello *ClientHelloInfo) (*Config, error) {
  1120. return nil, errors.New("should bubble up")
  1121. },
  1122. "should bubble up",
  1123. nil,
  1124. },
  1125. {
  1126. nil,
  1127. func(clientHello *ClientHelloInfo) (*Config, error) {
  1128. config := testConfig.Clone()
  1129. // Setting a maximum version of TLS 1.1 should cause
  1130. // the handshake to fail.
  1131. config.MaxVersion = VersionTLS11
  1132. return config, nil
  1133. },
  1134. "protocol version not supported",
  1135. nil,
  1136. },
  1137. {
  1138. func(config *Config) {
  1139. for i := range config.SessionTicketKey {
  1140. config.SessionTicketKey[i] = byte(i)
  1141. }
  1142. config.sessionTicketKeys = nil
  1143. },
  1144. func(clientHello *ClientHelloInfo) (*Config, error) {
  1145. config := testConfig.Clone()
  1146. for i := range config.SessionTicketKey {
  1147. config.SessionTicketKey[i] = 0
  1148. }
  1149. config.sessionTicketKeys = nil
  1150. return config, nil
  1151. },
  1152. "",
  1153. func(config *Config) error {
  1154. // The value of SessionTicketKey should have been
  1155. // duplicated into the per-connection Config.
  1156. for i := range config.SessionTicketKey {
  1157. if b := config.SessionTicketKey[i]; b != byte(i) {
  1158. return fmt.Errorf("SessionTicketKey was not duplicated from original Config: byte %d has value %d", i, b)
  1159. }
  1160. }
  1161. return nil
  1162. },
  1163. },
  1164. {
  1165. func(config *Config) {
  1166. var dummyKey [32]byte
  1167. for i := range dummyKey {
  1168. dummyKey[i] = byte(i)
  1169. }
  1170. config.SetSessionTicketKeys([][32]byte{dummyKey})
  1171. },
  1172. func(clientHello *ClientHelloInfo) (*Config, error) {
  1173. config := testConfig.Clone()
  1174. config.sessionTicketKeys = nil
  1175. return config, nil
  1176. },
  1177. "",
  1178. func(config *Config) error {
  1179. // The session ticket keys should have been duplicated
  1180. // into the per-connection Config.
  1181. if l := len(config.sessionTicketKeys); l != 1 {
  1182. return fmt.Errorf("got len(sessionTicketKeys) == %d, wanted 1", l)
  1183. }
  1184. return nil
  1185. },
  1186. },
  1187. }
  1188. func TestGetConfigForClient(t *testing.T) {
  1189. serverConfig := testConfig.Clone()
  1190. clientConfig := testConfig.Clone()
  1191. clientConfig.MinVersion = VersionTLS12
  1192. for i, test := range getConfigForClientTests {
  1193. if test.setup != nil {
  1194. test.setup(serverConfig)
  1195. }
  1196. var configReturned *Config
  1197. serverConfig.GetConfigForClient = func(clientHello *ClientHelloInfo) (*Config, error) {
  1198. config, err := test.callback(clientHello)
  1199. configReturned = config
  1200. return config, err
  1201. }
  1202. c, s := net.Pipe()
  1203. done := make(chan error)
  1204. go func() {
  1205. defer s.Close()
  1206. done <- Server(s, serverConfig).Handshake()
  1207. }()
  1208. clientErr := Client(c, clientConfig).Handshake()
  1209. c.Close()
  1210. serverErr := <-done
  1211. if len(test.errorSubstring) == 0 {
  1212. if serverErr != nil || clientErr != nil {
  1213. t.Errorf("test[%d]: expected no error but got serverErr: %q, clientErr: %q", i, serverErr, clientErr)
  1214. }
  1215. if test.verify != nil {
  1216. if err := test.verify(configReturned); err != nil {
  1217. t.Errorf("test[%d]: verify returned error: %v", i, err)
  1218. }
  1219. }
  1220. } else {
  1221. if serverErr == nil {
  1222. t.Errorf("test[%d]: expected error containing %q but got no error", i, test.errorSubstring)
  1223. } else if !strings.Contains(serverErr.Error(), test.errorSubstring) {
  1224. t.Errorf("test[%d]: expected error to contain %q but it was %q", i, test.errorSubstring, serverErr)
  1225. }
  1226. }
  1227. }
  1228. }
  1229. func bigFromString(s string) *big.Int {
  1230. ret := new(big.Int)
  1231. ret.SetString(s, 10)
  1232. return ret
  1233. }
  1234. func fromHex(s string) []byte {
  1235. b, _ := hex.DecodeString(s)
  1236. return b
  1237. }
  1238. var testRSACertificate = fromHex("3082024b308201b4a003020102020900e8f09d3fe25beaa6300d06092a864886f70d01010b0500301f310b3009060355040a1302476f3110300e06035504031307476f20526f6f74301e170d3136303130313030303030305a170d3235303130313030303030305a301a310b3009060355040a1302476f310b300906035504031302476f30819f300d06092a864886f70d010101050003818d0030818902818100db467d932e12270648bc062821ab7ec4b6a25dfe1e5245887a3647a5080d92425bc281c0be97799840fb4f6d14fd2b138bc2a52e67d8d4099ed62238b74a0b74732bc234f1d193e596d9747bf3589f6c613cc0b041d4d92b2b2423775b1c3bbd755dce2054cfa163871d1e24c4f31d1a508baab61443ed97a77562f414c852d70203010001a38193308190300e0603551d0f0101ff0404030205a0301d0603551d250416301406082b0601050507030106082b06010505070302300c0603551d130101ff0402300030190603551d0e041204109f91161f43433e49a6de6db680d79f60301b0603551d230414301280104813494d137e1631bba301d5acab6e7b30190603551d1104123010820e6578616d706c652e676f6c616e67300d06092a864886f70d01010b0500038181009d30cc402b5b50a061cbbae55358e1ed8328a9581aa938a495a1ac315a1a84663d43d32dd90bf297dfd320643892243a00bccf9c7db74020015faad3166109a276fd13c3cce10c5ceeb18782f16c04ed73bbb343778d0c1cf10fa1d8408361c94c722b9daedb4606064df4c1b33ec0d1bd42d4dbfe3d1360845c21d33be9fae7")
  1239. var testRSACertificateIssuer = fromHex("3082021930820182a003020102020900ca5e4e811a965964300d06092a864886f70d01010b0500301f310b3009060355040a1302476f3110300e06035504031307476f20526f6f74301e170d3136303130313030303030305a170d3235303130313030303030305a301f310b3009060355040a1302476f3110300e06035504031307476f20526f6f7430819f300d06092a864886f70d010101050003818d0030818902818100d667b378bb22f34143b6cd2008236abefaf2852adf3ab05e01329e2c14834f5105df3f3073f99dab5442d45ee5f8f57b0111c8cb682fbb719a86944eebfffef3406206d898b8c1b1887797c9c5006547bb8f00e694b7a063f10839f269f2c34fff7a1f4b21fbcd6bfdfb13ac792d1d11f277b5c5b48600992203059f2a8f8cc50203010001a35d305b300e0603551d0f0101ff040403020204301d0603551d250416301406082b0601050507030106082b06010505070302300f0603551d130101ff040530030101ff30190603551d0e041204104813494d137e1631bba301d5acab6e7b300d06092a864886f70d01010b050003818100c1154b4bab5266221f293766ae4138899bd4c5e36b13cee670ceeaa4cbdf4f6679017e2fe649765af545749fe4249418a56bd38a04b81e261f5ce86b8d5c65413156a50d12449554748c59a30c515bc36a59d38bddf51173e899820b282e40aa78c806526fd184fb6b4cf186ec728edffa585440d2b3225325f7ab580e87dd76")
  1240. var testECDSACertificate = fromHex("3082020030820162020900b8bf2d47a0d2ebf4300906072a8648ce3d04013045310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c7464301e170d3132313132323135303633325a170d3232313132303135303633325a3045310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c746430819b301006072a8648ce3d020106052b81040023038186000400c4a1edbe98f90b4873367ec316561122f23d53c33b4d213dcd6b75e6f6b0dc9adf26c1bcb287f072327cb3642f1c90bcea6823107efee325c0483a69e0286dd33700ef0462dd0da09c706283d881d36431aa9e9731bd96b068c09b23de76643f1a5c7fe9120e5858b65f70dd9bd8ead5d7f5d5ccb9b69f30665b669a20e227e5bffe3b300906072a8648ce3d040103818c0030818802420188a24febe245c5487d1bacf5ed989dae4770c05e1bb62fbdf1b64db76140d311a2ceee0b7e927eff769dc33b7ea53fcefa10e259ec472d7cacda4e970e15a06fd00242014dfcbe67139c2d050ebd3fa38c25c13313830d9406bbd4377af6ec7ac9862eddd711697f857c56defb31782be4c7780daecbbe9e4e3624317b6a0f399512078f2a")
  1241. var testSNICertificate = fromHex("0441883421114c81480804c430820237308201a0a003020102020900e8f09d3fe25beaa6300d06092a864886f70d01010b0500301f310b3009060355040a1302476f3110300e06035504031307476f20526f6f74301e170d3136303130313030303030305a170d3235303130313030303030305a3023310b3009060355040a1302476f311430120603550403130b736e69746573742e636f6d30819f300d06092a864886f70d010101050003818d0030818902818100db467d932e12270648bc062821ab7ec4b6a25dfe1e5245887a3647a5080d92425bc281c0be97799840fb4f6d14fd2b138bc2a52e67d8d4099ed62238b74a0b74732bc234f1d193e596d9747bf3589f6c613cc0b041d4d92b2b2423775b1c3bbd755dce2054cfa163871d1e24c4f31d1a508baab61443ed97a77562f414c852d70203010001a3773075300e0603551d0f0101ff0404030205a0301d0603551d250416301406082b0601050507030106082b06010505070302300c0603551d130101ff0402300030190603551d0e041204109f91161f43433e49a6de6db680d79f60301b0603551d230414301280104813494d137e1631bba301d5acab6e7b300d06092a864886f70d01010b0500038181007beeecff0230dbb2e7a334af65430b7116e09f327c3bbf918107fc9c66cb497493207ae9b4dbb045cb63d605ec1b5dd485bb69124d68fa298dc776699b47632fd6d73cab57042acb26f083c4087459bc5a3bb3ca4d878d7fe31016b7bc9a627438666566e3389bfaeebe6becc9a0093ceed18d0f9ac79d56f3a73f18188988ed")
  1242. var testP256Certificate = fromHex("308201693082010ea00302010202105012dc24e1124ade4f3e153326ff27bf300a06082a8648ce3d04030230123110300e060355040a130741636d6520436f301e170d3137303533313232343934375a170d3138303533313232343934375a30123110300e060355040a130741636d6520436f3059301306072a8648ce3d020106082a8648ce3d03010703420004c02c61c9b16283bbcc14956d886d79b358aa614596975f78cece787146abf74c2d5dc578c0992b4f3c631373479ebf3892efe53d21c4f4f1cc9a11c3536b7f75a3463044300e0603551d0f0101ff0404030205a030130603551d25040c300a06082b06010505070301300c0603551d130101ff04023000300f0603551d1104083006820474657374300a06082a8648ce3d0403020349003046022100963712d6226c7b2bef41512d47e1434131aaca3ba585d666c924df71ac0448b3022100f4d05c725064741aef125f243cdbccaa2a5d485927831f221c43023bd5ae471a")
  1243. var testRSAPrivateKey = &rsa.PrivateKey{
  1244. PublicKey: rsa.PublicKey{
  1245. N: bigFromString("153980389784927331788354528594524332344709972855165340650588877572729725338415474372475094155672066328274535240275856844648695200875763869073572078279316458648124537905600131008790701752441155668003033945258023841165089852359980273279085783159654751552359397986180318708491098942831252291841441726305535546071"),
  1246. E: 65537,
  1247. },
  1248. D: bigFromString("7746362285745539358014631136245887418412633787074173796862711588221766398229333338511838891484974940633857861775630560092874987828057333663969469797013996401149696897591265769095952887917296740109742927689053276850469671231961384712725169432413343763989564437170644270643461665184965150423819594083121075825"),
  1249. Primes: []*big.Int{
  1250. bigFromString("13299275414352936908236095374926261633419699590839189494995965049151460173257838079863316944311313904000258169883815802963543635820059341150014695560313417"),
  1251. bigFromString("11578103692682951732111718237224894755352163854919244905974423810539077224889290605729035287537520656160688625383765857517518932447378594964220731750802463"),
  1252. },
  1253. }
  1254. var testECDSAPrivateKey = &ecdsa.PrivateKey{
  1255. PublicKey: ecdsa.PublicKey{
  1256. Curve: elliptic.P521(),
  1257. X: bigFromString("2636411247892461147287360222306590634450676461695221912739908880441342231985950069527906976759812296359387337367668045707086543273113073382714101597903639351"),
  1258. Y: bigFromString("3204695818431246682253994090650952614555094516658732116404513121125038617915183037601737180082382202488628239201196033284060130040574800684774115478859677243"),
  1259. },
  1260. D: bigFromString("5477294338614160138026852784385529180817726002953041720191098180813046231640184669647735805135001309477695746518160084669446643325196003346204701381388769751"),
  1261. }
  1262. var testP256PrivateKey, _ = x509.ParseECPrivateKey(fromHex("30770201010420012f3b52bc54c36ba3577ad45034e2e8efe1e6999851284cb848725cfe029991a00a06082a8648ce3d030107a14403420004c02c61c9b16283bbcc14956d886d79b358aa614596975f78cece787146abf74c2d5dc578c0992b4f3c631373479ebf3892efe53d21c4f4f1cc9a11c3536b7f75"))