handshake_server_test.go 45 KB

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