| 1 |
package nebula |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"fmt" |
| 6 |
"log/slog" |
| 7 |
"math" |
| 8 |
mathbits "math/bits" |
| 9 |
|
| 10 |
"github.com/rcrowley/go-metrics" |
| 11 |
) |
| 12 |
|
| 13 |
const bitsPerWord = 64 |
| 14 |
|
| 15 |
// Bits is a sliding-window anti-replay tracker. The window is stored as a |
| 16 |
// circular bitmap packed into uint64 words (8x denser than a []bool), so a |
| 17 |
// length-N window costs N/8 bytes. length must be a power of two. |
| 18 |
type Bits struct { |
| 19 |
length uint64 |
| 20 |
lengthMask uint64 |
| 21 |
current uint64 |
| 22 |
bits []uint64 |
| 23 |
lostCounter metrics.Counter |
| 24 |
dupeCounter metrics.Counter |
| 25 |
outOfWindowCounter metrics.Counter |
| 26 |
} |
| 27 |
|
| 28 |
func NewBits(length uint64) *Bits { |
| 29 |
if length == 0 || length&(length-1) != 0 { |
| 30 |
panic(fmt.Sprintf("Bits length must be a power of two, got %d", length)) |
| 31 |
} |
| 32 |
|
| 33 |
nWords := length / bitsPerWord |
| 34 |
if nWords == 0 { |
| 35 |
nWords = 1 |
| 36 |
} |
| 37 |
b := &Bits{ |
| 38 |
length: length, |
| 39 |
lengthMask: length - 1, |
| 40 |
bits: make([]uint64, nWords), |
| 41 |
current: 0, |
| 42 |
lostCounter: metrics.GetOrRegisterCounter("network.packets.lost", nil), |
| 43 |
dupeCounter: metrics.GetOrRegisterCounter("network.packets.duplicate", nil), |
| 44 |
outOfWindowCounter: metrics.GetOrRegisterCounter("network.packets.out_of_window", nil), |
| 45 |
} |
| 46 |
|
| 47 |
// There is no counter value 0, mark it to avoid counting a lost packet later. |
| 48 |
b.bits[0] = 1 |
| 49 |
return b |
| 50 |
} |
| 51 |
|
| 52 |
func (b *Bits) get(i uint64) bool { |
| 53 |
pos := i & b.lengthMask |
| 54 |
//bit-shifting by 6 because i is a bit index, not a u64 index, and we need to find the u64 without bit in it |
| 55 |
return b.bits[pos>>6]&(uint64(1)<<(pos&63)) != 0 |
| 56 |
} |
| 57 |
|
| 58 |
func (b *Bits) set(i uint64) { |
| 59 |
pos := i & b.lengthMask |
| 60 |
b.bits[pos>>6] |= uint64(1) << (pos & 63) |
| 61 |
} |
| 62 |
|
| 63 |
// clearRange clears `count` bits starting at circular position `startPos` |
| 64 |
// (already masked to [0, length)) and returns how many of them were set |
| 65 |
// before the clear. count must be in [1, length]. |
| 66 |
func (b *Bits) clearRange(startPos, count uint64) uint64 { |
| 67 |
wasSet := uint64(0) |
| 68 |
if count >= b.length { |
| 69 |
for _, w := range b.bits { |
| 70 |
wasSet += uint64(mathbits.OnesCount64(w)) |
| 71 |
} |
| 72 |
clear(b.bits) |
| 73 |
return wasSet |
| 74 |
} |
| 75 |
|
| 76 |
pos := startPos |
| 77 |
remaining := count |
| 78 |
|
| 79 |
// handle the potential partial word before pos becomes u64 aligned |
| 80 |
word := pos >> 6 |
| 81 |
bit := pos & 63 |
| 82 |
take := uint64(64) - bit |
| 83 |
if take > remaining { |
| 84 |
take = remaining |
| 85 |
} |
| 86 |
if take > b.length-pos { |
| 87 |
take = b.length - pos |
| 88 |
} |
| 89 |
var mask uint64 |
| 90 |
if take == 64 { |
| 91 |
mask = math.MaxUint64 |
| 92 |
} else { |
| 93 |
mask = ((uint64(1) << take) - 1) << bit |
| 94 |
} |
| 95 |
wasSet += uint64(mathbits.OnesCount64(b.bits[word] & mask)) |
| 96 |
b.bits[word] &^= mask |
| 97 |
remaining -= take |
| 98 |
pos = (pos + take) & b.lengthMask |
| 99 |
|
| 100 |
// Clear whole words, keeping track of the number of set bits |
| 101 |
for remaining >= 64 { |
| 102 |
word = pos >> 6 |
| 103 |
wasSet += uint64(mathbits.OnesCount64(b.bits[word])) |
| 104 |
b.bits[word] = 0 |
| 105 |
remaining -= 64 |
| 106 |
pos = (pos + 64) & b.lengthMask |
| 107 |
} |
| 108 |
|
| 109 |
// Clear the remaining partial word |
| 110 |
if remaining > 0 { |
| 111 |
word = pos >> 6 |
| 112 |
mask = (uint64(1) << remaining) - 1 |
| 113 |
wasSet += uint64(mathbits.OnesCount64(b.bits[word] & mask)) |
| 114 |
b.bits[word] &^= mask |
| 115 |
} |
| 116 |
|
| 117 |
return wasSet |
| 118 |
} |
| 119 |
|
| 120 |
func (b *Bits) strictlyWithinWindow(i uint64) bool { |
| 121 |
// Handle the case where the window hasn't slid yet. This avoids u64 underflow. |
| 122 |
inWarmup := b.current < b.length |
| 123 |
if i < b.length && inWarmup { |
| 124 |
return true |
| 125 |
} |
| 126 |
|
| 127 |
// Next, if the packet is in-window, see if we've seen it before |
| 128 |
if i > b.current-b.length { |
| 129 |
return true |
| 130 |
} |
| 131 |
return false //not within window! |
| 132 |
} |
| 133 |
|
| 134 |
// Check returns true if i is within (or way out in front of) the window, and not a replay |
| 135 |
func (b *Bits) Check(l *slog.Logger, i uint64) bool { |
| 136 |
// If i is the next number, return true. |
| 137 |
if i > b.current { |
| 138 |
return true |
| 139 |
} |
| 140 |
|
| 141 |
if b.strictlyWithinWindow(i) { |
| 142 |
return !b.get(i) |
| 143 |
} |
| 144 |
|
| 145 |
// Not within the window |
| 146 |
if l.Enabled(context.Background(), slog.LevelDebug) { |
| 147 |
l.Debug("rejected a packet (top)", "current", b.current, "incoming", i) |
| 148 |
} |
| 149 |
return false |
| 150 |
} |
| 151 |
|
| 152 |
// Update has three branches: |
| 153 |
// - i == b.current+1: fast path; advance the cursor by one and lose-count |
| 154 |
// the slot we just stomped (only past warmup; see the i > b.length guard |
| 155 |
// below). |
| 156 |
// - i > b.current+1: jump path; clear all slots between current and i |
| 157 |
// (or up to a full window's worth, whichever is smaller) via clearRange, |
| 158 |
// then mark i. Two arms here: a warmup arm that handles the very first |
| 159 |
// window before the cursor has slid, and a steady-state arm that treats |
| 160 |
// every cleared empty slot as a lost packet. |
| 161 |
// - i <= b.current: in-window check for duplicates; out-of-window otherwise. |
| 162 |
// |
| 163 |
// NewBits seeds bits[0]=1 so counter 0 looks "received" — Update never |
| 164 |
// clears that marker during warmup (clearRange skips position 0 when |
| 165 |
// startPos=1), and once b.current >= b.length the marker is no longer |
| 166 |
// consulted. The marker prevents a fictitious "lost" hit on the first real |
| 167 |
// counter. |
| 168 |
func (b *Bits) Update(l *slog.Logger, i uint64) bool { |
| 169 |
// Fast path: i is the next expected counter. Split out so the function |
| 170 |
// stays small and avoids paying for the slow paths' slog argument-build |
| 171 |
// stack frame on every call. The bit read/test/write is inlined to |
| 172 |
// touch the backing word once. |
| 173 |
if i == b.current+1 { |
| 174 |
pos := i & b.lengthMask |
| 175 |
word := pos >> 6 |
| 176 |
mask := uint64(1) << (pos & 63) |
| 177 |
w := b.bits[word] |
| 178 |
if i > b.length && w&mask == 0 { |
| 179 |
b.lostCounter.Inc(1) |
| 180 |
} |
| 181 |
b.bits[word] = w | mask |
| 182 |
b.current = i |
| 183 |
return true |
| 184 |
} |
| 185 |
return b.updateSlow(l, i) |
| 186 |
} |
| 187 |
|
| 188 |
// updateSlow handles jumps, in-window backfill, dupes, and out-of-window. |
| 189 |
func (b *Bits) updateSlow(l *slog.Logger, i uint64) bool { |
| 190 |
// If i is a jump, adjust the window, record lost, update current, and return true |
| 191 |
if i > b.current { |
| 192 |
end := i |
| 193 |
if end > b.current+b.length { |
| 194 |
end = b.current + b.length |
| 195 |
} |
| 196 |
count := end - b.current |
| 197 |
startPos := (b.current + 1) & b.lengthMask |
| 198 |
|
| 199 |
var lost int64 |
| 200 |
if b.current >= b.length { |
| 201 |
// Steady state: every cleared slot is past warmup, so any unset |
| 202 |
// bit we evict is a lost packet from the previous cycle. |
| 203 |
wasSet := b.clearRange(startPos, count) |
| 204 |
lost = int64(count) - int64(wasSet) |
| 205 |
} else { |
| 206 |
// Warmup (the very first window). Some cleared slots represent |
| 207 |
// packets <= length where eviction is not "lost" in the usual |
| 208 |
// sense. This branch is taken at most once per connection so we |
| 209 |
// don't bother optimizing it. |
| 210 |
for n := b.current + 1; n <= end; n++ { |
| 211 |
if !b.get(n) && n > b.length { |
| 212 |
lost++ |
| 213 |
} |
| 214 |
} |
| 215 |
b.clearRange(startPos, count) |
| 216 |
} |
| 217 |
|
| 218 |
// Anything past the new window can never be backfilled, so it's lost. |
| 219 |
if i > b.current+b.length { |
| 220 |
lost += int64(i - b.current - b.length) |
| 221 |
} |
| 222 |
b.lostCounter.Inc(lost) |
| 223 |
|
| 224 |
b.set(i) |
| 225 |
b.current = i |
| 226 |
return true |
| 227 |
} |
| 228 |
|
| 229 |
// If i is within the current window but below the current counter, check to see if it's a duplicate |
| 230 |
if b.strictlyWithinWindow(i) { |
| 231 |
pos := i & b.lengthMask |
| 232 |
word := pos >> 6 |
| 233 |
mask := uint64(1) << (pos & 63) |
| 234 |
w := b.bits[word] |
| 235 |
if b.current == i || w&mask != 0 { |
| 236 |
if l.Enabled(context.Background(), slog.LevelDebug) { |
| 237 |
l.Debug("Receive window", |
| 238 |
"accepted", false, |
| 239 |
"currentCounter", b.current, |
| 240 |
"incomingCounter", i, |
| 241 |
"reason", "duplicate", |
| 242 |
) |
| 243 |
} |
| 244 |
b.dupeCounter.Inc(1) |
| 245 |
return false |
| 246 |
} |
| 247 |
|
| 248 |
b.bits[word] = w | mask |
| 249 |
return true |
| 250 |
} |
| 251 |
|
| 252 |
// In all other cases, fail and don't change current. |
| 253 |
b.outOfWindowCounter.Inc(1) |
| 254 |
if l.Enabled(context.Background(), slog.LevelDebug) { |
| 255 |
l.Debug("Receive window", |
| 256 |
"accepted", false, |
| 257 |
"currentCounter", b.current, |
| 258 |
"incomingCounter", i, |
| 259 |
"reason", "nonsense", |
| 260 |
) |
| 261 |
} |
| 262 |
return false |
| 263 |
} |