1use 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
23const SERVICE: &str = "WLANConfiguration";
25const ACTION: &str = "GetSecurityKeys";
27const OUTPUT: &str = "NewKeyPassphrase";
29pub const GUEST: &str = "guest";
31
32#[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 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub enum Auth {
56 Wpa,
58 Open,
60}
61
62impl Auth {
63 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#[derive(Debug)]
80pub struct Join {
81 pub service: String,
83 pub ssid: String,
86 pub auth: Auth,
87 pub hidden: bool,
89 pub enabled: Option<bool>,
91 pub guest: bool,
93 pub passphrase: Option<SecretString>,
95}
96
97impl Join {
98 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
121pub 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 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
180fn 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
192fn allowed(service: &Service, action: &Action) -> bool {
195 service.name() == SERVICE && action.name == ACTION && action.inputs().next().is_none()
196}
197
198async 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
227pub 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}