handshake_client.go 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022
  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. "time"
  20. )
  21. type clientHandshakeState struct {
  22. c *Conn
  23. serverHello *serverHelloMsg
  24. hello *clientHelloMsg
  25. suite *cipherSuite
  26. finishedHash finishedHash
  27. masterSecret []byte
  28. session *ClientSessionState
  29. }
  30. func (c *Conn) makeClientHello() (*clientHelloMsg, ecdheParameters, error) {
  31. config := c.config
  32. if len(config.ServerName) == 0 && !config.InsecureSkipVerify {
  33. return nil, nil, errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config")
  34. }
  35. nextProtosLength := 0
  36. for _, proto := range config.NextProtos {
  37. if l := len(proto); l == 0 || l > 255 {
  38. return nil, nil, errors.New("tls: invalid NextProtos value")
  39. } else {
  40. nextProtosLength += 1 + l
  41. }
  42. }
  43. if nextProtosLength > 0xffff {
  44. return nil, nil, errors.New("tls: NextProtos values too large")
  45. }
  46. supportedVersions := config.supportedVersions(true)
  47. if len(supportedVersions) == 0 {
  48. return nil, nil, errors.New("tls: no supported versions satisfy MinVersion and MaxVersion")
  49. }
  50. clientHelloVersion := supportedVersions[0]
  51. // The version at the beginning of the ClientHello was capped at TLS 1.2
  52. // for compatibility reasons. The supported_versions extension is used
  53. // to negotiate versions now. See RFC 8446, Section 4.2.1.
  54. if clientHelloVersion > VersionTLS12 {
  55. clientHelloVersion = VersionTLS12
  56. }
  57. hello := &clientHelloMsg{
  58. vers: clientHelloVersion,
  59. compressionMethods: []uint8{compressionNone},
  60. random: make([]byte, 32),
  61. sessionId: make([]byte, 32),
  62. ocspStapling: true,
  63. scts: true,
  64. serverName: hostnameInSNI(config.ServerName),
  65. supportedCurves: config.curvePreferences(),
  66. supportedPoints: []uint8{pointFormatUncompressed},
  67. nextProtoNeg: len(config.NextProtos) > 0,
  68. secureRenegotiationSupported: true,
  69. alpnProtocols: config.NextProtos,
  70. supportedVersions: supportedVersions,
  71. }
  72. if c.handshakes > 0 {
  73. hello.secureRenegotiation = c.clientFinished[:]
  74. }
  75. possibleCipherSuites := config.cipherSuites()
  76. hello.cipherSuites = make([]uint16, 0, len(possibleCipherSuites))
  77. NextCipherSuite:
  78. for _, suiteId := range possibleCipherSuites {
  79. for _, suite := range cipherSuites {
  80. if suite.id != suiteId {
  81. continue
  82. }
  83. // Don't advertise TLS 1.2-only cipher suites unless
  84. // we're attempting TLS 1.2.
  85. if hello.vers < VersionTLS12 && suite.flags&suiteTLS12 != 0 {
  86. continue
  87. }
  88. hello.cipherSuites = append(hello.cipherSuites, suiteId)
  89. continue NextCipherSuite
  90. }
  91. }
  92. _, err := io.ReadFull(config.rand(), hello.random)
  93. if err != nil {
  94. return nil, nil, errors.New("tls: short read from Rand: " + err.Error())
  95. }
  96. // A random session ID is used to detect when the server accepted a ticket
  97. // and is resuming a session (see RFC 5077). In TLS 1.3, it's always set as
  98. // a compatibility measure (see RFC 8446, Section 4.1.2).
  99. if _, err := io.ReadFull(config.rand(), hello.sessionId); err != nil {
  100. return nil, nil, errors.New("tls: short read from Rand: " + err.Error())
  101. }
  102. if hello.vers >= VersionTLS12 {
  103. hello.supportedSignatureAlgorithms = supportedSignatureAlgorithms
  104. }
  105. var params ecdheParameters
  106. if hello.supportedVersions[0] == VersionTLS13 {
  107. hello.cipherSuites = append(hello.cipherSuites, defaultCipherSuitesTLS13()...)
  108. curveID := config.curvePreferences()[0]
  109. if _, ok := curveForCurveID(curveID); curveID != X25519 && !ok {
  110. return nil, nil, errors.New("tls: CurvePreferences includes unsupported curve")
  111. }
  112. params, err = generateECDHEParameters(config.rand(), curveID)
  113. if err != nil {
  114. return nil, nil, err
  115. }
  116. hello.keyShares = []keyShare{{group: curveID, data: params.PublicKey()}}
  117. }
  118. return hello, params, nil
  119. }
  120. func (c *Conn) clientHandshake() (err error) {
  121. if c.config == nil {
  122. c.config = defaultConfig()
  123. }
  124. // This may be a renegotiation handshake, in which case some fields
  125. // need to be reset.
  126. c.didResume = false
  127. hello, ecdheParams, err := c.makeClientHello()
  128. if err != nil {
  129. return err
  130. }
  131. cacheKey, session, earlySecret, binderKey := c.loadSession(hello)
  132. if cacheKey != "" && session != nil {
  133. defer func() {
  134. // If we got a handshake failure when resuming a session, throw away
  135. // the session ticket. See RFC 5077, Section 3.2.
  136. //
  137. // RFC 8446 makes no mention of dropping tickets on failure, but it
  138. // does require servers to abort on invalid binders, so we need to
  139. // delete tickets to recover from a corrupted PSK.
  140. if err != nil {
  141. c.config.ClientSessionCache.Put(cacheKey, nil)
  142. }
  143. }()
  144. }
  145. if _, err := c.writeRecord(recordTypeHandshake, hello.marshal()); err != nil {
  146. return err
  147. }
  148. msg, err := c.readHandshake()
  149. if err != nil {
  150. return err
  151. }
  152. serverHello, ok := msg.(*serverHelloMsg)
  153. if !ok {
  154. c.sendAlert(alertUnexpectedMessage)
  155. return unexpectedMessageError(serverHello, msg)
  156. }
  157. if err := c.pickTLSVersion(serverHello); err != nil {
  158. return err
  159. }
  160. if c.vers == VersionTLS13 {
  161. hs := &clientHandshakeStateTLS13{
  162. c: c,
  163. serverHello: serverHello,
  164. hello: hello,
  165. ecdheParams: ecdheParams,
  166. session: session,
  167. earlySecret: earlySecret,
  168. binderKey: binderKey,
  169. }
  170. // In TLS 1.3, session tickets are delivered after the handshake.
  171. return hs.handshake()
  172. }
  173. hs := &clientHandshakeState{
  174. c: c,
  175. serverHello: serverHello,
  176. hello: hello,
  177. session: session,
  178. }
  179. if err := hs.handshake(); err != nil {
  180. return err
  181. }
  182. // If we had a successful handshake and hs.session is different from
  183. // the one already cached - cache a new one.
  184. if cacheKey != "" && hs.session != nil && session != hs.session {
  185. c.config.ClientSessionCache.Put(cacheKey, hs.session)
  186. }
  187. return nil
  188. }
  189. func (c *Conn) loadSession(hello *clientHelloMsg) (cacheKey string,
  190. session *ClientSessionState, earlySecret, binderKey []byte) {
  191. if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil {
  192. return "", nil, nil, nil
  193. }
  194. hello.ticketSupported = true
  195. if hello.supportedVersions[0] == VersionTLS13 {
  196. // Require DHE on resumption as it guarantees forward secrecy against
  197. // compromise of the session ticket key. See RFC 8446, Section 4.2.9.
  198. hello.pskModes = []uint8{pskModeDHE}
  199. }
  200. // Session resumption is not allowed if renegotiating because
  201. // renegotiation is primarily used to allow a client to send a client
  202. // certificate, which would be skipped if session resumption occurred.
  203. if c.handshakes != 0 {
  204. return "", nil, nil, nil
  205. }
  206. // Try to resume a previously negotiated TLS session, if available.
  207. cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
  208. session, ok := c.config.ClientSessionCache.Get(cacheKey)
  209. if !ok || session == nil {
  210. return cacheKey, nil, nil, nil
  211. }
  212. // Check that version used for the previous session is still valid.
  213. versOk := false
  214. for _, v := range hello.supportedVersions {
  215. if v == session.vers {
  216. versOk = true
  217. break
  218. }
  219. }
  220. if !versOk {
  221. return cacheKey, nil, nil, nil
  222. }
  223. // Check that the cached server certificate is not expired, and that it's
  224. // valid for the ServerName. This should be ensured by the cache key, but
  225. // protect the application from a faulty ClientSessionCache implementation.
  226. if !c.config.InsecureSkipVerify {
  227. if len(session.verifiedChains) == 0 {
  228. // The original connection had InsecureSkipVerify, while this doesn't.
  229. return cacheKey, nil, nil, nil
  230. }
  231. serverCert := session.serverCertificates[0]
  232. if c.config.time().After(serverCert.NotAfter) {
  233. // Expired certificate, delete the entry.
  234. c.config.ClientSessionCache.Put(cacheKey, nil)
  235. return cacheKey, nil, nil, nil
  236. }
  237. if err := serverCert.VerifyHostname(c.config.ServerName); err != nil {
  238. return cacheKey, nil, nil, nil
  239. }
  240. }
  241. if session.vers != VersionTLS13 {
  242. // In TLS 1.2 the cipher suite must match the resumed session. Ensure we
  243. // are still offering it.
  244. if mutualCipherSuite(hello.cipherSuites, session.cipherSuite) == nil {
  245. return cacheKey, nil, nil, nil
  246. }
  247. hello.sessionTicket = session.sessionTicket
  248. return
  249. }
  250. // Check that the session ticket is not expired.
  251. if c.config.time().After(session.useBy) {
  252. c.config.ClientSessionCache.Put(cacheKey, nil)
  253. return cacheKey, nil, nil, nil
  254. }
  255. // In TLS 1.3 the KDF hash must match the resumed session. Ensure we
  256. // offer at least one cipher suite with that hash.
  257. cipherSuite := cipherSuiteTLS13ByID(session.cipherSuite)
  258. if cipherSuite == nil {
  259. return cacheKey, nil, nil, nil
  260. }
  261. cipherSuiteOk := false
  262. for _, offeredID := range hello.cipherSuites {
  263. offeredSuite := cipherSuiteTLS13ByID(offeredID)
  264. if offeredSuite != nil && offeredSuite.hash == cipherSuite.hash {
  265. cipherSuiteOk = true
  266. break
  267. }
  268. }
  269. if !cipherSuiteOk {
  270. return cacheKey, nil, nil, nil
  271. }
  272. // Set the pre_shared_key extension. See RFC 8446, Section 4.2.11.1.
  273. ticketAge := uint32(c.config.time().Sub(session.receivedAt) / time.Millisecond)
  274. identity := pskIdentity{
  275. label: session.sessionTicket,
  276. obfuscatedTicketAge: ticketAge + session.ageAdd,
  277. }
  278. hello.pskIdentities = []pskIdentity{identity}
  279. hello.pskBinders = [][]byte{make([]byte, cipherSuite.hash.Size())}
  280. // Compute the PSK binders. See RFC 8446, Section 4.2.11.2.
  281. psk := cipherSuite.expandLabel(session.masterSecret, "resumption",
  282. session.nonce, cipherSuite.hash.Size())
  283. earlySecret = cipherSuite.extract(psk, nil)
  284. binderKey = cipherSuite.deriveSecret(earlySecret, resumptionBinderLabel, nil)
  285. transcript := cipherSuite.hash.New()
  286. transcript.Write(hello.marshalWithoutBinders())
  287. pskBinders := [][]byte{cipherSuite.finishedHash(binderKey, transcript)}
  288. hello.updateBinders(pskBinders)
  289. return
  290. }
  291. func (c *Conn) pickTLSVersion(serverHello *serverHelloMsg) error {
  292. peerVersion := serverHello.vers
  293. if serverHello.supportedVersion != 0 {
  294. peerVersion = serverHello.supportedVersion
  295. }
  296. vers, ok := c.config.mutualVersion(true, []uint16{peerVersion})
  297. if !ok {
  298. c.sendAlert(alertProtocolVersion)
  299. return fmt.Errorf("tls: server selected unsupported protocol version %x", peerVersion)
  300. }
  301. c.vers = vers
  302. c.haveVers = true
  303. c.in.version = vers
  304. c.out.version = vers
  305. return nil
  306. }
  307. // Does the handshake, either a full one or resumes old session. Requires hs.c,
  308. // hs.hello, hs.serverHello, and, optionally, hs.session to be set.
  309. func (hs *clientHandshakeState) handshake() error {
  310. c := hs.c
  311. isResume, err := hs.processServerHello()
  312. if err != nil {
  313. return err
  314. }
  315. hs.finishedHash = newFinishedHash(c.vers, hs.suite)
  316. // No signatures of the handshake are needed in a resumption.
  317. // Otherwise, in a full handshake, if we don't have any certificates
  318. // configured then we will never send a CertificateVerify message and
  319. // thus no signatures are needed in that case either.
  320. if isResume || (len(c.config.Certificates) == 0 && c.config.GetClientCertificate == nil) {
  321. hs.finishedHash.discardHandshakeBuffer()
  322. }
  323. hs.finishedHash.Write(hs.hello.marshal())
  324. hs.finishedHash.Write(hs.serverHello.marshal())
  325. c.buffering = true
  326. if isResume {
  327. if err := hs.establishKeys(); err != nil {
  328. return err
  329. }
  330. if err := hs.readSessionTicket(); err != nil {
  331. return err
  332. }
  333. if err := hs.readFinished(c.serverFinished[:]); err != nil {
  334. return err
  335. }
  336. c.clientFinishedIsFirst = false
  337. if err := hs.sendFinished(c.clientFinished[:]); err != nil {
  338. return err
  339. }
  340. if _, err := c.flush(); err != nil {
  341. return err
  342. }
  343. } else {
  344. if err := hs.doFullHandshake(); err != nil {
  345. return err
  346. }
  347. if err := hs.establishKeys(); err != nil {
  348. return err
  349. }
  350. if err := hs.sendFinished(c.clientFinished[:]); err != nil {
  351. return err
  352. }
  353. if _, err := c.flush(); err != nil {
  354. return err
  355. }
  356. c.clientFinishedIsFirst = true
  357. if err := hs.readSessionTicket(); err != nil {
  358. return err
  359. }
  360. if err := hs.readFinished(c.serverFinished[:]); err != nil {
  361. return err
  362. }
  363. }
  364. c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random)
  365. c.didResume = isResume
  366. atomic.StoreUint32(&c.handshakeStatus, 1)
  367. return nil
  368. }
  369. func (hs *clientHandshakeState) pickCipherSuite() error {
  370. if hs.suite = mutualCipherSuite(hs.hello.cipherSuites, hs.serverHello.cipherSuite); hs.suite == nil {
  371. hs.c.sendAlert(alertHandshakeFailure)
  372. return errors.New("tls: server chose an unconfigured cipher suite")
  373. }
  374. hs.c.cipherSuite = hs.suite.id
  375. return nil
  376. }
  377. func (hs *clientHandshakeState) doFullHandshake() error {
  378. c := hs.c
  379. msg, err := c.readHandshake()
  380. if err != nil {
  381. return err
  382. }
  383. certMsg, ok := msg.(*certificateMsg)
  384. if !ok || len(certMsg.certificates) == 0 {
  385. c.sendAlert(alertUnexpectedMessage)
  386. return unexpectedMessageError(certMsg, msg)
  387. }
  388. hs.finishedHash.Write(certMsg.marshal())
  389. if c.handshakes == 0 {
  390. // If this is the first handshake on a connection, process and
  391. // (optionally) verify the server's certificates.
  392. if err := c.verifyServerCertificate(certMsg.certificates); err != nil {
  393. return err
  394. }
  395. } else {
  396. // This is a renegotiation handshake. We require that the
  397. // server's identity (i.e. leaf certificate) is unchanged and
  398. // thus any previous trust decision is still valid.
  399. //
  400. // See https://mitls.org/pages/attacks/3SHAKE for the
  401. // motivation behind this requirement.
  402. if !bytes.Equal(c.peerCertificates[0].Raw, certMsg.certificates[0]) {
  403. c.sendAlert(alertBadCertificate)
  404. return errors.New("tls: server's identity changed during renegotiation")
  405. }
  406. }
  407. msg, err = c.readHandshake()
  408. if err != nil {
  409. return err
  410. }
  411. cs, ok := msg.(*certificateStatusMsg)
  412. if ok {
  413. // RFC4366 on Certificate Status Request:
  414. // The server MAY return a "certificate_status" message.
  415. if !hs.serverHello.ocspStapling {
  416. // If a server returns a "CertificateStatus" message, then the
  417. // server MUST have included an extension of type "status_request"
  418. // with empty "extension_data" in the extended server hello.
  419. c.sendAlert(alertUnexpectedMessage)
  420. return errors.New("tls: received unexpected CertificateStatus message")
  421. }
  422. hs.finishedHash.Write(cs.marshal())
  423. c.ocspResponse = cs.response
  424. msg, err = c.readHandshake()
  425. if err != nil {
  426. return err
  427. }
  428. }
  429. keyAgreement := hs.suite.ka(c.vers)
  430. skx, ok := msg.(*serverKeyExchangeMsg)
  431. if ok {
  432. hs.finishedHash.Write(skx.marshal())
  433. err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, c.peerCertificates[0], skx)
  434. if err != nil {
  435. c.sendAlert(alertUnexpectedMessage)
  436. return err
  437. }
  438. msg, err = c.readHandshake()
  439. if err != nil {
  440. return err
  441. }
  442. }
  443. var chainToSend *Certificate
  444. var certRequested bool
  445. certReq, ok := msg.(*certificateRequestMsg)
  446. if ok {
  447. certRequested = true
  448. hs.finishedHash.Write(certReq.marshal())
  449. cri := certificateRequestInfoFromMsg(certReq)
  450. if chainToSend, err = c.getClientCertificate(cri); err != nil {
  451. c.sendAlert(alertInternalError)
  452. return err
  453. }
  454. msg, err = c.readHandshake()
  455. if err != nil {
  456. return err
  457. }
  458. }
  459. shd, ok := msg.(*serverHelloDoneMsg)
  460. if !ok {
  461. c.sendAlert(alertUnexpectedMessage)
  462. return unexpectedMessageError(shd, msg)
  463. }
  464. hs.finishedHash.Write(shd.marshal())
  465. // If the server requested a certificate then we have to send a
  466. // Certificate message, even if it's empty because we don't have a
  467. // certificate to send.
  468. if certRequested {
  469. certMsg = new(certificateMsg)
  470. certMsg.certificates = chainToSend.Certificate
  471. hs.finishedHash.Write(certMsg.marshal())
  472. if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
  473. return err
  474. }
  475. }
  476. preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, c.peerCertificates[0])
  477. if err != nil {
  478. c.sendAlert(alertInternalError)
  479. return err
  480. }
  481. if ckx != nil {
  482. hs.finishedHash.Write(ckx.marshal())
  483. if _, err := c.writeRecord(recordTypeHandshake, ckx.marshal()); err != nil {
  484. return err
  485. }
  486. }
  487. if chainToSend != nil && len(chainToSend.Certificate) > 0 {
  488. certVerify := &certificateVerifyMsg{
  489. hasSignatureAlgorithm: c.vers >= VersionTLS12,
  490. }
  491. key, ok := chainToSend.PrivateKey.(crypto.Signer)
  492. if !ok {
  493. c.sendAlert(alertInternalError)
  494. return fmt.Errorf("tls: client certificate private key of type %T does not implement crypto.Signer", chainToSend.PrivateKey)
  495. }
  496. signatureAlgorithm, sigType, hashFunc, err := pickSignatureAlgorithm(key.Public(), certReq.supportedSignatureAlgorithms, hs.hello.supportedSignatureAlgorithms, c.vers)
  497. if err != nil {
  498. c.sendAlert(alertInternalError)
  499. return err
  500. }
  501. // SignatureAndHashAlgorithm was introduced in TLS 1.2.
  502. if certVerify.hasSignatureAlgorithm {
  503. certVerify.signatureAlgorithm = signatureAlgorithm
  504. }
  505. digest, err := hs.finishedHash.hashForClientCertificate(sigType, hashFunc, hs.masterSecret)
  506. if err != nil {
  507. c.sendAlert(alertInternalError)
  508. return err
  509. }
  510. signOpts := crypto.SignerOpts(hashFunc)
  511. if sigType == signatureRSAPSS {
  512. signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: hashFunc}
  513. }
  514. certVerify.signature, err = key.Sign(c.config.rand(), digest, signOpts)
  515. if err != nil {
  516. c.sendAlert(alertInternalError)
  517. return err
  518. }
  519. hs.finishedHash.Write(certVerify.marshal())
  520. if _, err := c.writeRecord(recordTypeHandshake, certVerify.marshal()); err != nil {
  521. return err
  522. }
  523. }
  524. if hs.hello.ems && hs.serverHello.ems {
  525. hs.masterSecret = extendedMasterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.finishedHash)
  526. } else {
  527. hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random)
  528. }
  529. if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.hello.random, hs.masterSecret); err != nil {
  530. c.sendAlert(alertInternalError)
  531. return errors.New("tls: failed to write to key log: " + err.Error())
  532. }
  533. hs.finishedHash.discardHandshakeBuffer()
  534. return nil
  535. }
  536. func (hs *clientHandshakeState) establishKeys() error {
  537. c := hs.c
  538. clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
  539. keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
  540. var clientCipher, serverCipher interface{}
  541. var clientHash, serverHash macFunction
  542. if hs.suite.cipher != nil {
  543. clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */)
  544. clientHash = hs.suite.mac(c.vers, clientMAC)
  545. serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */)
  546. serverHash = hs.suite.mac(c.vers, serverMAC)
  547. } else {
  548. clientCipher = hs.suite.aead(clientKey, clientIV)
  549. serverCipher = hs.suite.aead(serverKey, serverIV)
  550. }
  551. c.in.prepareCipherSpec(c.vers, serverCipher, serverHash)
  552. c.out.prepareCipherSpec(c.vers, clientCipher, clientHash)
  553. return nil
  554. }
  555. func (hs *clientHandshakeState) serverResumedSession() bool {
  556. // If the server responded with the same sessionId then it means the
  557. // sessionTicket is being used to resume a TLS session.
  558. return hs.session != nil && hs.hello.sessionId != nil &&
  559. bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId)
  560. }
  561. func (hs *clientHandshakeState) processServerHello() (bool, error) {
  562. c := hs.c
  563. if err := hs.pickCipherSuite(); err != nil {
  564. return false, err
  565. }
  566. if hs.serverHello.compressionMethod != compressionNone {
  567. c.sendAlert(alertUnexpectedMessage)
  568. return false, errors.New("tls: server selected unsupported compression format")
  569. }
  570. if c.handshakes == 0 && hs.serverHello.secureRenegotiationSupported {
  571. c.secureRenegotiation = true
  572. if len(hs.serverHello.secureRenegotiation) != 0 {
  573. c.sendAlert(alertHandshakeFailure)
  574. return false, errors.New("tls: initial handshake had non-empty renegotiation extension")
  575. }
  576. }
  577. if c.handshakes > 0 && c.secureRenegotiation {
  578. var expectedSecureRenegotiation [24]byte
  579. copy(expectedSecureRenegotiation[:], c.clientFinished[:])
  580. copy(expectedSecureRenegotiation[12:], c.serverFinished[:])
  581. if !bytes.Equal(hs.serverHello.secureRenegotiation, expectedSecureRenegotiation[:]) {
  582. c.sendAlert(alertHandshakeFailure)
  583. return false, errors.New("tls: incorrect renegotiation extension contents")
  584. }
  585. }
  586. clientDidNPN := hs.hello.nextProtoNeg
  587. clientDidALPN := len(hs.hello.alpnProtocols) > 0
  588. serverHasNPN := hs.serverHello.nextProtoNeg
  589. serverHasALPN := len(hs.serverHello.alpnProtocol) > 0
  590. if !clientDidNPN && serverHasNPN {
  591. c.sendAlert(alertHandshakeFailure)
  592. return false, errors.New("tls: server advertised unrequested NPN extension")
  593. }
  594. if !clientDidALPN && serverHasALPN {
  595. c.sendAlert(alertHandshakeFailure)
  596. return false, errors.New("tls: server advertised unrequested ALPN extension")
  597. }
  598. if serverHasNPN && serverHasALPN {
  599. c.sendAlert(alertHandshakeFailure)
  600. return false, errors.New("tls: server advertised both NPN and ALPN extensions")
  601. }
  602. if serverHasALPN {
  603. c.clientProtocol = hs.serverHello.alpnProtocol
  604. c.clientProtocolFallback = false
  605. }
  606. c.scts = hs.serverHello.scts
  607. if !hs.serverResumedSession() {
  608. return false, nil
  609. }
  610. if hs.session.vers != c.vers {
  611. c.sendAlert(alertHandshakeFailure)
  612. return false, errors.New("tls: server resumed a session with a different version")
  613. }
  614. if hs.session.cipherSuite != hs.suite.id {
  615. c.sendAlert(alertHandshakeFailure)
  616. return false, errors.New("tls: server resumed a session with a different cipher suite")
  617. }
  618. // Restore masterSecret and peerCerts from previous state
  619. hs.masterSecret = hs.session.masterSecret
  620. c.peerCertificates = hs.session.serverCertificates
  621. c.verifiedChains = hs.session.verifiedChains
  622. return true, nil
  623. }
  624. func (hs *clientHandshakeState) readFinished(out []byte) error {
  625. c := hs.c
  626. if err := c.readChangeCipherSpec(); err != nil {
  627. return err
  628. }
  629. msg, err := c.readHandshake()
  630. if err != nil {
  631. return err
  632. }
  633. serverFinished, ok := msg.(*finishedMsg)
  634. if !ok {
  635. c.sendAlert(alertUnexpectedMessage)
  636. return unexpectedMessageError(serverFinished, msg)
  637. }
  638. verify := hs.finishedHash.serverSum(hs.masterSecret)
  639. if len(verify) != len(serverFinished.verifyData) ||
  640. subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
  641. c.sendAlert(alertHandshakeFailure)
  642. return errors.New("tls: server's Finished message was incorrect")
  643. }
  644. hs.finishedHash.Write(serverFinished.marshal())
  645. copy(out, verify)
  646. return nil
  647. }
  648. func (hs *clientHandshakeState) readSessionTicket() error {
  649. if !hs.serverHello.ticketSupported {
  650. return nil
  651. }
  652. c := hs.c
  653. msg, err := c.readHandshake()
  654. if err != nil {
  655. return err
  656. }
  657. sessionTicketMsg, ok := msg.(*newSessionTicketMsg)
  658. if !ok {
  659. c.sendAlert(alertUnexpectedMessage)
  660. return unexpectedMessageError(sessionTicketMsg, msg)
  661. }
  662. hs.finishedHash.Write(sessionTicketMsg.marshal())
  663. hs.session = &ClientSessionState{
  664. sessionTicket: sessionTicketMsg.ticket,
  665. vers: c.vers,
  666. cipherSuite: hs.suite.id,
  667. masterSecret: hs.masterSecret,
  668. serverCertificates: c.peerCertificates,
  669. verifiedChains: c.verifiedChains,
  670. receivedAt: c.config.time(),
  671. }
  672. return nil
  673. }
  674. func (hs *clientHandshakeState) sendFinished(out []byte) error {
  675. c := hs.c
  676. if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
  677. return err
  678. }
  679. if hs.serverHello.nextProtoNeg {
  680. nextProto := new(nextProtoMsg)
  681. proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.nextProtos)
  682. nextProto.proto = proto
  683. c.clientProtocol = proto
  684. c.clientProtocolFallback = fallback
  685. hs.finishedHash.Write(nextProto.marshal())
  686. if _, err := c.writeRecord(recordTypeHandshake, nextProto.marshal()); err != nil {
  687. return err
  688. }
  689. }
  690. finished := new(finishedMsg)
  691. finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret)
  692. hs.finishedHash.Write(finished.marshal())
  693. if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
  694. return err
  695. }
  696. copy(out, finished.verifyData)
  697. return nil
  698. }
  699. // verifyServerCertificate parses and verifies the provided chain, setting
  700. // c.verifiedChains and c.peerCertificates or sending the appropriate alert.
  701. func (c *Conn) verifyServerCertificate(certificates [][]byte) error {
  702. certs := make([]*x509.Certificate, len(certificates))
  703. for i, asn1Data := range certificates {
  704. cert, err := x509.ParseCertificate(asn1Data)
  705. if err != nil {
  706. c.sendAlert(alertBadCertificate)
  707. return errors.New("tls: failed to parse certificate from server: " + err.Error())
  708. }
  709. certs[i] = cert
  710. }
  711. if !c.config.InsecureSkipVerify {
  712. opts := x509.VerifyOptions{
  713. Roots: c.config.RootCAs,
  714. CurrentTime: c.config.time(),
  715. DNSName: c.config.ServerName,
  716. Intermediates: x509.NewCertPool(),
  717. }
  718. for i, cert := range certs {
  719. if i == 0 {
  720. continue
  721. }
  722. opts.Intermediates.AddCert(cert)
  723. }
  724. var err error
  725. c.verifiedChains, err = certs[0].Verify(opts)
  726. if err != nil {
  727. c.sendAlert(alertBadCertificate)
  728. return err
  729. }
  730. }
  731. if c.config.VerifyPeerCertificate != nil {
  732. if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
  733. c.sendAlert(alertBadCertificate)
  734. return err
  735. }
  736. }
  737. switch certs[0].PublicKey.(type) {
  738. case *rsa.PublicKey, *ecdsa.PublicKey:
  739. break
  740. default:
  741. c.sendAlert(alertUnsupportedCertificate)
  742. return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey)
  743. }
  744. c.peerCertificates = certs
  745. return nil
  746. }
  747. // tls11SignatureSchemes contains the signature schemes that we synthesise for
  748. // a TLS <= 1.1 connection, based on the supported certificate types.
  749. var (
  750. tls11SignatureSchemes = []SignatureScheme{ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512, PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1}
  751. tls11SignatureSchemesECDSA = tls11SignatureSchemes[:3]
  752. tls11SignatureSchemesRSA = tls11SignatureSchemes[3:]
  753. )
  754. // certificateRequestInfoFromMsg generates a CertificateRequestInfo from a TLS
  755. // <= 1.2 CertificateRequest, making an effort to fill in missing information.
  756. func certificateRequestInfoFromMsg(certReq *certificateRequestMsg) *CertificateRequestInfo {
  757. var rsaAvail, ecdsaAvail bool
  758. for _, certType := range certReq.certificateTypes {
  759. switch certType {
  760. case certTypeRSASign:
  761. rsaAvail = true
  762. case certTypeECDSASign:
  763. ecdsaAvail = true
  764. }
  765. }
  766. cri := &CertificateRequestInfo{
  767. AcceptableCAs: certReq.certificateAuthorities,
  768. }
  769. if !certReq.hasSignatureAlgorithm {
  770. // Prior to TLS 1.2, the signature schemes were not
  771. // included in the certificate request message. In this
  772. // case we use a plausible list based on the acceptable
  773. // certificate types.
  774. switch {
  775. case rsaAvail && ecdsaAvail:
  776. cri.SignatureSchemes = tls11SignatureSchemes
  777. case rsaAvail:
  778. cri.SignatureSchemes = tls11SignatureSchemesRSA
  779. case ecdsaAvail:
  780. cri.SignatureSchemes = tls11SignatureSchemesECDSA
  781. }
  782. return cri
  783. }
  784. // In TLS 1.2, the signature schemes apply to both the certificate chain and
  785. // the leaf key, while the certificate types only apply to the leaf key.
  786. // See RFC 5246, Section 7.4.4 (where it calls this "somewhat complicated").
  787. // Filter the signature schemes based on the certificate type.
  788. cri.SignatureSchemes = make([]SignatureScheme, 0, len(certReq.supportedSignatureAlgorithms))
  789. for _, sigScheme := range certReq.supportedSignatureAlgorithms {
  790. switch signatureFromSignatureScheme(sigScheme) {
  791. case signatureECDSA:
  792. if ecdsaAvail {
  793. cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme)
  794. }
  795. case signatureRSAPSS, signaturePKCS1v15:
  796. if rsaAvail {
  797. cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme)
  798. }
  799. }
  800. }
  801. return cri
  802. }
  803. func (c *Conn) getClientCertificate(cri *CertificateRequestInfo) (*Certificate, error) {
  804. if c.config.GetClientCertificate != nil {
  805. return c.config.GetClientCertificate(cri)
  806. }
  807. // We need to search our list of client certs for one
  808. // where SignatureAlgorithm is acceptable to the server and the
  809. // Issuer is in AcceptableCAs.
  810. for i, chain := range c.config.Certificates {
  811. sigOK := false
  812. for _, alg := range signatureSchemesForCertificate(&chain) {
  813. if isSupportedSignatureAlgorithm(alg, cri.SignatureSchemes) {
  814. sigOK = true
  815. break
  816. }
  817. }
  818. if !sigOK {
  819. continue
  820. }
  821. if len(cri.AcceptableCAs) == 0 {
  822. return &chain, nil
  823. }
  824. for j, cert := range chain.Certificate {
  825. x509Cert := chain.Leaf
  826. // Parse the certificate if this isn't the leaf node, or if
  827. // chain.Leaf was nil.
  828. if j != 0 || x509Cert == nil {
  829. var err error
  830. if x509Cert, err = x509.ParseCertificate(cert); err != nil {
  831. c.sendAlert(alertInternalError)
  832. return nil, errors.New("tls: failed to parse configured certificate chain #" + strconv.Itoa(i) + ": " + err.Error())
  833. }
  834. }
  835. for _, ca := range cri.AcceptableCAs {
  836. if bytes.Equal(x509Cert.RawIssuer, ca) {
  837. return &chain, nil
  838. }
  839. }
  840. }
  841. }
  842. // No acceptable certificate found. Don't send a certificate.
  843. return new(Certificate), nil
  844. }
  845. // clientSessionCacheKey returns a key used to cache sessionTickets that could
  846. // be used to resume previously negotiated TLS sessions with a server.
  847. func clientSessionCacheKey(serverAddr net.Addr, config *Config) string {
  848. if len(config.ServerName) > 0 {
  849. return config.ServerName
  850. }
  851. return serverAddr.String()
  852. }
  853. // mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol
  854. // given list of possible protocols and a list of the preference order. The
  855. // first list must not be empty. It returns the resulting protocol and flag
  856. // indicating if the fallback case was reached.
  857. func mutualProtocol(protos, preferenceProtos []string) (string, bool) {
  858. for _, s := range preferenceProtos {
  859. for _, c := range protos {
  860. if s == c {
  861. return s, false
  862. }
  863. }
  864. }
  865. return protos[0], true
  866. }
  867. // hostnameInSNI converts name into an approriate hostname for SNI.
  868. // Literal IP addresses and absolute FQDNs are not permitted as SNI values.
  869. // See RFC 6066, Section 3.
  870. func hostnameInSNI(name string) string {
  871. host := name
  872. if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' {
  873. host = host[1 : len(host)-1]
  874. }
  875. if i := strings.LastIndex(host, "%"); i > 0 {
  876. host = host[:i]
  877. }
  878. if net.ParseIP(host) != nil {
  879. return ""
  880. }
  881. for len(name) > 0 && name[len(name)-1] == '.' {
  882. name = name[:len(name)-1]
  883. }
  884. return name
  885. }