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
// Copyright (c) 2014, 2015 Robert Clipsham <robert@octarineparrot.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! An IPv6 packet abstraction.

use crate::ip::IpNextHeaderProtocol;
use crate::{types::*, Packet};
use std::net::Ipv6Addr;

/// Represents an IPv6 Packet.
#[derive(Debug, Packet)]
pub struct Ipv6 {
    pub version: u4,
    pub traffic_class: u8,
    pub flow_label: u20be,
    pub payload_length: u16be,
    #[construct_with(u8)]
    pub next_header: IpNextHeaderProtocol,
    pub hop_limit: u8,
    #[construct_with(u16, u16, u16, u16, u16, u16, u16, u16)]
    pub source: Ipv6Addr,
    #[construct_with(u16, u16, u16, u16, u16, u16, u16, u16)]
    pub destination: Ipv6Addr,
    #[length = "payload_length"]
    #[payload]
    pub payload: Vec<u8>,
}

impl<'p> ExtensionIterable<'p> {
    pub fn new(buf: &[u8]) -> ExtensionIterable {
        ExtensionIterable { buf: buf }
    }
}

/// Represents an IPv6 Extension.
#[derive(Debug, Packet)]
pub struct Extension {
    #[construct_with(u8)]
    pub next_header: IpNextHeaderProtocol,
    pub hdr_ext_len: u8,
    #[length = "ipv6_extension_length(hdr_ext_len)"]
    #[payload]
    pub options: Vec<u8>,
}

fn ipv6_extension_length(hdr_ext_len: u8) -> usize {
    hdr_ext_len as usize * 8 + 8 - 2
}

/// Represents an IPv6 Hop-by-Hop Options.
pub type HopByHop = Extension;
/// A structure enabling manipulation of on the wire packets.
pub type HopByHopPacket<'p> = ExtensionPacket<'p>;
/// A structure enabling manipulation of on the wire packets.
pub type MutableHopByHopPacket<'p> = MutableExtensionPacket<'p>;

/// Represents an IPv6 Routing Extension.
#[derive(Debug, Packet)]
pub struct Routing {
    #[construct_with(u8)]
    pub next_header: IpNextHeaderProtocol,
    pub hdr_ext_len: u8,
    pub routing_type: u8,
    pub segments_left: u8,
    #[length = "routing_extension_length(hdr_ext_len)"]
    #[payload]
    pub data: Vec<u8>,
}

fn routing_extension_length(hdr_ext_len: u8) -> usize {
    hdr_ext_len as usize * 8 + 8 - 4
}

/// Represents an IPv6 Fragment Extension.
#[derive(Debug, Packet)]
pub struct Fragment {
    #[construct_with(u8)]
    pub next_header: IpNextHeaderProtocol,
    pub reserved: u8,
    pub fragment_offset_with_flags: u16be,
    pub id: u32be,
    #[length = "0"]
    #[payload]
    pub payload: Vec<u8>,
}

const FRAGMENT_FLAGS_MASK: u16 = 0x03;
const FRAGMENT_FLAGS_MORE_FRAGMENTS: u16 = 0x01;
const FRAGMENT_OFFSET_MASK: u16 = !FRAGMENT_FLAGS_MASK;

impl<'p> FragmentPacket<'p> {
    pub fn get_fragment_offset(&self) -> u16 {
        self.get_fragment_offset_with_flags() & FRAGMENT_OFFSET_MASK
    }

    pub fn is_last_fragment(&self) -> bool {
        (self.get_fragment_offset_with_flags() & FRAGMENT_FLAGS_MORE_FRAGMENTS) == 0
    }
}

impl<'p> MutableFragmentPacket<'p> {
    pub fn get_fragment_offset(&self) -> u16 {
        self.get_fragment_offset_with_flags() & FRAGMENT_OFFSET_MASK
    }

    pub fn is_last_fragment(&self) -> bool {
        (self.get_fragment_offset_with_flags() & FRAGMENT_FLAGS_MORE_FRAGMENTS) == 0
    }

    pub fn set_fragment_offset(&mut self, offset: u16) {
        let fragment_offset_with_flags = self.get_fragment_offset_with_flags();

        self.set_fragment_offset_with_flags(
            (offset & FRAGMENT_OFFSET_MASK) | (fragment_offset_with_flags & FRAGMENT_FLAGS_MASK),
        );
    }

    pub fn set_last_fragment(&mut self, is_last: bool) {
        let fragment_offset_with_flags = self.get_fragment_offset_with_flags();

        self.set_fragment_offset_with_flags(if is_last {
            fragment_offset_with_flags & !FRAGMENT_FLAGS_MORE_FRAGMENTS
        } else {
            fragment_offset_with_flags | FRAGMENT_FLAGS_MORE_FRAGMENTS
        });
    }
}

/// Represents an Destination Options.
pub type Destination = Extension;
/// A structure enabling manipulation of on the wire packets.
pub type DestinationPacket<'p> = ExtensionPacket<'p>;
/// A structure enabling manipulation of on the wire packets.
pub type MutableDestinationPacket<'p> = MutableExtensionPacket<'p>;

#[test]
fn ipv6_header_test() {
    use crate::ip::IpNextHeaderProtocols;
    use crate::{MutablePacket, Packet, PacketSize};

    let mut packet = [0u8; 0x200];
    {
        let mut ip_header = MutableIpv6Packet::new(&mut packet[..]).unwrap();
        ip_header.set_version(6);
        assert_eq!(ip_header.get_version(), 6);

        ip_header.set_traffic_class(17);
        assert_eq!(ip_header.get_traffic_class(), 17);

        ip_header.set_flow_label(0x10101);
        assert_eq!(ip_header.get_flow_label(), 0x10101);

        ip_header.set_payload_length(0x0101);
        assert_eq!(ip_header.get_payload_length(), 0x0101);
        assert_eq!(0x0101, ip_header.payload().len());

        ip_header.set_next_header(IpNextHeaderProtocols::Hopopt);
        assert_eq!(ip_header.get_next_header(), IpNextHeaderProtocols::Hopopt);

        ip_header.set_hop_limit(1);
        assert_eq!(ip_header.get_hop_limit(), 1);

        let source = Ipv6Addr::new(0x110, 0x1001, 0x110, 0x1001, 0x110, 0x1001, 0x110, 0x1001);
        ip_header.set_source(source);
        assert_eq!(ip_header.get_source(), source);

        let dest = Ipv6Addr::new(0x110, 0x1001, 0x110, 0x1001, 0x110, 0x1001, 0x110, 0x1001);
        ip_header.set_destination(dest);
        assert_eq!(ip_header.get_destination(), dest);

        let mut pos = {
            let mut hopopt = MutableHopByHopPacket::new(ip_header.payload_mut()).unwrap();

            hopopt.set_next_header(IpNextHeaderProtocols::Ipv6Opts);
            assert_eq!(hopopt.get_next_header(), IpNextHeaderProtocols::Ipv6Opts);

            hopopt.set_hdr_ext_len(1);
            assert_eq!(hopopt.get_hdr_ext_len(), 1);

            hopopt.set_options(&[b'A'; 14][..]);
            assert_eq!(hopopt.payload(), b"AAAAAAAAAAAAAA");

            hopopt.packet_size()
        };

        pos += {
            let mut dstopt =
                MutableDestinationPacket::new(&mut ip_header.payload_mut()[pos..]).unwrap();

            dstopt.set_next_header(IpNextHeaderProtocols::Ipv6Route);
            assert_eq!(dstopt.get_next_header(), IpNextHeaderProtocols::Ipv6Route);

            dstopt.set_hdr_ext_len(1);
            assert_eq!(dstopt.get_hdr_ext_len(), 1);

            dstopt.set_options(&[b'B'; 14][..]);
            assert_eq!(dstopt.payload(), b"BBBBBBBBBBBBBB");

            dstopt.packet_size()
        };

        pos += {
            let mut routing =
                MutableRoutingPacket::new(&mut ip_header.payload_mut()[pos..]).unwrap();

            routing.set_next_header(IpNextHeaderProtocols::Ipv6Frag);
            assert_eq!(routing.get_next_header(), IpNextHeaderProtocols::Ipv6Frag);

            routing.set_hdr_ext_len(1);
            assert_eq!(routing.get_hdr_ext_len(), 1);

            routing.set_routing_type(4);
            assert_eq!(routing.get_routing_type(), 4);

            routing.set_segments_left(2);
            assert_eq!(routing.get_segments_left(), 2);

            routing.set_data(&[b'C'; 12][..]);
            assert_eq!(routing.payload(), b"CCCCCCCCCCCC");

            routing.packet_size()
        };

        pos += {
            let mut frag = MutableFragmentPacket::new(&mut ip_header.payload_mut()[pos..]).unwrap();

            frag.set_next_header(IpNextHeaderProtocols::Udp);
            assert_eq!(frag.get_next_header(), IpNextHeaderProtocols::Udp);

            frag.set_fragment_offset(1024);
            assert_eq!(frag.get_fragment_offset(), 1024);

            frag.set_last_fragment(false);
            assert!(!frag.is_last_fragment());

            frag.set_id(1234);
            assert_eq!(frag.get_id(), 1234);

            frag.packet_size()
        };

        assert_eq!(
            ExtensionIterable::new(&ip_header.payload()[..pos])
                .map(|ext| (
                    ext.get_next_header(),
                    ext.get_hdr_ext_len(),
                    ext.packet_size()
                ))
                .collect::<Vec<_>>(),
            vec![
                (IpNextHeaderProtocols::Ipv6Opts, 1, 16),
                (IpNextHeaderProtocols::Ipv6Route, 1, 16),
                (IpNextHeaderProtocols::Ipv6Frag, 1, 16),
                (IpNextHeaderProtocols::Udp, 0, 8),
            ]
        );
    }

    let ref_packet = [
        0x61, /* ver/traffic class */
        0x11, /* traffic class/flow label */
        0x01, 0x01, /* flow label */
        0x01, 0x01, /* payload length */
        0x00, /* next header */
        0x01, /* hop limit */
        /* source ip */
        0x01, 0x10, 0x10, 0x01, 0x01, 0x10, 0x10, 0x01, 0x01, 0x10, 0x10, 0x01, 0x01, 0x10, 0x10,
        0x01, /* dest ip */
        0x01, 0x10, 0x10, 0x01, 0x01, 0x10, 0x10, 0x01, 0x01, 0x10, 0x10, 0x01, 0x01, 0x10, 0x10,
        0x01, /* Hop-by-Hop Options */
        0x3c, // Next Header
        0x01, // Hdr Ext Len
        b'A', b'A', b'A', b'A', b'A', b'A', b'A', b'A', b'A', b'A', b'A', b'A', b'A', b'A',
        /* Destination Options */
        0x2b, // Next Header
        0x01, // Hdr Ext Len
        b'B', b'B', b'B', b'B', b'B', b'B', b'B', b'B', b'B', b'B', b'B', b'B', b'B', b'B',
        /* Routing */
        0x2c, // Next Header
        0x01, // Hdr Ext Len
        0x04, // Routing Type
        0x02, // Segments Left
        b'C', b'C', b'C', b'C', b'C', b'C', b'C', b'C', b'C', b'C', b'C', b'C',
        /* Fragment */
        0x11, // Next Header
        0x00, // Reserved
        0x04, 0x01, // Fragment Offset
        0x00, 0x00, 0x04, 0xd2, // Identification
    ];
    assert_eq!(&ref_packet[..], &packet[..ref_packet.len()]);
}