Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 
 

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