Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 
 

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