Skip to main content

cmtraceopen_parser/intune/
policy_parser.rs

1//! Parses "Get policies" JSON payloads from AppWorkload logs.
2//!
3//! These payloads contain per-app policy metadata including detection rules
4//! with base64-encoded PowerShell scripts.
5
6use std::collections::HashMap;
7
8use base64::{engine::general_purpose::STANDARD, Engine};
9
10use super::ime_parser::ImeLine;
11use super::models::{AppPolicyMetadata, DetectionRuleMetadata, ReturnCodeEntry};
12
13const GET_POLICIES_PREFIX: &str = "Get policies = ";
14
15/// Extract policy metadata from all "Get policies" lines in a set of parsed log lines.
16pub fn extract_policy_metadata(lines: &[ImeLine]) -> HashMap<String, AppPolicyMetadata> {
17    let mut result = HashMap::new();
18
19    for line in lines {
20        if !line.message.starts_with(GET_POLICIES_PREFIX) {
21            continue;
22        }
23
24        let json_str = &line.message[GET_POLICIES_PREFIX.len()..];
25        let sanitized = sanitize_json(json_str);
26
27        let Ok(arr) = serde_json::from_str::<Vec<serde_json::Value>>(&sanitized) else {
28            log::warn!(
29                "event=policy_parse_fail line={} reason=invalid_json",
30                line.line_number
31            );
32            continue;
33        };
34
35        for obj in &arr {
36            if let Some(policy) = parse_single_policy(obj) {
37                result.insert(policy.id.clone(), policy);
38            }
39        }
40    }
41
42    log::debug!("event=policy_extraction_complete count={}", result.len());
43    result
44}
45
46/// Sanitize JSON that may contain invalid escape sequences (e.g. Windows paths
47/// with unescaped backslashes like `\Package` or `\norestart`).
48fn sanitize_json(input: &str) -> String {
49    let mut out = String::with_capacity(input.len());
50    let mut chars = input.chars().peekable();
51
52    while let Some(ch) = chars.next() {
53        if ch == '\\' {
54            if let Some(&next) = chars.peek() {
55                // Valid JSON escape chars: " \ / b f n r t u
56                if matches!(next, '"' | '\\' | '/' | 'b' | 'f' | 'n' | 'r' | 't' | 'u') {
57                    out.push('\\');
58                    out.push(next);
59                    chars.next(); // consume the valid escape char
60                } else {
61                    // Invalid escape — double the backslash to make it literal
62                    out.push_str("\\\\");
63                }
64            } else {
65                out.push('\\');
66            }
67        } else {
68            out.push(ch);
69        }
70    }
71    out
72}
73
74fn parse_single_policy(obj: &serde_json::Value) -> Option<AppPolicyMetadata> {
75    let id = obj.get("Id")?.as_str()?.to_string();
76    let name = obj
77        .get("Name")
78        .and_then(|v| v.as_str())
79        .unwrap_or("Unknown")
80        .to_string();
81
82    let intent = obj.get("Intent").and_then(|v| v.as_i64()).map(|v| v as i32);
83    let target_type = obj
84        .get("TargetType")
85        .and_then(|v| v.as_i64())
86        .map(|v| v as i32);
87    let install_command_line = obj
88        .get("InstallCommandLine")
89        .and_then(|v| v.as_str())
90        .map(String::from);
91    let uninstall_command_line = obj
92        .get("UninstallCommandLine")
93        .and_then(|v| v.as_str())
94        .map(String::from);
95    let install_behavior = obj
96        .get("InstallBehavior")
97        .and_then(|v| v.as_i64())
98        .map(|v| v as i32);
99    let requirement_rules = obj
100        .get("RequirementRules")
101        .and_then(|v| v.as_str())
102        .map(String::from);
103
104    let detection_rules = parse_detection_rules(obj);
105    let return_codes = parse_return_codes(obj);
106
107    Some(AppPolicyMetadata {
108        id,
109        name,
110        intent,
111        target_type,
112        install_command_line,
113        uninstall_command_line,
114        detection_rules,
115        return_codes,
116        requirement_rules,
117        install_behavior,
118    })
119}
120
121/// Parse the nested DetectionRule JSON string.
122///
123/// The field is a JSON-escaped string containing a JSON array:
124/// ```json
125/// "DetectionRule": "[{\"DetectionType\":3,\"DetectionText\":\"{...}\"}]"
126/// ```
127fn parse_detection_rules(obj: &serde_json::Value) -> Vec<DetectionRuleMetadata> {
128    let Some(dr_str) = obj.get("DetectionRule").and_then(|v| v.as_str()) else {
129        return Vec::new();
130    };
131
132    let Ok(rules) = serde_json::from_str::<Vec<serde_json::Value>>(dr_str) else {
133        return Vec::new();
134    };
135
136    rules
137        .iter()
138        .filter_map(|rule| {
139            let detection_type = rule.get("DetectionType")?.as_i64()? as i32;
140
141            let (script_body, enforce_signature_check, run_as_32_bit) = if detection_type == 3 {
142                parse_script_detection_text(rule)
143            } else {
144                (None, None, None)
145            };
146
147            Some(DetectionRuleMetadata {
148                detection_type,
149                script_body,
150                enforce_signature_check,
151                run_as_32_bit,
152            })
153        })
154        .collect()
155}
156
157/// Parse DetectionText for script-type rules (DetectionType 3).
158///
159/// The DetectionText is itself a JSON-escaped string:
160/// ```json
161/// "{\"EnforceSignatureCheck\":0,\"RunAs32Bit\":0,\"ScriptBody\":\"<base64>\"}"
162/// ```
163fn parse_script_detection_text(
164    rule: &serde_json::Value,
165) -> (Option<String>, Option<bool>, Option<bool>) {
166    let dt_str = match rule.get("DetectionText").and_then(|v| v.as_str()) {
167        Some(s) => s,
168        None => return (None, None, None),
169    };
170
171    let dt: serde_json::Value = match serde_json::from_str(dt_str) {
172        Ok(v) => v,
173        Err(_) => return (None, None, None),
174    };
175
176    let enforce_signature_check = dt
177        .get("EnforceSignatureCheck")
178        .and_then(|v| v.as_i64())
179        .map(|v| v != 0);
180    let run_as_32_bit = dt
181        .get("RunAs32Bit")
182        .and_then(|v| v.as_i64())
183        .map(|v| v != 0);
184
185    let script_body = dt
186        .get("ScriptBody")
187        .and_then(|v| v.as_str())
188        .and_then(decode_script_body);
189
190    (script_body, enforce_signature_check, run_as_32_bit)
191}
192
193/// Decode a base64-encoded PowerShell script body to UTF-8 text.
194fn decode_script_body(encoded: &str) -> Option<String> {
195    if encoded.is_empty() {
196        return None;
197    }
198    let bytes = STANDARD.decode(encoded).ok()?;
199    Some(match String::from_utf8(bytes) {
200        Ok(s) => s,
201        Err(e) => String::from_utf8_lossy(e.as_bytes()).into_owned(),
202    })
203}
204
205/// Parse the ReturnCodes JSON string.
206///
207/// Format: `"[{\"ReturnCode\":0,\"Type\":1},...]"`
208fn parse_return_codes(obj: &serde_json::Value) -> Vec<ReturnCodeEntry> {
209    let Some(rc_str) = obj.get("ReturnCodes").and_then(|v| v.as_str()) else {
210        return Vec::new();
211    };
212
213    let Ok(codes) = serde_json::from_str::<Vec<serde_json::Value>>(rc_str) else {
214        return Vec::new();
215    };
216
217    codes
218        .iter()
219        .filter_map(|code| {
220            let return_code = code.get("ReturnCode")?.as_i64()? as i32;
221            let code_type = code.get("Type")?.as_i64()? as i32;
222            Some(ReturnCodeEntry {
223                return_code,
224                code_type,
225            })
226        })
227        .collect()
228}
229
230#[cfg(test)]
231mod tests {
232    use super::*;
233
234    fn make_line(msg: &str) -> ImeLine {
235        ImeLine {
236            line_number: 1,
237            timestamp: None,
238            timestamp_utc: None,
239            message: msg.to_string(),
240            component: Some("AppWorkload".to_string()),
241        }
242    }
243
244    #[test]
245    fn sanitize_json_fixes_invalid_escapes() {
246        let input = r#"{"path":"C:\Program Files\Package Cache\foo"}"#;
247        let sanitized = sanitize_json(input);
248        let parsed: serde_json::Value = serde_json::from_str(&sanitized).unwrap();
249        let path = parsed["path"].as_str().unwrap();
250        assert!(path.contains("Program Files"));
251        assert!(path.contains("Package Cache"));
252    }
253
254    #[test]
255    fn sanitize_json_preserves_valid_escapes() {
256        let input = r#"{"msg":"line1\nline2","path":"C:\\Users"}"#;
257        let sanitized = sanitize_json(input);
258        let parsed: serde_json::Value = serde_json::from_str(&sanitized).unwrap();
259        assert_eq!(parsed["msg"].as_str().unwrap(), "line1\nline2");
260        assert_eq!(parsed["path"].as_str().unwrap(), "C:\\Users");
261    }
262
263    #[test]
264    fn parse_simple_policy() {
265        let json = r#"Get policies = [{"Id":"abc-123","Name":"Test App","Version":1,"Intent":3,"TargetType":2,"DetectionRule":"[{\"DetectionType\":0}]","ReturnCodes":"[{\"ReturnCode\":0,\"Type\":1}]","InstallCommandLine":"setup.exe /s","UninstallCommandLine":"setup.exe /uninstall","InstallBehavior":0}]"#;
266        let lines = vec![make_line(json)];
267        let result = extract_policy_metadata(&lines);
268
269        assert_eq!(result.len(), 1);
270        let policy = result.get("abc-123").unwrap();
271        assert_eq!(policy.name, "Test App");
272        assert_eq!(policy.intent, Some(3));
273        assert_eq!(policy.install_command_line.as_deref(), Some("setup.exe /s"));
274        assert_eq!(policy.detection_rules.len(), 1);
275        assert_eq!(policy.detection_rules[0].detection_type, 0);
276        assert!(policy.detection_rules[0].script_body.is_none());
277        assert_eq!(policy.return_codes.len(), 1);
278        assert_eq!(policy.return_codes[0].return_code, 0);
279        assert_eq!(policy.return_codes[0].code_type, 1);
280    }
281
282    #[test]
283    fn parse_script_detection_rule() {
284        // Base64 of "Write-Host 'Detected'"
285        let b64 = STANDARD.encode("Write-Host 'Detected'");
286        let json = format!(
287            r#"Get policies = [{{"Id":"def-456","Name":"Script App","DetectionRule":"[{{\"DetectionType\":3,\"DetectionText\":\"{{\\\"EnforceSignatureCheck\\\":0,\\\"RunAs32Bit\\\":1,\\\"ScriptBody\\\":\\\"{b64}\\\"}}\"}}]","ReturnCodes":"[]"}}]"#
288        );
289        let lines = vec![make_line(&json)];
290        let result = extract_policy_metadata(&lines);
291
292        assert_eq!(result.len(), 1);
293        let policy = result.get("def-456").unwrap();
294        assert_eq!(policy.detection_rules.len(), 1);
295
296        let rule = &policy.detection_rules[0];
297        assert_eq!(rule.detection_type, 3);
298        assert_eq!(rule.script_body.as_deref(), Some("Write-Host 'Detected'"));
299        assert_eq!(rule.enforce_signature_check, Some(false));
300        assert_eq!(rule.run_as_32_bit, Some(true));
301    }
302
303    #[test]
304    fn skips_non_policy_lines() {
305        let lines = vec![
306            make_line("[Win32App] Some other message"),
307            make_line("Not a policy line"),
308        ];
309        let result = extract_policy_metadata(&lines);
310        assert!(result.is_empty());
311    }
312
313    #[test]
314    fn handles_malformed_json_gracefully() {
315        let lines = vec![make_line("Get policies = not valid json")];
316        let result = extract_policy_metadata(&lines);
317        assert!(result.is_empty());
318    }
319
320    #[test]
321    fn handles_missing_detection_rule_fields() {
322        let json = r#"Get policies = [{"Id":"ghi-789","Name":"Minimal App"}]"#;
323        let lines = vec![make_line(json)];
324        let result = extract_policy_metadata(&lines);
325
326        assert_eq!(result.len(), 1);
327        let policy = result.get("ghi-789").unwrap();
328        assert!(policy.detection_rules.is_empty());
329        assert!(policy.return_codes.is_empty());
330    }
331}