Skip to main content

tirith_core/
script_analysis.rs

1use once_cell::sync::Lazy;
2use regex::Regex;
3use serde::Serialize;
4
5/// Result of static script analysis.
6#[derive(Debug, Clone, Serialize)]
7pub struct ScriptAnalysis {
8    pub domains_referenced: Vec<String>,
9    pub paths_referenced: Vec<String>,
10    pub has_sudo: bool,
11    pub has_eval: bool,
12    pub has_base64: bool,
13    pub has_curl_wget: bool,
14    pub interpreter: String,
15}
16
17static DOMAIN_RE: Lazy<Regex> = Lazy::new(|| {
18    Regex::new(r"(?:https?://)?([a-zA-Z0-9][-a-zA-Z0-9]*(?:\.[a-zA-Z0-9][-a-zA-Z0-9]*)+)").unwrap()
19});
20
21static PATH_RE: Lazy<Regex> = Lazy::new(|| {
22    Regex::new(r"(?:/(?:usr|etc|var|tmp|opt|home|root|bin|sbin|lib|dev)(?:/[\w.-]+)+)").unwrap()
23});
24
25/// Perform static analysis on script content.
26pub fn analyze(content: &str, interpreter: &str) -> ScriptAnalysis {
27    let mut domains = Vec::new();
28    for cap in DOMAIN_RE.captures_iter(content) {
29        if let Some(m) = cap.get(1) {
30            let domain = m.as_str().to_string();
31            if !domains.contains(&domain) {
32                domains.push(domain);
33            }
34        }
35    }
36
37    let mut paths = Vec::new();
38    for mat in PATH_RE.find_iter(content) {
39        let path = mat.as_str().to_string();
40        if !paths.contains(&path) {
41            paths.push(path);
42        }
43    }
44
45    ScriptAnalysis {
46        domains_referenced: domains,
47        paths_referenced: paths,
48        has_sudo: content.contains("sudo "),
49        has_eval: content.contains("eval ") || content.contains("eval("),
50        has_base64: content.contains("base64"),
51        has_curl_wget: content.contains("curl ") || content.contains("wget "),
52        interpreter: interpreter.to_string(),
53    }
54}
55
56/// Detect interpreter from shebang line.
57pub fn detect_interpreter(content: &str) -> &str {
58    if let Some(first_line) = content.lines().next() {
59        let first_line = first_line.trim();
60        if first_line.starts_with("#!") {
61            let shebang = first_line.trim_start_matches("#!");
62            let parts: Vec<&str> = shebang.split_whitespace().collect();
63            if let Some(prog) = parts.first() {
64                let base = prog.rsplit('/').next().unwrap_or(prog);
65                if base == "env" {
66                    // Skip flags (-S, -i, etc.) and VAR=val assignments
67                    for part in parts.iter().skip(1) {
68                        if part.starts_with('-') || part.contains('=') {
69                            continue;
70                        }
71                        return part;
72                    }
73                } else {
74                    return base;
75                }
76            }
77        }
78    }
79    "sh" // default
80}
81
82#[cfg(test)]
83mod tests {
84    use super::*;
85
86    #[test]
87    fn test_detect_interpreter_env_s() {
88        let content = "#!/usr/bin/env -S python3 -u\nprint('hello')";
89        assert_eq!(detect_interpreter(content), "python3");
90    }
91
92    #[test]
93    fn test_detect_interpreter_env_s_with_var() {
94        let content = "#!/usr/bin/env -S VAR=1 python3\nprint('hello')";
95        assert_eq!(detect_interpreter(content), "python3");
96    }
97
98    #[test]
99    fn test_detect_interpreter_crlf() {
100        let content = "#!/bin/bash\r\necho hello";
101        assert_eq!(detect_interpreter(content), "bash");
102    }
103
104    #[test]
105    fn test_detect_interpreter_basic() {
106        let content = "#!/usr/bin/env python3\nprint('hello')";
107        assert_eq!(detect_interpreter(content), "python3");
108    }
109
110    #[test]
111    fn test_detect_interpreter_no_shebang() {
112        let content = "echo hello";
113        assert_eq!(detect_interpreter(content), "sh");
114    }
115}