Skip to main content

fritz_core/wlan/
join.rs

1//! What a device needs to join a wireless network, as in a QR code:
2//! `WIFI:T:WPA;S:<ssid>;P:<password>;H:true;;`.
3//!
4//! The passphrase comes from `GetSecurityKeys`, a getter that the
5//! [policy](crate::policy) classes as secret and the read path refuses.
6//! [`join`] calls it on a narrow path of its own: only this action, only of a
7//! `WLANConfiguration` service, without inputs, and only for networks that
8//! need a passphrase. Of its answer, only `NewKeyPassphrase` is kept, in a
9//! [`SecretString`]; the other keys are dropped at once. The passphrase is
10//! never logged, and the errors never hold it. `fritz` offers this path in
11//! `fritz wlan qr` only; the MCP server, `fritz tr064 call` and the capture
12//! never reach it.
13
14use std::fmt;
15
16use secrecy::{ExposeSecret as _, SecretString};
17use tr064::{Action, Service};
18
19use super::{Read, is_named, networks};
20use crate::generic;
21use crate::read::Reader;
22
23/// The only service whose passphrase is read.
24const SERVICE: &str = "WLANConfiguration";
25/// The only secret getter that is called.
26const ACTION: &str = "GetSecurityKeys";
27/// The only output of [`ACTION`] that is kept.
28const OUTPUT: &str = "NewKeyPassphrase";
29/// The name of the guest network, ignoring case, on every model.
30pub const GUEST: &str = "guest";
31
32/// Why the data to join a network could not be read.
33#[derive(Debug, thiserror::Error)]
34pub enum Error {
35    #[error(transparent)]
36    Read(#[from] generic::Error),
37    #[error("no wireless network is named {0:?}")]
38    Unknown(String),
39    #[error("the device has no guest network")]
40    NoGuest,
41    #[error("{service} has no SSID")]
42    NoSsid { service: String },
43    /// WEP, or a beacon type that is not known.
44    #[error("{service} uses the beacon type {beacon_type:?}, which a QR code cannot describe")]
45    Unsupported {
46        service: String,
47        beacon_type: String,
48    },
49    #[error("the device returned no passphrase for {service}")]
50    NoPassphrase { service: String },
51}
52
53/// How a client authenticates, as a QR code names it.
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub enum Auth {
56    /// WPA, WPA2, WPA3 or a mix of them, with a passphrase.
57    Wpa,
58    /// An open network, or Enhanced Open (OWE), without a passphrase.
59    Open,
60}
61
62impl Auth {
63    /// The type in a QR code: `WPA` or `nopass`.
64    pub fn code(self) -> &'static str {
65        match self {
66            Self::Wpa => "WPA",
67            Self::Open => "nopass",
68        }
69    }
70}
71
72impl fmt::Display for Auth {
73    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74        f.write_str(self.code())
75    }
76}
77
78/// What a device needs to join a wireless network.
79#[derive(Debug)]
80pub struct Join {
81    /// The service, like `WLANConfiguration3`.
82    pub service: String,
83    /// The SSID verbatim, for the code: redact it with
84    /// [`redact::value`](crate::redact::value) before it is shown.
85    pub ssid: String,
86    pub auth: Auth,
87    /// Whether the SSID is not advertised.
88    pub hidden: bool,
89    /// Whether the network is on, if the device tells.
90    pub enabled: Option<bool>,
91    /// Whether the device reports it as its guest network.
92    pub guest: bool,
93    /// The passphrase, for [`Auth::Wpa`].
94    pub passphrase: Option<SecretString>,
95}
96
97impl Join {
98    /// The payload of a QR code, like
99    /// `WIFI:T:WPA;S:<ssid>;P:<password>;H:true;;`, with the SSID and the
100    /// passphrase [escaped](escape). `H:true` only for a hidden SSID.
101    pub fn payload(&self) -> SecretString {
102        let mut text = String::with_capacity(128);
103        text.push_str("WIFI:T:");
104        text.push_str(self.auth.code());
105        text.push_str(";S:");
106        escape(&self.ssid, &mut text);
107        text.push(';');
108        if let Some(passphrase) = &self.passphrase {
109            text.push_str("P:");
110            escape(passphrase.expose_secret(), &mut text);
111            text.push(';');
112        }
113        if self.hidden {
114            text.push_str("H:true;");
115        }
116        text.push(';');
117        SecretString::from(text)
118    }
119}
120
121/// Reads what a device needs to join the network that `network` names: the
122/// guest network by [`GUEST`], ignoring case, also if a network has it as
123/// its SSID, or else by service, number or SSID like
124/// [`named`](super::named). Of several networks with the name, the first
125/// one. Reads the passphrase only for a network that needs one.
126///
127/// # Errors
128///
129/// The errors of reading, [`Error::Unknown`] or [`Error::NoGuest`] if no
130/// network fits, [`Error::NoSsid`], [`Error::Unsupported`] for WEP and
131/// unknown beacon types, and [`Error::NoPassphrase`].
132pub async fn join(reader: &mut Reader, network: &str) -> Result<Join, Error> {
133    let mut networks = networks(reader).await?.into_iter();
134    let Read { wlan, info, .. } = if network.eq_ignore_ascii_case(GUEST) {
135        networks.find(|n| n.wlan.guest).ok_or(Error::NoGuest)?
136    } else {
137        networks
138            .find(|n| is_named(&n.wlan, network))
139            .ok_or_else(|| Error::Unknown(network.to_owned()))?
140    };
141    let service = wlan.service;
142    // The read hides values like `?sid=…`, which an SSID may hold too; the
143    // code needs it verbatim.
144    let ssid = reader
145        .output(&service, "GetInfo", &[])
146        .await?
147        .into_iter()
148        .find(|(name, value)| name == "NewSSID" && !value.is_empty());
149    let Some((_, ssid)) = ssid else {
150        return Err(Error::NoSsid { service });
151    };
152    let beacon_type = info.text("NewBeaconType").unwrap_or_default();
153    let basic = info.text("NewBasicEncryptionModes");
154    let Some(auth) = auth(&beacon_type, basic.as_deref()) else {
155        return Err(Error::Unsupported {
156            service,
157            beacon_type,
158        });
159    };
160    let hidden = reader
161        .try_read(&service, "GetBeaconAdvertisement", &[])
162        .await?
163        .and_then(|v| v.flag("NewBeaconAdvertisementEnabled"))
164        .is_some_and(|advertised| !advertised);
165    let passphrase = match auth {
166        Auth::Wpa => Some(passphrase(reader, &service).await?),
167        Auth::Open => None,
168    };
169    Ok(Join {
170        service,
171        ssid,
172        auth,
173        hidden,
174        enabled: wlan.enabled,
175        guest: wlan.guest,
176        passphrase,
177    })
178}
179
180/// How a client authenticates with a beacon type: WPA, WPA2, WPA3 and their
181/// mixes with a passphrase, open networks and OWE without. `None` for WEP
182/// and beacon types that are not known.
183fn auth(beacon_type: &str, basic_encryption: Option<&str>) -> Option<Auth> {
184    match beacon_type {
185        "Basic" if basic_encryption.is_some_and(|b| b.contains("WEP")) => None,
186        "None" | "Basic" | "OWE" | "OWETrans" => Some(Auth::Open),
187        "WPA" | "11i" | "WPAand11i" | "11iandWPA3" | "WPA3" => Some(Auth::Wpa),
188        _ => None,
189    }
190}
191
192/// Whether the narrow path may call `action` of `service`: only
193/// [`ACTION`] of a [`SERVICE`], without inputs.
194fn allowed(service: &Service, action: &Action) -> bool {
195    service.name() == SERVICE && action.name == ACTION && action.inputs().next().is_none()
196}
197
198/// The passphrase of the network of `reference`: the one call of a secret
199/// getter, see the [module](self). The other keys of the answer are
200/// dropped, and wiped from memory, at once.
201async fn passphrase(reader: &mut Reader, reference: &str) -> Result<SecretString, Error> {
202    let (service, scpd) = reader.service(reference).await?;
203    let action = generic::action(&service, scpd, ACTION)?;
204    let class = crate::policy::classify(&service, action);
205    let refused = generic::Error::Refused {
206        action: action.name.clone(),
207        class,
208    };
209    allowed(&service, action).then_some(()).ok_or(refused)?;
210    let output = reader
211        .client()
212        .call(&service, ACTION, &[])
213        .await
214        .map_err(generic::Error::from)?;
215    let mut passphrase = None;
216    for (name, value) in output {
217        let value = SecretString::from(value);
218        if name == OUTPUT && !value.expose_secret().is_empty() {
219            passphrase = Some(value);
220        }
221    }
222    passphrase.ok_or_else(|| Error::NoPassphrase {
223        service: reference.to_owned(),
224    })
225}
226
227/// Appends `text` to `out` with `\`, `;`, `,`, `:` and `"` escaped by a
228/// backslash, as the fields of a QR code need.
229pub fn escape(text: &str, out: &mut String) {
230    for c in text.chars() {
231        if matches!(c, '\\' | ';' | ',' | ':' | '"') {
232            out.push('\\');
233        }
234        out.push(c);
235    }
236}
237
238#[cfg(test)]
239mod tests {
240    use tr064::{Argument, Direction};
241
242    use super::*;
243
244    fn escaped(text: &str) -> String {
245        let mut out = String::new();
246        escape(text, &mut out);
247        out
248    }
249
250    fn join(auth: Auth, ssid: &str, passphrase: Option<&str>, hidden: bool) -> Join {
251        Join {
252            service: "WLANConfiguration1".to_owned(),
253            ssid: ssid.to_owned(),
254            auth,
255            hidden,
256            enabled: Some(true),
257            guest: false,
258            passphrase: passphrase.map(|p| SecretString::from(p.to_owned())),
259        }
260    }
261
262    #[test]
263    fn escapes_special_characters() {
264        assert_eq!(escaped("plain"), "plain");
265        assert_eq!(escaped(r#"a\b;c,d:e"f"#), r#"a\\b\;c\,d\:e\"f"#);
266        assert_eq!(escaped("äöü 🙂'"), "äöü 🙂'");
267    }
268
269    #[test]
270    fn builds_payloads() {
271        let wpa = join(Auth::Wpa, "wlan;1", Some("fake:pass"), false);
272        assert_eq!(
273            wpa.payload().expose_secret(),
274            r"WIFI:T:WPA;S:wlan\;1;P:fake\:pass;;"
275        );
276        let hidden = join(Auth::Wpa, "hidden", Some("fake"), true);
277        assert_eq!(
278            hidden.payload().expose_secret(),
279            "WIFI:T:WPA;S:hidden;P:fake;H:true;;"
280        );
281        let open = join(Auth::Open, "open", None, false);
282        assert_eq!(open.payload().expose_secret(), "WIFI:T:nopass;S:open;;");
283        assert!(!format!("{wpa:?}").contains("fake"));
284    }
285
286    #[test]
287    fn tells_the_auth_by_the_beacon_type() {
288        for beacon in ["WPA", "11i", "WPAand11i", "11iandWPA3", "WPA3"] {
289            assert_eq!(auth(beacon, None), Some(Auth::Wpa), "{beacon}");
290        }
291        for beacon in ["None", "OWE", "OWETrans"] {
292            assert_eq!(auth(beacon, None), Some(Auth::Open), "{beacon}");
293        }
294        assert_eq!(auth("Basic", Some("None")), Some(Auth::Open));
295        assert_eq!(auth("Basic", Some("WEPEncryption")), None);
296        assert_eq!(auth("Other", None), None);
297        assert_eq!(auth("", None), None);
298        assert_eq!(Auth::Wpa.to_string(), "WPA");
299        assert_eq!(Auth::Open.to_string(), "nopass");
300    }
301
302    #[test]
303    fn allows_only_the_passphrase_getter() {
304        let service = |name: &str| Service {
305            service_type: format!("urn:dslforum-org:service:{name}:1"),
306            service_id: format!("urn:{name}-com:serviceId:{name}1"),
307            control_url: "/upnp/control/x".to_owned(),
308            event_sub_url: None,
309            scpd_url: "/x.xml".to_owned(),
310        };
311        let action = |name: &str, inputs: &[&str]| Action {
312            name: name.to_owned(),
313            arguments: inputs
314                .iter()
315                .map(|input| Argument {
316                    name: (*input).to_owned(),
317                    direction: Direction::In,
318                    related_state_variable: "X".to_owned(),
319                })
320                .collect(),
321        };
322        let wlan = service("WLANConfiguration");
323        assert!(allowed(&wlan, &action(ACTION, &[])));
324        assert!(!allowed(&wlan, &action(ACTION, &["NewIndex"])));
325        assert!(!allowed(&wlan, &action("GetInfo", &[])));
326        assert!(!allowed(
327            &service("DeviceConfig"),
328            &action("X_AVM-DE_GetConfigFile", &[])
329        ));
330        assert!(!allowed(&service("X_VoIP"), &action(ACTION, &[])));
331    }
332}