Skip to main content

fritz_core/
users.rs

1//! The users of a device and how its login is protected, read with the
2//! getters of `LANConfigSecurity` and `X_AVM-DE_Auth` only.
3//!
4//! No passwords are read: the user list holds only names. The name of the
5//! current user is masked like every login name.
6
7use serde::Serialize;
8
9use crate::generic::Error;
10use crate::read::{Reader, Values};
11use crate::status::{self, Right};
12
13/// The service with the users and the login settings.
14const SERVICE: &str = "LANConfigSecurity1";
15
16/// A user of the device.
17#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
18pub struct User {
19    /// The login name.
20    pub name: String,
21    /// Whether this user logged in last.
22    pub last_login: bool,
23}
24
25/// How the login to the device is protected. Values the device does not
26/// report are `None`.
27#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
28pub struct Login {
29    /// Whether the login without a password is allowed.
30    pub anonymous: Option<bool>,
31    /// Whether the login by a button press on the device is allowed.
32    pub button: Option<bool>,
33    /// Whether the password set at the factory is still active.
34    pub default_password: Option<bool>,
35    /// Whether changes need a confirmation on the device.
36    pub two_factor: Option<bool>,
37}
38
39/// The users and the login settings.
40#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
41pub struct Users {
42    /// The users, or `None` if the device does not tell, usually because
43    /// the current user may not read them.
44    pub users: Option<Vec<User>>,
45    /// What the current user may do, like `BoxAdmin: readwrite`.
46    pub rights: Vec<Right>,
47    pub login: Login,
48    /// Weak settings, like `default password active`.
49    pub hints: Vec<String>,
50}
51
52impl Users {
53    /// Replaces the names of the users with `hidden`, for output that must
54    /// not identify them.
55    #[must_use]
56    pub fn without_names(mut self, hidden: &str) -> Self {
57        for user in self.users.iter_mut().flatten() {
58            hidden.clone_into(&mut user.name);
59        }
60        self
61    }
62}
63
64/// Reads the users and the login settings.
65///
66/// # Errors
67///
68/// The errors of reading other than missing parts, see
69/// [`Reader::try_read`].
70pub async fn users(reader: &mut Reader) -> Result<Users, Error> {
71    let list = reader
72        .try_read(SERVICE, "X_AVM-DE_GetUserList", &[])
73        .await?
74        .and_then(|values| values.text("NewX_AVM-DE_UserList"))
75        .map(|xml| list(&xml));
76    let rights = reader
77        .try_read(SERVICE, "X_AVM-DE_GetCurrentUser", &[])
78        .await?
79        .and_then(|values| values.text("NewX_AVM-DE_CurrentUserRights"))
80        .map_or_else(Vec::new, |xml| status::rights(&xml));
81    let anonymous = reader
82        .try_read(SERVICE, "X_AVM-DE_GetAnonymousLogin", &[])
83        .await?
84        .unwrap_or_default();
85    let info = reader
86        .try_read(SERVICE, "GetInfo", &[])
87        .await?
88        .unwrap_or_default();
89    let auth = reader
90        .try_read("X_AVM-DE_Auth1", "GetInfo", &[])
91        .await?
92        .unwrap_or_default();
93    let login = login(&anonymous, &info, &auth);
94    let hints = hints(&login);
95    Ok(Users {
96        users: list,
97        rights,
98        login,
99        hints,
100    })
101}
102
103/// The login settings from the answers of `X_AVM-DE_GetAnonymousLogin`,
104/// `LANConfigSecurity:GetInfo` and `X_AVM-DE_Auth:GetInfo`.
105fn login(anonymous: &Values, info: &Values, auth: &Values) -> Login {
106    Login {
107        anonymous: anonymous.flag("NewX_AVM-DE_AnonymousLoginEnabled"),
108        button: anonymous.flag("NewX_AVM-DE_ButtonLoginEnabled"),
109        default_password: info.flag("NewX_AVM-DE_IsDefaultPasswordActive"),
110        two_factor: auth.flag("NewEnabled"),
111    }
112}
113
114/// The weak login settings.
115fn hints(login: &Login) -> Vec<String> {
116    [
117        (login.default_password, "default password active"),
118        (login.anonymous, "login without password allowed"),
119        (login.button, "login by button press allowed"),
120        (
121            login.two_factor.map(|on| !on),
122            "two-factor confirmation off",
123        ),
124    ]
125    .into_iter()
126    .filter(|(weak, _)| *weak == Some(true))
127    .map(|(_, hint)| hint.to_owned())
128    .collect()
129}
130
131/// Parses a user list like
132/// `<List><Username last_user="1">admin</Username></List>`. Unreadable
133/// lists are empty.
134fn list(xml: &str) -> Vec<User> {
135    let Ok(document) = roxmltree::Document::parse(xml) else {
136        return Vec::new();
137    };
138    document
139        .root_element()
140        .children()
141        .filter(|node| node.has_tag_name("Username"))
142        .filter_map(|node| {
143            let name = node.text().unwrap_or_default().trim();
144            (!name.is_empty()).then(|| User {
145                name: name.to_owned(),
146                last_login: node.attribute("last_user") == Some("1"),
147            })
148        })
149        .collect()
150}
151
152#[cfg(test)]
153mod tests {
154    use super::*;
155    use crate::read::values;
156
157    #[test]
158    fn parses_the_user_list() {
159        let users = list(
160            "<List><Username last_user=\"0\">alice</Username><Username\n\
161             last_user=\"1\"> bob </Username><Username/><Other>x</Other></List>",
162        );
163        assert_eq!(
164            users,
165            [
166                User {
167                    name: "alice".to_owned(),
168                    last_login: false,
169                },
170                User {
171                    name: "bob".to_owned(),
172                    last_login: true,
173                },
174            ]
175        );
176        assert_eq!(list("not xml"), []);
177    }
178
179    #[test]
180    fn hints_at_weak_settings() {
181        let login = login(
182            &values(&[
183                ("NewX_AVM-DE_AnonymousLoginEnabled", "1"),
184                ("NewX_AVM-DE_ButtonLoginEnabled", "1"),
185            ]),
186            &values(&[("NewX_AVM-DE_IsDefaultPasswordActive", "1")]),
187            &values(&[("NewEnabled", "0")]),
188        );
189        assert_eq!(
190            hints(&login),
191            [
192                "default password active",
193                "login without password allowed",
194                "login by button press allowed",
195                "two-factor confirmation off",
196            ]
197        );
198        // Unknown settings give no hints.
199        assert_eq!(hints(&Login::default()), Vec::<String>::new());
200    }
201
202    #[test]
203    fn hides_the_names() {
204        let users = Users {
205            users: Some(list("<List><Username>alice</Username></List>")),
206            ..Users::default()
207        };
208        let hidden = users.without_names("(hidden)");
209        assert_eq!(hidden.users.unwrap()[0].name, "(hidden)");
210        assert_eq!(Users::default().without_names("x").users, None);
211    }
212}