use core::net::{IpAddr, SocketAddr};
use hmac::digest::Key;
use hmac::{Hmac, KeyInit, Mac};
use sha2::Sha256;
use subtle::ConstantTimeEq;
const COOKIE_DOMAIN: u8 = 0;
const SOCKET_ID_DOMAIN: u8 = 1;
const ISN_DOMAIN: u8 = 2;
const FAMILY_V4: u8 = 4;
const FAMILY_V6: u8 = 6;
const SECRET_LEN: usize = core::mem::size_of::<u128>();
const WORD_LEN: usize = core::mem::size_of::<u32>();
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct CookieOrigin {
pub time_bucket: u32,
pub secret: u128,
}
impl core::fmt::Debug for CookieOrigin {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("CookieOrigin")
.field("time_bucket", &self.time_bucket)
.finish_non_exhaustive()
}
}
fn tag(
domain: u8,
peer: &SocketAddr,
caller_socket_id: u32,
time_bucket: u32,
secret: u128,
) -> u32 {
let mut key = Key::<Hmac<Sha256>>::default();
key[..SECRET_LEN].copy_from_slice(&secret.to_le_bytes());
let mut mac = Hmac::<Sha256>::new(&key);
mac.update(&[domain]);
match peer.ip() {
IpAddr::V4(ip) => {
mac.update(&[FAMILY_V4]);
mac.update(&ip.octets());
}
IpAddr::V6(ip) => {
mac.update(&[FAMILY_V6]);
mac.update(&ip.octets());
}
}
mac.update(&peer.port().to_be_bytes());
mac.update(&caller_socket_id.to_be_bytes());
mac.update(&time_bucket.to_be_bytes());
let digest = mac.finalize().into_bytes();
let mut word = [0u8; WORD_LEN];
word.copy_from_slice(&digest[..WORD_LEN]);
u32::from_be_bytes(word)
}
#[must_use]
pub fn derive_cookie(
peer: &SocketAddr,
caller_socket_id: u32,
time_bucket: u32,
secret: u128,
) -> u32 {
tag(COOKIE_DOMAIN, peer, caller_socket_id, time_bucket, secret) | 1
}
#[must_use]
pub fn validate_cookie(
peer: &SocketAddr,
caller_socket_id: u32,
cookie: u32,
now_bucket: u32,
secrets: impl IntoIterator<Item = u128> + Clone,
) -> Option<CookieOrigin> {
let mut found = None;
for time_bucket in [now_bucket, now_bucket.wrapping_sub(1)] {
for secret in secrets.clone() {
let derived = derive_cookie(peer, caller_socket_id, time_bucket, secret);
if bool::from(derived.ct_eq(&cookie)) && found.is_none() {
found = Some(CookieOrigin {
time_bucket,
secret,
});
}
}
}
found
}
#[must_use]
pub fn derive_listener_ids(
peer: &SocketAddr,
caller_socket_id: u32,
time_bucket: u32,
secret: u128,
) -> (u32, u32) {
let socket_id = tag(
SOCKET_ID_DOMAIN,
peer,
caller_socket_id,
time_bucket,
secret,
) | 1;
let initial_seq = tag(ISN_DOMAIN, peer, caller_socket_id, time_bucket, secret)
& crate::packet::SEQ_NUMBER_MASK;
(socket_id, initial_seq)
}
#[cfg(test)]
mod tests {
use super::*;
const SECRET: u128 = 0x0123_4567_89AB_CDEF_FEDC_BA98_7654_3210;
const BUCKET: u32 = 29_000_000;
fn addr(s: &str) -> SocketAddr {
s.parse().unwrap()
}
#[test]
fn a_cookie_is_refused_from_another_address_port_or_socket_id() {
let a = addr("198.51.100.1:4000");
let cookie = derive_cookie(&a, 7, BUCKET, SECRET);
let ok = |p: &SocketAddr, id| validate_cookie(p, id, cookie, BUCKET, [SECRET]).is_some();
assert!(ok(&a, 7));
assert!(!ok(&addr("198.51.100.2:4000"), 7));
assert!(!ok(&addr("198.51.100.1:4001"), 7));
assert!(!ok(&a, 8));
assert!(!ok(&addr("[::ffff:198.51.100.1]:4000"), 7));
}
#[test]
fn a_cookie_older_than_two_buckets_is_refused_and_one_rolls_over() {
let a = addr("198.51.100.1:4000");
let cookie = derive_cookie(&a, 7, BUCKET, SECRET);
let at = |now| validate_cookie(&a, 7, cookie, now, [SECRET]);
assert!(at(BUCKET).is_some());
assert_eq!(at(BUCKET + 1).map(|o| o.time_bucket), Some(BUCKET));
assert!(at(BUCKET + 2).is_none());
assert!(at(BUCKET - 1).is_none());
}
#[test]
fn a_cookie_under_another_secret_is_refused() {
let a = addr("198.51.100.1:4000");
let cookie = derive_cookie(&a, 7, BUCKET, SECRET);
assert!(validate_cookie(&a, 7, cookie, BUCKET, [SECRET ^ 1]).is_none());
assert_eq!(
validate_cookie(&a, 7, cookie, BUCKET, [SECRET ^ 1, SECRET]).map(|o| o.secret),
Some(SECRET)
);
}
#[test]
fn distinct_sources_never_share_a_cookie_by_choice_of_socket_id() {
let a = addr("198.51.100.1:4000");
let b = addr("198.51.100.1:4001");
let wanted = derive_cookie(&a, 0, BUCKET, SECRET);
let collides = (0..=u16::MAX)
.map(u32::from)
.any(|id| derive_cookie(&b, id, BUCKET, SECRET) == wanted);
assert!(!collides);
}
#[test]
fn identifiers_are_stable_in_range_and_not_the_cookie() {
let a = addr("198.51.100.1:4000");
let first = derive_listener_ids(&a, 7, BUCKET, SECRET);
assert_eq!(first, derive_listener_ids(&a, 7, BUCKET, SECRET));
assert_ne!(first.0, 0);
assert!(first.1 <= crate::packet::SEQ_NUMBER_MASK);
assert_ne!(first.0, derive_cookie(&a, 7, BUCKET, SECRET));
assert_ne!(first, derive_listener_ids(&a, 7, BUCKET + 1, SECRET));
assert_ne!(first, derive_listener_ids(&a, 7, BUCKET, SECRET ^ 1));
}
#[test]
fn the_cookie_matches_an_independent_hmac() {
let a = addr("198.51.100.1:4000");
assert_eq!(derive_cookie(&a, 7, BUCKET, SECRET), 0x131f_6c61);
}
#[test]
fn both_halves_of_the_secret_feed_the_cookie_and_the_identifiers() {
let a = addr("198.51.100.1:4000");
let high = SECRET ^ (1u128 << 100);
let low = SECRET ^ 1;
for other in [high, low] {
assert_ne!(
derive_cookie(&a, 7, BUCKET, SECRET),
derive_cookie(&a, 7, BUCKET, other)
);
assert_ne!(
derive_listener_ids(&a, 7, BUCKET, SECRET),
derive_listener_ids(&a, 7, BUCKET, other)
);
}
}
#[test]
fn the_cookie_is_never_zero() {
let a = addr("198.51.100.1:4000");
assert!((0..1000).all(|id| derive_cookie(&a, id, BUCKET, SECRET) != 0));
}
}