1use std::fmt;
10
11use tr064::{Action, Direction, Service};
12
13use crate::names::{Sensitivity, sensitivity, words};
14
15const DENIED_GETTERS: &[(&str, &str)] = &[
17 (
18 "X_AVM-DE_GetConfigFile",
19 "exports the whole configuration including passwords",
20 ),
21 (
22 "GetPersistentData",
23 "returns opaque data that can hold credentials",
24 ),
25];
26
27const CRITICAL_SERVICES: &[&str] = &[
31 "DeviceConfig",
32 "DeviceInfo",
33 "LANConfigSecurity",
34 "LANHostConfigManagement",
35 "Layer3Forwarding",
36 "ManagementServer",
37 "UserInterface",
38 "X_AVM-DE_AppSetup",
39 "X_AVM-DE_Auth",
40 "X_AVM-DE_MyFritz",
41 "X_AVM-DE_RemoteAccess",
42 "X_AVM-DE_Storage",
43 "X_AVM-DE_USPController",
44 "X_AVM-DE_WANMobileConnection",
45];
46
47const CRITICAL_WORDS: &[&str] = &["dial", "firmware", "reboot", "reset", "update", "upgrade"];
50
51const WRITE_VERBS: &[&str] = &[
54 "add", "del", "delete", "discard", "disallow", "mark", "new", "set",
55];
56
57#[derive(Debug, Clone, PartialEq, Eq)]
59pub enum Class {
60 Read,
62 Personal,
65 Secret { reason: String },
67 Write,
69 Critical { reason: String },
72}
73
74impl Class {
75 pub fn name(&self) -> &'static str {
77 match self {
78 Self::Read => "read",
79 Self::Personal => "personal",
80 Self::Secret { .. } => "secret",
81 Self::Write => "write",
82 Self::Critical { .. } => "critical",
83 }
84 }
85
86 pub fn is_read(&self) -> bool {
88 matches!(self, Self::Read | Self::Personal)
89 }
90
91 pub fn reason(&self) -> Option<&str> {
93 match self {
94 Self::Secret { reason } | Self::Critical { reason } => Some(reason),
95 _ => None,
96 }
97 }
98}
99
100impl fmt::Display for Class {
101 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103 match self.reason() {
104 Some(reason) => write!(f, "{}: {reason}", self.name()),
105 None => f.write_str(self.name()),
106 }
107 }
108}
109
110pub fn is_getter(action: &str) -> bool {
113 action.starts_with("Get") || action.starts_with("X_AVM-DE_Get")
114}
115
116pub fn classify(service: &Service, action: &Action) -> Class {
118 let name = action.name.as_str();
119 if !is_getter(name) {
120 return change(service, action);
121 }
122 if let Some(reason) = denial(service, action) {
123 return Class::Secret { reason };
124 }
125 if is_personal(service, name) {
126 return Class::Personal;
127 }
128 Class::Read
129}
130
131fn denial(service: &Service, action: &Action) -> Option<String> {
133 let name = action.name.as_str();
134 if let Some((_, reason)) = DENIED_GETTERS.iter().find(|(n, _)| *n == name) {
135 return Some((*reason).to_owned());
136 }
137 if service.name() == "X_VoIP" && name.starts_with("X_AVM-DE_GetClient") {
138 return Some("returns the credentials of telephony clients".to_owned());
139 }
140 if sensitivity(name) == Sensitivity::Secret {
141 return Some("the name points to a secret".to_owned());
142 }
143 action
144 .arguments
145 .iter()
146 .find(|a| a.direction == Direction::Out && sensitivity(&a.name) == Sensitivity::Secret)
147 .map(|a| format!("returns {}, which points to a secret", a.name))
148}
149
150pub(crate) fn is_personal(service: &Service, action: &str) -> bool {
153 match service.name() {
154 "X_AVM-DE_OnTel" => action == "GetCallList" || action.starts_with("GetPhonebook"),
155 "X_AVM-DE_TAM" => action == "GetMessageList",
156 "DeviceInfo" => action == "GetDeviceLog",
157 _ => false,
158 }
159}
160
161pub fn is_personal_output(name: &str) -> bool {
164 name == "NewDeviceLog"
165}
166
167fn change(service: &Service, action: &Action) -> Class {
169 let critical = |reason: String| Class::Critical { reason };
170 let service_name = service.name();
171 if service_name.starts_with("WAN") || CRITICAL_SERVICES.contains(&service_name) {
172 return critical(format!("changes {service_name}"));
173 }
174 let name = action.name.as_str();
175 if sensitivity(name) == Sensitivity::Secret {
176 return critical("sets a secret".to_owned());
177 }
178 if let Some(input) = action
179 .inputs()
180 .find(|a| sensitivity(&a.name) == Sensitivity::Secret)
181 {
182 return critical(format!("sets {}, which points to a secret", input.name));
183 }
184 let words = words(name);
185 if let Some(word) = words.iter().find(|w| CRITICAL_WORDS.contains(&w.as_str())) {
186 return critical(format!("the name says {word}"));
187 }
188 let verb = words
189 .iter()
190 .find(|w| !["x", "avm", "de"].contains(&w.as_str()))
191 .map_or("", String::as_str);
192 if WRITE_VERBS.contains(&verb) {
193 Class::Write
194 } else {
195 critical(format!("unknown kind of action {name}"))
196 }
197}
198
199#[cfg(test)]
200mod tests {
201 use tr064::Argument;
202
203 use super::*;
204
205 fn service(name: &str) -> Service {
206 Service {
207 service_type: format!("urn:dslforum-org:service:{name}:1"),
208 service_id: format!("urn:{name}-com:serviceId:{name}1"),
209 control_url: "/upnp/control/x".to_owned(),
210 event_sub_url: None,
211 scpd_url: "/x.xml".to_owned(),
212 }
213 }
214
215 fn action(name: &str, outputs: &[&str]) -> Action {
216 with_arguments(name, Direction::Out, outputs)
217 }
218
219 fn with_arguments(name: &str, direction: Direction, arguments: &[&str]) -> Action {
220 Action {
221 name: name.to_owned(),
222 arguments: arguments
223 .iter()
224 .map(|name| Argument {
225 name: (*name).to_owned(),
226 direction,
227 related_state_variable: "X".to_owned(),
228 })
229 .collect(),
230 }
231 }
232
233 fn class(service_name: &str, name: &str) -> Class {
234 classify(&service(service_name), &action(name, &[]))
235 }
236
237 #[test]
238 fn reads_getters() {
239 assert_eq!(class("DeviceInfo", "GetInfo"), Class::Read);
240 assert_eq!(class("Hosts", "X_AVM-DE_GetHostListPath"), Class::Read);
241 assert_eq!(class("X_AVM-DE_Auth", "GetState"), Class::Read);
242 assert_eq!(class("X_AVM-DE_OnTel", "GetCallList"), Class::Personal);
243 }
244
245 #[test]
246 fn keeps_secrets() {
247 assert_eq!(
248 class("DeviceConfig", "X_AVM-DE_GetConfigFile"),
249 Class::Secret {
250 reason: "exports the whole configuration including passwords".to_owned()
251 }
252 );
253 assert_eq!(
254 classify(
255 &service("WLANConfiguration"),
256 &action("GetInfo", &["NewSSID", "NewWEPKey0"])
257 )
258 .to_string(),
259 "secret: returns NewWEPKey0, which points to a secret"
260 );
261 }
262
263 #[test]
264 fn tells_writes_from_critical_changes() {
265 for (service_name, name) in [
266 ("WLANConfiguration", "SetSSID"),
267 ("WLANConfiguration", "SetDefaultWEPKeyIndex"),
268 ("Hosts", "X_AVM-DE_SetFriendlyNameByMAC"),
269 ("X_AVM-DE_OnTel", "DeletePhonebookEntryUID"),
270 ("X_AVM-DE_HostFilter", "DisallowWANAccessByIP"),
271 ("X_AVM-DE_Filelinks", "NewFilelinkEntry"),
272 ("X_VoIP", "X_AVM-DE_DelVoIPAccount"),
273 ("Other", "X_SetEnable"),
274 ] {
275 assert_eq!(class(service_name, name), Class::Write, "{name}");
276 }
277 for (service_name, name, reason) in [
278 ("DeviceConfig", "Reboot", "changes DeviceConfig"),
279 (
280 "WANPPPConnection",
281 "SetUserName",
282 "changes WANPPPConnection",
283 ),
284 ("WLANConfiguration", "SetSecurityKeys", "sets a secret"),
285 ("X_VoIP", "X_AVM-DE_DialNumber", "the name says dial"),
286 ("Hosts", "X_AVM-DE_HostDoUpdate", "the name says update"),
287 (
288 "Hosts",
289 "X_AVM-DE_WakeOnLANByMACAddress",
290 "unknown kind of action X_AVM-DE_WakeOnLANByMACAddress",
291 ),
292 ("Other", "__", "unknown kind of action __"),
293 ] {
294 assert_eq!(
295 class(service_name, name),
296 Class::Critical {
297 reason: reason.to_owned()
298 },
299 "{name}"
300 );
301 }
302 let set_client = with_arguments(
303 "X_AVM-DE_SetClient",
304 Direction::In,
305 &["NewX_AVM-DE_ClientIndex", "NewX_AVM-DE_ClientPassword"],
306 );
307 assert_eq!(
308 classify(&service("X_VoIP"), &set_client).to_string(),
309 "critical: sets NewX_AVM-DE_ClientPassword, which points to a secret"
310 );
311 }
312
313 #[test]
314 fn finds_personal_outputs() {
315 assert!(is_personal_output("NewDeviceLog"));
316 assert!(!is_personal_output("NewDeviceLogPath"));
317 }
318
319 #[test]
320 fn names_the_classes() {
321 let names: Vec<String> = [
322 Class::Read,
323 Class::Personal,
324 Class::Write,
325 class("DeviceConfig", "Reboot"),
326 ]
327 .iter()
328 .map(ToString::to_string)
329 .collect();
330 assert_eq!(
331 names,
332 [
333 "read",
334 "personal",
335 "write",
336 "critical: changes DeviceConfig"
337 ]
338 );
339 assert!(Class::Personal.is_read());
340 assert!(!Class::Write.is_read());
341 }
342}