summaryrefslogtreecommitdiff
path: root/src/protocol/ipv4.rs
blob: f2fc19b183d52577c84c1ad03c1bbb46a8ac4be2 (plain)
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
use crate::protocol::codec::Decode;
use crate::protocol::ip::IPProtocol;
use nom::bits;
use nom::error::Error;
use nom::number;
use nom::sequence;
use nom::IResult;
use std::net::Ipv4Addr;

/******************************************************************************
 * Struct
 ******************************************************************************/

/*
 * Internet 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
 *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 *  |Version|  IHL  |Type of Service|          Total Length         |
 *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 *  |         Identification        |Flags|      Fragment Offset    |
 *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 *  |  Time to Live |    Protocol   |         Header Checksum       |
 *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 *  |                       Source Address                          |
 *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 *  |                    Destination Address                        |
 *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 *  |                    Options                    |    Padding    |
 *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 */

#[derive(Debug, PartialEq)]
pub struct IPv4Header {
    pub version: u8, // 4 bit
    pub ihl: u8,     // 4 bit
    pub tos: u8,
    pub length: u16,
    pub id: u16,
    pub flags: u8,        //  3 bit
    pub frag_offset: u16, // 13 bit
    pub ttl: u8,
    pub protocol: IPProtocol,
    pub checksum: u16,
    pub source_address: Ipv4Addr,
    pub dest_address: Ipv4Addr,
    pub options: Option<Vec<u8>>,
}

/******************************************************************************
 * API
 ******************************************************************************/

fn flag_offset_decode(input: &[u8]) -> IResult<&[u8], (u8, u16)> {
    bits::bits::<_, _, Error<_>, _, _>(sequence::pair(
        bits::streaming::take(3u8),
        bits::streaming::take(13u16),
    ))(input)
}

fn version_hlen_decode(input: &[u8]) -> IResult<&[u8], (u8, u8)> {
    bits::bits::<_, _, Error<_>, _, _>(sequence::pair(
        bits::streaming::take(4u8),
        bits::streaming::take(4u8),
    ))(input)
}

fn address_v4_decode(input: &[u8]) -> IResult<&[u8], Ipv4Addr> {
    let (input, ipv4) = nom::bytes::streaming::take(4u8)(input)?;

    Ok((input, Ipv4Addr::from(<[u8; 4]>::try_from(ipv4).unwrap())))
}

impl Decode for IPv4Header {
    type Iterm = IPv4Header;
    fn decode(input: &[u8]) -> IResult<&[u8], IPv4Header> {
        let (input, verihl) = version_hlen_decode(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_offset_decode(input)?;
        let (input, ttl) = number::streaming::be_u8(input)?;
        let (input, protocol) = IPProtocol::decode(input)?;
        let (input, checksum) = number::streaming::be_u16(input)?;
        let (input, source_address) = address_v4_decode(input)?;
        let (input, dest_address) = address_v4_decode(input)?;
        let (input, options) = match verihl.1 > 5 {
            true => nom::bytes::streaming::take((verihl.1 - 5) * 4)(input)
                .map(|(i, l)| (i, Some(l.to_vec())))?,
            false => (input, None),
        };

        Ok((
            input,
            IPv4Header {
                version: verihl.0,
                ihl: verihl.1 * 4, // verihl.1 * 32 / 8
                tos,
                length,
                id,
                flags: flag_frag_offset.0,
                frag_offset: flag_frag_offset.1,
                ttl,
                protocol,
                checksum,
                source_address,
                dest_address,
                options,
            },
        ))
    }
}

/******************************************************************************
 * TEST
 ******************************************************************************/

#[cfg(test)]
mod tests {
    use super::IPv4Header;
    use crate::protocol::codec::Decode;
    use crate::protocol::ip::IPProtocol;
    use std::net::Ipv4Addr;

    const LAST_SLICE: &'static [u8] = &[0xff];

    #[test]
    // Without Options
    fn ipv4_header_decode1() {
        /*
         * Internet Protocol Version 4, Src: 192.168.0.101, Dst: 121.14.154.93
         *     0100 .... = Version: 4
         *     .... 0101 = Header Length: 20 bytes (5)
         *     Differentiated Services Field: 0x00 (DSCP: CS0, ECN: Not-ECT)
         *         0000 00.. = Differentiated Services Codepoint: Default (0)
         *         .... ..00 = Explicit Congestion Notification: Not ECN-Capable Transport (0)
         *     Total Length: 70
         *     Identification: 0xe2db (58075)
         *     000. .... = Flags: 0x0
         *         0... .... = Reserved bit: Not set
         *         .0.. .... = Don't fragment: Not set
         *         ..0. .... = More fragments: Not set
         *     ...0 0000 0000 0000 = Fragment Offset: 0
         *     Time to Live: 64
         *     Protocol: UDP (17)
         *     Header Checksum: 0xc352 [correct]
         *     [Header checksum status: Good]
         *     [Calculated Checksum: 0xc352]
         *     Source Address: 192.168.0.101
         *    Destination Address: 121.14.154.93
         * User Datagram Protocol, Src Port: 64820, Dst Port: 53
         */

        let bytes = [
            0x45, /* Version and Header length */
            0x00, /* Differentiated Services Field */
            0x00, 0x46, /* Total Length */
            0xe2, 0xdb, /* Identification */
            0x00, 0x00, /* Flags and Fragment Offset */
            0x40, /* Time to Live */
            0x11, /* Protocol */
            0xc3, 0x52, /* Header Checksum */
            0xc0, 0xa8, 0x00, 0x65, /* Source Address */
            0x79, 0x0e, 0x9a, 0x5d, /* Destination Address */
            0xff, /* Payload */
        ];

        let expectation = IPv4Header {
            version: 4,
            ihl: 20,
            tos: 0,
            length: 70,
            id: 0xe2db,
            flags: 0x0,
            frag_offset: 0,
            ttl: 64,
            protocol: IPProtocol::UDP,
            checksum: 0xc352,
            source_address: Ipv4Addr::new(192, 168, 0, 101),
            dest_address: Ipv4Addr::new(121, 14, 154, 93),
            options: None,
        };

        assert_eq!(IPv4Header::decode(&bytes), Ok((LAST_SLICE, expectation)));

        // example
        let result = IPv4Header::decode(&bytes);
        match result {
            Ok((payload, header)) => {
                println!("OK: {:?}, payload: {}", header, payload.len());
            }
            Err(e) => {
                println!("ERR: {:?}", e);
            }
        }

        // assert_eq!(1, 0);
    }

    #[test]
    // With Options
    fn ipv4_header_decode2() {
        /*
         * Internet Protocol Version 4, Src: 127.0.0.1, Dst: 127.0.0.1
         *     0100 .... = Version: 4
         *     .... 1111 = Header Length: 60 bytes (15)
         *     Differentiated Services Field: 0x00 (DSCP: CS0, ECN: Not-ECT)
         *         0000 00.. = Differentiated Services Codepoint: Default (0)
         *         .... ..00 = Explicit Congestion Notification: Not ECN-Capable Transport (0)
         *     Total Length: 124
         *     Identification: 0x0000 (0)
         *     010. .... = Flags: 0x2, Don't fragment
         *         0... .... = Reserved bit: Not set
         *         .1.. .... = Don't fragment: Set
         *         ..0. .... = More fragments: Not set
         *     ...0 0000 0000 0000 = Fragment Offset: 0
         *     Time to Live: 64
         *     Protocol: ICMP (1)
         *     Header Checksum: 0xfd30 [correct]
         *     [Header checksum status: Good]
         *     [Calculated Checksum: 0xfd30]
         *     Source Address: 127.0.0.1
         *     Destination Address: 127.0.0.1
         *     Options: (40 bytes), Commercial Security
         *         IP Option - Commercial Security (40 bytes)
         *             Type: 134
         *                 1... .... = Copy on fragmentation: Yes
         *                 .00. .... = Class: Control (0)
         *                 ...0 0110 = Number: Commercial IP security option (6)
         *             Length: 40
         *             DOI: 1
         *             Tag Type: Restrictive Category Bitmap (1)
         *             Sensitivity Level: 1
         *             Categories: 0,2,4,5,6,239
         */

        let bytes = [
            0x4f, /* Version and Header length */
            0x00, /* Differentiated Services Field */
            0x00, 0x7c, /* Total Length */
            0x00, 0x00, /* Identification */
            0x40, 0x00, /* Flags and Fragment Offset */
            0x40, /* Time to Live */
            0x01, /* Protocol */
            0xfd, 0x30, /* Header Checksum */
            0x7f, 0x00, 0x00, 0x01, /* Source Address */
            0x7f, 0x00, 0x00, 0x01, /* Destination Address */
            0x86, 0x28, 0x00, 0x00, 0x00, 0x01, 0x01, 0x22, 0x00, 0x01, 0xae, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x01, /* Options */
            0xff, /* Payload */
        ];

        let expectation = IPv4Header {
            version: 4,
            ihl: 60,
            tos: 0,
            length: 124,
            id: 0x0000,
            flags: 0x2,
            frag_offset: 0,
            ttl: 64,
            protocol: IPProtocol::ICMP,
            checksum: 0xfd30,
            source_address: Ipv4Addr::new(127, 0, 0, 1),
            dest_address: Ipv4Addr::new(127, 0, 0, 1),
            options: Some(vec![
                0x86, 0x28, 0x00, 0x00, 0x00, 0x01, 0x01, 0x22, 0x00, 0x01, 0xae, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
            ]),
        };

        assert_eq!(IPv4Header::decode(&bytes), Ok((LAST_SLICE, expectation)));

        // example
        let result = IPv4Header::decode(&bytes);
        match result {
            Ok((payload, header)) => {
                println!("OK: {:?}, payload: {}", header, payload.len());
            }
            Err(e) => {
                println!("ERR: {:?}", e);
            }
        }

        // assert_eq!(1, 0);
    }
}