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
core/analyzers/extra.py
ADDED
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
import ast
|
|
2
|
+
import json
|
|
3
|
+
import re
|
|
4
|
+
import tempfile
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from .base import (
|
|
8
|
+
BLOCKER,
|
|
9
|
+
BUG,
|
|
10
|
+
CODE_SMELL,
|
|
11
|
+
HOTSPOT,
|
|
12
|
+
JS,
|
|
13
|
+
MAJOR,
|
|
14
|
+
MINOR,
|
|
15
|
+
PY,
|
|
16
|
+
TOOLS_DIR,
|
|
17
|
+
VULNERABILITY,
|
|
18
|
+
Analyzer,
|
|
19
|
+
Finding,
|
|
20
|
+
Result,
|
|
21
|
+
isolated_tool,
|
|
22
|
+
node_tool,
|
|
23
|
+
)
|
|
24
|
+
from .python_tools import LineCache, complexity_severity
|
|
25
|
+
|
|
26
|
+
# Lines naming a commit, checksum or integrity hash: high-entropy by design, not credentials.
|
|
27
|
+
NOT_SECRET_LINES = (r"""(?i)["']?(commit|sha\d{0,3}|hash|digest|integrity|checksum|etag|rev|revision|provenance"""
|
|
28
|
+
r"""|fingerprint)["']?\s{0,5}[:=]""")
|
|
29
|
+
SECRET_HEURISTICS = {"Base64 High Entropy String", "Hex High Entropy String", "Secret Keyword"}
|
|
30
|
+
DOCKERFILES = ("Dockerfile", "Containerfile")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def function_lines(path):
|
|
34
|
+
"""Qualified name ("Class::method") -> (first line, last line), as complexipy names functions."""
|
|
35
|
+
try:
|
|
36
|
+
tree = ast.parse(path.read_text(errors="replace"))
|
|
37
|
+
except (OSError, SyntaxError, ValueError):
|
|
38
|
+
return {}
|
|
39
|
+
found = {}
|
|
40
|
+
|
|
41
|
+
def walk(node, prefix):
|
|
42
|
+
for child in ast.iter_child_nodes(node):
|
|
43
|
+
if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
|
|
44
|
+
name = f"{prefix}::{child.name}" if prefix else child.name
|
|
45
|
+
if not isinstance(child, ast.ClassDef):
|
|
46
|
+
found.setdefault(name, (child.lineno, child.end_lineno))
|
|
47
|
+
walk(child, name)
|
|
48
|
+
|
|
49
|
+
walk(tree, "")
|
|
50
|
+
return found
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class CognitiveComplexity(Analyzer):
|
|
54
|
+
"""How hard code is to follow: nesting and breaks in linear flow cost more than plain branches."""
|
|
55
|
+
|
|
56
|
+
name = executable = "complexipy"
|
|
57
|
+
extensions = PY
|
|
58
|
+
|
|
59
|
+
def run(self, ctx):
|
|
60
|
+
threshold = ctx.cognitive_threshold
|
|
61
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
62
|
+
out = Path(tmp) / "out.json"
|
|
63
|
+
self.exec([*ctx.files_with(PY), "--output-format", "json", "--output", str(out), "--quiet",
|
|
64
|
+
"--ignore-complexity", "--cache-dir", tmp], ctx, ok_codes=(0, 1))
|
|
65
|
+
rows = json.loads(out.read_text()) if out.exists() else []
|
|
66
|
+
result = Result()
|
|
67
|
+
lines_by_file = {}
|
|
68
|
+
for row in rows:
|
|
69
|
+
if row["complexity"] <= threshold:
|
|
70
|
+
continue
|
|
71
|
+
path = ctx.rel(row["path"])
|
|
72
|
+
if path not in lines_by_file:
|
|
73
|
+
lines_by_file[path] = function_lines(ctx.root / path)
|
|
74
|
+
start, end = lines_by_file[path].get(row["function_name"], (None, None))
|
|
75
|
+
name = row["function_name"].replace("::", ".")
|
|
76
|
+
result.findings.append(
|
|
77
|
+
Finding("complexipy", "cognitive-complexity", complexity_severity(row["complexity"], threshold),
|
|
78
|
+
CODE_SMELL, f"{name} has cognitive complexity {row['complexity']} "
|
|
79
|
+
f"(threshold {threshold})", path, start, end)
|
|
80
|
+
)
|
|
81
|
+
result.metrics["cognitive_complexity"] = sum(r["complexity"] for r in rows)
|
|
82
|
+
return result
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
# Without Django's mypy plugin, pyright misreads model fields (descriptors) and a few Django internals.
|
|
86
|
+
# These message shapes are only ever those misreadings, so they're dropped rather than reported.
|
|
87
|
+
KNOWN_FALSE_POSITIVES = [
|
|
88
|
+
re.compile(r'parameter "default" of type "type\[NOT_PROVIDED\]"'),
|
|
89
|
+
re.compile(r'not assignable to declared type "cached_property"'),
|
|
90
|
+
re.compile(r'Method "__str__" overrides class "Model" in an incompatible manner'),
|
|
91
|
+
re.compile(r'on type "\w{1,60}Field"'),
|
|
92
|
+
re.compile(r'Object of type "\(\.\.\.\) -> object" cannot be used with "with"'),
|
|
93
|
+
]
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def known_false_positive(message):
|
|
97
|
+
return any(p.search(message) for p in KNOWN_FALSE_POSITIVES)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
DETECTOR = "detect-secrets"
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class TypeCheck(Analyzer):
|
|
104
|
+
"""Type errors (wrong arguments, None access, bad returns) with basedpyright in standard mode."""
|
|
105
|
+
|
|
106
|
+
name = "basedpyright"
|
|
107
|
+
executable = "basedpyright"
|
|
108
|
+
extensions = PY
|
|
109
|
+
|
|
110
|
+
@staticmethod
|
|
111
|
+
def config(ctx):
|
|
112
|
+
config = {
|
|
113
|
+
"typeCheckingMode": "standard",
|
|
114
|
+
"include": [str(ctx.root / f) for f in ctx.files_with(PY)],
|
|
115
|
+
# Third-party packages may not be installed where the scan runs; unresolved imports are not code bugs.
|
|
116
|
+
"reportMissingImports": "none",
|
|
117
|
+
"reportMissingModuleSource": "none",
|
|
118
|
+
"reportAttributeAccessIssue": "warning",
|
|
119
|
+
}
|
|
120
|
+
# basedpyright runs the venv's python to find its packages: only in the developer's own copy.
|
|
121
|
+
venv = next((ctx.root / v for v in ("venv", ".venv") if (ctx.root / v / "bin" / "python").exists()), None)
|
|
122
|
+
if venv and ctx.local:
|
|
123
|
+
config.update(venvPath=str(venv.parent), venv=venv.name)
|
|
124
|
+
return config
|
|
125
|
+
|
|
126
|
+
@staticmethod
|
|
127
|
+
def finding(ctx, diagnostic):
|
|
128
|
+
# File-level diagnostics (e.g. a file that can't be read) carry no range.
|
|
129
|
+
where = diagnostic.get("range")
|
|
130
|
+
start, end = (where["start"]["line"] + 1, where["end"]["line"] + 1) if where else (None, None)
|
|
131
|
+
return Finding("basedpyright", diagnostic.get("rule") or "type-error", MAJOR, BUG,
|
|
132
|
+
diagnostic["message"].split("\n")[0], ctx.rel(diagnostic["file"]), start, end)
|
|
133
|
+
|
|
134
|
+
def run(self, ctx):
|
|
135
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
136
|
+
cfg = Path(tmp) / "pyrightconfig.json"
|
|
137
|
+
cfg.write_text(json.dumps(self.config(ctx)))
|
|
138
|
+
out = self.exec(["--outputjson", "--project", str(cfg)], ctx, ok_codes=(0, 1))
|
|
139
|
+
result = Result()
|
|
140
|
+
result.findings = [self.finding(ctx, d) for d in json.loads(out or "{}").get("generalDiagnostics", [])
|
|
141
|
+
if d["severity"] == "error" and not known_false_positive(d["message"])]
|
|
142
|
+
return result
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
class Secrets(Analyzer):
|
|
146
|
+
"""Hard-coded credentials and API keys with detect-secrets, plus known token formats it has no plugin for."""
|
|
147
|
+
|
|
148
|
+
name = executable = DETECTOR
|
|
149
|
+
|
|
150
|
+
@staticmethod
|
|
151
|
+
def finding(ctx, path, line, types):
|
|
152
|
+
"""A secret detect-secrets names (a key format) is a vulnerability; a heuristic one is a hotspot."""
|
|
153
|
+
specific = sorted(types - SECRET_HEURISTICS)
|
|
154
|
+
return Finding(DETECTOR, specific[0] if specific else min(types), BLOCKER if specific else MAJOR,
|
|
155
|
+
VULNERABILITY if specific else HOTSPOT,
|
|
156
|
+
f"Possible hard-coded secret ({', '.join(sorted(types))}); move it to configuration "
|
|
157
|
+
"or a secret store, and rotate it if it was ever committed", ctx.rel(path), line)
|
|
158
|
+
|
|
159
|
+
def run(self, ctx):
|
|
160
|
+
out = self.exec(["scan", "--exclude-lines", NOT_SECRET_LINES, *ctx.files], ctx)
|
|
161
|
+
result = Result()
|
|
162
|
+
lines = LineCache(ctx.root)
|
|
163
|
+
for path, items in json.loads(out)["results"].items():
|
|
164
|
+
by_line = {}
|
|
165
|
+
for item in items:
|
|
166
|
+
by_line.setdefault(item["line_number"], set()).add(item["type"])
|
|
167
|
+
result.findings += [self.finding(ctx, path, line, types) for line, types in sorted(by_line.items())
|
|
168
|
+
if not types <= ENTROPY_ONLY
|
|
169
|
+
or CREDENTIAL_CONTEXT_RE.search(credential_context(lines, path, line))]
|
|
170
|
+
result.findings += known_tokens(ctx, {(f.path, f.line) for f in result.findings})
|
|
171
|
+
return result
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
# A random-looking string alone is usually a hash, id or fixture; it's a secret candidate when named like one.
|
|
175
|
+
ENTROPY_ONLY = {"Base64 High Entropy String", "Hex High Entropy String"}
|
|
176
|
+
CREDENTIAL_CONTEXT_RE = re.compile(
|
|
177
|
+
r"(?i)(?<![a-z])(?:api_?|private_?|secret_?|access_?|signing_?)?keys?(?![a-z])|apikey|token|secret|passw|pwd"
|
|
178
|
+
r"|(?<![a-z])auth(?!or)|credential|bearer|signature"
|
|
179
|
+
)
|
|
180
|
+
TOKEN_FORMATS = [
|
|
181
|
+
("SonarQube Token", re.compile(r"\b(?:squ|sqp|sqa)_[0-9a-f]{40}\b")),
|
|
182
|
+
("GitHub Token", re.compile(r"\b(?:gh[pousr]_[A-Za-z0-9]{36,255}|github_pat_[A-Za-z0-9_]{22,255})\b")),
|
|
183
|
+
("GitLab Token", re.compile(r"\bglpat-[A-Za-z0-9_-]{20,64}")),
|
|
184
|
+
("Anthropic API Key", re.compile(r"\bsk-ant-[A-Za-z0-9_-]{20,200}")),
|
|
185
|
+
("OpenAI API Key", re.compile(r"\bsk-(?:proj-)?[A-Za-z0-9]{20,200}T3BlbkFJ[A-Za-z0-9]{20,200}")),
|
|
186
|
+
("Google API Key", re.compile(r"\bAIza[0-9A-Za-z_-]{35}\b")),
|
|
187
|
+
("Hugging Face Token", re.compile(r"\bhf_[A-Za-z0-9]{34,40}\b")),
|
|
188
|
+
("npm Token", re.compile(r"\bnpm_[A-Za-z0-9]{36}\b")),
|
|
189
|
+
("codewatch Token", re.compile(r"\bcw_[A-Za-z0-9_-]{43}(?![A-Za-z0-9_-])")),
|
|
190
|
+
]
|
|
191
|
+
MAX_TOKEN_SCAN_BYTES = 2 * 1024 * 1024
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def credential_context(lines, path, line):
|
|
195
|
+
"""In Python, the whole function around the string (check_password() comparing a hard-coded hash); in data
|
|
196
|
+
and other files just the line, since neighbouring JSON keys say nothing about this value."""
|
|
197
|
+
return lines.function_text(path, line) if path.endswith(".py") else lines.get(path, line)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def small_text(full):
|
|
201
|
+
"""A text file's contents, or None if it is too large to scan or isn't text."""
|
|
202
|
+
try:
|
|
203
|
+
if full.stat().st_size > MAX_TOKEN_SCAN_BYTES:
|
|
204
|
+
return None
|
|
205
|
+
return full.read_text(errors="strict")
|
|
206
|
+
except (OSError, UnicodeDecodeError):
|
|
207
|
+
return None
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def token_kind(line):
|
|
211
|
+
return next((k for k, pattern in TOKEN_FORMATS if pattern.search(line)), None)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def known_tokens(ctx, already):
|
|
215
|
+
findings = []
|
|
216
|
+
for path in ctx.files:
|
|
217
|
+
text = small_text(ctx.root / path)
|
|
218
|
+
findings += [Finding(DETECTOR, kind, BLOCKER, VULNERABILITY,
|
|
219
|
+
f"{kind} committed to the repository; revoke it and load it from configuration", path, n)
|
|
220
|
+
for n, line in enumerate((text or "").splitlines(), 1)
|
|
221
|
+
if (path, n) not in already and (kind := token_kind(line))]
|
|
222
|
+
return findings
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
class Checkov(Analyzer):
|
|
226
|
+
"""Misconfigurations in Dockerfiles, Terraform, Kubernetes manifests and GitHub Actions workflows."""
|
|
227
|
+
|
|
228
|
+
name = executable = "checkov"
|
|
229
|
+
|
|
230
|
+
def binary(self):
|
|
231
|
+
return isolated_tool(self.name) or super().binary()
|
|
232
|
+
|
|
233
|
+
def applies(self, ctx):
|
|
234
|
+
return any(self.is_iac(f) for f in ctx.files)
|
|
235
|
+
|
|
236
|
+
@staticmethod
|
|
237
|
+
def is_iac(path):
|
|
238
|
+
p = Path(path)
|
|
239
|
+
return (p.name.startswith(DOCKERFILES) or p.suffix == ".tf"
|
|
240
|
+
or (p.suffix in (".yml", ".yaml") and ".github/workflows" in path))
|
|
241
|
+
|
|
242
|
+
def run(self, ctx):
|
|
243
|
+
files = [f for f in ctx.files if self.is_iac(f)]
|
|
244
|
+
args = ["--output", "json", "--quiet", "--compact", "--skip-download",
|
|
245
|
+
"--framework", "dockerfile", "terraform", "github_actions", "kubernetes"]
|
|
246
|
+
for f in files:
|
|
247
|
+
args += ["--file", str(ctx.root / f)]
|
|
248
|
+
# Checkov reads .checkov.yaml from its working directory: the scanned repository's could write report files
|
|
249
|
+
# into it (output-file-path) or load Python from it (external-checks-dir). It runs from an empty directory.
|
|
250
|
+
with tempfile.TemporaryDirectory() as cwd:
|
|
251
|
+
out = self.exec(args, ctx, ok_codes=(0, 1), cwd=cwd)
|
|
252
|
+
reports = json.loads(out or "[]")
|
|
253
|
+
result = Result()
|
|
254
|
+
for report in reports if isinstance(reports, list) else [reports]:
|
|
255
|
+
result.findings += [checkov_finding(ctx, c) for c in report.get("results", {}).get("failed_checks", [])]
|
|
256
|
+
return result
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def checkov_finding(ctx, check):
|
|
260
|
+
first, last = check.get("file_line_range") or [None, None]
|
|
261
|
+
resource = f" ({check['resource']})" if check.get("resource") else ""
|
|
262
|
+
return Finding(Checkov.name, check["check_id"], MAJOR, HOTSPOT, check["check_name"] + resource,
|
|
263
|
+
checkov_path(ctx, check["file_path"]), first or None, last or None)
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def checkov_path(ctx, path):
|
|
267
|
+
"""Checkov reports paths as absolute or as "/relative/to/root" depending on how files were passed."""
|
|
268
|
+
if path.startswith(str(ctx.root)):
|
|
269
|
+
return ctx.rel(path)
|
|
270
|
+
return path.lstrip("/")
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
class EslintQuality(Analyzer):
|
|
274
|
+
"""Bugs, risky APIs and maintainability for JS/TS: ESLint core rules plus eslint-plugin-security."""
|
|
275
|
+
|
|
276
|
+
name = executable = "eslint"
|
|
277
|
+
extensions = JS
|
|
278
|
+
|
|
279
|
+
def binary(self):
|
|
280
|
+
return node_tool(self.name)
|
|
281
|
+
|
|
282
|
+
def run(self, ctx):
|
|
283
|
+
result = Result()
|
|
284
|
+
result.findings = drop_shared_globals(ctx, self.lint(ctx, "eslint-quality.config.js", ctx.files_with(JS)))
|
|
285
|
+
typed = typed_ts_files(ctx)
|
|
286
|
+
if typed:
|
|
287
|
+
# A file the TypeScript project can't load reports a parse error here; the main pass already covers it.
|
|
288
|
+
result.findings += [f for f in self.lint(ctx, "eslint-typed.config.js", typed) if f.rule != "parse-error"]
|
|
289
|
+
return result
|
|
290
|
+
|
|
291
|
+
def lint(self, ctx, config, files):
|
|
292
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
293
|
+
report = Path(tmp) / "report.json"
|
|
294
|
+
self.exec(["--config", str(TOOLS_DIR / config), "--format", "json", "--output-file", str(report),
|
|
295
|
+
"--no-warn-ignored", *files], ctx, ok_codes=(0, 1))
|
|
296
|
+
data = json.loads(report.read_text()) if report.exists() else []
|
|
297
|
+
findings = []
|
|
298
|
+
for file_report in data:
|
|
299
|
+
for m in file_report["messages"]:
|
|
300
|
+
rule = m.get("ruleId") or "parse-error"
|
|
301
|
+
severity, type_ = eslint_classify(rule, m.get("severity"))
|
|
302
|
+
findings.append(Finding(self.name, rule, severity, type_, m["message"],
|
|
303
|
+
ctx.rel(file_report["filePath"]), m.get("line"), m.get("endLine")))
|
|
304
|
+
return findings
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
TS = {".ts", ".tsx", ".mts", ".cts"}
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def typed_ts_files(ctx):
|
|
311
|
+
"""TypeScript files with a tsconfig.json in their directory or above it (within the scanned tree)."""
|
|
312
|
+
configs = {Path(f).parent for f in ctx.files if Path(f).name == "tsconfig.json"}
|
|
313
|
+
return [f for f in ctx.files_with(TS) if any(d == Path(".") or d in Path(f).parents for d in configs)]
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
UNDEFINED_RE = re.compile(r"^'([\w$]{1,100})' is not defined")
|
|
317
|
+
TOP_LEVEL_DEF_RE = re.compile(r"^(?:async\s+)?(?:function\*?|var|let|const|class)\s+([\w$]{1,100})", re.MULTILINE)
|
|
318
|
+
GLOBAL_ASSIGN_RE = re.compile(r"\b(?:window|globalThis|self)\.([\w$]{1,100})\s{0,5}=[^=]")
|
|
319
|
+
HOST_GLOBAL_MIN_FILES = 3
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def defined_globals(ctx):
|
|
323
|
+
"""Names the project's scripts define at top level or assign to window/globalThis/self."""
|
|
324
|
+
defined = set()
|
|
325
|
+
for path in ctx.files_with(JS):
|
|
326
|
+
try:
|
|
327
|
+
text = (ctx.root / path).read_text(errors="replace")
|
|
328
|
+
except OSError:
|
|
329
|
+
continue
|
|
330
|
+
defined.update(TOP_LEVEL_DEF_RE.findall(text))
|
|
331
|
+
defined.update(GLOBAL_ASSIGN_RE.findall(text))
|
|
332
|
+
return defined
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def shared_names(undefined, defined):
|
|
336
|
+
"""The undefined names another script defines, or that several files use (globals the host page injects)."""
|
|
337
|
+
files_using = {}
|
|
338
|
+
for f, name in undefined:
|
|
339
|
+
files_using.setdefault(name, set()).add(f.path)
|
|
340
|
+
return {n for n, paths in files_using.items() if n in defined or len(paths) >= HOST_GLOBAL_MIN_FILES}
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def drop_shared_globals(ctx, findings):
|
|
344
|
+
"""no-undef sees one file at a time. Names another script defines at top level, or that several files use
|
|
345
|
+
without anyone defining them (globals the host page or runtime injects), are not undefined."""
|
|
346
|
+
undefined = [(f, m[1]) for f in findings if f.rule == "no-undef" and (m := UNDEFINED_RE.match(f.message))]
|
|
347
|
+
if not undefined:
|
|
348
|
+
return findings
|
|
349
|
+
shared = shared_names(undefined, defined_globals(ctx))
|
|
350
|
+
drop = {id(f) for f, name in undefined if name in shared}
|
|
351
|
+
return [f for f in findings if id(f) not in drop]
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
ESLINT_BUG_RULES = {
|
|
355
|
+
"no-undef", "no-unreachable", "no-dupe-keys", "no-dupe-else-if", "no-self-compare", "no-cond-assign",
|
|
356
|
+
"no-unmodified-loop-condition", "no-unreachable-loop", "use-isnan", "valid-typeof", "no-func-assign",
|
|
357
|
+
"no-import-assign", "no-const-assign", "no-unsafe-finally", "no-unsafe-negation", "no-fallthrough",
|
|
358
|
+
"no-sparse-arrays", "no-compare-neg-zero", "getter-return", "no-setter-return", "no-async-promise-executor",
|
|
359
|
+
"require-atomic-updates", "eqeqeq", "no-throw-literal", "no-unused-expressions", "consistent-return",
|
|
360
|
+
"no-mixed-operators", "no-restricted-syntax", "@typescript-eslint/no-floating-promises",
|
|
361
|
+
"@typescript-eslint/no-misused-promises",
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def eslint_classify(rule, level):
|
|
366
|
+
if rule == "parse-error":
|
|
367
|
+
return MAJOR, BUG
|
|
368
|
+
if rule.startswith("security/") or rule in ("no-eval", "no-implied-eval", "no-new-func"):
|
|
369
|
+
return MAJOR, HOTSPOT
|
|
370
|
+
if rule in ESLINT_BUG_RULES:
|
|
371
|
+
return (MAJOR if level == 2 else MINOR), BUG
|
|
372
|
+
return MINOR, CODE_SMELL
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
class Stylelint(Analyzer):
|
|
376
|
+
"""CSS errors (invalid values, unknown properties, duplicates) with stylelint's recommended rules."""
|
|
377
|
+
|
|
378
|
+
name = executable = "stylelint"
|
|
379
|
+
extensions = {".css"}
|
|
380
|
+
|
|
381
|
+
def binary(self):
|
|
382
|
+
return node_tool(self.name)
|
|
383
|
+
|
|
384
|
+
def run(self, ctx):
|
|
385
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
386
|
+
report = Path(tmp) / "report.json"
|
|
387
|
+
self.exec(["--config", str(TOOLS_DIR / "stylelint.config.json"), "--formatter", "json",
|
|
388
|
+
"--output-file", str(report), "--allow-empty-input", *ctx.files_with(self.extensions)],
|
|
389
|
+
ctx, ok_codes=(0, 2))
|
|
390
|
+
data = json.loads(report.read_text()) if report.exists() else []
|
|
391
|
+
result = Result()
|
|
392
|
+
for file_report in data:
|
|
393
|
+
for w in file_report["warnings"]:
|
|
394
|
+
error = w["severity"] == "error"
|
|
395
|
+
result.findings.append(
|
|
396
|
+
Finding(self.name, w["rule"], MAJOR if error else MINOR, BUG if error else CODE_SMELL,
|
|
397
|
+
w["text"].removesuffix(f" ({w['rule']})"), ctx.rel(file_report["source"]),
|
|
398
|
+
w.get("line"), w.get("endLine"))
|
|
399
|
+
)
|
|
400
|
+
return result
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Flask-RESTful / Flask-RESTX resources' URL parameters as request sources.
|
|
2
|
+
|
|
3
|
+
A Resource's handler methods take the URL's variable parts as parameters (`def get(self, rdtype, domain)`), but
|
|
4
|
+
the URL is given elsewhere: `api.add_resource(LookupRecordType, "/<rdtype>/<domain>")`. This reads those
|
|
5
|
+
registrations with ast and adds, per registered class, a source for the parameters the URL fills with text (no
|
|
6
|
+
converter, `string` or `path`): `<int:certificate_id>` is a number. OpenResolve GHSA-h3h4 (a record type and domain
|
|
7
|
+
from the path, reflected in error messages).
|
|
8
|
+
"""
|
|
9
|
+
import ast
|
|
10
|
+
import re
|
|
11
|
+
|
|
12
|
+
from .base import python_tree
|
|
13
|
+
from .body_models import takes_route_sources
|
|
14
|
+
|
|
15
|
+
PARAMETER_RE = re.compile(r"<(?:(\w+)(?:\([^()<>]*\))?:)?(\w+)>")
|
|
16
|
+
TEXT_CONVERTERS = {"", "string", "path"}
|
|
17
|
+
HANDLERS = "get|post|put|patch|delete"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def text_parameters(texts):
|
|
21
|
+
"""{resource class name: URL parameters filled with text}, from `$API.add_resource(Class, "/url", ...)`."""
|
|
22
|
+
found = {}
|
|
23
|
+
for tree in filter(None, (python_tree(text) for text in texts if "add_resource" in text)):
|
|
24
|
+
for node in ast.walk(tree):
|
|
25
|
+
if registered := resource_parameters(node):
|
|
26
|
+
found.setdefault(registered[0], set()).update(registered[1])
|
|
27
|
+
return found
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def resource_parameters(node):
|
|
31
|
+
"""(resource class name, {text URL parameters}) for an add_resource call that has both, else None."""
|
|
32
|
+
if not (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)
|
|
33
|
+
and node.func.attr == "add_resource" and node.args):
|
|
34
|
+
return None
|
|
35
|
+
target = node.args[0]
|
|
36
|
+
name = target.attr if isinstance(target, ast.Attribute) else getattr(target, "id", None)
|
|
37
|
+
params = text_url_parameters(node.args[1:])
|
|
38
|
+
return (name, params) if name and params else None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def text_url_parameters(args):
|
|
42
|
+
"""URL parameters filled with text in the URL strings among args."""
|
|
43
|
+
urls = [a.value for a in args if isinstance(a, ast.Constant) and isinstance(a.value, str)]
|
|
44
|
+
return {param for url in urls for converter, param in PARAMETER_RE.findall(url) if converter in TEXT_CONVERTERS}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def resource_source(cls, params):
|
|
48
|
+
names = "|".join(sorted(map(re.escape, params)))
|
|
49
|
+
return {"patterns": [
|
|
50
|
+
{"pattern-inside": f"class {cls}(...):\n ...\n"},
|
|
51
|
+
{"pattern-inside": "def $HANDLER(self, ..., $PARAM, ...):\n ...\n"},
|
|
52
|
+
{"metavariable-regex": {"metavariable": "$HANDLER", "regex": f"^({HANDLERS})$"}},
|
|
53
|
+
{"metavariable-regex": {"metavariable": "$PARAM", "regex": f"^({names})$"}},
|
|
54
|
+
{"focus-metavariable": "$PARAM"},
|
|
55
|
+
]}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def with_resource_sources(rules, texts):
|
|
59
|
+
"""The rules, with a source per registered resource on every Python taint rule that takes route parameters."""
|
|
60
|
+
found = text_parameters(texts)
|
|
61
|
+
if not found:
|
|
62
|
+
return rules
|
|
63
|
+
extra = [resource_source(cls, params) for cls, params in sorted(found.items())]
|
|
64
|
+
return [{**rule, "pattern-sources": [*rule["pattern-sources"], *extra]} if takes_route_sources(rule) else rule
|
|
65
|
+
for rule in rules]
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""A template's inline <script> blocks as JavaScript Semgrep can scan.
|
|
2
|
+
|
|
3
|
+
Python apps ship much of their front end as scripts inside Jinja and Django templates, which the JavaScript rules
|
|
4
|
+
never saw (only .js files are JavaScript to Semgrep). The copy keeps every line where it was: script code stays,
|
|
5
|
+
everything else (markup, <script src=...>, non-JavaScript script types) becomes blank, and template tags inside the
|
|
6
|
+
code become same-length filler, so a finding's line is the template's line.
|
|
7
|
+
"""
|
|
8
|
+
import re
|
|
9
|
+
|
|
10
|
+
# Attributes run to the first ">" (template tags such as <?= ?> included) and contents to the first </script, as a
|
|
11
|
+
# browser reads them; neither runs past another <script, so a page of unclosed tags is read once, not once per tag.
|
|
12
|
+
SCRIPT_RE = re.compile(r"<script\b((?:[^<>]|<(?!script\b))*)>([^<]*(?:<(?!/?script\b)[^<]*)*)</script\s*>", re.IGNORECASE)
|
|
13
|
+
# Script types that are JavaScript; anything else (text/template, application/json, x-tmpl-mustache) is data.
|
|
14
|
+
JS_TYPES = {"", "text/javascript", "application/javascript", "module", "text/ecmascript", "application/ecmascript"}
|
|
15
|
+
TYPE_RE = re.compile(r"""\btype\s*=\s*["']?([^"'\s>]*)""", re.IGNORECASE)
|
|
16
|
+
SRC_RE = re.compile(r"\bsrc\s*=", re.IGNORECASE)
|
|
17
|
+
# A template expression becomes a number (valid JavaScript wherever a value goes, plain text inside a string);
|
|
18
|
+
# statement tags and template comments become spaces. Newlines inside a tag are kept so lines don't move.
|
|
19
|
+
EXPRESSION_RE = re.compile(r"\{\{(?:[^{}]|\{(?!\{)|\}(?!\}))*\}\}")
|
|
20
|
+
STATEMENT_RE = re.compile(r"\{%(?:[^{%]|%(?!\})|\{(?!%))*%\}|\{#(?:[^{#]|#(?!\})|\{(?!#))*#\}")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _blank(text):
|
|
24
|
+
return re.sub(r"[^\n]", " ", text)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _filler(match):
|
|
28
|
+
text = match.group(0)
|
|
29
|
+
return "0" + _blank(text[1:])
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def inline_scripts(source):
|
|
33
|
+
"""The template as JavaScript with only its inline scripts kept, or None if it has none."""
|
|
34
|
+
pieces, last, found = [], 0, False
|
|
35
|
+
for match in SCRIPT_RE.finditer(source):
|
|
36
|
+
attributes, code = match.group(1), match.group(2)
|
|
37
|
+
kind = (m.group(1).lower() if (m := TYPE_RE.search(attributes)) else "")
|
|
38
|
+
start = match.start(2)
|
|
39
|
+
pieces.append(_blank(source[last:start]))
|
|
40
|
+
if SRC_RE.search(attributes) or kind not in JS_TYPES or not code.strip():
|
|
41
|
+
pieces.append(_blank(code))
|
|
42
|
+
else:
|
|
43
|
+
found = True
|
|
44
|
+
code = STATEMENT_RE.sub(lambda m: _blank(m.group(0)), code)
|
|
45
|
+
pieces.append(EXPRESSION_RE.sub(_filler, code))
|
|
46
|
+
last = match.end(2)
|
|
47
|
+
if not found:
|
|
48
|
+
return None
|
|
49
|
+
pieces.append(_blank(source[last:]))
|
|
50
|
+
return "".join(pieces)
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Jinja sandboxes the project makes in one module and renders with in another.
|
|
2
|
+
|
|
3
|
+
The template-injection rule leaves `env.from_string(text)` alone where `env = SandboxedEnvironment(...)` is in the
|
|
4
|
+
same function. paperless-ngx defines `class JinjaEnvironment(SandboxedEnvironment)`, makes
|
|
5
|
+
`_template_environment = JinjaEnvironment(...)` in one module and imports it where users' storage-path templates
|
|
6
|
+
are rendered. This reads the project with ast for classes based (through any of the project's classes) on
|
|
7
|
+
jinja2's SandboxedEnvironment or ImmutableSandboxedEnvironment, and the names and self fields assigned an instance
|
|
8
|
+
of one, and adds a sanitizer for `name.from_string(...)` and `name.get_template(...)` to that rule.
|
|
9
|
+
"""
|
|
10
|
+
import ast
|
|
11
|
+
import re
|
|
12
|
+
|
|
13
|
+
from .base import python_tree
|
|
14
|
+
|
|
15
|
+
RULE = "codewatch.python.web.template-injection"
|
|
16
|
+
SANDBOXES = {"SandboxedEnvironment", "ImmutableSandboxedEnvironment"}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def base_name(node):
|
|
20
|
+
return node.attr if isinstance(node, ast.Attribute) else getattr(node, "id", "")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def sandbox_names(texts):
|
|
24
|
+
"""Names (`env`, `self.env`) assigned an instance of a sandboxed Jinja environment anywhere in texts."""
|
|
25
|
+
trees = [tree for tree in (python_tree(text) for text in texts if "Environment" in text) if tree]
|
|
26
|
+
sandboxes = sandbox_classes(trees)
|
|
27
|
+
return {name for tree in trees for node in ast.walk(tree) if creates(node, sandboxes)
|
|
28
|
+
for name in assigned_names(node.targets)}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def creates(node, classes):
|
|
32
|
+
"""`x = Cls(...)` for one of classes."""
|
|
33
|
+
return isinstance(node, ast.Assign) and isinstance(node.value, ast.Call) and base_name(node.value.func) in classes
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def sandbox_classes(trees):
|
|
37
|
+
"""The sandboxed environment classes, and the project's classes derived from them at any depth."""
|
|
38
|
+
bases = {node.name: {base_name(b) for b in node.bases}
|
|
39
|
+
for tree in trees for node in ast.walk(tree) if isinstance(node, ast.ClassDef)}
|
|
40
|
+
sandboxes = set(SANDBOXES)
|
|
41
|
+
while more := {cls for cls, parents in bases.items() if cls not in sandboxes and parents & sandboxes}:
|
|
42
|
+
sandboxes |= more
|
|
43
|
+
return sandboxes
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def assigned_names(targets):
|
|
47
|
+
"""`env` and `self.env` among assignment targets."""
|
|
48
|
+
return [target.id if isinstance(target, ast.Name) else f"self.{target.attr}" for target in targets
|
|
49
|
+
if isinstance(target, ast.Name)
|
|
50
|
+
or (isinstance(target, ast.Attribute) and getattr(target.value, "id", None) == "self")]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def with_sandbox_sanitizers(rules, texts):
|
|
54
|
+
names = sandbox_names(texts)
|
|
55
|
+
if not names:
|
|
56
|
+
return rules
|
|
57
|
+
regex = "^(" + "|".join(sorted(map(re.escape, names))) + ")$"
|
|
58
|
+
sanitizer = {"patterns": [
|
|
59
|
+
{"pattern-either": [{"pattern": "$ENV.from_string(...)"}, {"pattern": "$ENV.get_template(...)"}]},
|
|
60
|
+
{"metavariable-regex": {"metavariable": "$ENV", "regex": regex}},
|
|
61
|
+
]}
|
|
62
|
+
return [{**rule, "pattern-sanitizers": [*rule.get("pattern-sanitizers", []), sanitizer]} if rule.get("id") == RULE
|
|
63
|
+
else rule for rule in rules]
|