handshake_client_tls13.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032
  1. // Copyright 2018 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. "context"
  8. "crypto"
  9. "crypto/hmac"
  10. "crypto/rsa"
  11. "crypto/subtle"
  12. "errors"
  13. "fmt"
  14. "hash"
  15. "sync/atomic"
  16. "time"
  17. circlKem "github.com/cloudflare/circl/kem"
  18. )
  19. type clientHandshakeStateTLS13 struct {
  20. c *Conn
  21. ctx context.Context
  22. serverHello *serverHelloMsg
  23. hello *clientHelloMsg
  24. helloInner *clientHelloMsg
  25. keySharePrivate clientKeySharePrivate
  26. session *ClientSessionState
  27. earlySecret []byte
  28. binderKey []byte
  29. selectedGroup CurveID
  30. certReq *certificateRequestMsgTLS13
  31. usingPSK bool
  32. sentDummyCCS bool
  33. suite *cipherSuiteTLS13
  34. transcript hash.Hash
  35. transcriptInner hash.Hash
  36. masterSecret []byte
  37. trafficSecret []byte // client_application_traffic_secret_0
  38. hsTimings CFEventTLS13ClientHandshakeTimingInfo
  39. }
  40. // processDelegatedCredentialFromServer unmarshals the DelegatedCredential
  41. // offered by the server (if present) and validates it using the peer's
  42. // certificate.
  43. func (hs *clientHandshakeStateTLS13) processDelegatedCredentialFromServer(rawDC []byte, certVerifyMsg *certificateVerifyMsg) error {
  44. c := hs.c
  45. var dc *DelegatedCredential
  46. var err error
  47. if rawDC != nil {
  48. // Assert that support for the DC extension was indicated by the client.
  49. if !hs.hello.delegatedCredentialSupported {
  50. c.sendAlert(alertUnexpectedMessage)
  51. return errors.New("tls: got Delegated Credential extension without indication")
  52. }
  53. dc, err = UnmarshalDelegatedCredential(rawDC)
  54. if err != nil {
  55. c.sendAlert(alertDecodeError)
  56. return fmt.Errorf("tls: Delegated Credential: %s", err)
  57. }
  58. if !isSupportedSignatureAlgorithm(dc.cred.expCertVerfAlgo, supportedSignatureAlgorithmsDC) {
  59. c.sendAlert(alertIllegalParameter)
  60. return errors.New("tls: Delegated Credential used with invalid signature algorithm")
  61. }
  62. if !isSupportedSignatureAlgorithm(dc.algorithm, c.config.supportedSignatureAlgorithms()) {
  63. c.sendAlert(alertIllegalParameter)
  64. return errors.New("tls: Delegated Credential signed with unsupported signature algorithm")
  65. }
  66. }
  67. if dc != nil {
  68. if !dc.Validate(c.peerCertificates[0], false, c.config.time(), certVerifyMsg) {
  69. c.sendAlert(alertIllegalParameter)
  70. return errors.New("tls: invalid Delegated Credential")
  71. }
  72. }
  73. c.verifiedDC = dc
  74. return nil
  75. }
  76. // handshake requires hs.c, hs.hello, hs.serverHello, hs.ecdheParams, and,
  77. // optionally, hs.session, hs.earlySecret and hs.binderKey to be set.
  78. func (hs *clientHandshakeStateTLS13) handshake() error {
  79. c := hs.c
  80. // The server must not select TLS 1.3 in a renegotiation. See RFC 8446,
  81. // sections 4.1.2 and 4.1.3.
  82. if c.handshakes > 0 {
  83. c.sendAlert(alertProtocolVersion)
  84. return errors.New("tls: server selected TLS 1.3 in a renegotiation")
  85. }
  86. // Consistency check on the presence of a keyShare and its parameters.
  87. if hs.keySharePrivate == nil || len(hs.hello.keyShares) != 1 {
  88. return c.sendAlert(alertInternalError)
  89. }
  90. if err := hs.checkServerHelloOrHRR(); err != nil {
  91. return err
  92. }
  93. hs.transcript = hs.suite.hash.New()
  94. hs.transcript.Write(hs.hello.marshal())
  95. // When offering ECH, we don't know whether ECH was accepted or rejected
  96. // until we get the server's response. Compute the transcript of both the
  97. // inner and outer handshake until we know.
  98. if c.ech.offered {
  99. hs.transcriptInner = hs.suite.hash.New()
  100. hs.transcriptInner.Write(hs.helloInner.marshal())
  101. }
  102. if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) {
  103. if err := hs.sendDummyChangeCipherSpec(); err != nil {
  104. return err
  105. }
  106. if err := hs.processHelloRetryRequest(); err != nil {
  107. return err
  108. }
  109. }
  110. // Check for ECH acceptance confirmation.
  111. if c.ech.offered {
  112. echAcceptConfTranscript := cloneHash(hs.transcriptInner, hs.suite.hash)
  113. if echAcceptConfTranscript == nil {
  114. c.sendAlert(alertInternalError)
  115. return errors.New("tls: internal error: failed to clone hash")
  116. }
  117. sh := hs.serverHello.marshal()
  118. echAcceptConfTranscript.Write(sh[:30])
  119. echAcceptConfTranscript.Write(zeros[:8])
  120. echAcceptConfTranscript.Write(sh[38:])
  121. echAcceptConf := hs.suite.expandLabel(
  122. hs.suite.extract(hs.helloInner.random, nil),
  123. echAcceptConfLabel,
  124. echAcceptConfTranscript.Sum(nil),
  125. 8)
  126. if subtle.ConstantTimeCompare(hs.serverHello.random[24:], echAcceptConf) == 1 {
  127. c.ech.accepted = true
  128. hs.hello = hs.helloInner
  129. hs.transcript = hs.transcriptInner
  130. }
  131. }
  132. hs.transcript.Write(hs.serverHello.marshal())
  133. // Resolve the server name now that ECH acceptance has been determined.
  134. //
  135. // NOTE(cjpatton): Currently the client sends the same ALPN extension in the
  136. // ClientHelloInner and ClientHelloOuter. If that changes, then we'll need
  137. // to resolve ALPN here as well.
  138. c.serverName = hs.hello.serverName
  139. c.buffering = true
  140. if err := hs.processServerHello(); err != nil {
  141. return err
  142. }
  143. if err := hs.sendDummyChangeCipherSpec(); err != nil {
  144. return err
  145. }
  146. if err := hs.establishHandshakeKeys(); err != nil {
  147. return err
  148. }
  149. if err := hs.readServerParameters(); err != nil {
  150. return err
  151. }
  152. if err := hs.readServerCertificate(); err != nil {
  153. return err
  154. }
  155. if err := hs.readServerFinished(); err != nil {
  156. return err
  157. }
  158. if err := hs.sendClientCertificate(); err != nil {
  159. return err
  160. }
  161. if err := hs.sendClientFinished(); err != nil {
  162. return err
  163. }
  164. if err := hs.abortIfRequired(); err != nil {
  165. return err
  166. }
  167. if _, err := c.flush(); err != nil {
  168. return err
  169. }
  170. c.handleCFEvent(hs.hsTimings)
  171. atomic.StoreUint32(&c.handshakeStatus, 1)
  172. return nil
  173. }
  174. // checkServerHelloOrHRR does validity checks that apply to both ServerHello and
  175. // HelloRetryRequest messages. It sets hs.suite.
  176. func (hs *clientHandshakeStateTLS13) checkServerHelloOrHRR() error {
  177. c := hs.c
  178. if hs.serverHello.supportedVersion == 0 {
  179. c.sendAlert(alertMissingExtension)
  180. return errors.New("tls: server selected TLS 1.3 using the legacy version field")
  181. }
  182. if hs.serverHello.supportedVersion != VersionTLS13 {
  183. c.sendAlert(alertIllegalParameter)
  184. return errors.New("tls: server selected an invalid version after a HelloRetryRequest")
  185. }
  186. if hs.serverHello.vers != VersionTLS12 {
  187. c.sendAlert(alertIllegalParameter)
  188. return errors.New("tls: server sent an incorrect legacy version")
  189. }
  190. if hs.serverHello.ocspStapling ||
  191. hs.serverHello.ticketSupported ||
  192. hs.serverHello.secureRenegotiationSupported ||
  193. len(hs.serverHello.secureRenegotiation) != 0 ||
  194. len(hs.serverHello.alpnProtocol) != 0 ||
  195. len(hs.serverHello.scts) != 0 {
  196. c.sendAlert(alertUnsupportedExtension)
  197. return errors.New("tls: server sent a ServerHello extension forbidden in TLS 1.3")
  198. }
  199. if !bytes.Equal(hs.hello.sessionId, hs.serverHello.sessionId) {
  200. c.sendAlert(alertIllegalParameter)
  201. return errors.New("tls: server did not echo the legacy session ID")
  202. }
  203. if hs.serverHello.compressionMethod != compressionNone {
  204. c.sendAlert(alertIllegalParameter)
  205. return errors.New("tls: server selected unsupported compression format")
  206. }
  207. selectedSuite := mutualCipherSuiteTLS13(hs.hello.cipherSuites, hs.serverHello.cipherSuite)
  208. if hs.suite != nil && selectedSuite != hs.suite {
  209. c.sendAlert(alertIllegalParameter)
  210. return errors.New("tls: server changed cipher suite after a HelloRetryRequest")
  211. }
  212. if selectedSuite == nil {
  213. c.sendAlert(alertIllegalParameter)
  214. return errors.New("tls: server chose an unconfigured cipher suite")
  215. }
  216. hs.suite = selectedSuite
  217. c.cipherSuite = hs.suite.id
  218. return nil
  219. }
  220. // sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility
  221. // with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4.
  222. func (hs *clientHandshakeStateTLS13) sendDummyChangeCipherSpec() error {
  223. if hs.sentDummyCCS {
  224. return nil
  225. }
  226. hs.sentDummyCCS = true
  227. _, err := hs.c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
  228. return err
  229. }
  230. // processHelloRetryRequest handles the HRR in hs.serverHello, modifies and
  231. // resends hs.hello, and reads the new ServerHello into hs.serverHello.
  232. func (hs *clientHandshakeStateTLS13) processHelloRetryRequest() error {
  233. c := hs.c
  234. c.handleCFEvent(CFEventTLS13HRR{})
  235. // The first ClientHello gets double-hashed into the transcript upon a
  236. // HelloRetryRequest. (The idea is that the server might offload transcript
  237. // storage to the client in the cookie.) See RFC 8446, Section 4.4.1.
  238. chHash := hs.transcript.Sum(nil)
  239. hs.transcript.Reset()
  240. hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
  241. hs.transcript.Write(chHash)
  242. hs.transcript.Write(hs.serverHello.marshal())
  243. // Determine which ClientHello message was consumed by the server. If ECH
  244. // was offered, this may be the ClientHelloInner or ClientHelloOuter.
  245. hello := hs.hello
  246. isInner := false
  247. if c.ech.offered {
  248. chHash = hs.transcriptInner.Sum(nil)
  249. hs.transcriptInner.Reset()
  250. hs.transcriptInner.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
  251. hs.transcriptInner.Write(chHash)
  252. // Check for ECH acceptance confirmation.
  253. if hs.serverHello.ech != nil {
  254. if len(hs.serverHello.ech) != 8 {
  255. c.sendAlert(alertDecodeError)
  256. return errors.New("tls: ech: hrr: malformed acceptance signal")
  257. }
  258. echAcceptConfHRRTranscript := cloneHash(hs.transcriptInner, hs.suite.hash)
  259. if echAcceptConfHRRTranscript == nil {
  260. c.sendAlert(alertInternalError)
  261. return errors.New("tls: internal error: failed to clone hash")
  262. }
  263. echAcceptConfHRR := echEncodeAcceptConfHelloRetryRequest(hs.serverHello.marshal())
  264. echAcceptConfHRRTranscript.Write(echAcceptConfHRR)
  265. echAcceptConfHRRSignal := hs.suite.expandLabel(
  266. hs.suite.extract(hs.helloInner.random, nil),
  267. echAcceptConfHRRLabel,
  268. echAcceptConfHRRTranscript.Sum(nil),
  269. 8)
  270. if subtle.ConstantTimeCompare(hs.serverHello.ech, echAcceptConfHRRSignal) == 1 {
  271. hello = hs.helloInner
  272. isInner = true
  273. }
  274. }
  275. hs.transcriptInner.Write(hs.serverHello.marshal())
  276. }
  277. // The only HelloRetryRequest extensions we support are key_share and
  278. // cookie, and clients must abort the handshake if the HRR would not result
  279. // in any change in the ClientHello.
  280. if hs.serverHello.selectedGroup == 0 && hs.serverHello.cookie == nil {
  281. c.sendAlert(alertIllegalParameter)
  282. return errors.New("tls: server sent an unnecessary HelloRetryRequest message")
  283. }
  284. if hs.serverHello.cookie != nil {
  285. hello.cookie = hs.serverHello.cookie
  286. }
  287. if hs.serverHello.serverShare.group != 0 {
  288. c.sendAlert(alertDecodeError)
  289. return errors.New("tls: received malformed key_share extension")
  290. }
  291. // If the server sent a key_share extension selecting a group, ensure it's
  292. // a group we advertised but did not send a key share for, and send a key
  293. // share for it this time.
  294. if curveID := hs.serverHello.selectedGroup; curveID != 0 {
  295. curveOK := false
  296. for _, id := range hello.supportedCurves {
  297. if id == curveID {
  298. curveOK = true
  299. break
  300. }
  301. }
  302. if !curveOK {
  303. c.sendAlert(alertIllegalParameter)
  304. return errors.New("tls: server selected unsupported group")
  305. }
  306. if clientKeySharePrivateCurveID(hs.keySharePrivate) == curveID {
  307. c.sendAlert(alertIllegalParameter)
  308. return errors.New("tls: server sent an unnecessary HelloRetryRequest key_share")
  309. }
  310. if scheme := curveIdToCirclScheme(curveID); scheme != nil {
  311. pk, sk, err := generateKemKeyPair(scheme, c.config.rand())
  312. if err != nil {
  313. c.sendAlert(alertInternalError)
  314. return fmt.Errorf("HRR generateKemKeyPair %s: %w",
  315. scheme.Name(), err)
  316. }
  317. packedPk, err := pk.MarshalBinary()
  318. if err != nil {
  319. c.sendAlert(alertInternalError)
  320. return fmt.Errorf("HRR pack circl public key %s: %w",
  321. scheme.Name(), err)
  322. }
  323. hs.keySharePrivate = sk
  324. hello.keyShares = []keyShare{{group: curveID, data: packedPk}}
  325. } else {
  326. if _, ok := curveForCurveID(curveID); curveID != X25519 && !ok {
  327. c.sendAlert(alertInternalError)
  328. return errors.New("tls: CurvePreferences includes unsupported curve")
  329. }
  330. params, err := generateECDHEParameters(c.config.rand(), curveID)
  331. if err != nil {
  332. c.sendAlert(alertInternalError)
  333. return err
  334. }
  335. hs.keySharePrivate = params
  336. hello.keyShares = []keyShare{{group: curveID, data: params.PublicKey()}}
  337. }
  338. }
  339. hello.raw = nil
  340. if len(hello.pskIdentities) > 0 {
  341. pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite)
  342. if pskSuite == nil {
  343. return c.sendAlert(alertInternalError)
  344. }
  345. if pskSuite.hash == hs.suite.hash {
  346. // Update binders and obfuscated_ticket_age.
  347. ticketAge := uint32(c.config.time().Sub(hs.session.receivedAt) / time.Millisecond)
  348. hello.pskIdentities[0].obfuscatedTicketAge = ticketAge + hs.session.ageAdd
  349. transcript := hs.suite.hash.New()
  350. transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))})
  351. transcript.Write(chHash)
  352. transcript.Write(hs.serverHello.marshal())
  353. transcript.Write(hello.marshalWithoutBinders())
  354. pskBinders := [][]byte{hs.suite.finishedHash(hs.binderKey, transcript)}
  355. hello.updateBinders(pskBinders)
  356. } else {
  357. // Server selected a cipher suite incompatible with the PSK.
  358. hello.pskIdentities = nil
  359. hello.pskBinders = nil
  360. }
  361. }
  362. if isInner {
  363. hs.helloInner = hello
  364. hs.transcriptInner.Write(hs.helloInner.marshal())
  365. if err := c.echUpdateClientHelloOuter(hs.hello, hs.helloInner, nil); err != nil {
  366. return err
  367. }
  368. } else {
  369. hs.hello = hello
  370. }
  371. if c.ech.offered && testingECHIllegalHandleAfterHRR {
  372. hs.hello.raw = nil
  373. // Change the cipher suite and config id and set an encapsulated key in
  374. // the updated ClientHello. This will trigger a server abort because the
  375. // cipher suite and config id are supposed to match the previous
  376. // ClientHello and the encapsulated key is supposed to be empty.
  377. var ech echClientOuter
  378. _, kdf, aead := c.ech.sealer.Suite().Params()
  379. ech.handle.suite.kdfId = uint16(kdf) ^ 0xff
  380. ech.handle.suite.aeadId = uint16(aead) ^ 0xff
  381. ech.handle.configId = c.ech.configId ^ 0xff
  382. ech.handle.enc = []byte{1, 2, 3, 4, 5}
  383. ech.payload = []byte{1, 2, 3, 4, 5}
  384. hs.hello.ech = ech.marshal()
  385. }
  386. if testingECHTriggerBypassAfterHRR {
  387. hs.hello.raw = nil
  388. // Don't send the ECH extension in the updated ClientHello. This will
  389. // trigger a server abort, since this is illegal.
  390. hs.hello.ech = nil
  391. }
  392. if testingECHTriggerBypassBeforeHRR {
  393. hs.hello.raw = nil
  394. // Send a dummy ECH extension in the updated ClientHello. This will
  395. // trigger a server abort, since no ECH extension was sent in the
  396. // previous ClientHello.
  397. var err error
  398. hs.hello.ech, err = echGenerateGreaseExt(c.config.rand())
  399. if err != nil {
  400. return fmt.Errorf("tls: ech: failed to generate grease ECH: %s", err)
  401. }
  402. }
  403. if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
  404. return err
  405. }
  406. msg, err := c.readHandshake()
  407. if err != nil {
  408. return err
  409. }
  410. serverHello, ok := msg.(*serverHelloMsg)
  411. if !ok {
  412. c.sendAlert(alertUnexpectedMessage)
  413. return unexpectedMessageError(serverHello, msg)
  414. }
  415. hs.serverHello = serverHello
  416. if err := hs.checkServerHelloOrHRR(); err != nil {
  417. return err
  418. }
  419. hs.transcript.Write(hs.hello.marshal())
  420. return nil
  421. }
  422. func (hs *clientHandshakeStateTLS13) processServerHello() error {
  423. c := hs.c
  424. defer func() {
  425. hs.hsTimings.ProcessServerHello = hs.hsTimings.elapsedTime()
  426. }()
  427. if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) {
  428. c.sendAlert(alertUnexpectedMessage)
  429. return errors.New("tls: server sent two HelloRetryRequest messages")
  430. }
  431. if len(hs.serverHello.cookie) != 0 {
  432. c.sendAlert(alertUnsupportedExtension)
  433. return errors.New("tls: server sent a cookie in a normal ServerHello")
  434. }
  435. if hs.serverHello.selectedGroup != 0 {
  436. c.sendAlert(alertDecodeError)
  437. return errors.New("tls: malformed key_share extension")
  438. }
  439. if hs.serverHello.serverShare.group == 0 {
  440. c.sendAlert(alertIllegalParameter)
  441. return errors.New("tls: server did not send a key share")
  442. }
  443. if hs.serverHello.serverShare.group != clientKeySharePrivateCurveID(hs.keySharePrivate) {
  444. c.sendAlert(alertIllegalParameter)
  445. return errors.New("tls: server selected unsupported group")
  446. }
  447. c.handleCFEvent(CFEventTLSNegotiatedNamedKEX{
  448. KEX: hs.serverHello.serverShare.group,
  449. })
  450. if !hs.serverHello.selectedIdentityPresent {
  451. return nil
  452. }
  453. // Per the rules of draft-ietf-tls-esni-13, Section 6.1, the server is not
  454. // permitted to resume a connection connection in the outer handshake. If
  455. // ECH is rejected and the client-facing server replies with a
  456. // "pre_shared_key" extension in its ServerHello, then the client MUST abort
  457. // the handshake with an "illegal_parameter" alert.
  458. if c.ech.offered && !c.ech.accepted {
  459. c.sendAlert(alertIllegalParameter)
  460. return errors.New("tls: ech: client-facing server offered PSK after ECH rejection")
  461. }
  462. if int(hs.serverHello.selectedIdentity) >= len(hs.hello.pskIdentities) {
  463. c.sendAlert(alertIllegalParameter)
  464. return errors.New("tls: server selected an invalid PSK")
  465. }
  466. if len(hs.hello.pskIdentities) != 1 || hs.session == nil {
  467. return c.sendAlert(alertInternalError)
  468. }
  469. pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite)
  470. if pskSuite == nil {
  471. return c.sendAlert(alertInternalError)
  472. }
  473. if pskSuite.hash != hs.suite.hash {
  474. c.sendAlert(alertIllegalParameter)
  475. return errors.New("tls: server selected an invalid PSK and cipher suite pair")
  476. }
  477. hs.usingPSK = true
  478. c.didResume = true
  479. c.peerCertificates = hs.session.serverCertificates
  480. c.verifiedChains = hs.session.verifiedChains
  481. c.ocspResponse = hs.session.ocspResponse
  482. c.scts = hs.session.scts
  483. return nil
  484. }
  485. func (hs *clientHandshakeStateTLS13) establishHandshakeKeys() error {
  486. c := hs.c
  487. var sharedKey []byte
  488. if params, ok := hs.keySharePrivate.(ecdheParameters); ok {
  489. sharedKey = params.SharedKey(hs.serverHello.serverShare.data)
  490. } else if sk, ok := hs.keySharePrivate.(circlKem.PrivateKey); ok {
  491. var err error
  492. sharedKey, err = sk.Scheme().Decapsulate(sk, hs.serverHello.serverShare.data)
  493. if err != nil {
  494. c.sendAlert(alertIllegalParameter)
  495. return fmt.Errorf("%s decaps: %w", sk.Scheme().Name(), err)
  496. }
  497. }
  498. if sharedKey == nil {
  499. c.sendAlert(alertIllegalParameter)
  500. return fmt.Errorf("tls: invalid server key share")
  501. }
  502. earlySecret := hs.earlySecret
  503. if !hs.usingPSK {
  504. earlySecret = hs.suite.extract(nil, nil)
  505. }
  506. handshakeSecret := hs.suite.extract(sharedKey,
  507. hs.suite.deriveSecret(earlySecret, "derived", nil))
  508. clientSecret := hs.suite.deriveSecret(handshakeSecret,
  509. clientHandshakeTrafficLabel, hs.transcript)
  510. c.out.setTrafficSecret(hs.suite, clientSecret)
  511. serverSecret := hs.suite.deriveSecret(handshakeSecret,
  512. serverHandshakeTrafficLabel, hs.transcript)
  513. c.in.setTrafficSecret(hs.suite, serverSecret)
  514. err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.hello.random, clientSecret)
  515. if err != nil {
  516. c.sendAlert(alertInternalError)
  517. return err
  518. }
  519. err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.hello.random, serverSecret)
  520. if err != nil {
  521. c.sendAlert(alertInternalError)
  522. return err
  523. }
  524. hs.masterSecret = hs.suite.extract(nil,
  525. hs.suite.deriveSecret(handshakeSecret, "derived", nil))
  526. return nil
  527. }
  528. func (hs *clientHandshakeStateTLS13) readServerParameters() error {
  529. c := hs.c
  530. msg, err := c.readHandshake()
  531. if err != nil {
  532. return err
  533. }
  534. encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
  535. if !ok {
  536. c.sendAlert(alertUnexpectedMessage)
  537. return unexpectedMessageError(encryptedExtensions, msg)
  538. }
  539. hs.transcript.Write(encryptedExtensions.marshal())
  540. if err := checkALPN(hs.hello.alpnProtocols, encryptedExtensions.alpnProtocol); err != nil {
  541. c.sendAlert(alertUnsupportedExtension)
  542. return err
  543. }
  544. c.clientProtocol = encryptedExtensions.alpnProtocol
  545. if c.ech.offered && len(encryptedExtensions.ech) > 0 {
  546. if !c.ech.accepted {
  547. // If the server rejects ECH, then it may send retry configurations.
  548. // If present, we must check them for syntactic correctness and
  549. // abort if they are not correct.
  550. c.ech.retryConfigs = encryptedExtensions.ech
  551. if _, err = UnmarshalECHConfigs(c.ech.retryConfigs); err != nil {
  552. c.sendAlert(alertDecodeError)
  553. return fmt.Errorf("tls: ech: failed to parse retry configs: %s", err)
  554. }
  555. } else {
  556. // Retry configs must not be sent in the inner handshake.
  557. c.sendAlert(alertUnsupportedExtension)
  558. return errors.New("tls: ech: got retry configs after ECH acceptance")
  559. }
  560. }
  561. hs.hsTimings.ReadEncryptedExtensions = hs.hsTimings.elapsedTime()
  562. return nil
  563. }
  564. func (hs *clientHandshakeStateTLS13) readServerCertificate() error {
  565. c := hs.c
  566. // Either a PSK or a certificate is always used, but not both.
  567. // See RFC 8446, Section 4.1.1.
  568. if hs.usingPSK {
  569. // Make sure the connection is still being verified whether or not this
  570. // is a resumption. Resumptions currently don't reverify certificates so
  571. // they don't call verifyServerCertificate. See Issue 31641.
  572. if c.config.VerifyConnection != nil {
  573. if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil {
  574. c.sendAlert(alertBadCertificate)
  575. return err
  576. }
  577. }
  578. return nil
  579. }
  580. msg, err := c.readHandshake()
  581. if err != nil {
  582. return err
  583. }
  584. certReq, ok := msg.(*certificateRequestMsgTLS13)
  585. if ok {
  586. hs.transcript.Write(certReq.marshal())
  587. hs.certReq = certReq
  588. msg, err = c.readHandshake()
  589. if err != nil {
  590. return err
  591. }
  592. }
  593. certMsg, ok := msg.(*certificateMsgTLS13)
  594. if !ok {
  595. c.sendAlert(alertUnexpectedMessage)
  596. return unexpectedMessageError(certMsg, msg)
  597. }
  598. if len(certMsg.certificate.Certificate) == 0 {
  599. c.sendAlert(alertDecodeError)
  600. return errors.New("tls: received empty certificates message")
  601. }
  602. hs.transcript.Write(certMsg.marshal())
  603. hs.hsTimings.ReadCertificate = hs.hsTimings.elapsedTime()
  604. c.scts = certMsg.certificate.SignedCertificateTimestamps
  605. c.ocspResponse = certMsg.certificate.OCSPStaple
  606. if err := c.verifyServerCertificate(certMsg.certificate.Certificate); err != nil {
  607. return err
  608. }
  609. msg, err = c.readHandshake()
  610. if err != nil {
  611. return err
  612. }
  613. certVerify, ok := msg.(*certificateVerifyMsg)
  614. if !ok {
  615. c.sendAlert(alertUnexpectedMessage)
  616. return unexpectedMessageError(certVerify, msg)
  617. }
  618. // See RFC 8446, Section 4.4.3.
  619. if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, c.config.supportedSignatureAlgorithms()) {
  620. c.sendAlert(alertIllegalParameter)
  621. return errors.New("tls: certificate used with invalid signature algorithm")
  622. }
  623. sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm)
  624. if err != nil {
  625. return c.sendAlert(alertInternalError)
  626. }
  627. if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 {
  628. c.sendAlert(alertIllegalParameter)
  629. return errors.New("tls: certificate used with invalid signature algorithm")
  630. }
  631. if certMsg.delegatedCredential {
  632. if err := hs.processDelegatedCredentialFromServer(certMsg.certificate.DelegatedCredential, certVerify); err != nil {
  633. return err // alert sent
  634. }
  635. }
  636. pk := c.peerCertificates[0].PublicKey
  637. if c.verifiedDC != nil {
  638. pk = c.verifiedDC.cred.publicKey
  639. }
  640. signed := signedMessage(sigHash, serverSignatureContext, hs.transcript)
  641. if err := verifyHandshakeSignature(sigType, pk,
  642. sigHash, signed, certVerify.signature); err != nil {
  643. c.sendAlert(alertDecryptError)
  644. return errors.New("tls: invalid signature by the server certificate: " + err.Error())
  645. }
  646. hs.transcript.Write(certVerify.marshal())
  647. hs.hsTimings.ReadCertificateVerify = hs.hsTimings.elapsedTime()
  648. return nil
  649. }
  650. func (hs *clientHandshakeStateTLS13) readServerFinished() error {
  651. c := hs.c
  652. msg, err := c.readHandshake()
  653. if err != nil {
  654. return err
  655. }
  656. finished, ok := msg.(*finishedMsg)
  657. if !ok {
  658. c.sendAlert(alertUnexpectedMessage)
  659. return unexpectedMessageError(finished, msg)
  660. }
  661. hs.hsTimings.ReadServerFinished = hs.hsTimings.elapsedTime()
  662. expectedMAC := hs.suite.finishedHash(c.in.trafficSecret, hs.transcript)
  663. if !hmac.Equal(expectedMAC, finished.verifyData) {
  664. c.sendAlert(alertDecryptError)
  665. return errors.New("tls: invalid server finished hash")
  666. }
  667. hs.transcript.Write(finished.marshal())
  668. // Derive secrets that take context through the server Finished.
  669. hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret,
  670. clientApplicationTrafficLabel, hs.transcript)
  671. serverSecret := hs.suite.deriveSecret(hs.masterSecret,
  672. serverApplicationTrafficLabel, hs.transcript)
  673. c.in.setTrafficSecret(hs.suite, serverSecret)
  674. err = c.config.writeKeyLog(keyLogLabelClientTraffic, hs.hello.random, hs.trafficSecret)
  675. if err != nil {
  676. c.sendAlert(alertInternalError)
  677. return err
  678. }
  679. err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.hello.random, serverSecret)
  680. if err != nil {
  681. c.sendAlert(alertInternalError)
  682. return err
  683. }
  684. c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript)
  685. return nil
  686. }
  687. func certificateRequestInfo(certReq *certificateRequestMsgTLS13, vers uint16, ctx context.Context) *CertificateRequestInfo {
  688. cri := &CertificateRequestInfo{
  689. SupportsDelegatedCredential: certReq.supportDelegatedCredential,
  690. SignatureSchemes: certReq.supportedSignatureAlgorithms,
  691. SignatureSchemesDC: certReq.supportedSignatureAlgorithmsDC,
  692. AcceptableCAs: certReq.certificateAuthorities,
  693. Version: vers,
  694. ctx: ctx,
  695. }
  696. return cri
  697. }
  698. // getClientDelegatedCredential will return a Delegated Credential pair (a
  699. // Delegated Credential and its private key) for the given CertificateRequestInfo,
  700. // defaulting to the first element of cert.DelegatedCredentialPair.
  701. // The returned Delegated Credential could be invalid for usage in the handshake.
  702. // Returns an error if there are no delegated credentials or if the one found
  703. // cannot be used for the current connection.
  704. func getClientDelegatedCredential(cri *CertificateRequestInfo, cert *Certificate) (*DelegatedCredentialPair, error) {
  705. if len(cert.DelegatedCredentials) == 0 {
  706. return nil, errors.New("no Delegated Credential found")
  707. }
  708. for _, dcPair := range cert.DelegatedCredentials {
  709. // If the client sent the signature_algorithms in the DC extension, ensure it supports
  710. // schemes we can use with this delegated credential.
  711. if len(cri.SignatureSchemesDC) > 0 {
  712. if _, err := selectSignatureSchemeDC(VersionTLS13, dcPair.DC, cri.SignatureSchemes, cri.SignatureSchemesDC); err == nil {
  713. return &dcPair, nil
  714. }
  715. }
  716. }
  717. // No delegated credential can be returned.
  718. return nil, errors.New("no valid Delegated Credential found")
  719. }
  720. func (hs *clientHandshakeStateTLS13) sendClientCertificate() error {
  721. c := hs.c
  722. if hs.certReq == nil {
  723. return nil
  724. }
  725. cri := certificateRequestInfo(hs.certReq, c.vers, hs.ctx)
  726. cert, err := c.getClientCertificate(cri)
  727. if err != nil {
  728. return err
  729. }
  730. var dcPair *DelegatedCredentialPair
  731. if hs.certReq.supportDelegatedCredential && len(hs.certReq.supportedSignatureAlgorithmsDC) > 0 {
  732. // getClientDelegatedCredential selects a delegated credential that the server has advertised support for, if possible.
  733. if delegatedCredentialPair, err := getClientDelegatedCredential(cri, cert); err == nil {
  734. if delegatedCredentialPair.DC != nil && delegatedCredentialPair.PrivateKey != nil {
  735. var err error
  736. // Even if the Delegated Credential has already been marshalled, be sure it is the correct one.
  737. if delegatedCredentialPair.DC.raw, err = delegatedCredentialPair.DC.Marshal(); err == nil {
  738. dcPair = delegatedCredentialPair
  739. cert.DelegatedCredential = dcPair.DC.raw
  740. }
  741. }
  742. }
  743. }
  744. certMsg := new(certificateMsgTLS13)
  745. certMsg.certificate = *cert
  746. certMsg.scts = hs.certReq.scts && len(cert.SignedCertificateTimestamps) > 0
  747. certMsg.ocspStapling = hs.certReq.ocspStapling && len(cert.OCSPStaple) > 0
  748. certMsg.delegatedCredential = hs.certReq.supportDelegatedCredential && len(cert.DelegatedCredential) > 0
  749. hs.transcript.Write(certMsg.marshal())
  750. if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
  751. return err
  752. }
  753. hs.hsTimings.WriteCertificate = hs.hsTimings.elapsedTime()
  754. // If we sent an empty certificate message, skip the CertificateVerify.
  755. if len(cert.Certificate) == 0 {
  756. return nil
  757. }
  758. certVerifyMsg := new(certificateVerifyMsg)
  759. certVerifyMsg.hasSignatureAlgorithm = true
  760. var sigAlgorithm SignatureScheme
  761. suppSigAlgo := hs.certReq.supportedSignatureAlgorithms
  762. sigAlgorithm, err = selectSignatureScheme(c.vers, cert, suppSigAlgo)
  763. if err != nil {
  764. // getClientCertificate returned a certificate incompatible with the
  765. // CertificateRequestInfo supported signature algorithms.
  766. c.sendAlert(alertHandshakeFailure)
  767. return err
  768. }
  769. if certMsg.delegatedCredential {
  770. suppSigAlgo = hs.certReq.supportedSignatureAlgorithmsDC
  771. if dcPair == nil || dcPair.DC == nil {
  772. cert.DelegatedCredential = nil
  773. } else {
  774. sigAlgorithm = dcPair.DC.cred.expCertVerfAlgo
  775. cert.PrivateKey = dcPair.PrivateKey
  776. }
  777. }
  778. certVerifyMsg.signatureAlgorithm = sigAlgorithm
  779. sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerifyMsg.signatureAlgorithm)
  780. if err != nil {
  781. return c.sendAlert(alertInternalError)
  782. }
  783. signed := signedMessage(sigHash, clientSignatureContext, hs.transcript)
  784. signOpts := crypto.SignerOpts(sigHash)
  785. if sigType == signatureRSAPSS {
  786. signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
  787. }
  788. sig, err := cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts)
  789. if err != nil {
  790. c.sendAlert(alertInternalError)
  791. return errors.New("tls: failed to sign handshake: " + err.Error())
  792. }
  793. certVerifyMsg.signature = sig
  794. hs.transcript.Write(certVerifyMsg.marshal())
  795. if _, err := c.writeRecord(recordTypeHandshake, certVerifyMsg.marshal()); err != nil {
  796. return err
  797. }
  798. hs.hsTimings.WriteCertificateVerify = hs.hsTimings.elapsedTime()
  799. return nil
  800. }
  801. func (hs *clientHandshakeStateTLS13) sendClientFinished() error {
  802. c := hs.c
  803. finished := &finishedMsg{
  804. verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript),
  805. }
  806. hs.transcript.Write(finished.marshal())
  807. if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
  808. return err
  809. }
  810. hs.hsTimings.WriteClientFinished = hs.hsTimings.elapsedTime()
  811. c.out.setTrafficSecret(hs.suite, hs.trafficSecret)
  812. if !c.config.SessionTicketsDisabled && c.config.ClientSessionCache != nil && !c.config.ECHEnabled {
  813. c.resumptionSecret = hs.suite.deriveSecret(hs.masterSecret,
  814. resumptionLabel, hs.transcript)
  815. }
  816. return nil
  817. }
  818. func (c *Conn) handleNewSessionTicket(msg *newSessionTicketMsgTLS13) error {
  819. if !c.isClient {
  820. c.sendAlert(alertUnexpectedMessage)
  821. return errors.New("tls: received new session ticket from a client")
  822. }
  823. if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil || c.config.ECHEnabled {
  824. return nil
  825. }
  826. // See RFC 8446, Section 4.6.1.
  827. if msg.lifetime == 0 {
  828. return nil
  829. }
  830. lifetime := time.Duration(msg.lifetime) * time.Second
  831. if lifetime > maxSessionTicketLifetime {
  832. c.sendAlert(alertIllegalParameter)
  833. return errors.New("tls: received a session ticket with invalid lifetime")
  834. }
  835. cipherSuite := cipherSuiteTLS13ByID(c.cipherSuite)
  836. if cipherSuite == nil || c.resumptionSecret == nil {
  837. return c.sendAlert(alertInternalError)
  838. }
  839. // Save the resumption_master_secret and nonce instead of deriving the PSK
  840. // to do the least amount of work on NewSessionTicket messages before we
  841. // know if the ticket will be used. Forward secrecy of resumed connections
  842. // is guaranteed by the requirement for pskModeDHE.
  843. session := &ClientSessionState{
  844. sessionTicket: msg.label,
  845. vers: c.vers,
  846. cipherSuite: c.cipherSuite,
  847. masterSecret: c.resumptionSecret,
  848. serverCertificates: c.peerCertificates,
  849. verifiedChains: c.verifiedChains,
  850. receivedAt: c.config.time(),
  851. nonce: msg.nonce,
  852. useBy: c.config.time().Add(lifetime),
  853. ageAdd: msg.ageAdd,
  854. ocspResponse: c.ocspResponse,
  855. scts: c.scts,
  856. }
  857. cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config)
  858. c.config.ClientSessionCache.Put(cacheKey, session)
  859. return nil
  860. }
  861. func (hs *clientHandshakeStateTLS13) abortIfRequired() error {
  862. c := hs.c
  863. if c.ech.offered && !c.ech.accepted {
  864. // If ECH was rejected, then abort the handshake.
  865. c.sendAlert(alertECHRequired)
  866. return errors.New("tls: ech: rejected")
  867. }
  868. return nil
  869. }