選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

handshake_server_test.go 45 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314
  1. // Copyright 2009 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/elliptic"
  9. "crypto/rsa"
  10. "encoding/hex"
  11. "encoding/pem"
  12. "errors"
  13. "fmt"
  14. "io"
  15. "math/big"
  16. "net"
  17. "os"
  18. "os/exec"
  19. "path/filepath"
  20. "strings"
  21. "testing"
  22. "time"
  23. )
  24. // zeroSource is an io.Reader that returns an unlimited number of zero bytes.
  25. type zeroSource struct{}
  26. func (zeroSource) Read(b []byte) (n int, err error) {
  27. for i := range b {
  28. b[i] = 0
  29. }
  30. return len(b), nil
  31. }
  32. var testConfig *Config
  33. func allCipherSuites() []uint16 {
  34. ids := make([]uint16, len(cipherSuites))
  35. for i, suite := range cipherSuites {
  36. ids[i] = suite.id
  37. }
  38. return ids
  39. }
  40. func init() {
  41. testConfig = &Config{
  42. Time: func() time.Time { return time.Unix(0, 0) },
  43. Rand: zeroSource{},
  44. Certificates: make([]Certificate, 2),
  45. InsecureSkipVerify: true,
  46. MinVersion: VersionSSL30,
  47. MaxVersion: VersionTLS12,
  48. CipherSuites: allCipherSuites(),
  49. }
  50. testConfig.Certificates[0].Certificate = [][]byte{testRSACertificate}
  51. testConfig.Certificates[0].PrivateKey = testRSAPrivateKey
  52. testConfig.Certificates[1].Certificate = [][]byte{testSNICertificate}
  53. testConfig.Certificates[1].PrivateKey = testRSAPrivateKey
  54. testConfig.BuildNameToCertificate()
  55. }
  56. func testClientHello(t *testing.T, serverConfig *Config, m handshakeMessage) {
  57. testClientHelloFailure(t, serverConfig, m, "")
  58. }
  59. func testClientHelloFailure(t *testing.T, serverConfig *Config, m handshakeMessage, expectedSubStr string) {
  60. // Create in-memory network connection,
  61. // send message to server. Should return
  62. // expected error.
  63. c, s := net.Pipe()
  64. go func() {
  65. cli := Client(c, testConfig)
  66. if ch, ok := m.(*clientHelloMsg); ok {
  67. cli.vers = ch.vers
  68. }
  69. cli.writeRecord(recordTypeHandshake, m.marshal())
  70. c.Close()
  71. }()
  72. hs := serverHandshakeState{
  73. c: Server(s, serverConfig),
  74. }
  75. _, err := hs.readClientHello()
  76. s.Close()
  77. if len(expectedSubStr) == 0 {
  78. if err != nil && err != io.EOF {
  79. t.Errorf("Got error: %s; expected to succeed", err)
  80. }
  81. } else if err == nil || !strings.Contains(err.Error(), expectedSubStr) {
  82. t.Errorf("Got error: %s; expected to match substring '%s'", err, expectedSubStr)
  83. }
  84. }
  85. func TestSimpleError(t *testing.T) {
  86. testClientHelloFailure(t, testConfig, &serverHelloDoneMsg{}, "unexpected handshake message")
  87. }
  88. var badProtocolVersions = []uint16{0x0000, 0x0005, 0x0100, 0x0105, 0x0200, 0x0205}
  89. func TestRejectBadProtocolVersion(t *testing.T) {
  90. for _, v := range badProtocolVersions {
  91. testClientHelloFailure(t, testConfig, &clientHelloMsg{vers: v}, "unsupported, maximum protocol version")
  92. }
  93. }
  94. func TestNoSuiteOverlap(t *testing.T) {
  95. clientHello := &clientHelloMsg{
  96. vers: VersionTLS10,
  97. cipherSuites: []uint16{0xff00},
  98. compressionMethods: []uint8{compressionNone},
  99. }
  100. testClientHelloFailure(t, testConfig, clientHello, "no cipher suite supported by both client and server")
  101. }
  102. func TestNoCompressionOverlap(t *testing.T) {
  103. clientHello := &clientHelloMsg{
  104. vers: VersionTLS10,
  105. cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
  106. compressionMethods: []uint8{0xff},
  107. }
  108. testClientHelloFailure(t, testConfig, clientHello, "client does not support uncompressed connections")
  109. }
  110. func TestNoRC4ByDefault(t *testing.T) {
  111. clientHello := &clientHelloMsg{
  112. vers: VersionTLS10,
  113. cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
  114. compressionMethods: []uint8{compressionNone},
  115. }
  116. serverConfig := testConfig.Clone()
  117. // Reset the enabled cipher suites to nil in order to test the
  118. // defaults.
  119. serverConfig.CipherSuites = nil
  120. testClientHelloFailure(t, serverConfig, clientHello, "no cipher suite supported by both client and server")
  121. }
  122. func TestDontSelectECDSAWithRSAKey(t *testing.T) {
  123. // Test that, even when both sides support an ECDSA cipher suite, it
  124. // won't be selected if the server's private key doesn't support it.
  125. clientHello := &clientHelloMsg{
  126. vers: VersionTLS10,
  127. cipherSuites: []uint16{TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA},
  128. compressionMethods: []uint8{compressionNone},
  129. supportedCurves: []CurveID{CurveP256},
  130. supportedPoints: []uint8{pointFormatUncompressed},
  131. }
  132. serverConfig := testConfig.Clone()
  133. serverConfig.CipherSuites = clientHello.cipherSuites
  134. serverConfig.Certificates = make([]Certificate, 1)
  135. serverConfig.Certificates[0].Certificate = [][]byte{testECDSACertificate}
  136. serverConfig.Certificates[0].PrivateKey = testECDSAPrivateKey
  137. serverConfig.BuildNameToCertificate()
  138. // First test that it *does* work when the server's key is ECDSA.
  139. testClientHello(t, serverConfig, clientHello)
  140. // Now test that switching to an RSA key causes the expected error (and
  141. // not an internal error about a signing failure).
  142. serverConfig.Certificates = testConfig.Certificates
  143. testClientHelloFailure(t, serverConfig, clientHello, "no cipher suite supported by both client and server")
  144. }
  145. func TestDontSelectRSAWithECDSAKey(t *testing.T) {
  146. // Test that, even when both sides support an RSA cipher suite, it
  147. // won't be selected if the server's private key doesn't support it.
  148. clientHello := &clientHelloMsg{
  149. vers: VersionTLS10,
  150. cipherSuites: []uint16{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA},
  151. compressionMethods: []uint8{compressionNone},
  152. supportedCurves: []CurveID{CurveP256},
  153. supportedPoints: []uint8{pointFormatUncompressed},
  154. }
  155. serverConfig := testConfig.Clone()
  156. serverConfig.CipherSuites = clientHello.cipherSuites
  157. // First test that it *does* work when the server's key is RSA.
  158. testClientHello(t, serverConfig, clientHello)
  159. // Now test that switching to an ECDSA key causes the expected error
  160. // (and not an internal error about a signing failure).
  161. serverConfig.Certificates = make([]Certificate, 1)
  162. serverConfig.Certificates[0].Certificate = [][]byte{testECDSACertificate}
  163. serverConfig.Certificates[0].PrivateKey = testECDSAPrivateKey
  164. serverConfig.BuildNameToCertificate()
  165. testClientHelloFailure(t, serverConfig, clientHello, "no cipher suite supported by both client and server")
  166. }
  167. func TestRenegotiationExtension(t *testing.T) {
  168. clientHello := &clientHelloMsg{
  169. vers: VersionTLS12,
  170. compressionMethods: []uint8{compressionNone},
  171. random: make([]byte, 32),
  172. secureRenegotiationSupported: true,
  173. cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
  174. }
  175. var buf []byte
  176. c, s := net.Pipe()
  177. go func() {
  178. cli := Client(c, testConfig)
  179. cli.vers = clientHello.vers
  180. cli.writeRecord(recordTypeHandshake, clientHello.marshal())
  181. buf = make([]byte, 1024)
  182. n, err := c.Read(buf)
  183. if err != nil {
  184. t.Errorf("Server read returned error: %s", err)
  185. return
  186. }
  187. buf = buf[:n]
  188. c.Close()
  189. }()
  190. Server(s, testConfig).Handshake()
  191. if len(buf) < 5+4 {
  192. t.Fatalf("Server returned short message of length %d", len(buf))
  193. }
  194. // buf contains a TLS record, with a 5 byte record header and a 4 byte
  195. // handshake header. The length of the ServerHello is taken from the
  196. // handshake header.
  197. serverHelloLen := int(buf[6])<<16 | int(buf[7])<<8 | int(buf[8])
  198. var serverHello serverHelloMsg
  199. // unmarshal expects to be given the handshake header, but
  200. // serverHelloLen doesn't include it.
  201. if !serverHello.unmarshal(buf[5 : 9+serverHelloLen]) {
  202. t.Fatalf("Failed to parse ServerHello")
  203. }
  204. if !serverHello.secureRenegotiationSupported {
  205. t.Errorf("Secure renegotiation extension was not echoed.")
  206. }
  207. }
  208. func TestTLS12OnlyCipherSuites(t *testing.T) {
  209. // Test that a Server doesn't select a TLS 1.2-only cipher suite when
  210. // the client negotiates TLS 1.1.
  211. var zeros [32]byte
  212. clientHello := &clientHelloMsg{
  213. vers: VersionTLS11,
  214. random: zeros[:],
  215. cipherSuites: []uint16{
  216. // The Server, by default, will use the client's
  217. // preference order. So the GCM cipher suite
  218. // will be selected unless it's excluded because
  219. // of the version in this ClientHello.
  220. TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  221. TLS_RSA_WITH_RC4_128_SHA,
  222. },
  223. compressionMethods: []uint8{compressionNone},
  224. supportedCurves: []CurveID{CurveP256, CurveP384, CurveP521},
  225. supportedPoints: []uint8{pointFormatUncompressed},
  226. }
  227. c, s := net.Pipe()
  228. var reply interface{}
  229. var clientErr error
  230. go func() {
  231. cli := Client(c, testConfig)
  232. cli.vers = clientHello.vers
  233. cli.writeRecord(recordTypeHandshake, clientHello.marshal())
  234. reply, clientErr = cli.readHandshake()
  235. c.Close()
  236. }()
  237. config := testConfig.Clone()
  238. config.CipherSuites = clientHello.cipherSuites
  239. Server(s, config).Handshake()
  240. s.Close()
  241. if clientErr != nil {
  242. t.Fatal(clientErr)
  243. }
  244. serverHello, ok := reply.(*serverHelloMsg)
  245. if !ok {
  246. t.Fatalf("didn't get ServerHello message in reply. Got %v\n", reply)
  247. }
  248. if s := serverHello.cipherSuite; s != TLS_RSA_WITH_RC4_128_SHA {
  249. t.Fatalf("bad cipher suite from server: %x", s)
  250. }
  251. }
  252. func TestAlertForwarding(t *testing.T) {
  253. c, s := net.Pipe()
  254. go func() {
  255. Client(c, testConfig).sendAlert(alertUnknownCA)
  256. c.Close()
  257. }()
  258. err := Server(s, testConfig).Handshake()
  259. s.Close()
  260. if e, ok := err.(*net.OpError); !ok || e.Err != error(alertUnknownCA) {
  261. t.Errorf("Got error: %s; expected: %s", err, error(alertUnknownCA))
  262. }
  263. }
  264. func TestClose(t *testing.T) {
  265. c, s := net.Pipe()
  266. go c.Close()
  267. err := Server(s, testConfig).Handshake()
  268. s.Close()
  269. if err != io.EOF {
  270. t.Errorf("Got error: %s; expected: %s", err, io.EOF)
  271. }
  272. }
  273. func testHandshake(clientConfig, serverConfig *Config) (serverState, clientState ConnectionState, err error) {
  274. c, s := net.Pipe()
  275. done := make(chan bool)
  276. go func() {
  277. cli := Client(c, clientConfig)
  278. cli.Handshake()
  279. clientState = cli.ConnectionState()
  280. c.Close()
  281. done <- true
  282. }()
  283. server := Server(s, serverConfig)
  284. err = server.Handshake()
  285. if err == nil {
  286. serverState = server.ConnectionState()
  287. }
  288. s.Close()
  289. <-done
  290. return
  291. }
  292. func TestVersion(t *testing.T) {
  293. serverConfig := &Config{
  294. Certificates: testConfig.Certificates,
  295. MaxVersion: VersionTLS11,
  296. }
  297. clientConfig := &Config{
  298. InsecureSkipVerify: true,
  299. }
  300. state, _, err := testHandshake(clientConfig, serverConfig)
  301. if err != nil {
  302. t.Fatalf("handshake failed: %s", err)
  303. }
  304. if state.Version != VersionTLS11 {
  305. t.Fatalf("Incorrect version %x, should be %x", state.Version, VersionTLS11)
  306. }
  307. }
  308. func TestCipherSuitePreference(t *testing.T) {
  309. serverConfig := &Config{
  310. CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA},
  311. Certificates: testConfig.Certificates,
  312. MaxVersion: VersionTLS11,
  313. }
  314. clientConfig := &Config{
  315. CipherSuites: []uint16{TLS_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_RC4_128_SHA},
  316. InsecureSkipVerify: true,
  317. }
  318. state, _, err := testHandshake(clientConfig, serverConfig)
  319. if err != nil {
  320. t.Fatalf("handshake failed: %s", err)
  321. }
  322. if state.CipherSuite != TLS_RSA_WITH_AES_128_CBC_SHA {
  323. // By default the server should use the client's preference.
  324. t.Fatalf("Client's preference was not used, got %x", state.CipherSuite)
  325. }
  326. serverConfig.PreferServerCipherSuites = true
  327. state, _, err = testHandshake(clientConfig, serverConfig)
  328. if err != nil {
  329. t.Fatalf("handshake failed: %s", err)
  330. }
  331. if state.CipherSuite != TLS_RSA_WITH_RC4_128_SHA {
  332. t.Fatalf("Server's preference was not used, got %x", state.CipherSuite)
  333. }
  334. }
  335. func TestSCTHandshake(t *testing.T) {
  336. expected := [][]byte{[]byte("certificate"), []byte("transparency")}
  337. serverConfig := &Config{
  338. Certificates: []Certificate{{
  339. Certificate: [][]byte{testRSACertificate},
  340. PrivateKey: testRSAPrivateKey,
  341. SignedCertificateTimestamps: expected,
  342. }},
  343. }
  344. clientConfig := &Config{
  345. InsecureSkipVerify: true,
  346. }
  347. _, state, err := testHandshake(clientConfig, serverConfig)
  348. if err != nil {
  349. t.Fatalf("handshake failed: %s", err)
  350. }
  351. actual := state.SignedCertificateTimestamps
  352. if len(actual) != len(expected) {
  353. t.Fatalf("got %d scts, want %d", len(actual), len(expected))
  354. }
  355. for i, sct := range expected {
  356. if !bytes.Equal(sct, actual[i]) {
  357. t.Fatalf("SCT #%d was %x, but expected %x", i, actual[i], sct)
  358. }
  359. }
  360. }
  361. func TestCrossVersionResume(t *testing.T) {
  362. serverConfig := &Config{
  363. CipherSuites: []uint16{TLS_RSA_WITH_AES_128_CBC_SHA},
  364. Certificates: testConfig.Certificates,
  365. }
  366. clientConfig := &Config{
  367. CipherSuites: []uint16{TLS_RSA_WITH_AES_128_CBC_SHA},
  368. InsecureSkipVerify: true,
  369. ClientSessionCache: NewLRUClientSessionCache(1),
  370. ServerName: "servername",
  371. }
  372. // Establish a session at TLS 1.1.
  373. clientConfig.MaxVersion = VersionTLS11
  374. _, _, err := testHandshake(clientConfig, serverConfig)
  375. if err != nil {
  376. t.Fatalf("handshake failed: %s", err)
  377. }
  378. // The client session cache now contains a TLS 1.1 session.
  379. state, _, err := testHandshake(clientConfig, serverConfig)
  380. if err != nil {
  381. t.Fatalf("handshake failed: %s", err)
  382. }
  383. if !state.DidResume {
  384. t.Fatalf("handshake did not resume at the same version")
  385. }
  386. // Test that the server will decline to resume at a lower version.
  387. clientConfig.MaxVersion = VersionTLS10
  388. state, _, err = testHandshake(clientConfig, serverConfig)
  389. if err != nil {
  390. t.Fatalf("handshake failed: %s", err)
  391. }
  392. if state.DidResume {
  393. t.Fatalf("handshake resumed at a lower version")
  394. }
  395. // The client session cache now contains a TLS 1.0 session.
  396. state, _, err = testHandshake(clientConfig, serverConfig)
  397. if err != nil {
  398. t.Fatalf("handshake failed: %s", err)
  399. }
  400. if !state.DidResume {
  401. t.Fatalf("handshake did not resume at the same version")
  402. }
  403. // Test that the server will decline to resume at a higher version.
  404. clientConfig.MaxVersion = VersionTLS11
  405. state, _, err = testHandshake(clientConfig, serverConfig)
  406. if err != nil {
  407. t.Fatalf("handshake failed: %s", err)
  408. }
  409. if state.DidResume {
  410. t.Fatalf("handshake resumed at a higher version")
  411. }
  412. }
  413. // Note: see comment in handshake_test.go for details of how the reference
  414. // tests work.
  415. // serverTest represents a test of the TLS server handshake against a reference
  416. // implementation.
  417. type serverTest struct {
  418. // name is a freeform string identifying the test and the file in which
  419. // the expected results will be stored.
  420. name string
  421. // command, if not empty, contains a series of arguments for the
  422. // command to run for the reference server.
  423. command []string
  424. // expectedPeerCerts contains a list of PEM blocks of expected
  425. // certificates from the client.
  426. expectedPeerCerts []string
  427. // config, if not nil, contains a custom Config to use for this test.
  428. config *Config
  429. // expectHandshakeErrorIncluding, when not empty, contains a string
  430. // that must be a substring of the error resulting from the handshake.
  431. expectHandshakeErrorIncluding string
  432. // validate, if not nil, is a function that will be called with the
  433. // ConnectionState of the resulting connection. It returns false if the
  434. // ConnectionState is unacceptable.
  435. validate func(ConnectionState) error
  436. }
  437. var defaultClientCommand = []string{"openssl", "s_client", "-no_ticket"}
  438. // connFromCommand starts opens a listening socket and starts the reference
  439. // client to connect to it. It returns a recordingConn that wraps the resulting
  440. // connection.
  441. func (test *serverTest) connFromCommand() (conn *recordingConn, child *exec.Cmd, err error) {
  442. l, err := net.ListenTCP("tcp", &net.TCPAddr{
  443. IP: net.IPv4(127, 0, 0, 1),
  444. Port: 0,
  445. })
  446. if err != nil {
  447. return nil, nil, err
  448. }
  449. defer l.Close()
  450. port := l.Addr().(*net.TCPAddr).Port
  451. var command []string
  452. command = append(command, test.command...)
  453. if len(command) == 0 {
  454. command = defaultClientCommand
  455. }
  456. command = append(command, "-connect")
  457. command = append(command, fmt.Sprintf("127.0.0.1:%d", port))
  458. cmd := exec.Command(command[0], command[1:]...)
  459. cmd.Stdin = nil
  460. var output bytes.Buffer
  461. cmd.Stdout = &output
  462. cmd.Stderr = &output
  463. if err := cmd.Start(); err != nil {
  464. return nil, nil, err
  465. }
  466. connChan := make(chan interface{})
  467. go func() {
  468. tcpConn, err := l.Accept()
  469. if err != nil {
  470. connChan <- err
  471. }
  472. connChan <- tcpConn
  473. }()
  474. var tcpConn net.Conn
  475. select {
  476. case connOrError := <-connChan:
  477. if err, ok := connOrError.(error); ok {
  478. return nil, nil, err
  479. }
  480. tcpConn = connOrError.(net.Conn)
  481. case <-time.After(2 * time.Second):
  482. output.WriteTo(os.Stdout)
  483. return nil, nil, errors.New("timed out waiting for connection from child process")
  484. }
  485. record := &recordingConn{
  486. Conn: tcpConn,
  487. }
  488. return record, cmd, nil
  489. }
  490. func (test *serverTest) dataPath() string {
  491. return filepath.Join("testdata", "Server-"+test.name)
  492. }
  493. func (test *serverTest) loadData() (flows [][]byte, err error) {
  494. in, err := os.Open(test.dataPath())
  495. if err != nil {
  496. return nil, err
  497. }
  498. defer in.Close()
  499. return parseTestData(in)
  500. }
  501. func (test *serverTest) run(t *testing.T, write bool) {
  502. checkOpenSSLVersion(t)
  503. var clientConn, serverConn net.Conn
  504. var recordingConn *recordingConn
  505. var childProcess *exec.Cmd
  506. if write {
  507. var err error
  508. recordingConn, childProcess, err = test.connFromCommand()
  509. if err != nil {
  510. t.Fatalf("Failed to start subcommand: %s", err)
  511. }
  512. serverConn = recordingConn
  513. } else {
  514. clientConn, serverConn = net.Pipe()
  515. }
  516. config := test.config
  517. if config == nil {
  518. config = testConfig
  519. }
  520. server := Server(serverConn, config)
  521. connStateChan := make(chan ConnectionState, 1)
  522. go func() {
  523. _, err := server.Write([]byte("hello, world\n"))
  524. if len(test.expectHandshakeErrorIncluding) > 0 {
  525. if err == nil {
  526. t.Errorf("Error expected, but no error returned")
  527. } else if s := err.Error(); !strings.Contains(s, test.expectHandshakeErrorIncluding) {
  528. t.Errorf("Error expected containing '%s' but got '%s'", test.expectHandshakeErrorIncluding, s)
  529. }
  530. } else {
  531. if err != nil {
  532. t.Logf("Error from Server.Write: '%s'", err)
  533. }
  534. }
  535. server.Close()
  536. serverConn.Close()
  537. connStateChan <- server.ConnectionState()
  538. }()
  539. if !write {
  540. flows, err := test.loadData()
  541. if err != nil {
  542. t.Fatalf("%s: failed to load data from %s", test.name, test.dataPath())
  543. }
  544. for i, b := range flows {
  545. if i%2 == 0 {
  546. clientConn.Write(b)
  547. continue
  548. }
  549. bb := make([]byte, len(b))
  550. n, err := io.ReadFull(clientConn, bb)
  551. if err != nil {
  552. t.Fatalf("%s #%d: %s\nRead %d, wanted %d, got %x, wanted %x\n", test.name, i+1, err, n, len(bb), bb[:n], b)
  553. }
  554. if !bytes.Equal(b, bb) {
  555. t.Fatalf("%s #%d: mismatch on read: got:%x want:%x", test.name, i+1, bb, b)
  556. }
  557. }
  558. clientConn.Close()
  559. }
  560. connState := <-connStateChan
  561. peerCerts := connState.PeerCertificates
  562. if len(peerCerts) == len(test.expectedPeerCerts) {
  563. for i, peerCert := range peerCerts {
  564. block, _ := pem.Decode([]byte(test.expectedPeerCerts[i]))
  565. if !bytes.Equal(block.Bytes, peerCert.Raw) {
  566. t.Fatalf("%s: mismatch on peer cert %d", test.name, i+1)
  567. }
  568. }
  569. } else {
  570. t.Fatalf("%s: mismatch on peer list length: %d (wanted) != %d (got)", test.name, len(test.expectedPeerCerts), len(peerCerts))
  571. }
  572. if test.validate != nil {
  573. if err := test.validate(connState); err != nil {
  574. t.Fatalf("validate callback returned error: %s", err)
  575. }
  576. }
  577. if write {
  578. path := test.dataPath()
  579. out, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
  580. if err != nil {
  581. t.Fatalf("Failed to create output file: %s", err)
  582. }
  583. defer out.Close()
  584. recordingConn.Close()
  585. if len(recordingConn.flows) < 3 {
  586. childProcess.Stdout.(*bytes.Buffer).WriteTo(os.Stdout)
  587. if len(test.expectHandshakeErrorIncluding) == 0 {
  588. t.Fatalf("Handshake failed")
  589. }
  590. }
  591. recordingConn.WriteTo(out)
  592. fmt.Printf("Wrote %s\n", path)
  593. childProcess.Wait()
  594. }
  595. }
  596. func runServerTestForVersion(t *testing.T, template *serverTest, prefix, option string) {
  597. setParallel(t)
  598. test := *template
  599. test.name = prefix + test.name
  600. if len(test.command) == 0 {
  601. test.command = defaultClientCommand
  602. }
  603. test.command = append([]string(nil), test.command...)
  604. test.command = append(test.command, option)
  605. test.run(t, *update)
  606. }
  607. func runServerTestSSLv3(t *testing.T, template *serverTest) {
  608. runServerTestForVersion(t, template, "SSLv3-", "-ssl3")
  609. }
  610. func runServerTestTLS10(t *testing.T, template *serverTest) {
  611. runServerTestForVersion(t, template, "TLSv10-", "-tls1")
  612. }
  613. func runServerTestTLS11(t *testing.T, template *serverTest) {
  614. runServerTestForVersion(t, template, "TLSv11-", "-tls1_1")
  615. }
  616. func runServerTestTLS12(t *testing.T, template *serverTest) {
  617. runServerTestForVersion(t, template, "TLSv12-", "-tls1_2")
  618. }
  619. func TestHandshakeServerRSARC4(t *testing.T) {
  620. test := &serverTest{
  621. name: "RSA-RC4",
  622. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "RC4-SHA"},
  623. }
  624. runServerTestSSLv3(t, test)
  625. runServerTestTLS10(t, test)
  626. runServerTestTLS11(t, test)
  627. runServerTestTLS12(t, test)
  628. }
  629. func TestHandshakeServerRSA3DES(t *testing.T) {
  630. test := &serverTest{
  631. name: "RSA-3DES",
  632. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "DES-CBC3-SHA"},
  633. }
  634. runServerTestSSLv3(t, test)
  635. runServerTestTLS10(t, test)
  636. runServerTestTLS12(t, test)
  637. }
  638. func TestHandshakeServerRSAAES(t *testing.T) {
  639. test := &serverTest{
  640. name: "RSA-AES",
  641. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA"},
  642. }
  643. runServerTestSSLv3(t, test)
  644. runServerTestTLS10(t, test)
  645. runServerTestTLS12(t, test)
  646. }
  647. func TestHandshakeServerAESGCM(t *testing.T) {
  648. test := &serverTest{
  649. name: "RSA-AES-GCM",
  650. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-AES128-GCM-SHA256"},
  651. }
  652. runServerTestTLS12(t, test)
  653. }
  654. func TestHandshakeServerAES256GCMSHA384(t *testing.T) {
  655. test := &serverTest{
  656. name: "RSA-AES256-GCM-SHA384",
  657. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-AES256-GCM-SHA384"},
  658. }
  659. runServerTestTLS12(t, test)
  660. }
  661. func TestHandshakeServerECDHEECDSAAES(t *testing.T) {
  662. config := testConfig.Clone()
  663. config.Certificates = make([]Certificate, 1)
  664. config.Certificates[0].Certificate = [][]byte{testECDSACertificate}
  665. config.Certificates[0].PrivateKey = testECDSAPrivateKey
  666. config.BuildNameToCertificate()
  667. test := &serverTest{
  668. name: "ECDHE-ECDSA-AES",
  669. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-ECDSA-AES256-SHA"},
  670. config: config,
  671. }
  672. runServerTestTLS10(t, test)
  673. runServerTestTLS12(t, test)
  674. }
  675. func TestHandshakeServerX25519(t *testing.T) {
  676. config := testConfig.Clone()
  677. config.CurvePreferences = []CurveID{X25519}
  678. test := &serverTest{
  679. name: "X25519-ECDHE-RSA-AES-GCM",
  680. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-AES128-GCM-SHA256"},
  681. config: config,
  682. }
  683. runServerTestTLS12(t, test)
  684. }
  685. func TestHandshakeServerALPN(t *testing.T) {
  686. config := testConfig.Clone()
  687. config.NextProtos = []string{"proto1", "proto2"}
  688. test := &serverTest{
  689. name: "ALPN",
  690. // Note that this needs OpenSSL 1.0.2 because that is the first
  691. // version that supports the -alpn flag.
  692. command: []string{"openssl", "s_client", "-alpn", "proto2,proto1"},
  693. config: config,
  694. validate: func(state ConnectionState) error {
  695. // The server's preferences should override the client.
  696. if state.NegotiatedProtocol != "proto1" {
  697. return fmt.Errorf("Got protocol %q, wanted proto1", state.NegotiatedProtocol)
  698. }
  699. return nil
  700. },
  701. }
  702. runServerTestTLS12(t, test)
  703. }
  704. func TestHandshakeServerALPNNoMatch(t *testing.T) {
  705. config := testConfig.Clone()
  706. config.NextProtos = []string{"proto3"}
  707. test := &serverTest{
  708. name: "ALPN-NoMatch",
  709. // Note that this needs OpenSSL 1.0.2 because that is the first
  710. // version that supports the -alpn flag.
  711. command: []string{"openssl", "s_client", "-alpn", "proto2,proto1"},
  712. config: config,
  713. validate: func(state ConnectionState) error {
  714. // Rather than reject the connection, Go doesn't select
  715. // a protocol when there is no overlap.
  716. if state.NegotiatedProtocol != "" {
  717. return fmt.Errorf("Got protocol %q, wanted ''", state.NegotiatedProtocol)
  718. }
  719. return nil
  720. },
  721. }
  722. runServerTestTLS12(t, test)
  723. }
  724. // TestHandshakeServerSNI involves a client sending an SNI extension of
  725. // "snitest.com", which happens to match the CN of testSNICertificate. The test
  726. // verifies that the server correctly selects that certificate.
  727. func TestHandshakeServerSNI(t *testing.T) {
  728. test := &serverTest{
  729. name: "SNI",
  730. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"},
  731. }
  732. runServerTestTLS12(t, test)
  733. }
  734. // TestHandshakeServerSNICertForName is similar to TestHandshakeServerSNI, but
  735. // tests the dynamic GetCertificate method
  736. func TestHandshakeServerSNIGetCertificate(t *testing.T) {
  737. config := testConfig.Clone()
  738. // Replace the NameToCertificate map with a GetCertificate function
  739. nameToCert := config.NameToCertificate
  740. config.NameToCertificate = nil
  741. config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
  742. cert, _ := nameToCert[clientHello.ServerName]
  743. return cert, nil
  744. }
  745. test := &serverTest{
  746. name: "SNI-GetCertificate",
  747. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"},
  748. config: config,
  749. }
  750. runServerTestTLS12(t, test)
  751. }
  752. // TestHandshakeServerSNICertForNameNotFound is similar to
  753. // TestHandshakeServerSNICertForName, but tests to make sure that when the
  754. // GetCertificate method doesn't return a cert, we fall back to what's in
  755. // the NameToCertificate map.
  756. func TestHandshakeServerSNIGetCertificateNotFound(t *testing.T) {
  757. config := testConfig.Clone()
  758. config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
  759. return nil, nil
  760. }
  761. test := &serverTest{
  762. name: "SNI-GetCertificateNotFound",
  763. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"},
  764. config: config,
  765. }
  766. runServerTestTLS12(t, test)
  767. }
  768. // TestHandshakeServerSNICertForNameError tests to make sure that errors in
  769. // GetCertificate result in a tls alert.
  770. func TestHandshakeServerSNIGetCertificateError(t *testing.T) {
  771. const errMsg = "TestHandshakeServerSNIGetCertificateError error"
  772. serverConfig := testConfig.Clone()
  773. serverConfig.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
  774. return nil, errors.New(errMsg)
  775. }
  776. clientHello := &clientHelloMsg{
  777. vers: VersionTLS10,
  778. cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
  779. compressionMethods: []uint8{compressionNone},
  780. serverName: "test",
  781. }
  782. testClientHelloFailure(t, serverConfig, clientHello, errMsg)
  783. }
  784. // TestHandshakeServerEmptyCertificates tests that GetCertificates is called in
  785. // the case that Certificates is empty, even without SNI.
  786. func TestHandshakeServerEmptyCertificates(t *testing.T) {
  787. const errMsg = "TestHandshakeServerEmptyCertificates error"
  788. serverConfig := testConfig.Clone()
  789. serverConfig.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) {
  790. return nil, errors.New(errMsg)
  791. }
  792. serverConfig.Certificates = nil
  793. clientHello := &clientHelloMsg{
  794. vers: VersionTLS10,
  795. cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
  796. compressionMethods: []uint8{compressionNone},
  797. }
  798. testClientHelloFailure(t, serverConfig, clientHello, errMsg)
  799. // With an empty Certificates and a nil GetCertificate, the server
  800. // should always return a “no certificates” error.
  801. serverConfig.GetCertificate = nil
  802. clientHello = &clientHelloMsg{
  803. vers: VersionTLS10,
  804. cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
  805. compressionMethods: []uint8{compressionNone},
  806. }
  807. testClientHelloFailure(t, serverConfig, clientHello, "no certificates")
  808. }
  809. // TestCipherSuiteCertPreferance ensures that we select an RSA ciphersuite with
  810. // an RSA certificate and an ECDSA ciphersuite with an ECDSA certificate.
  811. func TestCipherSuiteCertPreferenceECDSA(t *testing.T) {
  812. config := testConfig.Clone()
  813. config.CipherSuites = []uint16{TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA}
  814. config.PreferServerCipherSuites = true
  815. test := &serverTest{
  816. name: "CipherSuiteCertPreferenceRSA",
  817. config: config,
  818. }
  819. runServerTestTLS12(t, test)
  820. config = testConfig.Clone()
  821. config.CipherSuites = []uint16{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA}
  822. config.Certificates = []Certificate{
  823. {
  824. Certificate: [][]byte{testECDSACertificate},
  825. PrivateKey: testECDSAPrivateKey,
  826. },
  827. }
  828. config.BuildNameToCertificate()
  829. config.PreferServerCipherSuites = true
  830. test = &serverTest{
  831. name: "CipherSuiteCertPreferenceECDSA",
  832. config: config,
  833. }
  834. runServerTestTLS12(t, test)
  835. }
  836. func TestResumption(t *testing.T) {
  837. sessionFilePath := tempFile("")
  838. defer os.Remove(sessionFilePath)
  839. test := &serverTest{
  840. name: "IssueTicket",
  841. command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-sess_out", sessionFilePath},
  842. }
  843. runServerTestTLS12(t, test)
  844. test = &serverTest{
  845. name: "Resume",
  846. command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-sess_in", sessionFilePath},
  847. }
  848. runServerTestTLS12(t, test)
  849. }
  850. func TestResumptionDisabled(t *testing.T) {
  851. sessionFilePath := tempFile("")
  852. defer os.Remove(sessionFilePath)
  853. config := testConfig.Clone()
  854. test := &serverTest{
  855. name: "IssueTicketPreDisable",
  856. command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-sess_out", sessionFilePath},
  857. config: config,
  858. }
  859. runServerTestTLS12(t, test)
  860. config.SessionTicketsDisabled = true
  861. test = &serverTest{
  862. name: "ResumeDisabled",
  863. command: []string{"openssl", "s_client", "-cipher", "AES128-SHA", "-sess_in", sessionFilePath},
  864. config: config,
  865. }
  866. runServerTestTLS12(t, test)
  867. // One needs to manually confirm that the handshake in the golden data
  868. // file for ResumeDisabled does not include a resumption handshake.
  869. }
  870. func TestFallbackSCSV(t *testing.T) {
  871. serverConfig := Config{
  872. Certificates: testConfig.Certificates,
  873. }
  874. test := &serverTest{
  875. name: "FallbackSCSV",
  876. config: &serverConfig,
  877. // OpenSSL 1.0.1j is needed for the -fallback_scsv option.
  878. command: []string{"openssl", "s_client", "-fallback_scsv"},
  879. expectHandshakeErrorIncluding: "inappropriate protocol fallback",
  880. }
  881. runServerTestTLS11(t, test)
  882. }
  883. // clientCertificatePEM and clientKeyPEM were generated with generate_cert.go
  884. // Thus, they have no ExtKeyUsage fields and trigger an error when verification
  885. // is turned on.
  886. const clientCertificatePEM = `
  887. -----BEGIN CERTIFICATE-----
  888. MIIB7zCCAVigAwIBAgIQXBnBiWWDVW/cC8m5k5/pvDANBgkqhkiG9w0BAQsFADAS
  889. MRAwDgYDVQQKEwdBY21lIENvMB4XDTE2MDgxNzIxNTIzMVoXDTE3MDgxNzIxNTIz
  890. MVowEjEQMA4GA1UEChMHQWNtZSBDbzCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkC
  891. gYEAum+qhr3Pv5/y71yUYHhv6BPy0ZZvzdkybiI3zkH5yl0prOEn2mGi7oHLEMff
  892. NFiVhuk9GeZcJ3NgyI14AvQdpJgJoxlwaTwlYmYqqyIjxXuFOE8uCXMyp70+m63K
  893. hAfmDzr/d8WdQYUAirab7rCkPy1MTOZCPrtRyN1IVPQMjkcCAwEAAaNGMEQwDgYD
  894. VR0PAQH/BAQDAgWgMBMGA1UdJQQMMAoGCCsGAQUFBwMBMAwGA1UdEwEB/wQCMAAw
  895. DwYDVR0RBAgwBocEfwAAATANBgkqhkiG9w0BAQsFAAOBgQBGq0Si+yhU+Fpn+GKU
  896. 8ZqyGJ7ysd4dfm92lam6512oFmyc9wnTN+RLKzZ8Aa1B0jLYw9KT+RBrjpW5LBeK
  897. o0RIvFkTgxYEiKSBXCUNmAysEbEoVr4dzWFihAm/1oDGRY2CLLTYg5vbySK3KhIR
  898. e/oCO8HJ/+rJnahJ05XX1Q7lNQ==
  899. -----END CERTIFICATE-----`
  900. const clientKeyPEM = `
  901. -----BEGIN RSA PRIVATE KEY-----
  902. MIICXQIBAAKBgQC6b6qGvc+/n/LvXJRgeG/oE/LRlm/N2TJuIjfOQfnKXSms4Sfa
  903. YaLugcsQx980WJWG6T0Z5lwnc2DIjXgC9B2kmAmjGXBpPCViZiqrIiPFe4U4Ty4J
  904. czKnvT6brcqEB+YPOv93xZ1BhQCKtpvusKQ/LUxM5kI+u1HI3UhU9AyORwIDAQAB
  905. AoGAEJZ03q4uuMb7b26WSQsOMeDsftdatT747LGgs3pNRkMJvTb/O7/qJjxoG+Mc
  906. qeSj0TAZXp+PXXc3ikCECAc+R8rVMfWdmp903XgO/qYtmZGCorxAHEmR80SrfMXv
  907. PJnznLQWc8U9nphQErR+tTESg7xWEzmFcPKwnZd1xg8ERYkCQQDTGtrFczlB2b/Z
  908. 9TjNMqUlMnTLIk/a/rPE2fLLmAYhK5sHnJdvDURaH2mF4nso0EGtENnTsh6LATnY
  909. dkrxXGm9AkEA4hXHG2q3MnhgK1Z5hjv+Fnqd+8bcbII9WW4flFs15EKoMgS1w/PJ
  910. zbsySaSy5IVS8XeShmT9+3lrleed4sy+UwJBAJOOAbxhfXP5r4+5R6ql66jES75w
  911. jUCVJzJA5ORJrn8g64u2eGK28z/LFQbv9wXgCwfc72R468BdawFSLa/m2EECQGbZ
  912. rWiFla26IVXV0xcD98VWJsTBZMlgPnSOqoMdM1kSEd4fUmlAYI/dFzV1XYSkOmVr
  913. FhdZnklmpVDeu27P4c0CQQCuCOup0FlJSBpWY1TTfun/KMBkBatMz0VMA3d7FKIU
  914. csPezl677Yjo8u1r/KzeI6zLg87Z8E6r6ZWNc9wBSZK6
  915. -----END RSA PRIVATE KEY-----`
  916. const clientECDSACertificatePEM = `
  917. -----BEGIN CERTIFICATE-----
  918. MIIB/DCCAV4CCQCaMIRsJjXZFzAJBgcqhkjOPQQBMEUxCzAJBgNVBAYTAkFVMRMw
  919. EQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0
  920. eSBMdGQwHhcNMTIxMTE0MTMyNTUzWhcNMjIxMTEyMTMyNTUzWjBBMQswCQYDVQQG
  921. EwJBVTEMMAoGA1UECBMDTlNXMRAwDgYDVQQHEwdQeXJtb250MRIwEAYDVQQDEwlK
  922. b2VsIFNpbmcwgZswEAYHKoZIzj0CAQYFK4EEACMDgYYABACVjJF1FMBexFe01MNv
  923. ja5oHt1vzobhfm6ySD6B5U7ixohLZNz1MLvT/2XMW/TdtWo+PtAd3kfDdq0Z9kUs
  924. jLzYHQFMH3CQRnZIi4+DzEpcj0B22uCJ7B0rxE4wdihBsmKo+1vx+U56jb0JuK7q
  925. ixgnTy5w/hOWusPTQBbNZU6sER7m8TAJBgcqhkjOPQQBA4GMADCBiAJCAOAUxGBg
  926. C3JosDJdYUoCdFzCgbkWqD8pyDbHgf9stlvZcPE4O1BIKJTLCRpS8V3ujfK58PDa
  927. 2RU6+b0DeoeiIzXsAkIBo9SKeDUcSpoj0gq+KxAxnZxfvuiRs9oa9V2jI/Umi0Vw
  928. jWVim34BmT0Y9hCaOGGbLlfk+syxis7iI6CH8OFnUes=
  929. -----END CERTIFICATE-----`
  930. const clientECDSAKeyPEM = `
  931. -----BEGIN EC PARAMETERS-----
  932. BgUrgQQAIw==
  933. -----END EC PARAMETERS-----
  934. -----BEGIN EC PRIVATE KEY-----
  935. MIHcAgEBBEIBkJN9X4IqZIguiEVKMqeBUP5xtRsEv4HJEtOpOGLELwO53SD78Ew8
  936. k+wLWoqizS3NpQyMtrU8JFdWfj+C57UNkOugBwYFK4EEACOhgYkDgYYABACVjJF1
  937. FMBexFe01MNvja5oHt1vzobhfm6ySD6B5U7ixohLZNz1MLvT/2XMW/TdtWo+PtAd
  938. 3kfDdq0Z9kUsjLzYHQFMH3CQRnZIi4+DzEpcj0B22uCJ7B0rxE4wdihBsmKo+1vx
  939. +U56jb0JuK7qixgnTy5w/hOWusPTQBbNZU6sER7m8Q==
  940. -----END EC PRIVATE KEY-----`
  941. func TestClientAuth(t *testing.T) {
  942. setParallel(t)
  943. var certPath, keyPath, ecdsaCertPath, ecdsaKeyPath string
  944. if *update {
  945. certPath = tempFile(clientCertificatePEM)
  946. defer os.Remove(certPath)
  947. keyPath = tempFile(clientKeyPEM)
  948. defer os.Remove(keyPath)
  949. ecdsaCertPath = tempFile(clientECDSACertificatePEM)
  950. defer os.Remove(ecdsaCertPath)
  951. ecdsaKeyPath = tempFile(clientECDSAKeyPEM)
  952. defer os.Remove(ecdsaKeyPath)
  953. }
  954. config := testConfig.Clone()
  955. config.ClientAuth = RequestClientCert
  956. test := &serverTest{
  957. name: "ClientAuthRequestedNotGiven",
  958. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA"},
  959. config: config,
  960. }
  961. runServerTestTLS12(t, test)
  962. test = &serverTest{
  963. name: "ClientAuthRequestedAndGiven",
  964. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-cert", certPath, "-key", keyPath},
  965. config: config,
  966. expectedPeerCerts: []string{clientCertificatePEM},
  967. }
  968. runServerTestTLS12(t, test)
  969. test = &serverTest{
  970. name: "ClientAuthRequestedAndECDSAGiven",
  971. command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-cert", ecdsaCertPath, "-key", ecdsaKeyPath},
  972. config: config,
  973. expectedPeerCerts: []string{clientECDSACertificatePEM},
  974. }
  975. runServerTestTLS12(t, test)
  976. }
  977. func TestSNIGivenOnFailure(t *testing.T) {
  978. const expectedServerName = "test.testing"
  979. clientHello := &clientHelloMsg{
  980. vers: VersionTLS10,
  981. cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
  982. compressionMethods: []uint8{compressionNone},
  983. serverName: expectedServerName,
  984. }
  985. serverConfig := testConfig.Clone()
  986. // Erase the server's cipher suites to ensure the handshake fails.
  987. serverConfig.CipherSuites = nil
  988. c, s := net.Pipe()
  989. go func() {
  990. cli := Client(c, testConfig)
  991. cli.vers = clientHello.vers
  992. cli.writeRecord(recordTypeHandshake, clientHello.marshal())
  993. c.Close()
  994. }()
  995. hs := serverHandshakeState{
  996. c: Server(s, serverConfig),
  997. }
  998. _, err := hs.readClientHello()
  999. defer s.Close()
  1000. if err == nil {
  1001. t.Error("No error reported from server")
  1002. }
  1003. cs := hs.c.ConnectionState()
  1004. if cs.HandshakeComplete {
  1005. t.Error("Handshake registered as complete")
  1006. }
  1007. if cs.ServerName != expectedServerName {
  1008. t.Errorf("Expected ServerName of %q, but got %q", expectedServerName, cs.ServerName)
  1009. }
  1010. }
  1011. var getConfigForClientTests = []struct {
  1012. setup func(config *Config)
  1013. callback func(clientHello *ClientHelloInfo) (*Config, error)
  1014. errorSubstring string
  1015. verify func(config *Config) error
  1016. }{
  1017. {
  1018. nil,
  1019. func(clientHello *ClientHelloInfo) (*Config, error) {
  1020. return nil, nil
  1021. },
  1022. "",
  1023. nil,
  1024. },
  1025. {
  1026. nil,
  1027. func(clientHello *ClientHelloInfo) (*Config, error) {
  1028. return nil, errors.New("should bubble up")
  1029. },
  1030. "should bubble up",
  1031. nil,
  1032. },
  1033. {
  1034. nil,
  1035. func(clientHello *ClientHelloInfo) (*Config, error) {
  1036. config := testConfig.Clone()
  1037. // Setting a maximum version of TLS 1.1 should cause
  1038. // the handshake to fail.
  1039. config.MaxVersion = VersionTLS11
  1040. return config, nil
  1041. },
  1042. "version 301 when expecting version 302",
  1043. nil,
  1044. },
  1045. {
  1046. func(config *Config) {
  1047. for i := range config.SessionTicketKey {
  1048. config.SessionTicketKey[i] = byte(i)
  1049. }
  1050. config.sessionTicketKeys = nil
  1051. },
  1052. func(clientHello *ClientHelloInfo) (*Config, error) {
  1053. config := testConfig.Clone()
  1054. for i := range config.SessionTicketKey {
  1055. config.SessionTicketKey[i] = 0
  1056. }
  1057. config.sessionTicketKeys = nil
  1058. return config, nil
  1059. },
  1060. "",
  1061. func(config *Config) error {
  1062. // The value of SessionTicketKey should have been
  1063. // duplicated into the per-connection Config.
  1064. for i := range config.SessionTicketKey {
  1065. if b := config.SessionTicketKey[i]; b != byte(i) {
  1066. return fmt.Errorf("SessionTicketKey was not duplicated from original Config: byte %d has value %d", i, b)
  1067. }
  1068. }
  1069. return nil
  1070. },
  1071. },
  1072. {
  1073. func(config *Config) {
  1074. var dummyKey [32]byte
  1075. for i := range dummyKey {
  1076. dummyKey[i] = byte(i)
  1077. }
  1078. config.SetSessionTicketKeys([][32]byte{dummyKey})
  1079. },
  1080. func(clientHello *ClientHelloInfo) (*Config, error) {
  1081. config := testConfig.Clone()
  1082. config.sessionTicketKeys = nil
  1083. return config, nil
  1084. },
  1085. "",
  1086. func(config *Config) error {
  1087. // The session ticket keys should have been duplicated
  1088. // into the per-connection Config.
  1089. if l := len(config.sessionTicketKeys); l != 1 {
  1090. return fmt.Errorf("got len(sessionTicketKeys) == %d, wanted 1", l)
  1091. }
  1092. return nil
  1093. },
  1094. },
  1095. }
  1096. func TestGetConfigForClient(t *testing.T) {
  1097. serverConfig := testConfig.Clone()
  1098. clientConfig := testConfig.Clone()
  1099. clientConfig.MinVersion = VersionTLS12
  1100. for i, test := range getConfigForClientTests {
  1101. if test.setup != nil {
  1102. test.setup(serverConfig)
  1103. }
  1104. var configReturned *Config
  1105. serverConfig.GetConfigForClient = func(clientHello *ClientHelloInfo) (*Config, error) {
  1106. config, err := test.callback(clientHello)
  1107. configReturned = config
  1108. return config, err
  1109. }
  1110. c, s := net.Pipe()
  1111. done := make(chan error)
  1112. go func() {
  1113. defer s.Close()
  1114. done <- Server(s, serverConfig).Handshake()
  1115. }()
  1116. clientErr := Client(c, clientConfig).Handshake()
  1117. c.Close()
  1118. serverErr := <-done
  1119. if len(test.errorSubstring) == 0 {
  1120. if serverErr != nil || clientErr != nil {
  1121. t.Errorf("test[%d]: expected no error but got serverErr: %q, clientErr: %q", i, serverErr, clientErr)
  1122. }
  1123. if test.verify != nil {
  1124. if err := test.verify(configReturned); err != nil {
  1125. t.Errorf("test[%d]: verify returned error: %v", i, err)
  1126. }
  1127. }
  1128. } else {
  1129. if serverErr == nil {
  1130. t.Errorf("test[%d]: expected error containing %q but got no error", i, test.errorSubstring)
  1131. } else if !strings.Contains(serverErr.Error(), test.errorSubstring) {
  1132. t.Errorf("test[%d]: expected error to contain %q but it was %q", i, test.errorSubstring, serverErr)
  1133. }
  1134. }
  1135. }
  1136. }
  1137. func bigFromString(s string) *big.Int {
  1138. ret := new(big.Int)
  1139. ret.SetString(s, 10)
  1140. return ret
  1141. }
  1142. func fromHex(s string) []byte {
  1143. b, _ := hex.DecodeString(s)
  1144. return b
  1145. }
  1146. var testRSACertificate = fromHex("3082024b308201b4a003020102020900e8f09d3fe25beaa6300d06092a864886f70d01010b0500301f310b3009060355040a1302476f3110300e06035504031307476f20526f6f74301e170d3136303130313030303030305a170d3235303130313030303030305a301a310b3009060355040a1302476f310b300906035504031302476f30819f300d06092a864886f70d010101050003818d0030818902818100db467d932e12270648bc062821ab7ec4b6a25dfe1e5245887a3647a5080d92425bc281c0be97799840fb4f6d14fd2b138bc2a52e67d8d4099ed62238b74a0b74732bc234f1d193e596d9747bf3589f6c613cc0b041d4d92b2b2423775b1c3bbd755dce2054cfa163871d1e24c4f31d1a508baab61443ed97a77562f414c852d70203010001a38193308190300e0603551d0f0101ff0404030205a0301d0603551d250416301406082b0601050507030106082b06010505070302300c0603551d130101ff0402300030190603551d0e041204109f91161f43433e49a6de6db680d79f60301b0603551d230414301280104813494d137e1631bba301d5acab6e7b30190603551d1104123010820e6578616d706c652e676f6c616e67300d06092a864886f70d01010b0500038181009d30cc402b5b50a061cbbae55358e1ed8328a9581aa938a495a1ac315a1a84663d43d32dd90bf297dfd320643892243a00bccf9c7db74020015faad3166109a276fd13c3cce10c5ceeb18782f16c04ed73bbb343778d0c1cf10fa1d8408361c94c722b9daedb4606064df4c1b33ec0d1bd42d4dbfe3d1360845c21d33be9fae7")
  1147. var testRSACertificateIssuer = fromHex("3082021930820182a003020102020900ca5e4e811a965964300d06092a864886f70d01010b0500301f310b3009060355040a1302476f3110300e06035504031307476f20526f6f74301e170d3136303130313030303030305a170d3235303130313030303030305a301f310b3009060355040a1302476f3110300e06035504031307476f20526f6f7430819f300d06092a864886f70d010101050003818d0030818902818100d667b378bb22f34143b6cd2008236abefaf2852adf3ab05e01329e2c14834f5105df3f3073f99dab5442d45ee5f8f57b0111c8cb682fbb719a86944eebfffef3406206d898b8c1b1887797c9c5006547bb8f00e694b7a063f10839f269f2c34fff7a1f4b21fbcd6bfdfb13ac792d1d11f277b5c5b48600992203059f2a8f8cc50203010001a35d305b300e0603551d0f0101ff040403020204301d0603551d250416301406082b0601050507030106082b06010505070302300f0603551d130101ff040530030101ff30190603551d0e041204104813494d137e1631bba301d5acab6e7b300d06092a864886f70d01010b050003818100c1154b4bab5266221f293766ae4138899bd4c5e36b13cee670ceeaa4cbdf4f6679017e2fe649765af545749fe4249418a56bd38a04b81e261f5ce86b8d5c65413156a50d12449554748c59a30c515bc36a59d38bddf51173e899820b282e40aa78c806526fd184fb6b4cf186ec728edffa585440d2b3225325f7ab580e87dd76")
  1148. var testECDSACertificate = fromHex("3082020030820162020900b8bf2d47a0d2ebf4300906072a8648ce3d04013045310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c7464301e170d3132313132323135303633325a170d3232313132303135303633325a3045310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c746430819b301006072a8648ce3d020106052b81040023038186000400c4a1edbe98f90b4873367ec316561122f23d53c33b4d213dcd6b75e6f6b0dc9adf26c1bcb287f072327cb3642f1c90bcea6823107efee325c0483a69e0286dd33700ef0462dd0da09c706283d881d36431aa9e9731bd96b068c09b23de76643f1a5c7fe9120e5858b65f70dd9bd8ead5d7f5d5ccb9b69f30665b669a20e227e5bffe3b300906072a8648ce3d040103818c0030818802420188a24febe245c5487d1bacf5ed989dae4770c05e1bb62fbdf1b64db76140d311a2ceee0b7e927eff769dc33b7ea53fcefa10e259ec472d7cacda4e970e15a06fd00242014dfcbe67139c2d050ebd3fa38c25c13313830d9406bbd4377af6ec7ac9862eddd711697f857c56defb31782be4c7780daecbbe9e4e3624317b6a0f399512078f2a")
  1149. var testSNICertificate = fromHex("0441883421114c81480804c430820237308201a0a003020102020900e8f09d3fe25beaa6300d06092a864886f70d01010b0500301f310b3009060355040a1302476f3110300e06035504031307476f20526f6f74301e170d3136303130313030303030305a170d3235303130313030303030305a3023310b3009060355040a1302476f311430120603550403130b736e69746573742e636f6d30819f300d06092a864886f70d010101050003818d0030818902818100db467d932e12270648bc062821ab7ec4b6a25dfe1e5245887a3647a5080d92425bc281c0be97799840fb4f6d14fd2b138bc2a52e67d8d4099ed62238b74a0b74732bc234f1d193e596d9747bf3589f6c613cc0b041d4d92b2b2423775b1c3bbd755dce2054cfa163871d1e24c4f31d1a508baab61443ed97a77562f414c852d70203010001a3773075300e0603551d0f0101ff0404030205a0301d0603551d250416301406082b0601050507030106082b06010505070302300c0603551d130101ff0402300030190603551d0e041204109f91161f43433e49a6de6db680d79f60301b0603551d230414301280104813494d137e1631bba301d5acab6e7b300d06092a864886f70d01010b0500038181007beeecff0230dbb2e7a334af65430b7116e09f327c3bbf918107fc9c66cb497493207ae9b4dbb045cb63d605ec1b5dd485bb69124d68fa298dc776699b47632fd6d73cab57042acb26f083c4087459bc5a3bb3ca4d878d7fe31016b7bc9a627438666566e3389bfaeebe6becc9a0093ceed18d0f9ac79d56f3a73f18188988ed")
  1150. var testRSAPrivateKey = &rsa.PrivateKey{
  1151. PublicKey: rsa.PublicKey{
  1152. N: bigFromString("153980389784927331788354528594524332344709972855165340650588877572729725338415474372475094155672066328274535240275856844648695200875763869073572078279316458648124537905600131008790701752441155668003033945258023841165089852359980273279085783159654751552359397986180318708491098942831252291841441726305535546071"),
  1153. E: 65537,
  1154. },
  1155. D: bigFromString("7746362285745539358014631136245887418412633787074173796862711588221766398229333338511838891484974940633857861775630560092874987828057333663969469797013996401149696897591265769095952887917296740109742927689053276850469671231961384712725169432413343763989564437170644270643461665184965150423819594083121075825"),
  1156. Primes: []*big.Int{
  1157. bigFromString("13299275414352936908236095374926261633419699590839189494995965049151460173257838079863316944311313904000258169883815802963543635820059341150014695560313417"),
  1158. bigFromString("11578103692682951732111718237224894755352163854919244905974423810539077224889290605729035287537520656160688625383765857517518932447378594964220731750802463"),
  1159. },
  1160. }
  1161. var testECDSAPrivateKey = &ecdsa.PrivateKey{
  1162. PublicKey: ecdsa.PublicKey{
  1163. Curve: elliptic.P521(),
  1164. X: bigFromString("2636411247892461147287360222306590634450676461695221912739908880441342231985950069527906976759812296359387337367668045707086543273113073382714101597903639351"),
  1165. Y: bigFromString("3204695818431246682253994090650952614555094516658732116404513121125038617915183037601737180082382202488628239201196033284060130040574800684774115478859677243"),
  1166. },
  1167. D: bigFromString("5477294338614160138026852784385529180817726002953041720191098180813046231640184669647735805135001309477695746518160084669446643325196003346204701381388769751"),
  1168. }