Debian Codegraph @

third_party/rust/neqo-transport/src/packet/mod.rs

raw
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 // Encoding and decoding packets off the wire.
8
9 #![allow(
10 clippy::module_name_repetitions,
11 reason = "<https://github.com/mozilla/neqo/issues/2284#issuecomment-2782711813>"
12 )]
13
14 use std::{
15 cmp::min,
16 fmt,
17 ops::{Deref, DerefMut, Range},
18 time::Instant,
19 };
20
21 use enum_map::Enum;
22 use neqo_common::{hex, hex_with_len, qtrace, qwarn, Decoder, Encoder};
23 use neqo_crypto::random;
24 use strum::{EnumIter, FromRepr};
25
26 use crate::{
27 cid::{ConnectionId, ConnectionIdDecoder, ConnectionIdRef, MAX_CONNECTION_ID_LEN},
28 crypto::{CryptoDxState, CryptoStates, Epoch},
29 frame::FrameType,
30 recovery::SendProfile,
31 tracking::PacketNumberSpace,
32 version::{Version, WireVersion},
33 Error, Pmtud, Res,
34 };
35
36 /// `MIN_INITIAL_PACKET_SIZE` is the smallest packet that can be used to establish
37 /// a new connection across all QUIC versions this server supports.
38 pub const MIN_INITIAL_PACKET_SIZE: usize = 1200;
39
40 pub const PACKET_BIT_LONG: u8 = 0x80;
41 const PACKET_BIT_SHORT: u8 = 0x00;
42 const PACKET_BIT_FIXED_QUIC: u8 = 0x40;
43 const PACKET_BIT_SPIN: u8 = 0x20;
44 const PACKET_BIT_KEY_PHASE: u8 = 0x04;
45
46 const PACKET_HP_MASK_LONG: u8 = 0x0f;
47 const PACKET_HP_MASK_SHORT: u8 = 0x1f;
48
49 const SAMPLE_SIZE: usize = 16;
50 const SAMPLE_OFFSET: usize = 4;
51 const MAX_PACKET_NUMBER_LEN: usize = 4;
52
53 pub mod metadata;
54 mod retry;
55
56 pub use metadata::MetaData;
57
58 pub type PacketNumber = u64;
59
60 #[derive(Debug, Clone, Copy, PartialEq, Eq, Enum, EnumIter, FromRepr)]
61 #[repr(u8)]
62 pub enum PacketType {
63 Initial = 0,
64 ZeroRtt = 1,
65 Handshake = 2,
66 Retry = 3,
67 Short,
68 OtherVersion,
69 VersionNegotiation,
70 }
71
72 impl PacketType {
73 #[must_use]
74 fn from_byte(t: u8, v: Version) -> Self {
75 // Version2 adds one to the type, modulo 4
76 Self::from_repr(t.wrapping_sub(u8::from(v == Version::Version2)) & 3)
77 .expect("packet type in range")
78 }
79
80 #[must_use]
81 fn to_byte(self, v: Version) -> u8 {
82 assert!(
83 matches!(
84 self,
85 Self::Initial | Self::ZeroRtt | Self::Handshake | Self::Retry
86 ),
87 "is a long header packet type"
88 );
89 // Version2 adds one to the type, modulo 4
90 (self as u8 + u8::from(v == Version::Version2)) & 3
91 }
92 }
93
94 impl TryFrom<PacketType> for Epoch {
95 type Error = Error;
96
97 fn try_from(v: PacketType) -> Res<Self> {
98 match v {
99 PacketType::Initial => Ok(Self::Initial),
100 PacketType::ZeroRtt => Ok(Self::ZeroRtt),
101 PacketType::Handshake => Ok(Self::Handshake),
102 PacketType::Short => Ok(Self::ApplicationData),
103 _ => Err(Error::InvalidPacket),
104 }
105 }
106 }
107
108 impl From<Epoch> for PacketType {
109 fn from(cs: Epoch) -> Self {
110 match cs {
111 Epoch::Initial => Self::Initial,
112 Epoch::ZeroRtt => Self::ZeroRtt,
113 Epoch::Handshake => Self::Handshake,
114 Epoch::ApplicationData => Self::Short,
115 }
116 }
117 }
118
119 impl From<PacketNumberSpace> for PacketType {
120 fn from(space: PacketNumberSpace) -> Self {
121 match space {
122 PacketNumberSpace::Initial => Self::Initial,
123 PacketNumberSpace::Handshake => Self::Handshake,
124 PacketNumberSpace::ApplicationData => Self::Short,
125 }
126 }
127 }
128
129 struct PacketBuilderOffsets {
130 /// The bits of the first octet that need masking.
131 first_byte_mask: u8,
132 /// The offset of the length field.
133 len: usize,
134 /// The location of the packet number field.
135 pn: Range<usize>,
136 }
137
138 /// A packet builder that can be used to produce short packets and long packets.
139 /// This does not produce Retry or Version Negotiation.
140 pub struct PacketBuilder {
141 encoder: Encoder,
142 pn: PacketNumber,
143 header: Range<usize>,
144 offsets: PacketBuilderOffsets,
145 limit: usize,
146 /// Whether to pad the packet before construction.
147 padding: bool,
148 }
149
150 impl PacketBuilder {
151 /// The minimum useful frame size. If space is less than this, we will claim to be full.
152 pub const MINIMUM_FRAME_SIZE: usize = 2;
153
154 fn infer_limit(encoder: &Encoder) -> usize {
155 if encoder.capacity() > 64 {
156 encoder.capacity()
157 } else {
158 2048
159 }
160 }
161
162 /// Start building a short header packet.
163 ///
164 /// This doesn't fail if there isn't enough space; instead it returns a builder that
165 /// has no available space left. This allows the caller to extract the encoder
166 /// and any packets that might have been added before as adding a packet header is
167 /// only likely to fail if there are other packets already written.
168 ///
169 /// If, after calling this method, `remaining()` returns 0, then call `abort()` to get
170 /// the encoder back.
171 pub fn short(mut encoder: Encoder, key_phase: bool, dcid: Option<impl AsRef<[u8]>>) -> Self {
172 let mut limit = Self::infer_limit(&encoder);
173 let header_start = encoder.len();
174 // Check that there is enough space for the header.
175 // 5 = 1 (first byte) + 4 (packet number)
176 if limit > encoder.len()
177 && 5 + dcid.as_ref().map_or(0, |d| d.as_ref().len()) < limit - encoder.len()
178 {
179 encoder
180 .encode_byte(PACKET_BIT_SHORT | PACKET_BIT_FIXED_QUIC | (u8::from(key_phase) << 2));
181 if let Some(dcid) = dcid {
182 encoder.encode(dcid.as_ref());
183 }
184 } else {
185 limit = 0;
186 }
187 Self {
188 encoder,
189 pn: u64::MAX,
190 header: header_start..header_start,
191 offsets: PacketBuilderOffsets {
192 first_byte_mask: PACKET_HP_MASK_SHORT,
193 pn: 0..0,
194 len: 0,
195 },
196 limit,
197 padding: false,
198 }
199 }
200
201 /// Start building a long header packet.
202 /// For an Initial packet you will need to call `initial_token()`,
203 /// even if the token is empty.
204 ///
205 /// See `short()` for more on how to handle this in cases where there is no space.
206 pub fn long(
207 mut encoder: Encoder,
208 pt: PacketType,
209 version: Version,
210 mut dcid: Option<impl AsRef<[u8]>>,
211 mut scid: Option<impl AsRef<[u8]>>,
212 ) -> Self {
213 let mut limit = Self::infer_limit(&encoder);
214 let header_start = encoder.len();
215 // Check that there is enough space for the header.
216 // 11 = 1 (first byte) + 4 (version) + 2 (dcid+scid length) + 4 (packet number)
217 if limit > encoder.len()
218 && 11
219 + dcid.as_ref().map_or(0, |d| d.as_ref().len())
220 + scid.as_ref().map_or(0, |d| d.as_ref().len())
221 < limit - encoder.len()
222 {
223 encoder
224 .encode_byte(PACKET_BIT_LONG | PACKET_BIT_FIXED_QUIC | (pt.to_byte(version) << 4));
225 encoder.encode_uint(4, version.wire_version());
226 encoder.encode_vec(1, dcid.take().as_ref().map_or(&[], AsRef::as_ref));
227 encoder.encode_vec(1, scid.take().as_ref().map_or(&[], AsRef::as_ref));
228 } else {
229 limit = 0;
230 }
231
232 Self {
233 encoder,
234 pn: u64::MAX,
235 header: header_start..header_start,
236 offsets: PacketBuilderOffsets {
237 first_byte_mask: PACKET_HP_MASK_LONG,
238 pn: 0..0,
239 len: 0,
240 },
241 limit,
242 padding: false,
243 }
244 }
245
246 fn is_long(&self) -> bool {
247 self.as_ref()[self.header.start] & 0x80 == PACKET_BIT_LONG
248 }
249
250 /// This stores a value that can be used as a limit. This does not cause
251 /// this limit to be enforced until encryption occurs. Prior to that, it
252 /// is only used voluntarily by users of the builder, through `remaining()`.
253 pub fn set_limit(&mut self, limit: usize) {
254 self.limit = limit;
255 }
256
257 /// Set the initial limit for the packet, based on the profile and the PMTUD state.
258 /// Returns true if the packet needs padding.
259 pub fn set_initial_limit(
260 &mut self,
261 profile: &SendProfile,
262 aead_expansion: usize,
263 pmtud: &Pmtud,
264 ) -> bool {
265 if pmtud.needs_probe() {
266 debug_assert!(pmtud.probe_size() >= profile.limit());
267 self.limit = pmtud.probe_size() - aead_expansion;
268 true
269 } else {
270 self.limit = profile.limit() - aead_expansion;
271 false
272 }
273 }
274
275 /// Get the current limit.
276 #[must_use]
277 pub const fn limit(&self) -> usize {
278 self.limit
279 }
280
281 /// How many bytes remain against the size limit for the builder.
282 #[must_use]
283 pub fn remaining(&self) -> usize {
284 self.limit.saturating_sub(self.encoder.len())
285 }
286
287 /// Returns true if the packet has no more space for frames.
288 #[must_use]
289 pub fn is_full(&self) -> bool {
290 // No useful frame is smaller than 2 bytes long.
291 self.limit < self.encoder.len() + Self::MINIMUM_FRAME_SIZE
292 }
293
294 /// Adjust the limit to ensure that no more data is added.
295 pub fn mark_full(&mut self) {
296 self.limit = self.encoder.len();
297 }
298
299 /// Mark the packet as needing padding (or not).
300 pub fn enable_padding(&mut self, needs_padding: bool) {
301 self.padding = needs_padding;
302 }
303
304 /// Maybe pad with "PADDING" frames.
305 /// Only does so if padding was needed and this is a short packet.
306 /// Returns true if padding was added.
307 ///
308 /// # Panics
309 ///
310 /// Cannot happen.
311 pub fn pad(&mut self) -> bool {
312 if self.padding && !self.is_long() {
313 self.encoder.pad_to(self.limit, FrameType::Padding.into());
314 true
315 } else {
316 false
317 }
318 }
319
320 /// Add unpredictable values for unprotected parts of the packet.
321 pub fn scramble(&mut self, quic_bit: bool) {
322 debug_assert!(self.len() > self.header.start);
323 let mask = if quic_bit { PACKET_BIT_FIXED_QUIC } else { 0 }
324 | if self.is_long() { 0 } else { PACKET_BIT_SPIN };
325 let first = self.header.start;
326 self.encoder.as_mut()[first] ^= random::<1>()[0] & mask;
327 }
328
329 /// For an Initial packet, encode the token.
330 /// If you fail to do this, then you will not get a valid packet.
331 pub fn initial_token(&mut self, token: &[u8]) {
332 if Encoder::vvec_len(token.len()) < self.remaining() {
333 self.encoder.encode_vvec(token);
334 } else {
335 self.limit = 0;
336 }
337 }
338
339 /// Add a packet number of the given size.
340 /// For a long header packet, this also inserts a dummy length.
341 /// The length is filled in after calling `build`.
342 /// Does nothing if there isn't 4 bytes available other than render this builder
343 /// unusable; if `remaining()` returns 0 at any point, call `abort()`.
344 ///
345 /// # Panics
346 ///
347 /// This will panic if the packet number length is too large.
348 pub fn pn(&mut self, pn: PacketNumber, pn_len: usize) {
349 if self.remaining() < 4 {
350 self.limit = 0;
351 return;
352 }
353
354 // Reserve space for a length in long headers.
355 if self.is_long() {
356 self.offsets.len = self.encoder.len();
357 self.encoder.encode(&[0; 2]);
358 }
359
360 // This allows the input to be >4, which is absurd, but we can eat that.
361 let pn_len = min(MAX_PACKET_NUMBER_LEN, pn_len);
362 debug_assert_ne!(pn_len, 0);
363 // Encode the packet number and save its offset.
364 let pn_offset = self.encoder.len();
365 self.encoder.encode_uint(pn_len, pn);
366 self.offsets.pn = pn_offset..self.encoder.len();
367
368 // Now encode the packet number length and save the header length.
369 self.encoder.as_mut()[self.header.start] |=
370 u8::try_from(pn_len - 1).expect("packet number length fits in u8");
371 self.header.end = self.encoder.len();
372 self.pn = pn;
373 }
374
375 #[expect(clippy::cast_possible_truncation, reason = "AND'ing makes this safe.")]
376 fn write_len(&mut self, expansion: usize) {
377 let len = self.encoder.len() - (self.offsets.len + 2) + expansion;
378 self.encoder.as_mut()[self.offsets.len] = 0x40 | ((len >> 8) & 0x3f) as u8;
379 self.encoder.as_mut()[self.offsets.len + 1] = (len & 0xff) as u8;
380 }
381
382 fn pad_for_crypto(&mut self, crypto: &CryptoDxState) {
383 // Make sure that there is enough data in the packet.
384 // The length of the packet number plus the payload length needs to
385 // be at least 4 (MAX_PACKET_NUMBER_LEN) plus any amount by which
386 // the header protection sample exceeds the AEAD expansion.
387 let crypto_pad = crypto.extra_padding();
388 self.encoder.pad_to(
389 self.offsets.pn.start + MAX_PACKET_NUMBER_LEN + crypto_pad,
390 0,
391 );
392 }
393
394 /// A lot of frames here are just a collection of varints.
395 /// This helper functions writes a frame like that safely, returning `true` if
396 /// a frame was written.
397 pub fn write_varint_frame(&mut self, values: &[u64]) -> bool {
398 let write = self.remaining()
399 >= values
400 .iter()
401 .map(|&v| Encoder::varint_len(v))
402 .sum::<usize>();
403 if write {
404 for v in values {
405 self.encode_varint(*v);
406 }
407 debug_assert!(self.len() <= self.limit());
408 }
409 write
410 }
411
412 /// Build the packet and return the encoder.
413 ///
414 /// # Errors
415 ///
416 /// This will return an error if the packet is too large.
417 pub fn build(mut self, crypto: &mut CryptoDxState) -> Res<Encoder> {
418 if self.len() > self.limit {
419 qwarn!("Packet contents are more than the limit");
420 debug_assert!(false);
421 return Err(Error::InternalError);
422 }
423
424 self.pad_for_crypto(crypto);
425 if self.offsets.len > 0 {
426 self.write_len(crypto.expansion());
427 }
428
429 qtrace!(
430 "Packet build pn={} hdr={} body={}",
431 self.pn,
432 hex(&self.encoder.as_ref()[self.header.clone()]),
433 hex(&self.encoder.as_ref()[self.header.end..])
434 );
435
436 // Add space for crypto expansion.
437 let data_end = self.encoder.len();
438 self.pad_to(data_end + crypto.expansion(), 0);
439
440 // Calculate the mask.
441 let ciphertext = crypto.encrypt(self.pn, self.header.clone(), self.encoder.as_mut())?;
442 let offset = SAMPLE_OFFSET - self.offsets.pn.len();
443 if offset + SAMPLE_SIZE > ciphertext.len() {
444 return Err(Error::InternalError);
445 }
446 let sample = &ciphertext[offset..offset + SAMPLE_SIZE];
447 let mask = crypto.compute_mask(sample)?;
448
449 // Apply the mask.
450 self.encoder.as_mut()[self.header.start] ^= mask[0] & self.offsets.first_byte_mask;
451 for (i, j) in (1..=self.offsets.pn.len()).zip(self.offsets.pn) {
452 self.encoder.as_mut()[j] ^= mask[i];
453 }
454
455 qtrace!("Packet built {}", hex(&self.encoder));
456 Ok(self.encoder)
457 }
458
459 /// Abort writing of this packet and return the encoder.
460 #[must_use]
461 pub fn abort(mut self) -> Encoder {
462 self.encoder.truncate(self.header.start);
463 self.encoder
464 }
465
466 /// Work out if nothing was added after the header.
467 #[must_use]
468 pub fn packet_empty(&self) -> bool {
469 self.encoder.len() == self.header.end
470 }
471
472 /// Make a retry packet.
473 /// As this is a simple packet, this is just an associated function.
474 /// As Retry is odd (it has to be constructed with leading bytes),
475 /// this returns a [`Vec<u8>`] rather than building on an encoder.
476 ///
477 /// # Errors
478 ///
479 /// This will return an error if AEAD encrypt fails.
480 pub fn retry(
481 version: Version,
482 dcid: &[u8],
483 scid: &[u8],
484 token: &[u8],
485 odcid: &[u8],
486 ) -> Res<Vec<u8>> {
487 let mut encoder = Encoder::default();
488 encoder.encode_vec(1, odcid);
489 let start = encoder.len();
490 encoder.encode_byte(
491 PACKET_BIT_LONG
492 | PACKET_BIT_FIXED_QUIC
493 | (PacketType::Retry.to_byte(version) << 4)
494 | (random::<1>()[0] & 0xf),
495 );
496 encoder.encode_uint(4, version.wire_version());
497 encoder.encode_vec(1, dcid);
498 encoder.encode_vec(1, scid);
499 debug_assert_ne!(token.len(), 0);
500 encoder.encode(token);
501 let tag = retry::use_aead(version, |aead| {
502 let mut buf = vec![0; aead.expansion()];
503 Ok(aead.encrypt(0, encoder.as_ref(), &[], &mut buf)?.to_vec())
504 })?;
505 encoder.encode(&tag);
506 let mut complete: Vec<u8> = encoder.into();
507 Ok(complete.split_off(start))
508 }
509
510 /// Make a Version Negotiation packet.
511 #[must_use]
512 pub fn version_negotiation(
513 dcid: &[u8],
514 scid: &[u8],
515 client_version: u32,
516 versions: &[Version],
517 ) -> Vec<u8> {
518 let mut encoder = Encoder::default();
519 let mut grease = random::<4>();
520 // This will not include the "QUIC bit" sometimes. Intentionally.
521 encoder.encode_byte(PACKET_BIT_LONG | (grease[3] & 0x7f));
522 encoder.encode(&[0; 4]); // Zero version == VN.
523 encoder.encode_vec(1, dcid);
524 encoder.encode_vec(1, scid);
525
526 for v in versions {
527 encoder.encode_uint(4, v.wire_version());
528 }
529 // Add a greased version, using the randomness already generated.
530 for g in &mut grease[..3] {
531 *g = *g & 0xf0 | 0x0a;
532 }
533
534 // Ensure our greased version does not collide with the client version
535 // by making the last byte differ from the client initial.
536 grease[3] = (client_version.wrapping_add(0x10) & 0xf0) as u8 | 0x0a;
537 encoder.encode(&grease[..4]);
538
539 Vec::from(encoder)
540 }
541 }
542
543 impl Deref for PacketBuilder {
544 type Target = Encoder;
545
546 fn deref(&self) -> &Self::Target {
547 &self.encoder
548 }
549 }
550
551 impl DerefMut for PacketBuilder {
552 fn deref_mut(&mut self) -> &mut Self::Target {
553 &mut self.encoder
554 }
555 }
556
557 impl From<PacketBuilder> for Encoder {
558 fn from(v: PacketBuilder) -> Self {
559 v.encoder
560 }
561 }
562
563 /// `PublicPacket` holds information from packets that is public only. This allows for
564 /// processing of packets prior to decryption.
565 pub struct PublicPacket<'a> {
566 /// The packet type.
567 packet_type: PacketType,
568 /// The recovered destination connection ID.
569 dcid: ConnectionId,
570 /// The source connection ID, if this is a long header packet.
571 scid: Option<ConnectionId>,
572 /// Any token that is included in the packet (Retry always has a token; Initial sometimes
573 /// does). This is empty when there is no token.
574 token: Vec<u8>,
575 /// The size of the header, not including the packet number.
576 header_len: usize,
577 /// Protocol version, if present in header.
578 version: Option<WireVersion>,
579 /// A reference to the entire packet, including the header.
580 data: &'a mut [u8],
581 }
582
583 impl<'a> PublicPacket<'a> {
584 fn opt<T>(v: Option<T>) -> Res<T> {
585 v.map_or_else(|| Err(Error::NoMoreData), |v| Ok(v))
586 }
587
588 /// Decode the type-specific portions of a long header.
589 /// This includes reading the length and the remainder of the packet.
590 /// Returns a tuple of any token and the length of the header.
591 fn decode_long(
592 decoder: &mut Decoder<'a>,
593 packet_type: PacketType,
594 version: Version,
595 ) -> Res<(&'a [u8], usize)> {
596 if packet_type == PacketType::Retry {
597 let header_len = decoder.offset();
598 let expansion = retry::expansion(version);
599 let token = decoder
600 .remaining()
601 .checked_sub(expansion)
602 .map_or(Err(Error::InvalidPacket), |v| Self::opt(decoder.decode(v)))?;
603 if token.is_empty() {
604 return Err(Error::InvalidPacket);
605 }
606 Self::opt(decoder.decode(expansion))?;
607 return Ok((token, header_len));
608 }
609 let token = if packet_type == PacketType::Initial {
610 Self::opt(decoder.decode_vvec())?
611 } else {
612 &[]
613 };
614 let len = Self::opt(decoder.decode_varint())?;
615 let header_len = decoder.offset();
616 let _body = Self::opt(decoder.decode(usize::try_from(len)?))?;
617 Ok((token, header_len))
618 }
619
620 /// Decode the common parts of a packet. This provides minimal parsing and validation.
621 /// Returns a tuple of a `PublicPacket` and a slice with any remainder from the datagram.
622 ///
623 /// # Errors
624 ///
625 /// This will return an error if the packet could not be decoded.
626 pub fn decode(
627 data: &'a mut [u8],
628 dcid_decoder: &dyn ConnectionIdDecoder,
629 ) -> Res<(Self, &'a mut [u8])> {
630 let mut decoder = Decoder::new(data);
631 let first = Self::opt(decoder.decode_uint::<u8>())?;
632
633 if first & 0x80 == PACKET_BIT_SHORT {
634 // Conveniently, this also guarantees that there is enough space
635 // for a connection ID of any size.
636 if decoder.remaining() < SAMPLE_OFFSET + SAMPLE_SIZE {
637 return Err(Error::InvalidPacket);
638 }
639 let dcid = Self::opt(dcid_decoder.decode_cid(&mut decoder))?.into();
640 if decoder.remaining() < SAMPLE_OFFSET + SAMPLE_SIZE {
641 return Err(Error::InvalidPacket);
642 }
643 let header_len = decoder.offset();
644
645 return Ok((
646 Self {
647 packet_type: PacketType::Short,
648 dcid,
649 scid: None,
650 token: vec![],
651 header_len,
652 version: None,
653 data,
654 },
655 &mut [],
656 ));
657 }
658
659 // Generic long header.
660 let version = Self::opt(decoder.decode_uint())?;
661 let dcid = ConnectionIdRef::from(Self::opt(decoder.decode_vec(1))?).into();
662 let scid = ConnectionIdRef::from(Self::opt(decoder.decode_vec(1))?).into();
663
664 // Version negotiation.
665 if version == 0 {
666 return Ok((
667 Self {
668 packet_type: PacketType::VersionNegotiation,
669 dcid,
670 scid: Some(scid),
671 token: vec![],
672 header_len: decoder.offset(),
673 version: None,
674 data,
675 },
676 &mut [],
677 ));
678 }
679
680 // Check that this is a long header from a supported version.
681 let Ok(version) = Version::try_from(version) else {
682 return Ok((
683 Self {
684 packet_type: PacketType::OtherVersion,
685 dcid,
686 scid: Some(scid),
687 token: vec![],
688 header_len: decoder.offset(),
689 version: Some(version),
690 data,
691 },
692 &mut [],
693 ));
694 };
695
696 if dcid.len() > MAX_CONNECTION_ID_LEN || scid.len() > MAX_CONNECTION_ID_LEN {
697 return Err(Error::InvalidPacket);
698 }
699 let packet_type = PacketType::from_byte((first >> 4) & 3, version);
700
701 // The type-specific code includes a token. This consumes the remainder of the packet.
702 let (token, header_len) = PublicPacket::decode_long(&mut decoder, packet_type, version)?;
703 let token = token.to_vec();
704 let end = data.len() - decoder.remaining();
705 let (data, remainder) = data.split_at_mut(end);
706 Ok((
707 Self {
708 packet_type,
709 dcid,
710 scid: Some(scid),
711 token,
712 header_len,
713 version: Some(version.wire_version()),
714 data,
715 },
716 remainder,
717 ))
718 }
719
720 /// Validate the given packet as though it were a retry.
721 #[must_use]
722 pub fn is_valid_retry(&self, odcid: &ConnectionId) -> bool {
723 if self.packet_type != PacketType::Retry {
724 return false;
725 }
726 let Some(version) = self.version() else {
727 return false;
728 };
729 let expansion = retry::expansion(version);
730 if self.data.len() <= expansion {
731 return false;
732 }
733 let (header, tag) = self.data.split_at(self.data.len() - expansion);
734 let mut encoder = Encoder::with_capacity(self.data.len());
735 encoder.encode_vec(1, odcid);
736 encoder.encode(header);
737 retry::use_aead(version, |aead| {
738 let mut buf = vec![0; expansion];
739 Ok(aead.decrypt(0, encoder.as_ref(), tag, &mut buf)?.is_empty())
740 })
741 .unwrap_or(false)
742 }
743
744 #[must_use]
745 pub fn is_valid_initial(&self) -> bool {
746 // Packet has to be an initial, with a DCID of 8 bytes, or a token.
747 // Note: the Server class validates the token and checks the length.
748 self.packet_type == PacketType::Initial
749 && (self.dcid().len() >= 8 || !self.token.is_empty())
750 }
751
752 #[must_use]
753 pub const fn packet_type(&self) -> PacketType {
754 self.packet_type
755 }
756
757 #[must_use]
758 pub fn dcid(&self) -> ConnectionIdRef {
759 self.dcid.as_cid_ref()
760 }
761
762 /// # Panics
763 ///
764 /// This will panic if called for a short header packet.
765 #[must_use]
766 pub fn scid(&self) -> ConnectionIdRef {
767 self.scid
768 .as_ref()
769 .expect("should only be called for long header packets")
770 .as_cid_ref()
771 }
772
773 #[must_use]
774 pub fn token(&self) -> &[u8] {
775 &self.token
776 }
777
778 #[must_use]
779 pub fn version(&self) -> Option<Version> {
780 Version::try_from(self.version?).ok()
781 }
782
783 #[must_use]
784 pub fn wire_version(&self) -> WireVersion {
785 debug_assert!(self.version.is_some());
786 self.version.unwrap_or(0)
787 }
788
789 #[allow(
790 clippy::allow_attributes,
791 clippy::len_without_is_empty,
792 reason = "Is OK here."
793 )]
794 #[must_use]
795 pub const fn len(&self) -> usize {
796 self.data.len()
797 }
798
799 #[must_use]
800 pub fn data(&self) -> &[u8] {
801 self.data
802 }
803
804 const fn decode_pn(expected: PacketNumber, pn: u64, w: usize) -> PacketNumber {
805 let window = 1_u64 << (w * 8);
806 let candidate = (expected & !(window - 1)) | pn;
807 if candidate + (window / 2) <= expected {
808 candidate + window
809 } else if candidate > expected + (window / 2) {
810 match candidate.checked_sub(window) {
811 Some(pn_sub) => pn_sub,
812 None => candidate,
813 }
814 } else {
815 candidate
816 }
817 }
818
819 /// Decrypt the header of the packet.
820 fn decrypt_header(
821 &mut self,
822 crypto: &CryptoDxState,
823 ) -> Res<(bool, PacketNumber, Range<usize>)> {
824 assert_ne!(self.packet_type, PacketType::Retry);
825 assert_ne!(self.packet_type, PacketType::VersionNegotiation);
826
827 let sample_offset = self.header_len + SAMPLE_OFFSET;
828 let mask = self
829 .data
830 .get(sample_offset..(sample_offset + SAMPLE_SIZE))
831 .map_or(Err(Error::NoMoreData), |sample| {
832 qtrace!("unmask hdr={}", hex(&self.data[..sample_offset]));
833 crypto.compute_mask(sample)
834 })?;
835
836 // Un-mask the leading byte.
837 let bits = if self.packet_type == PacketType::Short {
838 PACKET_HP_MASK_SHORT
839 } else {
840 PACKET_HP_MASK_LONG
841 };
842 let first_byte = self.data[0] ^ (mask[0] & bits);
843
844 let mut hdrbytes = 0..self.header_len + 4;
845 self.data[0] = first_byte;
846
847 // Unmask the PN.
848 let mut pn_encoded: u64 = 0;
849 let mut pn_bytes =
850 self.data[self.header_len..self.header_len + MAX_PACKET_NUMBER_LEN].to_vec();
851 for i in 0..MAX_PACKET_NUMBER_LEN {
852 pn_bytes[i] ^= mask[1 + i];
853 pn_encoded <<= 8;
854 pn_encoded += u64::from(pn_bytes[i]);
855 }
856 // Now decode the packet number length and apply it, hopefully in constant time.
857 let pn_len = usize::from((first_byte & 0x3) + 1);
858 self.data[self.header_len..self.header_len + pn_len].copy_from_slice(&pn_bytes[..pn_len]);
859 hdrbytes.end = self.header_len + pn_len;
860 pn_encoded >>= 8 * (MAX_PACKET_NUMBER_LEN - pn_len);
861
862 qtrace!("unmasked hdr={}", hex(&self.data[hdrbytes.clone()]));
863
864 let key_phase = self.packet_type == PacketType::Short
865 && (first_byte & PACKET_BIT_KEY_PHASE) == PACKET_BIT_KEY_PHASE;
866 let pn = Self::decode_pn(crypto.next_pn(), pn_encoded, pn_len);
867 Ok((key_phase, pn, hdrbytes))
868 }
869
870 /// # Errors
871 ///
872 /// This will return an error if the packet cannot be decrypted.
873 pub fn decrypt(
874 &mut self,
875 crypto: &mut CryptoStates,
876 release_at: Instant,
877 ) -> Res<DecryptedPacket> {
878 let epoch: Epoch = self.packet_type.try_into()?;
879 // When we don't have a version, the crypto code doesn't need a version
880 // for lookup, so use the default, but fix it up if decryption succeeds.
881 let version = self.version().unwrap_or_default();
882 // This has to work in two stages because we need to remove header protection
883 // before picking the keys to use.
884 if let Some(rx) = crypto.rx_hp(version, epoch) {
885 // Note that this will dump early, which creates a side-channel.
886 // This is OK in this case because we the only reason this can
887 // fail is if the cryptographic module is bad or the packet is
888 // too small (which is public information).
889 let (key_phase, pn, header) = self.decrypt_header(rx)?;
890 qtrace!("[{rx}] decoded header: {header:?}");
891 let Some(rx) = crypto.rx(version, epoch, key_phase) else {
892 return Err(Error::DecryptError);
893 };
894 let version = rx.version(); // Version fixup; see above.
895 let d = rx.decrypt(pn, header, self.data)?;
896 // If this is the first packet ever successfully decrypted
897 // using `rx`, make sure to initiate a key update.
898 if rx.needs_update() {
899 crypto.key_update_received(release_at)?;
900 }
901 crypto.check_pn_overlap()?;
902 Ok(DecryptedPacket {
903 version,
904 pt: self.packet_type,
905 pn,
906 data: d,
907 })
908 } else if crypto.rx_pending(epoch) {
909 Err(Error::KeysPending(epoch))
910 } else {
911 qtrace!("keys for {epoch:?} already discarded");
912 Err(Error::KeysDiscarded(epoch))
913 }
914 }
915
916 /// # Errors
917 ///
918 /// This will return an error if the packet is not a version negotiation packet
919 /// or if the versions cannot be decoded.
920 pub fn supported_versions(&self) -> Res<Vec<WireVersion>> {
921 if self.packet_type != PacketType::VersionNegotiation {
922 return Err(Error::InvalidPacket);
923 }
924 let mut decoder = Decoder::new(&self.data[self.header_len..]);
925 let mut res = Vec::new();
926 while decoder.remaining() > 0 {
927 let version = Self::opt(decoder.decode_uint::<WireVersion>())?;
928 res.push(version);
929 }
930 Ok(res)
931 }
932 }
933
934 impl fmt::Debug for PublicPacket<'_> {
935 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
936 write!(
937 f,
938 "{:?}: {} {}",
939 self.packet_type(),
940 hex_with_len(&self.data[..self.header_len]),
941 hex_with_len(&self.data[self.header_len..])
942 )
943 }
944 }
945
946 pub struct DecryptedPacket<'a> {
947 version: Version,
948 pt: PacketType,
949 pn: PacketNumber,
950 data: &'a [u8],
951 }
952
953 impl DecryptedPacket<'_> {
954 #[must_use]
955 pub const fn version(&self) -> Version {
956 self.version
957 }
958
959 #[must_use]
960 pub const fn packet_type(&self) -> PacketType {
961 self.pt
962 }
963
964 #[must_use]
965 pub const fn pn(&self) -> PacketNumber {
966 self.pn
967 }
968 }
969
970 impl Deref for DecryptedPacket<'_> {
971 type Target = [u8];
972
973 fn deref(&self) -> &Self::Target {
974 self.data
975 }
976 }
977
978 #[cfg(all(test, not(feature = "disable-encryption")))]
979 #[cfg(test)]
980 mod tests {
981 use neqo_common::Encoder;
982 use test_fixture::{fixture_init, now};
983
984 use crate::{
985 cid::MAX_CONNECTION_ID_LEN,
986 crypto::{CryptoDxState, CryptoStates},
987 packet::{
988 PacketBuilder, PacketType, PublicPacket, PACKET_BIT_FIXED_QUIC, PACKET_BIT_LONG,
989 PACKET_BIT_SPIN,
990 },
991 ConnectionId, EmptyConnectionIdGenerator, RandomConnectionIdGenerator, Version,
992 };
993
994 const CLIENT_CID: &[u8] = &[0x83, 0x94, 0xc8, 0xf0, 0x3e, 0x51, 0x57, 0x08];
995 const SERVER_CID: &[u8] = &[0xf0, 0x67, 0xa5, 0x50, 0x2a, 0x42, 0x62, 0xb5];
996
997 /// This is a connection ID manager, which is only used for decoding short header packets.
998 const fn cid_mgr() -> RandomConnectionIdGenerator {
999 RandomConnectionIdGenerator::new(SERVER_CID.len())
1000 }
1001
1002 const SAMPLE_INITIAL_PAYLOAD: &[u8] = &[
1003 0x02, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x40, 0x5a, 0x02, 0x00, 0x00, 0x56, 0x03, 0x03,
1004 0xee, 0xfc, 0xe7, 0xf7, 0xb3, 0x7b, 0xa1, 0xd1, 0x63, 0x2e, 0x96, 0x67, 0x78, 0x25, 0xdd,
1005 0xf7, 0x39, 0x88, 0xcf, 0xc7, 0x98, 0x25, 0xdf, 0x56, 0x6d, 0xc5, 0x43, 0x0b, 0x9a, 0x04,
1006 0x5a, 0x12, 0x00, 0x13, 0x01, 0x00, 0x00, 0x2e, 0x00, 0x33, 0x00, 0x24, 0x00, 0x1d, 0x00,
1007 0x20, 0x9d, 0x3c, 0x94, 0x0d, 0x89, 0x69, 0x0b, 0x84, 0xd0, 0x8a, 0x60, 0x99, 0x3c, 0x14,
1008 0x4e, 0xca, 0x68, 0x4d, 0x10, 0x81, 0x28, 0x7c, 0x83, 0x4d, 0x53, 0x11, 0xbc, 0xf3, 0x2b,
1009 0xb9, 0xda, 0x1a, 0x00, 0x2b, 0x00, 0x02, 0x03, 0x04,
1010 ];
1011 const SAMPLE_INITIAL: &[u8] = &[
1012 0xcf, 0x00, 0x00, 0x00, 0x01, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a, 0x42, 0x62, 0xb5,
1013 0x00, 0x40, 0x75, 0xc0, 0xd9, 0x5a, 0x48, 0x2c, 0xd0, 0x99, 0x1c, 0xd2, 0x5b, 0x0a, 0xac,
1014 0x40, 0x6a, 0x58, 0x16, 0xb6, 0x39, 0x41, 0x00, 0xf3, 0x7a, 0x1c, 0x69, 0x79, 0x75, 0x54,
1015 0x78, 0x0b, 0xb3, 0x8c, 0xc5, 0xa9, 0x9f, 0x5e, 0xde, 0x4c, 0xf7, 0x3c, 0x3e, 0xc2, 0x49,
1016 0x3a, 0x18, 0x39, 0xb3, 0xdb, 0xcb, 0xa3, 0xf6, 0xea, 0x46, 0xc5, 0xb7, 0x68, 0x4d, 0xf3,
1017 0x54, 0x8e, 0x7d, 0xde, 0xb9, 0xc3, 0xbf, 0x9c, 0x73, 0xcc, 0x3f, 0x3b, 0xde, 0xd7, 0x4b,
1018 0x56, 0x2b, 0xfb, 0x19, 0xfb, 0x84, 0x02, 0x2f, 0x8e, 0xf4, 0xcd, 0xd9, 0x37, 0x95, 0xd7,
1019 0x7d, 0x06, 0xed, 0xbb, 0x7a, 0xaf, 0x2f, 0x58, 0x89, 0x18, 0x50, 0xab, 0xbd, 0xca, 0x3d,
1020 0x20, 0x39, 0x8c, 0x27, 0x64, 0x56, 0xcb, 0xc4, 0x21, 0x58, 0x40, 0x7d, 0xd0, 0x74, 0xee,
1021 ];
1022
1023 #[test]
1024 fn sample_server_initial() {
1025 fixture_init();
1026 let mut prot = CryptoDxState::test_default();
1027
1028 // The spec uses PN=1, but our crypto refuses to skip packet numbers.
1029 // So burn an encryption:
1030 let mut burn = [0; 16];
1031 prot.encrypt(0, 0..0, &mut burn).expect("burn OK");
1032 assert_eq!(burn.len(), prot.expansion());
1033
1034 let mut builder = PacketBuilder::long(
1035 Encoder::new(),
1036 PacketType::Initial,
1037 Version::default(),
1038 None::<&[u8]>,
1039 Some(ConnectionId::from(SERVER_CID)),
1040 );
1041 builder.initial_token(&[]);
1042 builder.pn(1, 2);
1043 builder.encode(SAMPLE_INITIAL_PAYLOAD);
1044 let packet = builder.build(&mut prot).expect("build");
1045 assert_eq!(packet.as_ref(), SAMPLE_INITIAL);
1046 }
1047
1048 #[test]
1049 fn decrypt_initial() {
1050 const EXTRA: &[u8] = &[0xce; 33];
1051
1052 fixture_init();
1053 let mut padded = SAMPLE_INITIAL.to_vec();
1054 padded.extend_from_slice(EXTRA);
1055 let (mut packet, remainder) = PublicPacket::decode(&mut padded, &cid_mgr()).unwrap();
1056 assert_eq!(packet.packet_type(), PacketType::Initial);
1057 assert_eq!(&packet.dcid()[..], &[] as &[u8]);
1058 assert_eq!(&packet.scid()[..], SERVER_CID);
1059 assert!(packet.token().is_empty());
1060 assert_eq!(remainder, EXTRA);
1061
1062 let decrypted = packet
1063 .decrypt(&mut CryptoStates::test_default(), now())
1064 .unwrap();
1065 assert_eq!(decrypted.pn(), 1);
1066 }
1067
1068 #[test]
1069 fn disallow_long_dcid() {
1070 let mut enc = Encoder::new();
1071 enc.encode_byte(PACKET_BIT_LONG | PACKET_BIT_FIXED_QUIC);
1072 enc.encode_uint(4, Version::default().wire_version());
1073 enc.encode_vec(1, &[0x00; MAX_CONNECTION_ID_LEN + 1]);
1074 enc.encode_vec(1, &[]);
1075 enc.encode(&[0xff; 40]); // junk
1076
1077 assert!(PublicPacket::decode(enc.as_mut(), &cid_mgr()).is_err());
1078 }
1079
1080 #[test]
1081 fn disallow_long_scid() {
1082 let mut enc = Encoder::new();
1083 enc.encode_byte(PACKET_BIT_LONG | PACKET_BIT_FIXED_QUIC);
1084 enc.encode_uint(4, Version::default().wire_version());
1085 enc.encode_vec(1, &[]);
1086 enc.encode_vec(1, &[0x00; MAX_CONNECTION_ID_LEN + 2]);
1087 enc.encode(&[0xff; 40]); // junk
1088
1089 assert!(PublicPacket::decode(enc.as_mut(), &cid_mgr()).is_err());
1090 }
1091
1092 const SAMPLE_SHORT: &[u8] = &[
1093 0x40, 0xf0, 0x67, 0xa5, 0x50, 0x2a, 0x42, 0x62, 0xb5, 0xf4, 0xa8, 0x30, 0x39, 0xc4, 0x7d,
1094 0x99, 0xe3, 0x94, 0x1c, 0x9b, 0xb9, 0x7a, 0x30, 0x1d, 0xd5, 0x8f, 0xf3, 0xdd, 0xa9,
1095 ];
1096 const SAMPLE_SHORT_PAYLOAD: &[u8] = &[0; 3];
1097
1098 #[test]
1099 fn build_short() {
1100 fixture_init();
1101 let mut builder =
1102 PacketBuilder::short(Encoder::new(), true, Some(ConnectionId::from(SERVER_CID)));
1103 builder.pn(0, 1);
1104 builder.encode(SAMPLE_SHORT_PAYLOAD); // Enough payload for sampling.
1105 let packet = builder
1106 .build(&mut CryptoDxState::test_default())
1107 .expect("build");
1108 assert_eq!(packet.as_ref(), SAMPLE_SHORT);
1109 }
1110
1111 #[test]
1112 fn scramble_short() {
1113 fixture_init();
1114 let mut firsts = Vec::new();
1115 for _ in 0..64 {
1116 let mut builder =
1117 PacketBuilder::short(Encoder::new(), true, Some(ConnectionId::from(SERVER_CID)));
1118 builder.scramble(true);
1119 builder.pn(0, 1);
1120 firsts.push(builder.as_ref()[0]);
1121 }
1122 let is_set = |bit| move |v| v & bit == bit;
1123 // There should be at least one value with the QUIC bit set:
1124 assert!(firsts.iter().any(is_set(PACKET_BIT_FIXED_QUIC)));
1125 // ... but not all:
1126 assert!(!firsts.iter().all(is_set(PACKET_BIT_FIXED_QUIC)));
1127 // There should be at least one value with the spin bit set:
1128 assert!(firsts.iter().any(is_set(PACKET_BIT_SPIN)));
1129 // ... but not all:
1130 assert!(!firsts.iter().all(is_set(PACKET_BIT_SPIN)));
1131 }
1132
1133 #[test]
1134 fn decode_short() {
1135 fixture_init();
1136 let mut sample_short = SAMPLE_SHORT.to_vec();
1137 let (mut packet, remainder) = PublicPacket::decode(&mut sample_short, &cid_mgr()).unwrap();
1138 assert_eq!(packet.packet_type(), PacketType::Short);
1139 assert!(remainder.is_empty());
1140 let decrypted = packet
1141 .decrypt(&mut CryptoStates::test_default(), now())
1142 .unwrap();
1143 assert_eq!(&decrypted[..], SAMPLE_SHORT_PAYLOAD);
1144 }
1145
1146 /// By telling the decoder that the connection ID is shorter than it really is, we get a
1147 /// decryption error.
1148 #[test]
1149 fn decode_short_bad_cid() {
1150 fixture_init();
1151 let mut sample_short = SAMPLE_SHORT.to_vec();
1152 let (mut packet, remainder) = PublicPacket::decode(
1153 &mut sample_short,
1154 &RandomConnectionIdGenerator::new(SERVER_CID.len() - 1),
1155 )
1156 .unwrap();
1157 assert_eq!(packet.packet_type(), PacketType::Short);
1158 assert!(remainder.is_empty());
1159 assert!(packet
1160 .decrypt(&mut CryptoStates::test_default(), now())
1161 .is_err());
1162 }
1163
1164 /// Saying that the connection ID is longer causes the initial decode to fail.
1165 #[test]
1166 fn decode_short_long_cid() {
1167 let mut sample_short = SAMPLE_SHORT.to_vec();
1168 assert!(PublicPacket::decode(
1169 &mut sample_short,
1170 &RandomConnectionIdGenerator::new(SERVER_CID.len() + 1)
1171 )
1172 .is_err());
1173 }
1174
1175 #[test]
1176 fn build_two() {
1177 fixture_init();
1178 let mut prot = CryptoDxState::test_default();
1179 let mut builder = PacketBuilder::long(
1180 Encoder::new(),
1181 PacketType::Handshake,
1182 Version::default(),
1183 Some(ConnectionId::from(SERVER_CID)),
1184 Some(ConnectionId::from(CLIENT_CID)),
1185 );
1186 builder.pn(0, 1);
1187 builder.encode(&[0; 3]);
1188 let encoder = builder.build(&mut prot).expect("build");
1189 assert_eq!(encoder.len(), 45);
1190 let first = encoder.clone();
1191
1192 let mut builder =
1193 PacketBuilder::short(encoder, false, Some(ConnectionId::from(SERVER_CID)));
1194 builder.pn(1, 3);
1195 builder.encode(&[0]); // Minimal size (packet number is big enough).
1196 let encoder = builder.build(&mut prot).expect("build");
1197 assert_eq!(
1198 first.as_ref(),
1199 &encoder.as_ref()[..first.len()],
1200 "the first packet should be a prefix"
1201 );
1202 assert_eq!(encoder.len(), 45 + 29);
1203 }
1204
1205 #[test]
1206 fn build_long() {
1207 const EXPECTED: &[u8] = &[
1208 0xe4, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x40, 0x14, 0xfb, 0xa9, 0x32, 0x3a, 0xf8,
1209 0xbb, 0x18, 0x63, 0xc6, 0xbd, 0x78, 0x0e, 0xba, 0x0c, 0x98, 0x65, 0x58, 0xc9, 0x62,
1210 0x31,
1211 ];
1212
1213 fixture_init();
1214 let mut builder = PacketBuilder::long(
1215 Encoder::new(),
1216 PacketType::Handshake,
1217 Version::default(),
1218 None::<&[u8]>,
1219 None::<&[u8]>,
1220 );
1221 builder.pn(0, 1);
1222 builder.encode(&[1, 2, 3]);
1223 let packet = builder.build(&mut CryptoDxState::test_default()).unwrap();
1224 assert_eq!(packet.as_ref(), EXPECTED);
1225 }
1226
1227 #[test]
1228 fn scramble_long() {
1229 fixture_init();
1230 let mut found_unset = false;
1231 let mut found_set = false;
1232 for _ in 1..64 {
1233 let mut builder = PacketBuilder::long(
1234 Encoder::new(),
1235 PacketType::Handshake,
1236 Version::default(),
1237 None::<&[u8]>,
1238 None::<&[u8]>,
1239 );
1240 builder.pn(0, 1);
1241 builder.scramble(true);
1242 if (builder.as_ref()[0] & PACKET_BIT_FIXED_QUIC) == 0 {
1243 found_unset = true;
1244 } else {
1245 found_set = true;
1246 }
1247 }
1248 assert!(found_unset);
1249 assert!(found_set);
1250 }
1251
1252 #[test]
1253 fn build_abort() {
1254 let mut builder = PacketBuilder::long(
1255 Encoder::new(),
1256 PacketType::Initial,
1257 Version::default(),
1258 None::<&[u8]>,
1259 Some(ConnectionId::from(SERVER_CID)),
1260 );
1261 assert_ne!(builder.remaining(), 0);
1262 builder.initial_token(&[]);
1263 assert_ne!(builder.remaining(), 0);
1264 builder.pn(1, 2);
1265 assert_ne!(builder.remaining(), 0);
1266 let encoder = builder.abort();
1267 assert!(encoder.is_empty());
1268 }
1269
1270 #[test]
1271 fn build_insufficient_space() {
1272 fixture_init();
1273
1274 let mut builder = PacketBuilder::short(
1275 Encoder::with_capacity(100),
1276 true,
1277 Some(ConnectionId::from(SERVER_CID)),
1278 );
1279 builder.pn(0, 1);
1280 // Pad, but not up to the full capacity. Leave enough space for the
1281 // AEAD expansion and some extra, but not for an entire long header.
1282 builder.set_limit(75);
1283 builder.enable_padding(true);
1284 assert!(builder.pad());
1285 let encoder = builder.build(&mut CryptoDxState::test_default()).unwrap();
1286 let encoder_copy = encoder.clone();
1287
1288 let builder = PacketBuilder::long(
1289 encoder,
1290 PacketType::Initial,
1291 Version::default(),
1292 Some(ConnectionId::from(SERVER_CID)),
1293 Some(ConnectionId::from(SERVER_CID)),
1294 );
1295 assert_eq!(builder.remaining(), 0);
1296 assert_eq!(builder.abort(), encoder_copy);
1297 }
1298
1299 const SAMPLE_RETRY_V2: &[u8] = &[
1300 0xcf, 0x6b, 0x33, 0x43, 0xcf, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a, 0x42, 0x62, 0xb5,
1301 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0xc8, 0x64, 0x6c, 0xe8, 0xbf, 0xe3, 0x39, 0x52, 0xd9, 0x55,
1302 0x54, 0x36, 0x65, 0xdc, 0xc7, 0xb6,
1303 ];
1304
1305 const SAMPLE_RETRY_V1: &[u8] = &[
1306 0xff, 0x00, 0x00, 0x00, 0x01, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a, 0x42, 0x62, 0xb5,
1307 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x04, 0xa2, 0x65, 0xba, 0x2e, 0xff, 0x4d, 0x82, 0x90, 0x58,
1308 0xfb, 0x3f, 0x0f, 0x24, 0x96, 0xba,
1309 ];
1310
1311 const SAMPLE_RETRY_29: &[u8] = &[
1312 0xff, 0xff, 0x00, 0x00, 0x1d, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a, 0x42, 0x62, 0xb5,
1313 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0xd1, 0x69, 0x26, 0xd8, 0x1f, 0x6f, 0x9c, 0xa2, 0x95, 0x3a,
1314 0x8a, 0xa4, 0x57, 0x5e, 0x1e, 0x49,
1315 ];
1316
1317 const RETRY_TOKEN: &[u8] = b"token";
1318
1319 #[cfg(test)]
1320 fn build_retry_single(version: Version, sample_retry: &[u8]) {
1321 fixture_init();
1322 let mut retry =
1323 PacketBuilder::retry(version, &[], SERVER_CID, RETRY_TOKEN, CLIENT_CID).unwrap();
1324
1325 let (packet, remainder) = PublicPacket::decode(&mut retry, &cid_mgr()).unwrap();
1326 assert!(packet.is_valid_retry(&ConnectionId::from(CLIENT_CID)));
1327 assert!(remainder.is_empty());
1328
1329 // The builder adds randomness, which makes expectations hard.
1330 // So only do a full check when that randomness matches up.
1331 if retry[0] == sample_retry[0] {
1332 assert_eq!(&retry, &sample_retry);
1333 } else {
1334 // Otherwise, just check that the header is OK.
1335 assert_eq!(
1336 retry[0] & 0xf0,
1337 0xc0 | (PacketType::Retry.to_byte(version) << 4)
1338 );
1339 let header_range = 1..retry.len() - 16;
1340 assert_eq!(&retry[header_range.clone()], &sample_retry[header_range]);
1341 }
1342 }
1343
1344 #[test]
1345 fn build_retry_v2() {
1346 build_retry_single(Version::Version2, SAMPLE_RETRY_V2);
1347 }
1348
1349 #[test]
1350 fn build_retry_v1() {
1351 build_retry_single(Version::Version1, SAMPLE_RETRY_V1);
1352 }
1353
1354 #[test]
1355 fn build_retry_29() {
1356 build_retry_single(Version::Draft29, SAMPLE_RETRY_29);
1357 }
1358
1359 #[test]
1360 fn build_retry_multiple() {
1361 // Run the build_retry test a few times.
1362 // Odds are approximately 1 in 8 that the full comparison doesn't happen
1363 // for a given version.
1364 for _ in 0..32 {
1365 build_retry_v2();
1366 build_retry_v1();
1367 build_retry_29();
1368 }
1369 }
1370
1371 fn decode_retry(version: Version, sample_retry: &mut [u8]) {
1372 fixture_init();
1373 let (packet, remainder) =
1374 PublicPacket::decode(sample_retry, &RandomConnectionIdGenerator::new(5)).unwrap();
1375 assert!(packet.is_valid_retry(&ConnectionId::from(CLIENT_CID)));
1376 assert_eq!(Some(version), packet.version());
1377 assert!(packet.dcid().is_empty());
1378 assert_eq!(&packet.scid()[..], SERVER_CID);
1379 assert_eq!(packet.token(), RETRY_TOKEN);
1380 assert!(remainder.is_empty());
1381 }
1382
1383 #[test]
1384 fn decode_retry_v2() {
1385 let mut sample_retry_v2 = SAMPLE_RETRY_V2.to_vec();
1386 decode_retry(Version::Version2, &mut sample_retry_v2);
1387 }
1388
1389 #[test]
1390 fn decode_retry_v1() {
1391 let mut sample_retry_v1 = SAMPLE_RETRY_V1.to_vec();
1392 decode_retry(Version::Version1, &mut sample_retry_v1);
1393 }
1394
1395 #[test]
1396 fn decode_retry_29() {
1397 let mut sample_retry_29 = SAMPLE_RETRY_29.to_vec();
1398 decode_retry(Version::Draft29, &mut sample_retry_29);
1399 }
1400
1401 /// Check some packets that are clearly not valid Retry packets.
1402 #[test]
1403 fn invalid_retry() {
1404 fixture_init();
1405 let cid_mgr = RandomConnectionIdGenerator::new(5);
1406 let odcid = ConnectionId::from(CLIENT_CID);
1407
1408 assert!(PublicPacket::decode(&mut [], &cid_mgr).is_err());
1409
1410 let mut sample_retry_v1 = SAMPLE_RETRY_V1.to_vec();
1411 let (packet, remainder) = PublicPacket::decode(&mut sample_retry_v1, &cid_mgr).unwrap();
1412 assert!(remainder.is_empty());
1413 assert!(packet.is_valid_retry(&odcid));
1414
1415 let mut damaged_retry = SAMPLE_RETRY_V1.to_vec();
1416 let last = damaged_retry.len() - 1;
1417 damaged_retry[last] ^= 66;
1418 let (packet, remainder) = PublicPacket::decode(&mut damaged_retry, &cid_mgr).unwrap();
1419 assert!(remainder.is_empty());
1420 assert!(!packet.is_valid_retry(&odcid));
1421
1422 damaged_retry.truncate(last);
1423 let (packet, remainder) = PublicPacket::decode(&mut damaged_retry, &cid_mgr).unwrap();
1424 assert!(remainder.is_empty());
1425 assert!(!packet.is_valid_retry(&odcid));
1426
1427 // An invalid token should be rejected sooner.
1428 damaged_retry.truncate(last - 4);
1429 assert!(PublicPacket::decode(&mut damaged_retry, &cid_mgr).is_err());
1430
1431 damaged_retry.truncate(last - 1);
1432 assert!(PublicPacket::decode(&mut damaged_retry, &cid_mgr).is_err());
1433 }
1434
1435 const SAMPLE_VN: &[u8] = &[
1436 0x80, 0x00, 0x00, 0x00, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a, 0x42, 0x62, 0xb5, 0x08,
1437 0x83, 0x94, 0xc8, 0xf0, 0x3e, 0x51, 0x57, 0x08, 0x6b, 0x33, 0x43, 0xcf, 0x00, 0x00, 0x00,
1438 0x01, 0xff, 0x00, 0x00, 0x1d, 0x0a, 0x0a, 0x0a, 0x0a,
1439 ];
1440
1441 #[test]
1442 fn build_vn() {
1443 fixture_init();
1444 let mut vn = PacketBuilder::version_negotiation(
1445 SERVER_CID,
1446 CLIENT_CID,
1447 0x0a0a_0a0a,
1448 &Version::all(),
1449 );
1450 // Erase randomness from greasing...
1451 assert_eq!(vn.len(), SAMPLE_VN.len());
1452 vn[0] &= 0x80;
1453 for v in vn.iter_mut().skip(SAMPLE_VN.len() - 4) {
1454 *v &= 0x0f;
1455 }
1456 assert_eq!(&vn, &SAMPLE_VN);
1457 }
1458
1459 #[test]
1460 fn vn_do_not_repeat_client_grease() {
1461 fixture_init();
1462 let vn = PacketBuilder::version_negotiation(
1463 SERVER_CID,
1464 CLIENT_CID,
1465 0x0a0a_0a0a,
1466 &Version::all(),
1467 );
1468 assert_ne!(&vn[SAMPLE_VN.len() - 4..], &[0x0a, 0x0a, 0x0a, 0x0a]);
1469 }
1470
1471 #[test]
1472 fn parse_vn() {
1473 let mut sample_vn = SAMPLE_VN.to_vec();
1474 let (packet, remainder) =
1475 PublicPacket::decode(&mut sample_vn, &EmptyConnectionIdGenerator::default()).unwrap();
1476 assert!(remainder.is_empty());
1477 assert_eq!(&packet.dcid[..], SERVER_CID);
1478 assert!(packet.scid.is_some());
1479 assert_eq!(&packet.scid.unwrap()[..], CLIENT_CID);
1480 }
1481
1482 /// A Version Negotiation packet can have a long connection ID.
1483 #[test]
1484 fn parse_vn_big_cid() {
1485 const BIG_DCID: &[u8] = &[0x44; MAX_CONNECTION_ID_LEN + 1];
1486 const BIG_SCID: &[u8] = &[0xee; 255];
1487
1488 let mut enc = Encoder::from(&[0xff, 0x00, 0x00, 0x00, 0x00][..]);
1489 enc.encode_vec(1, BIG_DCID);
1490 enc.encode_vec(1, BIG_SCID);
1491 enc.encode_uint(4, 0x1a2a_3a4a_u64);
1492 enc.encode_uint(4, Version::default().wire_version());
1493 enc.encode_uint(4, 0x5a6a_7a8a_u64);
1494
1495 let (packet, remainder) =
1496 PublicPacket::decode(enc.as_mut(), &EmptyConnectionIdGenerator::default()).unwrap();
1497 assert!(remainder.is_empty());
1498 assert_eq!(&packet.dcid[..], BIG_DCID);
1499 assert!(packet.scid.is_some());
1500 assert_eq!(&packet.scid.unwrap()[..], BIG_SCID);
1501 }
1502
1503 #[test]
1504 fn decode_pn() {
1505 // When the expected value is low, the value doesn't go negative.
1506 assert_eq!(PublicPacket::decode_pn(0, 0, 1), 0);
1507 assert_eq!(PublicPacket::decode_pn(0, 0xff, 1), 0xff);
1508 assert_eq!(PublicPacket::decode_pn(10, 0, 1), 0);
1509 assert_eq!(PublicPacket::decode_pn(0x7f, 0, 1), 0);
1510 assert_eq!(PublicPacket::decode_pn(0x80, 0, 1), 0x100);
1511 assert_eq!(PublicPacket::decode_pn(0x80, 2, 1), 2);
1512 assert_eq!(PublicPacket::decode_pn(0x80, 0xff, 1), 0xff);
1513 assert_eq!(PublicPacket::decode_pn(0x7ff, 0xfe, 1), 0x7fe);
1514
1515 // This is invalid by spec, as we are expected to check for overflow around 2^62-1,
1516 // but we don't need to worry about overflow
1517 // and hitting this is basically impossible in practice.
1518 assert_eq!(
1519 PublicPacket::decode_pn(0x3fff_ffff_ffff_ffff, 2, 4),
1520 0x4000_0000_0000_0002
1521 );
1522 }
1523
1524 #[test]
1525 fn chacha20_sample() {
1526 const PACKET: &[u8] = &[
1527 0x4c, 0xfe, 0x41, 0x89, 0x65, 0x5e, 0x5c, 0xd5, 0x5c, 0x41, 0xf6, 0x90, 0x80, 0x57,
1528 0x5d, 0x79, 0x99, 0xc2, 0x5a, 0x5b, 0xfb,
1529 ];
1530 fixture_init();
1531 let mut packet = PACKET.to_vec();
1532 let (mut packet, slice) =
1533 PublicPacket::decode(&mut packet, &EmptyConnectionIdGenerator::default()).unwrap();
1534 assert!(slice.is_empty());
1535 let decrypted = packet
1536 .decrypt(&mut CryptoStates::test_chacha(), now())
1537 .unwrap();
1538 assert_eq!(decrypted.packet_type(), PacketType::Short);
1539 assert_eq!(decrypted.pn(), 654_360_564);
1540 assert_eq!(&decrypted[..], &[0x01]);
1541 }
1542
1543 #[test]
1544 fn decode_empty() {
1545 neqo_crypto::init().unwrap();
1546 let res = PublicPacket::decode(&mut [], &EmptyConnectionIdGenerator::default());
1547 assert!(res.is_err());
1548 }
1549
1550 #[test]
1551 fn decode_too_short() {
1552 neqo_crypto::init().unwrap();
1553 let mut data = [179, 255, 0, 0, 29, 0, 0];
1554 let res = PublicPacket::decode(&mut data, &EmptyConnectionIdGenerator::default());
1555 assert!(res.is_err());
1556 }
1557 }