key_schedule.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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. "golang.org/x/crypto/cryptobyte"
  13. "golang.org/x/crypto/hkdf"
  14. "golang.org/x/crypto/sha3"
  15. "github.com/Psiphon-Labs/utls/internal/mlkem768"
  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. // [UTLS SECTION BEGIN]
  110. // The standard crypto/tls library only allows for a single curve to be used.
  111. // We need to support multiple curves to parrot TLS profiles such as Firefox.
  112. //
  113. // type keySharePrivateKeys struct {
  114. // curveID CurveID
  115. // ecdhe *ecdh.PrivateKey
  116. // kyber *mlkem768.DecapsulationKey
  117. // }
  118. type keySharePrivateKeys struct {
  119. ecdhe map[CurveID]*ecdh.PrivateKey
  120. kyber map[CurveID]*mlkem768.DecapsulationKey
  121. }
  122. func NewKeySharePrivateKeys() *keySharePrivateKeys {
  123. return &keySharePrivateKeys{
  124. ecdhe: make(map[CurveID]*ecdh.PrivateKey),
  125. kyber: make(map[CurveID]*mlkem768.DecapsulationKey),
  126. }
  127. }
  128. func (ks *keySharePrivateKeys) getEcdheKey(curveID CurveID) (*ecdh.PrivateKey, error) {
  129. if ks.ecdhe == nil {
  130. return nil, errors.New("tls: keySharePrivateKeys not initialized")
  131. }
  132. return ks.ecdhe[curveID], nil
  133. }
  134. func (ks *keySharePrivateKeys) setEcdheKey(curveID CurveID, key *ecdh.PrivateKey) error {
  135. if ks.ecdhe == nil {
  136. return errors.New("tls: keySharePrivateKeys not initialized")
  137. }
  138. ks.ecdhe[curveID] = key
  139. return nil
  140. }
  141. func (ks *keySharePrivateKeys) getKyberKey(curveID CurveID) (*mlkem768.DecapsulationKey, error) {
  142. if ks.kyber == nil {
  143. return nil, errors.New("tls: keySharePrivateKeys not initialized")
  144. }
  145. return ks.kyber[curveID], nil
  146. }
  147. func (ks *keySharePrivateKeys) setKyberKey(curveID CurveID, key *mlkem768.DecapsulationKey) error {
  148. if ks.kyber == nil {
  149. return errors.New("tls: keySharePrivateKeys not initialized")
  150. }
  151. ks.kyber[curveID] = key
  152. return nil
  153. }
  154. // [UTLS SECTION END]
  155. // kyberDecapsulate implements decapsulation according to Kyber Round 3.
  156. func kyberDecapsulate(dk *mlkem768.DecapsulationKey, c []byte) ([]byte, error) {
  157. K, err := mlkem768.Decapsulate(dk, c)
  158. if err != nil {
  159. return nil, err
  160. }
  161. return kyberSharedSecret(K, c), nil
  162. }
  163. // kyberEncapsulate implements encapsulation according to Kyber Round 3.
  164. func kyberEncapsulate(ek []byte) (c, ss []byte, err error) {
  165. c, ss, err = mlkem768.Encapsulate(ek)
  166. if err != nil {
  167. return nil, nil, err
  168. }
  169. return c, kyberSharedSecret(ss, c), nil
  170. }
  171. func kyberSharedSecret(K, c []byte) []byte {
  172. // Package mlkem768 implements ML-KEM, which compared to Kyber removed a
  173. // final hashing step. Compute SHAKE-256(K || SHA3-256(c), 32) to match Kyber.
  174. // See https://words.filippo.io/mlkem768/#bonus-track-using-a-ml-kem-implementation-as-kyber-v3.
  175. h := sha3.NewShake256()
  176. h.Write(K)
  177. ch := sha3.Sum256(c)
  178. h.Write(ch[:])
  179. out := make([]byte, 32)
  180. h.Read(out)
  181. return out
  182. }
  183. const x25519PublicKeySize = 32
  184. // generateECDHEKey returns a PrivateKey that implements Diffie-Hellman
  185. // according to RFC 8446, Section 4.2.8.2.
  186. func generateECDHEKey(rand io.Reader, curveID CurveID) (*ecdh.PrivateKey, error) {
  187. curve, ok := curveForCurveID(curveID)
  188. if !ok {
  189. return nil, errors.New("tls: internal error: unsupported curve")
  190. }
  191. return curve.GenerateKey(rand)
  192. }
  193. func curveForCurveID(id CurveID) (ecdh.Curve, bool) {
  194. switch id {
  195. case X25519:
  196. return ecdh.X25519(), true
  197. case CurveP256:
  198. return ecdh.P256(), true
  199. case CurveP384:
  200. return ecdh.P384(), true
  201. case CurveP521:
  202. return ecdh.P521(), true
  203. default:
  204. return nil, false
  205. }
  206. }
  207. func curveIDForCurve(curve ecdh.Curve) (CurveID, bool) {
  208. switch curve {
  209. case ecdh.X25519():
  210. return X25519, true
  211. case ecdh.P256():
  212. return CurveP256, true
  213. case ecdh.P384():
  214. return CurveP384, true
  215. case ecdh.P521():
  216. return CurveP521, true
  217. default:
  218. return 0, false
  219. }
  220. }