pktparse-0.7.1/.cargo_vcs_info.json 0000644 00000000136 00000000001 0012672 0 ustar {
"git": {
"sha1": "f8e470b077cdf1fe29fd3eda5d5bf16198f90611"
},
"path_in_vcs": ""
} pktparse-0.7.1/.github/workflows/rust.yml 0000644 0000000 0000000 00000000342 00726746425 0016626 0 ustar 0000000 0000000 name: Rust
on: [push]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Build and Lint
run: cargo clippy --verbose
- name: Run tests
run: cargo test --verbose
pktparse-0.7.1/.gitignore 0000644 0000000 0000000 00000000035 00726746425 0013500 0 ustar 0000000 0000000 target
Cargo.lock
*.bk
*.swp
pktparse-0.7.1/.travis.yml 0000644 0000000 0000000 00000000017 00726746425 0013621 0 ustar 0000000 0000000 language: rust
pktparse-0.7.1/Cargo.toml 0000644 00000001727 00000000001 0010677 0 ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2018"
name = "pktparse"
version = "0.7.1"
authors = ["Antoine Plaskowski", "Nathan Moos", "Xavier Bestel"]
description = "Collection of packet parsers"
readme = "README.md"
keywords = ["network", "packet", "parsing", "nom", "library"]
categories = ["encoding", "network-programming", "parser-implementations"]
license = "LGPL-3.0"
repository = "https://github.com/bestouff/pktparse-rs"
[dependencies.nom]
version = "7"
[dependencies.serde]
version = "1.0"
features = ["derive"]
optional = true
pktparse-0.7.1/Cargo.toml.orig 0000644 0000000 0000000 00000000765 00726746425 0014411 0 ustar 0000000 0000000 [package]
name = "pktparse"
version = "0.7.1"
authors = ["Antoine Plaskowski", "Nathan Moos", "Xavier Bestel"]
description = "Collection of packet parsers"
repository = "https://github.com/bestouff/pktparse-rs"
readme = "README.md"
license = "LGPL-3.0"
edition = "2018"
keywords = ["network", "packet", "parsing", "nom", "library"]
categories = ["encoding", "network-programming", "parser-implementations"]
[dependencies]
nom = "7"
serde = { version = "1.0", optional = true, features = ["derive"] }
pktparse-0.7.1/LICENSE.md 0000644 0000000 0000000 00000016730 00726746425 0013125 0 ustar 0000000 0000000 ### GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates the
terms and conditions of version 3 of the GNU General Public License,
supplemented by the additional permissions listed below.
#### 0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the
GNU General Public License.
"The Library" refers to a covered work governed by this License, other
than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
#### 1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
#### 2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
- a) under this License, provided that you make a good faith effort
to ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
- b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
#### 3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from a
header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
- a) Give prominent notice with each copy of the object code that
the Library is used in it and that the Library and its use are
covered by this License.
- b) Accompany the object code with a copy of the GNU GPL and this
license document.
#### 4. Combined Works.
You may convey a Combined Work under terms of your choice that, taken
together, effectively do not restrict modification of the portions of
the Library contained in the Combined Work and reverse engineering for
debugging such modifications, if you also do each of the following:
- a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
- b) Accompany the Combined Work with a copy of the GNU GPL and this
license document.
- c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
- d) Do one of the following:
- 0) Convey the Minimal Corresponding Source under the terms of
this License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
- 1) Use a suitable shared library mechanism for linking with
the Library. A suitable mechanism is one that (a) uses at run
time a copy of the Library already present on the user's
computer system, and (b) will operate properly with a modified
version of the Library that is interface-compatible with the
Linked Version.
- e) Provide Installation Information, but only if you would
otherwise be required to provide such information under section 6
of the GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the Application
with a modified version of the Linked Version. (If you use option
4d0, the Installation Information must accompany the Minimal
Corresponding Source and Corresponding Application Code. If you
use option 4d1, you must provide the Installation Information in
the manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.)
#### 5. Combined Libraries.
You may place library facilities that are a work based on the Library
side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
- a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities, conveyed under the terms of this License.
- b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
#### 6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
as you received it specifies that a certain numbered version of the
GNU Lesser General Public License "or any later version" applies to
it, you have the option of following the terms and conditions either
of that published version or of any later version published by the
Free Software Foundation. If the Library as you received it does not
specify a version number of the GNU Lesser General Public License, you
may choose any version of the GNU Lesser General Public License ever
published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library. pktparse-0.7.1/README.md 0000644 0000000 0000000 00000001242 00726746425 0012770 0 ustar 0000000 0000000 # PktParse
This repository is just a bunch of packet parsing routines made with [nom](https://github.com/Geal/nom)
## Usage
Admitting your `packet.data` is an `[u8]`:
```rust
if let Done(remaining, eth_frame) = ethernet::parse_ethernet_frame(packet.data) {
if eth_frame.ethertype != EtherType::IPv4 {
continue;
}
if let Done(remaining, ipv4_packet) = ipv4::parse_ipv4_header(remaining) {
```
For now the list of available parsers is rather short:
- ethernet (with optional VLAN tag)
- IPv4
- IPv6
- UDP
- TCP
- ICMP
... and we'll gladly accept contributions.
## Last changes
- IHL is not multiplied by 4 anymore
pktparse-0.7.1/src/arp.rs 0000644 0000000 0000000 00000010501 00726746425 0013426 0 ustar 0000000 0000000 //! Handles parsing of Arp pakets
use nom::number;
use nom::IResult;
use std::net::Ipv4Addr;
use crate::ethernet;
use crate::ethernet::MacAddress;
use crate::ipv4;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum HardwareAddressType {
Ethernet,
Other(u16),
}
impl From for HardwareAddressType {
fn from(raw: u16) -> Self {
match raw {
0x0001 => Self::Ethernet,
other => Self::Other(other),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ProtocolAddressType {
IPv4,
Other(u16),
}
impl From for ProtocolAddressType {
fn from(raw: u16) -> Self {
match raw {
0x0800 => Self::IPv4,
other => Self::Other(other),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Operation {
Request,
Reply,
Other(u16),
}
impl From for Operation {
fn from(raw: u16) -> Self {
match raw {
0x0001 => Self::Request,
0x0002 => Self::Reply,
other => Self::Other(other),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ArpPacket {
pub hw_addr_type: HardwareAddressType,
pub proto_addr_type: ProtocolAddressType,
pub hw_addr_size: u8,
pub proto_addr_size: u8,
pub operation: Operation,
pub src_mac: MacAddress,
pub src_addr: Ipv4Addr,
pub dest_mac: MacAddress,
pub dest_addr: Ipv4Addr,
}
fn parse_hw_addr_type(input: &[u8]) -> IResult<&[u8], HardwareAddressType> {
let (input, hw_addr_type) = number::streaming::be_u16(input)?;
Ok((input, hw_addr_type.into()))
}
fn parse_proto_addr_type(input: &[u8]) -> IResult<&[u8], ProtocolAddressType> {
let (input, proto_addr_type) = number::streaming::be_u16(input)?;
Ok((input, proto_addr_type.into()))
}
fn parse_operation(input: &[u8]) -> IResult<&[u8], Operation> {
let (input, operation) = number::streaming::be_u16(input)?;
Ok((input, operation.into()))
}
pub fn parse_arp_pkt(input: &[u8]) -> IResult<&[u8], ArpPacket> {
let (input, hw_addr_type) = parse_hw_addr_type(input)?;
let (input, proto_addr_type) = parse_proto_addr_type(input)?;
let (input, hw_addr_size) = number::streaming::be_u8(input)?;
let (input, proto_addr_size) = number::streaming::be_u8(input)?;
let (input, operation) = parse_operation(input)?;
let (input, src_mac) = ethernet::mac_address(input)?;
let (input, src_addr) = ipv4::address(input)?;
let (input, dest_mac) = ethernet::mac_address(input)?;
let (input, dest_addr) = ipv4::address(input)?;
Ok((
input,
ArpPacket {
hw_addr_type,
proto_addr_type,
hw_addr_size,
proto_addr_size,
operation,
src_mac,
src_addr,
dest_mac,
dest_addr,
},
))
}
#[cfg(test)]
mod tests {
use super::{
parse_arp_pkt, ArpPacket, HardwareAddressType, MacAddress, Operation, ProtocolAddressType,
};
use std::net::Ipv4Addr;
const EMPTY_SLICE: &'static [u8] = &[];
#[test]
fn arp_packet_works() {
let bytes = [
0, 1, // hardware type
8, 0, // proto type
6, 4, // sizes
0, 1, // arp operation
0x00, 0x1b, 0x21, 0x0f, 0x91, 0x9b, // src mac
10, 10, 1, 135, // src ip
0xde, 0xad, 0xc0, 0x00, 0xff, 0xee, // dest mac
192, 168, 1, 253, // dest ip
];
let expectation = ArpPacket {
hw_addr_type: HardwareAddressType::Ethernet,
proto_addr_type: ProtocolAddressType::IPv4,
hw_addr_size: 6,
proto_addr_size: 4,
operation: Operation::Request,
src_mac: MacAddress([0x00, 0x1b, 0x21, 0x0f, 0x91, 0x9b]),
src_addr: Ipv4Addr::new(10, 10, 1, 135),
dest_mac: MacAddress([0xde, 0xad, 0xc0, 0x00, 0xff, 0xee]),
dest_addr: Ipv4Addr::new(192, 168, 1, 253),
};
assert_eq!(parse_arp_pkt(&bytes), Ok((EMPTY_SLICE, expectation)));
}
}
pktparse-0.7.1/src/ethernet.rs 0000644 0000000 0000000 00000023530 00726746425 0014470 0 ustar 0000000 0000000 //! Handles parsing of Ethernet headers
use nom::bytes;
use nom::number;
use nom::IResult;
use std::convert::TryFrom;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct MacAddress(pub [u8; 6]);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum EtherType {
LANMIN,
LANMAX,
IPv4,
ARP,
WOL,
TRILL,
DECnet,
RARP,
AppleTalk,
AARP,
VLAN,
IPX,
Qnet,
IPv6,
FlowControl,
CobraNet,
MPLSuni,
MPLSmulti,
PPPoEdiscovery,
PPPoEsession,
HomePlug,
EAPOL,
PROFINET,
HyperSCSI,
ATAOE,
EtherCAT,
QinQ,
Powerlink,
GOOSE,
GSE,
LLDP,
SERCOS,
HomePlugAV,
MRP,
MACsec,
PBB,
PTP,
PRP,
CFM,
FCoE,
FCoEi,
RoCE,
TTE,
HSR,
CTP,
VLANdouble,
Other(u16),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct EthernetFrame {
pub source_mac: MacAddress,
pub dest_mac: MacAddress,
pub ethertype: EtherType,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct VlanEthernetFrame {
pub source_mac: MacAddress,
pub dest_mac: MacAddress,
pub ethertype: EtherType,
pub vid: Option,
}
/// The VID and actual ethertype that comes after the VLAN identifier 0x8100
struct VidEthertype {
vid: u16,
ethertype: EtherType,
}
impl From for EtherType {
fn from(raw: u16) -> Self {
match raw {
0x002E => Self::LANMIN, // 802.3 Min data length
0x05DC => Self::LANMAX, // 802.3 Max data length
0x0800 => Self::IPv4, // Internet Protocol version 4 (IPv4)
0x0806 => Self::ARP, // Address Resolution Protocol (ARP)
0x0842 => Self::WOL, // Wake-on-LAN[4]
0x22F3 => Self::TRILL, // IETF TRILL Protocol
0x6003 => Self::DECnet, // DECnet Phase IV
0x8035 => Self::RARP, // Reverse Address Resolution Protocol
0x809B => Self::AppleTalk, // AppleTalk (Ethertalk)
0x80F3 => Self::AARP, // AppleTalk Address Resolution Protocol (AARP)
0x8100 => Self::VLAN, // VLAN-tagged frame (IEEE 802.1Q) and Shortest Path Bridging IEEE 802.1aq[5]
0x8137 => Self::IPX, // IPX
0x8204 => Self::Qnet, // QNX Qnet
0x86DD => Self::IPv6, // Internet Protocol Version 6 (IPv6)
0x8808 => Self::FlowControl, // Ethernet flow control
0x8819 => Self::CobraNet, // CobraNet
0x8847 => Self::MPLSuni, // MPLS unicast
0x8848 => Self::MPLSmulti, // MPLS multicast
0x8863 => Self::PPPoEdiscovery, // PPPoE Discovery Stage
0x8864 => Self::PPPoEsession, // PPPoE Session Stage
0x887B => Self::HomePlug, // HomePlug 1.0 MME
0x888E => Self::EAPOL, // EAP over LAN (IEEE 802.1X)
0x8892 => Self::PROFINET, // PROFINET Protocol
0x889A => Self::HyperSCSI, // HyperSCSI (SCSI over Ethernet)
0x88A2 => Self::ATAOE, // ATA over Ethernet
0x88A4 => Self::EtherCAT, // EtherCAT Protocol
0x88A8 => Self::QinQ, // Provider Bridging (IEEE 802.1ad) & Shortest Path Bridging IEEE 802.1aq[5]
0x88AB => Self::Powerlink, // Ethernet Powerlink[citation needed]
0x88B8 => Self::GOOSE, // GOOSE (Generic Object Oriented Substation event)
0x88B9 => Self::GSE, // GSE (Generic Substation Events) Management Services
0x88CC => Self::LLDP, // Link Layer Discovery Protocol (LLDP)
0x88CD => Self::SERCOS, // SERCOS III
0x88E1 => Self::HomePlugAV, // HomePlug AV MME[citation needed]
0x88E3 => Self::MRP, // Media Redundancy Protocol (IEC62439-2)
0x88E5 => Self::MACsec, // MAC security (IEEE 802.1AE)
0x88E7 => Self::PBB, // Provider Backbone Bridges (PBB) (IEEE 802.1ah)
0x88F7 => Self::PTP, // Precision Time Protocol (PTP) over Ethernet (IEEE 1588)
0x88FB => Self::PRP, // Parallel Redundancy Protocol (PRP)
0x8902 => Self::CFM, // IEEE 802.1ag Connectivity Fault Management (CFM) Protocol / ITU-T Recommendation Y.1731 (OAM)
0x8906 => Self::FCoE, // Fibre Channel over Ethernet (FCoE)
0x8914 => Self::FCoEi, // FCoE Initialization Protocol
0x8915 => Self::RoCE, // RDMA over Converged Ethernet (RoCE)
0x891D => Self::TTE, // TTEthernet Protocol Control Frame (TTE)
0x892F => Self::HSR, // High-availability Seamless Redundancy (HSR)
0x9000 => Self::CTP, // Ethernet Configuration Testing Protocol[6]
0x9100 => Self::VLANdouble, // VLAN-tagged (IEEE 802.1Q) frame with double tagging
other => Self::Other(other),
}
}
}
pub(crate) fn mac_address(input: &[u8]) -> IResult<&[u8], MacAddress> {
let (input, mac) = bytes::streaming::take(6u8)(input)?;
Ok((input, MacAddress(<[u8; 6]>::try_from(mac).unwrap())))
}
fn parse_ethertype(input: &[u8]) -> IResult<&[u8], EtherType> {
let (input, ether) = number::streaming::be_u16(input)?;
Ok((input, ether.into()))
}
fn vid_ethertype(input: &[u8]) -> IResult<&[u8], VidEthertype> {
let (input, vid) = number::streaming::be_u16(input)?;
let (input, ethertype) = parse_ethertype(input)?;
Ok((input, VidEthertype { vid, ethertype }))
}
fn vlan_ethernet_frame(input: &[u8]) -> IResult<&[u8], VlanEthernetFrame> {
let (input, dest_mac) = mac_address(input)?;
let (input, source_mac) = mac_address(input)?;
let (input, ethertype) = parse_ethertype(input)?;
Ok((
input,
VlanEthernetFrame {
source_mac,
dest_mac,
ethertype,
vid: None,
},
))
}
pub fn parse_ethernet_frame(input: &[u8]) -> IResult<&[u8], EthernetFrame> {
let (input, dest_mac) = mac_address(input)?;
let (input, source_mac) = mac_address(input)?;
let (input, ethertype) = parse_ethertype(input)?;
Ok((
input,
EthernetFrame {
source_mac,
dest_mac,
ethertype,
},
))
}
/// Similar to `parse_ethernet_frame` but returns a `VlanEthernetFrame` on success. This uses more
/// CPU cycles but handles both tagged and untagged ethernet traffic.
pub fn parse_vlan_ethernet_frame(i: &[u8]) -> IResult<&[u8], VlanEthernetFrame> {
let (mut frame_content, mut frame) = vlan_ethernet_frame(i)?;
if frame.ethertype == EtherType::VLAN {
let (fc, vid_et) = vid_ethertype(frame_content)?;
frame.vid = Some(vid_et.vid);
frame.ethertype = vid_et.ethertype;
frame_content = fc;
}
Ok((frame_content, frame))
}
#[cfg(test)]
mod tests {
use super::{
mac_address, parse_ethernet_frame, parse_ethertype, EtherType, EthernetFrame, MacAddress,
};
const EMPTY_SLICE: &'static [u8] = &[];
#[test]
fn mac_address_works() {
let bytes = [0x9c, 0x5c, 0x8e, 0x90, 0xca, 0xfc];
assert_eq!(mac_address(&bytes), Ok((EMPTY_SLICE, MacAddress(bytes))));
}
macro_rules! mk_ethertype_test {
($func_name:ident, $bytes:expr, $correct_ethertype:expr) => {
#[test]
fn $func_name() {
let bytes = $bytes;
assert_eq!(
parse_ethertype(&bytes),
Ok((EMPTY_SLICE, $correct_ethertype))
);
}
};
}
mk_ethertype_test!(ethertype_gets_ipv4_correct, [0x08, 0x00], EtherType::IPv4);
mk_ethertype_test!(ethertype_gets_arp_correct, [0x08, 0x06], EtherType::ARP);
mk_ethertype_test!(ethertype_gets_ipv6_correct, [0x86, 0xDD], EtherType::IPv6);
mk_ethertype_test!(ethertype_gets_vlan_correct, [0x81, 0x00], EtherType::VLAN);
#[test]
fn ethernet_frame_works() {
let bytes = [
0x00, 0x23, 0x54, 0x07, 0x93, 0x6c, /* dest MAC */
0x00, 0x1b, 0x21, 0x0f, 0x91, 0x9b, /* src MAC */
0x08, 0x00, // Ethertype
];
let expectation = EthernetFrame {
source_mac: MacAddress([0x00, 0x1b, 0x21, 0x0f, 0x91, 0x9b]),
dest_mac: MacAddress([0x00, 0x23, 0x54, 0x07, 0x93, 0x6c]),
ethertype: EtherType::IPv4,
};
assert_eq!(parse_ethernet_frame(&bytes), Ok((EMPTY_SLICE, expectation)));
}
#[test]
fn parse_vlan_ethernet_frame_works() {
use super::{parse_vlan_ethernet_frame, VlanEthernetFrame};
let bytes = [
0x00, 0x23, 0x54, 0x07, 0x93, 0x6c, /* dest MAC */
0x00, 0x1b, 0x21, 0x0f, 0x91, 0x9b, /* src MAC */
0x81, 0x00, 0x04, 0xd2, // VLAN
0x08, 0x00, // Ethertype
];
let expectation = VlanEthernetFrame {
source_mac: MacAddress([0x00, 0x1b, 0x21, 0x0f, 0x91, 0x9b]),
dest_mac: MacAddress([0x00, 0x23, 0x54, 0x07, 0x93, 0x6c]),
ethertype: EtherType::IPv4,
vid: Some(1234),
};
assert_eq!(
parse_vlan_ethernet_frame(&bytes),
Ok((EMPTY_SLICE, expectation))
);
let bytes = [
0x00, 0x23, 0x54, 0x07, 0x93, 0x6c, /* dest MAC */
0x00, 0x1b, 0x21, 0x0f, 0x91, 0x9b, /* src MAC */
0x08, 0x00, // Ethertype
];
let expectation = VlanEthernetFrame {
source_mac: MacAddress([0x00, 0x1b, 0x21, 0x0f, 0x91, 0x9b]),
dest_mac: MacAddress([0x00, 0x23, 0x54, 0x07, 0x93, 0x6c]),
ethertype: EtherType::IPv4,
vid: None,
};
assert_eq!(
parse_vlan_ethernet_frame(&bytes),
Ok((EMPTY_SLICE, expectation))
);
}
}
pktparse-0.7.1/src/icmp.rs 0000644 0000000 0000000 00000031557 00726746425 0013612 0 ustar 0000000 0000000 //! Handles parsing of ICMP
use crate::ipv4::{address, parse_ipv4_header, IPv4Header};
use nom::{bytes::streaming::take, number, IResult};
use std::net::Ipv4Addr;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Unreachable {
DestinationNetworkUnreachable,
DestinationHostUnreachable,
DestinationProtocolUnreachable,
DestinationPortUnreachable,
FragmentationRequired,
SourceRouteFailed,
DestinationNetworkUnknown,
DestinationHostUnknown,
SourceHostIsolated,
NetworkAdministrativelyProhibited,
HostAdministrativelyProhibited,
NetworkUnreachableForTos,
HostUnreachableForTos,
CommunicationAdministrativelyProhibited,
HostPrecedenceViolation,
PrecedentCutoffInEffect,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Redirect {
Network,
Host,
TosAndNetwork,
TosAndHost,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum TimeExceeded {
TTL,
FragmentReassembly,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ParameterProblem {
Pointer,
MissingRequiredOption,
BadLength,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ExtendedEchoReply {
NoError,
MalformedQuery,
NoSuchInterface,
NoSuchTableEntry,
MupltipleInterfacesStatisfyQuery,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum IcmpCode {
EchoReply,
Reserved,
DestinationUnreachable(Unreachable),
SourceQuench,
Redirect(Redirect),
EchoRequest,
RouterAdvertisment,
RouterSolicication,
TimeExceeded(TimeExceeded),
ParameterProblem(ParameterProblem),
Timestamp,
TimestampReply,
ExtendedEchoRequest,
ExtendedEchoReply(ExtendedEchoReply),
Other(u16),
}
impl From for IcmpCode {
fn from(raw: u16) -> Self {
let [t, c] = raw.to_be_bytes();
match t {
0x00 => Self::EchoReply,
0x01 => Self::Reserved,
0x02 => Self::Reserved,
0x03 => match c {
0x00 => Self::DestinationUnreachable(Unreachable::DestinationNetworkUnreachable),
0x01 => Self::DestinationUnreachable(Unreachable::DestinationHostUnreachable),
0x02 => Self::DestinationUnreachable(Unreachable::DestinationProtocolUnreachable),
0x03 => Self::DestinationUnreachable(Unreachable::DestinationPortUnreachable),
0x04 => Self::DestinationUnreachable(Unreachable::FragmentationRequired),
0x05 => Self::DestinationUnreachable(Unreachable::SourceRouteFailed),
0x06 => Self::DestinationUnreachable(Unreachable::DestinationNetworkUnknown),
0x07 => Self::DestinationUnreachable(Unreachable::DestinationHostUnknown),
0x08 => Self::DestinationUnreachable(Unreachable::SourceHostIsolated),
0x09 => {
Self::DestinationUnreachable(Unreachable::NetworkAdministrativelyProhibited)
}
0x0A => Self::DestinationUnreachable(Unreachable::HostAdministrativelyProhibited),
0x0B => Self::DestinationUnreachable(Unreachable::NetworkUnreachableForTos),
0x0C => Self::DestinationUnreachable(Unreachable::HostUnreachableForTos),
0x0D => Self::DestinationUnreachable(
Unreachable::CommunicationAdministrativelyProhibited,
),
0x0E => Self::DestinationUnreachable(Unreachable::HostPrecedenceViolation),
0x0F => Self::DestinationUnreachable(Unreachable::PrecedentCutoffInEffect),
_ => Self::Other(raw),
},
0x04 => match c {
0x00 => Self::SourceQuench,
_ => Self::Other(raw),
},
0x05 => match c {
0x00 => Self::Redirect(Redirect::Network),
0x01 => Self::Redirect(Redirect::Host),
0x02 => Self::Redirect(Redirect::TosAndNetwork),
0x03 => Self::Redirect(Redirect::TosAndHost),
_ => Self::Other(raw),
},
0x07 => Self::Reserved,
0x08 => Self::EchoRequest,
0x09 => Self::RouterAdvertisment,
0x0A => Self::RouterSolicication,
0x0B => match c {
0x00 => Self::TimeExceeded(TimeExceeded::TTL),
0x01 => Self::TimeExceeded(TimeExceeded::FragmentReassembly),
_ => Self::Other(raw),
},
0x0C => match c {
0x00 => Self::ParameterProblem(ParameterProblem::Pointer),
0x01 => Self::ParameterProblem(ParameterProblem::MissingRequiredOption),
0x02 => Self::ParameterProblem(ParameterProblem::BadLength),
_ => Self::Other(raw),
},
0x0D => Self::Timestamp,
0x0E => Self::TimestampReply,
0x2A => Self::ExtendedEchoRequest,
0x2B => match c {
0x00 => Self::ExtendedEchoReply(ExtendedEchoReply::NoError),
0x01 => Self::ExtendedEchoReply(ExtendedEchoReply::MalformedQuery),
0x02 => Self::ExtendedEchoReply(ExtendedEchoReply::NoSuchInterface),
0x03 => Self::ExtendedEchoReply(ExtendedEchoReply::NoSuchTableEntry),
0x04 => {
Self::ExtendedEchoReply(ExtendedEchoReply::MupltipleInterfacesStatisfyQuery)
}
_ => Self::Other(raw),
},
_ => Self::Other(raw),
}
}
}
fn parse_icmp_code(input: &[u8]) -> IResult<&[u8], IcmpCode> {
let (input, code) = number::streaming::be_u16(input)?;
Ok((input, code.into()))
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(transparent)]
pub struct IcmpPayloadPacket([u8; 8]);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum IcmpData {
Unreachable {
nexthop_mtu: u16,
header: IPv4Header,
packet: IcmpPayloadPacket,
},
Redirect {
gateway: Ipv4Addr,
header: IPv4Header,
packet: IcmpPayloadPacket,
},
TimeExceeded {
header: IPv4Header,
packet: IcmpPayloadPacket,
},
None,
}
fn parse_ipv4_header_and_packet(input: &[u8]) -> IResult<&[u8], (IPv4Header, IcmpPayloadPacket)> {
let (input, header) = parse_ipv4_header(input)?;
let mut packet: [u8; 8] = Default::default();
let (input, data) = take(8usize)(input)?;
packet.copy_from_slice(data);
Ok((input, (header, IcmpPayloadPacket(packet))))
}
fn parse_icmp_unreachable_data(input: &[u8]) -> IResult<&[u8], IcmpData> {
let (input, _) = number::streaming::be_u16(input)?;
let (input, nexthop_mtu) = number::streaming::be_u16(input)?;
let (input, (header, packet)) = parse_ipv4_header_and_packet(input)?;
Ok((
input,
IcmpData::Unreachable {
nexthop_mtu,
header,
packet,
},
))
}
fn parse_icmp_redirect_data(input: &[u8]) -> IResult<&[u8], IcmpData> {
let (input, gateway) = address(input)?;
let (input, (header, packet)) = parse_ipv4_header_and_packet(input)?;
Ok((
input,
IcmpData::Redirect {
gateway,
header,
packet,
},
))
}
fn parse_icmp_timeexceeded_data(input: &[u8]) -> IResult<&[u8], IcmpData> {
let (input, _) = number::streaming::be_u32(input)?;
let (input, (header, packet)) = parse_ipv4_header_and_packet(input)?;
Ok((input, IcmpData::TimeExceeded { header, packet }))
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct IcmpHeader {
pub code: IcmpCode,
pub checksum: u16,
pub data: IcmpData,
}
pub fn parse_icmp_header(input: &[u8]) -> IResult<&[u8], IcmpHeader> {
let (input, code) = parse_icmp_code(input)?;
let (input, checksum) = number::streaming::be_u16(input)?;
let (input, data) = match code {
IcmpCode::DestinationUnreachable(_) => parse_icmp_unreachable_data(input)?,
IcmpCode::Redirect(_) => parse_icmp_redirect_data(input)?,
IcmpCode::TimeExceeded(_) => parse_icmp_timeexceeded_data(input)?,
_ => (input, IcmpData::None),
};
Ok((
input,
IcmpHeader {
code,
checksum,
data,
},
))
}
#[cfg(test)]
mod tests {
use super::{
parse_icmp_header, IcmpCode, IcmpData, IcmpHeader, IcmpPayloadPacket, Redirect, Unreachable,
};
use crate::ip::IPProtocol;
use crate::ipv4::IPv4Header;
use nom::{Err, Needed};
use std::net::Ipv4Addr;
const EMPTY_SLICE: &'static [u8] = &[];
fn get_icmp_ipv4_header_and_packet() -> (IPv4Header, IcmpPayloadPacket) {
(
IPv4Header {
version: 4,
ihl: 5,
tos: 0,
length: 1500,
id: 0x1ae6,
flags: 0x01,
fragment_offset: 0,
ttl: 64,
protocol: IPProtocol::ICMP,
chksum: 0x22ed,
source_addr: Ipv4Addr::new(10, 10, 1, 135),
dest_addr: Ipv4Addr::new(10, 10, 1, 180),
},
IcmpPayloadPacket([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]),
)
}
fn get_icmp_redirect_data() -> (Vec, IcmpHeader) {
let bytes = [
5, // type
1, // code
0xaa, 0xbb, // checksum
0x0a, 0x0a, 0x01, 0x86, // gateway addr
0x45, /* IP version and length = 20 */
0x00, /* Differentiated services field */
0x05, 0xdc, /* Total length */
0x1a, 0xe6, /* Identification */
0x20, 0x00, /* flags and fragment offset */
0x40, /* TTL */
0x01, /* protocol */
0x22, 0xed, /* checksum */
0x0a, 0x0a, 0x01, 0x87, /* source IP */
0x0a, 0x0a, 0x01, 0xb4, /* destination IP */
0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8,
];
let (header, packet) = get_icmp_ipv4_header_and_packet();
let expected = IcmpHeader {
code: IcmpCode::Redirect(Redirect::Host),
checksum: 0xaabb,
data: IcmpData::Redirect {
gateway: Ipv4Addr::new(10, 10, 1, 134),
header: header,
packet: packet,
},
};
(bytes.to_vec(), expected)
}
fn get_icmp_unreachable_data() -> (Vec, IcmpHeader) {
let bytes = [
3, // type
1, // code
0xaa, 0xbb, // checksum
0x00, 0x00, // unused
0x00, 0x7, // Next-hop MTU
0x45, /* IP version and length = 20 */
0x00, /* Differentiated services field */
0x05, 0xdc, /* Total length */
0x1a, 0xe6, /* Identification */
0x20, 0x00, /* flags and fragment offset */
0x40, /* TTL */
0x01, /* protocol */
0x22, 0xed, /* checksum */
0x0a, 0x0a, 0x01, 0x87, /* source IP */
0x0a, 0x0a, 0x01, 0xb4, /* destination IP */
0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8,
];
let (header, packet) = get_icmp_ipv4_header_and_packet();
let expected = IcmpHeader {
code: IcmpCode::DestinationUnreachable(Unreachable::DestinationHostUnreachable),
checksum: 0xaabb,
data: IcmpData::Unreachable {
nexthop_mtu: 7,
header: header,
packet: packet,
},
};
(bytes.to_vec(), expected)
}
#[test]
fn icmp_unreachable() {
let (bytes, expected) = get_icmp_unreachable_data();
assert_eq!(parse_icmp_header(&bytes), Ok((EMPTY_SLICE, expected)))
}
#[test]
fn icmp_unreachable_incomplete() {
let (mut bytes, _) = get_icmp_unreachable_data();
bytes.pop();
assert_eq!(
parse_icmp_header(&bytes),
Err(Err::Incomplete(Needed::new(1)))
)
}
#[test]
fn icmp_redirect() {
let (bytes, expected) = get_icmp_redirect_data();
assert_eq!(parse_icmp_header(&bytes), Ok((EMPTY_SLICE, expected)))
}
#[test]
fn icmp_redirect_incomplete() {
let (mut bytes, _) = get_icmp_redirect_data();
bytes.pop();
assert_eq!(
parse_icmp_header(&bytes),
Err(Err::Incomplete(Needed::new(1)))
)
}
}
pktparse-0.7.1/src/ip.rs 0000644 0000000 0000000 00000003370 00726746425 0013262 0 ustar 0000000 0000000 //! Handles parsing of Internet Protocol fields (shared between ipv4 and ipv6)
use nom::bits;
use nom::error::Error;
use nom::number;
use nom::sequence;
use nom::IResult;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum IPProtocol {
HOPOPT,
ICMP,
IGMP,
GGP,
IPINIP,
ST,
TCP,
CBT,
EGP,
IGP,
BBNRCCMON,
NVPII,
PUP,
ARGUS,
EMCON,
XNET,
CHAOS,
UDP,
IPV6,
ICMP6,
Other(u8),
}
impl From for IPProtocol {
fn from(raw: u8) -> Self {
match raw {
0 => IPProtocol::HOPOPT,
1 => IPProtocol::ICMP,
2 => IPProtocol::IGMP,
3 => IPProtocol::GGP,
4 => IPProtocol::IPINIP,
5 => IPProtocol::ST,
6 => IPProtocol::TCP,
7 => IPProtocol::CBT,
8 => IPProtocol::EGP,
9 => IPProtocol::IGP,
10 => IPProtocol::BBNRCCMON,
11 => IPProtocol::NVPII,
12 => IPProtocol::PUP,
13 => IPProtocol::ARGUS,
14 => IPProtocol::EMCON,
15 => IPProtocol::XNET,
16 => IPProtocol::CHAOS,
17 => IPProtocol::UDP,
41 => IPProtocol::IPV6,
58 => IPProtocol::ICMP6,
other => IPProtocol::Other(other),
}
}
}
pub(crate) fn two_nibbles(input: &[u8]) -> IResult<&[u8], (u8, u8)> {
bits::bits::<_, _, Error<_>, _, _>(sequence::pair(
bits::streaming::take(4u8),
bits::streaming::take(4u8),
))(input)
}
pub(crate) fn protocol(input: &[u8]) -> IResult<&[u8], IPProtocol> {
let (input, protocol) = number::streaming::be_u8(input)?;
Ok((input, protocol.into()))
}
pktparse-0.7.1/src/ipv4.rs 0000644 0000000 0000000 00000007326 00726746425 0013541 0 ustar 0000000 0000000 //! Handles parsing of IPv4 headers
use crate::ip::{self, IPProtocol};
use nom::bits;
use nom::bytes;
use nom::error::Error;
use nom::number;
use nom::sequence;
use nom::IResult;
use std::convert::TryFrom;
use std::net::Ipv4Addr;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct IPv4Header {
pub version: u8,
pub ihl: u8,
pub tos: u8,
pub length: u16,
pub id: u16,
pub flags: u8,
pub fragment_offset: u16,
pub ttl: u8,
pub protocol: IPProtocol,
pub chksum: u16,
pub source_addr: Ipv4Addr,
pub dest_addr: Ipv4Addr,
}
fn flag_frag_offset(input: &[u8]) -> IResult<&[u8], (u8, u16)> {
bits::bits::<_, _, Error<_>, _, _>(sequence::pair(
bits::streaming::take(3u8),
bits::streaming::take(13u16),
))(input)
}
pub(crate) fn address(input: &[u8]) -> IResult<&[u8], Ipv4Addr> {
let (input, ipv4) = bytes::streaming::take(4u8)(input)?;
Ok((input, Ipv4Addr::from(<[u8; 4]>::try_from(ipv4).unwrap())))
}
pub fn parse_ipv4_header(input: &[u8]) -> IResult<&[u8], IPv4Header> {
let (input, verihl) = ip::two_nibbles(input)?;
let (input, tos) = number::streaming::be_u8(input)?;
let (input, length) = number::streaming::be_u16(input)?;
let (input, id) = number::streaming::be_u16(input)?;
let (input, flag_frag_offset) = flag_frag_offset(input)?;
let (input, ttl) = number::streaming::be_u8(input)?;
let (input, protocol) = ip::protocol(input)?;
let (input, chksum) = number::streaming::be_u16(input)?;
let (input, source_addr) = address(input)?;
let (input, dest_addr) = address(input)?;
Ok((
input,
IPv4Header {
version: verihl.0,
ihl: verihl.1,
tos,
length,
id,
flags: flag_frag_offset.0,
fragment_offset: flag_frag_offset.1,
ttl,
protocol,
chksum,
source_addr,
dest_addr,
},
))
}
#[cfg(test)]
mod tests {
use super::{ip::protocol, parse_ipv4_header, IPProtocol, IPv4Header};
use std::net::Ipv4Addr;
const EMPTY_SLICE: &'static [u8] = &[];
macro_rules! mk_protocol_test {
($func_name:ident, $bytes:expr, $correct_proto:expr) => {
#[test]
fn $func_name() {
let bytes = $bytes;
assert_eq!(protocol(&bytes), Ok((EMPTY_SLICE, $correct_proto)));
}
};
}
mk_protocol_test!(protocol_gets_icmp_correct, [1], IPProtocol::ICMP);
mk_protocol_test!(protocol_gets_tcp_correct, [6], IPProtocol::TCP);
mk_protocol_test!(protocol_gets_udp_correct, [17], IPProtocol::UDP);
#[test]
fn ipparse_gets_packet_correct() {
let bytes = [
0x45, /* IP version and length = 20 */
0x00, /* Differentiated services field */
0x05, 0xdc, /* Total length */
0x1a, 0xe6, /* Identification */
0x20, 0x00, /* flags and fragment offset */
0x40, /* TTL */
0x01, /* protocol */
0x22, 0xed, /* checksum */
0x0a, 0x0a, 0x01, 0x87, /* source IP */
0x0a, 0x0a, 0x01, 0xb4, /* destination IP */
];
let expectation = IPv4Header {
version: 4,
ihl: 5,
tos: 0,
length: 1500,
id: 0x1ae6,
flags: 0x01,
fragment_offset: 0,
ttl: 64,
protocol: IPProtocol::ICMP,
chksum: 0x22ed,
source_addr: Ipv4Addr::new(10, 10, 1, 135),
dest_addr: Ipv4Addr::new(10, 10, 1, 180),
};
assert_eq!(parse_ipv4_header(&bytes), Ok((EMPTY_SLICE, expectation)));
}
}
pktparse-0.7.1/src/ipv6.rs 0000644 0000000 0000000 00000007721 00726746425 0013542 0 ustar 0000000 0000000 //! Handles parsing of IPv6 headers
use crate::ip::{self, IPProtocol};
use nom::bits;
use nom::bytes;
use nom::error::Error;
use nom::number;
use nom::IResult;
use std::convert::TryFrom;
use std::net::Ipv6Addr;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct IPv6Header {
pub version: u8,
pub ds: u8,
pub ecn: u8,
pub flow_label: u32,
pub length: u16,
pub next_header: IPProtocol,
pub hop_limit: u8,
pub source_addr: Ipv6Addr,
pub dest_addr: Ipv6Addr,
}
pub(crate) fn address(input: &[u8]) -> IResult<&[u8], Ipv6Addr> {
let (input, ipv6) = bytes::streaming::take(16u8)(input)?;
Ok((input, Ipv6Addr::from(<[u8; 16]>::try_from(ipv6).unwrap())))
}
/*
let (input, ds): (_, u8) =
bits::bits::<_, _, (_, ErrorKind), _, _>(bits::streaming::take(6u8))(input)?;
let (input, ecn): (_, u8) =
bits::bits::<_, _, (_, ErrorKind), _, _>(bits::streaming::take(2u8))(input)?;
let (input, flow_label): (_, u32) =
bits::bits::<_, _, (_, ErrorKind), _, _>(bits::streaming::take(20u8))(input)?;
*/
pub fn parse_ipv6_header(input: &[u8]) -> IResult<&[u8], IPv6Header> {
let (input, ver_tc) = ip::two_nibbles(input)?;
let (input, tc_fl) = ip::two_nibbles(input)?;
let (input, fl): (_, u32) =
bits::bits::<_, _, Error<_>, _, _>(bits::streaming::take(16u8))(input)?;
let (input, length) = number::streaming::be_u16(input)?;
let (input, next_header) = ip::protocol(input)?;
let (input, hop_limit) = number::streaming::be_u8(input)?;
let (input, source_addr) = address(input)?;
let (input, dest_addr) = address(input)?;
Ok((
input,
IPv6Header {
version: ver_tc.0,
ds: (ver_tc.1 << 2) + ((tc_fl.0 & 0b1100) >> 2),
ecn: tc_fl.0 & 0b11,
flow_label: (u32::from(tc_fl.1) << 16) + fl,
length,
next_header,
hop_limit,
source_addr,
dest_addr,
},
))
}
#[cfg(test)]
mod tests {
use super::{ip::protocol, parse_ipv6_header, IPProtocol, IPv6Header};
use std::net::Ipv6Addr;
const EMPTY_SLICE: &'static [u8] = &[];
macro_rules! mk_protocol_test {
($func_name:ident, $bytes:expr, $correct_proto:expr) => {
#[test]
fn $func_name() {
let bytes = $bytes;
assert_eq!(protocol(&bytes), Ok((EMPTY_SLICE, $correct_proto)));
}
};
}
mk_protocol_test!(protocol_gets_icmp_correct, [1], IPProtocol::ICMP);
mk_protocol_test!(protocol_gets_tcp_correct, [6], IPProtocol::TCP);
mk_protocol_test!(protocol_gets_udp_correct, [17], IPProtocol::UDP);
#[test]
fn ipparse_gets_packet_correct() {
let bytes = [
0x60, /* IP version and differentiated services */
0x20, /* Differentiated services,
explicit congestion notification and
partial flow label */
0x01, 0xff, /* Flow label */
0x05, 0x78, /* Payload length */
0x3a, /* Next header */
0x05, /* Hop limit */
0x20, 0x01, 0x0d, 0xb8, 0x5c, 0xf8, 0x1a, 0xa8, 0x24, 0x81, 0x61, 0xe6, 0x5a, 0xc6,
0x03, 0xe0, /* source IP */
0x20, 0x01, 0x0d, 0xb8, 0x78, 0x90, 0x2a, 0xe9, 0x90, 0x8f, 0xa9, 0xf4, 0x2f, 0x4a,
0x9b, 0x80, /* destination IP */
];
let expectation = IPv6Header {
version: 6,
ds: 0,
ecn: 2,
flow_label: 511,
length: 1400,
next_header: IPProtocol::ICMP6,
hop_limit: 5,
source_addr: Ipv6Addr::new(
0x2001, 0xdb8, 0x5cf8, 0x1aa8, 0x2481, 0x61e6, 0x5ac6, 0x3e0,
),
dest_addr: Ipv6Addr::new(
0x2001, 0xdb8, 0x7890, 0x2ae9, 0x908f, 0xa9f4, 0x2f4a, 0x9b80,
),
};
assert_eq!(parse_ipv6_header(&bytes), Ok((EMPTY_SLICE, expectation)));
}
}
pktparse-0.7.1/src/lib.rs 0000644 0000000 0000000 00000000157 00726746425 0013420 0 ustar 0000000 0000000 pub mod arp;
pub mod ethernet;
pub mod icmp;
pub mod ip;
pub mod ipv4;
pub mod ipv6;
pub mod tcp;
pub mod udp;
pktparse-0.7.1/src/tcp.rs 0000644 0000000 0000000 00000017674 00726746425 0013454 0 ustar 0000000 0000000 //! Handles parsing of TCP headers
use nom::bits;
use nom::error::{Error, ErrorKind};
use nom::number;
use nom::sequence;
use nom::{Err, IResult, Needed};
// TCP Header Format
//
//
// 0 1 2 3
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Source Port | Destination Port |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Sequence Number |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Acknowledgment Number |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Data | |U|A|P|R|S|F| |
// | Offset| Reserved |R|C|S|S|Y|I| Window |
// | | |G|K|H|T|N|N| |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Checksum | Urgent Pointer |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Options | Padding |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | data |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// TCP Flags:
// URG: Urgent Pointer field significant
// ACK: Acknowledgment field significant
// PSH: Push Function
// RST: Reset the connection
// SYN: Synchronize sequence numbers
// FIN: No more data from sender
const END_OF_OPTIONS: u8 = 0;
const NO_OP: u8 = 1;
const MSS: u8 = 2;
const WINDOW_SCALE: u8 = 3;
const SACK_PERMITTED: u8 = 4;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum TcpOption {
EndOfOptions,
NoOperation,
MaximumSegmentSize(MaximumSegmentSize),
WindowScale(WindowScale),
SackPermitted,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct MaximumSegmentSize {
pub mss: u16,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct WindowScale {
pub scaling: u8,
}
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct TcpHeader {
pub source_port: u16,
pub dest_port: u16,
pub sequence_no: u32,
pub ack_no: u32,
pub data_offset: u8,
pub reserved: u8,
pub flag_urg: bool,
pub flag_ack: bool,
pub flag_psh: bool,
pub flag_rst: bool,
pub flag_syn: bool,
pub flag_fin: bool,
pub window: u16,
pub checksum: u16,
pub urgent_pointer: u16,
pub options: Option>,
}
fn dataof_res_flags(input: &[u8]) -> IResult<&[u8], (u8, u8, u8)> {
bits::bits::<_, _, Error<_>, _, _>(sequence::tuple((
bits::streaming::take(4u8),
bits::streaming::take(6u8),
bits::streaming::take(6u8),
)))(input)
}
fn tcp_parse(input: &[u8]) -> IResult<&[u8], TcpHeader> {
let (input, source_port) = number::streaming::be_u16(input)?;
let (input, dest_port) = number::streaming::be_u16(input)?;
let (input, sequence_no) = number::streaming::be_u32(input)?;
let (input, ack_no) = number::streaming::be_u32(input)?;
let (input, dataof_res_flags) = dataof_res_flags(input)?;
let (input, window) = number::streaming::be_u16(input)?;
let (input, checksum) = number::streaming::be_u16(input)?;
let (input, urgent_pointer) = number::streaming::be_u16(input)?;
Ok((
input,
TcpHeader {
source_port,
dest_port,
sequence_no,
ack_no,
data_offset: dataof_res_flags.0,
reserved: dataof_res_flags.1,
flag_urg: dataof_res_flags.2 & 0b10_0000 == 0b10_0000,
flag_ack: dataof_res_flags.2 & 0b01_0000 == 0b01_0000,
flag_psh: dataof_res_flags.2 & 0b00_1000 == 0b00_1000,
flag_rst: dataof_res_flags.2 & 0b00_0100 == 0b00_0100,
flag_syn: dataof_res_flags.2 & 0b00_0010 == 0b00_0010,
flag_fin: dataof_res_flags.2 & 0b00_0001 == 0b00_0001,
window,
checksum,
urgent_pointer,
options: None,
},
))
}
fn tcp_parse_option(input: &[u8]) -> IResult<&[u8], TcpOption> {
match number::streaming::be_u8(input)? {
(input, END_OF_OPTIONS) => Ok((input, TcpOption::EndOfOptions)),
(input, NO_OP) => Ok((input, TcpOption::NoOperation)),
(input, MSS) => {
let (input, _len) = number::streaming::be_u8(input)?;
let (input, mss) = number::streaming::be_u16(input)?;
Ok((
input,
TcpOption::MaximumSegmentSize(MaximumSegmentSize { mss }),
))
}
(input, WINDOW_SCALE) => {
let (input, _len) = number::streaming::be_u8(input)?;
let (input, scaling) = number::streaming::be_u8(input)?;
Ok((input, TcpOption::WindowScale(WindowScale { scaling })))
}
(input, SACK_PERMITTED) => {
let (input, _len) = number::streaming::be_u8(input)?;
Ok((input, TcpOption::SackPermitted))
}
_ => Err(Err::Failure(Error::new(input, ErrorKind::Switch))),
}
}
fn tcp_parse_options(i: &[u8]) -> IResult<&[u8], Vec> {
let mut left = i;
let mut options: Vec = vec![];
loop {
match tcp_parse_option(left) {
Ok((l, opt)) => {
left = l;
options.push(opt);
if let TcpOption::EndOfOptions = opt {
break;
}
}
Err(e) => return Err(e),
}
}
Ok((left, options))
}
pub fn parse_tcp_header(i: &[u8]) -> IResult<&[u8], TcpHeader> {
match tcp_parse(i) {
Ok((left, mut tcp_header)) => {
// Offset in words (at least 5)
if tcp_header.data_offset > 5 {
let options_length = ((tcp_header.data_offset - 5) * 4) as usize;
if options_length <= left.len() {
if let Ok((_, options)) = tcp_parse_options(&left[0..options_length]) {
tcp_header.options = Some(options);
return Ok((&left[options_length..], tcp_header));
}
Ok((&left[options_length..], tcp_header))
} else {
Err(Err::Incomplete(Needed::new(options_length - left.len())))
}
} else {
Ok((left, tcp_header))
}
}
e => e,
}
}
#[cfg(test)]
mod tests {
use super::*;
const EMPTY_SLICE: &'static [u8] = &[];
#[test]
fn test_tcp_parse() {
let bytes = [
0xc2, 0x1f, /* Source port */
0x00, 0x50, /* Dest port */
0x0f, 0xd8, 0x7f, 0x4c, /* Seq no */
0xeb, 0x2f, 0x05, 0xc8, /* Ack no */
0x50, 0x18, 0x01, 0x00, /* Window */
0x7c, 0x29, /* Checksum */
0x00, 0x00, /* Urgent pointer */
];
let expectation = TcpHeader {
source_port: 49695,
dest_port: 80,
sequence_no: 0x0fd87f4c,
ack_no: 0xeb2f05c8,
data_offset: 5,
reserved: 0,
flag_urg: false,
flag_ack: true,
flag_psh: true,
flag_rst: false,
flag_syn: false,
flag_fin: false,
window: 256,
checksum: 0x7c29,
urgent_pointer: 0,
options: None,
};
assert_eq!(parse_tcp_header(&bytes), Ok((EMPTY_SLICE, expectation)));
}
}
pktparse-0.7.1/src/udp.rs 0000644 0000000 0000000 00000002515 00726746425 0013442 0 ustar 0000000 0000000 //! Handles parsing of UDP header
use nom::number;
use nom::IResult;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct UdpHeader {
pub source_port: u16,
pub dest_port: u16,
pub length: u16,
pub checksum: u16,
}
pub fn parse_udp_header(input: &[u8]) -> IResult<&[u8], UdpHeader> {
let (input, source_port) = number::streaming::be_u16(input)?;
let (input, dest_port) = number::streaming::be_u16(input)?;
let (input, length) = number::streaming::be_u16(input)?;
let (input, checksum) = number::streaming::be_u16(input)?;
Ok((
input,
UdpHeader {
source_port,
dest_port,
length,
checksum,
},
))
}
#[cfg(test)]
mod tests {
use super::{parse_udp_header, UdpHeader};
const EMPTY_SLICE: &'static [u8] = &[];
#[test]
fn udp_header_works() {
let bytes = [
0x00, 0x12, 0x11, 0x11, // source & destination ports
0x00, 0x1b, 0x21, 0x0f, // length & checksum
];
let expectation = UdpHeader {
source_port: 0x12,
dest_port: 0x1111,
length: 0x1b,
checksum: 0x210f,
};
assert_eq!(parse_udp_header(&bytes), Ok((EMPTY_SLICE, expectation)));
}
}
pktparse-0.7.1/tests/icmp_packet.rs 0000644 0000000 0000000 00000004141 00726746425 0015501 0 ustar 0000000 0000000 extern crate nom;
extern crate pktparse;
mod tests {
use pktparse::ethernet::{EtherType, EthernetFrame, MacAddress};
use pktparse::ip::IPProtocol;
use pktparse::ipv4::IPv4Header;
use pktparse::{ethernet, ipv4};
use std::net::Ipv4Addr;
#[test]
fn ipfrag_packet() {
let bytes = [
0x00, 0x23, 0x54, 0x07, 0x93, 0x6c, // Ethernet destination MAC
0x00, 0x1b, 0x21, 0x0f, 0x91, 0x9b, // Ethernet source MAC
0x08, 0x00, // Ethernet ethertype
0x45, // IP version and IHL
0x00, // IP Differentiated Services Field
0x05, 0xdc, // IP total length
0x1a, 0xe6, // IP id
0x20, 0x00, // IP flags and fragment offset
0x40, // IP TTL
0x01, // IP protocol
0x22, 0xed, // IP header checksum
0x0a, 0x0a, 0x01, 0x87, // IP source address
0x0a, 0x0a, 0x01, 0xb4, // IP dest address
];
let eth_expectation = EthernetFrame {
source_mac: MacAddress([0x00, 0x1b, 0x21, 0x0f, 0x91, 0x9b]),
dest_mac: MacAddress([0x00, 0x23, 0x54, 0x07, 0x93, 0x6c]),
ethertype: EtherType::IPv4,
};
let ip_expectation = IPv4Header {
version: 4,
ihl: 5,
tos: 0,
length: 1500,
id: 0x1ae6,
flags: 0x01,
fragment_offset: 0,
ttl: 64,
protocol: IPProtocol::ICMP,
chksum: 0x22ed,
source_addr: Ipv4Addr::new(10, 10, 1, 135),
dest_addr: Ipv4Addr::new(10, 10, 1, 180),
};
let parsed_eth_frame = ethernet::parse_ethernet_frame(&bytes);
if let Ok((remaining_data, eth_frame)) = parsed_eth_frame {
assert_eq!(eth_frame, eth_expectation);
let parsed_ip_hdr = ipv4::parse_ipv4_header(&remaining_data);
if let Ok((_remaining_data, ip_hdr)) = parsed_ip_hdr {
assert_eq!(ip_hdr, ip_expectation);
} else {
assert!(false);
}
} else {
assert!(false);
}
}
}
pktparse-0.7.1/tests/tcp_packet.rs 0000644 0000000 0000000 00000005137 00726746425 0015345 0 ustar 0000000 0000000 extern crate nom;
extern crate pktparse;
mod tests {
use pktparse::tcp::TcpOption;
use pktparse::{ipv4, tcp};
#[test]
fn parse_tcp_packet() {
let bytes = [
0x45, 0x00, 0x00, 0x38, 0x76, 0xf4, 0x40, 0x00, 0x40, 0x06, 0x80, 0xd9, 0xc0, 0xa8,
0x00, 0x6c, 0xd0, 0x61, 0xb1, 0x7c, 0xb0, 0xc2, 0x00, 0x50, 0xb0, 0xee, 0x32, 0xa6,
0x04, 0x39, 0xae, 0xe6, 0x50, 0x18, 0x00, 0xe5, 0x76, 0x92, 0x00, 0x00, 0x47, 0x45,
0x54, 0x20, 0x2f, 0x69, 0x6e, 0x64, 0x65, 0x78, 0x2e, 0x68, 0x74, 0x6d, 0x6c, 0x0a,
];
if let Ok((remaining, _)) = ipv4::parse_ipv4_header(&bytes) {
if let Ok((remaining, tcp_hdr)) = tcp::parse_tcp_header(remaining) {
assert_eq!(tcp_hdr.source_port, 45250);
assert_eq!(tcp_hdr.dest_port, 80);
assert_eq!(&remaining[..], b"GET /index.html\x0a");
} else {
assert!(false);
}
} else {
assert!(false);
}
}
#[test]
fn parse_tcp_packet_with_options() {
let bytes = [
0x45, 0x20, 0x00, 0x34, 0x78, 0xd6, 0x40, 0x00, 0x35, 0x06, 0x7e, 0x77, 0x45, 0xa4,
0x10, 0x00, 0xc0, 0xa8, 0x38, 0x0a, 0x00, 0x50, 0xc2, 0x27, 0x48, 0xf3, 0x02, 0xc2,
0x61, 0xd3, 0x16, 0xa8, 0x80, 0x12, 0xff, 0xff, 0x9b, 0x80, 0x00, 0x00, 0x02, 0x04,
0x05, 0x3a, 0x01, 0x03, 0x03, 0x04, 0x04, 0x02, 0x00, 0x00,
];
if let Ok((remaining, _)) = ipv4::parse_ipv4_header(&bytes) {
if let Ok((remaining, tcp_hdr)) = tcp::parse_tcp_header(remaining) {
assert_eq!(tcp_hdr.source_port, 80);
assert_eq!(tcp_hdr.dest_port, 49703);
assert_eq!(remaining.len(), 0);
let options = tcp_hdr.options.unwrap();
assert_eq!(options.len(), 5);
let o = options[0];
let expectation = tcp::MaximumSegmentSize { mss: 1338 };
assert_eq!(o, TcpOption::MaximumSegmentSize(expectation));
let o = options[1];
assert_eq!(o, TcpOption::NoOperation);
let o = options[2];
let expectation = tcp::WindowScale { scaling: 4 };
assert_eq!(o, TcpOption::WindowScale(expectation));
let o = options[3];
assert_eq!(o, TcpOption::SackPermitted);
let o = options[4];
assert_eq!(o, TcpOption::EndOfOptions);
} else {
assert!(false);
}
} else {
assert!(false);
}
}
}