Alternative TLS implementation in Go
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1164 rivejä
35 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. // middlebox compatibility mode: send CCS after first handshake message
  177. if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
  178. return err
  179. }
  180. hs.keySchedule.setSecret(ecdheSecret)
  181. clientCipher, cTrafficSecret := hs.keySchedule.prepareCipher(secretHandshakeClient)
  182. hs.hsClientCipher = clientCipher
  183. serverCipher, sTrafficSecret := hs.keySchedule.prepareCipher(secretHandshakeServer)
  184. c.out.setCipher(c.vers, serverCipher)
  185. serverFinishedKey := hkdfExpandLabel(hash, sTrafficSecret, nil, "finished", hashSize)
  186. hs.clientFinishedKey = hkdfExpandLabel(hash, cTrafficSecret, nil, "finished", hashSize)
  187. // EncryptedExtensions
  188. hs.keySchedule.write(hs.hello13Enc.marshal())
  189. if _, err := c.writeRecord(recordTypeHandshake, hs.hello13Enc.marshal()); err != nil {
  190. return err
  191. }
  192. // TODO: we should have 2 separated methods - one for full-handshake and the other for PSK-handshake
  193. if !c.didResume {
  194. // Server MUST NOT send CertificateRequest if authenticating with PSK
  195. if c.config.ClientAuth >= RequestClientCert {
  196. certReq := new(certificateRequestMsg13)
  197. // extension 'signature_algorithms' MUST be specified
  198. certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms13
  199. certReq.supportedSignatureAlgorithmsCert = supportedSigAlgorithmsCert(supportedSignatureAlgorithms13)
  200. hs.keySchedule.write(certReq.marshal())
  201. if _, err := hs.c.writeRecord(recordTypeHandshake, certReq.marshal()); err != nil {
  202. return err
  203. }
  204. }
  205. if err := hs.sendCertificate13(); err != nil {
  206. return err
  207. }
  208. }
  209. verifyData := hmacOfSum(hash, hs.keySchedule.transcriptHash, serverFinishedKey)
  210. serverFinished := &finishedMsg{
  211. verifyData: verifyData,
  212. }
  213. hs.keySchedule.write(serverFinished.marshal())
  214. if _, err := c.writeRecord(recordTypeHandshake, serverFinished.marshal()); err != nil {
  215. return err
  216. }
  217. hs.keySchedule.setSecret(nil) // derive master secret
  218. hs.appClientCipher, _ = hs.keySchedule.prepareCipher(secretApplicationClient)
  219. serverCipher, _ = hs.keySchedule.prepareCipher(secretApplicationServer)
  220. c.out.setCipher(c.vers, serverCipher)
  221. if c.hand.Len() > 0 {
  222. return c.sendAlert(alertUnexpectedMessage)
  223. }
  224. if hs.hello13Enc.earlyData {
  225. c.in.setCipher(c.vers, earlyClientCipher)
  226. c.phase = readingEarlyData
  227. } else if hs.clientHello.earlyData {
  228. c.in.setCipher(c.vers, hs.hsClientCipher)
  229. c.phase = discardingEarlyData
  230. } else {
  231. c.in.setCipher(c.vers, hs.hsClientCipher)
  232. c.phase = waitingClientFinished
  233. }
  234. return nil
  235. }
  236. // readClientFinished13 is called during the server handshake (when no early
  237. // data it available) or after reading all early data. It discards early data if
  238. // the server did not accept it and then verifies the Finished message. Once
  239. // done it sends the session tickets. Under c.in lock.
  240. func (hs *serverHandshakeState) readClientFinished13(hasConfirmLock bool) error {
  241. c := hs.c
  242. // If the client advertised and sends early data while the server does
  243. // not accept it, it must be fully skipped until the Finished message.
  244. for c.phase == discardingEarlyData {
  245. if err := c.readRecord(recordTypeApplicationData); err != nil {
  246. return err
  247. }
  248. // Assume receipt of Finished message (will be checked below).
  249. if c.hand.Len() > 0 {
  250. c.phase = waitingClientFinished
  251. break
  252. }
  253. }
  254. // If the client sends early data followed by a Finished message (but
  255. // no end_of_early_data), the server MUST terminate the connection.
  256. if c.phase != waitingClientFinished {
  257. c.sendAlert(alertUnexpectedMessage)
  258. return errors.New("tls: did not expect Client Finished yet")
  259. }
  260. c.phase = readingClientFinished
  261. msg, err := c.readHandshake()
  262. if err != nil {
  263. return err
  264. }
  265. // client authentication
  266. if certMsg, ok := msg.(*certificateMsg13); ok {
  267. // (4.4.2) Client MUST send certificate msg if requested by server
  268. if c.config.ClientAuth < RequestClientCert {
  269. c.sendAlert(alertUnexpectedMessage)
  270. return unexpectedMessageError(certMsg, msg)
  271. }
  272. hs.keySchedule.write(certMsg.marshal())
  273. certs := getCertsFromEntries(certMsg.certificates)
  274. pubKey, err := hs.processCertsFromClient(certs)
  275. if err != nil {
  276. return err
  277. }
  278. // 4.4.3: CertificateVerify MUST appear immediately after Certificate msg
  279. msg, err = c.readHandshake()
  280. if err != nil {
  281. return err
  282. }
  283. certVerify, ok := msg.(*certificateVerifyMsg)
  284. if !ok {
  285. c.sendAlert(alertUnexpectedMessage)
  286. return unexpectedMessageError(certVerify, msg)
  287. }
  288. err, alertCode := verifyPeerHandshakeSignature(
  289. certVerify,
  290. pubKey,
  291. supportedSignatureAlgorithms13,
  292. hs.keySchedule.transcriptHash.Sum(nil),
  293. "TLS 1.3, client CertificateVerify")
  294. if err != nil {
  295. c.sendAlert(alertCode)
  296. return err
  297. }
  298. hs.keySchedule.write(certVerify.marshal())
  299. // Read next chunk
  300. msg, err = c.readHandshake()
  301. if err != nil {
  302. return err
  303. }
  304. } else if (c.config.ClientAuth >= RequestClientCert) && !c.didResume {
  305. c.sendAlert(alertCertificateRequired)
  306. return unexpectedMessageError(certMsg, msg)
  307. }
  308. clientFinished, ok := msg.(*finishedMsg)
  309. if !ok {
  310. c.sendAlert(alertUnexpectedMessage)
  311. return unexpectedMessageError(clientFinished, msg)
  312. }
  313. hash := hashForSuite(hs.suite)
  314. expectedVerifyData := hmacOfSum(hash, hs.keySchedule.transcriptHash, hs.clientFinishedKey)
  315. if len(expectedVerifyData) != len(clientFinished.verifyData) ||
  316. subtle.ConstantTimeCompare(expectedVerifyData, clientFinished.verifyData) != 1 {
  317. c.sendAlert(alertDecryptError)
  318. return errors.New("tls: client's Finished message is incorrect")
  319. }
  320. hs.keySchedule.write(clientFinished.marshal())
  321. c.hs = nil // Discard the server handshake state
  322. if c.hand.Len() > 0 {
  323. return c.sendAlert(alertUnexpectedMessage)
  324. }
  325. c.in.setCipher(c.vers, hs.appClientCipher)
  326. c.in.traceErr, c.out.traceErr = nil, nil
  327. c.phase = handshakeConfirmed
  328. atomic.StoreInt32(&c.handshakeConfirmed, 1)
  329. // Any read operation after handshakeRunning and before handshakeConfirmed
  330. // will be holding this lock, which we release as soon as the confirmation
  331. // happens, even if the Read call might do more work.
  332. // If a Handshake is pending, c.confirmMutex will never be locked as
  333. // ConfirmHandshake will wait for the handshake to complete. If a
  334. // handshake was complete, and this was a confirmation, unlock
  335. // c.confirmMutex now to allow readers to proceed.
  336. if hasConfirmLock {
  337. c.confirmMutex.Unlock()
  338. }
  339. return hs.sendSessionTicket13() // TODO: do in a goroutine
  340. }
  341. func (hs *serverHandshakeState) sendCertificate13() error {
  342. c := hs.c
  343. certEntries := []certificateEntry{}
  344. for _, cert := range hs.cert.Certificate {
  345. certEntries = append(certEntries, certificateEntry{data: cert})
  346. }
  347. if len(certEntries) > 0 && hs.clientHello.ocspStapling {
  348. certEntries[0].ocspStaple = hs.cert.OCSPStaple
  349. }
  350. if len(certEntries) > 0 && hs.clientHello.scts {
  351. certEntries[0].sctList = hs.cert.SignedCertificateTimestamps
  352. }
  353. // If hs.delegatedCredential is set (see hs.readClientHello()) then the
  354. // server is using the delegated credential extension. The DC is added as an
  355. // extension to the end-entity certificate, i.e., the last CertificateEntry
  356. // of Certificate.certficate_list. (For details, see
  357. // https://tools.ietf.org/html/draft-ietf-tls-subcerts-02.)
  358. if len(certEntries) > 0 && hs.clientHello.delegatedCredential && hs.delegatedCredential != nil {
  359. certEntries[0].delegatedCredential = hs.delegatedCredential
  360. }
  361. certMsg := &certificateMsg13{certificates: certEntries}
  362. hs.keySchedule.write(certMsg.marshal())
  363. if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
  364. return err
  365. }
  366. sigScheme, err := hs.selectTLS13SignatureScheme()
  367. if err != nil {
  368. c.sendAlert(alertInternalError)
  369. return err
  370. }
  371. sigHash := hashForSignatureScheme(sigScheme)
  372. opts := crypto.SignerOpts(sigHash)
  373. if signatureSchemeIsPSS(sigScheme) {
  374. opts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash}
  375. }
  376. toSign := prepareDigitallySigned(sigHash, "TLS 1.3, server CertificateVerify", hs.keySchedule.transcriptHash.Sum(nil))
  377. signature, err := hs.privateKey.(crypto.Signer).Sign(c.config.rand(), toSign[:], opts)
  378. if err != nil {
  379. c.sendAlert(alertInternalError)
  380. return err
  381. }
  382. verifyMsg := &certificateVerifyMsg{
  383. hasSignatureAndHash: true,
  384. signatureAlgorithm: sigScheme,
  385. signature: signature,
  386. }
  387. hs.keySchedule.write(verifyMsg.marshal())
  388. if _, err := c.writeRecord(recordTypeHandshake, verifyMsg.marshal()); err != nil {
  389. return err
  390. }
  391. return nil
  392. }
  393. func (c *Conn) handleEndOfEarlyData() error {
  394. if c.phase != readingEarlyData || c.vers < VersionTLS13 {
  395. return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  396. }
  397. msg, err := c.readHandshake()
  398. if err != nil {
  399. return err
  400. }
  401. endOfEarlyData, ok := msg.(*endOfEarlyDataMsg)
  402. // No handshake messages are allowed after EOD.
  403. if !ok || c.hand.Len() > 0 {
  404. return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage))
  405. }
  406. c.hs.keySchedule.write(endOfEarlyData.marshal())
  407. c.phase = waitingClientFinished
  408. c.in.setCipher(c.vers, c.hs.hsClientCipher)
  409. return nil
  410. }
  411. // selectTLS13SignatureScheme chooses the SignatureScheme for the CertificateVerify
  412. // based on the certificate type and client supported schemes. If no overlap is found,
  413. // a fallback is selected.
  414. //
  415. // See https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.4.1.2
  416. func (hs *serverHandshakeState) selectTLS13SignatureScheme() (sigScheme SignatureScheme, err error) {
  417. var supportedSchemes []SignatureScheme
  418. signer, ok := hs.privateKey.(crypto.Signer)
  419. if !ok {
  420. return 0, errors.New("tls: private key does not implement crypto.Signer")
  421. }
  422. pk := signer.Public()
  423. if _, ok := pk.(*rsa.PublicKey); ok {
  424. sigScheme = PSSWithSHA256
  425. supportedSchemes = []SignatureScheme{PSSWithSHA256, PSSWithSHA384, PSSWithSHA512}
  426. } else if pk, ok := pk.(*ecdsa.PublicKey); ok {
  427. switch pk.Curve {
  428. case elliptic.P256():
  429. sigScheme = ECDSAWithP256AndSHA256
  430. supportedSchemes = []SignatureScheme{ECDSAWithP256AndSHA256}
  431. case elliptic.P384():
  432. sigScheme = ECDSAWithP384AndSHA384
  433. supportedSchemes = []SignatureScheme{ECDSAWithP384AndSHA384}
  434. case elliptic.P521():
  435. sigScheme = ECDSAWithP521AndSHA512
  436. supportedSchemes = []SignatureScheme{ECDSAWithP521AndSHA512}
  437. default:
  438. return 0, errors.New("tls: unknown ECDSA certificate curve")
  439. }
  440. } else {
  441. return 0, errors.New("tls: unknown certificate key type")
  442. }
  443. for _, ss := range supportedSchemes {
  444. for _, cs := range hs.clientHello.supportedSignatureAlgorithms {
  445. if ss == cs {
  446. return ss, nil
  447. }
  448. }
  449. }
  450. return sigScheme, nil
  451. }
  452. func signatureSchemeIsPSS(s SignatureScheme) bool {
  453. return s == PSSWithSHA256 || s == PSSWithSHA384 || s == PSSWithSHA512
  454. }
  455. // hashForSignatureScheme returns the Hash used by a SignatureScheme which is
  456. // supported by selectTLS13SignatureScheme.
  457. func hashForSignatureScheme(ss SignatureScheme) crypto.Hash {
  458. switch ss {
  459. case PSSWithSHA256, ECDSAWithP256AndSHA256:
  460. return crypto.SHA256
  461. case PSSWithSHA384, ECDSAWithP384AndSHA384:
  462. return crypto.SHA384
  463. case PSSWithSHA512, ECDSAWithP521AndSHA512:
  464. return crypto.SHA512
  465. default:
  466. panic("unsupported SignatureScheme passed to hashForSignatureScheme")
  467. }
  468. }
  469. func hashForSuite(suite *cipherSuite) crypto.Hash {
  470. if suite.flags&suiteSHA384 != 0 {
  471. return crypto.SHA384
  472. }
  473. return crypto.SHA256
  474. }
  475. func prepareDigitallySigned(hash crypto.Hash, context string, data []byte) []byte {
  476. message := bytes.Repeat([]byte{32}, 64)
  477. message = append(message, context...)
  478. message = append(message, 0)
  479. message = append(message, data...)
  480. h := hash.New()
  481. h.Write(message)
  482. return h.Sum(nil)
  483. }
  484. func (c *Config) generateKeyShare(curveID CurveID) ([]byte, keyShare, error) {
  485. if curveID == X25519 {
  486. var scalar, public [32]byte
  487. if _, err := io.ReadFull(c.rand(), scalar[:]); err != nil {
  488. return nil, keyShare{}, err
  489. }
  490. curve25519.ScalarBaseMult(&public, &scalar)
  491. return scalar[:], keyShare{group: curveID, data: public[:]}, nil
  492. }
  493. curve, ok := curveForCurveID(curveID)
  494. if !ok {
  495. return nil, keyShare{}, errors.New("tls: preferredCurves includes unsupported curve")
  496. }
  497. privateKey, x, y, err := elliptic.GenerateKey(curve, c.rand())
  498. if err != nil {
  499. return nil, keyShare{}, err
  500. }
  501. ecdhePublic := elliptic.Marshal(curve, x, y)
  502. return privateKey, keyShare{group: curveID, data: ecdhePublic}, nil
  503. }
  504. func deriveECDHESecret(ks keyShare, secretKey []byte) []byte {
  505. if ks.group == X25519 {
  506. if len(ks.data) != 32 {
  507. return nil
  508. }
  509. var theirPublic, sharedKey, scalar [32]byte
  510. copy(theirPublic[:], ks.data)
  511. copy(scalar[:], secretKey)
  512. curve25519.ScalarMult(&sharedKey, &scalar, &theirPublic)
  513. return sharedKey[:]
  514. }
  515. curve, ok := curveForCurveID(ks.group)
  516. if !ok {
  517. return nil
  518. }
  519. x, y := elliptic.Unmarshal(curve, ks.data)
  520. if x == nil {
  521. return nil
  522. }
  523. x, _ = curve.ScalarMult(x, y, secretKey)
  524. xBytes := x.Bytes()
  525. curveSize := (curve.Params().BitSize + 8 - 1) >> 3
  526. if len(xBytes) == curveSize {
  527. return xBytes
  528. }
  529. buf := make([]byte, curveSize)
  530. copy(buf[len(buf)-len(xBytes):], xBytes)
  531. return buf
  532. }
  533. func hkdfExpandLabel(hash crypto.Hash, secret, hashValue []byte, label string, L int) []byte {
  534. prefix := "tls13 "
  535. hkdfLabel := make([]byte, 4+len(prefix)+len(label)+len(hashValue))
  536. hkdfLabel[0] = byte(L >> 8)
  537. hkdfLabel[1] = byte(L)
  538. hkdfLabel[2] = byte(len(prefix) + len(label))
  539. copy(hkdfLabel[3:], prefix)
  540. z := hkdfLabel[3+len(prefix):]
  541. copy(z, label)
  542. z = z[len(label):]
  543. z[0] = byte(len(hashValue))
  544. copy(z[1:], hashValue)
  545. return hkdfExpand(hash, secret, hkdfLabel, L)
  546. }
  547. func hmacOfSum(f crypto.Hash, hash hash.Hash, key []byte) []byte {
  548. h := hmac.New(f.New, key)
  549. h.Write(hash.Sum(nil))
  550. return h.Sum(nil)
  551. }
  552. // Maximum allowed mismatch between the stated age of a ticket
  553. // and the server-observed one. See
  554. // https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.8.2.
  555. const ticketAgeSkewAllowance = 10 * time.Second
  556. // checkPSK tries to resume using a PSK, returning true (and updating the
  557. // early secret in the key schedule) if the PSK was used and false otherwise.
  558. func (hs *serverHandshakeState) checkPSK() (isResumed bool, alert alert) {
  559. if hs.c.config.SessionTicketsDisabled {
  560. return false, alertSuccess
  561. }
  562. foundDHE := false
  563. for _, mode := range hs.clientHello.pskKeyExchangeModes {
  564. if mode == pskDHEKeyExchange {
  565. foundDHE = true
  566. break
  567. }
  568. }
  569. if !foundDHE {
  570. return false, alertSuccess
  571. }
  572. hash := hashForSuite(hs.suite)
  573. hashSize := hash.Size()
  574. for i := range hs.clientHello.psks {
  575. sessionTicket := append([]uint8{}, hs.clientHello.psks[i].identity...)
  576. if hs.c.config.SessionTicketSealer != nil {
  577. var ok bool
  578. sessionTicket, ok = hs.c.config.SessionTicketSealer.Unseal(hs.clientHelloInfo(), sessionTicket)
  579. if !ok {
  580. continue
  581. }
  582. } else {
  583. sessionTicket, _ = hs.c.decryptTicket(sessionTicket)
  584. if sessionTicket == nil {
  585. continue
  586. }
  587. }
  588. s := &sessionState13{}
  589. if s.unmarshal(sessionTicket) != alertSuccess {
  590. continue
  591. }
  592. if s.vers != hs.c.vers {
  593. continue
  594. }
  595. clientAge := time.Duration(hs.clientHello.psks[i].obfTicketAge-s.ageAdd) * time.Millisecond
  596. serverAge := time.Since(time.Unix(int64(s.createdAt), 0))
  597. if clientAge-serverAge > ticketAgeSkewAllowance || clientAge-serverAge < -ticketAgeSkewAllowance {
  598. // XXX: NSS is off spec and sends obfuscated_ticket_age as seconds
  599. clientAge = time.Duration(hs.clientHello.psks[i].obfTicketAge-s.ageAdd) * time.Second
  600. if clientAge-serverAge > ticketAgeSkewAllowance || clientAge-serverAge < -ticketAgeSkewAllowance {
  601. continue
  602. }
  603. }
  604. // This enforces the stricter 0-RTT requirements on all ticket uses.
  605. // The benefit of using PSK+ECDHE without 0-RTT are small enough that
  606. // we can give them up in the edge case of changed suite or ALPN or SNI.
  607. if s.suite != hs.suite.id {
  608. continue
  609. }
  610. if s.alpnProtocol != hs.c.clientProtocol {
  611. continue
  612. }
  613. if s.SNI != hs.c.serverName {
  614. continue
  615. }
  616. hs.keySchedule.setSecret(s.pskSecret)
  617. binderKey := hs.keySchedule.deriveSecret(secretResumptionPskBinder)
  618. binderFinishedKey := hkdfExpandLabel(hash, binderKey, nil, "finished", hashSize)
  619. chHash := hash.New()
  620. chHash.Write(hs.clientHello.rawTruncated)
  621. expectedBinder := hmacOfSum(hash, chHash, binderFinishedKey)
  622. if subtle.ConstantTimeCompare(expectedBinder, hs.clientHello.psks[i].binder) != 1 {
  623. return false, alertDecryptError
  624. }
  625. if i == 0 && hs.clientHello.earlyData {
  626. // This is a ticket intended to be used for 0-RTT
  627. if s.maxEarlyDataLen == 0 {
  628. // But we had not tagged it as such.
  629. return false, alertIllegalParameter
  630. }
  631. if hs.c.config.Accept0RTTData {
  632. hs.c.binder = expectedBinder
  633. hs.c.ticketMaxEarlyData = int64(s.maxEarlyDataLen)
  634. hs.hello13Enc.earlyData = true
  635. }
  636. }
  637. hs.hello.psk = true
  638. hs.hello.pskIdentity = uint16(i)
  639. return true, alertSuccess
  640. }
  641. return false, alertSuccess
  642. }
  643. func (hs *serverHandshakeState) sendSessionTicket13() error {
  644. c := hs.c
  645. if c.config.SessionTicketsDisabled {
  646. return nil
  647. }
  648. foundDHE := false
  649. for _, mode := range hs.clientHello.pskKeyExchangeModes {
  650. if mode == pskDHEKeyExchange {
  651. foundDHE = true
  652. break
  653. }
  654. }
  655. if !foundDHE {
  656. return nil
  657. }
  658. resumptionMasterSecret := hs.keySchedule.deriveSecret(secretResumption)
  659. ageAddBuf := make([]byte, 4)
  660. sessionState := &sessionState13{
  661. vers: c.vers,
  662. suite: hs.suite.id,
  663. createdAt: uint64(time.Now().Unix()),
  664. alpnProtocol: c.clientProtocol,
  665. SNI: c.serverName,
  666. maxEarlyDataLen: c.config.Max0RTTDataSize,
  667. }
  668. hash := hashForSuite(hs.suite)
  669. for i := 0; i < numSessionTickets; i++ {
  670. if _, err := io.ReadFull(c.config.rand(), ageAddBuf); err != nil {
  671. c.sendAlert(alertInternalError)
  672. return err
  673. }
  674. sessionState.ageAdd = uint32(ageAddBuf[0])<<24 | uint32(ageAddBuf[1])<<16 |
  675. uint32(ageAddBuf[2])<<8 | uint32(ageAddBuf[3])
  676. // ticketNonce must be a unique value for this connection.
  677. // Assume there are no more than 255 tickets, otherwise two
  678. // tickets might have the same PSK which could be a problem if
  679. // one of them is compromised.
  680. ticketNonce := []byte{byte(i)}
  681. sessionState.pskSecret = hkdfExpandLabel(hash, resumptionMasterSecret, ticketNonce, "resumption", hash.Size())
  682. ticket := sessionState.marshal()
  683. var err error
  684. if c.config.SessionTicketSealer != nil {
  685. cs := c.ConnectionState()
  686. ticket, err = c.config.SessionTicketSealer.Seal(&cs, ticket)
  687. } else {
  688. ticket, err = c.encryptTicket(ticket)
  689. }
  690. if err != nil {
  691. c.sendAlert(alertInternalError)
  692. return err
  693. }
  694. if ticket == nil {
  695. continue
  696. }
  697. ticketMsg := &newSessionTicketMsg13{
  698. lifetime: 24 * 3600, // TODO(filippo)
  699. maxEarlyDataLength: c.config.Max0RTTDataSize,
  700. withEarlyDataInfo: c.config.Max0RTTDataSize > 0,
  701. ageAdd: sessionState.ageAdd,
  702. nonce: ticketNonce,
  703. ticket: ticket,
  704. }
  705. if _, err := c.writeRecord(recordTypeHandshake, ticketMsg.marshal()); err != nil {
  706. return err
  707. }
  708. }
  709. return nil
  710. }
  711. func (hs *serverHandshakeState) traceErr(err error) {
  712. if err == nil {
  713. return
  714. }
  715. if os.Getenv("TLSDEBUG") == "error" {
  716. if hs != nil && hs.clientHello != nil {
  717. os.Stderr.WriteString(hex.Dump(hs.clientHello.marshal()))
  718. } else if err == io.EOF {
  719. return // don't stack trace on EOF before CH
  720. }
  721. fmt.Fprintf(os.Stderr, "\n%s\n", debug.Stack())
  722. }
  723. if os.Getenv("TLSDEBUG") == "short" {
  724. var pcs [4]uintptr
  725. frames := runtime.CallersFrames(pcs[0:runtime.Callers(3, pcs[:])])
  726. for {
  727. frame, more := frames.Next()
  728. if frame.Function != "crypto/tls.(*halfConn).setErrorLocked" &&
  729. frame.Function != "crypto/tls.(*Conn).sendAlertLocked" &&
  730. frame.Function != "crypto/tls.(*Conn).sendAlert" {
  731. file := frame.File[strings.LastIndex(frame.File, "/")+1:]
  732. log.Printf("%s:%d (%s): %v", file, frame.Line, frame.Function, err)
  733. return
  734. }
  735. if !more {
  736. break
  737. }
  738. }
  739. }
  740. }
  741. func getCertsFromEntries(certEntries []certificateEntry) [][]byte {
  742. certs := make([][]byte, len(certEntries))
  743. for i, cert := range certEntries {
  744. certs[i] = cert.data
  745. }
  746. return certs
  747. }
  748. func (hs *clientHandshakeState) processEncryptedExtensions(ee *encryptedExtensionsMsg) error {
  749. c := hs.c
  750. if ee.alpnProtocol != "" {
  751. c.clientProtocol = ee.alpnProtocol
  752. c.clientProtocolFallback = false
  753. }
  754. return nil
  755. }
  756. func verifyPeerHandshakeSignature(
  757. certVerify *certificateVerifyMsg,
  758. pubKey crypto.PublicKey,
  759. signAlgosKnown []SignatureScheme,
  760. transHash []byte,
  761. contextString string) (error, alert) {
  762. _, sigType, hashFunc, err := pickSignatureAlgorithm(
  763. pubKey,
  764. []SignatureScheme{certVerify.signatureAlgorithm},
  765. signAlgosKnown,
  766. VersionTLS13)
  767. if err != nil {
  768. return err, alertHandshakeFailure
  769. }
  770. digest := prepareDigitallySigned(hashFunc, contextString, transHash)
  771. err = verifyHandshakeSignature(sigType, pubKey, hashFunc, digest, certVerify.signature)
  772. if err != nil {
  773. return err, alertDecryptError
  774. }
  775. return nil, alertSuccess
  776. }
  777. func (hs *clientHandshakeState) getCertificate13(certReq *certificateRequestMsg13) (*Certificate, error) {
  778. certReq12 := &certificateRequestMsg{
  779. hasSignatureAndHash: true,
  780. supportedSignatureAlgorithms: certReq.supportedSignatureAlgorithms,
  781. certificateAuthorities: certReq.certificateAuthorities,
  782. }
  783. var rsaAvail, ecdsaAvail bool
  784. for _, sigAlg := range certReq.supportedSignatureAlgorithms {
  785. switch signatureFromSignatureScheme(sigAlg) {
  786. case signaturePKCS1v15, signatureRSAPSS:
  787. rsaAvail = true
  788. case signatureECDSA:
  789. ecdsaAvail = true
  790. }
  791. }
  792. if rsaAvail {
  793. certReq12.certificateTypes = append(certReq12.certificateTypes, certTypeRSASign)
  794. }
  795. if ecdsaAvail {
  796. certReq12.certificateTypes = append(certReq12.certificateTypes, certTypeECDSASign)
  797. }
  798. return hs.getCertificate(certReq12)
  799. }
  800. func (hs *clientHandshakeState) sendCertificate13(chainToSend *Certificate, certReq *certificateRequestMsg13) error {
  801. c := hs.c
  802. certEntries := []certificateEntry{}
  803. for _, cert := range chainToSend.Certificate {
  804. certEntries = append(certEntries, certificateEntry{data: cert})
  805. }
  806. certMsg := &certificateMsg13{certificates: certEntries}
  807. hs.keySchedule.write(certMsg.marshal())
  808. if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
  809. return err
  810. }
  811. if len(certEntries) == 0 {
  812. // No client cert available, nothing to sign.
  813. return nil
  814. }
  815. key, ok := chainToSend.PrivateKey.(crypto.Signer)
  816. if !ok {
  817. c.sendAlert(alertInternalError)
  818. return fmt.Errorf("tls: client certificate private key of type %T does not implement crypto.Signer", chainToSend.PrivateKey)
  819. }
  820. signatureAlgorithm, sigType, hashFunc, err := pickSignatureAlgorithm(key.Public(), certReq.supportedSignatureAlgorithms, hs.hello.supportedSignatureAlgorithms, c.vers)
  821. if err != nil {
  822. hs.c.sendAlert(alertHandshakeFailure)
  823. return err
  824. }
  825. digest := prepareDigitallySigned(hashFunc, "TLS 1.3, client CertificateVerify", hs.keySchedule.transcriptHash.Sum(nil))
  826. signOpts := crypto.SignerOpts(hashFunc)
  827. if sigType == signatureRSAPSS {
  828. signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: hashFunc}
  829. }
  830. signature, err := key.Sign(c.config.rand(), digest, signOpts)
  831. if err != nil {
  832. c.sendAlert(alertInternalError)
  833. return err
  834. }
  835. verifyMsg := &certificateVerifyMsg{
  836. hasSignatureAndHash: true,
  837. signatureAlgorithm: signatureAlgorithm,
  838. signature: signature,
  839. }
  840. hs.keySchedule.write(verifyMsg.marshal())
  841. if _, err := c.writeRecord(recordTypeHandshake, verifyMsg.marshal()); err != nil {
  842. return err
  843. }
  844. return nil
  845. }
  846. func (hs *clientHandshakeState) doTLS13Handshake() error {
  847. c := hs.c
  848. hash := hashForSuite(hs.suite)
  849. hashSize := hash.Size()
  850. serverHello := hs.serverHello
  851. c.scts = serverHello.scts
  852. // middlebox compatibility mode, send CCS before second flight.
  853. if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
  854. return err
  855. }
  856. // TODO check if keyshare is unacceptable, raise HRR.
  857. clientKS := hs.hello.keyShares[0]
  858. if serverHello.keyShare.group != clientKS.group {
  859. c.sendAlert(alertIllegalParameter)
  860. return errors.New("bad or missing key share from server")
  861. }
  862. // 0-RTT is not supported yet, so use an empty PSK.
  863. hs.keySchedule.setSecret(nil)
  864. ecdheSecret := deriveECDHESecret(serverHello.keyShare, hs.privateKey)
  865. if ecdheSecret == nil {
  866. c.sendAlert(alertIllegalParameter)
  867. return errors.New("tls: bad ECDHE server share")
  868. }
  869. // Calculate handshake secrets.
  870. hs.keySchedule.setSecret(ecdheSecret)
  871. clientCipher, clientHandshakeSecret := hs.keySchedule.prepareCipher(secretHandshakeClient)
  872. serverCipher, serverHandshakeSecret := hs.keySchedule.prepareCipher(secretHandshakeServer)
  873. if c.hand.Len() > 0 {
  874. c.sendAlert(alertUnexpectedMessage)
  875. return errors.New("tls: unexpected data after Server Hello")
  876. }
  877. // Do not change the sender key yet, the server must authenticate first.
  878. c.in.setCipher(c.vers, serverCipher)
  879. // Calculate MAC key for Finished messages.
  880. serverFinishedKey := hkdfExpandLabel(hash, serverHandshakeSecret, nil, "finished", hashSize)
  881. clientFinishedKey := hkdfExpandLabel(hash, clientHandshakeSecret, nil, "finished", hashSize)
  882. msg, err := c.readHandshake()
  883. if err != nil {
  884. return err
  885. }
  886. encryptedExtensions, ok := msg.(*encryptedExtensionsMsg)
  887. if !ok {
  888. c.sendAlert(alertUnexpectedMessage)
  889. return unexpectedMessageError(encryptedExtensions, msg)
  890. }
  891. if err := hs.processEncryptedExtensions(encryptedExtensions); err != nil {
  892. return err
  893. }
  894. hs.keySchedule.write(encryptedExtensions.marshal())
  895. // PSKs are not supported, so receive Certificate message.
  896. msg, err = c.readHandshake()
  897. if err != nil {
  898. return err
  899. }
  900. var chainToSend *Certificate
  901. certReq, isCertRequested := msg.(*certificateRequestMsg13)
  902. if isCertRequested {
  903. hs.keySchedule.write(certReq.marshal())
  904. if chainToSend, err = hs.getCertificate13(certReq); err != nil {
  905. c.sendAlert(alertInternalError)
  906. return err
  907. }
  908. msg, err = c.readHandshake()
  909. if err != nil {
  910. return err
  911. }
  912. }
  913. certMsg, ok := msg.(*certificateMsg13)
  914. if !ok {
  915. c.sendAlert(alertUnexpectedMessage)
  916. return unexpectedMessageError(certMsg, msg)
  917. }
  918. hs.keySchedule.write(certMsg.marshal())
  919. // Validate certificates.
  920. certs := getCertsFromEntries(certMsg.certificates)
  921. if err := hs.processCertsFromServer(certs); err != nil {
  922. return err
  923. }
  924. // Receive CertificateVerify message.
  925. msg, err = c.readHandshake()
  926. if err != nil {
  927. return err
  928. }
  929. certVerifyMsg, ok := msg.(*certificateVerifyMsg)
  930. if !ok {
  931. c.sendAlert(alertUnexpectedMessage)
  932. return unexpectedMessageError(certVerifyMsg, msg)
  933. }
  934. // Validate the DC if present. The DC is only processed if the extension was
  935. // indicated by the ClientHello; otherwise this call will result in an
  936. // "illegal_parameter" alert.
  937. if len(certMsg.certificates) > 0 {
  938. if err := hs.processDelegatedCredentialFromServer(
  939. certMsg.certificates[0].delegatedCredential,
  940. certVerifyMsg.signatureAlgorithm); err != nil {
  941. return err
  942. }
  943. }
  944. // Set the public key used to verify the handshake.
  945. pk := hs.c.peerCertificates[0].PublicKey
  946. // If the delegated credential extension has successfully been negotiated,
  947. // then the CertificateVerify signature will have been produced with the
  948. // DelegatedCredential's private key.
  949. if hs.c.verifiedDc != nil {
  950. pk = hs.c.verifiedDc.cred.publicKey
  951. }
  952. // Verify the handshake signature.
  953. err, alertCode := verifyPeerHandshakeSignature(
  954. certVerifyMsg,
  955. pk,
  956. hs.hello.supportedSignatureAlgorithms,
  957. hs.keySchedule.transcriptHash.Sum(nil),
  958. "TLS 1.3, server CertificateVerify")
  959. if err != nil {
  960. c.sendAlert(alertCode)
  961. return err
  962. }
  963. hs.keySchedule.write(certVerifyMsg.marshal())
  964. // Receive Finished message.
  965. msg, err = c.readHandshake()
  966. if err != nil {
  967. return err
  968. }
  969. serverFinished, ok := msg.(*finishedMsg)
  970. if !ok {
  971. c.sendAlert(alertUnexpectedMessage)
  972. return unexpectedMessageError(serverFinished, msg)
  973. }
  974. // Validate server Finished hash.
  975. expectedVerifyData := hmacOfSum(hash, hs.keySchedule.transcriptHash, serverFinishedKey)
  976. if subtle.ConstantTimeCompare(expectedVerifyData, serverFinished.verifyData) != 1 {
  977. c.sendAlert(alertDecryptError)
  978. return errors.New("tls: server's Finished message is incorrect")
  979. }
  980. hs.keySchedule.write(serverFinished.marshal())
  981. // Server has authenticated itself. Calculate application traffic secrets.
  982. hs.keySchedule.setSecret(nil) // derive master secret
  983. appServerCipher, _ := hs.keySchedule.prepareCipher(secretApplicationServer)
  984. appClientCipher, _ := hs.keySchedule.prepareCipher(secretApplicationClient)
  985. // TODO store initial traffic secret key for KeyUpdate GH #85
  986. // Change outbound handshake cipher for final step
  987. c.out.setCipher(c.vers, clientCipher)
  988. // Client auth requires sending a (possibly empty) Certificate followed
  989. // by a CertificateVerify message (if there was an actual certificate).
  990. if isCertRequested {
  991. if err := hs.sendCertificate13(chainToSend, certReq); err != nil {
  992. return err
  993. }
  994. }
  995. // Send Finished
  996. verifyData := hmacOfSum(hash, hs.keySchedule.transcriptHash, clientFinishedKey)
  997. clientFinished := &finishedMsg{
  998. verifyData: verifyData,
  999. }
  1000. if _, err := c.writeRecord(recordTypeHandshake, clientFinished.marshal()); err != nil {
  1001. return err
  1002. }
  1003. // Handshake done, set application traffic secret
  1004. c.out.setCipher(c.vers, appClientCipher)
  1005. if c.hand.Len() > 0 {
  1006. c.sendAlert(alertUnexpectedMessage)
  1007. return errors.New("tls: unexpected data after handshake")
  1008. }
  1009. c.in.setCipher(c.vers, appServerCipher)
  1010. return nil
  1011. }
  1012. // supportedSigAlgorithmsCert iterates over schemes and filters out those algorithms
  1013. // which are not supported for certificate verification.
  1014. func supportedSigAlgorithmsCert(schemes []SignatureScheme) (ret []SignatureScheme) {
  1015. for _, sig := range schemes {
  1016. // X509 doesn't support PSS signatures
  1017. if !signatureSchemeIsPSS(sig) {
  1018. ret = append(ret, sig)
  1019. }
  1020. }
  1021. return
  1022. }