[][src]Crate etherparse

A zero allocation library for parsing & writing a bunch of packet based protocols (EthernetII, IPv4, IPv6, UDP, TCP ...).

Currently supported are:

  • Ethernet II
  • IEEE 802.1Q VLAN Tagging Header
  • IPv4
  • IPv6 (missing extension headers, but supporting skipping them)
  • UDP
  • TCP

Usage

First, add the following to your Cargo.toml:

[dependencies]
etherparse = "0.8.2"

Next, add this to your crate root:

extern crate etherparse;

What is etherparse?

Etherparse is intended to provide the basic network parsing functions that allow for easy analysis, transformation or generation of recorded network data.

Some key points are:

  • It is completly written in Rust and thoroughly tested.
  • Special attention has been paid to not use allocations or syscalls.
  • The package is still in development and can & will still change.
  • The current focus of development is on the most popular protocols in the internet & transport layer.

How to parse network packages?

Etherparse gives you two options for parsing network packages automatically:

Slicing the packet

Here the different components in a packet are seperated without parsing all their fields. For each header a slice is generated that allows access to the fields of a header.

match SlicedPacket::from_ethernet(&packet) {
    Err(value) => println!("Err {:?}", value),
    Ok(value) => {
        println!("link: {:?}", value.link);
        println!("vlan: {:?}", value.vlan);
        println!("ip: {:?}", value.ip);
        println!("transport: {:?}", value.transport);
    }
}

This is the faster option if your code is not interested in all fields of all the headers. It is a good choice if you just want filter or find packages based on a subset of the headers and/or their fields.

Depending from which point downward you want to slice a package check out the functions:

Deserializing all headers into structs

This option deserializes all known headers and transferes their contents to header structs.

match PacketHeaders::from_ethernet_slice(&packet) {
    Err(value) => println!("Err {:?}", value),
    Ok(value) => {
        println!("link: {:?}", value.link);
        println!("vlan: {:?}", value.vlan);
        println!("ip: {:?}", value.ip);
        println!("transport: {:?}", value.transport);
    }
}

This option is slower then slicing when only few fields are accessed. But it can be the faster option or useful if you are interested in most fields anyways or if you want to re-serialize the headers with modified values.

Depending from which point downward you want to unpack a package check out the functions

Manually slicing & parsing packets

It is also possible to manually slice & parse a packet. For each header type there is are metods that create a slice or struct from a memory slice.

Have a look at the documentation for the Slice.from_slice methods, if you want to create your own slices:

And for deserialization into the corresponding header structs have a look at:

How to generate fake packet data?

Packet Builder

The PacketBuilder struct provides a high level interface for quickly creating network packets. The PacketBuilder will automatically set fields which can be deduced from the content and compositions of the packet itself (e.g. checksums, lengths, ethertype, ip protocol number).

Example:

use etherparse::PacketBuilder;

let builder = PacketBuilder::
    ethernet2([1,2,3,4,5,6],     //source mac
               [7,8,9,10,11,12]) //destination mac
    .ipv4([192,168,1,1], //source ip
          [192,168,1,2], //desitination ip
          20)            //time to life
    .udp(21,    //source port 
         1234); //desitnation port
 
//payload of the udp packet
let payload = [1,2,3,4,5,6,7,8];

//get some memory to store the result
let mut result = Vec::<u8>::with_capacity(builder.size(payload.len()));
 
//serialize
//this will automatically set all length fields, checksums and identifiers (ethertype & protocol)
//before writing the packet out to "result"
builder.write(&mut result, &payload).unwrap();

There is also an example for TCP packets available.

Check out the PacketBuilder documentation for more informations.

Manually serialising each header

Alternativly it is possible to manually build a packet (example). Generally each struct representing a header has a "write" method that allows it to be serialized. These write methods sometimes automatically calculate checksums and fill them in. In case this is unwanted behavior (e.g. if you want to generate a packet with an invalid checksum), it is also possible to call a "write_raw" method that will simply serialize the data without doing checksum calculations.

Read the documentations of the different methods for a more details:

Roadmap

  • Documentation
    • Packet Builder
  • MutPacketSlice -> modifaction of fields in slices directly?
  • Reserializing SlicedPacket & MutSlicedPacket with corrected checksums & id's
  • Slicing & reading packet from different layers then ethernet onward (e.g. ip, vlan...)
  • IEEE 802.3

References

Modules

packet_filter

Structs

DoubleVlanHeader

IEEE 802.1Q double VLAN Tagging Header

DoubleVlanHeaderSlice

A slice containing an double vlan header of a network package.

Ethernet2Header

Ethernet II header.

Ethernet2HeaderSlice

A slice containing an ethernet 2 header of a network package.

Ipv4Header

IPv4 header without options.

Ipv4HeaderSlice

A slice containing an ipv4 header of a network package.

Ipv6Header

IPv6 header according to rfc8200.

Ipv6HeaderSlice

A slice containing an ipv6 header of a network package.

Ipv6ExtensionHeader

Dummy struct for ipv6 header extensions.

Ipv6ExtensionHeaderSlice

A slice containing an ipv6 extension header of a network package.

PacketBuilder

Helper for building packets.

PacketBuilderStep

An unfinished packet that is build with the packet builder

PacketHeaders

Decoded packet headers (data link layer and higher). You can use PacketHeaders::from_ethernet_slice or PacketHeader::from_ip_slice to decode and get this struct as a result.

SingleVlanHeader

IEEE 802.1Q VLAN Tagging Header

SingleVlanHeaderSlice

A slice containing a single vlan header of a network package.

SlicedPacket

A sliced into its component headers. Everything that could not be parsed is stored in a slice in the field "payload".

TcpHeader

TCP header according to rfc 793.

TcpHeaderSlice

A slice containing an tcp header of a network package.

TcpOptionsIterator

Allows iterating over the options after a TCP header.

UdpHeader

Udp header according to rfc768.

UdpHeaderSlice

A slice containing an udp header of a network package. Struct allows the selective read of fields in the header.

Enums

ErrorField

Fields that can produce errors when serialized.

EtherType

Ether type enum present in ethernet II header.

InternetSlice
IpHeader

Internet protocol headers version 4 & 6

IpTrafficClass

Identifiers for the traffic_class field in ipv6 headers and protocol field in ipv4 headers.

LinkSlice

A slice containing the link layer header (currently only Ethernet II is supported).

ReadError

Errors that can occur when reading.

TcpOptionElement

Different kinds of options that can be present in the options part of a tcp header.

TcpOptionReadError

Errors that can occour while reading the options of a TCP header.

TcpOptionWriteError

Errors that can occour when setting the options of a tcp header.

TransportHeader

The possible headers on the transport layer

TransportSlice
ValueError

Errors in the given data

VlanHeader

IEEE 802.1Q VLAN Tagging Header (can be single or double tagged).

VlanSlice

A slice containing a single or double vlan header.

WriteError

Errors that can occur when writing.

Constants

IPV6_MAX_NUM_HEADER_EXTENSIONS

Maximum number of header extensions allowed (according to the ipv6 rfc8200, & iana protocol numbers).

TCP_MAXIMUM_DATA_OFFSET

The maximum allowed value for the data offset (it is a 4 bit value).

TCP_MINIMUM_DATA_OFFSET

The minimum data offset size (size of the tcp header itself).

TCP_MINIMUM_HEADER_SIZE

The minimum size of the tcp header in bytes

TCP_OPTION_ID_END
TCP_OPTION_ID_MAXIMUM_SEGMENT_SIZE
TCP_OPTION_ID_NOP
TCP_OPTION_ID_SELECTIVE_ACK
TCP_OPTION_ID_SELECTIVE_ACK_PERMITTED
TCP_OPTION_ID_TIMESTAMP
TCP_OPTION_ID_WINDOW_SCALE

Traits

SerializedSize

Contains the size when serialized.