Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

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