| 1 |
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
| 2 |
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
| 3 |
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your |
| 4 |
// option. This file may not be copied, modified, or distributed |
| 5 |
// except according to those terms. |
| 6 |
|
| 7 |
// This file implements functions necessary for address validation. |
| 8 |
|
| 9 |
use std::{ |
| 10 |
net::{IpAddr, SocketAddr}, |
| 11 |
time::{Duration, Instant}, |
| 12 |
}; |
| 13 |
|
| 14 |
use neqo_common::{qinfo, qtrace, Decoder, Encoder, Role}; |
| 15 |
use neqo_crypto::{ |
| 16 |
constants::{TLS_AES_128_GCM_SHA256, TLS_VERSION_1_3}, |
| 17 |
selfencrypt::SelfEncrypt, |
| 18 |
}; |
| 19 |
use smallvec::SmallVec; |
| 20 |
|
| 21 |
use crate::{ |
| 22 |
cid::ConnectionId, frame::FrameType, packet::PacketBuilder, recovery::RecoveryToken, |
| 23 |
stats::FrameStats, Res, |
| 24 |
}; |
| 25 |
|
| 26 |
/// A prefix we add to Retry tokens to distinguish them from `NEW_TOKEN` tokens. |
| 27 |
const TOKEN_IDENTIFIER_RETRY: &[u8] = &[0x52, 0x65, 0x74, 0x72, 0x79]; |
| 28 |
/// A prefix on `NEW_TOKEN` tokens, that is maximally Hamming distant from `NEW_TOKEN`. |
| 29 |
/// Together, these need to have a low probability of collision, even if there is |
| 30 |
/// corruption of individual bits in transit. |
| 31 |
const TOKEN_IDENTIFIER_NEW_TOKEN: &[u8] = &[0xad, 0x9a, 0x8b, 0x8d, 0x86]; |
| 32 |
|
| 33 |
/// The maximum number of tokens we'll save from `NEW_TOKEN` frames. |
| 34 |
/// This should be the same as the value of `MAX_TICKETS` in neqo-crypto. |
| 35 |
const MAX_NEW_TOKEN: usize = 4; |
| 36 |
/// The number of tokens we'll track for the purposes of looking for duplicates. |
| 37 |
/// This is based on how many might be received over a period where could be |
| 38 |
/// retransmissions. It should be at least `MAX_NEW_TOKEN`. |
| 39 |
const MAX_SAVED_TOKENS: usize = 8; |
| 40 |
|
| 41 |
/// `ValidateAddress` determines what sort of address validation is performed. |
| 42 |
/// In short, this determines when a Retry packet is sent. |
| 43 |
#[derive(Debug, PartialEq, Eq)] |
| 44 |
pub enum ValidateAddress { |
| 45 |
/// Require address validation never. |
| 46 |
Never, |
| 47 |
/// Require address validation unless a `NEW_TOKEN` token is provided. |
| 48 |
NoToken, |
| 49 |
/// Require address validation even if a `NEW_TOKEN` token is provided. |
| 50 |
Always, |
| 51 |
} |
| 52 |
|
| 53 |
pub enum AddressValidationResult { |
| 54 |
Pass, |
| 55 |
ValidRetry(ConnectionId), |
| 56 |
Validate, |
| 57 |
Invalid, |
| 58 |
} |
| 59 |
|
| 60 |
pub struct AddressValidation { |
| 61 |
/// What sort of validation is performed. |
| 62 |
validation: ValidateAddress, |
| 63 |
/// A self-encryption object used for protecting Retry tokens. |
| 64 |
self_encrypt: SelfEncrypt, |
| 65 |
/// When this object was created. |
| 66 |
start_time: Instant, |
| 67 |
} |
| 68 |
|
| 69 |
impl AddressValidation { |
| 70 |
pub fn new(now: Instant, validation: ValidateAddress) -> Res<Self> { |
| 71 |
Ok(Self { |
| 72 |
validation, |
| 73 |
self_encrypt: SelfEncrypt::new(TLS_VERSION_1_3, TLS_AES_128_GCM_SHA256)?, |
| 74 |
start_time: now, |
| 75 |
}) |
| 76 |
} |
| 77 |
|
| 78 |
fn encode_aad(peer_address: SocketAddr, retry: bool) -> Encoder { |
| 79 |
// Let's be "clever" by putting the peer's address in the AAD. |
| 80 |
// We don't need to encode these into the token as they should be |
| 81 |
// available when we need to check the token. |
| 82 |
let mut aad = Encoder::default(); |
| 83 |
if retry { |
| 84 |
aad.encode(TOKEN_IDENTIFIER_RETRY); |
| 85 |
} else { |
| 86 |
aad.encode(TOKEN_IDENTIFIER_NEW_TOKEN); |
| 87 |
} |
| 88 |
match peer_address.ip() { |
| 89 |
IpAddr::V4(a) => { |
| 90 |
aad.encode_byte(4); |
| 91 |
aad.encode(&a.octets()); |
| 92 |
} |
| 93 |
IpAddr::V6(a) => { |
| 94 |
aad.encode_byte(6); |
| 95 |
aad.encode(&a.octets()); |
| 96 |
} |
| 97 |
} |
| 98 |
if retry { |
| 99 |
aad.encode_uint(2, peer_address.port()); |
| 100 |
} |
| 101 |
aad |
| 102 |
} |
| 103 |
|
| 104 |
pub fn generate_token( |
| 105 |
&self, |
| 106 |
dcid: Option<&ConnectionId>, |
| 107 |
peer_address: SocketAddr, |
| 108 |
now: Instant, |
| 109 |
) -> Res<Vec<u8>> { |
| 110 |
const EXPIRATION_RETRY: Duration = Duration::from_secs(5); |
| 111 |
const EXPIRATION_NEW_TOKEN: Duration = Duration::from_secs(60 * 60 * 24); |
| 112 |
|
| 113 |
// TODO(mt) rotate keys on a fixed schedule. |
| 114 |
let retry = dcid.is_some(); |
| 115 |
let mut data = Encoder::default(); |
| 116 |
let end = now |
| 117 |
+ if retry { |
| 118 |
EXPIRATION_RETRY |
| 119 |
} else { |
| 120 |
EXPIRATION_NEW_TOKEN |
| 121 |
}; |
| 122 |
let end_millis = u32::try_from(end.duration_since(self.start_time).as_millis())?; |
| 123 |
data.encode_uint(4, end_millis); |
| 124 |
if let Some(dcid) = dcid { |
| 125 |
data.encode(dcid); |
| 126 |
} |
| 127 |
|
| 128 |
// Include the token identifier ("Retry"/~) in the AAD, then keep it for plaintext. |
| 129 |
let mut buf = Self::encode_aad(peer_address, retry); |
| 130 |
let encrypted = self.self_encrypt.seal(buf.as_ref(), data.as_ref())?; |
| 131 |
buf.truncate(TOKEN_IDENTIFIER_RETRY.len()); |
| 132 |
buf.encode(&encrypted); |
| 133 |
Ok(buf.into()) |
| 134 |
} |
| 135 |
|
| 136 |
/// This generates a token for use with Retry. |
| 137 |
pub fn generate_retry_token( |
| 138 |
&self, |
| 139 |
dcid: &ConnectionId, |
| 140 |
peer_address: SocketAddr, |
| 141 |
now: Instant, |
| 142 |
) -> Res<Vec<u8>> { |
| 143 |
self.generate_token(Some(dcid), peer_address, now) |
| 144 |
} |
| 145 |
|
| 146 |
/// This generates a token for use with `NEW_TOKEN`. |
| 147 |
pub fn generate_new_token(&self, peer_address: SocketAddr, now: Instant) -> Res<Vec<u8>> { |
| 148 |
self.generate_token(None, peer_address, now) |
| 149 |
} |
| 150 |
|
| 151 |
pub fn set_validation(&mut self, validation: ValidateAddress) { |
| 152 |
qtrace!("AddressValidation {self:p}: set to {validation:?}"); |
| 153 |
self.validation = validation; |
| 154 |
} |
| 155 |
|
| 156 |
/// Decrypts `token` and returns the connection ID it contains. |
| 157 |
/// Returns a tuple with a boolean indicating whether this thinks |
| 158 |
/// that the token was a Retry token, and a connection ID, that is |
| 159 |
/// None if the token wasn't successfully decrypted. |
| 160 |
fn decrypt_token( |
| 161 |
&self, |
| 162 |
token: &[u8], |
| 163 |
peer_address: SocketAddr, |
| 164 |
retry: bool, |
| 165 |
now: Instant, |
| 166 |
) -> Option<ConnectionId> { |
| 167 |
let peer_addr = Self::encode_aad(peer_address, retry); |
| 168 |
let data = self.self_encrypt.open(peer_addr.as_ref(), token).ok()?; |
| 169 |
let mut dec = Decoder::new(&data); |
| 170 |
match dec.decode_uint::<u32>() { |
| 171 |
Some(d) => { |
| 172 |
let end = self.start_time + Duration::from_millis(u64::from(d)); |
| 173 |
if end < now { |
| 174 |
qtrace!("Expired token: {end:?} vs. {now:?}"); |
| 175 |
return None; |
| 176 |
} |
| 177 |
} |
| 178 |
_ => return None, |
| 179 |
} |
| 180 |
Some(ConnectionId::from(dec.decode_remainder())) |
| 181 |
} |
| 182 |
|
| 183 |
/// Calculate the Hamming difference between our identifier and the target. |
| 184 |
/// Less than one difference per byte indicates that it is likely not a Retry. |
| 185 |
/// This generous interpretation allows for a lot of damage in transit. |
| 186 |
/// Note that if this check fails, then the token will be treated like it came |
| 187 |
/// from `NEW_TOKEN` instead. If there truly is corruption of packets that causes |
| 188 |
/// validation failure, it will be a failure that we try to recover from. |
| 189 |
fn is_likely_retry(token: &[u8]) -> bool { |
| 190 |
let mut difference = 0; |
| 191 |
for i in 0..TOKEN_IDENTIFIER_RETRY.len() { |
| 192 |
difference += (token[i] ^ TOKEN_IDENTIFIER_RETRY[i]).count_ones(); |
| 193 |
} |
| 194 |
usize::try_from(difference).expect("u32 fits in usize") < TOKEN_IDENTIFIER_RETRY.len() |
| 195 |
} |
| 196 |
|
| 197 |
pub fn validate( |
| 198 |
&self, |
| 199 |
token: &[u8], |
| 200 |
peer_address: SocketAddr, |
| 201 |
now: Instant, |
| 202 |
) -> AddressValidationResult { |
| 203 |
qtrace!("AddressValidation {self:p}: validate {:?}", self.validation); |
| 204 |
|
| 205 |
if token.is_empty() { |
| 206 |
if self.validation == ValidateAddress::Never { |
| 207 |
qinfo!("AddressValidation: no token; accepting"); |
| 208 |
return AddressValidationResult::Pass; |
| 209 |
} |
| 210 |
qinfo!("AddressValidation: no token; validating"); |
| 211 |
return AddressValidationResult::Validate; |
| 212 |
} |
| 213 |
if token.len() <= TOKEN_IDENTIFIER_RETRY.len() { |
| 214 |
// Treat bad tokens strictly. |
| 215 |
qinfo!("AddressValidation: too short token"); |
| 216 |
return AddressValidationResult::Invalid; |
| 217 |
} |
| 218 |
let retry = Self::is_likely_retry(token); |
| 219 |
let enc = &token[TOKEN_IDENTIFIER_RETRY.len()..]; |
| 220 |
// Note that this allows the token identifier part to be corrupted. |
| 221 |
// That's OK here as we don't depend on that being authenticated. |
| 222 |
#[expect(clippy::option_if_let_else, reason = "Alternative is less readable.")] |
| 223 |
if let Some(cid) = self.decrypt_token(enc, peer_address, retry, now) { |
| 224 |
if retry { |
| 225 |
// This is from Retry, so we should have an ODCID >= 8. |
| 226 |
if cid.len() >= 8 { |
| 227 |
qinfo!("AddressValidation: valid Retry token for {cid}"); |
| 228 |
AddressValidationResult::ValidRetry(cid) |
| 229 |
} else { |
| 230 |
panic!("AddressValidation: Retry token with small CID {cid}"); |
| 231 |
} |
| 232 |
} else if cid.is_empty() { |
| 233 |
// An empty connection ID means NEW_TOKEN. |
| 234 |
if self.validation == ValidateAddress::Always { |
| 235 |
qinfo!("AddressValidation: valid NEW_TOKEN token; validating again"); |
| 236 |
AddressValidationResult::Validate |
| 237 |
} else { |
| 238 |
qinfo!("AddressValidation: valid NEW_TOKEN token; accepting"); |
| 239 |
AddressValidationResult::Pass |
| 240 |
} |
| 241 |
} else { |
| 242 |
panic!("AddressValidation: NEW_TOKEN token with CID {cid}"); |
| 243 |
} |
| 244 |
} else { |
| 245 |
// From here on, we have a token that we couldn't decrypt. |
| 246 |
// We've either lost the keys or we've received junk. |
| 247 |
if retry { |
| 248 |
// If this looked like a Retry, treat it as being bad. |
| 249 |
qinfo!("AddressValidation: invalid Retry token; rejecting"); |
| 250 |
AddressValidationResult::Invalid |
| 251 |
} else if self.validation == ValidateAddress::Never { |
| 252 |
// We don't require validation, so OK. |
| 253 |
qinfo!("AddressValidation: invalid NEW_TOKEN token; accepting"); |
| 254 |
AddressValidationResult::Pass |
| 255 |
} else { |
| 256 |
// This might be an invalid NEW_TOKEN token, or a valid one |
| 257 |
// for which we have since lost the keys. Check again. |
| 258 |
qinfo!("AddressValidation: invalid NEW_TOKEN token; validating again"); |
| 259 |
AddressValidationResult::Validate |
| 260 |
} |
| 261 |
} |
| 262 |
} |
| 263 |
} |
| 264 |
|
| 265 |
#[expect(clippy::large_enum_variant, reason = "No way around it.")] |
| 266 |
pub enum NewTokenState { |
| 267 |
Client { |
| 268 |
/// Tokens that haven't been taken yet. |
| 269 |
pending: SmallVec<[Vec<u8>; MAX_NEW_TOKEN]>, |
| 270 |
/// Tokens that have been taken, saved so that we can discard duplicates. |
| 271 |
old: SmallVec<[Vec<u8>; MAX_SAVED_TOKENS]>, |
| 272 |
}, |
| 273 |
Server(NewTokenSender), |
| 274 |
} |
| 275 |
|
| 276 |
impl NewTokenState { |
| 277 |
pub fn new(role: Role) -> Self { |
| 278 |
match role { |
| 279 |
Role::Client => Self::Client { |
| 280 |
pending: SmallVec::<[_; MAX_NEW_TOKEN]>::new(), |
| 281 |
old: SmallVec::<[_; MAX_SAVED_TOKENS]>::new(), |
| 282 |
}, |
| 283 |
Role::Server => Self::Server(NewTokenSender::default()), |
| 284 |
} |
| 285 |
} |
| 286 |
|
| 287 |
/// Is there a token available? |
| 288 |
pub fn has_token(&self) -> bool { |
| 289 |
match self { |
| 290 |
Self::Client { pending, .. } => !pending.is_empty(), |
| 291 |
Self::Server(..) => false, |
| 292 |
} |
| 293 |
} |
| 294 |
|
| 295 |
/// If this is a client, take a token if there is one. |
| 296 |
/// If this is a server, panic. |
| 297 |
pub fn take_token(&mut self) -> Option<&[u8]> { |
| 298 |
if let Self::Client { |
| 299 |
ref mut pending, |
| 300 |
ref mut old, |
| 301 |
} = self |
| 302 |
{ |
| 303 |
pending.pop().map(|t| { |
| 304 |
if old.len() >= MAX_SAVED_TOKENS { |
| 305 |
old.remove(0); |
| 306 |
} |
| 307 |
old.push(t); |
| 308 |
old[old.len() - 1].as_slice() |
| 309 |
}) |
| 310 |
} else { |
| 311 |
unreachable!(); |
| 312 |
} |
| 313 |
} |
| 314 |
|
| 315 |
/// If this is a client, save a token. |
| 316 |
/// If this is a server, panic. |
| 317 |
pub fn save_token(&mut self, token: Vec<u8>) { |
| 318 |
if let Self::Client { |
| 319 |
ref mut pending, |
| 320 |
old, |
| 321 |
} = self |
| 322 |
{ |
| 323 |
for t in old.iter().rev().chain(pending.iter().rev()) { |
| 324 |
if t == &token { |
| 325 |
qinfo!("NewTokenState discarding duplicate NEW_TOKEN"); |
| 326 |
return; |
| 327 |
} |
| 328 |
} |
| 329 |
|
| 330 |
if pending.len() >= MAX_NEW_TOKEN { |
| 331 |
pending.remove(0); |
| 332 |
} |
| 333 |
pending.push(token); |
| 334 |
} else { |
| 335 |
unreachable!(); |
| 336 |
} |
| 337 |
} |
| 338 |
|
| 339 |
/// If this is a server, maybe send a frame. |
| 340 |
/// If this is a client, do nothing. |
| 341 |
pub fn write_frames( |
| 342 |
&mut self, |
| 343 |
builder: &mut PacketBuilder, |
| 344 |
tokens: &mut Vec<RecoveryToken>, |
| 345 |
stats: &mut FrameStats, |
| 346 |
) { |
| 347 |
if let Self::Server(ref mut sender) = self { |
| 348 |
sender.write_frames(builder, tokens, stats); |
| 349 |
} |
| 350 |
} |
| 351 |
|
| 352 |
/// If this a server, buffer a `NEW_TOKEN` for sending. |
| 353 |
/// If this is a client, panic. |
| 354 |
pub fn send_new_token(&mut self, token: Vec<u8>) { |
| 355 |
if let Self::Server(ref mut sender) = self { |
| 356 |
sender.send_new_token(token); |
| 357 |
} else { |
| 358 |
unreachable!(); |
| 359 |
} |
| 360 |
} |
| 361 |
|
| 362 |
/// If this a server, process a lost signal for a `NEW_TOKEN` frame. |
| 363 |
/// If this is a client, panic. |
| 364 |
pub fn lost(&mut self, seqno: usize) { |
| 365 |
if let Self::Server(ref mut sender) = self { |
| 366 |
sender.lost(seqno); |
| 367 |
} else { |
| 368 |
unreachable!(); |
| 369 |
} |
| 370 |
} |
| 371 |
|
| 372 |
/// If this a server, process remove the acknowledged `NEW_TOKEN` frame. |
| 373 |
/// If this is a client, panic. |
| 374 |
pub fn acked(&mut self, seqno: usize) { |
| 375 |
if let Self::Server(ref mut sender) = self { |
| 376 |
sender.acked(seqno); |
| 377 |
} else { |
| 378 |
unreachable!(); |
| 379 |
} |
| 380 |
} |
| 381 |
} |
| 382 |
|
| 383 |
struct NewTokenFrameStatus { |
| 384 |
seqno: usize, |
| 385 |
token: Vec<u8>, |
| 386 |
needs_sending: bool, |
| 387 |
} |
| 388 |
|
| 389 |
impl NewTokenFrameStatus { |
| 390 |
fn len(&self) -> usize { |
| 391 |
1 + Encoder::vvec_len(self.token.len()) |
| 392 |
} |
| 393 |
} |
| 394 |
|
| 395 |
#[derive(Default)] |
| 396 |
pub struct NewTokenSender { |
| 397 |
/// The unacknowledged `NEW_TOKEN` frames we are yet to send. |
| 398 |
tokens: Vec<NewTokenFrameStatus>, |
| 399 |
/// A sequence number that is used to track individual tokens |
| 400 |
/// by reference (so that recovery tokens can be simple). |
| 401 |
next_seqno: usize, |
| 402 |
} |
| 403 |
|
| 404 |
impl NewTokenSender { |
| 405 |
/// Add a token to be sent. |
| 406 |
pub fn send_new_token(&mut self, token: Vec<u8>) { |
| 407 |
self.tokens.push(NewTokenFrameStatus { |
| 408 |
seqno: self.next_seqno, |
| 409 |
token, |
| 410 |
needs_sending: true, |
| 411 |
}); |
| 412 |
self.next_seqno += 1; |
| 413 |
} |
| 414 |
|
| 415 |
pub fn write_frames( |
| 416 |
&mut self, |
| 417 |
builder: &mut PacketBuilder, |
| 418 |
tokens: &mut Vec<RecoveryToken>, |
| 419 |
stats: &mut FrameStats, |
| 420 |
) { |
| 421 |
for t in &mut self.tokens { |
| 422 |
if t.needs_sending && t.len() <= builder.remaining() { |
| 423 |
t.needs_sending = false; |
| 424 |
|
| 425 |
builder.encode_varint(FrameType::NewToken); |
| 426 |
builder.encode_vvec(&t.token); |
| 427 |
|
| 428 |
tokens.push(RecoveryToken::NewToken(t.seqno)); |
| 429 |
stats.new_token += 1; |
| 430 |
} |
| 431 |
} |
| 432 |
} |
| 433 |
|
| 434 |
pub fn lost(&mut self, seqno: usize) { |
| 435 |
for t in &mut self.tokens { |
| 436 |
if t.seqno == seqno { |
| 437 |
t.needs_sending = true; |
| 438 |
break; |
| 439 |
} |
| 440 |
} |
| 441 |
} |
| 442 |
|
| 443 |
pub fn acked(&mut self, seqno: usize) { |
| 444 |
self.tokens.retain(|i| i.seqno != seqno); |
| 445 |
} |
| 446 |
} |
| 447 |
|
| 448 |
#[cfg(test)] |
| 449 |
mod tests { |
| 450 |
use neqo_common::Role; |
| 451 |
|
| 452 |
use super::NewTokenState; |
| 453 |
|
| 454 |
const ONE: &[u8] = &[1, 2, 3]; |
| 455 |
const TWO: &[u8] = &[4, 5]; |
| 456 |
|
| 457 |
#[test] |
| 458 |
fn duplicate_saved() { |
| 459 |
let mut tokens = NewTokenState::new(Role::Client); |
| 460 |
tokens.save_token(ONE.to_vec()); |
| 461 |
tokens.save_token(TWO.to_vec()); |
| 462 |
tokens.save_token(ONE.to_vec()); |
| 463 |
assert!(tokens.has_token()); |
| 464 |
assert!(tokens.take_token().is_some()); // probably TWO |
| 465 |
assert!(tokens.has_token()); |
| 466 |
assert!(tokens.take_token().is_some()); // probably ONE |
| 467 |
assert!(!tokens.has_token()); |
| 468 |
assert!(tokens.take_token().is_none()); |
| 469 |
} |
| 470 |
|
| 471 |
#[test] |
| 472 |
fn duplicate_after_take() { |
| 473 |
let mut tokens = NewTokenState::new(Role::Client); |
| 474 |
tokens.save_token(ONE.to_vec()); |
| 475 |
tokens.save_token(TWO.to_vec()); |
| 476 |
assert!(tokens.has_token()); |
| 477 |
assert!(tokens.take_token().is_some()); // probably TWO |
| 478 |
tokens.save_token(ONE.to_vec()); |
| 479 |
assert!(tokens.has_token()); |
| 480 |
assert!(tokens.take_token().is_some()); // probably ONE |
| 481 |
assert!(!tokens.has_token()); |
| 482 |
assert!(tokens.take_token().is_none()); |
| 483 |
} |
| 484 |
|
| 485 |
#[test] |
| 486 |
fn duplicate_after_empty() { |
| 487 |
let mut tokens = NewTokenState::new(Role::Client); |
| 488 |
tokens.save_token(ONE.to_vec()); |
| 489 |
tokens.save_token(TWO.to_vec()); |
| 490 |
assert!(tokens.has_token()); |
| 491 |
assert!(tokens.take_token().is_some()); // probably TWO |
| 492 |
assert!(tokens.has_token()); |
| 493 |
assert!(tokens.take_token().is_some()); // probably ONE |
| 494 |
tokens.save_token(ONE.to_vec()); |
| 495 |
assert!(!tokens.has_token()); |
| 496 |
assert!(tokens.take_token().is_none()); |
| 497 |
} |
| 498 |
} |