Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 
 
 

1235 righe
33 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 write finished A"
  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. var clientConn, serverConn net.Conn
  245. var recordingConn *recordingConn
  246. var childProcess *exec.Cmd
  247. var stdin opensslInput
  248. var stdout *opensslOutputSink
  249. if write {
  250. var err error
  251. recordingConn, childProcess, stdin, stdout, err = test.connFromCommand()
  252. if err != nil {
  253. t.Fatalf("Failed to start subcommand: %s", err)
  254. }
  255. clientConn = recordingConn
  256. } else {
  257. clientConn, serverConn = net.Pipe()
  258. }
  259. config := test.config
  260. if config == nil {
  261. config = testConfig
  262. }
  263. client := Client(clientConn, config)
  264. doneChan := make(chan bool)
  265. go func() {
  266. defer func() { doneChan <- true }()
  267. defer clientConn.Close()
  268. defer client.Close()
  269. if _, err := client.Write([]byte("hello\n")); err != nil {
  270. t.Errorf("Client.Write failed: %s", err)
  271. return
  272. }
  273. for i := 1; i <= test.numRenegotiations; i++ {
  274. // The initial handshake will generate a
  275. // handshakeComplete signal which needs to be quashed.
  276. if i == 1 && write {
  277. <-stdout.handshakeComplete
  278. }
  279. // OpenSSL will try to interleave application data and
  280. // a renegotiation if we send both concurrently.
  281. // Therefore: ask OpensSSL to start a renegotiation, run
  282. // a goroutine to call client.Read and thus process the
  283. // renegotiation request, watch for OpenSSL's stdout to
  284. // indicate that the handshake is complete and,
  285. // finally, have OpenSSL write something to cause
  286. // client.Read to complete.
  287. if write {
  288. stdin <- opensslRenegotiate
  289. }
  290. signalChan := make(chan struct{})
  291. go func() {
  292. defer func() { signalChan <- struct{}{} }()
  293. buf := make([]byte, 256)
  294. n, err := client.Read(buf)
  295. if test.checkRenegotiationError != nil {
  296. newErr := test.checkRenegotiationError(i, err)
  297. if err != nil && newErr == nil {
  298. return
  299. }
  300. err = newErr
  301. }
  302. if err != nil {
  303. t.Errorf("Client.Read failed after renegotiation #%d: %s", i, err)
  304. return
  305. }
  306. buf = buf[:n]
  307. if !bytes.Equal([]byte(opensslSentinel), buf) {
  308. t.Errorf("Client.Read returned %q, but wanted %q", string(buf), opensslSentinel)
  309. }
  310. if expected := i + 1; client.handshakes != expected {
  311. t.Errorf("client should have recorded %d handshakes, but believes that %d have occured", expected, client.handshakes)
  312. }
  313. }()
  314. if write && test.renegotiationExpectedToFail != i {
  315. <-stdout.handshakeComplete
  316. stdin <- opensslSendSentinel
  317. }
  318. <-signalChan
  319. }
  320. if test.validate != nil {
  321. if err := test.validate(client.ConnectionState()); err != nil {
  322. t.Errorf("validate callback returned error: %s", err)
  323. }
  324. }
  325. }()
  326. if !write {
  327. flows, err := test.loadData()
  328. if err != nil {
  329. t.Fatalf("%s: failed to load data from %s: %v", test.name, test.dataPath(), err)
  330. }
  331. for i, b := range flows {
  332. if i%2 == 1 {
  333. serverConn.Write(b)
  334. continue
  335. }
  336. bb := make([]byte, len(b))
  337. _, err := io.ReadFull(serverConn, bb)
  338. if err != nil {
  339. t.Fatalf("%s #%d: %s", test.name, i, err)
  340. }
  341. if !bytes.Equal(b, bb) {
  342. t.Fatalf("%s #%d: mismatch on read: got:%x want:%x", test.name, i, bb, b)
  343. }
  344. }
  345. serverConn.Close()
  346. }
  347. <-doneChan
  348. if write {
  349. path := test.dataPath()
  350. out, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
  351. if err != nil {
  352. t.Fatalf("Failed to create output file: %s", err)
  353. }
  354. defer out.Close()
  355. recordingConn.Close()
  356. close(stdin)
  357. childProcess.Process.Kill()
  358. childProcess.Wait()
  359. if len(recordingConn.flows) < 3 {
  360. childProcess.Stdout.(*bytes.Buffer).WriteTo(os.Stdout)
  361. t.Fatalf("Client connection didn't work")
  362. }
  363. recordingConn.WriteTo(out)
  364. fmt.Printf("Wrote %s\n", path)
  365. }
  366. }
  367. func runClientTestForVersion(t *testing.T, template *clientTest, prefix, option string) {
  368. test := *template
  369. test.name = prefix + test.name
  370. if len(test.command) == 0 {
  371. test.command = defaultClientCommand
  372. }
  373. test.command = append([]string(nil), test.command...)
  374. test.command = append(test.command, option)
  375. test.run(t, *update)
  376. }
  377. func runClientTestTLS10(t *testing.T, template *clientTest) {
  378. runClientTestForVersion(t, template, "TLSv10-", "-tls1")
  379. }
  380. func runClientTestTLS11(t *testing.T, template *clientTest) {
  381. runClientTestForVersion(t, template, "TLSv11-", "-tls1_1")
  382. }
  383. func runClientTestTLS12(t *testing.T, template *clientTest) {
  384. runClientTestForVersion(t, template, "TLSv12-", "-tls1_2")
  385. }
  386. func TestHandshakeClientRSARC4(t *testing.T) {
  387. test := &clientTest{
  388. name: "RSA-RC4",
  389. command: []string{"openssl", "s_server", "-cipher", "RC4-SHA"},
  390. }
  391. runClientTestTLS10(t, test)
  392. runClientTestTLS11(t, test)
  393. runClientTestTLS12(t, test)
  394. }
  395. func TestHandshakeClientRSAAES128GCM(t *testing.T) {
  396. test := &clientTest{
  397. name: "AES128-GCM-SHA256",
  398. command: []string{"openssl", "s_server", "-cipher", "AES128-GCM-SHA256"},
  399. }
  400. runClientTestTLS12(t, test)
  401. }
  402. func TestHandshakeClientRSAAES256GCM(t *testing.T) {
  403. test := &clientTest{
  404. name: "AES256-GCM-SHA384",
  405. command: []string{"openssl", "s_server", "-cipher", "AES256-GCM-SHA384"},
  406. }
  407. runClientTestTLS12(t, test)
  408. }
  409. func TestHandshakeClientECDHERSAAES(t *testing.T) {
  410. test := &clientTest{
  411. name: "ECDHE-RSA-AES",
  412. command: []string{"openssl", "s_server", "-cipher", "ECDHE-RSA-AES128-SHA"},
  413. }
  414. runClientTestTLS10(t, test)
  415. runClientTestTLS11(t, test)
  416. runClientTestTLS12(t, test)
  417. }
  418. func TestHandshakeClientECDHEECDSAAES(t *testing.T) {
  419. test := &clientTest{
  420. name: "ECDHE-ECDSA-AES",
  421. command: []string{"openssl", "s_server", "-cipher", "ECDHE-ECDSA-AES128-SHA"},
  422. cert: testECDSACertificate,
  423. key: testECDSAPrivateKey,
  424. }
  425. runClientTestTLS10(t, test)
  426. runClientTestTLS11(t, test)
  427. runClientTestTLS12(t, test)
  428. }
  429. func TestHandshakeClientECDHEECDSAAESGCM(t *testing.T) {
  430. test := &clientTest{
  431. name: "ECDHE-ECDSA-AES-GCM",
  432. command: []string{"openssl", "s_server", "-cipher", "ECDHE-ECDSA-AES128-GCM-SHA256"},
  433. cert: testECDSACertificate,
  434. key: testECDSAPrivateKey,
  435. }
  436. runClientTestTLS12(t, test)
  437. }
  438. func TestHandshakeClientAES256GCMSHA384(t *testing.T) {
  439. test := &clientTest{
  440. name: "ECDHE-ECDSA-AES256-GCM-SHA384",
  441. command: []string{"openssl", "s_server", "-cipher", "ECDHE-ECDSA-AES256-GCM-SHA384"},
  442. cert: testECDSACertificate,
  443. key: testECDSAPrivateKey,
  444. }
  445. runClientTestTLS12(t, test)
  446. }
  447. func TestHandshakeClientAES128CBCSHA256(t *testing.T) {
  448. test := &clientTest{
  449. name: "AES128-SHA256",
  450. command: []string{"openssl", "s_server", "-cipher", "AES128-SHA256"},
  451. }
  452. runClientTestTLS12(t, test)
  453. }
  454. func TestHandshakeClientECDHERSAAES128CBCSHA256(t *testing.T) {
  455. test := &clientTest{
  456. name: "ECDHE-RSA-AES128-SHA256",
  457. command: []string{"openssl", "s_server", "-cipher", "ECDHE-RSA-AES128-SHA256"},
  458. }
  459. runClientTestTLS12(t, test)
  460. }
  461. func TestHandshakeClientECDHEECDSAAES128CBCSHA256(t *testing.T) {
  462. test := &clientTest{
  463. name: "ECDHE-ECDSA-AES128-SHA256",
  464. command: []string{"openssl", "s_server", "-cipher", "ECDHE-ECDSA-AES128-SHA256"},
  465. cert: testECDSACertificate,
  466. key: testECDSAPrivateKey,
  467. }
  468. runClientTestTLS12(t, test)
  469. }
  470. func TestHandshakeClientCertRSA(t *testing.T) {
  471. config := testConfig.Clone()
  472. cert, _ := X509KeyPair([]byte(clientCertificatePEM), []byte(clientKeyPEM))
  473. config.Certificates = []Certificate{cert}
  474. test := &clientTest{
  475. name: "ClientCert-RSA-RSA",
  476. command: []string{"openssl", "s_server", "-cipher", "RC4-SHA", "-verify", "1"},
  477. config: config,
  478. }
  479. runClientTestTLS10(t, test)
  480. runClientTestTLS12(t, test)
  481. test = &clientTest{
  482. name: "ClientCert-RSA-ECDSA",
  483. command: []string{"openssl", "s_server", "-cipher", "ECDHE-ECDSA-AES128-SHA", "-verify", "1"},
  484. config: config,
  485. cert: testECDSACertificate,
  486. key: testECDSAPrivateKey,
  487. }
  488. runClientTestTLS10(t, test)
  489. runClientTestTLS12(t, test)
  490. test = &clientTest{
  491. name: "ClientCert-RSA-AES256-GCM-SHA384",
  492. command: []string{"openssl", "s_server", "-cipher", "ECDHE-RSA-AES256-GCM-SHA384", "-verify", "1"},
  493. config: config,
  494. cert: testRSACertificate,
  495. key: testRSAPrivateKey,
  496. }
  497. runClientTestTLS12(t, test)
  498. }
  499. func TestHandshakeClientCertECDSA(t *testing.T) {
  500. config := testConfig.Clone()
  501. cert, _ := X509KeyPair([]byte(clientECDSACertificatePEM), []byte(clientECDSAKeyPEM))
  502. config.Certificates = []Certificate{cert}
  503. test := &clientTest{
  504. name: "ClientCert-ECDSA-RSA",
  505. command: []string{"openssl", "s_server", "-cipher", "RC4-SHA", "-verify", "1"},
  506. config: config,
  507. }
  508. runClientTestTLS10(t, test)
  509. runClientTestTLS12(t, test)
  510. test = &clientTest{
  511. name: "ClientCert-ECDSA-ECDSA",
  512. command: []string{"openssl", "s_server", "-cipher", "ECDHE-ECDSA-AES128-SHA", "-verify", "1"},
  513. config: config,
  514. cert: testECDSACertificate,
  515. key: testECDSAPrivateKey,
  516. }
  517. runClientTestTLS10(t, test)
  518. runClientTestTLS12(t, test)
  519. }
  520. func TestClientResumption(t *testing.T) {
  521. serverConfig := &Config{
  522. CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA},
  523. Certificates: testConfig.Certificates,
  524. }
  525. issuer, err := x509.ParseCertificate(testRSACertificateIssuer)
  526. if err != nil {
  527. panic(err)
  528. }
  529. rootCAs := x509.NewCertPool()
  530. rootCAs.AddCert(issuer)
  531. clientConfig := &Config{
  532. CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
  533. ClientSessionCache: NewLRUClientSessionCache(32),
  534. RootCAs: rootCAs,
  535. ServerName: "example.golang",
  536. }
  537. testResumeState := func(test string, didResume bool) {
  538. _, hs, err := testHandshake(clientConfig, serverConfig)
  539. if err != nil {
  540. t.Fatalf("%s: handshake failed: %s", test, err)
  541. }
  542. if hs.DidResume != didResume {
  543. t.Fatalf("%s resumed: %v, expected: %v", test, hs.DidResume, didResume)
  544. }
  545. if didResume && (hs.PeerCertificates == nil || hs.VerifiedChains == nil) {
  546. t.Fatalf("expected non-nil certificates after resumption. Got peerCertificates: %#v, verifiedCertificates: %#v", hs.PeerCertificates, hs.VerifiedChains)
  547. }
  548. }
  549. getTicket := func() []byte {
  550. return clientConfig.ClientSessionCache.(*lruSessionCache).q.Front().Value.(*lruSessionCacheEntry).state.sessionTicket
  551. }
  552. randomKey := func() [32]byte {
  553. var k [32]byte
  554. if _, err := io.ReadFull(serverConfig.rand(), k[:]); err != nil {
  555. t.Fatalf("Failed to read new SessionTicketKey: %s", err)
  556. }
  557. return k
  558. }
  559. testResumeState("Handshake", false)
  560. ticket := getTicket()
  561. testResumeState("Resume", true)
  562. if !bytes.Equal(ticket, getTicket()) {
  563. t.Fatal("first ticket doesn't match ticket after resumption")
  564. }
  565. key1 := randomKey()
  566. serverConfig.SetSessionTicketKeys([][32]byte{key1})
  567. testResumeState("InvalidSessionTicketKey", false)
  568. testResumeState("ResumeAfterInvalidSessionTicketKey", true)
  569. key2 := randomKey()
  570. serverConfig.SetSessionTicketKeys([][32]byte{key2, key1})
  571. ticket = getTicket()
  572. testResumeState("KeyChange", true)
  573. if bytes.Equal(ticket, getTicket()) {
  574. t.Fatal("new ticket wasn't included while resuming")
  575. }
  576. testResumeState("KeyChangeFinish", true)
  577. // Reset serverConfig to ensure that calling SetSessionTicketKeys
  578. // before the serverConfig is used works.
  579. serverConfig = &Config{
  580. CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA},
  581. Certificates: testConfig.Certificates,
  582. }
  583. serverConfig.SetSessionTicketKeys([][32]byte{key2})
  584. testResumeState("FreshConfig", true)
  585. clientConfig.CipherSuites = []uint16{TLS_ECDHE_RSA_WITH_RC4_128_SHA}
  586. testResumeState("DifferentCipherSuite", false)
  587. testResumeState("DifferentCipherSuiteRecovers", true)
  588. clientConfig.ClientSessionCache = nil
  589. testResumeState("WithoutSessionCache", false)
  590. }
  591. func TestLRUClientSessionCache(t *testing.T) {
  592. // Initialize cache of capacity 4.
  593. cache := NewLRUClientSessionCache(4)
  594. cs := make([]ClientSessionState, 6)
  595. keys := []string{"0", "1", "2", "3", "4", "5", "6"}
  596. // Add 4 entries to the cache and look them up.
  597. for i := 0; i < 4; i++ {
  598. cache.Put(keys[i], &cs[i])
  599. }
  600. for i := 0; i < 4; i++ {
  601. if s, ok := cache.Get(keys[i]); !ok || s != &cs[i] {
  602. t.Fatalf("session cache failed lookup for added key: %s", keys[i])
  603. }
  604. }
  605. // Add 2 more entries to the cache. First 2 should be evicted.
  606. for i := 4; i < 6; i++ {
  607. cache.Put(keys[i], &cs[i])
  608. }
  609. for i := 0; i < 2; i++ {
  610. if s, ok := cache.Get(keys[i]); ok || s != nil {
  611. t.Fatalf("session cache should have evicted key: %s", keys[i])
  612. }
  613. }
  614. // Touch entry 2. LRU should evict 3 next.
  615. cache.Get(keys[2])
  616. cache.Put(keys[0], &cs[0])
  617. if s, ok := cache.Get(keys[3]); ok || s != nil {
  618. t.Fatalf("session cache should have evicted key 3")
  619. }
  620. // Update entry 0 in place.
  621. cache.Put(keys[0], &cs[3])
  622. if s, ok := cache.Get(keys[0]); !ok || s != &cs[3] {
  623. t.Fatalf("session cache failed update for key 0")
  624. }
  625. // Adding a nil entry is valid.
  626. cache.Put(keys[0], nil)
  627. if s, ok := cache.Get(keys[0]); !ok || s != nil {
  628. t.Fatalf("failed to add nil entry to cache")
  629. }
  630. }
  631. func TestKeyLog(t *testing.T) {
  632. var serverBuf, clientBuf bytes.Buffer
  633. clientConfig := testConfig.Clone()
  634. clientConfig.KeyLogWriter = &clientBuf
  635. serverConfig := testConfig.Clone()
  636. serverConfig.KeyLogWriter = &serverBuf
  637. c, s := net.Pipe()
  638. done := make(chan bool)
  639. go func() {
  640. defer close(done)
  641. if err := Server(s, serverConfig).Handshake(); err != nil {
  642. t.Errorf("server: %s", err)
  643. return
  644. }
  645. s.Close()
  646. }()
  647. if err := Client(c, clientConfig).Handshake(); err != nil {
  648. t.Fatalf("client: %s", err)
  649. }
  650. c.Close()
  651. <-done
  652. checkKeylogLine := func(side, loggedLine string) {
  653. if len(loggedLine) == 0 {
  654. t.Fatalf("%s: no keylog line was produced", side)
  655. }
  656. const expectedLen = 13 /* "CLIENT_RANDOM" */ +
  657. 1 /* space */ +
  658. 32*2 /* hex client nonce */ +
  659. 1 /* space */ +
  660. 48*2 /* hex master secret */ +
  661. 1 /* new line */
  662. if len(loggedLine) != expectedLen {
  663. t.Fatalf("%s: keylog line has incorrect length (want %d, got %d): %q", side, expectedLen, len(loggedLine), loggedLine)
  664. }
  665. if !strings.HasPrefix(loggedLine, "CLIENT_RANDOM "+strings.Repeat("0", 64)+" ") {
  666. t.Fatalf("%s: keylog line has incorrect structure or nonce: %q", side, loggedLine)
  667. }
  668. }
  669. checkKeylogLine("client", string(clientBuf.Bytes()))
  670. checkKeylogLine("server", string(serverBuf.Bytes()))
  671. }
  672. func TestHandshakeClientALPNMatch(t *testing.T) {
  673. config := testConfig.Clone()
  674. config.NextProtos = []string{"proto2", "proto1"}
  675. test := &clientTest{
  676. name: "ALPN",
  677. // Note that this needs OpenSSL 1.0.2 because that is the first
  678. // version that supports the -alpn flag.
  679. command: []string{"openssl", "s_server", "-alpn", "proto1,proto2"},
  680. config: config,
  681. validate: func(state ConnectionState) error {
  682. // The server's preferences should override the client.
  683. if state.NegotiatedProtocol != "proto1" {
  684. return fmt.Errorf("Got protocol %q, wanted proto1", state.NegotiatedProtocol)
  685. }
  686. return nil
  687. },
  688. }
  689. runClientTestTLS12(t, test)
  690. }
  691. func TestHandshakeClientALPNNoMatch(t *testing.T) {
  692. config := testConfig.Clone()
  693. config.NextProtos = []string{"proto3"}
  694. test := &clientTest{
  695. name: "ALPN-NoMatch",
  696. // Note that this needs OpenSSL 1.0.2 because that is the first
  697. // version that supports the -alpn flag.
  698. command: []string{"openssl", "s_server", "-alpn", "proto1,proto2"},
  699. config: config,
  700. validate: func(state ConnectionState) error {
  701. // There's no overlap so OpenSSL will not select a protocol.
  702. if state.NegotiatedProtocol != "" {
  703. return fmt.Errorf("Got protocol %q, wanted ''", state.NegotiatedProtocol)
  704. }
  705. return nil
  706. },
  707. }
  708. runClientTestTLS12(t, test)
  709. }
  710. // sctsBase64 contains data from `openssl s_client -serverinfo 18 -connect ritter.vg:443`
  711. const sctsBase64 = "ABIBaQFnAHUApLkJkLQYWBSHuxOizGdwCjw1mAT5G9+443fNDsgN3BAAAAFHl5nuFgAABAMARjBEAiAcS4JdlW5nW9sElUv2zvQyPoZ6ejKrGGB03gjaBZFMLwIgc1Qbbn+hsH0RvObzhS+XZhr3iuQQJY8S9G85D9KeGPAAdgBo9pj4H2SCvjqM7rkoHUz8cVFdZ5PURNEKZ6y7T0/7xAAAAUeX4bVwAAAEAwBHMEUCIDIhFDgG2HIuADBkGuLobU5a4dlCHoJLliWJ1SYT05z6AiEAjxIoZFFPRNWMGGIjskOTMwXzQ1Wh2e7NxXE1kd1J0QsAdgDuS723dc5guuFCaR+r4Z5mow9+X7By2IMAxHuJeqj9ywAAAUhcZIqHAAAEAwBHMEUCICmJ1rBT09LpkbzxtUC+Hi7nXLR0J+2PmwLp+sJMuqK+AiEAr0NkUnEVKVhAkccIFpYDqHOlZaBsuEhWWrYpg2RtKp0="
  712. func TestHandshakClientSCTs(t *testing.T) {
  713. config := testConfig.Clone()
  714. scts, err := base64.StdEncoding.DecodeString(sctsBase64)
  715. if err != nil {
  716. t.Fatal(err)
  717. }
  718. test := &clientTest{
  719. name: "SCT",
  720. // Note that this needs OpenSSL 1.0.2 because that is the first
  721. // version that supports the -serverinfo flag.
  722. command: []string{"openssl", "s_server"},
  723. config: config,
  724. extensions: [][]byte{scts},
  725. validate: func(state ConnectionState) error {
  726. expectedSCTs := [][]byte{
  727. scts[8:125],
  728. scts[127:245],
  729. scts[247:],
  730. }
  731. if n := len(state.SignedCertificateTimestamps); n != len(expectedSCTs) {
  732. return fmt.Errorf("Got %d scts, wanted %d", n, len(expectedSCTs))
  733. }
  734. for i, expected := range expectedSCTs {
  735. if sct := state.SignedCertificateTimestamps[i]; !bytes.Equal(sct, expected) {
  736. return fmt.Errorf("SCT #%d contained %x, expected %x", i, sct, expected)
  737. }
  738. }
  739. return nil
  740. },
  741. }
  742. runClientTestTLS12(t, test)
  743. }
  744. func TestRenegotiationRejected(t *testing.T) {
  745. config := testConfig.Clone()
  746. test := &clientTest{
  747. name: "RenegotiationRejected",
  748. command: []string{"openssl", "s_server", "-state"},
  749. config: config,
  750. numRenegotiations: 1,
  751. renegotiationExpectedToFail: 1,
  752. checkRenegotiationError: func(renegotiationNum int, err error) error {
  753. if err == nil {
  754. return errors.New("expected error from renegotiation but got nil")
  755. }
  756. if !strings.Contains(err.Error(), "no renegotiation") {
  757. return fmt.Errorf("expected renegotiation to be rejected but got %q", err)
  758. }
  759. return nil
  760. },
  761. }
  762. runClientTestTLS12(t, test)
  763. }
  764. func TestRenegotiateOnce(t *testing.T) {
  765. config := testConfig.Clone()
  766. config.Renegotiation = RenegotiateOnceAsClient
  767. test := &clientTest{
  768. name: "RenegotiateOnce",
  769. command: []string{"openssl", "s_server", "-state"},
  770. config: config,
  771. numRenegotiations: 1,
  772. }
  773. runClientTestTLS12(t, test)
  774. }
  775. func TestRenegotiateTwice(t *testing.T) {
  776. config := testConfig.Clone()
  777. config.Renegotiation = RenegotiateFreelyAsClient
  778. test := &clientTest{
  779. name: "RenegotiateTwice",
  780. command: []string{"openssl", "s_server", "-state"},
  781. config: config,
  782. numRenegotiations: 2,
  783. }
  784. runClientTestTLS12(t, test)
  785. }
  786. func TestRenegotiateTwiceRejected(t *testing.T) {
  787. config := testConfig.Clone()
  788. config.Renegotiation = RenegotiateOnceAsClient
  789. test := &clientTest{
  790. name: "RenegotiateTwiceRejected",
  791. command: []string{"openssl", "s_server", "-state"},
  792. config: config,
  793. numRenegotiations: 2,
  794. renegotiationExpectedToFail: 2,
  795. checkRenegotiationError: func(renegotiationNum int, err error) error {
  796. if renegotiationNum == 1 {
  797. return err
  798. }
  799. if err == nil {
  800. return errors.New("expected error from renegotiation but got nil")
  801. }
  802. if !strings.Contains(err.Error(), "no renegotiation") {
  803. return fmt.Errorf("expected renegotiation to be rejected but got %q", err)
  804. }
  805. return nil
  806. },
  807. }
  808. runClientTestTLS12(t, test)
  809. }
  810. var hostnameInSNITests = []struct {
  811. in, out string
  812. }{
  813. // Opaque string
  814. {"", ""},
  815. {"localhost", "localhost"},
  816. {"foo, bar, baz and qux", "foo, bar, baz and qux"},
  817. // DNS hostname
  818. {"golang.org", "golang.org"},
  819. {"golang.org.", "golang.org"},
  820. // Literal IPv4 address
  821. {"1.2.3.4", ""},
  822. // Literal IPv6 address
  823. {"::1", ""},
  824. {"::1%lo0", ""}, // with zone identifier
  825. {"[::1]", ""}, // as per RFC 5952 we allow the [] style as IPv6 literal
  826. {"[::1%lo0]", ""},
  827. }
  828. func TestHostnameInSNI(t *testing.T) {
  829. for _, tt := range hostnameInSNITests {
  830. c, s := net.Pipe()
  831. go func(host string) {
  832. Client(c, &Config{ServerName: host, InsecureSkipVerify: true}).Handshake()
  833. }(tt.in)
  834. var header [5]byte
  835. if _, err := io.ReadFull(s, header[:]); err != nil {
  836. t.Fatal(err)
  837. }
  838. recordLen := int(header[3])<<8 | int(header[4])
  839. record := make([]byte, recordLen)
  840. if _, err := io.ReadFull(s, record[:]); err != nil {
  841. t.Fatal(err)
  842. }
  843. c.Close()
  844. s.Close()
  845. var m clientHelloMsg
  846. if !m.unmarshal(record) {
  847. t.Errorf("unmarshaling ClientHello for %q failed", tt.in)
  848. continue
  849. }
  850. if tt.in != tt.out && m.serverName == tt.in {
  851. t.Errorf("prohibited %q found in ClientHello: %x", tt.in, record)
  852. }
  853. if m.serverName != tt.out {
  854. t.Errorf("expected %q not found in ClientHello: %x", tt.out, record)
  855. }
  856. }
  857. }
  858. func TestServerSelectingUnconfiguredCipherSuite(t *testing.T) {
  859. // This checks that the server can't select a cipher suite that the
  860. // client didn't offer. See #13174.
  861. c, s := net.Pipe()
  862. errChan := make(chan error, 1)
  863. go func() {
  864. client := Client(c, &Config{
  865. ServerName: "foo",
  866. CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
  867. })
  868. errChan <- client.Handshake()
  869. }()
  870. var header [5]byte
  871. if _, err := io.ReadFull(s, header[:]); err != nil {
  872. t.Fatal(err)
  873. }
  874. recordLen := int(header[3])<<8 | int(header[4])
  875. record := make([]byte, recordLen)
  876. if _, err := io.ReadFull(s, record); err != nil {
  877. t.Fatal(err)
  878. }
  879. // Create a ServerHello that selects a different cipher suite than the
  880. // sole one that the client offered.
  881. serverHello := &serverHelloMsg{
  882. vers: VersionTLS12,
  883. random: make([]byte, 32),
  884. cipherSuite: TLS_RSA_WITH_AES_256_GCM_SHA384,
  885. }
  886. serverHelloBytes := serverHello.marshal()
  887. s.Write([]byte{
  888. byte(recordTypeHandshake),
  889. byte(VersionTLS12 >> 8),
  890. byte(VersionTLS12 & 0xff),
  891. byte(len(serverHelloBytes) >> 8),
  892. byte(len(serverHelloBytes)),
  893. })
  894. s.Write(serverHelloBytes)
  895. s.Close()
  896. if err := <-errChan; !strings.Contains(err.Error(), "unconfigured cipher") {
  897. t.Fatalf("Expected error about unconfigured cipher suite but got %q", err)
  898. }
  899. }
  900. // brokenConn wraps a net.Conn and causes all Writes after a certain number to
  901. // fail with brokenConnErr.
  902. type brokenConn struct {
  903. net.Conn
  904. // breakAfter is the number of successful writes that will be allowed
  905. // before all subsequent writes fail.
  906. breakAfter int
  907. // numWrites is the number of writes that have been done.
  908. numWrites int
  909. }
  910. // brokenConnErr is the error that brokenConn returns once exhausted.
  911. var brokenConnErr = errors.New("too many writes to brokenConn")
  912. func (b *brokenConn) Write(data []byte) (int, error) {
  913. if b.numWrites >= b.breakAfter {
  914. return 0, brokenConnErr
  915. }
  916. b.numWrites++
  917. return b.Conn.Write(data)
  918. }
  919. func TestFailedWrite(t *testing.T) {
  920. // Test that a write error during the handshake is returned.
  921. for _, breakAfter := range []int{0, 1} {
  922. c, s := net.Pipe()
  923. done := make(chan bool)
  924. go func() {
  925. Server(s, testConfig).Handshake()
  926. s.Close()
  927. done <- true
  928. }()
  929. brokenC := &brokenConn{Conn: c, breakAfter: breakAfter}
  930. err := Client(brokenC, testConfig).Handshake()
  931. if err != brokenConnErr {
  932. t.Errorf("#%d: expected error from brokenConn but got %q", breakAfter, err)
  933. }
  934. brokenC.Close()
  935. <-done
  936. }
  937. }
  938. // writeCountingConn wraps a net.Conn and counts the number of Write calls.
  939. type writeCountingConn struct {
  940. net.Conn
  941. // numWrites is the number of writes that have been done.
  942. numWrites int
  943. }
  944. func (wcc *writeCountingConn) Write(data []byte) (int, error) {
  945. wcc.numWrites++
  946. return wcc.Conn.Write(data)
  947. }
  948. func TestBuffering(t *testing.T) {
  949. c, s := net.Pipe()
  950. done := make(chan bool)
  951. clientWCC := &writeCountingConn{Conn: c}
  952. serverWCC := &writeCountingConn{Conn: s}
  953. go func() {
  954. Server(serverWCC, testConfig).Handshake()
  955. serverWCC.Close()
  956. done <- true
  957. }()
  958. err := Client(clientWCC, testConfig).Handshake()
  959. if err != nil {
  960. t.Fatal(err)
  961. }
  962. clientWCC.Close()
  963. <-done
  964. if n := clientWCC.numWrites; n != 2 {
  965. t.Errorf("expected client handshake to complete with only two writes, but saw %d", n)
  966. }
  967. if n := serverWCC.numWrites; n != 2 {
  968. t.Errorf("expected server handshake to complete with only two writes, but saw %d", n)
  969. }
  970. }
  971. func TestAlertFlushing(t *testing.T) {
  972. c, s := net.Pipe()
  973. done := make(chan bool)
  974. clientWCC := &writeCountingConn{Conn: c}
  975. serverWCC := &writeCountingConn{Conn: s}
  976. serverConfig := testConfig.Clone()
  977. // Cause a signature-time error
  978. brokenKey := rsa.PrivateKey{PublicKey: testRSAPrivateKey.PublicKey}
  979. brokenKey.D = big.NewInt(42)
  980. serverConfig.Certificates = []Certificate{{
  981. Certificate: [][]byte{testRSACertificate},
  982. PrivateKey: &brokenKey,
  983. }}
  984. go func() {
  985. Server(serverWCC, serverConfig).Handshake()
  986. serverWCC.Close()
  987. done <- true
  988. }()
  989. err := Client(clientWCC, testConfig).Handshake()
  990. if err == nil {
  991. t.Fatal("client unexpectedly returned no error")
  992. }
  993. const expectedError = "remote error: tls: handshake failure"
  994. if e := err.Error(); !strings.Contains(e, expectedError) {
  995. t.Fatalf("expected to find %q in error but error was %q", expectedError, e)
  996. }
  997. clientWCC.Close()
  998. <-done
  999. if n := clientWCC.numWrites; n != 1 {
  1000. t.Errorf("expected client handshake to complete with one write, but saw %d", n)
  1001. }
  1002. if n := serverWCC.numWrites; n != 1 {
  1003. t.Errorf("expected server handshake to complete with one write, but saw %d", n)
  1004. }
  1005. }
  1006. func TestHandshakeRace(t *testing.T) {
  1007. // This test races a Read and Write to try and complete a handshake in
  1008. // order to provide some evidence that there are no races or deadlocks
  1009. // in the handshake locking.
  1010. for i := 0; i < 32; i++ {
  1011. c, s := net.Pipe()
  1012. go func() {
  1013. server := Server(s, testConfig)
  1014. if err := server.Handshake(); err != nil {
  1015. panic(err)
  1016. }
  1017. var request [1]byte
  1018. if n, err := server.Read(request[:]); err != nil || n != 1 {
  1019. panic(err)
  1020. }
  1021. server.Write(request[:])
  1022. server.Close()
  1023. }()
  1024. startWrite := make(chan struct{})
  1025. startRead := make(chan struct{})
  1026. readDone := make(chan struct{})
  1027. client := Client(c, testConfig)
  1028. go func() {
  1029. <-startWrite
  1030. var request [1]byte
  1031. client.Write(request[:])
  1032. }()
  1033. go func() {
  1034. <-startRead
  1035. var reply [1]byte
  1036. if n, err := client.Read(reply[:]); err != nil || n != 1 {
  1037. panic(err)
  1038. }
  1039. c.Close()
  1040. readDone <- struct{}{}
  1041. }()
  1042. if i&1 == 1 {
  1043. startWrite <- struct{}{}
  1044. startRead <- struct{}{}
  1045. } else {
  1046. startRead <- struct{}{}
  1047. startWrite <- struct{}{}
  1048. }
  1049. <-readDone
  1050. }
  1051. }