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
//! Forward taint propagation analysis
//!
//! Tracks which variables contain tainted (user-controlled) data
//! by propagating taint through assignments.
//!
//! Supports cross-file taint tracking via CallGraph integration.
//!
//! ## Function Body Taint Analysis
//!
//! The `FunctionBodyTaintAnalyzer` provides fine-grained intra-procedural taint
//! tracking by walking the AST and tracking taint flow through:
//! - Assignments: `x = tainted_var` propagates taint to `x`
//! - Method calls: `x = obj.method(tainted)` may propagate taint
//! - Binary operations: `x = tainted + "safe"` propagates taint
//! - Return statements: tracks what flows to return values
use super::cfg::CFG;
use super::interprocedural::TaintSummary;
use super::sources::{SourcePattern, TaintConfig};
use super::symbol_table::{SymbolTable, ValueOrigin};
use crate::callgraph::CallGraph;
use crate::semantics::LanguageSemantics;
use rma_common::Language;
use rma_parser::ParsedFile;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use tree_sitter::Node;
/// Taint level for path-sensitive analysis
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TaintLevel {
/// Variable is clean (never tainted, or sanitized on all paths)
Clean,
/// Variable is tainted on some paths but not others
Partial,
/// Variable is tainted on all paths to this point
Full,
}
/// Taint analyzer that propagates taint through the symbol table
pub struct TaintAnalyzer;
impl TaintAnalyzer {
/// Analyze symbol table and determine which variables are tainted
pub fn analyze(symbols: &SymbolTable, config: &TaintConfig) -> TaintResult {
Self::analyze_with_call_graph(symbols, config, None, None, None)
}
/// Analyze with optional CallGraph for cross-file taint tracking
///
/// # Arguments
/// * `symbols` - Symbol table from the file being analyzed
/// * `config` - Taint configuration (sources, sinks, sanitizers)
/// * `call_graph` - Optional call graph for cross-file function lookups
/// * `file_path` - Current file path (required if call_graph is provided)
/// * `cross_file_summaries` - Optional summaries from other files for cross-file taint
pub fn analyze_with_call_graph(
symbols: &SymbolTable,
config: &TaintConfig,
call_graph: Option<&CallGraph>,
file_path: Option<&Path>,
cross_file_summaries: Option<&HashMap<String, TaintSummary>>,
) -> TaintResult {
let mut tainted = HashSet::new();
let mut sanitization_points: HashMap<String, Vec<usize>> = HashMap::new();
let mut cross_file_sources: HashSet<String> = HashSet::new();
// Phase 1: Mark initial taint from sources
for (name, info) in symbols.iter() {
if Self::is_initially_tainted(&info.initializer, config) {
tainted.insert(name.clone());
}
}
// Phase 1.5: Check cross-file sources if call graph is available
if let (Some(cg), Some(fp)) = (call_graph, file_path) {
for (name, info) in symbols.iter() {
if let ValueOrigin::FunctionCall(func_name) = &info.initializer {
// Check if this function call is a cross-file source
if let Some(is_source) =
Self::check_cross_file_source(func_name, cg, fp, cross_file_summaries)
&& is_source
{
tainted.insert(name.clone());
cross_file_sources.insert(name.clone());
}
}
}
}
// Phase 2: Propagate taint through assignments (fixed-point iteration)
// If x = tainted_var, then x is tainted too
// If x = sanitize(tainted_var), then x is NOT tainted
loop {
let mut changed = false;
for (name, info) in symbols.iter() {
if tainted.contains(name) {
continue;
}
// Check initializer
let (propagates, is_sanitizer) =
Self::propagates_taint_with_sanitizer_and_call_graph(
&info.initializer,
&tainted,
config,
call_graph,
file_path,
cross_file_summaries,
);
if propagates {
tainted.insert(name.clone());
changed = true;
continue;
}
if is_sanitizer {
// Track sanitization point using the declaration node id
sanitization_points
.entry(name.clone())
.or_default()
.push(info.declaration_node_id);
}
// Check all reassignments
for origin in &info.reassignments {
let (propagates, is_sanitizer) =
Self::propagates_taint_with_sanitizer_and_call_graph(
origin,
&tainted,
config,
call_graph,
file_path,
cross_file_summaries,
);
if propagates {
tainted.insert(name.clone());
changed = true;
break;
}
if is_sanitizer {
sanitization_points
.entry(name.clone())
.or_default()
.push(info.declaration_node_id);
}
}
}
if !changed {
break;
}
}
TaintResult {
tainted_vars: tainted,
sanitization_points,
cross_file_sources,
file: file_path.map(|p| p.to_path_buf()),
}
}
/// Check if a function call to another file is a taint source
fn check_cross_file_source(
func_name: &str,
call_graph: &CallGraph,
current_file: &Path,
cross_file_summaries: Option<&HashMap<String, TaintSummary>>,
) -> Option<bool> {
// Look up the function in the call graph
let functions = call_graph.get_functions_by_name(func_name);
for func in functions {
// Skip functions in the same file
if func.file == current_file {
continue;
}
// Check if we have a summary for this cross-file function
if let Some(summaries) = cross_file_summaries {
let key = format!("{}:{}", func.file.display(), func_name);
if let Some(summary) = summaries.get(&key)
&& summary.is_source()
{
return Some(true);
}
// Also check by just the function name
if let Some(summary) = summaries.get(func_name)
&& summary.is_source()
{
return Some(true);
}
}
}
None
}
/// Check if a function call from another file propagates taint
#[allow(dead_code)]
fn check_cross_file_taint_propagation(
func_name: &str,
call_graph: &CallGraph,
current_file: &Path,
cross_file_summaries: Option<&HashMap<String, TaintSummary>>,
) -> Option<bool> {
let functions = call_graph.get_functions_by_name(func_name);
for func in functions {
if func.file == current_file {
continue;
}
if let Some(summaries) = cross_file_summaries {
let key = format!("{}:{}", func.file.display(), func_name);
if let Some(summary) = summaries.get(&key) {
// Check if any parameter taints the return value
if summary.propagates_taint {
return Some(true);
}
}
if let Some(summary) = summaries.get(func_name)
&& summary.propagates_taint
{
return Some(true);
}
}
}
None
}
/// Check if taint propagates, considering cross-file function calls
fn propagates_taint_with_sanitizer_and_call_graph(
origin: &ValueOrigin,
tainted: &HashSet<String>,
config: &TaintConfig,
call_graph: Option<&CallGraph>,
file_path: Option<&Path>,
cross_file_summaries: Option<&HashMap<String, TaintSummary>>,
) -> (bool, bool) {
match origin {
ValueOrigin::FunctionCall(func_name) => {
if config.is_sanitizer(func_name) {
return (false, true);
}
if config.is_source_function(func_name) {
return (true, false);
}
// Check cross-file sources
if let (Some(cg), Some(fp)) = (call_graph, file_path)
&& let Some(is_source) =
Self::check_cross_file_source(func_name, cg, fp, cross_file_summaries)
&& is_source
{
return (true, false);
}
(false, false)
}
ValueOrigin::Variable(src_name) => (tainted.contains(src_name), false),
ValueOrigin::MemberAccess(path) => (config.is_source_member(path), false),
// String concatenation: tainted if ANY operand variable is tainted
ValueOrigin::StringConcat(variables) => {
let any_tainted = variables.iter().any(|var| {
// Check direct variable taint
if tainted.contains(var) {
return true;
}
// Check if it's a member access that's a source (e.g., req.query)
if config.is_source_member(var) {
return true;
}
// Check partial matches (e.g., "req.query.id" contains "req.query")
for tainted_var in tainted {
if var.starts_with(tainted_var) || tainted_var.starts_with(var) {
return true;
}
}
false
});
(any_tainted, false)
}
// Template literals: tainted if ANY interpolated variable is tainted
ValueOrigin::TemplateLiteral(variables) => {
let any_tainted = variables.iter().any(|var| {
if tainted.contains(var) {
return true;
}
if config.is_source_member(var) {
return true;
}
for tainted_var in tainted {
if var.starts_with(tainted_var) || tainted_var.starts_with(var) {
return true;
}
}
false
});
(any_tainted, false)
}
// Method calls: check if receiver or any argument is tainted
ValueOrigin::MethodCall {
method,
receiver,
arguments,
} => {
// Check if it's a sanitizer method
if config.is_sanitizer(method) {
return (false, true);
}
// String methods that propagate taint
let propagating_methods = [
"concat",
"join",
"format",
"replace",
"trim",
"toLowerCase",
"toUpperCase",
"slice",
"substring",
"substr",
"split",
"repeat",
"padStart",
"padEnd",
"append",
"push_str",
"to_string",
"to_str",
"sprintf",
"printf",
"Sprintf",
"Join",
"Format",
"format!",
];
let is_propagating = propagating_methods
.iter()
.any(|m| method.eq_ignore_ascii_case(m) || method.contains(m));
if is_propagating {
// Check if receiver is tainted
if let Some(recv) = receiver
&& (tainted.contains(recv) || config.is_source_member(recv))
{
return (true, false);
}
// Check if any argument is tainted
let args_tainted = arguments.iter().any(|arg| {
if tainted.contains(arg) {
return true;
}
if config.is_source_member(arg) {
return true;
}
for tainted_var in tainted {
if arg.starts_with(tainted_var) || tainted_var.starts_with(arg) {
return true;
}
}
false
});
return (args_tainted, false);
}
(false, false)
}
// Legacy binary expression - try to be conservative
ValueOrigin::BinaryExpression => (false, false),
ValueOrigin::Literal(_) => (false, false),
ValueOrigin::Parameter(_) => (false, false),
ValueOrigin::Unknown => (false, false),
}
}
/// Check if taint propagates and whether a sanitizer is applied
/// Returns (propagates_taint, is_sanitizer_call)
#[allow(dead_code)]
fn propagates_taint_with_sanitizer(
origin: &ValueOrigin,
tainted: &HashSet<String>,
config: &TaintConfig,
) -> (bool, bool) {
Self::propagates_taint_with_sanitizer_and_call_graph(
origin, tainted, config, None, None, None,
)
}
/// Check if a value origin is an initial taint source
fn is_initially_tainted(origin: &ValueOrigin, config: &TaintConfig) -> bool {
match origin {
// All function parameters are conservatively tainted
ValueOrigin::Parameter(_) => config
.sources
.iter()
.any(|s| matches!(s.pattern, SourcePattern::Parameter)),
// Check if function call is a source
ValueOrigin::FunctionCall(func_name) => config.is_source_function(func_name),
// Check if member access is a source
ValueOrigin::MemberAccess(path) => config.is_source_member(path),
// Literals are never tainted
ValueOrigin::Literal(_) => false,
// Variables need propagation analysis
ValueOrigin::Variable(_) => false,
// Binary expressions need deeper analysis
ValueOrigin::BinaryExpression => false,
// String concatenation: check if any operand is directly a source
ValueOrigin::StringConcat(variables) => {
variables.iter().any(|var| config.is_source_member(var))
}
// Template literals: check if any interpolation is directly a source
ValueOrigin::TemplateLiteral(variables) => {
variables.iter().any(|var| config.is_source_member(var))
}
// Method calls: check if it's a source function or has source arguments
ValueOrigin::MethodCall {
method,
receiver,
arguments,
} => {
// Check if method itself is a source
if config.is_source_function(method) {
return true;
}
// Check if receiver is a source
if let Some(recv) = receiver
&& config.is_source_member(recv)
{
return true;
}
// Check arguments
arguments.iter().any(|arg| config.is_source_member(arg))
}
// Unknown is conservatively not tainted (would cause too many FPs)
ValueOrigin::Unknown => false,
}
}
}
// =============================================================================
// Function Body Taint Analyzer
// =============================================================================
/// Taint state at a specific program point
#[derive(Debug, Clone, Default)]
pub struct TaintState {
/// Variables that are tainted at this point
pub tainted: HashSet<String>,
/// Variables that have been sanitized at this point
pub sanitized: HashSet<String>,
}
impl TaintState {
/// Create a new empty taint state
pub fn new() -> Self {
Self::default()
}
/// Create a taint state with initial tainted variables
pub fn with_tainted(tainted: HashSet<String>) -> Self {
Self {
tainted,
sanitized: HashSet::new(),
}
}
/// Check if a variable is tainted
pub fn is_tainted(&self, var: &str) -> bool {
self.tainted.contains(var) && !self.sanitized.contains(var)
}
/// Mark a variable as tainted
pub fn mark_tainted(&mut self, var: String) {
self.sanitized.remove(&var);
self.tainted.insert(var);
}
/// Mark a variable as sanitized (no longer tainted)
pub fn mark_sanitized(&mut self, var: String) {
self.tainted.remove(&var);
self.sanitized.insert(var);
}
/// Mark a variable as clean (never tainted)
pub fn mark_clean(&mut self, var: &str) {
self.tainted.remove(var);
}
/// Merge another state into this one (union for taint, intersection for sanitized)
pub fn merge(&mut self, other: &TaintState) {
self.tainted.extend(other.tainted.iter().cloned());
// For sanitized, we need intersection (only sanitized if sanitized on all paths)
self.sanitized = self
.sanitized
.intersection(&other.sanitized)
.cloned()
.collect();
}
/// Clone the current state
pub fn clone_state(&self) -> Self {
self.clone()
}
}
/// Result of function body taint analysis
#[derive(Debug, Clone)]
pub struct FunctionBodyTaintResult {
/// Function name being analyzed
pub function_name: String,
/// Taint state at each statement (node_id -> state)
pub states_at: HashMap<usize, TaintState>,
/// Variables that flow to return statements
pub return_tainted: HashSet<String>,
/// Final taint state at function exit
pub exit_state: TaintState,
/// Parameters that are marked as tainted
pub tainted_params: HashSet<String>,
/// Variables assigned from tainted sources within the function
pub taint_sources: HashMap<String, TaintSourceInfo>,
}
/// Information about where a variable's taint originated
#[derive(Debug, Clone)]
pub struct TaintSourceInfo {
/// Variable name
pub var_name: String,
/// Line number where taint was introduced
pub line: usize,
/// Node ID where taint was introduced
pub node_id: usize,
/// Source of taint (e.g., parameter name, function call)
pub source: String,
}
impl FunctionBodyTaintResult {
/// Check if a variable is tainted at a specific program point
pub fn is_tainted_at(&self, var: &str, node_id: usize) -> bool {
self.states_at
.get(&node_id)
.map(|state| state.is_tainted(var))
.unwrap_or(false)
}
/// Check if any return value is tainted
pub fn has_tainted_return(&self) -> bool {
!self.return_tainted.is_empty()
}
/// Get all variables that are tainted at function exit
pub fn tainted_at_exit(&self) -> &HashSet<String> {
&self.exit_state.tainted
}
/// Check if a parameter propagates to tainted return
pub fn param_taints_return(&self, param: &str) -> bool {
self.tainted_params.contains(param) && self.return_tainted.contains(param)
}
}
/// Analyzes taint flow within a single function body
///
/// This analyzer walks the AST of a function and tracks taint propagation
/// through assignments, method calls, binary operations, and return statements.
///
/// # Example
///
/// ```ignore
/// let analyzer = FunctionBodyTaintAnalyzer::new(config, semantics);
/// let result = analyzer.analyze_function(parsed, func_node);
/// if result.has_tainted_return() {
/// println!("Function returns tainted data!");
/// }
/// ```
pub struct FunctionBodyTaintAnalyzer<'a> {
/// Taint configuration
config: &'a TaintConfig,
/// Language semantics for AST traversal
semantics: &'static LanguageSemantics,
/// Current taint state during analysis
current_state: TaintState,
/// States at each node
states_at: HashMap<usize, TaintState>,
/// Variables flowing to return
return_tainted: HashSet<String>,
/// Taint sources discovered
taint_sources: HashMap<String, TaintSourceInfo>,
/// Source content for text extraction
source: &'a [u8],
}
impl<'a> FunctionBodyTaintAnalyzer<'a> {
/// Create a new function body taint analyzer
pub fn new(
config: &'a TaintConfig,
semantics: &'static LanguageSemantics,
source: &'a [u8],
) -> Self {
Self {
config,
semantics,
current_state: TaintState::new(),
states_at: HashMap::new(),
return_tainted: HashSet::new(),
taint_sources: HashMap::new(),
source,
}
}
/// Analyze a function body for taint flow
///
/// # Arguments
/// * `func_node` - The tree-sitter node for the function definition
/// * `initial_tainted` - Variables that are initially tainted (e.g., parameters)
///
/// # Returns
/// A `FunctionBodyTaintResult` containing the analysis results
pub fn analyze_function(
mut self,
func_node: Node<'_>,
initial_tainted: HashSet<String>,
) -> FunctionBodyTaintResult {
// Extract function name
let function_name = func_node
.child_by_field_name(self.semantics.name_field)
.and_then(|n| n.utf8_text(self.source).ok())
.unwrap_or("anonymous")
.to_string();
// Initialize with tainted parameters
let tainted_params = initial_tainted.clone();
self.current_state = TaintState::with_tainted(initial_tainted);
// Find and analyze the function body
if let Some(body) = func_node.child_by_field_name("body") {
self.analyze_block(body);
}
FunctionBodyTaintResult {
function_name,
states_at: self.states_at,
return_tainted: self.return_tainted,
exit_state: self.current_state,
tainted_params,
taint_sources: self.taint_sources,
}
}
/// Analyze a block of statements
fn analyze_block(&mut self, block: Node<'_>) {
let mut cursor = block.walk();
for child in block.children(&mut cursor) {
if child.is_named() {
self.analyze_statement(child);
}
}
}
/// Analyze a single statement
fn analyze_statement(&mut self, node: Node<'_>) {
let kind = node.kind();
// Record state before processing this node
self.states_at
.insert(node.id(), self.current_state.clone_state());
// Handle different statement types
if self.semantics.is_assignment(kind) || self.is_variable_declaration(kind) {
self.analyze_assignment(node);
} else if self.semantics.is_return(kind) {
self.analyze_return(node);
} else if self.is_if_statement(kind) {
self.analyze_if(node);
} else if self.semantics.is_loop(kind) {
self.analyze_loop(node);
} else if self.is_block(kind) {
self.analyze_block(node);
} else if self.semantics.is_call(kind) {
// Standalone call expression (side effects only)
self.analyze_call_expression(node);
} else {
// Recurse into children for nested statements
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
if child.is_named() {
self.analyze_statement(child);
}
}
}
}
/// Analyze an assignment or variable declaration
fn analyze_assignment(&mut self, node: Node<'_>) {
// Extract variable name and check if value is tainted
let (var_name, is_tainted, is_sanitized, source_desc) = self.analyze_assignment_node(node);
if let Some(var_name) = var_name {
if is_sanitized {
self.current_state.mark_sanitized(var_name.clone());
} else if is_tainted {
self.current_state.mark_tainted(var_name.clone());
// Record taint source
if let Some(source) = source_desc {
self.taint_sources.insert(
var_name.clone(),
TaintSourceInfo {
var_name: var_name.clone(),
line: node.start_position().row + 1,
node_id: node.id(),
source,
},
);
}
} else {
self.current_state.mark_clean(&var_name);
}
}
}
/// Analyze an assignment node and return (var_name, is_tainted, is_sanitized, source_desc)
fn analyze_assignment_node(
&self,
node: Node<'_>,
) -> (Option<String>, bool, bool, Option<String>) {
let kind = node.kind();
// Handle variable_declarator (const x = ...)
if kind == "variable_declarator" {
let name = node
.child_by_field_name("name")
.and_then(|n| n.utf8_text(self.source).ok())
.map(String::from);
if let Some(value) = node.child_by_field_name("value") {
let is_tainted = self.is_expression_tainted(value);
let is_sanitized = self.is_sanitizer_call(value);
let source_desc = if is_tainted {
Some(self.describe_taint_source(value))
} else {
None
};
return (name, is_tainted, is_sanitized, source_desc);
}
return (name, false, false, None);
}
// Handle assignment_expression (x = ...)
if self.semantics.is_assignment(kind) {
let left = node.child_by_field_name("left");
let right = node.child_by_field_name("right");
let name = left
.filter(|n| self.semantics.is_identifier(n.kind()) || n.kind() == "identifier")
.and_then(|n| n.utf8_text(self.source).ok())
.map(String::from);
if let Some(value) = right {
let is_tainted = self.is_expression_tainted(value);
let is_sanitized = self.is_sanitizer_call(value);
let source_desc = if is_tainted {
Some(self.describe_taint_source(value))
} else {
None
};
return (name, is_tainted, is_sanitized, source_desc);
}
return (name, false, false, None);
}
// Handle let_declaration (Rust: let x = ...)
if kind == "let_declaration" {
let pattern = node.child_by_field_name("pattern");
let name = pattern
.and_then(|n| n.utf8_text(self.source).ok())
.map(|s| s.trim_start_matches("mut ").trim().to_string());
if let Some(value) = node.child_by_field_name("value") {
let is_tainted = self.is_expression_tainted(value);
let is_sanitized = self.is_sanitizer_call(value);
let source_desc = if is_tainted {
Some(self.describe_taint_source(value))
} else {
None
};
return (name, is_tainted, is_sanitized, source_desc);
}
return (name, false, false, None);
}
// Handle short_var_declaration (Go: x := ...)
if kind == "short_var_declaration" {
let left = node.child_by_field_name("left");
let right = node.child_by_field_name("right");
let name = left
.and_then(|n| {
if n.kind() == "expression_list" {
n.named_child(0)
} else {
Some(n)
}
})
.and_then(|n| n.utf8_text(self.source).ok())
.map(String::from);
let value = right.and_then(|n| {
if n.kind() == "expression_list" {
n.named_child(0)
} else {
Some(n)
}
});
if let Some(value) = value {
let is_tainted = self.is_expression_tainted(value);
let is_sanitized = self.is_sanitizer_call(value);
let source_desc = if is_tainted {
Some(self.describe_taint_source(value))
} else {
None
};
return (name, is_tainted, is_sanitized, source_desc);
}
return (name, false, false, None);
}
// Handle variable_declaration children
if kind == "variable_declaration" || kind == "lexical_declaration" {
// Find the declarator child
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
if child.kind() == "variable_declarator" {
return self.analyze_assignment_node(child);
}
}
}
(None, false, false, None)
}
/// Check if an expression is tainted
fn is_expression_tainted(&self, node: Node<'_>) -> bool {
let kind = node.kind();
// Identifier - check if variable is tainted
if (self.semantics.is_identifier(kind) || kind == "identifier")
&& let Ok(name) = node.utf8_text(self.source)
{
return self.current_state.is_tainted(name);
}
// Member access - check if it's a taint source
if self.is_member_access(kind)
&& let Ok(text) = node.utf8_text(self.source)
{
if self.config.is_source_member(text) {
return true;
}
// Also check if the base object is tainted
if let Some(obj) = node.child_by_field_name("object") {
return self.is_expression_tainted(obj);
}
}
// Function/method call
if self.semantics.is_call(kind) {
return self.is_call_tainted(node);
}
// Binary expression - tainted if any operand is tainted
if self.is_binary_expression(kind) {
let left = node.child_by_field_name("left");
let right = node.child_by_field_name("right");
let left_tainted = left.map(|n| self.is_expression_tainted(n)).unwrap_or(false);
let right_tainted = right
.map(|n| self.is_expression_tainted(n))
.unwrap_or(false);
return left_tainted || right_tainted;
}
// Template literal - check interpolations
if kind == "template_string" || kind == "template_literal" {
return self.is_template_tainted(node);
}
// Parenthesized expression - unwrap
if kind == "parenthesized_expression"
&& let Some(inner) = node.named_child(0)
{
return self.is_expression_tainted(inner);
}
// Await expression - check inner
if kind == "await_expression"
&& let Some(inner) = node.named_child(0)
{
return self.is_expression_tainted(inner);
}
// Array/object - check if any element is tainted
if kind == "array" || kind == "array_expression" || kind == "object" {
let mut cursor = node.walk();
for child in node.named_children(&mut cursor) {
if self.is_expression_tainted(child) {
return true;
}
}
}
false
}
/// Check if a call expression produces tainted output
fn is_call_tainted(&self, node: Node<'_>) -> bool {
let func_node = node
.child_by_field_name("function")
.or_else(|| node.child(0));
if let Some(func) = func_node {
let func_text = func.utf8_text(self.source).unwrap_or("");
// Check if it's a known source function
if self.config.is_source_function(func_text) {
return true;
}
// Check if it's a sanitizer (blocks taint)
if self.config.is_sanitizer(func_text) {
return false;
}
// Check if it's a method call on a tainted receiver
if self.is_member_access(func.kind())
&& let Some(obj) = func.child_by_field_name("object")
&& self.is_expression_tainted(obj)
{
// Check if method propagates taint
if let Some(method) = func.child_by_field_name("property") {
let method_name = method.utf8_text(self.source).unwrap_or("");
if self.is_taint_propagating_method(method_name) {
return true;
}
}
}
// Check if any argument is tainted and the function propagates taint
if let Some(args) = node.child_by_field_name("arguments") {
let mut cursor = args.walk();
for arg in args.named_children(&mut cursor) {
if self.is_expression_tainted(arg) {
// Check if function is known to propagate taint from args
if self.is_taint_propagating_function(func_text) {
return true;
}
}
}
}
}
false
}
/// Check if a template literal contains tainted interpolations
fn is_template_tainted(&self, node: Node<'_>) -> bool {
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
if child.kind() == "template_substitution"
&& let Some(expr) = child.named_child(0)
&& self.is_expression_tainted(expr)
{
return true;
}
}
false
}
/// Check if a call is to a sanitizer function
fn is_sanitizer_call(&self, node: Node<'_>) -> bool {
if !self.semantics.is_call(node.kind()) {
return false;
}
let func_node = node
.child_by_field_name("function")
.or_else(|| node.child(0));
if let Some(func) = func_node {
let func_text = func.utf8_text(self.source).unwrap_or("");
return self.config.is_sanitizer(func_text);
}
false
}
/// Check if a method name propagates taint
fn is_taint_propagating_method(&self, method: &str) -> bool {
let propagating = [
"concat",
"join",
"slice",
"substring",
"substr",
"trim",
"toLowerCase",
"toUpperCase",
"split",
"replace",
"toString",
"valueOf",
"format",
"append",
"push_str",
"to_string",
"to_str",
];
propagating
.iter()
.any(|m| method.eq_ignore_ascii_case(m) || method.contains(m))
}
/// Check if a function propagates taint from its arguments
fn is_taint_propagating_function(&self, func: &str) -> bool {
let propagating = [
"String",
"toString",
"format",
"sprintf",
"printf",
"fmt.Sprintf",
"fmt.Printf",
"String.format",
"concat",
"join",
];
propagating.iter().any(|f| func.contains(f))
}
/// Analyze a return statement
fn analyze_return(&mut self, node: Node<'_>) {
let value = node
.child_by_field_name("value")
.or_else(|| node.named_child(0));
if let Some(val) = value
&& self.is_expression_tainted(val)
{
// Collect all tainted variables in the return expression
self.collect_tainted_vars_in_expr(val, &mut self.return_tainted.clone());
}
}
/// Collect all tainted variable names in an expression
fn collect_tainted_vars_in_expr(&self, node: Node<'_>, result: &mut HashSet<String>) {
let kind = node.kind();
if (self.semantics.is_identifier(kind) || kind == "identifier")
&& let Ok(name) = node.utf8_text(self.source)
&& self.current_state.is_tainted(name)
{
result.insert(name.to_string());
}
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
self.collect_tainted_vars_in_expr(child, result);
}
}
/// Analyze an if statement (branches may have different taint states)
fn analyze_if(&mut self, node: Node<'_>) {
let condition = node.child_by_field_name("condition");
let consequence = node
.child_by_field_name("consequence")
.or_else(|| node.child_by_field_name("body"));
let alternative = node.child_by_field_name("alternative");
// Analyze condition (might have side effects)
if let Some(cond) = condition {
self.analyze_statement(cond);
}
let state_after_cond = self.current_state.clone_state();
// Analyze then branch
if let Some(then_branch) = consequence {
self.current_state = state_after_cond.clone();
self.analyze_statement(then_branch);
}
let state_after_then = self.current_state.clone_state();
// Analyze else branch (if present)
let state_after_else = if let Some(else_branch) = alternative {
self.current_state = state_after_cond.clone();
self.analyze_statement(else_branch);
self.current_state.clone_state()
} else {
state_after_cond
};
// Merge states from both branches
self.current_state = state_after_then;
self.current_state.merge(&state_after_else);
}
/// Analyze a loop (conservative: assume loop body can execute 0+ times)
fn analyze_loop(&mut self, node: Node<'_>) {
let body = node.child_by_field_name("body");
let state_before = self.current_state.clone_state();
// Analyze loop body
if let Some(body_node) = body {
self.analyze_statement(body_node);
}
// Merge with pre-loop state (loop might not execute)
self.current_state.merge(&state_before);
}
/// Analyze a standalone call expression for side effects
fn analyze_call_expression(&mut self, _node: Node<'_>) {
// For now, just check if any arguments become tainted
// More sophisticated analysis could track object mutations
}
/// Describe the source of taint for an expression
fn describe_taint_source(&self, node: Node<'_>) -> String {
let kind = node.kind();
if (self.semantics.is_identifier(kind) || kind == "identifier")
&& let Ok(name) = node.utf8_text(self.source)
{
return format!("variable '{}'", name);
}
if self.is_member_access(kind)
&& let Ok(text) = node.utf8_text(self.source)
{
return format!("member access '{}'", text);
}
if self.semantics.is_call(kind)
&& let Some(func) = node
.child_by_field_name("function")
.or_else(|| node.child(0))
&& let Ok(text) = func.utf8_text(self.source)
{
return format!("call to '{}'", text);
}
"unknown source".to_string()
}
// =========================================================================
// Helper methods for node kind checking
// =========================================================================
fn is_variable_declaration(&self, kind: &str) -> bool {
self.semantics.variable_declaration_kinds.contains(&kind)
|| kind == "variable_declarator"
|| kind == "lexical_declaration"
}
fn is_if_statement(&self, kind: &str) -> bool {
self.semantics.if_kinds.contains(&kind)
}
fn is_block(&self, kind: &str) -> bool {
self.semantics.block_scope_kinds.contains(&kind)
}
fn is_member_access(&self, kind: &str) -> bool {
self.semantics.member_access_kinds.contains(&kind) || kind == "member_expression"
}
fn is_binary_expression(&self, kind: &str) -> bool {
self.semantics.binary_expression_kinds.contains(&kind) || kind == "binary_expression"
}
}
/// Analyze taint flow within all functions in a parsed file
///
/// # Arguments
/// * `parsed` - The parsed file
/// * `language` - The programming language
/// * `config` - Taint configuration
/// * `initial_taint` - Variables that should be considered tainted at function entry
///
/// # Returns
/// A map from function name to its taint analysis result
pub fn analyze_function_bodies(
parsed: &ParsedFile,
language: Language,
config: &TaintConfig,
initial_taint: Option<HashSet<String>>,
) -> HashMap<String, FunctionBodyTaintResult> {
let semantics = LanguageSemantics::for_language(language);
let source = parsed.content.as_bytes();
let mut results = HashMap::new();
// Walk the tree to find all function definitions
let root = parsed.tree.root_node();
let mut cursor = root.walk();
fn find_functions<'a>(
node: Node<'a>,
cursor: &mut tree_sitter::TreeCursor<'a>,
semantics: &'static LanguageSemantics,
source: &'a [u8],
config: &TaintConfig,
initial_taint: &Option<HashSet<String>>,
results: &mut HashMap<String, FunctionBodyTaintResult>,
) {
if semantics.is_function_def(node.kind()) {
// Extract parameters as initially tainted
let mut params_tainted = initial_taint.clone().unwrap_or_default();
// Add function parameters to tainted set
if let Some(params) = node.child_by_field_name("parameters") {
let mut param_cursor = params.walk();
for param in params.named_children(&mut param_cursor) {
if let Some(name) = extract_param_name(param, source) {
params_tainted.insert(name);
}
}
}
let analyzer = FunctionBodyTaintAnalyzer::new(config, semantics, source);
let result = analyzer.analyze_function(node, params_tainted);
results.insert(result.function_name.clone(), result);
}
// Recurse into children
if cursor.goto_first_child() {
loop {
find_functions(
cursor.node(),
cursor,
semantics,
source,
config,
initial_taint,
results,
);
if !cursor.goto_next_sibling() {
break;
}
}
cursor.goto_parent();
}
}
find_functions(
root,
&mut cursor,
semantics,
source,
config,
&initial_taint,
&mut results,
);
results
}
/// Helper to extract parameter name from various parameter node types
fn extract_param_name(param: Node<'_>, source: &[u8]) -> Option<String> {
match param.kind() {
"identifier" => param.utf8_text(source).ok().map(String::from),
"formal_parameter" | "required_parameter" | "parameter" => param
.child_by_field_name("name")
.or_else(|| param.child_by_field_name("pattern"))
.or_else(|| param.named_child(0))
.and_then(|n| n.utf8_text(source).ok())
.map(|s| s.trim_start_matches("mut ").trim().to_string()),
"assignment_pattern" | "default_parameter" => param
.child_by_field_name("left")
.and_then(|n| n.utf8_text(source).ok())
.map(String::from),
"rest_pattern" | "rest_element" => param
.named_child(0)
.and_then(|n| n.utf8_text(source).ok())
.map(String::from),
_ => param.utf8_text(source).ok().map(String::from),
}
}
/// Integrate function body taint results with the main TaintResult
impl TaintResult {
/// Merge results from function body analysis
pub fn merge_function_body_results(
&mut self,
body_results: &HashMap<String, FunctionBodyTaintResult>,
) {
for result in body_results.values() {
// Add all tainted variables from exit state
self.tainted_vars
.extend(result.exit_state.tainted.iter().cloned());
// Track taint sources
for var in result.taint_sources.keys() {
if !self.tainted_vars.contains(var) {
self.tainted_vars.insert(var.clone());
}
}
}
}
/// Create a TaintResult from function body analysis
pub fn from_function_body_results(
body_results: HashMap<String, FunctionBodyTaintResult>,
) -> Self {
let mut result = TaintResult::default();
result.merge_function_body_results(&body_results);
result
}
}
/// Result of taint analysis
#[derive(Debug, Default)]
pub struct TaintResult {
/// Set of variable names that are tainted
pub tainted_vars: HashSet<String>,
/// Map of variable name to the block ID where it was sanitized
/// Used for path-sensitive analysis
pub sanitization_points: HashMap<String, Vec<usize>>,
/// Variables tainted from cross-file sources
pub cross_file_sources: HashSet<String>,
/// File this result is for (if single-file analysis)
pub file: Option<PathBuf>,
}
impl TaintResult {
/// Check if a variable is tainted
pub fn is_tainted(&self, var_name: &str) -> bool {
self.tainted_vars.contains(var_name)
}
/// Check if a variable is tainted from a cross-file source
pub fn is_tainted_from_cross_file(&self, var_name: &str) -> bool {
self.cross_file_sources.contains(var_name)
}
/// Check if any of the given variables is tainted
pub fn any_tainted(&self, var_names: &[&str]) -> bool {
var_names
.iter()
.any(|name| self.tainted_vars.contains(*name))
}
/// Get count of tainted variables
pub fn tainted_count(&self) -> usize {
self.tainted_vars.len()
}
/// Get count of variables tainted from cross-file sources
pub fn cross_file_tainted_count(&self) -> usize {
self.cross_file_sources.len()
}
/// Get all variables tainted from cross-file sources
pub fn cross_file_tainted_vars(&self) -> &HashSet<String> {
&self.cross_file_sources
}
/// Get the taint level of a variable at a specific program point
///
/// Uses the CFG to determine if sanitization is guaranteed on all paths.
pub fn taint_level_at(&self, var_name: &str, node_id: usize, cfg: &CFG) -> TaintLevel {
// If the variable is not in the tainted set, it's clean
if !self.tainted_vars.contains(var_name) {
return TaintLevel::Clean;
}
// Check if there are sanitization points for this variable
let sanitization_blocks = match self.sanitization_points.get(var_name) {
Some(blocks) if !blocks.is_empty() => blocks,
_ => {
// No sanitization - fully tainted
return TaintLevel::Full;
}
};
// Get the block containing the node
let target_block = match cfg.block_of(node_id) {
Some(b) => b,
None => return TaintLevel::Full,
};
// Check if ALL paths to target_block go through at least one sanitization point
let mut all_paths_sanitized = true;
let mut some_paths_sanitized = false;
for &sanitize_block in sanitization_blocks {
if cfg.all_paths_through(target_block, sanitize_block) {
some_paths_sanitized = true;
} else if cfg.has_path_bypassing(target_block, sanitize_block) {
// Can reach target without going through this sanitizer
all_paths_sanitized = false;
}
}
if all_paths_sanitized && some_paths_sanitized {
TaintLevel::Clean
} else if some_paths_sanitized {
TaintLevel::Partial
} else {
TaintLevel::Full
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::flow::symbol_table::SymbolTable;
use rma_common::Language;
use rma_parser::ParserEngine;
use std::path::Path;
fn parse_js(code: &str) -> rma_parser::ParsedFile {
let config = rma_common::RmaConfig::default();
let parser = ParserEngine::new(config);
parser
.parse_file(Path::new("test.js"), code)
.expect("parse failed")
}
#[test]
fn test_parameter_taint() {
let code = r#"
function handler(userInput) {
const data = userInput;
}
"#;
let parsed = parse_js(code);
let symbols = SymbolTable::build(&parsed, Language::JavaScript);
let config = TaintConfig::for_language(Language::JavaScript);
let result = TaintAnalyzer::analyze(&symbols, &config);
// userInput is a parameter, should be tainted
assert!(result.is_tainted("userInput"));
// data is assigned from userInput, should propagate
assert!(result.is_tainted("data"));
}
#[test]
fn test_source_taint() {
let code = r#"
const query = req.query;
const body = req.body;
const safe = "literal";
"#;
let parsed = parse_js(code);
let symbols = SymbolTable::build(&parsed, Language::JavaScript);
let config = TaintConfig::for_language(Language::JavaScript);
let result = TaintAnalyzer::analyze(&symbols, &config);
assert!(result.is_tainted("query"));
assert!(result.is_tainted("body"));
assert!(!result.is_tainted("safe"));
}
#[test]
fn test_sanitizer_stops_taint() {
let code = r#"
function handler(userInput) {
const safe = encodeURIComponent(userInput);
const sanitized = DOMPurify.sanitize(userInput);
}
"#;
let parsed = parse_js(code);
let symbols = SymbolTable::build(&parsed, Language::JavaScript);
let config = TaintConfig::for_language(Language::JavaScript);
let result = TaintAnalyzer::analyze(&symbols, &config);
// userInput is tainted (parameter)
assert!(result.is_tainted("userInput"));
// But safe and sanitized should NOT be tainted (sanitizer applied)
assert!(!result.is_tainted("safe"));
assert!(!result.is_tainted("sanitized"));
}
#[test]
fn test_taint_propagation_chain() {
let code = r#"
function handler(userInput) {
const a = userInput;
const b = a;
const c = b;
}
"#;
let parsed = parse_js(code);
let symbols = SymbolTable::build(&parsed, Language::JavaScript);
let config = TaintConfig::for_language(Language::JavaScript);
let result = TaintAnalyzer::analyze(&symbols, &config);
assert!(result.is_tainted("userInput"));
assert!(result.is_tainted("a"));
assert!(result.is_tainted("b"));
assert!(result.is_tainted("c"));
}
#[test]
fn test_literal_not_tainted() {
let code = r#"
const safe1 = "hello";
const safe2 = 42;
const safe3 = true;
"#;
let parsed = parse_js(code);
let symbols = SymbolTable::build(&parsed, Language::JavaScript);
let config = TaintConfig::for_language(Language::JavaScript);
let result = TaintAnalyzer::analyze(&symbols, &config);
assert!(!result.is_tainted("safe1"));
assert!(!result.is_tainted("safe2"));
assert!(!result.is_tainted("safe3"));
}
// =========================================================================
// String Concatenation Taint Tracking Tests
// =========================================================================
#[test]
fn test_string_concat_binary_plus() {
// Test: "SELECT " + userInput should be tainted
let code = r#"
function handler(userInput) {
const query = "SELECT * FROM users WHERE id = " + userInput;
}
"#;
let parsed = parse_js(code);
let symbols = SymbolTable::build(&parsed, Language::JavaScript);
let config = TaintConfig::for_language(Language::JavaScript);
let result = TaintAnalyzer::analyze(&symbols, &config);
// userInput is a parameter, should be tainted
assert!(
result.is_tainted("userInput"),
"userInput should be tainted as a parameter"
);
// query is a concatenation with tainted variable, should be tainted
assert!(
result.is_tainted("query"),
"query should be tainted due to string concatenation with userInput"
);
}
#[test]
fn test_string_concat_chain() {
// Test: chained concatenation preserves taint
let code = r#"
function handler(userInput) {
const a = "prefix" + userInput;
const b = a + " suffix";
const c = "SELECT " + b + " FROM table";
}
"#;
let parsed = parse_js(code);
let symbols = SymbolTable::build(&parsed, Language::JavaScript);
let config = TaintConfig::for_language(Language::JavaScript);
let result = TaintAnalyzer::analyze(&symbols, &config);
assert!(result.is_tainted("userInput"));
assert!(result.is_tainted("a"), "a should be tainted");
assert!(result.is_tainted("b"), "b should be tainted via chain");
assert!(result.is_tainted("c"), "c should be tainted via chain");
}
#[test]
fn test_template_literal_taint() {
// Test: template literals with interpolation should be tainted
let code = r#"
function handler(userInput) {
const query = `SELECT * FROM users WHERE id = ${userInput}`;
}
"#;
let parsed = parse_js(code);
let symbols = SymbolTable::build(&parsed, Language::JavaScript);
let config = TaintConfig::for_language(Language::JavaScript);
let result = TaintAnalyzer::analyze(&symbols, &config);
assert!(result.is_tainted("userInput"));
assert!(
result.is_tainted("query"),
"template literal with tainted interpolation should be tainted"
);
}
#[test]
fn test_template_literal_multiple_interpolations() {
// Test: template literal with multiple interpolations
let code = r#"
function handler(name, id) {
const safe = "safe";
const query = `SELECT ${safe} FROM users WHERE name = '${name}' AND id = ${id}`;
}
"#;
let parsed = parse_js(code);
let symbols = SymbolTable::build(&parsed, Language::JavaScript);
let config = TaintConfig::for_language(Language::JavaScript);
let result = TaintAnalyzer::analyze(&symbols, &config);
// name and id are parameters, should be tainted
assert!(result.is_tainted("name"));
assert!(result.is_tainted("id"));
// safe is a literal, not tainted
assert!(!result.is_tainted("safe"));
// query has tainted interpolations
assert!(
result.is_tainted("query"),
"template with tainted interpolations should be tainted"
);
}
#[test]
fn test_concat_with_source_member() {
// Test: concatenation with req.query should be tainted
let code = r#"
const id = req.query.id;
const query = "SELECT * FROM users WHERE id = " + id;
"#;
let parsed = parse_js(code);
let symbols = SymbolTable::build(&parsed, Language::JavaScript);
let config = TaintConfig::for_language(Language::JavaScript);
let result = TaintAnalyzer::analyze(&symbols, &config);
assert!(
result.is_tainted("id"),
"id from req.query should be tainted"
);
assert!(
result.is_tainted("query"),
"concatenation with tainted id should be tainted"
);
}
#[test]
fn test_concat_method_call() {
// Test: str.concat() should propagate taint
let code = r#"
function handler(userInput) {
const prefix = "SELECT ";
const query = prefix.concat(userInput);
}
"#;
let parsed = parse_js(code);
let symbols = SymbolTable::build(&parsed, Language::JavaScript);
let config = TaintConfig::for_language(Language::JavaScript);
let result = TaintAnalyzer::analyze(&symbols, &config);
assert!(result.is_tainted("userInput"));
assert!(
result.is_tainted("query"),
"concat() with tainted argument should produce tainted result"
);
}
#[test]
fn test_join_method_taint() {
// Test: arr.join() with tainted variable in join call
// Note: Array literal taint tracking is a more advanced feature.
// For now, we test that join() propagates taint from its receiver.
let code = r#"
function handler(userInput) {
const taintedParts = userInput.split(",");
const query = taintedParts.join(" ");
}
"#;
let parsed = parse_js(code);
let symbols = SymbolTable::build(&parsed, Language::JavaScript);
let config = TaintConfig::for_language(Language::JavaScript);
let result = TaintAnalyzer::analyze(&symbols, &config);
assert!(result.is_tainted("userInput"));
// taintedParts comes from splitting a tainted string
assert!(
result.is_tainted("taintedParts"),
"split result should be tainted"
);
// join on a tainted array should produce tainted result
assert!(
result.is_tainted("query"),
"join on tainted array should produce tainted result"
);
}
#[test]
fn test_safe_concatenation() {
// Test: concatenation of only safe literals should not be tainted
let code = r#"
const safe1 = "hello";
const safe2 = "world";
const result = safe1 + " " + safe2;
"#;
let parsed = parse_js(code);
let symbols = SymbolTable::build(&parsed, Language::JavaScript);
let config = TaintConfig::for_language(Language::JavaScript);
let result = TaintAnalyzer::analyze(&symbols, &config);
assert!(!result.is_tainted("safe1"));
assert!(!result.is_tainted("safe2"));
assert!(
!result.is_tainted("result"),
"concatenation of only safe literals should not be tainted"
);
}
#[test]
fn test_sanitized_then_concat() {
// Test: sanitized value used in concatenation should not taint result
let code = r#"
function handler(userInput) {
const safe = encodeURIComponent(userInput);
const query = "url=" + safe;
}
"#;
let parsed = parse_js(code);
let symbols = SymbolTable::build(&parsed, Language::JavaScript);
let config = TaintConfig::for_language(Language::JavaScript);
let result = TaintAnalyzer::analyze(&symbols, &config);
assert!(result.is_tainted("userInput"));
// safe is sanitized, should not be tainted
assert!(
!result.is_tainted("safe"),
"sanitized value should not be tainted"
);
// query uses sanitized value, should not be tainted
assert!(
!result.is_tainted("query"),
"concatenation with sanitized value should not be tainted"
);
}
#[test]
fn test_sql_injection_through_concat() {
// Complete SQL injection test case
let code = r#"
const input = req.query.id;
const query = "SELECT * FROM users WHERE id = " + input;
db.query(query);
"#;
let parsed = parse_js(code);
let symbols = SymbolTable::build(&parsed, Language::JavaScript);
let config = TaintConfig::for_language(Language::JavaScript);
let result = TaintAnalyzer::analyze(&symbols, &config);
assert!(
result.is_tainted("input"),
"input from req.query should be tainted"
);
assert!(
result.is_tainted("query"),
"SQL query with tainted input should be tainted"
);
// This demonstrates the taint flow that would trigger SQL injection detection
}
#[test]
fn test_complex_expression_taint() {
// Test: complex expression with method calls
let code = r#"
function handler(userInput) {
const clean = userInput.trim();
const upper = clean.toUpperCase();
const query = "SELECT " + upper;
}
"#;
let parsed = parse_js(code);
let symbols = SymbolTable::build(&parsed, Language::JavaScript);
let config = TaintConfig::for_language(Language::JavaScript);
let result = TaintAnalyzer::analyze(&symbols, &config);
assert!(result.is_tainted("userInput"));
// trim() and toUpperCase() don't sanitize
assert!(result.is_tainted("clean"), "trim() should propagate taint");
assert!(
result.is_tainted("upper"),
"toUpperCase() should propagate taint"
);
assert!(
result.is_tainted("query"),
"concatenation with tainted value should be tainted"
);
}
// =========================================================================
// Function Body Taint Analyzer Tests
// =========================================================================
#[test]
fn test_function_body_assignment_propagation() {
let code = r#"
function handler(userInput) {
const a = userInput;
const b = a;
const c = "safe";
return b;
}
"#;
let parsed = parse_js(code);
let config = TaintConfig::for_language(Language::JavaScript);
let results = analyze_function_bodies(&parsed, Language::JavaScript, &config, None);
assert!(!results.is_empty(), "Should find functions");
let handler_result = results
.get("handler")
.expect("Should find handler function");
// Parameters should be tainted
assert!(handler_result.tainted_params.contains("userInput"));
// Variables assigned from tainted sources should be tainted at exit
assert!(handler_result.exit_state.is_tainted("userInput"));
assert!(handler_result.exit_state.is_tainted("a"));
assert!(handler_result.exit_state.is_tainted("b"));
// Safe literal should not be tainted
assert!(!handler_result.exit_state.is_tainted("c"));
}
#[test]
fn test_function_body_binary_expression_taint() {
let code = r#"
function buildQuery(userInput) {
const query = "SELECT * FROM users WHERE id = " + userInput;
return query;
}
"#;
let parsed = parse_js(code);
let config = TaintConfig::for_language(Language::JavaScript);
let results = analyze_function_bodies(&parsed, Language::JavaScript, &config, None);
let func_result = results.get("buildQuery").expect("Should find buildQuery");
// query should be tainted due to concatenation with userInput
assert!(
func_result.exit_state.is_tainted("query"),
"query should be tainted from concatenation"
);
}
#[test]
fn test_function_body_sanitizer_blocks_taint() {
let code = r#"
function sanitize(userInput) {
const safe = encodeURIComponent(userInput);
const output = "url=" + safe;
return output;
}
"#;
let parsed = parse_js(code);
let config = TaintConfig::for_language(Language::JavaScript);
let results = analyze_function_bodies(&parsed, Language::JavaScript, &config, None);
let func_result = results
.get("sanitize")
.expect("Should find sanitize function");
// userInput is tainted
assert!(func_result.exit_state.is_tainted("userInput"));
// safe should NOT be tainted (sanitizer applied)
assert!(
!func_result.exit_state.is_tainted("safe"),
"sanitized value should not be tainted"
);
// output should also not be tainted (uses sanitized value)
assert!(
!func_result.exit_state.is_tainted("output"),
"concatenation with sanitized value should not be tainted"
);
}
#[test]
fn test_function_body_method_call_propagation() {
let code = r#"
function process(input) {
const trimmed = input.trim();
const upper = trimmed.toUpperCase();
const sliced = upper.slice(0, 10);
return sliced;
}
"#;
let parsed = parse_js(code);
let config = TaintConfig::for_language(Language::JavaScript);
let results = analyze_function_bodies(&parsed, Language::JavaScript, &config, None);
let func_result = results
.get("process")
.expect("Should find process function");
// All should be tainted - string methods propagate taint
assert!(func_result.exit_state.is_tainted("input"));
assert!(
func_result.exit_state.is_tainted("trimmed"),
"trim() should propagate taint"
);
assert!(
func_result.exit_state.is_tainted("upper"),
"toUpperCase() should propagate taint"
);
assert!(
func_result.exit_state.is_tainted("sliced"),
"slice() should propagate taint"
);
}
#[test]
fn test_function_body_source_member_taint() {
let code = r#"
function getQuery() {
const id = req.query.id;
const name = req.body.name;
const safe = "literal";
return id;
}
"#;
let parsed = parse_js(code);
let config = TaintConfig::for_language(Language::JavaScript);
let results = analyze_function_bodies(&parsed, Language::JavaScript, &config, None);
let func_result = results
.get("getQuery")
.expect("Should find getQuery function");
// id and name from req.query/body should be tainted
assert!(
func_result.exit_state.is_tainted("id"),
"req.query.id should be tainted"
);
assert!(
func_result.exit_state.is_tainted("name"),
"req.body.name should be tainted"
);
// safe literal should not be tainted
assert!(!func_result.exit_state.is_tainted("safe"));
}
#[test]
fn test_taint_state_operations() {
let mut state = TaintState::new();
// Initially empty
assert!(!state.is_tainted("x"));
// Mark as tainted
state.mark_tainted("x".to_string());
assert!(state.is_tainted("x"));
// Mark as sanitized
state.mark_sanitized("x".to_string());
assert!(!state.is_tainted("x"));
// Mark another variable
state.mark_tainted("y".to_string());
assert!(state.is_tainted("y"));
// Merge states
let mut state2 = TaintState::new();
state2.mark_tainted("z".to_string());
state.merge(&state2);
assert!(state.is_tainted("y"));
assert!(state.is_tainted("z"));
}
#[test]
fn test_function_body_result_integration() {
let code = r#"
function handler(userInput) {
const data = userInput;
return data;
}
"#;
let parsed = parse_js(code);
let config = TaintConfig::for_language(Language::JavaScript);
let body_results = analyze_function_bodies(&parsed, Language::JavaScript, &config, None);
// Create TaintResult from function body results
let result = TaintResult::from_function_body_results(body_results);
assert!(result.is_tainted("userInput"));
assert!(result.is_tainted("data"));
}
}