key_schedule.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  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. )
  15. // This file contains the functions necessary to compute the TLS 1.3 key
  16. // schedule. See RFC 8446, Section 7.
  17. const (
  18. resumptionBinderLabel = "res binder"
  19. clientEarlyTrafficLabel = "c e traffic"
  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. hkdfLabelBytes, err := hkdfLabel.Bytes()
  40. if err != nil {
  41. // Rather than calling BytesOrPanic, we explicitly handle this error, in
  42. // order to provide a reasonable error message. It should be basically
  43. // impossible for this to panic, and routing errors back through the
  44. // tree rooted in this function is quite painful. The labels are fixed
  45. // size, and the context is either a fixed-length computed hash, or
  46. // parsed from a field which has the same length limitation. As such, an
  47. // error here is likely to only be caused during development.
  48. //
  49. // NOTE: another reasonable approach here might be to return a
  50. // randomized slice if we encounter an error, which would break the
  51. // connection, but avoid panicking. This would perhaps be safer but
  52. // significantly more confusing to users.
  53. panic(fmt.Errorf("failed to construct HKDF label: %s", err))
  54. }
  55. out := make([]byte, length)
  56. n, err := hkdf.Expand(c.hash.New, secret, hkdfLabelBytes).Read(out)
  57. if err != nil || n != length {
  58. panic("tls: HKDF-Expand-Label invocation failed unexpectedly")
  59. }
  60. return out
  61. }
  62. // deriveSecret implements Derive-Secret from RFC 8446, Section 7.1.
  63. func (c *cipherSuiteTLS13) deriveSecret(secret []byte, label string, transcript hash.Hash) []byte {
  64. if transcript == nil {
  65. transcript = c.hash.New()
  66. }
  67. return c.expandLabel(secret, label, transcript.Sum(nil), c.hash.Size())
  68. }
  69. // extract implements HKDF-Extract with the cipher suite hash.
  70. func (c *cipherSuiteTLS13) extract(newSecret, currentSecret []byte) []byte {
  71. if newSecret == nil {
  72. newSecret = make([]byte, c.hash.Size())
  73. }
  74. return hkdf.Extract(c.hash.New, newSecret, currentSecret)
  75. }
  76. // nextTrafficSecret generates the next traffic secret, given the current one,
  77. // according to RFC 8446, Section 7.2.
  78. func (c *cipherSuiteTLS13) nextTrafficSecret(trafficSecret []byte) []byte {
  79. return c.expandLabel(trafficSecret, trafficUpdateLabel, nil, c.hash.Size())
  80. }
  81. // trafficKey generates traffic keys according to RFC 8446, Section 7.3.
  82. func (c *cipherSuiteTLS13) trafficKey(trafficSecret []byte) (key, iv []byte) {
  83. key = c.expandLabel(trafficSecret, "key", nil, c.keyLen)
  84. iv = c.expandLabel(trafficSecret, "iv", nil, aeadNonceLength)
  85. return
  86. }
  87. // finishedHash generates the Finished verify_data or PskBinderEntry according
  88. // to RFC 8446, Section 4.4.4. See sections 4.4 and 4.2.11.2 for the baseKey
  89. // selection.
  90. func (c *cipherSuiteTLS13) finishedHash(baseKey []byte, transcript hash.Hash) []byte {
  91. finishedKey := c.expandLabel(baseKey, "finished", nil, c.hash.Size())
  92. verifyData := hmac.New(c.hash.New, finishedKey)
  93. verifyData.Write(transcript.Sum(nil))
  94. return verifyData.Sum(nil)
  95. }
  96. // exportKeyingMaterial implements RFC5705 exporters for TLS 1.3 according to
  97. // RFC 8446, Section 7.5.
  98. func (c *cipherSuiteTLS13) exportKeyingMaterial(masterSecret []byte, transcript hash.Hash) func(string, []byte, int) ([]byte, error) {
  99. expMasterSecret := c.deriveSecret(masterSecret, exporterLabel, transcript)
  100. return func(label string, context []byte, length int) ([]byte, error) {
  101. secret := c.deriveSecret(expMasterSecret, label, nil)
  102. h := c.hash.New()
  103. h.Write(context)
  104. return c.expandLabel(secret, "exporter", h.Sum(nil), length), nil
  105. }
  106. }
  107. // generateECDHEKey returns a PrivateKey that implements Diffie-Hellman
  108. // according to RFC 8446, Section 4.2.8.2.
  109. func generateECDHEKey(rand io.Reader, curveID CurveID) (*ecdh.PrivateKey, error) {
  110. curve, ok := curveForCurveID(curveID)
  111. if !ok {
  112. return nil, errors.New("tls: internal error: unsupported curve")
  113. }
  114. return curve.GenerateKey(rand)
  115. }
  116. func curveForCurveID(id CurveID) (ecdh.Curve, bool) {
  117. switch id {
  118. case X25519:
  119. return ecdh.X25519(), true
  120. case CurveP256:
  121. return ecdh.P256(), true
  122. case CurveP384:
  123. return ecdh.P384(), true
  124. case CurveP521:
  125. return ecdh.P521(), true
  126. default:
  127. return nil, false
  128. }
  129. }
  130. func curveIDForCurve(curve ecdh.Curve) (CurveID, bool) {
  131. switch curve {
  132. case ecdh.X25519():
  133. return X25519, true
  134. case ecdh.P256():
  135. return CurveP256, true
  136. case ecdh.P384():
  137. return CurveP384, true
  138. case ecdh.P521():
  139. return CurveP521, true
  140. default:
  141. return 0, false
  142. }
  143. }