1use std::fmt::Write as _;
11
12use md5::{Digest as _, Md5};
13use secrecy::{ExposeSecret as _, SecretString};
14use sha2::Sha256;
15use tr064::Client;
16
17use crate::status::Right;
18
19pub const LOGIN: &str = "/login_sid.lua?version=2";
21
22pub const DATA: &str = "/data.lua";
24
25const NO_SESSION: &str = "0000000000000000";
27
28#[derive(Debug, thiserror::Error)]
30pub enum Error {
31 #[error(transparent)]
32 Tr064(#[from] tr064::Error),
33 #[error("invalid answer from {what}: {reason}")]
35 Invalid { what: &'static str, reason: String },
36 #[error("the device blocks logins for {0} more seconds after failed attempts")]
38 Blocked(u64),
39 #[error("the device rejected the user or the password{}", blocked(*.0))]
41 Rejected(u64),
42}
43
44fn blocked(seconds: u64) -> String {
45 if seconds == 0 {
46 String::new()
47 } else {
48 format!(", and blocks logins for {seconds} seconds")
49 }
50}
51
52pub async fn block_time(client: &Client) -> Result<u64, Error> {
61 Ok(SessionInfo::parse(&client.get(LOGIN).await?)?.block_time)
62}
63
64#[derive(Debug)]
66pub struct Session {
67 client: Client,
68 sid: SecretString,
69 rights: Vec<Right>,
70}
71
72impl Session {
73 pub async fn login(
82 client: Client,
83 username: &str,
84 password: &SecretString,
85 ) -> Result<Self, Error> {
86 let info = SessionInfo::parse(&client.get(LOGIN).await?)?;
87 if info.block_time > 0 {
88 tracing::debug!(seconds = info.block_time, "the web interface blocks logins");
89 return Err(Error::Blocked(info.block_time));
90 }
91 let response = response(&info.challenge, password.expose_secret())?;
92 let form = [("username", username), ("response", response.as_str())];
93 let info = SessionInfo::parse(&client.post_form(LOGIN, &form).await?)?;
94 if info.sid == NO_SESSION {
95 let block_seconds = info.block_time;
96 tracing::debug!(block_seconds, "the web interface rejected the login");
97 return Err(Error::Rejected(info.block_time));
98 }
99 tracing::debug!(rights = info.rights.len(), "logged in to the web interface");
100 Ok(Self {
101 client,
102 sid: SecretString::from(info.sid),
103 rights: info.rights,
104 })
105 }
106
107 pub fn rights(&self) -> &[Right] {
109 &self.rights
110 }
111
112 pub async fn get(&self, path: &str) -> Result<String, Error> {
119 let authorization = format!("AVM-SID {}", self.sid.expose_secret());
120 let headers = [("Authorization", authorization.as_str())];
121 Ok(self.client.get_with_headers(path, &headers).await?)
122 }
123
124 pub async fn post(&self, path: &str, form: &[(&str, &str)]) -> Result<String, Error> {
131 let mut fields = form.to_vec();
132 fields.push(("sid", self.sid.expose_secret()));
133 Ok(self.client.post_form(path, &fields).await?)
134 }
135
136 pub async fn page(&self, name: &str, fields: &[(&str, &str)]) -> Result<String, Error> {
144 let mut form = vec![
145 ("xhr", "1"),
146 ("lang", "en"),
147 ("page", name),
148 ("xhrId", "all"),
149 ("useajax", "1"),
150 ("no_sidrenew", ""),
151 ];
152 form.extend_from_slice(fields);
153 self.post(DATA, &form).await
154 }
155
156 pub async fn logout(self) -> Result<(), Error> {
163 let form = [("logout", "1"), ("sid", self.sid.expose_secret())];
164 self.client.post_form(LOGIN, &form).await?;
165 Ok(())
166 }
167}
168
169#[derive(Debug, PartialEq, Eq)]
171struct SessionInfo {
172 sid: String,
173 challenge: String,
174 block_time: u64,
176 rights: Vec<Right>,
177}
178
179impl SessionInfo {
180 fn parse(xml: &str) -> Result<Self, Error> {
181 let invalid = |reason: String| Error::Invalid {
182 what: "the login page",
183 reason,
184 };
185 let document = roxmltree::Document::parse(xml).map_err(|e| invalid(e.to_string()))?;
186 let root = document.root_element();
187 if !root.has_tag_name("SessionInfo") {
188 return Err(invalid(format!("unexpected <{}>", root.tag_name().name())));
189 }
190 let text = |name: &str| {
191 root.children()
192 .find(|n| n.has_tag_name(name))
193 .and_then(|n| n.text())
194 .unwrap_or_default()
195 .trim()
196 .to_owned()
197 };
198 let sid = text("SID");
199 if sid.len() != NO_SESSION.len() || !sid.bytes().all(|b| b.is_ascii_hexdigit()) {
200 return Err(invalid("no session ID".to_owned()));
201 }
202 let block_time = text("BlockTime");
203 let block_time = block_time
204 .parse()
205 .map_err(|_| invalid(format!("block time {block_time:?}")))?;
206 let rights = root
207 .children()
208 .filter(|n| n.has_tag_name("Rights"))
209 .flat_map(|rights| rights.children().filter(roxmltree::Node::is_element))
210 .collect::<Vec<_>>();
211 let rights = rights
212 .chunks(2)
213 .filter_map(|pair| match pair {
214 [name, access] if name.has_tag_name("Name") && access.has_tag_name("Access") => {
215 Some(Right {
216 area: name.text().unwrap_or_default().to_owned(),
217 access: match access.text() {
218 Some("1") => "read".to_owned(),
219 Some("2") => "readwrite".to_owned(),
220 other => other.unwrap_or_default().to_owned(),
221 },
222 })
223 }
224 _ => None,
225 })
226 .collect();
227 Ok(Self {
228 sid,
229 challenge: text("Challenge"),
230 block_time,
231 rights,
232 })
233 }
234}
235
236fn response(challenge: &str, password: &str) -> Result<String, Error> {
239 if !challenge.starts_with("2$") {
240 return Ok(md5_response(challenge, password));
241 }
242 let invalid = || Error::Invalid {
243 what: "the login page",
244 reason: format!("challenge {challenge:?}"),
245 };
246 let parts: Vec<&str> = challenge.split('$').collect();
247 let [_, iterations1, salt1, iterations2, salt2] = parts[..] else {
248 return Err(invalid());
249 };
250 let number = |text: &str| text.parse::<u32>().ok().filter(|n| *n > 0);
251 let (Some(iterations1), Some(salt1), Some(iterations2), Some(salt2)) = (
252 number(iterations1),
253 from_hex(salt1),
254 number(iterations2),
255 from_hex(salt2),
256 ) else {
257 return Err(invalid());
258 };
259 let first = pbkdf2::pbkdf2_hmac_array::<Sha256, 32>(password.as_bytes(), &salt1, iterations1);
260 let second = pbkdf2::pbkdf2_hmac_array::<Sha256, 32>(&first, &salt2, iterations2);
261 Ok(format!("{}${}", to_hex(&salt2), to_hex(&second)))
262}
263
264fn md5_response(challenge: &str, password: &str) -> String {
267 let text = format!("{challenge}-{password}");
268 let bytes: Vec<u8> = text
269 .chars()
270 .map(|c| if u32::from(c) > 255 { '.' } else { c })
271 .flat_map(|c| {
272 let mut units = [0; 2];
273 c.encode_utf16(&mut units);
274 units[0].to_le_bytes()
275 })
276 .collect();
277 format!("{challenge}-{}", to_hex(&Md5::digest(bytes)))
278}
279
280fn from_hex(text: &str) -> Option<Vec<u8>> {
281 if text.is_empty() || !text.len().is_multiple_of(2) {
282 return None;
283 }
284 (0..text.len())
285 .step_by(2)
286 .map(|i| u8::from_str_radix(text.get(i..i + 2)?, 16).ok())
287 .collect()
288}
289
290pub(crate) fn to_hex(bytes: &[u8]) -> String {
292 bytes.iter().fold(String::new(), |mut text, byte| {
293 let _ = write!(text, "{byte:02x}");
294 text
295 })
296}
297
298#[cfg(test)]
299mod tests {
300 use super::*;
301
302 #[test]
303 fn answers_pbkdf2_challenges() {
304 assert_eq!(
307 response("2$10000$5A1711$2000$5A1722", "1example!").unwrap(),
308 EXAMPLE_PBKDF2
309 );
310 }
311
312 #[test]
313 fn answers_md5_challenges() {
314 assert_eq!(
316 response("1234567z", "äbc").unwrap(),
317 "1234567z-9e224a41eeefa284df7bb0f26c2913e2"
318 );
319 assert_eq!(
321 response("1234567z", "€").unwrap(),
322 md5_response("1234567z", ".")
323 );
324 }
325
326 #[test]
327 fn rejects_invalid_challenges() {
328 for challenge in [
329 "2$10000$5A1711$2000",
330 "2$0$5A1711$2000$5A1722",
331 "2$x$5A1711$2000$5A1722",
332 "2$10000$5A171$2000$5A1722",
333 "2$10000$5A1711$2000$",
334 "2$10000$5A1711$2000$zz",
335 ] {
336 let error = response(challenge, "secret").unwrap_err();
337 assert_eq!(
338 error.to_string(),
339 format!("invalid answer from the login page: challenge {challenge:?}")
340 );
341 }
342 }
343
344 #[test]
345 fn converts_hex() {
346 assert_eq!(from_hex("00ff7A"), Some(vec![0, 255, 122]));
347 assert_eq!(from_hex("ä0"), None);
348 assert_eq!(to_hex(&[0, 255, 122]), "00ff7a");
349 }
350
351 #[test]
352 fn parses_session_infos() {
353 let info = SessionInfo::parse(
354 "<SessionInfo><SID>0123456789abcdef</SID><Challenge>2$1$aa$1$bb</Challenge>\
355 <BlockTime>0</BlockTime><Rights><Name>Dial</Name><Access>2</Access>\
356 <Name>HomeAuto</Name><Access>1</Access><Name>App</Name><Access>3</Access>\
357 <Name>Odd</Name></Rights><Users><User last=\"1\">agent</User></Users>\
358 </SessionInfo>",
359 )
360 .unwrap();
361 assert_eq!(info.sid, "0123456789abcdef");
362 assert_eq!(info.challenge, "2$1$aa$1$bb");
363 assert_eq!(info.block_time, 0);
364 let rights: Vec<_> = info
365 .rights
366 .iter()
367 .map(|r| format!("{}: {}", r.area, r.access))
368 .collect();
369 assert_eq!(rights, ["Dial: readwrite", "HomeAuto: read", "App: 3"]);
370 }
371
372 #[test]
373 fn rejects_invalid_session_infos() {
374 for (xml, reason) in [
375 ("<SessionInfo>", "never closed"),
376 ("<Other/>", "unexpected <Other>"),
377 ("<SessionInfo><SID>0</SID></SessionInfo>", "no session ID"),
378 (
379 "<SessionInfo><SID>000000000000000g</SID></SessionInfo>",
380 "no session ID",
381 ),
382 (
383 "<SessionInfo><SID>0000000000000000</SID><BlockTime>x</BlockTime></SessionInfo>",
384 "block time \"x\"",
385 ),
386 ] {
387 let error = SessionInfo::parse(xml).unwrap_err().to_string();
388 assert!(
389 error.starts_with("invalid answer from the login page: ") && error.contains(reason),
390 "{xml}: {error}"
391 );
392 }
393 }
394
395 #[test]
396 fn explains_rejections() {
397 assert_eq!(
398 Error::Rejected(0).to_string(),
399 "the device rejected the user or the password"
400 );
401 assert_eq!(
402 Error::Rejected(8).to_string(),
403 "the device rejected the user or the password, and blocks logins for 8 seconds"
404 );
405 }
406
407 const EXAMPLE_PBKDF2: &str =
408 "5a1722$1798a1672bca7c6463d6b245f82b53703b0f50813401b03e4045a5861e689adb";
409}