Skip to main content

wlan_hw_sim/
lib.rs

1// Copyright 2021 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use crate::event::action::{self, AuthenticationControl, AuthenticationTap};
6use crate::event::{Handler, branch};
7use fidl::endpoints::{create_endpoints, create_proxy};
8use fidl_fuchsia_sys2 as _;
9use fidl_fuchsia_wlan_common::WlanMacRole;
10use fidl_fuchsia_wlan_ieee80211 as fidl_ieee80211;
11use fidl_fuchsia_wlan_mlme as fidl_mlme;
12use fidl_fuchsia_wlan_policy as fidl_policy;
13use fidl_fuchsia_wlan_softmac as fidl_wlan_softmac;
14use fidl_fuchsia_wlan_tap::{WlanRxInfo, WlantapPhyConfig, WlantapPhyProxy};
15use fuchsia_component::client::connect_to_protocol_at;
16use ieee80211::{Bssid, MacAddr, Ssid};
17use std::future::Future;
18use std::pin::pin;
19use std::sync::LazyLock;
20use wlan_common::bss::Protection;
21use wlan_common::channel::{Cbw, Channel};
22use wlan_common::ie::rsn::cipher::{CIPHER_CCMP_128, CIPHER_TKIP, Cipher};
23use wlan_common::ie::rsn::rsne;
24use wlan_common::ie::rsn::suite_filter::DEFAULT_GROUP_MGMT_CIPHER;
25use wlan_common::ie::wpa;
26use wlan_common::{TimeUnit, data_writer, mac, mgmt_writer};
27use wlan_frame_writer::write_frame_to_vec;
28use wlan_rsn::rsna::UpdateSink;
29
30pub mod event;
31pub mod netdevice_helper;
32pub mod test_utils;
33
34pub use wlancfg_helper::*;
35
36mod config;
37mod wlancfg_helper;
38
39pub const PSK_STR_LEN: usize = 64;
40
41pub static CLIENT_MAC_ADDR: LazyLock<MacAddr> =
42    LazyLock::new(|| [0x67, 0x62, 0x6f, 0x6e, 0x69, 0x6b].into());
43pub static AP_MAC_ADDR: LazyLock<Bssid> =
44    LazyLock::new(|| [0x70, 0xf1, 0x1c, 0x05, 0x2d, 0x7f].into());
45pub static AP_SSID: LazyLock<Ssid> = LazyLock::new(|| Ssid::try_from("ap_ssid").unwrap());
46pub static ETH_DST_MAC: LazyLock<MacAddr> =
47    LazyLock::new(|| [0x65, 0x74, 0x68, 0x64, 0x73, 0x74].into());
48
49pub const WLANCFG_DEFAULT_AP_CHANNEL: Channel =
50    Channel::new(11, Cbw::Cbw20, fidl_ieee80211::WlanBand::TwoGhz);
51
52// TODO(https://fxbug.dev/42060050): This sleep was introduced to preserve the old timing behavior
53// of scanning when hw-sim depending on the SoftMAC driver iterating through all of the
54// channels.
55pub static ARTIFICIAL_SCAN_SLEEP: LazyLock<zx::MonotonicDuration> =
56    LazyLock::new(|| zx::MonotonicDuration::from_seconds(2));
57
58// Once a client interface is available for scanning, it takes up to around 30s for a scan
59// to complete (see https://fxbug.dev/42061276). Allow at least double that amount of time to reduce
60// flakiness and longer than the timeout WLAN policy should have.
61pub static SCAN_RESPONSE_TEST_TIMEOUT: LazyLock<zx::MonotonicDuration> =
62    LazyLock::new(|| zx::MonotonicDuration::from_seconds(70));
63
64/// A client supplicant.
65///
66/// Provides the client and security components necessary to attempt a connection via Policy.
67pub struct Supplicant<'a> {
68    pub controller: &'a fidl_policy::ClientControllerProxy,
69    pub state_update_stream: &'a mut fidl_policy::ClientStateUpdatesRequestStream,
70    pub security_type: fidl_policy::SecurityType,
71    pub password: Option<&'a str>,
72}
73
74impl<'a> Supplicant<'a> {
75    /// Clones the supplicant through reborrowing of mutable references.
76    ///
77    /// # Examples
78    ///
79    /// This function can be used for templating.
80    ///
81    /// ```rust,ignore
82    /// let mut supplicant = Supplicant { /* ... */ }; // Template.
83    /// // ...
84    /// // Connect via the template supplicant but with a particular password.
85    /// let _ = connect(Supplicant { password: "********", ..supplicant.reborrow() });
86    /// ```
87    pub fn reborrow(&mut self) -> Supplicant<'_> {
88        Supplicant {
89            controller: self.controller,
90            state_update_stream: &mut *self.state_update_stream,
91            security_type: self.security_type,
92            password: self.password,
93        }
94    }
95}
96
97pub fn default_wlantap_config_client() -> WlantapPhyConfig {
98    wlantap_config_client(format!("wlantap-client"), *CLIENT_MAC_ADDR)
99}
100
101pub fn wlantap_config_client(name: String, mac_addr: MacAddr) -> WlantapPhyConfig {
102    config::create_wlantap_config(name, mac_addr, WlanMacRole::Client)
103}
104
105pub fn default_wlantap_config_ap() -> WlantapPhyConfig {
106    wlantap_config_ap(format!("wlantap-ap"), (*AP_MAC_ADDR).into())
107}
108
109pub fn wlantap_config_ap(name: String, mac_addr: MacAddr) -> WlantapPhyConfig {
110    config::create_wlantap_config(name, mac_addr, WlanMacRole::Ap)
111}
112
113pub fn rx_info_with_default_ap() -> WlanRxInfo {
114    rx_info_with_valid_rssi(&WLANCFG_DEFAULT_AP_CHANNEL, 0)
115}
116
117fn rx_info_with_valid_rssi(channel: &Channel, rssi_dbm: i8) -> WlanRxInfo {
118    let (cbw, secondary80_num) = channel.cbw.to_fidl();
119    WlanRxInfo {
120        rx_flags: 0,
121        valid_fields: if rssi_dbm == 0 {
122            0
123        } else {
124            fidl_wlan_softmac::WlanRxInfoValid::RSSI.bits()
125        },
126        phy: fidl_ieee80211::WlanPhyType::Dsss,
127        data_rate: 0,
128        primary: (*channel).into(),
129        mcs: 0,
130        rssi_dbm,
131        snr_dbh: 0,
132        bandwidth: cbw,
133        vht_secondary_80_channel: fidl_ieee80211::ChannelNumber {
134            band: channel.band,
135            number: secondary80_num,
136        },
137    }
138}
139
140pub fn send_sae_authentication_frame(
141    sae_frame: &fidl_mlme::SaeFrame,
142    channel: &Channel,
143    bssid: &Bssid,
144    proxy: &WlantapPhyProxy,
145) -> Result<(), anyhow::Error> {
146    let buffer = write_frame_to_vec!({
147        headers: {
148            mac::MgmtHdr: &mgmt_writer::mgmt_hdr_from_ap(
149                mac::FrameControl(0)
150                    .with_frame_type(mac::FrameType::MGMT)
151                    .with_mgmt_subtype(mac::MgmtSubtype::AUTH),
152                *CLIENT_MAC_ADDR,
153                bssid.clone().into(),
154                mac::SequenceControl(0).with_seq_num(123),
155            ),
156            mac::AuthHdr: &mac::AuthHdr {
157                auth_alg_num: mac::AuthAlgorithmNumber::SAE,
158                auth_txn_seq_num: sae_frame.seq_num,
159                status_code: sae_frame.status_code.into(),
160            },
161        },
162        body: &sae_frame.sae_fields[..],
163    })?;
164    proxy.rx(&buffer, &rx_info_with_valid_rssi(channel, 0))?;
165    Ok(())
166}
167
168pub fn send_open_authentication(
169    channel: &Channel,
170    bssid: &Bssid,
171    status_code: impl Into<mac::StatusCode>,
172    proxy: &WlantapPhyProxy,
173) -> Result<(), anyhow::Error> {
174    let buffer = write_frame_to_vec!({
175        headers: {
176            mac::MgmtHdr: &mgmt_writer::mgmt_hdr_from_ap(
177                mac::FrameControl(0)
178                    .with_frame_type(mac::FrameType::MGMT)
179                    .with_mgmt_subtype(mac::MgmtSubtype::AUTH),
180                *CLIENT_MAC_ADDR,
181                bssid.clone().into(),
182                mac::SequenceControl(0).with_seq_num(123),
183            ),
184            mac::AuthHdr: &mac::AuthHdr {
185                auth_alg_num: mac::AuthAlgorithmNumber::OPEN,
186                auth_txn_seq_num: 2,
187                status_code: status_code.into(),
188            },
189        },
190    })?;
191    proxy.rx(&buffer, &rx_info_with_valid_rssi(channel, 0))?;
192    Ok(())
193}
194
195pub fn send_association_response(
196    channel: &Channel,
197    bssid: &Bssid,
198    status_code: impl Into<mac::StatusCode>,
199    proxy: &WlantapPhyProxy,
200) -> Result<(), anyhow::Error> {
201    let buffer = write_frame_to_vec!({
202        headers: {
203            mac::MgmtHdr: &mgmt_writer::mgmt_hdr_from_ap(
204                mac::FrameControl(0)
205                    .with_frame_type(mac::FrameType::MGMT)
206                    .with_mgmt_subtype(mac::MgmtSubtype::ASSOC_RESP),
207                *CLIENT_MAC_ADDR,
208                bssid.clone().into(),
209                mac::SequenceControl(0).with_seq_num(123),
210            ),
211            mac::AssocRespHdr: &mac::AssocRespHdr {
212                capabilities: mac::CapabilityInfo(0).with_ess(true).with_short_preamble(true),
213                status_code: status_code.into(),
214                aid: 2, // does not matter
215            },
216        },
217        ies: {
218            // These rates will be captured in assoc_cfg to initialize Minstrel. 11b rates are
219            // ignored.
220            // tx_vec_idx:        _     _     _   129   130     _   131   132
221            supported_rates: &[0x82, 0x84, 0x8b, 0x0c, 0x12, 0x96, 0x18, 0x24],
222            // tx_vec_idx:              133 134 basic_135  136
223            extended_supported_rates:  &[48, 72, 128 + 96, 108],
224        },
225    })?;
226    proxy.rx(&buffer, &rx_info_with_valid_rssi(channel, 0))?;
227    Ok(())
228}
229
230pub fn send_disassociate(
231    channel: &Channel,
232    bssid: &Bssid,
233    reason_code: impl Into<mac::ReasonCode>,
234    proxy: &WlantapPhyProxy,
235) -> Result<(), anyhow::Error> {
236    let buffer = write_frame_to_vec!({
237        headers: {
238            mac::MgmtHdr: &mgmt_writer::mgmt_hdr_from_ap(
239                mac::FrameControl(0)
240                    .with_frame_type(mac::FrameType::MGMT)
241                    .with_mgmt_subtype(mac::MgmtSubtype::DISASSOC),
242                *CLIENT_MAC_ADDR,
243                bssid.clone().into(),
244                mac::SequenceControl(0).with_seq_num(123),
245            ),
246            mac::DisassocHdr: &mac::DisassocHdr {
247                reason_code: reason_code.into(),
248            },
249        },
250    })?;
251    proxy.rx(&buffer, &rx_info_with_valid_rssi(channel, 0))?;
252    Ok(())
253}
254
255pub fn password_or_psk_to_policy_credential<S: ToString>(
256    password_or_psk: Option<S>,
257) -> fidl_policy::Credential {
258    return match password_or_psk {
259        None => fidl_policy::Credential::None(fidl_policy::Empty),
260        Some(p) => {
261            let p = p.to_string().as_bytes().to_vec();
262            if p.len() == PSK_STR_LEN {
263                // The PSK is given in a 64 character hexadecimal string.
264                let psk = hex::decode(p).expect("Failed to decode psk");
265                fidl_policy::Credential::Psk(psk)
266            } else {
267                fidl_policy::Credential::Password(p)
268            }
269        }
270    };
271}
272
273pub fn create_authenticator(
274    bssid: &Bssid,
275    ssid: &Ssid,
276    password_or_psk: &str,
277    // The group key cipher
278    gtk_cipher: Cipher,
279    // The advertised protection in the IEs during the 4-way handshake
280    advertised_protection: Protection,
281    // The protection used for the actual handshake
282    supplicant_protection: Protection,
283) -> wlan_rsn::Authenticator {
284    let nonce_rdr =
285        wlan_rsn::nonce::NonceReader::new(&bssid.clone().into()).expect("creating nonce reader");
286    let gtk_provider = wlan_rsn::GtkProvider::new(gtk_cipher, 1, 0).expect("creating gtk provider");
287
288    let advertised_protection_info = match advertised_protection {
289        Protection::Wpa3Personal => wlan_rsn::ProtectionInfo::Rsne(rsne::Rsne::wpa3_rsne()),
290        Protection::Wpa2Wpa3Personal => {
291            wlan_rsn::ProtectionInfo::Rsne(rsne::Rsne::wpa2_wpa3_rsne())
292        }
293        Protection::Wpa2Personal | Protection::Wpa1Wpa2Personal => wlan_rsn::ProtectionInfo::Rsne(
294            rsne::Rsne::wpa2_rsne_with_caps(rsne::RsnCapabilities(0)),
295        ),
296        Protection::Wpa2PersonalTkipOnly | Protection::Wpa1Wpa2PersonalTkipOnly => {
297            panic!("need tkip support")
298        }
299        Protection::Wpa1 => {
300            wlan_rsn::ProtectionInfo::LegacyWpa(wpa::fake_wpa_ies::fake_deprecated_wpa1_vendor_ie())
301        }
302        _ => {
303            panic!("{} not implemented", advertised_protection)
304        }
305    };
306
307    match supplicant_protection {
308        Protection::Wpa1 | Protection::Wpa2Personal => {
309            let psk = match password_or_psk.len() {
310                PSK_STR_LEN => {
311                    // The PSK is given in a 64 character hexadecimal string.
312                    hex::decode(password_or_psk).expect("Failed to decode psk").into_boxed_slice()
313                }
314                _ => {
315                    wlan_rsn::psk::compute(password_or_psk.as_bytes(), ssid).expect("computing PSK")
316                }
317            };
318            let supplicant_protection_info = match supplicant_protection {
319                Protection::Wpa1 => wlan_rsn::ProtectionInfo::LegacyWpa(
320                    wpa::fake_wpa_ies::fake_deprecated_wpa1_vendor_ie(),
321                ),
322                Protection::Wpa2Personal => wlan_rsn::ProtectionInfo::Rsne(
323                    rsne::Rsne::wpa2_rsne_with_caps(rsne::RsnCapabilities(0)),
324                ),
325                _ => unreachable!("impossible combination in this nested match"),
326            };
327            wlan_rsn::Authenticator::new_wpa2psk_ccmp128(
328                nonce_rdr,
329                std::sync::Arc::new(fuchsia_sync::Mutex::new(gtk_provider)),
330                psk,
331                *CLIENT_MAC_ADDR,
332                supplicant_protection_info,
333                bssid.clone().into(),
334                advertised_protection_info,
335            )
336            .expect("creating authenticator")
337        }
338        Protection::Wpa3Personal => {
339            let igtk_provider = wlan_rsn::IgtkProvider::new(DEFAULT_GROUP_MGMT_CIPHER)
340                .expect("creating igtk provider");
341            let supplicant_protection_info =
342                wlan_rsn::ProtectionInfo::Rsne(rsne::Rsne::wpa3_rsne());
343            wlan_rsn::Authenticator::new_wpa3(
344                nonce_rdr,
345                std::sync::Arc::new(fuchsia_sync::Mutex::new(gtk_provider)),
346                std::sync::Arc::new(fuchsia_sync::Mutex::new(igtk_provider)),
347                ssid.clone(),
348                password_or_psk.as_bytes().to_vec(),
349                *CLIENT_MAC_ADDR,
350                supplicant_protection_info,
351                bssid.clone().into(),
352                advertised_protection_info,
353            )
354            .expect("creating authenticator")
355        }
356        _ => {
357            panic!("Cannot create an authenticator for {}", supplicant_protection)
358        }
359    }
360}
361
362pub enum ApAdvertisementMode {
363    Beacon,
364    ProbeResponse,
365}
366
367pub trait ApAdvertisement {
368    fn mode(&self) -> ApAdvertisementMode;
369    fn channel(&self) -> &Channel;
370    fn bssid(&self) -> &Bssid;
371    fn ssid(&self) -> &Ssid;
372    fn protection(&self) -> &Protection;
373    fn rssi_dbm(&self) -> i8;
374    fn wsc_ie(&self) -> Option<&Vec<u8>>;
375
376    fn beacon_interval(&self) -> TimeUnit {
377        TimeUnit::DEFAULT_BEACON_INTERVAL * 20u16
378    }
379
380    fn capabilities(&self) -> mac::CapabilityInfo {
381        mac::CapabilityInfo(0)
382            // IEEE Std 802.11-2016, 9.4.1.4: An AP sets the ESS subfield to 1 and the IBSS
383            // subfield to 0 within transmitted Beacon or Probe Response frames.
384            .with_ess(true)
385            .with_ibss(false)
386            // IEEE Std 802.11-2016, 9.4.1.4: An AP sets the Privacy subfield to 1 within
387            // transmitted Beacon, Probe Response, (Re)Association Response frames if data
388            // confidentiality is required for all Data frames exchanged within the BSS.
389            .with_privacy(*self.protection() != Protection::Open)
390    }
391
392    fn send(&self, phy: &WlantapPhyProxy) -> Result<(), anyhow::Error> {
393        let buffer = self.generate_frame()?;
394        phy.rx(&buffer, &rx_info_with_valid_rssi(&self.channel(), self.rssi_dbm()))?;
395        Ok(())
396    }
397
398    fn generate_frame(&self) -> Result<Vec<u8>, anyhow::Error> {
399        let mode = self.mode();
400        let protection = self.protection();
401        let beacon_header = match mode {
402            ApAdvertisementMode::Beacon => {
403                Some(mac::BeaconHdr::new(self.beacon_interval(), self.capabilities()))
404            }
405            _ => None,
406        };
407        let probe_response_header = match mode {
408            ApAdvertisementMode::ProbeResponse => {
409                Some(mac::ProbeRespHdr::new(self.beacon_interval(), self.capabilities()))
410            }
411            _ => None,
412        };
413
414        let buffer = write_frame_to_vec!({
415            headers: {
416                mac::MgmtHdr: &mgmt_writer::mgmt_hdr_from_ap(
417                    mac::FrameControl(0)
418                        .with_frame_type(mac::FrameType::MGMT)
419                        .with_mgmt_subtype(match mode {
420                            ApAdvertisementMode::Beacon => mac::MgmtSubtype::BEACON,
421                            ApAdvertisementMode::ProbeResponse{..} => mac::MgmtSubtype::PROBE_RESP
422                        }),
423                    match mode {
424                        ApAdvertisementMode::Beacon => ieee80211::BROADCAST_ADDR,
425                        ApAdvertisementMode::ProbeResponse{..} => *CLIENT_MAC_ADDR
426                    },
427                    *self.bssid(),
428                    mac::SequenceControl(0).with_seq_num(123),
429                ),
430                mac::BeaconHdr?: beacon_header,
431                mac::ProbeRespHdr?: probe_response_header,
432            },
433            ies: {
434                ssid: &self.ssid(),
435                supported_rates: &[0x82, 0x84, 0x8b, 0x0c, 0x12, 0x96, 0x18, 0x24, 0x30, 0x48, 0xe0, 0x6c],
436                extended_supported_rates: { /* continues from supported_rates */ },
437                dsss_param_set: &ie::DsssParamSet { current_channel: self.channel().primary },
438                rsne?: match protection {
439                    Protection::Unknown => panic!("Cannot send beacon with unknown protection"),
440                    Protection::Open | Protection::Wep | Protection::Wpa1 => None,
441                    Protection::Wpa1Wpa2Personal | Protection::Wpa2Personal =>
442                        Some(rsne::Rsne::wpa2_rsne_with_caps(rsne::RsnCapabilities(0))),
443                    Protection::Wpa2Wpa3Personal => Some(rsne::Rsne::wpa2_wpa3_rsne()),
444                    Protection::Wpa3Personal => Some(rsne::Rsne::wpa3_rsne()),
445                    _ => panic!("unsupported fake beacon: {:?}", protection),
446                },
447                wpa1?: match protection {
448                    Protection::Unknown => panic!("Cannot send beacon with unknown protection"),
449                    Protection::Open | Protection::Wep => None,
450                    Protection::Wpa1 | Protection::Wpa1Wpa2Personal => Some(wpa::fake_wpa_ies::fake_deprecated_wpa1_vendor_ie()),
451                    Protection::Wpa2Personal | Protection::Wpa2Wpa3Personal | Protection::Wpa3Personal => None,
452                    _ => panic!("unsupported fake beacon: {:?}", protection),
453                },
454                wsc?: self.wsc_ie()
455            },
456        })?;
457        Ok(buffer.into())
458    }
459}
460
461pub struct Beacon {
462    pub channel: Channel,
463    pub bssid: Bssid,
464    pub ssid: Ssid,
465    pub protection: Protection,
466    pub rssi_dbm: i8,
467}
468
469impl ApAdvertisement for Beacon {
470    fn mode(&self) -> ApAdvertisementMode {
471        ApAdvertisementMode::Beacon
472    }
473    fn channel(&self) -> &Channel {
474        &self.channel
475    }
476    fn bssid(&self) -> &Bssid {
477        &self.bssid
478    }
479    fn ssid(&self) -> &Ssid {
480        &self.ssid
481    }
482    fn protection(&self) -> &Protection {
483        &self.protection
484    }
485    fn rssi_dbm(&self) -> i8 {
486        self.rssi_dbm
487    }
488    fn wsc_ie(&self) -> Option<&Vec<u8>> {
489        None
490    }
491}
492
493pub struct ProbeResponse {
494    pub channel: Channel,
495    pub bssid: Bssid,
496    pub ssid: Ssid,
497    pub protection: Protection,
498    pub rssi_dbm: i8,
499    pub wsc_ie: Option<Vec<u8>>,
500}
501
502impl ApAdvertisement for ProbeResponse {
503    fn mode(&self) -> ApAdvertisementMode {
504        ApAdvertisementMode::ProbeResponse
505    }
506    fn channel(&self) -> &Channel {
507        &self.channel
508    }
509    fn bssid(&self) -> &Bssid {
510        &self.bssid
511    }
512    fn ssid(&self) -> &Ssid {
513        &self.ssid
514    }
515    fn protection(&self) -> &Protection {
516        &self.protection
517    }
518    fn rssi_dbm(&self) -> i8 {
519        self.rssi_dbm
520    }
521    fn wsc_ie(&self) -> Option<&Vec<u8>> {
522        self.wsc_ie.as_ref()
523    }
524}
525
526pub async fn save_network_and_wait_until_connected(
527    test_ns_prefix: &str,
528    ssid: &Ssid,
529    security_type: fidl_policy::SecurityType,
530    credential: fidl_policy::Credential,
531) -> (fidl_policy::ClientControllerProxy, fidl_policy::ClientStateUpdatesRequestStream) {
532    // Connect to the client policy service and get a client controller.
533    let (client_controller, mut client_state_update_stream) =
534        wlancfg_helper::init_client_controller(test_ns_prefix).await;
535
536    save_network(&client_controller, ssid, security_type, credential).await;
537
538    // Wait until the policy layer indicates that the client has successfully connected.
539    let id = fidl_policy::NetworkIdentifier { ssid: ssid.to_vec(), type_: security_type.clone() };
540    wait_until_client_state(&mut client_state_update_stream, |update| {
541        has_id_and_state(update, &id, fidl_policy::ConnectionState::Connected)
542    })
543    .await;
544
545    (client_controller, client_state_update_stream)
546}
547
548/// Runs a future until completion or timeout with a client event handler that attempts to connect
549/// to an AP with the given SSID, BSSID, and protection.
550pub async fn connect_or_timeout_with<F>(
551    helper: &mut test_utils::TestHelper,
552    timeout: zx::MonotonicDuration,
553    ssid: &Ssid,
554    bssid: &Bssid,
555    protection: &Protection,
556    authenticator: Option<wlan_rsn::Authenticator>,
557    future: F,
558) -> F::Output
559where
560    F: Future + Unpin,
561{
562    let phy = helper.proxy();
563    let channel = Channel::new(1, Cbw::Cbw20, fidl_ieee80211::WlanBand::TwoGhz);
564    let beacons = [Beacon {
565        channel,
566        bssid: bssid.clone(),
567        ssid: ssid.clone(),
568        protection: protection.clone(),
569        rssi_dbm: -30,
570    }];
571    let mut control = authenticator
572        .map(|authenticator| AuthenticationControl { updates: UpdateSink::new(), authenticator });
573    let connect = if let Some(ref mut control) = control {
574        let tap = AuthenticationTap { control, handler: action::authenticate_with_control_state() };
575        event::boxed(action::connect_with_authentication_tap(
576            &phy, ssid, bssid, &channel, protection, tap,
577        ))
578    } else {
579        event::boxed(action::connect_with_open_authentication(
580            &phy, ssid, bssid, &channel, protection,
581        ))
582    };
583    helper
584        .run_until_complete_or_timeout(
585            timeout,
586            format!(
587                "connecting to {} ({:02X?}) with {:?} protection",
588                ssid.to_string_not_redactable(),
589                bssid,
590                protection,
591            ),
592            branch::or((
593                event::on_scan(action::send_advertisements_and_scan_completion(&phy, beacons)),
594                event::on_transmit(connect),
595            ))
596            .expect("failed to connect client"),
597            future,
598        )
599        .await
600}
601
602/// Waits for a timeout or Policy to establish a connection to an AP with the given SSID, BSSID,
603/// and protection.
604pub async fn connect_or_timeout(
605    helper: &mut test_utils::TestHelper,
606    timeout: zx::MonotonicDuration,
607    ssid: &Ssid,
608    bssid: &Bssid,
609    bss_protection: &Protection,
610    password_or_psk: Option<&str>,
611    security_type: fidl_policy::SecurityType,
612) {
613    let authenticator = match bss_protection {
614        Protection::Wpa3Personal | Protection::Wpa2Wpa3Personal => {
615            password_or_psk.map(|password_or_psk| {
616                create_authenticator(
617                    bssid,
618                    ssid,
619                    password_or_psk,
620                    CIPHER_CCMP_128,
621                    *bss_protection,
622                    Protection::Wpa3Personal,
623                )
624            })
625        }
626        Protection::Wpa2Personal | Protection::Wpa1Wpa2Personal => {
627            password_or_psk.map(|password_or_psk| {
628                create_authenticator(
629                    bssid,
630                    ssid,
631                    password_or_psk,
632                    CIPHER_CCMP_128,
633                    *bss_protection,
634                    Protection::Wpa2Personal,
635                )
636            })
637        }
638        Protection::Wpa2PersonalTkipOnly | Protection::Wpa1Wpa2PersonalTkipOnly => {
639            panic!("Hardware simulator does not support WPA2-TKIP.")
640        }
641        Protection::Wpa1 => password_or_psk.map(|password_or_psk| {
642            create_authenticator(
643                bssid,
644                ssid,
645                password_or_psk,
646                CIPHER_TKIP,
647                *bss_protection,
648                Protection::Wpa1,
649            )
650        }),
651        Protection::Open => None,
652        _ => {
653            panic!("Unsupported WLAN protection: {}", bss_protection)
654        }
655    };
656
657    let credential = password_or_psk_to_policy_credential(password_or_psk);
658    let test_ns_prefix = helper.test_ns_prefix().to_string();
659    let connect = pin!(save_network_and_wait_until_connected(
660        &test_ns_prefix,
661        ssid,
662        security_type,
663        credential
664    ));
665    connect_or_timeout_with(helper, timeout, ssid, bssid, bss_protection, authenticator, connect)
666        .await;
667}
668
669pub fn rx_wlan_data_frame(
670    channel: &Channel,
671    addr1: &MacAddr,
672    addr2: &MacAddr,
673    addr3: &MacAddr,
674    payload: &[u8],
675    ether_type: u16,
676    phy: &WlantapPhyProxy,
677) -> Result<(), anyhow::Error> {
678    let buffer = write_frame_to_vec!({
679        headers: {
680            mac::FixedDataHdrFields: &mac::FixedDataHdrFields {
681                frame_ctrl: mac::FrameControl(0)
682                    .with_frame_type(mac::FrameType::DATA)
683                    .with_data_subtype(mac::DataSubtype(0))
684                    .with_from_ds(true),
685                duration: 0,
686                addr1: *addr1,
687                addr2: *addr2,
688                addr3: *addr3,
689                seq_ctrl: mac::SequenceControl(0).with_seq_num(3),
690            },
691            mac::LlcHdr: &data_writer::make_snap_llc_hdr(ether_type),
692        },
693        payload: payload,
694    })?;
695
696    phy.rx(&buffer, &rx_info_with_valid_rssi(channel, 0))?;
697    Ok(())
698}
699
700pub async fn loop_until_iface_is_found(helper: &mut test_utils::TestHelper) {
701    // Connect to the client policy service and get a client controller.
702    let policy_provider =
703        connect_to_protocol_at::<fidl_policy::ClientProviderMarker>(helper.test_ns_prefix())
704            .expect("connecting to wlan policy");
705    let (client_controller, server_end) = create_proxy();
706    let (update_client_end, _update_server_end) = create_endpoints();
707    let () =
708        policy_provider.get_controller(server_end, update_client_end).expect("getting controller");
709
710    // Attempt to issue a scan command until the request succeeds.  Scanning will fail until a
711    // client interface is available.  A successful response to a scan request indicates that the
712    // client policy layer is ready to use.
713    // TODO(https://fxbug.dev/42135259): Figure out a new way to signal that the client policy layer is ready to go.
714    let mut retry = test_utils::RetryWithBackoff::infinite_with_max_interval(
715        zx::MonotonicDuration::from_seconds(10),
716    );
717    loop {
718        let (scan_proxy, server_end) = create_proxy();
719        client_controller.scan_for_networks(server_end).expect("requesting scan");
720
721        let fut = pin!(async move { scan_proxy.get_next().await.expect("getting scan results") });
722
723        let phy = helper.proxy();
724        match helper
725            .run_until_complete_or_timeout(
726                *SCAN_RESPONSE_TEST_TIMEOUT,
727                "receive a scan response",
728                event::on_scan(action::send_advertisements_and_scan_completion(
729                    &phy,
730                    [] as [Beacon; 0],
731                )),
732                fut,
733            )
734            .await
735        {
736            Err(_) => {
737                retry.sleep_unless_after_deadline().await.unwrap_or_else(|_| {
738                    panic!("Wlanstack did not recognize the interface in time")
739                });
740            }
741            Ok(_) => return,
742        }
743    }
744}