No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 
 
 

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