key_schedule.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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/elliptic"
  7. "crypto/hmac"
  8. "errors"
  9. "hash"
  10. "io"
  11. "math/big"
  12. "golang.org/x/crypto/cryptobyte"
  13. "golang.org/x/crypto/curve25519"
  14. "golang.org/x/crypto/hkdf"
  15. )
  16. // This file contains the functions necessary to compute the TLS 1.3 key
  17. // schedule. See RFC 8446, Section 7.
  18. const (
  19. resumptionBinderLabel = "res binder"
  20. clientHandshakeTrafficLabel = "c hs traffic"
  21. serverHandshakeTrafficLabel = "s hs traffic"
  22. clientApplicationTrafficLabel = "c ap traffic"
  23. serverApplicationTrafficLabel = "s ap traffic"
  24. exporterLabel = "exp master"
  25. resumptionLabel = "res master"
  26. trafficUpdateLabel = "traffic upd"
  27. )
  28. // expandLabel implements HKDF-Expand-Label from RFC 8446, Section 7.1.
  29. func (c *cipherSuiteTLS13) expandLabel(secret []byte, label string, context []byte, length int) []byte {
  30. var hkdfLabel cryptobyte.Builder
  31. hkdfLabel.AddUint16(uint16(length))
  32. hkdfLabel.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {
  33. b.AddBytes([]byte("tls13 "))
  34. b.AddBytes([]byte(label))
  35. })
  36. hkdfLabel.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {
  37. b.AddBytes(context)
  38. })
  39. out := make([]byte, length)
  40. n, err := hkdf.Expand(c.hash.New, secret, hkdfLabel.BytesOrPanic()).Read(out)
  41. if err != nil || n != length {
  42. panic("tls: HKDF-Expand-Label invocation failed unexpectedly")
  43. }
  44. return out
  45. }
  46. // deriveSecret implements Derive-Secret from RFC 8446, Section 7.1.
  47. func (c *cipherSuiteTLS13) deriveSecret(secret []byte, label string, transcript hash.Hash) []byte {
  48. if transcript == nil {
  49. transcript = c.hash.New()
  50. }
  51. return c.expandLabel(secret, label, transcript.Sum(nil), c.hash.Size())
  52. }
  53. // extract implements HKDF-Extract with the cipher suite hash.
  54. func (c *cipherSuiteTLS13) extract(newSecret, currentSecret []byte) []byte {
  55. if newSecret == nil {
  56. newSecret = make([]byte, c.hash.Size())
  57. }
  58. return hkdf.Extract(c.hash.New, newSecret, currentSecret)
  59. }
  60. // nextTrafficSecret generates the next traffic secret, given the current one,
  61. // according to RFC 8446, Section 7.2.
  62. func (c *cipherSuiteTLS13) nextTrafficSecret(trafficSecret []byte) []byte {
  63. return c.expandLabel(trafficSecret, trafficUpdateLabel, nil, c.hash.Size())
  64. }
  65. // trafficKey generates traffic keys according to RFC 8446, Section 7.3.
  66. func (c *cipherSuiteTLS13) trafficKey(trafficSecret []byte) (key, iv []byte) {
  67. key = c.expandLabel(trafficSecret, "key", nil, c.keyLen)
  68. iv = c.expandLabel(trafficSecret, "iv", nil, aeadNonceLength)
  69. return
  70. }
  71. // finishedHash generates the Finished verify_data or PskBinderEntry according
  72. // to RFC 8446, Section 4.4.4. See sections 4.4 and 4.2.11.2 for the baseKey
  73. // selection.
  74. func (c *cipherSuiteTLS13) finishedHash(baseKey []byte, transcript hash.Hash) []byte {
  75. finishedKey := c.expandLabel(baseKey, "finished", nil, c.hash.Size())
  76. verifyData := hmac.New(c.hash.New, finishedKey)
  77. verifyData.Write(transcript.Sum(nil))
  78. return verifyData.Sum(nil)
  79. }
  80. // exportKeyingMaterial implements RFC5705 exporters for TLS 1.3 according to
  81. // RFC 8446, Section 7.5.
  82. func (c *cipherSuiteTLS13) exportKeyingMaterial(masterSecret []byte, transcript hash.Hash) func(string, []byte, int) ([]byte, error) {
  83. expMasterSecret := c.deriveSecret(masterSecret, exporterLabel, transcript)
  84. return func(label string, context []byte, length int) ([]byte, error) {
  85. secret := c.deriveSecret(expMasterSecret, label, nil)
  86. h := c.hash.New()
  87. h.Write(context)
  88. return c.expandLabel(secret, "exporter", h.Sum(nil), length), nil
  89. }
  90. }
  91. // ecdheParameters implements Diffie-Hellman with either NIST curves or X25519,
  92. // according to RFC 8446, Section 4.2.8.2.
  93. type ecdheParameters interface {
  94. CurveID() CurveID
  95. PublicKey() []byte
  96. SharedKey(peerPublicKey []byte) []byte
  97. }
  98. func generateECDHEParameters(rand io.Reader, curveID CurveID) (ecdheParameters, error) {
  99. if curveID == X25519 {
  100. privateKey := make([]byte, curve25519.ScalarSize)
  101. if _, err := io.ReadFull(rand, privateKey); err != nil {
  102. return nil, err
  103. }
  104. publicKey, err := curve25519.X25519(privateKey, curve25519.Basepoint)
  105. if err != nil {
  106. return nil, err
  107. }
  108. return &x25519Parameters{privateKey: privateKey, publicKey: publicKey}, nil
  109. }
  110. curve, ok := curveForCurveID(curveID)
  111. if !ok {
  112. return nil, errors.New("tls: internal error: unsupported curve")
  113. }
  114. p := &nistParameters{curveID: curveID}
  115. var err error
  116. p.privateKey, p.x, p.y, err = elliptic.GenerateKey(curve, rand)
  117. if err != nil {
  118. return nil, err
  119. }
  120. return p, nil
  121. }
  122. func curveForCurveID(id CurveID) (elliptic.Curve, bool) {
  123. switch id {
  124. case CurveP256:
  125. return elliptic.P256(), true
  126. case CurveP384:
  127. return elliptic.P384(), true
  128. case CurveP521:
  129. return elliptic.P521(), true
  130. default:
  131. return nil, false
  132. }
  133. }
  134. type nistParameters struct {
  135. privateKey []byte
  136. x, y *big.Int // public key
  137. curveID CurveID
  138. }
  139. func (p *nistParameters) CurveID() CurveID {
  140. return p.curveID
  141. }
  142. func (p *nistParameters) PublicKey() []byte {
  143. curve, _ := curveForCurveID(p.curveID)
  144. return elliptic.Marshal(curve, p.x, p.y)
  145. }
  146. func (p *nistParameters) SharedKey(peerPublicKey []byte) []byte {
  147. curve, _ := curveForCurveID(p.curveID)
  148. // Unmarshal also checks whether the given point is on the curve.
  149. x, y := elliptic.Unmarshal(curve, peerPublicKey)
  150. if x == nil {
  151. return nil
  152. }
  153. xShared, _ := curve.ScalarMult(x, y, p.privateKey)
  154. sharedKey := make([]byte, (curve.Params().BitSize+7)/8)
  155. return xShared.FillBytes(sharedKey)
  156. }
  157. type x25519Parameters struct {
  158. privateKey []byte
  159. publicKey []byte
  160. }
  161. func (p *x25519Parameters) CurveID() CurveID {
  162. return X25519
  163. }
  164. func (p *x25519Parameters) PublicKey() []byte {
  165. return p.publicKey[:]
  166. }
  167. func (p *x25519Parameters) SharedKey(peerPublicKey []byte) []byte {
  168. sharedKey, err := curve25519.X25519(p.privateKey, peerPublicKey)
  169. if err != nil {
  170. return nil
  171. }
  172. return sharedKey
  173. }