Skip to main content

esp_radio/wifi/sta/
eap.rs

1//! Wi-Fi extensible authentication protocol.
2
3use alloc::string::String;
4use core::fmt;
5
6use procmacros::BuilderLite;
7
8use super::ScanMethod;
9use crate::{
10    WifiError,
11    wifi::{AuthenticationMethod, Protocols, Ssid},
12};
13
14/// Configuration for EAP-FAST authentication protocol.
15#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
16#[cfg_attr(feature = "defmt", derive(defmt::Format))]
17#[instability::unstable]
18pub struct EapFastConfig {
19    /// Specifies the provisioning mode for EAP-FAST.
20    pub fast_provisioning: u8,
21    /// The maximum length of the PAC (Protected Access Credentials) list.
22    pub fast_max_pac_list_len: u8,
23    /// Indicates whether the PAC file is in binary format.
24    pub fast_pac_format_binary: bool,
25}
26
27/// Phase 2 authentication methods
28#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
29#[cfg_attr(feature = "defmt", derive(defmt::Format))]
30#[instability::unstable]
31pub enum TtlsPhase2Method {
32    /// EAP (Extensible Authentication Protocol).
33    Eap,
34    /// MSCHAPv2 (Microsoft Challenge Handshake Authentication Protocol 2).
35    Mschapv2,
36    /// MSCHAP (Microsoft Challenge Handshake Authentication Protocol).
37    Mschap,
38    /// PAP (Password Authentication Protocol).
39    Pap,
40    /// CHAP (Challenge Handshake Authentication Protocol).
41    Chap,
42}
43
44impl TtlsPhase2Method {
45    /// Maps the phase 2 method to a raw `u32` representation.
46    pub(crate) fn to_raw(self) -> u32 {
47        match self {
48            TtlsPhase2Method::Eap => {
49                crate::sys::include::esp_eap_ttls_phase2_types_ESP_EAP_TTLS_PHASE2_EAP
50            }
51            TtlsPhase2Method::Mschapv2 => {
52                crate::sys::include::esp_eap_ttls_phase2_types_ESP_EAP_TTLS_PHASE2_MSCHAPV2
53            }
54            TtlsPhase2Method::Mschap => {
55                crate::sys::include::esp_eap_ttls_phase2_types_ESP_EAP_TTLS_PHASE2_MSCHAP
56            }
57            TtlsPhase2Method::Pap => {
58                crate::sys::include::esp_eap_ttls_phase2_types_ESP_EAP_TTLS_PHASE2_PAP
59            }
60            TtlsPhase2Method::Chap => {
61                crate::sys::include::esp_eap_ttls_phase2_types_ESP_EAP_TTLS_PHASE2_CHAP
62            }
63        }
64    }
65}
66
67type CertificateAndKey = (&'static [u8], &'static [u8], Option<&'static [u8]>);
68
69/// Configuration for an EAP (Extensible Authentication Protocol) station.
70#[derive(BuilderLite, Clone, PartialEq, Eq, Hash)]
71#[instability::unstable]
72pub struct EapStationConfig {
73    /// The SSID of the network the station is connecting to.
74    pub(crate) ssid: Ssid,
75    /// The BSSID (MAC Address) of the specific access point.
76    pub(crate) bssid: Option<[u8; 6]>,
77    /// The authentication method used for EAP.
78    pub(crate) auth_method: AuthenticationMethod,
79    /// The identity used during authentication.
80    #[builder_lite(reference)]
81    pub(crate) identity: Option<String>,
82    /// The username used for inner authentication.
83    /// Some EAP methods require a username for authentication.
84    #[builder_lite(reference)]
85    pub(crate) username: Option<String>,
86    /// The password used for inner authentication.
87    #[builder_lite(reference)]
88    pub(crate) password: Option<String>,
89    /// A new password to be set during the authentication process.
90    /// Some methods support password changes during authentication.
91    #[builder_lite(reference)]
92    pub(crate) new_password: Option<String>,
93    /// Configuration for EAP-FAST.
94    #[builder_lite(reference)]
95    pub(crate) eap_fast_config: Option<EapFastConfig>,
96    /// A PAC (Protected Access Credential) file for EAP-FAST.
97    pub(crate) pac_file: Option<&'static [u8]>,
98    /// A boolean flag indicating whether time checking is enforced during
99    /// authentication.
100    pub(crate) time_check: bool,
101    /// A CA (Certificate Authority) certificate for validating the
102    /// authentication server's certificate.
103    pub(crate) ca_cert: Option<&'static [u8]>,
104    /// A tuple containing the station's certificate, private key, and an
105    /// intermediate certificate.
106    pub(crate) certificate_and_key: Option<CertificateAndKey>,
107    /// The Phase 2 authentication method used for EAP-TTLS.
108    #[builder_lite(reference)]
109    pub(crate) ttls_phase2_method: Option<TtlsPhase2Method>,
110    /// The specific Wi-Fi channel to use for the connection.
111    pub(crate) channel: Option<u8>,
112    /// The set of protocols supported by the access point.
113    pub(crate) protocols: Protocols,
114    /// Interval for station to listen to beacon from access point.
115    ///
116    /// The unit of listen interval is one beacon interval.
117    /// For example, if beacon interval is 100 ms and listen interval is 3,
118    /// the interval for station to listen to beacon is 300 ms
119    #[builder_lite(unstable)]
120    pub(crate) listen_interval: u16,
121    /// Time to disconnect from access point if no data is received.
122    ///
123    /// Must be between 6 and 31.
124    #[builder_lite(unstable)]
125    pub(crate) beacon_timeout: u16,
126    /// Number of connection retries station will do before moving to next access point.
127    ///
128    /// `scan_method` should be set as [`ScanMethod::AllChannels`] to use this config.
129    ///
130    /// Note: Enabling this may cause connection time to increase in case the best access point
131    /// doesn't behave properly.
132    #[builder_lite(unstable)]
133    pub(crate) failure_retry_cnt: u8,
134    /// Scan method.
135    #[builder_lite(unstable)]
136    pub(crate) scan_method: ScanMethod,
137}
138
139impl EapStationConfig {
140    pub(crate) fn validate(&self) -> Result<(), WifiError> {
141        if self.identity.as_ref().unwrap_or(&String::new()).len() > 128 {
142            return Err(WifiError::InvalidArguments);
143        }
144
145        if self.username.as_ref().unwrap_or(&String::new()).len() > 128 {
146            return Err(WifiError::InvalidArguments);
147        }
148
149        if self.password.as_ref().unwrap_or(&String::new()).len() > 64 {
150            return Err(WifiError::InvalidArguments);
151        }
152
153        if self.new_password.as_ref().unwrap_or(&String::new()).len() > 64 {
154            return Err(WifiError::InvalidArguments);
155        }
156
157        if !(6..=31).contains(&self.beacon_timeout) {
158            return Err(WifiError::InvalidArguments);
159        }
160
161        Ok(())
162    }
163}
164
165impl Default for EapStationConfig {
166    fn default() -> Self {
167        EapStationConfig {
168            ssid: Ssid::default(),
169            bssid: None,
170            auth_method: AuthenticationMethod::Wpa2Enterprise,
171            identity: None,
172            username: None,
173            password: None,
174            channel: None,
175            eap_fast_config: None,
176            time_check: false,
177            new_password: None,
178            pac_file: None,
179            ca_cert: None,
180            certificate_and_key: None,
181            ttls_phase2_method: None,
182            protocols: Protocols::default(),
183            listen_interval: 3,
184            beacon_timeout: 6,
185            failure_retry_cnt: 1,
186            scan_method: ScanMethod::Fast,
187        }
188    }
189}
190
191impl fmt::Debug for EapStationConfig {
192    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
193        f.debug_struct("EapStationConfig")
194            .field("ssid", &self.ssid)
195            .field("bssid", &self.bssid)
196            .field("auth_method", &self.auth_method)
197            .field("channel", &self.channel)
198            .field("identity", &self.identity)
199            .field("username", &self.username)
200            .field("password", &"**REDACTED**")
201            .field("new_password", &"**REDACTED**")
202            .field("eap_fast_config", &self.eap_fast_config)
203            .field("time_check", &self.time_check)
204            .field("pac_file set", &self.pac_file.is_some())
205            .field("ca_cert set", &self.ca_cert.is_some())
206            .field("certificate_and_key set", &"**REDACTED**")
207            .field("ttls_phase2_method", &self.ttls_phase2_method)
208            .field("protocols", &self.protocols)
209            .field("listen_interval", &self.listen_interval)
210            .field("beacon_timeout", &self.beacon_timeout)
211            .field("failure_retry_cnt", &self.failure_retry_cnt)
212            .field("scan_method", &self.scan_method)
213            .finish()
214    }
215}
216
217#[cfg(feature = "defmt")]
218impl defmt::Format for EapStationConfig {
219    fn format(&self, fmt: defmt::Formatter<'_>) {
220        defmt::write!(
221            fmt,
222            "EapStationConfig {{\
223            ssid: {}, \
224            bssid: {:?}, \
225            auth_method: {:?}, \
226            channel: {:?}, \
227            identity: {:?}, \
228            username: {:?}, \
229            password: **REDACTED**, \
230            new_password: **REDACTED**, \
231            eap_fast_config: {:?}, \
232            time_check: {}, \
233            pac_file: {}, \
234            ca_cert: {}, \
235            certificate_and_key: **REDACTED**, \
236            ttls_phase2_method: {:?}, \
237            protocols: {}, \
238            listen_interval: {}, \
239            beacon_timeout: {}, \
240            failure_retry_cnt: {}, \
241            scan_method: {},
242            }}",
243            self.ssid.as_str(),
244            self.bssid,
245            self.auth_method,
246            self.channel,
247            &self.identity.as_ref().map_or("", |v| v.as_str()),
248            &self.username.as_ref().map_or("", |v| v.as_str()),
249            self.eap_fast_config,
250            self.time_check,
251            self.pac_file,
252            self.ca_cert,
253            self.ttls_phase2_method,
254            self.protocols,
255            self.listen_interval,
256            self.beacon_timeout,
257            self.failure_retry_cnt,
258            self.scan_method
259        )
260    }
261}