Skip to main content

waf_detection/
ssi.rs

1// SPDX-FileCopyrightText: 2026 0x00spor3
2// SPDX-License-Identifier: Apache-2.0
3
4use regex::RegexSet;
5use tracing::warn;
6use waf_core::{Config, Decision, Phase, RequestContext, ScoreItem, Severity, WafModule};
7
8use crate::{all_matches, body_str_values, inspectable_header_values, Rule};
9
10// ── rules (Fase 10b) ────────────────────────────────────────────────────────────
11//
12// Server-Side Includes injection: an SSI directive `<!--#exec|include|echo|…-->`
13// injected into a user value and evaluated by the server (command execution via
14// `#exec cmd`, file disclosure via `#include`, env leak via `#printenv`). gotestwaf
15// ss-include. Before this rule the payloads only tripped `sqli-quote-comment`
16// incidentally (the `"-->` tail) — a fragile, mis-attributed catch that a quote-less
17// SSI payload would evade. The directive opener `<!--#<verb>` is unequivocal SSI
18// syntax → Critical, block-alone (decision 3). Pattern targets the normalizer OUTPUT
19// (Fase 2): ASCII, NFKC-stable.
20
21pub static SSI_RULES: &[Rule] = &[
22    Rule {
23        id: "ssi-directive",
24        // SSI directive opener: `<!--#` then an SSI command verb. Matches
25        // `<!--#exec cmd="ls" -->`, `<!--#include virtual=…`, `<!--#printenv-->`.
26        // A plain HTML comment `<!-- text -->` has no `#verb` and is not flagged.
27        pattern: r"(?i)<!--#\s*(?:exec|include|echo|config|printenv|fsize|flastmod|set)\b",
28        severity: Severity::Critical,
29        paranoia: 1,
30    },
31];
32
33// ── module ──────────────────────────────────────────────────────────────────────
34
35#[derive(Default)]
36pub struct SsiModule {
37    rule_set: Option<RegexSet>,
38    /// Rules active at the configured paranoia level, index-aligned with `rule_set`.
39    active_rules: Vec<&'static Rule>,
40}
41
42impl SsiModule {
43    pub fn new() -> Self {
44        Self::default()
45    }
46}
47
48impl WafModule for SsiModule {
49    fn id(&self) -> &str {
50        "ssi"
51    }
52
53    fn phase(&self) -> Phase {
54        Phase::Body
55    }
56
57    fn init(&mut self, cfg: &Config) {
58        let pl = cfg.waf.paranoia_level;
59        self.active_rules = SSI_RULES.iter().filter(|r| r.paranoia <= pl).collect();
60        self.rule_set = Some(
61            RegexSet::new(self.active_rules.iter().map(|r| r.pattern))
62                .expect("SSI rule compilation failed — check patterns at startup"),
63        );
64    }
65
66    fn inspect(&self, ctx: &RequestContext) -> Decision {
67        let Some(rule_set) = &self.rule_set else {
68            return Decision::Allow;
69        };
70
71        let query = ctx.normalized.query_params.iter().map(|(_, v)| v.as_str());
72        let cookies = ctx.normalized.cookies.iter().map(|(_, v)| v.as_str());
73        let body_vals = body_str_values(&ctx.normalized.body);
74        let body = body_vals.iter().map(String::as_str);
75        let derived = ctx.normalized.derived_decoded.iter().map(String::as_str);
76
77        // URLPath coverage (10c REOPEN, pcap-confirmed): gotestwaf places payloads in the
78        // URL PATH; this module must scan the resolved path too (mirrors rce/xss), else a
79        // path-placed payload bypasses. The prefilter already scans the path (sound).
80        let path = std::iter::once(ctx.normalized.path.as_str());
81        // P1-B: also scan the allowlisted request headers (Referer / X-Forwarded-* / custom x-*).
82        let headers = inspectable_header_values(ctx);
83        let matched = all_matches(rule_set, path.chain(query).chain(cookies).chain(body).chain(derived).chain(headers));
84        if matched.is_empty() {
85            return Decision::Allow;
86        }
87
88        let items: Vec<ScoreItem> = matched
89            .iter()
90            .map(|&idx| {
91                let rule = self.active_rules[idx];
92                warn!(
93                    request_id = %ctx.request_id,
94                    rule_id = %rule.id,
95                    severity = ?rule.severity,
96                    "ssi detection"
97                );
98                ScoreItem {
99                    rule_id: rule.id.to_string(),
100                    severity: rule.severity,
101                }
102            })
103            .collect();
104
105        Decision::Scores(items)
106    }
107}