25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

738 lines
22 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. ks.secret = hkdfExtract(hash, secret, salt)
  63. }
  64. // write appends the data to the transcript hash context.
  65. func (ks *keySchedule13) write(data []byte) {
  66. ks.handshakeCtx = nil
  67. ks.transcriptHash.Write(data)
  68. }
  69. func (ks *keySchedule13) getLabel(secretLabel secretLabel) (label, keylogType string) {
  70. switch secretLabel {
  71. case secretResumptionPskBinder:
  72. label = "resumption psk binder key"
  73. case secretEarlyClient:
  74. label = "client early traffic secret"
  75. keylogType = "CLIENT_EARLY_TRAFFIC_SECRET"
  76. case secretHandshakeClient:
  77. label = "client handshake traffic secret"
  78. keylogType = "CLIENT_HANDSHAKE_TRAFFIC_SECRET"
  79. case secretHandshakeServer:
  80. label = "server handshake traffic secret"
  81. keylogType = "SERVER_HANDSHAKE_TRAFFIC_SECRET"
  82. case secretApplicationClient:
  83. label = "client application traffic secret"
  84. keylogType = "CLIENT_TRAFFIC_SECRET_0"
  85. case secretApplicationServer:
  86. label = "server application traffic secret"
  87. keylogType = "SERVER_TRAFFIC_SECRET_0"
  88. case secretResumption:
  89. label = "resumption master secret"
  90. }
  91. return
  92. }
  93. // deriveSecret returns the secret derived from the handshake context and label.
  94. func (ks *keySchedule13) deriveSecret(secretLabel secretLabel) []byte {
  95. label, keylogType := ks.getLabel(secretLabel)
  96. if ks.handshakeCtx == nil {
  97. ks.handshakeCtx = ks.transcriptHash.Sum(nil)
  98. }
  99. hash := hashForSuite(ks.suite)
  100. secret := hkdfExpandLabel(hash, ks.secret, ks.handshakeCtx, label, hash.Size())
  101. if keylogType != "" && ks.config != nil {
  102. ks.config.writeKeyLog(keylogType, ks.clientRandom, secret)
  103. }
  104. return secret
  105. }
  106. func (ks *keySchedule13) prepareCipher(secretLabel secretLabel) (interface{}, []byte) {
  107. trafficSecret := ks.deriveSecret(secretLabel)
  108. hash := hashForSuite(ks.suite)
  109. key := hkdfExpandLabel(hash, trafficSecret, nil, "key", ks.suite.keyLen)
  110. iv := hkdfExpandLabel(hash, trafficSecret, nil, "iv", ks.suite.ivLen)
  111. return ks.suite.aead(key, iv), trafficSecret
  112. }
  113. func (hs *serverHandshakeState) doTLS13Handshake() error {
  114. config := hs.c.config
  115. c := hs.c
  116. hs.c.cipherSuite, hs.hello.cipherSuite = hs.suite.id, hs.suite.id
  117. hs.c.clientHello = hs.clientHello.marshal()
  118. // When picking the group for the handshake, priority is given to groups
  119. // that the client provided a keyShare for, so to avoid a round-trip.
  120. // After that the order of CurvePreferences is respected.
  121. var ks keyShare
  122. CurvePreferenceLoop:
  123. for _, curveID := range config.curvePreferences() {
  124. for _, keyShare := range hs.clientHello.keyShares {
  125. if curveID == keyShare.group {
  126. ks = keyShare
  127. break CurvePreferenceLoop
  128. }
  129. }
  130. }
  131. if ks.group == 0 {
  132. c.sendAlert(alertInternalError)
  133. return errors.New("tls: HelloRetryRequest not implemented") // TODO(filippo)
  134. }
  135. if committer, ok := c.conn.(Committer); ok {
  136. if err := committer.Commit(); err != nil {
  137. return err
  138. }
  139. }
  140. privateKey, serverKS, err := config.generateKeyShare(ks.group)
  141. if err != nil {
  142. c.sendAlert(alertInternalError)
  143. return err
  144. }
  145. hs.hello.keyShare = serverKS
  146. hash := hashForSuite(hs.suite)
  147. hashSize := hash.Size()
  148. hs.keySchedule = newKeySchedule13(hs.suite, config, hs.clientHello.random)
  149. // Check for PSK and update key schedule with new early secret key
  150. isResumed, pskAlert := hs.checkPSK()
  151. switch {
  152. case pskAlert != alertSuccess:
  153. c.sendAlert(pskAlert)
  154. return errors.New("tls: invalid client PSK")
  155. case !isResumed:
  156. // apply an empty PSK if not resumed.
  157. hs.keySchedule.setSecret(nil)
  158. case isResumed:
  159. c.didResume = true
  160. }
  161. hs.keySchedule.write(hs.clientHello.marshal())
  162. earlyClientCipher, _ := hs.keySchedule.prepareCipher(secretEarlyClient)
  163. ecdheSecret := deriveECDHESecret(ks, privateKey)
  164. if ecdheSecret == nil {
  165. c.sendAlert(alertIllegalParameter)
  166. return errors.New("tls: bad ECDHE client share")
  167. }
  168. hs.keySchedule.write(hs.hello.marshal())
  169. if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
  170. return err
  171. }
  172. hs.keySchedule.setSecret(ecdheSecret)
  173. clientCipher, cTrafficSecret := hs.keySchedule.prepareCipher(secretHandshakeClient)
  174. hs.hsClientCipher = clientCipher
  175. serverCipher, sTrafficSecret := hs.keySchedule.prepareCipher(secretHandshakeServer)
  176. c.out.setCipher(c.vers, serverCipher)
  177. serverFinishedKey := hkdfExpandLabel(hash, sTrafficSecret, nil, "finished", hashSize)
  178. hs.clientFinishedKey = hkdfExpandLabel(hash, cTrafficSecret, nil, "finished", hashSize)
  179. hs.keySchedule.write(hs.hello13Enc.marshal())
  180. if _, err := c.writeRecord(recordTypeHandshake, hs.hello13Enc.marshal()); err != nil {
  181. return err
  182. }
  183. if !c.didResume {
  184. if err := hs.sendCertificate13(); err != nil {
  185. return err
  186. }
  187. }
  188. verifyData := hmacOfSum(hash, hs.keySchedule.transcriptHash, serverFinishedKey)
  189. serverFinished := &finishedMsg{
  190. verifyData: verifyData,
  191. }
  192. hs.keySchedule.write(serverFinished.marshal())
  193. if _, err := c.writeRecord(recordTypeHandshake, serverFinished.marshal()); err != nil {
  194. return err
  195. }
  196. hs.keySchedule.setSecret(nil) // derive master secret
  197. hs.appClientCipher, _ = hs.keySchedule.prepareCipher(secretApplicationClient)
  198. serverCipher, _ = hs.keySchedule.prepareCipher(secretApplicationServer)
  199. c.out.setCipher(c.vers, serverCipher)
  200. if c.hand.Len() > 0 {
  201. return c.sendAlert(alertUnexpectedMessage)
  202. }
  203. if hs.hello13Enc.earlyData {
  204. c.in.setCipher(c.vers, earlyClientCipher)
  205. c.phase = readingEarlyData
  206. } else if hs.clientHello.earlyData {
  207. c.in.setCipher(c.vers, hs.hsClientCipher)
  208. c.phase = discardingEarlyData
  209. } else {
  210. c.in.setCipher(c.vers, hs.hsClientCipher)
  211. c.phase = waitingClientFinished
  212. }
  213. return nil
  214. }
  215. // readClientFinished13 is called during the server handshake (when no early
  216. // data it available) or after reading all early data. It discards early data if
  217. // the server did not accept it and then verifies the Finished message. Once
  218. // done it sends the session tickets. Under c.in lock.
  219. func (hs *serverHandshakeState) readClientFinished13(hasConfirmLock bool) error {
  220. c := hs.c
  221. // If the client advertised and sends early data while the server does
  222. // not accept it, it must be fully skipped until the Finished message.
  223. for c.phase == discardingEarlyData {
  224. if err := c.readRecord(recordTypeApplicationData); err != nil {
  225. return err
  226. }
  227. // Assume receipt of Finished message (will be checked below).
  228. if c.hand.Len() > 0 {
  229. c.phase = waitingClientFinished
  230. break
  231. }
  232. }
  233. // If the client sends early data followed by a Finished message (but
  234. // no end_of_early_data), the server MUST terminate the connection.
  235. if c.phase != waitingClientFinished {
  236. c.sendAlert(alertUnexpectedMessage)
  237. return errors.New("tls: did not expect Client Finished yet")
  238. }
  239. c.phase = readingClientFinished
  240. msg, err := c.readHandshake()
  241. if err != nil {
  242. return err
  243. }
  244. clientFinished, ok := msg.(*finishedMsg)
  245. if !ok {
  246. c.sendAlert(alertUnexpectedMessage)
  247. return unexpectedMessageError(clientFinished, msg)
  248. }
  249. hash := hashForSuite(hs.suite)
  250. expectedVerifyData := hmacOfSum(hash, hs.keySchedule.transcriptHash, hs.clientFinishedKey)
  251. if len(expectedVerifyData) != len(clientFinished.verifyData) ||
  252. subtle.ConstantTimeCompare(expectedVerifyData, clientFinished.verifyData) != 1 {
  253. c.sendAlert(alertDecryptError)
  254. return errors.New("tls: client's Finished message is incorrect")
  255. }
  256. hs.keySchedule.write(clientFinished.marshal())
  257. c.hs = nil // Discard the server handshake state
  258. if c.hand.Len() > 0 {
  259. return c.sendAlert(alertUnexpectedMessage)
  260. }
  261. c.in.setCipher(c.vers, hs.appClientCipher)
  262. c.in.traceErr, c.out.traceErr = nil, nil
  263. c.phase = handshakeConfirmed
  264. atomic.StoreInt32(&c.handshakeConfirmed, 1)
  265. // Any read operation after handshakeRunning and before handshakeConfirmed
  266. // will be holding this lock, which we release as soon as the confirmation
  267. // happens, even if the Read call might do more work.
  268. // If a Handshake is pending, c.confirmMutex will never be locked as
  269. // ConfirmHandshake will wait for the handshake to complete. If a
  270. // handshake was complete, and this was a confirmation, unlock
  271. // c.confirmMutex now to allow readers to proceed.
  272. if hasConfirmLock {
  273. c.confirmMutex.Unlock()
  274. }
  275. return hs.sendSessionTicket13() // TODO: do in a goroutine
  276. }
  277. func (hs *serverHandshakeState) sendCertificate13() error {
  278. c := hs.c
  279. certEntries := []certificateEntry{}
  280. for _, cert := range hs.cert.Certificate {
  281. certEntries = append(certEntries, certificateEntry{data: cert})
  282. }
  283. if len(certEntries) > 0 && hs.clientHello.ocspStapling {
  284. certEntries[0].ocspStaple = hs.cert.OCSPStaple
  285. }
  286. if len(certEntries) > 0 && hs.clientHello.scts {
  287. certEntries[0].sctList = hs.cert.SignedCertificateTimestamps
  288. }
  289. certMsg := &certificateMsg13{certificates: certEntries}
  290. hs.keySchedule.write(certMsg.marshal())
  291. if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
  292. return err
  293. }
  294. sigScheme, err := hs.selectTLS13SignatureScheme()
  295. if err != nil {
  296. c.sendAlert(alertInternalError)
  297. return err
  298. }
  299. sigHash := hashForSignatureScheme(sigScheme)
  300. opts := crypto.SignerOpts(sigHash)
  301. if signatureSchemeIsPSS(sigScheme) {
  302. opts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
  303. }
  304. toSign := prepareDigitallySigned(sigHash, "TLS 1.3, server CertificateVerify", hs.keySchedule.transcriptHash.Sum(nil))
  305. signature, err := hs.cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), toSign[:], opts)
  306. if err != nil {
  307. c.sendAlert(alertInternalError)
  308. return err
  309. }
  310. verifyMsg := &certificateVerifyMsg{
  311. hasSignatureAndHash: true,
  312. signatureAlgorithm: sigScheme,
  313. signature: signature,
  314. }
  315. hs.keySchedule.write(verifyMsg.marshal())
  316. if _, err := c.writeRecord(recordTypeHandshake, verifyMsg.marshal()); err != nil {
  317. return err
  318. }
  319. return nil
  320. }
  321. func (c *Conn) handleEndOfEarlyData() {
  322. if c.phase != readingEarlyData || c.vers < VersionTLS13 {
  323. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  324. return
  325. }
  326. c.phase = waitingClientFinished
  327. if c.hand.Len() > 0 {
  328. c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  329. return
  330. }
  331. c.in.setCipher(c.vers, c.hs.hsClientCipher)
  332. }
  333. // selectTLS13SignatureScheme chooses the SignatureScheme for the CertificateVerify
  334. // based on the certificate type and client supported schemes. If no overlap is found,
  335. // a fallback is selected.
  336. //
  337. // See https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.4.1.2
  338. func (hs *serverHandshakeState) selectTLS13SignatureScheme() (sigScheme SignatureScheme, err error) {
  339. var supportedSchemes []SignatureScheme
  340. signer, ok := hs.cert.PrivateKey.(crypto.Signer)
  341. if !ok {
  342. return 0, errors.New("tls: certificate private key does not implement crypto.Signer")
  343. }
  344. pk := signer.Public()
  345. if _, ok := pk.(*rsa.PublicKey); ok {
  346. sigScheme = PSSWithSHA256
  347. supportedSchemes = []SignatureScheme{PSSWithSHA256, PSSWithSHA384, PSSWithSHA512}
  348. } else if pk, ok := pk.(*ecdsa.PublicKey); ok {
  349. switch pk.Curve {
  350. case elliptic.P256():
  351. sigScheme = ECDSAWithP256AndSHA256
  352. supportedSchemes = []SignatureScheme{ECDSAWithP256AndSHA256}
  353. case elliptic.P384():
  354. sigScheme = ECDSAWithP384AndSHA384
  355. supportedSchemes = []SignatureScheme{ECDSAWithP384AndSHA384}
  356. case elliptic.P521():
  357. sigScheme = ECDSAWithP521AndSHA512
  358. supportedSchemes = []SignatureScheme{ECDSAWithP521AndSHA512}
  359. default:
  360. return 0, errors.New("tls: unknown ECDSA certificate curve")
  361. }
  362. } else {
  363. return 0, errors.New("tls: unknown certificate key type")
  364. }
  365. for _, ss := range supportedSchemes {
  366. for _, cs := range hs.clientHello.supportedSignatureAlgorithms {
  367. if ss == cs {
  368. return ss, nil
  369. }
  370. }
  371. }
  372. return sigScheme, nil
  373. }
  374. func signatureSchemeIsPSS(s SignatureScheme) bool {
  375. return s == PSSWithSHA256 || s == PSSWithSHA384 || s == PSSWithSHA512
  376. }
  377. // hashForSignatureScheme returns the Hash used by a SignatureScheme which is
  378. // supported by selectTLS13SignatureScheme.
  379. func hashForSignatureScheme(ss SignatureScheme) crypto.Hash {
  380. switch ss {
  381. case PSSWithSHA256, ECDSAWithP256AndSHA256:
  382. return crypto.SHA256
  383. case PSSWithSHA384, ECDSAWithP384AndSHA384:
  384. return crypto.SHA384
  385. case PSSWithSHA512, ECDSAWithP521AndSHA512:
  386. return crypto.SHA512
  387. default:
  388. panic("unsupported SignatureScheme passed to hashForSignatureScheme")
  389. }
  390. }
  391. func hashForSuite(suite *cipherSuite) crypto.Hash {
  392. if suite.flags&suiteSHA384 != 0 {
  393. return crypto.SHA384
  394. }
  395. return crypto.SHA256
  396. }
  397. func prepareDigitallySigned(hash crypto.Hash, context string, data []byte) []byte {
  398. message := bytes.Repeat([]byte{32}, 64)
  399. message = append(message, context...)
  400. message = append(message, 0)
  401. message = append(message, data...)
  402. h := hash.New()
  403. h.Write(message)
  404. return h.Sum(nil)
  405. }
  406. func (c *Config) generateKeyShare(curveID CurveID) ([]byte, keyShare, error) {
  407. if curveID == X25519 {
  408. var scalar, public [32]byte
  409. if _, err := io.ReadFull(c.rand(), scalar[:]); err != nil {
  410. return nil, keyShare{}, err
  411. }
  412. curve25519.ScalarBaseMult(&public, &scalar)
  413. return scalar[:], keyShare{group: curveID, data: public[:]}, nil
  414. }
  415. curve, ok := curveForCurveID(curveID)
  416. if !ok {
  417. return nil, keyShare{}, errors.New("tls: preferredCurves includes unsupported curve")
  418. }
  419. privateKey, x, y, err := elliptic.GenerateKey(curve, c.rand())
  420. if err != nil {
  421. return nil, keyShare{}, err
  422. }
  423. ecdhePublic := elliptic.Marshal(curve, x, y)
  424. return privateKey, keyShare{group: curveID, data: ecdhePublic}, nil
  425. }
  426. func deriveECDHESecret(ks keyShare, secretKey []byte) []byte {
  427. if ks.group == X25519 {
  428. if len(ks.data) != 32 {
  429. return nil
  430. }
  431. var theirPublic, sharedKey, scalar [32]byte
  432. copy(theirPublic[:], ks.data)
  433. copy(scalar[:], secretKey)
  434. curve25519.ScalarMult(&sharedKey, &scalar, &theirPublic)
  435. return sharedKey[:]
  436. }
  437. curve, ok := curveForCurveID(ks.group)
  438. if !ok {
  439. return nil
  440. }
  441. x, y := elliptic.Unmarshal(curve, ks.data)
  442. if x == nil {
  443. return nil
  444. }
  445. x, _ = curve.ScalarMult(x, y, secretKey)
  446. xBytes := x.Bytes()
  447. curveSize := (curve.Params().BitSize + 8 - 1) >> 3
  448. if len(xBytes) == curveSize {
  449. return xBytes
  450. }
  451. buf := make([]byte, curveSize)
  452. copy(buf[len(buf)-len(xBytes):], xBytes)
  453. return buf
  454. }
  455. func hkdfExpandLabel(hash crypto.Hash, secret, hashValue []byte, label string, L int) []byte {
  456. hkdfLabel := make([]byte, 4+len("TLS 1.3, ")+len(label)+len(hashValue))
  457. hkdfLabel[0] = byte(L >> 8)
  458. hkdfLabel[1] = byte(L)
  459. hkdfLabel[2] = byte(len("TLS 1.3, ") + len(label))
  460. copy(hkdfLabel[3:], "TLS 1.3, ")
  461. z := hkdfLabel[3+len("TLS 1.3, "):]
  462. copy(z, label)
  463. z = z[len(label):]
  464. z[0] = byte(len(hashValue))
  465. copy(z[1:], hashValue)
  466. return hkdfExpand(hash, secret, hkdfLabel, L)
  467. }
  468. func hmacOfSum(f crypto.Hash, hash hash.Hash, key []byte) []byte {
  469. h := hmac.New(f.New, key)
  470. h.Write(hash.Sum(nil))
  471. return h.Sum(nil)
  472. }
  473. // Maximum allowed mismatch between the stated age of a ticket
  474. // and the server-observed one. See
  475. // https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.8.2.
  476. const ticketAgeSkewAllowance = 10 * time.Second
  477. // checkPSK tries to resume using a PSK, returning true (and updating the
  478. // early secret in the key schedule) if the PSK was used and false otherwise.
  479. func (hs *serverHandshakeState) checkPSK() (isResumed bool, alert alert) {
  480. if hs.c.config.SessionTicketsDisabled {
  481. return false, alertSuccess
  482. }
  483. foundDHE := false
  484. for _, mode := range hs.clientHello.pskKeyExchangeModes {
  485. if mode == pskDHEKeyExchange {
  486. foundDHE = true
  487. break
  488. }
  489. }
  490. if !foundDHE {
  491. return false, alertSuccess
  492. }
  493. hash := hashForSuite(hs.suite)
  494. hashSize := hash.Size()
  495. for i := range hs.clientHello.psks {
  496. sessionTicket := append([]uint8{}, hs.clientHello.psks[i].identity...)
  497. if hs.c.config.SessionTicketSealer != nil {
  498. var ok bool
  499. sessionTicket, ok = hs.c.config.SessionTicketSealer.Unseal(hs.clientHelloInfo(), sessionTicket)
  500. if !ok {
  501. continue
  502. }
  503. } else {
  504. sessionTicket, _ = hs.c.decryptTicket(sessionTicket)
  505. if sessionTicket == nil {
  506. continue
  507. }
  508. }
  509. s := &sessionState13{}
  510. if s.unmarshal(sessionTicket) != alertSuccess {
  511. continue
  512. }
  513. if s.vers != hs.c.vers {
  514. continue
  515. }
  516. clientAge := time.Duration(hs.clientHello.psks[i].obfTicketAge-s.ageAdd) * time.Millisecond
  517. serverAge := time.Since(time.Unix(int64(s.createdAt), 0))
  518. if clientAge-serverAge > ticketAgeSkewAllowance || clientAge-serverAge < -ticketAgeSkewAllowance {
  519. // XXX: NSS is off spec and sends obfuscated_ticket_age as seconds
  520. clientAge = time.Duration(hs.clientHello.psks[i].obfTicketAge-s.ageAdd) * time.Second
  521. if clientAge-serverAge > ticketAgeSkewAllowance || clientAge-serverAge < -ticketAgeSkewAllowance {
  522. continue
  523. }
  524. }
  525. // This enforces the stricter 0-RTT requirements on all ticket uses.
  526. // The benefit of using PSK+ECDHE without 0-RTT are small enough that
  527. // we can give them up in the edge case of changed suite or ALPN or SNI.
  528. if s.suite != hs.suite.id {
  529. continue
  530. }
  531. if s.alpnProtocol != hs.c.clientProtocol {
  532. continue
  533. }
  534. if s.SNI != hs.c.serverName {
  535. continue
  536. }
  537. hs.keySchedule.setSecret(s.resumptionSecret)
  538. binderKey := hs.keySchedule.deriveSecret(secretResumptionPskBinder)
  539. binderFinishedKey := hkdfExpandLabel(hash, binderKey, nil, "finished", hashSize)
  540. chHash := hash.New()
  541. chHash.Write(hs.clientHello.rawTruncated)
  542. expectedBinder := hmacOfSum(hash, chHash, binderFinishedKey)
  543. if subtle.ConstantTimeCompare(expectedBinder, hs.clientHello.psks[i].binder) != 1 {
  544. return false, alertDecryptError
  545. }
  546. if i == 0 && hs.clientHello.earlyData {
  547. // This is a ticket intended to be used for 0-RTT
  548. if s.maxEarlyDataLen == 0 {
  549. // But we had not tagged it as such.
  550. return false, alertIllegalParameter
  551. }
  552. if hs.c.config.Accept0RTTData {
  553. hs.c.binder = expectedBinder
  554. hs.c.ticketMaxEarlyData = int64(s.maxEarlyDataLen)
  555. hs.hello13Enc.earlyData = true
  556. }
  557. }
  558. hs.hello.psk = true
  559. hs.hello.pskIdentity = uint16(i)
  560. return true, alertSuccess
  561. }
  562. return false, alertSuccess
  563. }
  564. func (hs *serverHandshakeState) sendSessionTicket13() error {
  565. c := hs.c
  566. if c.config.SessionTicketsDisabled {
  567. return nil
  568. }
  569. foundDHE := false
  570. for _, mode := range hs.clientHello.pskKeyExchangeModes {
  571. if mode == pskDHEKeyExchange {
  572. foundDHE = true
  573. break
  574. }
  575. }
  576. if !foundDHE {
  577. return nil
  578. }
  579. resumptionSecret := hs.keySchedule.deriveSecret(secretResumption)
  580. ageAddBuf := make([]byte, 4)
  581. sessionState := &sessionState13{
  582. vers: c.vers,
  583. suite: hs.suite.id,
  584. createdAt: uint64(time.Now().Unix()),
  585. resumptionSecret: resumptionSecret,
  586. alpnProtocol: c.clientProtocol,
  587. SNI: c.serverName,
  588. maxEarlyDataLen: c.config.Max0RTTDataSize,
  589. }
  590. for i := 0; i < numSessionTickets; i++ {
  591. if _, err := io.ReadFull(c.config.rand(), ageAddBuf); err != nil {
  592. c.sendAlert(alertInternalError)
  593. return err
  594. }
  595. sessionState.ageAdd = uint32(ageAddBuf[0])<<24 | uint32(ageAddBuf[1])<<16 |
  596. uint32(ageAddBuf[2])<<8 | uint32(ageAddBuf[3])
  597. ticket := sessionState.marshal()
  598. var err error
  599. if c.config.SessionTicketSealer != nil {
  600. cs := c.ConnectionState()
  601. ticket, err = c.config.SessionTicketSealer.Seal(&cs, ticket)
  602. } else {
  603. ticket, err = c.encryptTicket(ticket)
  604. }
  605. if err != nil {
  606. c.sendAlert(alertInternalError)
  607. return err
  608. }
  609. if ticket == nil {
  610. continue
  611. }
  612. ticketMsg := &newSessionTicketMsg13{
  613. lifetime: 24 * 3600, // TODO(filippo)
  614. maxEarlyDataLength: c.config.Max0RTTDataSize,
  615. withEarlyDataInfo: c.config.Max0RTTDataSize > 0,
  616. ageAdd: sessionState.ageAdd,
  617. ticket: ticket,
  618. }
  619. if _, err := c.writeRecord(recordTypeHandshake, ticketMsg.marshal()); err != nil {
  620. return err
  621. }
  622. }
  623. return nil
  624. }
  625. func (hs *serverHandshakeState) traceErr(err error) {
  626. if err == nil {
  627. return
  628. }
  629. if os.Getenv("TLSDEBUG") == "error" {
  630. if hs != nil && hs.clientHello != nil {
  631. os.Stderr.WriteString(hex.Dump(hs.clientHello.marshal()))
  632. } else if err == io.EOF {
  633. return // don't stack trace on EOF before CH
  634. }
  635. fmt.Fprintf(os.Stderr, "\n%s\n", debug.Stack())
  636. }
  637. if os.Getenv("TLSDEBUG") == "short" {
  638. var pcs [4]uintptr
  639. frames := runtime.CallersFrames(pcs[0:runtime.Callers(3, pcs[:])])
  640. for {
  641. frame, more := frames.Next()
  642. if frame.Function != "crypto/tls.(*halfConn).setErrorLocked" &&
  643. frame.Function != "crypto/tls.(*Conn).sendAlertLocked" &&
  644. frame.Function != "crypto/tls.(*Conn).sendAlert" {
  645. file := frame.File[strings.LastIndex(frame.File, "/")+1:]
  646. log.Printf("%s:%d (%s): %v", file, frame.Line, frame.Function, err)
  647. return
  648. }
  649. if !more {
  650. break
  651. }
  652. }
  653. }
  654. }