key_schedule.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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. "golang.org/x/crypto/cryptobyte"
  10. "golang.org/x/crypto/curve25519"
  11. "golang.org/x/crypto/hkdf"
  12. "hash"
  13. "io"
  14. "math/big"
  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. p := &x25519Parameters{}
  101. if _, err := io.ReadFull(rand, p.privateKey[:]); err != nil {
  102. return nil, err
  103. }
  104. curve25519.ScalarBaseMult(&p.publicKey, &p.privateKey)
  105. return p, nil
  106. }
  107. curve, ok := curveForCurveID(curveID)
  108. if !ok {
  109. return nil, errors.New("tls: internal error: unsupported curve")
  110. }
  111. p := &nistParameters{curveID: curveID}
  112. var err error
  113. p.privateKey, p.x, p.y, err = elliptic.GenerateKey(curve, rand)
  114. if err != nil {
  115. return nil, err
  116. }
  117. return p, nil
  118. }
  119. func curveForCurveID(id CurveID) (elliptic.Curve, bool) {
  120. switch id {
  121. case CurveP256:
  122. return elliptic.P256(), true
  123. case CurveP384:
  124. return elliptic.P384(), true
  125. case CurveP521:
  126. return elliptic.P521(), true
  127. default:
  128. return nil, false
  129. }
  130. }
  131. type nistParameters struct {
  132. privateKey []byte
  133. x, y *big.Int // public key
  134. curveID CurveID
  135. }
  136. func (p *nistParameters) CurveID() CurveID {
  137. return p.curveID
  138. }
  139. func (p *nistParameters) PublicKey() []byte {
  140. curve, _ := curveForCurveID(p.curveID)
  141. return elliptic.Marshal(curve, p.x, p.y)
  142. }
  143. func (p *nistParameters) SharedKey(peerPublicKey []byte) []byte {
  144. curve, _ := curveForCurveID(p.curveID)
  145. // Unmarshal also checks whether the given point is on the curve.
  146. x, y := elliptic.Unmarshal(curve, peerPublicKey)
  147. if x == nil {
  148. return nil
  149. }
  150. xShared, _ := curve.ScalarMult(x, y, p.privateKey)
  151. sharedKey := make([]byte, (curve.Params().BitSize+7)>>3)
  152. xBytes := xShared.Bytes()
  153. copy(sharedKey[len(sharedKey)-len(xBytes):], xBytes)
  154. return sharedKey
  155. }
  156. type x25519Parameters struct {
  157. privateKey [32]byte
  158. publicKey [32]byte
  159. }
  160. func (p *x25519Parameters) CurveID() CurveID {
  161. return X25519
  162. }
  163. func (p *x25519Parameters) PublicKey() []byte {
  164. return p.publicKey[:]
  165. }
  166. func (p *x25519Parameters) SharedKey(peerPublicKey []byte) []byte {
  167. if len(peerPublicKey) != 32 {
  168. return nil
  169. }
  170. var theirPublicKey, sharedKey [32]byte
  171. copy(theirPublicKey[:], peerPublicKey)
  172. curve25519.ScalarMult(&sharedKey, &p.privateKey, &theirPublicKey)
  173. return sharedKey[:]
  174. }