codeveto 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. codeveto/__init__.py +3 -0
  2. codeveto/__main__.py +8 -0
  3. codeveto/ai/__init__.py +19 -0
  4. codeveto/ai/harness.py +303 -0
  5. codeveto/ai/packets.py +855 -0
  6. codeveto/ai/policy.py +222 -0
  7. codeveto/ai/prompt.py +101 -0
  8. codeveto/ai/providers/__init__.py +178 -0
  9. codeveto/ai/providers/claude.py +247 -0
  10. codeveto/ai/providers/openai_compat.py +246 -0
  11. codeveto/ai/runner.py +293 -0
  12. codeveto/ai/verify.py +324 -0
  13. codeveto/anchor.py +211 -0
  14. codeveto/cli.py +247 -0
  15. codeveto/cli_explain.py +49 -0
  16. codeveto/cli_hook.py +31 -0
  17. codeveto/cli_init.py +254 -0
  18. codeveto/cli_mcp.py +29 -0
  19. codeveto/cli_packets.py +35 -0
  20. codeveto/cli_publish.py +29 -0
  21. codeveto/cli_review.py +362 -0
  22. codeveto/cli_rules.py +78 -0
  23. codeveto/cli_verify.py +47 -0
  24. codeveto/config.py +1229 -0
  25. codeveto/data/README.md +16 -0
  26. codeveto/data/ai-wire.schema.json +53 -0
  27. codeveto/data/prompts/system.md +57 -0
  28. codeveto/data/report-v1.schema.json +268 -0
  29. codeveto/data/templates/forgejo-codeveto.yml +104 -0
  30. codeveto/data/templates/github-codeveto.yml +18 -0
  31. codeveto/embedded.py +311 -0
  32. codeveto/engine.py +1570 -0
  33. codeveto/git.py +1549 -0
  34. codeveto/globs.py +348 -0
  35. codeveto/integrations/__init__.py +1 -0
  36. codeveto/integrations/hooks.py +327 -0
  37. codeveto/integrations/mcp.py +770 -0
  38. codeveto/integrations/mcp_ai.py +77 -0
  39. codeveto/integrations/prepush.py +222 -0
  40. codeveto/jsonsafe.py +60 -0
  41. codeveto/languages.py +539 -0
  42. codeveto/lexers.py +2560 -0
  43. codeveto/model.py +372 -0
  44. codeveto/publish/__init__.py +28 -0
  45. codeveto/publish/action.py +330 -0
  46. codeveto/publish/common.py +84 -0
  47. codeveto/publish/diff.py +208 -0
  48. codeveto/publish/event.py +241 -0
  49. codeveto/publish/forgejo.py +184 -0
  50. codeveto/publish/github.py +380 -0
  51. codeveto/publish/http.py +263 -0
  52. codeveto/publish/pull.py +218 -0
  53. codeveto/publish/untrusted.py +110 -0
  54. codeveto/py.typed +0 -0
  55. codeveto/redact.py +113 -0
  56. codeveto/render/__init__.py +64 -0
  57. codeveto/render/agent.py +43 -0
  58. codeveto/render/github.py +101 -0
  59. codeveto/render/json.py +23 -0
  60. codeveto/render/markdown.py +208 -0
  61. codeveto/render/safe.py +249 -0
  62. codeveto/render/sarif.py +217 -0
  63. codeveto/render/text.py +210 -0
  64. codeveto/report.py +252 -0
  65. codeveto/rules/__init__.py +84 -0
  66. codeveto/rules/agent.py +2972 -0
  67. codeveto/rules/base.py +1026 -0
  68. codeveto/rules/ci.py +1708 -0
  69. codeveto/rules/config.py +493 -0
  70. codeveto/rules/deps.py +1693 -0
  71. codeveto/rules/docker.py +479 -0
  72. codeveto/rules/examples/__init__.py +148 -0
  73. codeveto/rules/examples/agent.py +839 -0
  74. codeveto/rules/examples/ci.py +1046 -0
  75. codeveto/rules/examples/config.py +191 -0
  76. codeveto/rules/examples/deps.py +369 -0
  77. codeveto/rules/examples/docker.py +157 -0
  78. codeveto/rules/examples/go.py +241 -0
  79. codeveto/rules/examples/hygiene.py +466 -0
  80. codeveto/rules/examples/js.py +462 -0
  81. codeveto/rules/examples/python.py +595 -0
  82. codeveto/rules/examples/rust.py +268 -0
  83. codeveto/rules/examples/secrets.py +561 -0
  84. codeveto/rules/examples/security.py +608 -0
  85. codeveto/rules/examples/shell.py +174 -0
  86. codeveto/rules/examples/sql.py +194 -0
  87. codeveto/rules/examples/tests.py +497 -0
  88. codeveto/rules/go.py +328 -0
  89. codeveto/rules/hygiene.py +1094 -0
  90. codeveto/rules/js.py +768 -0
  91. codeveto/rules/python.py +1642 -0
  92. codeveto/rules/rust.py +209 -0
  93. codeveto/rules/secrets.py +1335 -0
  94. codeveto/rules/security.py +3680 -0
  95. codeveto/rules/shell.py +867 -0
  96. codeveto/rules/sql.py +629 -0
  97. codeveto/rules/tests.py +1404 -0
  98. codeveto/schema.py +384 -0
  99. codeveto/statements.py +607 -0
  100. codeveto/worktree.py +1176 -0
  101. codeveto/yamlish.py +1179 -0
  102. codeveto-0.1.0.dist-info/METADATA +253 -0
  103. codeveto-0.1.0.dist-info/RECORD +106 -0
  104. codeveto-0.1.0.dist-info/WHEEL +4 -0
  105. codeveto-0.1.0.dist-info/entry_points.txt +2 -0
  106. codeveto-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,3680 @@
1
+ """Security pack (SPEC 6.1): cross-language injection sinks and unsafe calls.
2
+
3
+ Every rule here looks at whole logical statements (``ctx.statements()``) so a
4
+ call split over several lines is seen as one, and matches code patterns on the
5
+ masked view so text inside strings and comments never counts as code. Python
6
+ calls and arguments are read from the AST where it matters for an ``error``
7
+ rule (SQL, shell, eval, deserialization, TLS, JWT, permissions); without an
8
+ AST (a syntax error) those rules fall back to the statement text and only
9
+ report the shapes they can tell without it.
10
+
11
+ Scope shared by all rules:
12
+
13
+ - Languages: Python, JavaScript/TypeScript (Vue/Svelte script blocks
14
+ included), Go, Java and Kotlin; shell only for ``world-writable`` and
15
+ ``tls-verification-disabled``. Markdown, YAML and other data files are not
16
+ read (fenced examples are documentation). Workflow ``run:`` steps and
17
+ Dockerfile ``RUN`` commands belong to the ``ci`` and ``docker`` packs.
18
+ - File classes: every class (SPEC 5.4), since a test helper, ``conftest.py``
19
+ or vendored library runs as much as source does. In ``test`` and ``docs``
20
+ files and inside in-file test regions (Go test functions) every hit is
21
+ capped at ``warning``: tests deserialize their own fixtures, build
22
+ throwaway SQL and disable TLS against local servers on purpose, and docs
23
+ show vulnerable code to explain it. Generated, vendored and minified files
24
+ keep full severity.
25
+ - A finding is reported at the first changed line of its statement at or
26
+ after the construct; its evidence names the sink and the shape (never a
27
+ variable name), so a renamed variable does not report old debt again.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import ast
33
+ import bisect
34
+ import itertools
35
+ import re
36
+ from collections.abc import Callable, Iterator
37
+ from dataclasses import dataclass
38
+
39
+ from codeveto.lexers import StringSpan
40
+ from codeveto.rules.base import FileContext, Hit, PartialCoverage, Severity, rule
41
+ from codeveto.statements import Statement
42
+
43
+ _CAPPED_CLASSES = frozenset({"test", "docs"})
44
+ """File classes whose hits are capped at ``warning`` (as are in-file test regions)."""
45
+ _PY = frozenset({"python"})
46
+ _JS = frozenset({"javascript", "typescript"})
47
+ _GO = frozenset({"go"})
48
+ _JVM = frozenset({"java", "kotlin"})
49
+ _CODE = _PY | _JS | _GO | _JVM
50
+ _SHELL = frozenset({"shell"})
51
+
52
+ _S, _I, _T = "\x01", "\x02", "\x03"
53
+ """Sentinels standing in for a literal string, an interpolated one and a tagged template."""
54
+
55
+
56
+ def _norm(text: str) -> str:
57
+ return " ".join(text.split())[:200]
58
+
59
+
60
+ # --- Changed lines, views and hits ---------------------------------------------------------------
61
+
62
+
63
+ @dataclass(slots=True)
64
+ class _View:
65
+ """One statement: masked code, text with comments blanked, top-level strings."""
66
+
67
+ stmt: Statement
68
+ code: str
69
+ text: str
70
+ strings: tuple[StringSpan, ...]
71
+
72
+
73
+ class _File:
74
+ """Per-call helpers over one ``FileContext`` (nothing survives the call)."""
75
+
76
+ def __init__(self, ctx: FileContext) -> None:
77
+ self.ctx = ctx
78
+ self.lang = ctx.language
79
+ self.source = ctx.new_text or ""
80
+ self.changed = sorted(ctx.added_lines | ctx.deletion_points)
81
+ self._strings = ctx.strings()
82
+ self._string_starts = [s.start for s in self._strings]
83
+ self._comments = ctx.comments()
84
+ self._comment_starts = [c.start for c in self._comments]
85
+ self._views: dict[int, _View] = {}
86
+ self.incomplete = False
87
+
88
+ # Changed lines.
89
+
90
+ def first_changed(self, lo: int, hi: int) -> int | None:
91
+ i = bisect.bisect_left(self.changed, lo)
92
+ if i < len(self.changed) and self.changed[i] <= hi:
93
+ return self.changed[i]
94
+ return None
95
+
96
+ def touched(self, stmt: Statement) -> bool:
97
+ return self.first_changed(stmt.start_line, stmt.end_line) is not None
98
+
99
+ def statements(self) -> Iterator[Statement]:
100
+ for stmt in self.ctx.statements():
101
+ if self.touched(stmt):
102
+ yield stmt
103
+
104
+ # Views.
105
+
106
+ def view(self, stmt: Statement) -> _View:
107
+ cached = self._views.get(stmt.start)
108
+ if cached is not None and cached.stmt is stmt:
109
+ return cached
110
+ lo, hi = stmt.start, stmt.end
111
+ text = stmt.text
112
+ k = max(bisect.bisect_right(self._comment_starts, lo) - 1, 0)
113
+ while k < len(self._comments) and self._comments[k].start < hi:
114
+ c = self._comments[k]
115
+ a, b = max(c.start, lo) - lo, min(c.end, hi) - lo
116
+ if a < b:
117
+ text = text[:a] + re.sub(r"[^\r\n]", " ", text[a:b]) + text[b:]
118
+ k += 1
119
+ top: list[StringSpan] = []
120
+ last_end = lo
121
+ i = bisect.bisect_left(self._string_starts, lo)
122
+ while i < len(self._strings) and self._strings[i].start < hi:
123
+ s = self._strings[i]
124
+ if s.start >= last_end and s.end <= hi:
125
+ top.append(s)
126
+ last_end = s.end
127
+ i += 1
128
+ view = _View(stmt, stmt.masked, text, tuple(top))
129
+ self._views[stmt.start] = view
130
+ return view
131
+
132
+ def content(self, span: StringSpan) -> str:
133
+ """A string's literal content with its interpolations blanked."""
134
+ text = self.source[span.content_start : span.content_end]
135
+ if not span.interpolations:
136
+ return text
137
+ chars = list(text)
138
+ for interp in span.interpolations:
139
+ for i in range(
140
+ max(interp.start, span.content_start), min(interp.end, span.content_end)
141
+ ):
142
+ chars[i - span.content_start] = " "
143
+ return "".join(chars)
144
+
145
+ def interp_codes(self, span: StringSpan) -> list[str]:
146
+ return [self.source[i.start : i.end] for i in span.interpolations]
147
+
148
+ # Hits.
149
+
150
+ def anchor(self, line: int, ranges: list[tuple[int, int]]) -> int | None:
151
+ """First changed line at or after ``line`` in the first range, else anywhere."""
152
+ lo, hi = ranges[0]
153
+ at = self.first_changed(line, hi)
154
+ if at is None:
155
+ at = self.first_changed(lo, line - 1)
156
+ for lo2, hi2 in ranges[1:]:
157
+ if at is not None:
158
+ break
159
+ at = self.first_changed(lo2, hi2)
160
+ return at
161
+
162
+ def hit(
163
+ self,
164
+ offset: int,
165
+ ranges: list[tuple[int, int]],
166
+ message: str,
167
+ evidence: str,
168
+ *,
169
+ weak: bool = False,
170
+ ) -> Hit | None:
171
+ line, column = self.ctx.line_index.position(offset)
172
+ at = self.anchor(line, ranges)
173
+ if at is None:
174
+ return None
175
+ col = column if at == line else None
176
+ if self.ctx.file_class in _CAPPED_CLASSES or self.ctx.in_test_region(at):
177
+ weak = True
178
+ return Hit(
179
+ at,
180
+ column=col,
181
+ message=message,
182
+ evidence=_norm(evidence),
183
+ severity=Severity.WARNING if weak else None,
184
+ )
185
+
186
+ def stmt_hit(
187
+ self, view: _View, rel: int, message: str, evidence: str, *, weak: bool = False
188
+ ) -> Hit | None:
189
+ stmt = view.stmt
190
+ return self.hit(
191
+ stmt.start + rel, [(stmt.start_line, stmt.end_line)], message, evidence, weak=weak
192
+ )
193
+
194
+
195
+ def _code_start(view: _View, index: int) -> bool:
196
+ """Does a text-view match at ``index`` start in code (not inside a string)?"""
197
+ if index >= len(view.code):
198
+ return False
199
+ c = view.code[index]
200
+ return c == view.text[index] and not c.isspace()
201
+
202
+
203
+ # --- Calls and argument shapes -------------------------------------------------------------------
204
+
205
+
206
+ def _close(code: str, i: int) -> int | None:
207
+ """Index of the bracket closing ``code[i]``, or ``None`` within the text."""
208
+ depth = 0
209
+ for j in range(i, len(code)):
210
+ c = code[j]
211
+ if c in "([{":
212
+ depth += 1
213
+ elif c in ")]}":
214
+ depth -= 1
215
+ if depth == 0:
216
+ return j
217
+ return None
218
+
219
+
220
+ def _split(code: str, lo: int, hi: int) -> list[tuple[int, int]]:
221
+ """Top-level comma-separated ranges of ``code[lo:hi]`` (empty ones dropped)."""
222
+ out: list[tuple[int, int]] = []
223
+ depth = 0
224
+ start = lo
225
+ for j in range(lo, hi):
226
+ c = code[j]
227
+ if c in "([{":
228
+ depth += 1
229
+ elif c in ")]}":
230
+ depth -= 1
231
+ elif c == "," and depth == 0:
232
+ out.append((start, j))
233
+ start = j + 1
234
+ out.append((start, hi))
235
+ return [(a, b) for a, b in out if code[a:b].strip()]
236
+
237
+
238
+ def _call_args(f: _File, view: _View, open_index: int) -> tuple[int, list[tuple[int, int]]] | None:
239
+ """``(close, args)`` of the call whose ``(`` is at ``open_index`` in the view."""
240
+ close = _close(view.code, open_index)
241
+ if close is None:
242
+ if view.stmt.truncated:
243
+ f.incomplete = True
244
+ return None
245
+ return close, _split(view.code, open_index + 1, close)
246
+
247
+
248
+ @dataclass(slots=True)
249
+ class _Expr:
250
+ rest: str
251
+ """The code with each top-level string replaced by a sentinel."""
252
+ literal: str
253
+ """Literal contents of the top-level strings, interpolations blanked."""
254
+ strings: list[StringSpan]
255
+ contexts: list[str]
256
+ """For each non-literal value, the literal text right before it (its SQL position)."""
257
+
258
+
259
+ _CONST_PATH = re.compile(
260
+ r"\A\s*(?:[A-Za-z_$][\w$]{0,63}\s*\.\s*){0,6}_{0,2}[A-Z][A-Z0-9_]{1,63}\s*\Z"
261
+ )
262
+ _NUMERIC_EXPR = re.compile(
263
+ r"\A\s*(?:\d{1,20}|(?:int|float|len|bool|Number|parseInt|parseFloat|BigInt)\s*\(.{0,300}\))\s*\Z",
264
+ re.S,
265
+ )
266
+ _PLACEHOLDER_EXPR = re.compile(
267
+ r"placeholder|[\"'`]\s{0,2}(?:\?|%s|\$\d{1,3})\s{0,2},?\s{0,2}[\"'`]", re.I
268
+ )
269
+
270
+
271
+ def _safe_interp(code: str) -> bool:
272
+ """An interpolated value that cannot inject: a constant, a number, placeholders."""
273
+ return bool(
274
+ _CONST_PATH.match(code) or _NUMERIC_EXPR.match(code) or _PLACEHOLDER_EXPR.search(code)
275
+ )
276
+
277
+
278
+ def _expr(f: _File, view: _View, a: int, b: int) -> _Expr:
279
+ """The shape of ``view.code[a:b]``."""
280
+ base = view.stmt.start
281
+ parts: list[str] = []
282
+ literal: list[str] = []
283
+ strings: list[StringSpan] = []
284
+ contexts: list[str] = []
285
+ seen = ""
286
+ pos = a
287
+ for span in view.strings:
288
+ rs, re_ = span.start - base, span.end - base
289
+ if rs < a or re_ > b:
290
+ continue
291
+ gap = view.code[pos:rs]
292
+ parts.append(gap)
293
+ if _value_names(gap):
294
+ contexts.append(_context(seen))
295
+ before = view.code[rs - 1] if rs > 0 else " "
296
+ if f.lang in _JS and span.kind == "template" and (before.isalnum() or before in "_$)]"):
297
+ parts.append(_T)
298
+ elif any(not _safe_interp(c) for c in f.interp_codes(span)):
299
+ parts.append(_I)
300
+ cursor = span.content_start
301
+ for interp in span.interpolations:
302
+ seen += f.source[cursor : interp.start]
303
+ cursor = interp.end
304
+ if not _safe_interp(f.source[interp.start : interp.end]):
305
+ contexts.append(_context(seen))
306
+ seen += f.source[cursor : span.content_end]
307
+ else:
308
+ parts.append(_S)
309
+ if not span.interpolations or parts[-1] != _I:
310
+ seen += f.content(span)
311
+ literal.append(f.content(span))
312
+ strings.append(span)
313
+ pos = re_
314
+ tail = view.code[pos:b]
315
+ parts.append(tail)
316
+ if _value_names(tail) and strings:
317
+ contexts.append(_context(seen))
318
+ return _Expr("".join(parts), " ".join(literal), strings, contexts)
319
+
320
+
321
+ _SQL_VALUE_POSITION = re.compile(
322
+ r"(?:[=<>(,'%+*/|-]|\b(?:like|ilike|in|is|between|and|or|not|where|on|by|limit|offset|"
323
+ r"values|set|then|when|else|select|having|returning|case|any|all|default|top|regexp)\b)"
324
+ r"\s{0,8}[\"'`]?[%]?\Z",
325
+ re.I,
326
+ )
327
+ _SQL_FIELD = re.compile(
328
+ r"%(?:\(\w{1,64}\))?[-#0 +]{0,4}\d{0,3}(?:\.\d{1,3})?[srvq]|\{[^{}]{0,64}\}"
329
+ )
330
+
331
+
332
+ def _structural_only(contexts: list[str]) -> bool:
333
+ """Do all values sit where SQL expects a name or a clause, none where it expects a value?
334
+
335
+ A value position follows an operator, a quote, ``(``, ``,`` or a keyword
336
+ such as ``WHERE``, ``AND``, ``LIKE``, ``LIMIT``, ``VALUES``, ``SET`` or
337
+ ``ORDER BY``. Anything else (``FROM {table}``, ``"DELETE FROM t " + where``)
338
+ is a table name or a clause the program composes from its own parts.
339
+ """
340
+ return bool(contexts) and not any(_SQL_VALUE_POSITION.search(c) for c in contexts)
341
+
342
+
343
+ def _context(seen: str) -> str:
344
+ """The last literal text before a value, without an interpolation's opening delimiter."""
345
+ return _OPEN_INTERP.sub("", seen[-84:])[-80:]
346
+
347
+
348
+ _OPEN_INTERP = re.compile(r"(?:[$#]?\{|\$)\Z")
349
+
350
+
351
+ def _format_contexts(literal: str) -> list[str]:
352
+ return [literal[: m.start()][-80:] for m in _SQL_FIELD.finditer(literal)]
353
+
354
+
355
+ _NUMBER = re.compile(r"(?<![\w$])\d[\w.]{0,40}")
356
+ _PATH = re.compile(
357
+ r"[A-Za-z_$][\w$]{0,63}(?:\s{0,4}(?:\?\.|\.|::|->)\s{0,4}[A-Za-z_$][\w$]{0,63}){0,8}"
358
+ )
359
+ _NOT_VALUES = frozenset(
360
+ {
361
+ "null",
362
+ "nil",
363
+ "None",
364
+ "True",
365
+ "False",
366
+ "true",
367
+ "false",
368
+ "undefined",
369
+ "new",
370
+ "this",
371
+ "self",
372
+ "it",
373
+ "await",
374
+ "and",
375
+ "or",
376
+ "not",
377
+ "in",
378
+ "is",
379
+ "if",
380
+ "else",
381
+ "lambda",
382
+ "for",
383
+ "typeof",
384
+ "as",
385
+ "String",
386
+ "fmt",
387
+ "format",
388
+ "formatted",
389
+ "Sprintf",
390
+ "sprintf",
391
+ "Sprint",
392
+ "join",
393
+ "str",
394
+ "strings",
395
+ "valueOf",
396
+ "trim",
397
+ "strip",
398
+ "concat",
399
+ "Join",
400
+ }
401
+ )
402
+
403
+
404
+ def _value_names(rest: str) -> list[str]:
405
+ """Paths in ``rest`` that stand for values that are not constants."""
406
+ rest = _NUMBER.sub("0", rest)
407
+ names: list[str] = []
408
+ for m in _PATH.finditer(rest):
409
+ path = m.group(0)
410
+ last = re.split(r"\s*(?:\?\.|\.|::|->)\s*", path)[-1]
411
+ if _CONST_PATH.match(path) or path in _NOT_VALUES or last in _NOT_VALUES:
412
+ continue
413
+ before = rest[: m.start()].rstrip()
414
+ if before.endswith(".") and before[:-1].rstrip()[-1:] in (_S, _I, _T, ")"):
415
+ continue # a method on a literal or a call result: "x".format(...), f().trim()
416
+ names.append(path)
417
+ return names
418
+
419
+
420
+ _SIMPLE_PATH = re.compile(
421
+ r"\A\s*[A-Za-z_$][\w$]{0,63}(?:\s{0,4}(?:\?\.|\.|->)\s{0,4}[A-Za-z_$][\w$]{0,63}){0,8}\s*\Z"
422
+ )
423
+ _FORMAT_CALL = re.compile(r"(?:\bString\.format|\bfmt\.Sprintf|\bsprintf|\bformat)\s*\(\s*\x01")
424
+ _STR_VERB = re.compile(r"%(?:\(\w{1,64}\))?[-#0 +]{0,4}\d{0,3}(?:\.\d{1,3})?[srvq]")
425
+ _BRACE_FIELD = re.compile(r"\{[\w.\[\]]{0,64}(?:![rsa])?(?::[^{}]{0,32})?\}")
426
+
427
+
428
+ def _kind(e: _Expr) -> str | None:
429
+ """How a non-literal value enters ``e``, or ``None`` when it is literal or constant."""
430
+ rest = e.rest
431
+ if _I in rest:
432
+ return "interpolation"
433
+ if not _value_names(rest):
434
+ return None
435
+ if _S in rest:
436
+ if re.search(r"\x01\s*%", rest):
437
+ return "%-formatting" if _STR_VERB.search(e.literal) else None
438
+ if re.search(r"\x01\s*\.\s*format(?:ted)?\s*\(", rest):
439
+ return (
440
+ ".format()"
441
+ if (_BRACE_FIELD.search(e.literal) or _STR_VERB.search(e.literal))
442
+ else None
443
+ )
444
+ if _FORMAT_CALL.search(rest):
445
+ return "format call" if _STR_VERB.search(e.literal) else None
446
+ if "+" in rest:
447
+ return "concatenation"
448
+ return "expression"
449
+ if _SIMPLE_PATH.match(rest):
450
+ return "variable"
451
+ return "expression"
452
+
453
+
454
+ _BUILT = frozenset({"interpolation", "concatenation", "%-formatting", ".format()", "format call"})
455
+
456
+
457
+ # --- Statement walk with simple bindings ---------------------------------------------------------
458
+
459
+
460
+ @dataclass(slots=True)
461
+ class _Piece:
462
+ stmt: Statement
463
+ start: int
464
+ end: int
465
+
466
+
467
+ _C_ASSIGN = re.compile(
468
+ r"\A\s*(?:(?:export|const|let|var|val|final|private|public|protected|static|readonly|"
469
+ r"String|string|CharSequence|auto)\s+){0,4}([A-Za-z_$][\w$]{0,63})\s*"
470
+ r"(?::\s*[\w$.<>\[\]?]{1,64}\s*)?(\+=|:=|=)(?![=>])"
471
+ )
472
+ _C_DECL = re.compile(r"\A\s*(?:let|var|String|string)\s+([A-Za-z_$][\w$]{0,63})\s*;?\s*\Z")
473
+ _PY_ASSIGN = re.compile(r"\A\s*([A-Za-z_]\w{0,63})\s*(?::[^=\n]{1,80}?)?(\+=|=)(?!=)")
474
+ _CONTROL = re.compile(
475
+ r"\A\s*(?:\}\s*)?(?:if|for|while|switch|catch|else|do|try|synchronized|with|return|when)\b"
476
+ )
477
+ _FUNC_HEAD = re.compile(
478
+ r"\b(?:function|func|fun)\b|=>\s*\{\s*\Z|\)\s*(?::\s*[\w$.<>\[\]?, ]{1,80})?\s*"
479
+ r"(?:throws\s+[\w$., ]{1,200})?\{\s*\Z"
480
+ )
481
+ _WORD = re.compile(r"[A-Za-z_$][\w$]{0,127}")
482
+
483
+
484
+ class _Env:
485
+ """Bindings visible at one statement, and the enclosing function headers' names."""
486
+
487
+ def __init__(self) -> None:
488
+ self.scopes: list[dict[str, list[_Piece]]] = [{}]
489
+ self.funcs: list[tuple[int, tuple[str, ...]]] = []
490
+
491
+ def lookup(self, name: str) -> list[_Piece] | None:
492
+ for scope in reversed(self.scopes):
493
+ if name in scope:
494
+ return scope[name]
495
+ return None
496
+
497
+ def bind(self, name: str, piece: _Piece | None, augment: bool, declare: bool) -> None:
498
+ if declare:
499
+ self.scopes[-1][name] = [piece] if piece else []
500
+ return
501
+ for scope in reversed(self.scopes):
502
+ if name in scope:
503
+ if augment and piece:
504
+ scope[name] = [*scope[name], piece]
505
+ else:
506
+ scope[name] = [piece] if piece else []
507
+ return
508
+ self.scopes[-1][name] = [piece] if piece else []
509
+
510
+ @property
511
+ def func_words(self) -> tuple[str, ...]:
512
+ return tuple(w for _, words in self.funcs for w in words)
513
+
514
+
515
+ def _walk(f: _File) -> Iterator[tuple[Statement, _Env]]:
516
+ """Every statement in order with the bindings made before it.
517
+
518
+ C family: block scopes follow brace depth; a binding made inside a block
519
+ is forgotten when the block closes. Python: one scope per function (from
520
+ the AST when there is one). Branches are read in source order.
521
+ """
522
+ env = _Env()
523
+ if f.lang == "python":
524
+ yield from _walk_python(f, env)
525
+ return
526
+ depth = 0
527
+ for stmt in f.ctx.statements():
528
+ yield stmt, env
529
+ code = stmt.masked
530
+ m = _C_ASSIGN.match(code)
531
+ if m and not _CONTROL.match(code):
532
+ end = len(code.rstrip().rstrip(";"))
533
+ piece = _Piece(stmt, m.end(), max(end, m.end()))
534
+ declared = code.lstrip().split(None, 1)[0] in ("const", "let", "var", "val", "final")
535
+ env.bind(m.group(1), piece, m.group(2) == "+=", declared or m.group(2) == ":=")
536
+ else:
537
+ d = _C_DECL.match(code)
538
+ if d:
539
+ env.bind(d.group(1), None, False, True)
540
+ delta = code.count("{") - code.count("}")
541
+ new_depth = max(depth + delta, 0)
542
+ while len(env.scopes) - 1 > new_depth:
543
+ env.scopes.pop()
544
+ while len(env.scopes) - 1 < new_depth:
545
+ env.scopes.append({})
546
+ while env.funcs and env.funcs[-1][0] > new_depth:
547
+ env.funcs.pop()
548
+ if delta > 0 and _FUNC_HEAD.search(code) and not _CONTROL.match(code):
549
+ head = code.split("(", 1)[0]
550
+ env.funcs.append((new_depth, tuple(_WORD.findall(head))))
551
+ depth = new_depth
552
+
553
+
554
+ def _python_functions(f: _File) -> list[tuple[int, int, str]]:
555
+ tree = _py_tree(f)
556
+ if tree is None:
557
+ return []
558
+ out = [
559
+ (n.lineno, n.end_lineno or n.lineno, n.name)
560
+ for n in ast.walk(tree)
561
+ if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))
562
+ ]
563
+ out.sort()
564
+ return out
565
+
566
+
567
+ def _walk_python(f: _File, env: _Env) -> Iterator[tuple[Statement, _Env]]:
568
+ funcs = _python_functions(f)
569
+ scopes: dict[int, dict[str, list[_Piece]]] = {0: {}}
570
+ active: list[tuple[int, int, str]] = []
571
+ k = 0
572
+ for stmt in f.ctx.statements():
573
+ line = stmt.start_line
574
+ while active and active[-1][1] < line:
575
+ active.pop()
576
+ while k < len(funcs) and funcs[k][0] < line:
577
+ if funcs[k][1] >= line:
578
+ active.append(funcs[k])
579
+ k += 1
580
+ while active and active[-1][1] < line:
581
+ active.pop()
582
+ key = active[-1][0] if active else 0
583
+ env.scopes = [scopes.setdefault(key, {})]
584
+ env.funcs = [(0, (name,)) for _, _, name in active]
585
+ yield stmt, env
586
+ m = _PY_ASSIGN.match(stmt.masked)
587
+ if m:
588
+ piece = _Piece(stmt, m.end(), len(stmt.masked.rstrip()))
589
+ env.bind(m.group(1), piece, m.group(2) == "+=", False)
590
+
591
+
592
+ def _binding_exprs(f: _File, pieces: list[_Piece]) -> list[_Expr]:
593
+ return [_expr(f, f.view(p.stmt), p.start, p.end) for p in pieces[:16]]
594
+
595
+
596
+ # --- Python AST helpers --------------------------------------------------------------------------
597
+
598
+
599
+ _LONE_CR = re.compile(r"\r(?!\n)")
600
+
601
+
602
+ def _py_tree(f: _File) -> ast.Module | None:
603
+ """The new side's AST, or ``None`` when absent or its lines would not match Git's."""
604
+ tree = f.ctx.python_ast
605
+ if tree is None or _LONE_CR.search(f.source):
606
+ return None
607
+ return tree
608
+
609
+
610
+ def _py_dotted(node: ast.AST) -> str | None:
611
+ parts: list[str] = []
612
+ while isinstance(node, ast.Attribute):
613
+ parts.append(node.attr)
614
+ node = node.value
615
+ if isinstance(node, ast.Name):
616
+ parts.append(node.id)
617
+ return ".".join(reversed(parts))
618
+ if isinstance(node, ast.Call):
619
+ inner = _py_dotted(node.func)
620
+ if inner is not None:
621
+ parts.append(inner + "()")
622
+ return ".".join(reversed(parts))
623
+ return None
624
+
625
+
626
+ def _py_imports(tree: ast.Module) -> dict[str, str]:
627
+ """Local name to qualified name for every import in the module."""
628
+ names: dict[str, str] = {}
629
+ for node in ast.walk(tree):
630
+ if isinstance(node, ast.Import):
631
+ for a in node.names:
632
+ if a.asname:
633
+ names[a.asname] = a.name
634
+ else:
635
+ top = a.name.split(".", 1)[0]
636
+ names.setdefault(top, top)
637
+ elif isinstance(node, ast.ImportFrom) and node.module and not node.level:
638
+ for a in node.names:
639
+ names[a.asname or a.name] = f"{node.module}.{a.name}"
640
+ return names
641
+
642
+
643
+ def _py_qual(func: ast.AST, imports: dict[str, str]) -> str | None:
644
+ dotted = _py_dotted(func)
645
+ if dotted is None:
646
+ return None
647
+ head, _, tail = dotted.partition(".")
648
+ resolved = imports.get(head, head)
649
+ return f"{resolved}.{tail}" if tail else resolved
650
+
651
+
652
+ def _py_offset(f: _File, node: ast.AST) -> int:
653
+ line = getattr(node, "lineno", 1)
654
+ col = getattr(node, "col_offset", 0)
655
+ lines = f.ctx.lines
656
+ text = lines[line - 1] if 0 < line <= len(lines) else ""
657
+ chars = len(text.encode("utf-8", "surrogatepass")[:col].decode("utf-8", "ignore"))
658
+ if line == 1 and text.startswith(""):
659
+ chars += 1
660
+ return f.ctx.line_index.line_start(line) + chars
661
+
662
+
663
+ def _py_range(node: ast.AST) -> tuple[int, int]:
664
+ line = getattr(node, "lineno", 1)
665
+ return line, getattr(node, "end_lineno", None) or line
666
+
667
+
668
+ def _py_hit(
669
+ f: _File, node: ast.AST, message: str, evidence: str, *also: ast.AST, weak: bool = False
670
+ ) -> Hit | None:
671
+ ranges = [_py_range(node), *(_py_range(n) for n in also)]
672
+ return f.hit(_py_offset(f, node), ranges, message, evidence, weak=weak)
673
+
674
+
675
+ def _py_touches(f: _File, node: ast.AST) -> bool:
676
+ lo, hi = _py_range(node)
677
+ return f.first_changed(lo, hi) is not None
678
+
679
+
680
+ def _py_str(node: ast.AST) -> str | None:
681
+ if isinstance(node, ast.Constant) and isinstance(node.value, str):
682
+ return node.value
683
+ return None
684
+
685
+
686
+ def _py_arg(call: ast.Call, index: int, *names: str) -> ast.expr | None:
687
+ for kw in call.keywords:
688
+ if kw.arg in names:
689
+ return kw.value
690
+ if len(call.args) > index and not any(
691
+ isinstance(a, ast.Starred) for a in call.args[: index + 1]
692
+ ):
693
+ return call.args[index]
694
+ return None
695
+
696
+
697
+ def _py_kw(call: ast.Call, name: str) -> ast.expr | None:
698
+ for kw in call.keywords:
699
+ if kw.arg == name:
700
+ return kw.value
701
+ return None
702
+
703
+
704
+ def _py_is_const(node: ast.AST | None, value: object) -> bool:
705
+ return isinstance(node, ast.Constant) and node.value is value
706
+
707
+
708
+ _SCOPE_NODES = (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda, ast.ClassDef)
709
+ _PyEnv = dict[str, list[ast.expr]]
710
+
711
+
712
+ def _py_scoped_calls(tree: ast.Module) -> Iterator[tuple[ast.Call, _PyEnv]]:
713
+ """Every call with the simple-name bindings made before it in its scope.
714
+
715
+ A scope is the module, a function, a lambda or a class body. Assignments
716
+ are read in source order (branches are not told apart); ``x += y`` adds
717
+ ``y`` to ``x``'s values; any other binding of a name (loop targets,
718
+ ``with ... as``, tuple unpacking) forgets it.
719
+ """
720
+ pending: list[ast.AST] = [tree]
721
+ while pending:
722
+ scope = pending.pop()
723
+ events: list[tuple[tuple[int, int], int, ast.AST]] = []
724
+ targets: set[int] = set()
725
+ stack = list(ast.iter_child_nodes(scope))
726
+ while stack:
727
+ node = stack.pop()
728
+ if isinstance(node, _SCOPE_NODES):
729
+ pending.append(node)
730
+ continue
731
+ stack.extend(ast.iter_child_nodes(node))
732
+ if isinstance(node, (ast.Assign, ast.AnnAssign, ast.AugAssign, ast.NamedExpr)):
733
+ end = (node.end_lineno or node.lineno, node.end_col_offset or 0)
734
+ events.append((end, 1, node))
735
+ tgts = node.targets if isinstance(node, ast.Assign) else [node.target]
736
+ targets.update(id(t) for t in tgts if isinstance(t, ast.Name))
737
+ elif isinstance(node, ast.Call):
738
+ events.append(((node.lineno, node.col_offset), 0, node))
739
+ elif isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store):
740
+ events.append(((node.lineno, node.col_offset), 2, node))
741
+ events.sort(key=lambda e: (e[0], e[1]))
742
+ env: _PyEnv = {}
743
+ for _, kind, node in events:
744
+ if kind == 0:
745
+ yield node, env # type: ignore[misc]
746
+ elif kind == 2:
747
+ if id(node) not in targets:
748
+ env.pop(node.id, None) # type: ignore[attr-defined]
749
+ elif isinstance(node, ast.Assign):
750
+ for t in node.targets:
751
+ if isinstance(t, ast.Name):
752
+ env[t.id] = [node.value]
753
+ elif isinstance(node, (ast.AnnAssign, ast.NamedExpr)):
754
+ if isinstance(node.target, ast.Name) and node.value is not None:
755
+ env[node.target.id] = [node.value]
756
+ elif isinstance(node, ast.AugAssign) and isinstance(node.target, ast.Name):
757
+ name = node.target.id
758
+ if isinstance(node.op, ast.Add) and name in env:
759
+ env[name] = [*env[name][:15], node.value]
760
+ else:
761
+ env.pop(name, None)
762
+
763
+
764
+ _PY_NUMERIC_CALLS = frozenset({"int", "float", "len", "bool", "abs", "round"})
765
+
766
+
767
+ def _py_name_is_constant(name: str) -> bool:
768
+ return bool(re.fullmatch(r"_{0,2}[A-Z][A-Z0-9_]{1,63}", name))
769
+
770
+
771
+ def _py_literal(node: ast.AST, env: _PyEnv | None, depth: int = 0) -> bool:
772
+ """Is ``node`` built only from literals and constants?"""
773
+ if depth > 6:
774
+ return False
775
+ if isinstance(node, ast.Constant):
776
+ return True
777
+ if isinstance(node, ast.JoinedStr):
778
+ return all(
779
+ _py_safe_value(v.value, env, depth + 1)
780
+ for v in node.values
781
+ if isinstance(v, ast.FormattedValue)
782
+ )
783
+ if isinstance(node, ast.BinOp):
784
+ return _py_literal(node.left, env, depth + 1) and _py_literal(node.right, env, depth + 1)
785
+ if isinstance(node, (ast.Tuple, ast.List)):
786
+ return all(_py_literal(e, env, depth + 1) for e in node.elts)
787
+ if isinstance(node, ast.Name):
788
+ if _py_name_is_constant(node.id):
789
+ return True
790
+ values = env.get(node.id) if env is not None else None
791
+ return bool(values) and all(_py_literal(v, None, depth + 1) for v in values)
792
+ if isinstance(node, ast.Attribute):
793
+ return _py_name_is_constant(node.attr)
794
+ if (
795
+ isinstance(node, ast.Call)
796
+ and isinstance(node.func, ast.Attribute)
797
+ and node.func.attr in ("format", "join")
798
+ ):
799
+ return _py_literal(node.func.value, env, depth + 1) and all(
800
+ _py_literal(a, env, depth + 1) for a in node.args
801
+ )
802
+ return False
803
+
804
+
805
+ def _py_safe_value(node: ast.AST, env: _PyEnv | None, depth: int = 0) -> bool:
806
+ """A value that cannot inject: a literal, a constant, a number cast, placeholders."""
807
+ if _py_literal(node, env, depth):
808
+ return True
809
+ if isinstance(node, ast.Call):
810
+ name = _py_dotted(node.func) or ""
811
+ if name in _PY_NUMERIC_CALLS:
812
+ return True
813
+ if isinstance(node, ast.Name):
814
+ if "placeholder" in node.id.lower():
815
+ return True
816
+ values = env.get(node.id) if env is not None else None
817
+ if values and depth < 3 and all(_py_safe_value(v, None, depth + 1) for v in values):
818
+ return True
819
+ for sub in _bounded_walk(node, 200):
820
+ if (
821
+ isinstance(sub, ast.Constant)
822
+ and isinstance(sub.value, str)
823
+ and (sub.value.strip(" ,") in ("?", "%s") or re.fullmatch(r"\$\d{1,3}", sub.value))
824
+ ):
825
+ return True
826
+ return False
827
+
828
+
829
+ def _bounded_walk(node: ast.AST, limit: int) -> Iterator[ast.AST]:
830
+ stack = [node]
831
+ seen = 0
832
+ while stack and seen < limit:
833
+ n = stack.pop()
834
+ seen += 1
835
+ yield n
836
+ stack.extend(ast.iter_child_nodes(n))
837
+
838
+
839
+ def _py_add_parts(node: ast.AST, limit: int = 64) -> list[ast.expr]:
840
+ parts: list[ast.expr] = []
841
+ stack = [node]
842
+ while stack and len(parts) < limit:
843
+ n = stack.pop()
844
+ if isinstance(n, ast.BinOp) and isinstance(n.op, ast.Add):
845
+ stack.append(n.right)
846
+ stack.append(n.left)
847
+ else:
848
+ parts.append(n) # type: ignore[arg-type]
849
+ return parts
850
+
851
+
852
+ def _py_text(node: ast.AST) -> str:
853
+ """Literal text of a string-ish expression (placeholders for values)."""
854
+ if isinstance(node, ast.Constant) and isinstance(node.value, str):
855
+ return node.value
856
+ if isinstance(node, ast.JoinedStr):
857
+ return "".join(
858
+ v.value if isinstance(v, ast.Constant) and isinstance(v.value, str) else " ? "
859
+ for v in node.values
860
+ )
861
+ if isinstance(node, ast.BinOp) and isinstance(node.op, (ast.Add, ast.Mod)):
862
+ if isinstance(node.op, ast.Mod):
863
+ return _py_text(node.left)
864
+ return " ".join(_py_text(p) for p in _py_add_parts(node))
865
+ if (
866
+ isinstance(node, ast.Call)
867
+ and isinstance(node.func, ast.Attribute)
868
+ and node.func.attr == "format"
869
+ ):
870
+ return _py_text(node.func.value)
871
+ return ""
872
+
873
+
874
+ def _py_built(node: ast.AST, env: _PyEnv | None, *, quote_safe: bool = False) -> str | None:
875
+ """How a non-literal value enters a string expression, or ``None``."""
876
+ if quote_safe and _py_quoted(node):
877
+ return None
878
+ if isinstance(node, ast.JoinedStr):
879
+ unsafe = [
880
+ v
881
+ for v in node.values
882
+ if isinstance(v, ast.FormattedValue) and not _py_safe_value(v.value, env)
883
+ ]
884
+ return "f-string" if unsafe else None
885
+ if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
886
+ parts = _py_add_parts(node)
887
+ if any(not _py_safe_value(p, env) for p in parts):
888
+ return "concatenation"
889
+ return None
890
+ if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mod):
891
+ left = _py_str(node.left)
892
+ if left is not None and _STR_VERB.search(left) and not _py_safe_value(node.right, env):
893
+ return "%-formatting"
894
+ return None
895
+ if (
896
+ isinstance(node, ast.Call)
897
+ and isinstance(node.func, ast.Attribute)
898
+ and node.func.attr == "format"
899
+ and _py_str(node.func.value) is not None
900
+ ):
901
+ values = [*node.args, *(k.value for k in node.keywords)]
902
+ return ".format()" if any(not _py_safe_value(v, env) for v in values) else None
903
+ return None
904
+
905
+
906
+ def _py_quoted(node: ast.AST) -> bool:
907
+ """Does the expression quote its values for a shell (``shlex.quote``/``shlex.join``)?"""
908
+ for sub in _bounded_walk(node, 400):
909
+ if isinstance(sub, ast.Call):
910
+ name = _py_dotted(sub.func) or ""
911
+ if name.rsplit(".", 1)[-1] in ("quote", "join") and (
912
+ "shlex" in name or "pipes" in name or name in ("quote",)
913
+ ):
914
+ return True
915
+ return False
916
+
917
+
918
+ def _py_value_kind(node: ast.AST, env: _PyEnv, *, quote_safe: bool) -> str | None:
919
+ """How a non-literal command or code value is built: shape, variable or call."""
920
+ if quote_safe and _py_quoted(node):
921
+ return None
922
+ built = _py_built(node, env, quote_safe=quote_safe)
923
+ if built is not None:
924
+ return built
925
+ if _py_literal(node, env):
926
+ return None
927
+ if isinstance(node, ast.Name):
928
+ values = env.get(node.id)
929
+ if values:
930
+ for v in values:
931
+ inner = _py_built(v, None, quote_safe=quote_safe)
932
+ if inner is not None:
933
+ return f"{inner} via a variable"
934
+ if quote_safe and all(_py_quoted(v) for v in values):
935
+ return None
936
+ return "variable"
937
+ if isinstance(node, (ast.Attribute, ast.Subscript)):
938
+ return "variable"
939
+ if isinstance(node, ast.Call):
940
+ return "call result"
941
+ if isinstance(node, (ast.BinOp, ast.IfExp, ast.BoolOp)):
942
+ return "expression"
943
+ return None
944
+
945
+
946
+ # --- Shared word lists ---------------------------------------------------------------------------
947
+
948
+
949
+ _SECURITY_WORDS = frozenset(
950
+ {
951
+ "password",
952
+ "passwords",
953
+ "passwd",
954
+ "pwd",
955
+ "passphrase",
956
+ "secret",
957
+ "secrets",
958
+ "token",
959
+ "tokens",
960
+ "nonce",
961
+ "salt",
962
+ "otp",
963
+ "totp",
964
+ "hotp",
965
+ "signature",
966
+ "sign",
967
+ "signing",
968
+ "signed",
969
+ "credential",
970
+ "credentials",
971
+ "apikey",
972
+ "session",
973
+ "sessionid",
974
+ "sid",
975
+ "csrf",
976
+ "xsrf",
977
+ "jwt",
978
+ "verifier",
979
+ "verification",
980
+ "reset",
981
+ "invite",
982
+ "magic",
983
+ "cookie",
984
+ }
985
+ )
986
+ _KEY_QUALIFIERS = frozenset(
987
+ {
988
+ "api",
989
+ "secret",
990
+ "private",
991
+ "encryption",
992
+ "encrypt",
993
+ "crypto",
994
+ "aes",
995
+ "hmac",
996
+ "signing",
997
+ "access",
998
+ "master",
999
+ "session",
1000
+ "auth",
1001
+ }
1002
+ )
1003
+ _CAMEL = re.compile(r"[A-Z]{2,}(?=[A-Z][a-z]|\b|_|\d)|[A-Z]?[a-z]{1,64}|[A-Z]{1,64}|\d{1,20}")
1004
+
1005
+
1006
+ def _words(identifier: str) -> list[str]:
1007
+ return [w.lower() for w in _CAMEL.findall(identifier)]
1008
+
1009
+
1010
+ def _security_named(identifiers: list[str] | tuple[str, ...]) -> str | None:
1011
+ """The secret word (token, password, key, nonce, session...) the first matching name holds."""
1012
+ for ident in identifiers:
1013
+ words = _words(ident)
1014
+ for i, w in enumerate(words):
1015
+ if w in _SECURITY_WORDS:
1016
+ return w
1017
+ if w == "key" and i > 0 and words[i - 1] in _KEY_QUALIFIERS:
1018
+ return f"{words[i - 1]} key"
1019
+ return None
1020
+
1021
+
1022
+ def _statement_names(f: _File, view: _View) -> list[str]:
1023
+ """Identifiers in the statement's code plus short identifier-like string contents."""
1024
+ names = _WORD.findall(view.code)
1025
+ for span in view.strings:
1026
+ content = f.content(span).strip()
1027
+ if 0 < len(content) <= 40 and re.fullmatch(r"[\w.-]{1,40}", content):
1028
+ names.append(content)
1029
+ return names
1030
+
1031
+
1032
+ # --- Pattern tables ------------------------------------------------------------------------------
1033
+
1034
+
1035
+ @dataclass(frozen=True, slots=True)
1036
+ class _Pat:
1037
+ langs: frozenset[str]
1038
+ regex: re.Pattern[str]
1039
+ message: str
1040
+ view: str = "code"
1041
+ """``code`` (strings blanked) or ``text`` (comments blanked, strings kept)."""
1042
+ requires: re.Pattern[str] | None = None
1043
+ """Must also match the statement's text view."""
1044
+ unless: re.Pattern[str] | None = None
1045
+ """Must not match the statement's text view."""
1046
+ file_has: tuple[str, ...] = ()
1047
+ """The file must contain one of these substrings."""
1048
+ file_lacks: tuple[str, ...] = ()
1049
+ """The file must contain none of these substrings."""
1050
+ extend: int = 0
1051
+ """Characters of following code the match may reach into (block bodies)."""
1052
+ check: Callable[[_File, _View, re.Match[str]], bool] | None = None
1053
+ weak: bool = False
1054
+ """Report at warning severity under an error rule."""
1055
+
1056
+
1057
+ def _scan(f: _File, pats: tuple[_Pat, ...]) -> Iterator[Hit]:
1058
+ pats = tuple(p for p in pats if f.lang in p.langs)
1059
+ if not pats:
1060
+ return
1061
+ pats = tuple(
1062
+ p
1063
+ for p in pats
1064
+ if (not p.file_has or any(s in f.source for s in p.file_has))
1065
+ and not any(s in f.source for s in p.file_lacks)
1066
+ )
1067
+ if not pats:
1068
+ return
1069
+ for stmt in f.statements():
1070
+ candidates = [
1071
+ p
1072
+ for p in pats
1073
+ if p.regex.search(
1074
+ (stmt.masked + f.ctx.masked_code[stmt.end : stmt.end + p.extend])
1075
+ if p.view == "code"
1076
+ else stmt.text
1077
+ )
1078
+ ]
1079
+ if not candidates:
1080
+ continue
1081
+ view = f.view(stmt)
1082
+ for p in candidates:
1083
+ subject = view.code if p.view == "code" else view.text
1084
+ if p.extend:
1085
+ subject = subject + f.ctx.masked_code[stmt.end : stmt.end + p.extend]
1086
+ if p.requires is not None and not p.requires.search(view.text):
1087
+ continue
1088
+ if p.unless is not None and p.unless.search(view.text):
1089
+ continue
1090
+ for m in p.regex.finditer(subject):
1091
+ if m.start() >= len(view.code):
1092
+ break
1093
+ if p.view == "text" and not _code_start(view, m.start()):
1094
+ continue
1095
+ if p.check is not None and not p.check(f, view, m):
1096
+ continue
1097
+ hit = f.stmt_hit(view, m.start(), p.message, m.group(0), weak=p.weak)
1098
+ if hit is not None:
1099
+ yield hit
1100
+ break
1101
+
1102
+
1103
+ def _not_import(_f: _File, view: _View, _m: re.Match[str]) -> bool:
1104
+ return not re.match(r"\s*import\b", view.code)
1105
+
1106
+
1107
+ # --- security/sql-interpolation ------------------------------------------------------------------
1108
+
1109
+
1110
+ _SQL_START = re.compile(
1111
+ r"\A[\s(]{0,20}(?:select|insert|update|delete|replace|merge|with|upsert)\b", re.I
1112
+ )
1113
+ _SQL_STRUCT = re.compile(
1114
+ r"\b(?:select\b.{0,2000}?\bfrom|insert\s+(?:or\s+\w{1,16}\s+|ignore\s+)?into|"
1115
+ r"update\s+\S{1,128}\s+set|delete\s+from|replace\s+into|merge\s+into|with\s+\w{1,64}\s+as\s*\()\b",
1116
+ re.I | re.S,
1117
+ )
1118
+ _SQL_UPPER = re.compile(
1119
+ r"\b(?:SELECT\b.{0,2000}?\bFROM|INSERT\s+INTO|UPDATE\s+\S{1,128}\s+SET|DELETE\s+FROM|WHERE|"
1120
+ r"ORDER\s+BY|GROUP\s+BY|HAVING|VALUES|LIMIT|OFFSET|JOIN|AND|OR|IN)\b",
1121
+ re.S,
1122
+ )
1123
+
1124
+
1125
+ def _sql_shaped(text: str) -> bool:
1126
+ """Does literal text read as SQL: a statement, or upper-case clause keywords?"""
1127
+ if _SQL_START.search(text) and _SQL_STRUCT.search(text):
1128
+ return True
1129
+ return (
1130
+ bool(_SQL_UPPER.search(text))
1131
+ and not text.isupper()
1132
+ and bool(re.search(r"[=<>(?:]|\bFROM\b", text))
1133
+ )
1134
+
1135
+
1136
+ # Type arguments of a generic call, two levels deep: TypeScript and Kotlin put them
1137
+ # after the method name (db.query<Row>(...)), Java before it (jdbc.<Row>query(...)).
1138
+ _TYPE_ARG = r"[^<>()\n]{0,200}"
1139
+ _TYPE_ARGS = f"<{_TYPE_ARG}(?:<{_TYPE_ARG}(?:<{_TYPE_ARG}>{_TYPE_ARG})?>{_TYPE_ARG})?>"
1140
+ _SQL_SINKS = {
1141
+ "python": re.compile(
1142
+ r"(?:\.\s*(execute|executemany|executescript|raw|read_sql|read_sql_query|exec_driver_sql)"
1143
+ r"|(?<![\w.])(text|RawSQL|read_sql|read_sql_query))\s*\("
1144
+ ),
1145
+ "javascript": re.compile(
1146
+ r"\.\s*(query|execute|exec|raw|prepare|run|all|get|each|unsafe|\$queryRawUnsafe|"
1147
+ r"\$executeRawUnsafe|queryRawUnsafe|executeRawUnsafe|whereRaw|orderByRaw|havingRaw|"
1148
+ r"joinRaw|fromRaw|selectRaw)\s*(?:" + _TYPE_ARGS + r"\s*)?\("
1149
+ ),
1150
+ "go": re.compile(
1151
+ r"\.\s*(Exec|ExecContext|Query|QueryContext|QueryRow|QueryRowContext|Prepare|"
1152
+ r"PrepareContext|Raw|Select|Get|MustExec|Queryx|QueryRowx|NamedExec|NamedQuery)\s*\("
1153
+ ),
1154
+ "java": re.compile(
1155
+ r"\.\s*(?:" + _TYPE_ARGS + r"\s*)?"
1156
+ r"(executeQuery|executeUpdate|executeLargeUpdate|execute|addBatch|prepareStatement|"
1157
+ r"prepareCall|createQuery|createNativeQuery|createSQLQuery|query|queryForObject|"
1158
+ r"queryForList|queryForMap|queryForRowSet|queryForStream|update|batchUpdate|rawQuery|"
1159
+ r"execSQL)\s*(?:" + _TYPE_ARGS + r"\s*)?\("
1160
+ ),
1161
+ }
1162
+ _SQL_SINKS["typescript"] = _SQL_SINKS["javascript"]
1163
+ _SQL_SINKS["kotlin"] = _SQL_SINKS["java"]
1164
+
1165
+
1166
+ def _sql_expr_kind(e: _Expr) -> tuple[str, bool] | None:
1167
+ """``(kind, structural_only)`` when ``e`` is SQL built from non-literal values."""
1168
+ kind = _kind(e)
1169
+ if kind not in _BUILT or not _sql_shaped(e.literal):
1170
+ return None
1171
+ if kind in ("%-formatting", ".format()", "format call"):
1172
+ contexts = _format_contexts(e.literal)
1173
+ else:
1174
+ contexts = e.contexts
1175
+ return kind, _structural_only(contexts)
1176
+
1177
+
1178
+ def _sql_text(f: _File) -> Iterator[Hit]:
1179
+ sink = _SQL_SINKS[f.lang]
1180
+ for stmt, env in _walk(f):
1181
+ for m in sink.finditer(stmt.masked):
1182
+ name = m.group(1) or m.group(2)
1183
+ view = f.view(stmt)
1184
+ parsed = _call_args(f, view, m.end() - 1)
1185
+ if parsed is None:
1186
+ continue
1187
+ for a, b in parsed[1]:
1188
+ e = _expr(f, view, a, b)
1189
+ found = _sql_expr_kind(e)
1190
+ extra: list[tuple[int, int]] = []
1191
+ if found is None and _SIMPLE_PATH.match(e.rest) and f.lang != "python":
1192
+ pieces = env.lookup(e.rest.strip())
1193
+ if pieces:
1194
+ found = _sql_binding_kind(f, pieces)
1195
+ extra = [(p.stmt.start_line, p.stmt.end_line) for p in pieces]
1196
+ if found is None:
1197
+ continue
1198
+ hit = _sql_hit(
1199
+ f,
1200
+ stmt.start + m.start(1 if m.group(1) else 2),
1201
+ [(stmt.start_line, stmt.end_line), *extra],
1202
+ name,
1203
+ *found,
1204
+ )
1205
+ if hit is not None:
1206
+ yield hit
1207
+ break
1208
+
1209
+
1210
+ def _sql_hit(
1211
+ f: _File, offset: int, ranges: list[tuple[int, int]], name: str, kind: str, structural: bool
1212
+ ) -> Hit | None:
1213
+ if structural:
1214
+ return f.hit(
1215
+ offset,
1216
+ ranges,
1217
+ f"SQL name or clause built by {kind} reaches {name}()",
1218
+ f"{name}({kind}, structural)",
1219
+ weak=True,
1220
+ )
1221
+ return f.hit(offset, ranges, f"SQL built by {kind} reaches {name}()", f"{name}({kind})")
1222
+
1223
+
1224
+ def _sql_binding_kind(f: _File, pieces: list[_Piece]) -> tuple[str, bool] | None:
1225
+ exprs = _binding_exprs(f, pieces)
1226
+ found = [k for k in map(_sql_expr_kind, exprs) if k is not None]
1227
+ if found:
1228
+ return f"{found[0][0]} via a variable", all(ident for _, ident in found)
1229
+ if any(_sql_shaped(e.literal) for e in exprs):
1230
+ added = [e for e in exprs[1:] if _kind(e) in _BUILT]
1231
+ if added:
1232
+ contexts = [c for e in added for c in e.contexts]
1233
+ return "concatenation via a variable", _structural_only(contexts)
1234
+ return None
1235
+
1236
+
1237
+ _PY_SQL_ATTRS = frozenset(
1238
+ {
1239
+ "execute",
1240
+ "executemany",
1241
+ "executescript",
1242
+ "raw",
1243
+ "read_sql",
1244
+ "read_sql_query",
1245
+ "exec_driver_sql",
1246
+ "text",
1247
+ }
1248
+ )
1249
+ _PY_SQL_FUNCS = frozenset({"text", "RawSQL", "read_sql", "read_sql_query"})
1250
+
1251
+
1252
+ def _py_sql_kind(node: ast.AST, env: _PyEnv, depth: int = 0) -> tuple[str, bool] | None:
1253
+ """``(kind, structural_only)`` when ``node`` is SQL built from non-literal values."""
1254
+ built = _py_built(node, env)
1255
+ if built is not None:
1256
+ if not _sql_shaped(_py_text(node)):
1257
+ return None
1258
+ return built, _structural_only(_py_contexts(node, env))
1259
+ if isinstance(node, ast.Name) and depth < 2:
1260
+ values = env.get(node.id) or []
1261
+ for v in values:
1262
+ inner = _py_sql_kind(v, env, depth + 1)
1263
+ if inner is not None:
1264
+ kind = (
1265
+ inner[0]
1266
+ if inner[0].endswith("via a variable")
1267
+ else f"{inner[0]} via a variable"
1268
+ )
1269
+ return kind, inner[1]
1270
+ if len(values) > 1 and _sql_shaped(_py_text(values[0])):
1271
+ added = [v for v in values[1:] if not _py_safe_value(v, env)]
1272
+ if added:
1273
+ contexts = [
1274
+ c for v in added for c in _py_contexts(v, env, prefix=_py_text(values[0]))
1275
+ ]
1276
+ return "concatenation via a variable", _structural_only(contexts)
1277
+ return None
1278
+
1279
+
1280
+ def _py_contexts(node: ast.AST, env: _PyEnv, prefix: str = "") -> list[str]:
1281
+ """The literal text right before each non-literal value of a string expression."""
1282
+ contexts: list[str] = []
1283
+ if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mod):
1284
+ return _format_contexts(_py_text(node.left))
1285
+ if (
1286
+ isinstance(node, ast.Call)
1287
+ and isinstance(node.func, ast.Attribute)
1288
+ and node.func.attr == "format"
1289
+ ):
1290
+ return _format_contexts(_py_text(node.func.value))
1291
+ seen = prefix
1292
+ parts = _py_add_parts(node) if isinstance(node, ast.BinOp) else [node]
1293
+ for part in parts:
1294
+ if isinstance(part, ast.Constant) and isinstance(part.value, str):
1295
+ seen += part.value
1296
+ elif isinstance(part, ast.JoinedStr):
1297
+ for v in part.values:
1298
+ if isinstance(v, ast.Constant) and isinstance(v.value, str):
1299
+ seen += v.value
1300
+ elif isinstance(v, ast.FormattedValue) and not _py_safe_value(v.value, env):
1301
+ contexts.append(_context(seen))
1302
+ elif not _py_safe_value(part, env):
1303
+ contexts.append(_context(seen))
1304
+ return contexts
1305
+
1306
+
1307
+ def _sql_python(f: _File, tree: ast.Module) -> Iterator[Hit]:
1308
+ for call, env in _py_scoped_calls(tree):
1309
+ func = call.func
1310
+ if isinstance(func, ast.Attribute) and func.attr in _PY_SQL_ATTRS:
1311
+ name = func.attr
1312
+ elif isinstance(func, ast.Name) and func.id in _PY_SQL_FUNCS:
1313
+ name = func.id
1314
+ else:
1315
+ continue
1316
+ arg = _py_arg(call, 0, "sql", "query", "statement", "stmt", "operation")
1317
+ if arg is None:
1318
+ continue
1319
+ found = _py_sql_kind(arg, env)
1320
+ if found is None:
1321
+ continue
1322
+ also: list[ast.AST] = []
1323
+ if isinstance(arg, ast.Name):
1324
+ also = list(env.get(arg.id, ()))
1325
+ ranges = [_py_range(call), *(_py_range(n) for n in also)]
1326
+ hit = _sql_hit(f, _py_offset(f, call), ranges, name, *found)
1327
+ if hit is not None:
1328
+ yield hit
1329
+
1330
+
1331
+ @rule(
1332
+ id="security/sql-interpolation",
1333
+ severity="error",
1334
+ title="SQL built by string interpolation",
1335
+ languages=_CODE,
1336
+ rationale=(
1337
+ "Values interpolated or concatenated into SQL text become part of the statement, so a "
1338
+ "crafted value can change what the query does (SQL injection)."
1339
+ ),
1340
+ hint="Pass values as query parameters (placeholders) or use the query builder.",
1341
+ tags={"security", "cwe-89"},
1342
+ )
1343
+ def sql_interpolation(ctx: FileContext) -> Iterator[Hit]:
1344
+ """SQL-shaped text built from non-literal values reaches an execute or query call.
1345
+
1346
+ Shapes: f-strings, template literals and Kotlin templates with a value,
1347
+ ``+`` with a non-literal operand, ``%`` / ``.format()`` / ``String.format``
1348
+ / ``fmt.Sprintf`` with a ``%s``-style verb or ``{}`` field, either as the
1349
+ call's argument or through a variable assigned (or ``+=``-extended) earlier
1350
+ in the same scope. Sinks: ``execute``/``executemany``/``raw``/``text()``/
1351
+ ``read_sql`` (Python), ``query``/``execute``/``raw``/``prepare``/``*RawUnsafe``
1352
+ (JS/TS), ``Exec``/``Query``/``QueryRow``/``Prepare`` and their ``Context``
1353
+ forms (Go), ``executeQuery``/``prepareStatement``/``createQuery``/
1354
+ ``createNativeQuery``/JdbcTemplate methods (Java/Kotlin), also as generic
1355
+ calls (``db.query<Row>(...)``, ``jdbc.<Row>query(...)``).
1356
+
1357
+ Error when a value lands where SQL expects a value (after an operator, a
1358
+ quote, ``(``, ``,`` or ``WHERE``/``AND``/``LIKE``/``LIMIT``/``VALUES``/
1359
+ ``SET``/``ORDER BY``...); warning when every value is a name or clause the
1360
+ program composes (``FROM {table}``, ``"DELETE FROM t " + where``).
1361
+
1362
+ Ignores: parameterised calls (the SQL itself constant), tagged templates
1363
+ (``sql`...```, Prisma ``$queryRaw``), query builders, constant strings,
1364
+ upper-case constants and numeric casts (``int(x)``) as values, generated
1365
+ placeholder lists (``",".join("?" * n)``, names containing
1366
+ ``placeholder``), ``%d``-only formatting, text that does not read as SQL,
1367
+ and ``StringBuilder`` chains.
1368
+ """
1369
+ f = _File(ctx)
1370
+ if f.lang == "python":
1371
+ tree = _py_tree(f)
1372
+ if tree is not None:
1373
+ yield from _sql_python(f, tree)
1374
+ return
1375
+ yield from _sql_text(f)
1376
+ if f.incomplete:
1377
+ raise PartialCoverage("a call too long to read whole")
1378
+
1379
+
1380
+ # --- security/shell-injection --------------------------------------------------------------------
1381
+
1382
+
1383
+ _SHELLS = frozenset(
1384
+ {
1385
+ "sh",
1386
+ "bash",
1387
+ "zsh",
1388
+ "dash",
1389
+ "ksh",
1390
+ "/bin/sh",
1391
+ "/bin/bash",
1392
+ "/usr/bin/bash",
1393
+ "/bin/zsh",
1394
+ "cmd",
1395
+ "cmd.exe",
1396
+ "powershell",
1397
+ "pwsh",
1398
+ }
1399
+ )
1400
+ _SHELL_FLAG = re.compile(r"\A(?:-[a-z]{0,4}c|/c|-Command)\Z")
1401
+ _PY_SHELL_ALWAYS = frozenset(
1402
+ {
1403
+ "os.system",
1404
+ "os.popen",
1405
+ "commands.getoutput",
1406
+ "commands.getstatusoutput",
1407
+ "subprocess.getoutput",
1408
+ "subprocess.getstatusoutput",
1409
+ "asyncio.create_subprocess_shell",
1410
+ "platform.popen",
1411
+ }
1412
+ )
1413
+ _PY_SUBPROCESS = frozenset(
1414
+ {
1415
+ "subprocess.run",
1416
+ "subprocess.call",
1417
+ "subprocess.check_call",
1418
+ "subprocess.check_output",
1419
+ "subprocess.Popen",
1420
+ }
1421
+ )
1422
+ _QUOTED_TEXT = re.compile(
1423
+ r"\b(?:shlex\.(?:quote|join)|pipes\.quote|escapeshellarg|shellescape|shell-quote|shellQuote|quote)\s*\("
1424
+ )
1425
+
1426
+
1427
+ def _py_shell_list(node: ast.AST, env: _PyEnv) -> str | None:
1428
+ if not isinstance(node, (ast.List, ast.Tuple)):
1429
+ return None
1430
+ elts = node.elts
1431
+ for i in range(len(elts) - 2):
1432
+ shell, flag = _py_str(elts[i]), _py_str(elts[i + 1])
1433
+ if shell in _SHELLS and flag is not None and _SHELL_FLAG.match(flag):
1434
+ kind = _py_value_kind(elts[i + 2], env, quote_safe=True)
1435
+ if kind is not None:
1436
+ return kind
1437
+ return None
1438
+
1439
+
1440
+ def _shell_python(f: _File, tree: ast.Module) -> Iterator[Hit]:
1441
+ imports = _py_imports(tree)
1442
+ for call, env in _py_scoped_calls(tree):
1443
+ qual = _py_qual(call.func, imports) or ""
1444
+ if qual in _PY_SHELL_ALWAYS:
1445
+ cmd = _py_arg(call, 0, "cmd", "command")
1446
+ kind = None if cmd is None else _py_value_kind(cmd, env, quote_safe=True)
1447
+ elif qual in _PY_SUBPROCESS:
1448
+ cmd = _py_arg(call, 0, "args")
1449
+ if cmd is None:
1450
+ continue
1451
+ shell = _py_kw(call, "shell")
1452
+ if (
1453
+ isinstance(shell, ast.Constant)
1454
+ and shell.value is True
1455
+ and not isinstance(cmd, (ast.List, ast.Tuple))
1456
+ ):
1457
+ kind = _py_value_kind(cmd, env, quote_safe=True)
1458
+ else:
1459
+ kind = _py_shell_list(cmd, env)
1460
+ else:
1461
+ continue
1462
+ if kind is None:
1463
+ continue
1464
+ name = qual.rsplit(".", 1)[-1]
1465
+ hit = _py_hit(f, call, f"Shell command built by {kind} reaches {name}()", f"{name}({kind})")
1466
+ if hit is not None:
1467
+ yield hit
1468
+
1469
+
1470
+ _SHELL_TEXT: dict[str, re.Pattern[str]] = {
1471
+ "python": re.compile(
1472
+ r"\b(?:(os\.system|os\.popen|subprocess\.getoutput|subprocess\.getstatusoutput|"
1473
+ r"commands\.getoutput|asyncio\.create_subprocess_shell)|"
1474
+ r"(subprocess\.(?:run|call|check_call|check_output|Popen)))\s*\("
1475
+ ),
1476
+ "javascript": re.compile(
1477
+ r"(?:\b(?:child_process|childProcess|cp|shell)\s*\.\s*(exec|execSync)|(?<![\w$.])(exec|execSync)"
1478
+ r"|(?<![\w$])(spawn|spawnSync|execFile|execFileSync))\s*\("
1479
+ ),
1480
+ "go": re.compile(r"\bexec\.(Command|CommandContext)\s*\("),
1481
+ "java": re.compile(
1482
+ r"(?:Runtime\s*\.\s*getRuntime\s*\(\s*\)\s*\.\s*(exec)|(?<![\w.])(?:new\s+)?(ProcessBuilder))\s*\("
1483
+ ),
1484
+ }
1485
+ _SHELL_TEXT["typescript"] = _SHELL_TEXT["javascript"]
1486
+ _SHELL_TEXT["kotlin"] = _SHELL_TEXT["java"]
1487
+ _SHELL_KINDS = _BUILT | {"variable"}
1488
+
1489
+
1490
+ def _shell_c_kind(f: _File, view: _View, env: _Env, a: int, b: int) -> str | None:
1491
+ """Kind of a non-literal command value at ``view.code[a:b]`` (C family, Python text)."""
1492
+ if _QUOTED_TEXT.search(view.code[a:b]):
1493
+ return None
1494
+ e = _expr(f, view, a, b)
1495
+ kind = _kind(e)
1496
+ if kind == "variable":
1497
+ if f.lang == "python":
1498
+ return None # no AST: a variable's value is unknown
1499
+ pieces = env.lookup(e.rest.strip())
1500
+ if pieces:
1501
+ exprs = _binding_exprs(f, pieces)
1502
+ built = [k for k in map(_kind, exprs) if k is not None]
1503
+ if not built:
1504
+ return None
1505
+ quoted = all(_QUOTED_TEXT.search(f.view(p.stmt).code[p.start : p.end]) for p in pieces)
1506
+ return None if quoted else f"{built[0]} via a variable"
1507
+ return "variable"
1508
+ return kind if kind in _SHELL_KINDS else None
1509
+
1510
+
1511
+ def _shell_flag_arg(f: _File, view: _View, lo: int, hi: int) -> tuple[int, int] | None:
1512
+ """The element after a literal ``sh``/``bash`` and ``-c`` inside ``view.code[lo:hi]``."""
1513
+ base = view.stmt.start
1514
+ spans = [s for s in view.strings if lo <= s.start - base and s.end - base <= hi]
1515
+ for first, second in itertools.pairwise(spans):
1516
+ if f.content(first) in _SHELLS and _SHELL_FLAG.match(f.content(second)):
1517
+ between = view.code[first.end - base : second.start - base]
1518
+ if between.strip() != ",":
1519
+ continue
1520
+ j = second.end - base
1521
+ rest = view.code[j:hi]
1522
+ k = len(rest) - len(rest.lstrip())
1523
+ if rest[k : k + 1] != ",":
1524
+ continue
1525
+ start = j + k + 1
1526
+ depth = 0
1527
+ for i in range(start, hi):
1528
+ c = view.code[i]
1529
+ if c in "([{":
1530
+ depth += 1
1531
+ elif c in ")]}":
1532
+ if depth == 0:
1533
+ return start, i
1534
+ depth -= 1
1535
+ elif c == "," and depth == 0:
1536
+ return start, i
1537
+ return start, hi
1538
+ return None
1539
+
1540
+
1541
+ _CP_IMPORT = re.compile(
1542
+ r"\{([^{}]{0,400})\}\s*(?:=\s*require\s*\(\s*[\"'`](?:node:)?child_process[\"'`]|"
1543
+ r"from\s+[\"'`](?:node:)?child_process[\"'`])"
1544
+ )
1545
+ _CP_ALIAS = re.compile(
1546
+ r"\b(exec|execSync)\s*=\s*(?:\w{1,32}\.)?(?:promisify\s*\(\s*)?(?:require\s*\(\s*[\"'`]"
1547
+ r"(?:node:)?child_process[\"'`]\s*\)|child_process|childProcess|cp)\s*\.\s*(?:exec|execSync)\b"
1548
+ )
1549
+
1550
+ _CP_PROMISIFY = re.compile(
1551
+ r"\b(exec|execSync)\s*=\s*(?:\w{1,32}\.)?promisify\s*\(\s*\w{1,32}\s*\.\s*exec\b"
1552
+ )
1553
+
1554
+
1555
+ def _child_process_names(f: _File) -> frozenset[str]:
1556
+ """``exec``/``execSync`` imported from ``child_process`` under their own names."""
1557
+ if "child_process" not in f.source:
1558
+ return frozenset()
1559
+ names: set[str] = set()
1560
+ src = f.source
1561
+ pos = src.find("child_process")
1562
+ windows = 0
1563
+ while pos >= 0 and windows < 200:
1564
+ window = src[max(0, pos - 600) : pos + 40]
1565
+ for m in _CP_IMPORT.finditer(window):
1566
+ for part in m.group(1).split(","):
1567
+ name = part.strip().split(":")[0].strip()
1568
+ if name in ("exec", "execSync"):
1569
+ names.add(name)
1570
+ names.update(m.group(1) for m in _CP_ALIAS.finditer(window))
1571
+ pos = src.find("child_process", pos + 1)
1572
+ windows += 1
1573
+ pos = src.find("promisify")
1574
+ while pos >= 0 and windows < 400:
1575
+ window = src[max(0, pos - 80) : pos + 80]
1576
+ names.update(m.group(1) for m in _CP_PROMISIFY.finditer(window))
1577
+ pos = src.find("promisify", pos + 1)
1578
+ windows += 1
1579
+ return frozenset(names)
1580
+
1581
+
1582
+ def _shell_text(f: _File) -> Iterator[Hit]:
1583
+ sink = _SHELL_TEXT[f.lang]
1584
+ bare = _child_process_names(f) if f.lang in _JS else frozenset()
1585
+ for stmt, env in _walk(f):
1586
+ if not f.touched(stmt):
1587
+ continue
1588
+ view = f.view(stmt)
1589
+ for m in sink.finditer(stmt.masked):
1590
+ group = next(i for i in range(1, (m.lastindex or 1) + 1) if m.group(i))
1591
+ name = m.group(group)
1592
+ parsed = _call_args(f, view, m.end() - 1)
1593
+ if parsed is None:
1594
+ continue
1595
+ close, args = parsed
1596
+ if not args:
1597
+ continue
1598
+ kind: str | None = None
1599
+ target = args[0]
1600
+ if f.lang in _JS:
1601
+ if group == 2 and (
1602
+ name not in bare or re.match(r"\s*[{:]", view.code[close + 1 :])
1603
+ ):
1604
+ continue # not child_process, or a method definition
1605
+ if group == 3:
1606
+ inner = _shell_flag_arg(f, view, m.end(), close)
1607
+ if inner is not None:
1608
+ kind = _shell_c_kind(f, view, env, *inner)
1609
+ elif re.search(r"\bshell\s*:\s*true\b", view.code[m.end() : close]):
1610
+ kind = _shell_c_kind(f, view, env, *target)
1611
+ else:
1612
+ kind = _shell_c_kind(f, view, env, *target)
1613
+ elif f.lang == "python":
1614
+ if group != 2:
1615
+ kind = _shell_c_kind(f, view, env, *target)
1616
+ elif re.search(r"\bshell\s*=\s*True\b", view.code[m.end() : close]):
1617
+ if view.code[target[0] : target[1]].lstrip()[:1] not in "[(":
1618
+ kind = _shell_c_kind(f, view, env, *target)
1619
+ else:
1620
+ inner = _shell_flag_arg(f, view, m.end(), close)
1621
+ if inner is not None:
1622
+ kind = _shell_c_kind(f, view, env, *inner)
1623
+ else:
1624
+ inner = _shell_flag_arg(f, view, m.end(), close)
1625
+ if inner is not None:
1626
+ kind = _shell_c_kind(f, view, env, *inner)
1627
+ elif name == "exec" and not view.code[target[0] : target[1]].lstrip().startswith(
1628
+ "new"
1629
+ ):
1630
+ kind = _shell_c_kind(f, view, env, *target)
1631
+ if kind is None:
1632
+ continue
1633
+ hit = f.stmt_hit(
1634
+ view,
1635
+ m.start(group),
1636
+ f"Shell command built by {kind} reaches {name}()",
1637
+ f"{name}({kind})",
1638
+ )
1639
+ if hit is not None:
1640
+ yield hit
1641
+ break
1642
+
1643
+
1644
+ @rule(
1645
+ id="security/shell-injection",
1646
+ severity="error",
1647
+ title="Shell command built from non-literal values",
1648
+ languages=_CODE,
1649
+ rationale=(
1650
+ "A command line handed to a shell is parsed again, so a value inserted into it can add "
1651
+ "arguments or whole commands (command injection)."
1652
+ ),
1653
+ hint="Pass an argument list without a shell, or quote every value (shlex.quote).",
1654
+ tags={"security", "cwe-78"},
1655
+ )
1656
+ def shell_injection(ctx: FileContext) -> Iterator[Hit]:
1657
+ """A non-literal command line reaches a shell.
1658
+
1659
+ Sinks: ``os.system``, ``os.popen``, ``subprocess.getoutput``,
1660
+ ``asyncio.create_subprocess_shell`` and ``subprocess.*(..., shell=True)``
1661
+ (Python); ``child_process.exec``/``execSync`` and ``spawn``/``execFile``
1662
+ with ``shell: true`` (JS/TS); ``Runtime.getRuntime().exec(String)``
1663
+ (Java/Kotlin); and in every language an argument list that runs
1664
+ ``sh``/``bash``/``cmd`` with ``-c`` followed by a non-literal command.
1665
+ Non-literal: an f-string or template with a value, concatenation, ``%`` or
1666
+ ``.format()`` with a string field, or a variable (with the AST, a variable
1667
+ or call result whose value is not a literal).
1668
+
1669
+ Ignores: literal commands and upper-case constants, argument lists
1670
+ without a shell (``subprocess.run(["git", ref])``, ``exec.Command(name,
1671
+ arg)``, ``execFile``), values passed through ``shlex.quote``/``shlex.join``,
1672
+ ``%d``-only formatting, ``RegExp.prototype.exec``, bare ``exec`` in files
1673
+ that do not use ``child_process``, and (without a Python AST) variables.
1674
+ """
1675
+ f = _File(ctx)
1676
+ if f.lang == "python":
1677
+ tree = _py_tree(f)
1678
+ if tree is not None:
1679
+ yield from _shell_python(f, tree)
1680
+ return
1681
+ yield from _shell_text(f)
1682
+ if f.incomplete:
1683
+ raise PartialCoverage("a call too long to read whole")
1684
+
1685
+
1686
+ # --- security/eval -------------------------------------------------------------------------------
1687
+
1688
+
1689
+ def _py_shadowed(tree: ast.Module, names: frozenset[str]) -> frozenset[str]:
1690
+ """Builtin names the module rebinds (defines, imports or assigns at top level)."""
1691
+ found: set[str] = set()
1692
+ for node in tree.body:
1693
+ if (
1694
+ isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef))
1695
+ and node.name in names
1696
+ ):
1697
+ found.add(node.name)
1698
+ elif isinstance(node, (ast.Import, ast.ImportFrom)):
1699
+ found.update(a.asname or a.name for a in node.names if (a.asname or a.name) in names)
1700
+ elif isinstance(node, ast.Assign):
1701
+ found.update(t.id for t in node.targets if isinstance(t, ast.Name) and t.id in names)
1702
+ return frozenset(found)
1703
+
1704
+
1705
+ _PY_EVAL = frozenset({"eval", "exec"})
1706
+
1707
+
1708
+ def _eval_python(f: _File, tree: ast.Module) -> Iterator[Hit]:
1709
+ live = _PY_EVAL - _py_shadowed(tree, _PY_EVAL)
1710
+ for call, env in _py_scoped_calls(tree):
1711
+ if not isinstance(call.func, ast.Name) or call.func.id not in live:
1712
+ continue
1713
+ arg = _py_arg(call, 0, "source")
1714
+ if arg is None:
1715
+ continue
1716
+ kind = _py_value_kind(arg, env, quote_safe=False)
1717
+ if kind is None:
1718
+ continue
1719
+ name = call.func.id
1720
+ hit = _py_hit(f, call, f"{name}() runs code built by {kind}", f"{name}({kind})")
1721
+ if hit is not None:
1722
+ yield hit
1723
+
1724
+
1725
+ _EVAL_TEXT = {
1726
+ "python": re.compile(r"(?<![\w.])(eval|exec)\s*\("),
1727
+ "javascript": re.compile(r"(?<![\w$.])(eval|(?:new\s+)?Function)\s*\("),
1728
+ }
1729
+ _EVAL_TEXT["typescript"] = _EVAL_TEXT["javascript"]
1730
+
1731
+
1732
+ def _eval_text(f: _File) -> Iterator[Hit]:
1733
+ sink = _EVAL_TEXT.get(f.lang)
1734
+ if sink is None:
1735
+ return
1736
+ for stmt, env in _walk(f):
1737
+ if not f.touched(stmt):
1738
+ continue
1739
+ view = f.view(stmt)
1740
+ for m in sink.finditer(stmt.masked):
1741
+ before = stmt.masked[: m.start()].rstrip()
1742
+ if re.search(r"\b(?:def|function|fun|func|async|get|set|static)\Z", before):
1743
+ continue
1744
+ parsed = _call_args(f, view, m.end() - 1)
1745
+ if parsed is None:
1746
+ continue
1747
+ close, args = parsed
1748
+ if not args or re.match(r"\s*[{:]", view.code[close + 1 :]):
1749
+ continue # a method definition (JS/TS)
1750
+ name = m.group(1).replace("new", "").strip()
1751
+ a, b = args[-1] if name == "Function" else args[0]
1752
+ e = _expr(f, view, a, b)
1753
+ kind = _kind(e)
1754
+ if kind == "variable":
1755
+ if f.lang == "python":
1756
+ continue
1757
+ pieces = env.lookup(e.rest.strip())
1758
+ if (
1759
+ pieces is not None
1760
+ and pieces
1761
+ and all(_kind(x) is None for x in _binding_exprs(f, pieces))
1762
+ ):
1763
+ continue
1764
+ elif kind not in _BUILT:
1765
+ continue
1766
+ hit = f.stmt_hit(
1767
+ view, m.start(), f"{name}() runs code built by {kind}", f"{name}({kind})"
1768
+ )
1769
+ if hit is not None:
1770
+ yield hit
1771
+ break
1772
+
1773
+
1774
+ @rule(
1775
+ id="security/eval",
1776
+ severity="error",
1777
+ title="eval of a non-literal value",
1778
+ languages=_PY | _JS,
1779
+ rationale="Code built from data and then evaluated runs whatever that data says.",
1780
+ hint="Parse the data instead (json.loads, ast.literal_eval, a lookup table).",
1781
+ tags={"security", "cwe-95"},
1782
+ )
1783
+ def eval_(ctx: FileContext) -> Iterator[Hit]:
1784
+ """The builtin ``eval``/``exec`` (Python) or ``eval``/``Function`` (JS/TS) gets a non-literal.
1785
+
1786
+ Only bare calls of the builtins count. Ignores: ``ast.literal_eval``,
1787
+ attribute calls (``model.eval()``, ``vm.runInContext``, ``engine.eval``,
1788
+ ``window.eval``), literal and upper-case constant arguments, variables
1789
+ whose every assignment in scope is a literal, method definitions named
1790
+ ``eval``, and modules that define or import their own ``eval``/``exec``.
1791
+ Without a Python AST, variables are not reported.
1792
+ """
1793
+ f = _File(ctx)
1794
+ if f.lang == "python":
1795
+ tree = _py_tree(f)
1796
+ if tree is not None:
1797
+ yield from _eval_python(f, tree)
1798
+ return
1799
+ yield from _eval_text(f)
1800
+ if f.incomplete:
1801
+ raise PartialCoverage("a call too long to read whole")
1802
+
1803
+
1804
+ # --- security/unsafe-deserialization -------------------------------------------------------------
1805
+
1806
+ _PY_UNPICKLE = frozenset(
1807
+ {
1808
+ "pickle.load",
1809
+ "pickle.loads",
1810
+ "pickle.Unpickler",
1811
+ "cPickle.load",
1812
+ "cPickle.loads",
1813
+ "cPickle.Unpickler",
1814
+ "_pickle.load",
1815
+ "_pickle.loads",
1816
+ "_pickle.Unpickler",
1817
+ "marshal.load",
1818
+ "marshal.loads",
1819
+ "yaml.unsafe_load",
1820
+ "yaml.unsafe_load_all",
1821
+ }
1822
+ )
1823
+ _PY_WEAK_DESER = frozenset(
1824
+ {
1825
+ "dill.load",
1826
+ "dill.loads",
1827
+ "cloudpickle.load",
1828
+ "cloudpickle.loads",
1829
+ "joblib.load",
1830
+ "pandas.read_pickle",
1831
+ "torch.load",
1832
+ "shelve.open",
1833
+ "jsonpickle.decode",
1834
+ "jsonpickle.loads",
1835
+ }
1836
+ )
1837
+ _YAML_SAFE = frozenset({"SafeLoader", "CSafeLoader", "BaseLoader", "CBaseLoader"})
1838
+ _YAML_UNSAFE = frozenset({"Loader", "UnsafeLoader", "CLoader", "CUnsafeLoader"})
1839
+
1840
+
1841
+ def _py_roundtrip(arg: ast.AST | None) -> bool:
1842
+ if isinstance(arg, ast.Constant):
1843
+ return True
1844
+ if isinstance(arg, ast.Call):
1845
+ name = _py_dotted(arg.func) or ""
1846
+ return name.endswith(("dumps", "dump"))
1847
+ return False
1848
+
1849
+
1850
+ def _deser_python(f: _File, tree: ast.Module) -> Iterator[Hit]:
1851
+ imports = _py_imports(tree)
1852
+ for node in ast.walk(tree):
1853
+ if not isinstance(node, ast.Call) or not _py_touches(f, node):
1854
+ continue
1855
+ qual = _py_qual(node.func, imports) or ""
1856
+ if qual in _PY_UNPICKLE:
1857
+ if _py_roundtrip(_py_arg(node, 0, "file", "data", "stream")):
1858
+ continue
1859
+ hit = _py_hit(f, node, f"{qual}() can run code while it reads untrusted data", qual)
1860
+ elif qual in ("yaml.load", "yaml.load_all"):
1861
+ loader = _py_arg(node, 1, "Loader")
1862
+ loader_name = None if loader is None else (_py_dotted(loader) or "").rsplit(".", 1)[-1]
1863
+ if loader_name is None or loader_name in _YAML_UNSAFE:
1864
+ hit = _py_hit(
1865
+ f, node, f"{qual}() without a safe loader can construct any object", qual
1866
+ )
1867
+ elif loader_name == "FullLoader":
1868
+ hit = _py_hit(
1869
+ f, node, f"{qual}() with FullLoader constructs Python objects", qual, weak=True
1870
+ )
1871
+ else:
1872
+ continue
1873
+ elif qual in _PY_WEAK_DESER or (
1874
+ qual == "numpy.load" and _py_is_const(_py_kw(node, "allow_pickle"), True)
1875
+ ):
1876
+ if qual == "torch.load" and _py_is_const(_py_kw(node, "weights_only"), True):
1877
+ continue
1878
+ hit = _py_hit(f, node, f"{qual}() unpickles its input", qual, weak=True)
1879
+ else:
1880
+ continue
1881
+ if hit is not None:
1882
+ yield hit
1883
+
1884
+
1885
+ _DESER_PATS = (
1886
+ _Pat(
1887
+ _PY,
1888
+ re.compile(
1889
+ r"\b(?:c?[Pp]ickle|_pickle|marshal)\.(?:loads?|Unpickler)\s*\(|\byaml\.unsafe_load(?:_all)?\s*\("
1890
+ ),
1891
+ "Deserializer that can run code while it reads untrusted data",
1892
+ unless=re.compile(r"\bdumps?\s*\("),
1893
+ ),
1894
+ _Pat(
1895
+ _PY,
1896
+ re.compile(r"\byaml\.load(?:_all)?\s*\("),
1897
+ "yaml.load() without a safe loader can construct any object",
1898
+ unless=re.compile(
1899
+ r"Loader\s*=\s*(?:yaml\.)?(?!(?:C?Unsafe)?C?Loader\b)\w|SafeLoader|BaseLoader"
1900
+ ),
1901
+ ),
1902
+ _Pat(
1903
+ frozenset({"java"}),
1904
+ re.compile(r"\bnew\s+ObjectInputStream\s*\("),
1905
+ "ObjectInputStream deserializes any class on the classpath",
1906
+ unless=re.compile(r"\bnew\s+ObjectInputStream\s*\([^;]{0,400}\)\s*\{"),
1907
+ file_lacks=("ObjectInputFilter", "setObjectInputFilter"),
1908
+ ),
1909
+ _Pat(
1910
+ frozenset({"kotlin"}),
1911
+ re.compile(r"(?<![\w.:])(?<!:\s)ObjectInputStream\s*\("),
1912
+ "ObjectInputStream deserializes any class on the classpath",
1913
+ unless=re.compile(r"\bclass\b|:\s*ObjectInputStream\s*\(|\bobject\s*:"),
1914
+ file_lacks=("ObjectInputFilter", "setObjectInputFilter"),
1915
+ check=_not_import,
1916
+ ),
1917
+ )
1918
+
1919
+ _WEAK_DESER_PATS = (
1920
+ _Pat(
1921
+ _JVM,
1922
+ re.compile(r"\bnew\s+XMLDecoder\s*\(|(?<![\w.])XMLDecoder\s*\(|\.fromXML\s*\("),
1923
+ "XMLDecoder and XStream build arbitrary objects",
1924
+ check=_not_import,
1925
+ weak=True,
1926
+ ),
1927
+ _Pat(
1928
+ _JS,
1929
+ re.compile(r"(?<![\w$.])unserialize\s*\(|\bserialize\s*\.\s*unserialize\s*\("),
1930
+ "node-serialize unserialize() evaluates functions in its input",
1931
+ file_has=("node-serialize",),
1932
+ weak=True,
1933
+ ),
1934
+ _Pat(
1935
+ _PY,
1936
+ re.compile(
1937
+ r"\b(?:dill|cloudpickle|jsonpickle)\.(?:loads?|decode)\s*\(|\b(?:joblib|torch)\.load\s*\(|\bpd\.read_pickle\s*\(|\bshelve\.open\s*\("
1938
+ ),
1939
+ "Loader that unpickles its input",
1940
+ weak=True,
1941
+ ),
1942
+ )
1943
+
1944
+
1945
+ @rule(
1946
+ id="security/unsafe-deserialization",
1947
+ severity="error",
1948
+ title="Unsafe deserialization",
1949
+ languages=_CODE,
1950
+ rationale=(
1951
+ "Formats that rebuild arbitrary objects (pickle, marshal, full YAML tags, Java "
1952
+ "serialization) run code chosen by whoever wrote the data."
1953
+ ),
1954
+ hint="Use a data-only format (JSON, yaml.safe_load) or restrict the classes that may load.",
1955
+ tags={"security", "cwe-502"},
1956
+ )
1957
+ def unsafe_deserialization(ctx: FileContext) -> Iterator[Hit]:
1958
+ """Deserializers that can construct arbitrary objects.
1959
+
1960
+ Error: ``pickle``/``cPickle``/``_pickle``/``marshal`` ``load``/``loads``/
1961
+ ``Unpickler``, ``yaml.unsafe_load`` and ``yaml.load``/``load_all`` with no
1962
+ loader or an unsafe one (``Loader``, ``UnsafeLoader``, ``CLoader``), Java
1963
+ ``new ObjectInputStream`` and Kotlin ``ObjectInputStream(...)``.
1964
+ Warning: ``yaml.load`` with ``FullLoader``, ``dill``/``cloudpickle``/
1965
+ ``joblib``/``torch.load`` (without ``weights_only=True``)/
1966
+ ``pandas.read_pickle``/``shelve``/``jsonpickle``, ``numpy.load`` with
1967
+ ``allow_pickle=True``, ``XMLDecoder``/XStream ``fromXML`` and
1968
+ ``node-serialize``.
1969
+
1970
+ Ignores: safe YAML loaders (``SafeLoader``, ``CSafeLoader``,
1971
+ ``BaseLoader``) and custom loader names, pickle round trips
1972
+ (``loads(dumps(x))``) and literal bytes, ``ObjectInputStream`` subclasses
1973
+ and anonymous subclasses (they override ``resolveClass``), and Java files
1974
+ that install an ``ObjectInputFilter``.
1975
+ """
1976
+ f = _File(ctx)
1977
+ if f.lang == "python":
1978
+ tree = _py_tree(f)
1979
+ if tree is not None:
1980
+ yield from _deser_python(f, tree)
1981
+ return
1982
+ yield from _scan(f, _DESER_PATS + _WEAK_DESER_PATS)
1983
+
1984
+
1985
+ # --- security/tls-verification-disabled ----------------------------------------------------------
1986
+
1987
+ _HTTP_ATTRS = frozenset(
1988
+ {
1989
+ "get",
1990
+ "post",
1991
+ "put",
1992
+ "patch",
1993
+ "delete",
1994
+ "head",
1995
+ "options",
1996
+ "request",
1997
+ "send",
1998
+ "stream",
1999
+ "Client",
2000
+ "AsyncClient",
2001
+ "Session",
2002
+ "ClientSession",
2003
+ "TCPConnector",
2004
+ "urlopen",
2005
+ "PoolManager",
2006
+ "ProxyManager",
2007
+ "client",
2008
+ "resource",
2009
+ "ws_connect",
2010
+ "HTTPAdapter",
2011
+ "fetch",
2012
+ }
2013
+ )
2014
+ _HTTP_ROOTS = (
2015
+ "requests",
2016
+ "httpx",
2017
+ "aiohttp",
2018
+ "urllib3",
2019
+ "boto3",
2020
+ "botocore",
2021
+ "grequests",
2022
+ "niquests",
2023
+ )
2024
+
2025
+
2026
+ def _py_http_call(call: ast.Call, imports: dict[str, str]) -> bool:
2027
+ qual = _py_qual(call.func, imports) or ""
2028
+ if qual.split(".", 1)[0] in ("jwt", "jose", "jws"):
2029
+ return False
2030
+ if qual.split(".", 1)[0] in _HTTP_ROOTS:
2031
+ return True
2032
+ return isinstance(call.func, ast.Attribute) and call.func.attr in _HTTP_ATTRS
2033
+
2034
+
2035
+ def _tls_python(f: _File, tree: ast.Module) -> Iterator[Hit]:
2036
+ imports = _py_imports(tree)
2037
+ http_module = any(v.split(".", 1)[0] in _HTTP_ROOTS for v in imports.values())
2038
+ for node in ast.walk(tree):
2039
+ if not _py_touches(f, node):
2040
+ continue
2041
+ found: tuple[ast.AST, str] | None = None
2042
+ weak = False
2043
+ if isinstance(node, ast.Call):
2044
+ for kw in node.keywords:
2045
+ if kw.arg in ("verify", "verify_ssl") and _py_is_const(kw.value, False):
2046
+ if _py_http_call(node, imports):
2047
+ found = (kw, f"{kw.arg}=False")
2048
+ elif kw.arg == "ssl" and _py_is_const(kw.value, False):
2049
+ qual = _py_qual(node.func, imports) or ""
2050
+ if qual.startswith("aiohttp") or (
2051
+ isinstance(node.func, ast.Attribute) and node.func.attr in _HTTP_ATTRS
2052
+ ):
2053
+ found = (kw, "ssl=False")
2054
+ elif kw.arg == "cert_reqs":
2055
+ v = kw.value
2056
+ if (isinstance(v, ast.Attribute) and v.attr == "CERT_NONE") or _py_str(v) in (
2057
+ "CERT_NONE",
2058
+ "none",
2059
+ ):
2060
+ found = (kw, "cert_reqs=CERT_NONE")
2061
+ elif isinstance(node, ast.Attribute) and node.attr == "_create_unverified_context":
2062
+ found = (node, "ssl._create_unverified_context")
2063
+ elif isinstance(node, ast.Assign) and len(node.targets) == 1:
2064
+ t = node.targets[0]
2065
+ if isinstance(t, ast.Attribute):
2066
+ if t.attr == "check_hostname" and _py_is_const(node.value, False):
2067
+ found = (node, "check_hostname = False")
2068
+ weak = True
2069
+ elif (
2070
+ t.attr == "verify_mode"
2071
+ and isinstance(node.value, ast.Attribute)
2072
+ and node.value.attr == "CERT_NONE"
2073
+ ):
2074
+ found = (node, "verify_mode = CERT_NONE")
2075
+ elif t.attr == "verify" and _py_is_const(node.value, False):
2076
+ receiver = (_py_dotted(t.value) or "").lower()
2077
+ if http_module or any(w in receiver for w in ("session", "client", "http")):
2078
+ found = (node, "verify = False")
2079
+ if found is None:
2080
+ continue
2081
+ at, evidence = found
2082
+ what = "Host name verification" if weak else "TLS certificate verification"
2083
+ hit = _py_hit(f, at, f"{what} is disabled ({evidence})", evidence, weak=weak)
2084
+ if hit is not None:
2085
+ yield hit
2086
+
2087
+
2088
+ _GO_OWN_VERIFY = ("VerifyPeerCertificate", "VerifyConnection")
2089
+ _TLS_PATS = (
2090
+ _Pat(
2091
+ _PY,
2092
+ re.compile(r"\bverify(?:_ssl)?\s*=\s*False\b"),
2093
+ "TLS certificate verification is disabled",
2094
+ requires=re.compile(r"\b(?:requests|httpx|aiohttp|urllib3|boto3|[Ss]ession|[Cc]lient)\b"),
2095
+ unless=re.compile(r"\bjwt\b|\bjose\b"),
2096
+ ),
2097
+ _Pat(
2098
+ _PY,
2099
+ re.compile(
2100
+ r"\bssl\._create_unverified_context\b|\bverify_mode\s*=\s*ssl\.CERT_NONE\b|\bcert_reqs\s*=\s*ssl\.CERT_NONE\b"
2101
+ ),
2102
+ "TLS certificate verification is disabled",
2103
+ ),
2104
+ _Pat(
2105
+ _PY,
2106
+ re.compile(r"\bcheck_hostname\s*=\s*False\b"),
2107
+ "Host name verification is disabled",
2108
+ weak=True,
2109
+ ),
2110
+ _Pat(
2111
+ _JS,
2112
+ re.compile(r"\brejectUnauthorized\s*:\s*false\b|\bstrictSSL\s*:\s*false\b"),
2113
+ "TLS certificate verification is disabled",
2114
+ ),
2115
+ _Pat(
2116
+ _JS,
2117
+ re.compile(
2118
+ r"\bprocess\.env(?:\.NODE_TLS_REJECT_UNAUTHORIZED|\[\s*[\"'`]NODE_TLS_REJECT_UNAUTHORIZED[\"'`]\s*\])\s*=\s*(?:[\"'`]0[\"'`]|0\b)"
2119
+ ),
2120
+ "TLS certificate verification is disabled for the whole process",
2121
+ view="text",
2122
+ ),
2123
+ _Pat(
2124
+ _GO,
2125
+ re.compile(r"\bInsecureSkipVerify\s*(?::|=)\s*true\b"),
2126
+ "TLS certificate verification is disabled",
2127
+ file_lacks=_GO_OWN_VERIFY,
2128
+ ),
2129
+ _Pat(
2130
+ _GO,
2131
+ re.compile(r"\bInsecureSkipVerify\s*(?::|=)\s*true\b"),
2132
+ "Default certificate verification is replaced; check the custom verifier",
2133
+ file_has=_GO_OWN_VERIFY,
2134
+ weak=True,
2135
+ ),
2136
+ _Pat(
2137
+ _JVM,
2138
+ re.compile(
2139
+ r"\bNoopHostnameVerifier\b|\bALLOW_ALL_HOSTNAME_VERIFIER\b|\bTrustAllStrategy\b|\bInsecureTrustManagerFactory\s*\.\s*INSTANCE\b"
2140
+ ),
2141
+ "TLS certificate or host name verification is disabled",
2142
+ check=_not_import,
2143
+ ),
2144
+ _Pat(
2145
+ _JVM,
2146
+ re.compile(
2147
+ r"\b(?:setHostnameVerifier|setDefaultHostnameVerifier|hostnameVerifier)\s*(?:\(\s*)?(?:\(\s*\w+\s*,\s*\w+\s*\)\s*->|\{\s*_?\w*\s*,\s*_?\w*\s*->)\s*(?:\{\s*return\s+)?true\b"
2148
+ ),
2149
+ "Host name verification accepts every host",
2150
+ ),
2151
+ _Pat(
2152
+ _JVM,
2153
+ re.compile(
2154
+ r"\bcheckServerTrusted\s*\([^)]{0,300}\)\s*(?::\s*Unit\s*)?(?:throws\s+[\w.,\s]{1,200})?\{[\s/*]{0,300}\}"
2155
+ ),
2156
+ "Trust manager accepts every certificate",
2157
+ extend=400,
2158
+ ),
2159
+ )
2160
+
2161
+ _SHELL_TLS = re.compile(
2162
+ r"\bhttp\.sslVerify(?:=|\s+)false\b|\bGIT_SSL_NO_VERIFY=[\"']?(?:1|true)\b|"
2163
+ r"\bNODE_TLS_REJECT_UNAUTHORIZED=[\"']?0\b|\bPYTHONHTTPSVERIFY=[\"']?0\b|"
2164
+ r"--insecure-skip-tls-verify(?:=true)?(?![=\w-])|\bstrict-ssl\s+false\b|--no-check-certificate\b",
2165
+ re.I,
2166
+ )
2167
+ _SHELL_LOCAL = re.compile(r"\blocalhost\b|\b127\.0\.0\.1\b|\[::1\]")
2168
+ _SHELL_COMMAND = re.compile(r"(?<![\w./-])(curl|chmod|mkdir|install)(?=[ \t])")
2169
+ _SHELL_END = re.compile(r"[;&|\n)`]")
2170
+
2171
+
2172
+ def _shell_tokens(code: str, start: int) -> list[tuple[int, str]]:
2173
+ end = _SHELL_END.search(code, start)
2174
+ stop = end.start() if end else len(code)
2175
+ stop = min(stop, start + 1000)
2176
+ return [(m.start(), m.group(0)) for m in _SHELL_TOKEN.finditer(code, start, stop)]
2177
+
2178
+
2179
+ _SHELL_TOKEN = re.compile(r"\S{1,400}")
2180
+
2181
+
2182
+ def _tls_shell(f: _File) -> Iterator[Hit]:
2183
+ for stmt in f.statements():
2184
+ view = f.view(stmt)
2185
+ if _SHELL_LOCAL.search(view.text):
2186
+ continue
2187
+ m = _SHELL_TLS.search(view.text)
2188
+ if m and _code_start(view, m.start()):
2189
+ hit = f.stmt_hit(
2190
+ view, m.start(), "TLS certificate verification is disabled", m.group(0)
2191
+ )
2192
+ if hit is not None:
2193
+ yield hit
2194
+ continue
2195
+ for c in _SHELL_COMMAND.finditer(view.code):
2196
+ if c.group(1) != "curl":
2197
+ continue
2198
+ for pos, tok in _shell_tokens(view.code, c.end()):
2199
+ if tok == "--insecure" or re.fullmatch(r"-[A-Za-z]{0,12}k[A-Za-z]{0,12}", tok):
2200
+ hit = f.stmt_hit(
2201
+ view, pos, "curl skips TLS certificate verification", "curl --insecure"
2202
+ )
2203
+ if hit is not None:
2204
+ yield hit
2205
+ break
2206
+
2207
+
2208
+ @rule(
2209
+ id="security/tls-verification-disabled",
2210
+ severity="error",
2211
+ title="TLS certificate verification disabled",
2212
+ languages=_CODE | _SHELL,
2213
+ rationale=(
2214
+ "Without certificate and host name checks anyone on the network path can impersonate "
2215
+ "the server and read or change the traffic."
2216
+ ),
2217
+ hint="Keep verification on; trust a private CA by passing its bundle instead.",
2218
+ tags={"security", "cwe-295"},
2219
+ )
2220
+ def tls_verification_disabled(ctx: FileContext) -> Iterator[Hit]:
2221
+ """Code or commands that turn off TLS certificate or host name verification.
2222
+
2223
+ Python: ``verify=False``/``verify_ssl=False`` on HTTP clients (requests,
2224
+ httpx, aiohttp, urllib3, boto3, any ``.get``/``.post``/``Session``-like
2225
+ call), aiohttp ``ssl=False``, ``cert_reqs=CERT_NONE``,
2226
+ ``ssl._create_unverified_context``, ``check_hostname = False``,
2227
+ ``verify_mode = CERT_NONE``, ``session.verify = False``. JS/TS:
2228
+ ``rejectUnauthorized: false``, ``strictSSL: false``,
2229
+ ``NODE_TLS_REJECT_UNAUTHORIZED = "0"``. Go: ``InsecureSkipVerify: true``.
2230
+ Java/Kotlin: ``NoopHostnameVerifier``, ``ALLOW_ALL_HOSTNAME_VERIFIER``,
2231
+ ``TrustAllStrategy``, ``InsecureTrustManagerFactory``, host name
2232
+ verifiers returning ``true``, empty ``checkServerTrusted``. Shell: ``curl
2233
+ -k``/``--insecure``, ``wget --no-check-certificate``, ``http.sslVerify
2234
+ false``, ``GIT_SSL_NO_VERIFY``, ``--insecure-skip-tls-verify``, npm
2235
+ ``strict-ssl false``.
2236
+
2237
+ Ignores: ``verify=False`` on non-HTTP calls (``jwt.decode`` is the JWT
2238
+ rule's), ``ssl=False`` on database drivers (that disables TLS, not
2239
+ verification), shell commands aimed at ``localhost``/``127.0.0.1``,
2240
+ ``import`` lines, and ``urllib3.disable_warnings``.
2241
+ """
2242
+ f = _File(ctx)
2243
+ if f.lang == "shell":
2244
+ yield from _tls_shell(f)
2245
+ return
2246
+ if f.lang == "python":
2247
+ tree = _py_tree(f)
2248
+ if tree is not None:
2249
+ yield from _tls_python(f, tree)
2250
+ return
2251
+ yield from _scan(f, _TLS_PATS)
2252
+
2253
+
2254
+ # --- security/jwt-verification-disabled ----------------------------------------------------------
2255
+
2256
+
2257
+ def _jwt_python(f: _File, tree: ast.Module) -> Iterator[Hit]:
2258
+ for node in ast.walk(tree):
2259
+ if not isinstance(node, ast.Call) or not isinstance(node.func, ast.Attribute):
2260
+ continue
2261
+ if node.func.attr != "decode" or not _py_touches(f, node):
2262
+ continue
2263
+ receiver = (_py_dotted(node.func.value) or "").lower()
2264
+ if "jwt" not in receiver and "jws" not in receiver and "jose" not in receiver:
2265
+ continue
2266
+ evidence = None
2267
+ verify = _py_kw(node, "verify")
2268
+ options = _py_kw(node, "options")
2269
+ algorithms = _py_kw(node, "algorithms")
2270
+ if _py_is_const(verify, False):
2271
+ evidence = "verify=False"
2272
+ elif isinstance(options, ast.Dict):
2273
+ for k, v in zip(options.keys, options.values, strict=False):
2274
+ if k is not None and _py_str(k) == "verify_signature" and _py_is_const(v, False):
2275
+ evidence = "verify_signature: False"
2276
+ if (
2277
+ evidence is None
2278
+ and isinstance(algorithms, (ast.List, ast.Tuple, ast.Set))
2279
+ and any((_py_str(e) or "").lower() == "none" for e in algorithms.elts)
2280
+ ):
2281
+ evidence = 'algorithms=["none"]'
2282
+ if evidence is None:
2283
+ continue
2284
+ hit = _py_hit(
2285
+ f, node, f"JWT accepted without verifying its signature ({evidence})", evidence
2286
+ )
2287
+ if hit is not None:
2288
+ yield hit
2289
+
2290
+
2291
+ _ALG_NONE = re.compile(r"algorithms?\s*[:=]\s*\[?[^\]\n]{0,100}?[\"'`]none[\"'`]", re.I)
2292
+
2293
+ _JWT_PATS = (
2294
+ _Pat(
2295
+ _PY,
2296
+ re.compile(r"[\"']verify_signature[\"']\s*:\s*False\b"),
2297
+ "JWT accepted without verifying its signature",
2298
+ view="text",
2299
+ ),
2300
+ _Pat(
2301
+ _PY,
2302
+ re.compile(r"\bjwt\.decode\s*\("),
2303
+ "JWT accepted without verifying its signature",
2304
+ requires=re.compile(
2305
+ r"\bverify\s*=\s*False\b|algorithms\s*=\s*\[[^\]]{0,100}[\"']none[\"']", re.I
2306
+ ),
2307
+ ),
2308
+ _Pat(
2309
+ _JS,
2310
+ re.compile(r"\b(?:jwt|jsonwebtoken|jws)\s*\.\s*verify\s*\("),
2311
+ "JWT verification allows the 'none' algorithm",
2312
+ requires=_ALG_NONE,
2313
+ ),
2314
+ _Pat(
2315
+ _JS, re.compile(r"\bUnsecuredJWT\s*\.\s*decode\s*\("), "Unsecured (unsigned) JWT accepted"
2316
+ ),
2317
+ _Pat(
2318
+ _GO,
2319
+ re.compile(r"\bjwt\.UnsafeAllowNoneSignatureType\b"),
2320
+ "JWT verification allows the 'none' algorithm",
2321
+ ),
2322
+ _Pat(
2323
+ _JVM,
2324
+ re.compile(
2325
+ r"\.\s*(?:parseClaimsJwt|parsePlaintextJwt|parseUnsecuredClaims|parseUnsecuredContent)\s*\(|\.\s*unsecured\s*\(\s*\)|\bAlgorithm\s*\.\s*none\s*\(\s*\)"
2326
+ ),
2327
+ "Unsigned JWT accepted",
2328
+ ),
2329
+ )
2330
+
2331
+
2332
+ @rule(
2333
+ id="security/jwt-verification-disabled",
2334
+ severity="error",
2335
+ title="JWT signature verification disabled",
2336
+ languages=_CODE,
2337
+ rationale="A token whose signature is not checked can be forged by anyone.",
2338
+ hint="Verify the signature with the expected key and a fixed list of real algorithms.",
2339
+ tags={"security", "cwe-347"},
2340
+ )
2341
+ def jwt_verification_disabled(ctx: FileContext) -> Iterator[Hit]:
2342
+ """JWTs decoded or parsed without signature verification.
2343
+
2344
+ Python: ``jwt.decode`` (PyJWT, python-jose) with ``verify=False``,
2345
+ ``options={"verify_signature": False}`` or ``"none"`` in ``algorithms``.
2346
+ JS/TS: ``jwt.verify`` allowing ``"none"``, jose ``UnsecuredJWT.decode``.
2347
+ Go: ``jwt.UnsafeAllowNoneSignatureType``. Java/Kotlin: jjwt
2348
+ ``parseClaimsJwt``/``parsePlaintextJwt``/``unsecured()``, auth0
2349
+ ``Algorithm.none()``.
2350
+
2351
+ Ignores: reading headers or claims on purpose before verifying
2352
+ (``jwt.get_unverified_header``, jsonwebtoken ``jwt.decode``,
2353
+ ``ParseUnverified``, auth0 ``JWT.decode``), expiry options such as
2354
+ ``ignoreExpiration``, and issuing tokens.
2355
+ """
2356
+ f = _File(ctx)
2357
+ if f.lang == "python":
2358
+ tree = _py_tree(f)
2359
+ if tree is not None:
2360
+ yield from _jwt_python(f, tree)
2361
+ return
2362
+ yield from _scan(f, _JWT_PATS)
2363
+
2364
+
2365
+ # --- security/world-writable ---------------------------------------------------------------------
2366
+
2367
+ _STAT_BITS = {
2368
+ "S_ISUID": 0o4000,
2369
+ "S_ISGID": 0o2000,
2370
+ "S_ISVTX": 0o1000,
2371
+ "S_IRWXU": 0o700,
2372
+ "S_IRUSR": 0o400,
2373
+ "S_IWUSR": 0o200,
2374
+ "S_IXUSR": 0o100,
2375
+ "S_IREAD": 0o400,
2376
+ "S_IWRITE": 0o200,
2377
+ "S_IEXEC": 0o100,
2378
+ "S_IRWXG": 0o70,
2379
+ "S_IRGRP": 0o40,
2380
+ "S_IWGRP": 0o20,
2381
+ "S_IXGRP": 0o10,
2382
+ "S_IRWXO": 0o7,
2383
+ "S_IROTH": 0o4,
2384
+ "S_IWOTH": 0o2,
2385
+ "S_IXOTH": 0o1,
2386
+ "ModePerm": 0o777,
2387
+ "ModeSticky": 0o1000,
2388
+ }
2389
+
2390
+
2391
+ def _world_writable(mode: int) -> bool:
2392
+ """Others may write and the sticky bit is not set (a shared ``/tmp``-style directory)."""
2393
+ return bool(mode & 0o002) and not mode & 0o1000
2394
+
2395
+
2396
+ def _py_mode(node: ast.AST | None, depth: int = 0) -> int | None:
2397
+ if node is None or depth > 8:
2398
+ return None
2399
+ if (
2400
+ isinstance(node, ast.Constant)
2401
+ and isinstance(node.value, int)
2402
+ and not isinstance(node.value, bool)
2403
+ ):
2404
+ return node.value
2405
+ if isinstance(node, ast.BinOp) and isinstance(node.op, (ast.BitOr, ast.Add)):
2406
+ left, right = _py_mode(node.left, depth + 1), _py_mode(node.right, depth + 1)
2407
+ if left is None or right is None:
2408
+ return None
2409
+ return left | right
2410
+ name = (
2411
+ node.attr
2412
+ if isinstance(node, ast.Attribute)
2413
+ else node.id
2414
+ if isinstance(node, ast.Name)
2415
+ else None
2416
+ )
2417
+ return _STAT_BITS.get(name) if name else None
2418
+
2419
+
2420
+ def _ww_python(f: _File, tree: ast.Module) -> Iterator[Hit]:
2421
+ imports = _py_imports(tree)
2422
+ for node in ast.walk(tree):
2423
+ if not isinstance(node, ast.Call) or not _py_touches(f, node):
2424
+ continue
2425
+ qual = _py_qual(node.func, imports) or ""
2426
+ if qual in ("os.chmod", "os.lchmod", "os.fchmod"):
2427
+ mode_node = _py_arg(node, 1, "mode")
2428
+ elif isinstance(node.func, ast.Attribute) and node.func.attr in ("chmod", "lchmod"):
2429
+ mode_node = _py_kw(node, "mode") or (node.args[-1] if node.args else None)
2430
+ else:
2431
+ continue
2432
+ mode = _py_mode(mode_node)
2433
+ if mode is None or not _world_writable(mode):
2434
+ continue
2435
+ hit = _py_hit(
2436
+ f, node, f"chmod to {mode:o} lets every user write the file", f"chmod {mode:o}"
2437
+ )
2438
+ if hit is not None:
2439
+ yield hit
2440
+
2441
+
2442
+ _WW_SINKS = {
2443
+ "python": re.compile(r"\b(?:os\.(?:l|f)?chmod|\.\s*l?chmod)\s*\("),
2444
+ "javascript": re.compile(
2445
+ r"(?:\bfs(?:\.promises)?\s*\.\s*|(?<![\w$.])|\.\s*)(?:l|f)?chmod(?:Sync)?\s*\("
2446
+ ),
2447
+ "go": re.compile(r"\bos\.Chmod\s*\(|\.\s*Chmod\s*\("),
2448
+ }
2449
+ _WW_SINKS["typescript"] = _WW_SINKS["javascript"]
2450
+ _MODE_NUMBER = re.compile(r"\A\s*(?:0[oO]([0-7]{1,6})|0([0-7]{1,6})|([1-9]\d{0,5}))\s*\Z")
2451
+
2452
+
2453
+ def _text_mode(f: _File, view: _View, a: int, b: int) -> int | None:
2454
+ code = view.code[a:b]
2455
+ e = _expr(f, view, a, b)
2456
+ if e.strings:
2457
+ if e.rest.strip() == _S and re.fullmatch(r"0?[0-7]{3,4}", e.literal.strip()):
2458
+ return int(e.literal.strip(), 8)
2459
+ return None
2460
+ total = 0
2461
+ for part in code.split("|"):
2462
+ part = part.strip()
2463
+ m = _MODE_NUMBER.match(part)
2464
+ if m:
2465
+ if m.group(1) or m.group(2):
2466
+ total |= int(m.group(1) or m.group(2), 8)
2467
+ else:
2468
+ total |= int(m.group(3))
2469
+ continue
2470
+ name = re.split(r"[.\s]", part)[-1] if part else ""
2471
+ if name in _STAT_BITS and re.fullmatch(r"[\w.]{1,64}", part):
2472
+ total |= _STAT_BITS[name]
2473
+ continue
2474
+ return None
2475
+ return total
2476
+
2477
+
2478
+ _WW_JVM = (
2479
+ _Pat(
2480
+ _JVM,
2481
+ re.compile(r"\.\s*setWritable\s*\(\s*true\s*,\s*false\s*\)"),
2482
+ "File made writable by every user",
2483
+ ),
2484
+ _Pat(
2485
+ _JVM,
2486
+ re.compile(
2487
+ r"\bPosixFilePermissions\s*\.\s*fromString\s*\(\s*\"[r-][w-][xsS-][r-][w-][xsS-][r-]w[x-]\"\s*\)"
2488
+ ),
2489
+ "Permissions let every user write the file",
2490
+ view="text",
2491
+ ),
2492
+ _Pat(
2493
+ _JVM,
2494
+ re.compile(r"\b(?:PosixFilePermission\s*\.\s*)?OTHERS_WRITE\b"),
2495
+ "Permissions let every user write the file",
2496
+ requires=re.compile(
2497
+ r"\b(?:add|addAll|of|asList|setOf|mutableSetOf|setPosixFilePermissions)\s*\("
2498
+ ),
2499
+ unless=re.compile(r"\b(?:remove|removeAll|contains|minus)\s*\(|-=|\bimport\b"),
2500
+ ),
2501
+ )
2502
+
2503
+
2504
+ def _shell_mode_ww(tok: str) -> bool:
2505
+ if re.fullmatch(r"[0-7]{1,4}", tok):
2506
+ return _world_writable(int(tok, 8))
2507
+ sticky = False
2508
+ writable = False
2509
+ for clause in tok.split(","):
2510
+ m = re.fullmatch(r"([ugoa]{0,4})((?:[-+=][rwxXstugo]{0,8}){1,4})", clause)
2511
+ if not m:
2512
+ return False
2513
+ who = m.group(1)
2514
+ for op in re.findall(r"[-+=][rwxXstugo]{0,8}", m.group(2)):
2515
+ if op[0] in "+=" and "t" in op:
2516
+ sticky = True
2517
+ if op[0] in "+=" and "w" in op and ("o" in who or "a" in who):
2518
+ writable = True
2519
+ return writable and not sticky
2520
+
2521
+
2522
+ def _ww_shell(f: _File) -> Iterator[Hit]:
2523
+ for stmt in f.statements():
2524
+ view = f.view(stmt)
2525
+ for c in _SHELL_COMMAND.finditer(view.code):
2526
+ command = c.group(1)
2527
+ if command == "curl":
2528
+ continue
2529
+ tokens = _shell_tokens(view.code, c.end())
2530
+ found: tuple[int, str] | None = None
2531
+ if command == "chmod":
2532
+ for pos, tok in tokens:
2533
+ if tok.startswith("--") or re.fullmatch(r"-[Rvfch]{1,5}", tok):
2534
+ continue
2535
+ if _shell_mode_ww(tok):
2536
+ found = (pos, tok)
2537
+ break
2538
+ else:
2539
+ for i, (pos, tok) in enumerate(tokens):
2540
+ value = None
2541
+ if tok in ("-m", "-pm", "-mp", "-Dm") and i + 1 < len(tokens):
2542
+ pos, value = tokens[i + 1]
2543
+ elif tok.startswith("--mode="):
2544
+ value = tok[7:]
2545
+ elif re.fullmatch(r"-m[0-7]{3,4}", tok):
2546
+ value = tok[2:]
2547
+ if value is not None:
2548
+ if _shell_mode_ww(value):
2549
+ found = (pos, value)
2550
+ break
2551
+ if found is not None:
2552
+ hit = f.stmt_hit(
2553
+ view,
2554
+ found[0],
2555
+ f"{command} mode {found[1]} lets every user write",
2556
+ f"{command} {found[1]}",
2557
+ )
2558
+ if hit is not None:
2559
+ yield hit
2560
+ break
2561
+
2562
+
2563
+ def _ww_text(f: _File) -> Iterator[Hit]:
2564
+ sink = _WW_SINKS.get(f.lang)
2565
+ if sink is None:
2566
+ return
2567
+ for stmt in f.statements():
2568
+ view = f.view(stmt)
2569
+ for m in sink.finditer(view.code):
2570
+ parsed = _call_args(f, view, m.end() - 1)
2571
+ if parsed is None:
2572
+ continue
2573
+ for a, b in reversed(parsed[1]):
2574
+ mode = _text_mode(f, view, a, b)
2575
+ if mode is None:
2576
+ continue
2577
+ if _world_writable(mode):
2578
+ hit = f.stmt_hit(
2579
+ view,
2580
+ m.start(),
2581
+ f"chmod to {mode:o} lets every user write the file",
2582
+ f"chmod {mode:o}",
2583
+ )
2584
+ if hit is not None:
2585
+ yield hit
2586
+ break
2587
+
2588
+
2589
+ @rule(
2590
+ id="security/world-writable",
2591
+ severity="error",
2592
+ title="File or directory made world-writable",
2593
+ languages=_CODE | _SHELL,
2594
+ rationale=(
2595
+ "Any local user or process can replace or change a world-writable file, which turns a "
2596
+ "config, script or binary into a way to run code as its owner."
2597
+ ),
2598
+ hint="Grant write access to the owner (and group) only, e.g. 0o755 or 0o644.",
2599
+ tags={"security", "cwe-732"},
2600
+ )
2601
+ def world_writable(ctx: FileContext) -> Iterator[Hit]:
2602
+ """Explicit permission changes that give others write access.
2603
+
2604
+ ``os.chmod``/``Path.chmod`` (Python), ``fs.chmod*`` (JS/TS), ``os.Chmod``
2605
+ and ``File.Chmod`` (Go) with a mode whose others-write bit is set (octal,
2606
+ decimal, ``stat`` constants combined with ``|``, ``os.ModePerm``, string
2607
+ modes); ``setWritable(true, false)``, ``PosixFilePermissions.fromString``
2608
+ with others-write and ``OTHERS_WRITE`` added to a set (Java/Kotlin); shell
2609
+ ``chmod`` with an octal or symbolic mode (``o+w``, ``a+w``, ``a=rwx``) and
2610
+ ``mkdir -m``/``install -m``.
2611
+
2612
+ Ignores: modes with the sticky bit (``1777``: a shared ``/tmp``-style
2613
+ directory), creation modes the umask still applies to (``os.makedirs``,
2614
+ ``os.open``, ``os.WriteFile``, ``fs.mkdir``), ``chmod +w`` without a
2615
+ who-part (umask applies), quoted or variable modes, ``OTHERS_WRITE`` being
2616
+ removed or checked, and chmod inside workflow or Dockerfile scripts (the
2617
+ ``ci`` and ``docker`` packs).
2618
+ """
2619
+ f = _File(ctx)
2620
+ if f.lang == "shell":
2621
+ yield from _ww_shell(f)
2622
+ return
2623
+ if f.lang == "python":
2624
+ tree = _py_tree(f)
2625
+ if tree is not None:
2626
+ yield from _ww_python(f, tree)
2627
+ return
2628
+ yield from _ww_text(f)
2629
+ yield from _scan(f, _WW_JVM)
2630
+ if f.incomplete:
2631
+ raise PartialCoverage("a call too long to read whole")
2632
+
2633
+
2634
+ # --- security/archive-extraction -----------------------------------------------------------------
2635
+
2636
+
2637
+ def _archive_unguarded(f: _File, _view: _View, _m: re.Match[str]) -> bool:
2638
+ src = f.source
2639
+ if f.lang == "go":
2640
+ return not any(s in src for s in ("HasPrefix(", "IsLocal(", "filepath.Rel(", "securejoin"))
2641
+ if f.lang in _JVM:
2642
+ return not (
2643
+ "startsWith(" in src
2644
+ and any(
2645
+ s in src
2646
+ for s in ("normalize()", "canonicalPath", "getCanonicalPath(", "toRealPath(")
2647
+ )
2648
+ )
2649
+ if f.lang in _JS:
2650
+ return not (
2651
+ "startsWith(" in src
2652
+ and any(s in src for s in ("path.resolve(", "path.normalize(", "resolve("))
2653
+ )
2654
+ return True
2655
+
2656
+
2657
+ def _tar_receiver(_f: _File, view: _View, m: re.Match[str]) -> bool:
2658
+ receiver = view.code[max(0, m.start() - 64) : m.start()]
2659
+ return "zip" not in receiver.lower().rsplit(None, 1)[-1] if receiver.strip() else True
2660
+
2661
+
2662
+ _ARCHIVE_PATS = (
2663
+ _Pat(
2664
+ _PY,
2665
+ re.compile(r"\.\s*extract(?:all)?\s*\("),
2666
+ "tar extraction without a filter can write outside the target directory",
2667
+ unless=re.compile(r"\bfilter\s*="),
2668
+ file_has=("tarfile",),
2669
+ check=_tar_receiver,
2670
+ ),
2671
+ _Pat(
2672
+ _PY,
2673
+ re.compile(r"\bshutil\.unpack_archive\s*\("),
2674
+ "unpack_archive without a filter can write outside the target directory",
2675
+ unless=re.compile(r"\bfilter\s*="),
2676
+ ),
2677
+ _Pat(
2678
+ _JS,
2679
+ re.compile(r"\.\s*extractAllTo\s*\("),
2680
+ "Archive extracted without checking entry paths (zip slip)",
2681
+ file_has=("adm-zip",),
2682
+ ),
2683
+ _Pat(
2684
+ _JS,
2685
+ re.compile(
2686
+ r"\bpath\s*\.\s*(?:join|resolve)\s*\([^;]{0,300}?\b\w{1,32}\s*\.\s*(?:entryName|fileName|path)\b"
2687
+ ),
2688
+ "Archive entry name used as a path without a containment check (zip slip)",
2689
+ file_has=(
2690
+ "adm-zip",
2691
+ "unzipper",
2692
+ "yauzl",
2693
+ "tar-stream",
2694
+ "jszip",
2695
+ "decompress",
2696
+ "node-stream-zip",
2697
+ ),
2698
+ check=_archive_unguarded,
2699
+ ),
2700
+ _Pat(
2701
+ _GO,
2702
+ re.compile(r"\b(?:filepath|path)\.Join\s*\([^;]{0,300}?\b\w{1,32}\.Name\b(?!\s*\()"),
2703
+ "Archive entry name used as a path without a containment check (zip slip)",
2704
+ file_has=('"archive/zip"', '"archive/tar"'),
2705
+ check=_archive_unguarded,
2706
+ ),
2707
+ _Pat(
2708
+ _JVM,
2709
+ re.compile(
2710
+ r"(?:\bnew\s+File(?:OutputStream)?\s*\(|(?<![\w.])File\s*\(|\bPaths\s*\.\s*get\s*\(|\bPath\s*\.\s*of\s*\(|\.\s*resolve\s*\()[^;]{0,300}?(?:\.\s*getName\s*\(\s*\)|\b\w{0,24}[eE]ntry\s*\.\s*name\b)"
2711
+ ),
2712
+ "Archive entry name used as a path without a containment check (zip slip)",
2713
+ file_has=("ZipEntry", "ArchiveEntry", "JarEntry", "ZipInputStream", "ZipFile"),
2714
+ check=_archive_unguarded,
2715
+ ),
2716
+ )
2717
+
2718
+
2719
+ @rule(
2720
+ id="security/archive-extraction",
2721
+ severity="warning",
2722
+ title="Archive extracted without path checks",
2723
+ languages=_CODE,
2724
+ rationale=(
2725
+ "Archive entries may be named ../../something or be absolute paths or links, so "
2726
+ "extracting them unchecked can overwrite files outside the target (zip slip)."
2727
+ ),
2728
+ hint=(
2729
+ "Use a safe extraction filter (tarfile filter='data') or check each resolved "
2730
+ "path stays inside the target."
2731
+ ),
2732
+ tags={"security", "cwe-22"},
2733
+ )
2734
+ def archive_extraction(ctx: FileContext) -> Iterator[Hit]:
2735
+ """Extraction or entry-name joins with no path containment.
2736
+
2737
+ Python: ``tarfile`` ``extractall``/``extract`` and ``shutil.unpack_archive``
2738
+ without ``filter=``. JS/TS: adm-zip ``extractAllTo``, ``path.join`` with an
2739
+ entry's ``entryName``/``fileName``/``path``. Go: ``filepath.Join`` with an
2740
+ archive header's ``Name``. Java/Kotlin: ``new File``/``Paths.get``/
2741
+ ``resolve`` with an entry's ``getName()``.
2742
+
2743
+ Ignores: ``zipfile`` (it strips ``..`` and absolute paths), receivers
2744
+ named like zip files in tar-using modules, and files that check the
2745
+ result (``HasPrefix``/``IsLocal``/``filepath.Rel`` in Go, ``normalize``
2746
+ or ``getCanonicalPath`` plus ``startsWith`` in Java, ``resolve`` plus
2747
+ ``startsWith`` in JS).
2748
+ """
2749
+ yield from _scan(_File(ctx), _ARCHIVE_PATS)
2750
+
2751
+
2752
+ # --- security/xss-sink ---------------------------------------------------------------------------
2753
+
2754
+ _SANITIZED = re.compile(
2755
+ r"\b(?:DOMPurify|sanitize\w{0,20}|escape\w{0,20}|purify|xss|encodeHTML|htmlEscape|textContent)\b",
2756
+ re.I,
2757
+ )
2758
+
2759
+
2760
+ def _xss_rhs(f: _File, view: _View, m: re.Match[str]) -> bool:
2761
+ rest = view.code[m.end() :]
2762
+ end = len(rest.rstrip().rstrip(";"))
2763
+ if _SANITIZED.search(view.text[m.end() : m.end() + end]):
2764
+ return False
2765
+ e = _expr(f, view, m.end(), m.end() + end)
2766
+ return _kind(e) is not None
2767
+
2768
+
2769
+ def _xss_arg(index: int) -> Callable[[_File, _View, re.Match[str]], bool]:
2770
+ def check(f: _File, view: _View, m: re.Match[str]) -> bool:
2771
+ parsed = _call_args(f, view, m.end() - 1)
2772
+ if parsed is None or len(parsed[1]) <= index:
2773
+ return False
2774
+ a, b = parsed[1][index]
2775
+ if _SANITIZED.search(view.text[a:b]):
2776
+ return False
2777
+ return _kind(_expr(f, view, a, b)) is not None
2778
+
2779
+ return check
2780
+
2781
+
2782
+ def _xss_html_prop(f: _File, view: _View, m: re.Match[str]) -> bool:
2783
+ rest = view.code[m.end() : m.end() + 400]
2784
+ close = re.search(r"\}", rest)
2785
+ end = m.end() + (close.start() if close else len(rest))
2786
+ if _SANITIZED.search(view.text[m.end() : end]):
2787
+ return False
2788
+ return _kind(_expr(f, view, m.end(), end)) is not None
2789
+
2790
+
2791
+ _XSS_PATS = (
2792
+ _Pat(
2793
+ _JS,
2794
+ re.compile(r"\.\s*(?:innerHTML|outerHTML)\s*\+?=(?!=)"),
2795
+ "HTML built from a value is written to the DOM",
2796
+ check=_xss_rhs,
2797
+ ),
2798
+ _Pat(
2799
+ _JS,
2800
+ re.compile(r"\.\s*insertAdjacentHTML\s*\("),
2801
+ "HTML built from a value is written to the DOM",
2802
+ check=_xss_arg(1),
2803
+ ),
2804
+ _Pat(
2805
+ _JS,
2806
+ re.compile(r"\bdocument\s*\.\s*write(?:ln)?\s*\("),
2807
+ "HTML built from a value is written to the document",
2808
+ check=_xss_arg(0),
2809
+ ),
2810
+ _Pat(
2811
+ _JS,
2812
+ re.compile(r"\bdangerouslySetInnerHTML\s*=\s*\{\s*\{\s*__html\s*:"),
2813
+ "Raw HTML rendered from a value",
2814
+ check=_xss_html_prop,
2815
+ ),
2816
+ _Pat(
2817
+ _JS,
2818
+ re.compile(r"(?:\$|\bjQuery)\s*\([^;]{0,200}?\)\s*\.\s*html\s*\("),
2819
+ "HTML built from a value is written to the DOM",
2820
+ check=_xss_arg(0),
2821
+ ),
2822
+ _Pat(
2823
+ _PY,
2824
+ re.compile(
2825
+ r"(?<![\w.])(?:mark_safe|Markup|SafeString|SafeText)\s*\(|\bmarkupsafe\.Markup\s*\("
2826
+ ),
2827
+ "Value marked safe HTML skips escaping",
2828
+ check=_xss_arg(0),
2829
+ ),
2830
+ _Pat(
2831
+ _GO,
2832
+ re.compile(r"\btemplate\.(?:HTML|JS|HTMLAttr|JSStr|CSS|URL|Srcset)\s*\("),
2833
+ "Value converted to trusted template content skips escaping",
2834
+ check=_xss_arg(0),
2835
+ ),
2836
+ )
2837
+ _TEMPLATE_RAW = re.compile(r"\bv-html\s*=|\{@html\s")
2838
+
2839
+
2840
+ @rule(
2841
+ id="security/xss-sink",
2842
+ severity="warning",
2843
+ title="Value written as raw HTML",
2844
+ languages=_PY | _JS | _GO,
2845
+ rationale=(
2846
+ "HTML built from data and inserted without escaping lets that data run script "
2847
+ "in the page (XSS)."
2848
+ ),
2849
+ hint="Insert text (textContent, template escaping) or sanitize the HTML first.",
2850
+ tags={"security", "cwe-79"},
2851
+ )
2852
+ def xss_sink(ctx: FileContext) -> Iterator[Hit]:
2853
+ """Raw-HTML sinks that receive a non-literal value.
2854
+
2855
+ JS/TS: ``innerHTML``/``outerHTML`` assignments, ``insertAdjacentHTML``,
2856
+ ``document.write``, React ``dangerouslySetInnerHTML``, jQuery ``.html(x)``,
2857
+ Vue ``v-html`` and Svelte ``{@html}`` in single-file components. Python:
2858
+ ``mark_safe``, ``Markup``, ``SafeString``. Go: ``template.HTML``/``JS``/
2859
+ ``URL`` conversions.
2860
+
2861
+ Ignores: literal markup and constants, values passed through a
2862
+ sanitizer or escaper (DOMPurify, ``sanitize*``, ``escape*``),
2863
+ ``format_html``, and Java/Kotlin (server templates are not read).
2864
+ """
2865
+ f = _File(ctx)
2866
+ yield from _scan(f, _XSS_PATS)
2867
+ if ctx.path.endswith((".vue", ".svelte")):
2868
+ for number, text in ctx.changed_lines():
2869
+ m = _TEMPLATE_RAW.search(text)
2870
+ if m:
2871
+ yield Hit(
2872
+ number,
2873
+ column=text.column(m.start()),
2874
+ message="Raw HTML rendered from a value",
2875
+ evidence=_norm(m.group(0)),
2876
+ )
2877
+
2878
+
2879
+ # --- security/autoescape-disabled ----------------------------------------------------------------
2880
+
2881
+
2882
+ def _jinja_env_unescaped(f: _File, view: _View, m: re.Match[str]) -> bool:
2883
+ parsed = _call_args(f, view, m.end() - 1)
2884
+ if parsed is None:
2885
+ return False
2886
+ inside = view.code[m.end() : parsed[0]]
2887
+ return "autoescape" not in inside and "**" not in inside
2888
+
2889
+
2890
+ _AUTOESCAPE_PATS = (
2891
+ _Pat(_PY, re.compile(r"\bautoescape\s*=\s*False\b"), "Template autoescaping is turned off"),
2892
+ _Pat(
2893
+ _PY,
2894
+ re.compile(r"[\"']autoescape[\"']\s*:\s*False\b"),
2895
+ "Template autoescaping is turned off",
2896
+ view="text",
2897
+ ),
2898
+ _Pat(
2899
+ _PY,
2900
+ re.compile(r"(?<![\w.])(?:jinja2\s*\.\s*)?Environment\s*\("),
2901
+ "Jinja Environment without autoescape renders HTML unescaped",
2902
+ file_has=("jinja2",),
2903
+ check=lambda f, v, m: (
2904
+ (".html" in f.source or '.htm"' in f.source) and _jinja_env_unescaped(f, v, m)
2905
+ ),
2906
+ ),
2907
+ _Pat(
2908
+ _JS,
2909
+ re.compile(r"\bautoescape\s*:\s*false\b|\bnoEscape\s*:\s*true\b"),
2910
+ "Template autoescaping is turned off",
2911
+ ),
2912
+ _Pat(
2913
+ _JVM,
2914
+ re.compile(r"\bDISABLE_AUTO_ESCAPING_POLICY\b"),
2915
+ "Template autoescaping is turned off",
2916
+ check=_not_import,
2917
+ ),
2918
+ )
2919
+
2920
+
2921
+ @rule(
2922
+ id="security/autoescape-disabled",
2923
+ severity="warning",
2924
+ title="Template autoescaping disabled",
2925
+ languages=_PY | _JS | _JVM,
2926
+ rationale=(
2927
+ "With autoescaping off every value a template prints is raw HTML, so any "
2928
+ "unescaped value is an XSS."
2929
+ ),
2930
+ hint="Keep autoescaping on (select_autoescape) and mark trusted markup explicitly.",
2931
+ tags={"security", "cwe-79"},
2932
+ )
2933
+ def autoescape_disabled(ctx: FileContext) -> Iterator[Hit]:
2934
+ """Template engines configured not to escape.
2935
+
2936
+ Python: ``autoescape=False``, ``"autoescape": False`` (Django
2937
+ ``TEMPLATES`` options), and a ``jinja2.Environment`` without
2938
+ ``autoescape`` in a module that loads ``.html`` templates. JS/TS:
2939
+ Nunjucks ``autoescape: false``, Handlebars ``noEscape: true``.
2940
+ Java/Kotlin: FreeMarker ``DISABLE_AUTO_ESCAPING_POLICY``.
2941
+
2942
+ Ignores: Jinja environments for non-HTML output (no ``.html`` in the
2943
+ module), environments built from ``**options``, and template files
2944
+ themselves (``{% autoescape off %}``).
2945
+ """
2946
+ yield from _scan(_File(ctx), _AUTOESCAPE_PATS)
2947
+
2948
+
2949
+ # --- security/csrf-disabled ----------------------------------------------------------------------
2950
+
2951
+ _CSRF_PATS = (
2952
+ _Pat(
2953
+ _PY,
2954
+ re.compile(r"@\s*csrf_exempt\b|@\s*csrf\s*\.\s*exempt\b|\bcsrf\s*\.\s*exempt\s*\("),
2955
+ "CSRF protection is turned off for this view",
2956
+ ),
2957
+ _Pat(
2958
+ _PY,
2959
+ re.compile(r"\bWTF_CSRF_(?:ENABLED|CHECK_DEFAULT)\s*=\s*False\b"),
2960
+ "CSRF protection is turned off",
2961
+ ),
2962
+ _Pat(
2963
+ _PY,
2964
+ re.compile(
2965
+ r"\bconfig\s*\[\s*[\"']WTF_CSRF_(?:ENABLED|CHECK_DEFAULT)[\"']\s*\]\s*=\s*False\b"
2966
+ ),
2967
+ "CSRF protection is turned off",
2968
+ view="text",
2969
+ ),
2970
+ _Pat(
2971
+ _JVM,
2972
+ re.compile(
2973
+ r"\.\s*csrf\s*\(\s*\)\s*\.\s*disable\s*\(\s*\)|\bcsrf\s*\(\s*(?:\w{1,40}\s*::\s*disable|\w{1,20}\s*->\s*\w{1,20}\s*\.\s*disable\s*\(\s*\))\s*\)"
2974
+ ),
2975
+ "CSRF protection is turned off",
2976
+ ),
2977
+ _Pat(
2978
+ frozenset({"kotlin"}),
2979
+ re.compile(r"\bcsrf\s*\{[\s/*]{0,200}(?:it\s*\.\s*)?disable\s*(?:\(\s*\)|=\s*true)"),
2980
+ "CSRF protection is turned off",
2981
+ extend=240,
2982
+ ),
2983
+ _Pat(
2984
+ _JS,
2985
+ re.compile(r"\bcheckOrigin\s*:\s*false\b|\bcsrf\s*:\s*false\b"),
2986
+ "CSRF protection is turned off",
2987
+ ),
2988
+ _Pat(
2989
+ _GO,
2990
+ re.compile(r"\bcsrf\.UnsafeSkipCheck\s*\("),
2991
+ "CSRF protection is skipped for this request",
2992
+ ),
2993
+ )
2994
+
2995
+
2996
+ @rule(
2997
+ id="security/csrf-disabled",
2998
+ severity="warning",
2999
+ title="CSRF protection disabled",
3000
+ languages=_CODE,
3001
+ rationale=(
3002
+ "Without CSRF checks another site can make a logged-in user's browser send "
3003
+ "state-changing requests."
3004
+ ),
3005
+ hint=(
3006
+ "Keep CSRF checks on for cookie-authenticated endpoints; disable them only for "
3007
+ "token-authenticated APIs."
3008
+ ),
3009
+ tags={"security", "cwe-352"},
3010
+ )
3011
+ def csrf_disabled(ctx: FileContext) -> Iterator[Hit]:
3012
+ """CSRF protection switched off.
3013
+
3014
+ Django ``@csrf_exempt``, Flask-WTF ``@csrf.exempt`` and
3015
+ ``WTF_CSRF_ENABLED = False``; Spring Security ``csrf().disable()``,
3016
+ ``csrf(AbstractHttpConfigurer::disable)``, ``csrf { disable() }``;
3017
+ SvelteKit ``checkOrigin: false`` and ``csrf: false`` options; gorilla
3018
+ ``csrf.UnsafeSkipCheck``.
3019
+
3020
+ Ignores: removed middleware (removals are not read), framework defaults,
3021
+ and ``CSRF_COOKIE_*`` settings (``insecure-cookie``).
3022
+ """
3023
+ yield from _scan(_File(ctx), _CSRF_PATS)
3024
+
3025
+
3026
+ # --- security/insecure-cookie --------------------------------------------------------------------
3027
+
3028
+ _COOKIE_CONTEXT = re.compile(r"ookie", re.I)
3029
+
3030
+ _COOKIE_PATS = (
3031
+ _Pat(
3032
+ _PY,
3033
+ re.compile(r"\bset_cookie\s*\([^;]{0,600}?\b(?:secure|httponly)\s*=\s*False\b"),
3034
+ "Cookie set without Secure or HttpOnly",
3035
+ ),
3036
+ _Pat(
3037
+ _PY,
3038
+ re.compile(
3039
+ r"\b(?:SESSION|CSRF|REMEMBER|LANGUAGE)_COOKIE_(?:SECURE|HTTPONLY)\s*=\s*False\b"
3040
+ ),
3041
+ "Session cookie sent without Secure or HttpOnly",
3042
+ ),
3043
+ _Pat(
3044
+ _PY,
3045
+ re.compile(
3046
+ r"\bconfig\s*\[\s*[\"'](?:SESSION|REMEMBER)_COOKIE_(?:SECURE|HTTPONLY)[\"']\s*\]\s*=\s*False\b"
3047
+ ),
3048
+ "Session cookie sent without Secure or HttpOnly",
3049
+ view="text",
3050
+ ),
3051
+ _Pat(
3052
+ _JS,
3053
+ re.compile(r"\b(?:secure|httpOnly|httponly)\s*:\s*false\b"),
3054
+ "Cookie set without Secure or HttpOnly",
3055
+ requires=_COOKIE_CONTEXT,
3056
+ ),
3057
+ _Pat(
3058
+ _GO,
3059
+ re.compile(r"\b(?:Secure|HttpOnly)\s*(?::|=)\s*false\b"),
3060
+ "Cookie set without Secure or HttpOnly",
3061
+ requires=_COOKIE_CONTEXT,
3062
+ ),
3063
+ _Pat(
3064
+ _JVM,
3065
+ re.compile(
3066
+ r"\.\s*(?:setSecure|setHttpOnly|secure|httpOnly)\s*\(\s*false\s*\)|\b(?:isSecure|isHttpOnly)\s*=\s*false\b"
3067
+ ),
3068
+ "Cookie set without Secure or HttpOnly",
3069
+ requires=_COOKIE_CONTEXT,
3070
+ ),
3071
+ )
3072
+
3073
+
3074
+ @rule(
3075
+ id="security/insecure-cookie",
3076
+ severity="warning",
3077
+ title="Cookie without Secure or HttpOnly",
3078
+ languages=_CODE,
3079
+ rationale=(
3080
+ "A cookie without Secure travels over plain HTTP, and one without HttpOnly can be read "
3081
+ "by any script on the page, so session cookies leak."
3082
+ ),
3083
+ hint="Set Secure and HttpOnly (and SameSite) on session and authentication cookies.",
3084
+ tags={"security", "cwe-614", "cwe-1004"},
3085
+ )
3086
+ def insecure_cookie(ctx: FileContext) -> Iterator[Hit]:
3087
+ """Cookies or cookie settings that explicitly turn Secure or HttpOnly off.
3088
+
3089
+ ``set_cookie(..., secure=False)``, Django/Flask ``SESSION_COOKIE_SECURE``/
3090
+ ``HTTPONLY``, ``CSRF_COOKIE_SECURE`` and ``REMEMBER_COOKIE_*`` set to
3091
+ ``False``; ``secure: false``/``httpOnly: false`` in cookie options
3092
+ (JS/TS); ``Secure: false``/``HttpOnly: false`` on Go cookies;
3093
+ ``setSecure(false)``/``setHttpOnly(false)`` and Spring
3094
+ ``ResponseCookie.secure(false)`` (Java/Kotlin).
3095
+
3096
+ Ignores: cookies that merely omit the flags (framework defaults differ),
3097
+ ``secure: false`` outside a cookie context (SMTP, database options) and
3098
+ values read from configuration.
3099
+ """
3100
+ yield from _scan(_File(ctx), _COOKIE_PATS)
3101
+
3102
+
3103
+ # --- security/permissive-cors --------------------------------------------------------------------
3104
+
3105
+ _CREDENTIALS = re.compile(
3106
+ r"\b(?:credentials\s*:\s*true|supports_credentials\s*=\s*True|allow_credentials\s*=\s*True|AllowCredentials\s*:\s*true|allowCredentials\s*\(\s*true\s*\)|allowCredentials\s*=\s*\"true\"|allowCredentials\s*=\s*true)\b"
3107
+ )
3108
+ _REFLECT = re.compile(r"(?i:origin)")
3109
+
3110
+ _CORS_PATS = (
3111
+ _Pat(
3112
+ _PY,
3113
+ re.compile(r"\bCORS_(?:ORIGIN_ALLOW_ALL|ALLOW_ALL_ORIGINS)\s*=\s*True\b"),
3114
+ "CORS allows every origin",
3115
+ ),
3116
+ _Pat(
3117
+ _PY,
3118
+ re.compile(r"(?<![\w.])CORS\s*\("),
3119
+ "CORS allows every origin with credentials",
3120
+ requires=re.compile(r"\bsupports_credentials\s*=\s*True\b"),
3121
+ unless=re.compile(r"\b(?:origins|resources)\s*=\s*(?![\[\"' ]{0,3}\*)"),
3122
+ ),
3123
+ _Pat(
3124
+ _PY,
3125
+ re.compile(r"\ballow_origins\s*=\s*\[\s*[\"']\*[\"']\s*\]"),
3126
+ "CORS allows every origin with credentials",
3127
+ view="text",
3128
+ requires=_CREDENTIALS,
3129
+ ),
3130
+ _Pat(
3131
+ _PY,
3132
+ re.compile(
3133
+ r"\bheaders\s*\[\s*[\"']Access-Control-Allow-Origin[\"']\s*\]\s*=\s*request\.headers(?:\.get\s*\(|\s*\[)\s*[\"']origin[\"']",
3134
+ re.I,
3135
+ ),
3136
+ "CORS reflects the request's Origin",
3137
+ view="text",
3138
+ ),
3139
+ _Pat(
3140
+ _JS,
3141
+ re.compile(r"\b(?:cors|enableCors)\s*\("),
3142
+ "CORS reflects any origin with credentials",
3143
+ requires=re.compile(
3144
+ r"\borigin\s*:\s*(?:true|[\"'`]\*[\"'`]|\(\s*\w{0,32}\s*,\s*(\w{1,32})\s*\)\s*=>\s*\1\s*\(\s*null\s*,\s*true\s*\))"
3145
+ ),
3146
+ unless=re.compile(r"\bcredentials\s*:\s*false\b"),
3147
+ ),
3148
+ _Pat(
3149
+ _JS,
3150
+ re.compile(
3151
+ r"\.\s*(?:set|setHeader|header|append)\s*\(\s*[\"'`]Access-Control-Allow-Origin[\"'`]\s*,\s*(?:req|request|ctx\.request)\s*\.\s*(?:headers\s*(?:\.\s*origin|\[\s*[\"'`]origin[\"'`]\s*\])|get\s*\(\s*[\"'`]origin[\"'`]\s*\)|header\s*\(\s*[\"'`]origin[\"'`]\s*\))",
3152
+ re.I,
3153
+ ),
3154
+ "CORS reflects the request's Origin",
3155
+ view="text",
3156
+ ),
3157
+ _Pat(
3158
+ _GO,
3159
+ re.compile(
3160
+ r"\bAllowAllOrigins\s*:\s*true\b|\bAllowOriginFunc\s*:\s*func\s*\([^)]{0,80}\)\s*bool\s*\{\s*return\s+true\b"
3161
+ ),
3162
+ "CORS allows every origin",
3163
+ ),
3164
+ _Pat(
3165
+ _GO,
3166
+ re.compile(r"\bAllowedOrigins\s*:\s*\[\]string\s*\{\s*\"\*\"\s*\}"),
3167
+ "CORS allows every origin with credentials",
3168
+ view="text",
3169
+ requires=_CREDENTIALS,
3170
+ ),
3171
+ _Pat(
3172
+ _GO,
3173
+ re.compile(
3174
+ r"\.\s*(?:Set|Add)\s*\(\s*\"Access-Control-Allow-Origin\"\s*,\s*r\s*\.\s*Header\s*\.\s*Get\s*\(\s*\"Origin\"\s*\)",
3175
+ re.I,
3176
+ ),
3177
+ "CORS reflects the request's Origin",
3178
+ view="text",
3179
+ ),
3180
+ _Pat(
3181
+ _JVM,
3182
+ re.compile(r"\ballowedOrigin(?:Pattern)?s\s*\(\s*\"\*\"\s*\)"),
3183
+ "CORS allows every origin with credentials",
3184
+ view="text",
3185
+ requires=_CREDENTIALS,
3186
+ ),
3187
+ _Pat(
3188
+ _JVM,
3189
+ re.compile(r"@\s*CrossOrigin\b"),
3190
+ "CORS allows every origin with credentials",
3191
+ requires=re.compile(r"allowCredentials\s*=\s*\"true\""),
3192
+ unless=re.compile(r"\b(?:origins|value|originPatterns)\s*=\s*(?:\{\s*)?\"(?!\*)"),
3193
+ ),
3194
+ _Pat(
3195
+ _JVM,
3196
+ re.compile(
3197
+ r"\.\s*(?:setHeader|addHeader)\s*\(\s*\"Access-Control-Allow-Origin\"\s*,\s*\w{1,32}\s*\.\s*getHeader\s*\(\s*\"Origin\"\s*\)",
3198
+ re.I,
3199
+ ),
3200
+ "CORS reflects the request's Origin",
3201
+ view="text",
3202
+ ),
3203
+ )
3204
+
3205
+
3206
+ @rule(
3207
+ id="security/permissive-cors",
3208
+ severity="warning",
3209
+ title="CORS open to every origin",
3210
+ languages=_CODE,
3211
+ rationale=(
3212
+ "A CORS policy that reflects any Origin or allows every origin with credentials lets "
3213
+ "any website read authenticated responses."
3214
+ ),
3215
+ hint="List the allowed origins explicitly.",
3216
+ tags={"security", "cwe-942"},
3217
+ )
3218
+ def permissive_cors(ctx: FileContext) -> Iterator[Hit]:
3219
+ """CORS that reflects the request's Origin, or allows any origin with credentials.
3220
+
3221
+ Reflection: ``Access-Control-Allow-Origin`` set from the request's
3222
+ ``Origin`` header (Python, JS/TS, Go, Java/Kotlin), cors() with
3223
+ ``origin: true`` or a callback that accepts everything. Any origin plus
3224
+ credentials in one call: flask-cors ``supports_credentials=True`` without
3225
+ ``origins``, FastAPI ``allow_origins=["*"]`` with
3226
+ ``allow_credentials=True``, rs/cors, Spring ``allowedOrigins("*")`` and
3227
+ ``@CrossOrigin(allowCredentials = "true")``. Global switches: Django
3228
+ ``CORS_ALLOW_ALL_ORIGINS = True``, gin ``AllowAllOrigins: true``.
3229
+
3230
+ Ignores: a plain ``*`` without credentials (public APIs and assets),
3231
+ explicit origin lists, and header pairs set in separate statements.
3232
+ """
3233
+ yield from _scan(_File(ctx), _CORS_PATS)
3234
+
3235
+
3236
+ # --- security/debug-enabled ----------------------------------------------------------------------
3237
+
3238
+ _DEV_PATH = re.compile(
3239
+ r"(?:^|[/_.-])(?:dev|devel|development|local|debug|test|tests|testing|example|examples|sample)(?:[/_.-]|$)",
3240
+ re.I,
3241
+ )
3242
+
3243
+
3244
+ def _module_level(f: _File, view: _View, _m: re.Match[str]) -> bool:
3245
+ return f.ctx.line_index.position(view.stmt.start)[1] == 1 and not _DEV_PATH.search(f.ctx.path)
3246
+
3247
+
3248
+ _DEBUG_PATS = (
3249
+ _Pat(
3250
+ _PY,
3251
+ re.compile(r"\A\s*DEBUG\s*=\s*True\b"),
3252
+ "DEBUG = True in settings exposes tracebacks and internals",
3253
+ check=_module_level,
3254
+ ),
3255
+ _Pat(
3256
+ _PY,
3257
+ re.compile(r"\b(?!asyncio\b)\w{1,40}\s*\.\s*run\s*\([^;]{0,600}?\bdebug\s*=\s*True\b"),
3258
+ "App runs with the debugger enabled",
3259
+ ),
3260
+ _Pat(
3261
+ _PY,
3262
+ re.compile(r"\b(?:app|application|server)\s*\.\s*debug\s*=\s*True\b"),
3263
+ "App runs with debug mode enabled",
3264
+ ),
3265
+ _Pat(
3266
+ _PY,
3267
+ re.compile(r"\bconfig\s*\[\s*[\"']DEBUG[\"']\s*\]\s*=\s*True\b"),
3268
+ "App runs with debug mode enabled",
3269
+ view="text",
3270
+ ),
3271
+ _Pat(_GO, re.compile(r"\bgin\.SetMode\s*\(\s*gin\.DebugMode\s*\)"), "gin runs in debug mode"),
3272
+ _Pat(
3273
+ _GO,
3274
+ re.compile(r"(?<![\w.])_\s+\"net/http/pprof\""),
3275
+ "net/http/pprof registers debug handlers on the default mux",
3276
+ view="text",
3277
+ ),
3278
+ _Pat(
3279
+ _JVM,
3280
+ re.compile(r"@\s*EnableWebSecurity\s*\(\s*debug\s*=\s*true\s*\)"),
3281
+ "Spring Security debug mode logs requests and security details",
3282
+ ),
3283
+ )
3284
+
3285
+
3286
+ @rule(
3287
+ id="security/debug-enabled",
3288
+ severity="warning",
3289
+ title="Debug mode enabled",
3290
+ languages=_PY | _GO | _JVM,
3291
+ rationale=(
3292
+ "Debug modes show stack traces, settings and sometimes an interactive console to anyone "
3293
+ "who can reach the app."
3294
+ ),
3295
+ hint="Read debug settings from the environment and keep them off in production.",
3296
+ tags={"security", "cwe-489"},
3297
+ )
3298
+ def debug_enabled(ctx: FileContext) -> Iterator[Hit]:
3299
+ """Debug switches hard-coded on.
3300
+
3301
+ Python: module-level ``DEBUG = True`` (Django settings),
3302
+ ``app.run(debug=True)``, ``app.debug = True``, ``app.config["DEBUG"] =
3303
+ True``. Go: ``gin.SetMode(gin.DebugMode)`` and the ``net/http/pprof``
3304
+ side-effect import. Java/Kotlin: ``@EnableWebSecurity(debug = true)``.
3305
+
3306
+ Ignores: paths for development, local, test or example settings,
3307
+ ``asyncio.run(..., debug=True)``, debug flags read from the environment,
3308
+ ``DEBUG`` inside functions or classes, and JS/TS (no common
3309
+ framework-level switch).
3310
+ """
3311
+ yield from _scan(_File(ctx), _DEBUG_PATS)
3312
+
3313
+
3314
+ # --- security/weak-hash --------------------------------------------------------------------------
3315
+
3316
+ _WEAK_HASH = {
3317
+ "python": re.compile(
3318
+ r"\bhashlib\s*\.\s*(md5|sha1)\s*\(|\bhashlib\s*\.\s*new\s*\(\s*[\"'](md5|sha1)[\"']|\b(MD5|SHA)\s*\.\s*new\s*\("
3319
+ ),
3320
+ "javascript": re.compile(
3321
+ r"\bcreateHash\s*\(\s*[\"'`](md5|sha1)[\"'`]|\bCryptoJS\s*\.\s*(MD5|SHA1)\s*\(|(?<![\w$.])(md5|sha1)\s*\("
3322
+ ),
3323
+ "go": re.compile(r"\b(md5|sha1)\s*\.\s*(?:New|Sum)\s*\("),
3324
+ "java": re.compile(
3325
+ r"\bMessageDigest\s*\.\s*getInstance\s*\(\s*\"(MD5|SHA-?1)\"|\bDigestUtils\s*\.\s*(md5|sha1)(?:Hex)?\s*\(|\bHashing\s*\.\s*(md5|sha1)\s*\("
3326
+ ),
3327
+ }
3328
+ _WEAK_HASH["typescript"] = _WEAK_HASH["javascript"]
3329
+ _WEAK_HASH["kotlin"] = _WEAK_HASH["java"]
3330
+
3331
+
3332
+ @rule(
3333
+ id="security/weak-hash",
3334
+ severity="warning",
3335
+ title="MD5 or SHA-1 used for a secret",
3336
+ languages=_CODE,
3337
+ rationale=(
3338
+ "MD5 and SHA-1 are broken for collision resistance and far too fast for passwords, so "
3339
+ "they must not protect passwords, tokens or signatures."
3340
+ ),
3341
+ hint=(
3342
+ "Use a password hash (argon2, bcrypt, scrypt) for passwords and SHA-256 or HMAC "
3343
+ "for tokens and signatures."
3344
+ ),
3345
+ tags={"security", "cwe-328"},
3346
+ )
3347
+ def weak_hash(ctx: FileContext) -> Iterator[Hit]:
3348
+ """MD5/SHA-1 whose statement or enclosing function names a secret.
3349
+
3350
+ A secret name contains password, passwd, passphrase, secret, token,
3351
+ nonce, salt, otp, signature/sign, credential, session, csrf, jwt, or an
3352
+ api/secret/private/signing key (camelCase and snake_case split into
3353
+ words).
3354
+
3355
+ Ignores: ``usedforsecurity=False``, checksums, ETags, cache keys and
3356
+ other non-secret uses (no secret name in sight), HMAC constructions
3357
+ (``hmac.new(key, msg, hashlib.sha1)``), and SHA-2 or better.
3358
+ """
3359
+ f = _File(ctx)
3360
+ sink = _WEAK_HASH[f.lang]
3361
+ for stmt, env in _walk(f):
3362
+ if not f.touched(stmt) or not sink.search(stmt.text):
3363
+ continue
3364
+ view = f.view(stmt)
3365
+ m = None
3366
+ for cand in sink.finditer(view.text):
3367
+ if _code_start(view, cand.start()):
3368
+ m = cand
3369
+ break
3370
+ if m is None or re.search(
3371
+ r"\busedforsecurity\s*=\s*False\b|\bhmac\b|\bHmac\b|\bHMAC\b", view.code
3372
+ ):
3373
+ continue
3374
+ named = _security_named(_statement_names(f, view)) or _security_named(env.func_words)
3375
+ if named is None:
3376
+ continue
3377
+ algo = next(g for g in m.groups() if g).lower().replace("-", "")
3378
+ algo = "sha1" if algo in ("sha", "sha1") else algo
3379
+ hit = f.stmt_hit(
3380
+ view,
3381
+ m.start(),
3382
+ f"{algo.upper()} used for a {named}",
3383
+ f"{algo} for a secret",
3384
+ )
3385
+ if hit is not None:
3386
+ yield hit
3387
+
3388
+
3389
+ # --- security/insecure-random --------------------------------------------------------------------
3390
+
3391
+ _RANDOM = {
3392
+ "python": re.compile(
3393
+ r"\brandom\s*\.\s*(?:random|randint|randrange|choice|choices|sample|getrandbits|randbytes|uniform|shuffle)\s*\("
3394
+ ),
3395
+ "javascript": re.compile(r"\bMath\s*\.\s*random\s*\("),
3396
+ "java": re.compile(
3397
+ r"\bnew\s+Random\s*\(|\bMath\s*\.\s*random\s*\(|\bThreadLocalRandom\s*\.\s*current\s*\(|\bRandomStringUtils\s*\.\s*random\w{0,24}\s*\("
3398
+ ),
3399
+ "kotlin": re.compile(
3400
+ r"(?<![\w.])Random\s*\.\s*next\w{1,16}\s*\(|(?<![\w.])Random\s*\(|\bMath\s*\.\s*random\s*\(|\bThreadLocalRandom\s*\.\s*current\s*\(|\.\s*random\s*\(\s*\)|\bRandomStringUtils\s*\.\s*random\w{0,24}\s*\("
3401
+ ),
3402
+ }
3403
+ _RANDOM["typescript"] = _RANDOM["javascript"]
3404
+ _GO_RAND_IMPORT = re.compile(r"(?:^|[\s(])(?:(\w{1,32})\s+)?\"math/rand(?:/v2)?\"")
3405
+
3406
+
3407
+ def _go_random(f: _File) -> re.Pattern[str] | None:
3408
+ aliases: set[str] = set()
3409
+ for line in f.ctx.lines[:400]:
3410
+ m = _GO_RAND_IMPORT.search(line)
3411
+ if m:
3412
+ aliases.add(m.group(1) or "rand")
3413
+ aliases.discard("_")
3414
+ if not aliases:
3415
+ return None
3416
+ names = "|".join(sorted(re.escape(a) for a in aliases))
3417
+ return re.compile(
3418
+ rf"(?<![\w.])(?:{names})\s*\.\s*(?:Int\w{{0,8}}|Uint\w{{0,8}}|Read|Float\w{{0,4}}|Perm|Shuffle|N)\s*\("
3419
+ )
3420
+
3421
+
3422
+ @rule(
3423
+ id="security/insecure-random",
3424
+ severity="warning",
3425
+ title="Non-cryptographic random value for a secret",
3426
+ languages=_CODE,
3427
+ rationale=(
3428
+ "General-purpose generators (random, Math.random, math/rand, java.util.Random) are "
3429
+ "predictable, so tokens, passwords, keys or nonces made from them can be guessed."
3430
+ ),
3431
+ hint=(
3432
+ "Use the platform's CSPRNG: secrets, crypto.randomBytes/getRandomValues, "
3433
+ "crypto/rand, SecureRandom."
3434
+ ),
3435
+ tags={"security", "cwe-338"},
3436
+ )
3437
+ def insecure_random(ctx: FileContext) -> Iterator[Hit]:
3438
+ """A predictable generator whose statement or enclosing function names a secret.
3439
+
3440
+ Generators: Python ``random.*`` module functions, ``Math.random``, Go
3441
+ ``math/rand`` (by its import name), ``java.util.Random``,
3442
+ ``ThreadLocalRandom``, ``RandomStringUtils``, Kotlin ``Random`` and
3443
+ ``.random()``. Secret names as in ``weak-hash`` (token, password, key,
3444
+ nonce, session, otp, salt, ...).
3445
+
3446
+ Ignores: ``secrets``, ``random.SystemRandom``, ``crypto.randomUUID``,
3447
+ ``crypto/rand``, ``SecureRandom``, seeded generators held in variables,
3448
+ and random values used for anything not named like a secret (jitter,
3449
+ sampling, shuffling, test data).
3450
+ """
3451
+ f = _File(ctx)
3452
+ sink = _go_random(f) if f.lang == "go" else _RANDOM[f.lang]
3453
+ if sink is None:
3454
+ return
3455
+ for stmt, env in _walk(f):
3456
+ if not f.touched(stmt) or not sink.search(stmt.masked):
3457
+ continue
3458
+ view = f.view(stmt)
3459
+ m = sink.search(view.code)
3460
+ if m is None or "SystemRandom" in view.code or "SecureRandom" in view.code:
3461
+ continue
3462
+ named = _security_named(_statement_names(f, view)) or _security_named(env.func_words)
3463
+ if named is None:
3464
+ continue
3465
+ hit = f.stmt_hit(
3466
+ view,
3467
+ m.start(),
3468
+ f"Predictable random value used for a {named}",
3469
+ "random for a secret",
3470
+ )
3471
+ if hit is not None:
3472
+ yield hit
3473
+
3474
+
3475
+ # --- security/insecure-tempfile ------------------------------------------------------------------
3476
+
3477
+ _TMP_SINKS = {
3478
+ "python": re.compile(
3479
+ r"(?<![\w.])(?:open|io\.open|codecs\.open|os\.open|Path|os\.path\.join|os\.makedirs|os\.mkdir|shutil\.\w{1,16})\s*\("
3480
+ ),
3481
+ "javascript": re.compile(
3482
+ r"\bfs(?:\.promises)?\s*\.\s*(?:writeFile|writeFileSync|appendFile|appendFileSync|createWriteStream|open|openSync|mkdir|mkdirSync)\s*\(|\bpath\s*\.\s*join\s*\("
3483
+ ),
3484
+ "go": re.compile(
3485
+ r"\b(?:os\.(?:Create|WriteFile|OpenFile|Mkdir|MkdirAll)|ioutil\.WriteFile|filepath\.Join)\s*\("
3486
+ ),
3487
+ "java": re.compile(
3488
+ r"\bnew\s+(?:File|FileOutputStream|FileWriter|PrintWriter)\s*\(|\bPaths\s*\.\s*get\s*\(|\bPath\s*\.\s*of\s*\(|\bFiles\s*\.\s*(?:write|writeString|newOutputStream|newBufferedWriter|createFile|createDirectory|createDirectories)\s*\(|(?<![\w.])File\s*\("
3489
+ ),
3490
+ }
3491
+ _TMP_SINKS["typescript"] = _TMP_SINKS["javascript"]
3492
+ _TMP_SINKS["kotlin"] = _TMP_SINKS["java"]
3493
+ _TMP_PATH = re.compile(r"\A(?:/var)?/tmp(?:/|\Z)")
3494
+ _MKTEMP = re.compile(r"\btempfile\s*\.\s*mktemp\s*\(|(?<![\w.])(?<!def )mktemp\s*\(")
3495
+
3496
+
3497
+ @rule(
3498
+ id="security/insecure-tempfile",
3499
+ severity="warning",
3500
+ title="Predictable temporary file",
3501
+ languages=_CODE,
3502
+ rationale=(
3503
+ "A fixed or merely unique-looking name in a shared temporary directory can be created "
3504
+ "first by another user, who then reads or redirects what is written there."
3505
+ ),
3506
+ hint=(
3507
+ "Create temporary files atomically: tempfile.mkstemp/NamedTemporaryFile, "
3508
+ "fs.mkdtemp, os.CreateTemp, Files.createTempFile."
3509
+ ),
3510
+ tags={"security", "cwe-377"},
3511
+ )
3512
+ def insecure_tempfile(ctx: FileContext) -> Iterator[Hit]:
3513
+ """``tempfile.mktemp`` and file APIs handed a literal ``/tmp/...`` path.
3514
+
3515
+ File APIs: ``open``/``Path``/``os.path.join`` (Python), ``fs.writeFile``/
3516
+ ``createWriteStream``/``open``/``path.join`` (JS/TS), ``os.Create``/
3517
+ ``WriteFile``/``OpenFile``/``filepath.Join`` (Go), ``new File``/
3518
+ ``Paths.get``/``Files.write`` (Java/Kotlin), with a string argument that
3519
+ starts with ``/tmp`` or ``/var/tmp``.
3520
+
3521
+ Ignores: ``mkstemp``, ``NamedTemporaryFile``, ``mkdtemp``,
3522
+ ``os.CreateTemp``, ``createTempFile``, paths built from
3523
+ ``tempfile.gettempdir()``/``os.tmpdir()``, ``/tmp`` in strings that are
3524
+ not file arguments, and shell scripts.
3525
+ """
3526
+ f = _File(ctx)
3527
+ sink = _TMP_SINKS[f.lang]
3528
+ for stmt in f.statements():
3529
+ view = f.view(stmt)
3530
+ if f.lang == "python":
3531
+ mk = _MKTEMP.search(view.code)
3532
+ if mk and ("tempfile" in f.source):
3533
+ hit = f.stmt_hit(
3534
+ view,
3535
+ mk.start(),
3536
+ "tempfile.mktemp() returns a name another process can claim first",
3537
+ "mktemp",
3538
+ )
3539
+ if hit is not None:
3540
+ yield hit
3541
+ continue
3542
+ for m in sink.finditer(view.code):
3543
+ parsed = _call_args(f, view, m.end() - 1)
3544
+ if parsed is None:
3545
+ continue
3546
+ close = parsed[0]
3547
+ base = stmt.start
3548
+ tmp = next(
3549
+ (
3550
+ s
3551
+ for s in view.strings
3552
+ if m.end() <= s.start - base < close and _TMP_PATH.match(f.content(s))
3553
+ ),
3554
+ None,
3555
+ )
3556
+ if tmp is None:
3557
+ continue
3558
+ hit = f.stmt_hit(
3559
+ view,
3560
+ tmp.start - base,
3561
+ "File in a shared temporary directory at a predictable path",
3562
+ "fixed /tmp path",
3563
+ )
3564
+ if hit is not None:
3565
+ yield hit
3566
+ break
3567
+
3568
+
3569
+ # --- security/request-path-traversal -------------------------------------------------------------
3570
+
3571
+ _PATH_SINKS = {
3572
+ "python": re.compile(
3573
+ r"(?<![\w.])(?:open|io\.open|send_file|FileResponse|Path|os\.path\.join|os\.remove|os\.unlink|os\.listdir|os\.rmdir|shutil\.rmtree|shutil\.copy\w{0,8})\s*\("
3574
+ ),
3575
+ "javascript": re.compile(
3576
+ r"\b(?:res\s*\.\s*(?:sendFile|download)|fs(?:\.promises)?\s*\.\s*(?:readFile|readFileSync|createReadStream|writeFile|writeFileSync|unlink|unlinkSync|rm|rmSync|readdir|readdirSync|open|openSync)|path\s*\.\s*(?:join|resolve))\s*\("
3577
+ ),
3578
+ "go": re.compile(
3579
+ r"\b(?:os\.(?:Open|OpenFile|ReadFile|Create|WriteFile|Remove|RemoveAll|ReadDir)|ioutil\.ReadFile|http\.ServeFile|filepath\.Join|c\.(?:File|FileAttachment))\s*\("
3580
+ ),
3581
+ "java": re.compile(
3582
+ r"\bnew\s+(?:File|FileInputStream|FileOutputStream|FileReader|FileWriter)\s*\(|\bPaths\s*\.\s*get\s*\(|\bPath\s*\.\s*of\s*\(|\bFiles\s*\.\s*\w{2,24}\s*\(|(?<![\w.])File\s*\("
3583
+ ),
3584
+ }
3585
+ _PATH_SINKS["typescript"] = _PATH_SINKS["javascript"]
3586
+ _PATH_SINKS["kotlin"] = _PATH_SINKS["java"]
3587
+ _REQUEST_SOURCES = {
3588
+ "python": re.compile(
3589
+ r"\brequest\s*\.\s*(?:args|form|values|GET|POST|query_params|path_params|files|json|cookies|data|match_info)\b"
3590
+ ),
3591
+ "javascript": re.compile(
3592
+ r"\breq(?:uest)?\s*\.\s*(?:params|query|body|files?|cookies)\b|\bctx\s*\.\s*(?:params|query|request\s*\.\s*body)\b"
3593
+ ),
3594
+ "go": re.compile(
3595
+ r"\br\s*\.\s*(?:URL\s*\.\s*Query\s*\(\s*\)\s*\.\s*Get|FormValue|PostFormValue|PathValue)\s*\(|\bmux\s*\.\s*Vars\s*\(|\bc\s*\.\s*(?:Param|Query|PostForm|DefaultQuery|Params\s*\.\s*ByName)\s*\(|\bchi\s*\.\s*URLParam\s*\("
3596
+ ),
3597
+ "java": re.compile(
3598
+ r"\b\w{1,32}\s*\.\s*(?:getParameter|getHeader|getPathInfo|getQueryString)\s*\(|\bcall\s*\.\s*(?:parameters|request\s*\.\s*queryParameters)\s*\["
3599
+ ),
3600
+ }
3601
+ _REQUEST_SOURCES["typescript"] = _REQUEST_SOURCES["javascript"]
3602
+ _REQUEST_SOURCES["kotlin"] = _REQUEST_SOURCES["java"]
3603
+ _PATH_SAFE = re.compile(
3604
+ r"\b(?:secure_filename|basename|safe_join|send_from_directory|filepath\s*\.\s*Base|path\s*\.\s*Base|getFileName|FilenameUtils\s*\.\s*getName|sanitize\w{0,16})\b|\broot\s*:"
3605
+ )
3606
+
3607
+
3608
+ @rule(
3609
+ id="security/request-path-traversal",
3610
+ severity="warning",
3611
+ title="Request value used as a file path",
3612
+ languages=_CODE,
3613
+ rationale=(
3614
+ "A path taken from the request can contain ../ or be absolute and reach files "
3615
+ "outside the intended directory."
3616
+ ),
3617
+ hint=(
3618
+ "Reduce the value to a base name or resolve it and check it stays inside the "
3619
+ "intended directory."
3620
+ ),
3621
+ tags={"security", "cwe-22"},
3622
+ )
3623
+ def request_path_traversal(ctx: FileContext) -> Iterator[Hit]:
3624
+ """A request parameter reaches a file API, directly or through a variable.
3625
+
3626
+ Sources: Flask/Django/Starlette ``request.args``/``form``/``GET``/
3627
+ ``files``..., Express/Koa ``req.params``/``query``/``body``, Go
3628
+ ``r.URL.Query().Get``/``FormValue``/``PathValue``/``mux.Vars``/gin
3629
+ ``c.Param``, servlet ``getParameter``/``getPathInfo`` and Ktor
3630
+ ``call.parameters``. Sinks: ``open``/``send_file``/``Path``/
3631
+ ``os.path.join``, ``res.sendFile``/``fs.*``/``path.join``, ``os.Open``/
3632
+ ``ReadFile``/``http.ServeFile``/``filepath.Join``, ``new File``/
3633
+ ``Paths.get``/``Files.*``.
3634
+
3635
+ Ignores: values reduced with ``secure_filename``/``basename``/
3636
+ ``filepath.Base``/``getFileName``, ``send_from_directory`` and
3637
+ ``safe_join``, ``res.sendFile`` with a ``root`` option, framework path
3638
+ parameters passed as function arguments (not traceable here), and
3639
+ ``http.ServeFile`` with ``r.URL.Path`` (it rejects ``..``).
3640
+ """
3641
+ f = _File(ctx)
3642
+ sink, source = _PATH_SINKS[f.lang], _REQUEST_SOURCES[f.lang]
3643
+ for stmt, env in _walk(f):
3644
+ if not f.touched(stmt):
3645
+ continue
3646
+ view = f.view(stmt)
3647
+ for m in sink.finditer(view.code):
3648
+ parsed = _call_args(f, view, m.end() - 1)
3649
+ if parsed is None:
3650
+ continue
3651
+ close = parsed[0]
3652
+ inside = view.code[m.end() : close]
3653
+ if _PATH_SAFE.search(inside):
3654
+ continue
3655
+ extra: list[tuple[int, int]] = []
3656
+ via = source.search(inside)
3657
+ if via is None:
3658
+ for name in set(_WORD.findall(inside)):
3659
+ pieces = env.lookup(name)
3660
+ if not pieces:
3661
+ continue
3662
+ texts = [f.view(p.stmt).code[p.start : p.end] for p in pieces]
3663
+ if any(source.search(t) for t in texts) and not any(
3664
+ _PATH_SAFE.search(t) for t in texts
3665
+ ):
3666
+ via = True # type: ignore[assignment]
3667
+ extra = [(p.stmt.start_line, p.stmt.end_line) for p in pieces]
3668
+ break
3669
+ if via is None:
3670
+ continue
3671
+ ranges = [(stmt.start_line, stmt.end_line), *extra]
3672
+ hit = f.hit(
3673
+ stmt.start + m.start(),
3674
+ ranges,
3675
+ "Request value used as a file path",
3676
+ m.group(0).rstrip("( "),
3677
+ )
3678
+ if hit is not None:
3679
+ yield hit
3680
+ break