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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
use super::*;
use byteorder::{ByteOrder, LittleEndian};
use std::collections::HashMap;
use std::{error::Error, fmt};

#[derive(Default)]
pub struct TaggedParameters<'a> {
    tags: HashMap<TagName, Cow<'a, [u8]>>,
}

impl<'a> TaggedParameters<'a> {
    #[must_use]
    pub fn new() -> Self {
        Self {
            tags: HashMap::new(),
        }
    }

    pub fn add<T: Into<Cow<'a, [u8]>>>(&mut self, tag_name: TagName, tag_data: T) {
        self.tags.insert(tag_name, tag_data.into());
    }

    #[must_use]
    pub fn get_all(&self) -> &HashMap<TagName, Cow<'a, [u8]>> {
        &self.tags
    }

    #[must_use]
    pub fn get_bytes(&self, tag_name: TagName) -> Option<&[u8]> {
        self.tags.get(&tag_name).map(AsRef::as_ref)
    }

    #[must_use]
    pub fn ssid(&self) -> Option<&[u8]> {
        self.get_bytes(TagName::SSID).map(AsRef::as_ref)
    }

    /// in Mbit/sec
    #[must_use]
    pub fn supported_rates(&self) -> Option<Vec<f64>> {
        self.tags
            .get(&TagName::SupportedRates)
            .map(|supported_rates| {
                let mut rates = Vec::new();
                for rate in supported_rates.as_ref() {
                    // let is_basic = (rate & 0b1000_0000) != 0;
                    let kbps = rate & 0b0111_1111;

                    rates.push((f64::from(kbps) * 500.0) / 1000.0);
                }

                rates
            })
    }

    #[must_use]
    pub fn channel(&self) -> Option<u8> {
        self.tags
            .get(&TagName::DSParameter)
            .map(|bytes| bytes[0])
            // 5GHz
            .or_else(|| self.tags.get(&TagName::HTInformation).map(|bytes| bytes[0]))
    }

    #[must_use]
    pub fn rsn(&self) -> Option<RSNVersion> {
        self.tags.get(&TagName::RSNInformation).and_then(|bytes| {
            let mut i = 0;
            let len = bytes.len();

            if (i + 1) >= len {
                return None;
            }
            let version = LittleEndian::read_u16(&bytes[i..=(i + 1)]);
            Some(match version {
                1 => {
                    i += 2;
                    RSNVersion::Standard(make_std_rsn(&bytes[i..]))
                }
                other => RSNVersion::Reserved(other),
            })
        })
    }
}

fn make_std_rsn(bytes: &[u8]) -> RSN {
    let mut i = 0;
    let len = bytes.len();

    let mut rsn = RSN::default();

    if (i + 4) > len {
        return rsn;
    }
    let group_cipher_suite = RSN::read_cipher_suite(&bytes[i..(i + 4)]);
    rsn.group_cipher_suite = Some(group_cipher_suite);
    i += 4;

    if (i + 2) > len {
        return rsn;
    }
    let pairwise_cipher_suite_count = LittleEndian::read_u16(&bytes[i..(i + 2)]);
    i += 2;

    for _ in 0..pairwise_cipher_suite_count {
        if (i + 4) > len {
            return rsn;
        }
        let pairwise_cipher_suite = RSN::read_cipher_suite(&bytes[i..(i + 4)]);
        rsn.pairwise_cipher_suites.push(pairwise_cipher_suite);
        i += 4;
    }

    if (i + 2) > len {
        return rsn;
    }
    let akm_suite_count = LittleEndian::read_u16(&bytes[i..(i + 2)]);
    i += 2;

    for _ in 0..akm_suite_count {
        if (i + 4) > len {
            return rsn;
        }
        let akm_suite = RSN::read_akm_suite(&bytes[i..(i + 4)]);
        rsn.akm_suites.push(akm_suite);
        i += 4;
    }

    if (i + 2) > len {
        return rsn;
    }
    let b = LittleEndian::read_u16(&bytes[i..(i + 2)]);
    rsn.capabilities = Some(RSNCapabilities {
        pre_auth: (b & 0b0000_0000_0000_0001) != 0,
        pairwise: (b & 0b0000_0000_0000_0010) != 0,
        ptksa_replay_counter_value: ((b & 0b0000_0000_0000_1100) >> 2) as u8,
        gtksa_replay_counter_value: ((b & 0b0000_0000_0011_0000) >> 4) as u8,
        management_frame_protection_required: (b & 0b0000_0000_0100_0000) != 0,
        management_frame_protection_capable: (b & 0b0000_0000_1000_0000) != 0,
        joint_multi_band_rsna: (b & 0b0000_0001_0000_0000) != 0,
        peerkey: (b & 0b0000_0010_0000_0000) != 0,
    });

    rsn
}

#[derive(Debug, PartialEq)]
pub struct RSNCapabilities {
    /// 0: RSN Pre-Auth capabilities: Transmitter does not support pre-authentication
    pub pre_auth: bool,
    /// 0: RSN No Pairwise capabilities: Transmitter can support WEP default key 0 simultaneously with Pairwise key
    pub pairwise: bool,

    // {0x00, "1 replay counter per PTKSA/GTKSA/STAKeySA"},
    // {0x01, "2 replay counters per PTKSA/GTKSA/STAKeySA"},
    // {0x02, "4 replay counters per PTKSA/GTKSA/STAKeySA"},
    // {0x03, "16 replay counters per PTKSA/GTKSA/STAKeySA"},
    pub ptksa_replay_counter_value: u8,
    pub gtksa_replay_counter_value: u8,

    /// Management Frame Protection Required
    pub management_frame_protection_required: bool,

    /// Management Frame Protection Capable
    pub management_frame_protection_capable: bool,

    /// Joint Multi-band RSNA
    pub joint_multi_band_rsna: bool,

    /// PeerKey Enabled
    pub peerkey: bool,
}

#[derive(Debug, PartialEq)]
pub enum RSNVersion {
    Standard(RSN), // 1
    Reserved(u16),
}

#[derive(Debug, Default, PartialEq)]
pub struct RSN {
    pub group_cipher_suite: Option<CipherSuite>,
    pub pairwise_cipher_suites: Vec<CipherSuite>,
    pub akm_suites: Vec<AKMSuite>,
    pub capabilities: Option<RSNCapabilities>,
}

impl RSN {
    fn read_suite_oui_and_type(bytes: &[u8]) -> ([u8; 3], u8) {
        let mut suite_oui = [0; 3];
        suite_oui.clone_from_slice(&bytes[0..3]);
        let suite_type = bytes[3];
        (suite_oui, suite_type)
    }

    fn read_cipher_suite(bytes: &[u8]) -> CipherSuite {
        let (oui, type_) = Self::read_suite_oui_and_type(&bytes);

        CipherSuite::from(oui, type_)
    }

    fn read_akm_suite(bytes: &[u8]) -> AKMSuite {
        let (oui, type_) = Self::read_suite_oui_and_type(&bytes);

        AKMSuite::from(oui, type_)
    }
}

#[derive(Debug, PartialEq)]
pub enum CipherSuite {
    Standard(CipherSuiteType),
    Vendor([u8; 3], u8),
}

impl CipherSuite {
    fn from(oui: [u8; 3], type_: u8) -> Self {
        match oui {
            [0x00, 0x0f, 0xac] => Self::Standard(CipherSuiteType::from(type_)),
            other => Self::Vendor(other, type_),
        }
    }
}

#[derive(Debug, PartialEq)]
pub enum CipherSuiteType {
    UseGroupCipherSuite, // 0
    WEP40,               // 1
    TKIP,                // 2
    Reserved(u8),        // 3 Reserved
    CCMP,                // 4 // AES (CCM)
    WEP104,              // 5
    BIP,                 // 6
    GroupAddressedTrafficNotAllowed, /* 7
                          * 8-255 Reserved */
}
impl CipherSuiteType {
    fn from(type_: u8) -> Self {
        match type_ {
            1 => Self::WEP40,
            2 => Self::TKIP,
            4 => Self::CCMP,
            5 => Self::WEP104,
            6 => Self::BIP,
            7 => Self::GroupAddressedTrafficNotAllowed,
            other => Self::Reserved(other),
        }
    }
}

#[derive(Debug, PartialEq)]
pub enum AKMSuite {
    Standard(AKMSuiteType),
    Vendor([u8; 3], u8),
}

impl AKMSuite {
    fn from(oui: [u8; 3], type_: u8) -> Self {
        match oui {
            [0x00, 0x0f, 0xac] => Self::Standard(AKMSuiteType::from(type_)),
            other => Self::Vendor(other, type_),
        }
    }
}

/// Authentication and Key Management Suite
#[derive(Debug, PartialEq)]
pub enum AKMSuiteType {
    // 0 Reserved
    // 10-255 Reserved
    Reserved(u8),
    /// IEEE 802.1X with RSNA default
    IEEE802_1X, // 1
    /// Pre-Shared-Key
    PSK, // 2
    /// FT auth negotiated over IEEE 802.1X
    FTOver802_1X, // 3
    /// FT auth using PSK
    FTPSK, // 4

    /// IEEE 802.1X with SHA256 Key Derivation
    IEEE802_1XSHA, // 5
    /// PSK with SHA256 Key Derivation
    PSKSHA, // 6
    /// TPK Handshake
    TDLS, // 7
    /// SAE with SHA256
    SAE, // 8
    /// FT auth over SAE with SHA256
    FTOverSAE, // 9
}
impl AKMSuiteType {
    fn from(type_: u8) -> Self {
        match type_ {
            1 => Self::IEEE802_1X,
            2 => Self::PSK,
            3 => Self::FTOver802_1X,
            4 => Self::FTPSK,
            5 => Self::IEEE802_1XSHA,
            6 => Self::PSKSHA,
            7 => Self::TDLS,
            8 => Self::SAE,
            9 => Self::FTOverSAE,
            other => Self::Reserved(other),
        }
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Hash, Eq)]
pub enum TagName {
    Other(u8),
    SSID,
    SupportedRates,
    DSParameter,
    TrafficIndicationMap,
    CountryInformation,
    ERPInformation,
    ExtendedSupportedRates,
    RSNInformation,
    QBSSLoadElement,
    HTCapabilities,
    HTInformation,
    ExtendedCapabilities,
    VHTCapabilities,
    PowerCapabilities,
}

impl From<u8> for TagName {
    fn from(tag_number: u8) -> Self {
        match tag_number {
            0 => TagName::SSID,
            1 => TagName::SupportedRates,
            3 => TagName::DSParameter,
            5 => TagName::TrafficIndicationMap,
            7 => TagName::CountryInformation,
            33 => TagName::PowerCapabilities,
            42 => TagName::ERPInformation,
            50 => TagName::ExtendedSupportedRates,
            48 => TagName::RSNInformation,
            11 => TagName::QBSSLoadElement,
            45 => TagName::HTCapabilities,
            61 => TagName::HTInformation,
            127 => TagName::ExtendedCapabilities,
            191 => TagName::VHTCapabilities,

            n => TagName::Other(n),
        }
    }
}

#[derive(Debug)]
pub struct OverflowError {
    required_length: usize,
    remaining_length: usize,
}

impl OverflowError {
    #[must_use]
    pub fn new(required_length: usize,
               remaining_length: usize) -> Self {
        Self {
            required_length,
            remaining_length,
        }
    }
}

impl fmt::Display for OverflowError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "OverflowError: Expected {} bytes but only {} are remaining",
               self.required_length,
               self.remaining_length)
    }
}

impl Error for OverflowError {}

pub struct TaggedParameterIterator<'a> {
    bytes: &'a [u8],
}

impl<'a> Iterator for TaggedParameterIterator<'a> {
    type Item = Result<(TagName, &'a [u8]), OverflowError>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.bytes.len() < 2 {
            return None;
        }

        let tag_number = self.bytes[0];
        let tag_length = self.bytes[1] as usize;
        if self.bytes.len() < 2 + tag_length {
            self.bytes = &self.bytes[self.bytes.len()..];
            return Some(Err(OverflowError::new(tag_length, self.bytes.len())));
        }

        let tag_buffer = &self.bytes[2..(2+tag_length)];
        self.bytes = &self.bytes[2+tag_length..];

        Some(Ok((tag_number.into(), tag_buffer)))
    }
}

pub trait TaggedParametersTrait: FrameTrait {
    const TAGGED_PARAMETERS_START: usize;

    fn iter_tagged_parameters(&self) -> TaggedParameterIterator {
        TaggedParameterIterator {
            bytes: &self.bytes()[Self::TAGGED_PARAMETERS_START..]
        }
    }

    fn tagged_parameters(&self) -> Result<TaggedParameters, OverflowError> {
        let mut tagged_parameters = TaggedParameters::new();

        for tag in self.iter_tagged_parameters() {
            let (tag_name, tag) = tag?;
            tagged_parameters.add(tag_name, tag);
        }

        Ok(tagged_parameters)
    }

    fn ssid(&self) -> Option<Vec<u8>> {
        self.tagged_parameters().ok()?.ssid().map(ToOwned::to_owned)
    }
}

pub trait OptionalTaggedParametersTrait: ManagementFrameTrait {
    fn iter_tagged_parameters(&self) -> Option<TaggedParameterIterator> {
        let subtype = match self.subtype() {
            FrameSubtype::Management(subtype) => subtype,
            _ => return None
        };

        let offset = match subtype {
            ManagementSubtype::AssociationRequest => AssociationRequestFrame::TAGGED_PARAMETERS_START,
            ManagementSubtype::AssociationResponse => AssociationResponseFrame::TAGGED_PARAMETERS_START,
            ManagementSubtype::Authentication => AuthenticationFrame::TAGGED_PARAMETERS_START,
            ManagementSubtype::Beacon => BeaconFrame::TAGGED_PARAMETERS_START,
            ManagementSubtype::ProbeRequest => ProbeRequestFrame::TAGGED_PARAMETERS_START,
            ManagementSubtype::ProbeResponse => ProbeResponseFrame::TAGGED_PARAMETERS_START,
            _ => return None
        };

        if offset > self.bytes().len() {
            return None;
        }

        Some(TaggedParameterIterator {
            bytes: &self.bytes()[offset..]
        })
    }
}

impl OptionalTaggedParametersTrait for ManagementFrame<'_> {}