tirith_core/
script_analysis.rs1use once_cell::sync::Lazy;
2use regex::Regex;
3use serde::Serialize;
4
5#[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
25pub 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
56pub fn detect_interpreter(content: &str) -> &str {
58 if let Some(first_line) = content.lines().next() {
59 if first_line.starts_with("#!") {
60 let shebang = first_line.trim_start_matches("#!");
61 let parts: Vec<&str> = shebang.split_whitespace().collect();
62 if let Some(prog) = parts.first() {
63 let base = prog.rsplit('/').next().unwrap_or(prog);
64 match base {
65 "env" => {
66 if let Some(actual) = parts.get(1) {
67 return actual;
68 }
69 }
70 other => return other,
71 }
72 }
73 }
74 }
75 "sh" }