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.
- codewatch/__init__.py +0 -0
- codewatch/__main__.py +14 -0
- codewatch/asgi.py +16 -0
- codewatch/settings.py +175 -0
- codewatch/urls.py +40 -0
- codewatch/wsgi.py +16 -0
- codewatch_scan-0.1.0.dist-info/METADATA +81 -0
- codewatch_scan-0.1.0.dist-info/RECORD +136 -0
- codewatch_scan-0.1.0.dist-info/WHEEL +5 -0
- codewatch_scan-0.1.0.dist-info/entry_points.txt +4 -0
- codewatch_scan-0.1.0.dist-info/licenses/LICENSE +21 -0
- codewatch_scan-0.1.0.dist-info/top_level.txt +2 -0
- core/__init__.py +0 -0
- core/analyzers/__init__.py +19 -0
- core/analyzers/accessibility.py +199 -0
- core/analyzers/base.py +192 -0
- core/analyzers/body_models.py +154 -0
- core/analyzers/codewatch_checks.py +394 -0
- core/analyzers/constant_branches.py +251 -0
- core/analyzers/containers.py +316 -0
- core/analyzers/coverage.py +131 -0
- core/analyzers/dependencies.py +347 -0
- core/analyzers/drf_serializers.py +65 -0
- core/analyzers/else_branches.py +106 -0
- core/analyzers/extra.py +400 -0
- core/analyzers/flask_resources.py +65 -0
- core/analyzers/inline_scripts.py +50 -0
- core/analyzers/jinja_sandboxes.py +63 -0
- core/analyzers/match_statements.py +148 -0
- core/analyzers/multi_tools.py +888 -0
- core/analyzers/php_template_sinks.py +444 -0
- core/analyzers/project_checks.py +150 -0
- core/analyzers/python_tools.py +333 -0
- core/analyzers/route_converters.py +237 -0
- core/analyzers/slices.py +94 -0
- core/analyzers/starred_targets.py +42 -0
- core/analyzers/stored_fields.py +386 -0
- core/analyzers/summaries.py +1387 -0
- core/analyzers/template_sinks.py +162 -0
- core/api.py +360 -0
- core/apps.py +6 -0
- core/benchmark.py +955 -0
- core/bundled/catalog/codewatch/rules/javascript-crypto.yml +224 -0
- core/bundled/catalog/codewatch/rules/javascript-injection.yml +116 -0
- core/bundled/catalog/codewatch/rules/javascript-taint.yml +1539 -0
- core/bundled/catalog/codewatch/rules/javascript-web.yml +562 -0
- core/bundled/catalog/codewatch/rules/php-web.yml +719 -0
- core/bundled/catalog/codewatch/rules/python-crypto.yml +203 -0
- core/bundled/catalog/codewatch/rules/python-django.yml +267 -0
- core/bundled/catalog/codewatch/rules/python-injection.yml +115 -0
- core/bundled/catalog/codewatch/rules/python-web.yml +3382 -0
- core/bundled/catalog/custom/mappings.json +360 -0
- core/bundled/catalog/custom/overrides.json +4 -0
- core/bundled/catalog/custom/rules/django-settings.yml +19 -0
- core/bundled/catalog/imported/changes.json +5 -0
- core/bundled/catalog/imported/docs.json +1143 -0
- core/bundled/catalog/imported/meta.json +54 -0
- core/bundled/catalog/imported/rules.json +85421 -0
- core/bundled/catalog/imported/standards.json +11191 -0
- core/bundled/tools/analyzers.lock +786 -0
- core/bundled/tools/axe-scan.mjs +45 -0
- core/bundled/tools/checkov.lock +2463 -0
- core/bundled/tools/codewatch-checks.mjs +99 -0
- core/bundled/tools/eslint-a11y.config.js +16 -0
- core/bundled/tools/eslint-quality.config.js +63 -0
- core/bundled/tools/eslint-typed.config.js +18 -0
- core/bundled/tools/package-lock.json +6102 -0
- core/bundled/tools/package.json +32 -0
- core/bundled/tools/rule-metadata.mjs +56 -0
- core/bundled/tools/semgrep.lock +1232 -0
- core/bundled/tools/stylelint.config.json +11 -0
- core/catalog/__init__.py +190 -0
- core/catalog/build.py +84 -0
- core/catalog/merge.py +122 -0
- core/catalog/sources.py +418 -0
- core/catalog/standards.py +119 -0
- core/catalog/update.py +99 -0
- core/catalog_views.py +115 -0
- core/client.py +645 -0
- core/collect.py +518 -0
- core/duplicates.py +60 -0
- core/fingerprint.py +25 -0
- core/folders.py +73 -0
- core/gate.py +77 -0
- core/git.py +149 -0
- core/jobs.py +86 -0
- core/management/__init__.py +0 -0
- core/management/commands/__init__.py +0 -0
- core/management/commands/addproject.py +40 -0
- core/management/commands/buildcatalog.py +15 -0
- core/management/commands/scan.py +74 -0
- core/management/commands/updatecatalog.py +14 -0
- core/mcp_server.py +140 -0
- core/middleware.py +17 -0
- core/migrations/0001_initial.py +115 -0
- core/migrations/0002_auth_tokens_a11y.py +60 -0
- core/migrations/0003_default_admin.py +43 -0
- core/migrations/0004_project_members.py +28 -0
- core/migrations/0005_uploads_and_sources.py +55 -0
- core/migrations/0006_thresholds.py +28 -0
- core/migrations/0007_also_reported_by.py +18 -0
- core/migrations/0008_new_code_period.py +18 -0
- core/migrations/0009_resolution_safe.py +18 -0
- core/migrations/0010_analysis_progress.py +18 -0
- core/migrations/0011_overall_gate_conditions.py +20 -0
- core/migrations/__init__.py +0 -0
- core/models.py +323 -0
- core/network.py +41 -0
- core/paths.py +29 -0
- core/ratings.py +67 -0
- core/runner.py +168 -0
- core/templates/core/account.html +30 -0
- core/templates/core/analysis.html +49 -0
- core/templates/core/base.html +121 -0
- core/templates/core/form_table.html +12 -0
- core/templates/core/gate_badge.html +1 -0
- core/templates/core/index.html +26 -0
- core/templates/core/issues.html +38 -0
- core/templates/core/login.html +13 -0
- core/templates/core/new_project.html +27 -0
- core/templates/core/password_change.html +10 -0
- core/templates/core/project.html +40 -0
- core/templates/core/rating.html +1 -0
- core/templates/core/ratings.html +32 -0
- core/templates/core/rule.html +33 -0
- core/templates/core/rules.html +42 -0
- core/templates/core/scan_progress.html +2 -0
- core/templates/core/settings.html +36 -0
- core/templates/core/source.html +15 -0
- core/templates/core/standards.html +30 -0
- core/templates/core/user_edit.html +15 -0
- core/templates/core/users.html +18 -0
- core/templatetags/__init__.py +0 -0
- core/templatetags/codewatch.py +42 -0
- core/tool_setup.py +68 -0
- core/views.py +564 -0
|
@@ -0,0 +1,444 @@
|
|
|
1
|
+
"""PHP template variables printed unescaped, as sinks for a copy of the PHP XSS rule (codewatch.php.web.template.xss).
|
|
2
|
+
|
|
3
|
+
Twig, Blade and Latte escape what a template prints, except where it says not to: Twig's `{{ x|raw }}` and
|
|
4
|
+
`{% autoescape false %}` (or an Environment made with 'autoescape' => false, as OpenCart does), Blade's `{!! $x !!}`,
|
|
5
|
+
Latte's `{$x|noescape}`. Smarty escapes nothing unless the project turns escape_html on, so a `{$x}` without an
|
|
6
|
+
escaping modifier is raw. A plain PHP view (CakePHP's .ctp and templates/, CodeIgniter's and Laravel's non-Blade
|
|
7
|
+
views, any .phtml) prints `<?= $x ?>` raw unless the expression escapes it (h(), htmlspecialchars(), e(), esc_html()...).
|
|
8
|
+
|
|
9
|
+
The argument that sets such a variable is a sink: in a call naming the template (Twig's render/renderView/display,
|
|
10
|
+
Laravel's view()/View::make() and ->with(), CodeIgniter's load->view(), Latte's render, CakePHP's element()), or,
|
|
11
|
+
where the call doesn't name one (Smarty's assign(), CakePHP's $this->set(), Nette's $template->x = ...), by the
|
|
12
|
+
variable's name alone, against the templates of that kind. The finding's message names the template (or the
|
|
13
|
+
variable), so a fix made in the template can be matched to it (core/benchmark.py).
|
|
14
|
+
"""
|
|
15
|
+
import re
|
|
16
|
+
from pathlib import PurePosixPath
|
|
17
|
+
|
|
18
|
+
TEMPLATE_RULE = "codewatch.php.web.template.xss"
|
|
19
|
+
XSS_RULE = "codewatch.php.web.xss"
|
|
20
|
+
# Files read as templates: by extension, and PHP views by folder.
|
|
21
|
+
PHP_VIEW_DIR_RE = re.compile(r"(^|/)(views?|View|templates?|Template|Elements?|element|layouts?|Layout)/")
|
|
22
|
+
PHP_VIEW_SUFFIXES = (".php", ".ctp", ".phtml")
|
|
23
|
+
VAR_RE = re.compile(r"\$([A-Za-z_]\w*)")
|
|
24
|
+
|
|
25
|
+
# Twig: {{ name...|raw }} and everything under {% autoescape false %}.
|
|
26
|
+
# The name ends where the filters start, so the two parts can't trade characters; a block's contents can't hold another
|
|
27
|
+
# opener, so a file of unclosed tags is read once rather than once per tag.
|
|
28
|
+
TWIG_PRINT_RE = re.compile(r"\{\{-?\s*([A-Za-z_]\w*)(?!\w)([^{}]*?)-?\}\}")
|
|
29
|
+
TWIG_AUTOESCAPE_OFF_RE = re.compile(
|
|
30
|
+
r"\{%-?\s*autoescape\s+false\s*-?%\}((?:(?!\{%-?\s*autoescape\b)[\s\S])*?)\{%-?\s*endautoescape\s*-?%\}")
|
|
31
|
+
TWIG_FOR_RE = re.compile(r"\{%-?\s*for\s+(\w+)(?:\s*,\s*\w+)?\s+in\s+([A-Za-z_]\w*)")
|
|
32
|
+
TWIG_KEYWORDS = {"loop", "app", "_self", "_context", "true", "false", "null", "not", "attribute", "include", "block",
|
|
33
|
+
"parent", "range", "constant", "dump", "source", "path", "url", "asset", "csrf_token", "form"}
|
|
34
|
+
TWIG_SAFE_FILTER_RE = re.compile(r"\|\s*(e|escape|striptags|length|abs|round|number_format|date|json_encode|"
|
|
35
|
+
r"url_encode|trans|default\(\s*['\"][^'\"]*['\"]\s*\)\s*\|\s*e)\b")
|
|
36
|
+
TWIG_OFF_RE = re.compile(r"['\"]autoescape['\"]\s*=>\s*false")
|
|
37
|
+
# Blade: {!! $name ... !!}.
|
|
38
|
+
BLADE_RAW_RE = re.compile(r"\{!!((?:[^!{]|!(?!!\})|\{(?!!!))*)!!\}")
|
|
39
|
+
# Latte: {$name|noescape} and the old {!$name}.
|
|
40
|
+
LATTE_RAW_RE = re.compile(r"\{(?:!\s*(\$\w+)(?!\w)[^{}]*|(\$\w+)(?!\w)(?:[^{}|]|\|(?!\s*noescape))*\|\s*noescape[^{}]*)\}")
|
|
41
|
+
# Smarty: {$name|modifier...}, raw unless a modifier escapes or the project escapes by default.
|
|
42
|
+
SMARTY_PRINT_RE = re.compile(r"\{\$(\w+)(?!\w)([^{}]*)\}")
|
|
43
|
+
SMARTY_SAFE_RE = re.compile(r"\|\s*(escape|strip_tags|intval|floatval|count|date_format|string_format|"
|
|
44
|
+
r"number_format|urlencode|json_encode)\b|\bnofilter\b")
|
|
45
|
+
SMARTY_ESCAPE_ON_RE = re.compile(r"escape_html\s*=\s*true|setEscapeHtml\s*\(\s*true")
|
|
46
|
+
# A plain PHP view's printed expressions: <?= ... ?>, and echo/print statements anywhere in its PHP.
|
|
47
|
+
SHORT_ECHO_RE = re.compile(r"<\?=((?:[^?<]|\?(?!>)|<(?!\?=))*)\?>")
|
|
48
|
+
ECHO_RE = re.compile(r"\b(?:echo|print)\b")
|
|
49
|
+
PHP_FOREACH_RE = re.compile(r"foreach\s*\(\s*\$(\w+)\s+as\s+(?:\$\w+\s*=>\s*)?\$(\w+)")
|
|
50
|
+
# Calls whose result can't carry markup: escapers and encoders, numbers, booleans and counts.
|
|
51
|
+
ESCAPING_CALL_RE = re.compile(
|
|
52
|
+
r"(?i)^(h|e|htmlspecialchars|htmlentities|esc_\w+|(?=\w*escape)\w+|strip_tags|intval|floatval|boolval|"
|
|
53
|
+
r"count|sizeof|number_format|json_encode|urlencode|rawurlencode|date|strlen|mb_strlen|md5|sha1|base64_encode|"
|
|
54
|
+
r"purify|wp_kses\w*|sanitize_\w+|filter_var|empty|isset|is_\w+|in_array|array_key_exists|\$this->.*)$")
|
|
55
|
+
CAST_RE = re.compile(r"\(\s*(int|integer|float|double|bool|boolean)\s*\)\s*$")
|
|
56
|
+
NAME_RE = re.compile(r"(?<![\w\\])(\$this(?:->\w+)+|[A-Za-z_\\][\w\\]*(?:::\w+)?)\s*$")
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def string_end(text, i):
|
|
60
|
+
"""Index of the quote closing the string that opens at i (past the end if it is unclosed); backslashes escape."""
|
|
61
|
+
quote, i = text[i], i + 1
|
|
62
|
+
while i < len(text) and text[i] != quote:
|
|
63
|
+
i += 2 if text[i] == "\\" else 1
|
|
64
|
+
return i
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def escaping_frame(expression, i):
|
|
68
|
+
"""Whether the bracket at i opens an escaping call (or a $this-> helper, which escapes by default)."""
|
|
69
|
+
name = NAME_RE.search(expression[:i])
|
|
70
|
+
return bool(name and ESCAPING_CALL_RE.match(name.group(1).replace(" ", "")))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def printed_in_string(expression, i, end, frames):
|
|
74
|
+
"""The variables a double-quoted string interpolates, when nothing around it escapes."""
|
|
75
|
+
if expression[i] != '"' or any(frames):
|
|
76
|
+
return set()
|
|
77
|
+
return {v for v in VAR_RE.findall(expression[i + 1:end]) if v != "this"}
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def printed_variable(expression, i, frames):
|
|
81
|
+
"""(the variable at i if it prints unescaped, else None; where scanning resumes)."""
|
|
82
|
+
m = re.match(r"\$(\w+)", expression[i:])
|
|
83
|
+
if not m:
|
|
84
|
+
return None, i + 1
|
|
85
|
+
name = m.group(1)
|
|
86
|
+
printed = name != "this" and not any(frames) and not CAST_RE.search(expression[:i])
|
|
87
|
+
return (name if printed else None), i + len(m.group(0))
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def printed_variables(expression):
|
|
91
|
+
"""The variables an expression prints unescaped: each $name not inside an escaping call (or a $this-> helper,
|
|
92
|
+
which escapes by default), nor cast to a number. Double-quoted strings print the variables they interpolate."""
|
|
93
|
+
found, frames, i = set(), [], 0
|
|
94
|
+
while i < len(expression):
|
|
95
|
+
c = expression[i]
|
|
96
|
+
if c in "'\"":
|
|
97
|
+
end = string_end(expression, i)
|
|
98
|
+
found |= printed_in_string(expression, i, end, frames)
|
|
99
|
+
i = end + 1
|
|
100
|
+
continue
|
|
101
|
+
if c == "$":
|
|
102
|
+
name, i = printed_variable(expression, i, frames)
|
|
103
|
+
found |= {name} if name else set()
|
|
104
|
+
continue
|
|
105
|
+
if c == "(":
|
|
106
|
+
frames.append(escaping_frame(expression, i))
|
|
107
|
+
elif c == ")" and frames:
|
|
108
|
+
frames.pop()
|
|
109
|
+
i += 1
|
|
110
|
+
return found
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def statement_end(text, start):
|
|
114
|
+
"""Where the PHP statement beginning at start ends: its ; or ?> outside strings and brackets."""
|
|
115
|
+
depth, i, n = 0, start, len(text)
|
|
116
|
+
while i < n:
|
|
117
|
+
c = text[i]
|
|
118
|
+
if c in "'\"":
|
|
119
|
+
i = string_end(text, i)
|
|
120
|
+
elif c in "([{":
|
|
121
|
+
depth += 1
|
|
122
|
+
elif c in ")]}":
|
|
123
|
+
depth -= 1
|
|
124
|
+
elif depth <= 0 and (c == ";" or text.startswith("?>", i)):
|
|
125
|
+
return i
|
|
126
|
+
i += 1
|
|
127
|
+
return n
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def printed_expressions(text):
|
|
131
|
+
return ([m.group(1) for m in SHORT_ECHO_RE.finditer(text)]
|
|
132
|
+
+ [text[m.end():statement_end(text, m.end())] for m in ECHO_RE.finditer(text)])
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
TWIG, BLADE, LATTE, SMARTY, PHP = "twig", "blade", "latte", "smarty", "php"
|
|
136
|
+
KIND_SUFFIXES = ((".twig", TWIG), (".blade.php", BLADE), (".latte", LATTE))
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def is_php_view(lower, path, text):
|
|
140
|
+
"""A .ctp or .phtml file, or a .php file in a view folder that leaves PHP mode and defines no class."""
|
|
141
|
+
if lower.endswith((".ctp", ".phtml")):
|
|
142
|
+
return True
|
|
143
|
+
return (lower.endswith(".php") and bool(PHP_VIEW_DIR_RE.search(path)) and "?>" in text
|
|
144
|
+
and not re.search(r"^[ \t]*(?:abstract\s+|final\s+)?class\s", text, re.MULTILINE))
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def kind(path, text):
|
|
148
|
+
"""The template kind of a file: twig, blade, latte, smarty, php (a plain PHP view), or None."""
|
|
149
|
+
lower = path.lower()
|
|
150
|
+
if found := next((k for suffix, k in KIND_SUFFIXES if lower.endswith(suffix)), None):
|
|
151
|
+
return found
|
|
152
|
+
if lower.endswith(".tpl"):
|
|
153
|
+
# OpenCart 2's and others' .tpl files are plain PHP.
|
|
154
|
+
return PHP if ("<?php" in text or "<?=" in text) else SMARTY
|
|
155
|
+
return PHP if is_php_view(lower, path, text) else None
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def names(path, kind_):
|
|
159
|
+
"""The names a call can give this template: every tail of its path, with and without the extension, and for
|
|
160
|
+
Blade and plain PHP views the dotted form (`admin.users.show`)."""
|
|
161
|
+
stem = path
|
|
162
|
+
for suffix in (".blade.php", ".html.twig", ".twig", ".latte", ".tpl", ".ctp", ".phtml", ".php"):
|
|
163
|
+
if stem.lower().endswith(suffix):
|
|
164
|
+
stem = stem[: -len(suffix)]
|
|
165
|
+
break
|
|
166
|
+
parts = PurePosixPath(path).parts
|
|
167
|
+
stem_parts = PurePosixPath(stem).parts
|
|
168
|
+
found = set()
|
|
169
|
+
for i in range(len(parts)):
|
|
170
|
+
found.add("/".join(parts[i:]))
|
|
171
|
+
found.add("/".join(stem_parts[i:]))
|
|
172
|
+
if kind_ in (BLADE, PHP):
|
|
173
|
+
found.add(".".join(stem_parts[i:]))
|
|
174
|
+
return {n for n in found if n}
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def followed(name, loops):
|
|
178
|
+
"""A loop variable traced back to the list it walks."""
|
|
179
|
+
seen = set()
|
|
180
|
+
while name in loops and name not in seen:
|
|
181
|
+
seen.add(name)
|
|
182
|
+
name = loops[name]
|
|
183
|
+
return name
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def twig_raw(text, all_raw):
|
|
187
|
+
loops = dict(TWIG_FOR_RE.findall(text))
|
|
188
|
+
printed = [(n, f) for n, f in TWIG_PRINT_RE.findall(text) if all_raw or re.search(r"\|\s*raw\b", f)]
|
|
189
|
+
for block in TWIG_AUTOESCAPE_OFF_RE.findall(text):
|
|
190
|
+
printed += TWIG_PRINT_RE.findall(block)
|
|
191
|
+
raw = set()
|
|
192
|
+
for name, filters in printed:
|
|
193
|
+
before_raw = re.split(r"\|\s*raw\b", filters)[0]
|
|
194
|
+
if TWIG_SAFE_FILTER_RE.search(before_raw):
|
|
195
|
+
continue
|
|
196
|
+
if (traced := followed(name, loops)) not in TWIG_KEYWORDS:
|
|
197
|
+
raw.add(traced)
|
|
198
|
+
return raw
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def php_raw(text):
|
|
202
|
+
"""Variables a PHP view prints unescaped. One the view assigns itself is its own, not what the controller
|
|
203
|
+
passed (MISP's populate_event_from_template.ctp rebuilds $fileArray, escaped, before printing it)."""
|
|
204
|
+
loops = {item: items for items, item in PHP_FOREACH_RE.findall(text)}
|
|
205
|
+
own = set(re.findall(r"\$(\w+)\s*(?:\[[^\][]*\]\s*)*=(?!=|>)", text))
|
|
206
|
+
raw = set()
|
|
207
|
+
for expression in printed_expressions(text):
|
|
208
|
+
raw.update(followed(name, loops) for name in printed_variables(expression))
|
|
209
|
+
return {name for name in raw if name not in own}
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def smarty_raw(text, escapes_by_default):
|
|
213
|
+
return {name for name, rest in SMARTY_PRINT_RE.findall(text)
|
|
214
|
+
if not SMARTY_SAFE_RE.search(rest) and (not escapes_by_default or "nofilter" in rest)}
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
RAW_VARIABLES = {
|
|
218
|
+
TWIG: lambda text, settings: twig_raw(text, settings["twig_off"]),
|
|
219
|
+
BLADE: lambda text, _settings: {v for expression in BLADE_RAW_RE.findall(text)
|
|
220
|
+
for v in printed_variables(expression.strip())},
|
|
221
|
+
LATTE: lambda text, _settings: {(a or b).lstrip("$") for a, b in LATTE_RAW_RE.findall(text)},
|
|
222
|
+
SMARTY: lambda text, settings: smarty_raw(text, settings["smarty_escapes"]),
|
|
223
|
+
PHP: lambda text, _settings: php_raw(text),
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def raw_variables(text, kind_, settings):
|
|
228
|
+
return RAW_VARIABLES[kind_](text, settings) if kind_ in RAW_VARIABLES else set()
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def unescaped(templates, php_texts=()):
|
|
232
|
+
"""{kind: {variable: {template path}}} for the project's templates."""
|
|
233
|
+
joined = "\n".join(php_texts)
|
|
234
|
+
settings = {"twig_off": bool(TWIG_OFF_RE.search(joined)), "smarty_escapes": bool(SMARTY_ESCAPE_ON_RE.search(joined))}
|
|
235
|
+
found = {}
|
|
236
|
+
for path, text in templates.items():
|
|
237
|
+
kind_ = kind(path, text)
|
|
238
|
+
if kind_ is None:
|
|
239
|
+
continue
|
|
240
|
+
for variable in raw_variables(text, kind_, settings):
|
|
241
|
+
found.setdefault(kind_, {}).setdefault(variable, set()).add(path)
|
|
242
|
+
return found
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def alternation(values):
|
|
246
|
+
return "|".join(re.escape(v) for v in sorted(values))
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
# Characters of template names per sink. Semgrep's regex engine rejects a regex of about 30,000 characters or more,
|
|
250
|
+
# and one alternation of LimeSurvey's 1,110 view names (CVE-2014-5016) was 40,000, which failed the whole scan.
|
|
251
|
+
NAMES_LENGTH = 10_000
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def alternations(values):
|
|
255
|
+
"""Alternations of the values, sorted, each at most NAMES_LENGTH characters (one longer value alone)."""
|
|
256
|
+
batches, batch, length = [], [], 0
|
|
257
|
+
for value in sorted(map(re.escape, values)):
|
|
258
|
+
if batch and length + len(value) + 1 > NAMES_LENGTH:
|
|
259
|
+
batches.append("|".join(batch))
|
|
260
|
+
batch, length = [], 0
|
|
261
|
+
batch.append(value)
|
|
262
|
+
length += len(value) + 1
|
|
263
|
+
return [*batches, "|".join(batch)] if batch else batches
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def filled_array(patterns):
|
|
267
|
+
"""The same calls given an array filled entry by entry in the function that renders it: `$data['redirect'] =
|
|
268
|
+
...;` (in an if or not) and then `$this->load->view('common/login', $data)` (OpenCart, CodeIgniter), or `return
|
|
269
|
+
view('x', $data)`."""
|
|
270
|
+
calls = [p.replace(ARRAY, "$DATA") for p in patterns if ARRAY in p]
|
|
271
|
+
return [{"patterns": [{"pattern-inside": f"function $F(...) {{\n ...\n {form}\n ...\n}}"},
|
|
272
|
+
{"pattern": "$DATA[$KEY] = $VALUE"}]}
|
|
273
|
+
for call in calls for form in (f"<... {call} ...>;", f"return <... {call} ...>;")]
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def named_sink(patterns, name_regex, variable):
|
|
277
|
+
return {"patterns": [{"pattern-either": [*({"pattern": p} for p in patterns), *filled_array(patterns)]},
|
|
278
|
+
{"metavariable-regex": {"metavariable": "$NAME", "regex": f"^['\"]({name_regex})['\"]$"}},
|
|
279
|
+
{"metavariable-regex": {"metavariable": "$KEY", "regex": f"^['\"]{re.escape(variable)}['\"]$"}},
|
|
280
|
+
FOCUS_VALUE]}
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def unnamed_sink(patterns, variable):
|
|
284
|
+
return {"patterns": [{"pattern-either": [{"pattern": p} for p in patterns]},
|
|
285
|
+
{"metavariable-regex": {"metavariable": "$KEY", "regex": f"^['\"]{re.escape(variable)}['\"]$"}},
|
|
286
|
+
FOCUS_VALUE]}
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
ARRAY = "[..., $KEY => $VALUE, ...]"
|
|
290
|
+
FOCUS_VALUE = {"focus-metavariable": "$VALUE"}
|
|
291
|
+
# Calls that name the template they render. Every engine's list is the same: the name has to be one of that kind's
|
|
292
|
+
# templates, so OpenCart's Twig through $this->load->view() and CodeIgniter's PHP views through view() both match.
|
|
293
|
+
NAMED_CALLS = [f"$T->render($NAME, {ARRAY}, ...)", f"$T->renderView($NAME, {ARRAY}, ...)",
|
|
294
|
+
f"$T->display($NAME, {ARRAY}, ...)", f"$T->load($NAME)->render({ARRAY}, ...)",
|
|
295
|
+
f"$T->renderResponse($NAME, {ARRAY}, ...)", f"$T->renderToString($NAME, {ARRAY}, ...)",
|
|
296
|
+
f"$T->fetch($NAME, {ARRAY}, ...)", f"$T->load->view($NAME, {ARRAY}, ...)",
|
|
297
|
+
f"$T->element($NAME, {ARRAY}, ...)", f"$T->partial($NAME, {ARRAY}, ...)",
|
|
298
|
+
f"view($NAME, {ARRAY}, ...)", f"View::make($NAME, {ARRAY}, ...)",
|
|
299
|
+
"view($NAME, ...)->with($KEY, $VALUE)", f"view($NAME, ...)->with({ARRAY})",
|
|
300
|
+
"View::make($NAME, ...)->with($KEY, $VALUE)"]
|
|
301
|
+
NAMED = dict.fromkeys((TWIG, BLADE, LATTE, PHP), NAMED_CALLS)
|
|
302
|
+
UNNAMED = {
|
|
303
|
+
SMARTY: ["$S->assign($KEY, $VALUE, ...)", f"$S->assign({ARRAY})", "$S->assignByRef($KEY, $VALUE)",
|
|
304
|
+
"$S->assign_by_ref($KEY, $VALUE)"],
|
|
305
|
+
# A CakePHP component's view variables, for whichever view its controller renders. A controller's own
|
|
306
|
+
# $this->set() is matched to its action's view (cake_sinks).
|
|
307
|
+
PHP: ["$this->Controller->set($KEY, $VALUE)", "$this->controller->set($KEY, $VALUE)",
|
|
308
|
+
f"$this->Controller->set({ARRAY})", f"$this->controller->set({ARRAY})"],
|
|
309
|
+
LATTE: ["$this->template->$KEY = $VALUE;", "$template->$KEY = $VALUE;"],
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def latte_sink(patterns, variable):
|
|
314
|
+
"""A Latte property assignment: $KEY binds the bare identifier, not a string."""
|
|
315
|
+
return {"patterns": [{"pattern-either": [{"pattern": p} for p in patterns]},
|
|
316
|
+
{"metavariable-regex": {"metavariable": "$KEY", "regex": f"^{re.escape(variable)}$"}},
|
|
317
|
+
FOCUS_VALUE]}
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def variable_sinks(kind_, variable, paths):
|
|
321
|
+
"""The sinks for one template variable of one kind: calls that name its templates, and calls that don't."""
|
|
322
|
+
sinks = []
|
|
323
|
+
if kind_ in NAMED:
|
|
324
|
+
tails = set().union(*(names(path, kind_) for path in paths))
|
|
325
|
+
sinks += [named_sink(NAMED[kind_], regex, variable) for regex in alternations(tails)]
|
|
326
|
+
if kind_ in UNNAMED:
|
|
327
|
+
build = latte_sink if kind_ == LATTE else unnamed_sink
|
|
328
|
+
sinks.append(build(UNNAMED[kind_], variable))
|
|
329
|
+
return sinks
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def template_sinks(found):
|
|
333
|
+
return [sink for kind_, variables in sorted(found.items())
|
|
334
|
+
for variable, paths in sorted(variables.items()) for sink in variable_sinks(kind_, variable, paths)]
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
# CakePHP: a controller action renders View/<Controller>/<action>.ctp (2.x) or templates/<Controller>/<action>.php
|
|
338
|
+
# (3.x and later), its name underscored, unless it calls $this->render('other'); a view's elements print too.
|
|
339
|
+
CAKE_VIEW_RE = re.compile(r"(?:^|/)(?:View|templates)/(?!Elements?/|element/|Layouts?/|layout/|email/|Emails/)"
|
|
340
|
+
r"([A-Z]\w*)/(\w+)\.(?:ctp|php)$")
|
|
341
|
+
CAKE_ELEMENT_DIR_RE = re.compile(r"(?:^|/)(?:View/Elements|templates/element)/")
|
|
342
|
+
CONTROLLER_RE = re.compile(r"\bclass\s+(\w+)Controller\s+extends\s+\w+")
|
|
343
|
+
FUNCTION_RE = re.compile(r"\bfunction\s+(\w+)\s*\(")
|
|
344
|
+
RENDER_RE = re.compile(r"\$this->render\(\s*['\"]/?([\w/]+)['\"]")
|
|
345
|
+
ELEMENT_CALL_RE = re.compile(r"\$this->element\(\s*['\"]([\w/]+)['\"]")
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def squashed(name):
|
|
349
|
+
"""CakePHP's view file for an action is its name underscored: viewAll -> view_all."""
|
|
350
|
+
return name.replace("_", "").lower()
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def cake_element(path):
|
|
354
|
+
"""The element name of a CakePHP element file (View/Elements/a/b.ctp -> a/b), or None."""
|
|
355
|
+
found = CAKE_ELEMENT_DIR_RE.search(path)
|
|
356
|
+
name = path[found.end():] if found else ""
|
|
357
|
+
return name[:-4] if name.endswith((".ctp", ".php")) and len(name) > 4 else None
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def cake_views(templates):
|
|
361
|
+
"""{(controller, squashed view name): variables the view, or an element it includes, prints unescaped}."""
|
|
362
|
+
elements = {name: text for path, text in templates.items() if (name := cake_element(path))}
|
|
363
|
+
views = {}
|
|
364
|
+
for path, text in templates.items():
|
|
365
|
+
if not (m := CAKE_VIEW_RE.search(path)):
|
|
366
|
+
continue
|
|
367
|
+
raw = php_raw(text)
|
|
368
|
+
for name in ELEMENT_CALL_RE.findall(text):
|
|
369
|
+
if name in elements:
|
|
370
|
+
raw |= php_raw(elements[name])
|
|
371
|
+
views.setdefault((m.group(1).lower(), squashed(m.group(2))), set()).update(raw)
|
|
372
|
+
return views
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def render_keys(controller, action, body):
|
|
376
|
+
"""The (controller, squashed view) pairs an action can render: its own view and each $this->render() target."""
|
|
377
|
+
keys = {(controller.lower(), squashed(action))}
|
|
378
|
+
for name in RENDER_RE.findall(body):
|
|
379
|
+
parts = name.split("/")
|
|
380
|
+
keys.add((parts[-2].lower(), squashed(parts[-1])) if len(parts) > 1 else (controller.lower(), squashed(name)))
|
|
381
|
+
return keys
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def controller_actions(controller, text, views):
|
|
385
|
+
"""{variable: {actions whose view prints it unescaped}} for one controller's source."""
|
|
386
|
+
starts = [(m.start(), m.group(1)) for m in FUNCTION_RE.finditer(text)]
|
|
387
|
+
ends = [start for start, _ in starts[1:]] + [len(text)]
|
|
388
|
+
actions = {}
|
|
389
|
+
for (start, action), end in zip(starts, ends, strict=True):
|
|
390
|
+
keys = render_keys(controller, action, text[start:end])
|
|
391
|
+
for variable in set().union(*(views.get(key, set()) for key in keys)):
|
|
392
|
+
actions.setdefault(variable, set()).add(action)
|
|
393
|
+
return actions
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def cake_sink(controller, variable, actions):
|
|
397
|
+
return {"patterns": [
|
|
398
|
+
{"pattern-inside": "class $CLASS extends $PARENT { ... }"},
|
|
399
|
+
{"metavariable-regex": {"metavariable": "$CLASS", "regex": f"^{re.escape(controller)}Controller$"}},
|
|
400
|
+
{"pattern-inside": "function $ACTION(...) { ... }"},
|
|
401
|
+
{"metavariable-regex": {"metavariable": "$ACTION", "regex": f"^({alternation(actions)})$"}},
|
|
402
|
+
{"pattern-either": [{"pattern": "$this->set($KEY, $VALUE)"}, {"pattern": f"$this->set({ARRAY})"}]},
|
|
403
|
+
{"metavariable-regex": {"metavariable": "$KEY", "regex": f"^['\"]{re.escape(variable)}['\"]$"}},
|
|
404
|
+
FOCUS_VALUE]}
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def cake_sinks(templates):
|
|
408
|
+
"""A controller's $this->set() of a variable its action's view prints unescaped."""
|
|
409
|
+
views = cake_views(templates)
|
|
410
|
+
if not views:
|
|
411
|
+
return []
|
|
412
|
+
sinks = []
|
|
413
|
+
for path, text in sorted(templates.items()):
|
|
414
|
+
if path.endswith(".php") and (match := CONTROLLER_RE.search(text)):
|
|
415
|
+
actions = controller_actions(match.group(1), text, views)
|
|
416
|
+
sinks += [cake_sink(match.group(1), variable, names_) for variable, names_ in sorted(actions.items())]
|
|
417
|
+
return sinks
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
MESSAGE = ("Data from the HTTP request is passed to the template variable $KEY, which a template (template $NAME) "
|
|
421
|
+
"prints unescaped (Twig |raw, Blade {!! !!}, Latte |noescape, Smarty without |escape, or a PHP view's "
|
|
422
|
+
"echo), so it's written into the page as HTML. Escape it here or in the template.")
|
|
423
|
+
UNNAMED_TEMPLATE = " (template $NAME)"
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def tidy_message(message):
|
|
427
|
+
"""A call that doesn't name its template (Smarty's assign(), CakePHP's set()) leaves $NAME unfilled."""
|
|
428
|
+
return message.replace(UNNAMED_TEMPLATE, "")
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def with_php_template_sinks(rules, templates, php_texts=()):
|
|
432
|
+
"""The rules, plus a copy of the PHP XSS rule whose sinks are the arguments that set variables the project's
|
|
433
|
+
templates print unescaped (none when no template does). templates: {path: text} of the candidate files;
|
|
434
|
+
php_texts: the project's PHP, read for Twig's and Smarty's escaping settings."""
|
|
435
|
+
xss = next((rule for rule in rules if rule.get("id") == XSS_RULE), None)
|
|
436
|
+
if xss is None:
|
|
437
|
+
return rules
|
|
438
|
+
sinks = template_sinks(unescaped(templates, php_texts)) + cake_sinks(templates)
|
|
439
|
+
if not sinks:
|
|
440
|
+
return rules
|
|
441
|
+
return [*rules, {
|
|
442
|
+
**xss, "id": TEMPLATE_RULE,
|
|
443
|
+
"message": MESSAGE,
|
|
444
|
+
"pattern-sinks": sinks}]
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"""Sanitizers learnt from the project's own Python code, which name-based rules can't see.
|
|
2
|
+
|
|
3
|
+
Refusal checks: a helper that tests a parameter (a regex match, an allowlist) and returns a message when it fails,
|
|
4
|
+
`def scan_refusal(project, branch=None): if branch and not BRANCH_RE.match(branch): return "That isn't a branch
|
|
5
|
+
name."` (codewatch's own server). A caller that stops when it answers, `if scan_refusal(project, branch): return
|
|
6
|
+
None`, or `refusal = scan_refusal(...)` then `if refusal: return ...`, has a checked value after that. The helper's
|
|
7
|
+
name says nothing (refusal, problem, error_for), so its body decides: every return is None, a constant or an
|
|
8
|
+
f-string (never a parameter, so a truthy answer can only mean "refused"), and at least one returns a message from an
|
|
9
|
+
`if` that tests a parameter.
|
|
10
|
+
|
|
11
|
+
Configured bases: a URL whose scheme and host come from configuration, `base = os.environ.get("CODEWATCH_URL",
|
|
12
|
+
...).rstrip("/")` then `f"{base}/api/{path}"`, has only its path from the caller (codewatch's MCP server). Semgrep
|
|
13
|
+
can't tie an f-string's first part to the variable assigned (a regex group doesn't unify with a metavariable), so the
|
|
14
|
+
names assigned from configuration anywhere in the project are listed here and both the assignment and the f-string's
|
|
15
|
+
start are matched against them.
|
|
16
|
+
"""
|
|
17
|
+
import ast
|
|
18
|
+
import re
|
|
19
|
+
|
|
20
|
+
from .base import python_tree
|
|
21
|
+
from .summaries import is_js
|
|
22
|
+
|
|
23
|
+
SSRF_RULE = "codewatch.python.web.ssrf"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _param_names(node):
|
|
27
|
+
args = node.args
|
|
28
|
+
return {a.arg for a in [*args.posonlyargs, *args.args, *args.kwonlyargs]}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _names(node):
|
|
32
|
+
return {n.id for n in ast.walk(node) if isinstance(n, ast.Name)}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _called_name(call):
|
|
36
|
+
return call.func.attr if isinstance(call.func, ast.Attribute) else getattr(call.func, "id", "")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _failed_match(node, params):
|
|
40
|
+
"""`not RE.match(p)` or `not re.fullmatch(..., p)` on a parameter."""
|
|
41
|
+
if not (isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not) and isinstance(node.operand, ast.Call)):
|
|
42
|
+
return False
|
|
43
|
+
call = node.operand
|
|
44
|
+
return _called_name(call) in ("match", "fullmatch", "search") and any(_names(a) & params for a in call.args)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _not_allowed(node, params):
|
|
48
|
+
"""`p not in ALLOWED` on a parameter."""
|
|
49
|
+
return (isinstance(node, ast.Compare) and any(isinstance(op, ast.NotIn) for op in node.ops)
|
|
50
|
+
and isinstance(node.left, ast.Name) and node.left.id in params)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _tests_a_parameter(test, params):
|
|
54
|
+
"""`not RE.match(p)`, `not re.fullmatch(..., p)`, `p not in ALLOWED`, or such a test inside and/or."""
|
|
55
|
+
return any(_failed_match(node, params) or _not_allowed(node, params) for node in ast.walk(test))
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _message(value):
|
|
59
|
+
return isinstance(value, ast.JoinedStr) or (isinstance(value, ast.Constant) and bool(value.value))
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _harmless(value):
|
|
63
|
+
return value is None or isinstance(value, (ast.Constant, ast.JoinedStr))
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _is_refusal_helper(node):
|
|
67
|
+
"""A function whose returns are all harmless, and which returns a message from an if that tests a parameter."""
|
|
68
|
+
params = _param_names(node) - {"self", "cls"}
|
|
69
|
+
returns = [n for n in ast.walk(node) if isinstance(n, ast.Return)]
|
|
70
|
+
if not params or not returns or not all(_harmless(r.value) for r in returns):
|
|
71
|
+
return False
|
|
72
|
+
return any(_refuses(n, params) for n in ast.walk(node))
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _refuses(node, params):
|
|
76
|
+
"""`if <test of a parameter>: return "message"`."""
|
|
77
|
+
return (isinstance(node, ast.If) and _tests_a_parameter(node.test, params)
|
|
78
|
+
and any(isinstance(s, ast.Return) and _message(s.value) for s in node.body))
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def refusal_helpers(texts):
|
|
82
|
+
"""Names of the project's functions that answer with a message when a parameter fails a check."""
|
|
83
|
+
trees = (python_tree(text) for text in texts if "def " in text and "return" in text)
|
|
84
|
+
return {node.name for tree in filter(None, trees) for node in ast.walk(tree)
|
|
85
|
+
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and _is_refusal_helper(node)}
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def refusal_sanitizers(names):
|
|
89
|
+
regex = "^(.*\\.)?(" + "|".join(sorted(map(re.escape, names))) + ")$"
|
|
90
|
+
check = {"metavariable-regex": {"metavariable": "$CHECK", "regex": regex}}
|
|
91
|
+
direct = [{"pattern-inside": f"if $CHECK(..., $X, ...):\n ...\n {end} ...\n...\n"} for end in ("return", "raise")]
|
|
92
|
+
stored = [{"pattern-inside": f"$R = $CHECK(..., $X, ...)\n...\nif $R:\n ...\n {end} ...\n...\n"}
|
|
93
|
+
for end in ("return", "raise")]
|
|
94
|
+
return [
|
|
95
|
+
{"patterns": [{"pattern-either": direct}, {"pattern-not-inside": "if $CHECK(..., $X, ...):\n ...\n"},
|
|
96
|
+
check, {"pattern": "$X"}]},
|
|
97
|
+
{"patterns": [{"pattern-either": stored}, {"pattern-not-inside": "if $R:\n ...\n"}, check,
|
|
98
|
+
{"pattern": "$X"}]},
|
|
99
|
+
]
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
CONFIG_VALUE_RE = re.compile(r"^(os\.environ\b|os\.getenv\(|(django\.conf\.)?settings\.\w)")
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _configured_assignment(node):
|
|
106
|
+
"""The name `name = os.environ...` (or os.getenv, or Django settings) assigns, or None."""
|
|
107
|
+
if (isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name)
|
|
108
|
+
and CONFIG_VALUE_RE.match(ast.unparse(node.value))):
|
|
109
|
+
return node.targets[0].id
|
|
110
|
+
return None
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def configured_names(texts):
|
|
114
|
+
"""Variables the project assigns from os.environ, os.getenv() or Django settings (possibly stripped first)."""
|
|
115
|
+
trees = (python_tree(text) for text in texts if "environ" in text or "getenv" in text or "settings." in text)
|
|
116
|
+
return {name for tree in filter(None, trees) for node in ast.walk(tree) if (name := _configured_assignment(node))}
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def configured_base_sanitizer(names):
|
|
120
|
+
alternatives = "|".join(sorted(map(re.escape, names)))
|
|
121
|
+
starts = [f"$BASE = {value}\n...\n" for value in (
|
|
122
|
+
"os.environ.get(...)", "os.environ.get(...).$CLEAN(...)", "os.environ[$KEY]", "os.environ[$KEY].$CLEAN(...)",
|
|
123
|
+
"os.getenv(...)", "os.getenv(...).$CLEAN(...)", "settings.$NAME", "settings.$NAME.$CLEAN(...)")]
|
|
124
|
+
return {"patterns": [
|
|
125
|
+
{"pattern-either": [{"pattern-inside": s} for s in starts]},
|
|
126
|
+
{"metavariable-regex": {"metavariable": "$BASE", "regex": f"^({alternatives})$"}},
|
|
127
|
+
{"pattern": "$URL"},
|
|
128
|
+
{"metavariable-pattern": {"metavariable": "$URL", "patterns": [
|
|
129
|
+
{"pattern": 'f"..."'},
|
|
130
|
+
{"pattern-regex": "^f[\"']\\{\\s*(" + alternatives + ")\\s*\\}/"}]}},
|
|
131
|
+
]}
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def is_python_taint(rule):
|
|
135
|
+
return rule.get("mode") == "taint" and not is_js(rule) and "python" in rule.get("languages", [])
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def with_project_checks(rules, texts):
|
|
139
|
+
"""Python taint rules with the refusal checks' sanitizers, and SSRF's with the configured bases'."""
|
|
140
|
+
texts = list(texts)
|
|
141
|
+
refusals, bases = refusal_helpers(texts), configured_names(texts)
|
|
142
|
+
if not refusals and not bases:
|
|
143
|
+
return rules
|
|
144
|
+
extra = refusal_sanitizers(refusals) if refusals else []
|
|
145
|
+
base_sanitizers = [configured_base_sanitizer(bases)] if bases else []
|
|
146
|
+
out = []
|
|
147
|
+
for rule in rules:
|
|
148
|
+
added = (extra + (base_sanitizers if rule.get("id") == SSRF_RULE else [])) if is_python_taint(rule) else []
|
|
149
|
+
out.append({**rule, "pattern-sanitizers": [*rule.get("pattern-sanitizers", []), *added]} if added else rule)
|
|
150
|
+
return out
|