key_schedule.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. // Copyright 2018 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package tls
  5. import (
  6. "crypto/ecdh"
  7. "crypto/hmac"
  8. "errors"
  9. "fmt"
  10. "hash"
  11. "io"
  12. "github.com/Psiphon-Labs/psiphon-tls/internal/mlkem768"
  13. "golang.org/x/crypto/cryptobyte"
  14. "golang.org/x/crypto/hkdf"
  15. "golang.org/x/crypto/sha3"
  16. )
  17. // This file contains the functions necessary to compute the TLS 1.3 key
  18. // schedule. See RFC 8446, Section 7.
  19. const (
  20. resumptionBinderLabel = "res binder"
  21. clientEarlyTrafficLabel = "c e traffic"
  22. clientHandshakeTrafficLabel = "c hs traffic"
  23. serverHandshakeTrafficLabel = "s hs traffic"
  24. clientApplicationTrafficLabel = "c ap traffic"
  25. serverApplicationTrafficLabel = "s ap traffic"
  26. exporterLabel = "exp master"
  27. resumptionLabel = "res master"
  28. trafficUpdateLabel = "traffic upd"
  29. )
  30. // expandLabel implements HKDF-Expand-Label from RFC 8446, Section 7.1.
  31. func (c *cipherSuiteTLS13) expandLabel(secret []byte, label string, context []byte, length int) []byte {
  32. var hkdfLabel cryptobyte.Builder
  33. hkdfLabel.AddUint16(uint16(length))
  34. hkdfLabel.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {
  35. b.AddBytes([]byte("tls13 "))
  36. b.AddBytes([]byte(label))
  37. })
  38. hkdfLabel.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {
  39. b.AddBytes(context)
  40. })
  41. hkdfLabelBytes, err := hkdfLabel.Bytes()
  42. if err != nil {
  43. // Rather than calling BytesOrPanic, we explicitly handle this error, in
  44. // order to provide a reasonable error message. It should be basically
  45. // impossible for this to panic, and routing errors back through the
  46. // tree rooted in this function is quite painful. The labels are fixed
  47. // size, and the context is either a fixed-length computed hash, or
  48. // parsed from a field which has the same length limitation. As such, an
  49. // error here is likely to only be caused during development.
  50. //
  51. // NOTE: another reasonable approach here might be to return a
  52. // randomized slice if we encounter an error, which would break the
  53. // connection, but avoid panicking. This would perhaps be safer but
  54. // significantly more confusing to users.
  55. panic(fmt.Errorf("failed to construct HKDF label: %s", err))
  56. }
  57. out := make([]byte, length)
  58. n, err := hkdf.Expand(c.hash.New, secret, hkdfLabelBytes).Read(out)
  59. if err != nil || n != length {
  60. panic("tls: HKDF-Expand-Label invocation failed unexpectedly")
  61. }
  62. return out
  63. }
  64. // deriveSecret implements Derive-Secret from RFC 8446, Section 7.1.
  65. func (c *cipherSuiteTLS13) deriveSecret(secret []byte, label string, transcript hash.Hash) []byte {
  66. if transcript == nil {
  67. transcript = c.hash.New()
  68. }
  69. return c.expandLabel(secret, label, transcript.Sum(nil), c.hash.Size())
  70. }
  71. // extract implements HKDF-Extract with the cipher suite hash.
  72. func (c *cipherSuiteTLS13) extract(newSecret, currentSecret []byte) []byte {
  73. if newSecret == nil {
  74. newSecret = make([]byte, c.hash.Size())
  75. }
  76. return hkdf.Extract(c.hash.New, newSecret, currentSecret)
  77. }
  78. // nextTrafficSecret generates the next traffic secret, given the current one,
  79. // according to RFC 8446, Section 7.2.
  80. func (c *cipherSuiteTLS13) nextTrafficSecret(trafficSecret []byte) []byte {
  81. return c.expandLabel(trafficSecret, trafficUpdateLabel, nil, c.hash.Size())
  82. }
  83. // trafficKey generates traffic keys according to RFC 8446, Section 7.3.
  84. func (c *cipherSuiteTLS13) trafficKey(trafficSecret []byte) (key, iv []byte) {
  85. key = c.expandLabel(trafficSecret, "key", nil, c.keyLen)
  86. iv = c.expandLabel(trafficSecret, "iv", nil, aeadNonceLength)
  87. return
  88. }
  89. // finishedHash generates the Finished verify_data or PskBinderEntry according
  90. // to RFC 8446, Section 4.4.4. See sections 4.4 and 4.2.11.2 for the baseKey
  91. // selection.
  92. func (c *cipherSuiteTLS13) finishedHash(baseKey []byte, transcript hash.Hash) []byte {
  93. finishedKey := c.expandLabel(baseKey, "finished", nil, c.hash.Size())
  94. verifyData := hmac.New(c.hash.New, finishedKey)
  95. verifyData.Write(transcript.Sum(nil))
  96. return verifyData.Sum(nil)
  97. }
  98. // exportKeyingMaterial implements RFC5705 exporters for TLS 1.3 according to
  99. // RFC 8446, Section 7.5.
  100. func (c *cipherSuiteTLS13) exportKeyingMaterial(masterSecret []byte, transcript hash.Hash) func(string, []byte, int) ([]byte, error) {
  101. expMasterSecret := c.deriveSecret(masterSecret, exporterLabel, transcript)
  102. return func(label string, context []byte, length int) ([]byte, error) {
  103. secret := c.deriveSecret(expMasterSecret, label, nil)
  104. h := c.hash.New()
  105. h.Write(context)
  106. return c.expandLabel(secret, "exporter", h.Sum(nil), length), nil
  107. }
  108. }
  109. type keySharePrivateKeys struct {
  110. curveID CurveID
  111. ecdhe *ecdh.PrivateKey
  112. kyber *mlkem768.DecapsulationKey
  113. }
  114. // kyberDecapsulate implements decapsulation according to Kyber Round 3.
  115. func kyberDecapsulate(dk *mlkem768.DecapsulationKey, c []byte) ([]byte, error) {
  116. K, err := mlkem768.Decapsulate(dk, c)
  117. if err != nil {
  118. return nil, err
  119. }
  120. return kyberSharedSecret(K, c), nil
  121. }
  122. // kyberEncapsulate implements encapsulation according to Kyber Round 3.
  123. func kyberEncapsulate(ek []byte) (c, ss []byte, err error) {
  124. c, ss, err = mlkem768.Encapsulate(ek)
  125. if err != nil {
  126. return nil, nil, err
  127. }
  128. return c, kyberSharedSecret(ss, c), nil
  129. }
  130. func kyberSharedSecret(K, c []byte) []byte {
  131. // Package mlkem768 implements ML-KEM, which compared to Kyber removed a
  132. // final hashing step. Compute SHAKE-256(K || SHA3-256(c), 32) to match Kyber.
  133. // See https://words.filippo.io/mlkem768/#bonus-track-using-a-ml-kem-implementation-as-kyber-v3.
  134. h := sha3.NewShake256()
  135. h.Write(K)
  136. ch := sha3.Sum256(c)
  137. h.Write(ch[:])
  138. out := make([]byte, 32)
  139. h.Read(out)
  140. return out
  141. }
  142. const x25519PublicKeySize = 32
  143. // generateECDHEKey returns a PrivateKey that implements Diffie-Hellman
  144. // according to RFC 8446, Section 4.2.8.2.
  145. func generateECDHEKey(rand io.Reader, curveID CurveID) (*ecdh.PrivateKey, error) {
  146. curve, ok := curveForCurveID(curveID)
  147. if !ok {
  148. return nil, errors.New("tls: internal error: unsupported curve")
  149. }
  150. return curve.GenerateKey(rand)
  151. }
  152. func curveForCurveID(id CurveID) (ecdh.Curve, bool) {
  153. switch id {
  154. case X25519:
  155. return ecdh.X25519(), true
  156. case CurveP256:
  157. return ecdh.P256(), true
  158. case CurveP384:
  159. return ecdh.P384(), true
  160. case CurveP521:
  161. return ecdh.P521(), true
  162. default:
  163. return nil, false
  164. }
  165. }
  166. func curveIDForCurve(curve ecdh.Curve) (CurveID, bool) {
  167. switch curve {
  168. case ecdh.X25519():
  169. return X25519, true
  170. case ecdh.P256():
  171. return CurveP256, true
  172. case ecdh.P384():
  173. return CurveP384, true
  174. case ecdh.P521():
  175. return CurveP521, true
  176. default:
  177. return 0, false
  178. }
  179. }