codewatch-scan 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 (136) hide show
  1. codewatch/__init__.py +0 -0
  2. codewatch/__main__.py +14 -0
  3. codewatch/asgi.py +16 -0
  4. codewatch/settings.py +175 -0
  5. codewatch/urls.py +40 -0
  6. codewatch/wsgi.py +16 -0
  7. codewatch_scan-0.1.0.dist-info/METADATA +81 -0
  8. codewatch_scan-0.1.0.dist-info/RECORD +136 -0
  9. codewatch_scan-0.1.0.dist-info/WHEEL +5 -0
  10. codewatch_scan-0.1.0.dist-info/entry_points.txt +4 -0
  11. codewatch_scan-0.1.0.dist-info/licenses/LICENSE +21 -0
  12. codewatch_scan-0.1.0.dist-info/top_level.txt +2 -0
  13. core/__init__.py +0 -0
  14. core/analyzers/__init__.py +19 -0
  15. core/analyzers/accessibility.py +199 -0
  16. core/analyzers/base.py +192 -0
  17. core/analyzers/body_models.py +154 -0
  18. core/analyzers/codewatch_checks.py +394 -0
  19. core/analyzers/constant_branches.py +251 -0
  20. core/analyzers/containers.py +316 -0
  21. core/analyzers/coverage.py +131 -0
  22. core/analyzers/dependencies.py +347 -0
  23. core/analyzers/drf_serializers.py +65 -0
  24. core/analyzers/else_branches.py +106 -0
  25. core/analyzers/extra.py +400 -0
  26. core/analyzers/flask_resources.py +65 -0
  27. core/analyzers/inline_scripts.py +50 -0
  28. core/analyzers/jinja_sandboxes.py +63 -0
  29. core/analyzers/match_statements.py +148 -0
  30. core/analyzers/multi_tools.py +888 -0
  31. core/analyzers/php_template_sinks.py +444 -0
  32. core/analyzers/project_checks.py +150 -0
  33. core/analyzers/python_tools.py +333 -0
  34. core/analyzers/route_converters.py +237 -0
  35. core/analyzers/slices.py +94 -0
  36. core/analyzers/starred_targets.py +42 -0
  37. core/analyzers/stored_fields.py +386 -0
  38. core/analyzers/summaries.py +1387 -0
  39. core/analyzers/template_sinks.py +162 -0
  40. core/api.py +360 -0
  41. core/apps.py +6 -0
  42. core/benchmark.py +955 -0
  43. core/bundled/catalog/codewatch/rules/javascript-crypto.yml +224 -0
  44. core/bundled/catalog/codewatch/rules/javascript-injection.yml +116 -0
  45. core/bundled/catalog/codewatch/rules/javascript-taint.yml +1539 -0
  46. core/bundled/catalog/codewatch/rules/javascript-web.yml +562 -0
  47. core/bundled/catalog/codewatch/rules/php-web.yml +719 -0
  48. core/bundled/catalog/codewatch/rules/python-crypto.yml +203 -0
  49. core/bundled/catalog/codewatch/rules/python-django.yml +267 -0
  50. core/bundled/catalog/codewatch/rules/python-injection.yml +115 -0
  51. core/bundled/catalog/codewatch/rules/python-web.yml +3382 -0
  52. core/bundled/catalog/custom/mappings.json +360 -0
  53. core/bundled/catalog/custom/overrides.json +4 -0
  54. core/bundled/catalog/custom/rules/django-settings.yml +19 -0
  55. core/bundled/catalog/imported/changes.json +5 -0
  56. core/bundled/catalog/imported/docs.json +1143 -0
  57. core/bundled/catalog/imported/meta.json +54 -0
  58. core/bundled/catalog/imported/rules.json +85421 -0
  59. core/bundled/catalog/imported/standards.json +11191 -0
  60. core/bundled/tools/analyzers.lock +786 -0
  61. core/bundled/tools/axe-scan.mjs +45 -0
  62. core/bundled/tools/checkov.lock +2463 -0
  63. core/bundled/tools/codewatch-checks.mjs +99 -0
  64. core/bundled/tools/eslint-a11y.config.js +16 -0
  65. core/bundled/tools/eslint-quality.config.js +63 -0
  66. core/bundled/tools/eslint-typed.config.js +18 -0
  67. core/bundled/tools/package-lock.json +6102 -0
  68. core/bundled/tools/package.json +32 -0
  69. core/bundled/tools/rule-metadata.mjs +56 -0
  70. core/bundled/tools/semgrep.lock +1232 -0
  71. core/bundled/tools/stylelint.config.json +11 -0
  72. core/catalog/__init__.py +190 -0
  73. core/catalog/build.py +84 -0
  74. core/catalog/merge.py +122 -0
  75. core/catalog/sources.py +418 -0
  76. core/catalog/standards.py +119 -0
  77. core/catalog/update.py +99 -0
  78. core/catalog_views.py +115 -0
  79. core/client.py +645 -0
  80. core/collect.py +518 -0
  81. core/duplicates.py +60 -0
  82. core/fingerprint.py +25 -0
  83. core/folders.py +73 -0
  84. core/gate.py +77 -0
  85. core/git.py +149 -0
  86. core/jobs.py +86 -0
  87. core/management/__init__.py +0 -0
  88. core/management/commands/__init__.py +0 -0
  89. core/management/commands/addproject.py +40 -0
  90. core/management/commands/buildcatalog.py +15 -0
  91. core/management/commands/scan.py +74 -0
  92. core/management/commands/updatecatalog.py +14 -0
  93. core/mcp_server.py +140 -0
  94. core/middleware.py +17 -0
  95. core/migrations/0001_initial.py +115 -0
  96. core/migrations/0002_auth_tokens_a11y.py +60 -0
  97. core/migrations/0003_default_admin.py +43 -0
  98. core/migrations/0004_project_members.py +28 -0
  99. core/migrations/0005_uploads_and_sources.py +55 -0
  100. core/migrations/0006_thresholds.py +28 -0
  101. core/migrations/0007_also_reported_by.py +18 -0
  102. core/migrations/0008_new_code_period.py +18 -0
  103. core/migrations/0009_resolution_safe.py +18 -0
  104. core/migrations/0010_analysis_progress.py +18 -0
  105. core/migrations/0011_overall_gate_conditions.py +20 -0
  106. core/migrations/__init__.py +0 -0
  107. core/models.py +323 -0
  108. core/network.py +41 -0
  109. core/paths.py +29 -0
  110. core/ratings.py +67 -0
  111. core/runner.py +168 -0
  112. core/templates/core/account.html +30 -0
  113. core/templates/core/analysis.html +49 -0
  114. core/templates/core/base.html +121 -0
  115. core/templates/core/form_table.html +12 -0
  116. core/templates/core/gate_badge.html +1 -0
  117. core/templates/core/index.html +26 -0
  118. core/templates/core/issues.html +38 -0
  119. core/templates/core/login.html +13 -0
  120. core/templates/core/new_project.html +27 -0
  121. core/templates/core/password_change.html +10 -0
  122. core/templates/core/project.html +40 -0
  123. core/templates/core/rating.html +1 -0
  124. core/templates/core/ratings.html +32 -0
  125. core/templates/core/rule.html +33 -0
  126. core/templates/core/rules.html +42 -0
  127. core/templates/core/scan_progress.html +2 -0
  128. core/templates/core/settings.html +36 -0
  129. core/templates/core/source.html +15 -0
  130. core/templates/core/standards.html +30 -0
  131. core/templates/core/user_edit.html +15 -0
  132. core/templates/core/users.html +18 -0
  133. core/templatetags/__init__.py +0 -0
  134. core/templatetags/codewatch.py +42 -0
  135. core/tool_setup.py +68 -0
  136. core/views.py +564 -0
@@ -0,0 +1,1387 @@
1
+ """One level of interprocedural taint for codewatch's own Semgrep taint rules.
2
+
3
+ Semgrep OSS follows data within a function only, so `load_css(request.args["css"])` is missed when the file read
4
+ happens inside load_css. Two passes close that gap:
5
+
6
+ 1. Each taint rule runs with the parameters of every named function as its sources. A hit means that parameter
7
+ reaches the rule's sink inside the function (sanitizers still apply): a summary (function, parameter).
8
+ 2. The rules run again with each summarised call as an extra sink for that argument: `load_css(<arg>)`.
9
+
10
+ Pass 1 repeats with the summarised calls as sinks too, so a wrapper that hands its parameter to load_css is
11
+ summarised as well, up to MAX_DEPTH calls deep.
12
+
13
+ Data also comes out of helpers: `def get_param(name): return request.args.get(name)`. A third pass runs each
14
+ rule with `return` as the sink to find functions that return request data (returners), and the final rules get a
15
+ variant whose sources are calls to them. Returners repeat up to MAX_DEPTH like summaries, and a value looked up
16
+ by the request data (a model fetched by id, a decoded token) isn't returned request data.
17
+
18
+ Data also waits in object fields: `self.term = request.GET["q"]` in one method, `os.system("grep " + self.term)`
19
+ in another. The returner pass's first scan also runs each rule with stores to `self.x`/`this.x` as the sink, and
20
+ the final rules get a variant whose sources are reads of those fields, kept only in the file that stores them.
21
+
22
+ Semgrep taints whatever a call returns when an argument is tainted. For the project's own Python functions the
23
+ same first scan finds which ones can return a parameter (params as sources, `return` as the sink); a function
24
+ that can't, isn't summarised and doesn't return request data itself is a sanitizer: the variable its result is
25
+ assigned to is clean (`return_url = self.get_return_to(request.POST)`, which returns the value only inside
26
+ `if self.is_safe_url(...)`).
27
+
28
+ A call only counts where the function is visible: in the file that defines it, or in a file that imports it or
29
+ its module, so same-named functions elsewhere don't connect.
30
+ """
31
+ import ast
32
+ import builtins
33
+ import copy
34
+ import functools
35
+ import json
36
+ import re
37
+ from pathlib import Path
38
+
39
+ from .base import python_tree
40
+
41
+ PARAM, VALUE, FUNC, VIA_FUNC, PT_ARG = "$PARAM", "$VALUE", "$FUNC", "$VIA_FUNC", "$PT_ARG"
42
+ SANITIZERS = "pattern-sanitizers"
43
+ SUMMARY_SUFFIX = ".params"
44
+ VIA_SUFFIX = ".via"
45
+ VIA_RE = re.compile(r"\[via (\w+)\(\)\]$")
46
+ RETURNS_SUFFIX = ".returns"
47
+ FROM_SUFFIX = ".from"
48
+ FROM_RE = re.compile(r"\[from (\w+)\(\)\]$")
49
+ PASSES_SUFFIX = ".passes"
50
+ FIELDS_SUFFIX = ".fields"
51
+ FIELD_SUFFIX = ".field"
52
+ FIELD_RE = re.compile(r"\[field (\w+)\]$")
53
+ # Keyword via-sinks match any summarised function called with any summarised keyword; the message carries the pair
54
+ # so a call passing one function's keyword to another (f(name=x) when only g's name is summarised) is dropped.
55
+ KEYWORD_MARK = " {keyword $VIA_FUNC $VIA_KW}"
56
+ KEYWORD_RE = re.compile(r" \{keyword (\S+) (\S+)\}")
57
+ MAX_DEPTH = 3
58
+ JS_LANGUAGES = {"javascript", "typescript"}
59
+ RECEIVERS = {"self", "cls"}
60
+
61
+ PYTHON_PARAM_SOURCES = [
62
+ {"patterns": [{"pattern-either": [{"pattern-inside": "def $FUNC(..., $PARAM, ...):\n ...\n"},
63
+ {"pattern-inside": "async def $FUNC(..., $PARAM, ...):\n ...\n"}]},
64
+ {"pattern": PARAM},
65
+ {"metavariable-regex": {"metavariable": PARAM, "regex": "^(?!(self|cls)$)\\w+$"}}]},
66
+ ]
67
+ JS_PARAM_SOURCES = [
68
+ {"patterns": [{"pattern-either": [
69
+ {"pattern-inside": "function $FUNC(..., $PARAM, ...) { ... }"},
70
+ {"pattern-inside": "const $FUNC = (..., $PARAM, ...) => { ... }"},
71
+ {"pattern-inside": "const $FUNC = (..., $PARAM, ...) => $BODY"},
72
+ {"pattern-inside": "const $FUNC = function (..., $PARAM, ...) { ... }"},
73
+ {"pattern-inside": "class $CLASS { ... $FUNC(..., $PARAM, ...) { ... } ... }"},
74
+ {"pattern-inside": "$OBJ.$FUNC = (..., $PARAM, ...) => { ... }"},
75
+ {"pattern-inside": "$OBJ.$FUNC = function (..., $PARAM, ...) { ... }"},
76
+ ]}, {"pattern": PARAM}]},
77
+ ]
78
+
79
+ # A view returns a response, not data, even when another view returns its result.
80
+ ROUTE_DECORATORS = ("route", "get", "post", "put", "patch", "delete", "api_route", "websocket")
81
+ # Class-based handlers (Django's View.get, a Nest controller's get) also return responses, and their names are
82
+ # everyone's: requests.get(...) isn't a call to one.
83
+ HANDLER_NAMES = {*ROUTE_DECORATORS, "head", "options", "dispatch", "handle", "handler", "render", "__call__"}
84
+ # A Python function named like a builtin is a method (DRF's ViewSet.list, taiga): a bare list(...) call is the builtin.
85
+ PYTHON_BUILTINS = {name for name in dir(builtins) if not name.startswith("_")}
86
+ RESPONSE_CALL_RE = (r"^(?!([\w.]+\.)?(\w*Response|Ok|Created|Accepted|NoContent|BadRequest|NotFound|Forbidden|Unauthorized"
87
+ r"|jsonify|render|render_template|redirect|HttpResponse\w*)\()")
88
+ PYTHON_RETURN_SINKS = [
89
+ {"patterns": [{"pattern-either": [{"pattern-inside": "def $FUNC(...):\n ...\n"},
90
+ {"pattern-inside": "async def $FUNC(...):\n ...\n"}]},
91
+ *({"pattern-not-inside": f"@$APP.{d}(...)\n{a}def $FUNC(...):\n ...\n"}
92
+ for d in ROUTE_DECORATORS for a in ("", "async ")),
93
+ {"pattern": "return $VALUE"},
94
+ # A view's response (DRF's Response(...), taiga's response.Ok(...)) is for the client, not data
95
+ # for a caller.
96
+ {"metavariable-regex": {"metavariable": VALUE, "regex": RESPONSE_CALL_RE}},
97
+ {"focus-metavariable": VALUE}]},
98
+ ]
99
+ JS_RETURN_SINKS = [
100
+ {"patterns": [{"pattern-either": [
101
+ {"pattern-inside": "function $FUNC(...) { ... }"},
102
+ {"pattern-inside": "const $FUNC = (...) => { ... }"},
103
+ {"pattern-inside": "const $FUNC = function (...) { ... }"},
104
+ {"pattern-inside": "$FUNC(...) { ... }"},
105
+ {"pattern-inside": "$OBJ.$FUNC = (...) => { ... }"},
106
+ {"pattern-inside": "$OBJ.$FUNC = function (...) { ... }"},
107
+ ]},
108
+ # A Koa/Express handler (last parameter `next`) returns the response's promise, not data for its caller
109
+ # (outline: `return renderShare(ctx, next)` passing one route on to another).
110
+ {"pattern-not-inside": "function $FUNC(..., next) { ... }"},
111
+ {"pattern-not-inside": "const $FUNC = (..., next) => { ... }"},
112
+ {"pattern-not-inside": "$FUNC(..., next) { ... }"},
113
+ {"pattern": "return $VALUE;"}, {"focus-metavariable": VALUE}]},
114
+ ]
115
+ LOOKUP_RESULT_MARK = "(get|fetch|load|find|lookup)_(?!"
116
+ JS_LOOKUP_RESULT_MARK = "(get|fetch|load|find|lookup)(?!("
117
+ # What a helper looks up with the request data (a user by token, a row by id) is stored data, not the request's.
118
+ LOOKUP_SANITIZER = {"patterns": [
119
+ {"pattern-either": [{"pattern": "$F(...)"}, {"pattern": "await $F(...)"}]},
120
+ {"metavariable-regex": {"metavariable": "$F", "regex": (
121
+ "(?is)(.*\\.(objects|query|session|db|repo|repository|manager|collection|model)\\.\\w+"
122
+ # An ORM query run to its row: manager.only(...).filter(id=x).first() (paperless-ngx).
123
+ "|.*\\.(only|filter|filter_by|exclude|where|select_related|prefetch_related|order_by)\\(.*\\)"
124
+ "\\.(first|last|get|one|one_or_none|scalar_one_or_none|first_or_404|get_or_404)"
125
+ "|(.*\\.)?(get_object_or_404|get_list_or_404|first_or_404|get_or_404|find\\w*|load\\w*|fetch\\w*"
126
+ "|lookup\\w*|decode\\w*|verify\\w*|authenticate\\w*|get_user\\w*|get_current_user\\w*))$")}},
127
+ ]}
128
+ # The same in JavaScript's names: a camelCase loader (WIKI.models.pages.getPage({ id }), Repo.findOne(...)) other
129
+ # than one named for request data (getQuery, getParam), or any method of a model or store
130
+ # (WIKI.models.feedback.boardOfIdea(...), db.users.byId(...)). So wiki.js's loadIdea(req, reply), which returns the
131
+ # page and board it looked up, isn't a returner of request data, while getParam(req) { return req.query.x } is.
132
+ JS_LOOKUP_SANITIZER = {"patterns": [
133
+ {"pattern-either": [{"pattern": "$F(...)"}, {"pattern": "await $F(...)"}]},
134
+ {"metavariable-regex": {"metavariable": "$F", "regex": (
135
+ "(?s)^(?!(req|request|ctx|ctx\\.request|context\\.req|reply|res|response)\\.)"
136
+ "(([\\w$]+\\.)*_?(get|fetch|load|find|lookup)(?!(Json|Data|Params?|Args?|Query|Queries|Headers?|Cookies?|Body"
137
+ "|Form|Fields?|Values?|Inputs?|Text|Str|String|Url|Uri|Path|File|Filename|Name|Key|Id|Var|Env|Config|Setting"
138
+ "|Content|Request|Req|Payload|Redirect|Next|Return|Target|Dest|Destination|Location|Callback|Referr?er|Host"
139
+ "|Origin)([A-Z]|$))[A-Z][\\w$]*"
140
+ "|([\\w$]+\\.)*(models?|db|database|repo|repository|repositories|store|collection|collections|prisma)"
141
+ "(\\.[\\w$]+){1,2})$")}},
142
+ ]}
143
+
144
+
145
+ def taint_rules(rules):
146
+ """Taint rules that follow data across calls. A rule whose sources aren't request data (a stack trace, a
147
+ file name) sets metadata `interprocedural: false`: a parameter reaching its sink says nothing about them."""
148
+ return [r for r in rules if r.get("mode") == "taint" and r.get("metadata", {}).get("interprocedural", True)]
149
+
150
+
151
+ def is_js(rule):
152
+ return bool(JS_LANGUAGES & set(rule.get("languages", [])))
153
+
154
+
155
+ def summary_rules(rules, summaries=None, base=True, receivers=None):
156
+ """Pass 1: every taint rule with function parameters as sources, reporting "function|parameter|callee".
157
+
158
+ With summaries, only the summarised rules, and calls to the summarised functions are sinks as well (the callee
159
+ names which one was reached, so parse_summaries can check it is visible). Without base, those calls are the
160
+ only sinks: a deeper pass given just the summaries the last one added finds only what they add."""
161
+ out = []
162
+ for rule in taint_rules(rules):
163
+ found = (summaries or {}).get(rule["id"])
164
+ # Listed with no summaries left is still asked about: resummarise's kept can empty a rule (PostHog
165
+ # GHSA-jrwm's only SSRF summary was the stale one).
166
+ if summaries is not None and rule["id"] not in summaries:
167
+ continue
168
+ variant = copy.deepcopy(rule)
169
+ variant["id"] = rule["id"] + SUMMARY_SUFFIX
170
+ variant["message"] = "$FUNC|$PARAM|$VIA_FUNC|$VIA_KW"
171
+ variant["pattern-sources"] = copy.deepcopy(JS_PARAM_SOURCES if is_js(rule) else PYTHON_PARAM_SOURCES)
172
+ if found:
173
+ variant["pattern-sinks"] = (rule["pattern-sinks"] if base else []) + via_sinks(found, is_js(rule), receivers)
174
+ unshielded(variant, found)
175
+ out.append(variant)
176
+ return out
177
+
178
+
179
+ @functools.lru_cache(maxsize=32)
180
+ def python_functions(text):
181
+ """{name: [(def node, defined directly in a class)]}, parsed once per file: pass 1 can report thousands of
182
+ hits in one large module."""
183
+ try:
184
+ tree = ast.parse(text)
185
+ except (SyntaxError, ValueError):
186
+ return {}
187
+ functions = {}
188
+ for parent in ast.walk(tree):
189
+ for node in ast.iter_child_nodes(parent):
190
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
191
+ functions.setdefault(node.name, []).append((node, isinstance(parent, ast.ClassDef)))
192
+ return functions
193
+
194
+
195
+ def innermost_def(defs, line):
196
+ """(def, in a class) of the innermost of defs around line, or None."""
197
+ around = [(node, in_class) for node, in_class in defs if node.lineno <= line <= (node.end_lineno or node.lineno)]
198
+ return max(around, key=lambda d: d[0].lineno, default=None)
199
+
200
+
201
+ def python_signature(text, func, line):
202
+ """(positional index or None, is_method) of the parameters of the def named func around line."""
203
+ best = innermost_def(python_functions(text).get(func, ()), line)
204
+ if best is None:
205
+ return None
206
+ node, in_class = best
207
+ positional = [a.arg for a in node.args.posonlyargs + node.args.args]
208
+ method = in_class and bool(positional) and positional[0] in RECEIVERS
209
+ return positional[1:] if method else positional, [a.arg for a in node.args.kwonlyargs], method
210
+
211
+
212
+ # Parameters run to the first ")" but never past the next `function` keyword, or hold one level of parentheses for
213
+ # an assignment: no pattern scans past the next header, so a line of unclosed headers is read once, not once per
214
+ # header.
215
+ JS_HEADER_RES = [
216
+ re.compile(r"\bfunction\b\s*(?:\*\s*)?(?P<name>\w+)\s*(?:<[^<>]*>\s*)?\((?P<params>(?:[^)f]|f(?!unction\b))*)\)"),
217
+ re.compile(r"\b(?P<name>\w+)\s*=\s*(async\s+)?(function\s*)?\((?P<params>[^()]*(?:\([^()]*\)[^()]*)*)\)"),
218
+ re.compile(r"^\s*(public\s+|private\s+|protected\s+|static\s+|async\s+)*(?P<name>\w+)\s*(?:<[^>]*>\s*)?\((?P<params>[^)]*)\)[^;]*\{"),
219
+ ]
220
+
221
+
222
+ def js_param_name(param):
223
+ param = param.strip()
224
+ if not param or param[0] in "{[" or param.startswith("..."):
225
+ return None
226
+ return re.split(r"[?:=\s]", param, maxsplit=1)[0]
227
+
228
+
229
+ def js_signature(text, func, line):
230
+ """Parameters of the nearest header for func at or above line (single-line headers only)."""
231
+ lines = text.splitlines()
232
+ for i in range(min(line, len(lines)) - 1, -1, -1):
233
+ for header in JS_HEADER_RES:
234
+ if (m := header.search(lines[i])) and m.group("name") == func:
235
+ params = [js_param_name(p) for p in m.group("params").split(",")]
236
+ return params, [], False
237
+ return None
238
+
239
+
240
+ def callee_visible(path, func, said, read_text):
241
+ """A result reached through a summarised callee counts only where that callee is visible from path, for a
242
+ keyword it names. said: (callee, keyword, the rule's known summaries)."""
243
+ callee, keyword, rule_known = said
244
+ if not keyword_summarised(callee, keyword, rule_known):
245
+ return False
246
+ defining = {s[4] for s in rule_known if s[0] == callee}
247
+ return callee != func and bool(defining) and visible(path, defining, read_text)
248
+
249
+
250
+ def summary_entry(path, line, func, param, read_text):
251
+ """(function, positional index or None, parameter, is_method, path) when param is a parameter of the def
252
+ named func around line, else None."""
253
+ text = read_text(path)
254
+ signature = None if text is None else (python_signature if path.endswith(".py") else js_signature)(text, func, line)
255
+ if signature is None:
256
+ return None
257
+ positional, keyword_only, method = signature
258
+ if param not in positional and param not in keyword_only:
259
+ return None
260
+ return func, positional.index(param) if param in positional else None, param, method, path
261
+
262
+
263
+ def parse_summaries(results, read_text, known=None, hits=None):
264
+ """{rule id: {(function, positional index or None, parameter, is_method, defining path)}} from pass 1.
265
+
266
+ known: the summaries the pass used as sinks; a hit on one counts only where that callee is visible.
267
+ hits: collects (rule id, path, line, function, parameter) for each accepted result."""
268
+ summaries = {}
269
+ for check_id, path, line, message in results:
270
+ func, param, callee, keyword = [*message.split("|"), "", "", ""][:4]
271
+ rule_id = check_id.removesuffix(SUMMARY_SUFFIX)
272
+ if not func or not param or (callee and not callee.startswith("$") and not callee_visible(
273
+ path, func, (callee, keyword, (known or {}).get(rule_id, ())), read_text)):
274
+ continue
275
+ entry = summary_entry(path, line, func, param, read_text)
276
+ if entry is None:
277
+ continue
278
+ summaries.setdefault(rule_id, set()).add(entry)
279
+ if hits is not None:
280
+ hits.append((rule_id, path, line, func, param))
281
+ return summaries
282
+
283
+
284
+ NAME_RE = re.compile(r"[A-Za-z_$][\w$]*")
285
+ DEFINITION_RE = re.compile(r"\b(?:def|class|function(?:\s*\*)?)\s+$")
286
+ DEFINITION_REACH = 64
287
+ NOT_A_USE_RE = re.compile(r"^\s*(#|//|\*|/\*)|module\.exports|\bexports\.|^\s*export\s*\{|__all__")
288
+
289
+
290
+ def referenced_names(files):
291
+ """Names used somewhere other than their own definition, an export list or a comment: a function whose name
292
+ is never used has no caller in the project, so whatever reaches its parameters comes from outside."""
293
+ used = set()
294
+ for path, text in files:
295
+ js = not path.endswith(".py")
296
+ for line in text.splitlines():
297
+ if NOT_A_USE_RE.search(line):
298
+ continue
299
+ # Positions rather than slices of the line: minified bundles have lines of 100k characters and
300
+ # thousands of names each, and copying the line per name is quadratic.
301
+ for match in NAME_RE.finditer(line):
302
+ start, end = match.span()
303
+ if (DEFINITION_RE.search(line, max(0, start - DEFINITION_REACH), start)
304
+ or (js and js_definition(line, start, end))):
305
+ continue
306
+ used.add(match.group())
307
+ return used
308
+
309
+
310
+ JS_ASSIGNED_FUNCTION_RE = re.compile(r"\s*[:=]\s*(async\s+)?(function\b|\([^)]*\)\s*=>|\w+\s*=>)")
311
+ JS_MODIFIERS_RE = re.compile(r"\s*((public|private|protected|static|async)\s+)*")
312
+ JS_METHOD_HEADER_RE = re.compile(r"\s*\([^)]*\)[^;]*\{\s*$")
313
+
314
+
315
+ def js_definition(line, start, end):
316
+ """line[start:end] is defined here: `name = (...) =>`, `name: function`, or a class method header
317
+ `name(...) {` at the start of the line."""
318
+ if JS_ASSIGNED_FUNCTION_RE.match(line, end):
319
+ return True
320
+ return bool(JS_MODIFIERS_RE.fullmatch(line, 0, start) and JS_METHOD_HEADER_RE.match(line, end))
321
+
322
+
323
+ def callees(method, js):
324
+ receivers = ["this"] if js else sorted(RECEIVERS)
325
+ return [f"{r}.$VIA_FUNC" for r in receivers] if method else [VIA_FUNC, "$MODULE.$VIA_FUNC"]
326
+
327
+
328
+ # A method summarised in one class is also reached through other receivers (`store.load_run(run_id)` with store a
329
+ # SwarmStore, Vibe-Trading GHSA-mjrq), but only where the calling file imports the defining module (visible()), and
330
+ # not for names every library object has: `form.save(x)` or `cache.get(x)` isn't a call to the project's save/get.
331
+ GENERIC_METHODS = PYTHON_BUILTINS | HANDLER_NAMES | {
332
+ name for kind in (dict, list, str, bytes, set, frozenset) for name in dir(kind) if not name.startswith("_")} | {
333
+ "add", "all", "apply", "call", "clean", "close", "commit", "connect", "create", "decode", "delete", "dump",
334
+ "dumps", "emit", "encode", "execute", "exists", "fetch", "filter", "first", "flush", "load", "loads", "open",
335
+ "parse", "patch", "post", "process", "put", "query", "read", "remove", "run", "save", "send", "set", "start",
336
+ "stop", "submit", "update", "validate", "write"}
337
+ OTHER_RECEIVER = {"metavariable-regex": {"metavariable": "$OBJ", "regex": "^(?!(self|cls)$)"}}
338
+
339
+
340
+ def other_receiver_methods(found):
341
+ """Summarised Python methods that a call on another object may reach."""
342
+ return {f for f, _index, _param, method, _path in found if method and f not in GENERIC_METHODS}
343
+
344
+
345
+ def constructed_class(value, classes):
346
+ """The project class a value is made from: `Class(...)`, `module.Class(...)`, or one side of `x or Class()` /
347
+ `a if c else Class()` (Vibe-Trading: self._memory = memory or PersistentMemory())."""
348
+ if isinstance(value, ast.Call):
349
+ name = value.func.attr if isinstance(value.func, ast.Attribute) else getattr(value.func, "id", None)
350
+ return name if name in classes else None
351
+ parts = value.values if isinstance(value, ast.BoolOp) else (
352
+ [value.body, value.orelse] if isinstance(value, ast.IfExp) else [])
353
+ return next((c for part in parts if (c := constructed_class(part, classes))), None)
354
+
355
+
356
+ def receiver_text(target):
357
+ """`name` or `self.field` as written, or None for anything else."""
358
+ if isinstance(target, ast.Name):
359
+ return target.id
360
+ if isinstance(target, ast.Attribute) and isinstance(target.value, ast.Name) and target.value.id in RECEIVERS:
361
+ return f"{target.value.id}.{target.attr}"
362
+ return None
363
+
364
+
365
+ def generic_methods(trees):
366
+ """{class: {(generic-named method, defining path)}} for the project's classes."""
367
+ methods = {}
368
+ for path, tree in trees.items():
369
+ for node in (n for n in ast.walk(tree) if isinstance(n, ast.ClassDef)):
370
+ methods.setdefault(node.name, set()).update(
371
+ (item.name, path) for item in node.body
372
+ if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)) and item.name in GENERIC_METHODS)
373
+ return {cls: found for cls, found in methods.items() if found}
374
+
375
+
376
+ def instance_receivers(node, classes):
377
+ """(class, [receivers]) for `x = Class(...)` or `self.x: T = Class(...)` of one of classes, else None."""
378
+ if not isinstance(node, (ast.Assign, ast.AnnAssign)) or node.value is None:
379
+ return None
380
+ cls = constructed_class(node.value, classes)
381
+ if not cls:
382
+ return None
383
+ targets = node.targets if isinstance(node, ast.Assign) else [node.target]
384
+ return cls, [text for target in targets if (text := receiver_text(target)) and text not in RECEIVERS]
385
+
386
+
387
+ def typed_receivers(texts):
388
+ """{(method, defining path): receivers} for the generic-named methods of the project's classes (GENERIC_METHODS:
389
+ `get`, `add`, `save`), and the variables and self fields assigned an instance of that class anywhere in texts
390
+ ({path: source}). A call on one of them reaches the project's method, not a library's: taiga's
391
+ `self._client = JiraClient(...)` then `self._client.get(url)`, Vibe-Trading's `self._memory.add(...)`
392
+ (GHSA-3j25). By name across files, so visible() still decides whether the calling file can reach it."""
393
+ trees = {path: tree for path, text in texts.items() if (tree := python_tree(text)) is not None}
394
+ methods = generic_methods(trees)
395
+ if not methods:
396
+ return {}
397
+ by_class = class_receivers(trees, methods)
398
+ return {key: receivers for cls, receivers in by_class.items() for key in methods[cls]}
399
+
400
+
401
+ def class_receivers(trees, classes):
402
+ """{class: receivers assigned an instance of it}."""
403
+ by_class = {}
404
+ for found in (instance_receivers(node, classes) for tree in trees.values() for node in ast.walk(tree)):
405
+ if found and found[1]:
406
+ by_class.setdefault(found[0], set()).update(found[1])
407
+ return by_class
408
+
409
+
410
+ def typed_receiver_sinks(found, receivers):
411
+ """Sinks for calls to summarised generic-named methods through a receiver typed as their class."""
412
+ sinks = []
413
+ for func, index, param, method, path in sorted(found, key=str):
414
+ names = receivers.get((func, path)) if method else None
415
+ if not names:
416
+ continue
417
+ shape = [{"metavariable-regex": {"metavariable": "$OBJ", "regex": regex}} for regex in name_regexes(names)]
418
+ named = {"metavariable-regex": {"metavariable": VIA_FUNC, "regex": f"^{re.escape(func)}$"}}
419
+ if index is not None:
420
+ call = "$OBJ.$VIA_FUNC(" + "".join(f"$A{i}, " for i in range(index)) + "$ARG, ...)"
421
+ sinks += [{"patterns": [{"pattern": call}, s, named, {"focus-metavariable": "$ARG"}]} for s in shape]
422
+ keyword = {"metavariable-regex": {"metavariable": "$VIA_KW", "regex": f"^{re.escape(param)}$"}}
423
+ sinks += [{"patterns": [{"pattern": "$OBJ.$VIA_FUNC(..., $VIA_KW=$ARG, ...)"}, s, named, keyword,
424
+ {"focus-metavariable": "$ARG"}]} for s in shape]
425
+ return sinks
426
+
427
+
428
+ def call_patterns(index, method, js):
429
+ """Semgrep patterns for a call passing $ARG at that position; $VIA_FUNC binds the name."""
430
+ if index is None:
431
+ return []
432
+ before = "".join(f"$A{i}, " for i in range(index))
433
+ return [f"{callee}({before}$ARG, ...)" for callee in callees(method, js)]
434
+
435
+
436
+ NAME_BATCH = 400
437
+
438
+
439
+ def name_regexes(names):
440
+ """Anchored alternations of names, NAME_BATCH at a time: Semgrep's regex engine rejects one listing
441
+ a large project's thousands of functions."""
442
+ names = sorted(names)
443
+ return [f"^({'|'.join(map(re.escape, names[i:i + NAME_BATCH]))})$"
444
+ for i in range(0, len(names), NAME_BATCH)]
445
+
446
+
447
+ FOCUS_ARG = {"focus-metavariable": "$ARG"}
448
+
449
+
450
+ def via_func(regex):
451
+ return {"metavariable-regex": {"metavariable": VIA_FUNC, "regex": regex}}
452
+
453
+
454
+ def via_keyword(regex):
455
+ return {"metavariable-regex": {"metavariable": "$VIA_KW", "regex": regex}}
456
+
457
+
458
+ def positional_call(index):
459
+ return "$OBJ.$VIA_FUNC(" + "".join(f"$A{i}, " for i in range(index)) + "$ARG, ...)"
460
+
461
+
462
+ def call_shape_sinks(found, js):
463
+ """A sink per call shape (plain, module or receiver call with the argument at a position), naming every function
464
+ called that way."""
465
+ callers = {}
466
+ for func, index, _param, method, _path in found:
467
+ for pattern in call_patterns(index, method, js):
468
+ callers.setdefault(pattern, set()).add(func)
469
+ return [{"patterns": [{"pattern": pattern}, via_func(regex), FOCUS_ARG]}
470
+ for pattern, funcs in sorted(callers.items()) for regex in name_regexes(funcs)]
471
+
472
+
473
+ def by_position(found, funcs):
474
+ """{argument position: functions among funcs summarised at it}."""
475
+ positional = {}
476
+ for func, index, _param, _method, _path in found:
477
+ if func in funcs and index is not None:
478
+ positional.setdefault(index, set()).add(func)
479
+ return positional
480
+
481
+
482
+ def other_receiver_sinks(found):
483
+ """Calls on another object to summarised methods with names no library object has, positional and keyword."""
484
+ others = other_receiver_methods(found)
485
+ if not others:
486
+ return []
487
+ sinks = [{"patterns": [{"pattern": positional_call(index)}, OTHER_RECEIVER, via_func(regex), FOCUS_ARG]}
488
+ for index, funcs in sorted(by_position(found, others).items()) for regex in name_regexes(funcs)]
489
+ params = {p for f, _index, p, m, _path in found if m and f in others}
490
+ return sinks + [{"patterns": [{"pattern": "$OBJ.$VIA_FUNC(..., $VIA_KW=$ARG, ...)"}, OTHER_RECEIVER,
491
+ via_func(func_regex), via_keyword(param_regex), FOCUS_ARG]}
492
+ for func_regex in name_regexes(others) for param_regex in name_regexes(params)]
493
+
494
+
495
+ def keyword_sinks(found):
496
+ """One sink per kind of callee (function or method) for keyword arguments, naming every summarised function
497
+ and keyword of that kind (see KEYWORD_MARK)."""
498
+ sinks = []
499
+ for method in (False, True):
500
+ funcs = {f for f, _index, _param, m, _path in found if m == method}
501
+ params = {p for _f, _index, p, m, _path in found if m == method}
502
+ sinks += [{"patterns": [
503
+ {"pattern-either": [{"pattern": f"{c}(..., $VIA_KW=$ARG, ...)"} for c in callees(method, False)]},
504
+ via_func(func_regex), via_keyword(param_regex), FOCUS_ARG,
505
+ ]} for func_regex in name_regexes(funcs) for param_regex in name_regexes(params)]
506
+ return sinks
507
+
508
+
509
+ def via_sinks(found, js, receivers=None):
510
+ """One sink per call shape, naming every function called that way: a sink per function made Semgrep match
511
+ thousands of patterns in a large project. Python keyword arguments get one sink per kind of callee, naming every
512
+ summarised function and keyword (see KEYWORD_MARK)."""
513
+ sinks = call_shape_sinks(found, js)
514
+ if js:
515
+ return sinks
516
+ return (sinks + typed_receiver_sinks(found, receivers or {}) + other_receiver_sinks(found)
517
+ + keyword_sinks(found))
518
+
519
+
520
+ def keyword_summarised(callee, keyword, found):
521
+ """A via-sink's call passes a summarised parameter: always for a positional one or a result from another sink
522
+ ($VIA_KW or $VIA_FUNC unbound), and for a keyword only when that function's summary names it."""
523
+ if not keyword or keyword.startswith("$") or not callee or callee.startswith("$"):
524
+ return True
525
+ return any(s[0] == callee and s[2] == keyword for s in found)
526
+
527
+
528
+ def split_keyword(message):
529
+ """(message without KEYWORD_MARK, callee, keyword) for a final-pass result."""
530
+ match = KEYWORD_RE.search(message)
531
+ if not match:
532
+ return message, "", ""
533
+ return message[:match.start()] + message[match.end():], match.group(1), match.group(2)
534
+
535
+
536
+ def added(before, after):
537
+ """{rule: entries of after that before lacks}, for the rules that gained some."""
538
+ return {rule: new for rule, found in after.items() if (new := found - before.get(rule, set()))}
539
+
540
+
541
+ def merge(summaries, more):
542
+ """summaries plus more; None when more adds nothing."""
543
+ merged = {rule: set(found) for rule, found in summaries.items()}
544
+ for rule, found in more.items():
545
+ merged.setdefault(rule, set()).update(found)
546
+ return None if merged == summaries else merged
547
+
548
+
549
+ # Names the rules' sanitizers trust as checks (`known-safe`, the guards: validate_url, is_safe, sanitize_path...).
550
+ CHECK_NAME_RE = re.compile(r"(?i)^_?(get_|make_|to_|is_?|check_?|can_?)?\w{0,30}"
551
+ r"(safe|valid|saniti[sz]|clean|allow|permit|trust|whitelist|escape)")
552
+
553
+
554
+ def unshielded(variant, found):
555
+ """The variant with its sanitizers no longer trusting, by name, a summarised function that passes a parameter
556
+ to the rule's sink. Semgrep clears everything inside a sanitized call, so `validate_credentials(subdomain=s)`,
557
+ PostHog's check that is itself the outbound request (GHSA-jrwm), hid its own via-sink. Only names a sanitizer
558
+ could match are listed, so a project with many summaries doesn't get a pattern-not per function."""
559
+ names = sorted({func for func, *_ in found if CHECK_NAME_RE.match(func)})
560
+ if not names or not variant.get(SANITIZERS):
561
+ return variant
562
+ nots = [{"pattern-not": f"{name}(...)"} for name in names] + [{"pattern-not": f"$OBJ.{name}(...)"} for name in names]
563
+ variant[SANITIZERS] = [{"patterns": [sanitizer, *nots]} for sanitizer in variant[SANITIZERS]]
564
+ return variant
565
+
566
+
567
+ def via_rules(rules, summaries, receivers=None):
568
+ """Pass 2 rules: each summarised taint rule with calls to its functions as extra sinks."""
569
+ out = []
570
+ for rule in taint_rules(rules):
571
+ found = summaries.get(rule["id"])
572
+ if not found:
573
+ continue
574
+ variant = copy.deepcopy(rule)
575
+ variant["id"] = rule["id"] + VIA_SUFFIX
576
+ variant["pattern-sinks"] = via_sinks(found, is_js(rule), receivers)
577
+ variant["message"] = rule["message"].strip() + KEYWORD_MARK + " [via $VIA_FUNC()]"
578
+ out.append(unshielded(variant, found))
579
+ return out
580
+
581
+
582
+ # The module and each name list start with something other than a space, so the spaces around them are read once.
583
+ PY_IMPORT_RE = re.compile(
584
+ r"^[ \t]*(?:from[ \t]+(\.*\w[\w.]*|\.+)[ \t]+import[ \t]+([\w.,()*][\w., ()*]*)|import[ \t]+([\w.,][\w., ]*))",
585
+ re.MULTILINE)
586
+ JS_IMPORT_RE = re.compile(r"""(?:\bfrom\s+|\brequire\s*\(\s*|\bimport\s*\(\s*)['"](\.{1,2}/[^'"]+)['"]""")
587
+ JS_EXTENSIONS = ("", ".js", ".ts", ".jsx", ".tsx", ".mjs", ".cjs", "/index.js", "/index.ts")
588
+
589
+
590
+ def plain_modules(plain):
591
+ """The modules of `import a.b as c, d`."""
592
+ return [n.split(" as ")[0].strip() for n in plain.split(",")]
593
+
594
+
595
+ def bare_names(names):
596
+ """The names of `from x import (a as b, c)`."""
597
+ return [n.split(" as ")[0].strip(" ()") for n in names.split(",")]
598
+
599
+
600
+ def relative_files(folder, source, names):
601
+ """The files a relative import (`from ..a import b`) in folder may name."""
602
+ dots = len(source) - len(source.lstrip("."))
603
+ base = source.lstrip(".")
604
+ anchor = folder.parents[dots - 2] if dots > 1 else folder
605
+ prefix = anchor.joinpath(*base.split(".")) if base else anchor
606
+ modules_here = [prefix, *(prefix / n for n in bare_names(names) if n)]
607
+ return [*(f"{m}.py" for m in modules_here), *(f"{m}/__init__.py" for m in modules_here)]
608
+
609
+
610
+ def absolute_modules(match):
611
+ """The modules an absolute import names: its own and, for `from a import b`, a.b too; none for a relative one."""
612
+ source, names, plain = match.groups()
613
+ if plain:
614
+ return plain_modules(plain)
615
+ if source.startswith("."):
616
+ return []
617
+ return [source, *(f"{source}.{n}" for n in bare_names(names) if n and n != "*")]
618
+
619
+
620
+ def python_imports(path, text):
621
+ """Repo-relative files a Python module may import, trying every ancestor folder as an import root."""
622
+ folder = Path(path).parent
623
+ roots = [folder, *folder.parents]
624
+ modules = []
625
+ for match in PY_IMPORT_RE.finditer(text):
626
+ source, names, plain = match.groups()
627
+ if not plain and source.startswith("."):
628
+ yield from relative_files(folder, source, names)
629
+ else:
630
+ modules += absolute_modules(match)
631
+ for module in modules:
632
+ for root in roots:
633
+ target = root.joinpath(*module.split("."))
634
+ yield f"{target}.py"
635
+ yield f"{target}/__init__.py"
636
+
637
+
638
+ def js_imports(path, text):
639
+ folder = Path(path).parent
640
+ for match in JS_IMPORT_RE.finditer(text):
641
+ target = (folder / match.group(1)).as_posix()
642
+ parts = []
643
+ for part in target.split("/"):
644
+ if part == "..":
645
+ if parts:
646
+ parts.pop()
647
+ elif part not in ("", "."):
648
+ parts.append(part)
649
+ yield from ("/".join(parts) + ext for ext in JS_EXTENSIONS)
650
+
651
+
652
+ def python_absolute_modules(text):
653
+ """Module files a package-qualified absolute import names, relative to whatever folder is its import root:
654
+ `from a.b import c` gives a/b.py, a/b/__init__.py, a/b/c.py and a/b/c/__init__.py."""
655
+ for match in PY_IMPORT_RE.finditer(text):
656
+ # Only a package-qualified name: `import libuser` could be any libuser.py in the project.
657
+ for module in (m for m in absolute_modules(match) if "." in m):
658
+ stem = "/".join(module.split("."))
659
+ yield f"{stem}.py"
660
+ yield f"{stem}/__init__.py"
661
+
662
+
663
+ def python_aliases(texts, names):
664
+ """{alias: name} for `from module import name as alias` of the given function names, in any of texts. PostHog
665
+ imports two `validate_credentials` as `validate_zendesk_credentials` and `validate_vitally_credentials`
666
+ (GHSA-jrwm): the via-sinks list functions by their own name. visible() still requires the importing file to
667
+ import the module that defines the name."""
668
+ aliases = {}
669
+ for tree in filter(None, (python_tree(text) for text in texts if " as " in text)):
670
+ for alias in imported_aliases(tree, names):
671
+ aliases.setdefault(alias.asname, alias.name)
672
+ return aliases
673
+
674
+
675
+ def imported_aliases(tree, names):
676
+ """`from m import name as other` aliases of names in a module."""
677
+ return [a for node in ast.walk(tree) if isinstance(node, ast.ImportFrom) for a in node.names
678
+ if a.asname and a.asname != a.name and a.name in names]
679
+
680
+
681
+ def with_aliases(summaries, aliases):
682
+ """summaries plus, for each Python entry whose function has an alias, the same entry under the alias."""
683
+ if not aliases:
684
+ return summaries
685
+ by_name = {}
686
+ for alias, name in aliases.items():
687
+ by_name.setdefault(name, []).append(alias)
688
+ return {rule: entries | {(alias, *entry[1:]) for entry in entries if entry[4].endswith(".py")
689
+ for alias in by_name.get(entry[0], ())}
690
+ for rule, entries in summaries.items()}
691
+
692
+
693
+ def realiased(summaries, aliases):
694
+ """summaries with the alias entries made again from their functions' current entries: resummarise can drop a
695
+ parameter from a function (PostHog's validate_credentials no longer passing region) or the function itself."""
696
+ if not aliases:
697
+ return summaries
698
+ return with_aliases({rule: {e for e in entries if e[0] not in aliases} for rule, entries in summaries.items()},
699
+ aliases)
700
+
701
+
702
+ def visible(path, defining_paths, read_text):
703
+ """The call in path can reach one of the summarised definitions of func: it is in the same file, or the file
704
+ imports the module that defines it. An absolute import also matches a module under another folder of the
705
+ project (a monorepo's packages: Dagster's webserver imports dagster._core.storage from
706
+ python_modules/dagster/dagster/_core/storage, GHSA-q93c)."""
707
+ if path in defining_paths:
708
+ return True
709
+ text = read_text(path) or ""
710
+ imports = python_imports(path, text) if path.endswith(".py") else js_imports(path, text)
711
+ normalised = {Path(p).as_posix().removeprefix("./") for p in imports}
712
+ if normalised & set(defining_paths):
713
+ return True
714
+ if not path.endswith(".py"):
715
+ return False
716
+ modules = set(python_absolute_modules(text))
717
+ return any(defining.endswith(tuple(f"/{m}" for m in modules)) for defining in defining_paths) if modules else False
718
+
719
+
720
+ DOTTED_STRING_RE = re.compile(r"""["']([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)+)(?::\w+)?["']""")
721
+
722
+
723
+ def python_string_modules(text):
724
+ """Module files named in a dotted string: what's loaded without an import statement, such as Django's
725
+ MIDDLEWARE and ROOT_URLCONF, include("app.urls"), importlib.import_module("pkg.mod") and entry points
726
+ ("pkg.mod:func"). The string may end in a name inside the module, so its parent is tried too."""
727
+ for match in DOTTED_STRING_RE.finditer(text):
728
+ parts = match.group(1).split(".")
729
+ for stem in ("/".join(parts), "/".join(parts[:-1])):
730
+ if "/" in stem:
731
+ yield f"{stem}.py"
732
+ yield f"{stem}/__init__.py"
733
+
734
+
735
+ def suffix_index(paths):
736
+ """{every path suffix of a Python file ("b.py", "a/b.py", ...): the files ending with it}."""
737
+ by_suffix = {}
738
+ for path in (p for p in paths if p.endswith(".py")):
739
+ parts = path.split("/")
740
+ for k in range(1, len(parts) + 1):
741
+ by_suffix.setdefault("/".join(parts[-k:]), []).append(path)
742
+ return by_suffix
743
+
744
+
745
+ def imported_paths(path, text, by_suffix):
746
+ """The files one file imports, as import_closure resolves them."""
747
+ if not path.endswith(".py"):
748
+ return set(js_imports(path, text))
749
+ targets = {Path(p).as_posix().removeprefix("./") for p in python_imports(path, text)}
750
+ return targets | {d for m in set(python_absolute_modules(text)) | set(python_string_modules(text))
751
+ for d in by_suffix.get(m, ())}
752
+
753
+
754
+ def import_closure(paths, seeds, read_text):
755
+ """seeds plus every file among paths that they import, transitively, resolved as visible() does (relative and
756
+ every-ancestor-root imports, package-qualified absolute imports under another folder, relative JS imports).
757
+ The summary rounds need only these when findings are scored in seeds alone: a function reached from a seed is
758
+ defined in a file the seed imports, directly or through others (step 64). Modules named in dotted strings
759
+ count as imported (python_string_modules); what this can still miss is code reached by neither, such as a
760
+ method called on an object whose class comes from a module nobody here imports."""
761
+ known = set(paths)
762
+ by_suffix = suffix_index(known)
763
+ found = {s for s in seeds if s in known}
764
+ todo = list(found)
765
+ while todo:
766
+ path = todo.pop()
767
+ for target in (imported_paths(path, read_text(path) or "", by_suffix) & known) - found:
768
+ found.add(target)
769
+ todo.append(target)
770
+ return found
771
+
772
+
773
+ def returner_rules(rules, returners=None, base=True):
774
+ """Pass 3: every taint rule with `return` as its sink, reporting the function that returns request data.
775
+
776
+ With returners, calls to them are sources too, so a helper that returns another helper's result is found.
777
+ Without base, those calls are the only sources, and rules with no returners are left out."""
778
+ out = []
779
+ for rule in taint_rules(rules):
780
+ found = (returners or {}).get(rule["id"], ())
781
+ if not base and not found:
782
+ continue
783
+ variant = copy.deepcopy(rule)
784
+ variant["id"] = rule["id"] + RETURNS_SUFFIX
785
+ variant["message"] = FUNC
786
+ variant["pattern-sources"] = (rule["pattern-sources"] if base else []) + from_sources(found, is_js(rule))
787
+ lookup = JS_LOOKUP_SANITIZER if is_js(rule) else LOOKUP_SANITIZER
788
+ variant[SANITIZERS] = [*without_lookup_result(rule), copy.deepcopy(lookup)]
789
+ variant["pattern-sinks"] = copy.deepcopy(JS_RETURN_SINKS if is_js(rule) else PYTHON_RETURN_SINKS)
790
+ out.append(variant)
791
+ return out
792
+
793
+
794
+ def innermost_python_function(text, line):
795
+ """Name of the innermost def around line."""
796
+ best = None
797
+ for name, nodes in python_functions(text).items():
798
+ for node, _ in nodes:
799
+ if node.lineno <= line <= (node.end_lineno or node.lineno) and (best is None or node.lineno > best[1]):
800
+ best = (name, node.lineno)
801
+ return best and best[0]
802
+
803
+
804
+ def parse_returners(results, read_text):
805
+ """{rule id: {(function, defining path)}} from pass 3. A return inside a nested function also binds the outer
806
+ one, so only the innermost Python function counts."""
807
+ returners = {}
808
+ for check_id, path, line, func in results:
809
+ if not func or func.startswith("$") or func in HANDLER_NAMES:
810
+ continue
811
+ if path.endswith(".py"):
812
+ if func in PYTHON_BUILTINS:
813
+ continue
814
+ text = read_text(path)
815
+ if text is None or innermost_python_function(text, line) != func:
816
+ continue
817
+ returners.setdefault(check_id.removesuffix(RETURNS_SUFFIX), set()).add((func, path))
818
+ return returners
819
+
820
+
821
+ def from_sources(found, js):
822
+ """Sources for calls to the returners in found; $RET_FUNC binds the name."""
823
+ names = sorted({func for func, _path in found})
824
+ if not names:
825
+ return []
826
+ receivers = ["this"] if js else sorted(RECEIVERS)
827
+ calls: list[dict] = [{"pattern": c} for c in ("$RET_FUNC(...)", *(f"{r}.$RET_FUNC(...)" for r in receivers))]
828
+ # A module or object named once (services.get_x(), share.perform()), not a chain: Project.objects.create()
829
+ # is Django's, not a view's create() (taiga).
830
+ calls.append({"patterns": [{"pattern": "$MODULE.$RET_FUNC(...)"},
831
+ {"metavariable-regex": {"metavariable": "$MODULE", "regex": "^\\w+$"}}]})
832
+ # Exact: the call's value is the source, not its arguments. Otherwise a call that is also a summarised
833
+ # function's via-sink matches itself (outline: `X.perform(context)`, one class's perform returning request
834
+ # data and another's passing its argument to a query).
835
+ return [{"patterns": [{"pattern-either": calls},
836
+ {"metavariable-regex": {"metavariable": "$RET_FUNC", "regex": regex}}], "exact": True}
837
+ for regex in name_regexes(names)]
838
+
839
+
840
+ def from_rules(rules, returners, summaries):
841
+ """Final-pass variants of each rule whose sources are calls to its returners, with the summarised calls as
842
+ sinks too: "[from get_param()]" names the returner so the finding can be checked for visibility."""
843
+ out = []
844
+ for rule in taint_rules(rules):
845
+ found = returners.get(rule["id"])
846
+ if not found:
847
+ continue
848
+ variant = copy.deepcopy(rule)
849
+ variant["id"] = rule["id"] + FROM_SUFFIX
850
+ variant["pattern-sources"] = from_sources(found, is_js(rule))
851
+ # The pass-through sanitizers stay: they never name a returner (clean_functions leaves them out), and a
852
+ # helper that hands nothing back is as clean fed a returner's value as the request's (MobSF GHSA-8m9j at
853
+ # its fix: redirect(get_redirect_url(req)), req from prepare_django_request(request)).
854
+ variant[SANITIZERS] = without_lookup_result(rule, keep_pass_through=True)
855
+ variant["pattern-sinks"] = rule["pattern-sinks"] + via_sinks(summaries.get(rule["id"], ()), is_js(rule))
856
+ variant["message"] = rule["message"].strip() + KEYWORD_MARK + " [from $RET_FUNC()]"
857
+ out.append(variant)
858
+ return out
859
+
860
+
861
+ def without_lookup_result(rule, keep_pass_through=False):
862
+ """The rule's sanitizers minus lookup-result (python-web.yml, javascript-taint.yml) and the pass-through
863
+ sanitizer, which would also clean get_cmd() when get_cmd is a returner: what the returner pass found overrides
864
+ the name."""
865
+ marks = (LOOKUP_RESULT_MARK, JS_LOOKUP_RESULT_MARK) + (() if keep_pass_through else (PASS_THROUGH_MARK,))
866
+ return [s for s in rule.get(SANITIZERS, []) if not any(mark in repr(s) for mark in marks)]
867
+
868
+
869
+ # Not $FIELD: the JS request sources bind that name (req.$FIELD).
870
+ FIELD_SINKS = {
871
+ False: [{"patterns": [{"pattern": "self.$STORED_FIELD = $VALUE"}, {"focus-metavariable": VALUE}]}],
872
+ True: [{"patterns": [{"pattern": "this.$STORED_FIELD = $VALUE;"}, {"focus-metavariable": VALUE}]}],
873
+ }
874
+
875
+
876
+ def field_rules(rules):
877
+ """Every taint rule with stores to a field of self/this as the sink, reporting the field."""
878
+ out = []
879
+ for rule in taint_rules(rules):
880
+ variant = copy.deepcopy(rule)
881
+ variant["id"] = rule["id"] + FIELDS_SUFFIX
882
+ variant["message"] = "$STORED_FIELD"
883
+ variant["pattern-sinks"] = copy.deepcopy(FIELD_SINKS[is_js(rule)])
884
+ out.append(variant)
885
+ return out
886
+
887
+
888
+ def parse_fields(results):
889
+ """{rule id: {(field, path)}} from field_rules results."""
890
+ fields = {}
891
+ for check_id, path, _line, field in results:
892
+ if field and not field.startswith("$"):
893
+ fields.setdefault(check_id.removesuffix(FIELDS_SUFFIX), set()).add((field, path))
894
+ return fields
895
+
896
+
897
+ def field_variants(rules, fields, summaries):
898
+ """Final-pass variants of each rule whose sources are reads of the fields request data was stored in:
899
+ "[field term]" names the field so the finding can be kept to the file that stores it."""
900
+ out = []
901
+ for rule in taint_rules(rules):
902
+ found = fields.get(rule["id"])
903
+ if not found:
904
+ continue
905
+ names = sorted({field for field, _path in found})
906
+ variant = copy.deepcopy(rule)
907
+ variant["id"] = rule["id"] + FIELD_SUFFIX
908
+ variant["pattern-sources"] = [{"patterns": [
909
+ {"pattern": "this.$STORED_FIELD" if is_js(rule) else "self.$STORED_FIELD"},
910
+ {"metavariable-regex": {"metavariable": "$STORED_FIELD", "regex": regex}},
911
+ ]} for regex in name_regexes(names)]
912
+ variant["pattern-sinks"] = rule["pattern-sinks"] + via_sinks(summaries.get(rule["id"], ()), is_js(rule))
913
+ variant["message"] = rule["message"].strip() + KEYWORD_MARK + " [field $STORED_FIELD]"
914
+ out.append(variant)
915
+ return out
916
+
917
+
918
+ PASS_THROUGH_MARK = "$KEEPS_PARAMS"
919
+ # The mark of the argument sanitizers: what a call's own arguments contribute, kept in every variant (cleaning an
920
+ # argument inside a returner's call leaves the call itself a source).
921
+ ARGUMENT_MARK = "$PT_FUNC"
922
+ # Arguments past this position are never cleaned: a sanitizer per position.
923
+ MAX_ARGUMENT_POSITION = 6
924
+ # Pass-through is a fixpoint: a helper that hands its argument to one that drops it doesn't pass it either
925
+ # (paperless-ngx: a view's request goes three helpers deep to a version number). Each round can only remove.
926
+ PASS_MAX_ROUNDS = 4
927
+
928
+
929
+ # What with_pass_through's sanitizer matches: a variable assigned from a call, or a call returned (a superset; a
930
+ # miss only means a function is never treated as clean). Any receiver: `obj.method(` is asked about too, for
931
+ # other_receiver_methods.
932
+ ASSIGNED_CALL_RE = re.compile(r"(?:=|\breturn\b)\s*(?:await\s+)?(?:\w+(?:\.\w+)*\.)?(\w+)\s*\(")
933
+ # Python only: a call interpolated into an f-string (PostHog GHSA-jrwm: f"{get_base_url(region, subdomain)}users",
934
+ # where only subdomain reaches the URL and region is compared). In JavaScript `{` starts every block.
935
+ FSTRING_CALL_RE = re.compile(r"\{\s*(?:await\s+)?(?:[\w.]+\.)?(\w+)\s*\(")
936
+ # Python only: a call passed straight on as another call's positional argument (munhak-moa GHSA-4q38 at its fix:
937
+ # send_file(get_absolute_path(f"./images/{path}")), the helper returning safe_join(...)). A keyword argument is
938
+ # already `=`. In JavaScript the same shape is mostly callbacks and chains, and js_functions asks only about calls in
939
+ # request-handling files.
940
+ ARGUMENT_CALL_RE = re.compile(r"[(,]\s*(?:await\s+)?(?:[\w.]+\.)?(\w+)\s*\(")
941
+
942
+
943
+ def assigned_calls(texts, python=False):
944
+ """Names of functions whose result some code assigns to a variable or returns (or, for Python, puts in an
945
+ f-string or passes straight to another call)."""
946
+ regexes = (ASSIGNED_CALL_RE, FSTRING_CALL_RE, ARGUMENT_CALL_RE) if python else (ASSIGNED_CALL_RE,)
947
+ return {name for text in texts for regex in regexes for name in regex.findall(text)}
948
+
949
+
950
+ # Rules whose pass-through answer uses their own sanitizers rather than those every rule shares: a helper that
951
+ # checks containment before returning a path (Dagster GHSA-q93c's get_captured_local_path, Vibe-Trading GHSA-mjrq's
952
+ # run_dir at their fixes) hands back nothing for path traversal. One more variant of the pass rules; a variant per
953
+ # rule was the slowest part of a large project's scan.
954
+ OWN_PASS_RULES = {"codewatch.python.web.path-traversal"}
955
+ # A row the ORM has just saved is stored data, as lookup-result says of one read back; pass-through drops
956
+ # lookup-result (its names would hide a returner), so a helper returning `Project.objects.create(owner=owner,
957
+ # **fields)` handed the whole row back as request data and its key reached a file path (codewatch's own
958
+ # create_project, called with fields from the request body). These name no project function.
959
+ ORM_CREATED = [{"pattern": f"$MODEL.objects.{method}(...)"} for method in ("create", "get_or_create", "update_or_create")]
960
+ PASS_RULE_OWN_KEYS = {"id", "message", "metadata", "severity", "pattern-sources", "pattern-sinks", SANITIZERS}
961
+
962
+
963
+ def common_sanitizers(rules):
964
+ """The sanitizers (lookup-result left out) that every one of rules has."""
965
+ if not rules:
966
+ return []
967
+ sanitizers = [[json.dumps(s, sort_keys=True) for s in without_lookup_result(rule)] for rule in rules]
968
+ return [json.loads(s) for s in sanitizers[0] if all(s in others for others in sanitizers[1:])]
969
+
970
+
971
+ def named_sinks(sinks, names):
972
+ """The sinks, each limited to $FUNC among names (a batch of names per copy)."""
973
+ return [{"patterns": [*sink["patterns"], {"metavariable-regex": {"metavariable": FUNC, "regex": regex}}]}
974
+ for sink in sinks for regex in name_regexes(names)]
975
+
976
+
977
+ def grouped_variants(rules, variant_of):
978
+ """[(variant, [ids of the rules it answers for])]: rules whose variants are alike share one."""
979
+ groups = {}
980
+ for rule in rules:
981
+ variant = variant_of(rule)
982
+ groups.setdefault(json.dumps(variant, sort_keys=True), (variant, []))[1].append(rule["id"])
983
+ return list(groups.values())
984
+
985
+
986
+ def python_pass_variant(rule, common, signatures, passes):
987
+ """A rule's part of a pass rule: its own keys gone, the common sanitizers (or its own, for OWN_PASS_RULES),
988
+ ORM_CREATED and, with passes, argument_sanitizers."""
989
+ variant = {k: v for k, v in rule.items() if k not in PASS_RULE_OWN_KEYS}
990
+ variant[SANITIZERS] = copy.deepcopy(
991
+ without_lookup_result(rule) if rule["id"] in OWN_PASS_RULES else common) + copy.deepcopy(ORM_CREATED)
992
+ if passes is not None:
993
+ variant[SANITIZERS] += argument_sanitizers(
994
+ signatures, passing_parameters(passes.get(rule["id"], ())), PYTHON_BUILTINS | HANDLER_NAMES,
995
+ mixed_only=False)
996
+ return variant
997
+
998
+
999
+ def pass_rules(rules, names, signatures=None, passes=None):
1000
+ """Python taint rules with function parameters as sources and `return` as the sink: which parameters of names
1001
+ can be handed back (under the rule's sanitizers). Only the functions whose result is assigned or returned need
1002
+ an answer; every function in a large project meant tens of thousands of results for Semgrep to write out.
1003
+
1004
+ With passes from the last round, the arguments its functions don't hand back are clean (argument_sanitizers)."""
1005
+ if not names:
1006
+ return []
1007
+ sinks = named_sinks(PYTHON_RETURN_SINKS, names)
1008
+ # Sources and sinks are the same for every rule, so rules alike in the rest (propagators) give the same answer:
1009
+ # one variant per such group, its message naming the rules it answers for. Only the sanitizers every rule has
1010
+ # count (a parameter handed back under fewer is still handed back): a group per rule's own sanitizers made
1011
+ # eleven variants, the slowest part of a large project's scan (paperless-ngx).
1012
+ python = [rule for rule in taint_rules(rules) if not is_js(rule)]
1013
+ common = common_sanitizers([rule for rule in python if rule["id"] not in OWN_PASS_RULES])
1014
+ groups = grouped_variants(python, lambda rule: python_pass_variant(rule, common, signatures, passes))
1015
+ return [{**copy.deepcopy(variant), "id": ids[0] + PASSES_SUFFIX, "severity": "INFO",
1016
+ # The source's own function name is bound as $OWNER: the message names the function that returns, the
1017
+ # one whose parameter it is (a nested def can return its outer one's) and which.
1018
+ "message": "$FUNC|$OWNER|$PARAM|" + ",".join(ids),
1019
+ "pattern-sources": json.loads(json.dumps(PYTHON_PARAM_SOURCES).replace(FUNC, "$OWNER")),
1020
+ "pattern-sinks": copy.deepcopy(sinks)}
1021
+ for variant, ids in groups]
1022
+
1023
+
1024
+ # Every shape of JS function the pass rule sees a parameter and a return of. Not an object literal's properties
1025
+ # (`{ onSave: (a) => a }`): matching every object literal doubled the scan's time (actual).
1026
+ JS_PASS_SOURCES = [{"patterns": [{"pattern-either": [{"pattern-inside": p} for p in (
1027
+ "function $OWNER(..., $PARAM, ...) { ... }",
1028
+ "const $OWNER = (..., $PARAM, ...) => $BODY",
1029
+ "const $OWNER = function (..., $PARAM, ...) { ... }",
1030
+ "$OWNER(..., $PARAM, ...) { ... }",
1031
+ "$OBJ.$OWNER = (..., $PARAM, ...) => $BODY",
1032
+ "$OBJ.$OWNER = function (..., $PARAM, ...) { ... }",
1033
+ )]}, {"pattern": PARAM}]}]
1034
+ JS_NOT_HANDLERS = [{"pattern-not-inside": p} for p in (
1035
+ "function $FUNC(..., next) { ... }", "const $FUNC = (..., next) => { ... }", "$FUNC(..., next) { ... }")]
1036
+ JS_PASS_SINKS = [
1037
+ {"patterns": [{"pattern-either": [{"pattern-inside": p} for p in (
1038
+ "function $FUNC(...) { ... }",
1039
+ "const $FUNC = (...) => { ... }",
1040
+ "const $FUNC = function (...) { ... }",
1041
+ "$FUNC(...) { ... }",
1042
+ "$OBJ.$FUNC = (...) => { ... }",
1043
+ "$OBJ.$FUNC = function (...) { ... }",
1044
+ )]}, *JS_NOT_HANDLERS, {"pattern": "return $VALUE;"}, {"focus-metavariable": VALUE}]},
1045
+ # An arrow's expression body is what it returns.
1046
+ {"patterns": [{"pattern-either": [{"pattern": p} for p in (
1047
+ "const $FUNC = (...) => $VALUE", "$OBJ.$FUNC = (...) => $VALUE")]},
1048
+ *({"pattern-not": p} for p in ("const $FUNC = (...) => { ... }", "$OBJ.$FUNC = (...) => { ... }")),
1049
+ {"focus-metavariable": VALUE}]},
1050
+ ]
1051
+ JS_KEYWORDS = {"if", "for", "while", "switch", "catch", "function", "return", "with", "constructor", "super"}
1052
+ # Function definitions in the shapes JS_PASS_SOURCES covers (a miss only means a function is never clean)...
1053
+ JS_DEFINED_RE = re.compile(
1054
+ r"\bfunction\b\s*(?:\*\s*)?(\w+)\s*\("
1055
+ r"|\b(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?(?:function\b|\([^()]*\)\s*(?::[^=;{]+)?=>|\w+\s*=>)"
1056
+ r"|^[ \t]*(?:(?:public|private|protected|static|async|override|get|set)[ \t]+)*(\w+)[ \t]*(?:<[^<>()]*>[ \t]*)?"
1057
+ r"\([^()]*\)\s*(?::[^{;=:]+)?\{[ \t]*$", re.MULTILINE)
1058
+ # ...and in shapes it doesn't: a class field (`handle = (a) => a`), a plain reassignment or an object literal's
1059
+ # property. A name defined either way is never clean.
1060
+ # A method's return type, and a property's outside brackets, holds no colon, so no match reads past the next
1061
+ # `name(): type` or `name:`. A field's modifiers and annotation are on its line; (?<![^\n]) is the start of a line.
1062
+ JS_UNCOVERED_FIELD_RE = re.compile(
1063
+ r"(?<![^\n])[ \t]*(?:(?:public|private|protected|static|readonly|override)[ \t]+)*(\w+)[ \t]*(?:\??:[^=;\r\n]+)?="
1064
+ r"\s*(?:async\s+)?(?:function\b|\(|\w+\s*=>)")
1065
+ JS_UNCOVERED_PROPERTY_RE = re.compile(
1066
+ r"\b(\w+)\s*:\s*(?:async\s+)?(?:function\b|\([^()]*\)\s*(?::(?:[^=;{():]|\((?:[^()]|\([^()]*\))*\))+)?=>|\w+\s*=>)")
1067
+
1068
+
1069
+ # A file that reads the request: Express/Koa handlers and Nest's parameter decorators.
1070
+ JS_REQUEST_RE = re.compile(r"\b(req|request|ctx)\.|@(Body|Query|Param|Req|Headers)\(")
1071
+
1072
+
1073
+ def js_functions(texts):
1074
+ """Names of the JS functions pass-through can answer for: defined only in the shapes JS_PASS_SOURCES covers."""
1075
+ defined, uncovered = set(), set()
1076
+ for text in texts:
1077
+ defined |= {name for groups in JS_DEFINED_RE.findall(text) for name in groups if name}
1078
+ uncovered |= set(JS_UNCOVERED_FIELD_RE.findall(text)) | set(JS_UNCOVERED_PROPERTY_RE.findall(text))
1079
+ return defined - uncovered - JS_KEYWORDS - HANDLER_NAMES
1080
+
1081
+
1082
+ def js_pass_rules(rules, names):
1083
+ """pass_rules for JS taint rules: which functions in names can return a parameter. Per function, not per
1084
+ parameter (no argument sanitizers)."""
1085
+ js = [rule for rule in taint_rules(rules) if is_js(rule)]
1086
+ if not names or not js:
1087
+ return []
1088
+ common = common_sanitizers(js)
1089
+ sinks = named_sinks(JS_PASS_SINKS, names)
1090
+
1091
+ def variant_of(rule):
1092
+ return {**{k: v for k, v in rule.items() if k not in PASS_RULE_OWN_KEYS}, SANITIZERS: copy.deepcopy(common)}
1093
+
1094
+ return [{**copy.deepcopy(variant), "id": ids[0] + PASSES_SUFFIX, "severity": "INFO",
1095
+ "message": "$FUNC|$OWNER|$PARAM|" + ",".join(ids),
1096
+ "pattern-sources": copy.deepcopy(JS_PASS_SOURCES), "pattern-sinks": copy.deepcopy(sinks)}
1097
+ for variant, ids in grouped_variants(js, variant_of)]
1098
+
1099
+
1100
+ ANY_PARAMETER = "*"
1101
+
1102
+
1103
+ def parse_passes(results):
1104
+ """{rule id: {(function, parameter it can return, path)}}; ANY_PARAMETER when the returned one is an
1105
+ enclosing function's (or Semgrep didn't say)."""
1106
+ passes = {}
1107
+ for _check_id, path, _line, message in results:
1108
+ func, owner, param, ids = [*message.split("|", 3), "", "", ""][:4]
1109
+ if not func or func.startswith("$"):
1110
+ continue
1111
+ if owner != func or not param or param.startswith("$"):
1112
+ param = ANY_PARAMETER
1113
+ for rule_id in ids.split(","):
1114
+ passes.setdefault(rule_id, set()).add((func, param, path))
1115
+ return passes
1116
+
1117
+
1118
+ def passing_parameters(found):
1119
+ """{function: parameters it can return} from parse_passes entries."""
1120
+ passing = {}
1121
+ for func, param, *_path in found:
1122
+ passing.setdefault(func, set()).add(param)
1123
+ return passing
1124
+
1125
+
1126
+ def takes_receiver(node, in_class, positional):
1127
+ """A method (not a staticmethod) whose first parameter is self or cls."""
1128
+ static = any(isinstance(d, ast.Name) and d.id == "staticmethod" for d in node.decorator_list)
1129
+ return in_class and not static and bool(positional) and positional[0] in RECEIVERS
1130
+
1131
+
1132
+ def def_signature(node, in_class):
1133
+ """(positional parameters, keyword-only parameters, positional-only count) of a def, self/cls left out of a
1134
+ method's positions; None if it takes nothing else."""
1135
+ args = node.args
1136
+ positional = [a.arg for a in args.posonlyargs + args.args]
1137
+ dropped = int(takes_receiver(node, in_class, positional))
1138
+ positional = positional[dropped:]
1139
+ keyword_only = [a.arg for a in args.kwonlyargs]
1140
+ if not (args.vararg or args.kwarg or positional or keyword_only):
1141
+ return None
1142
+ # *args and **kwargs aren't named by position or keyword: a call can't be cleaned past them.
1143
+ return (tuple(positional) + ((ANY_PARAMETER,) if args.vararg else ()),
1144
+ tuple(keyword_only) + ((ANY_PARAMETER,) if args.kwarg else ()),
1145
+ max(0, len(args.posonlyargs) - dropped))
1146
+
1147
+
1148
+ def python_signatures(texts):
1149
+ """{name: [(positional parameters, keyword-only parameters, positional-only count) per def]} of the project's
1150
+ Python functions that take a parameter other than self/cls (left out of a method's positions)."""
1151
+ signatures = {}
1152
+ for name, nodes in (item for text in texts for item in python_functions(text).items()):
1153
+ for found in (def_signature(node, in_class) for node, in_class in nodes):
1154
+ if found is not None:
1155
+ signatures.setdefault(name, []).append(found)
1156
+ return signatures
1157
+
1158
+
1159
+ def called_names(node):
1160
+ """Names a def's body calls, plainly or as a method."""
1161
+ return {c.func.id if isinstance(c.func, ast.Name) else c.func.attr
1162
+ for c in ast.walk(node) if isinstance(c, ast.Call) and isinstance(c.func, (ast.Name, ast.Attribute))}
1163
+
1164
+
1165
+ def python_callers(texts, callees):
1166
+ """{function name: paths of its defs} for the defs whose body calls one of callees, by name or as a method:
1167
+ what a later round of pass_rules can change. texts: {path: text}."""
1168
+ callers = {}
1169
+ for path, text in texts.items():
1170
+ for name, nodes in python_functions(text).items():
1171
+ if any(not called_names(node).isdisjoint(callees) for node, _in_class in nodes):
1172
+ callers.setdefault(name, set()).add(path)
1173
+ return callers
1174
+
1175
+
1176
+ def python_definers(texts, names):
1177
+ """Paths whose text defines one of names. texts: {path: text}."""
1178
+ return {path for path, text in texts.items() if not names.isdisjoint(python_functions(text))}
1179
+
1180
+
1181
+ def excluded_callees(rule):
1182
+ """Names whose arguments are never cleaned: builtins, handlers, and what the rule's sinks name (a project
1183
+ method called open() mustn't clean the builtin's argument)."""
1184
+ return PYTHON_BUILTINS | HANDLER_NAMES | set(re.findall(r"\w+", repr(rule.get("pattern-sinks", []))))
1185
+
1186
+
1187
+ # Only an argument without a call is cleaned: one with a call can hold a sink, which a sanitizer around it hides
1188
+ # (OWASP Benchmark: escape_for_html(p.read_text()[:1000])).
1189
+ PLAIN_ARGUMENT = {"metavariable-regex": {"metavariable": PT_ARG, "regex": "^[^()]+$"}}
1190
+
1191
+
1192
+ def clean_positions(defs, through):
1193
+ """Argument positions that no def of a name hands back: each def has a parameter there, and it isn't passing."""
1194
+ return [k for k in range(MAX_ARGUMENT_POSITION)
1195
+ if all(k < len(pos) and pos[k] not in through | {ANY_PARAMETER} for pos, _kw, _only in defs)]
1196
+
1197
+
1198
+ def clean_keywords(defs, through):
1199
+ """Keyword names that every def of a name accepts and none hands back; none when a def takes **kwargs."""
1200
+ named = [set(pos[only:]) | set(kw) for pos, kw, only in defs]
1201
+ if any(ANY_PARAMETER in n for n in named):
1202
+ return set()
1203
+ return set.intersection(*named) - through
1204
+
1205
+
1206
+ def clean_arguments(signatures, passing, excluded, mixed_only):
1207
+ """({position: function names}, {function name: keyword names}) of the arguments argument_sanitizers cleans."""
1208
+ positions, by_names = {}, {}
1209
+ for func, defs in (signatures or {}).items():
1210
+ through = passing.get(func, set())
1211
+ if func in excluded or (mixed_only and not through) or ANY_PARAMETER in through:
1212
+ continue
1213
+ for k in clean_positions(defs, through):
1214
+ positions.setdefault(k, set()).add(func)
1215
+ if safe := clean_keywords(defs, through):
1216
+ by_names[func] = safe
1217
+ return positions, by_names
1218
+
1219
+
1220
+ def positional_sanitizers(positions):
1221
+ """A sanitizer per argument position and batch of names: `f(a, b, $PT_ARG, ...)`, plain or on self/cls."""
1222
+ sanitizers = []
1223
+ for k, funcs in sorted(positions.items()):
1224
+ args = ", ".join([*(f"$PT_{i}" for i in range(k)), PT_ARG, "..."])
1225
+ sanitizers += [{"patterns": [
1226
+ {"pattern-either": [{"pattern": f"{r}{ARGUMENT_MARK}({args})"} for r in ("", "self.", "cls.")]},
1227
+ {"metavariable-regex": {"metavariable": ARGUMENT_MARK, "regex": regex}},
1228
+ PLAIN_ARGUMENT,
1229
+ {"focus-metavariable": PT_ARG},
1230
+ ]} for regex in name_regexes(funcs)]
1231
+ return sanitizers
1232
+
1233
+
1234
+ def keyword_terms(batch):
1235
+ """Comparison terms pairing each group of functions with its own keyword names, functions with the same names
1236
+ grouped. batch: {function name: keyword names}."""
1237
+ groups = {}
1238
+ for func, names in batch.items():
1239
+ groups.setdefault(frozenset(names), set()).add(func)
1240
+ return [f're.match("{f}", str($PT_FUNC)) and re.match("{k}", str($PT_KW))'
1241
+ for names, group in sorted(groups.items(), key=lambda item: sorted(item[1]))
1242
+ for f in name_regexes(group) for k in name_regexes(names)]
1243
+
1244
+
1245
+ def keyword_batch_sanitizers(batch):
1246
+ """The keyword sanitizers for one batch of functions: plain name filters first (the comparison is slow), then
1247
+ the comparison, at most NAME_BATCH terms per sanitizer."""
1248
+ terms = keyword_terms(batch)
1249
+ funcs_filter = {"metavariable-regex": {"metavariable": ARGUMENT_MARK, "regex": name_regexes(batch)[0]}}
1250
+ names = set().union(*batch.values())
1251
+ names_filter = [{"metavariable-regex": {"metavariable": "$PT_KW", "regex": regex}}
1252
+ for regex in name_regexes(names)][:1] if len(names) <= NAME_BATCH else []
1253
+ return [{"patterns": [
1254
+ {"pattern-either": [{"pattern": f"{r}{ARGUMENT_MARK}(..., $PT_KW=$PT_ARG, ...)"}
1255
+ for r in ("", "self.", "cls.")]},
1256
+ funcs_filter, *names_filter,
1257
+ {"metavariable-comparison": {"comparison": " or ".join(f"({t})" for t in terms[i:i + NAME_BATCH])}},
1258
+ PLAIN_ARGUMENT,
1259
+ {"focus-metavariable": PT_ARG},
1260
+ ]} for i in range(0, len(terms), NAME_BATCH)]
1261
+
1262
+
1263
+ def keyword_sanitizers(by_names):
1264
+ """One sanitizer for every keyword, its comparison pairing each function with its own keywords: a pattern per
1265
+ keyword made the final scan half as slow again (djangoproject.com). Each covers one batch of functions, its
1266
+ filter naming them: with one filter over every function, a project with more than a batch (mlflow, 3,282) had
1267
+ none, and every keyword argument in every file ran thousands of comparisons (PLAN.md step 68)."""
1268
+ funcs = sorted(by_names)
1269
+ return [sanitizer for start in range(0, len(funcs), NAME_BATCH)
1270
+ for sanitizer in keyword_batch_sanitizers({func: by_names[func] for func in funcs[start:start + NAME_BATCH]})]
1271
+
1272
+
1273
+ def argument_sanitizers(signatures, passing, excluded: set[str] | frozenset[str] = frozenset(), mixed_only=True):
1274
+ """Sanitizers for each argument of a call to the project's functions that the function can't hand back:
1275
+ `self.resolve(doc, request)` is the doc's data, not the request's, when resolve returns only what it looks up
1276
+ with the request. A position is clean only when it is a parameter that isn't passed in every def of the name.
1277
+
1278
+ mixed_only: only for functions that hand back some parameter. One that hands back none has the cheaper result
1279
+ sanitizer in the final scan (with_pass_through); pass_rules have no such sanitizer and need every function."""
1280
+ positions, by_names = clean_arguments(signatures, passing, excluded, mixed_only)
1281
+ return positional_sanitizers(positions) + keyword_sanitizers(by_names)
1282
+
1283
+
1284
+ def with_arguments(rules, signatures, passes, summaries=None):
1285
+ """Each Python taint rule plus argument_sanitizers for its passes; a summarised function's arguments reach a
1286
+ sink, so they stay as they are."""
1287
+ out = []
1288
+ for rule in rules:
1289
+ if rule not in taint_rules([rule]) or is_js(rule) or not signatures:
1290
+ out.append(rule)
1291
+ continue
1292
+ summarised = {func for func, *_ in (summaries or {}).get(rule["id"], ())}
1293
+ extra = argument_sanitizers(signatures, passing_parameters(passes.get(rule["id"], ())),
1294
+ excluded_callees(rule) | summarised)
1295
+ out.append({**rule, SANITIZERS: [*rule.get(SANITIZERS, []), *extra]} if extra else rule)
1296
+ return out
1297
+
1298
+
1299
+ def clean_functions(rule, functions, passes, summaries, returners):
1300
+ """with_pass_through's functions for rule: asked about, and not passing, summarised or a returner."""
1301
+ rule_id = rule["id"]
1302
+ return sorted(set(functions.get(is_js(rule), ()))
1303
+ - set(passing_parameters(passes.get(rule_id, ())))
1304
+ - {func for func, *_ in summaries.get(rule_id, ())}
1305
+ - {func for func, _path in returners.get(rule_id, ())}
1306
+ - HANDLER_NAMES)
1307
+
1308
+
1309
+ def partly_passing(signatures, passing):
1310
+ """Functions that hand back some of their parameters but not all, whose other arguments with_arguments cleans."""
1311
+ return {func for func, defs in (signatures or {}).items()
1312
+ if (through := passing.get(func)) and ANY_PARAMETER not in through
1313
+ and any((set(pos) | set(kw)) - through for pos, kw, _only in defs)}
1314
+
1315
+
1316
+ def stale_summaries(rules, summaries, texts, known):
1317
+ """{rule id: summarised Python functions} whose body calls one that clean_functions says hands nothing back, or
1318
+ (with signatures) one that hands back only some parameters: pass 1 ran before the passes were known, so their
1319
+ summary may rest on that call's result. PostHog GHSA-jrwm: validate_credentials builds its URL with
1320
+ get_base_url(region, subdomain), which hands back subdomain only, so region doesn't reach the request.
1321
+ texts: {path: text}; known: (functions, passes, signatures or None)."""
1322
+ functions, passes, signatures = known
1323
+ stale = {}
1324
+ for rule in taint_rules(rules):
1325
+ found = summaries.get(rule["id"])
1326
+ if not found or is_js(rule):
1327
+ continue
1328
+ summarised_names = {func for func, *_ in found}
1329
+ clean = set(clean_functions(rule, functions, passes, summaries, {})) | (
1330
+ partly_passing(signatures, passing_parameters(passes.get(rule["id"], ()))) - summarised_names)
1331
+ summarised = {func for func, *_ in found}
1332
+ callers = set(python_callers(texts, clean)) & summarised if clean else set()
1333
+ if callers:
1334
+ stale[rule["id"]] = callers
1335
+ return stale
1336
+
1337
+
1338
+ PLAIN_ARGUMENTS = {"metavariable-regex": {"metavariable": "$...PT_ARGS", "regex": "^[^()]*$"}}
1339
+
1340
+
1341
+ def pass_through_mark(regex):
1342
+ return {"metavariable-regex": {"metavariable": PASS_THROUGH_MARK, "regex": regex}}
1343
+
1344
+
1345
+ def result_sanitizers(clean, js):
1346
+ """A clean function's result assigned and used, and (Python) the call itself inside an expression."""
1347
+ receivers, end = (("", "this."), ";") if js else (("", "self.", "cls."), "")
1348
+ calls = [f"{a}{r}{PASS_THROUGH_MARK}(...){end}" for a in ("", "await ") for r in receivers]
1349
+ sanitizers = [{"patterns": [{"pattern-either": [{"pattern-inside": f"$RESULT = {c}\n...\n"} for c in calls]},
1350
+ {"pattern": "$RESULT"}, pass_through_mark(regex)]}
1351
+ for regex in name_regexes(clean)]
1352
+ if js:
1353
+ return sanitizers
1354
+ # The call itself, where its result is used inside an expression (`self.run_dir(run_id) / "run.json"`,
1355
+ # Vibe-Trading GHSA-mjrq at its fix), only when no argument holds a call: a sanitizer on a call hides sinks
1356
+ # among its arguments.
1357
+ return sanitizers + [{"patterns": [
1358
+ {"pattern-either": [{"pattern": f"{r}{PASS_THROUGH_MARK}($...PT_ARGS)"} for r in receivers]},
1359
+ pass_through_mark(regex), PLAIN_ARGUMENTS]} for regex in name_regexes(clean)]
1360
+
1361
+
1362
+ def any_receiver_sanitizers(methods):
1363
+ """A Python method that hands nothing back is clean on any receiver too, unless every library has its name."""
1364
+ return [{"patterns": [
1365
+ {"pattern-either": [{"pattern-inside": f"$RESULT = {a}$OBJ.{PASS_THROUGH_MARK}(...)\n...\n"}
1366
+ for a in ("", "await ")]},
1367
+ {"pattern": "$RESULT"}, pass_through_mark(regex)]} for regex in name_regexes(methods)] + [{"patterns": [
1368
+ {"pattern": f"$OBJ.{PASS_THROUGH_MARK}($...PT_ARGS)"}, pass_through_mark(regex), PLAIN_ARGUMENTS,
1369
+ ]} for regex in name_regexes(methods)]
1370
+
1371
+
1372
+ def with_pass_through(rules, functions, passes, summaries, returners):
1373
+ """Each taint rule plus a sanitizer for the result of calls to functions that can't return a parameter: not
1374
+ found by pass_rules (js_pass_rules for JS), not summarised (a call to one is a via-sink) and not a returner.
1375
+ functions: {is_js: names asked about}. A plain call or one on self/cls/this; in Python also one on another
1376
+ object, for names not in GENERIC_METHODS (`obj.check(x)` may be anyone's)."""
1377
+ out = []
1378
+ for rule in rules:
1379
+ clean = clean_functions(rule, functions, passes, summaries, returners) if rule in taint_rules([rule]) else []
1380
+ if not clean:
1381
+ out.append(rule)
1382
+ continue
1383
+ js = is_js(rule)
1384
+ methods = [] if js else sorted(set(clean) - GENERIC_METHODS)
1385
+ sanitizers = result_sanitizers(clean, js) + any_receiver_sanitizers(methods)
1386
+ out.append({**rule, SANITIZERS: [*rule.get(SANITIZERS, []), *sanitizers]})
1387
+ return out