1use crate::error::{BenchError, Result};
40use crate::security_payloads::{
41 PayloadLocation as SecurityPayloadLocation, SecurityCategory, SecurityPayload,
42};
43use glob::glob;
44use serde::{Deserialize, Serialize};
45use std::collections::HashMap;
46use std::path::Path;
47
48#[derive(Debug, Clone, Deserialize, Serialize)]
50pub struct WafBenchMeta {
51 pub author: Option<String>,
53 pub description: Option<String>,
55 #[serde(default = "default_enabled")]
57 pub enabled: bool,
58 pub name: Option<String>,
60}
61
62fn default_enabled() -> bool {
63 true
64}
65
66#[derive(Debug, Clone, Deserialize, Serialize)]
68pub struct WafBenchTest {
69 pub desc: Option<String>,
71 pub test_title: String,
73 #[serde(default)]
75 pub stages: Vec<WafBenchStage>,
76}
77
78#[derive(Debug, Clone, Deserialize, Serialize)]
81pub struct WafBenchStage {
82 pub input: Option<WafBenchInput>,
84 pub output: Option<WafBenchOutput>,
86 pub stage: Option<WafBenchStageInner>,
88}
89
90#[derive(Debug, Clone, Deserialize, Serialize)]
92pub struct WafBenchStageInner {
93 pub input: WafBenchInput,
95 pub output: Option<WafBenchOutput>,
97}
98
99impl WafBenchStage {
100 pub fn get_input(&self) -> Option<&WafBenchInput> {
102 if let Some(stage) = &self.stage {
104 Some(&stage.input)
105 } else {
106 self.input.as_ref()
107 }
108 }
109
110 pub fn get_output(&self) -> Option<&WafBenchOutput> {
112 if let Some(stage) = &self.stage {
114 stage.output.as_ref()
115 } else {
116 self.output.as_ref()
117 }
118 }
119}
120
121#[derive(Debug, Clone, Deserialize, Serialize)]
123pub struct WafBenchInput {
124 pub dest_addr: Option<String>,
126 #[serde(default)]
128 pub headers: HashMap<String, String>,
129 #[serde(default = "default_method")]
131 pub method: String,
132 #[serde(default = "default_port")]
134 pub port: u16,
135 pub uri: Option<String>,
137 pub data: Option<String>,
139 pub version: Option<String>,
141}
142
143fn default_method() -> String {
144 "GET".to_string()
145}
146
147fn default_port() -> u16 {
148 80
149}
150
151#[derive(Debug, Clone, Deserialize, Serialize)]
153pub struct WafBenchOutput {
154 #[serde(default)]
156 pub status: Vec<u16>,
157 #[serde(default)]
159 pub response_headers: HashMap<String, String>,
160 #[serde(default, deserialize_with = "deserialize_string_or_vec")]
162 pub log_contains: Vec<String>,
163 #[serde(default, deserialize_with = "deserialize_string_or_vec")]
165 pub no_log_contains: Vec<String>,
166}
167
168fn deserialize_string_or_vec<'de, D>(deserializer: D) -> std::result::Result<Vec<String>, D::Error>
170where
171 D: serde::Deserializer<'de>,
172{
173 use serde::de::{self, Visitor};
174
175 struct StringOrVec;
176
177 impl<'de> Visitor<'de> for StringOrVec {
178 type Value = Vec<String>;
179
180 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
181 formatter.write_str("string or array of strings")
182 }
183
184 fn visit_str<E>(self, value: &str) -> std::result::Result<Self::Value, E>
185 where
186 E: de::Error,
187 {
188 Ok(vec![value.to_string()])
189 }
190
191 fn visit_string<E>(self, value: String) -> std::result::Result<Self::Value, E>
192 where
193 E: de::Error,
194 {
195 Ok(vec![value])
196 }
197
198 fn visit_seq<A>(self, mut seq: A) -> std::result::Result<Self::Value, A::Error>
199 where
200 A: de::SeqAccess<'de>,
201 {
202 let mut vec = Vec::new();
203 while let Some(value) = seq.next_element::<String>()? {
204 vec.push(value);
205 }
206 Ok(vec)
207 }
208
209 fn visit_none<E>(self) -> std::result::Result<Self::Value, E>
210 where
211 E: de::Error,
212 {
213 Ok(Vec::new())
214 }
215
216 fn visit_unit<E>(self) -> std::result::Result<Self::Value, E>
217 where
218 E: de::Error,
219 {
220 Ok(Vec::new())
221 }
222 }
223
224 deserializer.deserialize_any(StringOrVec)
225}
226
227#[derive(Debug, Clone, Deserialize, Serialize)]
229pub struct WafBenchFile {
230 pub meta: WafBenchMeta,
232 #[serde(default)]
234 pub tests: Vec<WafBenchTest>,
235}
236
237#[derive(Debug, Clone)]
239pub struct WafBenchTestCase {
240 pub test_id: String,
242 pub description: String,
244 pub rule_id: String,
246 pub category: SecurityCategory,
248 pub method: String,
250 pub payloads: Vec<WafBenchPayload>,
252 pub expects_block: bool,
254}
255
256#[derive(Debug, Clone)]
258pub struct WafBenchPayload {
259 pub location: PayloadLocation,
261 pub value: String,
263 pub header_name: Option<String>,
265}
266
267#[derive(Debug, Clone, Copy, PartialEq, Eq)]
269pub enum PayloadLocation {
270 Uri,
272 Header,
274 Body,
276}
277
278impl std::fmt::Display for PayloadLocation {
279 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
280 match self {
281 Self::Uri => write!(f, "uri"),
282 Self::Header => write!(f, "header"),
283 Self::Body => write!(f, "body"),
284 }
285 }
286}
287
288pub struct WafBenchLoader {
290 test_cases: Vec<WafBenchTestCase>,
292 stats: WafBenchStats,
294}
295
296#[derive(Debug, Clone, Default)]
298pub struct WafBenchStats {
299 pub files_processed: usize,
301 pub test_cases_loaded: usize,
303 pub payloads_extracted: usize,
305 pub by_category: HashMap<SecurityCategory, usize>,
307 pub parse_errors: Vec<String>,
309}
310
311impl WafBenchLoader {
312 pub fn new() -> Self {
314 Self {
315 test_cases: Vec::new(),
316 stats: WafBenchStats::default(),
317 }
318 }
319
320 pub fn load_from_pattern(&mut self, pattern: &str) -> Result<()> {
331 if !pattern.contains('*') && !pattern.contains('?') {
333 let path = Path::new(pattern);
334 if path.is_file() {
335 return self.load_file(path);
337 } else if path.is_dir() {
338 return self.load_from_directory(path);
339 } else {
340 return Err(BenchError::Other(format!(
341 "WAFBench path does not exist: {}",
342 pattern
343 )));
344 }
345 }
346
347 let entries = glob(pattern).map_err(|e| {
349 BenchError::Other(format!("Invalid WAFBench pattern '{}': {}", pattern, e))
350 })?;
351
352 for entry in entries {
353 match entry {
354 Ok(path) => {
355 if path.is_file()
356 && path.extension().is_some_and(|ext| ext == "yaml" || ext == "yml")
357 {
358 if let Err(e) = self.load_file(&path) {
359 self.stats.parse_errors.push(format!("{}: {}", path.display(), e));
360 }
361 } else if path.is_dir() {
362 if let Err(e) = self.load_from_directory(&path) {
363 self.stats.parse_errors.push(format!("{}: {}", path.display(), e));
364 }
365 }
366 }
367 Err(e) => {
368 self.stats.parse_errors.push(format!("Glob error: {}", e));
369 }
370 }
371 }
372
373 Ok(())
374 }
375
376 pub fn load_from_directory(&mut self, dir: &Path) -> Result<()> {
378 if !dir.is_dir() {
379 return Err(BenchError::Other(format!(
380 "WAFBench path is not a directory: {}",
381 dir.display()
382 )));
383 }
384
385 self.load_directory_recursive(dir)?;
386 Ok(())
387 }
388
389 fn load_directory_recursive(&mut self, dir: &Path) -> Result<()> {
390 let entries = std::fs::read_dir(dir)
391 .map_err(|e| BenchError::Other(format!("Failed to read WAFBench directory: {}", e)))?;
392
393 for entry in entries.flatten() {
394 let path = entry.path();
395 if path.is_dir() {
396 self.load_directory_recursive(&path)?;
398 } else if path.extension().is_some_and(|ext| ext == "yaml" || ext == "yml") {
399 if let Err(e) = self.load_file(&path) {
400 self.stats.parse_errors.push(format!("{}: {}", path.display(), e));
401 }
402 }
403 }
404
405 Ok(())
406 }
407
408 pub fn load_file(&mut self, path: &Path) -> Result<()> {
410 let content = std::fs::read_to_string(path).map_err(|e| {
411 BenchError::Other(format!("Failed to read WAFBench file {}: {}", path.display(), e))
412 })?;
413
414 let wafbench_file: WafBenchFile = serde_yaml::from_str(&content).map_err(|e| {
415 BenchError::Other(format!("Failed to parse WAFBench YAML {}: {}", path.display(), e))
416 })?;
417
418 if !wafbench_file.meta.enabled {
420 return Ok(());
421 }
422
423 self.stats.files_processed += 1;
424
425 let category = self.detect_category(path, &wafbench_file.meta);
427
428 for test in wafbench_file.tests {
430 if let Some(test_case) = self.parse_test_case(&test, category) {
431 self.stats.payloads_extracted += test_case.payloads.len();
432 *self.stats.by_category.entry(category).or_insert(0) += 1;
433 self.test_cases.push(test_case);
434 self.stats.test_cases_loaded += 1;
435 }
436 }
437
438 Ok(())
439 }
440
441 fn detect_category(&self, path: &Path, _meta: &WafBenchMeta) -> SecurityCategory {
443 let path_str = path.to_string_lossy().to_uppercase();
444
445 if path_str.contains("XSS") || path_str.contains("941") {
446 SecurityCategory::Xss
447 } else if path_str.contains("SQLI") || path_str.contains("942") {
448 SecurityCategory::SqlInjection
449 } else if path_str.contains("RCE") || path_str.contains("932") {
450 SecurityCategory::CommandInjection
451 } else if path_str.contains("LFI") || path_str.contains("930") {
452 SecurityCategory::PathTraversal
453 } else if path_str.contains("LDAP") {
454 SecurityCategory::LdapInjection
455 } else if path_str.contains("XXE") || path_str.contains("XML") {
456 SecurityCategory::Xxe
457 } else if path_str.contains("TEMPLATE") || path_str.contains("SSTI") {
458 SecurityCategory::Ssti
459 } else {
460 SecurityCategory::Xss
462 }
463 }
464
465 fn parse_test_case(
467 &self,
468 test: &WafBenchTest,
469 category: SecurityCategory,
470 ) -> Option<WafBenchTestCase> {
471 let rule_id = test.test_title.split('-').next().unwrap_or(&test.test_title).to_string();
473
474 let mut payloads = Vec::new();
475 let mut method = "GET".to_string();
476 let mut expects_block = false;
477
478 for stage in &test.stages {
479 let Some(input) = stage.get_input() else {
481 continue;
482 };
483
484 method = input.method.clone();
485
486 if let Some(output) = stage.get_output() {
488 if output.status.contains(&403) {
489 expects_block = true;
490 }
491 }
492
493 if let Some(uri) = &input.uri {
498 if !uri.is_empty() {
499 payloads.push(WafBenchPayload {
500 location: PayloadLocation::Uri,
501 value: uri.clone(),
502 header_name: None,
503 });
504 }
505 }
506
507 for (header_name, header_value) in &input.headers {
509 if !header_value.is_empty() {
510 payloads.push(WafBenchPayload {
511 location: PayloadLocation::Header,
512 value: header_value.clone(),
513 header_name: Some(header_name.clone()),
514 });
515 }
516 }
517
518 if let Some(data) = &input.data {
520 if !data.is_empty() {
521 payloads.push(WafBenchPayload {
522 location: PayloadLocation::Body,
523 value: data.clone(),
524 header_name: None,
525 });
526 }
527 }
528 }
529
530 if payloads.is_empty() {
532 if let Some(stage) = test.stages.first() {
533 if let Some(input) = stage.get_input() {
534 if let Some(uri) = &input.uri {
535 payloads.push(WafBenchPayload {
536 location: PayloadLocation::Uri,
537 value: uri.clone(),
538 header_name: None,
539 });
540 }
541 }
542 }
543 }
544
545 if payloads.is_empty() {
546 return None;
547 }
548
549 let description = test.desc.clone().unwrap_or_else(|| format!("CRS Rule {} test", rule_id));
550
551 Some(WafBenchTestCase {
552 test_id: test.test_title.clone(),
553 description,
554 rule_id,
555 category,
556 method,
557 payloads,
558 expects_block,
559 })
560 }
561
562 #[cfg(test)]
564 fn looks_like_attack(&self, s: &str) -> bool {
565 let attack_patterns = [
567 "<script",
568 "javascript:",
569 "onerror=",
570 "onload=",
571 "onclick=",
572 "onfocus=",
573 "onmouseover=",
574 "eval(",
575 "alert(",
576 "document.",
577 "window.",
578 "'--",
579 "' OR ",
580 "' AND ",
581 "1=1",
582 "UNION SELECT",
583 "CONCAT(",
584 "CHAR(",
585 "../",
586 "..\\",
587 "/etc/passwd",
588 "cmd.exe",
589 "powershell",
590 "; ls",
591 "| cat",
592 "${",
593 "{{",
594 "<%",
595 "<?",
596 "<!ENTITY",
597 "SYSTEM \"",
598 ];
599
600 let lower = s.to_lowercase();
601 attack_patterns.iter().any(|p| lower.contains(&p.to_lowercase()))
602 }
603
604 pub fn test_cases(&self) -> &[WafBenchTestCase] {
606 &self.test_cases
607 }
608
609 pub fn stats(&self) -> &WafBenchStats {
611 &self.stats
612 }
613
614 fn decode_form_encoded_body(value: &str) -> String {
619 let plus_decoded = value.replace('+', " ");
621 let decoded = urlencoding::decode(&plus_decoded)
623 .map(|s| s.into_owned())
624 .unwrap_or(plus_decoded);
625 Self::strip_form_key(&decoded)
629 }
630
631 fn strip_form_key(value: &str) -> String {
636 if let Some(eq_pos) = value.find('=') {
639 let key = &value[..eq_pos];
640 if !key.is_empty() && key.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
642 return value[eq_pos + 1..].to_string();
643 }
644 }
645 value.to_string()
646 }
647
648 pub fn to_security_payloads(&self) -> Vec<SecurityPayload> {
650 let mut payloads = Vec::new();
651
652 for test_case in &self.test_cases {
653 let group_id = if test_case.payloads.len() > 1 {
655 Some(test_case.test_id.clone())
656 } else {
657 None
658 };
659
660 for payload in &test_case.payloads {
661 let payload_str = match payload.location {
663 PayloadLocation::Body => {
664 Self::decode_form_encoded_body(&payload.value)
666 }
667 PayloadLocation::Uri => {
668 self.extract_uri_payload(&payload.value)
670 }
671 PayloadLocation::Header => {
672 payload.value.clone()
674 }
675 };
676
677 let location = match payload.location {
679 PayloadLocation::Uri => SecurityPayloadLocation::Uri,
680 PayloadLocation::Header => SecurityPayloadLocation::Header,
681 PayloadLocation::Body => SecurityPayloadLocation::Body,
682 };
683
684 let mut sec_payload = SecurityPayload::new(
685 payload_str,
686 test_case.category,
687 format!(
688 "[WAFBench {}] {} ({})",
689 test_case.rule_id, test_case.description, payload.location
690 ),
691 )
692 .high_risk()
693 .with_location(location);
694
695 if let Some(header_name) = &payload.header_name {
697 sec_payload = sec_payload.with_header_name(header_name.clone());
698 }
699
700 if let Some(gid) = &group_id {
702 sec_payload = sec_payload.with_group_id(gid.clone());
703 }
704
705 if payload.location == PayloadLocation::Uri && !payload.value.contains('?') {
708 sec_payload = sec_payload.with_inject_as_path();
709 }
710
711 if payload.location == PayloadLocation::Body {
714 sec_payload = sec_payload.with_form_encoded_body(payload.value.clone());
715 }
716
717 payloads.push(sec_payload);
718 }
719 }
720
721 payloads
722 }
723
724 fn extract_uri_payload(&self, value: &str) -> String {
732 if value.contains('?') {
735 if let Some(query) = value.split('?').nth(1) {
736 for param in query.split('&') {
737 if let Some(val) = param.split('=').nth(1) {
738 let decoded = urlencoding::decode(val).unwrap_or_else(|_| val.into());
739 if !decoded.is_empty() {
740 return decoded.to_string();
741 }
742 }
743 }
744 }
745 }
746
747 let decoded = urlencoding::decode(value)
750 .map(|s| s.into_owned())
751 .unwrap_or_else(|_| value.to_string());
752 let trimmed = decoded.trim_start_matches('/');
753 if trimmed.is_empty() {
754 return decoded;
756 }
757 trimmed.to_string()
758 }
759}
760
761impl Default for WafBenchLoader {
762 fn default() -> Self {
763 Self::new()
764 }
765}
766
767#[cfg(test)]
768mod tests {
769 use super::*;
770
771 #[test]
772 fn test_parse_wafbench_yaml() {
773 let yaml = r#"
774meta:
775 author: test
776 description: Test XSS rules
777 enabled: true
778 name: test.yaml
779
780tests:
781 - desc: "XSS in URI parameter"
782 test_title: "941100-1"
783 stages:
784 - input:
785 dest_addr: "127.0.0.1"
786 headers:
787 Host: "localhost"
788 User-Agent: "Mozilla/5.0"
789 method: "GET"
790 port: 80
791 uri: "/test?param=<script>alert(1)</script>"
792 output:
793 status: [403]
794"#;
795
796 let file: WafBenchFile = serde_yaml::from_str(yaml).unwrap();
797 assert!(file.meta.enabled);
798 assert_eq!(file.tests.len(), 1);
799 assert_eq!(file.tests[0].test_title, "941100-1");
800 }
801
802 #[test]
803 fn test_detect_category() {
804 let loader = WafBenchLoader::new();
805 let meta = WafBenchMeta {
806 author: None,
807 description: None,
808 enabled: true,
809 name: None,
810 };
811
812 assert_eq!(
813 loader.detect_category(Path::new("/wafbench/REQUEST-941-XSS/test.yaml"), &meta),
814 SecurityCategory::Xss
815 );
816
817 assert_eq!(
818 loader.detect_category(Path::new("/wafbench/REQUEST-942-SQLI/test.yaml"), &meta),
819 SecurityCategory::SqlInjection
820 );
821 }
822
823 #[test]
824 fn test_looks_like_attack() {
825 let loader = WafBenchLoader::new();
826
827 assert!(loader.looks_like_attack("<script>alert(1)</script>"));
828 assert!(loader.looks_like_attack("' OR '1'='1"));
829 assert!(loader.looks_like_attack("../../../etc/passwd"));
830 assert!(loader.looks_like_attack("; ls -la"));
831 assert!(!loader.looks_like_attack("normal text"));
832 assert!(!loader.looks_like_attack("hello world"));
833 }
834
835 #[test]
836 fn test_extract_uri_payload_with_query_params() {
837 let loader = WafBenchLoader::new();
838
839 let uri = "/test?param=%3Cscript%3Ealert(1)%3C/script%3E";
841 let payload = loader.extract_uri_payload(uri);
842 assert_eq!(payload, "<script>alert(1)</script>");
843 }
844
845 #[test]
846 fn test_extract_uri_payload_path_only() {
847 let loader = WafBenchLoader::new();
848
849 let uri = "/1234%20OR%201=1";
851 let payload = loader.extract_uri_payload(uri);
852 assert_eq!(payload, "1234 OR 1=1");
853
854 let uri2 = "/foo')waitfor%20delay'5%3a0%3a20'--";
856 let payload2 = loader.extract_uri_payload(uri2);
857 assert_eq!(payload2, "foo')waitfor delay'5:0:20'--");
858
859 let uri3 = "/";
861 let payload3 = loader.extract_uri_payload(uri3);
862 assert_eq!(payload3, "/");
863 }
864
865 #[test]
866 fn test_group_id_assigned_for_multi_part_test_cases() {
867 let yaml = r#"
868meta:
869 author: test
870 description: Multi-part test
871 enabled: true
872 name: test.yaml
873
874tests:
875 - desc: "Multi-part attack with URI and header"
876 test_title: "942290-1"
877 stages:
878 - input:
879 dest_addr: "127.0.0.1"
880 headers:
881 Host: "localhost"
882 User-Agent: "ModSecurity CRS 3 Tests"
883 method: "GET"
884 port: 80
885 uri: "/test?param=attack"
886 output:
887 status: [403]
888"#;
889
890 let file: WafBenchFile = serde_yaml::from_str(yaml).unwrap();
891 let mut loader = WafBenchLoader::new();
892 loader.stats.files_processed += 1;
893
894 let category = SecurityCategory::SqlInjection;
895 for test in &file.tests {
896 if let Some(test_case) = loader.parse_test_case(test, category) {
897 loader.test_cases.push(test_case);
898 }
899 }
900
901 let payloads = loader.to_security_payloads();
902 assert!(payloads.len() >= 2, "Should have at least 2 payloads");
904 let group_ids: Vec<_> = payloads.iter().map(|p| p.group_id.clone()).collect();
905 assert!(
906 group_ids.iter().all(|g| g.is_some()),
907 "All payloads in multi-part test should have group_id"
908 );
909 assert!(
910 group_ids.iter().all(|g| g.as_deref() == Some("942290-1")),
911 "All payloads should share the same group_id"
912 );
913 }
914
915 #[test]
916 fn test_single_payload_no_group_id() {
917 let yaml = r#"
918meta:
919 author: test
920 description: Single payload test
921 enabled: true
922 name: test.yaml
923
924tests:
925 - desc: "Simple XSS"
926 test_title: "941100-1"
927 stages:
928 - input:
929 dest_addr: "127.0.0.1"
930 headers: {}
931 method: "GET"
932 port: 80
933 uri: "/test?param=<script>alert(1)</script>"
934 output:
935 status: [403]
936"#;
937
938 let file: WafBenchFile = serde_yaml::from_str(yaml).unwrap();
939 let mut loader = WafBenchLoader::new();
940 loader.stats.files_processed += 1;
941
942 let category = SecurityCategory::Xss;
943 for test in &file.tests {
944 if let Some(test_case) = loader.parse_test_case(test, category) {
945 loader.test_cases.push(test_case);
946 }
947 }
948
949 let payloads = loader.to_security_payloads();
950 assert_eq!(payloads.len(), 1, "Should have exactly 1 payload");
951 assert!(payloads[0].group_id.is_none(), "Single-payload test should NOT have group_id");
952 }
953
954 #[test]
955 fn test_body_payload_form_url_decoded() {
956 let yaml = r#"
957meta:
958 author: test
959 description: Body payload test
960 enabled: true
961 name: test.yaml
962
963tests:
964 - desc: "SQL injection in body"
965 test_title: "942240-1"
966 stages:
967 - stage:
968 input:
969 dest_addr: 127.0.0.1
970 headers:
971 Host: localhost
972 method: POST
973 port: 80
974 uri: "/"
975 data: "%22+WAITFOR+DELAY+%270%3A0%3A5%27"
976 output:
977 log_contains: id "942240"
978"#;
979
980 let file: WafBenchFile = serde_yaml::from_str(yaml).unwrap();
981 let mut loader = WafBenchLoader::new();
982 loader.stats.files_processed += 1;
983
984 let category = SecurityCategory::SqlInjection;
985 for test in &file.tests {
986 if let Some(test_case) = loader.parse_test_case(test, category) {
987 loader.test_cases.push(test_case);
988 }
989 }
990
991 let payloads = loader.to_security_payloads();
992 let body_payload = payloads
994 .iter()
995 .find(|p| p.location == SecurityPayloadLocation::Body)
996 .expect("Should have a body payload");
997
998 assert!(
1000 body_payload.payload.contains('"'),
1001 "Body payload should have decoded %22 to double-quote: {}",
1002 body_payload.payload
1003 );
1004 assert!(
1005 body_payload.payload.contains(' '),
1006 "Body payload should have decoded + to space: {}",
1007 body_payload.payload
1008 );
1009 assert!(
1010 !body_payload.payload.contains("%22"),
1011 "Body payload should NOT contain literal %22: {}",
1012 body_payload.payload
1013 );
1014 }
1015
1016 #[test]
1017 fn test_decode_form_encoded_body() {
1018 assert_eq!(
1020 WafBenchLoader::decode_form_encoded_body("%22+WAITFOR+DELAY+%27%0A"),
1021 "\" WAITFOR DELAY '\n"
1022 );
1023 assert_eq!(WafBenchLoader::decode_form_encoded_body("normal+text"), "normal text");
1024 assert_eq!(
1025 WafBenchLoader::decode_form_encoded_body("no+encoding+needed"),
1026 "no encoding needed"
1027 );
1028 assert_eq!(
1030 WafBenchLoader::decode_form_encoded_body("var%3D%3B%3Bdd+foo+bar"),
1031 ";;dd foo bar"
1032 );
1033 assert_eq!(WafBenchLoader::decode_form_encoded_body("pay%3Dexec+%28%40%0A"), "exec (@\n");
1035 assert_eq!(WafBenchLoader::decode_form_encoded_body("%22+WAITFOR"), "\" WAITFOR");
1037 }
1038
1039 #[test]
1040 fn test_strip_form_key() {
1041 assert_eq!(WafBenchLoader::strip_form_key("var=;;dd foo bar"), ";;dd foo bar");
1043 assert_eq!(WafBenchLoader::strip_form_key("pay=exec (@\n"), "exec (@\n");
1044 assert_eq!(WafBenchLoader::strip_form_key("pay=DECLARE/**/@x\n"), "DECLARE/**/@x\n");
1045 assert_eq!(WafBenchLoader::strip_form_key("\" WAITFOR DELAY '\n"), "\" WAITFOR DELAY '\n");
1047 assert_eq!(WafBenchLoader::strip_form_key("' OR 1=1"), "' OR 1=1");
1049 assert_eq!(WafBenchLoader::strip_form_key(""), "");
1051 assert_eq!(WafBenchLoader::strip_form_key("var="), "");
1053 }
1054
1055 #[test]
1056 fn test_uri_path_only_gets_inject_as_path() {
1057 let yaml = r#"
1058meta:
1059 author: test
1060 description: Path injection test
1061 enabled: true
1062 name: test.yaml
1063
1064tests:
1065 - desc: "Path-based SQL injection"
1066 test_title: "942101-1"
1067 stages:
1068 - stage:
1069 input:
1070 dest_addr: 127.0.0.1
1071 headers:
1072 Host: localhost
1073 method: POST
1074 port: 80
1075 uri: "/1234%20OR%201=1"
1076 output:
1077 log_contains: id "942101"
1078"#;
1079
1080 let file: WafBenchFile = serde_yaml::from_str(yaml).unwrap();
1081 let mut loader = WafBenchLoader::new();
1082 loader.stats.files_processed += 1;
1083
1084 let category = SecurityCategory::SqlInjection;
1085 for test in &file.tests {
1086 if let Some(test_case) = loader.parse_test_case(test, category) {
1087 loader.test_cases.push(test_case);
1088 }
1089 }
1090
1091 let payloads = loader.to_security_payloads();
1092 let uri_payload = payloads
1093 .iter()
1094 .find(|p| p.location == SecurityPayloadLocation::Uri)
1095 .expect("Should have URI payload");
1096
1097 assert_eq!(
1098 uri_payload.inject_as_path,
1099 Some(true),
1100 "Path-only URI should have inject_as_path=true"
1101 );
1102 }
1103
1104 #[test]
1105 fn test_uri_with_query_no_inject_as_path() {
1106 let yaml = r#"
1107meta:
1108 author: test
1109 description: Query param test
1110 enabled: true
1111 name: test.yaml
1112
1113tests:
1114 - desc: "Query-param SQL injection"
1115 test_title: "942100-1"
1116 stages:
1117 - stage:
1118 input:
1119 dest_addr: 127.0.0.1
1120 headers: {}
1121 method: GET
1122 port: 80
1123 uri: "/test?param=1+OR+1%3D1"
1124 output:
1125 log_contains: id "942100"
1126"#;
1127
1128 let file: WafBenchFile = serde_yaml::from_str(yaml).unwrap();
1129 let mut loader = WafBenchLoader::new();
1130 loader.stats.files_processed += 1;
1131
1132 let category = SecurityCategory::SqlInjection;
1133 for test in &file.tests {
1134 if let Some(test_case) = loader.parse_test_case(test, category) {
1135 loader.test_cases.push(test_case);
1136 }
1137 }
1138
1139 let payloads = loader.to_security_payloads();
1140 let uri_payload = payloads
1141 .iter()
1142 .find(|p| p.location == SecurityPayloadLocation::Uri)
1143 .expect("Should have URI payload");
1144
1145 assert!(
1146 uri_payload.inject_as_path.is_none(),
1147 "URI with query params should NOT have inject_as_path"
1148 );
1149 }
1150
1151 #[test]
1152 fn test_body_payload_gets_form_encoded_body() {
1153 let yaml = r#"
1154meta:
1155 author: test
1156 description: Form body test
1157 enabled: true
1158 name: test.yaml
1159
1160tests:
1161 - desc: "Form-encoded body attack"
1162 test_title: "942432-1"
1163 stages:
1164 - stage:
1165 input:
1166 dest_addr: 127.0.0.1
1167 headers:
1168 Host: localhost
1169 method: POST
1170 port: 80
1171 uri: "/"
1172 data: "var=%3B%3Bdd+foo+bar"
1173 output:
1174 log_contains: id "942432"
1175"#;
1176
1177 let file: WafBenchFile = serde_yaml::from_str(yaml).unwrap();
1178 let mut loader = WafBenchLoader::new();
1179 loader.stats.files_processed += 1;
1180
1181 let category = SecurityCategory::SqlInjection;
1182 for test in &file.tests {
1183 if let Some(test_case) = loader.parse_test_case(test, category) {
1184 loader.test_cases.push(test_case);
1185 }
1186 }
1187
1188 let payloads = loader.to_security_payloads();
1189 let body_payload = payloads
1190 .iter()
1191 .find(|p| p.location == SecurityPayloadLocation::Body)
1192 .expect("Should have body payload");
1193
1194 assert!(
1195 body_payload.form_encoded_body.is_some(),
1196 "Body payload should have form_encoded_body set"
1197 );
1198 assert_eq!(
1199 body_payload.form_encoded_body.as_deref().unwrap(),
1200 "var=%3B%3Bdd+foo+bar",
1201 "form_encoded_body should contain the raw CRS data value"
1202 );
1203 }
1204
1205 #[test]
1206 fn test_parse_crs_v33_format() {
1207 let yaml = r#"
1209meta:
1210 author: "Christian Folini"
1211 description: Various SQL injection tests
1212 enabled: true
1213 name: 942100.yaml
1214
1215tests:
1216 - test_title: 942100-1
1217 desc: "Simple SQL Injection"
1218 stages:
1219 - stage:
1220 input:
1221 dest_addr: 127.0.0.1
1222 headers:
1223 Host: localhost
1224 method: POST
1225 port: 80
1226 uri: "/"
1227 data: "var=1234 OR 1=1"
1228 version: HTTP/1.0
1229 output:
1230 log_contains: id "942100"
1231"#;
1232
1233 let file: WafBenchFile = serde_yaml::from_str(yaml).unwrap();
1234 assert!(file.meta.enabled);
1235 assert_eq!(file.tests.len(), 1);
1236 assert_eq!(file.tests[0].test_title, "942100-1");
1237
1238 let stage = &file.tests[0].stages[0];
1240 let input = stage.get_input().expect("Should have input");
1241 assert_eq!(input.method, "POST");
1242 assert_eq!(input.data.as_deref(), Some("var=1234 OR 1=1"));
1243 }
1244}