use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use pnet::datalink::MacAddr;
use pnet::packet::arp::{ArpHardwareTypes, ArpOperation, MutableArpPacket};
use pnet::packet::ethernet::{EtherType, EtherTypes, MutableEthernetPacket};
use pnet::packet::icmp::IcmpPacket;
use pnet::packet::icmpv6::Icmpv6Packet;
use pnet::packet::ip::{IpNextHeaderProtocol, IpNextHeaderProtocols};
use pnet::packet::ipv4::{MutableIpv4Packet, checksum as ipv4_checksum};
use pnet::packet::ipv6::MutableIpv6Packet;
use pnet::packet::tcp::{MutableTcpPacket, TcpPacket};
use pnet::packet::udp::{MutableUdpPacket, UdpPacket};
use crate::protocols::error::{PacketError, Result};
use crate::protocols::sizes::{
ARP_LEN, ETH_HDR_LEN, ICMP_HDR_LEN, IP_V4_HDR_LEN, IP_V6_HDR_LEN, SCTP_COMMON_HDR_LEN,
TCP_HDR_LEN, UDP_HDR_LEN,
};
pub use crate::protocols::tcp::flags as tcp_flags;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Field<T> {
#[default]
Computed,
Exact(T),
}
impl<T> Field<T> {
fn resolve(self, computed: impl FnOnce() -> T) -> T {
match self {
Self::Computed => computed(),
Self::Exact(value) => value,
}
}
pub const fn is_exact(&self) -> bool {
matches!(self, Self::Exact(_))
}
pub fn exact(self) -> Option<T> {
match self {
Self::Computed => None,
Self::Exact(value) => Some(value),
}
}
}
impl<T> From<T> for Field<T> {
fn from(value: T) -> Self {
Self::Exact(value)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Ethernet {
pub source: MacAddr,
pub destination: MacAddr,
pub ethertype: Field<EtherType>,
}
impl Ethernet {
pub fn new(source: MacAddr, destination: MacAddr) -> Self {
Self {
source,
destination,
ethertype: Field::Computed,
}
}
#[must_use]
pub fn with_ethertype(mut self, ethertype: EtherType) -> Self {
self.ethertype = Field::Exact(ethertype);
self
}
pub fn header_bytes(&self) -> Vec<u8> {
write_ethernet(self, Vec::new(), None).expect("nothing here can overflow")
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Ipv4 {
pub source: Ipv4Addr,
pub destination: Ipv4Addr,
pub dscp: u8,
pub ecn: u8,
pub identification: Field<u16>,
pub flags: u8,
pub fragment_offset: u16,
pub ttl: u8,
pub protocol: Field<IpNextHeaderProtocol>,
pub total_length: Field<u16>,
pub checksum: Field<u16>,
pub options: Vec<u8>,
}
pub mod ipv4_flags {
pub const DONT_FRAGMENT: u8 = 0b010;
pub const MORE_FRAGMENTS: u8 = 0b001;
}
impl Ipv4 {
pub fn new(source: Ipv4Addr, destination: Ipv4Addr) -> Self {
Self {
source,
destination,
dscp: 0,
ecn: 0,
identification: Field::Computed,
flags: ipv4_flags::DONT_FRAGMENT,
fragment_offset: 0,
ttl: super::ip::HOP_LIMIT_ROUTED,
protocol: Field::Computed,
total_length: Field::Computed,
checksum: Field::Computed,
options: Vec::new(),
}
}
#[must_use]
pub fn with_ttl(mut self, ttl: u8) -> Self {
self.ttl = ttl;
self
}
#[must_use]
pub fn with_checksum(mut self, checksum: u16) -> Self {
self.checksum = Field::Exact(checksum);
self
}
#[must_use]
pub fn with_total_length(mut self, total_length: u16) -> Self {
self.total_length = Field::Exact(total_length);
self
}
fn header_len(&self) -> usize {
IP_V4_HDR_LEN + self.options.len()
}
pub fn header_bytes(&self, payload_length: u16) -> Result<Vec<u8>> {
let mut bytes = write_ipv4(self, Vec::new(), None)?;
let total_length = match self.total_length {
Field::Exact(value) => value,
Field::Computed => (self.header_len() as u32 + u32::from(payload_length))
.try_into()
.map_err(|_| {
PacketError::too_long(
"the IPv4 total length",
self.header_len(),
payload_length as usize,
)
})?,
};
let mut ipv4 =
MutableIpv4Packet::new(&mut bytes).expect("a header-sized buffer holds a header");
ipv4.set_total_length(total_length);
ipv4.set_checksum(0);
let sum = self
.checksum
.resolve(|| ipv4_checksum(&ipv4.to_immutable()));
ipv4.set_checksum(sum);
Ok(bytes)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Ipv6 {
pub source: Ipv6Addr,
pub destination: Ipv6Addr,
pub traffic_class: u8,
pub flow_label: Field<u32>,
pub next_header: Field<IpNextHeaderProtocol>,
pub payload_length: Field<u16>,
pub hop_limit: u8,
}
impl Ipv6 {
pub fn new(source: Ipv6Addr, destination: Ipv6Addr) -> Self {
Self {
source,
destination,
traffic_class: 0,
flow_label: Field::Computed,
next_header: Field::Computed,
payload_length: Field::Computed,
hop_limit: super::ip::HOP_LIMIT_ROUTED,
}
}
#[must_use]
pub fn with_hop_limit(mut self, hop_limit: u8) -> Self {
self.hop_limit = hop_limit;
self
}
#[must_use]
pub fn with_payload_length(mut self, payload_length: u16) -> Self {
self.payload_length = Field::Exact(payload_length);
self
}
pub fn header_bytes(&self, payload_length: u16) -> Vec<u8> {
let declared = Ipv6 {
payload_length: Field::Exact(self.payload_length.resolve(|| payload_length)),
..self.clone()
};
write_ipv6(&declared, Vec::new(), None).expect("nothing here can overflow")
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Tcp {
pub source_port: u16,
pub destination_port: u16,
pub sequence: u32,
pub acknowledgement: u32,
pub flags: u8,
pub window: u16,
pub urgent_pointer: u16,
pub data_offset: Field<u8>,
pub checksum: Field<u16>,
pub options: Vec<u8>,
pub payload: Vec<u8>,
}
impl Tcp {
pub fn new(source_port: u16, destination_port: u16) -> Self {
Self {
source_port,
destination_port,
sequence: 0,
acknowledgement: 0,
flags: 0,
window: 1024,
urgent_pointer: 0,
data_offset: Field::Computed,
checksum: Field::Computed,
options: Vec::new(),
payload: Vec::new(),
}
}
#[must_use]
pub fn with_flags(mut self, flags: u8) -> Self {
self.flags = flags;
self
}
#[must_use]
pub fn with_sequence(mut self, sequence: u32) -> Self {
self.sequence = sequence;
self
}
#[must_use]
pub fn with_acknowledgement(mut self, acknowledgement: u32) -> Self {
self.acknowledgement = acknowledgement;
self
}
#[must_use]
pub fn with_checksum(mut self, checksum: u16) -> Self {
self.checksum = Field::Exact(checksum);
self
}
#[must_use]
pub fn with_payload(mut self, payload: impl Into<Vec<u8>>) -> Self {
self.payload = payload.into();
self
}
fn header_len(&self) -> usize {
TCP_HDR_LEN + self.options.len()
}
pub fn to_bytes(&self, addresses: Option<(IpAddr, IpAddr)>) -> Result<Vec<u8>> {
write_tcp(self, Vec::new(), addresses)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Udp {
pub source_port: u16,
pub destination_port: u16,
pub length: Field<u16>,
pub checksum: Field<u16>,
pub payload: Vec<u8>,
}
impl Udp {
pub fn new(source_port: u16, destination_port: u16) -> Self {
Self {
source_port,
destination_port,
length: Field::Computed,
checksum: Field::Computed,
payload: Vec::new(),
}
}
#[must_use]
pub fn with_payload(mut self, payload: impl Into<Vec<u8>>) -> Self {
self.payload = payload.into();
self
}
#[must_use]
pub fn with_checksum(mut self, checksum: u16) -> Self {
self.checksum = Field::Exact(checksum);
self
}
pub fn to_bytes(&self, addresses: Option<(IpAddr, IpAddr)>) -> Result<Vec<u8>> {
write_udp(self, Vec::new(), addresses)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Sctp {
pub source_port: u16,
pub destination_port: u16,
pub verification_tag: u32,
pub checksum: Field<u32>,
pub chunks: Vec<u8>,
}
impl Sctp {
pub fn new(source_port: u16, destination_port: u16) -> Self {
Self {
source_port,
destination_port,
verification_tag: 0,
checksum: Field::Computed,
chunks: Vec::new(),
}
}
#[must_use]
pub fn with_verification_tag(mut self, verification_tag: u32) -> Self {
self.verification_tag = verification_tag;
self
}
#[must_use]
pub fn with_chunks(mut self, chunks: impl Into<Vec<u8>>) -> Self {
self.chunks = chunks.into();
self
}
#[must_use]
pub fn with_checksum(mut self, checksum: u32) -> Self {
self.checksum = Field::Exact(checksum);
self
}
pub fn to_bytes(&self) -> Vec<u8> {
write_sctp(self, Vec::new())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Icmpv4 {
pub icmp_type: u8,
pub code: u8,
pub checksum: Field<u16>,
pub rest_of_header: [u8; 4],
pub payload: Vec<u8>,
}
impl Icmpv4 {
pub fn echo_request(identifier: u16, sequence: u16) -> Self {
Self::echo(ECHO_REQUEST_V4, identifier, sequence)
}
pub fn echo_reply(identifier: u16, sequence: u16) -> Self {
Self::echo(ECHO_REPLY_V4, identifier, sequence)
}
fn echo(icmp_type: u8, identifier: u16, sequence: u16) -> Self {
let [id_hi, id_lo] = identifier.to_be_bytes();
let [seq_hi, seq_lo] = sequence.to_be_bytes();
Self {
icmp_type,
code: 0,
checksum: Field::Computed,
rest_of_header: [id_hi, id_lo, seq_hi, seq_lo],
payload: Vec::new(),
}
}
#[must_use]
pub fn with_payload(mut self, payload: impl Into<Vec<u8>>) -> Self {
self.payload = payload.into();
self
}
#[must_use]
pub fn with_checksum(mut self, checksum: u16) -> Self {
self.checksum = Field::Exact(checksum);
self
}
pub fn to_bytes(&self) -> Vec<u8> {
let mut bytes = icmp_body(
self.icmp_type,
self.code,
self.rest_of_header,
&self.payload,
);
let sum = self.checksum.resolve(|| {
let message = IcmpPacket::new(&bytes).expect("just written");
pnet::packet::icmp::checksum(&message)
});
bytes[2..4].copy_from_slice(&sum.to_be_bytes());
bytes
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Icmpv6 {
pub icmp_type: u8,
pub code: u8,
pub checksum: Field<u16>,
pub rest_of_header: [u8; 4],
pub payload: Vec<u8>,
}
impl Icmpv6 {
pub fn echo_request(identifier: u16, sequence: u16) -> Self {
Self::echo(ECHO_REQUEST_V6, identifier, sequence)
}
pub fn echo_reply(identifier: u16, sequence: u16) -> Self {
Self::echo(ECHO_REPLY_V6, identifier, sequence)
}
fn echo(icmp_type: u8, identifier: u16, sequence: u16) -> Self {
let [id_hi, id_lo] = identifier.to_be_bytes();
let [seq_hi, seq_lo] = sequence.to_be_bytes();
Self {
icmp_type,
code: 0,
checksum: Field::Computed,
rest_of_header: [id_hi, id_lo, seq_hi, seq_lo],
payload: Vec::new(),
}
}
#[must_use]
pub fn with_payload(mut self, payload: impl Into<Vec<u8>>) -> Self {
self.payload = payload.into();
self
}
#[must_use]
pub fn with_checksum(mut self, checksum: u16) -> Self {
self.checksum = Field::Exact(checksum);
self
}
pub fn to_bytes(&self, addresses: Option<(IpAddr, IpAddr)>) -> Result<Vec<u8>> {
let mut bytes = icmp_body(
self.icmp_type,
self.code,
self.rest_of_header,
&self.payload,
);
let sum = match self.checksum {
Field::Exact(value) => value,
Field::Computed => {
let message = Icmpv6Packet::new(&bytes).expect("just written");
match addresses {
None => 0,
Some((IpAddr::V6(src), IpAddr::V6(dst))) => {
pnet::packet::icmpv6::checksum(&message, &src, &dst)
}
Some((src, dst)) => return Err(PacketError::FamilyMismatch { src, dst }),
}
}
};
bytes[2..4].copy_from_slice(&sum.to_be_bytes());
Ok(bytes)
}
}
fn icmp_body(icmp_type: u8, code: u8, rest_of_header: [u8; 4], payload: &[u8]) -> Vec<u8> {
let mut bytes = Vec::with_capacity(ICMP_HDR_LEN + payload.len());
bytes.push(icmp_type);
bytes.push(code);
bytes.extend_from_slice(&[0, 0]);
bytes.extend_from_slice(&rest_of_header);
bytes.extend_from_slice(payload);
bytes
}
const ECHO_REQUEST_V4: u8 = 8;
const ECHO_REPLY_V4: u8 = 0;
const ECHO_REQUEST_V6: u8 = 128;
const ECHO_REPLY_V6: u8 = 129;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Arp {
pub operation: u16,
pub hw_addr_len: u8,
pub proto_addr_len: u8,
pub sender_hw_addr: MacAddr,
pub sender_proto_addr: Ipv4Addr,
pub target_hw_addr: MacAddr,
pub target_proto_addr: Ipv4Addr,
}
pub mod arp_operations {
pub const REQUEST: u16 = 1;
pub const REPLY: u16 = 2;
}
impl Arp {
pub fn request(
sender_hw_addr: MacAddr,
sender_proto_addr: Ipv4Addr,
target_proto_addr: Ipv4Addr,
) -> Self {
Self {
operation: arp_operations::REQUEST,
hw_addr_len: 6,
proto_addr_len: 4,
sender_hw_addr,
sender_proto_addr,
target_hw_addr: MacAddr::zero(),
target_proto_addr,
}
}
pub fn reply(
sender_hw_addr: MacAddr,
sender_proto_addr: Ipv4Addr,
target_hw_addr: MacAddr,
target_proto_addr: Ipv4Addr,
) -> Self {
Self {
operation: arp_operations::REPLY,
hw_addr_len: 6,
proto_addr_len: 4,
sender_hw_addr,
sender_proto_addr,
target_hw_addr,
target_proto_addr,
}
}
pub fn to_bytes(&self) -> Vec<u8> {
let mut bytes = vec![0u8; ARP_LEN];
{
let mut arp =
MutableArpPacket::new(&mut bytes).expect("an ARP-sized buffer holds an ARP packet");
arp.set_hardware_type(ArpHardwareTypes::Ethernet);
arp.set_protocol_type(EtherTypes::Ipv4);
arp.set_hw_addr_len(self.hw_addr_len);
arp.set_proto_addr_len(self.proto_addr_len);
arp.set_operation(ArpOperation(self.operation));
arp.set_sender_hw_addr(self.sender_hw_addr);
arp.set_sender_proto_addr(self.sender_proto_addr);
arp.set_target_hw_addr(self.target_hw_addr);
arp.set_target_proto_addr(self.target_proto_addr);
}
bytes
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Layer {
Ethernet(Ethernet),
Ipv4(Ipv4),
Ipv6(Ipv6),
Tcp(Tcp),
Udp(Udp),
Sctp(Sctp),
Icmpv4(Icmpv4),
Icmpv6(Icmpv6),
Arp(Arp),
Raw(Vec<u8>),
}
macro_rules! layer_from {
($($variant:ident($ty:ty)),* $(,)?) => {
$(impl From<$ty> for Layer {
fn from(header: $ty) -> Self {
Self::$variant(header)
}
})*
};
}
layer_from!(
Ethernet(Ethernet),
Ipv4(Ipv4),
Ipv6(Ipv6),
Tcp(Tcp),
Udp(Udp),
Sctp(Sctp),
Icmpv4(Icmpv4),
Icmpv6(Icmpv6),
Arp(Arp),
Raw(Vec<u8>),
);
impl Layer {
fn ip_protocol(&self) -> Option<IpNextHeaderProtocol> {
match self {
Self::Tcp(_) => Some(IpNextHeaderProtocols::Tcp),
Self::Udp(_) => Some(IpNextHeaderProtocols::Udp),
Self::Sctp(_) => Some(IpNextHeaderProtocols::Sctp),
Self::Icmpv4(_) => Some(IpNextHeaderProtocols::Icmp),
Self::Icmpv6(_) => Some(IpNextHeaderProtocols::Icmpv6),
_ => None,
}
}
fn ethertype(&self) -> Option<EtherType> {
match self {
Self::Ipv4(_) => Some(EtherTypes::Ipv4),
Self::Ipv6(_) => Some(EtherTypes::Ipv6),
Self::Arp(_) => Some(EtherTypes::Arp),
_ => None,
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Packet {
layers: Vec<Layer>,
}
impl Packet {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn push(mut self, layer: impl Into<Layer>) -> Self {
self.layers.push(layer.into());
self
}
pub fn layers(&self) -> &[Layer] {
&self.layers
}
pub fn layers_mut(&mut self) -> &mut Vec<Layer> {
&mut self.layers
}
pub fn build(&self) -> Result<Vec<u8>> {
let addresses = self.enclosing_addresses();
let mut bytes = Vec::new();
let mut inner: Option<&Layer> = None;
for layer in self.layers.iter().rev() {
bytes = write_layer(layer, bytes, inner, addresses)?;
inner = Some(layer);
}
Ok(bytes)
}
fn enclosing_addresses(&self) -> Option<(IpAddr, IpAddr)> {
self.layers.iter().find_map(|layer| match layer {
Layer::Ipv4(h) => Some((IpAddr::V4(h.source), IpAddr::V4(h.destination))),
Layer::Ipv6(h) => Some((IpAddr::V6(h.source), IpAddr::V6(h.destination))),
_ => None,
})
}
}
fn write_layer(
layer: &Layer,
payload: Vec<u8>,
inner: Option<&Layer>,
addresses: Option<(IpAddr, IpAddr)>,
) -> Result<Vec<u8>> {
match layer {
Layer::Raw(bytes) => Ok([bytes.as_slice(), payload.as_slice()].concat()),
Layer::Ethernet(header) => write_ethernet(header, payload, inner),
Layer::Ipv4(header) => write_ipv4(header, payload, inner),
Layer::Ipv6(header) => write_ipv6(header, payload, inner),
Layer::Tcp(header) => write_tcp(header, payload, addresses),
Layer::Udp(header) => write_udp(header, payload, addresses),
Layer::Sctp(header) => Ok(write_sctp(header, payload)),
Layer::Icmpv4(message) => Ok([message.to_bytes(), payload].concat()),
Layer::Icmpv6(message) => Ok([message.to_bytes(addresses)?, payload].concat()),
Layer::Arp(packet) => Ok([packet.to_bytes(), payload].concat()),
}
}
fn write_ethernet(header: &Ethernet, payload: Vec<u8>, inner: Option<&Layer>) -> Result<Vec<u8>> {
let mut bytes = vec![0u8; ETH_HDR_LEN];
{
let mut eth =
MutableEthernetPacket::new(&mut bytes).expect("a header-sized buffer holds a header");
eth.set_source(header.source);
eth.set_destination(header.destination);
eth.set_ethertype(
header
.ethertype
.resolve(|| inner.and_then(Layer::ethertype).unwrap_or(EtherTypes::Ipv4)),
);
}
bytes.extend_from_slice(&payload);
Ok(bytes)
}
fn write_ipv4(header: &Ipv4, payload: Vec<u8>, inner: Option<&Layer>) -> Result<Vec<u8>> {
let header_len = header.header_len();
let total = header_len + payload.len();
let total_length = match header.total_length {
Field::Exact(value) => value,
Field::Computed => u16::try_from(total).map_err(|_| {
PacketError::too_long("the IPv4 total length", header_len, payload.len())
})?,
};
let mut bytes = vec![0u8; header_len];
{
let mut ipv4 =
MutableIpv4Packet::new(&mut bytes).expect("a header-sized buffer holds a header");
ipv4.set_version(4);
ipv4.set_header_length((header_len / 4) as u8);
ipv4.set_dscp(header.dscp);
ipv4.set_ecn(header.ecn);
ipv4.set_total_length(total_length);
ipv4.set_identification(header.identification.resolve(rand::random));
ipv4.set_flags(header.flags);
ipv4.set_fragment_offset(header.fragment_offset);
ipv4.set_ttl(header.ttl);
ipv4.set_next_level_protocol(header.protocol.resolve(|| {
inner
.and_then(Layer::ip_protocol)
.unwrap_or(IpNextHeaderProtocols::Tcp)
}));
ipv4.set_source(header.source);
ipv4.set_destination(header.destination);
if !header.options.is_empty() {
bytes[IP_V4_HDR_LEN..header_len].copy_from_slice(&header.options);
}
}
{
let mut ipv4 =
MutableIpv4Packet::new(&mut bytes).expect("a header-sized buffer holds a header");
let sum = header
.checksum
.resolve(|| ipv4_checksum(&ipv4.to_immutable()));
ipv4.set_checksum(sum);
}
bytes.extend_from_slice(&payload);
Ok(bytes)
}
fn write_ipv6(header: &Ipv6, payload: Vec<u8>, inner: Option<&Layer>) -> Result<Vec<u8>> {
let payload_length = match header.payload_length {
Field::Exact(value) => value,
Field::Computed => u16::try_from(payload.len())
.map_err(|_| PacketError::too_long("the IPv6 payload length", 0, payload.len()))?,
};
let mut bytes = vec![0u8; IP_V6_HDR_LEN];
{
let mut ipv6 =
MutableIpv6Packet::new(&mut bytes).expect("a header-sized buffer holds a header");
ipv6.set_version(6);
ipv6.set_traffic_class(header.traffic_class);
ipv6.set_flow_label(header.flow_label.resolve(rand::random));
ipv6.set_payload_length(payload_length);
ipv6.set_next_header(header.next_header.resolve(|| {
inner
.and_then(Layer::ip_protocol)
.unwrap_or(IpNextHeaderProtocols::Tcp)
}));
ipv6.set_hop_limit(header.hop_limit);
ipv6.set_source(header.source);
ipv6.set_destination(header.destination);
}
bytes.extend_from_slice(&payload);
Ok(bytes)
}
fn write_tcp(
header: &Tcp,
payload: Vec<u8>,
addresses: Option<(IpAddr, IpAddr)>,
) -> Result<Vec<u8>> {
let header_len = header.header_len();
let mut bytes = vec![0u8; header_len];
bytes.extend_from_slice(&header.payload);
bytes.extend_from_slice(&payload);
{
let mut tcp =
MutableTcpPacket::new(&mut bytes).expect("a header-sized buffer holds a header");
tcp.set_source(header.source_port);
tcp.set_destination(header.destination_port);
tcp.set_sequence(header.sequence);
tcp.set_acknowledgement(header.acknowledgement);
tcp.set_data_offset(header.data_offset.resolve(|| (header_len / 4) as u8));
tcp.set_flags(header.flags);
tcp.set_window(header.window);
tcp.set_urgent_ptr(header.urgent_pointer);
tcp.set_checksum(0);
if !header.options.is_empty() {
bytes[TCP_HDR_LEN..header_len].copy_from_slice(&header.options);
}
}
let sum = match header.checksum {
Field::Exact(value) => value,
Field::Computed => {
let segment = TcpPacket::new(&bytes).expect("just written");
transport_checksum(
addresses,
|src, dst| pnet::packet::tcp::ipv4_checksum(&segment, src, dst),
|src, dst| pnet::packet::tcp::ipv6_checksum(&segment, src, dst),
)?
}
};
MutableTcpPacket::new(&mut bytes)
.expect("a header-sized buffer holds a header")
.set_checksum(sum);
Ok(bytes)
}
fn write_udp(
header: &Udp,
payload: Vec<u8>,
addresses: Option<(IpAddr, IpAddr)>,
) -> Result<Vec<u8>> {
let body_len = header.payload.len() + payload.len();
let length = match header.length {
Field::Exact(value) => value,
Field::Computed => u16::try_from(UDP_HDR_LEN + body_len)
.map_err(|_| PacketError::too_long("the UDP length", UDP_HDR_LEN, body_len))?,
};
let mut bytes = vec![0u8; UDP_HDR_LEN];
bytes.extend_from_slice(&header.payload);
bytes.extend_from_slice(&payload);
{
let mut udp =
MutableUdpPacket::new(&mut bytes).expect("a header-sized buffer holds a header");
udp.set_source(header.source_port);
udp.set_destination(header.destination_port);
udp.set_length(length);
udp.set_checksum(0);
}
let sum = match header.checksum {
Field::Exact(value) => value,
Field::Computed => {
let datagram = UdpPacket::new(&bytes).expect("just written");
let computed = transport_checksum(
addresses,
|src, dst| pnet::packet::udp::ipv4_checksum(&datagram, src, dst),
|src, dst| pnet::packet::udp::ipv6_checksum(&datagram, src, dst),
)?;
if computed == 0 { 0xFFFF } else { computed }
}
};
MutableUdpPacket::new(&mut bytes)
.expect("a header-sized buffer holds a header")
.set_checksum(sum);
Ok(bytes)
}
fn transport_checksum(
addresses: Option<(IpAddr, IpAddr)>,
v4: impl FnOnce(&Ipv4Addr, &Ipv4Addr) -> u16,
v6: impl FnOnce(&Ipv6Addr, &Ipv6Addr) -> u16,
) -> Result<u16> {
match addresses {
None => Ok(0),
Some((IpAddr::V4(src), IpAddr::V4(dst))) => Ok(v4(&src, &dst)),
Some((IpAddr::V6(src), IpAddr::V6(dst))) => Ok(v6(&src, &dst)),
Some((src, dst)) => Err(PacketError::FamilyMismatch { src, dst }),
}
}
fn write_sctp(header: &Sctp, payload: Vec<u8>) -> Vec<u8> {
let mut bytes = Vec::with_capacity(SCTP_COMMON_HDR_LEN + header.chunks.len() + payload.len());
bytes.extend_from_slice(&header.source_port.to_be_bytes());
bytes.extend_from_slice(&header.destination_port.to_be_bytes());
bytes.extend_from_slice(&header.verification_tag.to_be_bytes());
bytes.extend_from_slice(&[0; 4]); bytes.extend_from_slice(&header.chunks);
bytes.extend_from_slice(&payload);
let sum = header.checksum.resolve(|| crc32c(&bytes));
bytes[8..12].copy_from_slice(&sum.to_le_bytes());
bytes
}
static CRC32C_TABLE: [u32; 256] = {
let mut table = [0u32; 256];
let mut byte = 0;
while byte < 256 {
let mut crc = byte as u32;
let mut bit = 0;
while bit < 8 {
crc = if crc & 1 != 0 {
(crc >> 1) ^ 0x82F6_3B78
} else {
crc >> 1
};
bit += 1;
}
table[byte] = crc;
byte += 1;
}
table
};
pub(crate) fn crc32c(data: &[u8]) -> u32 {
let mut crc = !0u32;
for &byte in data {
crc = (crc >> 8) ^ CRC32C_TABLE[((crc ^ u32::from(byte)) & 0xFF) as usize];
}
!crc
}
#[cfg(test)]
mod tests {
use super::*;
use pnet::packet::Packet as _;
use pnet::packet::ethernet::EthernetPacket;
use pnet::packet::ipv4::Ipv4Packet;
use pnet::packet::ipv6::Ipv6Packet;
const V4_SRC: Ipv4Addr = Ipv4Addr::new(192, 0, 2, 1);
const V4_DST: Ipv4Addr = Ipv4Addr::new(192, 0, 2, 9);
const MAC: MacAddr = MacAddr(0x02, 0, 0, 0, 0, 1);
fn v6(s: &str) -> Ipv6Addr {
s.parse().expect("a valid address")
}
#[test]
fn a_packet_nobody_overrode_is_one_a_stack_would_accept() {
let bytes = Packet::new()
.push(Ipv4::new(V4_SRC, V4_DST))
.push(Tcp::new(50_000, 80).with_flags(tcp_flags::SYN))
.build()
.expect("builds");
let ip = Ipv4Packet::new(&bytes).expect("an IPv4 header");
assert_eq!(ip.get_total_length() as usize, bytes.len());
assert_eq!(ip.get_next_level_protocol(), IpNextHeaderProtocols::Tcp);
assert_eq!(
ip.get_checksum(),
ipv4_checksum(&Ipv4Packet::new(&bytes[..20]).expect("header")),
"the header checksums itself"
);
let tcp = TcpPacket::new(ip.payload()).expect("a TCP header");
assert_eq!(tcp.get_data_offset(), 5);
assert_eq!(tcp.get_flags(), tcp_flags::SYN);
assert_ne!(tcp.get_checksum(), 0, "checksummed over the pseudo-header");
}
#[test]
fn an_enclosing_header_names_what_is_inside_it() {
let over_udp = Packet::new()
.push(Ethernet::new(MAC, MacAddr::broadcast()))
.push(Ipv4::new(V4_SRC, V4_DST))
.push(Udp::new(50_000, 53))
.build()
.expect("builds");
let eth = EthernetPacket::new(&over_udp).expect("a frame");
assert_eq!(eth.get_ethertype(), EtherTypes::Ipv4);
assert_eq!(
Ipv4Packet::new(eth.payload())
.expect("an IPv4 header")
.get_next_level_protocol(),
IpNextHeaderProtocols::Udp
);
let over_v6 = Packet::new()
.push(Ethernet::new(MAC, MacAddr::broadcast()))
.push(Ipv6::new(v6("2001:db8::1"), v6("2001:db8::2")))
.push(Tcp::new(50_000, 80))
.build()
.expect("builds");
let eth = EthernetPacket::new(&over_v6).expect("a frame");
assert_eq!(eth.get_ethertype(), EtherTypes::Ipv6);
assert_eq!(
Ipv6Packet::new(eth.payload())
.expect("an IPv6 header")
.get_next_header(),
IpNextHeaderProtocols::Tcp
);
}
#[test]
fn a_transport_checksum_covers_the_addresses_of_the_layer_around_it() {
let checksum_with = |dst: Ipv4Addr| {
let bytes = Packet::new()
.push(Ipv4::new(V4_SRC, dst))
.push(Tcp::new(50_000, 80).with_flags(tcp_flags::SYN))
.build()
.expect("builds");
let ip = Ipv4Packet::new(&bytes).expect("header");
TcpPacket::new(ip.payload())
.expect("segment")
.get_checksum()
};
assert_ne!(
checksum_with(V4_DST),
checksum_with(Ipv4Addr::new(192, 0, 2, 10)),
"the destination is part of what is summed"
);
}
#[test]
fn an_exact_field_is_written_verbatim_and_nothing_else_moves() {
let bytes = Packet::new()
.push(Ipv4 {
total_length: Field::Exact(4),
..Ipv4::new(V4_SRC, V4_DST)
})
.push(Tcp::new(50_000, 80).with_flags(tcp_flags::SYN))
.build()
.expect("a wrong length is not an error, it is the request");
let ip = Ipv4Packet::new(&bytes).expect("an IPv4 header");
assert_eq!(ip.get_total_length(), 4, "written as asked");
assert_eq!(bytes.len(), 40, "and the packet is its real size");
assert_eq!(
ip.get_next_level_protocol(),
IpNextHeaderProtocols::Tcp,
"the fields nobody touched are still correct"
);
assert!(ip.payload().is_empty(), "a reader believes the header");
let tcp = TcpPacket::new(&bytes[20..]).expect("the segment is really there");
assert_ne!(tcp.get_checksum(), 0, "and is checksummed correctly");
assert_eq!(tcp.get_destination(), 80);
}
#[test]
fn a_deliberately_wrong_checksum_survives_to_the_wire() {
let bytes = Packet::new()
.push(Ipv4::new(V4_SRC, V4_DST).with_checksum(0))
.push(Tcp::new(50_000, 80).with_checksum(0xDEAD))
.build()
.expect("builds");
let ip = Ipv4Packet::new(&bytes).expect("an IPv4 header");
assert_eq!(ip.get_checksum(), 0);
assert_eq!(
TcpPacket::new(ip.payload()).expect("tcp").get_checksum(),
0xDEAD
);
}
#[test]
fn a_data_offset_that_lies_about_the_header_is_written_as_given() {
let bytes = Packet::new()
.push(Ipv4::new(V4_SRC, V4_DST))
.push(Tcp {
data_offset: Field::Exact(15),
..Tcp::new(50_000, 80)
})
.build()
.expect("builds");
let ip = Ipv4Packet::new(&bytes).expect("header");
assert_eq!(
TcpPacket::new(ip.payload()).expect("tcp").get_data_offset(),
15
);
}
#[test]
fn a_computed_length_that_cannot_fit_is_refused() {
let refused = Packet::new()
.push(Ipv4::new(V4_SRC, V4_DST))
.push(Udp::new(50_000, 53).with_payload(vec![0u8; u16::MAX as usize]))
.build();
assert!(
matches!(refused, Err(PacketError::TooLong { .. })),
"got {refused:?}"
);
}
#[test]
fn editing_the_ip_layer_moves_the_checksum_that_depends_on_it() {
let mut packet = Packet::new()
.push(Ipv4::new(V4_SRC, V4_DST))
.push(Tcp::new(50_000, 80).with_flags(tcp_flags::SYN));
let over_v4 = packet.build().expect("builds");
packet.layers_mut()[0] = Layer::Ipv6(Ipv6::new(v6("2001:db8::1"), v6("2001:db8::2")));
let over_v6 = packet.build().expect("builds");
let v4_sum = TcpPacket::new(&over_v4[20..]).expect("tcp").get_checksum();
let v6_sum = TcpPacket::new(&over_v6[40..]).expect("tcp").get_checksum();
assert_ne!(
v4_sum, v6_sum,
"the pseudo-header changed, so the checksum must have"
);
}
#[test]
fn a_bare_transport_layer_builds_without_inventing_addresses() {
let bytes = Packet::new()
.push(Tcp::new(50_000, 80).with_flags(tcp_flags::SYN))
.build()
.expect("builds");
assert_eq!(bytes.len(), 20);
assert_eq!(TcpPacket::new(&bytes).expect("tcp").get_checksum(), 0);
}
#[test]
fn a_payload_is_counted_by_every_length_above_it() {
let bytes = Packet::new()
.push(Ipv4::new(V4_SRC, V4_DST))
.push(Udp::new(50_000, 53).with_payload(b"hello".to_vec()))
.build()
.expect("builds");
let ip = Ipv4Packet::new(&bytes).expect("header");
assert_eq!(ip.get_total_length() as usize, 20 + 8 + 5);
assert_eq!(
UdpPacket::new(ip.payload()).expect("udp").get_length(),
8 + 5
);
assert_eq!(&bytes[bytes.len() - 5..], b"hello");
}
#[test]
fn tcp_options_move_the_data_offset_that_finds_the_payload() {
let bytes = Packet::new()
.push(Ipv4::new(V4_SRC, V4_DST))
.push(Tcp {
options: vec![2, 4, 0x05, 0x84],
payload: b"body".to_vec(),
..Tcp::new(50_000, 80)
})
.build()
.expect("builds");
let ip = Ipv4Packet::new(&bytes).expect("header");
let tcp = TcpPacket::new(ip.payload()).expect("tcp");
assert_eq!(tcp.get_data_offset(), 6, "twenty bytes plus one word");
assert_eq!(tcp.payload(), b"body");
}
#[test]
fn a_raw_layer_is_written_exactly_as_given() {
let bytes = Packet::new()
.push(Ipv4::new(V4_SRC, V4_DST))
.push(Layer::Raw(vec![0xDE, 0xAD, 0xBE, 0xEF]))
.build()
.expect("builds");
assert_eq!(&bytes[20..], &[0xDE, 0xAD, 0xBE, 0xEF]);
assert_eq!(
Ipv4Packet::new(&bytes).expect("header").get_total_length(),
24
);
}
#[test]
fn crc32c_matches_the_published_check_value() {
assert_eq!(crc32c(b"123456789"), 0xE306_9283);
}
#[test]
fn an_sctp_checksum_is_written_little_endian_over_a_zeroed_field() {
let bytes = Sctp::new(50_000, 9)
.with_chunks(vec![1, 0, 0, 4]) .to_bytes();
let mut zeroed = bytes.clone();
zeroed[8..12].copy_from_slice(&[0; 4]);
let crc = crc32c(&zeroed);
assert_eq!(&bytes[8..12], &crc.to_le_bytes());
assert_ne!(
&bytes[8..12],
&crc.to_be_bytes(),
"little-endian, not big — the check value makes the two differ"
);
}
#[test]
fn an_ip_header_names_the_sctp_inside_it() {
let bytes = Packet::new()
.push(Ipv4::new(V4_SRC, V4_DST))
.push(Sctp::new(50_000, 9).with_chunks(vec![1, 0, 0, 4]))
.build()
.expect("builds");
assert_eq!(
Ipv4Packet::new(&bytes)
.expect("header")
.get_next_level_protocol(),
IpNextHeaderProtocols::Sctp
);
}
#[test]
fn a_deliberately_wrong_sctp_checksum_survives_to_the_wire() {
let bytes = Sctp::new(50_000, 9).with_checksum(0).to_bytes();
assert_eq!(&bytes[8..12], &[0; 4]);
}
}