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,394 @@
|
|
|
1
|
+
"""codewatch's own checks: repeated string literals and regexes vulnerable to catastrophic backtracking.
|
|
2
|
+
|
|
3
|
+
Python files are parsed here with ast; JS/TS parsing and the ReDoS analysis (recheck) run in
|
|
4
|
+
tools/codewatch-checks.mjs.
|
|
5
|
+
"""
|
|
6
|
+
import ast
|
|
7
|
+
import json
|
|
8
|
+
import re
|
|
9
|
+
import shutil
|
|
10
|
+
import subprocess
|
|
11
|
+
import tempfile
|
|
12
|
+
from collections import defaultdict
|
|
13
|
+
from html.parser import HTMLParser
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from .accessibility import TEMPLATES, blank_template_syntax
|
|
17
|
+
from .base import (
|
|
18
|
+
ACCESSIBILITY,
|
|
19
|
+
CODE_SMELL,
|
|
20
|
+
CRITICAL,
|
|
21
|
+
HOTSPOT,
|
|
22
|
+
JS,
|
|
23
|
+
MAJOR,
|
|
24
|
+
MINOR,
|
|
25
|
+
PY,
|
|
26
|
+
TOOLS_DIR,
|
|
27
|
+
VULNERABILITY,
|
|
28
|
+
Analyzer,
|
|
29
|
+
Finding,
|
|
30
|
+
Result,
|
|
31
|
+
is_test_file,
|
|
32
|
+
node_tool,
|
|
33
|
+
python_tree,
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
TOOL = "codewatch"
|
|
37
|
+
MIN_LITERAL_LENGTH = 5
|
|
38
|
+
RE_MODULES = {"re", "regex"}
|
|
39
|
+
MATCH, FULLMATCH = "match", "fullmatch"
|
|
40
|
+
BACKTRACKING = "regex-backtracking"
|
|
41
|
+
RE_FUNCTIONS = {"compile", MATCH, "search", FULLMATCH, "sub", "subn", "split", "findall", "finditer"}
|
|
42
|
+
PY_FLAGS = {"IGNORECASE": "i", "I": "i", "MULTILINE": "m", "M": "m", "DOTALL": "s", "S": "s", "VERBOSE": "x", "X": "x"}
|
|
43
|
+
|
|
44
|
+
RULES = [
|
|
45
|
+
{
|
|
46
|
+
"code": "data-table-without-headers", "title": "Data table without header cells",
|
|
47
|
+
"languages": ["html"], "type": ACCESSIBILITY, "severity": MAJOR,
|
|
48
|
+
"summary": "A table of data has no <th> cells, so screen readers can't announce which row or column a "
|
|
49
|
+
"value belongs to. Mark header cells with <th scope=\"col\"> or <th scope=\"row\">.",
|
|
50
|
+
"references": [{"label": "WCAG technique H51: table markup", "url": "https://www.w3.org/WAI/WCAG22/Techniques/html/H51"},
|
|
51
|
+
{"label": "WCAG 2.2 SC 1.3.1", "url": "https://www.w3.org/WAI/WCAG22/Understanding/info-and-relationships.html"}],
|
|
52
|
+
"cwe": [], "wcag": ["1.3.1"],
|
|
53
|
+
},
|
|
54
|
+
{
|
|
55
|
+
"code": "layout-table-with-headers", "title": "Layout table uses data-table markup",
|
|
56
|
+
"languages": ["html"], "type": ACCESSIBILITY, "severity": MAJOR,
|
|
57
|
+
"summary": "A table marked role=\"presentation\" (layout only) contains <th>, <caption>, <thead> or scope, "
|
|
58
|
+
"which tells assistive technology two contradictory things. Use CSS layout, or make it a real "
|
|
59
|
+
"data table.",
|
|
60
|
+
"references": [{"label": "WCAG failure F46", "url": "https://www.w3.org/WAI/WCAG22/Techniques/failures/F46"},
|
|
61
|
+
{"label": "WCAG 2.2 SC 1.3.1", "url": "https://www.w3.org/WAI/WCAG22/Understanding/info-and-relationships.html"}],
|
|
62
|
+
"cwe": [], "wcag": ["1.3.1"],
|
|
63
|
+
},
|
|
64
|
+
{
|
|
65
|
+
"code": "duplicate-string-literal", "title": "String literal repeated too often",
|
|
66
|
+
"languages": ["python", "javascript"], "type": CODE_SMELL, "severity": MINOR,
|
|
67
|
+
"summary": "The same string literal appears more than the allowed number of times in one file. "
|
|
68
|
+
"Define it once as a named constant so a change can't miss a copy.",
|
|
69
|
+
"references": [{"label": "The Pragmatic Programmer: DRY", "url": "https://en.wikipedia.org/wiki/Don%27t_repeat_yourself"}],
|
|
70
|
+
"cwe": [1041],
|
|
71
|
+
},
|
|
72
|
+
{
|
|
73
|
+
"code": BACKTRACKING, "title": "Regular expression vulnerable to catastrophic backtracking (ReDoS)",
|
|
74
|
+
"languages": ["python", "javascript"], "type": VULNERABILITY, "severity": MAJOR,
|
|
75
|
+
"summary": "Some inputs make this pattern take exponential or polynomial time, so crafted input can "
|
|
76
|
+
"stall the process. Remove nested or overlapping quantifiers, anchor the pattern, or bound "
|
|
77
|
+
"repetition and input length. Exponential backtracking is reported as a vulnerability; "
|
|
78
|
+
"polynomial, which needs long input, as a security hotspot to review where the pattern reads "
|
|
79
|
+
"outside text.",
|
|
80
|
+
"references": [
|
|
81
|
+
{"label": "OWASP: Regular expression Denial of Service",
|
|
82
|
+
"url": "https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS"},
|
|
83
|
+
{"label": "recheck (ReDoS checker)", "url": "https://makenowjust-labs.github.io/recheck/"},
|
|
84
|
+
],
|
|
85
|
+
"cwe": [1333],
|
|
86
|
+
},
|
|
87
|
+
]
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def docstring_nodes(tree):
|
|
91
|
+
out = set()
|
|
92
|
+
for node in ast.walk(tree):
|
|
93
|
+
if isinstance(node, (ast.Module, ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)) and node.body:
|
|
94
|
+
first = node.body[0]
|
|
95
|
+
if isinstance(first, ast.Expr) and isinstance(first.value, ast.Constant):
|
|
96
|
+
out.add(id(first.value))
|
|
97
|
+
return out
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def name_like_parts(node):
|
|
101
|
+
"""Sub-nodes holding names or prose rather than data: f-string fragments, annotations, keys, subscripts."""
|
|
102
|
+
if isinstance(node, ast.JoinedStr):
|
|
103
|
+
return node.values
|
|
104
|
+
if isinstance(node, (ast.AnnAssign, ast.arg)) and node.annotation is not None:
|
|
105
|
+
return list(ast.walk(node.annotation))
|
|
106
|
+
if isinstance(node, ast.Dict):
|
|
107
|
+
return [k for k in node.keys if k is not None]
|
|
108
|
+
if isinstance(node, ast.Subscript):
|
|
109
|
+
return list(ast.walk(node.slice))
|
|
110
|
+
return []
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def skipped_nodes(tree):
|
|
114
|
+
skip = docstring_nodes(tree)
|
|
115
|
+
for node in ast.walk(tree):
|
|
116
|
+
skip.update(id(part) for part in name_like_parts(node))
|
|
117
|
+
return skip
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def python_literals(tree, max_repeats):
|
|
121
|
+
skip = skipped_nodes(tree)
|
|
122
|
+
seen = defaultdict(list)
|
|
123
|
+
for node in ast.walk(tree):
|
|
124
|
+
if (isinstance(node, ast.Constant) and isinstance(node.value, str) and id(node) not in skip
|
|
125
|
+
and len(node.value.strip()) >= MIN_LITERAL_LENGTH):
|
|
126
|
+
seen[node.value].append(node.lineno)
|
|
127
|
+
return [(value, sorted(lines)) for value, lines in seen.items() if len(lines) > max_repeats]
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def python_flags(call):
|
|
131
|
+
flags = ""
|
|
132
|
+
for arg in [*call.args[1:], *(k.value for k in call.keywords if k.arg == "flags")]:
|
|
133
|
+
for node in ast.walk(arg):
|
|
134
|
+
if isinstance(node, ast.Attribute) and node.attr in PY_FLAGS:
|
|
135
|
+
flags += PY_FLAGS[node.attr]
|
|
136
|
+
return flags
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
INLINE_FLAGS_RE = re.compile(r"\(\?([aiLmsux]+)\)")
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def without_verbose_layout(pattern):
|
|
143
|
+
"""A verbose pattern (re.X) as the regex it means: whitespace and # comments outside character classes and
|
|
144
|
+
escapes are layout, not text to match."""
|
|
145
|
+
out, in_class, i = [], False, 0
|
|
146
|
+
while i < len(pattern):
|
|
147
|
+
char = pattern[i]
|
|
148
|
+
if char == "\\":
|
|
149
|
+
out.append(pattern[i:i + 2])
|
|
150
|
+
i += 2
|
|
151
|
+
continue
|
|
152
|
+
if in_class:
|
|
153
|
+
in_class = char != "]"
|
|
154
|
+
elif char == "[":
|
|
155
|
+
in_class = True
|
|
156
|
+
elif char.isspace():
|
|
157
|
+
i += 1
|
|
158
|
+
continue
|
|
159
|
+
elif char == "#":
|
|
160
|
+
i = pattern.find("\n", i)
|
|
161
|
+
i = len(pattern) if i < 0 else i
|
|
162
|
+
continue
|
|
163
|
+
out.append(char)
|
|
164
|
+
i += 1
|
|
165
|
+
return "".join(out)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def inline_flags(pattern, flags):
|
|
169
|
+
"""A leading (?imsx) group moved into the flags: JavaScript has no inline flags, and a pattern it can't parse
|
|
170
|
+
isn't checked at all (five of codewatch's own regexes went unchecked that way)."""
|
|
171
|
+
found = INLINE_FLAGS_RE.match(pattern)
|
|
172
|
+
if not found:
|
|
173
|
+
return pattern, flags
|
|
174
|
+
letters = found.group(1)
|
|
175
|
+
pattern = pattern[found.end():]
|
|
176
|
+
if "x" in letters:
|
|
177
|
+
pattern = without_verbose_layout(pattern)
|
|
178
|
+
return pattern, flags + "".join(f for f in "ims" if f in letters and f not in flags)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def to_js_syntax(pattern):
|
|
182
|
+
"""Python-only regex syntax rewritten to its JavaScript equivalent so recheck can analyse it."""
|
|
183
|
+
pattern = re.sub(r"\(\?P<(\w+)>", r"(?<\1>", pattern)
|
|
184
|
+
pattern = re.sub(r"\(\?P=(\w+)\)", r"\\k<\1>", pattern)
|
|
185
|
+
return pattern.replace(r"\A", "^").replace(r"\Z", "$")
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def anchored(pattern, function):
|
|
189
|
+
"""re.match/fullmatch only try position 0, so analyse them as anchored rather than as a search."""
|
|
190
|
+
if function in (MATCH, FULLMATCH) and not pattern.startswith("^"):
|
|
191
|
+
pattern = f"^(?:{pattern})"
|
|
192
|
+
if function == FULLMATCH and not pattern.endswith("$"):
|
|
193
|
+
pattern += "$"
|
|
194
|
+
return pattern
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
ANCHORED_METHODS = (MATCH, FULLMATCH)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def compiled_patterns(tree):
|
|
201
|
+
"""{name: re.compile calls assigned to it} in this module."""
|
|
202
|
+
compiled = defaultdict(list)
|
|
203
|
+
for node in ast.walk(tree):
|
|
204
|
+
if (isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name)
|
|
205
|
+
and is_re_call(node.value) and node.value.func.attr == "compile"):
|
|
206
|
+
compiled[node.targets[0].id].append(node.value)
|
|
207
|
+
return compiled
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def name_uses(tree, names):
|
|
211
|
+
"""{name: what each read of it does}: the attribute taken (NAME.match) or None for any other use."""
|
|
212
|
+
attributes = {id(node.value): node.attr for node in ast.walk(tree)
|
|
213
|
+
if isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name)}
|
|
214
|
+
uses = defaultdict(list)
|
|
215
|
+
for node in ast.walk(tree):
|
|
216
|
+
if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load) and node.id in names:
|
|
217
|
+
uses[node.id].append(attributes.get(id(node)))
|
|
218
|
+
return uses
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def compiled_uses(tree):
|
|
222
|
+
"""{id of a re.compile call: "match" or "fullmatch"} for a pattern assigned once to a name that is only ever
|
|
223
|
+
used as NAME.match(...) or NAME.fullmatch(...) in this module: those try one position, so they are analysed
|
|
224
|
+
anchored, as re.match(...) is. A name used any other way (searched, passed on, put in a list) stays a search."""
|
|
225
|
+
compiled = compiled_patterns(tree)
|
|
226
|
+
uses = name_uses(tree, compiled)
|
|
227
|
+
out = {}
|
|
228
|
+
for name, calls in compiled.items():
|
|
229
|
+
methods = set(uses.get(name, ()))
|
|
230
|
+
if len(calls) == 1 and methods and methods <= set(ANCHORED_METHODS):
|
|
231
|
+
out[id(calls[0])] = MATCH if MATCH in methods else FULLMATCH
|
|
232
|
+
return out
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def is_re_call(node):
|
|
236
|
+
return (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr in RE_FUNCTIONS
|
|
237
|
+
and isinstance(node.func.value, ast.Name) and node.func.value.id in RE_MODULES and bool(node.args))
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def python_regexes(tree, path):
|
|
241
|
+
out = []
|
|
242
|
+
anchored_compiles = compiled_uses(tree)
|
|
243
|
+
for node in ast.walk(tree):
|
|
244
|
+
if not is_re_call(node):
|
|
245
|
+
continue
|
|
246
|
+
first = node.args[0]
|
|
247
|
+
if isinstance(first, ast.Constant) and isinstance(first.value, str):
|
|
248
|
+
flags = python_flags(node)
|
|
249
|
+
pattern = without_verbose_layout(first.value) if "x" in flags else first.value
|
|
250
|
+
pattern, flags = inline_flags(pattern, flags.replace("x", ""))
|
|
251
|
+
out.append({"path": path, "line": node.lineno, "flags": flags, "original": first.value,
|
|
252
|
+
"pattern": anchored(to_js_syntax(pattern), anchored_compiles.get(id(node), node.func.attr))})
|
|
253
|
+
return out
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
class TableSemantics(HTMLParser):
|
|
257
|
+
"""Collects (line, problem) for tables whose markup contradicts their role."""
|
|
258
|
+
|
|
259
|
+
LAYOUT_ROLES = {"presentation", "none"}
|
|
260
|
+
HEADER_TAGS = {"th", "caption", "thead"}
|
|
261
|
+
# A caption names the table but doesn't identify any cell, so it doesn't make a data table accessible.
|
|
262
|
+
CELL_HEADERS = {"th"}
|
|
263
|
+
|
|
264
|
+
def __init__(self):
|
|
265
|
+
super().__init__(convert_charrefs=True)
|
|
266
|
+
self.stack, self.problems = [], []
|
|
267
|
+
|
|
268
|
+
def handle_starttag(self, tag, attrs):
|
|
269
|
+
attrs = dict(attrs)
|
|
270
|
+
if tag == "table":
|
|
271
|
+
self.stack.append({"line": self.getpos()[0], "layout": attrs.get("role") in self.LAYOUT_ROLES,
|
|
272
|
+
"headers": False, "cell_headers": False, "cells": False})
|
|
273
|
+
elif self.stack:
|
|
274
|
+
table = self.stack[-1]
|
|
275
|
+
table["headers"] |= tag in self.HEADER_TAGS or "scope" in attrs
|
|
276
|
+
table["cell_headers"] |= tag in self.CELL_HEADERS or "scope" in attrs or "headers" in attrs
|
|
277
|
+
table["cells"] |= tag == "td"
|
|
278
|
+
|
|
279
|
+
def handle_endtag(self, tag):
|
|
280
|
+
if tag != "table" or not self.stack:
|
|
281
|
+
return
|
|
282
|
+
table = self.stack.pop()
|
|
283
|
+
if table["layout"] and table["headers"]:
|
|
284
|
+
self.problems.append((table["line"], "layout-table-with-headers"))
|
|
285
|
+
elif not table["layout"] and table["cells"] and not table["cell_headers"]:
|
|
286
|
+
self.problems.append((table["line"], "data-table-without-headers"))
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def table_problems(text):
|
|
290
|
+
parser = TableSemantics()
|
|
291
|
+
parser.feed(text)
|
|
292
|
+
parser.close()
|
|
293
|
+
return parser.problems
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
TABLE_MESSAGES = {
|
|
297
|
+
"data-table-without-headers": "Data table has no header cells (<th>); add them so cells can be identified",
|
|
298
|
+
"layout-table-with-headers": "Layout table (role=presentation) contains <th>/<caption>/<thead>/scope",
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
class CodewatchChecks(Analyzer):
|
|
303
|
+
name = TOOL
|
|
304
|
+
executable = "node"
|
|
305
|
+
extensions = PY | JS | TEMPLATES
|
|
306
|
+
|
|
307
|
+
def available(self):
|
|
308
|
+
return shutil.which("node") is not None and node_tool("tsc") is not None
|
|
309
|
+
|
|
310
|
+
@staticmethod
|
|
311
|
+
def python_checks(ctx):
|
|
312
|
+
"""(repeated-literal findings, regexes to check) from the Python files."""
|
|
313
|
+
findings, regexes = [], []
|
|
314
|
+
for path in ctx.files_with(PY):
|
|
315
|
+
tree = python_tree((ctx.root / path).read_text(errors="replace"))
|
|
316
|
+
if tree is None:
|
|
317
|
+
continue
|
|
318
|
+
if not is_test_file(path):
|
|
319
|
+
findings += [literal_finding(path, value, lines)
|
|
320
|
+
for value, lines in python_literals(tree, ctx.max_literal_repeats)]
|
|
321
|
+
regexes += [{**r, "tooling": True} if developer_tool(tree, path) else r
|
|
322
|
+
for r in python_regexes(tree, path)]
|
|
323
|
+
return findings, regexes
|
|
324
|
+
|
|
325
|
+
def run(self, ctx):
|
|
326
|
+
result = Result()
|
|
327
|
+
literal_findings, regexes = self.python_checks(ctx)
|
|
328
|
+
result.findings += literal_findings + self.table_findings(ctx)
|
|
329
|
+
node_out = self.run_node(ctx, regexes)
|
|
330
|
+
result.findings += [literal_finding(path, lit["value"], lit["lines"]) for lit in node_out["literals"]
|
|
331
|
+
if not is_test_file(path := ctx.rel(lit["path"]))]
|
|
332
|
+
result.findings += [regex_finding(ctx.rel(r["path"]), r) for r in node_out["regexes"]]
|
|
333
|
+
return result
|
|
334
|
+
|
|
335
|
+
def table_findings(self, ctx):
|
|
336
|
+
findings = []
|
|
337
|
+
for path in ctx.files_with(TEMPLATES):
|
|
338
|
+
text = blank_template_syntax((ctx.root / path).read_text(errors="replace"))
|
|
339
|
+
findings += [Finding(TOOL, code, MAJOR, ACCESSIBILITY, TABLE_MESSAGES[code], path, line)
|
|
340
|
+
for line, code in table_problems(text)]
|
|
341
|
+
return findings
|
|
342
|
+
|
|
343
|
+
def run_node(self, ctx, python_regexes_):
|
|
344
|
+
spec = {"jsFiles": [str(ctx.root / f) for f in ctx.files_with(JS)], "minLength": MIN_LITERAL_LENGTH,
|
|
345
|
+
"maxRepeats": ctx.max_literal_repeats, "pythonRegexes": python_regexes_}
|
|
346
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
347
|
+
spec_file, out_file = Path(tmp) / "spec.json", Path(tmp) / "out.json"
|
|
348
|
+
spec_file.write_text(json.dumps(spec))
|
|
349
|
+
subprocess.run(["node", str(TOOLS_DIR / "codewatch-checks.mjs"), str(spec_file), str(out_file)],
|
|
350
|
+
cwd=TOOLS_DIR, capture_output=True, text=True, check=False, timeout=1800)
|
|
351
|
+
return json.loads(out_file.read_text()) if out_file.exists() else {"literals": [], "regexes": []}
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def literal_finding(path, value, lines):
|
|
355
|
+
shown = value if len(value) <= 60 else value[:57] + "..."
|
|
356
|
+
return Finding(TOOL, "duplicate-string-literal", MINOR, CODE_SMELL,
|
|
357
|
+
f'"{shown}" appears {len(lines)} times (lines {", ".join(map(str, lines[:10]))}'
|
|
358
|
+
f'{"…" if len(lines) > 10 else ""}); define it once as a constant', path, lines[0])
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def regex_finding(path, r):
|
|
362
|
+
severity = CRITICAL if r.get("complexity") == "exponential" else MAJOR
|
|
363
|
+
pattern = r.get("original") or r["pattern"]
|
|
364
|
+
message = (f"Regex /{pattern[:80]}/ has {r.get('complexity', 'super-linear')} backtracking "
|
|
365
|
+
f"({r.get('summary') or 'ReDoS'}); e.g. input {r.get('attack', '')[:80]}")
|
|
366
|
+
if r.get("tooling"):
|
|
367
|
+
return Finding(TOOL, BACKTRACKING, MINOR, HOTSPOT,
|
|
368
|
+
message + ". It is in a developer tool (a script or management command), so it only "
|
|
369
|
+
"matters if that tool reads text someone else controls", path, r["line"])
|
|
370
|
+
# Polynomial backtracking needs long input to hurt (a request body, an uploaded file), and the check can't
|
|
371
|
+
# tell what the regex reads: a parser's patterns over its own source files were most of a scan's
|
|
372
|
+
# "vulnerabilities" (codewatch on its own code, 2026-11-17). Exponential stays one: a few dozen characters
|
|
373
|
+
# are enough.
|
|
374
|
+
if r.get("complexity") != "exponential":
|
|
375
|
+
return Finding(TOOL, BACKTRACKING, MAJOR, HOTSPOT,
|
|
376
|
+
message + ". Polynomial backtracking is slow only on long input: it matters where this "
|
|
377
|
+
"pattern reads text from outside (a request, an upload) without a length limit",
|
|
378
|
+
path, r["line"])
|
|
379
|
+
return Finding(TOOL, BACKTRACKING, severity, VULNERABILITY, message, path, r["line"])
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
# A file that builds a web app, even if it also runs itself under `if __name__ == "__main__"` (app.run()).
|
|
383
|
+
WEB_APP_RE = re.compile(r"\b(Flask|FastAPI|Starlette|Quart|Sanic|APIRouter|Blueprint)\(|urlpatterns\b|@\w+\.(route|get|post)\(")
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def developer_tool(tree, path):
|
|
387
|
+
"""A Django management command, or a script run by hand (`if __name__ == "__main__":`) that builds no web
|
|
388
|
+
app: what its regexes read is the developer's own input (a changelog, the repo's files), not a visitor's.
|
|
389
|
+
A slow regex there is a hotspot, not a denial of service anyone outside can trigger."""
|
|
390
|
+
if "/management/commands/" in f"/{path}":
|
|
391
|
+
return True
|
|
392
|
+
main = any(isinstance(n, ast.If) and isinstance(n.test, ast.Compare) and isinstance(n.test.left, ast.Name)
|
|
393
|
+
and n.test.left.id == "__name__" for n in tree.body)
|
|
394
|
+
return main and not WEB_APP_RE.search(ast.unparse(tree))
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
"""Blank out branches whose condition is decided by constants, for Semgrep's taint analysis.
|
|
2
|
+
|
|
3
|
+
`num = 106` then `bar = "fixed" if 7 * 18 + num > 200 else param` never uses `param`, but Semgrep follows both
|
|
4
|
+
branches. On the copy Semgrep scans, a branch that can't run is replaced: a dead `if`/`else`/`case` body becomes
|
|
5
|
+
`pass` lines, a dead ternary arm becomes `None`. Only conditions built from literals and names assigned exactly
|
|
6
|
+
once from a literal are evaluated; anything else is left alone. Every line keeps its number.
|
|
7
|
+
"""
|
|
8
|
+
import ast
|
|
9
|
+
import contextlib
|
|
10
|
+
import operator
|
|
11
|
+
|
|
12
|
+
BINOPS = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.FloorDiv: operator.floordiv,
|
|
13
|
+
ast.Mod: operator.mod}
|
|
14
|
+
COMPARES = {ast.Lt: operator.lt, ast.Gt: operator.gt, ast.LtE: operator.le, ast.GtE: operator.ge,
|
|
15
|
+
ast.Eq: operator.eq, ast.NotEq: operator.ne, ast.In: lambda a, b: a in b,
|
|
16
|
+
ast.NotIn: lambda a, b: a not in b}
|
|
17
|
+
MAX_INT = 10 ** 12
|
|
18
|
+
MAX_STR = 1000
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Unknown(Exception):
|
|
22
|
+
pass
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def constant_value(node, _env):
|
|
26
|
+
if not isinstance(node.value, (int, str, bool)):
|
|
27
|
+
raise Unknown
|
|
28
|
+
return node.value
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def name_value(node, env):
|
|
32
|
+
if node.id not in env:
|
|
33
|
+
raise Unknown
|
|
34
|
+
return env[node.id]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def binop_value(node, env):
|
|
38
|
+
if type(node.op) not in BINOPS:
|
|
39
|
+
raise Unknown
|
|
40
|
+
left, right = evaluate(node.left, env), evaluate(node.right, env)
|
|
41
|
+
if not (isinstance(left, int) and isinstance(right, int)) or (
|
|
42
|
+
isinstance(node.op, (ast.FloorDiv, ast.Mod)) and right == 0):
|
|
43
|
+
raise Unknown
|
|
44
|
+
return BINOPS[type(node.op)](left, right)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def unary_value(node, env):
|
|
48
|
+
if not isinstance(node.op, (ast.USub, ast.Not)):
|
|
49
|
+
raise Unknown
|
|
50
|
+
operand = evaluate(node.operand, env)
|
|
51
|
+
if isinstance(node.op, ast.Not):
|
|
52
|
+
return not operand
|
|
53
|
+
# -"text" is a TypeError in Python, not a value: the branch it decides is left alone, not the scan stopped.
|
|
54
|
+
if isinstance(operand, str):
|
|
55
|
+
raise Unknown
|
|
56
|
+
return -operand
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def boolop_value(node, env):
|
|
60
|
+
values = [evaluate(v, env) for v in node.values]
|
|
61
|
+
return all(values) if isinstance(node.op, ast.And) else any(values)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def compare_value(node, env):
|
|
65
|
+
if not all(type(op) in COMPARES for op in node.ops):
|
|
66
|
+
raise Unknown
|
|
67
|
+
left, value = evaluate(node.left, env), True
|
|
68
|
+
for op, comparator in zip(node.ops, node.comparators, strict=True):
|
|
69
|
+
right = evaluate(comparator, env)
|
|
70
|
+
try:
|
|
71
|
+
value = value and COMPARES[type(op)](left, right)
|
|
72
|
+
except TypeError as exc:
|
|
73
|
+
raise Unknown from exc
|
|
74
|
+
left = right
|
|
75
|
+
return value
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def subscript_value(node, env):
|
|
79
|
+
if not isinstance(node.slice, ast.Constant):
|
|
80
|
+
raise Unknown
|
|
81
|
+
base, index = evaluate(node.value, env), node.slice.value
|
|
82
|
+
if not (isinstance(base, str) and isinstance(index, int) and -len(base) <= index < len(base)):
|
|
83
|
+
raise Unknown
|
|
84
|
+
return base[index]
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
EVALUATORS = ((ast.Constant, constant_value), (ast.Name, name_value), (ast.BinOp, binop_value),
|
|
88
|
+
(ast.UnaryOp, unary_value), (ast.BoolOp, boolop_value), (ast.Compare, compare_value),
|
|
89
|
+
(ast.Subscript, subscript_value))
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def evaluate(node, env):
|
|
93
|
+
"""The value of a constant expression, or Unknown."""
|
|
94
|
+
value_of = next((f for kind, f in EVALUATORS if isinstance(node, kind)), None)
|
|
95
|
+
if value_of is None:
|
|
96
|
+
raise Unknown
|
|
97
|
+
value = value_of(node, env)
|
|
98
|
+
if (isinstance(value, int) and abs(value) > MAX_INT) or (isinstance(value, str) and len(value) > MAX_STR):
|
|
99
|
+
raise Unknown
|
|
100
|
+
return value
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def assignments(scope):
|
|
104
|
+
"""({name: times stored}, {name: [values assigned to it alone]}); a global or nonlocal name counts as stored
|
|
105
|
+
twice."""
|
|
106
|
+
stores, literal = {}, {}
|
|
107
|
+
for node in ast.walk(scope):
|
|
108
|
+
if isinstance(node, ast.Name) and isinstance(node.ctx, (ast.Store, ast.Del)):
|
|
109
|
+
stores[node.id] = stores.get(node.id, 0) + 1
|
|
110
|
+
elif isinstance(node, (ast.Global, ast.Nonlocal)):
|
|
111
|
+
stores |= dict.fromkeys(node.names, 2)
|
|
112
|
+
if isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name):
|
|
113
|
+
literal.setdefault(node.targets[0].id, []).append(node.value)
|
|
114
|
+
return stores, literal
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def constants(scope):
|
|
118
|
+
"""Names assigned exactly once in a function (or module), from a literal or another such constant."""
|
|
119
|
+
stores, literal = assignments(scope)
|
|
120
|
+
env = {}
|
|
121
|
+
for name, values in literal.items():
|
|
122
|
+
if stores.get(name) == 1 and len(values) == 1:
|
|
123
|
+
with contextlib.suppress(Unknown):
|
|
124
|
+
env[name] = evaluate(values[0], env)
|
|
125
|
+
return env
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def scopes(tree):
|
|
129
|
+
yield tree, [n for n in tree.body if not isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))]
|
|
130
|
+
for node in ast.walk(tree):
|
|
131
|
+
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
132
|
+
yield node, node.body
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def nodes_in(body):
|
|
136
|
+
"""Every node in a scope's statements, without entering nested functions (they have their own constants)."""
|
|
137
|
+
stack = list(body)
|
|
138
|
+
while stack:
|
|
139
|
+
node = stack.pop()
|
|
140
|
+
yield node
|
|
141
|
+
stack += [c for c in ast.iter_child_nodes(node)
|
|
142
|
+
if not isinstance(c, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda))]
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def decide(test, env):
|
|
146
|
+
try:
|
|
147
|
+
return bool(evaluate(test, env))
|
|
148
|
+
except Unknown:
|
|
149
|
+
return None
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def case_matches(pattern, subject):
|
|
153
|
+
"""True/False when a literal case pattern can be compared with the subject, None otherwise."""
|
|
154
|
+
if isinstance(pattern, ast.MatchAs) and pattern.pattern is None:
|
|
155
|
+
return True
|
|
156
|
+
if isinstance(pattern, ast.MatchValue) and isinstance(pattern.value, ast.Constant):
|
|
157
|
+
return pattern.value.value == subject
|
|
158
|
+
if isinstance(pattern, ast.MatchOr):
|
|
159
|
+
results = [case_matches(p, subject) for p in pattern.patterns]
|
|
160
|
+
return None if None in results else any(results)
|
|
161
|
+
return None
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def dead_branch(node, env):
|
|
165
|
+
"""The dead body of an if or while decided by constants (none for a loop that runs), as a list of blocks."""
|
|
166
|
+
taken = decide(node.test, env)
|
|
167
|
+
if taken is None or (isinstance(node, ast.While) and taken):
|
|
168
|
+
return []
|
|
169
|
+
dead = node.orelse if taken else node.body
|
|
170
|
+
return [dead] if dead else []
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def dead_parts(node, env):
|
|
174
|
+
"""([dead statement blocks], [dead expressions]) of one node."""
|
|
175
|
+
if isinstance(node, (ast.If, ast.While)):
|
|
176
|
+
return dead_branch(node, env), []
|
|
177
|
+
if isinstance(node, ast.IfExp) and (taken := decide(node.test, env)) is not None:
|
|
178
|
+
return [], [node.orelse if taken else node.body]
|
|
179
|
+
if isinstance(node, ast.Match):
|
|
180
|
+
return dead_cases(node, env), []
|
|
181
|
+
return [], []
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def dead_code(tree):
|
|
185
|
+
"""(dead statement blocks, dead expressions) for branches decided by constants."""
|
|
186
|
+
blocks, exprs = [], []
|
|
187
|
+
for scope, body in scopes(tree):
|
|
188
|
+
env = constants(scope) if scope is not tree else constants(ast.Module(body=body, type_ignores=[]))
|
|
189
|
+
for node in nodes_in(body) if env else ():
|
|
190
|
+
dead_blocks, dead_exprs = dead_parts(node, env)
|
|
191
|
+
blocks += dead_blocks
|
|
192
|
+
exprs += dead_exprs
|
|
193
|
+
return blocks, exprs
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def dead_cases(node, env):
|
|
197
|
+
try:
|
|
198
|
+
subject = evaluate(node.subject, env)
|
|
199
|
+
except Unknown:
|
|
200
|
+
return []
|
|
201
|
+
results = [None if case.guard else case_matches(case.pattern, subject) for case in node.cases]
|
|
202
|
+
if None in results or True not in results:
|
|
203
|
+
return []
|
|
204
|
+
live = results.index(True)
|
|
205
|
+
return [case.body for i, case in enumerate(node.cases) if i != live]
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def blanked_rows(lines, blocks):
|
|
209
|
+
"""{line number: indent} for every line of the dead blocks."""
|
|
210
|
+
blank = {}
|
|
211
|
+
for block in blocks:
|
|
212
|
+
first = lines[block[0].lineno - 1]
|
|
213
|
+
indent = first[:len(first) - len(first.lstrip())]
|
|
214
|
+
for row in range(block[0].lineno, max(s.end_lineno or s.lineno for s in block) + 1):
|
|
215
|
+
blank[row] = indent
|
|
216
|
+
return blank
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def replace_expressions(lines, exprs, blank):
|
|
220
|
+
"""Each dead single-line expression outside a blanked line replaced by None, in place. An expression inside
|
|
221
|
+
nested scopes is reached once per enclosing scope; it is replaced once."""
|
|
222
|
+
unique = {(e.lineno, e.col_offset, e.end_col_offset): e for e in exprs}.values()
|
|
223
|
+
for expr in sorted(unique, key=lambda e: (e.lineno, e.col_offset), reverse=True):
|
|
224
|
+
if expr.lineno != expr.end_lineno or expr.lineno in blank:
|
|
225
|
+
continue
|
|
226
|
+
line = lines[expr.lineno - 1]
|
|
227
|
+
start, end = col_to_index(line, expr.col_offset), col_to_index(line, expr.end_col_offset)
|
|
228
|
+
lines[expr.lineno - 1] = line[:start] + "None" + line[end:]
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def blank_dead_branches(source):
|
|
232
|
+
"""The source with constant-decided dead branches blanked, or None if there are none."""
|
|
233
|
+
try:
|
|
234
|
+
tree = ast.parse(source)
|
|
235
|
+
except (SyntaxError, ValueError):
|
|
236
|
+
return None
|
|
237
|
+
blocks, exprs = dead_code(tree)
|
|
238
|
+
if not blocks and not exprs:
|
|
239
|
+
return None
|
|
240
|
+
lines = source.splitlines(keepends=True)
|
|
241
|
+
blank = blanked_rows(lines, blocks)
|
|
242
|
+
replace_expressions(lines, exprs, blank)
|
|
243
|
+
for row, indent in blank.items():
|
|
244
|
+
ending = "\n" if lines[row - 1].endswith("\n") else ""
|
|
245
|
+
lines[row - 1] = f"{indent}pass{ending}"
|
|
246
|
+
return "".join(lines)
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def col_to_index(line, col):
|
|
250
|
+
"""ast columns count UTF-8 bytes; string slicing counts characters."""
|
|
251
|
+
return len(line.encode()[:col].decode(errors="ignore"))
|