Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 
 
 

837 righe
24 KiB

  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"
  8. "crypto/ecdsa"
  9. "crypto/rsa"
  10. "crypto/subtle"
  11. "crypto/x509"
  12. "errors"
  13. "fmt"
  14. "io"
  15. "net"
  16. "strconv"
  17. "strings"
  18. "sync/atomic"
  19. )
  20. type clientHandshakeState struct {
  21. c *Conn
  22. serverHello *serverHelloMsg
  23. hello *clientHelloMsg
  24. suite *cipherSuite
  25. finishedHash finishedHash
  26. masterSecret []byte
  27. session *ClientSessionState
  28. }
  29. // c.out.Mutex <= L; c.handshakeMutex <= L.
  30. func (c *Conn) clientHandshake() error {
  31. if c.config == nil {
  32. c.config = defaultConfig()
  33. }
  34. // This may be a renegotiation handshake, in which case some fields
  35. // need to be reset.
  36. c.didResume = false
  37. if len(c.config.ServerName) == 0 && !c.config.InsecureSkipVerify {
  38. return errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config")
  39. }
  40. nextProtosLength := 0
  41. for _, proto := range c.config.NextProtos {
  42. if l := len(proto); l == 0 || l > 255 {
  43. return errors.New("tls: invalid NextProtos value")
  44. } else {
  45. nextProtosLength += 1 + l
  46. }
  47. }
  48. if nextProtosLength > 0xffff {
  49. return errors.New("tls: NextProtos values too large")
  50. }
  51. hello := &clientHelloMsg{
  52. vers: c.config.maxVersion(),
  53. compressionMethods: []uint8{compressionNone},
  54. random: make([]byte, 32),
  55. ocspStapling: true,
  56. scts: true,
  57. serverName: hostnameInSNI(c.config.ServerName),
  58. supportedCurves: c.config.curvePreferences(),
  59. supportedPoints: []uint8{pointFormatUncompressed},
  60. nextProtoNeg: len(c.config.NextProtos) > 0,
  61. secureRenegotiationSupported: true,
  62. alpnProtocols: c.config.NextProtos,
  63. }
  64. if c.handshakes > 0 {
  65. hello.secureRenegotiation = c.clientFinished[:]
  66. }
  67. possibleCipherSuites := c.config.cipherSuites()
  68. hello.cipherSuites = make([]uint16, 0, len(possibleCipherSuites))
  69. NextCipherSuite:
  70. for _, suiteId := range possibleCipherSuites {
  71. for _, suite := range cipherSuites {
  72. if suite.id != suiteId {
  73. continue
  74. }
  75. // Don't advertise TLS 1.2-only cipher suites unless
  76. // we're attempting TLS 1.2.
  77. if hello.vers < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
  78. continue NextCipherSuite
  79. }
  80. // Don't advertise TLS 1.3-only cipher suites unless
  81. // we're attempting TLS 1.3.
  82. if hello.vers < VersionTLS13 && suite.flags&suiteTLS13 != 0 {
  83. continue NextCipherSuite
  84. }
  85. hello.cipherSuites = append(hello.cipherSuites, suiteId)
  86. continue NextCipherSuite
  87. }
  88. }
  89. _, err := io.ReadFull(c.config.rand(), hello.random)
  90. if err != nil {
  91. c.sendAlert(alertInternalError)
  92. return errors.New("tls: short read from Rand: " + err.Error())
  93. }
  94. if hello.vers >= VersionTLS12 {
  95. hello.signatureAndHashes = supportedSignatureAlgorithms
  96. }
  97. var session *ClientSessionState
  98. var cacheKey string
  99. sessionCache := c.config.ClientSessionCache
  100. if c.config.SessionTicketsDisabled {
  101. sessionCache = nil
  102. }
  103. if sessionCache != nil {
  104. hello.ticketSupported = true
  105. }
  106. // Session resumption is not allowed if renegotiating because
  107. // renegotiation is primarily used to allow a client to send a client
  108. // certificate, which would be skipped if session resumption occurred.
  109. if sessionCache != nil && c.handshakes == 0 {
  110. // Try to resume a previously negotiated TLS session, if
  111. // available.
  112. cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
  113. candidateSession, ok := sessionCache.Get(cacheKey)
  114. if ok {
  115. // Check that the ciphersuite/version used for the
  116. // previous session are still valid.
  117. cipherSuiteOk := false
  118. for _, id := range hello.cipherSuites {
  119. if id == candidateSession.cipherSuite {
  120. cipherSuiteOk = true
  121. break
  122. }
  123. }
  124. versOk := candidateSession.vers >= c.config.minVersion() &&
  125. candidateSession.vers <= c.config.maxVersion()
  126. if versOk && cipherSuiteOk {
  127. session = candidateSession
  128. }
  129. }
  130. }
  131. if session != nil {
  132. hello.sessionTicket = session.sessionTicket
  133. // A random session ID is used to detect when the
  134. // server accepted the ticket and is resuming a session
  135. // (see RFC 5077).
  136. hello.sessionId = make([]byte, 16)
  137. if _, err := io.ReadFull(c.config.rand(), hello.sessionId); err != nil {
  138. c.sendAlert(alertInternalError)
  139. return errors.New("tls: short read from Rand: " + err.Error())
  140. }
  141. }
  142. if _, err := c.writeRecord(recordTypeHandshake, hello.marshal()); err != nil {
  143. return err
  144. }
  145. msg, err := c.readHandshake()
  146. if err != nil {
  147. return err
  148. }
  149. serverHello, ok := msg.(*serverHelloMsg)
  150. if !ok {
  151. c.sendAlert(alertUnexpectedMessage)
  152. return unexpectedMessageError(serverHello, msg)
  153. }
  154. vers, ok := c.config.pickVersion([]uint16{serverHello.vers})
  155. if !ok || vers < VersionTLS10 {
  156. // TLS 1.0 is the minimum version supported as a client.
  157. c.sendAlert(alertProtocolVersion)
  158. return fmt.Errorf("tls: server selected unsupported protocol version %x", serverHello.vers)
  159. }
  160. c.vers = vers
  161. c.haveVers = true
  162. suite := mutualCipherSuite(hello.cipherSuites, serverHello.cipherSuite)
  163. if suite == nil {
  164. c.sendAlert(alertHandshakeFailure)
  165. return errors.New("tls: server chose an unconfigured cipher suite")
  166. }
  167. // Check that the chosen cipher suite matches the protocol version.
  168. if c.vers >= VersionTLS13 && suite.flags&suiteTLS13 == 0 ||
  169. c.vers < VersionTLS13 && suite.flags&suiteTLS13 != 0 {
  170. c.sendAlert(alertHandshakeFailure)
  171. return errors.New("tls: server chose an inappropriate cipher suite")
  172. }
  173. hs := &clientHandshakeState{
  174. c: c,
  175. serverHello: serverHello,
  176. hello: hello,
  177. suite: suite,
  178. finishedHash: newFinishedHash(c.vers, suite),
  179. session: session,
  180. }
  181. isResume, err := hs.processServerHello()
  182. if err != nil {
  183. return err
  184. }
  185. // No signatures of the handshake are needed in a resumption.
  186. // Otherwise, in a full handshake, if we don't have any certificates
  187. // configured then we will never send a CertificateVerify message and
  188. // thus no signatures are needed in that case either.
  189. if isResume || (len(c.config.Certificates) == 0 && c.config.GetClientCertificate == nil) {
  190. hs.finishedHash.discardHandshakeBuffer()
  191. }
  192. hs.finishedHash.Write(hs.hello.marshal())
  193. hs.finishedHash.Write(hs.serverHello.marshal())
  194. c.buffering = true
  195. if isResume {
  196. if err := hs.establishKeys(); err != nil {
  197. return err
  198. }
  199. if err := hs.readSessionTicket(); err != nil {
  200. return err
  201. }
  202. if err := hs.readFinished(c.serverFinished[:]); err != nil {
  203. return err
  204. }
  205. c.clientFinishedIsFirst = false
  206. if err := hs.sendFinished(c.clientFinished[:]); err != nil {
  207. return err
  208. }
  209. if _, err := c.flush(); err != nil {
  210. return err
  211. }
  212. } else {
  213. if err := hs.doFullHandshake(); err != nil {
  214. return err
  215. }
  216. if err := hs.establishKeys(); err != nil {
  217. return err
  218. }
  219. if err := hs.sendFinished(c.clientFinished[:]); err != nil {
  220. return err
  221. }
  222. if _, err := c.flush(); err != nil {
  223. return err
  224. }
  225. c.clientFinishedIsFirst = true
  226. if err := hs.readSessionTicket(); err != nil {
  227. return err
  228. }
  229. if err := hs.readFinished(c.serverFinished[:]); err != nil {
  230. return err
  231. }
  232. }
  233. if sessionCache != nil && hs.session != nil && session != hs.session {
  234. sessionCache.Put(cacheKey, hs.session)
  235. }
  236. c.didResume = isResume
  237. c.phase = handshakeConfirmed
  238. atomic.StoreInt32(&c.handshakeConfirmed, 1)
  239. c.handshakeComplete = true
  240. c.cipherSuite = suite.id
  241. return nil
  242. }
  243. func (hs *clientHandshakeState) doFullHandshake() error {
  244. c := hs.c
  245. msg, err := c.readHandshake()
  246. if err != nil {
  247. return err
  248. }
  249. certMsg, ok := msg.(*certificateMsg)
  250. if !ok || len(certMsg.certificates) == 0 {
  251. c.sendAlert(alertUnexpectedMessage)
  252. return unexpectedMessageError(certMsg, msg)
  253. }
  254. hs.finishedHash.Write(certMsg.marshal())
  255. if c.handshakes == 0 {
  256. // If this is the first handshake on a connection, process and
  257. // (optionally) verify the server's certificates.
  258. certs := make([]*x509.Certificate, len(certMsg.certificates))
  259. for i, asn1Data := range certMsg.certificates {
  260. cert, err := x509.ParseCertificate(asn1Data)
  261. if err != nil {
  262. c.sendAlert(alertBadCertificate)
  263. return errors.New("tls: failed to parse certificate from server: " + err.Error())
  264. }
  265. certs[i] = cert
  266. }
  267. if !c.config.InsecureSkipVerify {
  268. opts := x509.VerifyOptions{
  269. Roots: c.config.RootCAs,
  270. CurrentTime: c.config.time(),
  271. DNSName: c.config.ServerName,
  272. Intermediates: x509.NewCertPool(),
  273. }
  274. for i, cert := range certs {
  275. if i == 0 {
  276. continue
  277. }
  278. opts.Intermediates.AddCert(cert)
  279. }
  280. c.verifiedChains, err = certs[0].Verify(opts)
  281. if err != nil {
  282. c.sendAlert(alertBadCertificate)
  283. return err
  284. }
  285. }
  286. if c.config.VerifyPeerCertificate != nil {
  287. if err := c.config.VerifyPeerCertificate(certMsg.certificates, c.verifiedChains); err != nil {
  288. c.sendAlert(alertBadCertificate)
  289. return err
  290. }
  291. }
  292. switch certs[0].PublicKey.(type) {
  293. case *rsa.PublicKey, *ecdsa.PublicKey:
  294. break
  295. default:
  296. c.sendAlert(alertUnsupportedCertificate)
  297. return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
  298. }
  299. c.peerCertificates = certs
  300. } else {
  301. // This is a renegotiation handshake. We require that the
  302. // server's identity (i.e. leaf certificate) is unchanged and
  303. // thus any previous trust decision is still valid.
  304. //
  305. // See https://mitls.org/pages/attacks/3SHAKE for the
  306. // motivation behind this requirement.
  307. if !bytes.Equal(c.peerCertificates[0].Raw, certMsg.certificates[0]) {
  308. c.sendAlert(alertBadCertificate)
  309. return errors.New("tls: server's identity changed during renegotiation")
  310. }
  311. }
  312. if hs.serverHello.ocspStapling {
  313. msg, err = c.readHandshake()
  314. if err != nil {
  315. return err
  316. }
  317. cs, ok := msg.(*certificateStatusMsg)
  318. if !ok {
  319. c.sendAlert(alertUnexpectedMessage)
  320. return unexpectedMessageError(cs, msg)
  321. }
  322. hs.finishedHash.Write(cs.marshal())
  323. if cs.statusType == statusTypeOCSP {
  324. c.ocspResponse = cs.response
  325. }
  326. }
  327. msg, err = c.readHandshake()
  328. if err != nil {
  329. return err
  330. }
  331. keyAgreement := hs.suite.ka(c.vers)
  332. skx, ok := msg.(*serverKeyExchangeMsg)
  333. if ok {
  334. hs.finishedHash.Write(skx.marshal())
  335. err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, c.peerCertificates[0], skx)
  336. if err != nil {
  337. c.sendAlert(alertUnexpectedMessage)
  338. return err
  339. }
  340. msg, err = c.readHandshake()
  341. if err != nil {
  342. return err
  343. }
  344. }
  345. var chainToSend *Certificate
  346. var certRequested bool
  347. certReq, ok := msg.(*certificateRequestMsg)
  348. if ok {
  349. certRequested = true
  350. hs.finishedHash.Write(certReq.marshal())
  351. if chainToSend, err = hs.getCertificate(certReq); err != nil {
  352. c.sendAlert(alertInternalError)
  353. return err
  354. }
  355. msg, err = c.readHandshake()
  356. if err != nil {
  357. return err
  358. }
  359. }
  360. shd, ok := msg.(*serverHelloDoneMsg)
  361. if !ok {
  362. c.sendAlert(alertUnexpectedMessage)
  363. return unexpectedMessageError(shd, msg)
  364. }
  365. hs.finishedHash.Write(shd.marshal())
  366. // If the server requested a certificate then we have to send a
  367. // Certificate message, even if it's empty because we don't have a
  368. // certificate to send.
  369. if certRequested {
  370. certMsg = new(certificateMsg)
  371. certMsg.certificates = chainToSend.Certificate
  372. hs.finishedHash.Write(certMsg.marshal())
  373. if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
  374. return err
  375. }
  376. }
  377. preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, c.peerCertificates[0])
  378. if err != nil {
  379. c.sendAlert(alertInternalError)
  380. return err
  381. }
  382. if ckx != nil {
  383. hs.finishedHash.Write(ckx.marshal())
  384. if _, err := c.writeRecord(recordTypeHandshake, ckx.marshal()); err != nil {
  385. return err
  386. }
  387. }
  388. if chainToSend != nil && len(chainToSend.Certificate) > 0 {
  389. certVerify := &certificateVerifyMsg{
  390. hasSignatureAndHash: c.vers >= VersionTLS12,
  391. }
  392. key, ok := chainToSend.PrivateKey.(crypto.Signer)
  393. if !ok {
  394. c.sendAlert(alertInternalError)
  395. return fmt.Errorf("tls: client certificate private key of type %T does not implement crypto.Signer", chainToSend.PrivateKey)
  396. }
  397. var signatureType uint8
  398. switch key.Public().(type) {
  399. case *ecdsa.PublicKey:
  400. signatureType = signatureECDSA
  401. case *rsa.PublicKey:
  402. signatureType = signatureRSA
  403. default:
  404. c.sendAlert(alertInternalError)
  405. return fmt.Errorf("tls: failed to sign handshake with client certificate: unknown client certificate key type: %T", key)
  406. }
  407. certVerify.signatureAndHash, err = hs.finishedHash.selectClientCertSignatureAlgorithm(certReq.signatureAndHashes, signatureType)
  408. if err != nil {
  409. c.sendAlert(alertInternalError)
  410. return err
  411. }
  412. digest, hashFunc, err := hs.finishedHash.hashForClientCertificate(certVerify.signatureAndHash, hs.masterSecret)
  413. if err != nil {
  414. c.sendAlert(alertInternalError)
  415. return err
  416. }
  417. certVerify.signature, err = key.Sign(c.config.rand(), digest, hashFunc)
  418. if err != nil {
  419. c.sendAlert(alertInternalError)
  420. return err
  421. }
  422. hs.finishedHash.Write(certVerify.marshal())
  423. if _, err := c.writeRecord(recordTypeHandshake, certVerify.marshal()); err != nil {
  424. return err
  425. }
  426. }
  427. hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
  428. if err := c.config.writeKeyLog("CLIENT_RANDOM", hs.hello.random, hs.masterSecret); err != nil {
  429. c.sendAlert(alertInternalError)
  430. return errors.New("tls: failed to write to key log: " + err.Error())
  431. }
  432. hs.finishedHash.discardHandshakeBuffer()
  433. return nil
  434. }
  435. func (hs *clientHandshakeState) establishKeys() error {
  436. c := hs.c
  437. clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
  438. keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
  439. var clientCipher, serverCipher interface{}
  440. var clientHash, serverHash macFunction
  441. if hs.suite.cipher != nil {
  442. clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
  443. clientHash = hs.suite.mac(c.vers, clientMAC)
  444. serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
  445. serverHash = hs.suite.mac(c.vers, serverMAC)
  446. } else {
  447. clientCipher = hs.suite.aead(clientKey, clientIV)
  448. serverCipher = hs.suite.aead(serverKey, serverIV)
  449. }
  450. c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
  451. c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
  452. return nil
  453. }
  454. func (hs *clientHandshakeState) serverResumedSession() bool {
  455. // If the server responded with the same sessionId then it means the
  456. // sessionTicket is being used to resume a TLS session.
  457. return hs.session != nil && hs.hello.sessionId != nil &&
  458. bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
  459. }
  460. func (hs *clientHandshakeState) processServerHello() (bool, error) {
  461. c := hs.c
  462. if hs.serverHello.compressionMethod != compressionNone {
  463. c.sendAlert(alertUnexpectedMessage)
  464. return false, errors.New("tls: server selected unsupported compression format")
  465. }
  466. if c.handshakes == 0 && hs.serverHello.secureRenegotiationSupported {
  467. c.secureRenegotiation = true
  468. if len(hs.serverHello.secureRenegotiation) != 0 {
  469. c.sendAlert(alertHandshakeFailure)
  470. return false, errors.New("tls: initial handshake had non-empty renegotiation extension")
  471. }
  472. }
  473. if c.handshakes > 0 && c.secureRenegotiation {
  474. var expectedSecureRenegotiation [24]byte
  475. copy(expectedSecureRenegotiation[:], c.clientFinished[:])
  476. copy(expectedSecureRenegotiation[12:], c.serverFinished[:])
  477. if !bytes.Equal(hs.serverHello.secureRenegotiation, expectedSecureRenegotiation[:]) {
  478. c.sendAlert(alertHandshakeFailure)
  479. return false, errors.New("tls: incorrect renegotiation extension contents")
  480. }
  481. }
  482. clientDidNPN := hs.hello.nextProtoNeg
  483. clientDidALPN := len(hs.hello.alpnProtocols) > 0
  484. serverHasNPN := hs.serverHello.nextProtoNeg
  485. serverHasALPN := len(hs.serverHello.alpnProtocol) > 0
  486. if !clientDidNPN && serverHasNPN {
  487. c.sendAlert(alertHandshakeFailure)
  488. return false, errors.New("tls: server advertised unrequested NPN extension")
  489. }
  490. if !clientDidALPN && serverHasALPN {
  491. c.sendAlert(alertHandshakeFailure)
  492. return false, errors.New("tls: server advertised unrequested ALPN extension")
  493. }
  494. if serverHasNPN && serverHasALPN {
  495. c.sendAlert(alertHandshakeFailure)
  496. return false, errors.New("tls: server advertised both NPN and ALPN extensions")
  497. }
  498. if serverHasALPN {
  499. c.clientProtocol = hs.serverHello.alpnProtocol
  500. c.clientProtocolFallback = false
  501. }
  502. c.scts = hs.serverHello.scts
  503. if !hs.serverResumedSession() {
  504. return false, nil
  505. }
  506. if hs.session.vers != c.vers {
  507. c.sendAlert(alertHandshakeFailure)
  508. return false, errors.New("tls: server resumed a session with a different version")
  509. }
  510. if hs.session.cipherSuite != hs.suite.id {
  511. c.sendAlert(alertHandshakeFailure)
  512. return false, errors.New("tls: server resumed a session with a different cipher suite")
  513. }
  514. // Restore masterSecret and peerCerts from previous state
  515. hs.masterSecret = hs.session.masterSecret
  516. c.peerCertificates = hs.session.serverCertificates
  517. c.verifiedChains = hs.session.verifiedChains
  518. return true, nil
  519. }
  520. func (hs *clientHandshakeState) readFinished(out []byte) error {
  521. c := hs.c
  522. c.readRecord(recordTypeChangeCipherSpec)
  523. if c.in.err != nil {
  524. return c.in.err
  525. }
  526. msg, err := c.readHandshake()
  527. if err != nil {
  528. return err
  529. }
  530. serverFinished, ok := msg.(*finishedMsg)
  531. if !ok {
  532. c.sendAlert(alertUnexpectedMessage)
  533. return unexpectedMessageError(serverFinished, msg)
  534. }
  535. verify := hs.finishedHash.serverSum(hs.masterSecret)
  536. if len(verify) != len(serverFinished.verifyData) ||
  537. subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
  538. c.sendAlert(alertDecryptError)
  539. return errors.New("tls: server's Finished message was incorrect")
  540. }
  541. hs.finishedHash.Write(serverFinished.marshal())
  542. copy(out, verify)
  543. return nil
  544. }
  545. func (hs *clientHandshakeState) readSessionTicket() error {
  546. if !hs.serverHello.ticketSupported {
  547. return nil
  548. }
  549. c := hs.c
  550. msg, err := c.readHandshake()
  551. if err != nil {
  552. return err
  553. }
  554. sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
  555. if !ok {
  556. c.sendAlert(alertUnexpectedMessage)
  557. return unexpectedMessageError(sessionTicketMsg, msg)
  558. }
  559. hs.finishedHash.Write(sessionTicketMsg.marshal())
  560. hs.session = &ClientSessionState{
  561. sessionTicket: sessionTicketMsg.ticket,
  562. vers: c.vers,
  563. cipherSuite: hs.suite.id,
  564. masterSecret: hs.masterSecret,
  565. serverCertificates: c.peerCertificates,
  566. verifiedChains: c.verifiedChains,
  567. }
  568. return nil
  569. }
  570. func (hs *clientHandshakeState) sendFinished(out []byte) error {
  571. c := hs.c
  572. if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
  573. return err
  574. }
  575. if hs.serverHello.nextProtoNeg {
  576. nextProto := new(nextProtoMsg)
  577. proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.nextProtos)
  578. nextProto.proto = proto
  579. c.clientProtocol = proto
  580. c.clientProtocolFallback = fallback
  581. hs.finishedHash.Write(nextProto.marshal())
  582. if _, err := c.writeRecord(recordTypeHandshake, nextProto.marshal()); err != nil {
  583. return err
  584. }
  585. }
  586. finished := new(finishedMsg)
  587. finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
  588. hs.finishedHash.Write(finished.marshal())
  589. if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
  590. return err
  591. }
  592. copy(out, finished.verifyData)
  593. return nil
  594. }
  595. // tls11SignatureSchemes contains the signature schemes that we synthesise for
  596. // a TLS <= 1.1 connection, based on the supported certificate types.
  597. var tls11SignatureSchemes = []SignatureScheme{ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512, PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1}
  598. const (
  599. // tls11SignatureSchemesNumECDSA is the number of initial elements of
  600. // tls11SignatureSchemes that use ECDSA.
  601. tls11SignatureSchemesNumECDSA = 3
  602. // tls11SignatureSchemesNumRSA is the number of trailing elements of
  603. // tls11SignatureSchemes that use RSA.
  604. tls11SignatureSchemesNumRSA = 4
  605. )
  606. func (hs *clientHandshakeState) getCertificate(certReq *certificateRequestMsg) (*Certificate, error) {
  607. c := hs.c
  608. var rsaAvail, ecdsaAvail bool
  609. for _, certType := range certReq.certificateTypes {
  610. switch certType {
  611. case certTypeRSASign:
  612. rsaAvail = true
  613. case certTypeECDSASign:
  614. ecdsaAvail = true
  615. }
  616. }
  617. if c.config.GetClientCertificate != nil {
  618. var signatureSchemes []SignatureScheme
  619. if !certReq.hasSignatureAndHash {
  620. // Prior to TLS 1.2, the signature schemes were not
  621. // included in the certificate request message. In this
  622. // case we use a plausible list based on the acceptable
  623. // certificate types.
  624. signatureSchemes = tls11SignatureSchemes
  625. if !ecdsaAvail {
  626. signatureSchemes = signatureSchemes[tls11SignatureSchemesNumECDSA:]
  627. }
  628. if !rsaAvail {
  629. signatureSchemes = signatureSchemes[:len(signatureSchemes)-tls11SignatureSchemesNumRSA]
  630. }
  631. } else {
  632. signatureSchemes = make([]SignatureScheme, 0, len(certReq.signatureAndHashes))
  633. for _, sah := range certReq.signatureAndHashes {
  634. signatureSchemes = append(signatureSchemes, SignatureScheme(sah.hash)<<8+SignatureScheme(sah.signature))
  635. }
  636. }
  637. return c.config.GetClientCertificate(&CertificateRequestInfo{
  638. AcceptableCAs: certReq.certificateAuthorities,
  639. SignatureSchemes: signatureSchemes,
  640. })
  641. }
  642. // RFC 4346 on the certificateAuthorities field: A list of the
  643. // distinguished names of acceptable certificate authorities.
  644. // These distinguished names may specify a desired
  645. // distinguished name for a root CA or for a subordinate CA;
  646. // thus, this message can be used to describe both known roots
  647. // and a desired authorization space. If the
  648. // certificate_authorities list is empty then the client MAY
  649. // send any certificate of the appropriate
  650. // ClientCertificateType, unless there is some external
  651. // arrangement to the contrary.
  652. // We need to search our list of client certs for one
  653. // where SignatureAlgorithm is acceptable to the server and the
  654. // Issuer is in certReq.certificateAuthorities
  655. findCert:
  656. for i, chain := range c.config.Certificates {
  657. if !rsaAvail && !ecdsaAvail {
  658. continue
  659. }
  660. for j, cert := range chain.Certificate {
  661. x509Cert := chain.Leaf
  662. // parse the certificate if this isn't the leaf
  663. // node, or if chain.Leaf was nil
  664. if j != 0 || x509Cert == nil {
  665. var err error
  666. if x509Cert, err = x509.ParseCertificate(cert); err != nil {
  667. c.sendAlert(alertInternalError)
  668. return nil, errors.New("tls: failed to parse client certificate #" + strconv.Itoa(i) + ": " + err.Error())
  669. }
  670. }
  671. switch {
  672. case rsaAvail && x509Cert.PublicKeyAlgorithm == x509.RSA:
  673. case ecdsaAvail && x509Cert.PublicKeyAlgorithm == x509.ECDSA:
  674. default:
  675. continue findCert
  676. }
  677. if len(certReq.certificateAuthorities) == 0 {
  678. // they gave us an empty list, so just take the
  679. // first cert from c.config.Certificates
  680. return &chain, nil
  681. }
  682. for _, ca := range certReq.certificateAuthorities {
  683. if bytes.Equal(x509Cert.RawIssuer, ca) {
  684. return &chain, nil
  685. }
  686. }
  687. }
  688. }
  689. // No acceptable certificate found. Don't send a certificate.
  690. return new(Certificate), nil
  691. }
  692. // clientSessionCacheKey returns a key used to cache sessionTickets that could
  693. // be used to resume previously negotiated TLS sessions with a server.
  694. func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
  695. if len(config.ServerName) > 0 {
  696. return config.ServerName
  697. }
  698. return serverAddr.String()
  699. }
  700. // mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
  701. // given list of possible protocols and a list of the preference order. The
  702. // first list must not be empty. It returns the resulting protocol and flag
  703. // indicating if the fallback case was reached.
  704. func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
  705. for _, s := range preferenceProtos {
  706. for _, c := range protos {
  707. if s == c {
  708. return s, false
  709. }
  710. }
  711. }
  712. return protos[0], true
  713. }
  714. // hostnameInSNI converts name into an appropriate hostname for SNI.
  715. // Literal IP addresses and absolute FQDNs are not permitted as SNI values.
  716. // See https://tools.ietf.org/html/rfc6066#section-3.
  717. func hostnameInSNI(name string) string {
  718. host := name
  719. if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' {
  720. host = host[1 : len(host)-1]
  721. }
  722. if i := strings.LastIndex(host, "%"); i > 0 {
  723. host = host[:i]
  724. }
  725. if net.ParseIP(host) != nil {
  726. return ""
  727. }
  728. for len(name) > 0 && name[len(name)-1] == '.' {
  729. name = name[:len(name)-1]
  730. }
  731. return name
  732. }