Alternative TLS implementation in Go
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.

handshake_client_test.go 30 KiB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084
  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. key1 := randomKey()
  565. serverConfig.SetSessionTicketKeys([][32]byte{key1})
  566. testResumeState("InvalidSessionTicketKey", false)
  567. testResumeState("ResumeAfterInvalidSessionTicketKey", true)
  568. key2 := randomKey()
  569. serverConfig.SetSessionTicketKeys([][32]byte{key2, key1})
  570. ticket = getTicket()
  571. testResumeState("KeyChange", true)
  572. if bytes.Equal(ticket, getTicket()) {
  573. t.Fatal("new ticket wasn't included while resuming")
  574. }
  575. testResumeState("KeyChangeFinish", true)
  576. // Reset serverConfig to ensure that calling SetSessionTicketKeys
  577. // before the serverConfig is used works.
  578. serverConfig = &Config{
  579. CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA},
  580. Certificates: testConfig.Certificates,
  581. }
  582. serverConfig.SetSessionTicketKeys([][32]byte{key2})
  583. testResumeState("FreshConfig", true)
  584. clientConfig.CipherSuites = []uint16{TLS_ECDHE_RSA_WITH_RC4_128_SHA}
  585. testResumeState("DifferentCipherSuite", false)
  586. testResumeState("DifferentCipherSuiteRecovers", true)
  587. clientConfig.ClientSessionCache = nil
  588. testResumeState("WithoutSessionCache", false)
  589. }
  590. func TestLRUClientSessionCache(t *testing.T) {
  591. // Initialize cache of capacity 4.
  592. cache := NewLRUClientSessionCache(4)
  593. cs := make([]ClientSessionState, 6)
  594. keys := []string{"0", "1", "2", "3", "4", "5", "6"}
  595. // Add 4 entries to the cache and look them up.
  596. for i := 0; i < 4; i++ {
  597. cache.Put(keys[i], &cs[i])
  598. }
  599. for i := 0; i < 4; i++ {
  600. if s, ok := cache.Get(keys[i]); !ok || s != &cs[i] {
  601. t.Fatalf("session cache failed lookup for added key: %s", keys[i])
  602. }
  603. }
  604. // Add 2 more entries to the cache. First 2 should be evicted.
  605. for i := 4; i < 6; i++ {
  606. cache.Put(keys[i], &cs[i])
  607. }
  608. for i := 0; i < 2; i++ {
  609. if s, ok := cache.Get(keys[i]); ok || s != nil {
  610. t.Fatalf("session cache should have evicted key: %s", keys[i])
  611. }
  612. }
  613. // Touch entry 2. LRU should evict 3 next.
  614. cache.Get(keys[2])
  615. cache.Put(keys[0], &cs[0])
  616. if s, ok := cache.Get(keys[3]); ok || s != nil {
  617. t.Fatalf("session cache should have evicted key 3")
  618. }
  619. // Update entry 0 in place.
  620. cache.Put(keys[0], &cs[3])
  621. if s, ok := cache.Get(keys[0]); !ok || s != &cs[3] {
  622. t.Fatalf("session cache failed update for key 0")
  623. }
  624. // Adding a nil entry is valid.
  625. cache.Put(keys[0], nil)
  626. if s, ok := cache.Get(keys[0]); !ok || s != nil {
  627. t.Fatalf("failed to add nil entry to cache")
  628. }
  629. }
  630. func TestHandshakeClientALPNMatch(t *testing.T) {
  631. config := testConfig.clone()
  632. config.NextProtos = []string{"proto2", "proto1"}
  633. test := &clientTest{
  634. name: "ALPN",
  635. // Note that this needs OpenSSL 1.0.2 because that is the first
  636. // version that supports the -alpn flag.
  637. command: []string{"openssl", "s_server", "-alpn", "proto1,proto2"},
  638. config: config,
  639. validate: func(state ConnectionState) error {
  640. // The server's preferences should override the client.
  641. if state.NegotiatedProtocol != "proto1" {
  642. return fmt.Errorf("Got protocol %q, wanted proto1", state.NegotiatedProtocol)
  643. }
  644. return nil
  645. },
  646. }
  647. runClientTestTLS12(t, test)
  648. }
  649. func TestHandshakeClientALPNNoMatch(t *testing.T) {
  650. config := testConfig.clone()
  651. config.NextProtos = []string{"proto3"}
  652. test := &clientTest{
  653. name: "ALPN-NoMatch",
  654. // Note that this needs OpenSSL 1.0.2 because that is the first
  655. // version that supports the -alpn flag.
  656. command: []string{"openssl", "s_server", "-alpn", "proto1,proto2"},
  657. config: config,
  658. validate: func(state ConnectionState) error {
  659. // There's no overlap so OpenSSL will not select a protocol.
  660. if state.NegotiatedProtocol != "" {
  661. return fmt.Errorf("Got protocol %q, wanted ''", state.NegotiatedProtocol)
  662. }
  663. return nil
  664. },
  665. }
  666. runClientTestTLS12(t, test)
  667. }
  668. // sctsBase64 contains data from `openssl s_client -serverinfo 18 -connect ritter.vg:443`
  669. const sctsBase64 = "ABIBaQFnAHUApLkJkLQYWBSHuxOizGdwCjw1mAT5G9+443fNDsgN3BAAAAFHl5nuFgAABAMARjBEAiAcS4JdlW5nW9sElUv2zvQyPoZ6ejKrGGB03gjaBZFMLwIgc1Qbbn+hsH0RvObzhS+XZhr3iuQQJY8S9G85D9KeGPAAdgBo9pj4H2SCvjqM7rkoHUz8cVFdZ5PURNEKZ6y7T0/7xAAAAUeX4bVwAAAEAwBHMEUCIDIhFDgG2HIuADBkGuLobU5a4dlCHoJLliWJ1SYT05z6AiEAjxIoZFFPRNWMGGIjskOTMwXzQ1Wh2e7NxXE1kd1J0QsAdgDuS723dc5guuFCaR+r4Z5mow9+X7By2IMAxHuJeqj9ywAAAUhcZIqHAAAEAwBHMEUCICmJ1rBT09LpkbzxtUC+Hi7nXLR0J+2PmwLp+sJMuqK+AiEAr0NkUnEVKVhAkccIFpYDqHOlZaBsuEhWWrYpg2RtKp0="
  670. func TestHandshakClientSCTs(t *testing.T) {
  671. config := testConfig.clone()
  672. scts, err := base64.StdEncoding.DecodeString(sctsBase64)
  673. if err != nil {
  674. t.Fatal(err)
  675. }
  676. test := &clientTest{
  677. name: "SCT",
  678. // Note that this needs OpenSSL 1.0.2 because that is the first
  679. // version that supports the -serverinfo flag.
  680. command: []string{"openssl", "s_server"},
  681. config: config,
  682. extensions: [][]byte{scts},
  683. validate: func(state ConnectionState) error {
  684. expectedSCTs := [][]byte{
  685. scts[8:125],
  686. scts[127:245],
  687. scts[247:],
  688. }
  689. if n := len(state.SignedCertificateTimestamps); n != len(expectedSCTs) {
  690. return fmt.Errorf("Got %d scts, wanted %d", n, len(expectedSCTs))
  691. }
  692. for i, expected := range expectedSCTs {
  693. if sct := state.SignedCertificateTimestamps[i]; !bytes.Equal(sct, expected) {
  694. return fmt.Errorf("SCT #%d contained %x, expected %x", i, sct, expected)
  695. }
  696. }
  697. return nil
  698. },
  699. }
  700. runClientTestTLS12(t, test)
  701. }
  702. func TestRenegotiationRejected(t *testing.T) {
  703. config := testConfig.clone()
  704. test := &clientTest{
  705. name: "RenegotiationRejected",
  706. command: []string{"openssl", "s_server", "-state"},
  707. config: config,
  708. numRenegotiations: 1,
  709. renegotiationExpectedToFail: 1,
  710. checkRenegotiationError: func(renegotiationNum int, err error) error {
  711. if err == nil {
  712. return errors.New("expected error from renegotiation but got nil")
  713. }
  714. if !strings.Contains(err.Error(), "no renegotiation") {
  715. return fmt.Errorf("expected renegotiation to be rejected but got %q", err)
  716. }
  717. return nil
  718. },
  719. }
  720. runClientTestTLS12(t, test)
  721. }
  722. func TestRenegotiateOnce(t *testing.T) {
  723. config := testConfig.clone()
  724. config.Renegotiation = RenegotiateOnceAsClient
  725. test := &clientTest{
  726. name: "RenegotiateOnce",
  727. command: []string{"openssl", "s_server", "-state"},
  728. config: config,
  729. numRenegotiations: 1,
  730. }
  731. runClientTestTLS12(t, test)
  732. }
  733. func TestRenegotiateTwice(t *testing.T) {
  734. config := testConfig.clone()
  735. config.Renegotiation = RenegotiateFreelyAsClient
  736. test := &clientTest{
  737. name: "RenegotiateTwice",
  738. command: []string{"openssl", "s_server", "-state"},
  739. config: config,
  740. numRenegotiations: 2,
  741. }
  742. runClientTestTLS12(t, test)
  743. }
  744. func TestRenegotiateTwiceRejected(t *testing.T) {
  745. config := testConfig.clone()
  746. config.Renegotiation = RenegotiateOnceAsClient
  747. test := &clientTest{
  748. name: "RenegotiateTwiceRejected",
  749. command: []string{"openssl", "s_server", "-state"},
  750. config: config,
  751. numRenegotiations: 2,
  752. renegotiationExpectedToFail: 2,
  753. checkRenegotiationError: func(renegotiationNum int, err error) error {
  754. if renegotiationNum == 1 {
  755. return err
  756. }
  757. if err == nil {
  758. return errors.New("expected error from renegotiation but got nil")
  759. }
  760. if !strings.Contains(err.Error(), "no renegotiation") {
  761. return fmt.Errorf("expected renegotiation to be rejected but got %q", err)
  762. }
  763. return nil
  764. },
  765. }
  766. runClientTestTLS12(t, test)
  767. }
  768. var hostnameInSNITests = []struct {
  769. in, out string
  770. }{
  771. // Opaque string
  772. {"", ""},
  773. {"localhost", "localhost"},
  774. {"foo, bar, baz and qux", "foo, bar, baz and qux"},
  775. // DNS hostname
  776. {"golang.org", "golang.org"},
  777. {"golang.org.", "golang.org"},
  778. // Literal IPv4 address
  779. {"1.2.3.4", ""},
  780. // Literal IPv6 address
  781. {"::1", ""},
  782. {"::1%lo0", ""}, // with zone identifier
  783. {"[::1]", ""}, // as per RFC 5952 we allow the [] style as IPv6 literal
  784. {"[::1%lo0]", ""},
  785. }
  786. func TestHostnameInSNI(t *testing.T) {
  787. for _, tt := range hostnameInSNITests {
  788. c, s := net.Pipe()
  789. go func(host string) {
  790. Client(c, &Config{ServerName: host, InsecureSkipVerify: true}).Handshake()
  791. }(tt.in)
  792. var header [5]byte
  793. if _, err := io.ReadFull(s, header[:]); err != nil {
  794. t.Fatal(err)
  795. }
  796. recordLen := int(header[3])<<8 | int(header[4])
  797. record := make([]byte, recordLen)
  798. if _, err := io.ReadFull(s, record[:]); err != nil {
  799. t.Fatal(err)
  800. }
  801. c.Close()
  802. s.Close()
  803. var m clientHelloMsg
  804. if !m.unmarshal(record) {
  805. t.Errorf("unmarshaling ClientHello for %q failed", tt.in)
  806. continue
  807. }
  808. if tt.in != tt.out && m.serverName == tt.in {
  809. t.Errorf("prohibited %q found in ClientHello: %x", tt.in, record)
  810. }
  811. if m.serverName != tt.out {
  812. t.Errorf("expected %q not found in ClientHello: %x", tt.out, record)
  813. }
  814. }
  815. }
  816. func TestServerSelectingUnconfiguredCipherSuite(t *testing.T) {
  817. // This checks that the server can't select a cipher suite that the
  818. // client didn't offer. See #13174.
  819. c, s := net.Pipe()
  820. errChan := make(chan error, 1)
  821. go func() {
  822. client := Client(c, &Config{
  823. ServerName: "foo",
  824. CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
  825. })
  826. errChan <- client.Handshake()
  827. }()
  828. var header [5]byte
  829. if _, err := io.ReadFull(s, header[:]); err != nil {
  830. t.Fatal(err)
  831. }
  832. recordLen := int(header[3])<<8 | int(header[4])
  833. record := make([]byte, recordLen)
  834. if _, err := io.ReadFull(s, record); err != nil {
  835. t.Fatal(err)
  836. }
  837. // Create a ServerHello that selects a different cipher suite than the
  838. // sole one that the client offered.
  839. serverHello := &serverHelloMsg{
  840. vers: VersionTLS12,
  841. random: make([]byte, 32),
  842. cipherSuite: TLS_RSA_WITH_AES_256_GCM_SHA384,
  843. }
  844. serverHelloBytes := serverHello.marshal()
  845. s.Write([]byte{
  846. byte(recordTypeHandshake),
  847. byte(VersionTLS12 >> 8),
  848. byte(VersionTLS12 & 0xff),
  849. byte(len(serverHelloBytes) >> 8),
  850. byte(len(serverHelloBytes)),
  851. })
  852. s.Write(serverHelloBytes)
  853. s.Close()
  854. if err := <-errChan; !strings.Contains(err.Error(), "unconfigured cipher") {
  855. t.Fatalf("Expected error about unconfigured cipher suite but got %q", err)
  856. }
  857. }
  858. // brokenConn wraps a net.Conn and causes all Writes after a certain number to
  859. // fail with brokenConnErr.
  860. type brokenConn struct {
  861. net.Conn
  862. // breakAfter is the number of successful writes that will be allowed
  863. // before all subsequent writes fail.
  864. breakAfter int
  865. // numWrites is the number of writes that have been done.
  866. numWrites int
  867. }
  868. // brokenConnErr is the error that brokenConn returns once exhausted.
  869. var brokenConnErr = errors.New("too many writes to brokenConn")
  870. func (b *brokenConn) Write(data []byte) (int, error) {
  871. if b.numWrites >= b.breakAfter {
  872. return 0, brokenConnErr
  873. }
  874. b.numWrites++
  875. return b.Conn.Write(data)
  876. }
  877. func TestFailedWrite(t *testing.T) {
  878. // Test that a write error during the handshake is returned.
  879. for _, breakAfter := range []int{0, 1} {
  880. c, s := net.Pipe()
  881. done := make(chan bool)
  882. go func() {
  883. Server(s, testConfig).Handshake()
  884. s.Close()
  885. done <- true
  886. }()
  887. brokenC := &brokenConn{Conn: c, breakAfter: breakAfter}
  888. err := Client(brokenC, testConfig).Handshake()
  889. if err != brokenConnErr {
  890. t.Errorf("#%d: expected error from brokenConn but got %q", breakAfter, err)
  891. }
  892. brokenC.Close()
  893. <-done
  894. }
  895. }
  896. // writeCountingConn wraps a net.Conn and counts the number of Write calls.
  897. type writeCountingConn struct {
  898. net.Conn
  899. // numWrites is the number of writes that have been done.
  900. numWrites int
  901. }
  902. func (wcc *writeCountingConn) Write(data []byte) (int, error) {
  903. wcc.numWrites++
  904. return wcc.Conn.Write(data)
  905. }
  906. func TestBuffering(t *testing.T) {
  907. c, s := net.Pipe()
  908. done := make(chan bool)
  909. clientWCC := &writeCountingConn{Conn: c}
  910. serverWCC := &writeCountingConn{Conn: s}
  911. go func() {
  912. Server(serverWCC, testConfig).Handshake()
  913. serverWCC.Close()
  914. done <- true
  915. }()
  916. err := Client(clientWCC, testConfig).Handshake()
  917. if err != nil {
  918. t.Fatal(err)
  919. }
  920. clientWCC.Close()
  921. <-done
  922. if n := clientWCC.numWrites; n != 2 {
  923. t.Errorf("expected client handshake to complete with only two writes, but saw %d", n)
  924. }
  925. if n := serverWCC.numWrites; n != 2 {
  926. t.Errorf("expected server handshake to complete with only two writes, but saw %d", n)
  927. }
  928. }