integrity.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
  2. // SPDX-License-Identifier: MIT
  3. package stun
  4. import ( //nolint:gci
  5. "crypto/md5" //nolint:gosec
  6. "crypto/sha1" //nolint:gosec
  7. "errors"
  8. "fmt"
  9. "strings"
  10. "github.com/pion/stun/internal/hmac"
  11. )
  12. // separator for credentials.
  13. const credentialsSep = ":"
  14. // NewLongTermIntegrity returns new MessageIntegrity with key for long-term
  15. // credentials. Password, username, and realm must be SASL-prepared.
  16. func NewLongTermIntegrity(username, realm, password string) MessageIntegrity {
  17. k := strings.Join([]string{username, realm, password}, credentialsSep)
  18. h := md5.New() //nolint:gosec
  19. fmt.Fprint(h, k)
  20. return MessageIntegrity(h.Sum(nil))
  21. }
  22. // NewShortTermIntegrity returns new MessageIntegrity with key for short-term
  23. // credentials. Password must be SASL-prepared.
  24. func NewShortTermIntegrity(password string) MessageIntegrity {
  25. return MessageIntegrity(password)
  26. }
  27. // MessageIntegrity represents MESSAGE-INTEGRITY attribute.
  28. //
  29. // AddTo and Check methods are using zero-allocation version of hmac, see
  30. // newHMAC function and internal/hmac/pool.go.
  31. //
  32. // RFC 5389 Section 15.4
  33. type MessageIntegrity []byte
  34. func newHMAC(key, message, buf []byte) []byte {
  35. mac := hmac.AcquireSHA1(key)
  36. writeOrPanic(mac, message)
  37. defer hmac.PutSHA1(mac)
  38. return mac.Sum(buf)
  39. }
  40. func (i MessageIntegrity) String() string {
  41. return fmt.Sprintf("KEY: 0x%x", []byte(i))
  42. }
  43. const messageIntegritySize = 20
  44. // ErrFingerprintBeforeIntegrity means that FINGERPRINT attribute is already in
  45. // message, so MESSAGE-INTEGRITY attribute cannot be added.
  46. var ErrFingerprintBeforeIntegrity = errors.New("FINGERPRINT before MESSAGE-INTEGRITY attribute")
  47. // AddTo adds MESSAGE-INTEGRITY attribute to message.
  48. //
  49. // CPU costly, see BenchmarkMessageIntegrity_AddTo.
  50. func (i MessageIntegrity) AddTo(m *Message) error {
  51. for _, a := range m.Attributes {
  52. // Message should not contain FINGERPRINT attribute
  53. // before MESSAGE-INTEGRITY.
  54. if a.Type == AttrFingerprint {
  55. return ErrFingerprintBeforeIntegrity
  56. }
  57. }
  58. // The text used as input to HMAC is the STUN message,
  59. // including the header, up to and including the attribute preceding the
  60. // MESSAGE-INTEGRITY attribute.
  61. length := m.Length
  62. // Adjusting m.Length to contain MESSAGE-INTEGRITY TLV.
  63. m.Length += messageIntegritySize + attributeHeaderSize
  64. m.WriteLength() // writing length to m.Raw
  65. v := newHMAC(i, m.Raw, m.Raw[len(m.Raw):]) // calculating HMAC for adjusted m.Raw
  66. m.Length = length // changing m.Length back
  67. // Copy hmac value to temporary variable to protect it from resetting
  68. // while processing m.Add call.
  69. vBuf := make([]byte, sha1.Size)
  70. copy(vBuf, v)
  71. m.Add(AttrMessageIntegrity, vBuf)
  72. return nil
  73. }
  74. // ErrIntegrityMismatch means that computed HMAC differs from expected.
  75. var ErrIntegrityMismatch = errors.New("integrity check failed")
  76. // Check checks MESSAGE-INTEGRITY attribute.
  77. //
  78. // CPU costly, see BenchmarkMessageIntegrity_Check.
  79. func (i MessageIntegrity) Check(m *Message) error {
  80. v, err := m.Get(AttrMessageIntegrity)
  81. if err != nil {
  82. return err
  83. }
  84. // Adjusting length in header to match m.Raw that was
  85. // used when computing HMAC.
  86. var (
  87. length = m.Length
  88. afterIntegrity = false
  89. sizeReduced int
  90. )
  91. for _, a := range m.Attributes {
  92. if afterIntegrity {
  93. sizeReduced += nearestPaddedValueLength(int(a.Length))
  94. sizeReduced += attributeHeaderSize
  95. }
  96. if a.Type == AttrMessageIntegrity {
  97. afterIntegrity = true
  98. }
  99. }
  100. m.Length -= uint32(sizeReduced)
  101. m.WriteLength()
  102. // startOfHMAC should be first byte of integrity attribute.
  103. startOfHMAC := messageHeaderSize + m.Length - (attributeHeaderSize + messageIntegritySize)
  104. b := m.Raw[:startOfHMAC] // data before integrity attribute
  105. expected := newHMAC(i, b, m.Raw[len(m.Raw):])
  106. m.Length = length
  107. m.WriteLength() // writing length back
  108. return checkHMAC(v, expected)
  109. }