auditwright 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.
- auditwright/__init__.py +7 -0
- auditwright/__main__.py +5 -0
- auditwright/_util.py +55 -0
- auditwright/_version.py +1 -0
- auditwright/attack.py +224 -0
- auditwright/cli.py +521 -0
- auditwright/config.py +104 -0
- auditwright/cvss.py +49 -0
- auditwright/deps.py +532 -0
- auditwright/engine.py +108 -0
- auditwright/inventory.py +92 -0
- auditwright/model.py +181 -0
- auditwright/net.py +91 -0
- auditwright/netscan.py +532 -0
- auditwright/pentest.py +405 -0
- auditwright/py.typed +0 -0
- auditwright/report/__init__.py +1 -0
- auditwright/report/formats.py +220 -0
- auditwright/report/html.py +541 -0
- auditwright/rules/__init__.py +1 -0
- auditwright/rules/base.py +136 -0
- auditwright/rules/crypto.py +101 -0
- auditwright/rules/iac.py +572 -0
- auditwright/rules/patterns.py +266 -0
- auditwright/rules/python_ast.py +843 -0
- auditwright/rules/unicode.py +129 -0
- auditwright/secrets.py +216 -0
- auditwright/testgen.py +483 -0
- auditwright/testrun.py +257 -0
- auditwright/walk.py +255 -0
- auditwright-0.1.0.dist-info/METADATA +280 -0
- auditwright-0.1.0.dist-info/RECORD +36 -0
- auditwright-0.1.0.dist-info/WHEEL +4 -0
- auditwright-0.1.0.dist-info/entry_points.txt +2 -0
- auditwright-0.1.0.dist-info/licenses/LICENSE +202 -0
- auditwright-0.1.0.dist-info/licenses/NOTICE +5 -0
auditwright/deps.py
ADDED
|
@@ -0,0 +1,532 @@
|
|
|
1
|
+
"""Dependency inventory, vulnerability lookup (OSV) and lockfile hygiene.
|
|
2
|
+
|
|
3
|
+
Lockfile parsers are self-contained: requirements*.txt, poetry.lock, uv.lock,
|
|
4
|
+
pdm.lock, Pipfile.lock, package-lock.json / npm-shrinkwrap.json (v1-v3),
|
|
5
|
+
yarn.lock (classic and berry), pnpm-lock.yaml, Cargo.lock, go.sum,
|
|
6
|
+
Gemfile.lock, composer.lock, packages.lock.json (NuGet) and gradle.lockfile.
|
|
7
|
+
|
|
8
|
+
Vulnerabilities come from the OSV database (https://osv.dev), queried in
|
|
9
|
+
batches; details are cached on disk for three days. Severity is computed from
|
|
10
|
+
the advisory's CVSS v3 vector when present, otherwise from the database's own
|
|
11
|
+
rating. Advisories in OSV's malicious-package feed (MAL-*) are always critical.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import re
|
|
19
|
+
import time
|
|
20
|
+
import tomllib
|
|
21
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
22
|
+
from dataclasses import asdict, dataclass, field
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import Any
|
|
25
|
+
|
|
26
|
+
from . import cvss
|
|
27
|
+
from .model import Finding, RuleMeta
|
|
28
|
+
from .net import Http
|
|
29
|
+
from .rules.base import register
|
|
30
|
+
from .walk import Project, SourceFile
|
|
31
|
+
|
|
32
|
+
A06 = "A06:2021 Vulnerable and Outdated Components"
|
|
33
|
+
A08 = "A08:2021 Software and Data Integrity Failures"
|
|
34
|
+
|
|
35
|
+
R_VULN = register(RuleMeta("AW-DEP-001", "Dependency with a known vulnerability", "deps", "high", "CWE-1395", A06,
|
|
36
|
+
"Upgrade to a fixed version (shown in the finding), or remove the dependency.")) # fmt: skip
|
|
37
|
+
R_MAL = register(RuleMeta("AW-DEP-002", "Known malicious package", "deps", "critical", "CWE-506", A08,
|
|
38
|
+
"Remove the package immediately, rotate every credential the machine could reach, and rebuild from clean images.")) # fmt: skip
|
|
39
|
+
R_NOLOCK = register(RuleMeta("AW-DEP-101", "Dependencies without a lockfile", "supply-chain", "low", "CWE-1357", A08,
|
|
40
|
+
"Commit a lockfile so every install resolves to the same, reviewed versions.")) # fmt: skip
|
|
41
|
+
R_HTTP = register(RuleMeta("AW-DEP-102", "Dependency downloaded over plain HTTP", "supply-chain", "high", "CWE-494", A08,
|
|
42
|
+
"Use HTTPS registry URLs; regenerate the lockfile.")) # fmt: skip
|
|
43
|
+
R_GIT = register(RuleMeta("AW-DEP-103", "Dependency from a mutable URL", "supply-chain", "medium", "CWE-829", A08,
|
|
44
|
+
"Pin git dependencies to a full commit SHA, or publish and depend on a released version.")) # fmt: skip
|
|
45
|
+
R_INTEGRITY = register(RuleMeta("AW-DEP-104", "Lockfile entry without an integrity hash", "supply-chain", "medium", "CWE-353", A08,
|
|
46
|
+
"Regenerate the lockfile with a current package manager so every entry has an integrity hash.")) # fmt: skip
|
|
47
|
+
R_UNPINNED = register(RuleMeta("AW-DEP-105", "Unpinned dependency", "supply-chain", "low", "CWE-1357", A08,
|
|
48
|
+
"Pin with == (or use a lockfile/constraints file) so builds are reproducible.")) # fmt: skip
|
|
49
|
+
|
|
50
|
+
OSV_BATCH = "https://api.osv.dev/v1/querybatch"
|
|
51
|
+
OSV_VULN = "https://api.osv.dev/v1/vulns/"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass
|
|
55
|
+
class Dep:
|
|
56
|
+
ecosystem: str # OSV ecosystem name
|
|
57
|
+
name: str
|
|
58
|
+
version: str
|
|
59
|
+
file: str
|
|
60
|
+
line: int = 0
|
|
61
|
+
direct: bool | None = None
|
|
62
|
+
vulns: list[dict[str, Any]] = field(default_factory=list)
|
|
63
|
+
|
|
64
|
+
def key(self) -> tuple[str, str, str]:
|
|
65
|
+
return (self.ecosystem, self.name.lower() if self.ecosystem == "PyPI" else self.name, self.version)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
# -- parsers ------------------------------------------------------------------------------
|
|
69
|
+
|
|
70
|
+
_REQ = re.compile(r"^\s*([A-Za-z0-9][A-Za-z0-9._\-]*)(?:\[[^\]]*\])?\s*===?\s*([A-Za-z0-9._+!\-]+)")
|
|
71
|
+
_REQ_NAME = re.compile(r"^\s*([A-Za-z0-9][A-Za-z0-9._\-]*)(?:\[[^\]]*\])?\s*(?:[<>~!]=?|;|$)")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _norm_py(name: str) -> str:
|
|
75
|
+
return re.sub(r"[-_.]+", "-", name).lower()
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def parse_requirements(f: SourceFile) -> tuple[list[Dep], list[Finding]]:
|
|
79
|
+
deps, findings = [], []
|
|
80
|
+
for i, line in enumerate(f.lines(), 1):
|
|
81
|
+
s = line.split(" #", 1)[0].strip()
|
|
82
|
+
if not s or s.startswith(("#", "-r", "-c", "--", "-e", "-i")):
|
|
83
|
+
continue
|
|
84
|
+
if re.match(r"(?i)^(git\+|hg\+|svn\+|https?://)", s) or "@ git+" in s or "@ http" in s:
|
|
85
|
+
if not re.search(r"@[0-9a-f]{40}\b", s):
|
|
86
|
+
findings.append(
|
|
87
|
+
Finding.from_rule(
|
|
88
|
+
R_GIT, f"'{s[:120]}' is not pinned to a commit.", file=f.rel, line=i, snippet=s[:200]
|
|
89
|
+
)
|
|
90
|
+
)
|
|
91
|
+
if "http://" in s:
|
|
92
|
+
findings.append(
|
|
93
|
+
Finding.from_rule(R_HTTP, "Downloaded over plain HTTP.", file=f.rel, line=i, snippet=s[:200])
|
|
94
|
+
)
|
|
95
|
+
continue
|
|
96
|
+
m = _REQ.match(s)
|
|
97
|
+
if m:
|
|
98
|
+
deps.append(Dep("PyPI", _norm_py(m.group(1)), m.group(2), f.rel, i))
|
|
99
|
+
elif _REQ_NAME.match(s) and "requirements" in f.path.name:
|
|
100
|
+
findings.append(
|
|
101
|
+
Finding.from_rule(
|
|
102
|
+
R_UNPINNED,
|
|
103
|
+
f"'{s[:80]}' has no exact version.",
|
|
104
|
+
file=f.rel,
|
|
105
|
+
line=i,
|
|
106
|
+
snippet=s[:200],
|
|
107
|
+
confidence="medium",
|
|
108
|
+
) # fmt: skip
|
|
109
|
+
)
|
|
110
|
+
return deps, findings
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _toml_packages(f: SourceFile, eco: str) -> list[Dep]:
|
|
114
|
+
try:
|
|
115
|
+
data = tomllib.loads(f.text())
|
|
116
|
+
except (tomllib.TOMLDecodeError, ValueError):
|
|
117
|
+
return []
|
|
118
|
+
out = []
|
|
119
|
+
for p in data.get("package", []) or []:
|
|
120
|
+
if isinstance(p, dict) and p.get("name") and p.get("version"):
|
|
121
|
+
src = p.get("source")
|
|
122
|
+
if eco == "crates.io" and isinstance(src, str) and not src.startswith("registry+"):
|
|
123
|
+
continue # path or git crates are not on crates.io
|
|
124
|
+
name = _norm_py(p["name"]) if eco == "PyPI" else p["name"]
|
|
125
|
+
out.append(Dep(eco, name, str(p["version"]), f.rel))
|
|
126
|
+
return out
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def parse_pipfile_lock(f: SourceFile) -> list[Dep]:
|
|
130
|
+
try:
|
|
131
|
+
data = json.loads(f.text())
|
|
132
|
+
except ValueError:
|
|
133
|
+
return []
|
|
134
|
+
out = []
|
|
135
|
+
for section in ("default", "develop"):
|
|
136
|
+
for name, info in (data.get(section) or {}).items():
|
|
137
|
+
v = (info or {}).get("version", "") if isinstance(info, dict) else ""
|
|
138
|
+
if v.startswith("=="):
|
|
139
|
+
out.append(Dep("PyPI", _norm_py(name), v[2:], f.rel, direct=None))
|
|
140
|
+
return out
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def parse_package_lock(f: SourceFile) -> tuple[list[Dep], list[Finding]]:
|
|
144
|
+
try:
|
|
145
|
+
data = json.loads(f.text())
|
|
146
|
+
except ValueError:
|
|
147
|
+
return [], []
|
|
148
|
+
deps, findings = [], []
|
|
149
|
+
missing_integrity = 0
|
|
150
|
+
packages = data.get("packages")
|
|
151
|
+
if isinstance(packages, dict):
|
|
152
|
+
for path, info in packages.items():
|
|
153
|
+
if not path or not isinstance(info, dict) or info.get("link"):
|
|
154
|
+
continue
|
|
155
|
+
name = info.get("name") or path.rsplit("node_modules/", 1)[-1]
|
|
156
|
+
version = info.get("version")
|
|
157
|
+
resolved = str(info.get("resolved") or "")
|
|
158
|
+
if version:
|
|
159
|
+
deps.append(Dep("npm", name, str(version), f.rel, direct=path.count("node_modules/") == 1))
|
|
160
|
+
if resolved.startswith("http://"):
|
|
161
|
+
findings.append(
|
|
162
|
+
Finding.from_rule(
|
|
163
|
+
R_HTTP, f"{name} resolves to {resolved[:120]}.", file=f.rel, snippet=resolved[:200]
|
|
164
|
+
)
|
|
165
|
+
)
|
|
166
|
+
elif resolved.startswith(("git+", "git:", "github:")) or "codeload.github.com" in resolved:
|
|
167
|
+
findings.append(
|
|
168
|
+
Finding.from_rule(
|
|
169
|
+
R_GIT, f"{name} is installed from {resolved[:120]}.", file=f.rel, snippet=resolved[:200]
|
|
170
|
+
)
|
|
171
|
+
)
|
|
172
|
+
if version and resolved.startswith("https://") and not info.get("integrity"):
|
|
173
|
+
missing_integrity += 1
|
|
174
|
+
else:
|
|
175
|
+
|
|
176
|
+
def walk(tree: dict, depth: int) -> None:
|
|
177
|
+
for name, info in (tree or {}).items():
|
|
178
|
+
if isinstance(info, dict) and info.get("version"):
|
|
179
|
+
deps.append(Dep("npm", name, str(info["version"]), f.rel, direct=depth == 0))
|
|
180
|
+
walk(info.get("dependencies") or {}, depth + 1)
|
|
181
|
+
|
|
182
|
+
walk(data.get("dependencies") or {}, 0)
|
|
183
|
+
if missing_integrity:
|
|
184
|
+
findings.append(
|
|
185
|
+
Finding.from_rule(
|
|
186
|
+
R_INTEGRITY,
|
|
187
|
+
f"{missing_integrity} entries have no integrity hash.",
|
|
188
|
+
file=f.rel,
|
|
189
|
+
snippet=f"{missing_integrity} entries without integrity",
|
|
190
|
+
) # fmt: skip
|
|
191
|
+
)
|
|
192
|
+
return deps, findings
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
_YARN_HEAD = re.compile(r'^"?((?:@[^@/"\s]+/)?[^@/"\s]+)@')
|
|
196
|
+
_YARN_VER = re.compile(r'^\s+version:?\s+"?([^"\s]+)"?')
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def parse_yarn_lock(f: SourceFile) -> tuple[list[Dep], list[Finding]]:
|
|
200
|
+
deps, findings = [], []
|
|
201
|
+
current = None
|
|
202
|
+
for i, line in enumerate(f.lines(), 1):
|
|
203
|
+
if line and not line.startswith((" ", "#")) and line.rstrip().endswith(":"):
|
|
204
|
+
m = _YARN_HEAD.match(line)
|
|
205
|
+
current = m.group(1) if m and not line.startswith("__metadata") else None
|
|
206
|
+
continue
|
|
207
|
+
if current:
|
|
208
|
+
m = _YARN_VER.match(line)
|
|
209
|
+
if m:
|
|
210
|
+
deps.append(Dep("npm", current, m.group(1), f.rel, i))
|
|
211
|
+
current = None
|
|
212
|
+
if line.strip().startswith(("resolved", "resolution")) and "http://" in line:
|
|
213
|
+
findings.append(
|
|
214
|
+
Finding.from_rule(
|
|
215
|
+
R_HTTP, "A package resolves over plain HTTP.", file=f.rel, line=i, snippet=line.strip()[:200]
|
|
216
|
+
)
|
|
217
|
+
)
|
|
218
|
+
return deps, findings
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
_PNPM_KEY = re.compile(r"^ '?/?((?:@[^@/\s]+/)?[^@/\s(]+)[@/]([0-9][^\s:(']*)")
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def parse_pnpm_lock(f: SourceFile) -> list[Dep]:
|
|
225
|
+
deps, in_packages = [], False
|
|
226
|
+
seen = set()
|
|
227
|
+
for i, line in enumerate(f.lines(), 1):
|
|
228
|
+
if not line.startswith(" "):
|
|
229
|
+
in_packages = line.startswith(("packages:", "snapshots:"))
|
|
230
|
+
continue
|
|
231
|
+
if in_packages:
|
|
232
|
+
m = _PNPM_KEY.match(line)
|
|
233
|
+
if m and (m.group(1), m.group(2)) not in seen:
|
|
234
|
+
seen.add((m.group(1), m.group(2)))
|
|
235
|
+
deps.append(Dep("npm", m.group(1), m.group(2), f.rel, i))
|
|
236
|
+
return deps
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def parse_go_sum(f: SourceFile) -> list[Dep]:
|
|
240
|
+
out, seen = [], set()
|
|
241
|
+
for i, line in enumerate(f.lines(), 1):
|
|
242
|
+
parts = line.split()
|
|
243
|
+
if len(parts) < 3:
|
|
244
|
+
continue
|
|
245
|
+
mod, ver = parts[0], parts[1].removesuffix("/go.mod").removesuffix("+incompatible")
|
|
246
|
+
if (mod, ver) not in seen:
|
|
247
|
+
seen.add((mod, ver))
|
|
248
|
+
out.append(Dep("Go", mod, ver, f.rel, i))
|
|
249
|
+
return out
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def parse_gemfile_lock(f: SourceFile) -> list[Dep]:
|
|
253
|
+
out, in_specs = [], False
|
|
254
|
+
for i, line in enumerate(f.lines(), 1):
|
|
255
|
+
if line.strip() == "specs:":
|
|
256
|
+
in_specs = True
|
|
257
|
+
continue
|
|
258
|
+
if line and not line.startswith(" "):
|
|
259
|
+
in_specs = False
|
|
260
|
+
if in_specs:
|
|
261
|
+
m = re.match(r"^ {4}([A-Za-z0-9_.\-]+) \(([^)\s]+)\)", line)
|
|
262
|
+
if m:
|
|
263
|
+
out.append(Dep("RubyGems", m.group(1), m.group(2).split("-")[0], f.rel, i))
|
|
264
|
+
return out
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def parse_composer_lock(f: SourceFile) -> list[Dep]:
|
|
268
|
+
try:
|
|
269
|
+
data = json.loads(f.text())
|
|
270
|
+
except ValueError:
|
|
271
|
+
return []
|
|
272
|
+
out = []
|
|
273
|
+
for section in ("packages", "packages-dev"):
|
|
274
|
+
for p in data.get(section) or []:
|
|
275
|
+
if isinstance(p, dict) and p.get("name") and p.get("version"):
|
|
276
|
+
out.append(Dep("Packagist", p["name"], str(p["version"]).lstrip("v"), f.rel))
|
|
277
|
+
return out
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def parse_nuget_lock(f: SourceFile) -> list[Dep]:
|
|
281
|
+
try:
|
|
282
|
+
data = json.loads(f.text())
|
|
283
|
+
except ValueError:
|
|
284
|
+
return []
|
|
285
|
+
out, seen = [], set()
|
|
286
|
+
for fw in (data.get("dependencies") or {}).values():
|
|
287
|
+
for name, info in (fw or {}).items():
|
|
288
|
+
v = (info or {}).get("resolved") if isinstance(info, dict) else None
|
|
289
|
+
if v and (name, v) not in seen:
|
|
290
|
+
seen.add((name, v))
|
|
291
|
+
out.append(Dep("NuGet", name, v, f.rel, direct=(info or {}).get("type") == "Direct"))
|
|
292
|
+
return out
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def parse_gradle_lock(f: SourceFile) -> list[Dep]:
|
|
296
|
+
out = []
|
|
297
|
+
for i, line in enumerate(f.lines(), 1):
|
|
298
|
+
m = re.match(r"^([\w.\-]+):([\w.\-]+):([\w.\-+]+)=", line)
|
|
299
|
+
if m:
|
|
300
|
+
out.append(Dep("Maven", f"{m.group(1)}:{m.group(2)}", m.group(3), f.rel, i))
|
|
301
|
+
return out
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
LOCKFILES = {
|
|
305
|
+
"poetry.lock": ("PyPI", "toml"), "uv.lock": ("PyPI", "toml"), "pdm.lock": ("PyPI", "toml"),
|
|
306
|
+
"Cargo.lock": ("crates.io", "toml"), "Pipfile.lock": ("PyPI", "pipfile"),
|
|
307
|
+
"package-lock.json": ("npm", "npm"), "npm-shrinkwrap.json": ("npm", "npm"), "yarn.lock": ("npm", "yarn"),
|
|
308
|
+
"pnpm-lock.yaml": ("npm", "pnpm"), "go.sum": ("Go", "gosum"), "Gemfile.lock": ("RubyGems", "gem"),
|
|
309
|
+
"composer.lock": ("Packagist", "composer"), "packages.lock.json": ("NuGet", "nuget"),
|
|
310
|
+
"gradle.lockfile": ("Maven", "gradle"),
|
|
311
|
+
} # fmt: skip
|
|
312
|
+
MANIFEST_LOCKS = {
|
|
313
|
+
"package.json": (
|
|
314
|
+
"package-lock.json",
|
|
315
|
+
"npm-shrinkwrap.json",
|
|
316
|
+
"yarn.lock",
|
|
317
|
+
"pnpm-lock.yaml",
|
|
318
|
+
"bun.lockb",
|
|
319
|
+
"bun.lock",
|
|
320
|
+
),
|
|
321
|
+
"Cargo.toml": ("Cargo.lock",),
|
|
322
|
+
"Gemfile": ("Gemfile.lock",),
|
|
323
|
+
"composer.json": ("composer.lock",),
|
|
324
|
+
"Pipfile": ("Pipfile.lock",),
|
|
325
|
+
"go.mod": ("go.sum",),
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def collect(project: Project) -> tuple[list[Dep], list[Finding]]:
|
|
330
|
+
deps: list[Dep] = []
|
|
331
|
+
findings: list[Finding] = []
|
|
332
|
+
for f in project.files():
|
|
333
|
+
name = f.path.name
|
|
334
|
+
if re.match(r"^(.*requirements.*|constraints.*)\.(txt|in)$", name):
|
|
335
|
+
d, fs = parse_requirements(f)
|
|
336
|
+
deps += d
|
|
337
|
+
findings += fs
|
|
338
|
+
elif name in LOCKFILES:
|
|
339
|
+
eco, kind = LOCKFILES[name]
|
|
340
|
+
if kind == "toml":
|
|
341
|
+
deps += _toml_packages(f, eco)
|
|
342
|
+
elif kind == "pipfile":
|
|
343
|
+
deps += parse_pipfile_lock(f)
|
|
344
|
+
elif kind == "npm":
|
|
345
|
+
d, fs = parse_package_lock(f)
|
|
346
|
+
deps += d
|
|
347
|
+
findings += fs
|
|
348
|
+
elif kind == "yarn":
|
|
349
|
+
d, fs = parse_yarn_lock(f)
|
|
350
|
+
deps += d
|
|
351
|
+
findings += fs
|
|
352
|
+
elif kind == "pnpm":
|
|
353
|
+
deps += parse_pnpm_lock(f)
|
|
354
|
+
elif kind == "gosum":
|
|
355
|
+
deps += parse_go_sum(f)
|
|
356
|
+
elif kind == "gem":
|
|
357
|
+
deps += parse_gemfile_lock(f)
|
|
358
|
+
elif kind == "composer":
|
|
359
|
+
deps += parse_composer_lock(f)
|
|
360
|
+
elif kind == "nuget":
|
|
361
|
+
deps += parse_nuget_lock(f)
|
|
362
|
+
elif kind == "gradle":
|
|
363
|
+
deps += parse_gradle_lock(f)
|
|
364
|
+
names_by_dir: dict[str, set[str]] = {}
|
|
365
|
+
for f in project.files():
|
|
366
|
+
names_by_dir.setdefault(str(Path(f.rel).parent), set()).add(f.path.name)
|
|
367
|
+
for f in project.files():
|
|
368
|
+
locks = MANIFEST_LOCKS.get(f.path.name)
|
|
369
|
+
if locks and not names_by_dir.get(str(Path(f.rel).parent), set()) & set(locks):
|
|
370
|
+
if (
|
|
371
|
+
f.path.name == "package.json"
|
|
372
|
+
and '"dependencies"' not in f.text()
|
|
373
|
+
and '"devDependencies"' not in f.text()
|
|
374
|
+
):
|
|
375
|
+
continue
|
|
376
|
+
findings.append(
|
|
377
|
+
Finding.from_rule(
|
|
378
|
+
R_NOLOCK, f"{f.rel} has no lockfile ({' or '.join(locks[:2])}).", file=f.rel, snippet=f.path.name
|
|
379
|
+
) # fmt: skip
|
|
380
|
+
)
|
|
381
|
+
unique: dict[tuple[str, str, str], Dep] = {}
|
|
382
|
+
for d in deps:
|
|
383
|
+
unique.setdefault(d.key(), d)
|
|
384
|
+
return list(unique.values()), findings
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
# -- OSV ----------------------------------------------------------------------------------------
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def _cache_dir() -> Path:
|
|
391
|
+
base = os.environ.get("AUDITWRIGHT_CACHE") or os.path.join(
|
|
392
|
+
os.environ.get("XDG_CACHE_HOME") or os.path.join(os.path.expanduser("~"), ".cache"), "auditwright"
|
|
393
|
+
)
|
|
394
|
+
return Path(base) / "osv"
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def _vuln_details(http: Http, vid: str, ttl: float = 3 * 86400) -> dict[str, Any] | None:
|
|
398
|
+
if not re.fullmatch(r"[A-Za-z0-9._:\-]{3,80}", vid):
|
|
399
|
+
return None
|
|
400
|
+
path = _cache_dir() / f"{vid}.json"
|
|
401
|
+
try:
|
|
402
|
+
if path.is_file() and time.time() - path.stat().st_mtime < ttl:
|
|
403
|
+
return json.loads(path.read_text("utf-8"))
|
|
404
|
+
except (OSError, ValueError):
|
|
405
|
+
pass
|
|
406
|
+
resp = http.get(OSV_VULN + vid)
|
|
407
|
+
if resp.status != 200:
|
|
408
|
+
return None
|
|
409
|
+
data = resp.json()
|
|
410
|
+
try:
|
|
411
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
412
|
+
path.write_text(json.dumps(data), "utf-8")
|
|
413
|
+
except OSError:
|
|
414
|
+
pass
|
|
415
|
+
return data
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
def _severity(v: dict[str, Any]) -> tuple[str, float | None]:
|
|
419
|
+
if str(v.get("id", "")).startswith("MAL-"):
|
|
420
|
+
return "critical", None
|
|
421
|
+
best = None
|
|
422
|
+
for s in v.get("severity") or []:
|
|
423
|
+
score = cvss.base_score(str(s.get("score", "")))
|
|
424
|
+
if score is not None:
|
|
425
|
+
best = max(best or 0.0, score)
|
|
426
|
+
if best is not None:
|
|
427
|
+
return cvss.severity_for(best), best
|
|
428
|
+
db = str((v.get("database_specific") or {}).get("severity", "")).upper()
|
|
429
|
+
mapped = {"CRITICAL": "critical", "HIGH": "high", "MODERATE": "medium", "MEDIUM": "medium", "LOW": "low"}.get(db)
|
|
430
|
+
return mapped or "medium", None
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
def _fixed_versions(v: dict[str, Any], dep: Dep) -> list[str]:
|
|
434
|
+
out = []
|
|
435
|
+
for a in v.get("affected") or []:
|
|
436
|
+
pkg = a.get("package") or {}
|
|
437
|
+
if pkg.get("ecosystem") != dep.ecosystem:
|
|
438
|
+
continue
|
|
439
|
+
for r in a.get("ranges") or []:
|
|
440
|
+
for e in r.get("events") or []:
|
|
441
|
+
if "fixed" in e:
|
|
442
|
+
out.append(str(e["fixed"]))
|
|
443
|
+
return sorted(set(out))[:5]
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def query_osv(deps: list[Dep], http: Http | None = None) -> tuple[list[Finding], list[str]]:
|
|
447
|
+
http = http or Http(timeout=30)
|
|
448
|
+
errors: list[str] = []
|
|
449
|
+
ids_for: dict[int, list[str]] = {}
|
|
450
|
+
for start in range(0, len(deps), 500):
|
|
451
|
+
chunk = deps[start : start + 500]
|
|
452
|
+
payload = {
|
|
453
|
+
"queries": [{"package": {"name": d.name, "ecosystem": d.ecosystem}, "version": d.version} for d in chunk]
|
|
454
|
+
}
|
|
455
|
+
try:
|
|
456
|
+
resp = http.post_json(OSV_BATCH, payload)
|
|
457
|
+
results = resp.json().get("results", []) if resp.status == 200 else None
|
|
458
|
+
except (OSError, ValueError) as exc:
|
|
459
|
+
errors.append(f"OSV query failed: {type(exc).__name__}")
|
|
460
|
+
break
|
|
461
|
+
if results is None:
|
|
462
|
+
errors.append(f"OSV query failed: HTTP {resp.status}")
|
|
463
|
+
break
|
|
464
|
+
for i, r in enumerate(results):
|
|
465
|
+
vulns = [v.get("id") for v in (r or {}).get("vulns") or [] if v.get("id")]
|
|
466
|
+
if vulns:
|
|
467
|
+
ids_for[start + i] = vulns
|
|
468
|
+
all_ids = sorted({v for ids in ids_for.values() for v in ids})[:1500]
|
|
469
|
+
details: dict[str, dict[str, Any]] = {}
|
|
470
|
+
|
|
471
|
+
def fetch(vid: str):
|
|
472
|
+
try:
|
|
473
|
+
return vid, _vuln_details(http, vid)
|
|
474
|
+
except (OSError, ValueError):
|
|
475
|
+
return vid, None
|
|
476
|
+
|
|
477
|
+
with ThreadPoolExecutor(max_workers=8) as pool:
|
|
478
|
+
for vid, data in pool.map(fetch, all_ids):
|
|
479
|
+
if data:
|
|
480
|
+
details[vid] = data
|
|
481
|
+
findings = []
|
|
482
|
+
for idx, ids in ids_for.items():
|
|
483
|
+
dep = deps[idx]
|
|
484
|
+
# Prefer one finding per advisory family: skip IDs that are aliases of another reported ID.
|
|
485
|
+
reported: set[str] = set()
|
|
486
|
+
for vid in ids:
|
|
487
|
+
v = details.get(vid, {"id": vid})
|
|
488
|
+
aliases = set(v.get("aliases") or [])
|
|
489
|
+
if aliases & reported:
|
|
490
|
+
continue
|
|
491
|
+
reported.add(vid)
|
|
492
|
+
reported |= aliases
|
|
493
|
+
sev, score = _severity(v)
|
|
494
|
+
fixed = _fixed_versions(v, dep)
|
|
495
|
+
summary = str(v.get("summary") or v.get("details") or "").strip().splitlines()[0][:200] if v else ""
|
|
496
|
+
cve = next((a for a in sorted(aliases) if a.startswith("CVE-")), "")
|
|
497
|
+
rule = R_MAL if vid.startswith("MAL-") else R_VULN
|
|
498
|
+
msg = f"{dep.name} {dep.version} ({dep.ecosystem}): {vid}{f' / {cve}' if cve else ''}"
|
|
499
|
+
msg += f" - {summary}" if summary else ""
|
|
500
|
+
msg += f". Fixed in {', '.join(fixed)}." if fixed else ". No fixed version published."
|
|
501
|
+
dep.vulns.append(
|
|
502
|
+
{"id": vid, "cve": cve, "severity": sev, "cvss": score, "fixed": fixed, "summary": summary}
|
|
503
|
+
)
|
|
504
|
+
findings.append(
|
|
505
|
+
Finding.from_rule(
|
|
506
|
+
rule,
|
|
507
|
+
msg,
|
|
508
|
+
file=dep.file,
|
|
509
|
+
line=dep.line,
|
|
510
|
+
severity=sev,
|
|
511
|
+
confidence="high",
|
|
512
|
+
snippet=f"{dep.name}@{dep.version}",
|
|
513
|
+
extra={
|
|
514
|
+
"advisory": vid,
|
|
515
|
+
"cve": cve,
|
|
516
|
+
"cvss": score,
|
|
517
|
+
"fixed": fixed,
|
|
518
|
+
"package": dep.name,
|
|
519
|
+
"version": dep.version,
|
|
520
|
+
"ecosystem": dep.ecosystem,
|
|
521
|
+
"url": f"https://osv.dev/vulnerability/{vid}",
|
|
522
|
+
},
|
|
523
|
+
) # fmt: skip
|
|
524
|
+
)
|
|
525
|
+
return findings, errors
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
def inventory_rows(deps: list[Dep]) -> list[dict[str, Any]]:
|
|
529
|
+
return [
|
|
530
|
+
{k: v for k, v in asdict(d).items() if k != "line"}
|
|
531
|
+
for d in sorted(deps, key=lambda d: (d.ecosystem, d.name.lower(), d.version))
|
|
532
|
+
]
|
auditwright/engine.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""Run the selected analyzers over a project and assemble one report."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from . import deps as deps_mod
|
|
10
|
+
from . import inventory, secrets
|
|
11
|
+
from ._util import utc_now
|
|
12
|
+
from ._version import __version__
|
|
13
|
+
from .attack import finalize
|
|
14
|
+
from .config import Config, load_baseline
|
|
15
|
+
from .model import Finding, Report
|
|
16
|
+
from .rules import crypto, iac, python_ast, unicode
|
|
17
|
+
from .rules.base import run_patterns
|
|
18
|
+
from .rules.iac import PATTERNS as IAC_PATTERNS
|
|
19
|
+
from .rules.patterns import RULES as LANG_PATTERNS
|
|
20
|
+
from .walk import Project
|
|
21
|
+
|
|
22
|
+
ANALYZERS = ("code", "secrets", "deps", "config", "unicode", "crypto")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass
|
|
26
|
+
class Options:
|
|
27
|
+
analyzers: tuple[str, ...] = ANALYZERS
|
|
28
|
+
offline: bool = False
|
|
29
|
+
history: bool = False
|
|
30
|
+
history_commits: int = 2000
|
|
31
|
+
exclude: list[str] = field(default_factory=list)
|
|
32
|
+
include_ignored: bool = False
|
|
33
|
+
baseline: str = ""
|
|
34
|
+
config_path: str | None = None
|
|
35
|
+
name: str = ""
|
|
36
|
+
progress: Callable[[str], None] | None = None
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def scan(root: Path, opts: Options | None = None) -> Report:
|
|
40
|
+
opts = opts or Options()
|
|
41
|
+
cfg = Config.load(root, opts.config_path)
|
|
42
|
+
project = Project(root, exclude=[*cfg.exclude, *opts.exclude], include_ignored=opts.include_ignored)
|
|
43
|
+
# Reports show a project name, never the absolute local path (which can leak user names).
|
|
44
|
+
report = Report(tool_version=__version__, target=opts.name or project.root.name or "project", started=utc_now())
|
|
45
|
+
say = opts.progress or (lambda _m: None)
|
|
46
|
+
files = project.files()
|
|
47
|
+
say(f"{len(files)} files in scope")
|
|
48
|
+
report.inventory = inventory.build(project)
|
|
49
|
+
findings: list[Finding] = []
|
|
50
|
+
|
|
51
|
+
def run(name: str, fn: Callable[[], list[Finding]]) -> None:
|
|
52
|
+
if name.split(":")[0] not in opts.analyzers:
|
|
53
|
+
return
|
|
54
|
+
say(f"running {name}")
|
|
55
|
+
try:
|
|
56
|
+
findings.extend(fn())
|
|
57
|
+
except Exception as exc: # noqa: BLE001 - one analyzer failing must not lose the rest of the report
|
|
58
|
+
report.errors.append(f"{name} analyzer failed: {type(exc).__name__}: {exc}")
|
|
59
|
+
if name.split(":")[0] not in report.analyzers:
|
|
60
|
+
report.analyzers.append(name.split(":")[0])
|
|
61
|
+
|
|
62
|
+
run("code:python", lambda: list(python_ast.analyze(files)))
|
|
63
|
+
run("code:patterns", lambda: list(run_patterns([*LANG_PATTERNS, *IAC_PATTERNS], files)))
|
|
64
|
+
run("config", lambda: list(iac.analyze(files)))
|
|
65
|
+
run("unicode", lambda: list(unicode.analyze(files)))
|
|
66
|
+
run("secrets", lambda: list(secrets.scan_files(files)))
|
|
67
|
+
if "secrets" in opts.analyzers and opts.history:
|
|
68
|
+
say("scanning git history")
|
|
69
|
+
hist, err = secrets.scan_history(project.root, max_commits=opts.history_commits)
|
|
70
|
+
current = {(f.rule_id, f.snippet) for f in findings}
|
|
71
|
+
findings.extend(f for f in hist if (f.rule_id, f.snippet) not in current)
|
|
72
|
+
if err:
|
|
73
|
+
report.errors.append(err)
|
|
74
|
+
if "crypto" in opts.analyzers:
|
|
75
|
+
say("running crypto")
|
|
76
|
+
cf, inv = crypto.analyze(files)
|
|
77
|
+
findings.extend(cf)
|
|
78
|
+
report.crypto_inventory = inv
|
|
79
|
+
report.analyzers.append("crypto")
|
|
80
|
+
if "deps" in opts.analyzers:
|
|
81
|
+
say("collecting dependencies")
|
|
82
|
+
deps, dep_findings = deps_mod.collect(project)
|
|
83
|
+
findings.extend(dep_findings)
|
|
84
|
+
if deps and not opts.offline:
|
|
85
|
+
say(f"checking {len(deps)} packages against OSV")
|
|
86
|
+
vf, errs = deps_mod.query_osv(deps)
|
|
87
|
+
findings.extend(vf)
|
|
88
|
+
report.errors.extend(errs)
|
|
89
|
+
elif deps:
|
|
90
|
+
report.notes.append("Offline mode: dependency vulnerabilities were not checked.")
|
|
91
|
+
report.dependencies = deps_mod.inventory_rows(deps)
|
|
92
|
+
report.analyzers.append("deps")
|
|
93
|
+
|
|
94
|
+
# De-duplicate (the same issue can be reached by two rules on one line).
|
|
95
|
+
unique: dict[tuple[str, str, int, str], Finding] = {}
|
|
96
|
+
for f in findings:
|
|
97
|
+
unique.setdefault((f.rule_id, f.file, f.line, f.message), f)
|
|
98
|
+
kept, report.suppressed = cfg.apply(list(unique.values()))
|
|
99
|
+
baseline_path = opts.baseline or cfg.baseline
|
|
100
|
+
if baseline_path:
|
|
101
|
+
known = load_baseline((root / baseline_path) if not Path(baseline_path).is_absolute() else Path(baseline_path))
|
|
102
|
+
before = len(kept)
|
|
103
|
+
kept = [f for f in kept if f.fingerprint not in known]
|
|
104
|
+
report.baseline_matched = before - len(kept)
|
|
105
|
+
report.findings = kept
|
|
106
|
+
finalize(report)
|
|
107
|
+
report.finished = utc_now()
|
|
108
|
+
return report
|