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

929 lines
32 KiB

  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package tls
  5. import (
  6. "bytes"
  7. "crypto/ecdsa"
  8. "crypto/elliptic"
  9. "crypto/rsa"
  10. "encoding/hex"
  11. "encoding/pem"
  12. "errors"
  13. "fmt"
  14. "io"
  15. "math/big"
  16. "net"
  17. "os"
  18. "os/exec"
  19. "path/filepath"
  20. "strings"
  21. "testing"
  22. "time"
  23. )
  24. // zeroSource is an io.Reader that returns an unlimited number of zero bytes.
  25. type zeroSource struct{}
  26. func (zeroSource) Read(b []byte) (n int, err error) {
  27. for i := range b {
  28. b[i] = 0
  29. }
  30. return len(b), nil
  31. }
  32. var testConfig *Config
  33. func init() {
  34. testConfig = &Config{
  35. Time: func() time.Time { return time.Unix(0, 0) },
  36. Rand: zeroSource{},
  37. Certificates: make([]Certificate, 2),
  38. InsecureSkipVerify: true,
  39. MinVersion: VersionSSL30,
  40. MaxVersion: VersionTLS12,
  41. }
  42. testConfig.Certificates[0].Certificate = [][]byte{testRSACertificate}
  43. testConfig.Certificates[0].PrivateKey = testRSAPrivateKey
  44. testConfig.Certificates[1].Certificate = [][]byte{testSNICertificate}
  45. testConfig.Certificates[1].PrivateKey = testRSAPrivateKey
  46. testConfig.BuildNameToCertificate()
  47. }
  48. func testClientHelloFailure(t *testing.T, m handshakeMessage, expectedSubStr string) {
  49. // Create in-memory network connection,
  50. // send message to server. Should return
  51. // expected error.
  52. c, s := net.Pipe()
  53. go func() {
  54. cli := Client(c, testConfig)
  55. if ch, ok := m.(*clientHelloMsg); ok {
  56. cli.vers = ch.vers
  57. }
  58. cli.writeRecord(recordTypeHandshake, m.marshal())
  59. c.Close()
  60. }()
  61. err := Server(s, testConfig).Handshake()
  62. s.Close()
  63. if err == nil || !strings.Contains(err.Error(), expectedSubStr) {
  64. t.Errorf("Got error: %s; expected to match substring '%s'", err, expectedSubStr)
  65. }
  66. }
  67. func TestSimpleError(t *testing.T) {
  68. testClientHelloFailure(t, &serverHelloDoneMsg{}, "unexpected handshake message")
  69. }
  70. var badProtocolVersions = []uint16{0x0000, 0x0005, 0x0100, 0x0105, 0x0200, 0x0205}
  71. func TestRejectBadProtocolVersion(t *testing.T) {
  72. for _, v := range badProtocolVersions {
  73. testClientHelloFailure(t, &clientHelloMsg{vers: v}, "unsupported, maximum protocol version")
  74. }
  75. }
  76. func TestNoSuiteOverlap(t *testing.T) {
  77. clientHello := &clientHelloMsg{
  78. vers: 0x0301,
  79. cipherSuites: []uint16{0xff00},
  80. compressionMethods: []uint8{0},
  81. }
  82. testClientHelloFailure(t, clientHello, "no cipher suite supported by both client and server")
  83. }
  84. func TestNoCompressionOverlap(t *testing.T) {
  85. clientHello := &clientHelloMsg{
  86. vers: 0x0301,
  87. cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
  88. compressionMethods: []uint8{0xff},
  89. }
  90. testClientHelloFailure(t, clientHello, "client does not support uncompressed connections")
  91. }
  92. func TestRenegotiationExtension(t *testing.T) {
  93. clientHello := &clientHelloMsg{
  94. vers: VersionTLS12,
  95. compressionMethods: []uint8{compressionNone},
  96. random: make([]byte, 32),
  97. secureRenegotiation: true,
  98. cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
  99. }
  100. var buf []byte
  101. c, s := net.Pipe()
  102. go func() {
  103. cli := Client(c, testConfig)
  104. cli.vers = clientHello.vers
  105. cli.writeRecord(recordTypeHandshake, clientHello.marshal())
  106. buf = make([]byte, 1024)
  107. n, err := c.Read(buf)
  108. if err != nil {
  109. t.Fatalf("Server read returned error: %s", err)
  110. }
  111. buf = buf[:n]
  112. c.Close()
  113. }()
  114. Server(s, testConfig).Handshake()
  115. if len(buf) < 5+4 {
  116. t.Fatalf("Server returned short message of length %d", len(buf))
  117. }
  118. // buf contains a TLS record, with a 5 byte record header and a 4 byte
  119. // handshake header. The length of the ServerHello is taken from the
  120. // handshake header.
  121. serverHelloLen := int(buf[6])<<16 | int(buf[7])<<8 | int(buf[8])
  122. var serverHello serverHelloMsg
  123. // unmarshal expects to be given the handshake header, but
  124. // serverHelloLen doesn't include it.
  125. if !serverHello.unmarshal(buf[5 : 9+serverHelloLen]) {
  126. t.Fatalf("Failed to parse ServerHello")
  127. }
  128. if !serverHello.secureRenegotiation {
  129. t.Errorf("Secure renegotiation extension was not echoed.")
  130. }
  131. }
  132. func TestTLS12OnlyCipherSuites(t *testing.T) {
  133. // Test that a Server doesn't select a TLS 1.2-only cipher suite when
  134. // the client negotiates TLS 1.1.
  135. var zeros [32]byte
  136. clientHello := &clientHelloMsg{
  137. vers: VersionTLS11,
  138. random: zeros[:],
  139. cipherSuites: []uint16{
  140. // The Server, by default, will use the client's
  141. // preference order. So the GCM cipher suite
  142. // will be selected unless it's excluded because
  143. // of the version in this ClientHello.
  144. TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  145. TLS_RSA_WITH_RC4_128_SHA,
  146. },
  147. compressionMethods: []uint8{compressionNone},
  148. supportedCurves: []CurveID{CurveP256, CurveP384, CurveP521},
  149. supportedPoints: []uint8{pointFormatUncompressed},
  150. }
  151. c, s := net.Pipe()
  152. var reply interface{}
  153. var clientErr error
  154. go func() {
  155. cli := Client(c, testConfig)
  156. cli.vers = clientHello.vers
  157. cli.writeRecord(recordTypeHandshake, clientHello.marshal())
  158. reply, clientErr = cli.readHandshake()
  159. c.Close()
  160. }()
  161. config := *testConfig
  162. config.CipherSuites = clientHello.cipherSuites
  163. Server(s, &config).Handshake()
  164. s.Close()
  165. if clientErr != nil {
  166. t.Fatal(clientErr)
  167. }
  168. serverHello, ok := reply.(*serverHelloMsg)
  169. if !ok {
  170. t.Fatalf("didn't get ServerHello message in reply. Got %v\n", reply)
  171. }
  172. if s := serverHello.cipherSuite; s != TLS_RSA_WITH_RC4_128_SHA {
  173. t.Fatalf("bad cipher suite from server: %x", s)
  174. }
  175. }
  176. func TestAlertForwarding(t *testing.T) {
  177. c, s := net.Pipe()
  178. go func() {
  179. Client(c, testConfig).sendAlert(alertUnknownCA)
  180. c.Close()
  181. }()
  182. err := Server(s, testConfig).Handshake()
  183. s.Close()
  184. if e, ok := err.(*net.OpError); !ok || e.Err != error(alertUnknownCA) {
  185. t.Errorf("Got error: %s; expected: %s", err, error(alertUnknownCA))
  186. }
  187. }
  188. func TestClose(t *testing.T) {
  189. c, s := net.Pipe()
  190. go c.Close()
  191. err := Server(s, testConfig).Handshake()
  192. s.Close()
  193. if err != io.EOF {
  194. t.Errorf("Got error: %s; expected: %s", err, io.EOF)
  195. }
  196. }
  197. func testHandshake(clientConfig, serverConfig *Config) (state ConnectionState, err error) {
  198. c, s := net.Pipe()
  199. done := make(chan bool)
  200. go func() {
  201. cli := Client(c, clientConfig)
  202. cli.Handshake()
  203. c.Close()
  204. done <- true
  205. }()
  206. server := Server(s, serverConfig)
  207. err = server.Handshake()
  208. if err == nil {
  209. state = server.ConnectionState()
  210. }
  211. s.Close()
  212. <-done
  213. return
  214. }
  215. func TestVersion(t *testing.T) {
  216. serverConfig := &Config{
  217. Certificates: testConfig.Certificates,
  218. MaxVersion: VersionTLS11,
  219. }
  220. clientConfig := &Config{
  221. InsecureSkipVerify: true,
  222. }
  223. state, err := testHandshake(clientConfig, serverConfig)
  224. if err != nil {
  225. t.Fatalf("handshake failed: %s", err)
  226. }
  227. if state.Version != VersionTLS11 {
  228. t.Fatalf("Incorrect version %x, should be %x", state.Version, VersionTLS11)
  229. }
  230. }
  231. func TestCipherSuitePreference(t *testing.T) {
  232. serverConfig := &Config{
  233. CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA},
  234. Certificates: testConfig.Certificates,
  235. MaxVersion: VersionTLS11,
  236. }
  237. clientConfig := &Config{
  238. CipherSuites: []uint16{TLS_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_RC4_128_SHA},
  239. InsecureSkipVerify: true,
  240. }
  241. state, err := testHandshake(clientConfig, serverConfig)
  242. if err != nil {
  243. t.Fatalf("handshake failed: %s", err)
  244. }
  245. if state.CipherSuite != TLS_RSA_WITH_AES_128_CBC_SHA {
  246. // By default the server should use the client's preference.
  247. t.Fatalf("Client's preference was not used, got %x", state.CipherSuite)
  248. }
  249. serverConfig.PreferServerCipherSuites = true
  250. state, err = testHandshake(clientConfig, serverConfig)
  251. if err != nil {
  252. t.Fatalf("handshake failed: %s", err)
  253. }
  254. if state.CipherSuite != TLS_RSA_WITH_RC4_128_SHA {
  255. t.Fatalf("Server's preference was not used, got %x", state.CipherSuite)
  256. }
  257. }
  258. // Note: see comment in handshake_test.go for details of how the reference
  259. // tests work.
  260. // serverTest represents a test of the TLS server handshake against a reference
  261. // implementation.
  262. type serverTest struct {
  263. // name is a freeform string identifying the test and the file in which
  264. // the expected results will be stored.
  265. name string
  266. // command, if not empty, contains a series of arguments for the
  267. // command to run for the reference server.
  268. command []string
  269. // expectedPeerCerts contains a list of PEM blocks of expected
  270. // certificates from the client.
  271. expectedPeerCerts []string
  272. // config, if not nil, contains a custom Config to use for this test.
  273. config *Config
  274. // expectAlert, if true, indicates that a fatal alert should be returned
  275. // when handshaking with the server.
  276. expectAlert bool
  277. // expectHandshakeErrorIncluding, when not empty, contains a string
  278. // that must be a substring of the error resulting from the handshake.
  279. expectHandshakeErrorIncluding string
  280. // validate, if not nil, is a function that will be called with the
  281. // ConnectionState of the resulting connection. It returns false if the
  282. // ConnectionState is unacceptable.
  283. validate func(ConnectionState) error
  284. }
  285. var defaultClientCommand = []string{"openssl", "s_client", "-no_ticket"}
  286. // connFromCommand starts opens a listening socket and starts the reference
  287. // client to connect to it. It returns a recordingConn that wraps the resulting
  288. // connection.
  289. func (test *serverTest) connFromCommand() (conn *recordingConn, child *exec.Cmd, err error) {
  290. l, err := net.ListenTCP("tcp", &net.TCPAddr{
  291. IP: net.IPv4(127, 0, 0, 1),
  292. Port: 0,
  293. })
  294. if err != nil {
  295. return nil, nil, err
  296. }
  297. defer l.Close()
  298. port := l.Addr().(*net.TCPAddr).Port
  299. var command []string
  300. command = append(command, test.command...)
  301. if len(command) == 0 {
  302. command = defaultClientCommand
  303. }
  304. command = append(command, "-connect")
  305. command = append(command, fmt.Sprintf("127.0.0.1:%d", port))
  306. cmd := exec.Command(command[0], command[1:]...)
  307. cmd.Stdin = nil
  308. var output bytes.Buffer
  309. cmd.Stdout = &output
  310. cmd.Stderr = &output
  311. if err := cmd.Start(); err != nil {
  312. return nil, nil, err
  313. }
  314. connChan := make(chan interface{})
  315. go func() {
  316. tcpConn, err := l.Accept()
  317. if err != nil {
  318. connChan <- err
  319. }
  320. connChan <- tcpConn
  321. }()
  322. var tcpConn net.Conn
  323. select {
  324. case connOrError := <-connChan:
  325. if err, ok := connOrError.(error); ok {
  326. return nil, nil, err
  327. }
  328. tcpConn = connOrError.(net.Conn)
  329. case <-time.After(2 * time.Second):
  330. output.WriteTo(os.Stdout)
  331. return nil, nil, errors.New("timed out waiting for connection from child process")
  332. }
  333. record := &recordingConn{
  334. Conn: tcpConn,
  335. }
  336. return record, cmd, nil
  337. }
  338. func (test *serverTest) dataPath() string {
  339. return filepath.Join("testdata", "Server-"+test.name)
  340. }
  341. func (test *serverTest) loadData() (flows [][]byte, err error) {
  342. in, err := os.Open(test.dataPath())
  343. if err != nil {
  344. return nil, err
  345. }
  346. defer in.Close()
  347. return parseTestData(in)
  348. }
  349. func (test *serverTest) run(t *testing.T, write bool) {
  350. var clientConn, serverConn net.Conn
  351. var recordingConn *recordingConn
  352. var childProcess *exec.Cmd
  353. if write {
  354. var err error
  355. recordingConn, childProcess, err = test.connFromCommand()
  356. if err != nil {
  357. t.Fatalf("Failed to start subcommand: %s", err)
  358. }
  359. serverConn = recordingConn
  360. } else {
  361. clientConn, serverConn = net.Pipe()
  362. }
  363. config := test.config
  364. if config == nil {
  365. config = testConfig
  366. }
  367. server := Server(serverConn, config)
  368. connStateChan := make(chan ConnectionState, 1)
  369. go func() {
  370. var err error
  371. if _, err = server.Write([]byte("hello, world\n")); err != nil {
  372. t.Logf("Error from Server.Write: %s", err)
  373. }
  374. if len(test.expectHandshakeErrorIncluding) > 0 {
  375. if err == nil {
  376. t.Errorf("Error expected, but no error returned")
  377. } else if s := err.Error(); !strings.Contains(s, test.expectHandshakeErrorIncluding) {
  378. t.Errorf("Error expected containing '%s' but got '%s'", test.expectHandshakeErrorIncluding, s)
  379. }
  380. }
  381. server.Close()
  382. serverConn.Close()
  383. connStateChan <- server.ConnectionState()
  384. }()
  385. if !write {
  386. flows, err := test.loadData()
  387. if err != nil {
  388. if !test.expectAlert {
  389. t.Fatalf("%s: failed to load data from %s", test.name, test.dataPath())
  390. }
  391. }
  392. for i, b := range flows {
  393. if i%2 == 0 {
  394. clientConn.Write(b)
  395. continue
  396. }
  397. bb := make([]byte, len(b))
  398. n, err := io.ReadFull(clientConn, bb)
  399. if test.expectAlert {
  400. if err == nil {
  401. t.Fatal("Expected read failure but read succeeded")
  402. }
  403. } else {
  404. if err != nil {
  405. 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)
  406. }
  407. if !bytes.Equal(b, bb) {
  408. t.Fatalf("%s #%d: mismatch on read: got:%x want:%x", test.name, i+1, bb, b)
  409. }
  410. }
  411. }
  412. clientConn.Close()
  413. }
  414. connState := <-connStateChan
  415. peerCerts := connState.PeerCertificates
  416. if len(peerCerts) == len(test.expectedPeerCerts) {
  417. for i, peerCert := range peerCerts {
  418. block, _ := pem.Decode([]byte(test.expectedPeerCerts[i]))
  419. if !bytes.Equal(block.Bytes, peerCert.Raw) {
  420. t.Fatalf("%s: mismatch on peer cert %d", test.name, i+1)
  421. }
  422. }
  423. } else {
  424. t.Fatalf("%s: mismatch on peer list length: %d (wanted) != %d (got)", test.name, len(test.expectedPeerCerts), len(peerCerts))
  425. }
  426. if test.validate != nil {
  427. if err := test.validate(connState); err != nil {
  428. t.Fatalf("validate callback returned error: %s", err)
  429. }
  430. }
  431. if write {
  432. path := test.dataPath()
  433. out, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
  434. if err != nil {
  435. t.Fatalf("Failed to create output file: %s", err)
  436. }
  437. defer out.Close()
  438. recordingConn.Close()
  439. if len(recordingConn.flows) < 3 {
  440. childProcess.Stdout.(*bytes.Buffer).WriteTo(os.Stdout)
  441. if len(test.expectHandshakeErrorIncluding) == 0 {
  442. t.Fatalf("Handshake failed")
  443. }
  444. }
  445. recordingConn.WriteTo(out)
  446. fmt.Printf("Wrote %s\n", path)
  447. childProcess.Wait()
  448. }
  449. }
  450. func runServerTestForVersion(t *testing.T, template *serverTest, prefix, option string) {
  451. test := *template
  452. test.name = prefix + test.name
  453. if len(test.command) == 0 {
  454. test.command = defaultClientCommand
  455. }
  456. test.command = append([]string(nil), test.command...)
  457. test.command = append(test.command, option)
  458. test.run(t, *update)
  459. }
  460. func runServerTestSSLv3(t *testing.T, template *serverTest) {
  461. runServerTestForVersion(t, template, "SSLv3-", "-ssl3")
  462. }
  463. func runServerTestTLS10(t *testing.T, template *serverTest) {
  464. runServerTestForVersion(t, template, "TLSv10-", "-tls1")
  465. }
  466. func runServerTestTLS11(t *testing.T, template *serverTest) {
  467. runServerTestForVersion(t, template, "TLSv11-", "-tls1_1")
  468. }
  469. func runServerTestTLS12(t *testing.T, template *serverTest) {
  470. runServerTestForVersion(t, template, "TLSv12-", "-tls1_2")
  471. }
  472. func TestHandshakeServerRSARC4(t *testing.T) {
  473. test := &serverTest{
  474. name: "RSA-RC4",
  475. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "RC4-SHA"},
  476. }
  477. runServerTestSSLv3(t, test)
  478. runServerTestTLS10(t, test)
  479. runServerTestTLS11(t, test)
  480. runServerTestTLS12(t, test)
  481. }
  482. func TestHandshakeServerRSA3DES(t *testing.T) {
  483. test := &serverTest{
  484. name: "RSA-3DES",
  485. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "DES-CBC3-SHA"},
  486. }
  487. runServerTestSSLv3(t, test)
  488. runServerTestTLS10(t, test)
  489. runServerTestTLS12(t, test)
  490. }
  491. func TestHandshakeServerRSAAES(t *testing.T) {
  492. test := &serverTest{
  493. name: "RSA-AES",
  494. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA"},
  495. }
  496. runServerTestSSLv3(t, test)
  497. runServerTestTLS10(t, test)
  498. runServerTestTLS12(t, test)
  499. }
  500. func TestHandshakeServerAESGCM(t *testing.T) {
  501. test := &serverTest{
  502. name: "RSA-AES-GCM",
  503. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-AES128-GCM-SHA256"},
  504. }
  505. runServerTestTLS12(t, test)
  506. }
  507. func TestHandshakeServerAES256GCMSHA384(t *testing.T) {
  508. test := &serverTest{
  509. name: "RSA-AES256-GCM-SHA384",
  510. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-AES256-GCM-SHA384"},
  511. }
  512. runServerTestTLS12(t, test)
  513. }
  514. func TestHandshakeServerECDHEECDSAAES(t *testing.T) {
  515. config := *testConfig
  516. config.Certificates = make([]Certificate, 1)
  517. config.Certificates[0].Certificate = [][]byte{testECDSACertificate}
  518. config.Certificates[0].PrivateKey = testECDSAPrivateKey
  519. config.BuildNameToCertificate()
  520. test := &serverTest{
  521. name: "ECDHE-ECDSA-AES",
  522. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-ECDSA-AES256-SHA"},
  523. config: &config,
  524. }
  525. runServerTestTLS10(t, test)
  526. runServerTestTLS12(t, test)
  527. }
  528. func TestHandshakeServerALPN(t *testing.T) {
  529. config := *testConfig
  530. config.NextProtos = []string{"proto1", "proto2"}
  531. test := &serverTest{
  532. name: "ALPN",
  533. // Note that this needs OpenSSL 1.0.2 because that is the first
  534. // version that supports the -alpn flag.
  535. command: []string{"openssl", "s_client", "-alpn", "proto2,proto1"},
  536. config: &config,
  537. validate: func(state ConnectionState) error {
  538. // The server's preferences should override the client.
  539. if state.NegotiatedProtocol != "proto1" {
  540. return fmt.Errorf("Got protocol %q, wanted proto1", state.NegotiatedProtocol)
  541. }
  542. return nil
  543. },
  544. }
  545. runServerTestTLS12(t, test)
  546. }
  547. func TestHandshakeServerALPNNoMatch(t *testing.T) {
  548. config := *testConfig
  549. config.NextProtos = []string{"proto3"}
  550. test := &serverTest{
  551. name: "ALPN-NoMatch",
  552. // Note that this needs OpenSSL 1.0.2 because that is the first
  553. // version that supports the -alpn flag.
  554. command: []string{"openssl", "s_client", "-alpn", "proto2,proto1"},
  555. config: &config,
  556. validate: func(state ConnectionState) error {
  557. // Rather than reject the connection, Go doesn't select
  558. // a protocol when there is no overlap.
  559. if state.NegotiatedProtocol != "" {
  560. return fmt.Errorf("Got protocol %q, wanted ''", state.NegotiatedProtocol)
  561. }
  562. return nil
  563. },
  564. }
  565. runServerTestTLS12(t, test)
  566. }
  567. // TestHandshakeServerSNI involves a client sending an SNI extension of
  568. // "snitest.com", which happens to match the CN of testSNICertificate. The test
  569. // verifies that the server correctly selects that certificate.
  570. func TestHandshakeServerSNI(t *testing.T) {
  571. test := &serverTest{
  572. name: "SNI",
  573. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"},
  574. }
  575. runServerTestTLS12(t, test)
  576. }
  577. // TestHandshakeServerSNICertForName is similar to TestHandshakeServerSNI, but
  578. // tests the dynamic GetCertificate method
  579. func TestHandshakeServerSNIGetCertificate(t *testing.T) {
  580. config := *testConfig
  581. // Replace the NameToCertificate map with a GetCertificate function
  582. nameToCert := config.NameToCertificate
  583. config.NameToCertificate = nil
  584. config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
  585. cert, _ := nameToCert[clientHello.ServerName]
  586. return cert, nil
  587. }
  588. test := &serverTest{
  589. name: "SNI",
  590. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"},
  591. config: &config,
  592. }
  593. runServerTestTLS12(t, test)
  594. }
  595. // TestHandshakeServerSNICertForNameNotFound is similar to
  596. // TestHandshakeServerSNICertForName, but tests to make sure that when the
  597. // GetCertificate method doesn't return a cert, we fall back to what's in
  598. // the NameToCertificate map.
  599. func TestHandshakeServerSNIGetCertificateNotFound(t *testing.T) {
  600. config := *testConfig
  601. config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
  602. return nil, nil
  603. }
  604. test := &serverTest{
  605. name: "SNI",
  606. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"},
  607. config: &config,
  608. }
  609. runServerTestTLS12(t, test)
  610. }
  611. // TestHandshakeServerSNICertForNameError tests to make sure that errors in
  612. // GetCertificate result in a tls alert.
  613. func TestHandshakeServerSNIGetCertificateError(t *testing.T) {
  614. config := *testConfig
  615. config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
  616. return nil, fmt.Errorf("Test error in GetCertificate")
  617. }
  618. test := &serverTest{
  619. name: "SNI",
  620. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"},
  621. config: &config,
  622. expectAlert: true,
  623. }
  624. runServerTestTLS12(t, test)
  625. }
  626. // TestCipherSuiteCertPreferance ensures that we select an RSA ciphersuite with
  627. // an RSA certificate and an ECDSA ciphersuite with an ECDSA certificate.
  628. func TestCipherSuiteCertPreferenceECDSA(t *testing.T) {
  629. config := *testConfig
  630. config.CipherSuites = []uint16{TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA}
  631. config.PreferServerCipherSuites = true
  632. test := &serverTest{
  633. name: "CipherSuiteCertPreferenceRSA",
  634. config: &config,
  635. }
  636. runServerTestTLS12(t, test)
  637. config = *testConfig
  638. config.CipherSuites = []uint16{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA}
  639. config.Certificates = []Certificate{
  640. {
  641. Certificate: [][]byte{testECDSACertificate},
  642. PrivateKey: testECDSAPrivateKey,
  643. },
  644. }
  645. config.BuildNameToCertificate()
  646. config.PreferServerCipherSuites = true
  647. test = &serverTest{
  648. name: "CipherSuiteCertPreferenceECDSA",
  649. config: &config,
  650. }
  651. runServerTestTLS12(t, test)
  652. }
  653. func TestResumption(t *testing.T) {
  654. sessionFilePath := tempFile("")
  655. defer os.Remove(sessionFilePath)
  656. test := &serverTest{
  657. name: "IssueTicket",
  658. command: []string{"openssl", "s_client", "-cipher", "RC4-SHA", "-sess_out", sessionFilePath},
  659. }
  660. runServerTestTLS12(t, test)
  661. test = &serverTest{
  662. name: "Resume",
  663. command: []string{"openssl", "s_client", "-cipher", "RC4-SHA", "-sess_in", sessionFilePath},
  664. }
  665. runServerTestTLS12(t, test)
  666. }
  667. func TestResumptionDisabled(t *testing.T) {
  668. sessionFilePath := tempFile("")
  669. defer os.Remove(sessionFilePath)
  670. config := *testConfig
  671. test := &serverTest{
  672. name: "IssueTicketPreDisable",
  673. command: []string{"openssl", "s_client", "-cipher", "RC4-SHA", "-sess_out", sessionFilePath},
  674. config: &config,
  675. }
  676. runServerTestTLS12(t, test)
  677. config.SessionTicketsDisabled = true
  678. test = &serverTest{
  679. name: "ResumeDisabled",
  680. command: []string{"openssl", "s_client", "-cipher", "RC4-SHA", "-sess_in", sessionFilePath},
  681. config: &config,
  682. }
  683. runServerTestTLS12(t, test)
  684. // One needs to manually confirm that the handshake in the golden data
  685. // file for ResumeDisabled does not include a resumption handshake.
  686. }
  687. func TestFallbackSCSV(t *testing.T) {
  688. serverConfig := &Config{
  689. Certificates: testConfig.Certificates,
  690. }
  691. test := &serverTest{
  692. name: "FallbackSCSV",
  693. config: serverConfig,
  694. // OpenSSL 1.0.1j is needed for the -fallback_scsv option.
  695. command: []string{"openssl", "s_client", "-fallback_scsv"},
  696. expectHandshakeErrorIncluding: "inappropriate protocol fallback",
  697. }
  698. runServerTestTLS11(t, test)
  699. }
  700. // cert.pem and key.pem were generated with generate_cert.go
  701. // Thus, they have no ExtKeyUsage fields and trigger an error
  702. // when verification is turned on.
  703. const clientCertificatePEM = `
  704. -----BEGIN CERTIFICATE-----
  705. MIIB7TCCAVigAwIBAgIBADALBgkqhkiG9w0BAQUwJjEQMA4GA1UEChMHQWNtZSBD
  706. bzESMBAGA1UEAxMJMTI3LjAuMC4xMB4XDTExMTIwODA3NTUxMloXDTEyMTIwNzA4
  707. MDAxMlowJjEQMA4GA1UEChMHQWNtZSBDbzESMBAGA1UEAxMJMTI3LjAuMC4xMIGc
  708. MAsGCSqGSIb3DQEBAQOBjAAwgYgCgYBO0Hsx44Jk2VnAwoekXh6LczPHY1PfZpIG
  709. hPZk1Y/kNqcdK+izIDZFI7Xjla7t4PUgnI2V339aEu+H5Fto5OkOdOwEin/ekyfE
  710. ARl6vfLcPRSr0FTKIQzQTW6HLlzF0rtNS0/Otiz3fojsfNcCkXSmHgwa2uNKWi7e
  711. E5xMQIhZkwIDAQABozIwMDAOBgNVHQ8BAf8EBAMCAKAwDQYDVR0OBAYEBAECAwQw
  712. DwYDVR0jBAgwBoAEAQIDBDALBgkqhkiG9w0BAQUDgYEANh+zegx1yW43RmEr1b3A
  713. p0vMRpqBWHyFeSnIyMZn3TJWRSt1tukkqVCavh9a+hoV2cxVlXIWg7nCto/9iIw4
  714. hB2rXZIxE0/9gzvGnfERYraL7KtnvshksBFQRlgXa5kc0x38BvEO5ZaoDPl4ILdE
  715. GFGNEH5PlGffo05wc46QkYU=
  716. -----END CERTIFICATE-----`
  717. const clientKeyPEM = `
  718. -----BEGIN RSA PRIVATE KEY-----
  719. MIICWgIBAAKBgE7QezHjgmTZWcDCh6ReHotzM8djU99mkgaE9mTVj+Q2px0r6LMg
  720. NkUjteOVru3g9SCcjZXff1oS74fkW2jk6Q507ASKf96TJ8QBGXq98tw9FKvQVMoh
  721. DNBNbocuXMXSu01LT862LPd+iOx81wKRdKYeDBra40paLt4TnExAiFmTAgMBAAEC
  722. gYBxvXd8yNteFTns8A/2yomEMC4yeosJJSpp1CsN3BJ7g8/qTnrVPxBy+RU+qr63
  723. t2WquaOu/cr5P8iEsa6lk20tf8pjKLNXeX0b1RTzK8rJLbS7nGzP3tvOhL096VtQ
  724. dAo4ROEaro0TzYpHmpciSvxVIeEIAAdFDObDJPKqcJAxyQJBAJizfYgK8Gzx9fsx
  725. hxp+VteCbVPg2euASH5Yv3K5LukRdKoSzHE2grUVQgN/LafC0eZibRanxHegYSr7
  726. 7qaswKUCQQCEIWor/X4XTMdVj3Oj+vpiw75y/S9gh682+myZL+d/02IEkwnB098P
  727. RkKVpenBHyrGg0oeN5La7URILWKj7CPXAkBKo6F+d+phNjwIFoN1Xb/RA32w/D1I
  728. saG9sF+UEhRt9AxUfW/U/tIQ9V0ZHHcSg1XaCM5Nvp934brdKdvTOKnJAkBD5h/3
  729. Rybatlvg/fzBEaJFyq09zhngkxlZOUtBVTqzl17RVvY2orgH02U4HbCHy4phxOn7
  730. qTdQRYlHRftgnWK1AkANibn9PRYJ7mJyJ9Dyj2QeNcSkSTzrt0tPvUMf4+meJymN
  731. 1Ntu5+S1DLLzfxlaljWG6ylW6DNxujCyuXIV2rvA
  732. -----END RSA PRIVATE KEY-----`
  733. const clientECDSACertificatePEM = `
  734. -----BEGIN CERTIFICATE-----
  735. MIIB/DCCAV4CCQCaMIRsJjXZFzAJBgcqhkjOPQQBMEUxCzAJBgNVBAYTAkFVMRMw
  736. EQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0
  737. eSBMdGQwHhcNMTIxMTE0MTMyNTUzWhcNMjIxMTEyMTMyNTUzWjBBMQswCQYDVQQG
  738. EwJBVTEMMAoGA1UECBMDTlNXMRAwDgYDVQQHEwdQeXJtb250MRIwEAYDVQQDEwlK
  739. b2VsIFNpbmcwgZswEAYHKoZIzj0CAQYFK4EEACMDgYYABACVjJF1FMBexFe01MNv
  740. ja5oHt1vzobhfm6ySD6B5U7ixohLZNz1MLvT/2XMW/TdtWo+PtAd3kfDdq0Z9kUs
  741. jLzYHQFMH3CQRnZIi4+DzEpcj0B22uCJ7B0rxE4wdihBsmKo+1vx+U56jb0JuK7q
  742. ixgnTy5w/hOWusPTQBbNZU6sER7m8TAJBgcqhkjOPQQBA4GMADCBiAJCAOAUxGBg
  743. C3JosDJdYUoCdFzCgbkWqD8pyDbHgf9stlvZcPE4O1BIKJTLCRpS8V3ujfK58PDa
  744. 2RU6+b0DeoeiIzXsAkIBo9SKeDUcSpoj0gq+KxAxnZxfvuiRs9oa9V2jI/Umi0Vw
  745. jWVim34BmT0Y9hCaOGGbLlfk+syxis7iI6CH8OFnUes=
  746. -----END CERTIFICATE-----`
  747. const clientECDSAKeyPEM = `
  748. -----BEGIN EC PARAMETERS-----
  749. BgUrgQQAIw==
  750. -----END EC PARAMETERS-----
  751. -----BEGIN EC PRIVATE KEY-----
  752. MIHcAgEBBEIBkJN9X4IqZIguiEVKMqeBUP5xtRsEv4HJEtOpOGLELwO53SD78Ew8
  753. k+wLWoqizS3NpQyMtrU8JFdWfj+C57UNkOugBwYFK4EEACOhgYkDgYYABACVjJF1
  754. FMBexFe01MNvja5oHt1vzobhfm6ySD6B5U7ixohLZNz1MLvT/2XMW/TdtWo+PtAd
  755. 3kfDdq0Z9kUsjLzYHQFMH3CQRnZIi4+DzEpcj0B22uCJ7B0rxE4wdihBsmKo+1vx
  756. +U56jb0JuK7qixgnTy5w/hOWusPTQBbNZU6sER7m8Q==
  757. -----END EC PRIVATE KEY-----`
  758. func TestClientAuth(t *testing.T) {
  759. var certPath, keyPath, ecdsaCertPath, ecdsaKeyPath string
  760. if *update {
  761. certPath = tempFile(clientCertificatePEM)
  762. defer os.Remove(certPath)
  763. keyPath = tempFile(clientKeyPEM)
  764. defer os.Remove(keyPath)
  765. ecdsaCertPath = tempFile(clientECDSACertificatePEM)
  766. defer os.Remove(ecdsaCertPath)
  767. ecdsaKeyPath = tempFile(clientECDSAKeyPEM)
  768. defer os.Remove(ecdsaKeyPath)
  769. }
  770. config := *testConfig
  771. config.ClientAuth = RequestClientCert
  772. test := &serverTest{
  773. name: "ClientAuthRequestedNotGiven",
  774. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "RC4-SHA"},
  775. config: &config,
  776. }
  777. runServerTestTLS12(t, test)
  778. test = &serverTest{
  779. name: "ClientAuthRequestedAndGiven",
  780. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "RC4-SHA", "-cert", certPath, "-key", keyPath},
  781. config: &config,
  782. expectedPeerCerts: []string{clientCertificatePEM},
  783. }
  784. runServerTestTLS12(t, test)
  785. test = &serverTest{
  786. name: "ClientAuthRequestedAndECDSAGiven",
  787. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "RC4-SHA", "-cert", ecdsaCertPath, "-key", ecdsaKeyPath},
  788. config: &config,
  789. expectedPeerCerts: []string{clientECDSACertificatePEM},
  790. }
  791. runServerTestTLS12(t, test)
  792. }
  793. func bigFromString(s string) *big.Int {
  794. ret := new(big.Int)
  795. ret.SetString(s, 10)
  796. return ret
  797. }
  798. func fromHex(s string) []byte {
  799. b, _ := hex.DecodeString(s)
  800. return b
  801. }
  802. var testRSACertificate = fromHex("308202b030820219a00302010202090085b0bba48a7fb8ca300d06092a864886f70d01010505003045310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c7464301e170d3130303432343039303933385a170d3131303432343039303933385a3045310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c746430819f300d06092a864886f70d010101050003818d0030818902818100bb79d6f517b5e5bf4610d0dc69bee62b07435ad0032d8a7a4385b71452e7a5654c2c78b8238cb5b482e5de1f953b7e62a52ca533d6fe125c7a56fcf506bffa587b263fb5cd04d3d0c921964ac7f4549f5abfef427100fe1899077f7e887d7df10439c4a22edb51c97ce3c04c3b326601cfafb11db8719a1ddbdb896baeda2d790203010001a381a73081a4301d0603551d0e04160414b1ade2855acfcb28db69ce2369ded3268e18883930750603551d23046e306c8014b1ade2855acfcb28db69ce2369ded3268e188839a149a4473045310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c746482090085b0bba48a7fb8ca300c0603551d13040530030101ff300d06092a864886f70d010105050003818100086c4524c76bb159ab0c52ccf2b014d7879d7a6475b55a9566e4c52b8eae12661feb4f38b36e60d392fdf74108b52513b1187a24fb301dbaed98b917ece7d73159db95d31d78ea50565cd5825a2d5a5f33c4b6d8c97590968c0f5298b5cd981f89205ff2a01ca31b9694dda9fd57e970e8266d71999b266e3850296c90a7bdd9")
  803. var testECDSACertificate = fromHex("3082020030820162020900b8bf2d47a0d2ebf4300906072a8648ce3d04013045310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c7464301e170d3132313132323135303633325a170d3232313132303135303633325a3045310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c746430819b301006072a8648ce3d020106052b81040023038186000400c4a1edbe98f90b4873367ec316561122f23d53c33b4d213dcd6b75e6f6b0dc9adf26c1bcb287f072327cb3642f1c90bcea6823107efee325c0483a69e0286dd33700ef0462dd0da09c706283d881d36431aa9e9731bd96b068c09b23de76643f1a5c7fe9120e5858b65f70dd9bd8ead5d7f5d5ccb9b69f30665b669a20e227e5bffe3b300906072a8648ce3d040103818c0030818802420188a24febe245c5487d1bacf5ed989dae4770c05e1bb62fbdf1b64db76140d311a2ceee0b7e927eff769dc33b7ea53fcefa10e259ec472d7cacda4e970e15a06fd00242014dfcbe67139c2d050ebd3fa38c25c13313830d9406bbd4377af6ec7ac9862eddd711697f857c56defb31782be4c7780daecbbe9e4e3624317b6a0f399512078f2a")
  804. var testSNICertificate = fromHex("308201f23082015da003020102020100300b06092a864886f70d01010530283110300e060355040a130741636d6520436f311430120603550403130b736e69746573742e636f6d301e170d3132303431313137343033355a170d3133303431313137343533355a30283110300e060355040a130741636d6520436f311430120603550403130b736e69746573742e636f6d30819d300b06092a864886f70d01010103818d0030818902818100bb79d6f517b5e5bf4610d0dc69bee62b07435ad0032d8a7a4385b71452e7a5654c2c78b8238cb5b482e5de1f953b7e62a52ca533d6fe125c7a56fcf506bffa587b263fb5cd04d3d0c921964ac7f4549f5abfef427100fe1899077f7e887d7df10439c4a22edb51c97ce3c04c3b326601cfafb11db8719a1ddbdb896baeda2d790203010001a3323030300e0603551d0f0101ff0404030200a0300d0603551d0e0406040401020304300f0603551d2304083006800401020304300b06092a864886f70d0101050381810089c6455f1c1f5ef8eb1ab174ee2439059f5c4259bb1a8d86cdb1d056f56a717da40e95ab90f59e8deaf627c157995094db0802266eb34fc6842dea8a4b68d9c1389103ab84fb9e1f85d9b5d23ff2312c8670fbb540148245a4ebafe264d90c8a4cf4f85b0fac12ac2fc4a3154bad52462868af96c62c6525d652b6e31845bdcc")
  805. var testRSAPrivateKey = &rsa.PrivateKey{
  806. PublicKey: rsa.PublicKey{
  807. N: bigFromString("131650079503776001033793877885499001334664249354723305978524647182322416328664556247316495448366990052837680518067798333412266673813370895702118944398081598789828837447552603077848001020611640547221687072142537202428102790818451901395596882588063427854225330436740647715202971973145151161964464812406232198521"),
  808. E: 65537,
  809. },
  810. D: bigFromString("29354450337804273969007277378287027274721892607543397931919078829901848876371746653677097639302788129485893852488285045793268732234230875671682624082413996177431586734171663258657462237320300610850244186316880055243099640544518318093544057213190320837094958164973959123058337475052510833916491060913053867729"),
  811. Primes: []*big.Int{
  812. bigFromString("11969277782311800166562047708379380720136961987713178380670422671426759650127150688426177829077494755200794297055316163155755835813760102405344560929062149"),
  813. bigFromString("10998999429884441391899182616418192492905073053684657075974935218461686523870125521822756579792315215543092255516093840728890783887287417039645833477273829"),
  814. },
  815. }
  816. var testECDSAPrivateKey = &ecdsa.PrivateKey{
  817. PublicKey: ecdsa.PublicKey{
  818. Curve: elliptic.P521(),
  819. X: bigFromString("2636411247892461147287360222306590634450676461695221912739908880441342231985950069527906976759812296359387337367668045707086543273113073382714101597903639351"),
  820. Y: bigFromString("3204695818431246682253994090650952614555094516658732116404513121125038617915183037601737180082382202488628239201196033284060130040574800684774115478859677243"),
  821. },
  822. D: bigFromString("5477294338614160138026852784385529180817726002953041720191098180813046231640184669647735805135001309477695746518160084669446643325196003346204701381388769751"),
  823. }