handshake_client_test.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101
  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 TestHandshakeClientCertRSA(t *testing.T) {
  447. config := testConfig.clone()
  448. cert, _ := X509KeyPair([]byte(clientCertificatePEM), []byte(clientKeyPEM))
  449. config.Certificates = []Certificate{cert}
  450. test := &clientTest{
  451. name: "ClientCert-RSA-RSA",
  452. command: []string{"openssl", "s_server", "-cipher", "RC4-SHA", "-verify", "1"},
  453. config: config,
  454. }
  455. runClientTestTLS10(t, test)
  456. runClientTestTLS12(t, test)
  457. test = &clientTest{
  458. name: "ClientCert-RSA-ECDSA",
  459. command: []string{"openssl", "s_server", "-cipher", "ECDHE-ECDSA-AES128-SHA", "-verify", "1"},
  460. config: config,
  461. cert: testECDSACertificate,
  462. key: testECDSAPrivateKey,
  463. }
  464. runClientTestTLS10(t, test)
  465. runClientTestTLS12(t, test)
  466. test = &clientTest{
  467. name: "ClientCert-RSA-AES256-GCM-SHA384",
  468. command: []string{"openssl", "s_server", "-cipher", "ECDHE-RSA-AES256-GCM-SHA384", "-verify", "1"},
  469. config: config,
  470. cert: testRSACertificate,
  471. key: testRSAPrivateKey,
  472. }
  473. runClientTestTLS12(t, test)
  474. }
  475. func TestHandshakeClientCertECDSA(t *testing.T) {
  476. config := testConfig.clone()
  477. cert, _ := X509KeyPair([]byte(clientECDSACertificatePEM), []byte(clientECDSAKeyPEM))
  478. config.Certificates = []Certificate{cert}
  479. test := &clientTest{
  480. name: "ClientCert-ECDSA-RSA",
  481. command: []string{"openssl", "s_server", "-cipher", "RC4-SHA", "-verify", "1"},
  482. config: config,
  483. }
  484. runClientTestTLS10(t, test)
  485. runClientTestTLS12(t, test)
  486. test = &clientTest{
  487. name: "ClientCert-ECDSA-ECDSA",
  488. command: []string{"openssl", "s_server", "-cipher", "ECDHE-ECDSA-AES128-SHA", "-verify", "1"},
  489. config: config,
  490. cert: testECDSACertificate,
  491. key: testECDSAPrivateKey,
  492. }
  493. runClientTestTLS10(t, test)
  494. runClientTestTLS12(t, test)
  495. }
  496. func TestClientResumption(t *testing.T) {
  497. serverConfig := &Config{
  498. CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA},
  499. Certificates: testConfig.Certificates,
  500. }
  501. issuer, err := x509.ParseCertificate(testRSACertificateIssuer)
  502. if err != nil {
  503. panic(err)
  504. }
  505. rootCAs := x509.NewCertPool()
  506. rootCAs.AddCert(issuer)
  507. clientConfig := &Config{
  508. CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
  509. ClientSessionCache: NewLRUClientSessionCache(32),
  510. RootCAs: rootCAs,
  511. ServerName: "example.golang",
  512. }
  513. testResumeState := func(test string, didResume bool) {
  514. _, hs, err := testHandshake(clientConfig, serverConfig)
  515. if err != nil {
  516. t.Fatalf("%s: handshake failed: %s", test, err)
  517. }
  518. if hs.DidResume != didResume {
  519. t.Fatalf("%s resumed: %v, expected: %v", test, hs.DidResume, didResume)
  520. }
  521. if didResume && (hs.PeerCertificates == nil || hs.VerifiedChains == nil) {
  522. t.Fatalf("expected non-nil certificates after resumption. Got peerCertificates: %#v, verifiedCertificates: %#v", hs.PeerCertificates, hs.VerifiedChains)
  523. }
  524. }
  525. getTicket := func() []byte {
  526. return clientConfig.ClientSessionCache.(*lruSessionCache).q.Front().Value.(*lruSessionCacheEntry).state.sessionTicket
  527. }
  528. randomKey := func() [32]byte {
  529. var k [32]byte
  530. if _, err := io.ReadFull(serverConfig.rand(), k[:]); err != nil {
  531. t.Fatalf("Failed to read new SessionTicketKey: %s", err)
  532. }
  533. return k
  534. }
  535. testResumeState("Handshake", false)
  536. ticket := getTicket()
  537. testResumeState("Resume", true)
  538. if !bytes.Equal(ticket, getTicket()) {
  539. t.Fatal("first ticket doesn't match ticket after resumption")
  540. }
  541. key2 := randomKey()
  542. serverConfig.SetSessionTicketKeys([][32]byte{key2})
  543. testResumeState("InvalidSessionTicketKey", false)
  544. testResumeState("ResumeAfterInvalidSessionTicketKey", true)
  545. serverConfig.SetSessionTicketKeys([][32]byte{randomKey(), key2})
  546. ticket = getTicket()
  547. testResumeState("KeyChange", true)
  548. if bytes.Equal(ticket, getTicket()) {
  549. t.Fatal("new ticket wasn't included while resuming")
  550. }
  551. testResumeState("KeyChangeFinish", true)
  552. clientConfig.CipherSuites = []uint16{TLS_ECDHE_RSA_WITH_RC4_128_SHA}
  553. testResumeState("DifferentCipherSuite", false)
  554. testResumeState("DifferentCipherSuiteRecovers", true)
  555. clientConfig.ClientSessionCache = nil
  556. testResumeState("WithoutSessionCache", false)
  557. }
  558. func TestLRUClientSessionCache(t *testing.T) {
  559. // Initialize cache of capacity 4.
  560. cache := NewLRUClientSessionCache(4)
  561. cs := make([]ClientSessionState, 6)
  562. keys := []string{"0", "1", "2", "3", "4", "5", "6"}
  563. // Add 4 entries to the cache and look them up.
  564. for i := 0; i < 4; i++ {
  565. cache.Put(keys[i], &cs[i])
  566. }
  567. for i := 0; i < 4; i++ {
  568. if s, ok := cache.Get(keys[i]); !ok || s != &cs[i] {
  569. t.Fatalf("session cache failed lookup for added key: %s", keys[i])
  570. }
  571. }
  572. // Add 2 more entries to the cache. First 2 should be evicted.
  573. for i := 4; i < 6; i++ {
  574. cache.Put(keys[i], &cs[i])
  575. }
  576. for i := 0; i < 2; i++ {
  577. if s, ok := cache.Get(keys[i]); ok || s != nil {
  578. t.Fatalf("session cache should have evicted key: %s", keys[i])
  579. }
  580. }
  581. // Touch entry 2. LRU should evict 3 next.
  582. cache.Get(keys[2])
  583. cache.Put(keys[0], &cs[0])
  584. if s, ok := cache.Get(keys[3]); ok || s != nil {
  585. t.Fatalf("session cache should have evicted key 3")
  586. }
  587. // Update entry 0 in place.
  588. cache.Put(keys[0], &cs[3])
  589. if s, ok := cache.Get(keys[0]); !ok || s != &cs[3] {
  590. t.Fatalf("session cache failed update for key 0")
  591. }
  592. // Adding a nil entry is valid.
  593. cache.Put(keys[0], nil)
  594. if s, ok := cache.Get(keys[0]); !ok || s != nil {
  595. t.Fatalf("failed to add nil entry to cache")
  596. }
  597. }
  598. func TestHandshakeClientALPNMatch(t *testing.T) {
  599. config := testConfig.clone()
  600. config.NextProtos = []string{"proto2", "proto1"}
  601. test := &clientTest{
  602. name: "ALPN",
  603. // Note that this needs OpenSSL 1.0.2 because that is the first
  604. // version that supports the -alpn flag.
  605. command: []string{"openssl", "s_server", "-alpn", "proto1,proto2"},
  606. config: config,
  607. validate: func(state ConnectionState) error {
  608. // The server's preferences should override the client.
  609. if state.NegotiatedProtocol != "proto1" {
  610. return fmt.Errorf("Got protocol %q, wanted proto1", state.NegotiatedProtocol)
  611. }
  612. return nil
  613. },
  614. }
  615. runClientTestTLS12(t, test)
  616. }
  617. func TestHandshakeClientALPNNoMatch(t *testing.T) {
  618. config := testConfig.clone()
  619. config.NextProtos = []string{"proto3"}
  620. test := &clientTest{
  621. name: "ALPN-NoMatch",
  622. // Note that this needs OpenSSL 1.0.2 because that is the first
  623. // version that supports the -alpn flag.
  624. command: []string{"openssl", "s_server", "-alpn", "proto1,proto2"},
  625. config: config,
  626. validate: func(state ConnectionState) error {
  627. // There's no overlap so OpenSSL will not select a protocol.
  628. if state.NegotiatedProtocol != "" {
  629. return fmt.Errorf("Got protocol %q, wanted ''", state.NegotiatedProtocol)
  630. }
  631. return nil
  632. },
  633. }
  634. runClientTestTLS12(t, test)
  635. }
  636. // sctsBase64 contains data from `openssl s_client -serverinfo 18 -connect ritter.vg:443`
  637. const sctsBase64 = "ABIBaQFnAHUApLkJkLQYWBSHuxOizGdwCjw1mAT5G9+443fNDsgN3BAAAAFHl5nuFgAABAMARjBEAiAcS4JdlW5nW9sElUv2zvQyPoZ6ejKrGGB03gjaBZFMLwIgc1Qbbn+hsH0RvObzhS+XZhr3iuQQJY8S9G85D9KeGPAAdgBo9pj4H2SCvjqM7rkoHUz8cVFdZ5PURNEKZ6y7T0/7xAAAAUeX4bVwAAAEAwBHMEUCIDIhFDgG2HIuADBkGuLobU5a4dlCHoJLliWJ1SYT05z6AiEAjxIoZFFPRNWMGGIjskOTMwXzQ1Wh2e7NxXE1kd1J0QsAdgDuS723dc5guuFCaR+r4Z5mow9+X7By2IMAxHuJeqj9ywAAAUhcZIqHAAAEAwBHMEUCICmJ1rBT09LpkbzxtUC+Hi7nXLR0J+2PmwLp+sJMuqK+AiEAr0NkUnEVKVhAkccIFpYDqHOlZaBsuEhWWrYpg2RtKp0="
  638. func TestHandshakClientSCTs(t *testing.T) {
  639. config := testConfig.clone()
  640. scts, err := base64.StdEncoding.DecodeString(sctsBase64)
  641. if err != nil {
  642. t.Fatal(err)
  643. }
  644. test := &clientTest{
  645. name: "SCT",
  646. // Note that this needs OpenSSL 1.0.2 because that is the first
  647. // version that supports the -serverinfo flag.
  648. command: []string{"openssl", "s_server"},
  649. config: config,
  650. extensions: [][]byte{scts},
  651. validate: func(state ConnectionState) error {
  652. expectedSCTs := [][]byte{
  653. scts[8:125],
  654. scts[127:245],
  655. scts[247:],
  656. }
  657. if n := len(state.SignedCertificateTimestamps); n != len(expectedSCTs) {
  658. return fmt.Errorf("Got %d scts, wanted %d", n, len(expectedSCTs))
  659. }
  660. for i, expected := range expectedSCTs {
  661. if sct := state.SignedCertificateTimestamps[i]; !bytes.Equal(sct, expected) {
  662. return fmt.Errorf("SCT #%d contained %x, expected %x", i, sct, expected)
  663. }
  664. }
  665. return nil
  666. },
  667. }
  668. runClientTestTLS12(t, test)
  669. }
  670. func TestRenegotiationRejected(t *testing.T) {
  671. config := testConfig.clone()
  672. test := &clientTest{
  673. name: "RenegotiationRejected",
  674. command: []string{"openssl", "s_server", "-state"},
  675. config: config,
  676. numRenegotiations: 1,
  677. renegotiationExpectedToFail: 1,
  678. checkRenegotiationError: func(renegotiationNum int, err error) error {
  679. if err == nil {
  680. return errors.New("expected error from renegotiation but got nil")
  681. }
  682. if !strings.Contains(err.Error(), "no renegotiation") {
  683. return fmt.Errorf("expected renegotiation to be rejected but got %q", err)
  684. }
  685. return nil
  686. },
  687. }
  688. runClientTestTLS12(t, test)
  689. }
  690. func TestRenegotiateOnce(t *testing.T) {
  691. config := testConfig.clone()
  692. config.Renegotiation = RenegotiateOnceAsClient
  693. test := &clientTest{
  694. name: "RenegotiateOnce",
  695. command: []string{"openssl", "s_server", "-state"},
  696. config: config,
  697. numRenegotiations: 1,
  698. }
  699. runClientTestTLS12(t, test)
  700. }
  701. func TestRenegotiateTwice(t *testing.T) {
  702. config := testConfig.clone()
  703. config.Renegotiation = RenegotiateFreelyAsClient
  704. test := &clientTest{
  705. name: "RenegotiateTwice",
  706. command: []string{"openssl", "s_server", "-state"},
  707. config: config,
  708. numRenegotiations: 2,
  709. }
  710. runClientTestTLS12(t, test)
  711. }
  712. func TestRenegotiateTwiceRejected(t *testing.T) {
  713. config := testConfig.clone()
  714. config.Renegotiation = RenegotiateOnceAsClient
  715. test := &clientTest{
  716. name: "RenegotiateTwiceRejected",
  717. command: []string{"openssl", "s_server", "-state"},
  718. config: config,
  719. numRenegotiations: 2,
  720. renegotiationExpectedToFail: 2,
  721. checkRenegotiationError: func(renegotiationNum int, err error) error {
  722. if renegotiationNum == 1 {
  723. return err
  724. }
  725. if err == nil {
  726. return errors.New("expected error from renegotiation but got nil")
  727. }
  728. if !strings.Contains(err.Error(), "no renegotiation") {
  729. return fmt.Errorf("expected renegotiation to be rejected but got %q", err)
  730. }
  731. return nil
  732. },
  733. }
  734. runClientTestTLS12(t, test)
  735. }
  736. var hostnameInSNITests = []struct {
  737. in, out string
  738. }{
  739. // Opaque string
  740. {"", ""},
  741. {"localhost", "localhost"},
  742. {"foo, bar, baz and qux", "foo, bar, baz and qux"},
  743. // DNS hostname
  744. {"golang.org", "golang.org"},
  745. {"golang.org.", "golang.org"},
  746. // Literal IPv4 address
  747. {"1.2.3.4", ""},
  748. // Literal IPv6 address
  749. {"::1", ""},
  750. {"::1%lo0", ""}, // with zone identifier
  751. {"[::1]", ""}, // as per RFC 5952 we allow the [] style as IPv6 literal
  752. {"[::1%lo0]", ""},
  753. }
  754. func TestHostnameInSNI(t *testing.T) {
  755. for _, tt := range hostnameInSNITests {
  756. c, s := net.Pipe()
  757. go func(host string) {
  758. Client(c, &Config{ServerName: host, InsecureSkipVerify: true}).Handshake()
  759. }(tt.in)
  760. var header [5]byte
  761. if _, err := io.ReadFull(s, header[:]); err != nil {
  762. t.Fatal(err)
  763. }
  764. recordLen := int(header[3])<<8 | int(header[4])
  765. record := make([]byte, recordLen)
  766. if _, err := io.ReadFull(s, record[:]); err != nil {
  767. t.Fatal(err)
  768. }
  769. c.Close()
  770. s.Close()
  771. var m clientHelloMsg
  772. if !m.unmarshal(record) {
  773. t.Errorf("unmarshaling ClientHello for %q failed", tt.in)
  774. continue
  775. }
  776. if tt.in != tt.out && m.serverName == tt.in {
  777. t.Errorf("prohibited %q found in ClientHello: %x", tt.in, record)
  778. }
  779. if m.serverName != tt.out {
  780. t.Errorf("expected %q not found in ClientHello: %x", tt.out, record)
  781. }
  782. }
  783. }
  784. func TestServerSelectingUnconfiguredCipherSuite(t *testing.T) {
  785. // This checks that the server can't select a cipher suite that the
  786. // client didn't offer. See #13174.
  787. c, s := net.Pipe()
  788. errChan := make(chan error, 1)
  789. go func() {
  790. client := Client(c, &Config{
  791. ServerName: "foo",
  792. CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
  793. })
  794. errChan <- client.Handshake()
  795. }()
  796. var header [5]byte
  797. if _, err := io.ReadFull(s, header[:]); err != nil {
  798. t.Fatal(err)
  799. }
  800. recordLen := int(header[3])<<8 | int(header[4])
  801. record := make([]byte, recordLen)
  802. if _, err := io.ReadFull(s, record); err != nil {
  803. t.Fatal(err)
  804. }
  805. // Create a ServerHello that selects a different cipher suite than the
  806. // sole one that the client offered.
  807. serverHello := &serverHelloMsg{
  808. vers: VersionTLS12,
  809. random: make([]byte, 32),
  810. cipherSuite: TLS_RSA_WITH_AES_256_GCM_SHA384,
  811. }
  812. serverHelloBytes := serverHello.marshal()
  813. s.Write([]byte{
  814. byte(recordTypeHandshake),
  815. byte(VersionTLS12 >> 8),
  816. byte(VersionTLS12 & 0xff),
  817. byte(len(serverHelloBytes) >> 8),
  818. byte(len(serverHelloBytes)),
  819. })
  820. s.Write(serverHelloBytes)
  821. s.Close()
  822. if err := <-errChan; !strings.Contains(err.Error(), "unconfigured cipher") {
  823. t.Fatalf("Expected error about unconfigured cipher suite but got %q", err)
  824. }
  825. }
  826. // brokenConn wraps a net.Conn and causes all Writes after a certain number to
  827. // fail with brokenConnErr.
  828. type brokenConn struct {
  829. net.Conn
  830. // breakAfter is the number of successful writes that will be allowed
  831. // before all subsequent writes fail.
  832. breakAfter int
  833. // numWrites is the number of writes that have been done.
  834. numWrites int
  835. }
  836. // brokenConnErr is the error that brokenConn returns once exhausted.
  837. var brokenConnErr = errors.New("too many writes to brokenConn")
  838. func (b *brokenConn) Write(data []byte) (int, error) {
  839. if b.numWrites >= b.breakAfter {
  840. return 0, brokenConnErr
  841. }
  842. b.numWrites++
  843. return b.Conn.Write(data)
  844. }
  845. func TestFailedWrite(t *testing.T) {
  846. // Test that a write error during the handshake is returned.
  847. for _, breakAfter := range []int{0, 1} {
  848. c, s := net.Pipe()
  849. done := make(chan bool)
  850. go func() {
  851. Server(s, testConfig).Handshake()
  852. s.Close()
  853. done <- true
  854. }()
  855. brokenC := &brokenConn{Conn: c, breakAfter: breakAfter}
  856. err := Client(brokenC, testConfig).Handshake()
  857. if err != brokenConnErr {
  858. t.Errorf("#%d: expected error from brokenConn but got %q", breakAfter, err)
  859. }
  860. brokenC.Close()
  861. <-done
  862. }
  863. }
  864. // writeCountingConn wraps a net.Conn and counts the number of Write calls.
  865. type writeCountingConn struct {
  866. net.Conn
  867. // numWrites is the number of writes that have been done.
  868. numWrites int
  869. }
  870. func (wcc *writeCountingConn) Write(data []byte) (int, error) {
  871. wcc.numWrites++
  872. return wcc.Conn.Write(data)
  873. }
  874. func TestBuffering(t *testing.T) {
  875. c, s := net.Pipe()
  876. done := make(chan bool)
  877. clientWCC := &writeCountingConn{Conn: c}
  878. serverWCC := &writeCountingConn{Conn: s}
  879. go func() {
  880. Server(serverWCC, testConfig).Handshake()
  881. serverWCC.Close()
  882. done <- true
  883. }()
  884. err := Client(clientWCC, testConfig).Handshake()
  885. if err != nil {
  886. t.Fatal(err)
  887. }
  888. clientWCC.Close()
  889. <-done
  890. if n := clientWCC.numWrites; n != 2 {
  891. t.Errorf("expected client handshake to complete with only two writes, but saw %d", n)
  892. }
  893. if n := serverWCC.numWrites; n != 2 {
  894. t.Errorf("expected server handshake to complete with only two writes, but saw %d", n)
  895. }
  896. }
  897. func TestHandshakeRace(t *testing.T) {
  898. // This test races a Read and Write to try and complete a handshake in
  899. // order to provide some evidence that there are no races or deadlocks
  900. // in the handshake locking.
  901. for i := 0; i < 32; i++ {
  902. c, s := net.Pipe()
  903. go func() {
  904. server := Server(s, testConfig)
  905. if err := server.Handshake(); err != nil {
  906. panic(err)
  907. }
  908. var request [1]byte
  909. if n, err := server.Read(request[:]); err != nil || n != 1 {
  910. panic(err)
  911. }
  912. server.Write(request[:])
  913. server.Close()
  914. }()
  915. startWrite := make(chan struct{})
  916. startRead := make(chan struct{})
  917. readDone := make(chan struct{})
  918. client := Client(c, testConfig)
  919. go func() {
  920. <-startWrite
  921. var request [1]byte
  922. client.Write(request[:])
  923. }()
  924. go func() {
  925. <-startRead
  926. var reply [1]byte
  927. if n, err := client.Read(reply[:]); err != nil || n != 1 {
  928. panic(err)
  929. }
  930. c.Close()
  931. readDone <- struct{}{}
  932. }()
  933. if i&1 == 1 {
  934. startWrite <- struct{}{}
  935. startRead <- struct{}{}
  936. } else {
  937. startRead <- struct{}{}
  938. startWrite <- struct{}{}
  939. }
  940. <-readDone
  941. }
  942. }