zentinel-modsec 0.4.0

Pure Rust ModSecurity implementation with full OWASP CRS compatibility
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
//! Variable parsing for SecRule.
//!
//! Optimized with perfect hash function for O(1) variable name lookup.

use crate::error::{Error, Result};
use phf::phf_map;

/// A variable specification in a SecRule.
#[derive(Debug, Clone)]
pub struct VariableSpec {
    /// The variable name.
    pub name: VariableName,
    /// Optional selection (e.g., ARGS:foo or ARGS:/^user/).
    pub selection: Option<Selection>,
    /// Count mode (& prefix).
    pub count_mode: bool,
    /// Exclusions (e.g., !ARGS:foo).
    pub exclusions: Vec<String>,
}

/// Selection mode for collection variables.
#[derive(Debug, Clone)]
pub enum Selection {
    /// Static key selection (ARGS:foo).
    Key(String),
    /// Regex key selection (ARGS:/^user/).
    Regex(String),
}

/// Variable names supported by ModSecurity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum VariableName {
    // Request variables
    Args, ArgsGet, ArgsPost, ArgsNames, ArgsGetNames, ArgsPostNames, ArgsCombinedSize,
    RequestUri, RequestUriRaw, RequestFilename, RequestBasename, RequestLine,
    RequestMethod, RequestProtocol, RequestHeaders, RequestHeadersNames,
    RequestCookies, RequestCookiesNames, RequestBody, RequestBodyLength, QueryString,

    // Response variables
    ResponseStatus, ResponseProtocol, ResponseHeaders, ResponseHeadersNames,
    ResponseBody, ResponseContentType, ResponseContentLength,

    // Server/Client info
    RemoteAddr, RemotePort, RemoteHost, RemoteUser,
    ServerAddr, ServerPort, ServerName,

    // Collections
    Tx, Session, Env, Ip, Global, Resource, User, Geo,

    // Matched data
    MatchedVar, MatchedVars, MatchedVarName, MatchedVarsNames,

    // Time variables
    Time, TimeEpoch, TimeDay, TimeHour, TimeMin, TimeSec, TimeWday, TimeMon, TimeYear,

    // Files
    Files, FilesSizes, FilesTmpnames, FilesCombinedSize, FilesNames,

    // Special
    UniqueId, InboundAnomalyScore, OutboundAnomalyScore, Duration,
    MultipartBoundaryQuoted, MultipartBoundaryWhitespace, MultipartDataAfter,
    MultipartDataBefore, MultipartFileLimitExceeded, MultipartHeaderFolding,
    MultipartInvalidHeaderFolding, MultipartInvalidPart, MultipartInvalidQuoting,
    MultipartLfLine, MultipartMissingSemicolon, MultipartStrictError,
    MultipartUnmatchedBoundary, MultipartPartHeaders,

    // XML
    Xml,

    // Web server
    WebserverErrorLog, HighestSeverity, StatusLine, FullRequest, FullRequestLength,

    // Auth
    AuthType,

    // Request body processing
    ReqBodyProcessor, ReqBodyError, ReqBodyErrorMsg, ReqBodyProcessorError, ReqBodyProcessorErrorMsg,

    // Multipart strict
    MultipartStrictCheck,
}

/// Which part of a flattened XML body an `XML:` selector refers to.
///
/// ModSecurity selects XML through XPath. This engine has no XPath evaluator
/// and flattens XML bodies into `ARGS` instead, but the two selectors the OWASP
/// CRS actually writes -- `XML:/*` for element content and `XML://@*` for
/// attributes -- map onto that flattening exactly, and between them account for
/// every `XML:` target in the stock rule set. Resolving those two costs nothing
/// at request time and needs no XPath engine.
///
/// Anything else is genuinely unsupported and is reported when the rules load,
/// rather than resolving to nothing and leaving the rule silently dead.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum XmlTarget {
    /// `XML:/*` -- element text.
    Elements,
    /// `XML://@*` -- attribute values.
    Attributes,
    /// A bare `XML` with no selector: everything extracted from the body.
    All,
}

impl XmlTarget {
    /// Interpret an `XML:` selector, or `None` if this engine cannot express it.
    pub fn from_selection(selection: Option<&Selection>) -> Option<Self> {
        match selection {
            None => Some(XmlTarget::All),
            Some(Selection::Key(sel)) => match sel.trim() {
                "/*" => Some(XmlTarget::Elements),
                "//@*" => Some(XmlTarget::Attributes),
                _ => None,
            },
            // `XML:/foo/` parses as a regex selection because of the
            // delimiters, but an XPath expression is not a key regex.
            Some(Selection::Regex(_)) => None,
        }
    }
}

impl VariableName {
    /// Whether the resolver can produce a value for this variable.
    ///
    /// A variable the parser accepts but the resolver has no arm for silently
    /// resolves to nothing, which makes a rule targeting it dead. Callers use
    /// this to say so at load time instead of leaving it to be discovered from
    /// traffic. The match is deliberately exhaustive: a new variant will not
    /// compile until it has been classified here.
    pub fn is_implemented(&self) -> bool {
        match self {
            VariableName::Xml | VariableName::Args | VariableName::ArgsGet | VariableName::ArgsPost |
            VariableName::ArgsNames | VariableName::ArgsGetNames | VariableName::ArgsPostNames |
            VariableName::ArgsCombinedSize | VariableName::RequestUri | VariableName::RequestUriRaw |
            VariableName::RequestFilename | VariableName::RequestBasename | VariableName::RequestLine |
            VariableName::RequestMethod | VariableName::RequestProtocol | VariableName::RequestHeaders |
            VariableName::RequestHeadersNames | VariableName::RequestCookies | VariableName::RequestCookiesNames |
            VariableName::RequestBody | VariableName::RequestBodyLength | VariableName::QueryString |
            VariableName::ResponseStatus | VariableName::ResponseHeaders | VariableName::ResponseBody |
            VariableName::ResponseContentType | VariableName::RemoteAddr | VariableName::RemotePort |
            VariableName::ServerAddr | VariableName::ServerPort | VariableName::ServerName |
            VariableName::Tx | VariableName::MatchedVar | VariableName::MatchedVars |
            VariableName::MatchedVarName | VariableName::MatchedVarsNames | VariableName::Files |
            VariableName::FilesNames | VariableName::MultipartPartHeaders | VariableName::ReqBodyProcessor |
            VariableName::ReqBodyError | VariableName::ReqBodyErrorMsg | VariableName::ReqBodyProcessorError |
            VariableName::ReqBodyProcessorErrorMsg => true,

            VariableName::ResponseProtocol | VariableName::ResponseHeadersNames | VariableName::ResponseContentLength |
            VariableName::RemoteHost | VariableName::RemoteUser | VariableName::Session |
            VariableName::Env | VariableName::Ip | VariableName::Global |
            VariableName::Resource | VariableName::User | VariableName::Geo |
            VariableName::Time | VariableName::TimeEpoch | VariableName::TimeDay |
            VariableName::TimeHour | VariableName::TimeMin | VariableName::TimeSec |
            VariableName::TimeWday | VariableName::TimeMon | VariableName::TimeYear |
            VariableName::FilesSizes | VariableName::FilesTmpnames | VariableName::FilesCombinedSize |
            VariableName::UniqueId | VariableName::InboundAnomalyScore | VariableName::OutboundAnomalyScore |
            VariableName::Duration | VariableName::MultipartBoundaryQuoted | VariableName::MultipartBoundaryWhitespace |
            VariableName::MultipartDataAfter | VariableName::MultipartDataBefore | VariableName::MultipartFileLimitExceeded |
            VariableName::MultipartHeaderFolding | VariableName::MultipartInvalidHeaderFolding | VariableName::MultipartInvalidPart |
            VariableName::MultipartInvalidQuoting | VariableName::MultipartLfLine | VariableName::MultipartMissingSemicolon |
            VariableName::MultipartStrictError | VariableName::MultipartUnmatchedBoundary |
            VariableName::WebserverErrorLog | VariableName::HighestSeverity | VariableName::StatusLine |
            VariableName::FullRequest | VariableName::FullRequestLength | VariableName::AuthType |
            VariableName::MultipartStrictCheck => false,
        }
    }
}

/// Perfect hash map for O(1) variable name lookup.
static VARIABLE_MAP: phf::Map<&'static str, VariableName> = phf_map! {
    "ARGS" => VariableName::Args,
    "ARGS_GET" => VariableName::ArgsGet,
    "ARGS_POST" => VariableName::ArgsPost,
    "ARGS_NAMES" => VariableName::ArgsNames,
    "ARGS_GET_NAMES" => VariableName::ArgsGetNames,
    "ARGS_POST_NAMES" => VariableName::ArgsPostNames,
    "ARGS_COMBINED_SIZE" => VariableName::ArgsCombinedSize,
    "REQUEST_URI" => VariableName::RequestUri,
    "REQUEST_URI_RAW" => VariableName::RequestUriRaw,
    "REQUEST_FILENAME" => VariableName::RequestFilename,
    "REQUEST_BASENAME" => VariableName::RequestBasename,
    "REQUEST_LINE" => VariableName::RequestLine,
    "REQUEST_METHOD" => VariableName::RequestMethod,
    "REQUEST_PROTOCOL" => VariableName::RequestProtocol,
    "REQUEST_HEADERS" => VariableName::RequestHeaders,
    "REQUEST_HEADERS_NAMES" => VariableName::RequestHeadersNames,
    "REQUEST_COOKIES" => VariableName::RequestCookies,
    "REQUEST_COOKIES_NAMES" => VariableName::RequestCookiesNames,
    "REQUEST_BODY" => VariableName::RequestBody,
    "REQUEST_BODY_LENGTH" => VariableName::RequestBodyLength,
    "QUERY_STRING" => VariableName::QueryString,
    "RESPONSE_STATUS" => VariableName::ResponseStatus,
    "RESPONSE_PROTOCOL" => VariableName::ResponseProtocol,
    "RESPONSE_HEADERS" => VariableName::ResponseHeaders,
    "RESPONSE_HEADERS_NAMES" => VariableName::ResponseHeadersNames,
    "RESPONSE_BODY" => VariableName::ResponseBody,
    "RESPONSE_CONTENT_TYPE" => VariableName::ResponseContentType,
    "RESPONSE_CONTENT_LENGTH" => VariableName::ResponseContentLength,
    "REMOTE_ADDR" => VariableName::RemoteAddr,
    "REMOTE_PORT" => VariableName::RemotePort,
    "REMOTE_HOST" => VariableName::RemoteHost,
    "REMOTE_USER" => VariableName::RemoteUser,
    "SERVER_ADDR" => VariableName::ServerAddr,
    "SERVER_PORT" => VariableName::ServerPort,
    "SERVER_NAME" => VariableName::ServerName,
    "TX" => VariableName::Tx,
    "SESSION" => VariableName::Session,
    "ENV" => VariableName::Env,
    "IP" => VariableName::Ip,
    "GLOBAL" => VariableName::Global,
    "RESOURCE" => VariableName::Resource,
    "USER" => VariableName::User,
    "GEO" => VariableName::Geo,
    "MATCHED_VAR" => VariableName::MatchedVar,
    "MATCHED_VARS" => VariableName::MatchedVars,
    "MATCHED_VAR_NAME" => VariableName::MatchedVarName,
    "MATCHED_VARS_NAMES" => VariableName::MatchedVarsNames,
    "TIME" => VariableName::Time,
    "TIME_EPOCH" => VariableName::TimeEpoch,
    "TIME_DAY" => VariableName::TimeDay,
    "TIME_HOUR" => VariableName::TimeHour,
    "TIME_MIN" => VariableName::TimeMin,
    "TIME_SEC" => VariableName::TimeSec,
    "TIME_WDAY" => VariableName::TimeWday,
    "TIME_MON" => VariableName::TimeMon,
    "TIME_YEAR" => VariableName::TimeYear,
    "FILES" => VariableName::Files,
    "FILES_SIZES" => VariableName::FilesSizes,
    "FILES_TMPNAMES" => VariableName::FilesTmpnames,
    "FILES_COMBINED_SIZE" => VariableName::FilesCombinedSize,
    "FILES_NAMES" => VariableName::FilesNames,
    "UNIQUE_ID" => VariableName::UniqueId,
    "DURATION" => VariableName::Duration,
    "HIGHEST_SEVERITY" => VariableName::HighestSeverity,
    "STATUS_LINE" => VariableName::StatusLine,
    "FULL_REQUEST" => VariableName::FullRequest,
    "FULL_REQUEST_LENGTH" => VariableName::FullRequestLength,
    "AUTH_TYPE" => VariableName::AuthType,
    "XML" => VariableName::Xml,
    "REQBODY_PROCESSOR" => VariableName::ReqBodyProcessor,
    "REQBODY_ERROR" => VariableName::ReqBodyError,
    "REQBODY_ERROR_MSG" => VariableName::ReqBodyErrorMsg,
    "REQBODY_PROCESSOR_ERROR" => VariableName::ReqBodyProcessorError,
    "REQBODY_PROCESSOR_ERROR_MSG" => VariableName::ReqBodyProcessorErrorMsg,
    "MULTIPART_STRICT_ERROR" => VariableName::MultipartStrictCheck,
    "MULTIPART_PART_HEADERS" => VariableName::MultipartPartHeaders,
};

impl VariableName {
    /// Parse a variable name from a string (O(1) lookup).
    #[inline]
    pub fn from_str(s: &str) -> Option<Self> {
        // Fast path: check if already uppercase ASCII
        if s.bytes().all(|b| b.is_ascii_uppercase() || b == b'_') {
            return VARIABLE_MAP.get(s).copied();
        }
        // Slow path: need to uppercase
        let mut buf = [0u8; 64];
        let len = s.len().min(64);
        for (i, b) in s.bytes().take(len).enumerate() {
            buf[i] = b.to_ascii_uppercase();
        }
        let upper = std::str::from_utf8(&buf[..len]).ok()?;
        VARIABLE_MAP.get(upper).copied()
    }

    /// Check if this variable is a collection.
    #[inline]
    pub fn is_collection(&self) -> bool {
        matches!(
            self,
            Self::Args | Self::ArgsGet | Self::ArgsPost | Self::ArgsNames
                | Self::RequestHeaders | Self::RequestHeadersNames
                | Self::RequestCookies | Self::RequestCookiesNames
                | Self::ResponseHeaders | Self::ResponseHeadersNames
                | Self::Tx | Self::Session | Self::Env | Self::Ip
                | Self::Global | Self::Resource | Self::User | Self::Geo
                | Self::MatchedVars | Self::MatchedVarsNames
                | Self::Files | Self::FilesSizes | Self::FilesTmpnames | Self::FilesNames
                | Self::MultipartPartHeaders
        )
    }
}

/// Parse a variable specification string.
#[inline]
pub fn parse_variables(input: &str) -> Result<Vec<VariableSpec>> {
    let mut variables = Vec::with_capacity(4);
    let mut exclusions: Vec<String> = Vec::new();

    // Split by | for OR conditions
    for part in input.split('|') {
        let part = part.trim();
        if part.is_empty() {
            continue;
        }

        // Handle exclusions (!VAR)
        if part.starts_with('!') {
            exclusions.push(part[1..].to_string());
            continue;
        }

        let spec = parse_single_variable(part)?;
        variables.push(spec);
    }

    // Apply exclusions to all variables
    if !exclusions.is_empty() {
        for var in &mut variables {
            var.exclusions = exclusions.clone();
        }
    }

    Ok(variables)
}

/// Parse a `SecRuleUpdateTargetById`-style target list.
///
/// Unlike [`parse_variables`], exclusions (`!TARGET`) are returned separately
/// rather than being attached to the positive specs, because for a target
/// update they must be applied to the *existing* variables of the rule being
/// updated. Returns `(positive_specs, exclusion_strings)`.
pub fn parse_update_targets(input: &str) -> Result<(Vec<VariableSpec>, Vec<String>)> {
    let mut additions = Vec::new();
    let mut exclusions = Vec::new();

    for part in input.split('|') {
        let part = part.trim();
        if part.is_empty() {
            continue;
        }
        if let Some(excl) = part.strip_prefix('!') {
            // Validate the collection name so a typo'd exclusion is a load
            // error rather than a silently dead exclusion.
            let name_end = excl.find(':').unwrap_or(excl.len());
            let name_str = &excl[..name_end];
            if VariableName::from_str(name_str).is_none() {
                return Err(Error::UnknownVariable {
                    name: name_str.to_string(),
                });
            }
            exclusions.push(excl.to_string());
        } else {
            additions.push(parse_single_variable(part)?);
        }
    }

    Ok((additions, exclusions))
}

/// Parse a single variable specification.
#[inline]
pub(crate) fn parse_single_variable(input: &str) -> Result<VariableSpec> {
    let input = input.trim();
    let bytes = input.as_bytes();

    // Check for count mode (& prefix)
    let (count_mode, input) = if bytes.first() == Some(&b'&') {
        (true, &input[1..])
    } else {
        (false, input)
    };

    // Find colon for selection (use memchr-style search)
    let colon_pos = input.bytes().position(|b| b == b':');

    let (name_str, selection) = match colon_pos {
        Some(pos) => {
            let name = &input[..pos];
            let sel_str = &input[pos + 1..];

            let selection = if sel_str.starts_with('/') && sel_str.ends_with('/') && sel_str.len() > 2 {
                Some(Selection::Regex(sel_str[1..sel_str.len() - 1].to_string()))
            } else {
                Some(Selection::Key(sel_str.to_string()))
            };

            (name, selection)
        }
        None => (input, None),
    };

    let name = VariableName::from_str(name_str).ok_or_else(|| Error::UnknownVariable {
        name: name_str.to_string(),
    })?;

    Ok(VariableSpec {
        name,
        selection,
        count_mode,
        exclusions: Vec::new(),
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_simple_variable() {
        let vars = parse_variables("REQUEST_URI").unwrap();
        assert_eq!(vars.len(), 1);
        assert_eq!(vars[0].name, VariableName::RequestUri);
        assert!(vars[0].selection.is_none());
        assert!(!vars[0].count_mode);
    }

    #[test]
    fn test_parse_variable_with_selection() {
        let vars = parse_variables("ARGS:username").unwrap();
        assert_eq!(vars.len(), 1);
        assert_eq!(vars[0].name, VariableName::Args);
        assert!(matches!(&vars[0].selection, Some(Selection::Key(k)) if k == "username"));
    }

    #[test]
    fn test_parse_variable_with_regex() {
        let vars = parse_variables("ARGS:/^user/").unwrap();
        assert_eq!(vars.len(), 1);
        assert_eq!(vars[0].name, VariableName::Args);
        assert!(matches!(&vars[0].selection, Some(Selection::Regex(r)) if r == "^user"));
    }

    #[test]
    fn test_parse_multipart_part_headers() {
        // Used by CRS REQUEST-922; must parse rather than erroring as unknown.
        let vars = parse_variables("MULTIPART_PART_HEADERS").unwrap();
        assert_eq!(vars.len(), 1);
        assert_eq!(vars[0].name, VariableName::MultipartPartHeaders);
    }

    #[test]
    fn test_parse_count_mode() {
        let vars = parse_variables("&ARGS").unwrap();
        assert_eq!(vars.len(), 1);
        assert!(vars[0].count_mode);
    }

    #[test]
    fn test_parse_multiple_variables() {
        let vars = parse_variables("REQUEST_URI|ARGS|REQUEST_HEADERS").unwrap();
        assert_eq!(vars.len(), 3);
    }

    #[test]
    fn test_variable_lookup_case_insensitive() {
        assert_eq!(VariableName::from_str("REQUEST_URI"), Some(VariableName::RequestUri));
        assert_eq!(VariableName::from_str("request_uri"), Some(VariableName::RequestUri));
        assert_eq!(VariableName::from_str("Request_Uri"), Some(VariableName::RequestUri));
    }
}