perquisition 0.7.1__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.
- perquisition/__init__.py +7 -0
- perquisition/cli.py +376 -0
- perquisition/data/grype.yaml +16 -0
- perquisition/db.py +523 -0
- perquisition/envelope.py +133 -0
- perquisition/findings.py +1078 -0
- perquisition/grype.py +208 -0
- perquisition/sbom.py +426 -0
- perquisition/schema/envelope.schema.json +182 -0
- perquisition/semver.py +172 -0
- perquisition/snapshot.py +99 -0
- perquisition/view.py +337 -0
- perquisition-0.7.1.dist-info/METADATA +403 -0
- perquisition-0.7.1.dist-info/RECORD +16 -0
- perquisition-0.7.1.dist-info/WHEEL +4 -0
- perquisition-0.7.1.dist-info/entry_points.txt +2 -0
perquisition/__init__.py
ADDED
perquisition/cli.py
ADDED
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
"""Command line entry point: `perquisition-analysis <command>`.
|
|
2
|
+
|
|
3
|
+
Deliberately small. This is the local side of the fence, where scripts are
|
|
4
|
+
ephemeral — the CLI only does the two things every analysis needs: put an audit
|
|
5
|
+
into SQLite, and show what is in there.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import argparse
|
|
11
|
+
import sqlite3
|
|
12
|
+
import sys
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from . import __version__
|
|
16
|
+
from . import grype as grype_tool
|
|
17
|
+
from .db import (
|
|
18
|
+
DatabaseError,
|
|
19
|
+
connect,
|
|
20
|
+
create_schema,
|
|
21
|
+
load_file,
|
|
22
|
+
record_grype_run,
|
|
23
|
+
)
|
|
24
|
+
from .envelope import EnvelopeError
|
|
25
|
+
from .sbom import (
|
|
26
|
+
DistroError,
|
|
27
|
+
audit_distro,
|
|
28
|
+
build_sbom,
|
|
29
|
+
container_distro,
|
|
30
|
+
containers_of,
|
|
31
|
+
write_json,
|
|
32
|
+
write_sbom,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def main(argv: list[str] | None = None) -> int:
|
|
37
|
+
parser = _build_parser()
|
|
38
|
+
args = parser.parse_args(argv)
|
|
39
|
+
try:
|
|
40
|
+
return args.func(args)
|
|
41
|
+
except (EnvelopeError, DatabaseError, DistroError, grype_tool.GrypeError) as exc:
|
|
42
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
43
|
+
return 1
|
|
44
|
+
except sqlite3.Error as exc:
|
|
45
|
+
print(f"error: sqlite: {exc}", file=sys.stderr)
|
|
46
|
+
return 1
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
50
|
+
parser = argparse.ArgumentParser(
|
|
51
|
+
prog="perquisition-analysis",
|
|
52
|
+
description="Load perquisition audits into SQLite and look at them.",
|
|
53
|
+
)
|
|
54
|
+
parser.add_argument("--version", action="version", version=__version__)
|
|
55
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
56
|
+
|
|
57
|
+
load = sub.add_parser("load", help="load an audit JSON into a SQLite database")
|
|
58
|
+
load.add_argument("audit", help="audit file as emitted on the probe's STDOUT")
|
|
59
|
+
load.add_argument(
|
|
60
|
+
"--db",
|
|
61
|
+
help="destination database (default: the audit file with a .sqlite suffix)",
|
|
62
|
+
)
|
|
63
|
+
load.add_argument(
|
|
64
|
+
"--force",
|
|
65
|
+
action="store_true",
|
|
66
|
+
help="replace the rows of an audit id already present",
|
|
67
|
+
)
|
|
68
|
+
load.set_defaults(func=_cmd_load)
|
|
69
|
+
|
|
70
|
+
summary = sub.add_parser("summary", help="print what the database holds")
|
|
71
|
+
summary.add_argument("--db", required=True, help="database to summarize")
|
|
72
|
+
summary.set_defaults(func=_cmd_summary)
|
|
73
|
+
|
|
74
|
+
scan = sub.add_parser(
|
|
75
|
+
"grype",
|
|
76
|
+
help="build the SBOM of an audit and scan it with grype (needs the grype binary)",
|
|
77
|
+
)
|
|
78
|
+
scan.add_argument("--db", required=True, help="database holding the loaded audit")
|
|
79
|
+
scan.add_argument(
|
|
80
|
+
"--audit",
|
|
81
|
+
help="audit id to scan; required when the database holds several",
|
|
82
|
+
)
|
|
83
|
+
scan.add_argument(
|
|
84
|
+
"--out",
|
|
85
|
+
help="directory for the SBOM and report files (default: <db>-grype/ beside the database)",
|
|
86
|
+
)
|
|
87
|
+
scan.add_argument(
|
|
88
|
+
"--container-distro",
|
|
89
|
+
action="append",
|
|
90
|
+
metavar="ID=id:version",
|
|
91
|
+
default=[],
|
|
92
|
+
help=(
|
|
93
|
+
"assert one container's distro when the audit has none (repeatable;"
|
|
94
|
+
" containers[].distro is null for distroless images and for audits"
|
|
95
|
+
" older than the field)"
|
|
96
|
+
),
|
|
97
|
+
)
|
|
98
|
+
scan.add_argument(
|
|
99
|
+
"--distro",
|
|
100
|
+
help="override the distro context as id:version (default: the audit's own distribution facts)",
|
|
101
|
+
)
|
|
102
|
+
scan.add_argument(
|
|
103
|
+
"--timeout",
|
|
104
|
+
type=float,
|
|
105
|
+
default=grype_tool.DEFAULT_TIMEOUT,
|
|
106
|
+
help=f"seconds before grype is considered hung (default {grype_tool.DEFAULT_TIMEOUT:g})",
|
|
107
|
+
)
|
|
108
|
+
scan.set_defaults(func=_cmd_grype)
|
|
109
|
+
return parser
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _cmd_load(args: argparse.Namespace) -> int:
|
|
113
|
+
audit_path = Path(args.audit)
|
|
114
|
+
db_path = Path(args.db) if args.db else audit_path.with_suffix(".sqlite")
|
|
115
|
+
conn = connect(db_path)
|
|
116
|
+
try:
|
|
117
|
+
audit_id = load_file(conn, audit_path, force=args.force)
|
|
118
|
+
counts = {
|
|
119
|
+
status: n
|
|
120
|
+
for status, n in conn.execute(
|
|
121
|
+
"SELECT status, COUNT(*) FROM collector_result"
|
|
122
|
+
" WHERE audit_id = ? GROUP BY status ORDER BY status",
|
|
123
|
+
(audit_id,),
|
|
124
|
+
)
|
|
125
|
+
}
|
|
126
|
+
total_packages = conn.execute(
|
|
127
|
+
"SELECT COUNT(*) FROM package WHERE audit_id = ?", (audit_id,)
|
|
128
|
+
).fetchone()[0]
|
|
129
|
+
finally:
|
|
130
|
+
conn.close()
|
|
131
|
+
breakdown = ", ".join(f"{status}={n}" for status, n in counts.items())
|
|
132
|
+
print(f"loaded {audit_id} -> {db_path} ({breakdown}; packages={total_packages})")
|
|
133
|
+
return 0
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _cmd_summary(args: argparse.Namespace) -> int:
|
|
137
|
+
conn = connect(args.db)
|
|
138
|
+
try:
|
|
139
|
+
has_schema = conn.execute(
|
|
140
|
+
"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'audit'"
|
|
141
|
+
).fetchone()
|
|
142
|
+
if has_schema is None:
|
|
143
|
+
print("no audit loaded")
|
|
144
|
+
return 0
|
|
145
|
+
has_runs = conn.execute(
|
|
146
|
+
"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'grype_run'"
|
|
147
|
+
).fetchone()
|
|
148
|
+
audits = conn.execute(
|
|
149
|
+
"SELECT audit_id, hostname, mode, schema_version, probe_version,"
|
|
150
|
+
" started_at FROM audit ORDER BY loaded_at, audit_id"
|
|
151
|
+
).fetchall()
|
|
152
|
+
if not audits:
|
|
153
|
+
print("no audit loaded")
|
|
154
|
+
return 0
|
|
155
|
+
for audit in audits:
|
|
156
|
+
print(
|
|
157
|
+
f"audit {audit['audit_id']} host={audit['hostname']!r}"
|
|
158
|
+
f" mode={audit['mode']} envelope={audit['schema_version']}"
|
|
159
|
+
f" probe={audit['probe_version']} started={audit['started_at']}"
|
|
160
|
+
)
|
|
161
|
+
for row in conn.execute(
|
|
162
|
+
"SELECT collector, status, error_code, duration_ms"
|
|
163
|
+
" FROM collector_result WHERE audit_id = ?"
|
|
164
|
+
" ORDER BY collector",
|
|
165
|
+
(audit["audit_id"],),
|
|
166
|
+
):
|
|
167
|
+
reason = f" ({row['error_code']})" if row["error_code"] else ""
|
|
168
|
+
print(
|
|
169
|
+
f" {row['collector']:<16} {row['status']:<8}"
|
|
170
|
+
f" {row['duration_ms']:>6} ms{reason}"
|
|
171
|
+
)
|
|
172
|
+
packages = conn.execute(
|
|
173
|
+
"SELECT COUNT(DISTINCT manager), COUNT(*) FROM package"
|
|
174
|
+
" WHERE audit_id = ?",
|
|
175
|
+
(audit["audit_id"],),
|
|
176
|
+
).fetchone()
|
|
177
|
+
print(f" packages: {packages[1]} records, {packages[0]} managers")
|
|
178
|
+
if has_runs:
|
|
179
|
+
for run in conn.execute(
|
|
180
|
+
"SELECT run, scope, grype_version, matches, db_built, distro"
|
|
181
|
+
" FROM grype_run WHERE audit_id = ? ORDER BY run",
|
|
182
|
+
(audit["audit_id"],),
|
|
183
|
+
):
|
|
184
|
+
print(
|
|
185
|
+
f" grype run {run['run']} scope {run['scope']}:"
|
|
186
|
+
f" {run['matches']} matches"
|
|
187
|
+
f" vs {run['distro']} (grype {run['grype_version']},"
|
|
188
|
+
f" db built {run['db_built']})"
|
|
189
|
+
)
|
|
190
|
+
finally:
|
|
191
|
+
conn.close()
|
|
192
|
+
return 0
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _resolve_audit(conn: sqlite3.Connection, wanted: str | None) -> str:
|
|
196
|
+
if wanted:
|
|
197
|
+
if (
|
|
198
|
+
conn.execute("SELECT 1 FROM audit WHERE audit_id = ?", (wanted,)).fetchone()
|
|
199
|
+
is None
|
|
200
|
+
):
|
|
201
|
+
raise DatabaseError(f"audit {wanted} is not loaded in this database")
|
|
202
|
+
return wanted
|
|
203
|
+
ids = [
|
|
204
|
+
row[0]
|
|
205
|
+
for row in conn.execute(
|
|
206
|
+
"SELECT audit_id FROM audit ORDER BY loaded_at, audit_id"
|
|
207
|
+
)
|
|
208
|
+
]
|
|
209
|
+
if not ids:
|
|
210
|
+
raise DatabaseError("no audit loaded; run `load` first")
|
|
211
|
+
if len(ids) == 1:
|
|
212
|
+
return ids[0]
|
|
213
|
+
raise DatabaseError(
|
|
214
|
+
f"this database holds {len(ids)} audits; choose one with --audit: "
|
|
215
|
+
+ ", ".join(ids)
|
|
216
|
+
)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _parse_distro(value: str) -> tuple[str, str]:
|
|
220
|
+
parts = value.replace("@", ":").split(":")
|
|
221
|
+
if len(parts) != 2 or not all(parts):
|
|
222
|
+
raise grype_tool.GrypeError(
|
|
223
|
+
f"--distro must be id:version (e.g. debian:12), got {value!r}"
|
|
224
|
+
)
|
|
225
|
+
return parts[0], parts[1]
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _parse_container_distros(values: list[str]) -> dict[str, tuple[str, str]]:
|
|
229
|
+
"""--container-distro <container-id>=<id:version>, repeatable."""
|
|
230
|
+
out: dict[str, tuple[str, str]] = {}
|
|
231
|
+
for value in values:
|
|
232
|
+
container_id, sep, distro = value.partition("=")
|
|
233
|
+
parts = distro.replace("@", ":").split(":") if sep else []
|
|
234
|
+
if not container_id or len(parts) != 2 or not all(parts):
|
|
235
|
+
raise grype_tool.GrypeError(
|
|
236
|
+
"--container-distro must be container-id=id:version"
|
|
237
|
+
f" (e.g. 5c2de2e0541a=alpine:3.21), got {value!r}"
|
|
238
|
+
)
|
|
239
|
+
out[container_id] = (parts[0], parts[1])
|
|
240
|
+
return out
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _cmd_grype(args: argparse.Namespace) -> int:
|
|
244
|
+
conn = connect(args.db)
|
|
245
|
+
try:
|
|
246
|
+
# Idempotent: a database loaded before this feature existed gets the
|
|
247
|
+
# grype tables here instead of failing on its first scan.
|
|
248
|
+
create_schema(conn)
|
|
249
|
+
audit_id = _resolve_audit(conn, args.audit)
|
|
250
|
+
packages = conn.execute(
|
|
251
|
+
"SELECT COUNT(*) FROM package WHERE audit_id = ?", (audit_id,)
|
|
252
|
+
).fetchone()[0]
|
|
253
|
+
if packages == 0:
|
|
254
|
+
raise DatabaseError(
|
|
255
|
+
f"audit {audit_id} has no packages loaded; nothing to scan"
|
|
256
|
+
)
|
|
257
|
+
# One document per scope: the host first — its distro refusal is the
|
|
258
|
+
# one that stops everything — then every container the audit reported.
|
|
259
|
+
# A container is never folded into the host's document: its purls are
|
|
260
|
+
# namespaced by a distro the host does not run.
|
|
261
|
+
overrides = _parse_container_distros(args.container_distro or [])
|
|
262
|
+
scopes: list[tuple[str, str | None]] = [("host", None)]
|
|
263
|
+
for container in containers_of(conn, audit_id):
|
|
264
|
+
records = conn.execute(
|
|
265
|
+
"SELECT COUNT(*) FROM package WHERE audit_id = ? AND container = ?",
|
|
266
|
+
(audit_id, container["id"]),
|
|
267
|
+
).fetchone()[0]
|
|
268
|
+
if records == 0:
|
|
269
|
+
# Explicit, not silent: an inventory with no records has
|
|
270
|
+
# nothing to scan, and saying so is not a failure.
|
|
271
|
+
print(
|
|
272
|
+
f"scope container:{container['id']}: 0 packages —"
|
|
273
|
+
" no document (nothing to scan)"
|
|
274
|
+
)
|
|
275
|
+
continue
|
|
276
|
+
scopes.append((f"container:{container['id']}", container["id"]))
|
|
277
|
+
|
|
278
|
+
out = (
|
|
279
|
+
Path(args.out)
|
|
280
|
+
if args.out
|
|
281
|
+
else Path(args.db).parent / (Path(args.db).stem + "-grype")
|
|
282
|
+
)
|
|
283
|
+
grype_bin: str | None = None
|
|
284
|
+
status: dict | None = None
|
|
285
|
+
|
|
286
|
+
for scope, container_id in scopes:
|
|
287
|
+
try:
|
|
288
|
+
if container_id is None:
|
|
289
|
+
distro = (
|
|
290
|
+
_parse_distro(args.distro)
|
|
291
|
+
if args.distro
|
|
292
|
+
else audit_distro(conn, audit_id)
|
|
293
|
+
)
|
|
294
|
+
elif container_id in overrides:
|
|
295
|
+
distro = overrides[container_id]
|
|
296
|
+
else:
|
|
297
|
+
distro = container_distro(conn, audit_id, container_id)
|
|
298
|
+
except DistroError as exc:
|
|
299
|
+
if container_id is None:
|
|
300
|
+
raise # the host's distro is not optional
|
|
301
|
+
# Refused for this scope only: scoping the refusal is the
|
|
302
|
+
# whole point of scoping the scan. The reason — and the
|
|
303
|
+
# --container-distro escape it carries — is printed, not
|
|
304
|
+
# swallowed, and the host's scan is unaffected.
|
|
305
|
+
print(f"scope {scope}: SKIPPED — {exc}")
|
|
306
|
+
continue
|
|
307
|
+
distro_str = f"{distro[0]}:{distro[1]}"
|
|
308
|
+
suffix = "host" if container_id is None else f"container-{container_id}"
|
|
309
|
+
|
|
310
|
+
sbom = build_sbom(conn, audit_id, distro, container=container_id)
|
|
311
|
+
sbom_path = out / f"sbom-{audit_id}-{suffix}.json"
|
|
312
|
+
sbom_sha = write_sbom(sbom, sbom_path)
|
|
313
|
+
|
|
314
|
+
if grype_bin is None:
|
|
315
|
+
# After the first SBOM is on disk, on purpose: when grype's own
|
|
316
|
+
# database is unusable, the document that caused it must exist
|
|
317
|
+
# to be inspected, and the refusal keeps its wording.
|
|
318
|
+
grype_bin = grype_tool.locate()
|
|
319
|
+
status = grype_tool.db_status(grype_bin, timeout=args.timeout)
|
|
320
|
+
grype_tool.require_valid_db(status)
|
|
321
|
+
|
|
322
|
+
report, _stderr = grype_tool.scan(
|
|
323
|
+
grype_bin, sbom_path, distro_str, timeout=args.timeout
|
|
324
|
+
)
|
|
325
|
+
echo = grype_tool.check_report_distro(report, *distro)
|
|
326
|
+
|
|
327
|
+
report_path = out / f"report-{audit_id}-{suffix}.json"
|
|
328
|
+
report_sha = write_json(report, report_path)
|
|
329
|
+
run = record_grype_run(
|
|
330
|
+
conn,
|
|
331
|
+
audit_id,
|
|
332
|
+
report=report,
|
|
333
|
+
distro=distro_str,
|
|
334
|
+
report_distro=echo,
|
|
335
|
+
grype_version=grype_tool.grype_version(report),
|
|
336
|
+
db_schema=status.get("schemaVersion"),
|
|
337
|
+
db_built=status.get("built"),
|
|
338
|
+
config_sha256=grype_tool.config_fingerprint(report),
|
|
339
|
+
sbom_path=str(sbom_path),
|
|
340
|
+
sbom_sha256=sbom_sha,
|
|
341
|
+
report_path=str(report_path),
|
|
342
|
+
report_sha256=report_sha,
|
|
343
|
+
scope=scope,
|
|
344
|
+
)
|
|
345
|
+
severities = conn.execute(
|
|
346
|
+
"SELECT severity, COUNT(*) AS n FROM vulnerability"
|
|
347
|
+
" WHERE audit_id = ? AND run = ? GROUP BY severity",
|
|
348
|
+
(audit_id, run),
|
|
349
|
+
).fetchall()
|
|
350
|
+
order = {"Critical": 0, "High": 1, "Medium": 2, "Low": 3, "Negligible": 4}
|
|
351
|
+
breakdown = ", ".join(
|
|
352
|
+
f"{row['severity'] or 'unknown'}={row['n']}"
|
|
353
|
+
for row in sorted(
|
|
354
|
+
severities,
|
|
355
|
+
key=lambda r: (order.get(r["severity"], 9), r["severity"] or ""),
|
|
356
|
+
)
|
|
357
|
+
)
|
|
358
|
+
total = sum(row["n"] for row in severities)
|
|
359
|
+
print(
|
|
360
|
+
f"run {run} scope {scope}: {total} matches"
|
|
361
|
+
+ (f" ({breakdown})" if breakdown else "")
|
|
362
|
+
+ f" vs {distro_str}"
|
|
363
|
+
)
|
|
364
|
+
print(
|
|
365
|
+
f" grype {grype_tool.grype_version(report)}, db built"
|
|
366
|
+
f" {status.get('built')} ({status.get('schemaVersion')})"
|
|
367
|
+
)
|
|
368
|
+
print(f" sbom: {sbom_path} sha256={sbom_sha}")
|
|
369
|
+
print(f" report: {report_path} sha256={report_sha}")
|
|
370
|
+
finally:
|
|
371
|
+
conn.close()
|
|
372
|
+
return 0
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
if __name__ == "__main__":
|
|
376
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# Configuration owned by perquisition-analysis, passed to grype with
|
|
2
|
+
# --config on every run.
|
|
3
|
+
#
|
|
4
|
+
# Its first purpose is to REPLACE grype's config discovery: without it, a
|
|
5
|
+
# ~/.grype.yaml or a .grype.yaml in the working directory is loaded, and an
|
|
6
|
+
# `ignore:` rule there silently removes matches from the report (verified on
|
|
7
|
+
# grype 0.122.1: a cwd ignore drops the fixture from 54 matches to 53). A
|
|
8
|
+
# report must say what actually ran — the effective configuration is also
|
|
9
|
+
# echoed by grype itself under descriptor.configuration and is hashed into
|
|
10
|
+
# the database row of every run.
|
|
11
|
+
#
|
|
12
|
+
# Everything else stays at grype's defaults; these keys are stated so the
|
|
13
|
+
# file reads as a decision rather than as an empty vessel.
|
|
14
|
+
db:
|
|
15
|
+
auto-update: true
|
|
16
|
+
validate-age: true
|