Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 
 
 

911 rindas
27 KiB

  1. package tls
  2. import (
  3. "bytes"
  4. "crypto"
  5. "crypto/ecdsa"
  6. "crypto/elliptic"
  7. "crypto/hmac"
  8. "crypto/rsa"
  9. "crypto/subtle"
  10. "encoding/hex"
  11. "errors"
  12. "fmt"
  13. "hash"
  14. "io"
  15. "log"
  16. "os"
  17. "runtime"
  18. "runtime/debug"
  19. "strings"
  20. "sync/atomic"
  21. "time"
  22. "golang_org/x/crypto/curve25519"
  23. )
  24. // numSessionTickets is the number of different session tickets the
  25. // server sends to a TLS 1.3 client, who will use each only once.
  26. const numSessionTickets = 2
  27. type secretLabel int
  28. const (
  29. secretResumptionPskBinder secretLabel = iota
  30. secretEarlyClient
  31. secretHandshakeClient
  32. secretHandshakeServer
  33. secretApplicationClient
  34. secretApplicationServer
  35. secretResumption
  36. )
  37. type keySchedule13 struct {
  38. suite *cipherSuite
  39. transcriptHash hash.Hash // uses the cipher suite hash algo
  40. secret []byte // Current secret as used for Derive-Secret
  41. handshakeCtx []byte // cached handshake context, invalidated on updates.
  42. clientRandom []byte // Used for keylogging, nil if keylogging is disabled.
  43. config *Config // Used for KeyLogWriter callback, nil if keylogging is disabled.
  44. }
  45. func newKeySchedule13(suite *cipherSuite, config *Config, clientRandom []byte) *keySchedule13 {
  46. if config.KeyLogWriter == nil {
  47. clientRandom = nil
  48. config = nil
  49. }
  50. return &keySchedule13{
  51. suite: suite,
  52. transcriptHash: hashForSuite(suite).New(),
  53. clientRandom: clientRandom,
  54. config: config,
  55. }
  56. }
  57. // setSecret sets the early/handshake/master secret based on the given secret
  58. // (IKM). The salt is based on previous secrets (nil for the early secret).
  59. func (ks *keySchedule13) setSecret(secret []byte) {
  60. hash := hashForSuite(ks.suite)
  61. salt := ks.secret
  62. if salt != nil {
  63. h0 := hash.New().Sum(nil)
  64. salt = hkdfExpandLabel(hash, salt, h0, "derived", hash.Size())
  65. }
  66. ks.secret = hkdfExtract(hash, secret, salt)
  67. }
  68. // write appends the data to the transcript hash context.
  69. func (ks *keySchedule13) write(data []byte) {
  70. ks.handshakeCtx = nil
  71. ks.transcriptHash.Write(data)
  72. }
  73. func (ks *keySchedule13) getLabel(secretLabel secretLabel) (label, keylogType string) {
  74. switch secretLabel {
  75. case secretResumptionPskBinder:
  76. label = "res binder"
  77. case secretEarlyClient:
  78. label = "c e traffic"
  79. keylogType = "CLIENT_EARLY_TRAFFIC_SECRET"
  80. case secretHandshakeClient:
  81. label = "c hs traffic"
  82. keylogType = "CLIENT_HANDSHAKE_TRAFFIC_SECRET"
  83. case secretHandshakeServer:
  84. label = "s hs traffic"
  85. keylogType = "SERVER_HANDSHAKE_TRAFFIC_SECRET"
  86. case secretApplicationClient:
  87. label = "c ap traffic"
  88. keylogType = "CLIENT_TRAFFIC_SECRET_0"
  89. case secretApplicationServer:
  90. label = "s ap traffic"
  91. keylogType = "SERVER_TRAFFIC_SECRET_0"
  92. case secretResumption:
  93. label = "res master"
  94. }
  95. return
  96. }
  97. // deriveSecret returns the secret derived from the handshake context and label.
  98. func (ks *keySchedule13) deriveSecret(secretLabel secretLabel) []byte {
  99. label, keylogType := ks.getLabel(secretLabel)
  100. if ks.handshakeCtx == nil {
  101. ks.handshakeCtx = ks.transcriptHash.Sum(nil)
  102. }
  103. hash := hashForSuite(ks.suite)
  104. secret := hkdfExpandLabel(hash, ks.secret, ks.handshakeCtx, label, hash.Size())
  105. if keylogType != "" && ks.config != nil {
  106. ks.config.writeKeyLog(keylogType, ks.clientRandom, secret)
  107. }
  108. return secret
  109. }
  110. func (ks *keySchedule13) prepareCipher(secretLabel secretLabel) (interface{}, []byte) {
  111. trafficSecret := ks.deriveSecret(secretLabel)
  112. hash := hashForSuite(ks.suite)
  113. key := hkdfExpandLabel(hash, trafficSecret, nil, "key", ks.suite.keyLen)
  114. iv := hkdfExpandLabel(hash, trafficSecret, nil, "iv", ks.suite.ivLen)
  115. return ks.suite.aead(key, iv), trafficSecret
  116. }
  117. func (hs *serverHandshakeState) doTLS13Handshake() error {
  118. config := hs.c.config
  119. c := hs.c
  120. hs.c.cipherSuite, hs.hello.cipherSuite = hs.suite.id, hs.suite.id
  121. hs.c.clientHello = hs.clientHello.marshal()
  122. // When picking the group for the handshake, priority is given to groups
  123. // that the client provided a keyShare for, so to avoid a round-trip.
  124. // After that the order of CurvePreferences is respected.
  125. var ks keyShare
  126. CurvePreferenceLoop:
  127. for _, curveID := range config.curvePreferences() {
  128. for _, keyShare := range hs.clientHello.keyShares {
  129. if curveID == keyShare.group {
  130. ks = keyShare
  131. break CurvePreferenceLoop
  132. }
  133. }
  134. }
  135. if ks.group == 0 {
  136. c.sendAlert(alertInternalError)
  137. return errors.New("tls: HelloRetryRequest not implemented") // TODO(filippo)
  138. }
  139. if committer, ok := c.conn.(Committer); ok {
  140. if err := committer.Commit(); err != nil {
  141. return err
  142. }
  143. }
  144. privateKey, serverKS, err := config.generateKeyShare(ks.group)
  145. if err != nil {
  146. c.sendAlert(alertInternalError)
  147. return err
  148. }
  149. hs.hello.keyShare = serverKS
  150. hash := hashForSuite(hs.suite)
  151. hashSize := hash.Size()
  152. hs.keySchedule = newKeySchedule13(hs.suite, config, hs.clientHello.random)
  153. // Check for PSK and update key schedule with new early secret key
  154. isResumed, pskAlert := hs.checkPSK()
  155. switch {
  156. case pskAlert != alertSuccess:
  157. c.sendAlert(pskAlert)
  158. return errors.New("tls: invalid client PSK")
  159. case !isResumed:
  160. // apply an empty PSK if not resumed.
  161. hs.keySchedule.setSecret(nil)
  162. case isResumed:
  163. c.didResume = true
  164. }
  165. hs.keySchedule.write(hs.clientHello.marshal())
  166. earlyClientCipher, _ := hs.keySchedule.prepareCipher(secretEarlyClient)
  167. ecdheSecret := deriveECDHESecret(ks, privateKey)
  168. if ecdheSecret == nil {
  169. c.sendAlert(alertIllegalParameter)
  170. return errors.New("tls: bad ECDHE client share")
  171. }
  172. hs.keySchedule.write(hs.hello.marshal())
  173. if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
  174. return err
  175. }
  176. hs.keySchedule.setSecret(ecdheSecret)
  177. clientCipher, cTrafficSecret := hs.keySchedule.prepareCipher(secretHandshakeClient)
  178. hs.hsClientCipher = clientCipher
  179. serverCipher, sTrafficSecret := hs.keySchedule.prepareCipher(secretHandshakeServer)
  180. c.out.setCipher(c.vers, serverCipher)
  181. serverFinishedKey := hkdfExpandLabel(hash, sTrafficSecret, nil, "finished", hashSize)
  182. hs.clientFinishedKey = hkdfExpandLabel(hash, cTrafficSecret, nil, "finished", hashSize)
  183. hs.keySchedule.write(hs.hello13Enc.marshal())
  184. if _, err := c.writeRecord(recordTypeHandshake, hs.hello13Enc.marshal()); err != nil {
  185. return err
  186. }
  187. if !c.didResume {
  188. if err := hs.sendCertificate13(); err != nil {
  189. return err
  190. }
  191. }
  192. verifyData := hmacOfSum(hash, hs.keySchedule.transcriptHash, serverFinishedKey)
  193. serverFinished := &finishedMsg{
  194. verifyData: verifyData,
  195. }
  196. hs.keySchedule.write(serverFinished.marshal())
  197. if _, err := c.writeRecord(recordTypeHandshake, serverFinished.marshal()); err != nil {
  198. return err
  199. }
  200. hs.keySchedule.setSecret(nil) // derive master secret
  201. hs.appClientCipher, _ = hs.keySchedule.prepareCipher(secretApplicationClient)
  202. serverCipher, _ = hs.keySchedule.prepareCipher(secretApplicationServer)
  203. c.out.setCipher(c.vers, serverCipher)
  204. if c.hand.Len() > 0 {
  205. return c.sendAlert(alertUnexpectedMessage)
  206. }
  207. if hs.hello13Enc.earlyData {
  208. c.in.setCipher(c.vers, earlyClientCipher)
  209. c.phase = readingEarlyData
  210. } else if hs.clientHello.earlyData {
  211. c.in.setCipher(c.vers, hs.hsClientCipher)
  212. c.phase = discardingEarlyData
  213. } else {
  214. c.in.setCipher(c.vers, hs.hsClientCipher)
  215. c.phase = waitingClientFinished
  216. }
  217. return nil
  218. }
  219. // readClientFinished13 is called during the server handshake (when no early
  220. // data it available) or after reading all early data. It discards early data if
  221. // the server did not accept it and then verifies the Finished message. Once
  222. // done it sends the session tickets. Under c.in lock.
  223. func (hs *serverHandshakeState) readClientFinished13(hasConfirmLock bool) error {
  224. c := hs.c
  225. // If the client advertised and sends early data while the server does
  226. // not accept it, it must be fully skipped until the Finished message.
  227. for c.phase == discardingEarlyData {
  228. if err := c.readRecord(recordTypeApplicationData); err != nil {
  229. return err
  230. }
  231. // Assume receipt of Finished message (will be checked below).
  232. if c.hand.Len() > 0 {
  233. c.phase = waitingClientFinished
  234. break
  235. }
  236. }
  237. // If the client sends early data followed by a Finished message (but
  238. // no end_of_early_data), the server MUST terminate the connection.
  239. if c.phase != waitingClientFinished {
  240. c.sendAlert(alertUnexpectedMessage)
  241. return errors.New("tls: did not expect Client Finished yet")
  242. }
  243. c.phase = readingClientFinished
  244. msg, err := c.readHandshake()
  245. if err != nil {
  246. return err
  247. }
  248. clientFinished, ok := msg.(*finishedMsg)
  249. if !ok {
  250. c.sendAlert(alertUnexpectedMessage)
  251. return unexpectedMessageError(clientFinished, msg)
  252. }
  253. hash := hashForSuite(hs.suite)
  254. expectedVerifyData := hmacOfSum(hash, hs.keySchedule.transcriptHash, hs.clientFinishedKey)
  255. if len(expectedVerifyData) != len(clientFinished.verifyData) ||
  256. subtle.ConstantTimeCompare(expectedVerifyData, clientFinished.verifyData) != 1 {
  257. c.sendAlert(alertDecryptError)
  258. return errors.New("tls: client's Finished message is incorrect")
  259. }
  260. hs.keySchedule.write(clientFinished.marshal())
  261. c.hs = nil // Discard the server handshake state
  262. if c.hand.Len() > 0 {
  263. return c.sendAlert(alertUnexpectedMessage)
  264. }
  265. c.in.setCipher(c.vers, hs.appClientCipher)
  266. c.in.traceErr, c.out.traceErr = nil, nil
  267. c.phase = handshakeConfirmed
  268. atomic.StoreInt32(&c.handshakeConfirmed, 1)
  269. // Any read operation after handshakeRunning and before handshakeConfirmed
  270. // will be holding this lock, which we release as soon as the confirmation
  271. // happens, even if the Read call might do more work.
  272. // If a Handshake is pending, c.confirmMutex will never be locked as
  273. // ConfirmHandshake will wait for the handshake to complete. If a
  274. // handshake was complete, and this was a confirmation, unlock
  275. // c.confirmMutex now to allow readers to proceed.
  276. if hasConfirmLock {
  277. c.confirmMutex.Unlock()
  278. }
  279. return hs.sendSessionTicket13() // TODO: do in a goroutine
  280. }
  281. func (hs *serverHandshakeState) sendCertificate13() error {
  282. c := hs.c
  283. certEntries := []certificateEntry{}
  284. for _, cert := range hs.cert.Certificate {
  285. certEntries = append(certEntries, certificateEntry{data: cert})
  286. }
  287. if len(certEntries) > 0 && hs.clientHello.ocspStapling {
  288. certEntries[0].ocspStaple = hs.cert.OCSPStaple
  289. }
  290. if len(certEntries) > 0 && hs.clientHello.scts {
  291. certEntries[0].sctList = hs.cert.SignedCertificateTimestamps
  292. }
  293. certMsg := &certificateMsg13{certificates: certEntries}
  294. hs.keySchedule.write(certMsg.marshal())
  295. if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
  296. return err
  297. }
  298. sigScheme, err := hs.selectTLS13SignatureScheme()
  299. if err != nil {
  300. c.sendAlert(alertInternalError)
  301. return err
  302. }
  303. sigHash := hashForSignatureScheme(sigScheme)
  304. opts := crypto.SignerOpts(sigHash)
  305. if signatureSchemeIsPSS(sigScheme) {
  306. opts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
  307. }
  308. toSign := prepareDigitallySigned(sigHash, "TLS 1.3, server CertificateVerify", hs.keySchedule.transcriptHash.Sum(nil))
  309. signature, err := hs.cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), toSign[:], opts)
  310. if err != nil {
  311. c.sendAlert(alertInternalError)
  312. return err
  313. }
  314. verifyMsg := &certificateVerifyMsg{
  315. hasSignatureAndHash: true,
  316. signatureAlgorithm: sigScheme,
  317. signature: signature,
  318. }
  319. hs.keySchedule.write(verifyMsg.marshal())
  320. if _, err := c.writeRecord(recordTypeHandshake, verifyMsg.marshal()); err != nil {
  321. return err
  322. }
  323. return nil
  324. }
  325. func (c *Conn) handleEndOfEarlyData() {
  326. if c.phase != readingEarlyData || c.vers < VersionTLS13 {
  327. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  328. return
  329. }
  330. c.phase = waitingClientFinished
  331. if c.hand.Len() > 0 {
  332. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  333. return
  334. }
  335. c.in.setCipher(c.vers, c.hs.hsClientCipher)
  336. }
  337. // selectTLS13SignatureScheme chooses the SignatureScheme for the CertificateVerify
  338. // based on the certificate type and client supported schemes. If no overlap is found,
  339. // a fallback is selected.
  340. //
  341. // See https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.4.1.2
  342. func (hs *serverHandshakeState) selectTLS13SignatureScheme() (sigScheme SignatureScheme, err error) {
  343. var supportedSchemes []SignatureScheme
  344. signer, ok := hs.cert.PrivateKey.(crypto.Signer)
  345. if !ok {
  346. return 0, errors.New("tls: certificate private key does not implement crypto.Signer")
  347. }
  348. pk := signer.Public()
  349. if _, ok := pk.(*rsa.PublicKey); ok {
  350. sigScheme = PSSWithSHA256
  351. supportedSchemes = []SignatureScheme{PSSWithSHA256, PSSWithSHA384, PSSWithSHA512}
  352. } else if pk, ok := pk.(*ecdsa.PublicKey); ok {
  353. switch pk.Curve {
  354. case elliptic.P256():
  355. sigScheme = ECDSAWithP256AndSHA256
  356. supportedSchemes = []SignatureScheme{ECDSAWithP256AndSHA256}
  357. case elliptic.P384():
  358. sigScheme = ECDSAWithP384AndSHA384
  359. supportedSchemes = []SignatureScheme{ECDSAWithP384AndSHA384}
  360. case elliptic.P521():
  361. sigScheme = ECDSAWithP521AndSHA512
  362. supportedSchemes = []SignatureScheme{ECDSAWithP521AndSHA512}
  363. default:
  364. return 0, errors.New("tls: unknown ECDSA certificate curve")
  365. }
  366. } else {
  367. return 0, errors.New("tls: unknown certificate key type")
  368. }
  369. for _, ss := range supportedSchemes {
  370. for _, cs := range hs.clientHello.supportedSignatureAlgorithms {
  371. if ss == cs {
  372. return ss, nil
  373. }
  374. }
  375. }
  376. return sigScheme, nil
  377. }
  378. func signatureSchemeIsPSS(s SignatureScheme) bool {
  379. return s == PSSWithSHA256 || s == PSSWithSHA384 || s == PSSWithSHA512
  380. }
  381. // hashForSignatureScheme returns the Hash used by a SignatureScheme which is
  382. // supported by selectTLS13SignatureScheme.
  383. func hashForSignatureScheme(ss SignatureScheme) crypto.Hash {
  384. switch ss {
  385. case PSSWithSHA256, ECDSAWithP256AndSHA256:
  386. return crypto.SHA256
  387. case PSSWithSHA384, ECDSAWithP384AndSHA384:
  388. return crypto.SHA384
  389. case PSSWithSHA512, ECDSAWithP521AndSHA512:
  390. return crypto.SHA512
  391. default:
  392. panic("unsupported SignatureScheme passed to hashForSignatureScheme")
  393. }
  394. }
  395. func hashForSuite(suite *cipherSuite) crypto.Hash {
  396. if suite.flags&suiteSHA384 != 0 {
  397. return crypto.SHA384
  398. }
  399. return crypto.SHA256
  400. }
  401. func prepareDigitallySigned(hash crypto.Hash, context string, data []byte) []byte {
  402. message := bytes.Repeat([]byte{32}, 64)
  403. message = append(message, context...)
  404. message = append(message, 0)
  405. message = append(message, data...)
  406. h := hash.New()
  407. h.Write(message)
  408. return h.Sum(nil)
  409. }
  410. func (c *Config) generateKeyShare(curveID CurveID) ([]byte, keyShare, error) {
  411. if curveID == X25519 {
  412. var scalar, public [32]byte
  413. if _, err := io.ReadFull(c.rand(), scalar[:]); err != nil {
  414. return nil, keyShare{}, err
  415. }
  416. curve25519.ScalarBaseMult(&public, &scalar)
  417. return scalar[:], keyShare{group: curveID, data: public[:]}, nil
  418. }
  419. curve, ok := curveForCurveID(curveID)
  420. if !ok {
  421. return nil, keyShare{}, errors.New("tls: preferredCurves includes unsupported curve")
  422. }
  423. privateKey, x, y, err := elliptic.GenerateKey(curve, c.rand())
  424. if err != nil {
  425. return nil, keyShare{}, err
  426. }
  427. ecdhePublic := elliptic.Marshal(curve, x, y)
  428. return privateKey, keyShare{group: curveID, data: ecdhePublic}, nil
  429. }
  430. func deriveECDHESecret(ks keyShare, secretKey []byte) []byte {
  431. if ks.group == X25519 {
  432. if len(ks.data) != 32 {
  433. return nil
  434. }
  435. var theirPublic, sharedKey, scalar [32]byte
  436. copy(theirPublic[:], ks.data)
  437. copy(scalar[:], secretKey)
  438. curve25519.ScalarMult(&sharedKey, &scalar, &theirPublic)
  439. return sharedKey[:]
  440. }
  441. curve, ok := curveForCurveID(ks.group)
  442. if !ok {
  443. return nil
  444. }
  445. x, y := elliptic.Unmarshal(curve, ks.data)
  446. if x == nil {
  447. return nil
  448. }
  449. x, _ = curve.ScalarMult(x, y, secretKey)
  450. xBytes := x.Bytes()
  451. curveSize := (curve.Params().BitSize + 8 - 1) >> 3
  452. if len(xBytes) == curveSize {
  453. return xBytes
  454. }
  455. buf := make([]byte, curveSize)
  456. copy(buf[len(buf)-len(xBytes):], xBytes)
  457. return buf
  458. }
  459. func hkdfExpandLabel(hash crypto.Hash, secret, hashValue []byte, label string, L int) []byte {
  460. prefix := "tls13 "
  461. hkdfLabel := make([]byte, 4+len(prefix)+len(label)+len(hashValue))
  462. hkdfLabel[0] = byte(L >> 8)
  463. hkdfLabel[1] = byte(L)
  464. hkdfLabel[2] = byte(len(prefix) + len(label))
  465. copy(hkdfLabel[3:], prefix)
  466. z := hkdfLabel[3+len(prefix):]
  467. copy(z, label)
  468. z = z[len(label):]
  469. z[0] = byte(len(hashValue))
  470. copy(z[1:], hashValue)
  471. return hkdfExpand(hash, secret, hkdfLabel, L)
  472. }
  473. func hmacOfSum(f crypto.Hash, hash hash.Hash, key []byte) []byte {
  474. h := hmac.New(f.New, key)
  475. h.Write(hash.Sum(nil))
  476. return h.Sum(nil)
  477. }
  478. // Maximum allowed mismatch between the stated age of a ticket
  479. // and the server-observed one. See
  480. // https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.8.2.
  481. const ticketAgeSkewAllowance = 10 * time.Second
  482. // checkPSK tries to resume using a PSK, returning true (and updating the
  483. // early secret in the key schedule) if the PSK was used and false otherwise.
  484. func (hs *serverHandshakeState) checkPSK() (isResumed bool, alert alert) {
  485. if hs.c.config.SessionTicketsDisabled {
  486. return false, alertSuccess
  487. }
  488. foundDHE := false
  489. for _, mode := range hs.clientHello.pskKeyExchangeModes {
  490. if mode == pskDHEKeyExchange {
  491. foundDHE = true
  492. break
  493. }
  494. }
  495. if !foundDHE {
  496. return false, alertSuccess
  497. }
  498. hash := hashForSuite(hs.suite)
  499. hashSize := hash.Size()
  500. for i := range hs.clientHello.psks {
  501. sessionTicket := append([]uint8{}, hs.clientHello.psks[i].identity...)
  502. if hs.c.config.SessionTicketSealer != nil {
  503. var ok bool
  504. sessionTicket, ok = hs.c.config.SessionTicketSealer.Unseal(hs.clientHelloInfo(), sessionTicket)
  505. if !ok {
  506. continue
  507. }
  508. } else {
  509. sessionTicket, _ = hs.c.decryptTicket(sessionTicket)
  510. if sessionTicket == nil {
  511. continue
  512. }
  513. }
  514. s := &sessionState13{}
  515. if s.unmarshal(sessionTicket) != alertSuccess {
  516. continue
  517. }
  518. if s.vers != hs.c.vers {
  519. continue
  520. }
  521. clientAge := time.Duration(hs.clientHello.psks[i].obfTicketAge-s.ageAdd) * time.Millisecond
  522. serverAge := time.Since(time.Unix(int64(s.createdAt), 0))
  523. if clientAge-serverAge > ticketAgeSkewAllowance || clientAge-serverAge < -ticketAgeSkewAllowance {
  524. // XXX: NSS is off spec and sends obfuscated_ticket_age as seconds
  525. clientAge = time.Duration(hs.clientHello.psks[i].obfTicketAge-s.ageAdd) * time.Second
  526. if clientAge-serverAge > ticketAgeSkewAllowance || clientAge-serverAge < -ticketAgeSkewAllowance {
  527. continue
  528. }
  529. }
  530. // This enforces the stricter 0-RTT requirements on all ticket uses.
  531. // The benefit of using PSK+ECDHE without 0-RTT are small enough that
  532. // we can give them up in the edge case of changed suite or ALPN or SNI.
  533. if s.suite != hs.suite.id {
  534. continue
  535. }
  536. if s.alpnProtocol != hs.c.clientProtocol {
  537. continue
  538. }
  539. if s.SNI != hs.c.serverName {
  540. continue
  541. }
  542. hs.keySchedule.setSecret(s.pskSecret)
  543. binderKey := hs.keySchedule.deriveSecret(secretResumptionPskBinder)
  544. binderFinishedKey := hkdfExpandLabel(hash, binderKey, nil, "finished", hashSize)
  545. chHash := hash.New()
  546. chHash.Write(hs.clientHello.rawTruncated)
  547. expectedBinder := hmacOfSum(hash, chHash, binderFinishedKey)
  548. if subtle.ConstantTimeCompare(expectedBinder, hs.clientHello.psks[i].binder) != 1 {
  549. return false, alertDecryptError
  550. }
  551. if i == 0 && hs.clientHello.earlyData {
  552. // This is a ticket intended to be used for 0-RTT
  553. if s.maxEarlyDataLen == 0 {
  554. // But we had not tagged it as such.
  555. return false, alertIllegalParameter
  556. }
  557. if hs.c.config.Accept0RTTData {
  558. hs.c.binder = expectedBinder
  559. hs.c.ticketMaxEarlyData = int64(s.maxEarlyDataLen)
  560. hs.hello13Enc.earlyData = true
  561. }
  562. }
  563. hs.hello.psk = true
  564. hs.hello.pskIdentity = uint16(i)
  565. return true, alertSuccess
  566. }
  567. return false, alertSuccess
  568. }
  569. func (hs *serverHandshakeState) sendSessionTicket13() error {
  570. c := hs.c
  571. if c.config.SessionTicketsDisabled {
  572. return nil
  573. }
  574. foundDHE := false
  575. for _, mode := range hs.clientHello.pskKeyExchangeModes {
  576. if mode == pskDHEKeyExchange {
  577. foundDHE = true
  578. break
  579. }
  580. }
  581. if !foundDHE {
  582. return nil
  583. }
  584. resumptionMasterSecret := hs.keySchedule.deriveSecret(secretResumption)
  585. ageAddBuf := make([]byte, 4)
  586. sessionState := &sessionState13{
  587. vers: c.vers,
  588. suite: hs.suite.id,
  589. createdAt: uint64(time.Now().Unix()),
  590. alpnProtocol: c.clientProtocol,
  591. SNI: c.serverName,
  592. maxEarlyDataLen: c.config.Max0RTTDataSize,
  593. }
  594. hash := hashForSuite(hs.suite)
  595. for i := 0; i < numSessionTickets; i++ {
  596. if _, err := io.ReadFull(c.config.rand(), ageAddBuf); err != nil {
  597. c.sendAlert(alertInternalError)
  598. return err
  599. }
  600. sessionState.ageAdd = uint32(ageAddBuf[0])<<24 | uint32(ageAddBuf[1])<<16 |
  601. uint32(ageAddBuf[2])<<8 | uint32(ageAddBuf[3])
  602. // ticketNonce must be a unique value for this connection.
  603. // Assume there are no more than 255 tickets, otherwise two
  604. // tickets might have the same PSK which could be a problem if
  605. // one of them is compromised.
  606. ticketNonce := []byte{byte(i)}
  607. sessionState.pskSecret = hkdfExpandLabel(hash, resumptionMasterSecret, ticketNonce, "resumption", hash.Size())
  608. ticket := sessionState.marshal()
  609. var err error
  610. if c.config.SessionTicketSealer != nil {
  611. cs := c.ConnectionState()
  612. ticket, err = c.config.SessionTicketSealer.Seal(&cs, ticket)
  613. } else {
  614. ticket, err = c.encryptTicket(ticket)
  615. }
  616. if err != nil {
  617. c.sendAlert(alertInternalError)
  618. return err
  619. }
  620. if ticket == nil {
  621. continue
  622. }
  623. ticketMsg := &newSessionTicketMsg13{
  624. lifetime: 24 * 3600, // TODO(filippo)
  625. maxEarlyDataLength: c.config.Max0RTTDataSize,
  626. withEarlyDataInfo: c.config.Max0RTTDataSize > 0,
  627. ageAdd: sessionState.ageAdd,
  628. nonce: ticketNonce,
  629. ticket: ticket,
  630. }
  631. if _, err := c.writeRecord(recordTypeHandshake, ticketMsg.marshal()); err != nil {
  632. return err
  633. }
  634. }
  635. return nil
  636. }
  637. func (hs *serverHandshakeState) traceErr(err error) {
  638. if err == nil {
  639. return
  640. }
  641. if os.Getenv("TLSDEBUG") == "error" {
  642. if hs != nil && hs.clientHello != nil {
  643. os.Stderr.WriteString(hex.Dump(hs.clientHello.marshal()))
  644. } else if err == io.EOF {
  645. return // don't stack trace on EOF before CH
  646. }
  647. fmt.Fprintf(os.Stderr, "\n%s\n", debug.Stack())
  648. }
  649. if os.Getenv("TLSDEBUG") == "short" {
  650. var pcs [4]uintptr
  651. frames := runtime.CallersFrames(pcs[0:runtime.Callers(3, pcs[:])])
  652. for {
  653. frame, more := frames.Next()
  654. if frame.Function != "crypto/tls.(*halfConn).setErrorLocked" &&
  655. frame.Function != "crypto/tls.(*Conn).sendAlertLocked" &&
  656. frame.Function != "crypto/tls.(*Conn).sendAlert" {
  657. file := frame.File[strings.LastIndex(frame.File, "/")+1:]
  658. log.Printf("%s:%d (%s): %v", file, frame.Line, frame.Function, err)
  659. return
  660. }
  661. if !more {
  662. break
  663. }
  664. }
  665. }
  666. }
  667. func (hs *clientHandshakeState) processCertsFromServer13(certMsg *certificateMsg13) error {
  668. certs := make([][]byte, len(certMsg.certificates))
  669. for i, cert := range certMsg.certificates {
  670. certs[i] = cert.data
  671. }
  672. return hs.processCertsFromServer(certs)
  673. }
  674. func (hs *clientHandshakeState) processEncryptedExtensions(ee *encryptedExtensionsMsg) error {
  675. c := hs.c
  676. if ee.alpnProtocol != "" {
  677. c.clientProtocol = ee.alpnProtocol
  678. c.clientProtocolFallback = false
  679. }
  680. return nil
  681. }
  682. func (hs *clientHandshakeState) verifyPeerCertificate(certVerify *certificateVerifyMsg) error {
  683. pub := hs.c.peerCertificates[0].PublicKey
  684. _, sigType, hashFunc, err := pickSignatureAlgorithm(pub, []SignatureScheme{certVerify.signatureAlgorithm}, hs.hello.supportedSignatureAlgorithms, hs.c.vers)
  685. if err != nil {
  686. hs.c.sendAlert(alertHandshakeFailure)
  687. return err
  688. }
  689. digest := prepareDigitallySigned(hashFunc, "TLS 1.3, server CertificateVerify", hs.keySchedule.transcriptHash.Sum(nil))
  690. err = verifyHandshakeSignature(sigType, pub, hashFunc, digest, certVerify.signature)
  691. if err != nil {
  692. hs.c.sendAlert(alertDecryptError)
  693. return err
  694. }
  695. return nil
  696. }
  697. func (hs *clientHandshakeState) doTLS13Handshake() error {
  698. c := hs.c
  699. hash := hashForSuite(hs.suite)
  700. hashSize := hash.Size()
  701. serverHello := hs.serverHello
  702. // TODO check if keyshare is unacceptable, raise HRR.
  703. clientKS := hs.hello.keyShares[0]
  704. if serverHello.keyShare.group != clientKS.group {
  705. c.sendAlert(alertIllegalParameter)
  706. return errors.New("bad or missing key share from server")
  707. }
  708. // 0-RTT is not supported yet, so use an empty PSK.
  709. hs.keySchedule.setSecret(nil)
  710. ecdheSecret := deriveECDHESecret(serverHello.keyShare, hs.privateKey)
  711. if ecdheSecret == nil {
  712. c.sendAlert(alertIllegalParameter)
  713. return errors.New("tls: bad ECDHE server share")
  714. }
  715. // Calculate handshake secrets.
  716. hs.keySchedule.setSecret(ecdheSecret)
  717. clientCipher, clientHandshakeSecret := hs.keySchedule.prepareCipher(secretHandshakeClient)
  718. serverCipher, serverHandshakeSecret := hs.keySchedule.prepareCipher(secretHandshakeServer)
  719. if c.hand.Len() > 0 {
  720. c.sendAlert(alertUnexpectedMessage)
  721. return errors.New("tls: unexpected data after Server Hello")
  722. }
  723. // Do not change the sender key yet, the server must authenticate first.
  724. c.in.setCipher(c.vers, serverCipher)
  725. // Calculate MAC key for Finished messages.
  726. serverFinishedKey := hkdfExpandLabel(hash, serverHandshakeSecret, nil, "finished", hashSize)
  727. clientFinishedKey := hkdfExpandLabel(hash, clientHandshakeSecret, nil, "finished", hashSize)
  728. msg, err := c.readHandshake()
  729. if err != nil {
  730. return err
  731. }
  732. encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
  733. if !ok {
  734. c.sendAlert(alertUnexpectedMessage)
  735. return unexpectedMessageError(encryptedExtensions, msg)
  736. }
  737. if err := hs.processEncryptedExtensions(encryptedExtensions); err != nil {
  738. return err
  739. }
  740. hs.keySchedule.write(encryptedExtensions.marshal())
  741. // PSKs are not supported, so receive Certificate message.
  742. msg, err = c.readHandshake()
  743. if err != nil {
  744. return err
  745. }
  746. // TODO handle optional CertificateRequest
  747. certMsg, ok := msg.(*certificateMsg13)
  748. if !ok {
  749. c.sendAlert(alertUnexpectedMessage)
  750. return unexpectedMessageError(certMsg, msg)
  751. }
  752. hs.keySchedule.write(certMsg.marshal())
  753. // Validate certificates.
  754. if err := hs.processCertsFromServer13(certMsg); err != nil {
  755. return err
  756. }
  757. // Receive CertificateVerify message.
  758. msg, err = c.readHandshake()
  759. if err != nil {
  760. return err
  761. }
  762. certVerifyMsg, ok := msg.(*certificateVerifyMsg)
  763. if !ok {
  764. c.sendAlert(alertUnexpectedMessage)
  765. return unexpectedMessageError(certVerifyMsg, msg)
  766. }
  767. if err = hs.verifyPeerCertificate(certVerifyMsg); err != nil {
  768. return err
  769. }
  770. hs.keySchedule.write(certVerifyMsg.marshal())
  771. // Receive Finished message.
  772. msg, err = c.readHandshake()
  773. if err != nil {
  774. return err
  775. }
  776. serverFinished, ok := msg.(*finishedMsg)
  777. if !ok {
  778. c.sendAlert(alertUnexpectedMessage)
  779. return unexpectedMessageError(serverFinished, msg)
  780. }
  781. // Validate server Finished hash.
  782. expectedVerifyData := hmacOfSum(hash, hs.keySchedule.transcriptHash, serverFinishedKey)
  783. if subtle.ConstantTimeCompare(expectedVerifyData, serverFinished.verifyData) != 1 {
  784. c.sendAlert(alertDecryptError)
  785. return errors.New("tls: server's Finished message is incorrect")
  786. }
  787. hs.keySchedule.write(serverFinished.marshal())
  788. // Server has authenticated itself, change our cipher.
  789. c.out.setCipher(c.vers, clientCipher)
  790. // TODO optionally send a client cert
  791. // Send Finished
  792. verifyData := hmacOfSum(hash, hs.keySchedule.transcriptHash, clientFinishedKey)
  793. clientFinished := &finishedMsg{
  794. verifyData: verifyData,
  795. }
  796. if _, err := c.writeRecord(recordTypeHandshake, clientFinished.marshal()); err != nil {
  797. return err
  798. }
  799. // Calculate application traffic secrets.
  800. hs.keySchedule.setSecret(nil) // derive master secret
  801. // TODO store initial traffic secret key for KeyUpdate
  802. clientCipher, _ = hs.keySchedule.prepareCipher(secretApplicationClient)
  803. serverCipher, _ = hs.keySchedule.prepareCipher(secretApplicationServer)
  804. c.out.setCipher(c.vers, clientCipher)
  805. if c.hand.Len() > 0 {
  806. c.sendAlert(alertUnexpectedMessage)
  807. return errors.New("tls: unexpected data after handshake")
  808. }
  809. c.in.setCipher(c.vers, serverCipher)
  810. return nil
  811. }