replay.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. // Copyright 2020 Jigsaw Operations LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package service
  15. import (
  16. "encoding/binary"
  17. "errors"
  18. "sync"
  19. )
  20. // MaxCapacity is the largest allowed size of ReplayCache.
  21. //
  22. // Capacities in excess of 20,000 are not recommended, due to the false
  23. // positive rate of up to 2 * capacity / 2^32 = 1 / 100,000. If larger
  24. // capacities are desired, the key type should be changed to uint64.
  25. const MaxCapacity = 20_000
  26. type empty struct{}
  27. // ReplayCache allows us to check whether a handshake salt was used within
  28. // the last `capacity` handshakes. It requires approximately 20*capacity
  29. // bytes of memory (as measured by BenchmarkReplayCache_Creation).
  30. //
  31. // The nil and zero values represent a cache with capacity 0, i.e. no cache.
  32. type ReplayCache struct {
  33. mutex sync.Mutex
  34. capacity int
  35. active map[uint32]empty
  36. archive map[uint32]empty
  37. }
  38. // NewReplayCache returns a fresh ReplayCache that promises to remember at least
  39. // the most recent `capacity` handshakes.
  40. func NewReplayCache(capacity int) ReplayCache {
  41. if capacity > MaxCapacity {
  42. panic("ReplayCache capacity would result in too many false positives")
  43. }
  44. return ReplayCache{
  45. capacity: capacity,
  46. active: make(map[uint32]empty, capacity),
  47. // `archive` is read-only and initially empty.
  48. }
  49. }
  50. // Trivially reduces the key and salt to a uint32, avoiding collisions
  51. // in case of salts with a shared prefix or suffix. Salts are normally
  52. // random, but in principle a client might use a counter instead, so
  53. // using only the prefix or suffix is not sufficient. Including the key
  54. // ID in the hash avoids accidental collisions when the same salt is used
  55. // by different access keys, as might happen in the case of a counter.
  56. //
  57. // Secure hashing is not required, because only authenticated handshakes
  58. // are added to the cache. A hostile client could produce colliding salts,
  59. // but this would not impact other users. Each map uses a new random hash
  60. // function, so it is not trivial for a hostile client to mount an
  61. // algorithmic complexity attack with nearly-colliding hashes:
  62. // https://dave.cheney.net/2018/05/29/how-the-go-runtime-implements-maps-efficiently-without-generics
  63. func preHash(id string, salt []byte) uint32 {
  64. buf := [4]byte{}
  65. for i := 0; i < len(id); i++ {
  66. buf[i&0x3] ^= id[i]
  67. }
  68. for i, v := range salt {
  69. buf[i&0x3] ^= v
  70. }
  71. return binary.BigEndian.Uint32(buf[:])
  72. }
  73. // Add a handshake with this key ID and salt to the cache.
  74. // Returns false if it is already present.
  75. func (c *ReplayCache) Add(id string, salt []byte) bool {
  76. if c == nil || c.capacity == 0 {
  77. // Cache is disabled, so every salt is new.
  78. return true
  79. }
  80. hash := preHash(id, salt)
  81. c.mutex.Lock()
  82. defer c.mutex.Unlock()
  83. if _, ok := c.active[hash]; ok {
  84. // Fast replay: `salt` is already in the active set.
  85. return false
  86. }
  87. _, inArchive := c.archive[hash]
  88. if len(c.active) >= c.capacity {
  89. // Discard the archive and move active to archive.
  90. c.archive = c.active
  91. c.active = make(map[uint32]empty, c.capacity)
  92. }
  93. c.active[hash] = empty{}
  94. return !inArchive
  95. }
  96. // Resize adjusts the capacity of the ReplayCache.
  97. func (c *ReplayCache) Resize(capacity int) error {
  98. if capacity > MaxCapacity {
  99. return errors.New("ReplayCache capacity would result in too many false positives")
  100. }
  101. c.mutex.Lock()
  102. defer c.mutex.Unlock()
  103. c.capacity = capacity
  104. // NOTE: The active handshakes and archive lists are not explicitly shrunk.
  105. // Their sizes will naturally adjust as new handshakes are added and the cache
  106. // adheres to the updated capacity.
  107. return nil
  108. }