wlan_sme/client/
protection.rs

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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use crate::client::rsn::Rsna;
use crate::client::ClientConfig;
use anyhow::{format_err, Error};
use fidl_fuchsia_wlan_common as fidl_common;
use fidl_fuchsia_wlan_mlme::DeviceInfo;
use wlan_common::bss::BssDescription;
use wlan_common::ie::rsn::rsne::{self, Rsne};
use wlan_common::ie::wpa::WpaIe;
use wlan_common::ie::{self};
use wlan_common::security::wep::{self, WepKey};
use wlan_common::security::{wpa, SecurityAuthenticator};
use wlan_rsn::auth::psk::ToPsk;
use wlan_rsn::auth::{self};
use wlan_rsn::nonce::NonceReader;
use wlan_rsn::{NegotiatedProtection, ProtectionInfo};

#[derive(Debug)]
pub enum Protection {
    Open,
    Wep(WepKey),
    // WPA1 is based off of a modified pre-release version of IEEE 802.11i. It is similar enough
    // that we can reuse the existing RSNA implementation rather than duplicating large pieces of
    // logic.
    LegacyWpa(Rsna),
    Rsna(Rsna),
}

impl Protection {
    pub fn rsn_auth_method(&self) -> Option<auth::MethodName> {
        let rsna = match self {
            Self::LegacyWpa(rsna) => rsna,
            Self::Rsna(rsna) => rsna,
            // Neither WEP or Open use an RSN, so None is returned.
            Self::Wep(_) | Self::Open => {
                return None;
            }
        };

        Some(rsna.supplicant.get_auth_method())
    }
}

#[derive(Debug)]
pub enum ProtectionIe {
    Rsne(Vec<u8>),
    VendorIes(Vec<u8>),
}

/// Context for authentication.
///
/// This ephemeral type is used to query and derive various IEs and RSN entities based on
/// parameterized security data, the configured client, and the target BSS. This is exposed to
/// client code via `TryFrom` implementations, which allow a context to be converted into a
/// negotiated `Protection`. These conversions fail if the combination of an authenticator and a
/// network is incompatible.
///
/// The type parameter `C` represents the parameterized security data and is either a type
/// representing credential data or a `SecurityAuthenticator`.
///
/// # Examples
///
/// To derive a `Protection`, construct a `SecurityContext` using a `SecurityAuthenticator` and
/// perform a conversion.
///
/// ```rust,ignore
/// // See the documentation for `SecurityAuthenticator` for more details.
/// let authenticator = SecurityAuthenticator::try_from(authentication)?;
/// let protection = Protection::try_from(SecurityContext {
///     security: &authenticator,
///     device: &device, // Device information.
///     security_support: &security_support, // Security features.
///     config: &config, // Client configuration.
///     bss: &bss, // BSS description.
/// })?;
/// ```
#[derive(Clone, Copy, Debug)]
pub struct SecurityContext<'a, C> {
    /// Contextual security data. This field has security-related
    pub security: &'a C,
    pub device: &'a DeviceInfo,
    pub security_support: &'a fidl_common::SecuritySupport,
    pub config: &'a ClientConfig,
    pub bss: &'a BssDescription,
}

impl<'a, C> SecurityContext<'a, C> {
    /// Gets a context with a subject replaced by the given subject. Other fields are unmodified.
    fn map<U>(&self, subject: &'a U) -> SecurityContext<'a, U> {
        SecurityContext {
            security: subject,
            device: self.device,
            security_support: self.security_support,
            config: self.config,
            bss: self.bss,
        }
    }
}

impl SecurityContext<'_, wpa::Wpa1Credentials> {
    /// Gets the authenticator and supplicant IEs for WPA1 from the associated BSS.
    fn authenticator_supplicant_ie(&self) -> Result<(WpaIe, WpaIe), Error> {
        let a_wpa_ie = self.bss.wpa_ie()?;
        if !crate::client::wpa::is_legacy_wpa_compatible(&a_wpa_ie) {
            return Err(format_err!("Legacy WPA requested but IE is incompatible: {:?}", a_wpa_ie));
        }
        let s_wpa_ie = crate::client::wpa::construct_s_wpa(&a_wpa_ie);
        Ok((a_wpa_ie, s_wpa_ie))
    }

    /// Gets the PSK used to authenticate via WPA1.
    fn authentication_config(&self) -> auth::Config {
        auth::Config::ComputedPsk(self.security.to_psk(&self.bss.ssid).into())
    }
}

impl SecurityContext<'_, wpa::Wpa2PersonalCredentials> {
    /// Gets the authenticator and supplicant RSNEs for WPA2 Personal from the associated BSS.
    fn authenticator_supplicant_rsne(&self) -> Result<(Rsne, Rsne), Error> {
        let a_rsne_ie = self
            .bss
            .rsne()
            .ok_or_else(|| format_err!("WPA2 requested but RSNE is not present in BSS."))?;
        let (_, a_rsne) = rsne::from_bytes(a_rsne_ie)
            .map_err(|error| format_err!("Invalid RSNE IE {:02x?}: {:?}", a_rsne_ie, error))?;
        let s_rsne = a_rsne.derive_wpa2_s_rsne(self.security_support)?;
        Ok((a_rsne, s_rsne))
    }

    /// Gets the PSK used to authenticate via WPA2 Personal.
    fn authentication_config(&self) -> auth::Config {
        auth::Config::ComputedPsk(self.security.to_psk(&self.bss.ssid).into())
    }
}

impl SecurityContext<'_, wpa::Wpa3PersonalCredentials> {
    /// Gets the authenticator and supplicant RSNEs for WPA3 Personal from the associated BSS.
    fn authenticator_supplicant_rsne(&self) -> Result<(Rsne, Rsne), Error> {
        let a_rsne_ie = self
            .bss
            .rsne()
            .ok_or_else(|| format_err!("WPA3 requested but RSNE is not present in BSS."))?;
        let (_, a_rsne) = rsne::from_bytes(a_rsne_ie)
            .map_err(|error| format_err!("Invalid RSNE IE {:02x?}: {:?}", a_rsne_ie, error))?;
        let s_rsne = a_rsne.derive_wpa3_s_rsne(self.security_support)?;
        Ok((a_rsne, s_rsne))
    }

    /// Gets the SAE used to authenticate via WPA3 Personal.
    fn authentication_config(&self) -> Result<auth::Config, Error> {
        match self.security {
            wpa::Wpa3PersonalCredentials::Passphrase(ref passphrase) => {
                // Prefer SAE in SME.
                if self.security_support.sae.sme_handler_supported {
                    Ok(auth::Config::Sae {
                        ssid: self.bss.ssid.clone(),
                        password: passphrase.clone().into(),
                        mac: self.device.sta_addr.into(),
                        peer_mac: self.bss.bssid.into(),
                    })
                } else if self.security_support.sae.driver_handler_supported {
                    Ok(auth::Config::DriverSae { password: passphrase.clone().into() })
                } else {
                    Err(format_err!(
                        "Failed to generate WPA3 authentication config: no SAE SME nor driver \
                         handler"
                    ))
                }
            }
        }
    }
}

impl<'a> TryFrom<SecurityContext<'a, SecurityAuthenticator>> for Protection {
    type Error = Error;

    fn try_from(context: SecurityContext<'a, SecurityAuthenticator>) -> Result<Self, Self::Error> {
        match context.security {
            SecurityAuthenticator::Open => context
                .bss
                .is_open()
                .then(|| Protection::Open)
                .ok_or_else(|| format_err!("BSS is not configured for open authentication")),
            SecurityAuthenticator::Wep(authenticator) => context.map(authenticator).try_into(),
            SecurityAuthenticator::Wpa(wpa) => match wpa {
                wpa::WpaAuthenticator::Wpa1 { credentials, .. } => {
                    context.map(credentials).try_into()
                }
                wpa::WpaAuthenticator::Wpa2 { authentication, .. } => match authentication {
                    wpa::Authentication::Personal(personal) => context.map(personal).try_into(),
                    // TODO(https://fxbug.dev/42174395): Implement conversions for WPA Enterprise.
                    _ => Err(format_err!("WPA Enterprise is unsupported")),
                },
                wpa::WpaAuthenticator::Wpa3 { authentication, .. } => match authentication {
                    wpa::Authentication::Personal(personal) => context.map(personal).try_into(),
                    // TODO(https://fxbug.dev/42174395): Implement conversions for WPA Enterprise.
                    _ => Err(format_err!("WPA Enterprise is unsupported")),
                },
            },
        }
    }
}

impl<'a> TryFrom<SecurityContext<'a, wep::WepAuthenticator>> for Protection {
    type Error = Error;

    fn try_from(context: SecurityContext<'a, wep::WepAuthenticator>) -> Result<Self, Self::Error> {
        context
            .bss
            .has_wep_configured()
            .then(|| Protection::Wep(context.security.key.clone()))
            .ok_or_else(|| format_err!("BSS is not configured for WEP"))
    }
}

impl<'a> TryFrom<SecurityContext<'a, wpa::Wpa1Credentials>> for Protection {
    type Error = Error;

    fn try_from(context: SecurityContext<'a, wpa::Wpa1Credentials>) -> Result<Self, Self::Error> {
        context
            .bss
            .has_wpa1_configured()
            .then(|| -> Result<_, Self::Error> {
                let sta_addr = context.device.sta_addr.into();
                let (a_wpa_ie, s_wpa_ie) = context.authenticator_supplicant_ie()?;
                let negotiated_protection = NegotiatedProtection::from_legacy_wpa(&s_wpa_ie)?;
                let supplicant = wlan_rsn::Supplicant::new_wpa_personal(
                    NonceReader::new(&sta_addr)?,
                    context.authentication_config(),
                    sta_addr,
                    ProtectionInfo::LegacyWpa(s_wpa_ie),
                    context.bss.bssid.into(),
                    ProtectionInfo::LegacyWpa(a_wpa_ie),
                )
                .map_err(|error| format_err!("Failed to create ESS-SA: {:?}", error))?;
                Ok(Protection::LegacyWpa(Rsna {
                    negotiated_protection,
                    supplicant: Box::new(supplicant),
                }))
            })
            .transpose()?
            .ok_or_else(|| format_err!("BSS is not configured for WPA1"))
    }
}

impl<'a> TryFrom<SecurityContext<'a, wpa::Wpa2PersonalCredentials>> for Protection {
    type Error = Error;

    fn try_from(
        context: SecurityContext<'a, wpa::Wpa2PersonalCredentials>,
    ) -> Result<Self, Self::Error> {
        context
            .bss
            .has_wpa2_personal_configured()
            .then(|| -> Result<_, Self::Error> {
                let sta_addr = context.device.sta_addr.into();
                let (a_rsne, s_rsne) = context.authenticator_supplicant_rsne()?;
                let negotiated_protection = NegotiatedProtection::from_rsne(&s_rsne)?;
                let supplicant = wlan_rsn::Supplicant::new_wpa_personal(
                    NonceReader::new(&sta_addr)?,
                    context.authentication_config(),
                    sta_addr,
                    ProtectionInfo::Rsne(s_rsne),
                    context.bss.bssid.into(),
                    ProtectionInfo::Rsne(a_rsne),
                )
                .map_err(|error| format_err!("Failed to creat ESS-SA: {:?}", error))?;
                Ok(Protection::Rsna(Rsna {
                    negotiated_protection,
                    supplicant: Box::new(supplicant),
                }))
            })
            .transpose()?
            .ok_or_else(|| format_err!("BSS is not configured for WPA2 Personal"))
    }
}

impl<'a> TryFrom<SecurityContext<'a, wpa::Wpa3PersonalCredentials>> for Protection {
    type Error = Error;

    fn try_from(
        context: SecurityContext<'a, wpa::Wpa3PersonalCredentials>,
    ) -> Result<Self, Self::Error> {
        context
            .bss
            .has_wpa3_personal_configured()
            .then(|| -> Result<_, Self::Error> {
                let sta_addr = context.device.sta_addr.into();
                if !context.config.wpa3_supported {
                    return Err(format_err!("WPA3 requested but client does not support WPA3"));
                }
                let (a_rsne, s_rsne) = context.authenticator_supplicant_rsne()?;
                let negotiated_protection = NegotiatedProtection::from_rsne(&s_rsne)?;
                let supplicant = wlan_rsn::Supplicant::new_wpa_personal(
                    NonceReader::new(&sta_addr)?,
                    context.authentication_config()?,
                    sta_addr,
                    ProtectionInfo::Rsne(s_rsne),
                    context.bss.bssid.into(),
                    ProtectionInfo::Rsne(a_rsne),
                )
                .map_err(|error| format_err!("Failed to create ESS-SA: {:?}", error))?;
                Ok(Protection::Rsna(Rsna {
                    negotiated_protection,
                    supplicant: Box::new(supplicant),
                }))
            })
            .transpose()?
            .ok_or_else(|| format_err!("BSS is not configured for WPA3 Personal"))
    }
}

/// Based on the type of protection, derive either RSNE or Vendor IEs:
/// No Protection or WEP: Neither
/// WPA2: RSNE
/// WPA1: Vendor IEs
pub(crate) fn build_protection_ie(protection: &Protection) -> Result<Option<ProtectionIe>, Error> {
    match protection {
        Protection::Open | Protection::Wep(_) => Ok(None),
        Protection::LegacyWpa(rsna) => {
            let s_protection = rsna.negotiated_protection.to_full_protection();
            let s_wpa = match s_protection {
                ProtectionInfo::Rsne(_) => {
                    return Err(format_err!("found RSNE protection inside a WPA1 association..."));
                }
                ProtectionInfo::LegacyWpa(wpa) => wpa,
            };
            let mut buf = vec![];
            ie::write_wpa1_ie(&mut buf, &s_wpa).unwrap(); // Writing to a Vec never fails
            Ok(Some(ProtectionIe::VendorIes(buf)))
        }
        Protection::Rsna(rsna) => {
            let s_protection = rsna.negotiated_protection.to_full_protection();
            let s_rsne = match s_protection {
                ProtectionInfo::Rsne(rsne) => rsne,
                ProtectionInfo::LegacyWpa(_) => {
                    return Err(format_err!("found WPA protection inside an RSNA..."));
                }
            };
            let mut buf = Vec::with_capacity(s_rsne.len());
            // Writing an RSNE into a Vector can never fail as a Vector can be grown when more
            // space is required. If this panic ever triggers, something is clearly broken
            // somewhere else.
            let () = s_rsne.write_into(&mut buf).unwrap();
            Ok(Some(ProtectionIe::Rsne(buf)))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::client::{self};
    use wlan_common::ie::fake_ies::fake_wpa_ie;
    use wlan_common::ie::rsn::fake_rsnes::{fake_wpa2_s_rsne, fake_wpa3_s_rsne};
    use wlan_common::security::wep::{WEP104_KEY_BYTES, WEP40_KEY_BYTES};
    use wlan_common::security::wpa::credential::PSK_SIZE_BYTES;
    use wlan_common::test_utils::fake_features::{
        fake_security_support, fake_security_support_empty,
    };
    use wlan_common::{assert_variant, fake_bss_description};

    #[test]
    fn rsn_auth_method() {
        // Open
        let protection = Protection::Open;
        assert!(protection.rsn_auth_method().is_none());

        // Wep
        let protection = Protection::Wep(WepKey::parse([1; 5]).expect("unable to parse WEP key"));
        assert!(protection.rsn_auth_method().is_none());

        // WPA1
        let protection_info = ProtectionInfo::LegacyWpa(fake_wpa_ie());
        let negotiated_protection = NegotiatedProtection::from_protection(&protection_info)
            .expect("could create mocked WPA1 NegotiatedProtection");
        let protection = Protection::LegacyWpa(Rsna {
            negotiated_protection,
            supplicant: Box::new(client::test_utils::mock_psk_supplicant().0),
        });
        assert_eq!(protection.rsn_auth_method(), Some(auth::MethodName::Psk));

        // WPA2
        let protection_info = ProtectionInfo::Rsne(fake_wpa2_s_rsne());
        let negotiated_protection = NegotiatedProtection::from_protection(&protection_info)
            .expect("could create mocked WPA2 NegotiatedProtection");
        let protection = Protection::Rsna(Rsna {
            negotiated_protection,
            supplicant: Box::new(client::test_utils::mock_psk_supplicant().0),
        });
        assert_eq!(protection.rsn_auth_method(), Some(auth::MethodName::Psk));

        // WPA3
        let protection_info = ProtectionInfo::Rsne(fake_wpa3_s_rsne());
        let negotiated_protection = NegotiatedProtection::from_protection(&protection_info)
            .expect("could create mocked WPA3 NegotiatedProtection");
        let protection = Protection::Rsna(Rsna {
            negotiated_protection,
            supplicant: Box::new(client::test_utils::mock_sae_supplicant().0),
        });
        assert_eq!(protection.rsn_auth_method(), Some(auth::MethodName::Sae));
    }

    #[test]
    fn protection_from_wep40() {
        let device = crate::test_utils::fake_device_info([1u8; 6].into());
        let security_support = fake_security_support();
        let config = Default::default();
        let bss = fake_bss_description!(Wep);
        let authenticator = wep::WepAuthenticator { key: WepKey::from([1u8; WEP40_KEY_BYTES]) };
        let protection = Protection::try_from(SecurityContext {
            security: &authenticator,
            device: &device,
            security_support: &security_support,
            config: &config,
            bss: &bss,
        })
        .unwrap();
        assert!(matches!(protection, Protection::Wep(_)));
    }

    #[test]
    fn protection_from_wep104() {
        let device = crate::test_utils::fake_device_info([1u8; 6].into());
        let security_support = fake_security_support();
        let config = Default::default();
        let bss = fake_bss_description!(Wep);
        let authenticator = wep::WepAuthenticator { key: WepKey::from([1u8; WEP104_KEY_BYTES]) };
        let protection = Protection::try_from(SecurityContext {
            security: &authenticator,
            device: &device,
            security_support: &security_support,
            config: &config,
            bss: &bss,
        })
        .unwrap();
        assert!(matches!(protection, Protection::Wep(_)));
    }

    #[test]
    fn protection_from_wpa1_psk() {
        let device = crate::test_utils::fake_device_info([1u8; 6].into());
        let security_support = fake_security_support();
        let config = Default::default();
        let bss = fake_bss_description!(Wpa1);
        let credentials = wpa::Wpa1Credentials::Psk([1u8; PSK_SIZE_BYTES].into());
        let protection = Protection::try_from(SecurityContext {
            security: &credentials,
            device: &device,
            security_support: &security_support,
            config: &config,
            bss: &bss,
        })
        .unwrap();
        assert!(matches!(protection, Protection::LegacyWpa(_)));
    }

    #[test]
    fn protection_from_wpa2_personal_psk() {
        let device = crate::test_utils::fake_device_info([1u8; 6].into());
        let security_support = fake_security_support();
        let config = Default::default();
        let bss = fake_bss_description!(Wpa2);
        let credentials = wpa::Wpa2PersonalCredentials::Psk([1u8; PSK_SIZE_BYTES].into());
        let protection = Protection::try_from(SecurityContext {
            security: &credentials,
            device: &device,
            security_support: &security_support,
            config: &config,
            bss: &bss,
        })
        .unwrap();
        assert!(matches!(protection, Protection::Rsna(_)));
    }

    #[test]
    fn protection_from_wpa2_personal_passphrase() {
        let device = crate::test_utils::fake_device_info([1u8; 6].into());
        let security_support = fake_security_support();
        let config = Default::default();
        let bss = fake_bss_description!(Wpa2);
        let credentials =
            wpa::Wpa2PersonalCredentials::Passphrase("password".as_bytes().try_into().unwrap());
        let protection = Protection::try_from(SecurityContext {
            security: &credentials,
            device: &device,
            security_support: &security_support,
            config: &config,
            bss: &bss,
        })
        .unwrap();
        assert!(matches!(protection, Protection::Rsna(_)));
    }

    #[test]
    fn protection_from_wpa2_personal_tkip_only_passphrase() {
        let device = crate::test_utils::fake_device_info([1u8; 6].into());
        let security_support = fake_security_support();
        let config = Default::default();
        let bss = fake_bss_description!(Wpa2TkipOnly);
        let credentials =
            wpa::Wpa2PersonalCredentials::Passphrase("password".as_bytes().try_into().unwrap());
        let protection = Protection::try_from(SecurityContext {
            security: &credentials,
            device: &device,
            security_support: &security_support,
            config: &config,
            bss: &bss,
        })
        .unwrap();
        assert!(matches!(protection, Protection::Rsna(_)));
    }

    #[test]
    fn protection_from_wpa3_personal_passphrase() {
        let device = crate::test_utils::fake_device_info([1u8; 6].into());
        let security_support = fake_security_support();
        let config = ClientConfig { wpa3_supported: true, ..Default::default() };
        let bss = fake_bss_description!(Wpa3);
        let credentials =
            wpa::Wpa3PersonalCredentials::Passphrase("password".as_bytes().try_into().unwrap());
        let protection = Protection::try_from(SecurityContext {
            security: &credentials,
            device: &device,
            security_support: &security_support,
            config: &config,
            bss: &bss,
        })
        .unwrap();
        assert!(matches!(protection, Protection::Rsna(_)));
    }

    #[test]
    fn protection_from_wpa1_passphrase_with_open_bss() {
        let device = crate::test_utils::fake_device_info([1u8; 6].into());
        let security_support = fake_security_support();
        let config = Default::default();
        let bss = fake_bss_description!(Open);
        let credentials =
            wpa::Wpa1Credentials::Passphrase("password".as_bytes().try_into().unwrap());
        let _ = Protection::try_from(SecurityContext {
            security: &credentials,
            device: &device,
            security_support: &security_support,
            config: &config,
            bss: &bss,
        })
        .expect_err("incorrectly accepted WPA1 passphrase credentials with open BSS");
    }

    #[test]
    fn protection_from_open_authenticator_with_wpa1_bss() {
        let device = crate::test_utils::fake_device_info([1u8; 6].into());
        let security_support = fake_security_support();
        let config = Default::default();
        let bss = fake_bss_description!(Wpa1);
        // Note that there is no credentials type associated with an open authenticator, so an
        // authenticator is used here instead.
        let authenticator = SecurityAuthenticator::Open;
        let _ = Protection::try_from(SecurityContext {
            security: &authenticator,
            device: &device,
            security_support: &security_support,
            config: &config,
            bss: &bss,
        })
        .expect_err("incorrectly accepted open authenticator with WPA1 BSS");
    }

    #[test]
    fn protection_from_wpa2_personal_passphrase_with_wpa3_bss() {
        let device = crate::test_utils::fake_device_info([1u8; 6].into());
        let security_support = fake_security_support();
        let config = ClientConfig { wpa3_supported: true, ..Default::default() };
        let bss = fake_bss_description!(Wpa3);
        let credentials =
            wpa::Wpa2PersonalCredentials::Passphrase("password".as_bytes().try_into().unwrap());
        let _ = Protection::try_from(SecurityContext {
            security: &credentials,
            device: &device,
            security_support: &security_support,
            config: &config,
            bss: &bss,
        })
        .expect_err("incorrectly accepted WPA2 passphrase credentials with WPA3 BSS");
    }

    #[test]
    fn wpa1_psk_rsna() {
        let device = crate::test_utils::fake_device_info([1u8; 6].into());
        let security_support = fake_security_support();
        let config = Default::default();
        let bss = fake_bss_description!(Wpa1);
        let credentials = wpa::Wpa1Credentials::Psk([1u8; PSK_SIZE_BYTES].into());
        let context = SecurityContext {
            security: &credentials,
            device: &device,
            security_support: &security_support,
            config: &config,
            bss: &bss,
        };
        assert!(context.authenticator_supplicant_ie().is_ok());
        assert!(matches!(context.authentication_config(), auth::Config::ComputedPsk(_)));

        let protection = Protection::try_from(context).unwrap();
        assert_variant!(protection, Protection::LegacyWpa(rsna) => {
            assert_eq!(rsna.supplicant.get_auth_method(), auth::MethodName::Psk);
        });
    }

    #[test]
    fn wpa2_personal_psk_rsna() {
        let device = crate::test_utils::fake_device_info([1u8; 6].into());
        let security_support = fake_security_support();
        let config = Default::default();
        let bss = fake_bss_description!(Wpa2);
        let credentials = wpa::Wpa2PersonalCredentials::Psk([1u8; PSK_SIZE_BYTES].into());
        let context = SecurityContext {
            security: &credentials,
            device: &device,
            security_support: &security_support,
            config: &config,
            bss: &bss,
        };
        assert!(context.authenticator_supplicant_rsne().is_ok());
        assert!(matches!(context.authentication_config(), auth::Config::ComputedPsk(_)));

        let protection = Protection::try_from(context).unwrap();
        assert_variant!(protection, Protection::Rsna(rsna) => {
            assert_eq!(rsna.supplicant.get_auth_method(), auth::MethodName::Psk);
        });
    }

    #[test]
    fn wpa3_personal_passphrase_rsna_sme_auth() {
        let device = crate::test_utils::fake_device_info([1u8; 6].into());
        let security_support = fake_security_support();
        let config = ClientConfig { wpa3_supported: true, ..Default::default() };
        let bss = fake_bss_description!(Wpa3);
        let credentials =
            wpa::Wpa3PersonalCredentials::Passphrase("password".as_bytes().try_into().unwrap());
        let context = SecurityContext {
            security: &credentials,
            device: &device,
            security_support: &security_support,
            config: &config,
            bss: &bss,
        };
        assert!(context.authenticator_supplicant_rsne().is_ok());
        assert!(matches!(context.authentication_config(), Ok(auth::Config::Sae { .. })));

        let protection = Protection::try_from(context).unwrap();
        assert_variant!(protection, Protection::Rsna(rsna) => {
            assert_eq!(rsna.supplicant.get_auth_method(), auth::MethodName::Sae);
        });
    }

    #[test]
    fn wpa3_personal_passphrase_rsna_driver_auth() {
        let device = crate::test_utils::fake_device_info([1u8; 6].into());
        let mut security_support = fake_security_support_empty();
        security_support.mfp.supported = true;
        security_support.sae.driver_handler_supported = true;
        let config = ClientConfig { wpa3_supported: true, ..Default::default() };
        let bss = fake_bss_description!(Wpa3);
        let credentials =
            wpa::Wpa3PersonalCredentials::Passphrase("password".as_bytes().try_into().unwrap());
        let context = SecurityContext {
            security: &credentials,
            device: &device,
            security_support: &security_support,
            config: &config,
            bss: &bss,
        };
        assert!(context.authenticator_supplicant_rsne().is_ok());
        assert!(matches!(context.authentication_config(), Ok(auth::Config::DriverSae { .. })));

        let protection = Protection::try_from(context).unwrap();
        assert_variant!(protection, Protection::Rsna(rsna) => {
            assert_eq!(rsna.supplicant.get_auth_method(), auth::MethodName::Sae);
        });
    }

    #[test]
    fn wpa3_personal_passphrase_prefer_sme_auth() {
        let device = crate::test_utils::fake_device_info([1u8; 6].into());
        let mut security_support = fake_security_support_empty();
        security_support.mfp.supported = true;
        security_support.sae.driver_handler_supported = true;
        security_support.sae.sme_handler_supported = true;
        let config = ClientConfig { wpa3_supported: true, ..Default::default() };
        let bss = fake_bss_description!(Wpa3);
        let credentials =
            wpa::Wpa3PersonalCredentials::Passphrase("password".as_bytes().try_into().unwrap());
        let context = SecurityContext {
            security: &credentials,
            device: &device,
            security_support: &security_support,
            config: &config,
            bss: &bss,
        };
        assert!(matches!(context.authentication_config(), Ok(auth::Config::Sae { .. })));
    }

    #[test]
    fn wpa3_personal_passphrase_no_security_support_features() {
        let device = crate::test_utils::fake_device_info([1u8; 6].into());
        let security_support = fake_security_support_empty();
        let config = Default::default();
        let bss = fake_bss_description!(Wpa3);
        let credentials =
            wpa::Wpa3PersonalCredentials::Passphrase("password".as_bytes().try_into().unwrap());
        let context = SecurityContext {
            security: &credentials,
            device: &device,
            security_support: &security_support,
            config: &config,
            bss: &bss,
        };
        let _ = context
            .authentication_config()
            .expect_err("created WPA3 auth config for incompatible device");
    }
}