25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

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