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

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