Skip to main content

fritz_core/
settings.rs

1//! Settings of the device, read through the REST API of the web interface
2//! with a [`Session`]: `/api/v0/generic/<module>` answers with the settings
3//! of a module, like `ipv6` or `dnscfg`, as JSON.
4//!
5//! The API is not documented. Modules and their fields come from the web
6//! interface and may change with FRITZ!OS. Only `GET` is used. Values whose
7//! names point to secrets, like passwords and keys, are hidden.
8
9use std::collections::BTreeMap;
10
11use serde::Serialize;
12use serde_json::{Map, Value};
13
14use crate::names::{Sensitivity, sensitivity};
15use crate::redact::{self, HIDDEN};
16use crate::session::{Error, Session};
17
18/// Where the modules are.
19pub const PREFIX: &str = "/api/v0/generic/";
20
21/// The modules the device is known to have, with what they hold, and
22/// whether they are read by default. The others are large or personal.
23pub const MODULES: &[(&str, &str, bool)] = &[
24    (
25        "box",
26        "name, LEDs, night time, UPnP and DHCP lease times",
27        true,
28    ),
29    (
30        "connections",
31        "internet connections, with IPv4 and IPv6 DNS",
32        true,
33    ),
34    ("dnscfg", "DNS servers and DNS over TLS", true),
35    (
36        "dns_excepted_domains",
37        "domains excepted from DNS rebind protection",
38        true,
39    ),
40    (
41        "eth_ports",
42        "LAN ports, their speed and energy saving",
43        true,
44    ),
45    ("forwardrules", "whether a host is exposed", true),
46    ("ipv6", "IPv6 of the home network, MTU and DHCPv6", true),
47    (
48        MESH,
49        "whether mesh devices choose the best connection themselves, and the role in the mesh",
50        true,
51    ),
52    ("route", "static IPv4 routes", true),
53    (
54        "sync_groups",
55        "IPv4 and IPv6 modes of the internet connection",
56        true,
57    ),
58    ("time", "time server and time zone", true),
59    ("dect", "DECT and its handsets", false),
60    (
61        "filter_profile",
62        "access profiles of the parental controls",
63        false,
64    ),
65    (
66        "inetstat",
67        "online counter: traffic by day, week and month",
68        false,
69    ),
70    ("landevice", "hosts of the home network", false),
71    ("mobiled", "mobile modem", false),
72    ("plc", "powerline energy saving", false),
73    ("tam", "answering machines", false),
74    ("user", "users of the parental controls", false),
75    ("vpn", "VPN connections", false),
76    ("wlan", "wireless networks and their clients", false),
77];
78
79/// A module that the device does not have: the settings of the mesh, put
80/// together from the [`MESH_FIELDS`].
81pub const MESH: &str = "mesh";
82
83/// The fields of [`MESH`], by the module that holds them:
84/// `backhaul_steering` is the switch "Mesh devices choose the best
85/// connection automatically" of the web interface.
86pub const MESH_FIELDS: &[(&str, &[&str])] = &[
87    ("wlan", &["backhaul_steering"]),
88    ("nexus", &["role", "is_master"]),
89];
90
91/// The settings of several modules.
92#[derive(Debug, Default, Serialize)]
93pub struct Settings {
94    /// The settings by module.
95    pub modules: BTreeMap<String, Value>,
96    /// Why modules could not be read, by module.
97    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
98    pub unavailable: BTreeMap<String, String>,
99}
100
101/// Reads `modules`, or the [`MODULES`] if empty. A module that cannot be
102/// read is listed in [`Settings::unavailable`] instead.
103pub async fn settings(session: &Session, modules: &[String]) -> Settings {
104    let defaults: Vec<String> = MODULES
105        .iter()
106        .filter(|(_, _, default)| *default)
107        .map(|(name, _, _)| (*name).to_owned())
108        .collect();
109    let modules = if modules.is_empty() {
110        &defaults
111    } else {
112        modules
113    };
114    let mut settings = Settings::default();
115    for name in modules {
116        let value = if name == MESH {
117            mesh(session).await
118        } else {
119            module(session, name).await
120        };
121        match value {
122            Ok(value) => {
123                settings.modules.insert(name.clone(), value);
124            }
125            Err(e) => {
126                settings.unavailable.insert(name.clone(), e.to_string());
127            }
128        }
129    }
130    settings
131}
132
133/// Reads the settings of one module, with secrets hidden.
134///
135/// # Errors
136///
137/// [`Error::Invalid`] if `name` is not a module name or the answer is not
138/// JSON, and the errors of the request.
139pub async fn module(session: &Session, name: &str) -> Result<Value, Error> {
140    let valid = !name.is_empty()
141        && name
142            .chars()
143            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_');
144    if !valid {
145        return Err(Error::Invalid {
146            what: "the module name",
147            reason: format!("{name:?} is not a module"),
148        });
149    }
150    parse(&session.get(&format!("{PREFIX}{name}")).await?)
151}
152
153/// The settings of the mesh: the [`MESH_FIELDS`] of the modules that can
154/// be read.
155///
156/// # Errors
157///
158/// The error of the first module if none can be read.
159pub async fn mesh(session: &Session) -> Result<Value, Error> {
160    let mut modules = Vec::new();
161    let mut first = None;
162    for (name, _) in MESH_FIELDS {
163        match module(session, name).await {
164            Ok(value) => modules.push((*name, value)),
165            Err(e) => {
166                first.get_or_insert(e);
167            }
168        }
169    }
170    match first {
171        Some(e) if modules.is_empty() => Err(e),
172        _ => Ok(mesh_of(&modules)),
173    }
174}
175
176/// The [`MESH_FIELDS`] found in `modules`, by module name.
177fn mesh_of(modules: &[(&str, Value)]) -> Value {
178    let mut mesh = Map::new();
179    for (name, value) in modules {
180        let fields = MESH_FIELDS
181            .iter()
182            .filter(|(module, _)| module == name)
183            .flat_map(|(_, fields)| fields.iter());
184        for field in fields {
185            if let Some(found) = value.get(field) {
186                mesh.insert((*field).to_owned(), found.clone());
187            }
188        }
189    }
190    Value::Object(mesh)
191}
192
193/// The settings in `json`, with secrets hidden.
194///
195/// # Errors
196///
197/// [`Error::Invalid`] if `json` is not JSON.
198pub fn parse(json: &str) -> Result<Value, Error> {
199    let value = serde_json::from_str(json).map_err(|e| Error::Invalid {
200        what: "the settings API",
201        reason: e.to_string(),
202    })?;
203    Ok(hide(value))
204}
205
206/// `value` with the values of [`secret`] names, and texts with private
207/// keys, replaced by [`HIDDEN`], at any depth, and session IDs in URLs
208/// hidden.
209pub fn hide(value: Value) -> Value {
210    match value {
211        Value::Object(object) => Value::Object(
212            object
213                .into_iter()
214                .map(|(name, value)| {
215                    let value = if secret(&name) {
216                        Value::String(HIDDEN.to_owned())
217                    } else {
218                        hide(value)
219                    };
220                    (name, value)
221                })
222                .collect(),
223        ),
224        Value::Array(items) => Value::Array(items.into_iter().map(hide).collect()),
225        Value::String(text) if PRIVATE.iter().any(|p| text.contains(p)) => {
226            Value::String(HIDDEN.to_owned())
227        }
228        Value::String(text) => Value::String(redact::value("", &text)),
229        other => other,
230    }
231}
232
233/// Parts of names of secrets that are not words of their own, like in
234/// `pskvalue`, the password of a wireless network.
235const SECRET_PARTS: &[&str] = &["psk", "passw", "secret", "privatekey", "private_key"];
236
237/// Texts that only private keys contain, like a `WireGuard` configuration.
238const PRIVATE: &[&str] = &["PrivateKey", "PRIVATE KEY"];
239
240/// Whether the value of `name` is hidden: the names that are not plain for
241/// TR-064, names with one of the [`SECRET_PARTS`], and `WireGuard`
242/// configurations like `wg_slave_config`, which contain private keys.
243fn secret(name: &str) -> bool {
244    let lower = name.to_ascii_lowercase();
245    sensitivity(name) != Sensitivity::Plain
246        || SECRET_PARTS.iter().any(|part| lower.contains(part))
247        || (lower.starts_with("wg_") && lower.ends_with("config"))
248}
249
250#[cfg(test)]
251mod tests {
252    use serde_json::json;
253
254    use super::*;
255
256    #[test]
257    fn hides_secrets_at_any_depth() {
258        let value = json!({
259            "name": "box",
260            "password": "secret",
261            "accounts": [{"username": "user", "psk": {"value": "key"}, "pin_enabled": "1"}],
262            "url": "/x.lua?sid=0123",
263            "mtu": 1492,
264            "pskvalue": "wlan key",
265            "guest_pskvalue": "guest key",
266            "wg_slave_config": "[Interface]",
267            "dns_domains": "[Interface]\nPrivateKey = abc",
268            "ip4_is_private": "1",
269        });
270        assert_eq!(
271            hide(value),
272            json!({
273                "name": "box",
274                "password": "***",
275                "accounts": [{"username": "***", "psk": "***", "pin_enabled": "1"}],
276                "url": "/x.lua?sid=***",
277                "mtu": 1492,
278                "pskvalue": "***",
279                "guest_pskvalue": "***",
280                "wg_slave_config": "***",
281                "dns_domains": "***",
282                "ip4_is_private": "1",
283            })
284        );
285    }
286
287    #[test]
288    fn puts_the_mesh_together() {
289        let modules = [
290            (
291                "wlan",
292                json!({"backhaul_steering": "1", "pskvalue": "***", "ssid": "wlan-1"}),
293            ),
294            (
295                "nexus",
296                json!({"role": "auto", "is_master": "1", "peers": []}),
297            ),
298        ];
299        assert_eq!(
300            mesh_of(&modules),
301            json!({"backhaul_steering": "1", "role": "auto", "is_master": "1"})
302        );
303        // Fields the device does not have are left out.
304        assert_eq!(
305            mesh_of(&modules[1..]),
306            json!({"role": "auto", "is_master": "1"})
307        );
308    }
309
310    #[test]
311    fn rejects_invalid_json() {
312        assert!(matches!(parse("<html>"), Err(Error::Invalid { .. })));
313    }
314}