packet_parser 1.5.3

A powerful and modular Rust crate for network packet parsing.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
pub mod protocols;

use std::convert::TryFrom;
use std::net::IpAddr;

use crate::errors::internet::InternetError;
use crate::parse::internet::protocols::profinet;
use crate::parse::transport::protocols::TransportProtocol;
use protocols::arp::ArpPacket;
use protocols::ipv4;
use protocols::ipv6;
use serde::Serialize;
pub mod ip_type;
use super::transport::Transport;
use ip_type::IpType;

#[derive(Debug, Clone, Serialize, Eq)]
pub struct Internet<'a> {
    /// Source IP address when the internet layer carries one.
    pub source: Option<IpAddr>,
    /// Classification of the source IP address.
    pub source_type: Option<IpType>,
    /// Destination IP address when the internet layer carries one.
    pub destination: Option<IpAddr>,
    /// Classification of the destination IP address.
    pub destination_type: Option<IpType>,
    /// Parsed internet-layer protocol name.
    pub protocol_name: String,
    /// Transport protocol parsable from `payload`.
    ///
    /// This is not a pure copy of an IP header protocol field. For IPv4
    /// fragments, it is `None` because parsing L4 safely requires IP
    /// reassembly, which this crate does not perform.
    pub payload_protocol: Option<TransportProtocol>,
    /// Internet-layer payload bytes.
    #[serde(skip_serializing)]
    pub payload: &'a [u8],
}

impl<'a> TryFrom<&'a [u8]> for Internet<'a> {
    type Error = InternetError;

    fn try_from(packet: &'a [u8]) -> Result<Self, Self::Error> {
        if packet.is_empty() {
            return Err(InternetError::EmptyPacket);
        }

        // Try to parse as ARP first
        if let Ok(arp_packet) = ArpPacket::try_from(packet) {
            return Ok(Internet {
                source: Some(arp_packet.sender_protocol_addr),
                source_type: Some(IpType::from_ip(
                    &arp_packet.sender_protocol_addr.to_string(),
                )),
                destination: Some(arp_packet.target_protocol_addr),
                destination_type: Some(IpType::from_ip(
                    &arp_packet.target_protocol_addr.to_string(),
                )),
                protocol_name: "ARP".to_string(),
                payload_protocol: None,
                payload: &[],
            });
        }

        if let Ok(ipv4_packet) = ipv4::Ipv4Packet::try_from(packet) {
            let payload_protocol = if ipv4_packet.is_fragmented() {
                None
            } else {
                Some(Transport::transport_from_u8(&ipv4_packet.protocol))
            };

            return Ok(Internet {
                source: Some(IpAddr::V4(ipv4_packet.source_addr)),
                source_type: Some(IpType::from_ip(&ipv4_packet.source_addr.to_string())),
                destination: Some(IpAddr::V4(ipv4_packet.dest_addr)),
                destination_type: Some(IpType::from_ip(&ipv4_packet.dest_addr.to_string())),
                protocol_name: "IPv4".to_string(),
                payload_protocol,
                payload: ipv4_packet.payload,
            });
        }

        if let Ok(ipv6_packet) = ipv6::Ipv6Packet::try_from(packet) {
            return Ok(Internet {
                source: Some(IpAddr::V6(ipv6_packet.source_addr)),
                source_type: Some(IpType::from_ip(&ipv6_packet.source_addr.to_string())),
                destination: Some(IpAddr::V6(ipv6_packet.dest_addr)),
                destination_type: Some(IpType::from_ip(&ipv6_packet.dest_addr.to_string())),
                protocol_name: "IPv6".to_string(),
                payload_protocol: Some(Transport::transport_from_u8(&ipv6_packet.next_header)),
                payload: ipv6_packet.payload,
            });
        }
        if profinet::ProfinetPacket::try_from(packet).is_ok() {
            return Ok(Internet {
                source: None,
                source_type: None,
                destination: None,
                destination_type: None,
                protocol_name: "Profinet".to_string(),
                payload_protocol: None,
                payload: &[],
            });
        }
        Err(InternetError::UnsupportedProtocol)
    }
}

// impl<'a> Internet<'a> {
//     pub fn to_transport(&self) -> Option<Transport<'a>> {
//        let protocol = match self.payload_protocol.as_deref()? {
//             "ICMPv6" => TransportProtocol::IcmpV6,
//             "ICMP" => TransportProtocol::Icmp,
//             "UDP" => TransportProtocol::Udp,
//             "TCP" => TransportProtocol::Tcp,
//             "IGMP" => TransportProtocol::Igmp,
//             "PIM" => TransportProtocol::Pim,
//             "PIMv2" => TransportProtocol::PimV2,
//             "VRRP" => TransportProtocol::Vrrp,
//             // Ajoutez d'autres correspondances si nécessaire
//             _ => return None,
//         };

//         Some(Transport {
//             protocol,
//             source_port: None,
//             destination_port: None,
//             payload: None,
//         })
//     }
// }

impl<'a> PartialEq for Internet<'a> {
    fn eq(&self, other: &Self) -> bool {
        self.source == other.source
            && self.source_type == other.source_type
            && self.destination == other.destination
            && self.destination_type == other.destination_type
            && self.protocol_name == other.protocol_name
            && self.payload_protocol == other.payload_protocol
    }
}
use std::hash::{Hash, Hasher};

impl<'a> Hash for Internet<'a> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.source.hash(state);
        self.source_type.hash(state);
        self.destination.hash(state);
        self.destination_type.hash(state);
        self.protocol_name.hash(state);
        self.payload_protocol.hash(state);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parse::transport::protocols::TransportProtocol;
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};
    use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};

    fn ipv4_udp_packet(flags_fragment: u16) -> Vec<u8> {
        vec![
            0x45, // Version + IHL
            0x00, // DSCP/ECN
            0x00,
            0x20, // Total Length = 32
            0x12,
            0x34, // Identification
            (flags_fragment >> 8) as u8,
            flags_fragment as u8,
            64, // TTL
            17, // Protocol = UDP
            0x00,
            0x00, // Header checksum
            192,
            168,
            1,
            10, // Source IP
            192,
            168,
            1,
            20, // Destination IP
            0x30,
            0x39, // UDP source port
            0x00,
            0x35, // UDP destination port
            0x00,
            0x0c, // UDP length
            0x00,
            0x00, // UDP checksum
            0xde,
            0xad,
            0xbe,
            0xef, // UDP payload or fragment bytes
        ]
    }

    #[test]
    fn test_internet_try_from_empty_packet() {
        let packet: &[u8] = &[];
        let result = Internet::try_from(packet);

        assert!(matches!(result, Err(InternetError::EmptyPacket)));
    }

    #[test]
    fn test_internet_try_from_arp() {
        // ARP request minimal valide :
        // HTYPE=1 (Ethernet), PTYPE=0x0800 (IPv4), HLEN=6, PLEN=4, OPER=1 (request)
        // Sender MAC = 00:11:22:33:44:55
        // Sender IP  = 192.168.1.10
        // Target MAC = 00:00:00:00:00:00
        // Target IP  = 192.168.1.1
        let packet = vec![
            0x00, 0x01, // HTYPE
            0x08, 0x00, // PTYPE
            0x06, // HLEN
            0x04, // PLEN
            0x00, 0x01, // OPER
            0x00, 0x11, 0x22, 0x33, 0x44, 0x55, // Sender MAC
            192, 168, 1, 10, // Sender IP
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Target MAC
            192, 168, 1, 1, // Target IP
        ];

        let result = Internet::try_from(packet.as_slice()).unwrap();

        assert_eq!(
            result.source,
            Some(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 10)))
        );
        assert_eq!(
            result.destination,
            Some(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1)))
        );
        assert_eq!(result.source_type, Some(IpType::from_ip("192.168.1.10")));
        assert_eq!(
            result.destination_type,
            Some(IpType::from_ip("192.168.1.1"))
        );
        assert_eq!(result.protocol_name, "ARP");
        assert_eq!(result.payload_protocol, None);
        assert!(result.payload.is_empty());
    }

    #[test]
    fn test_internet_try_from_ipv4_tcp() {
        // Header IPv4 minimal valide (20 octets), protocol = TCP (6)
        // Version=4, IHL=5, Total Length=20
        // Source=192.168.1.10, Destination=192.168.1.20
        let packet = vec![
            0x45, // Version + IHL
            0x00, // DSCP/ECN
            0x00, 0x14, // Total Length = 20
            0x12, 0x34, // Identification
            0x00, 0x00, // Flags + Fragment offset
            64,   // TTL
            6,    // Protocol = TCP
            0x00, 0x00, // Header checksum
            192, 168, 1, 10, // Source IP
            192, 168, 1, 20, // Destination IP
        ];

        let result = Internet::try_from(packet.as_slice()).unwrap();

        assert_eq!(
            result.source,
            Some(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 10)))
        );
        assert_eq!(
            result.destination,
            Some(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 20)))
        );
        assert_eq!(result.source_type, Some(IpType::from_ip("192.168.1.10")));
        assert_eq!(
            result.destination_type,
            Some(IpType::from_ip("192.168.1.20"))
        );
        assert_eq!(result.protocol_name, "IPv4");
        assert_eq!(result.payload_protocol, Some(TransportProtocol::Tcp));
        assert!(result.payload.is_empty());
    }

    #[test]
    fn test_internet_try_from_ipv4_udp_not_fragmented_keeps_transport_protocol() {
        let packet = ipv4_udp_packet(0);

        let result = Internet::try_from(packet.as_slice()).unwrap();

        assert_eq!(result.protocol_name, "IPv4");
        assert_eq!(result.payload_protocol, Some(TransportProtocol::Udp));
    }

    #[test]
    fn test_internet_try_from_ipv4_initial_fragment_skips_transport_protocol() {
        let packet = ipv4_udp_packet(0x2000);

        let result = Internet::try_from(packet.as_slice()).unwrap();

        assert_eq!(result.protocol_name, "IPv4");
        assert_eq!(result.payload_protocol, None);
    }

    #[test]
    fn test_internet_try_from_ipv4_non_initial_fragment_skips_transport_protocol() {
        let packet = ipv4_udp_packet(1);

        let result = Internet::try_from(packet.as_slice()).unwrap();

        assert_eq!(result.protocol_name, "IPv4");
        assert_eq!(result.payload_protocol, None);
    }

    #[test]
    fn test_internet_try_from_ipv6_udp() {
        // Header IPv6 minimal valide (40 octets), next_header = UDP (17), payload length = 0
        let packet = vec![
            0x60, 0x00, 0x00, 0x00, // Version, Traffic Class, Flow Label
            0x00, 0x00, // Payload Length = 0
            17,   // Next Header = UDP
            64,   // Hop Limit
            // Source IP = 2001:db8::1
            0x20, 0x01, 0x0d, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x01, // Destination IP = 2001:db8::2
            0x20, 0x01, 0x0d, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x02,
        ];

        let result = Internet::try_from(packet.as_slice()).unwrap();

        assert_eq!(
            result.source,
            Some(IpAddr::V6(Ipv6Addr::new(0x2001, 0x0db8, 0, 0, 0, 0, 0, 1)))
        );
        assert_eq!(
            result.destination,
            Some(IpAddr::V6(Ipv6Addr::new(0x2001, 0x0db8, 0, 0, 0, 0, 0, 2)))
        );
        assert_eq!(result.source_type, Some(IpType::from_ip("2001:db8::1")));
        assert_eq!(
            result.destination_type,
            Some(IpType::from_ip("2001:db8::2"))
        );
        assert_eq!(result.protocol_name, "IPv6");
        assert_eq!(result.payload_protocol, Some(TransportProtocol::Udp));
        assert!(result.payload.is_empty());
    }

    #[test]
    fn test_internet_try_from_unsupported_protocol() {
        // Données volontairement invalides pour ARP / IPv4 / IPv6 / Profinet
        let packet = vec![0xff, 0xaa, 0xbb, 0xcc, 0xdd, 0xee];

        let result = Internet::try_from(packet.as_slice());

        assert!(matches!(result, Err(InternetError::UnsupportedProtocol)));
    }

    #[test]
    fn test_internet_partial_eq_ignores_payload() {
        let a = Internet {
            source: Some(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 10))),
            source_type: Some(IpType::from_ip("192.168.1.10")),
            destination: Some(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 20))),
            destination_type: Some(IpType::from_ip("192.168.1.20")),
            protocol_name: "IPv4".to_string(),
            payload_protocol: Some(TransportProtocol::Tcp),
            payload: &[1, 2, 3, 4],
        };

        let b = Internet {
            source: Some(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 10))),
            source_type: Some(IpType::from_ip("192.168.1.10")),
            destination: Some(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 20))),
            destination_type: Some(IpType::from_ip("192.168.1.20")),
            protocol_name: "IPv4".to_string(),
            payload_protocol: Some(TransportProtocol::Tcp),
            payload: &[9, 9, 9, 9],
        };

        assert_eq!(a, b);
    }

    #[test]
    fn test_internet_hash_ignores_payload() {
        let a = Internet {
            source: Some(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1))),
            source_type: Some(IpType::from_ip("10.0.0.1")),
            destination: Some(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 2))),
            destination_type: Some(IpType::from_ip("10.0.0.2")),
            protocol_name: "IPv4".to_string(),
            payload_protocol: Some(TransportProtocol::Udp),
            payload: &[1, 2, 3],
        };

        let b = Internet {
            source: Some(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1))),
            source_type: Some(IpType::from_ip("10.0.0.1")),
            destination: Some(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 2))),
            destination_type: Some(IpType::from_ip("10.0.0.2")),
            protocol_name: "IPv4".to_string(),
            payload_protocol: Some(TransportProtocol::Udp),
            payload: &[99, 88, 77],
        };

        let mut hasher_a = DefaultHasher::new();
        let mut hasher_b = DefaultHasher::new();

        a.hash(&mut hasher_a);
        b.hash(&mut hasher_b);

        assert_eq!(hasher_a.finish(), hasher_b.finish());
    }

    #[test]
    fn test_internet_partial_eq_detects_difference() {
        let a = Internet {
            source: Some(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 10))),
            source_type: Some(IpType::from_ip("192.168.1.10")),
            destination: Some(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 20))),
            destination_type: Some(IpType::from_ip("192.168.1.20")),
            protocol_name: "IPv4".to_string(),
            payload_protocol: Some(TransportProtocol::Tcp),
            payload: &[],
        };

        let b = Internet {
            source: Some(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 11))),
            source_type: Some(IpType::from_ip("192.168.1.11")),
            destination: Some(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 20))),
            destination_type: Some(IpType::from_ip("192.168.1.20")),
            protocol_name: "IPv4".to_string(),
            payload_protocol: Some(TransportProtocol::Tcp),
            payload: &[],
        };

        assert_ne!(a, b);
    }
}