Skip to main content

tirith_core/rules/
cloaking.rs

1/// Server-side cloaking detection — Unix only.
2///
3/// Fetches a URL with multiple user-agents and compares responses to detect
4/// content differentiation (serving different content to AI bots vs browsers).
5#[cfg(unix)]
6use crate::verdict::{Evidence, Finding, RuleId, Severity};
7
8/// User-agent profiles for cloaking detection.
9#[cfg(unix)]
10const USER_AGENTS: &[(&str, &str)] = &[
11    ("chrome", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"),
12    ("claudebot", "ClaudeBot/1.0"),
13    ("chatgpt", "ChatGPT-User"),
14    ("perplexity", "PerplexityBot/1.0"),
15    ("googlebot", "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"),
16    ("curl", "curl/8.7.1"),
17];
18
19/// Result of a cloaking check.
20#[cfg(unix)]
21pub struct CloakingResult {
22    pub url: String,
23    pub cloaking_detected: bool,
24    pub findings: Vec<Finding>,
25    /// Per-agent response summaries (agent name, status code, content length).
26    pub agent_responses: Vec<AgentResponse>,
27    /// Pairs of agents whose responses differed significantly.
28    pub diff_pairs: Vec<DiffPair>,
29}
30
31#[cfg(unix)]
32pub struct AgentResponse {
33    pub agent_name: String,
34    pub status_code: u16,
35    pub content_length: usize,
36}
37
38#[cfg(unix)]
39pub struct DiffPair {
40    pub agent_a: String,
41    pub agent_b: String,
42    pub diff_chars: usize,
43    /// Full diff text (populated for Pro enrichment).
44    pub diff_text: Option<String>,
45}
46
47#[cfg(unix)]
48impl CloakingResult {
49    /// Serialize to JSON. When `include_diff_text` is true (Pro tier), diff text
50    /// is included in the output; otherwise it is omitted.
51    pub fn to_json(&self, include_diff_text: bool) -> serde_json::Value {
52        serde_json::json!({
53            "url": self.url,
54            "cloaking_detected": self.cloaking_detected,
55            "agents": self.agent_responses.iter().map(|a| {
56                serde_json::json!({
57                    "agent": a.agent_name,
58                    "status_code": a.status_code,
59                    "content_length": a.content_length,
60                })
61            }).collect::<Vec<_>>(),
62            "diffs": self.diff_pairs.iter().map(|d| {
63                let mut entry = serde_json::json!({
64                    "agent_a": d.agent_a,
65                    "agent_b": d.agent_b,
66                    "diff_chars": d.diff_chars,
67                });
68                if include_diff_text {
69                    if let Some(ref text) = d.diff_text {
70                        entry.as_object_mut().unwrap().insert(
71                            "diff_text".into(),
72                            serde_json::json!(text),
73                        );
74                    }
75                }
76                entry
77            }).collect::<Vec<_>>(),
78            "findings": self.findings,
79        })
80    }
81}
82
83/// Check a URL for server-side cloaking.
84#[cfg(unix)]
85pub fn check(url: &str) -> Result<CloakingResult, String> {
86    let client = reqwest::blocking::Client::builder()
87        .timeout(std::time::Duration::from_secs(30))
88        .redirect(reqwest::redirect::Policy::limited(10))
89        .build()
90        .map_err(|e| format!("HTTP client error: {e}"))?;
91
92    const MAX_BODY: usize = 10 * 1024 * 1024; // 10 MiB
93
94    // Fetch with each user-agent
95    let mut responses: Vec<(String, u16, String)> = Vec::new();
96
97    for (name, ua) in USER_AGENTS {
98        match fetch_with_ua(&client, url, ua, MAX_BODY) {
99            Ok((status, body)) => {
100                responses.push((name.to_string(), status, body));
101            }
102            Err(e) => {
103                eprintln!("tirith: cloaking: {name} fetch failed: {e}");
104                responses.push((name.to_string(), 0, String::new()));
105            }
106        }
107    }
108
109    // Check if all fetches failed
110    let successful_count = responses.iter().filter(|(_, s, _)| *s != 0).count();
111    if successful_count == 0 {
112        return Err("all user-agent fetches failed — cannot perform cloaking analysis".to_string());
113    }
114
115    // Use chrome as baseline
116    let baseline_idx = 0; // chrome is first
117    let baseline_body = &responses[baseline_idx].2;
118
119    // If baseline fetch failed (empty body), we cannot reliably compare — return no findings
120    // rather than false-flagging every non-empty response as cloaking.
121    if baseline_body.is_empty() {
122        let agent_responses: Vec<AgentResponse> = responses
123            .iter()
124            .map(|(name, status, body)| AgentResponse {
125                agent_name: name.clone(),
126                status_code: *status,
127                content_length: body.len(),
128            })
129            .collect();
130        return Ok(CloakingResult {
131            url: url.to_string(),
132            cloaking_detected: false,
133            findings: Vec::new(),
134            agent_responses,
135            diff_pairs: Vec::new(),
136        });
137    }
138
139    let baseline_normalized = normalize_html(baseline_body);
140
141    let mut diff_pairs = Vec::new();
142    let mut cloaking_detected = false;
143
144    let agent_responses: Vec<AgentResponse> = responses
145        .iter()
146        .map(|(name, status, body)| AgentResponse {
147            agent_name: name.clone(),
148            status_code: *status,
149            content_length: body.len(),
150        })
151        .collect();
152
153    // Compare each non-baseline response against chrome baseline
154    for (i, (name, _status, body)) in responses.iter().enumerate() {
155        if i == baseline_idx {
156            continue;
157        }
158        if body.is_empty() {
159            continue; // Skip failed fetches
160        }
161
162        let normalized = normalize_html(body);
163        let diff_chars = word_diff_size(&baseline_normalized, &normalized);
164
165        if diff_chars > 10 {
166            cloaking_detected = true;
167            // Generate diff text showing what words differ
168            let diff_detail = generate_diff_text(&baseline_normalized, &normalized);
169            diff_pairs.push(DiffPair {
170                agent_a: "chrome".to_string(),
171                agent_b: name.clone(),
172                diff_chars,
173                diff_text: Some(diff_detail),
174            });
175        }
176    }
177
178    let mut findings = Vec::new();
179    if cloaking_detected {
180        let differing: Vec<&str> = diff_pairs.iter().map(|d| d.agent_b.as_str()).collect();
181        findings.push(Finding {
182            rule_id: RuleId::ServerCloaking,
183            severity: Severity::High,
184            title: "Server-side cloaking detected".to_string(),
185            description: format!(
186                "URL serves different content to different user-agents. \
187                 Differing agents: {}",
188                differing.join(", ")
189            ),
190            evidence: diff_pairs
191                .iter()
192                .map(|d| Evidence::Text {
193                    detail: format!(
194                        "{} vs {}: {} chars different",
195                        d.agent_a, d.agent_b, d.diff_chars
196                    ),
197                })
198                .collect(),
199            human_view: None,
200            agent_view: None,
201            mitre_id: None,
202            custom_rule_id: None,
203        });
204    }
205
206    Ok(CloakingResult {
207        url: url.to_string(),
208        cloaking_detected,
209        findings,
210        agent_responses,
211        diff_pairs,
212    })
213}
214
215#[cfg(unix)]
216fn fetch_with_ua(
217    client: &reqwest::blocking::Client,
218    url: &str,
219    ua: &str,
220    max_body: usize,
221) -> Result<(u16, String), String> {
222    let response = client
223        .get(url)
224        .header("User-Agent", ua)
225        .send()
226        .map_err(|e| format!("request failed: {e}"))?;
227
228    let status = response.status().as_u16();
229
230    // Check content length hint
231    if let Some(len) = response.content_length() {
232        if len > max_body as u64 {
233            return Err(format!("response too large: {len} bytes"));
234        }
235    }
236
237    // Read body with size limit to prevent OOM from servers without Content-Length
238    use std::io::Read as _;
239    let mut body_bytes = Vec::with_capacity(max_body.min(1024 * 1024));
240    response
241        .take((max_body as u64) + 1)
242        .read_to_end(&mut body_bytes)
243        .map_err(|e| format!("read body: {e}"))?;
244    if body_bytes.len() > max_body {
245        return Err(format!("response too large: {} bytes", body_bytes.len()));
246    }
247
248    let body = String::from_utf8_lossy(&body_bytes).into_owned();
249    Ok((status, body))
250}
251
252/// Normalize HTML for comparison — strip volatile content that changes
253/// between requests (scripts, styles, CSRF tokens, nonces, timestamps).
254#[cfg(unix)]
255fn normalize_html(input: &str) -> String {
256    use once_cell::sync::Lazy;
257    use regex::Regex;
258
259    static SCRIPT: Lazy<Regex> =
260        Lazy::new(|| Regex::new(r"(?is)<script[^>]*>.*?</script>").unwrap());
261    static STYLE: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?is)<style[^>]*>.*?</style>").unwrap());
262    static NONCE: Lazy<Regex> = Lazy::new(|| Regex::new(r#"(?i)\bnonce="[^"]*""#).unwrap());
263    static CSRF: Lazy<Regex> =
264        Lazy::new(|| Regex::new(r#"(?i)<[^>]*csrf[_-]?token[^>]*>"#).unwrap());
265    static WHITESPACE: Lazy<Regex> = Lazy::new(|| Regex::new(r"\s+").unwrap());
266
267    let s = SCRIPT.replace_all(input, "");
268    let s = STYLE.replace_all(&s, "");
269    let s = NONCE.replace_all(&s, "");
270    let s = CSRF.replace_all(&s, "");
271    let s = WHITESPACE.replace_all(&s, " ");
272    s.trim().to_string()
273}
274
275/// Build a word-frequency map for diff computation.
276#[cfg(unix)]
277fn word_counts(s: &str) -> std::collections::HashMap<&str, usize> {
278    let mut counts = std::collections::HashMap::new();
279    for word in s.split_whitespace() {
280        *counts.entry(word).or_insert(0) += 1;
281    }
282    counts
283}
284
285/// Generate a human-readable summary of word-level differences between two texts.
286/// Shows words present in one response but not the other (capped at 500 chars).
287#[cfg(unix)]
288fn generate_diff_text(baseline: &str, other: &str) -> String {
289    let counts_a = word_counts(baseline);
290    let counts_b = word_counts(other);
291
292    let mut only_in_baseline = Vec::new();
293    let mut only_in_other = Vec::new();
294
295    for (word, &count_a) in &counts_a {
296        let count_b = counts_b.get(word).copied().unwrap_or(0);
297        if count_a > count_b {
298            only_in_baseline.push(*word);
299        }
300    }
301
302    for (word, &count_b) in &counts_b {
303        let count_a = counts_a.get(word).copied().unwrap_or(0);
304        if count_b > count_a {
305            only_in_other.push(*word);
306        }
307    }
308
309    let mut result = String::new();
310    if !only_in_baseline.is_empty() {
311        result.push_str("Only in baseline (chrome): ");
312        let preview: String = only_in_baseline
313            .iter()
314            .take(20)
315            .copied()
316            .collect::<Vec<_>>()
317            .join(" ");
318        result.push_str(&preview);
319        if only_in_baseline.len() > 20 {
320            result.push_str(&format!(" ... (+{} more)", only_in_baseline.len() - 20));
321        }
322    }
323    if !only_in_other.is_empty() {
324        if !result.is_empty() {
325            result.push_str(" | ");
326        }
327        result.push_str("Only in this agent: ");
328        let preview: String = only_in_other
329            .iter()
330            .take(20)
331            .copied()
332            .collect::<Vec<_>>()
333            .join(" ");
334        result.push_str(&preview);
335        if only_in_other.len() > 20 {
336            result.push_str(&format!(" ... (+{} more)", only_in_other.len() - 20));
337        }
338    }
339
340    // Char-safe truncation (avoid panic on multibyte boundary)
341    if result.len() > 500 {
342        let truncated: String = result.chars().take(497).collect();
343        result = format!("{truncated}...");
344    }
345    result
346}
347
348/// Simple word-level diff size in characters.
349///
350/// Counts total characters in words that are in one string but not the other.
351/// This is a rough measure — not a proper edit distance, but sufficient for
352/// detecting meaningful content differences vs. cosmetic variations.
353#[cfg(unix)]
354fn word_diff_size(a: &str, b: &str) -> usize {
355    let counts_a = word_counts(a);
356    let counts_b = word_counts(b);
357
358    let mut diff = 0usize;
359
360    // Words in A not in B (or fewer in B)
361    for (word, &count_a) in &counts_a {
362        let count_b = counts_b.get(word).copied().unwrap_or(0);
363        if count_a > count_b {
364            diff += word.len() * (count_a - count_b);
365        }
366    }
367
368    // Words in B not in A (or fewer in A)
369    for (word, &count_b) in &counts_b {
370        let count_a = counts_a.get(word).copied().unwrap_or(0);
371        if count_b > count_a {
372            diff += word.len() * (count_b - count_a);
373        }
374    }
375
376    diff
377}
378
379#[cfg(test)]
380#[cfg(unix)]
381mod tests {
382    use super::*;
383
384    #[test]
385    fn test_normalize_html_strips_scripts() {
386        let input = "<html><script>var x = 1;</script><body>Hello</body></html>";
387        let normalized = normalize_html(input);
388        assert!(!normalized.contains("var x"));
389        assert!(normalized.contains("Hello"));
390    }
391
392    #[test]
393    fn test_normalize_html_strips_styles() {
394        let input = "<html><style>.hidden { display:none }</style><body>Hello</body></html>";
395        let normalized = normalize_html(input);
396        assert!(!normalized.contains("display:none"));
397        assert!(normalized.contains("Hello"));
398    }
399
400    #[test]
401    fn test_normalize_html_strips_nonces() {
402        // Use a non-script element so the NONCE regex is actually exercised
403        // (the SCRIPT regex would strip the entire <script> tag before NONCE runs).
404        let input = r#"<div nonce="abc123">Content</div><p>More</p>"#;
405        let normalized = normalize_html(input);
406        assert!(
407            !normalized.contains("nonce"),
408            "nonce attribute should be stripped: {normalized}"
409        );
410        assert!(normalized.contains("Content"));
411    }
412
413    #[test]
414    fn test_word_diff_size_identical() {
415        assert_eq!(word_diff_size("hello world", "hello world"), 0);
416    }
417
418    #[test]
419    fn test_word_diff_size_different() {
420        let diff = word_diff_size("hello world", "hello planet");
421        assert!(diff > 0, "different words should produce non-zero diff");
422    }
423
424    #[test]
425    fn test_word_diff_size_threshold() {
426        // Small cosmetic difference (single word)
427        let diff = word_diff_size("Welcome to our site today", "Welcome to our site");
428        assert!(diff <= 10, "minor diff should be <=10 chars, got {diff}");
429    }
430
431    #[test]
432    fn test_word_diff_size_large_difference() {
433        let a = "Welcome to our website. We offer great products and services.";
434        let b = "Access denied. This content is not available for automated crawlers.";
435        let diff = word_diff_size(a, b);
436        assert!(
437            diff > 10,
438            "significant content difference should exceed threshold, got {diff}"
439        );
440    }
441}