Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

1581 linhas
43 KiB

  1. // Copyright 2010 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/rsa"
  9. "crypto/x509"
  10. "encoding/base64"
  11. "encoding/binary"
  12. "encoding/pem"
  13. "errors"
  14. "fmt"
  15. "io"
  16. "math/big"
  17. "net"
  18. "os"
  19. "os/exec"
  20. "path/filepath"
  21. "strconv"
  22. "strings"
  23. "sync"
  24. "testing"
  25. "time"
  26. )
  27. // Note: see comment in handshake_test.go for details of how the reference
  28. // tests work.
  29. // opensslInputEvent enumerates possible inputs that can be sent to an `openssl
  30. // s_client` process.
  31. type opensslInputEvent int
  32. const (
  33. // opensslRenegotiate causes OpenSSL to request a renegotiation of the
  34. // connection.
  35. opensslRenegotiate opensslInputEvent = iota
  36. // opensslSendBanner causes OpenSSL to send the contents of
  37. // opensslSentinel on the connection.
  38. opensslSendSentinel
  39. )
  40. const opensslSentinel = "SENTINEL\n"
  41. type opensslInput chan opensslInputEvent
  42. func (i opensslInput) Read(buf []byte) (n int, err error) {
  43. for event := range i {
  44. switch event {
  45. case opensslRenegotiate:
  46. return copy(buf, []byte("R\n")), nil
  47. case opensslSendSentinel:
  48. return copy(buf, []byte(opensslSentinel)), nil
  49. default:
  50. panic("unknown event")
  51. }
  52. }
  53. return 0, io.EOF
  54. }
  55. // opensslOutputSink is an io.Writer that receives the stdout and stderr from
  56. // an `openssl` process and sends a value to handshakeComplete when it sees a
  57. // log message from a completed server handshake.
  58. type opensslOutputSink struct {
  59. handshakeComplete chan struct{}
  60. all []byte
  61. line []byte
  62. }
  63. func newOpensslOutputSink() *opensslOutputSink {
  64. return &opensslOutputSink{make(chan struct{}), nil, nil}
  65. }
  66. // opensslEndOfHandshake is a message that the “openssl s_server” tool will
  67. // print when a handshake completes if run with “-state”.
  68. const opensslEndOfHandshake = "SSL_accept:SSLv3/TLS write finished"
  69. func (o *opensslOutputSink) Write(data []byte) (n int, err error) {
  70. o.line = append(o.line, data...)
  71. o.all = append(o.all, data...)
  72. for {
  73. i := bytes.IndexByte(o.line, '\n')
  74. if i < 0 {
  75. break
  76. }
  77. if bytes.Equal([]byte(opensslEndOfHandshake), o.line[:i]) {
  78. o.handshakeComplete <- struct{}{}
  79. }
  80. o.line = o.line[i+1:]
  81. }
  82. return len(data), nil
  83. }
  84. func (o *opensslOutputSink) WriteTo(w io.Writer) (int64, error) {
  85. n, err := w.Write(o.all)
  86. return int64(n), err
  87. }
  88. // clientTest represents a test of the TLS client handshake against a reference
  89. // implementation.
  90. type clientTest struct {
  91. // name is a freeform string identifying the test and the file in which
  92. // the expected results will be stored.
  93. name string
  94. // command, if not empty, contains a series of arguments for the
  95. // command to run for the reference server.
  96. command []string
  97. // config, if not nil, contains a custom Config to use for this test.
  98. config *Config
  99. // cert, if not empty, contains a DER-encoded certificate for the
  100. // reference server.
  101. cert []byte
  102. // key, if not nil, contains either a *rsa.PrivateKey or
  103. // *ecdsa.PrivateKey which is the private key for the reference server.
  104. key interface{}
  105. // extensions, if not nil, contains a list of extension data to be returned
  106. // from the ServerHello. The data should be in standard TLS format with
  107. // a 2-byte uint16 type, 2-byte data length, followed by the extension data.
  108. extensions [][]byte
  109. // validate, if not nil, is a function that will be called with the
  110. // ConnectionState of the resulting connection. It returns a non-nil
  111. // error if the ConnectionState is unacceptable.
  112. validate func(ConnectionState) error
  113. // numRenegotiations is the number of times that the connection will be
  114. // renegotiated.
  115. numRenegotiations int
  116. // renegotiationExpectedToFail, if not zero, is the number of the
  117. // renegotiation attempt that is expected to fail.
  118. renegotiationExpectedToFail int
  119. // checkRenegotiationError, if not nil, is called with any error
  120. // arising from renegotiation. It can map expected errors to nil to
  121. // ignore them.
  122. checkRenegotiationError func(renegotiationNum int, err error) error
  123. }
  124. var defaultServerCommand = []string{"openssl", "s_server"}
  125. // connFromCommand starts the reference server process, connects to it and
  126. // returns a recordingConn for the connection. The stdin return value is an
  127. // opensslInput for the stdin of the child process. It must be closed before
  128. // Waiting for child.
  129. func (test *clientTest) connFromCommand() (conn *recordingConn, child *exec.Cmd, stdin opensslInput, stdout *opensslOutputSink, err error) {
  130. cert := testRSACertificate
  131. if len(test.cert) > 0 {
  132. cert = test.cert
  133. }
  134. certPath := tempFile(string(cert))
  135. defer os.Remove(certPath)
  136. var key interface{} = testRSAPrivateKey
  137. if test.key != nil {
  138. key = test.key
  139. }
  140. var pemType string
  141. var derBytes []byte
  142. switch key := key.(type) {
  143. case *rsa.PrivateKey:
  144. pemType = "RSA"
  145. derBytes = x509.MarshalPKCS1PrivateKey(key)
  146. case *ecdsa.PrivateKey:
  147. pemType = "EC"
  148. var err error
  149. derBytes, err = x509.MarshalECPrivateKey(key)
  150. if err != nil {
  151. panic(err)
  152. }
  153. default:
  154. panic("unknown key type")
  155. }
  156. var pemOut bytes.Buffer
  157. pem.Encode(&pemOut, &pem.Block{Type: pemType + " PRIVATE KEY", Bytes: derBytes})
  158. keyPath := tempFile(string(pemOut.Bytes()))
  159. defer os.Remove(keyPath)
  160. var command []string
  161. if len(test.command) > 0 {
  162. command = append(command, test.command...)
  163. } else {
  164. command = append(command, defaultServerCommand...)
  165. }
  166. command = append(command, "-cert", certPath, "-certform", "DER", "-key", keyPath)
  167. // serverPort contains the port that OpenSSL will listen on. OpenSSL
  168. // can't take "0" as an argument here so we have to pick a number and
  169. // hope that it's not in use on the machine. Since this only occurs
  170. // when -update is given and thus when there's a human watching the
  171. // test, this isn't too bad.
  172. const serverPort = 24323
  173. command = append(command, "-accept", strconv.Itoa(serverPort))
  174. if len(test.extensions) > 0 {
  175. var serverInfo bytes.Buffer
  176. for _, ext := range test.extensions {
  177. pem.Encode(&serverInfo, &pem.Block{
  178. Type: fmt.Sprintf("SERVERINFO FOR EXTENSION %d", binary.BigEndian.Uint16(ext)),
  179. Bytes: ext,
  180. })
  181. }
  182. serverInfoPath := tempFile(serverInfo.String())
  183. defer os.Remove(serverInfoPath)
  184. command = append(command, "-serverinfo", serverInfoPath)
  185. }
  186. if test.numRenegotiations > 0 {
  187. found := false
  188. for _, flag := range command[1:] {
  189. if flag == "-state" {
  190. found = true
  191. break
  192. }
  193. }
  194. if !found {
  195. panic("-state flag missing to OpenSSL. You need this if testing renegotiation")
  196. }
  197. }
  198. cmd := exec.Command(command[0], command[1:]...)
  199. stdin = opensslInput(make(chan opensslInputEvent))
  200. cmd.Stdin = stdin
  201. out := newOpensslOutputSink()
  202. cmd.Stdout = out
  203. cmd.Stderr = out
  204. if err := cmd.Start(); err != nil {
  205. return nil, nil, nil, nil, err
  206. }
  207. // OpenSSL does print an "ACCEPT" banner, but it does so *before*
  208. // opening the listening socket, so we can't use that to wait until it
  209. // has started listening. Thus we are forced to poll until we get a
  210. // connection.
  211. var tcpConn net.Conn
  212. for i := uint(0); i < 5; i++ {
  213. tcpConn, err = net.DialTCP("tcp", nil, &net.TCPAddr{
  214. IP: net.IPv4(127, 0, 0, 1),
  215. Port: serverPort,
  216. })
  217. if err == nil {
  218. break
  219. }
  220. time.Sleep((1 << i) * 5 * time.Millisecond)
  221. }
  222. if err != nil {
  223. close(stdin)
  224. out.WriteTo(os.Stdout)
  225. cmd.Process.Kill()
  226. return nil, nil, nil, nil, cmd.Wait()
  227. }
  228. record := &recordingConn{
  229. Conn: tcpConn,
  230. }
  231. return record, cmd, stdin, out, nil
  232. }
  233. func (test *clientTest) dataPath() string {
  234. return filepath.Join("testdata", "Client-"+test.name)
  235. }
  236. func (test *clientTest) loadData() (flows [][]byte, err error) {
  237. in, err := os.Open(test.dataPath())
  238. if err != nil {
  239. return nil, err
  240. }
  241. defer in.Close()
  242. return parseTestData(in)
  243. }
  244. func (test *clientTest) run(t *testing.T, write bool) {
  245. checkOpenSSLVersion(t)
  246. var clientConn, serverConn net.Conn
  247. var recordingConn *recordingConn
  248. var childProcess *exec.Cmd
  249. var stdin opensslInput
  250. var stdout *opensslOutputSink
  251. if write {
  252. var err error
  253. recordingConn, childProcess, stdin, stdout, err = test.connFromCommand()
  254. if err != nil {
  255. t.Fatalf("Failed to start subcommand: %s", err)
  256. }
  257. clientConn = recordingConn
  258. } else {
  259. clientConn, serverConn = net.Pipe()
  260. }
  261. config := test.config
  262. if config == nil {
  263. config = testConfig
  264. }
  265. client := Client(clientConn, config)
  266. doneChan := make(chan bool)
  267. go func() {
  268. defer func() { doneChan <- true }()
  269. defer clientConn.Close()
  270. defer client.Close()
  271. if _, err := client.Write([]byte("hello\n")); err != nil {
  272. t.Errorf("Client.Write failed: %s", err)
  273. return
  274. }
  275. for i := 1; i <= test.numRenegotiations; i++ {
  276. // The initial handshake will generate a
  277. // handshakeComplete signal which needs to be quashed.
  278. if i == 1 && write {
  279. <-stdout.handshakeComplete
  280. }
  281. // OpenSSL will try to interleave application data and
  282. // a renegotiation if we send both concurrently.
  283. // Therefore: ask OpensSSL to start a renegotiation, run
  284. // a goroutine to call client.Read and thus process the
  285. // renegotiation request, watch for OpenSSL's stdout to
  286. // indicate that the handshake is complete and,
  287. // finally, have OpenSSL write something to cause
  288. // client.Read to complete.
  289. if write {
  290. stdin <- opensslRenegotiate
  291. }
  292. signalChan := make(chan struct{})
  293. go func() {
  294. defer func() { signalChan <- struct{}{} }()
  295. buf := make([]byte, 256)
  296. n, err := client.Read(buf)
  297. if test.checkRenegotiationError != nil {
  298. newErr := test.checkRenegotiationError(i, err)
  299. if err != nil && newErr == nil {
  300. return
  301. }
  302. err = newErr
  303. }
  304. if err != nil {
  305. t.Errorf("Client.Read failed after renegotiation #%d: %s", i, err)
  306. return
  307. }
  308. buf = buf[:n]
  309. if !bytes.Equal([]byte(opensslSentinel), buf) {
  310. t.Errorf("Client.Read returned %q, but wanted %q", string(buf), opensslSentinel)
  311. }
  312. if expected := i + 1; client.handshakes != expected {
  313. t.Errorf("client should have recorded %d handshakes, but believes that %d have occurred", expected, client.handshakes)
  314. }
  315. }()
  316. if write && test.renegotiationExpectedToFail != i {
  317. <-stdout.handshakeComplete
  318. stdin <- opensslSendSentinel
  319. }
  320. <-signalChan
  321. }
  322. if test.validate != nil {
  323. if err := test.validate(client.ConnectionState()); err != nil {
  324. t.Errorf("validate callback returned error: %s", err)
  325. }
  326. }
  327. }()
  328. if !write {
  329. flows, err := test.loadData()
  330. if err != nil {
  331. t.Fatalf("%s: failed to load data from %s: %v", test.name, test.dataPath(), err)
  332. }
  333. for i, b := range flows {
  334. if i%2 == 1 {
  335. serverConn.Write(b)
  336. continue
  337. }
  338. bb := make([]byte, len(b))
  339. _, err := io.ReadFull(serverConn, bb)
  340. if err != nil {
  341. t.Fatalf("%s #%d: %s", test.name, i, err)
  342. }
  343. if !bytes.Equal(b, bb) {
  344. t.Fatalf("%s #%d: mismatch on read: got:%x want:%x", test.name, i, bb, b)
  345. }
  346. }
  347. serverConn.Close()
  348. }
  349. <-doneChan
  350. if write {
  351. path := test.dataPath()
  352. out, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
  353. if err != nil {
  354. t.Fatalf("Failed to create output file: %s", err)
  355. }
  356. defer out.Close()
  357. recordingConn.Close()
  358. close(stdin)
  359. childProcess.Process.Kill()
  360. childProcess.Wait()
  361. if len(recordingConn.flows) < 3 {
  362. os.Stdout.Write(childProcess.Stdout.(*opensslOutputSink).all)
  363. t.Fatalf("Client connection didn't work")
  364. }
  365. recordingConn.WriteTo(out)
  366. fmt.Printf("Wrote %s\n", path)
  367. }
  368. }
  369. var (
  370. didParMu sync.Mutex
  371. didPar = map[*testing.T]bool{}
  372. )
  373. // setParallel calls t.Parallel once. If you call it twice, it would
  374. // panic.
  375. func setParallel(t *testing.T) {
  376. didParMu.Lock()
  377. v := didPar[t]
  378. didPar[t] = true
  379. didParMu.Unlock()
  380. if !v {
  381. t.Parallel()
  382. }
  383. }
  384. func runClientTestForVersion(t *testing.T, template *clientTest, prefix, option string) {
  385. setParallel(t)
  386. test := *template
  387. test.name = prefix + test.name
  388. if len(test.command) == 0 {
  389. test.command = defaultClientCommand
  390. }
  391. test.command = append([]string(nil), test.command...)
  392. test.command = append(test.command, option)
  393. test.run(t, *update)
  394. }
  395. func runClientTestTLS10(t *testing.T, template *clientTest) {
  396. runClientTestForVersion(t, template, "TLSv10-", "-tls1")
  397. }
  398. func runClientTestTLS11(t *testing.T, template *clientTest) {
  399. runClientTestForVersion(t, template, "TLSv11-", "-tls1_1")
  400. }
  401. func runClientTestTLS12(t *testing.T, template *clientTest) {
  402. runClientTestForVersion(t, template, "TLSv12-", "-tls1_2")
  403. }
  404. func TestHandshakeClientRSARC4(t *testing.T) {
  405. test := &clientTest{
  406. name: "RSA-RC4",
  407. command: []string{"openssl", "s_server", "-cipher", "RC4-SHA"},
  408. }
  409. runClientTestTLS10(t, test)
  410. runClientTestTLS11(t, test)
  411. runClientTestTLS12(t, test)
  412. }
  413. func TestHandshakeClientRSAAES128GCM(t *testing.T) {
  414. test := &clientTest{
  415. name: "AES128-GCM-SHA256",
  416. command: []string{"openssl", "s_server", "-cipher", "AES128-GCM-SHA256"},
  417. }
  418. runClientTestTLS12(t, test)
  419. }
  420. func TestHandshakeClientRSAAES256GCM(t *testing.T) {
  421. test := &clientTest{
  422. name: "AES256-GCM-SHA384",
  423. command: []string{"openssl", "s_server", "-cipher", "AES256-GCM-SHA384"},
  424. }
  425. runClientTestTLS12(t, test)
  426. }
  427. func TestHandshakeClientECDHERSAAES(t *testing.T) {
  428. test := &clientTest{
  429. name: "ECDHE-RSA-AES",
  430. command: []string{"openssl", "s_server", "-cipher", "ECDHE-RSA-AES128-SHA"},
  431. }
  432. runClientTestTLS10(t, test)
  433. runClientTestTLS11(t, test)
  434. runClientTestTLS12(t, test)
  435. }
  436. func TestHandshakeClientECDHEECDSAAES(t *testing.T) {
  437. test := &clientTest{
  438. name: "ECDHE-ECDSA-AES",
  439. command: []string{"openssl", "s_server", "-cipher", "ECDHE-ECDSA-AES128-SHA"},
  440. cert: testECDSACertificate,
  441. key: testECDSAPrivateKey,
  442. }
  443. runClientTestTLS10(t, test)
  444. runClientTestTLS11(t, test)
  445. runClientTestTLS12(t, test)
  446. }
  447. func TestHandshakeClientECDHEECDSAAESGCM(t *testing.T) {
  448. test := &clientTest{
  449. name: "ECDHE-ECDSA-AES-GCM",
  450. command: []string{"openssl", "s_server", "-cipher", "ECDHE-ECDSA-AES128-GCM-SHA256"},
  451. cert: testECDSACertificate,
  452. key: testECDSAPrivateKey,
  453. }
  454. runClientTestTLS12(t, test)
  455. }
  456. func TestHandshakeClientAES256GCMSHA384(t *testing.T) {
  457. test := &clientTest{
  458. name: "ECDHE-ECDSA-AES256-GCM-SHA384",
  459. command: []string{"openssl", "s_server", "-cipher", "ECDHE-ECDSA-AES256-GCM-SHA384"},
  460. cert: testECDSACertificate,
  461. key: testECDSAPrivateKey,
  462. }
  463. runClientTestTLS12(t, test)
  464. }
  465. func TestHandshakeClientAES128CBCSHA256(t *testing.T) {
  466. test := &clientTest{
  467. name: "AES128-SHA256",
  468. command: []string{"openssl", "s_server", "-cipher", "AES128-SHA256"},
  469. }
  470. runClientTestTLS12(t, test)
  471. }
  472. func TestHandshakeClientECDHERSAAES128CBCSHA256(t *testing.T) {
  473. test := &clientTest{
  474. name: "ECDHE-RSA-AES128-SHA256",
  475. command: []string{"openssl", "s_server", "-cipher", "ECDHE-RSA-AES128-SHA256"},
  476. }
  477. runClientTestTLS12(t, test)
  478. }
  479. func TestHandshakeClientECDHEECDSAAES128CBCSHA256(t *testing.T) {
  480. test := &clientTest{
  481. name: "ECDHE-ECDSA-AES128-SHA256",
  482. command: []string{"openssl", "s_server", "-cipher", "ECDHE-ECDSA-AES128-SHA256"},
  483. cert: testECDSACertificate,
  484. key: testECDSAPrivateKey,
  485. }
  486. runClientTestTLS12(t, test)
  487. }
  488. func TestHandshakeClientX25519(t *testing.T) {
  489. config := testConfig.Clone()
  490. config.CurvePreferences = []CurveID{X25519}
  491. test := &clientTest{
  492. name: "X25519-ECDHE-RSA-AES-GCM",
  493. command: []string{"openssl", "s_server", "-cipher", "ECDHE-RSA-AES128-GCM-SHA256"},
  494. config: config,
  495. }
  496. runClientTestTLS12(t, test)
  497. }
  498. func TestHandshakeClientECDHERSAChaCha20(t *testing.T) {
  499. config := testConfig.Clone()
  500. config.CipherSuites = []uint16{TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305}
  501. test := &clientTest{
  502. name: "ECDHE-RSA-CHACHA20-POLY1305",
  503. command: []string{"openssl", "s_server", "-cipher", "ECDHE-RSA-CHACHA20-POLY1305"},
  504. config: config,
  505. }
  506. runClientTestTLS12(t, test)
  507. }
  508. func TestHandshakeClientECDHEECDSAChaCha20(t *testing.T) {
  509. config := testConfig.Clone()
  510. config.CipherSuites = []uint16{TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305}
  511. test := &clientTest{
  512. name: "ECDHE-ECDSA-CHACHA20-POLY1305",
  513. command: []string{"openssl", "s_server", "-cipher", "ECDHE-ECDSA-CHACHA20-POLY1305"},
  514. config: config,
  515. cert: testECDSACertificate,
  516. key: testECDSAPrivateKey,
  517. }
  518. runClientTestTLS12(t, test)
  519. }
  520. func TestHandshakeClientCertRSA(t *testing.T) {
  521. config := testConfig.Clone()
  522. cert, _ := X509KeyPair([]byte(clientCertificatePEM), []byte(clientKeyPEM))
  523. config.Certificates = []Certificate{cert}
  524. test := &clientTest{
  525. name: "ClientCert-RSA-RSA",
  526. command: []string{"openssl", "s_server", "-cipher", "AES128", "-verify", "1"},
  527. config: config,
  528. }
  529. runClientTestTLS10(t, test)
  530. runClientTestTLS12(t, test)
  531. test = &clientTest{
  532. name: "ClientCert-RSA-ECDSA",
  533. command: []string{"openssl", "s_server", "-cipher", "ECDHE-ECDSA-AES128-SHA", "-verify", "1"},
  534. config: config,
  535. cert: testECDSACertificate,
  536. key: testECDSAPrivateKey,
  537. }
  538. runClientTestTLS10(t, test)
  539. runClientTestTLS12(t, test)
  540. test = &clientTest{
  541. name: "ClientCert-RSA-AES256-GCM-SHA384",
  542. command: []string{"openssl", "s_server", "-cipher", "ECDHE-RSA-AES256-GCM-SHA384", "-verify", "1"},
  543. config: config,
  544. cert: testRSACertificate,
  545. key: testRSAPrivateKey,
  546. }
  547. runClientTestTLS12(t, test)
  548. }
  549. func TestHandshakeClientCertECDSA(t *testing.T) {
  550. config := testConfig.Clone()
  551. cert, _ := X509KeyPair([]byte(clientECDSACertificatePEM), []byte(clientECDSAKeyPEM))
  552. config.Certificates = []Certificate{cert}
  553. test := &clientTest{
  554. name: "ClientCert-ECDSA-RSA",
  555. command: []string{"openssl", "s_server", "-cipher", "AES128", "-verify", "1"},
  556. config: config,
  557. }
  558. runClientTestTLS10(t, test)
  559. runClientTestTLS12(t, test)
  560. test = &clientTest{
  561. name: "ClientCert-ECDSA-ECDSA",
  562. command: []string{"openssl", "s_server", "-cipher", "ECDHE-ECDSA-AES128-SHA", "-verify", "1"},
  563. config: config,
  564. cert: testECDSACertificate,
  565. key: testECDSAPrivateKey,
  566. }
  567. runClientTestTLS10(t, test)
  568. runClientTestTLS12(t, test)
  569. }
  570. func TestClientResumption(t *testing.T) {
  571. serverConfig := &Config{
  572. CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA},
  573. Certificates: testConfig.Certificates,
  574. }
  575. issuer, err := x509.ParseCertificate(testRSACertificateIssuer)
  576. if err != nil {
  577. panic(err)
  578. }
  579. rootCAs := x509.NewCertPool()
  580. rootCAs.AddCert(issuer)
  581. clientConfig := &Config{
  582. CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
  583. ClientSessionCache: NewLRUClientSessionCache(32),
  584. RootCAs: rootCAs,
  585. ServerName: "example.golang",
  586. }
  587. testResumeState := func(test string, didResume bool) {
  588. _, hs, err := testHandshake(clientConfig, serverConfig)
  589. if err != nil {
  590. t.Fatalf("%s: handshake failed: %s", test, err)
  591. }
  592. if hs.DidResume != didResume {
  593. t.Fatalf("%s resumed: %v, expected: %v", test, hs.DidResume, didResume)
  594. }
  595. if didResume && (hs.PeerCertificates == nil || hs.VerifiedChains == nil) {
  596. t.Fatalf("expected non-nil certificates after resumption. Got peerCertificates: %#v, verifiedCertificates: %#v", hs.PeerCertificates, hs.VerifiedChains)
  597. }
  598. }
  599. getTicket := func() []byte {
  600. return clientConfig.ClientSessionCache.(*lruSessionCache).q.Front().Value.(*lruSessionCacheEntry).state.sessionTicket
  601. }
  602. randomKey := func() [32]byte {
  603. var k [32]byte
  604. if _, err := io.ReadFull(serverConfig.rand(), k[:]); err != nil {
  605. t.Fatalf("Failed to read new SessionTicketKey: %s", err)
  606. }
  607. return k
  608. }
  609. testResumeState("Handshake", false)
  610. ticket := getTicket()
  611. testResumeState("Resume", true)
  612. if !bytes.Equal(ticket, getTicket()) {
  613. t.Fatal("first ticket doesn't match ticket after resumption")
  614. }
  615. key1 := randomKey()
  616. serverConfig.SetSessionTicketKeys([][32]byte{key1})
  617. testResumeState("InvalidSessionTicketKey", false)
  618. testResumeState("ResumeAfterInvalidSessionTicketKey", true)
  619. key2 := randomKey()
  620. serverConfig.SetSessionTicketKeys([][32]byte{key2, key1})
  621. ticket = getTicket()
  622. testResumeState("KeyChange", true)
  623. if bytes.Equal(ticket, getTicket()) {
  624. t.Fatal("new ticket wasn't included while resuming")
  625. }
  626. testResumeState("KeyChangeFinish", true)
  627. // Reset serverConfig to ensure that calling SetSessionTicketKeys
  628. // before the serverConfig is used works.
  629. serverConfig = &Config{
  630. CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA},
  631. Certificates: testConfig.Certificates,
  632. }
  633. serverConfig.SetSessionTicketKeys([][32]byte{key2})
  634. testResumeState("FreshConfig", true)
  635. clientConfig.CipherSuites = []uint16{TLS_ECDHE_RSA_WITH_RC4_128_SHA}
  636. testResumeState("DifferentCipherSuite", false)
  637. testResumeState("DifferentCipherSuiteRecovers", true)
  638. clientConfig.ClientSessionCache = nil
  639. testResumeState("WithoutSessionCache", false)
  640. }
  641. func TestLRUClientSessionCache(t *testing.T) {
  642. // Initialize cache of capacity 4.
  643. cache := NewLRUClientSessionCache(4)
  644. cs := make([]ClientSessionState, 6)
  645. keys := []string{"0", "1", "2", "3", "4", "5", "6"}
  646. // Add 4 entries to the cache and look them up.
  647. for i := 0; i < 4; i++ {
  648. cache.Put(keys[i], &cs[i])
  649. }
  650. for i := 0; i < 4; i++ {
  651. if s, ok := cache.Get(keys[i]); !ok || s != &cs[i] {
  652. t.Fatalf("session cache failed lookup for added key: %s", keys[i])
  653. }
  654. }
  655. // Add 2 more entries to the cache. First 2 should be evicted.
  656. for i := 4; i < 6; i++ {
  657. cache.Put(keys[i], &cs[i])
  658. }
  659. for i := 0; i < 2; i++ {
  660. if s, ok := cache.Get(keys[i]); ok || s != nil {
  661. t.Fatalf("session cache should have evicted key: %s", keys[i])
  662. }
  663. }
  664. // Touch entry 2. LRU should evict 3 next.
  665. cache.Get(keys[2])
  666. cache.Put(keys[0], &cs[0])
  667. if s, ok := cache.Get(keys[3]); ok || s != nil {
  668. t.Fatalf("session cache should have evicted key 3")
  669. }
  670. // Update entry 0 in place.
  671. cache.Put(keys[0], &cs[3])
  672. if s, ok := cache.Get(keys[0]); !ok || s != &cs[3] {
  673. t.Fatalf("session cache failed update for key 0")
  674. }
  675. // Adding a nil entry is valid.
  676. cache.Put(keys[0], nil)
  677. if s, ok := cache.Get(keys[0]); !ok || s != nil {
  678. t.Fatalf("failed to add nil entry to cache")
  679. }
  680. }
  681. func TestKeyLog(t *testing.T) {
  682. var serverBuf, clientBuf bytes.Buffer
  683. clientConfig := testConfig.Clone()
  684. clientConfig.KeyLogWriter = &clientBuf
  685. serverConfig := testConfig.Clone()
  686. serverConfig.KeyLogWriter = &serverBuf
  687. c, s := net.Pipe()
  688. done := make(chan bool)
  689. go func() {
  690. defer close(done)
  691. if err := Server(s, serverConfig).Handshake(); err != nil {
  692. t.Errorf("server: %s", err)
  693. return
  694. }
  695. s.Close()
  696. }()
  697. if err := Client(c, clientConfig).Handshake(); err != nil {
  698. t.Fatalf("client: %s", err)
  699. }
  700. c.Close()
  701. <-done
  702. checkKeylogLine := func(side, loggedLine string) {
  703. if len(loggedLine) == 0 {
  704. t.Fatalf("%s: no keylog line was produced", side)
  705. }
  706. const expectedLen = 13 /* "CLIENT_RANDOM" */ +
  707. 1 /* space */ +
  708. 32*2 /* hex client nonce */ +
  709. 1 /* space */ +
  710. 48*2 /* hex master secret */ +
  711. 1 /* new line */
  712. if len(loggedLine) != expectedLen {
  713. t.Fatalf("%s: keylog line has incorrect length (want %d, got %d): %q", side, expectedLen, len(loggedLine), loggedLine)
  714. }
  715. if !strings.HasPrefix(loggedLine, "CLIENT_RANDOM "+strings.Repeat("0", 64)+" ") {
  716. t.Fatalf("%s: keylog line has incorrect structure or nonce: %q", side, loggedLine)
  717. }
  718. }
  719. checkKeylogLine("client", string(clientBuf.Bytes()))
  720. checkKeylogLine("server", string(serverBuf.Bytes()))
  721. }
  722. func TestHandshakeClientALPNMatch(t *testing.T) {
  723. config := testConfig.Clone()
  724. config.NextProtos = []string{"proto2", "proto1"}
  725. test := &clientTest{
  726. name: "ALPN",
  727. // Note that this needs OpenSSL 1.0.2 because that is the first
  728. // version that supports the -alpn flag.
  729. command: []string{"openssl", "s_server", "-alpn", "proto1,proto2"},
  730. config: config,
  731. validate: func(state ConnectionState) error {
  732. // The server's preferences should override the client.
  733. if state.NegotiatedProtocol != "proto1" {
  734. return fmt.Errorf("Got protocol %q, wanted proto1", state.NegotiatedProtocol)
  735. }
  736. return nil
  737. },
  738. }
  739. runClientTestTLS12(t, test)
  740. }
  741. // sctsBase64 contains data from `openssl s_client -serverinfo 18 -connect ritter.vg:443`
  742. const sctsBase64 = "ABIBaQFnAHUApLkJkLQYWBSHuxOizGdwCjw1mAT5G9+443fNDsgN3BAAAAFHl5nuFgAABAMARjBEAiAcS4JdlW5nW9sElUv2zvQyPoZ6ejKrGGB03gjaBZFMLwIgc1Qbbn+hsH0RvObzhS+XZhr3iuQQJY8S9G85D9KeGPAAdgBo9pj4H2SCvjqM7rkoHUz8cVFdZ5PURNEKZ6y7T0/7xAAAAUeX4bVwAAAEAwBHMEUCIDIhFDgG2HIuADBkGuLobU5a4dlCHoJLliWJ1SYT05z6AiEAjxIoZFFPRNWMGGIjskOTMwXzQ1Wh2e7NxXE1kd1J0QsAdgDuS723dc5guuFCaR+r4Z5mow9+X7By2IMAxHuJeqj9ywAAAUhcZIqHAAAEAwBHMEUCICmJ1rBT09LpkbzxtUC+Hi7nXLR0J+2PmwLp+sJMuqK+AiEAr0NkUnEVKVhAkccIFpYDqHOlZaBsuEhWWrYpg2RtKp0="
  743. func TestHandshakClientSCTs(t *testing.T) {
  744. config := testConfig.Clone()
  745. scts, err := base64.StdEncoding.DecodeString(sctsBase64)
  746. if err != nil {
  747. t.Fatal(err)
  748. }
  749. test := &clientTest{
  750. name: "SCT",
  751. // Note that this needs OpenSSL 1.0.2 because that is the first
  752. // version that supports the -serverinfo flag.
  753. command: []string{"openssl", "s_server"},
  754. config: config,
  755. extensions: [][]byte{scts},
  756. validate: func(state ConnectionState) error {
  757. expectedSCTs := [][]byte{
  758. scts[8:125],
  759. scts[127:245],
  760. scts[247:],
  761. }
  762. if n := len(state.SignedCertificateTimestamps); n != len(expectedSCTs) {
  763. return fmt.Errorf("Got %d scts, wanted %d", n, len(expectedSCTs))
  764. }
  765. for i, expected := range expectedSCTs {
  766. if sct := state.SignedCertificateTimestamps[i]; !bytes.Equal(sct, expected) {
  767. return fmt.Errorf("SCT #%d contained %x, expected %x", i, sct, expected)
  768. }
  769. }
  770. return nil
  771. },
  772. }
  773. runClientTestTLS12(t, test)
  774. }
  775. func TestRenegotiationRejected(t *testing.T) {
  776. config := testConfig.Clone()
  777. test := &clientTest{
  778. name: "RenegotiationRejected",
  779. command: []string{"openssl", "s_server", "-state"},
  780. config: config,
  781. numRenegotiations: 1,
  782. renegotiationExpectedToFail: 1,
  783. checkRenegotiationError: func(renegotiationNum int, err error) error {
  784. if err == nil {
  785. return errors.New("expected error from renegotiation but got nil")
  786. }
  787. if !strings.Contains(err.Error(), "no renegotiation") {
  788. return fmt.Errorf("expected renegotiation to be rejected but got %q", err)
  789. }
  790. return nil
  791. },
  792. }
  793. runClientTestTLS12(t, test)
  794. }
  795. func TestRenegotiateOnce(t *testing.T) {
  796. config := testConfig.Clone()
  797. config.Renegotiation = RenegotiateOnceAsClient
  798. test := &clientTest{
  799. name: "RenegotiateOnce",
  800. command: []string{"openssl", "s_server", "-state"},
  801. config: config,
  802. numRenegotiations: 1,
  803. }
  804. runClientTestTLS12(t, test)
  805. }
  806. func TestRenegotiateTwice(t *testing.T) {
  807. config := testConfig.Clone()
  808. config.Renegotiation = RenegotiateFreelyAsClient
  809. test := &clientTest{
  810. name: "RenegotiateTwice",
  811. command: []string{"openssl", "s_server", "-state"},
  812. config: config,
  813. numRenegotiations: 2,
  814. }
  815. runClientTestTLS12(t, test)
  816. }
  817. func TestRenegotiateTwiceRejected(t *testing.T) {
  818. config := testConfig.Clone()
  819. config.Renegotiation = RenegotiateOnceAsClient
  820. test := &clientTest{
  821. name: "RenegotiateTwiceRejected",
  822. command: []string{"openssl", "s_server", "-state"},
  823. config: config,
  824. numRenegotiations: 2,
  825. renegotiationExpectedToFail: 2,
  826. checkRenegotiationError: func(renegotiationNum int, err error) error {
  827. if renegotiationNum == 1 {
  828. return err
  829. }
  830. if err == nil {
  831. return errors.New("expected error from renegotiation but got nil")
  832. }
  833. if !strings.Contains(err.Error(), "no renegotiation") {
  834. return fmt.Errorf("expected renegotiation to be rejected but got %q", err)
  835. }
  836. return nil
  837. },
  838. }
  839. runClientTestTLS12(t, test)
  840. }
  841. var hostnameInSNITests = []struct {
  842. in, out string
  843. }{
  844. // Opaque string
  845. {"", ""},
  846. {"localhost", "localhost"},
  847. {"foo, bar, baz and qux", "foo, bar, baz and qux"},
  848. // DNS hostname
  849. {"golang.org", "golang.org"},
  850. {"golang.org.", "golang.org"},
  851. // Literal IPv4 address
  852. {"1.2.3.4", ""},
  853. // Literal IPv6 address
  854. {"::1", ""},
  855. {"::1%lo0", ""}, // with zone identifier
  856. {"[::1]", ""}, // as per RFC 5952 we allow the [] style as IPv6 literal
  857. {"[::1%lo0]", ""},
  858. }
  859. func TestHostnameInSNI(t *testing.T) {
  860. for _, tt := range hostnameInSNITests {
  861. c, s := net.Pipe()
  862. go func(host string) {
  863. Client(c, &Config{ServerName: host, InsecureSkipVerify: true}).Handshake()
  864. }(tt.in)
  865. var header [5]byte
  866. if _, err := io.ReadFull(s, header[:]); err != nil {
  867. t.Fatal(err)
  868. }
  869. recordLen := int(header[3])<<8 | int(header[4])
  870. record := make([]byte, recordLen)
  871. if _, err := io.ReadFull(s, record[:]); err != nil {
  872. t.Fatal(err)
  873. }
  874. c.Close()
  875. s.Close()
  876. var m clientHelloMsg
  877. if !m.unmarshal(record) {
  878. t.Errorf("unmarshaling ClientHello for %q failed", tt.in)
  879. continue
  880. }
  881. if tt.in != tt.out && m.serverName == tt.in {
  882. t.Errorf("prohibited %q found in ClientHello: %x", tt.in, record)
  883. }
  884. if m.serverName != tt.out {
  885. t.Errorf("expected %q not found in ClientHello: %x", tt.out, record)
  886. }
  887. }
  888. }
  889. func TestServerSelectingUnconfiguredCipherSuite(t *testing.T) {
  890. // This checks that the server can't select a cipher suite that the
  891. // client didn't offer. See #13174.
  892. c, s := net.Pipe()
  893. errChan := make(chan error, 1)
  894. go func() {
  895. client := Client(c, &Config{
  896. ServerName: "foo",
  897. CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
  898. })
  899. errChan <- client.Handshake()
  900. }()
  901. var header [5]byte
  902. if _, err := io.ReadFull(s, header[:]); err != nil {
  903. t.Fatal(err)
  904. }
  905. recordLen := int(header[3])<<8 | int(header[4])
  906. record := make([]byte, recordLen)
  907. if _, err := io.ReadFull(s, record); err != nil {
  908. t.Fatal(err)
  909. }
  910. // Create a ServerHello that selects a different cipher suite than the
  911. // sole one that the client offered.
  912. serverHello := &serverHelloMsg{
  913. vers: VersionTLS12,
  914. random: make([]byte, 32),
  915. cipherSuite: TLS_RSA_WITH_AES_256_GCM_SHA384,
  916. }
  917. serverHelloBytes := serverHello.marshal()
  918. s.Write([]byte{
  919. byte(recordTypeHandshake),
  920. byte(VersionTLS12 >> 8),
  921. byte(VersionTLS12 & 0xff),
  922. byte(len(serverHelloBytes) >> 8),
  923. byte(len(serverHelloBytes)),
  924. })
  925. s.Write(serverHelloBytes)
  926. s.Close()
  927. if err := <-errChan; !strings.Contains(err.Error(), "unconfigured cipher") {
  928. t.Fatalf("Expected error about unconfigured cipher suite but got %q", err)
  929. }
  930. }
  931. func TestVerifyPeerCertificate(t *testing.T) {
  932. issuer, err := x509.ParseCertificate(testRSACertificateIssuer)
  933. if err != nil {
  934. panic(err)
  935. }
  936. rootCAs := x509.NewCertPool()
  937. rootCAs.AddCert(issuer)
  938. now := func() time.Time { return time.Unix(1476984729, 0) }
  939. sentinelErr := errors.New("TestVerifyPeerCertificate")
  940. verifyCallback := func(called *bool, rawCerts [][]byte, validatedChains [][]*x509.Certificate) error {
  941. if l := len(rawCerts); l != 1 {
  942. return fmt.Errorf("got len(rawCerts) = %d, wanted 1", l)
  943. }
  944. if len(validatedChains) == 0 {
  945. return errors.New("got len(validatedChains) = 0, wanted non-zero")
  946. }
  947. *called = true
  948. return nil
  949. }
  950. tests := []struct {
  951. configureServer func(*Config, *bool)
  952. configureClient func(*Config, *bool)
  953. validate func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error)
  954. }{
  955. {
  956. configureServer: func(config *Config, called *bool) {
  957. config.InsecureSkipVerify = false
  958. config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error {
  959. return verifyCallback(called, rawCerts, validatedChains)
  960. }
  961. },
  962. configureClient: func(config *Config, called *bool) {
  963. config.InsecureSkipVerify = false
  964. config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error {
  965. return verifyCallback(called, rawCerts, validatedChains)
  966. }
  967. },
  968. validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) {
  969. if clientErr != nil {
  970. t.Errorf("test[%d]: client handshake failed: %v", testNo, clientErr)
  971. }
  972. if serverErr != nil {
  973. t.Errorf("test[%d]: server handshake failed: %v", testNo, serverErr)
  974. }
  975. if !clientCalled {
  976. t.Errorf("test[%d]: client did not call callback", testNo)
  977. }
  978. if !serverCalled {
  979. t.Errorf("test[%d]: server did not call callback", testNo)
  980. }
  981. },
  982. },
  983. {
  984. configureServer: func(config *Config, called *bool) {
  985. config.InsecureSkipVerify = false
  986. config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error {
  987. return sentinelErr
  988. }
  989. },
  990. configureClient: func(config *Config, called *bool) {
  991. config.VerifyPeerCertificate = nil
  992. },
  993. validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) {
  994. if serverErr != sentinelErr {
  995. t.Errorf("#%d: got server error %v, wanted sentinelErr", testNo, serverErr)
  996. }
  997. },
  998. },
  999. {
  1000. configureServer: func(config *Config, called *bool) {
  1001. config.InsecureSkipVerify = false
  1002. },
  1003. configureClient: func(config *Config, called *bool) {
  1004. config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error {
  1005. return sentinelErr
  1006. }
  1007. },
  1008. validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) {
  1009. if clientErr != sentinelErr {
  1010. t.Errorf("#%d: got client error %v, wanted sentinelErr", testNo, clientErr)
  1011. }
  1012. },
  1013. },
  1014. {
  1015. configureServer: func(config *Config, called *bool) {
  1016. config.InsecureSkipVerify = false
  1017. },
  1018. configureClient: func(config *Config, called *bool) {
  1019. config.InsecureSkipVerify = true
  1020. config.VerifyPeerCertificate = func(rawCerts [][]byte, validatedChains [][]*x509.Certificate) error {
  1021. if l := len(rawCerts); l != 1 {
  1022. return fmt.Errorf("got len(rawCerts) = %d, wanted 1", l)
  1023. }
  1024. // With InsecureSkipVerify set, this
  1025. // callback should still be called but
  1026. // validatedChains must be empty.
  1027. if l := len(validatedChains); l != 0 {
  1028. return fmt.Errorf("got len(validatedChains) = %d, wanted zero", l)
  1029. }
  1030. *called = true
  1031. return nil
  1032. }
  1033. },
  1034. validate: func(t *testing.T, testNo int, clientCalled, serverCalled bool, clientErr, serverErr error) {
  1035. if clientErr != nil {
  1036. t.Errorf("test[%d]: client handshake failed: %v", testNo, clientErr)
  1037. }
  1038. if serverErr != nil {
  1039. t.Errorf("test[%d]: server handshake failed: %v", testNo, serverErr)
  1040. }
  1041. if !clientCalled {
  1042. t.Errorf("test[%d]: client did not call callback", testNo)
  1043. }
  1044. },
  1045. },
  1046. }
  1047. for i, test := range tests {
  1048. c, s := net.Pipe()
  1049. done := make(chan error)
  1050. var clientCalled, serverCalled bool
  1051. go func() {
  1052. config := testConfig.Clone()
  1053. config.ServerName = "example.golang"
  1054. config.ClientAuth = RequireAndVerifyClientCert
  1055. config.ClientCAs = rootCAs
  1056. config.Time = now
  1057. test.configureServer(config, &serverCalled)
  1058. err = Server(s, config).Handshake()
  1059. s.Close()
  1060. done <- err
  1061. }()
  1062. config := testConfig.Clone()
  1063. config.ServerName = "example.golang"
  1064. config.RootCAs = rootCAs
  1065. config.Time = now
  1066. test.configureClient(config, &clientCalled)
  1067. clientErr := Client(c, config).Handshake()
  1068. c.Close()
  1069. serverErr := <-done
  1070. test.validate(t, i, clientCalled, serverCalled, clientErr, serverErr)
  1071. }
  1072. }
  1073. // brokenConn wraps a net.Conn and causes all Writes after a certain number to
  1074. // fail with brokenConnErr.
  1075. type brokenConn struct {
  1076. net.Conn
  1077. // breakAfter is the number of successful writes that will be allowed
  1078. // before all subsequent writes fail.
  1079. breakAfter int
  1080. // numWrites is the number of writes that have been done.
  1081. numWrites int
  1082. }
  1083. // brokenConnErr is the error that brokenConn returns once exhausted.
  1084. var brokenConnErr = errors.New("too many writes to brokenConn")
  1085. func (b *brokenConn) Write(data []byte) (int, error) {
  1086. if b.numWrites >= b.breakAfter {
  1087. return 0, brokenConnErr
  1088. }
  1089. b.numWrites++
  1090. return b.Conn.Write(data)
  1091. }
  1092. func TestFailedWrite(t *testing.T) {
  1093. // Test that a write error during the handshake is returned.
  1094. for _, breakAfter := range []int{0, 1} {
  1095. c, s := net.Pipe()
  1096. done := make(chan bool)
  1097. go func() {
  1098. Server(s, testConfig).Handshake()
  1099. s.Close()
  1100. done <- true
  1101. }()
  1102. brokenC := &brokenConn{Conn: c, breakAfter: breakAfter}
  1103. err := Client(brokenC, testConfig).Handshake()
  1104. if err != brokenConnErr {
  1105. t.Errorf("#%d: expected error from brokenConn but got %q", breakAfter, err)
  1106. }
  1107. brokenC.Close()
  1108. <-done
  1109. }
  1110. }
  1111. // writeCountingConn wraps a net.Conn and counts the number of Write calls.
  1112. type writeCountingConn struct {
  1113. net.Conn
  1114. // numWrites is the number of writes that have been done.
  1115. numWrites int
  1116. }
  1117. func (wcc *writeCountingConn) Write(data []byte) (int, error) {
  1118. wcc.numWrites++
  1119. return wcc.Conn.Write(data)
  1120. }
  1121. func TestBuffering(t *testing.T) {
  1122. c, s := net.Pipe()
  1123. done := make(chan bool)
  1124. clientWCC := &writeCountingConn{Conn: c}
  1125. serverWCC := &writeCountingConn{Conn: s}
  1126. go func() {
  1127. Server(serverWCC, testConfig).Handshake()
  1128. serverWCC.Close()
  1129. done <- true
  1130. }()
  1131. err := Client(clientWCC, testConfig).Handshake()
  1132. if err != nil {
  1133. t.Fatal(err)
  1134. }
  1135. clientWCC.Close()
  1136. <-done
  1137. if n := clientWCC.numWrites; n != 2 {
  1138. t.Errorf("expected client handshake to complete with only two writes, but saw %d", n)
  1139. }
  1140. if n := serverWCC.numWrites; n != 2 {
  1141. t.Errorf("expected server handshake to complete with only two writes, but saw %d", n)
  1142. }
  1143. }
  1144. func TestAlertFlushing(t *testing.T) {
  1145. c, s := net.Pipe()
  1146. done := make(chan bool)
  1147. clientWCC := &writeCountingConn{Conn: c}
  1148. serverWCC := &writeCountingConn{Conn: s}
  1149. serverConfig := testConfig.Clone()
  1150. // Cause a signature-time error
  1151. brokenKey := rsa.PrivateKey{PublicKey: testRSAPrivateKey.PublicKey}
  1152. brokenKey.D = big.NewInt(42)
  1153. serverConfig.Certificates = []Certificate{{
  1154. Certificate: [][]byte{testRSACertificate},
  1155. PrivateKey: &brokenKey,
  1156. }}
  1157. go func() {
  1158. Server(serverWCC, serverConfig).Handshake()
  1159. serverWCC.Close()
  1160. done <- true
  1161. }()
  1162. err := Client(clientWCC, testConfig).Handshake()
  1163. if err == nil {
  1164. t.Fatal("client unexpectedly returned no error")
  1165. }
  1166. const expectedError = "remote error: tls: handshake failure"
  1167. if e := err.Error(); !strings.Contains(e, expectedError) {
  1168. t.Fatalf("expected to find %q in error but error was %q", expectedError, e)
  1169. }
  1170. clientWCC.Close()
  1171. <-done
  1172. if n := clientWCC.numWrites; n != 1 {
  1173. t.Errorf("expected client handshake to complete with one write, but saw %d", n)
  1174. }
  1175. if n := serverWCC.numWrites; n != 1 {
  1176. t.Errorf("expected server handshake to complete with one write, but saw %d", n)
  1177. }
  1178. }
  1179. func TestHandshakeRace(t *testing.T) {
  1180. t.Parallel()
  1181. // This test races a Read and Write to try and complete a handshake in
  1182. // order to provide some evidence that there are no races or deadlocks
  1183. // in the handshake locking.
  1184. for i := 0; i < 32; i++ {
  1185. c, s := net.Pipe()
  1186. go func() {
  1187. server := Server(s, testConfig)
  1188. if err := server.Handshake(); err != nil {
  1189. panic(err)
  1190. }
  1191. var request [1]byte
  1192. if n, err := server.Read(request[:]); err != nil || n != 1 {
  1193. panic(err)
  1194. }
  1195. server.Write(request[:])
  1196. server.Close()
  1197. }()
  1198. startWrite := make(chan struct{})
  1199. startRead := make(chan struct{})
  1200. readDone := make(chan struct{})
  1201. client := Client(c, testConfig)
  1202. go func() {
  1203. <-startWrite
  1204. var request [1]byte
  1205. client.Write(request[:])
  1206. }()
  1207. go func() {
  1208. <-startRead
  1209. var reply [1]byte
  1210. if n, err := client.Read(reply[:]); err != nil || n != 1 {
  1211. panic(err)
  1212. }
  1213. c.Close()
  1214. readDone <- struct{}{}
  1215. }()
  1216. if i&1 == 1 {
  1217. startWrite <- struct{}{}
  1218. startRead <- struct{}{}
  1219. } else {
  1220. startRead <- struct{}{}
  1221. startWrite <- struct{}{}
  1222. }
  1223. <-readDone
  1224. }
  1225. }
  1226. func TestTLS11SignatureSchemes(t *testing.T) {
  1227. expected := tls11SignatureSchemesNumECDSA + tls11SignatureSchemesNumRSA
  1228. if expected != len(tls11SignatureSchemes) {
  1229. t.Errorf("expected to find %d TLS 1.1 signature schemes, but found %d", expected, len(tls11SignatureSchemes))
  1230. }
  1231. }
  1232. var getClientCertificateTests = []struct {
  1233. setup func(*Config, *Config)
  1234. expectedClientError string
  1235. verify func(*testing.T, int, *ConnectionState)
  1236. }{
  1237. {
  1238. func(clientConfig, serverConfig *Config) {
  1239. // Returning a Certificate with no certificate data
  1240. // should result in an empty message being sent to the
  1241. // server.
  1242. serverConfig.ClientCAs = nil
  1243. clientConfig.GetClientCertificate = func(cri *CertificateRequestInfo) (*Certificate, error) {
  1244. if len(cri.SignatureSchemes) == 0 {
  1245. panic("empty SignatureSchemes")
  1246. }
  1247. if len(cri.AcceptableCAs) != 0 {
  1248. panic("AcceptableCAs should have been empty")
  1249. }
  1250. return new(Certificate), nil
  1251. }
  1252. },
  1253. "",
  1254. func(t *testing.T, testNum int, cs *ConnectionState) {
  1255. if l := len(cs.PeerCertificates); l != 0 {
  1256. t.Errorf("#%d: expected no certificates but got %d", testNum, l)
  1257. }
  1258. },
  1259. },
  1260. {
  1261. func(clientConfig, serverConfig *Config) {
  1262. // With TLS 1.1, the SignatureSchemes should be
  1263. // synthesised from the supported certificate types.
  1264. clientConfig.MaxVersion = VersionTLS11
  1265. clientConfig.GetClientCertificate = func(cri *CertificateRequestInfo) (*Certificate, error) {
  1266. if len(cri.SignatureSchemes) == 0 {
  1267. panic("empty SignatureSchemes")
  1268. }
  1269. return new(Certificate), nil
  1270. }
  1271. },
  1272. "",
  1273. func(t *testing.T, testNum int, cs *ConnectionState) {
  1274. if l := len(cs.PeerCertificates); l != 0 {
  1275. t.Errorf("#%d: expected no certificates but got %d", testNum, l)
  1276. }
  1277. },
  1278. },
  1279. {
  1280. func(clientConfig, serverConfig *Config) {
  1281. // Returning an error should abort the handshake with
  1282. // that error.
  1283. clientConfig.GetClientCertificate = func(cri *CertificateRequestInfo) (*Certificate, error) {
  1284. return nil, errors.New("GetClientCertificate")
  1285. }
  1286. },
  1287. "GetClientCertificate",
  1288. func(t *testing.T, testNum int, cs *ConnectionState) {
  1289. },
  1290. },
  1291. {
  1292. func(clientConfig, serverConfig *Config) {
  1293. clientConfig.GetClientCertificate = func(cri *CertificateRequestInfo) (*Certificate, error) {
  1294. if len(cri.AcceptableCAs) == 0 {
  1295. panic("empty AcceptableCAs")
  1296. }
  1297. cert := &Certificate{
  1298. Certificate: [][]byte{testRSACertificate},
  1299. PrivateKey: testRSAPrivateKey,
  1300. }
  1301. return cert, nil
  1302. }
  1303. },
  1304. "",
  1305. func(t *testing.T, testNum int, cs *ConnectionState) {
  1306. if len(cs.VerifiedChains) == 0 {
  1307. t.Errorf("#%d: expected some verified chains, but found none", testNum)
  1308. }
  1309. },
  1310. },
  1311. }
  1312. func TestGetClientCertificate(t *testing.T) {
  1313. issuer, err := x509.ParseCertificate(testRSACertificateIssuer)
  1314. if err != nil {
  1315. panic(err)
  1316. }
  1317. for i, test := range getClientCertificateTests {
  1318. serverConfig := testConfig.Clone()
  1319. serverConfig.ClientAuth = VerifyClientCertIfGiven
  1320. serverConfig.RootCAs = x509.NewCertPool()
  1321. serverConfig.RootCAs.AddCert(issuer)
  1322. serverConfig.ClientCAs = serverConfig.RootCAs
  1323. serverConfig.Time = func() time.Time { return time.Unix(1476984729, 0) }
  1324. clientConfig := testConfig.Clone()
  1325. test.setup(clientConfig, serverConfig)
  1326. type serverResult struct {
  1327. cs ConnectionState
  1328. err error
  1329. }
  1330. c, s := net.Pipe()
  1331. done := make(chan serverResult)
  1332. go func() {
  1333. defer s.Close()
  1334. server := Server(s, serverConfig)
  1335. err := server.Handshake()
  1336. var cs ConnectionState
  1337. if err == nil {
  1338. cs = server.ConnectionState()
  1339. }
  1340. done <- serverResult{cs, err}
  1341. }()
  1342. clientErr := Client(c, clientConfig).Handshake()
  1343. c.Close()
  1344. result := <-done
  1345. if clientErr != nil {
  1346. if len(test.expectedClientError) == 0 {
  1347. t.Errorf("#%d: client error: %v", i, clientErr)
  1348. } else if got := clientErr.Error(); got != test.expectedClientError {
  1349. t.Errorf("#%d: expected client error %q, but got %q", i, test.expectedClientError, got)
  1350. } else {
  1351. test.verify(t, i, &result.cs)
  1352. }
  1353. } else if len(test.expectedClientError) > 0 {
  1354. t.Errorf("#%d: expected client error %q, but got no error", i, test.expectedClientError)
  1355. } else if err := result.err; err != nil {
  1356. t.Errorf("#%d: server error: %v", i, err)
  1357. } else {
  1358. test.verify(t, i, &result.cs)
  1359. }
  1360. }
  1361. }