Skip to main content

packet_formats/
testutil.rs

1// Copyright 2018 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5//! Testing-related utilities.
6
7// TODO(https://fxbug.dev/326330182): this import seems actually necessary. Is this a bug on the
8// lint?
9#[allow(unused_imports)]
10use alloc::vec::Vec;
11use core::num::NonZeroU16;
12use core::ops::Range;
13use zerocopy::SplitByteSlice;
14
15use log::debug;
16use net_types::ethernet::Mac;
17use net_types::ip::{Ipv4Addr, Ipv6Addr};
18use packet::{ParsablePacket, ParseBuffer, SliceBufViewMut};
19
20use crate::arp::{ArpOp, ArpPacket};
21use crate::error::{IpParseResult, ParseError, ParseResult};
22use crate::ethernet::{EtherType, EthernetFrame, EthernetFrameLengthCheck};
23use crate::icmp::{IcmpIpExt, IcmpMessage, IcmpPacket, IcmpParseArgs, Icmpv6PacketRaw};
24use crate::ip::{DscpAndEcn, IpExt, Ipv4Proto};
25use crate::ipv4::{Ipv4FragmentType, Ipv4Header, Ipv4Packet};
26use crate::ipv6::{Ipv6Header, Ipv6Packet};
27use crate::tcp::TcpSegment;
28use crate::tcp::options::{TcpOptions, TcpOptionsBuilder};
29use crate::udp::UdpPacket;
30
31#[cfg(test)]
32pub(crate) use crateonly::*;
33
34/// Metadata of an Ethernet frame.
35#[allow(missing_docs)]
36pub struct EthernetFrameMetadata {
37    pub src_mac: Mac,
38    pub dst_mac: Mac,
39    pub ethertype: Option<EtherType>,
40}
41
42/// Metadata of an IPv4 packet.
43#[allow(missing_docs)]
44pub struct Ipv4PacketMetadata {
45    pub id: u16,
46    pub dscp_and_ecn: DscpAndEcn,
47    pub dont_fragment: bool,
48    pub more_fragments: bool,
49    pub fragment_offset: u16,
50    pub fragment_type: Ipv4FragmentType,
51    pub ttl: u8,
52    pub proto: Ipv4Proto,
53    pub src_ip: Ipv4Addr,
54    pub dst_ip: Ipv4Addr,
55}
56
57/// Metadata of an IPv6 packet.
58#[allow(missing_docs)]
59pub struct Ipv6PacketMetadata {
60    pub dscp_and_ecn: DscpAndEcn,
61    pub flowlabel: u32,
62    pub hop_limit: u8,
63    pub src_ip: Ipv6Addr,
64    pub dst_ip: Ipv6Addr,
65}
66
67/// Metadata of a TCP segment.
68#[allow(missing_docs)]
69pub struct TcpSegmentMetadata {
70    pub src_port: u16,
71    pub dst_port: u16,
72    pub seq_num: u32,
73    pub ack_num: Option<u32>,
74    pub flags: u16,
75    pub psh: bool,
76    pub rst: bool,
77    pub syn: bool,
78    pub fin: bool,
79    pub window_size: u16,
80    pub options: TcpOptionsBuilder<'static>,
81}
82
83/// Metadata of a UDP packet.
84#[allow(missing_docs)]
85pub struct UdpPacketMetadata {
86    pub src_port: u16,
87    pub dst_port: u16,
88}
89
90/// Represents a packet (usually from a live capture) used for testing.
91///
92/// Includes the raw bytes, metadata of the packet (currently just fields from the packet header)
93/// and the range which indicates where the body is.
94#[allow(missing_docs)]
95pub struct TestPacket<M> {
96    pub bytes: &'static [u8],
97    pub metadata: M,
98    pub body_range: Range<usize>,
99}
100
101/// Verify that a parsed Ethernet frame is as expected.
102///
103/// Ensures the parsed packet's header fields and body are equal to those in the test packet.
104pub fn verify_ethernet_frame(
105    frame: &EthernetFrame<&[u8]>,
106    expected: TestPacket<EthernetFrameMetadata>,
107) {
108    assert_eq!(frame.src_mac(), expected.metadata.src_mac);
109    assert_eq!(frame.dst_mac(), expected.metadata.dst_mac);
110    assert_eq!(frame.ethertype(), expected.metadata.ethertype);
111    assert_eq!(frame.body(), &expected.bytes[expected.body_range]);
112}
113
114/// Verify that a parsed IPv4 packet is as expected.
115///
116/// Ensures the parsed packet's header fields and body are equal to those in the test packet.
117pub fn verify_ipv4_packet(packet: &Ipv4Packet<&[u8]>, expected: TestPacket<Ipv4PacketMetadata>) {
118    assert_eq!(packet.dscp_and_ecn(), expected.metadata.dscp_and_ecn);
119    assert_eq!(packet.id(), expected.metadata.id);
120    assert_eq!(packet.df_flag(), expected.metadata.dont_fragment);
121    assert_eq!(packet.mf_flag(), expected.metadata.more_fragments);
122    assert_eq!(packet.fragment_offset().into_raw(), expected.metadata.fragment_offset);
123    assert_eq!(packet.ttl(), expected.metadata.ttl);
124    assert_eq!(packet.proto(), expected.metadata.proto);
125    assert_eq!(packet.src_ip(), expected.metadata.src_ip);
126    assert_eq!(packet.dst_ip(), expected.metadata.dst_ip);
127    assert_eq!(packet.body(), &expected.bytes[expected.body_range]);
128}
129
130/// Verify that a parsed IPv6 packet is as expected.
131///
132/// Ensures the parsed packet's header fields and body are equal to those in the test packet.
133pub fn verify_ipv6_packet(packet: &Ipv6Packet<&[u8]>, expected: TestPacket<Ipv6PacketMetadata>) {
134    assert_eq!(packet.dscp_and_ecn(), expected.metadata.dscp_and_ecn);
135    assert_eq!(packet.flowlabel(), expected.metadata.flowlabel);
136    assert_eq!(packet.hop_limit(), expected.metadata.hop_limit);
137    assert_eq!(packet.src_ip(), expected.metadata.src_ip);
138    assert_eq!(packet.dst_ip(), expected.metadata.dst_ip);
139    assert_eq!(packet.body(), &expected.bytes[expected.body_range]);
140}
141
142/// Verify that a parsed UDP packet is as expected.
143///
144/// Ensures the parsed packet's header fields and body are equal to those in the test packet.
145pub fn verify_udp_packet(packet: &UdpPacket<&[u8]>, expected: TestPacket<UdpPacketMetadata>) {
146    assert_eq!(packet.src_port().map(NonZeroU16::get).unwrap_or(0), expected.metadata.src_port);
147    assert_eq!(packet.dst_port().get(), expected.metadata.dst_port);
148    assert_eq!(packet.body(), &expected.bytes[expected.body_range]);
149}
150
151/// Verify that a parsed TCP segment is as expected.
152///
153/// Ensures the parsed packet's header fields and body are equal to those in the test packet.
154pub fn verify_tcp_segment(segment: &TcpSegment<&[u8]>, expected: TestPacket<TcpSegmentMetadata>) {
155    assert_eq!(segment.src_port().get(), expected.metadata.src_port);
156    assert_eq!(segment.dst_port().get(), expected.metadata.dst_port);
157    assert_eq!(segment.seq_num(), expected.metadata.seq_num);
158    assert_eq!(segment.ack_num(), expected.metadata.ack_num);
159    assert_eq!(segment.rst(), expected.metadata.rst);
160    assert_eq!(segment.syn(), expected.metadata.syn);
161    assert_eq!(segment.fin(), expected.metadata.fin);
162    assert_eq!(segment.window_size(), expected.metadata.window_size);
163
164    let TcpOptionsBuilder { mss, window_scale, sack_permitted, sack_blocks, timestamp } =
165        expected.metadata.options;
166    assert_eq!(segment.options().mss(), mss);
167    assert_eq!(segment.options().window_scale(), window_scale);
168    assert_eq!(segment.options().sack_permitted(), sack_permitted);
169    assert_eq!(segment.options().sack_blocks(), sack_blocks);
170    assert_eq!(segment.options().timestamp(), timestamp.as_ref());
171
172    assert_eq!(segment.body(), &expected.bytes[expected.body_range]);
173}
174
175/// Parse an ethernet frame.
176///
177/// `parse_ethernet_frame` parses an ethernet frame, returning the body along
178/// with some important header fields.
179pub fn parse_ethernet_frame(
180    mut buf: &[u8],
181    ethernet_length_check: EthernetFrameLengthCheck,
182) -> ParseResult<(&[u8], Mac, Mac, Option<EtherType>)> {
183    let frame = (&mut buf).parse_with::<_, EthernetFrame<_>>(ethernet_length_check)?;
184    let src_mac = frame.src_mac();
185    let dst_mac = frame.dst_mac();
186    let ethertype = frame.ethertype();
187    Ok((buf, src_mac, dst_mac, ethertype))
188}
189
190/// Information about an [`ArpPacket`].
191#[allow(missing_docs)]
192pub struct ArpPacketInfo {
193    pub sender_hardware_address: Mac,
194    pub sender_protocol_address: Ipv4Addr,
195    pub target_hardware_address: Mac,
196    pub target_protocol_address: Ipv4Addr,
197    pub operation: ArpOp,
198}
199
200impl<B: SplitByteSlice> From<ArpPacket<B, Mac, Ipv4Addr>> for ArpPacketInfo {
201    fn from(packet: ArpPacket<B, Mac, Ipv4Addr>) -> ArpPacketInfo {
202        ArpPacketInfo {
203            sender_hardware_address: packet.sender_hardware_address(),
204            sender_protocol_address: packet.sender_protocol_address(),
205            target_hardware_address: packet.target_hardware_address(),
206            target_protocol_address: packet.target_protocol_address(),
207            operation: packet.operation(),
208        }
209    }
210}
211
212/// Parse an ARP packet.
213pub fn parse_arp_packet(mut buf: &[u8]) -> ParseResult<ArpPacketInfo> {
214    (&mut buf).parse::<ArpPacket<_, Mac, Ipv4Addr>>().map(ArpPacketInfo::from)
215}
216
217/// Parse an ARP packet in an Ethernet frame.
218pub fn parse_arp_packet_in_ethernet_frame(
219    buf: &[u8],
220    ethernet_length_check: EthernetFrameLengthCheck,
221) -> ParseResult<ArpPacketInfo> {
222    let (body, _src_mac, _dst_mac, ethertype) = parse_ethernet_frame(buf, ethernet_length_check)?;
223    if ethertype != Some(EtherType::Arp) {
224        debug!("unexpected ethertype: {:?}", ethertype);
225        return Err(ParseError::NotExpected.into());
226    }
227
228    parse_arp_packet(body)
229}
230
231/// Parse an IP packet.
232///
233/// `parse_ip_packet` parses an IP packet, returning the body along with some
234/// important header fields.
235#[allow(clippy::type_complexity)]
236pub fn parse_ip_packet<I: IpExt>(
237    mut buf: &[u8],
238) -> IpParseResult<I, (&[u8], I::Addr, I::Addr, I::Proto, u8)> {
239    use crate::ip::IpPacket;
240
241    let packet = (&mut buf).parse::<I::Packet<_>>().map_err(|e| {
242        let e: I::PacketParseError = e;
243        e
244    })?;
245    let src_ip = packet.src_ip();
246    let dst_ip = packet.dst_ip();
247    let proto = packet.proto();
248    let ttl = packet.ttl();
249    // Because the packet type here is generic, Rust doesn't know that it
250    // doesn't implement Drop, and so it doesn't know that it's safe to drop as
251    // soon as it's no longer used and allow buf to no longer be borrowed on the
252    // next line. It works fine in parse_ethernet_frame because EthernetFrame is
253    // a concrete type which Rust knows doesn't implement Drop.
254    core::mem::drop(packet);
255    Ok((buf, src_ip, dst_ip, proto, ttl))
256}
257
258/// Parse an ICMP packet.
259///
260/// `parse_icmp_packet` parses an ICMP packet, returning the body along with
261/// some important fields. Before returning, it invokes the callback `f` on the
262/// parsed packet.
263pub fn parse_icmp_packet<
264    I: IcmpIpExt,
265    C,
266    M: IcmpMessage<I, Code = C>,
267    F: for<'a> FnOnce(&IcmpPacket<I, &'a [u8], M>),
268>(
269    mut buf: &[u8],
270    src_ip: I::Addr,
271    dst_ip: I::Addr,
272    f: F,
273) -> ParseResult<(M, C)>
274where
275    for<'a> IcmpPacket<I, &'a [u8], M>:
276        ParsablePacket<&'a [u8], IcmpParseArgs<I::Addr>, Error = ParseError>,
277{
278    let packet =
279        (&mut buf).parse_with::<_, IcmpPacket<I, _, M>>(IcmpParseArgs::new(src_ip, dst_ip))?;
280    let message = *packet.message();
281    let code = packet.code();
282    f(&packet);
283    Ok((message, code))
284}
285
286/// Parse an IP packet in an Ethernet frame.
287///
288/// `parse_ip_packet_in_ethernet_frame` parses an IP packet in an Ethernet
289/// frame, returning the body of the IP packet along with some important fields
290/// from both the IP and Ethernet headers.
291#[allow(clippy::type_complexity)]
292pub fn parse_ip_packet_in_ethernet_frame<I: IpExt>(
293    buf: &[u8],
294    ethernet_length_check: EthernetFrameLengthCheck,
295) -> IpParseResult<I, (&[u8], Mac, Mac, I::Addr, I::Addr, I::Proto, u8)> {
296    let (body, src_mac, dst_mac, ethertype) = parse_ethernet_frame(buf, ethernet_length_check)?;
297    if ethertype != Some(I::ETHER_TYPE) {
298        debug!("unexpected ethertype: {:?}", ethertype);
299        return Err(ParseError::NotExpected.into());
300    }
301
302    let (body, src_ip, dst_ip, proto, ttl) = parse_ip_packet::<I>(body)?;
303    Ok((body, src_mac, dst_mac, src_ip, dst_ip, proto, ttl))
304}
305
306/// Parse an ICMP packet in an IP packet in an Ethernet frame.
307///
308/// `parse_icmp_packet_in_ip_packet_in_ethernet_frame` parses an ICMP packet in
309/// an IP packet in an Ethernet frame, returning the message and code from the
310/// ICMP packet along with some important fields from both the IP and Ethernet
311/// headers. Before returning, it invokes the callback `f` on the parsed packet.
312#[allow(clippy::type_complexity)]
313pub fn parse_icmp_packet_in_ip_packet_in_ethernet_frame<
314    I: IpExt,
315    C,
316    M: IcmpMessage<I, Code = C>,
317    F: for<'a> FnOnce(&IcmpPacket<I, &'a [u8], M>),
318>(
319    buf: &[u8],
320    ethernet_length_check: EthernetFrameLengthCheck,
321    f: F,
322) -> IpParseResult<I, (Mac, Mac, I::Addr, I::Addr, u8, M, C)>
323where
324    for<'a> IcmpPacket<I, &'a [u8], M>:
325        ParsablePacket<&'a [u8], IcmpParseArgs<I::Addr>, Error = ParseError>,
326{
327    let (body, src_mac, dst_mac, src_ip, dst_ip, proto, ttl) =
328        parse_ip_packet_in_ethernet_frame::<I>(buf, ethernet_length_check)?;
329    if proto != I::ICMP_IP_PROTO {
330        debug!("unexpected IP protocol: {} (wanted {})", proto, I::ICMP_IP_PROTO);
331        return Err(ParseError::NotExpected.into());
332    }
333    let (message, code) = parse_icmp_packet(body, src_ip, dst_ip, f)?;
334    Ok((src_mac, dst_mac, src_ip, dst_ip, ttl, message, code))
335}
336
337/// Overwrite the checksum in an ICMPv6 message, returning the original value.
338///
339/// On `Err`, the provided buf is unmodified.
340pub fn overwrite_icmpv6_checksum(buf: &mut [u8], checksum: [u8; 2]) -> ParseResult<[u8; 2]> {
341    let buf = SliceBufViewMut::new(buf);
342    let mut message = Icmpv6PacketRaw::parse_mut(buf, ())?;
343    Ok(message.overwrite_checksum(checksum))
344}
345
346#[cfg(test)]
347mod crateonly {
348    use std::sync::Once;
349
350    /// Install a logger for tests.
351    ///
352    /// Call this method at the beginning of the test for which logging is desired.
353    /// This function sets global program state, so all tests that run after this
354    /// function is called will use the logger.
355    pub(crate) fn set_logger_for_test() {
356        /// log::Log implementation that uses stdout.
357        ///
358        /// Useful when debugging tests.
359        struct Logger;
360
361        impl log::Log for Logger {
362            fn enabled(&self, _metadata: &log::Metadata<'_>) -> bool {
363                true
364            }
365
366            fn log(&self, record: &log::Record<'_>) {
367                println!("{}", record.args())
368            }
369
370            fn flush(&self) {}
371        }
372        static LOGGER_ONCE: Once = Once::new();
373
374        // log::set_logger will panic if called multiple times; using a Once makes
375        // set_logger_for_test idempotent
376        LOGGER_ONCE.call_once(|| {
377            log::set_logger(&Logger).unwrap();
378            log::set_max_level(log::LevelFilter::Trace);
379        })
380    }
381}
382
383#[cfg(test)]
384mod tests {
385    use net_types::ip::{Ipv4, Ipv6};
386
387    use crate::icmp::{IcmpDestUnreachable, IcmpEchoReply, Icmpv4DestUnreachableCode};
388    use crate::ip::Ipv6Proto;
389
390    use super::*;
391
392    #[test]
393    fn test_parse_ethernet_frame() {
394        use crate::testdata::arp_request::*;
395        let (body, src_mac, dst_mac, ethertype) =
396            parse_ethernet_frame(ETHERNET_FRAME.bytes, EthernetFrameLengthCheck::Check).unwrap();
397        assert_eq!(body, &ETHERNET_FRAME.bytes[14..]);
398        assert_eq!(src_mac, ETHERNET_FRAME.metadata.src_mac);
399        assert_eq!(dst_mac, ETHERNET_FRAME.metadata.dst_mac);
400        assert_eq!(ethertype, ETHERNET_FRAME.metadata.ethertype);
401    }
402
403    #[test]
404    fn test_parse_ip_packet() {
405        use crate::testdata::icmp_redirect::IP_PACKET_BYTES;
406        let (body, src_ip, dst_ip, proto, ttl) = parse_ip_packet::<Ipv4>(IP_PACKET_BYTES).unwrap();
407        assert_eq!(body, &IP_PACKET_BYTES[20..]);
408        assert_eq!(src_ip, Ipv4Addr::new([10, 123, 0, 2]));
409        assert_eq!(dst_ip, Ipv4Addr::new([10, 123, 0, 1]));
410        assert_eq!(proto, Ipv4Proto::Icmp);
411        assert_eq!(ttl, 255);
412
413        use crate::testdata::icmp_echo_v6::REQUEST_IP_PACKET_BYTES;
414        let (body, src_ip, dst_ip, proto, ttl) =
415            parse_ip_packet::<Ipv6>(REQUEST_IP_PACKET_BYTES).unwrap();
416        assert_eq!(body, &REQUEST_IP_PACKET_BYTES[40..]);
417        assert_eq!(src_ip, Ipv6Addr::new([0, 0, 0, 0, 0, 0, 0, 1]));
418        assert_eq!(dst_ip, Ipv6Addr::new([0xfec0, 0, 0, 0, 0, 0, 0, 0]));
419        assert_eq!(proto, Ipv6Proto::Icmpv6);
420        assert_eq!(ttl, 64);
421    }
422
423    #[test]
424    fn test_parse_ip_packet_in_ethernet_frame() {
425        use crate::testdata::tls_client_hello_v4::*;
426        let (body, src_mac, dst_mac, src_ip, dst_ip, proto, ttl) =
427            parse_ip_packet_in_ethernet_frame::<Ipv4>(
428                ETHERNET_FRAME.bytes,
429                EthernetFrameLengthCheck::Check,
430            )
431            .unwrap();
432        assert_eq!(body, &IPV4_PACKET.bytes[IPV4_PACKET.body_range]);
433        assert_eq!(src_mac, ETHERNET_FRAME.metadata.src_mac);
434        assert_eq!(dst_mac, ETHERNET_FRAME.metadata.dst_mac);
435        assert_eq!(src_ip, IPV4_PACKET.metadata.src_ip);
436        assert_eq!(dst_ip, IPV4_PACKET.metadata.dst_ip);
437        assert_eq!(proto, IPV4_PACKET.metadata.proto);
438        assert_eq!(ttl, IPV4_PACKET.metadata.ttl);
439    }
440
441    #[test]
442    fn test_parse_icmp_packet() {
443        set_logger_for_test();
444        use crate::testdata::icmp_dest_unreachable::*;
445        let (body, ..) = parse_ip_packet::<Ipv4>(&IP_PACKET_BYTES).unwrap();
446        let (_, code) = parse_icmp_packet::<Ipv4, _, IcmpDestUnreachable, _>(
447            body,
448            Ipv4Addr::new([172, 217, 6, 46]),
449            Ipv4Addr::new([192, 168, 0, 105]),
450            |_| {},
451        )
452        .unwrap();
453        assert_eq!(code, Icmpv4DestUnreachableCode::DestHostUnreachable);
454    }
455
456    #[test]
457    fn test_parse_icmp_packet_in_ip_packet_in_ethernet_frame() {
458        set_logger_for_test();
459        use crate::testdata::icmp_echo_ethernet::*;
460        let (src_mac, dst_mac, src_ip, dst_ip, _, _, _) =
461            parse_icmp_packet_in_ip_packet_in_ethernet_frame::<Ipv4, _, IcmpEchoReply, _>(
462                &REPLY_ETHERNET_FRAME_BYTES,
463                EthernetFrameLengthCheck::Check,
464                |_| {},
465            )
466            .unwrap();
467        assert_eq!(src_mac, Mac::new([0x50, 0xc7, 0xbf, 0x1d, 0xf4, 0xd2]));
468        assert_eq!(dst_mac, Mac::new([0x8c, 0x85, 0x90, 0xc9, 0xc9, 0x00]));
469        assert_eq!(src_ip, Ipv4Addr::new([172, 217, 6, 46]));
470        assert_eq!(dst_ip, Ipv4Addr::new([192, 168, 0, 105]));
471    }
472}