bext-waf 0.2.0

Web Application Firewall for bext — rate limiting, IP filtering, GeoIP, rule engine
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
//! HTTP protocol violation detection — null bytes in paths, control characters
//! in headers, oversized header values, and malformed request structure.

use crate::WafRequest;

/// Maximum allowed header value length in bytes (8 KB).
const MAX_HEADER_VALUE_LEN: usize = 8 * 1024;

/// Check a request for HTTP protocol violations.
/// Returns `Some(description)` if a violation is found.
pub fn check_protocol(req: &WafRequest) -> Option<String> {
    // 1. Null bytes in path.
    if req.path.contains('\0') || req.path.contains("%00") || req.path.contains("%2500") {
        return Some("null byte in request path".into());
    }

    // 2. Null bytes in query string.
    if let Some(ref q) = req.query {
        if q.contains('\0') || q.contains("%00") || q.contains("%2500") {
            return Some("null byte in query string".into());
        }
    }

    // 3. Control characters in header values (ASCII 0x00-0x08, 0x0B, 0x0C, 0x0E-0x1F).
    // Tabs (0x09), LF (0x0A), CR (0x0D) are allowed per HTTP spec.
    for (name, value) in &req.headers {
        // Check header name for control characters.
        if has_illegal_control_chars(name) {
            return Some(format!("control character in header name: {name}"));
        }
        // Check header value for control characters.
        if has_illegal_control_chars(value) {
            return Some(format!("control character in header value for: {name}"));
        }
    }

    // 4. Excessively long header values (>8KB).
    for (name, value) in &req.headers {
        if value.len() > MAX_HEADER_VALUE_LEN {
            return Some(format!(
                "header value too long for {name}: {} bytes (max {})",
                value.len(),
                MAX_HEADER_VALUE_LEN
            ));
        }
    }

    // 5. Request with body but no Content-Length or Transfer-Encoding.
    if req.body.is_some() && is_body_method(&req.method) {
        let has_content_length = req
            .headers
            .keys()
            .any(|k| k.eq_ignore_ascii_case("content-length"));
        let has_transfer_encoding = req
            .headers
            .keys()
            .any(|k| k.eq_ignore_ascii_case("transfer-encoding"));
        if !has_content_length && !has_transfer_encoding {
            return Some(
                "request has body but no Content-Length or Transfer-Encoding header".into(),
            );
        }
    }

    // 6. Request smuggling: both Content-Length AND Transfer-Encoding present
    let has_cl = req
        .headers
        .keys()
        .any(|k| k.eq_ignore_ascii_case("content-length"));
    let has_te = req
        .headers
        .keys()
        .any(|k| k.eq_ignore_ascii_case("transfer-encoding"));
    if has_cl && has_te {
        return Some(
            "request smuggling attempt: both Content-Length and Transfer-Encoding present".into(),
        );
    }

    // 7. Content-Length must be numeric
    if let Some(cl) = req
        .headers
        .iter()
        .find(|(k, _)| k.eq_ignore_ascii_case("content-length"))
        .map(|(_, v)| v)
    {
        if !cl.trim().chars().all(|c| c.is_ascii_digit()) {
            return Some("invalid Content-Length: non-numeric value".into());
        }
    }

    // 8. Control characters in path (not percent-encoded).
    if has_illegal_control_chars(&req.path) {
        return Some("control character in request path".into());
    }

    // 9. Double-slash normalization bypass.
    if req.path.contains("//") {
        return Some("double-slash in path (normalization bypass attempt)".into());
    }

    // 10. Unusual HTTP methods (TRACE, TRACK, DEBUG, CONNECT used in attacks).
    let upper = req.method.to_uppercase();
    match upper.as_str() {
        "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS" => {}
        "TRACE" | "TRACK" => {
            return Some(format!(
                "dangerous HTTP method: {} (XST/cross-site tracing)",
                req.method
            ))
        }
        "DEBUG" => return Some("dangerous HTTP method: DEBUG (ASP.NET debug mode)".into()),
        "CONNECT" => return Some("CONNECT method not allowed".into()),
        _ => return Some(format!("non-standard HTTP method: {}", req.method)),
    }

    None
}

/// Returns true for HTTP methods that typically carry a body.
fn is_body_method(method: &str) -> bool {
    matches!(method.to_uppercase().as_str(), "POST" | "PUT" | "PATCH")
}

/// Check if a string contains illegal control characters.
/// Allows tab (0x09), LF (0x0A), and CR (0x0D) which are valid in HTTP.
fn has_illegal_control_chars(s: &str) -> bool {
    s.bytes()
        .any(|b| b < 0x20 && b != 0x09 && b != 0x0A && b != 0x0D)
}

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

    fn make_req(
        method: &str,
        path: &str,
        headers: Vec<(&str, &str)>,
        body: Option<&str>,
    ) -> WafRequest {
        WafRequest {
            client_ip: "127.0.0.1".parse().unwrap(),
            method: method.into(),
            path: path.into(),
            query: None,
            headers: headers
                .into_iter()
                .map(|(k, v)| (k.into(), v.into()))
                .collect(),
            body: body.map(String::from),
            user_agent: None,
        }
    }

    #[test]
    fn clean_request_passes() {
        let req = make_req(
            "POST",
            "/api/data",
            vec![
                ("Content-Length", "13"),
                ("Content-Type", "application/json"),
            ],
            Some(r#"{"key":"val"}"#),
        );
        assert!(check_protocol(&req).is_none());
    }

    #[test]
    fn clean_get_without_body_passes() {
        let req = make_req("GET", "/api/users", vec![], None);
        assert!(check_protocol(&req).is_none());
    }

    // ---- Null byte tests ----

    #[test]
    fn detects_null_byte_in_path() {
        let req = make_req("GET", "/uploads/shell.php\0.jpg", vec![], None);
        let result = check_protocol(&req);
        assert!(result.is_some());
        assert!(result.unwrap().contains("null byte"));
    }

    #[test]
    fn detects_percent_encoded_null_in_path() {
        let req = make_req("GET", "/uploads/shell.php%00.jpg", vec![], None);
        let result = check_protocol(&req);
        assert!(result.is_some());
        assert!(result.unwrap().contains("null byte"));
    }

    #[test]
    fn detects_double_encoded_null_in_path() {
        let req = make_req("GET", "/uploads/shell.php%2500.jpg", vec![], None);
        let result = check_protocol(&req);
        assert!(result.is_some());
    }

    #[test]
    fn detects_null_byte_in_query() {
        let mut req = make_req("GET", "/search", vec![], None);
        req.query = Some("q=test%00.php".into());
        let result = check_protocol(&req);
        assert!(result.is_some());
        assert!(result.unwrap().contains("null byte"));
    }

    // ---- Control character tests ----

    #[test]
    fn detects_control_char_in_header_value() {
        let value = format!("normal\x01value");
        let mut headers = HashMap::new();
        headers.insert("X-Custom".into(), value);
        let req = WafRequest {
            client_ip: "127.0.0.1".parse().unwrap(),
            method: "GET".into(),
            path: "/".into(),
            query: None,
            headers,
            body: None,
            user_agent: None,
        };
        let result = check_protocol(&req);
        assert!(result.is_some());
        assert!(result.unwrap().contains("control character"));
    }

    #[test]
    fn detects_control_char_in_header_name() {
        let name = format!("X-Bad\x02Header");
        let mut headers = HashMap::new();
        headers.insert(name, "value".into());
        let req = WafRequest {
            client_ip: "127.0.0.1".parse().unwrap(),
            method: "GET".into(),
            path: "/".into(),
            query: None,
            headers,
            body: None,
            user_agent: None,
        };
        let result = check_protocol(&req);
        assert!(result.is_some());
        assert!(result.unwrap().contains("control character"));
    }

    #[test]
    fn allows_tab_in_header_value() {
        let value = "value\twith\ttabs".to_string();
        let mut headers = HashMap::new();
        headers.insert("X-Custom".into(), value);
        let req = WafRequest {
            client_ip: "127.0.0.1".parse().unwrap(),
            method: "GET".into(),
            path: "/".into(),
            query: None,
            headers,
            body: None,
            user_agent: None,
        };
        assert!(check_protocol(&req).is_none());
    }

    #[test]
    fn detects_control_char_in_path() {
        let path = "/api/\x01endpoint";
        let req = make_req("GET", path, vec![], None);
        let result = check_protocol(&req);
        assert!(result.is_some());
        assert!(result.unwrap().contains("control character"));
    }

    // ---- Long header tests ----

    #[test]
    fn detects_excessively_long_header_value() {
        let long_value = "x".repeat(MAX_HEADER_VALUE_LEN + 1);
        let req = make_req("GET", "/", vec![("X-Big", long_value.as_str())], None);
        let result = check_protocol(&req);
        assert!(result.is_some());
        assert!(result.unwrap().contains("too long"));
    }

    #[test]
    fn allows_header_at_limit() {
        let value = "x".repeat(MAX_HEADER_VALUE_LEN);
        let req = make_req("GET", "/", vec![("X-Big", value.as_str())], None);
        assert!(check_protocol(&req).is_none());
    }

    // ---- Body without Content-Length tests ----

    #[test]
    fn detects_post_body_without_content_length() {
        let req = make_req("POST", "/api/data", vec![], Some("some body data"));
        let result = check_protocol(&req);
        assert!(result.is_some());
        assert!(result.unwrap().contains("Content-Length"));
    }

    #[test]
    fn detects_put_body_without_content_length() {
        let req = make_req("PUT", "/api/data", vec![], Some("body data"));
        let result = check_protocol(&req);
        assert!(result.is_some());
    }

    #[test]
    fn allows_post_body_with_content_length() {
        let req = make_req(
            "POST",
            "/api/data",
            vec![("Content-Length", "14")],
            Some("some body data"),
        );
        assert!(check_protocol(&req).is_none());
    }

    #[test]
    fn allows_post_body_with_transfer_encoding() {
        let req = make_req(
            "POST",
            "/api/data",
            vec![("Transfer-Encoding", "chunked")],
            Some("some body data"),
        );
        assert!(check_protocol(&req).is_none());
    }

    #[test]
    fn get_body_without_content_length_allowed() {
        // GET with body but no Content-Length — allowed since GET is not a "body method"
        let req = make_req("GET", "/api/data", vec![], Some("unexpected body"));
        assert!(check_protocol(&req).is_none());
    }

    // ---- Request smuggling tests ----

    #[test]
    fn detects_request_smuggling_cl_te() {
        let req = make_req(
            "POST",
            "/api/data",
            vec![("Content-Length", "13"), ("Transfer-Encoding", "chunked")],
            Some(r#"{"key":"val"}"#),
        );
        let result = check_protocol(&req);
        assert!(result.is_some());
        assert!(result.unwrap().contains("request smuggling"));
    }

    #[test]
    fn detects_request_smuggling_case_insensitive() {
        let req = make_req(
            "POST",
            "/api/data",
            vec![("content-length", "13"), ("transfer-encoding", "chunked")],
            Some(r#"{"key":"val"}"#),
        );
        let result = check_protocol(&req);
        assert!(result.is_some());
        assert!(result.unwrap().contains("request smuggling"));
    }

    #[test]
    fn allows_cl_without_te() {
        let req = make_req(
            "POST",
            "/api/data",
            vec![("Content-Length", "13")],
            Some(r#"{"key":"val"}"#),
        );
        assert!(check_protocol(&req).is_none());
    }

    #[test]
    fn allows_te_without_cl() {
        let req = make_req(
            "POST",
            "/api/data",
            vec![("Transfer-Encoding", "chunked")],
            Some(r#"{"key":"val"}"#),
        );
        assert!(check_protocol(&req).is_none());
    }

    // ---- Non-numeric Content-Length tests ----

    #[test]
    fn detects_non_numeric_content_length() {
        let req = make_req(
            "POST",
            "/api/data",
            vec![("Content-Length", "13abc")],
            Some(r#"{"key":"val"}"#),
        );
        let result = check_protocol(&req);
        assert!(result.is_some());
        assert!(result.unwrap().contains("non-numeric"));
    }

    #[test]
    fn detects_negative_content_length() {
        let req = make_req(
            "POST",
            "/api/data",
            vec![("Content-Length", "-1")],
            Some(r#"{"key":"val"}"#),
        );
        let result = check_protocol(&req);
        assert!(result.is_some());
        assert!(result.unwrap().contains("non-numeric"));
    }

    #[test]
    fn allows_valid_numeric_content_length() {
        let req = make_req(
            "POST",
            "/api/data",
            vec![("Content-Length", "13")],
            Some(r#"{"key":"val"}"#),
        );
        assert!(check_protocol(&req).is_none());
    }

    #[test]
    fn allows_content_length_with_whitespace() {
        let req = make_req(
            "POST",
            "/api/data",
            vec![("Content-Length", " 13 ")],
            Some(r#"{"key":"val"}"#),
        );
        assert!(check_protocol(&req).is_none());
    }

    // ---- Helper function tests ----

    #[test]
    fn has_illegal_control_chars_works() {
        assert!(!has_illegal_control_chars("normal text"));
        assert!(!has_illegal_control_chars("text\twith\ttabs"));
        assert!(!has_illegal_control_chars("text\nwith\nnewlines"));
        assert!(!has_illegal_control_chars("text\r\nwith\r\ncrlf"));
        assert!(has_illegal_control_chars("text\x00with null"));
        assert!(has_illegal_control_chars("text\x01with SOH"));
        assert!(has_illegal_control_chars("text\x1Fwith US"));
    }

    #[test]
    fn is_body_method_works() {
        assert!(is_body_method("POST"));
        assert!(is_body_method("PUT"));
        assert!(is_body_method("PATCH"));
        assert!(is_body_method("post")); // case insensitive
        assert!(!is_body_method("GET"));
        assert!(!is_body_method("DELETE"));
        assert!(!is_body_method("HEAD"));
        assert!(!is_body_method("OPTIONS"));
    }
}