handshake_client_test.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  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. "fmt"
  14. "io"
  15. "net"
  16. "os"
  17. "os/exec"
  18. "path/filepath"
  19. "strconv"
  20. "strings"
  21. "testing"
  22. "time"
  23. )
  24. // Note: see comment in handshake_test.go for details of how the reference
  25. // tests work.
  26. // blockingSource is an io.Reader that blocks a Read call until it's closed.
  27. type blockingSource chan bool
  28. func (b blockingSource) Read([]byte) (n int, err error) {
  29. <-b
  30. return 0, io.EOF
  31. }
  32. // clientTest represents a test of the TLS client handshake against a reference
  33. // implementation.
  34. type clientTest struct {
  35. // name is a freeform string identifying the test and the file in which
  36. // the expected results will be stored.
  37. name string
  38. // command, if not empty, contains a series of arguments for the
  39. // command to run for the reference server.
  40. command []string
  41. // config, if not nil, contains a custom Config to use for this test.
  42. config *Config
  43. // cert, if not empty, contains a DER-encoded certificate for the
  44. // reference server.
  45. cert []byte
  46. // key, if not nil, contains either a *rsa.PrivateKey or
  47. // *ecdsa.PrivateKey which is the private key for the reference server.
  48. key interface{}
  49. // extensions, if not nil, contains a list of extension data to be returned
  50. // from the ServerHello. The data should be in standard TLS format with
  51. // a 2-byte uint16 type, 2-byte data length, followed by the extension data.
  52. extensions [][]byte
  53. // validate, if not nil, is a function that will be called with the
  54. // ConnectionState of the resulting connection. It returns a non-nil
  55. // error if the ConnectionState is unacceptable.
  56. validate func(ConnectionState) error
  57. }
  58. var defaultServerCommand = []string{"openssl", "s_server"}
  59. // connFromCommand starts the reference server process, connects to it and
  60. // returns a recordingConn for the connection. The stdin return value is a
  61. // blockingSource for the stdin of the child process. It must be closed before
  62. // Waiting for child.
  63. func (test *clientTest) connFromCommand() (conn *recordingConn, child *exec.Cmd, stdin blockingSource, err error) {
  64. cert := testRSACertificate
  65. if len(test.cert) > 0 {
  66. cert = test.cert
  67. }
  68. certPath := tempFile(string(cert))
  69. defer os.Remove(certPath)
  70. var key interface{} = testRSAPrivateKey
  71. if test.key != nil {
  72. key = test.key
  73. }
  74. var pemType string
  75. var derBytes []byte
  76. switch key := key.(type) {
  77. case *rsa.PrivateKey:
  78. pemType = "RSA"
  79. derBytes = x509.MarshalPKCS1PrivateKey(key)
  80. case *ecdsa.PrivateKey:
  81. pemType = "EC"
  82. var err error
  83. derBytes, err = x509.MarshalECPrivateKey(key)
  84. if err != nil {
  85. panic(err)
  86. }
  87. default:
  88. panic("unknown key type")
  89. }
  90. var pemOut bytes.Buffer
  91. pem.Encode(&pemOut, &pem.Block{Type: pemType + " PRIVATE KEY", Bytes: derBytes})
  92. keyPath := tempFile(string(pemOut.Bytes()))
  93. defer os.Remove(keyPath)
  94. var command []string
  95. if len(test.command) > 0 {
  96. command = append(command, test.command...)
  97. } else {
  98. command = append(command, defaultServerCommand...)
  99. }
  100. command = append(command, "-cert", certPath, "-certform", "DER", "-key", keyPath)
  101. // serverPort contains the port that OpenSSL will listen on. OpenSSL
  102. // can't take "0" as an argument here so we have to pick a number and
  103. // hope that it's not in use on the machine. Since this only occurs
  104. // when -update is given and thus when there's a human watching the
  105. // test, this isn't too bad.
  106. const serverPort = 24323
  107. command = append(command, "-accept", strconv.Itoa(serverPort))
  108. if len(test.extensions) > 0 {
  109. var serverInfo bytes.Buffer
  110. for _, ext := range test.extensions {
  111. pem.Encode(&serverInfo, &pem.Block{
  112. Type: fmt.Sprintf("SERVERINFO FOR EXTENSION %d", binary.BigEndian.Uint16(ext)),
  113. Bytes: ext,
  114. })
  115. }
  116. serverInfoPath := tempFile(serverInfo.String())
  117. defer os.Remove(serverInfoPath)
  118. command = append(command, "-serverinfo", serverInfoPath)
  119. }
  120. cmd := exec.Command(command[0], command[1:]...)
  121. stdin = blockingSource(make(chan bool))
  122. cmd.Stdin = stdin
  123. var out bytes.Buffer
  124. cmd.Stdout = &out
  125. cmd.Stderr = &out
  126. if err := cmd.Start(); err != nil {
  127. return nil, nil, nil, err
  128. }
  129. // OpenSSL does print an "ACCEPT" banner, but it does so *before*
  130. // opening the listening socket, so we can't use that to wait until it
  131. // has started listening. Thus we are forced to poll until we get a
  132. // connection.
  133. var tcpConn net.Conn
  134. for i := uint(0); i < 5; i++ {
  135. tcpConn, err = net.DialTCP("tcp", nil, &net.TCPAddr{
  136. IP: net.IPv4(127, 0, 0, 1),
  137. Port: serverPort,
  138. })
  139. if err == nil {
  140. break
  141. }
  142. time.Sleep((1 << i) * 5 * time.Millisecond)
  143. }
  144. if err != nil {
  145. close(stdin)
  146. out.WriteTo(os.Stdout)
  147. cmd.Process.Kill()
  148. return nil, nil, nil, cmd.Wait()
  149. }
  150. record := &recordingConn{
  151. Conn: tcpConn,
  152. }
  153. return record, cmd, stdin, nil
  154. }
  155. func (test *clientTest) dataPath() string {
  156. return filepath.Join("testdata", "Client-"+test.name)
  157. }
  158. func (test *clientTest) loadData() (flows [][]byte, err error) {
  159. in, err := os.Open(test.dataPath())
  160. if err != nil {
  161. return nil, err
  162. }
  163. defer in.Close()
  164. return parseTestData(in)
  165. }
  166. func (test *clientTest) run(t *testing.T, write bool) {
  167. var clientConn, serverConn net.Conn
  168. var recordingConn *recordingConn
  169. var childProcess *exec.Cmd
  170. var stdin blockingSource
  171. if write {
  172. var err error
  173. recordingConn, childProcess, stdin, err = test.connFromCommand()
  174. if err != nil {
  175. t.Fatalf("Failed to start subcommand: %s", err)
  176. }
  177. clientConn = recordingConn
  178. } else {
  179. clientConn, serverConn = net.Pipe()
  180. }
  181. config := test.config
  182. if config == nil {
  183. config = testConfig
  184. }
  185. client := Client(clientConn, config)
  186. doneChan := make(chan bool)
  187. go func() {
  188. if _, err := client.Write([]byte("hello\n")); err != nil {
  189. t.Errorf("Client.Write failed: %s", err)
  190. }
  191. if test.validate != nil {
  192. if err := test.validate(client.ConnectionState()); err != nil {
  193. t.Errorf("validate callback returned error: %s", err)
  194. }
  195. }
  196. client.Close()
  197. clientConn.Close()
  198. doneChan <- true
  199. }()
  200. if !write {
  201. flows, err := test.loadData()
  202. if err != nil {
  203. t.Fatalf("%s: failed to load data from %s: %v", test.name, test.dataPath(), err)
  204. }
  205. for i, b := range flows {
  206. if i%2 == 1 {
  207. serverConn.Write(b)
  208. continue
  209. }
  210. bb := make([]byte, len(b))
  211. _, err := io.ReadFull(serverConn, bb)
  212. if err != nil {
  213. t.Fatalf("%s #%d: %s", test.name, i, err)
  214. }
  215. if !bytes.Equal(b, bb) {
  216. t.Fatalf("%s #%d: mismatch on read: got:%x want:%x", test.name, i, bb, b)
  217. }
  218. }
  219. serverConn.Close()
  220. }
  221. <-doneChan
  222. if write {
  223. path := test.dataPath()
  224. out, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
  225. if err != nil {
  226. t.Fatalf("Failed to create output file: %s", err)
  227. }
  228. defer out.Close()
  229. recordingConn.Close()
  230. close(stdin)
  231. childProcess.Process.Kill()
  232. childProcess.Wait()
  233. if len(recordingConn.flows) < 3 {
  234. childProcess.Stdout.(*bytes.Buffer).WriteTo(os.Stdout)
  235. t.Fatalf("Client connection didn't work")
  236. }
  237. recordingConn.WriteTo(out)
  238. fmt.Printf("Wrote %s\n", path)
  239. }
  240. }
  241. func runClientTestForVersion(t *testing.T, template *clientTest, prefix, option string) {
  242. test := *template
  243. test.name = prefix + test.name
  244. if len(test.command) == 0 {
  245. test.command = defaultClientCommand
  246. }
  247. test.command = append([]string(nil), test.command...)
  248. test.command = append(test.command, option)
  249. test.run(t, *update)
  250. }
  251. func runClientTestTLS10(t *testing.T, template *clientTest) {
  252. runClientTestForVersion(t, template, "TLSv10-", "-tls1")
  253. }
  254. func runClientTestTLS11(t *testing.T, template *clientTest) {
  255. runClientTestForVersion(t, template, "TLSv11-", "-tls1_1")
  256. }
  257. func runClientTestTLS12(t *testing.T, template *clientTest) {
  258. runClientTestForVersion(t, template, "TLSv12-", "-tls1_2")
  259. }
  260. func TestHandshakeClientRSARC4(t *testing.T) {
  261. test := &clientTest{
  262. name: "RSA-RC4",
  263. command: []string{"openssl", "s_server", "-cipher", "RC4-SHA"},
  264. }
  265. runClientTestTLS10(t, test)
  266. runClientTestTLS11(t, test)
  267. runClientTestTLS12(t, test)
  268. }
  269. func TestHandshakeClientRSAAES128GCM(t *testing.T) {
  270. test := &clientTest{
  271. name: "AES128-GCM-SHA256",
  272. command: []string{"openssl", "s_server", "-cipher", "AES128-GCM-SHA256"},
  273. }
  274. runClientTestTLS12(t, test)
  275. }
  276. func TestHandshakeClientRSAAES256GCM(t *testing.T) {
  277. test := &clientTest{
  278. name: "AES256-GCM-SHA384",
  279. command: []string{"openssl", "s_server", "-cipher", "AES256-GCM-SHA384"},
  280. }
  281. runClientTestTLS12(t, test)
  282. }
  283. func TestHandshakeClientECDHERSAAES(t *testing.T) {
  284. test := &clientTest{
  285. name: "ECDHE-RSA-AES",
  286. command: []string{"openssl", "s_server", "-cipher", "ECDHE-RSA-AES128-SHA"},
  287. }
  288. runClientTestTLS10(t, test)
  289. runClientTestTLS11(t, test)
  290. runClientTestTLS12(t, test)
  291. }
  292. func TestHandshakeClientECDHEECDSAAES(t *testing.T) {
  293. test := &clientTest{
  294. name: "ECDHE-ECDSA-AES",
  295. command: []string{"openssl", "s_server", "-cipher", "ECDHE-ECDSA-AES128-SHA"},
  296. cert: testECDSACertificate,
  297. key: testECDSAPrivateKey,
  298. }
  299. runClientTestTLS10(t, test)
  300. runClientTestTLS11(t, test)
  301. runClientTestTLS12(t, test)
  302. }
  303. func TestHandshakeClientECDHEECDSAAESGCM(t *testing.T) {
  304. test := &clientTest{
  305. name: "ECDHE-ECDSA-AES-GCM",
  306. command: []string{"openssl", "s_server", "-cipher", "ECDHE-ECDSA-AES128-GCM-SHA256"},
  307. cert: testECDSACertificate,
  308. key: testECDSAPrivateKey,
  309. }
  310. runClientTestTLS12(t, test)
  311. }
  312. func TestHandshakeClientAES256GCMSHA384(t *testing.T) {
  313. test := &clientTest{
  314. name: "ECDHE-ECDSA-AES256-GCM-SHA384",
  315. command: []string{"openssl", "s_server", "-cipher", "ECDHE-ECDSA-AES256-GCM-SHA384"},
  316. cert: testECDSACertificate,
  317. key: testECDSAPrivateKey,
  318. }
  319. runClientTestTLS12(t, test)
  320. }
  321. func TestHandshakeClientCertRSA(t *testing.T) {
  322. config := *testConfig
  323. cert, _ := X509KeyPair([]byte(clientCertificatePEM), []byte(clientKeyPEM))
  324. config.Certificates = []Certificate{cert}
  325. test := &clientTest{
  326. name: "ClientCert-RSA-RSA",
  327. command: []string{"openssl", "s_server", "-cipher", "RC4-SHA", "-verify", "1"},
  328. config: &config,
  329. }
  330. runClientTestTLS10(t, test)
  331. runClientTestTLS12(t, test)
  332. test = &clientTest{
  333. name: "ClientCert-RSA-ECDSA",
  334. command: []string{"openssl", "s_server", "-cipher", "ECDHE-ECDSA-AES128-SHA", "-verify", "1"},
  335. config: &config,
  336. cert: testECDSACertificate,
  337. key: testECDSAPrivateKey,
  338. }
  339. runClientTestTLS10(t, test)
  340. runClientTestTLS12(t, test)
  341. test = &clientTest{
  342. name: "ClientCert-RSA-AES256-GCM-SHA384",
  343. command: []string{"openssl", "s_server", "-cipher", "ECDHE-RSA-AES256-GCM-SHA384", "-verify", "1"},
  344. config: &config,
  345. cert: testRSACertificate,
  346. key: testRSAPrivateKey,
  347. }
  348. runClientTestTLS12(t, test)
  349. }
  350. func TestHandshakeClientCertECDSA(t *testing.T) {
  351. config := *testConfig
  352. cert, _ := X509KeyPair([]byte(clientECDSACertificatePEM), []byte(clientECDSAKeyPEM))
  353. config.Certificates = []Certificate{cert}
  354. test := &clientTest{
  355. name: "ClientCert-ECDSA-RSA",
  356. command: []string{"openssl", "s_server", "-cipher", "RC4-SHA", "-verify", "1"},
  357. config: &config,
  358. }
  359. runClientTestTLS10(t, test)
  360. runClientTestTLS12(t, test)
  361. test = &clientTest{
  362. name: "ClientCert-ECDSA-ECDSA",
  363. command: []string{"openssl", "s_server", "-cipher", "ECDHE-ECDSA-AES128-SHA", "-verify", "1"},
  364. config: &config,
  365. cert: testECDSACertificate,
  366. key: testECDSAPrivateKey,
  367. }
  368. runClientTestTLS10(t, test)
  369. runClientTestTLS12(t, test)
  370. }
  371. func TestClientResumption(t *testing.T) {
  372. serverConfig := &Config{
  373. CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA},
  374. Certificates: testConfig.Certificates,
  375. }
  376. issuer, err := x509.ParseCertificate(testRSACertificateIssuer)
  377. if err != nil {
  378. panic(err)
  379. }
  380. rootCAs := x509.NewCertPool()
  381. rootCAs.AddCert(issuer)
  382. clientConfig := &Config{
  383. CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
  384. ClientSessionCache: NewLRUClientSessionCache(32),
  385. RootCAs: rootCAs,
  386. ServerName: "example.golang",
  387. }
  388. testResumeState := func(test string, didResume bool) {
  389. _, hs, err := testHandshake(clientConfig, serverConfig)
  390. if err != nil {
  391. t.Fatalf("%s: handshake failed: %s", test, err)
  392. }
  393. if hs.DidResume != didResume {
  394. t.Fatalf("%s resumed: %v, expected: %v", test, hs.DidResume, didResume)
  395. }
  396. if didResume && (hs.PeerCertificates == nil || hs.VerifiedChains == nil) {
  397. t.Fatalf("expected non-nil certificates after resumption. Got peerCertificates: %#v, verifedCertificates: %#v", hs.PeerCertificates, hs.VerifiedChains)
  398. }
  399. }
  400. getTicket := func() []byte {
  401. return clientConfig.ClientSessionCache.(*lruSessionCache).q.Front().Value.(*lruSessionCacheEntry).state.sessionTicket
  402. }
  403. randomKey := func() [32]byte {
  404. var k [32]byte
  405. if _, err := io.ReadFull(serverConfig.rand(), k[:]); err != nil {
  406. t.Fatalf("Failed to read new SessionTicketKey: %s", err)
  407. }
  408. return k
  409. }
  410. testResumeState("Handshake", false)
  411. ticket := getTicket()
  412. testResumeState("Resume", true)
  413. if !bytes.Equal(ticket, getTicket()) {
  414. t.Fatal("first ticket doesn't match ticket after resumption")
  415. }
  416. key2 := randomKey()
  417. serverConfig.SetSessionTicketKeys([][32]byte{key2})
  418. testResumeState("InvalidSessionTicketKey", false)
  419. testResumeState("ResumeAfterInvalidSessionTicketKey", true)
  420. serverConfig.SetSessionTicketKeys([][32]byte{randomKey(), key2})
  421. ticket = getTicket()
  422. testResumeState("KeyChange", true)
  423. if bytes.Equal(ticket, getTicket()) {
  424. t.Fatal("new ticket wasn't included while resuming")
  425. }
  426. testResumeState("KeyChangeFinish", true)
  427. clientConfig.CipherSuites = []uint16{TLS_ECDHE_RSA_WITH_RC4_128_SHA}
  428. testResumeState("DifferentCipherSuite", false)
  429. testResumeState("DifferentCipherSuiteRecovers", true)
  430. clientConfig.ClientSessionCache = nil
  431. testResumeState("WithoutSessionCache", false)
  432. }
  433. func TestLRUClientSessionCache(t *testing.T) {
  434. // Initialize cache of capacity 4.
  435. cache := NewLRUClientSessionCache(4)
  436. cs := make([]ClientSessionState, 6)
  437. keys := []string{"0", "1", "2", "3", "4", "5", "6"}
  438. // Add 4 entries to the cache and look them up.
  439. for i := 0; i < 4; i++ {
  440. cache.Put(keys[i], &cs[i])
  441. }
  442. for i := 0; i < 4; i++ {
  443. if s, ok := cache.Get(keys[i]); !ok || s != &cs[i] {
  444. t.Fatalf("session cache failed lookup for added key: %s", keys[i])
  445. }
  446. }
  447. // Add 2 more entries to the cache. First 2 should be evicted.
  448. for i := 4; i < 6; i++ {
  449. cache.Put(keys[i], &cs[i])
  450. }
  451. for i := 0; i < 2; i++ {
  452. if s, ok := cache.Get(keys[i]); ok || s != nil {
  453. t.Fatalf("session cache should have evicted key: %s", keys[i])
  454. }
  455. }
  456. // Touch entry 2. LRU should evict 3 next.
  457. cache.Get(keys[2])
  458. cache.Put(keys[0], &cs[0])
  459. if s, ok := cache.Get(keys[3]); ok || s != nil {
  460. t.Fatalf("session cache should have evicted key 3")
  461. }
  462. // Update entry 0 in place.
  463. cache.Put(keys[0], &cs[3])
  464. if s, ok := cache.Get(keys[0]); !ok || s != &cs[3] {
  465. t.Fatalf("session cache failed update for key 0")
  466. }
  467. // Adding a nil entry is valid.
  468. cache.Put(keys[0], nil)
  469. if s, ok := cache.Get(keys[0]); !ok || s != nil {
  470. t.Fatalf("failed to add nil entry to cache")
  471. }
  472. }
  473. func TestHandshakeClientALPNMatch(t *testing.T) {
  474. config := *testConfig
  475. config.NextProtos = []string{"proto2", "proto1"}
  476. test := &clientTest{
  477. name: "ALPN",
  478. // Note that this needs OpenSSL 1.0.2 because that is the first
  479. // version that supports the -alpn flag.
  480. command: []string{"openssl", "s_server", "-alpn", "proto1,proto2"},
  481. config: &config,
  482. validate: func(state ConnectionState) error {
  483. // The server's preferences should override the client.
  484. if state.NegotiatedProtocol != "proto1" {
  485. return fmt.Errorf("Got protocol %q, wanted proto1", state.NegotiatedProtocol)
  486. }
  487. return nil
  488. },
  489. }
  490. runClientTestTLS12(t, test)
  491. }
  492. func TestHandshakeClientALPNNoMatch(t *testing.T) {
  493. config := *testConfig
  494. config.NextProtos = []string{"proto3"}
  495. test := &clientTest{
  496. name: "ALPN-NoMatch",
  497. // Note that this needs OpenSSL 1.0.2 because that is the first
  498. // version that supports the -alpn flag.
  499. command: []string{"openssl", "s_server", "-alpn", "proto1,proto2"},
  500. config: &config,
  501. validate: func(state ConnectionState) error {
  502. // There's no overlap so OpenSSL will not select a protocol.
  503. if state.NegotiatedProtocol != "" {
  504. return fmt.Errorf("Got protocol %q, wanted ''", state.NegotiatedProtocol)
  505. }
  506. return nil
  507. },
  508. }
  509. runClientTestTLS12(t, test)
  510. }
  511. // sctsBase64 contains data from `openssl s_client -serverinfo 18 -connect ritter.vg:443`
  512. const sctsBase64 = "ABIBaQFnAHUApLkJkLQYWBSHuxOizGdwCjw1mAT5G9+443fNDsgN3BAAAAFHl5nuFgAABAMARjBEAiAcS4JdlW5nW9sElUv2zvQyPoZ6ejKrGGB03gjaBZFMLwIgc1Qbbn+hsH0RvObzhS+XZhr3iuQQJY8S9G85D9KeGPAAdgBo9pj4H2SCvjqM7rkoHUz8cVFdZ5PURNEKZ6y7T0/7xAAAAUeX4bVwAAAEAwBHMEUCIDIhFDgG2HIuADBkGuLobU5a4dlCHoJLliWJ1SYT05z6AiEAjxIoZFFPRNWMGGIjskOTMwXzQ1Wh2e7NxXE1kd1J0QsAdgDuS723dc5guuFCaR+r4Z5mow9+X7By2IMAxHuJeqj9ywAAAUhcZIqHAAAEAwBHMEUCICmJ1rBT09LpkbzxtUC+Hi7nXLR0J+2PmwLp+sJMuqK+AiEAr0NkUnEVKVhAkccIFpYDqHOlZaBsuEhWWrYpg2RtKp0="
  513. func TestHandshakClientSCTs(t *testing.T) {
  514. config := *testConfig
  515. scts, err := base64.StdEncoding.DecodeString(sctsBase64)
  516. if err != nil {
  517. t.Fatal(err)
  518. }
  519. test := &clientTest{
  520. name: "SCT",
  521. // Note that this needs OpenSSL 1.0.2 because that is the first
  522. // version that supports the -serverinfo flag.
  523. command: []string{"openssl", "s_server"},
  524. config: &config,
  525. extensions: [][]byte{scts},
  526. validate: func(state ConnectionState) error {
  527. expectedSCTs := [][]byte{
  528. scts[8:125],
  529. scts[127:245],
  530. scts[247:],
  531. }
  532. if n := len(state.SignedCertificateTimestamps); n != len(expectedSCTs) {
  533. return fmt.Errorf("Got %d scts, wanted %d", n, len(expectedSCTs))
  534. }
  535. for i, expected := range expectedSCTs {
  536. if sct := state.SignedCertificateTimestamps[i]; !bytes.Equal(sct, expected) {
  537. return fmt.Errorf("SCT #%d contained %x, expected %x", i, sct, expected)
  538. }
  539. }
  540. return nil
  541. },
  542. }
  543. runClientTestTLS12(t, test)
  544. }
  545. func TestNoIPAddressesInSNI(t *testing.T) {
  546. for _, ipLiteral := range []string{"1.2.3.4", "::1"} {
  547. c, s := net.Pipe()
  548. go func() {
  549. client := Client(c, &Config{ServerName: ipLiteral})
  550. client.Handshake()
  551. }()
  552. var header [5]byte
  553. if _, err := io.ReadFull(s, header[:]); err != nil {
  554. t.Fatal(err)
  555. }
  556. recordLen := int(header[3])<<8 | int(header[4])
  557. record := make([]byte, recordLen)
  558. if _, err := io.ReadFull(s, record[:]); err != nil {
  559. t.Fatal(err)
  560. }
  561. s.Close()
  562. if bytes.Index(record, []byte(ipLiteral)) != -1 {
  563. t.Errorf("IP literal %q found in ClientHello: %x", ipLiteral, record)
  564. }
  565. }
  566. }
  567. func TestServerSelectingUnconfiguredCipherSuite(t *testing.T) {
  568. // This checks that the server can't select a cipher suite that the
  569. // client didn't offer. See #13174.
  570. c, s := net.Pipe()
  571. errChan := make(chan error, 1)
  572. go func() {
  573. client := Client(c, &Config{
  574. ServerName: "foo",
  575. CipherSuites: []uint16{TLS_RSA_WITH_AES_128_GCM_SHA256},
  576. })
  577. errChan <- client.Handshake()
  578. }()
  579. var header [5]byte
  580. if _, err := io.ReadFull(s, header[:]); err != nil {
  581. t.Fatal(err)
  582. }
  583. recordLen := int(header[3])<<8 | int(header[4])
  584. record := make([]byte, recordLen)
  585. if _, err := io.ReadFull(s, record); err != nil {
  586. t.Fatal(err)
  587. }
  588. // Create a ServerHello that selects a different cipher suite than the
  589. // sole one that the client offered.
  590. serverHello := &serverHelloMsg{
  591. vers: VersionTLS12,
  592. random: make([]byte, 32),
  593. cipherSuite: TLS_RSA_WITH_AES_256_GCM_SHA384,
  594. }
  595. serverHelloBytes := serverHello.marshal()
  596. s.Write([]byte{
  597. byte(recordTypeHandshake),
  598. byte(VersionTLS12 >> 8),
  599. byte(VersionTLS12 & 0xff),
  600. byte(len(serverHelloBytes) >> 8),
  601. byte(len(serverHelloBytes)),
  602. })
  603. s.Write(serverHelloBytes)
  604. s.Close()
  605. if err := <-errChan; !strings.Contains(err.Error(), "unconfigured cipher") {
  606. t.Fatalf("Expected error about unconfigured cipher suite but got %q", err)
  607. }
  608. }