Skip to main content

fritz_core/
exposure.rs

1//! What of the home network can be reached from the internet or managed
2//! from outside: remote access, MyFRITZ, dynamic DNS, port forwardings, an
3//! exposed host, UPnP, FTP from the internet, shared links, VPN, provider
4//! management (TR-069) and USP controllers.
5//!
6//! Only getters are called, and the settings modules `forwardrules` and
7//! `vpn` of the web interface are only read. No passwords or credentials
8//! are read: login names come masked, and the URLs of shared links, which
9//! grant access, are left out. What a device lacks is unknown, not an
10//! error.
11
12use serde::Serialize;
13use serde_json::Value;
14
15use crate::generic::Error;
16use crate::ports::{self, Forwarding};
17use crate::read::{Reader, Values};
18use crate::session::Session;
19use crate::settings;
20
21mod items;
22
23pub use items::{Item, Kind, Severity, State};
24
25/// The most entries read of each list, as a guard against a device that
26/// never ends a list.
27const MAX_ENTRIES: u32 = 100;
28
29/// Everything that can be reached from the internet, with a summary of
30/// each [`Kind`] in [`items`](Self::items). Parts the device does not
31/// report are `None`.
32#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
33pub struct Exposure {
34    /// One item per [`Kind`], in order, with its state and severity.
35    pub items: Vec<Item>,
36    pub remote_access: Option<RemoteAccess>,
37    pub myfritz: Option<MyFritz>,
38    pub dynamic_dns: Option<DynamicDns>,
39    /// The port forwardings, enabled or not.
40    pub port_forwardings: Option<Vec<Forwarding>>,
41    /// Whether all ports of one host are open to the internet.
42    pub exposed_host: Option<bool>,
43    /// Whether hosts may open ports themselves through UPnP.
44    pub upnp: Option<bool>,
45    pub ftp: Option<Ftp>,
46    pub shared_links: Option<Vec<Link>>,
47    pub vpn: Option<Vec<Vpn>>,
48    pub tr069: Option<Tr069>,
49    pub usp: Option<Usp>,
50}
51
52/// Remote access to the web interface of the device over HTTPS.
53#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
54pub struct RemoteAccess {
55    pub enabled: bool,
56    pub port: Option<u16>,
57    /// Whether the certificate comes from Let's Encrypt rather than being
58    /// signed by the device itself.
59    pub lets_encrypt: Option<bool>,
60}
61
62/// The MyFRITZ account of the device and the services it shares.
63#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
64pub struct MyFritz {
65    pub enabled: bool,
66    pub registered: Option<bool>,
67    /// The `MyFRITZ` address of the device. Identifying.
68    pub address: Option<String>,
69    pub services: Vec<Service>,
70}
71
72/// A service of the home network shared through `MyFRITZ`.
73#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
74pub struct Service {
75    /// The name of the service. Identifying.
76    pub name: Option<String>,
77    pub enabled: bool,
78    /// Like `https`.
79    pub scheme: Option<String>,
80    pub port: Option<u16>,
81}
82
83/// A dynamic DNS name of the device at a provider.
84#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
85pub struct DynamicDns {
86    pub enabled: bool,
87    /// The domain. Identifying.
88    pub domain: Option<String>,
89    pub provider: Option<String>,
90}
91
92/// Access to the storage of the device by FTP from the internet.
93#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
94pub struct Ftp {
95    pub enabled: bool,
96    pub port: Option<u16>,
97    /// Whether only connections with TLS are allowed.
98    pub tls_only: Option<bool>,
99}
100
101/// A link that shares a file or folder of the storage. Its URL grants
102/// access and is never read.
103#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
104pub struct Link {
105    pub valid: bool,
106    /// The shared file or folder. Identifying.
107    pub path: Option<String>,
108    pub directory: bool,
109    /// When the link expires, or `None` if it never does.
110    pub expires: Option<String>,
111    pub accesses: Option<u32>,
112    /// The most accesses allowed, or `None` without a limit.
113    pub access_limit: Option<u32>,
114}
115
116/// A VPN connection from the settings module `vpn`.
117#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
118pub struct Vpn {
119    /// The name of the connection. Identifying.
120    pub name: Option<String>,
121}
122
123/// Management of the device by the provider (TR-069).
124#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
125pub struct Tr069 {
126    /// Whether a management server is set.
127    pub enabled: bool,
128    /// The management server. Identifying.
129    pub url: Option<String>,
130    /// Whether the device contacts the server at intervals.
131    pub periodic_inform: Option<bool>,
132}
133
134/// Controllers that may manage the device through USP.
135#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
136pub struct Usp {
137    /// Whether `MyFRITZ` may manage the device through USP.
138    pub myfritz: Option<bool>,
139    pub controllers: Vec<Controller>,
140}
141
142/// A USP controller.
143#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
144pub struct Controller {
145    pub enabled: bool,
146    /// The host of the controller. Identifying.
147    pub host: Option<String>,
148    pub port: Option<u16>,
149    pub tls: Option<bool>,
150}
151
152impl Exposure {
153    /// Replaces the values that identify the owner, like the `MyFRITZ`
154    /// address, domains, names, shared paths, hosts and the addresses a
155    /// forwarding is limited to, with `hidden`, for output that must not
156    /// identify them.
157    #[must_use]
158    pub fn without_identifying(mut self, hidden: &str) -> Self {
159        let hide = |value: &mut Option<String>| {
160            if value.is_some() {
161                *value = Some(hidden.to_owned());
162            }
163        };
164        if let Some(myfritz) = &mut self.myfritz {
165            hide(&mut myfritz.address);
166            myfritz.services.iter_mut().for_each(|s| hide(&mut s.name));
167        }
168        if let Some(dns) = &mut self.dynamic_dns {
169            hide(&mut dns.domain);
170        }
171        let forwardings = self.port_forwardings.iter_mut().flatten();
172        forwardings.for_each(|f| hide(&mut f.remote_host));
173        let links = self.shared_links.iter_mut().flatten();
174        links.for_each(|l| hide(&mut l.path));
175        self.vpn
176            .iter_mut()
177            .flatten()
178            .for_each(|v| hide(&mut v.name));
179        if let Some(tr069) = &mut self.tr069 {
180            hide(&mut tr069.url);
181        }
182        let controllers = self.usp.iter_mut().flat_map(|u| &mut u.controllers);
183        controllers.for_each(|c| hide(&mut c.host));
184        self
185    }
186
187    /// Whether an item has the severity `warning`.
188    pub fn has_warning(&self) -> bool {
189        self.items.iter().any(|i| i.severity == Severity::Warning)
190    }
191}
192
193/// Reads what can be reached from the internet: through TR-064, and the
194/// exposed host and VPN through the web interface with `session`, which
195/// it then logs out. Without a session, those two are unknown.
196///
197/// # Errors
198///
199/// The errors of reading other than missing parts, see
200/// [`Reader::try_read`].
201pub async fn exposure(reader: &mut Reader, session: Option<Session>) -> Result<Exposure, Error> {
202    let web = session.is_some();
203    let (exposed_host, vpn, upnp_control) = match session {
204        Some(session) => {
205            let read = (
206                exposed_host(&session).await,
207                vpn(&session).await,
208                upnp_control(&session).await,
209            );
210            // The device ends the session itself after a while.
211            let _ = session.logout().await;
212            read
213        }
214        None => (None, None, None),
215    };
216    let ports = ports::ports(reader).await?;
217    // Hosts open ports only if UPnP is on and may change settings.
218    let upnp = match ports.upnp {
219        Some(true) => upnp_control,
220        other => other,
221    };
222    let mut exposure = Exposure {
223        items: Vec::new(),
224        remote_access: remote_access(reader).await?,
225        myfritz: myfritz(reader).await?,
226        dynamic_dns: dynamic_dns(reader).await?,
227        port_forwardings: ports.listed.then_some(ports.forwardings),
228        exposed_host,
229        upnp,
230        ftp: ftp(reader).await?,
231        shared_links: shared_links(reader).await?,
232        vpn,
233        tr069: tr069(reader).await?,
234        usp: usp(reader).await?,
235    };
236    exposure.items = items::items(&exposure, web);
237    Ok(exposure)
238}
239
240async fn remote_access(reader: &mut Reader) -> Result<Option<RemoteAccess>, Error> {
241    let info = reader
242        .try_read("X_AVM-DE_RemoteAccess1", "GetInfo", &[])
243        .await?;
244    Ok(info.map(|info| RemoteAccess {
245        enabled: info.flag("NewEnabled").unwrap_or_default(),
246        port: port(&info, "NewPort"),
247        lets_encrypt: info.flag("NewLetsEncryptEnabled"),
248    }))
249}
250
251async fn dynamic_dns(reader: &mut Reader) -> Result<Option<DynamicDns>, Error> {
252    let info = reader
253        .try_read("X_AVM-DE_RemoteAccess1", "GetDDNSInfo", &[])
254        .await?;
255    Ok(info.map(|info| DynamicDns {
256        enabled: info.flag("NewEnabled").unwrap_or_default(),
257        domain: info.text("NewDomain"),
258        provider: info.text("NewProviderName"),
259    }))
260}
261
262async fn myfritz(reader: &mut Reader) -> Result<Option<MyFritz>, Error> {
263    const SERVICE: &str = "X_AVM-DE_MyFritz1";
264    let Some(info) = reader.try_read(SERVICE, "GetInfo", &[]).await? else {
265        return Ok(None);
266    };
267    let services = reader
268        .entries(
269            SERVICE,
270            ("GetNumberOfServices", "NewNumberOfServices"),
271            ("GetServiceByIndex", "NewIndex"),
272            MAX_ENTRIES,
273        )
274        .await?
275        .map_or_else(Vec::new, |(_, entries)| entries);
276    Ok(Some(MyFritz {
277        enabled: info.flag("NewEnabled").unwrap_or_default(),
278        registered: info.flag("NewDeviceRegistered"),
279        address: info.text("NewDynDNSName"),
280        services: services
281            .iter()
282            .map(|entry| Service {
283                name: entry.text("NewName"),
284                enabled: entry.flag("NewEnabled").unwrap_or_default(),
285                scheme: entry.text("NewScheme"),
286                port: port(entry, "NewPort"),
287            })
288            .collect(),
289    }))
290}
291
292async fn ftp(reader: &mut Reader) -> Result<Option<Ftp>, Error> {
293    let info = reader.try_read("X_AVM-DE_Storage1", "GetInfo", &[]).await?;
294    Ok(info.map(|info| Ftp {
295        enabled: info.flag("NewFTPWANEnable").unwrap_or_default(),
296        port: port(&info, "NewFTPWANPort"),
297        tls_only: info.flag("NewFTPWANSSLOnly"),
298    }))
299}
300
301async fn shared_links(reader: &mut Reader) -> Result<Option<Vec<Link>>, Error> {
302    let entries = reader
303        .entries(
304            "X_AVM-DE_Filelinks1",
305            ("GetNumberOfFilelinkEntries", "NewNumberOfEntries"),
306            ("GetGenericFilelinkEntry", "NewIndex"),
307            MAX_ENTRIES,
308        )
309        .await?;
310    Ok(entries.map(|(_, entries)| entries.iter().map(link).collect()))
311}
312
313/// A shared link from the answer of `GetGenericFilelinkEntry`, without its
314/// URL. `NewExpire` is the number of days the link was made for, 0 for no
315/// end.
316fn link(entry: &Values) -> Link {
317    let expires = entry.number::<u32>("NewExpire").unwrap_or_default() != 0;
318    Link {
319        valid: entry.flag("NewValid").unwrap_or_default(),
320        path: entry.text("NewPath"),
321        directory: entry.flag("NewIsDirectory").unwrap_or_default(),
322        expires: entry.text("NewExpireDate").filter(|_| expires),
323        accesses: entry.number("NewAccessCount"),
324        access_limit: entry
325            .number("NewAccessCountLimit")
326            .filter(|&n: &u32| n != 0),
327    }
328}
329
330async fn tr069(reader: &mut Reader) -> Result<Option<Tr069>, Error> {
331    let info = reader.try_read("ManagementServer1", "GetInfo", &[]).await?;
332    Ok(info.map(|info| {
333        let url = info.text("NewURL");
334        Tr069 {
335            enabled: url.is_some(),
336            url,
337            periodic_inform: info.flag("NewPeriodicInformEnable"),
338        }
339    }))
340}
341
342async fn usp(reader: &mut Reader) -> Result<Option<Usp>, Error> {
343    const SERVICE: &str = "X_AVM-DE_USPController1";
344    let Some((_, entries)) = reader
345        .entries(
346            SERVICE,
347            (
348                "GetUSPControllerNumberOfEntries",
349                "NewUSPControllerNumberOfEntries",
350            ),
351            ("GetUSPControllerByIndex", "NewIndex"),
352            MAX_ENTRIES,
353        )
354        .await?
355    else {
356        return Ok(None);
357    };
358    let myfritz = reader
359        .try_read(SERVICE, "GetUSPMyFRITZEnable", &[])
360        .await?
361        .and_then(|values| values.flag("NewUSPMyFRITZEnabled"));
362    Ok(Some(Usp {
363        myfritz,
364        controllers: entries
365            .iter()
366            .map(|entry| Controller {
367                enabled: entry.flag("NewEnable").unwrap_or_default(),
368                host: entry.text("NewHostname"),
369                port: port(entry, "NewPort"),
370                tls: entry.flag("NewUseTLS"),
371            })
372            .collect(),
373    }))
374}
375
376/// A port, unless it is 0.
377fn port(values: &Values, name: &str) -> Option<u16> {
378    values.number(name).filter(|&p| p != 0)
379}
380
381/// Whether a host is exposed, from the settings module `forwardrules`.
382async fn exposed_host(session: &Session) -> Option<bool> {
383    let module = settings::module(session, "forwardrules").await.ok()?;
384    flag(module.get("use_exposed_host")?)
385}
386
387/// Whether hosts may change settings of the device through UPnP, like
388/// opening ports, from the settings module `box`.
389async fn upnp_control(session: &Session) -> Option<bool> {
390    let module = settings::module(session, "box").await.ok()?;
391    flag(module.get("upnp_control_activated")?)
392}
393
394/// A flag of the web interface, `"1"` or `true`.
395fn flag(value: &Value) -> Option<bool> {
396    match value {
397        Value::String(flag) => Some(flag == "1"),
398        Value::Bool(flag) => Some(*flag),
399        _ => None,
400    }
401}
402
403/// The VPN connections in the settings module `vpn`.
404async fn vpn(session: &Session) -> Option<Vec<Vpn>> {
405    let module = settings::module(session, "vpn").await.ok()?;
406    Some(connections(&module))
407}
408
409/// The VPN connections of the settings module `vpn`: the objects with a
410/// name in its lists, at any depth.
411fn connections(value: &Value) -> Vec<Vpn> {
412    match value {
413        Value::Object(object) => object.values().flat_map(connections).collect(),
414        Value::Array(entries) => entries
415            .iter()
416            .flat_map(|entry| match entry.get("name") {
417                Some(Value::String(name)) => vec![Vpn {
418                    name: Some(name.clone()).filter(|n| !n.is_empty()),
419                }],
420                _ => connections(entry),
421            })
422            .collect(),
423        _ => Vec::new(),
424    }
425}
426
427#[cfg(test)]
428mod tests {
429    use serde_json::json;
430
431    use super::*;
432    use crate::read::values;
433
434    #[test]
435    fn reads_flags_of_the_web_interface() {
436        assert_eq!(flag(&json!("1")), Some(true));
437        assert_eq!(flag(&json!("0")), Some(false));
438        assert_eq!(flag(&json!(true)), Some(true));
439        assert_eq!(flag(&json!(1)), None);
440    }
441
442    #[test]
443    fn reads_shared_links_without_their_url() {
444        let entry = values(&[
445            ("NewValid", "1"),
446            ("NewPath", "/photos"),
447            ("NewIsDirectory", "1"),
448            ("NewUrl", "https://link.example/secret"),
449            ("NewExpire", "7"),
450            ("NewExpireDate", "2026-12-01T00:00:00"),
451            ("NewAccessCount", "2"),
452            ("NewAccessCountLimit", "0"),
453        ]);
454        let link = link(&entry);
455        assert_eq!(
456            link,
457            Link {
458                valid: true,
459                path: Some("/photos".to_owned()),
460                directory: true,
461                expires: Some("2026-12-01T00:00:00".to_owned()),
462                accesses: Some(2),
463                access_limit: None,
464            }
465        );
466        let forever = values(&[("NewExpire", "0"), ("NewExpireDate", "x")]);
467        assert_eq!(super::link(&forever).expires, None);
468    }
469
470    #[test]
471    fn finds_vpn_connections_at_any_depth() {
472        let module = json!({
473            "enabled": "1",
474            "wireguard": {"connections": [{"name": "phone"}, {"name": ""}]},
475            "ipsec": [{"name": "office", "user": [{"name": "nested"}]}],
476            "other": [1, "x", {"id": 3}],
477        });
478        let names: Vec<Option<String>> = connections(&module).into_iter().map(|c| c.name).collect();
479        assert_eq!(
480            names,
481            [Some("office".to_owned()), Some("phone".to_owned()), None]
482        );
483        assert_eq!(connections(&json!("text")), []);
484    }
485
486    #[test]
487    fn hides_what_identifies_the_owner() {
488        let named = |name: &str| Some(name.to_owned());
489        let exposure = Exposure {
490            myfritz: Some(MyFritz {
491                address: named("box.myfritz.example"),
492                services: vec![Service {
493                    name: named("nas"),
494                    ..Service::default()
495                }],
496                ..MyFritz::default()
497            }),
498            dynamic_dns: Some(DynamicDns {
499                domain: named("home.example"),
500                ..DynamicDns::default()
501            }),
502            port_forwardings: Some(vec![Forwarding {
503                remote_host: named("198.51.100.7"),
504                description: named("nas"),
505                ..Forwarding::default()
506            }]),
507            shared_links: Some(vec![Link {
508                path: named("/photos"),
509                ..Link::default()
510            }]),
511            vpn: Some(vec![Vpn {
512                name: named("phone"),
513            }]),
514            tr069: Some(Tr069 {
515                url: named("https://acs.example"),
516                ..Tr069::default()
517            }),
518            usp: Some(Usp {
519                myfritz: None,
520                controllers: vec![Controller {
521                    host: named("usp.example"),
522                    ..Controller::default()
523                }],
524            }),
525            ..Exposure::default()
526        };
527        let hidden = exposure.without_identifying("x");
528        let json = serde_json::to_string(&hidden).unwrap();
529        for value in [
530            "box.myfritz.example",
531            "home.example",
532            "198.51.100.7",
533            "/photos",
534            "phone",
535            "acs.example",
536            "usp.example",
537        ] {
538            assert!(!json.contains(value), "{value} in {json}");
539        }
540        // Not identifying, as in `fritz_ports`.
541        assert!(json.contains("\"description\":\"nas\""), "{json}");
542        // Missing values stay missing.
543        let empty = Exposure::default().without_identifying("x");
544        assert_eq!(empty, Exposure::default());
545    }
546}