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,347 @@
|
|
|
1
|
+
import fnmatch
|
|
2
|
+
import json
|
|
3
|
+
import re
|
|
4
|
+
import tomllib
|
|
5
|
+
import urllib.request
|
|
6
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
import yaml
|
|
10
|
+
|
|
11
|
+
from .base import MAJOR, Analyzer, Finding, Result, ToolError
|
|
12
|
+
|
|
13
|
+
OSV_URL = "https://api.osv.dev/v1/vulns/{}"
|
|
14
|
+
OSV_SEVERITY = {"CRITICAL": "blocker", "HIGH": "critical", "MODERATE": MAJOR, "MEDIUM": MAJOR, "LOW": "minor"}
|
|
15
|
+
REQUIREMENTS_GLOB = "requirements*.txt"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def normalize(name):
|
|
19
|
+
return re.sub(r"[-_.]+", "-", name).lower()
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def manifests(files, root):
|
|
23
|
+
found = []
|
|
24
|
+
for f in files:
|
|
25
|
+
name = Path(f).name
|
|
26
|
+
if fnmatch.fnmatch(name, REQUIREMENTS_GLOB):
|
|
27
|
+
found.append(f)
|
|
28
|
+
elif name == "pyproject.toml":
|
|
29
|
+
try:
|
|
30
|
+
data = tomllib.loads((root / f).read_text())
|
|
31
|
+
except (OSError, tomllib.TOMLDecodeError):
|
|
32
|
+
continue
|
|
33
|
+
if data.get("project", {}).get("dependencies"):
|
|
34
|
+
found.append(f)
|
|
35
|
+
return found
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def osv_severity(vuln_ids):
|
|
39
|
+
"""GitHub-reviewed advisories carry a CRITICAL/HIGH/MODERATE/LOW rating that PYSEC entries lack."""
|
|
40
|
+
for vid in sorted(vuln_ids, key=lambda v: not v.startswith("GHSA")):
|
|
41
|
+
try:
|
|
42
|
+
with urllib.request.urlopen(OSV_URL.format(vid), timeout=10) as resp:
|
|
43
|
+
rating = json.load(resp).get("database_specific", {}).get("severity")
|
|
44
|
+
except (OSError, ValueError):
|
|
45
|
+
continue
|
|
46
|
+
if rating in OSV_SEVERITY:
|
|
47
|
+
return OSV_SEVERITY[rating]
|
|
48
|
+
return MAJOR
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class PipAudit(Analyzer):
|
|
52
|
+
"""Known CVEs/advisories in Python dependencies, resolved transitively by pip-audit against PyPI + OSV."""
|
|
53
|
+
|
|
54
|
+
name = "pip-audit"
|
|
55
|
+
executable = "pip-audit"
|
|
56
|
+
|
|
57
|
+
def applies(self, ctx):
|
|
58
|
+
return bool(manifests(ctx.files, ctx.root))
|
|
59
|
+
|
|
60
|
+
def audit(self, ctx, manifest):
|
|
61
|
+
"""Dependencies with advisories, resolved from the manifest. If pip can't resolve it (a package missing
|
|
62
|
+
for this Python, a private index), the packages installed in the project's own venv are audited instead;
|
|
63
|
+
None if neither works."""
|
|
64
|
+
args = [str(Path(manifest).parent)] if manifest.endswith(".toml") else ["-r", manifest]
|
|
65
|
+
if not ctx.local:
|
|
66
|
+
# Resolving installs the requirements, and building a project or a package from source runs its code:
|
|
67
|
+
# on the server only pinned requirements are checked, as written.
|
|
68
|
+
if manifest.endswith(".toml"):
|
|
69
|
+
return None
|
|
70
|
+
args += ["--no-deps", "--disable-pip"]
|
|
71
|
+
for attempt in ([*args], *(["--path", str(p)] for p in project_site_packages(ctx.root))):
|
|
72
|
+
try:
|
|
73
|
+
out = self.exec([*attempt, "--format", "json", "--progress-spinner", "off"], ctx, ok_codes=(0, 1))
|
|
74
|
+
return json.loads(out)["dependencies"]
|
|
75
|
+
except (ToolError, ValueError, KeyError):
|
|
76
|
+
continue
|
|
77
|
+
return None
|
|
78
|
+
|
|
79
|
+
def run(self, ctx):
|
|
80
|
+
pending, seen, unresolved = [], set(), 0
|
|
81
|
+
for manifest in manifests(ctx.files, ctx.root):
|
|
82
|
+
text = read_manifest(ctx.root / manifest)
|
|
83
|
+
deps = self.audit(ctx, manifest)
|
|
84
|
+
if deps is None:
|
|
85
|
+
unresolved += 1
|
|
86
|
+
continue
|
|
87
|
+
for dep in deps:
|
|
88
|
+
for vuln in dep.get("vulns", []):
|
|
89
|
+
if (manifest, dep["name"], vuln["id"]) not in seen:
|
|
90
|
+
seen.add((manifest, dep["name"], vuln["id"]))
|
|
91
|
+
pending.append((manifest, text, dep, vuln))
|
|
92
|
+
result = Result()
|
|
93
|
+
with ThreadPoolExecutor(max_workers=8) as pool:
|
|
94
|
+
result.findings = list(pool.map(vulnerability_finding, pending))
|
|
95
|
+
result.metrics["vulnerable_dependencies"] = len({normalize(dep["name"]) for _, _, dep, _ in pending})
|
|
96
|
+
result.metrics["dependency_vulnerabilities"] = len(result.findings)
|
|
97
|
+
result.metrics["dependency_critical_vulnerabilities"] = sum(
|
|
98
|
+
f.severity in ("blocker", "critical") for f in result.findings
|
|
99
|
+
)
|
|
100
|
+
result.metrics["dependency_manifests_unresolved"] = unresolved
|
|
101
|
+
return result
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def project_site_packages(root):
|
|
105
|
+
return sorted(Path(root).glob("*venv/lib/python3*/site-packages"))
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def read_manifest(path):
|
|
109
|
+
"""Requirements files are sometimes saved as UTF-16 (PowerShell's default); pip reads those by their BOM."""
|
|
110
|
+
raw = path.read_bytes()
|
|
111
|
+
for bom, encoding in ((b"\xff\xfe", "utf-16"), (b"\xfe\xff", "utf-16"), (b"\xef\xbb\xbf", "utf-8-sig")):
|
|
112
|
+
if raw.startswith(bom):
|
|
113
|
+
return raw.decode(encoding, errors="replace")
|
|
114
|
+
return raw.decode("utf-8", errors="replace")
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def advisory_summary(vuln):
|
|
118
|
+
"""First prose line of an advisory; GitHub advisories start with Markdown headings."""
|
|
119
|
+
lines = (vuln.get("description") or "").splitlines()
|
|
120
|
+
return next((ln.strip() for ln in lines if ln.strip() and not ln.lstrip().startswith("#")), "")[:300]
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def vulnerability_finding(item):
|
|
124
|
+
manifest, text, dep, vuln = item
|
|
125
|
+
ids = [vuln["id"], *vuln.get("aliases", [])]
|
|
126
|
+
cve = next((a for a in ids if a.startswith("CVE-")), vuln["id"])
|
|
127
|
+
line = declaration_line(text, dep["name"])
|
|
128
|
+
fix = ", ".join(vuln.get("fix_versions") or []) or "none available"
|
|
129
|
+
where = "" if line else " (transitive)"
|
|
130
|
+
return Finding("pip-audit", cve, osv_severity(ids), "vulnerability",
|
|
131
|
+
f"{dep['name']} {dep['version']}{where}: {cve} \u2014 fixed in {fix}. {advisory_summary(vuln)}",
|
|
132
|
+
manifest, line)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def declaration_line(text, package):
|
|
136
|
+
target = normalize(package)
|
|
137
|
+
for i, line in enumerate(text.splitlines(), 1):
|
|
138
|
+
m = re.match(r"""\s*["']?([A-Za-z0-9][A-Za-z0-9._-]*)""", line)
|
|
139
|
+
if m and normalize(m[1]) == target:
|
|
140
|
+
return i
|
|
141
|
+
return None
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
# --- JavaScript lockfiles, checked against OSV directly ------------------------------------------------------
|
|
145
|
+
|
|
146
|
+
OSV_BATCH_URL = "https://api.osv.dev/v1/querybatch"
|
|
147
|
+
OSV_BATCH_SIZE = 1000
|
|
148
|
+
LOCKFILES = ("package-lock.json", "npm-shrinkwrap.json", "yarn.lock", "pnpm-lock.yaml")
|
|
149
|
+
YARN_VERSION_RE = re.compile(r"""^\s+version:?\s+"?([^"\s]+)"?\s*$""")
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def mark(found, package, dev):
|
|
153
|
+
"""A package counts as development-only when every place that installs it says so."""
|
|
154
|
+
found[package] = found.get(package, True) and bool(dev)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def lockfile_v2_packages(found, packages):
|
|
158
|
+
"""Lockfile versions 2 and 3: `packages`, keyed by node_modules path."""
|
|
159
|
+
for key, entry in packages.items():
|
|
160
|
+
if "node_modules/" in key and not entry.get("link") and entry.get("version"):
|
|
161
|
+
name = entry.get("name") or key.rsplit("node_modules/", 1)[1]
|
|
162
|
+
mark(found, (name, entry["version"]), entry.get("dev") or entry.get("devOptional"))
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def lockfile_v1_packages(found, dependencies):
|
|
166
|
+
"""Lockfile version 1: nested `dependencies`."""
|
|
167
|
+
stack = list(dependencies.items())
|
|
168
|
+
while stack:
|
|
169
|
+
name, entry = stack.pop()
|
|
170
|
+
if isinstance(entry, dict) and entry.get("version") and not str(entry["version"]).startswith("file:"):
|
|
171
|
+
mark(found, (name, entry["version"]), entry.get("dev"))
|
|
172
|
+
stack.extend((entry.get("dependencies") or {}).items())
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def package_lock_packages(text):
|
|
176
|
+
"""{(name, version): development only} from package-lock.json / npm-shrinkwrap.json, lockfile versions 1-3."""
|
|
177
|
+
data = json.loads(text)
|
|
178
|
+
found = {}
|
|
179
|
+
lockfile_v2_packages(found, data.get("packages") or {})
|
|
180
|
+
if not data.get("packages"):
|
|
181
|
+
lockfile_v1_packages(found, data.get("dependencies") or {})
|
|
182
|
+
return found
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def yarn_spec_name(spec):
|
|
186
|
+
"""`"@scope/pkg@^1.2"` or `pkg@npm:^1.2` -> the package name; None for workspace, patch and link entries."""
|
|
187
|
+
spec = spec.strip().strip('"')
|
|
188
|
+
at = spec.find("@", 1)
|
|
189
|
+
name, rest = (spec[:at], spec[at + 1:]) if at > 0 else ("", "")
|
|
190
|
+
if not name or rest.startswith(("workspace:", "patch:", "link:", "portal:", "file:")):
|
|
191
|
+
return None
|
|
192
|
+
return name
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def yarn_entry_names(line):
|
|
196
|
+
"""The package names an entry header (`"a@^1", a@^1.2:`) names, or None for any other line."""
|
|
197
|
+
if not line or line[0].isspace() or not line.rstrip().endswith(":") or line.startswith("#"):
|
|
198
|
+
return None
|
|
199
|
+
return [n for n in (yarn_spec_name(s) for s in line.rstrip()[:-1].split(",")) if n]
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def yarn_lock_packages(text):
|
|
203
|
+
"""{(name, version): False} from yarn.lock, classic (v1) and Berry formats, which don't mark dev packages."""
|
|
204
|
+
found, names = {}, []
|
|
205
|
+
for line in text.splitlines():
|
|
206
|
+
if (header := yarn_entry_names(line)) is not None:
|
|
207
|
+
names = header
|
|
208
|
+
elif names and (match := YARN_VERSION_RE.match(line)):
|
|
209
|
+
found.update(((name, match[1]), False) for name in names)
|
|
210
|
+
names = []
|
|
211
|
+
return found
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def pnpm_lock_packages(text):
|
|
215
|
+
"""{(name, version): development only} from pnpm-lock.yaml: `/name/1.2.3` (v5), `/name@1.2.3(peer)` (v6) or
|
|
216
|
+
`name@1.2.3` (v9, which no longer marks dev packages)."""
|
|
217
|
+
data = yaml.safe_load(text) or {}
|
|
218
|
+
found = {}
|
|
219
|
+
for raw, entry in (data.get("packages") or {}).items():
|
|
220
|
+
key = re.split(r"[(_]", str(raw).lstrip("/"), maxsplit=1)[0] # without the peer suffix
|
|
221
|
+
at = key.rfind("@")
|
|
222
|
+
if at > 0:
|
|
223
|
+
name, version = key[:at], key[at + 1:]
|
|
224
|
+
else:
|
|
225
|
+
name, _, version = key.rpartition("/")
|
|
226
|
+
if name and version and version[0].isdigit():
|
|
227
|
+
mark(found, (name, version), isinstance(entry, dict) and entry.get("dev"))
|
|
228
|
+
return found
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
LOCKFILE_PARSERS = {"package-lock.json": package_lock_packages, "npm-shrinkwrap.json": package_lock_packages,
|
|
232
|
+
"yarn.lock": yarn_lock_packages, "pnpm-lock.yaml": pnpm_lock_packages}
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def osv_post(url, body):
|
|
236
|
+
request = urllib.request.Request(url, data=json.dumps(body).encode(), headers={"Content-Type": "application/json"})
|
|
237
|
+
with urllib.request.urlopen(request, timeout=30) as resp:
|
|
238
|
+
return json.load(resp)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def osv_get(vuln_id):
|
|
242
|
+
with urllib.request.urlopen(OSV_URL.format(vuln_id), timeout=10) as resp:
|
|
243
|
+
return json.load(resp)
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def osv_advisories(packages):
|
|
247
|
+
"""{(name, version): [vulnerability id]} for npm packages, in batches."""
|
|
248
|
+
packages = sorted(packages)
|
|
249
|
+
hits = {}
|
|
250
|
+
for start in range(0, len(packages), OSV_BATCH_SIZE):
|
|
251
|
+
chunk = packages[start:start + OSV_BATCH_SIZE]
|
|
252
|
+
body = {"queries": [{"package": {"name": n, "ecosystem": "npm"}, "version": v} for n, v in chunk]}
|
|
253
|
+
for pkg, result in zip(chunk, osv_post(OSV_BATCH_URL, body).get("results", []), strict=False):
|
|
254
|
+
ids = [v["id"] for v in result.get("vulns") or []]
|
|
255
|
+
if ids:
|
|
256
|
+
hits[pkg] = ids
|
|
257
|
+
return hits
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def fixed_versions(vuln, name):
|
|
261
|
+
return sorted({event["fixed"] for affected in vuln.get("affected", [])
|
|
262
|
+
if affected.get("package", {}).get("name") == name
|
|
263
|
+
for rng in affected.get("ranges", []) for event in rng.get("events", []) if "fixed" in event})
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def lockfile_line(text, name):
|
|
267
|
+
"""Line where the lockfile lists the package, or None."""
|
|
268
|
+
needles = (f'"node_modules/{name}"', f'"{name}@', f"{name}@", f"/{name}@", f"/{name}/", f'"{name}": {{')
|
|
269
|
+
for i, line in enumerate(text.splitlines(), 1):
|
|
270
|
+
if any(n in line for n in needles):
|
|
271
|
+
return i
|
|
272
|
+
return None
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def dependency_metrics(locked, advisories, findings):
|
|
276
|
+
return {"vulnerable_dependencies": len({pkg for _, packages in locked.values() for pkg in packages
|
|
277
|
+
if pkg in advisories}),
|
|
278
|
+
"dependency_vulnerabilities": len(findings),
|
|
279
|
+
"dependency_critical_vulnerabilities": sum(f.severity in ("blocker", "critical") for f in findings)}
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
class OsvLockfiles(Analyzer):
|
|
283
|
+
"""Known advisories in the exact package versions an npm, yarn or pnpm lockfile pins, looked up in OSV."""
|
|
284
|
+
|
|
285
|
+
name = "osv"
|
|
286
|
+
|
|
287
|
+
def applies(self, ctx):
|
|
288
|
+
return any(Path(f).name in LOCKFILES for f in ctx.files)
|
|
289
|
+
|
|
290
|
+
def available(self):
|
|
291
|
+
return True
|
|
292
|
+
|
|
293
|
+
@staticmethod
|
|
294
|
+
def locked(ctx):
|
|
295
|
+
"""{lockfile: (its text, {(name, version): development only})} for the lockfiles that parse."""
|
|
296
|
+
locked = {}
|
|
297
|
+
for f in ctx.files:
|
|
298
|
+
parse = LOCKFILE_PARSERS.get(Path(f).name)
|
|
299
|
+
if not parse:
|
|
300
|
+
continue
|
|
301
|
+
try:
|
|
302
|
+
text = (ctx.root / f).read_text(errors="replace")
|
|
303
|
+
locked[f] = (text, parse(text))
|
|
304
|
+
except (OSError, ValueError, yaml.YAMLError):
|
|
305
|
+
continue
|
|
306
|
+
return locked
|
|
307
|
+
|
|
308
|
+
def all_details(self, advisories):
|
|
309
|
+
ids = sorted({i for found in advisories.values() for i in found})
|
|
310
|
+
with ThreadPoolExecutor(max_workers=8) as pool:
|
|
311
|
+
return dict(zip(ids, pool.map(self.details, ids), strict=True))
|
|
312
|
+
|
|
313
|
+
def run(self, ctx):
|
|
314
|
+
locked = self.locked(ctx)
|
|
315
|
+
try:
|
|
316
|
+
advisories = osv_advisories({pkg for _, packages in locked.values() for pkg in packages})
|
|
317
|
+
except (OSError, ValueError) as exc:
|
|
318
|
+
raise ToolError(f"OSV query failed: {exc}") from exc
|
|
319
|
+
details = self.all_details(advisories)
|
|
320
|
+
result = Result()
|
|
321
|
+
for path, (text, packages) in sorted(locked.items()):
|
|
322
|
+
result.findings += [self.finding(path, text, (name, version, dev), details.get(vid) or {"id": vid})
|
|
323
|
+
for (name, version), dev in sorted(packages.items())
|
|
324
|
+
for vid in advisories.get((name, version), [])]
|
|
325
|
+
result.metrics |= dependency_metrics(locked, advisories, result.findings)
|
|
326
|
+
return result
|
|
327
|
+
|
|
328
|
+
@staticmethod
|
|
329
|
+
def details(vuln_id):
|
|
330
|
+
try:
|
|
331
|
+
return osv_get(vuln_id)
|
|
332
|
+
except (OSError, ValueError):
|
|
333
|
+
return None
|
|
334
|
+
|
|
335
|
+
@staticmethod
|
|
336
|
+
def finding(path, text, package, vuln):
|
|
337
|
+
"""A development-only package (build tools, test runners) isn't shipped, so its advisory is for review."""
|
|
338
|
+
name, version, dev = package
|
|
339
|
+
ids = [vuln["id"], *vuln.get("aliases", [])]
|
|
340
|
+
cve = next((a for a in ids if a.startswith("CVE-")), vuln["id"])
|
|
341
|
+
rating = vuln.get("database_specific", {}).get("severity")
|
|
342
|
+
fix = ", ".join(fixed_versions(vuln, name)) or "none available"
|
|
343
|
+
summary = vuln.get("summary") or advisory_summary(vuln)
|
|
344
|
+
where = " (development only)" if dev else ""
|
|
345
|
+
return Finding("osv", cve, OSV_SEVERITY.get(rating, MAJOR), "security_hotspot" if dev else "vulnerability",
|
|
346
|
+
f"{name} {version}{where}: {cve} \u2014 fixed in {fix}. {summary}"[:600], path,
|
|
347
|
+
lockfile_line(text, name))
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Django REST framework field checks as sanitizers: `validated_data["field"]` in a serializer that defines
|
|
2
|
+
`validate_field`.
|
|
3
|
+
|
|
4
|
+
DRF calls a serializer's `validate_<field>(self, value)` on that field before create() or update() sees it, and
|
|
5
|
+
whatever the method returns (or raises) is what lands in `validated_data`. The rules can't tie a key to a method's
|
|
6
|
+
name, so this reads the project's serializers with ast and adds, per serializer, a sanitizer for its checked
|
|
7
|
+
fields read from any mapping inside the class. firefighter GHSA-fqvv's fix: validate_attachments() rejects
|
|
8
|
+
private and non-http URLs, and create() then fetches validated_data["attachments"].
|
|
9
|
+
"""
|
|
10
|
+
import ast
|
|
11
|
+
import re
|
|
12
|
+
|
|
13
|
+
from .base import python_tree
|
|
14
|
+
|
|
15
|
+
SERIALIZER_BASE_RE = re.compile(r"Serializer$")
|
|
16
|
+
CHECK_PREFIX = "validate_"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def base_name(node):
|
|
20
|
+
"""The last name of a base class expression: `serializers.ModelSerializer[JiraTicket]` -> ModelSerializer."""
|
|
21
|
+
if isinstance(node, ast.Subscript):
|
|
22
|
+
node = node.value
|
|
23
|
+
if isinstance(node, ast.Attribute):
|
|
24
|
+
return node.attr
|
|
25
|
+
return getattr(node, "id", "")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def checked_fields(texts):
|
|
29
|
+
"""{serializer class name: fields it checks with validate_<field>}, from the project's Python sources."""
|
|
30
|
+
checked = {}
|
|
31
|
+
trees = (python_tree(text) for text in texts if CHECK_PREFIX in text and "Serializer" in text)
|
|
32
|
+
for tree in filter(None, trees):
|
|
33
|
+
for node in ast.walk(tree):
|
|
34
|
+
if fields := serializer_checks(node):
|
|
35
|
+
checked.setdefault(node.name, set()).update(fields)
|
|
36
|
+
return checked
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def serializer_checks(node):
|
|
40
|
+
"""The fields a serializer class checks with validate_<field> methods; empty for any other node."""
|
|
41
|
+
if not isinstance(node, ast.ClassDef) or not any(SERIALIZER_BASE_RE.search(base_name(b)) for b in node.bases):
|
|
42
|
+
return set()
|
|
43
|
+
return {item.name.removeprefix(CHECK_PREFIX) for item in node.body
|
|
44
|
+
if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef))
|
|
45
|
+
and item.name.startswith(CHECK_PREFIX) and len(item.name) > len(CHECK_PREFIX)}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def field_sanitizer(cls, fields):
|
|
49
|
+
keys = "|".join(sorted(map(re.escape, fields)))
|
|
50
|
+
return {"patterns": [
|
|
51
|
+
{"pattern-inside": f"class {cls}(...):\n ...\n"},
|
|
52
|
+
{"pattern-either": [{"pattern": "$DATA[$KEY]"}, {"pattern": "$DATA.get($KEY, ...)"}]},
|
|
53
|
+
{"metavariable-regex": {"metavariable": "$KEY", "regex": f"^[rbu]*['\"]({keys})['\"]$"}},
|
|
54
|
+
]}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def with_serializer_checks(rules, texts):
|
|
58
|
+
"""The rules, with a sanitizer per serializer's checked fields on every Python taint rule."""
|
|
59
|
+
checked = checked_fields(texts)
|
|
60
|
+
if not checked:
|
|
61
|
+
return rules
|
|
62
|
+
extra = [field_sanitizer(cls, fields) for cls, fields in sorted(checked.items())]
|
|
63
|
+
return [{**rule, "pattern-sanitizers": [*rule.get("pattern-sanitizers", []), *extra]}
|
|
64
|
+
if rule.get("mode") == "taint" and "python" in rule.get("languages", []) else rule
|
|
65
|
+
for rule in rules]
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Split `if ... else` so a check's sanitizers don't reach the branch where it failed.
|
|
2
|
+
|
|
3
|
+
The rules clear a value inside a check that passed: `if ext in ALLOWED: ...` or `if is_safe(url): ...`, written
|
|
4
|
+
as `pattern-inside: if <... $X in $ALLOWED ...>: ...`. Semgrep's range for that pattern is the whole `if`
|
|
5
|
+
statement, else branch included, so `else: return mark_safe(f"...{ext}...")` (the value that failed the check)
|
|
6
|
+
was cleared too. In the copy Semgrep scans (never run; every line and column kept), `else:` becomes `if E:` and
|
|
7
|
+
`elif c:` becomes `if c:`, so each branch is a statement of its own and only the checked one is inside the
|
|
8
|
+
check. Taint still flows into both branches, as it would at run time.
|
|
9
|
+
|
|
10
|
+
Rules are written against the source as people write it: `rules_for_copies` rewrites the `else:` lines of Python
|
|
11
|
+
rules' patterns the same way before they run, so no rule has to know about the copy.
|
|
12
|
+
"""
|
|
13
|
+
import ast
|
|
14
|
+
import re
|
|
15
|
+
|
|
16
|
+
ELSE_RE = re.compile(r"^(\s*)else(\s*):")
|
|
17
|
+
ELIF_RE = re.compile(r"^(\s*)elif\b")
|
|
18
|
+
IF_RE = re.compile(r"^(\s*)(?:if|elif)\b")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def else_rows(tree, lines):
|
|
22
|
+
"""(row, kind) of each `else:` / `elif` line that belongs to an if statement."""
|
|
23
|
+
return [found for node in ast.walk(tree) if isinstance(node, ast.If) and node.orelse
|
|
24
|
+
and (found := else_row(node, lines))]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def is_elif(node, lines):
|
|
28
|
+
first = node.orelse[0]
|
|
29
|
+
return (isinstance(first, ast.If) and len(node.orelse) == 1
|
|
30
|
+
and (elif_line := ELIF_RE.match(lines[first.lineno - 1])) is not None
|
|
31
|
+
and len(elif_line.group(1)) == node.col_offset)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def else_row(node, lines):
|
|
35
|
+
"""(row, kind) of an if statement's `elif` or `else:` line, or None. The `else:` line is the last one before
|
|
36
|
+
the else body at the if's own indentation."""
|
|
37
|
+
first = node.orelse[0]
|
|
38
|
+
if is_elif(node, lines):
|
|
39
|
+
return first.lineno, "elif"
|
|
40
|
+
for row in range(first.lineno, node.lineno, -1):
|
|
41
|
+
m = ELSE_RE.match(lines[row - 1])
|
|
42
|
+
if m and len(m.group(1)) == node.col_offset:
|
|
43
|
+
return row, "else"
|
|
44
|
+
return None
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def split_else(source):
|
|
48
|
+
"""The source with if statements' else/elif branches made separate ifs, or None if none (or it doesn't
|
|
49
|
+
parse)."""
|
|
50
|
+
if "else" not in source and "elif" not in source:
|
|
51
|
+
return None
|
|
52
|
+
try:
|
|
53
|
+
tree = ast.parse(source)
|
|
54
|
+
except (SyntaxError, ValueError):
|
|
55
|
+
return None
|
|
56
|
+
lines = source.splitlines(keepends=True)
|
|
57
|
+
rows = else_rows(tree, lines)
|
|
58
|
+
if not rows:
|
|
59
|
+
return None
|
|
60
|
+
for row, kind in rows:
|
|
61
|
+
line = lines[row - 1]
|
|
62
|
+
if kind == "elif":
|
|
63
|
+
lines[row - 1] = ELIF_RE.sub(lambda m: m.group(1) + "if ", line, count=1)
|
|
64
|
+
else:
|
|
65
|
+
lines[row - 1] = ELSE_RE.sub(lambda m: m.group(1) + "if E" + m.group(2) + ":", line, count=1)
|
|
66
|
+
result = "".join(lines)
|
|
67
|
+
try:
|
|
68
|
+
ast.parse(result)
|
|
69
|
+
except (SyntaxError, ValueError):
|
|
70
|
+
return None
|
|
71
|
+
return None if result == source else result
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def pattern_for_copies(pattern):
|
|
75
|
+
"""A Semgrep pattern with each `else:` of an if statement written `if E:`, as split_else writes the copies.
|
|
76
|
+
An `else:` counts when the nearest line above it at its indentation starts with `if` or `elif` (not `for`,
|
|
77
|
+
`while` or `try`, whose else the copies keep)."""
|
|
78
|
+
lines = pattern.splitlines(keepends=True)
|
|
79
|
+
for row, line in enumerate(lines):
|
|
80
|
+
m = ELSE_RE.match(line)
|
|
81
|
+
if m and opened_by_if(lines[:row], len(m.group(1))):
|
|
82
|
+
lines[row] = ELSE_RE.sub(lambda m: m.group(1) + "if E" + m.group(2) + ":", line, count=1)
|
|
83
|
+
return "".join(lines)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def opened_by_if(above, indent):
|
|
87
|
+
for line in reversed(above):
|
|
88
|
+
if not line.strip() or len(line) - len(line.lstrip()) > indent:
|
|
89
|
+
continue
|
|
90
|
+
return len(line) - len(line.lstrip()) == indent and IF_RE.match(line) is not None
|
|
91
|
+
return False
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def rules_for_copies(rules):
|
|
95
|
+
"""Python rules with their patterns' if-statement `else:` lines written as the copies have them."""
|
|
96
|
+
return [rewritten_patterns(rule) if "python" in rule.get("languages", ()) else rule for rule in rules]
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def rewritten_patterns(node, key=""):
|
|
100
|
+
if isinstance(node, dict):
|
|
101
|
+
return {k: rewritten_patterns(v, k) for k, v in node.items()}
|
|
102
|
+
if isinstance(node, list):
|
|
103
|
+
return [rewritten_patterns(v, key) for v in node]
|
|
104
|
+
if isinstance(node, str) and key.startswith("pattern") and "else" in node:
|
|
105
|
+
return pattern_for_copies(node)
|
|
106
|
+
return node
|