zentinel-modsec 0.1.2

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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
//! Normalization transformations.

use super::Transformation;
use std::borrow::Cow;

/// Lowercase transformation.
pub struct Lowercase;

impl Transformation for Lowercase {
    fn transform<'a>(&self, input: &'a str) -> Cow<'a, str> {
        let lower = input.to_lowercase();
        if lower == input {
            Cow::Borrowed(input)
        } else {
            Cow::Owned(lower)
        }
    }

    fn name(&self) -> &'static str {
        "lowercase"
    }
}

/// Uppercase transformation.
pub struct Uppercase;

impl Transformation for Uppercase {
    fn transform<'a>(&self, input: &'a str) -> Cow<'a, str> {
        let upper = input.to_uppercase();
        if upper == input {
            Cow::Borrowed(input)
        } else {
            Cow::Owned(upper)
        }
    }

    fn name(&self) -> &'static str {
        "uppercase"
    }
}

/// Compress whitespace transformation.
pub struct CompressWhitespace;

impl Transformation for CompressWhitespace {
    fn transform<'a>(&self, input: &'a str) -> Cow<'a, str> {
        let mut result = String::new();
        let mut last_was_space = false;
        let mut modified = false;

        for c in input.chars() {
            if c.is_whitespace() {
                if !last_was_space {
                    result.push(' ');
                } else {
                    modified = true;
                }
                last_was_space = true;
            } else {
                result.push(c);
                last_was_space = false;
            }
        }

        if modified || result.chars().any(|c| c.is_whitespace() && c != ' ') {
            Cow::Owned(result)
        } else if result == input {
            Cow::Borrowed(input)
        } else {
            Cow::Owned(result)
        }
    }

    fn name(&self) -> &'static str {
        "compressWhitespace"
    }
}

/// Remove whitespace transformation.
pub struct RemoveWhitespace;

impl Transformation for RemoveWhitespace {
    fn transform<'a>(&self, input: &'a str) -> Cow<'a, str> {
        let result: String = input.chars().filter(|c| !c.is_whitespace()).collect();
        if result == input {
            Cow::Borrowed(input)
        } else {
            Cow::Owned(result)
        }
    }

    fn name(&self) -> &'static str {
        "removeWhitespace"
    }
}

/// Remove null bytes transformation.
pub struct RemoveNulls;

impl Transformation for RemoveNulls {
    fn transform<'a>(&self, input: &'a str) -> Cow<'a, str> {
        if !input.contains('\0') {
            return Cow::Borrowed(input);
        }
        Cow::Owned(input.replace('\0', ""))
    }

    fn name(&self) -> &'static str {
        "removeNulls"
    }
}

/// Replace null bytes with spaces transformation.
pub struct ReplaceNulls;

impl Transformation for ReplaceNulls {
    fn transform<'a>(&self, input: &'a str) -> Cow<'a, str> {
        if !input.contains('\0') {
            return Cow::Borrowed(input);
        }
        Cow::Owned(input.replace('\0', " "))
    }

    fn name(&self) -> &'static str {
        "replaceNulls"
    }
}

/// Trim transformation.
pub struct Trim;

impl Transformation for Trim {
    fn transform<'a>(&self, input: &'a str) -> Cow<'a, str> {
        let trimmed = input.trim();
        if trimmed.len() == input.len() {
            Cow::Borrowed(input)
        } else {
            Cow::Owned(trimmed.to_string())
        }
    }

    fn name(&self) -> &'static str {
        "trim"
    }
}

/// Trim left transformation.
pub struct TrimLeft;

impl Transformation for TrimLeft {
    fn transform<'a>(&self, input: &'a str) -> Cow<'a, str> {
        let trimmed = input.trim_start();
        if trimmed.len() == input.len() {
            Cow::Borrowed(input)
        } else {
            Cow::Owned(trimmed.to_string())
        }
    }

    fn name(&self) -> &'static str {
        "trimLeft"
    }
}

/// Trim right transformation.
pub struct TrimRight;

impl Transformation for TrimRight {
    fn transform<'a>(&self, input: &'a str) -> Cow<'a, str> {
        let trimmed = input.trim_end();
        if trimmed.len() == input.len() {
            Cow::Borrowed(input)
        } else {
            Cow::Owned(trimmed.to_string())
        }
    }

    fn name(&self) -> &'static str {
        "trimRight"
    }
}

/// Normalize path transformation (Unix-style).
pub struct NormalizePath;

impl Transformation for NormalizePath {
    fn transform<'a>(&self, input: &'a str) -> Cow<'a, str> {
        let mut result = String::new();
        let mut modified = false;

        // Replace backslashes with forward slashes
        let normalized = if input.contains('\\') {
            modified = true;
            Cow::Owned(input.replace('\\', "/"))
        } else {
            Cow::Borrowed(input)
        };

        // Collapse multiple slashes
        let mut last_was_slash = false;
        for c in normalized.chars() {
            if c == '/' {
                if !last_was_slash {
                    result.push('/');
                } else {
                    modified = true;
                }
                last_was_slash = true;
            } else {
                result.push(c);
                last_was_slash = false;
            }
        }

        // Remove . and .. components
        let parts: Vec<&str> = result.split('/').collect();
        let mut stack: Vec<&str> = Vec::new();

        for part in parts {
            match part {
                "." => {
                    modified = true;
                }
                ".." => {
                    modified = true;
                    stack.pop();
                }
                "" if !stack.is_empty() => {
                    // Keep leading empty string for absolute paths
                }
                other => {
                    stack.push(other);
                }
            }
        }

        if modified {
            Cow::Owned(stack.join("/"))
        } else {
            Cow::Borrowed(input)
        }
    }

    fn name(&self) -> &'static str {
        "normalizePath"
    }
}

/// Normalize path transformation (Windows-style).
pub struct NormalizePathWin;

impl Transformation for NormalizePathWin {
    fn transform<'a>(&self, input: &'a str) -> Cow<'a, str> {
        // Same as NormalizePath but preserves backslashes
        let np = NormalizePath;
        let result = np.transform(input);
        // Convert back to backslashes
        if result.contains('/') {
            Cow::Owned(result.replace('/', "\\"))
        } else {
            result
        }
    }

    fn name(&self) -> &'static str {
        "normalizePathWin"
    }
}

/// Remove comments transformation.
pub struct RemoveComments;

impl Transformation for RemoveComments {
    fn transform<'a>(&self, input: &'a str) -> Cow<'a, str> {
        let mut result = String::new();
        let mut in_comment = false;
        let mut chars = input.chars().peekable();

        while let Some(c) = chars.next() {
            if in_comment {
                if c == '*' && chars.peek() == Some(&'/') {
                    chars.next();
                    in_comment = false;
                }
            } else if c == '/' && chars.peek() == Some(&'*') {
                chars.next();
                in_comment = true;
            } else {
                result.push(c);
            }
        }

        if result == input {
            Cow::Borrowed(input)
        } else {
            Cow::Owned(result)
        }
    }

    fn name(&self) -> &'static str {
        "removeComments"
    }
}

/// Replace comments transformation (replaces /* ... */ with space).
pub struct ReplaceComments;

impl Transformation for ReplaceComments {
    fn transform<'a>(&self, input: &'a str) -> Cow<'a, str> {
        let mut result = String::new();
        let mut in_comment = false;
        let mut chars = input.chars().peekable();
        let mut modified = false;

        while let Some(c) = chars.next() {
            if in_comment {
                if c == '*' && chars.peek() == Some(&'/') {
                    chars.next();
                    in_comment = false;
                    result.push(' '); // Replace comment with space
                }
            } else if c == '/' && chars.peek() == Some(&'*') {
                chars.next();
                in_comment = true;
                modified = true;
            } else {
                result.push(c);
            }
        }

        if modified {
            Cow::Owned(result)
        } else {
            Cow::Borrowed(input)
        }
    }

    fn name(&self) -> &'static str {
        "replaceComments"
    }
}

/// Remove comment characters transformation.
pub struct RemoveCommentsChar;

impl Transformation for RemoveCommentsChar {
    fn transform<'a>(&self, input: &'a str) -> Cow<'a, str> {
        // Remove /*, */, --, and #
        let mut result = input.to_string();
        result = result.replace("/*", "");
        result = result.replace("*/", "");
        result = result.replace("--", "");
        result = result.replace('#', "");

        if result == input {
            Cow::Borrowed(input)
        } else {
            Cow::Owned(result)
        }
    }

    fn name(&self) -> &'static str {
        "removeCommentsChar"
    }
}

/// SQL hex decode transformation.
pub struct SqlHexDecode;

impl Transformation for SqlHexDecode {
    fn transform<'a>(&self, input: &'a str) -> Cow<'a, str> {
        // Decode SQL hex strings like 0x41424344 to ABCD
        let mut result = String::new();
        let mut chars = input.chars().peekable();
        let mut modified = false;

        while let Some(c) = chars.next() {
            if c == '0' && chars.peek() == Some(&'x') {
                chars.next(); // consume 'x'
                let mut hex = String::new();
                while let Some(&next) = chars.peek() {
                    if next.is_ascii_hexdigit() {
                        hex.push(chars.next().unwrap());
                    } else {
                        break;
                    }
                }
                // Decode hex pairs
                let mut i = 0;
                while i + 1 < hex.len() {
                    if let Ok(byte) = u8::from_str_radix(&hex[i..i+2], 16) {
                        result.push(byte as char);
                    }
                    i += 2;
                }
                modified = true;
            } else {
                result.push(c);
            }
        }

        if modified {
            Cow::Owned(result)
        } else {
            Cow::Borrowed(input)
        }
    }

    fn name(&self) -> &'static str {
        "sqlHexDecode"
    }
}

/// UTF-8 to Unicode transformation (pass-through for now).
pub struct Utf8ToUnicode;

impl Transformation for Utf8ToUnicode {
    fn transform<'a>(&self, input: &'a str) -> Cow<'a, str> {
        // In Rust strings are already UTF-8, this is a no-op
        Cow::Borrowed(input)
    }

    fn name(&self) -> &'static str {
        "utf8ToUnicode"
    }
}

/// Command line normalization transformation.
pub struct CmdLine;

impl Transformation for CmdLine {
    fn transform<'a>(&self, input: &'a str) -> Cow<'a, str> {
        let mut result = String::new();
        let mut modified = false;

        for c in input.chars() {
            match c {
                // Replace with space
                ',' | ';' | '\'' | '"' | '`' => {
                    result.push(' ');
                    modified = true;
                }
                // Remove caret (Windows escape)
                '^' => {
                    modified = true;
                }
                // Lowercase
                c if c.is_ascii_uppercase() => {
                    result.push(c.to_ascii_lowercase());
                    modified = true;
                }
                _ => {
                    result.push(c);
                }
            }
        }

        // Compress whitespace
        let compressed: String = result
            .split_whitespace()
            .collect::<Vec<_>>()
            .join(" ");

        if modified || compressed != result {
            Cow::Owned(compressed)
        } else {
            Cow::Borrowed(input)
        }
    }

    fn name(&self) -> &'static str {
        "cmdLine"
    }
}

/// Escape sequence decode transformation.
pub struct EscapeSeqDecode;

impl Transformation for EscapeSeqDecode {
    fn transform<'a>(&self, input: &'a str) -> Cow<'a, str> {
        // Decode escape sequences like \n, \r, \t, \xHH, \uHHHH
        let mut result = String::new();
        let mut chars = input.chars().peekable();
        let mut modified = false;

        while let Some(c) = chars.next() {
            if c == '\\' {
                if let Some(&next) = chars.peek() {
                    modified = true;
                    chars.next();
                    match next {
                        'n' => result.push('\n'),
                        'r' => result.push('\r'),
                        't' => result.push('\t'),
                        '\\' => result.push('\\'),
                        '0' => result.push('\0'),
                        'x' => {
                            // Hex escape \xHH
                            let mut hex = String::new();
                            for _ in 0..2 {
                                if let Some(&h) = chars.peek() {
                                    if h.is_ascii_hexdigit() {
                                        hex.push(chars.next().unwrap());
                                    } else {
                                        break;
                                    }
                                }
                            }
                            if let Ok(byte) = u8::from_str_radix(&hex, 16) {
                                result.push(byte as char);
                            } else {
                                result.push('x');
                                result.push_str(&hex);
                            }
                        }
                        'u' => {
                            // Unicode escape \uHHHH
                            let mut hex = String::new();
                            for _ in 0..4 {
                                if let Some(&h) = chars.peek() {
                                    if h.is_ascii_hexdigit() {
                                        hex.push(chars.next().unwrap());
                                    } else {
                                        break;
                                    }
                                }
                            }
                            if let Ok(code) = u32::from_str_radix(&hex, 16) {
                                if let Some(c) = char::from_u32(code) {
                                    result.push(c);
                                } else {
                                    result.push('u');
                                    result.push_str(&hex);
                                }
                            } else {
                                result.push('u');
                                result.push_str(&hex);
                            }
                        }
                        _ => {
                            result.push('\\');
                            result.push(next);
                        }
                    }
                } else {
                    result.push(c);
                }
            } else {
                result.push(c);
            }
        }

        if modified {
            Cow::Owned(result)
        } else {
            Cow::Borrowed(input)
        }
    }

    fn name(&self) -> &'static str {
        "escapeSeqDecode"
    }
}

/// SHA-256 hash transformation.
pub struct Sha256;

impl Transformation for Sha256 {
    fn transform<'a>(&self, input: &'a str) -> Cow<'a, str> {
        use sha2::{Digest, Sha256 as Sha256Hasher};
        let mut hasher = Sha256Hasher::new();
        hasher.update(input.as_bytes());
        let result = hasher.finalize();
        Cow::Owned(hex::encode(result))
    }

    fn name(&self) -> &'static str {
        "sha256"
    }
}

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

    #[test]
    fn test_lowercase() {
        let t = Lowercase;
        assert_eq!(t.transform("Hello World"), "hello world");
        assert_eq!(t.transform("already lower"), "already lower");
    }

    #[test]
    fn test_compress_whitespace() {
        let t = CompressWhitespace;
        assert_eq!(t.transform("hello   world"), "hello world");
        assert_eq!(t.transform("a\t\nb"), "a b");
    }

    #[test]
    fn test_remove_whitespace() {
        let t = RemoveWhitespace;
        assert_eq!(t.transform("hello world"), "helloworld");
    }

    #[test]
    fn test_normalize_path() {
        let t = NormalizePath;
        assert_eq!(t.transform("/a/b/../c"), "/a/c");
        assert_eq!(t.transform("/a//b/./c"), "/a/b/c");
        assert_eq!(t.transform("a\\b\\c"), "a/b/c");
    }

    #[test]
    fn test_cmdline() {
        let t = CmdLine;
        // Semicolon replaced with space, uppercase to lowercase
        assert_eq!(t.transform("CMD;/C"), "cmd /c");
        // Caret is the Windows escape character - it's simply removed
        assert_eq!(t.transform("echo^hello"), "echohello");
        // Multiple transformations
        assert_eq!(t.transform("CMD,/C;DIR"), "cmd /c dir");
    }
}