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
//! 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`:
//! 
//! ```toml
//! [dependencies]
//! etherparse = "0.8.3"
//! ```
//! 
//! 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.
//! ```
//! # use etherparse::{SlicedPacket, PacketBuilder};
//! # let builder = PacketBuilder::
//! #    ethernet2([1,2,3,4,5,6],     //source mac
//! #               [7,8,9,10,11,12]) //destionation mac
//! #    .ipv4([192,168,1,1], //source ip
//! #          [192,168,1,2], //desitionation 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 serialized data
//! #    let mut packet = Vec::<u8>::with_capacity(
//! #                            builder.size(payload.len()));
//! #    builder.write(&mut packet, &payload).unwrap();
//! 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:
//!
//! * [`SlicedPacket.from_ethernet`](struct.SlicedPacket.html#method.from_ethernet) for parsing from an Ethernet II header downwards
//! * [`SlicedPacket.from_ip`](struct.SlicedPacket.html#method.from_ip) for parsing from an IPv4 or IPv6 downwards
//!
//! ## Deserializing all headers into structs
//! This option deserializes all known headers and transferes their contents to header structs.
//! ```rust
//! # use etherparse::{PacketHeaders, PacketBuilder};
//! # let builder = PacketBuilder::
//! #    ethernet2([1,2,3,4,5,6],     //source mac
//! #               [7,8,9,10,11,12]) //destionation mac
//! #    .ipv4([192,168,1,1], //source ip
//! #          [192,168,1,2], //desitionation 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 serialized data
//! #    let mut packet = Vec::<u8>::with_capacity(
//! #                            builder.size(payload.len()));
//! #    builder.write(&mut packet, &payload).unwrap();
//! 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
//!
//! * [`PacketHeaders.from_ethernet_slice`](struct.PacketHeaders.html#method.from_ethernet_slice) for parsing from an Ethernet II header downwards
//! * [`PacketHeaders.from_ip_slice`](struct.PacketHeaders.html#method.from_ip_slice) for parsing from an IPv4 or IPv6 downwards
//!
//! ## 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 <NAME>Slice.from_slice methods, if you want to create your own slices:
//! 
//! * [`Ethernet2HeaderSlice.from_slice`](struct.Ethernet2HeaderSlice.html#method.from_slice)
//! * [`SingleVlanHeaderSlice.from_slice`](struct.SingleVlanHeaderSlice.html#method.from_slice)
//! * [`DoubleVlanHeaderSlice.from_slice`](struct.DoubleVlanHeaderSlice.html#method.from_slice)
//! * [`Ipv4HeaderSlice.from_slice`](struct.Ipv4HeaderSlice.html#method.from_slice)
//! * [`Ipv6HeaderSlice.from_slice`](struct.Ipv6HeaderSlice.html#method.from_slice)
//! * [`Ipv6ExtensionHeaderSlice.from_slice`](struct.Ipv6ExtensionHeaderSlice.html)
//! * [`UdpHeaderSlice.from_slice`](struct.UdpHeaderSlice.html#method.from_slice)
//! * [`TcpHeaderSlice.from_slice`](struct.TcpHeaderSlice.html#method.from_slice)
//! 
//! And for deserialization into the corresponding header structs have a look at:
//! 
//! * [`Ethernet2Header.read`](struct.Ethernet2Header.html#method.read) & [`Ethernet2Header.read_from_slice`](struct.Ethernet2Header.html#method.read_from_slice)
//! * [`SingleVlanHeader.read`](struct.SingleVlanHeader.html#method.read) & [`SingleVlanHeader.read_from_slice`](struct.SingleVlanHeader.html#method.read_from_slice)
//! * [`DoubleVlanHeader.read`](struct.DoubleVlanHeader.html#method.read) & [`DoubleVlanHeader.read_from_slice`](struct.DoubleVlanHeader.html#method.read_from_slice)
//! * [`IpHeader.read`](enum.IpHeader.html#method.read) & [`IpHeader.read_from_slice`](enum.IpHeader.html#method.read_from_slice)
//! * [`Ipv4Header.read`](struct.Ipv4Header.html#method.read) & [`Ipv4Header.read_from_slice`](struct.Ipv4Header.html#method.read_from_slice)
//! * [`Ipv6Header.read`](struct.Ipv6Header.html#method.read) & [`Ipv6Header.read_from_slice`](struct.Ipv6Header.html#method.read_from_slice)
//! * [`UdpHeader.read`](struct.UdpHeader.html#method.read) & [`UdpHeader.read_from_slice`](struct.UdpHeader.html#method.read_from_slice)
//! * [`TcpHeader.read`](struct.TcpHeader.html#method.read) & [`TcpHeader.read_from_slice`](struct.TcpHeader.html#method.read_from_slice)
//! 
//! # 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:](https://github.com/JulianSchmid/etherparse/blob/0.8.0/examples/write_udp.rs)
//! ```rust
//! 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](https://github.com/JulianSchmid/etherparse/blob/0.8.0/examples/write_tcp.rs) available.
//! 
//! Check out the [PacketBuilder documentation](struct.PacketBuilder.html) for more informations.
//! 
//! ## Manually serialising each header
//! Alternativly it is possible to manually build a packet ([example](https://github.com/JulianSchmid/etherparse/blob/0.8.0/examples/write_ipv4_udp.rs)). 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:
//! 
//! * [`Ethernet2Header.write`](struct.Ethernet2Header.html#method.write)
//! * [`SingleVlanHeader.write`](struct.SingleVlanHeader.html#method.write)
//! * [`DoubleVlanHeader.write`](struct.DoubleVlanHeader.html#method.write)
//! * [`Ipv4Header.write`](struct.Ipv4Header.html#method.write)
//! * [`Ipv4Header.write_raw`](struct.Ipv4Header.html#method.write_raw)
//! * [`Ipv6Header.write`](struct.Ipv6Header.html#method.write)
//! * [`UdpHeader.write`](struct.UdpHeader.html#method.write)
//! * [`TcpHeader.write`](struct.TcpHeader.html#method.write)
//!
//! # 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
//! * Darpa Internet Program Protocol Specification [RFC 791](https://tools.ietf.org/html/rfc791)
//! * Internet Protocol, Version 6 (IPv6) Specification [RFC 8200](https://tools.ietf.org/html/rfc8200)
//! * [IANA Protocol Numbers](https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml)
//! * [Internet Protocol Version 6 (IPv6) Parameters](https://www.iana.org/assignments/ipv6-parameters/ipv6-parameters.xhtml)
//! * [Wikipedia IEEE_802.1Q](https://en.wikipedia.org/w/index.php?title=IEEE_802.1Q&oldid=820983900)
//! * User Datagram Protocol (UDP) [RFC 768](https://tools.ietf.org/html/rfc768)
//! * Transmission Control Protocol [RFC 793](https://tools.ietf.org/html/rfc793)
//! * TCP Extensions for High Performance [RFC 7323](https://tools.ietf.org/html/rfc7323)
//! * The Addition of Explicit Congestion Notification (ECN) to IP [RFC 3168](https://tools.ietf.org/html/rfc3168)
//! * Robust Explicit Congestion Notification (ECN) Signaling with Nonces [RFC 3540](https://tools.ietf.org/html/rfc3540)

use std::io;

mod link;
pub use crate::link::ethernet::*;
pub use crate::link::vlan_tagging::*;

mod internet;
pub use crate::internet::ip::*;
pub use crate::internet::ipv4::*;
pub use crate::internet::ipv6::*;

mod transport;
pub use crate::transport::tcp::*;
pub use crate::transport::udp::*;
pub use crate::transport::TransportHeader;

mod packet_builder;
pub use crate::packet_builder::*;

mod packet_decoder;
pub use crate::packet_decoder::*;

mod packet_slicing;
pub use crate::packet_slicing::*;

pub mod packet_filter;

///Contains the size when serialized.
pub trait SerializedSize {
    const SERIALIZED_SIZE: usize;
}

///Errors that can occur when reading.
#[derive(Debug)]
pub enum ReadError {
    IoError(std::io::Error),
    ///Error when an unexpected end of a slice was reached even though more data was expected to be present (expected minimum size as argument).
    UnexpectedEndOfSlice(usize),
    ///Error when a double vlan tag was expected but the tpid of the outer vlan does not contain the expected id of 0x8100.
    VlanDoubleTaggingUnexpectedOuterTpid(u16),
    ///Error when the ip header version is not supported (only 4 & 6 are supported). The value is the version that was received.
    IpUnsupportedVersion(u8),
    ///Error when the ip header version field is not equal 4. The value is the version that was received.
    Ipv4UnexpectedVersion(u8),
    ///Error when the ipv4 header length is smaller then the header itself (5).
    Ipv4HeaderLengthBad(u8),
    ///Error when the total length field is too small to contain the header itself.
    Ipv4TotalLengthTooSmall(u16),
    ///Error when then ip header version field is not equal 6. The value is the version that was received.
    Ipv6UnexpectedVersion(u8),
    ///Error when more then 7 header extensions are present (according to RFC82000 this should never happen).
    Ipv6TooManyHeaderExtensions,
    ///Error given if the data_offset field in a TCP header is smaller then the minimum size of the tcp header itself.
    TcpDataOffsetTooSmall(u8),
}

impl ReadError {
    ///Adds an offset value to the UnexpectedEndOfSlice error.
    pub fn add_slice_offset(self, offset: usize) -> ReadError {
        use crate::ReadError::*;
        match self {
            UnexpectedEndOfSlice(value) => UnexpectedEndOfSlice(value + offset),
            value => value
        }
    }
}

impl From<std::io::Error> for ReadError {
    fn from(err: std::io::Error) -> ReadError {
        ReadError::IoError(err)
    }
}

///Errors that can occur when writing.
#[derive(Debug)]
pub enum WriteError {
    IoError(std::io::Error),
    ///Error in the data that was given to write
    ValueError(ValueError),
    ///Error when a given slice is not big enough to serialize the data.
    SliceTooSmall(usize),
}

impl WriteError {
    pub fn value_error(self) -> Option<ValueError> {
        match self {
            WriteError::ValueError(value) => Some(value),
            _ => None
        }
    }
}

impl From<ValueError> for WriteError {
    fn from(err: ValueError) -> WriteError {
        WriteError::ValueError(err)
    }
}

///Errors in the given data
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum ValueError {
    ///Error when the ipv4 options length is too big or not aligned (cannot be bigger then 40 bytes and must be a multiple of 4 bytes).
    Ipv4OptionsLengthBad(usize),
    ///Error when a given payload & ipv4 header is bigger then what fits inside an ipv4 total_length field.
    Ipv4PayloadLengthTooLarge(usize),
    ///Error when a given payload & ipv6 header block is bigger then what fits inside an ipv6 payload_length field.
    Ipv6PayloadLengthTooLarge(usize),
    ///Error when a given payload is bigger then what fits inside an udp packet
    ///Note that a the maximum payload size, as far as udp is conceirned, is max_value(u16) - 8. The 8 is for the size of the udp header itself.
    UdpPayloadLengthTooLarge(usize),
    ///Error when a given payload + tcp header options is bigger then what fits inside an tcp packet
    ///Note that a the maximum size, as far as tcp is conceirned, is max_value(u16) - tcp_header.data_offset()*4. The data_offset is for the size of the udp header itself.
    TcpLengthTooLarge(usize),
    ///Error when a u8 field in a header has a larger value then supported.
    U8TooLarge{value: u8, max: u8, field: ErrorField},
    ///Error when a u16 field in a header has a larger value then supported.
    U16TooLarge{value: u16, max: u16, field: ErrorField},
    ///Error when a u32 field in a header has a larger value then supported.
    U32TooLarge{value: u32, max: u32, field: ErrorField}
}

impl From<std::io::Error> for WriteError {
    fn from(err: std::io::Error) -> WriteError {
        WriteError::IoError(err)
    }
}

///Fields that can produce errors when serialized.
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum ErrorField {
    Ipv4HeaderLength,
    Ipv4PayloadLength,
    Ipv4Dscp,
    Ipv4Ecn,
    Ipv4FragmentsOffset,
    Ipv6FlowLabel,
    ///VlanTaggingHeader.priority_code_point
    VlanTagPriorityCodePoint,
    ///VlanTaggingHeader.vlan_identifier
    VlanTagVlanId,
    ///The data offset field in a tcp header
    TcpDataOffset
}

fn max_check_u8(value: u8, max: u8, field: ErrorField) -> Result<(), ValueError> {
    use crate::ValueError::U8TooLarge;
    if value <= max {
        Ok(())
    } else {
        Err(U8TooLarge { 
            value, 
            max,
            field
        })
    }
}

fn max_check_u16(value: u16, max: u16, field: ErrorField) -> Result<(), ValueError> {
    use crate::ValueError::U16TooLarge;
    if value <= max {
        Ok(())
    } else {
        Err(U16TooLarge{ 
            value, 
            max, 
            field
        })
    }
}

//NOTE: Replace this with std::Iterator::step_by as soon as it is in stable (see https://github.com/rust-lang/rust/issues/27741)
struct RangeStep {
    start: usize,
    end: usize,
    step: usize 
}

impl RangeStep {
    fn new(start: usize, end: usize, step: usize) -> RangeStep {
        RangeStep {
            start,
            end,
            step 
        }
    }
}

impl Iterator for RangeStep {
    type Item = usize;

    #[inline]
    fn next(&mut self) -> Option<usize> {
        if self.start < self.end {
            let result = self.start;
            self.start = result + self.step;
            Some(result)
        } else {
            None
        }
    }
}