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<_>>()?;
242    let src_ip = packet.src_ip();
243    let dst_ip = packet.dst_ip();
244    let proto = packet.proto();
245    let ttl = packet.ttl();
246    // Because the packet type here is generic, Rust doesn't know that it
247    // doesn't implement Drop, and so it doesn't know that it's safe to drop as
248    // soon as it's no longer used and allow buf to no longer be borrowed on the
249    // next line. It works fine in parse_ethernet_frame because EthernetFrame is
250    // a concrete type which Rust knows doesn't implement Drop.
251    core::mem::drop(packet);
252    Ok((buf, src_ip, dst_ip, proto, ttl))
253}
254
255/// Parse an ICMP packet.
256///
257/// `parse_icmp_packet` parses an ICMP packet, returning the body along with
258/// some important fields. Before returning, it invokes the callback `f` on the
259/// parsed packet.
260pub fn parse_icmp_packet<
261    I: IcmpIpExt,
262    C,
263    M: IcmpMessage<I, Code = C>,
264    F: for<'a> FnOnce(&IcmpPacket<I, &'a [u8], M>),
265>(
266    mut buf: &[u8],
267    src_ip: I::Addr,
268    dst_ip: I::Addr,
269    f: F,
270) -> ParseResult<(M, C)>
271where
272    for<'a> IcmpPacket<I, &'a [u8], M>:
273        ParsablePacket<&'a [u8], IcmpParseArgs<I::Addr>, Error = ParseError>,
274{
275    let packet =
276        (&mut buf).parse_with::<_, IcmpPacket<I, _, M>>(IcmpParseArgs::new(src_ip, dst_ip))?;
277    let message = *packet.message();
278    let code = packet.code();
279    f(&packet);
280    Ok((message, code))
281}
282
283/// Parse an IP packet in an Ethernet frame.
284///
285/// `parse_ip_packet_in_ethernet_frame` parses an IP packet in an Ethernet
286/// frame, returning the body of the IP packet along with some important fields
287/// from both the IP and Ethernet headers.
288#[allow(clippy::type_complexity)]
289pub fn parse_ip_packet_in_ethernet_frame<I: IpExt>(
290    buf: &[u8],
291    ethernet_length_check: EthernetFrameLengthCheck,
292) -> IpParseResult<I, (&[u8], Mac, Mac, I::Addr, I::Addr, I::Proto, u8)> {
293    let (body, src_mac, dst_mac, ethertype) = parse_ethernet_frame(buf, ethernet_length_check)?;
294    if ethertype != Some(I::ETHER_TYPE) {
295        debug!("unexpected ethertype: {:?}", ethertype);
296        return Err(ParseError::NotExpected.into());
297    }
298
299    let (body, src_ip, dst_ip, proto, ttl) = parse_ip_packet::<I>(body)?;
300    Ok((body, src_mac, dst_mac, src_ip, dst_ip, proto, ttl))
301}
302
303/// Parse an ICMP packet in an IP packet in an Ethernet frame.
304///
305/// `parse_icmp_packet_in_ip_packet_in_ethernet_frame` parses an ICMP packet in
306/// an IP packet in an Ethernet frame, returning the message and code from the
307/// ICMP packet along with some important fields from both the IP and Ethernet
308/// headers. Before returning, it invokes the callback `f` on the parsed packet.
309#[allow(clippy::type_complexity)]
310pub fn parse_icmp_packet_in_ip_packet_in_ethernet_frame<
311    I: IpExt,
312    C,
313    M: IcmpMessage<I, Code = C>,
314    F: for<'a> FnOnce(&IcmpPacket<I, &'a [u8], M>),
315>(
316    buf: &[u8],
317    ethernet_length_check: EthernetFrameLengthCheck,
318    f: F,
319) -> IpParseResult<I, (Mac, Mac, I::Addr, I::Addr, u8, M, C)>
320where
321    for<'a> IcmpPacket<I, &'a [u8], M>:
322        ParsablePacket<&'a [u8], IcmpParseArgs<I::Addr>, Error = ParseError>,
323{
324    let (body, src_mac, dst_mac, src_ip, dst_ip, proto, ttl) =
325        parse_ip_packet_in_ethernet_frame::<I>(buf, ethernet_length_check)?;
326    if proto != I::ICMP_IP_PROTO {
327        debug!("unexpected IP protocol: {} (wanted {})", proto, I::ICMP_IP_PROTO);
328        return Err(ParseError::NotExpected.into());
329    }
330    let (message, code) = parse_icmp_packet(body, src_ip, dst_ip, f)?;
331    Ok((src_mac, dst_mac, src_ip, dst_ip, ttl, message, code))
332}
333
334/// Overwrite the checksum in an ICMPv6 message, returning the original value.
335///
336/// On `Err`, the provided buf is unmodified.
337pub fn overwrite_icmpv6_checksum(buf: &mut [u8], checksum: [u8; 2]) -> ParseResult<[u8; 2]> {
338    let buf = SliceBufViewMut::new(buf);
339    let mut message = Icmpv6PacketRaw::parse_mut(buf, ())?;
340    Ok(message.overwrite_checksum(checksum))
341}
342
343#[cfg(test)]
344mod crateonly {
345    use std::sync::Once;
346
347    /// Install a logger for tests.
348    ///
349    /// Call this method at the beginning of the test for which logging is desired.
350    /// This function sets global program state, so all tests that run after this
351    /// function is called will use the logger.
352    pub(crate) fn set_logger_for_test() {
353        /// log::Log implementation that uses stdout.
354        ///
355        /// Useful when debugging tests.
356        struct Logger;
357
358        impl log::Log for Logger {
359            fn enabled(&self, _metadata: &log::Metadata<'_>) -> bool {
360                true
361            }
362
363            fn log(&self, record: &log::Record<'_>) {
364                println!("{}", record.args())
365            }
366
367            fn flush(&self) {}
368        }
369        static LOGGER_ONCE: Once = Once::new();
370
371        // log::set_logger will panic if called multiple times; using a Once makes
372        // set_logger_for_test idempotent
373        LOGGER_ONCE.call_once(|| {
374            log::set_logger(&Logger).unwrap();
375            log::set_max_level(log::LevelFilter::Trace);
376        })
377    }
378}
379
380#[cfg(test)]
381mod tests {
382    use net_types::ip::{Ipv4, Ipv6};
383
384    use crate::icmp::{IcmpDestUnreachable, IcmpEchoReply, Icmpv4DestUnreachableCode};
385    use crate::ip::Ipv6Proto;
386
387    use super::*;
388
389    #[test]
390    fn test_parse_ethernet_frame() {
391        use crate::testdata::arp_request::*;
392        let (body, src_mac, dst_mac, ethertype) =
393            parse_ethernet_frame(ETHERNET_FRAME.bytes, EthernetFrameLengthCheck::Check).unwrap();
394        assert_eq!(body, &ETHERNET_FRAME.bytes[14..]);
395        assert_eq!(src_mac, ETHERNET_FRAME.metadata.src_mac);
396        assert_eq!(dst_mac, ETHERNET_FRAME.metadata.dst_mac);
397        assert_eq!(ethertype, ETHERNET_FRAME.metadata.ethertype);
398    }
399
400    #[test]
401    fn test_parse_ip_packet() {
402        use crate::testdata::icmp_redirect::IP_PACKET_BYTES;
403        let (body, src_ip, dst_ip, proto, ttl) = parse_ip_packet::<Ipv4>(IP_PACKET_BYTES).unwrap();
404        assert_eq!(body, &IP_PACKET_BYTES[20..]);
405        assert_eq!(src_ip, Ipv4Addr::new([10, 123, 0, 2]));
406        assert_eq!(dst_ip, Ipv4Addr::new([10, 123, 0, 1]));
407        assert_eq!(proto, Ipv4Proto::Icmp);
408        assert_eq!(ttl, 255);
409
410        use crate::testdata::icmp_echo_v6::REQUEST_IP_PACKET_BYTES;
411        let (body, src_ip, dst_ip, proto, ttl) =
412            parse_ip_packet::<Ipv6>(REQUEST_IP_PACKET_BYTES).unwrap();
413        assert_eq!(body, &REQUEST_IP_PACKET_BYTES[40..]);
414        assert_eq!(src_ip, Ipv6Addr::new([0, 0, 0, 0, 0, 0, 0, 1]));
415        assert_eq!(dst_ip, Ipv6Addr::new([0xfec0, 0, 0, 0, 0, 0, 0, 0]));
416        assert_eq!(proto, Ipv6Proto::Icmpv6);
417        assert_eq!(ttl, 64);
418    }
419
420    #[test]
421    fn test_parse_ip_packet_in_ethernet_frame() {
422        use crate::testdata::tls_client_hello_v4::*;
423        let (body, src_mac, dst_mac, src_ip, dst_ip, proto, ttl) =
424            parse_ip_packet_in_ethernet_frame::<Ipv4>(
425                ETHERNET_FRAME.bytes,
426                EthernetFrameLengthCheck::Check,
427            )
428            .unwrap();
429        assert_eq!(body, &IPV4_PACKET.bytes[IPV4_PACKET.body_range]);
430        assert_eq!(src_mac, ETHERNET_FRAME.metadata.src_mac);
431        assert_eq!(dst_mac, ETHERNET_FRAME.metadata.dst_mac);
432        assert_eq!(src_ip, IPV4_PACKET.metadata.src_ip);
433        assert_eq!(dst_ip, IPV4_PACKET.metadata.dst_ip);
434        assert_eq!(proto, IPV4_PACKET.metadata.proto);
435        assert_eq!(ttl, IPV4_PACKET.metadata.ttl);
436    }
437
438    #[test]
439    fn test_parse_icmp_packet() {
440        set_logger_for_test();
441        use crate::testdata::icmp_dest_unreachable::*;
442        let (body, ..) = parse_ip_packet::<Ipv4>(&IP_PACKET_BYTES).unwrap();
443        let (_, code) = parse_icmp_packet::<Ipv4, _, IcmpDestUnreachable, _>(
444            body,
445            Ipv4Addr::new([172, 217, 6, 46]),
446            Ipv4Addr::new([192, 168, 0, 105]),
447            |_| {},
448        )
449        .unwrap();
450        assert_eq!(code, Icmpv4DestUnreachableCode::DestHostUnreachable);
451    }
452
453    #[test]
454    fn test_parse_icmp_packet_in_ip_packet_in_ethernet_frame() {
455        set_logger_for_test();
456        use crate::testdata::icmp_echo_ethernet::*;
457        let (src_mac, dst_mac, src_ip, dst_ip, _, _, _) =
458            parse_icmp_packet_in_ip_packet_in_ethernet_frame::<Ipv4, _, IcmpEchoReply, _>(
459                &REPLY_ETHERNET_FRAME_BYTES,
460                EthernetFrameLengthCheck::Check,
461                |_| {},
462            )
463            .unwrap();
464        assert_eq!(src_mac, Mac::new([0x50, 0xc7, 0xbf, 0x1d, 0xf4, 0xd2]));
465        assert_eq!(dst_mac, Mac::new([0x8c, 0x85, 0x90, 0xc9, 0xc9, 0x00]));
466        assert_eq!(src_ip, Ipv4Addr::new([172, 217, 6, 46]));
467        assert_eq!(dst_ip, Ipv4Addr::new([192, 168, 0, 105]));
468    }
469}