2019-01-02 01:55:51 +01:00
|
|
|
/* SPDX-License-Identifier: MIT
|
2018-05-03 15:04:00 +02:00
|
|
|
*
|
2022-09-20 17:21:32 +02:00
|
|
|
* Copyright (C) 2017-2023 WireGuard LLC. All Rights Reserved.
|
2018-05-03 15:04:00 +02:00
|
|
|
*/
|
|
|
|
|
2020-09-09 19:55:24 +02:00
|
|
|
// Package replay implements an efficient anti-replay algorithm as specified in RFC 6479.
|
2018-05-23 02:32:02 +02:00
|
|
|
package replay
|
2017-07-12 23:11:49 +02:00
|
|
|
|
2020-09-09 19:55:24 +02:00
|
|
|
type block uint64
|
2017-07-10 12:09:19 +02:00
|
|
|
|
|
|
|
const (
|
2020-09-09 19:55:24 +02:00
|
|
|
blockBitLog = 6 // 1<<6 == 64 bits
|
|
|
|
blockBits = 1 << blockBitLog // must be power of 2
|
|
|
|
ringBlocks = 1 << 7 // must be power of 2
|
|
|
|
windowSize = (ringBlocks - 1) * blockBits
|
|
|
|
blockMask = ringBlocks - 1
|
|
|
|
bitMask = blockBits - 1
|
2017-07-10 12:09:19 +02:00
|
|
|
)
|
|
|
|
|
2020-09-09 20:06:44 +02:00
|
|
|
// A Filter rejects replayed messages by checking if message counter value is
|
2020-09-09 19:55:24 +02:00
|
|
|
// within a sliding window of previously received messages.
|
2020-09-09 20:06:44 +02:00
|
|
|
// The zero value for Filter is an empty filter ready to use.
|
2020-09-09 19:55:24 +02:00
|
|
|
// Filters are unsafe for concurrent use.
|
2020-09-09 20:06:44 +02:00
|
|
|
type Filter struct {
|
2020-09-09 19:55:24 +02:00
|
|
|
last uint64
|
|
|
|
ring [ringBlocks]block
|
2017-07-10 12:09:19 +02:00
|
|
|
}
|
|
|
|
|
2020-09-09 20:06:44 +02:00
|
|
|
// Reset resets the filter to empty state.
|
|
|
|
func (f *Filter) Reset() {
|
2020-09-09 19:55:24 +02:00
|
|
|
f.last = 0
|
|
|
|
f.ring[0] = 0
|
2017-07-10 12:09:19 +02:00
|
|
|
}
|
|
|
|
|
2020-09-09 19:55:24 +02:00
|
|
|
// ValidateCounter checks if the counter should be accepted.
|
|
|
|
// Overlimit counters (>= limit) are always rejected.
|
2021-12-09 17:55:50 +01:00
|
|
|
func (f *Filter) ValidateCounter(counter, limit uint64) bool {
|
2018-05-23 02:32:02 +02:00
|
|
|
if counter >= limit {
|
2017-07-10 12:09:19 +02:00
|
|
|
return false
|
|
|
|
}
|
2020-09-09 19:55:24 +02:00
|
|
|
indexBlock := counter >> blockBitLog
|
|
|
|
if counter > f.last { // move window forward
|
|
|
|
current := f.last >> blockBitLog
|
|
|
|
diff := indexBlock - current
|
|
|
|
if diff > ringBlocks {
|
|
|
|
diff = ringBlocks // cap diff to clear the whole ring
|
2017-07-10 12:09:19 +02:00
|
|
|
}
|
2020-09-09 19:55:24 +02:00
|
|
|
for i := current + 1; i <= current+diff; i++ {
|
|
|
|
f.ring[i&blockMask] = 0
|
|
|
|
}
|
|
|
|
f.last = counter
|
|
|
|
} else if f.last-counter > windowSize { // behind current window
|
2017-07-10 12:09:19 +02:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
// check and set bit
|
2020-09-09 19:55:24 +02:00
|
|
|
indexBlock &= blockMask
|
|
|
|
indexBit := counter & bitMask
|
|
|
|
old := f.ring[indexBlock]
|
|
|
|
new := old | 1<<indexBit
|
|
|
|
f.ring[indexBlock] = new
|
|
|
|
return old != new
|
2017-07-10 12:09:19 +02:00
|
|
|
}
|