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/cli.py ADDED
@@ -0,0 +1,521 @@
1
+ """Command-line interface.
2
+
3
+ Exit codes: 0 = clean, 1 = findings at or above --fail-on (or failing tests),
4
+ 2 = usage or runtime error.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import json
11
+ import os
12
+ import shutil
13
+ import subprocess
14
+ import sys
15
+ from pathlib import Path
16
+
17
+ from . import netscan as netscan_mod
18
+ from . import pentest as pentest_mod
19
+ from . import testgen, testrun
20
+ from ._util import atomic_write, safe_term, utc_now
21
+ from ._version import __version__
22
+ from .attack import finalize
23
+ from .config import CONFIG_NAME, Config, ConfigError, write_baseline
24
+ from .engine import ANALYZERS, Options, scan
25
+ from .model import RANK, SEVERITIES, Report
26
+ from .report.formats import to_csv, to_json, to_junit, to_markdown, to_sarif, to_text
27
+ from .report.html import render as to_html
28
+ from .rules.base import REGISTRY
29
+ from .walk import Project
30
+
31
+ EXIT_OK, EXIT_FINDINGS, EXIT_ERROR = 0, 1, 2
32
+ FORMATS = ("text", "html", "md", "json", "sarif", "junit", "csv")
33
+ EXT = {"html": "html", "md": "md", "json": "json", "sarif": "sarif", "junit": "junit.xml", "csv": "csv"}
34
+
35
+
36
+ def _progress(quiet: bool):
37
+ if quiet or not sys.stderr.isatty():
38
+ return None
39
+ return lambda m: print(f" - {m}", file=sys.stderr)
40
+
41
+
42
+ def _formats(values: list[str] | None, default: list[str]) -> list[str]:
43
+ out: list[str] = []
44
+ for v in values or default:
45
+ for part in v.split(","):
46
+ part = part.strip().lower()
47
+ if part == "all":
48
+ out += [f for f in FORMATS if f != "text"]
49
+ elif part:
50
+ if part not in FORMATS:
51
+ raise ConfigError(f"unknown format {part!r} (choose from {', '.join(FORMATS)}, all)")
52
+ out.append(part)
53
+ return list(dict.fromkeys(out))
54
+
55
+
56
+ def emit(
57
+ report: Report, formats: list[str], out_dir: Path, *, quiet: bool, fail_on: str, min_severity: str
58
+ ) -> list[Path]:
59
+ written = []
60
+ renderers = {"html": to_html, "md": to_markdown, "json": to_json, "sarif": to_sarif, "csv": to_csv,
61
+ "junit": lambda r: to_junit(r, fail_on)} # fmt: skip
62
+ for fmt in formats:
63
+ if fmt == "text":
64
+ continue
65
+ path = out_dir / f"auditwright.{EXT[fmt]}"
66
+ atomic_write(path, renderers[fmt](report).encode("utf-8"))
67
+ written.append(path)
68
+ if "text" in formats or not quiet:
69
+ print(to_text(report, color=sys.stdout.isatty() and not os.environ.get("NO_COLOR"), min_severity=min_severity))
70
+ for p in written:
71
+ print(f"wrote {p}", file=sys.stderr)
72
+ return written
73
+
74
+
75
+ def _exit_for(report: Report, fail_on: str) -> int:
76
+ failing = any(RANK[f.severity] >= RANK[fail_on] for f in report.findings)
77
+ tests_failed = any(
78
+ r.exit_code not in (0, None) or r.counts()["failed"] or r.counts()["error"] for r in report.test_runs
79
+ )
80
+ return EXIT_FINDINGS if failing or tests_failed else EXIT_OK
81
+
82
+
83
+ def _options(args, root: Path) -> Options:
84
+ only = [a.strip() for a in (args.only or ",".join(ANALYZERS)).split(",") if a.strip()]
85
+ skip = {a.strip() for a in (args.skip or "").split(",") if a.strip()}
86
+ bad = [a for a in [*only, *skip] if a not in ANALYZERS]
87
+ if bad:
88
+ raise ConfigError(f"unknown analyzer(s) {', '.join(bad)} (choose from {', '.join(ANALYZERS)})")
89
+ return Options(
90
+ analyzers=tuple(a for a in only if a not in skip),
91
+ offline=args.offline,
92
+ history=args.history,
93
+ history_commits=args.history_commits,
94
+ exclude=args.exclude or [],
95
+ include_ignored=args.include_ignored,
96
+ baseline=args.baseline or "",
97
+ config_path=args.config,
98
+ name=args.name or "",
99
+ progress=_progress(args.quiet),
100
+ )
101
+
102
+
103
+ def _fail_on(args, root: Path) -> str:
104
+ return args.fail_on or Config.load(root, args.config).fail_on
105
+
106
+
107
+ def cmd_scan(args) -> int:
108
+ root = Path(args.path).resolve()
109
+ if not root.is_dir():
110
+ raise ConfigError(f"{root} is not a directory")
111
+ report = scan(root, _options(args, root))
112
+ fail_on = _fail_on(args, root)
113
+ emit(
114
+ report,
115
+ _formats(args.format, ["text"]),
116
+ Path(args.output),
117
+ quiet=args.quiet,
118
+ fail_on=fail_on,
119
+ min_severity=args.min_severity,
120
+ )
121
+ return _exit_for(report, fail_on)
122
+
123
+
124
+ def cmd_full(args) -> int:
125
+ root = Path(args.path).resolve()
126
+ if not root.is_dir():
127
+ raise ConfigError(f"{root} is not a directory")
128
+ if (args.pentest or args.netscan) and not args.i_am_authorized:
129
+ raise ConfigError(
130
+ "--pentest/--netscan need --i-am-authorized: only test systems you own or have permission to test"
131
+ )
132
+ report = scan(root, _options(args, root))
133
+ if args.run_tests:
134
+ print("running the project's tests (this executes project code)...", file=sys.stderr)
135
+ report.test_runs = testrun.run_all(Project(root), timeout=args.test_timeout)
136
+ report.analyzers.append("tests")
137
+ if args.pentest:
138
+ findings, facts = pentest_mod.run(args.pentest, delay=args.delay, max_requests=args.max_requests)
139
+ report.findings.extend(findings)
140
+ report.pentest = facts
141
+ report.analyzers.append("pentest")
142
+ finalize(report)
143
+ if args.netscan:
144
+ try:
145
+ findings, facts = netscan_mod.run(args.netscan, progress=_progress(args.quiet))
146
+ except netscan_mod.ScopeError as exc:
147
+ raise ConfigError(str(exc)) from exc
148
+ report.findings.extend(findings)
149
+ report.network = facts
150
+ report.analyzers.append("network")
151
+ finalize(report)
152
+ gen = testgen.find_targets(Project(root))
153
+ if gen.targets or gen.already_tested:
154
+ report.notes.append(
155
+ f"Test coverage gaps: {len(gen.targets)} public Python functions have no test that mentions them "
156
+ f"({gen.already_tested} do). Run `auditwright gen-tests --write` to generate edge-case tests."
157
+ )
158
+ report.finished = utc_now()
159
+ fail_on = _fail_on(args, root)
160
+ emit(
161
+ report,
162
+ _formats(args.format, ["all"]),
163
+ Path(args.output),
164
+ quiet=args.quiet,
165
+ fail_on=fail_on,
166
+ min_severity=args.min_severity,
167
+ )
168
+ return _exit_for(report, fail_on)
169
+
170
+
171
+ def cmd_test(args) -> int:
172
+ root = Path(args.path).resolve()
173
+ project = Project(root)
174
+ frameworks = [args.framework] if args.framework else None
175
+ if not frameworks and not testrun.detect(project):
176
+ print("no test suites detected", file=sys.stderr)
177
+ return EXIT_OK
178
+ print("running the project's tests (this executes project code)...", file=sys.stderr)
179
+ report = Report(tool_version=__version__, target=root.name or "project", started=utc_now(), analyzers=["tests"])
180
+ report.test_runs = testrun.run_all(project, timeout=args.timeout, coverage=not args.no_coverage, only=frameworks)
181
+ report.finished = utc_now()
182
+ emit(
183
+ report,
184
+ _formats(args.format, ["text"]),
185
+ Path(args.output),
186
+ quiet=args.quiet,
187
+ fail_on="critical",
188
+ min_severity="info",
189
+ )
190
+ return _exit_for(report, "critical")
191
+
192
+
193
+ def cmd_gen_tests(args) -> int:
194
+ root = Path(args.path).resolve()
195
+ result = testgen.generate(Project(root), args.out, args.timeout)
196
+ print(f"{len(result.targets)} untested public functions, {result.already_tested} already referenced by tests, "
197
+ f"{len(result.skipped)} skipped for possible side effects") # fmt: skip
198
+ for s in result.skipped[:30]:
199
+ print(f" skipped {safe_term(s['function'])}: {safe_term(s['reason'])}")
200
+ if not args.write:
201
+ for t in result.targets[:50]:
202
+ print(f" would test {safe_term(t.module)}.{safe_term(t.name)} ({safe_term(t.file)}:{t.line})")
203
+ print("preview only; add --write to create the test files")
204
+ return EXIT_OK
205
+ for rel, source in result.files.items():
206
+ dest = root / rel
207
+ if dest.exists() and not args.force:
208
+ print(f" exists, not overwritten: {rel} (use --force)")
209
+ continue
210
+ atomic_write(dest, source.encode("utf-8"))
211
+ print(f" wrote {rel}")
212
+ if result.files:
213
+ print("Review the generated tests, then run them with: python -m pytest " + args.out)
214
+ return EXIT_OK
215
+
216
+
217
+ def cmd_pentest(args) -> int:
218
+ if not args.i_am_authorized:
219
+ raise ConfigError(
220
+ "refusing to test without --i-am-authorized: only test systems you own or have written permission to test"
221
+ )
222
+ report = Report(tool_version=__version__, target=args.url, started=utc_now(), analyzers=["pentest"])
223
+ print(f"testing {safe_term(args.url)} (up to {args.max_requests} requests, {args.delay}s apart)", file=sys.stderr)
224
+ report.findings, report.pentest = pentest_mod.run(args.url, delay=args.delay, max_requests=args.max_requests)
225
+ finalize(report)
226
+ report.finished = utc_now()
227
+ fail_on = args.fail_on or "high"
228
+ emit(
229
+ report,
230
+ _formats(args.format, ["text"]),
231
+ Path(args.output),
232
+ quiet=args.quiet,
233
+ fail_on=fail_on,
234
+ min_severity=args.min_severity,
235
+ )
236
+ return _exit_for(report, fail_on)
237
+
238
+
239
+ def cmd_netscan(args) -> int:
240
+ if not args.i_am_authorized:
241
+ raise ConfigError(
242
+ "refusing to scan without --i-am-authorized: only scan networks you own or have written permission to test"
243
+ )
244
+ try:
245
+ ports = netscan_mod.parse_ports(args.ports)
246
+ hosts = netscan_mod.expand_targets(args.targets, allow_public=args.allow_public, max_hosts=args.max_hosts)
247
+ except ValueError as exc:
248
+ raise ConfigError(str(exc)) from exc
249
+ print(f"scanning {len(hosts)} hosts on {len(ports)} ports (read-only probes)", file=sys.stderr)
250
+ report = Report(
251
+ tool_version=__version__, target=args.name or args.targets, started=utc_now(), analyzers=["network"]
252
+ )
253
+ scanner = netscan_mod.NetScan(
254
+ hosts, ports=ports, timeout=args.timeout, workers=args.workers, progress=_progress(args.quiet)
255
+ )
256
+ report.findings, report.network = scanner.run()
257
+ if args.web:
258
+ for h in report.network.get("hosts", []):
259
+ for svc in h["services"]:
260
+ if svc["service"] in ("http", "https") and svc.get("status"):
261
+ found, _facts = pentest_mod.run(
262
+ f"{svc['service']}://{h['host']}:{svc['port']}/", delay=0.1, max_requests=60
263
+ )
264
+ report.findings.extend(found)
265
+ svc["web_findings"] = len(found)
266
+ finalize(report)
267
+ report.finished = utc_now()
268
+ if not args.quiet:
269
+ for h in report.network.get("hosts", []):
270
+ ports_txt = ", ".join(f"{s['port']}/{s['service']}" for s in h["services"])
271
+ print(f" {h['host']:<16} {safe_term(ports_txt, 160)}", file=sys.stderr)
272
+ fail_on = args.fail_on or "high"
273
+ emit(
274
+ report,
275
+ _formats(args.format, ["text"]),
276
+ Path(args.output),
277
+ quiet=args.quiet,
278
+ fail_on=fail_on,
279
+ min_severity=args.min_severity,
280
+ )
281
+ return _exit_for(report, fail_on)
282
+
283
+
284
+ def cmd_baseline(args) -> int:
285
+ root = Path(args.path).resolve()
286
+ opts = _options(args, root)
287
+ opts.baseline = ""
288
+ report = scan(root, opts)
289
+ dest = root / args.file
290
+ write_baseline(dest, report.findings)
291
+ print(
292
+ f'wrote {dest} with {len(report.findings)} accepted findings; use --baseline {args.file} (or set "baseline" in {CONFIG_NAME})'
293
+ )
294
+ return EXIT_OK
295
+
296
+
297
+ def cmd_rules(args) -> int:
298
+ rules = sorted(REGISTRY.values(), key=lambda r: r.id)
299
+ if args.format == "json":
300
+ print(json.dumps([r.__dict__ for r in rules], indent=2))
301
+ elif args.format == "md":
302
+ print("| ID | Severity | Area | Title | CWE | OWASP |\n|---|---|---|---|---|---|")
303
+ for r in rules:
304
+ print(f"| {r.id} | {r.severity} | {r.category} | {r.title} | {r.cwe} | {r.owasp} |")
305
+ else:
306
+ for r in rules:
307
+ print(f"{r.id:<14} {r.severity:<9} {r.category:<13} {r.title}")
308
+ print(f"\n{len(rules)} rules")
309
+ return EXIT_OK
310
+
311
+
312
+ TEMPLATE = {
313
+ "exclude": ["tests/fixtures/"],
314
+ "disable": [],
315
+ "severity": {},
316
+ "ignore": [],
317
+ "fail_on": "high",
318
+ "baseline": "",
319
+ }
320
+
321
+
322
+ def cmd_init(args) -> int:
323
+ root = Path(args.path).resolve()
324
+ dest = root / CONFIG_NAME
325
+ if dest.exists() and not args.force:
326
+ raise ConfigError(f"{dest} exists (use --force)")
327
+ atomic_write(dest, (json.dumps(TEMPLATE, indent=2) + "\n").encode())
328
+ print(f"wrote {dest}")
329
+ print("CI example (GitHub Actions):\n"
330
+ " - run: pip install auditwright\n"
331
+ " - run: auditwright scan --format sarif,html,junit -o auditwright-report --fail-on high") # fmt: skip
332
+ return EXIT_OK
333
+
334
+
335
+ def cmd_doctor(args) -> int:
336
+ from .net import Http
337
+
338
+ print(f"auditwright {__version__}")
339
+ print(f"python {sys.version.split()[0]} on {sys.platform}")
340
+ git = shutil.which("git")
341
+ print(f"git: {'found' if git else 'not found (history scanning unavailable)'}")
342
+ if git:
343
+ try:
344
+ out = subprocess.run(
345
+ [git, "--version"], capture_output=True, text=True, timeout=10, check=False
346
+ ).stdout.strip()
347
+ print(f" {out}")
348
+ except (OSError, subprocess.TimeoutExpired):
349
+ pass
350
+ try:
351
+ r = Http(timeout=10).post_json(
352
+ "https://api.osv.dev/v1/query", {"package": {"name": "jinja2", "ecosystem": "PyPI"}, "version": "2.4.1"}
353
+ )
354
+ print(f"OSV database: reachable (HTTP {r.status})")
355
+ except OSError as exc:
356
+ print(f"OSV database: unreachable ({type(exc).__name__}); use --offline")
357
+ print(f"rules: {len(REGISTRY)}")
358
+ return EXIT_OK
359
+
360
+
361
+ def _add_scan_args(p: argparse.ArgumentParser, default_formats: str) -> None:
362
+ p.add_argument("path", nargs="?", default=".", help="project directory (default: current directory)")
363
+ p.add_argument(
364
+ "-f",
365
+ "--format",
366
+ action="append",
367
+ help=f"output formats, comma separated: {', '.join(FORMATS)}, all (default: {default_formats})",
368
+ )
369
+ p.add_argument(
370
+ "-o", "--output", default="auditwright-report", help="directory for report files (default: auditwright-report)"
371
+ )
372
+ p.add_argument("--only", help=f"run only these analyzers: {','.join(ANALYZERS)}")
373
+ p.add_argument("--skip", help="skip these analyzers")
374
+ p.add_argument("--offline", action="store_true", help="do not query the vulnerability database")
375
+ p.add_argument("--history", action="store_true", help="also scan git history for secrets")
376
+ p.add_argument("--history-commits", type=int, default=2000, help="commits to scan with --history (default 2000)")
377
+ p.add_argument("--exclude", action="append", help="path or glob to exclude (repeatable)")
378
+ p.add_argument("--include-ignored", action="store_true", help="also scan files ignored by .gitignore")
379
+ p.add_argument("--baseline", help="only report findings not in this baseline file")
380
+ p.add_argument("--config", help=f"config file (default: ./{CONFIG_NAME})")
381
+ p.add_argument(
382
+ "--fail-on",
383
+ choices=SEVERITIES,
384
+ help="exit 1 when a finding is at least this severe (default from config: high)",
385
+ )
386
+ p.add_argument(
387
+ "--min-severity",
388
+ choices=SEVERITIES,
389
+ default="low",
390
+ help="lowest severity printed in the terminal (default low)",
391
+ )
392
+ p.add_argument("-q", "--quiet", action="store_true", help="no terminal report or progress")
393
+ p.add_argument("--name", help="project name shown in reports (default: the directory name)")
394
+
395
+
396
+ def build_parser() -> argparse.ArgumentParser:
397
+ p = argparse.ArgumentParser(
398
+ prog="auditwright",
399
+ description="Security audit, vulnerability check, test run, test generation and pen test reports for any project.",
400
+ )
401
+ p.add_argument("--version", action="version", version=f"auditwright {__version__}")
402
+ sub = p.add_subparsers(dest="command", metavar="command")
403
+
404
+ s = sub.add_parser("scan", help="static security audit: code, secrets, dependencies, config, unicode, crypto")
405
+ _add_scan_args(s, "text")
406
+ s.set_defaults(func=cmd_scan)
407
+
408
+ s = sub.add_parser("full", help="scan + optional tests and pen test; writes every report format")
409
+ _add_scan_args(s, "all")
410
+ s.add_argument("--run-tests", action="store_true", help="run the project's test suites (executes project code)")
411
+ s.add_argument("--test-timeout", type=float, default=900.0)
412
+ s.add_argument("--pentest", metavar="URL", help="also pen test this URL (requires --i-am-authorized)")
413
+ s.add_argument(
414
+ "--i-am-authorized",
415
+ action="store_true",
416
+ help="confirm you own the target or have written permission to test it",
417
+ )
418
+ s.add_argument("--delay", type=float, default=0.25)
419
+ s.add_argument("--max-requests", type=int, default=120)
420
+ s.add_argument(
421
+ "--netscan",
422
+ metavar="TARGETS",
423
+ help="also scan these hosts/CIDRs for exposed services (requires --i-am-authorized)",
424
+ )
425
+ s.set_defaults(func=cmd_full)
426
+
427
+ s = sub.add_parser(
428
+ "netscan", help="authorised network exposure scan: open ports, unauthenticated services, weak protocols"
429
+ )
430
+ s.add_argument("targets", help="IPs, CIDRs or host names, comma separated (for example 192.168.1.0/24)")
431
+ s.add_argument(
432
+ "--i-am-authorized",
433
+ action="store_true",
434
+ help="confirm you own the network or have written permission to scan it",
435
+ )
436
+ s.add_argument("--ports", default="top", help="'top' (default), or a list like 22,80,8000-8100,6380=redis")
437
+ s.add_argument(
438
+ "--allow-public", action="store_true", help="allow public IP addresses (only with written permission)"
439
+ )
440
+ s.add_argument("--max-hosts", type=int, default=1024)
441
+ s.add_argument("--timeout", type=float, default=0.8, help="connect timeout per port in seconds")
442
+ s.add_argument("--workers", type=int, default=64, help="parallel connections (default 64, max 256)")
443
+ s.add_argument("--web", action="store_true", help="also run the web pen test against every web service found")
444
+ s.add_argument("--name", help="name shown in reports")
445
+ s.add_argument("-f", "--format", action="append")
446
+ s.add_argument("-o", "--output", default="auditwright-report")
447
+ s.add_argument("--fail-on", choices=SEVERITIES)
448
+ s.add_argument("--min-severity", choices=SEVERITIES, default="low")
449
+ s.add_argument("-q", "--quiet", action="store_true")
450
+ s.set_defaults(func=cmd_netscan)
451
+
452
+ s = sub.add_parser("test", help="detect and run the project's tests (executes project code)")
453
+ s.add_argument("path", nargs="?", default=".")
454
+ s.add_argument("--framework", choices=["pytest", "unittest", "jest", "vitest", "npm", "go", "cargo"])
455
+ s.add_argument("--timeout", type=float, default=900.0)
456
+ s.add_argument("--no-coverage", action="store_true")
457
+ s.add_argument("-f", "--format", action="append")
458
+ s.add_argument("-o", "--output", default="auditwright-report")
459
+ s.add_argument("-q", "--quiet", action="store_true")
460
+ s.set_defaults(func=cmd_test)
461
+
462
+ s = sub.add_parser("gen-tests", help="generate edge-case and security tests for untested Python functions")
463
+ s.add_argument("path", nargs="?", default=".")
464
+ s.add_argument("--write", action="store_true", help="write the files (default: preview)")
465
+ s.add_argument("--out", default="tests/generated", help="directory for generated tests (default tests/generated)")
466
+ s.add_argument("--timeout", type=float, default=5.0, help="seconds each generated call may take")
467
+ s.add_argument("--force", action="store_true", help="overwrite existing generated files")
468
+ s.set_defaults(func=cmd_gen_tests)
469
+
470
+ s = sub.add_parser("pentest", help="authorised, non-destructive web pen test of one origin")
471
+ s.add_argument("url")
472
+ s.add_argument(
473
+ "--i-am-authorized",
474
+ action="store_true",
475
+ help="confirm you own the target or have written permission to test it",
476
+ )
477
+ s.add_argument("--delay", type=float, default=0.25, help="seconds between requests (default 0.25)")
478
+ s.add_argument("--max-requests", type=int, default=120)
479
+ s.add_argument("-f", "--format", action="append")
480
+ s.add_argument("-o", "--output", default="auditwright-report")
481
+ s.add_argument("--fail-on", choices=SEVERITIES)
482
+ s.add_argument("--min-severity", choices=SEVERITIES, default="info")
483
+ s.add_argument("-q", "--quiet", action="store_true")
484
+ s.set_defaults(func=cmd_pentest)
485
+
486
+ s = sub.add_parser("baseline", help="accept current findings; later scans report only new ones")
487
+ _add_scan_args(s, "text")
488
+ s.add_argument("--file", default=".auditwright-baseline.json")
489
+ s.set_defaults(func=cmd_baseline)
490
+
491
+ s = sub.add_parser("rules", help="list every rule")
492
+ s.add_argument("--format", choices=["text", "json", "md"], default="text")
493
+ s.set_defaults(func=cmd_rules)
494
+
495
+ s = sub.add_parser("init", help=f"write a starter {CONFIG_NAME}")
496
+ s.add_argument("path", nargs="?", default=".")
497
+ s.add_argument("--force", action="store_true")
498
+ s.set_defaults(func=cmd_init)
499
+
500
+ s = sub.add_parser("doctor", help="check the environment (git, network access to the vulnerability database)")
501
+ s.set_defaults(func=cmd_doctor)
502
+ return p
503
+
504
+
505
+ def main(argv: list[str] | None = None) -> int:
506
+ parser = build_parser()
507
+ args = parser.parse_args(argv)
508
+ if not getattr(args, "func", None):
509
+ parser.print_help()
510
+ return EXIT_ERROR
511
+ try:
512
+ return args.func(args)
513
+ except ConfigError as exc:
514
+ print(f"auditwright: error: {exc}", file=sys.stderr)
515
+ return EXIT_ERROR
516
+ except KeyboardInterrupt:
517
+ return 130
518
+
519
+
520
+ if __name__ == "__main__": # pragma: no cover
521
+ sys.exit(main())
auditwright/config.py ADDED
@@ -0,0 +1,104 @@
1
+ """Project configuration (auditwright.json) and baselines.
2
+
3
+ Example ``auditwright.json``::
4
+
5
+ {
6
+ "exclude": ["fixtures/", "*.min.js"],
7
+ "disable": ["AW-PQ-001"],
8
+ "severity": {"AW-GHA-005": "info"},
9
+ "ignore": [{"rule": "AW-PY-004", "path": "scripts/", "reason": "admin-only tooling"}],
10
+ "fail_on": "high",
11
+ "baseline": ".auditwright-baseline.json"
12
+ }
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ from dataclasses import dataclass, field
19
+ from pathlib import Path
20
+ from typing import Any
21
+
22
+ from ._util import atomic_write, utc_now
23
+ from .model import RANK, Finding
24
+
25
+ CONFIG_NAME = "auditwright.json"
26
+
27
+
28
+ class ConfigError(Exception):
29
+ pass
30
+
31
+
32
+ @dataclass
33
+ class Config:
34
+ exclude: list[str] = field(default_factory=list)
35
+ disable: list[str] = field(default_factory=list)
36
+ severity: dict[str, str] = field(default_factory=dict)
37
+ ignore: list[dict[str, str]] = field(default_factory=list)
38
+ fail_on: str = "high"
39
+ baseline: str = ""
40
+
41
+ @classmethod
42
+ def load(cls, root: Path, explicit: str | None = None) -> Config:
43
+ path = Path(explicit) if explicit else root / CONFIG_NAME
44
+ if not path.is_file():
45
+ if explicit:
46
+ raise ConfigError(f"config file not found: {path}")
47
+ return cls()
48
+ try:
49
+ data = json.loads(path.read_text("utf-8"))
50
+ except (OSError, ValueError) as exc:
51
+ raise ConfigError(f"cannot read {path.name}: {exc}") from exc
52
+ if not isinstance(data, dict):
53
+ raise ConfigError(f"{path.name} must contain a JSON object")
54
+ cfg = cls(
55
+ exclude=[str(x) for x in data.get("exclude", [])],
56
+ disable=[str(x) for x in data.get("disable", [])],
57
+ severity={str(k): str(v) for k, v in (data.get("severity") or {}).items()},
58
+ ignore=[x for x in data.get("ignore", []) if isinstance(x, dict)],
59
+ fail_on=str(data.get("fail_on", "high")),
60
+ baseline=str(data.get("baseline", "")),
61
+ )
62
+ for sev in [cfg.fail_on, *cfg.severity.values()]:
63
+ if sev not in RANK:
64
+ raise ConfigError(f"unknown severity {sev!r} in {path.name}")
65
+ return cfg
66
+
67
+ def apply(self, findings: list[Finding]) -> tuple[list[Finding], int]:
68
+ kept, dropped = [], 0
69
+ for f in findings:
70
+ if any(f.rule_id == d or f.rule_id.startswith(d.rstrip("*")) and d.endswith("*") for d in self.disable):
71
+ dropped += 1
72
+ continue
73
+ if any(
74
+ (not ig.get("rule") or ig["rule"] == f.rule_id)
75
+ and (not ig.get("path") or f.file.replace("\\", "/").startswith(ig["path"]))
76
+ and (not ig.get("fingerprint") or ig["fingerprint"] == f.fingerprint)
77
+ for ig in self.ignore
78
+ ):
79
+ dropped += 1
80
+ continue
81
+ if f.rule_id in self.severity:
82
+ f.severity = self.severity[f.rule_id]
83
+ kept.append(f)
84
+ return kept, dropped
85
+
86
+
87
+ def load_baseline(path: Path) -> set[str]:
88
+ try:
89
+ data = json.loads(path.read_text("utf-8"))
90
+ except (OSError, ValueError):
91
+ return set()
92
+ return {str(x["fingerprint"]) for x in data.get("findings", []) if isinstance(x, dict) and "fingerprint" in x}
93
+
94
+
95
+ def write_baseline(path: Path, findings: list[Finding]) -> None:
96
+ doc: dict[str, Any] = {
97
+ "created": utc_now(),
98
+ "note": "Findings accepted at this point; auditwright reports only new ones when this baseline is used.",
99
+ "findings": [
100
+ {"fingerprint": f.fingerprint, "rule": f.rule_id, "file": f.file, "title": f.title}
101
+ for f in sorted(findings, key=lambda f: (f.file, f.rule_id, f.fingerprint))
102
+ ],
103
+ }
104
+ atomic_write(path, (json.dumps(doc, indent=2) + "\n").encode("utf-8"))
auditwright/cvss.py ADDED
@@ -0,0 +1,49 @@
1
+ """CVSS v3.0/v3.1 base score calculation (FIRST specification, section 7.1)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+
7
+ _AV = {"N": 0.85, "A": 0.62, "L": 0.55, "P": 0.2}
8
+ _AC = {"L": 0.77, "H": 0.44}
9
+ _PR_U = {"N": 0.85, "L": 0.62, "H": 0.27}
10
+ _PR_C = {"N": 0.85, "L": 0.68, "H": 0.5}
11
+ _UI = {"N": 0.85, "R": 0.62}
12
+ _CIA = {"H": 0.56, "L": 0.22, "N": 0.0}
13
+
14
+
15
+ def _roundup(x: float) -> float:
16
+ i = round(x * 100000)
17
+ return i / 100000.0 if i % 10000 == 0 else (math.floor(i / 10000) + 1) / 10.0
18
+
19
+
20
+ def base_score(vector: str) -> float | None:
21
+ """Score a 'CVSS:3.x/AV:N/AC:L/...' vector, or None if it is not a valid v3 vector."""
22
+ if not vector.startswith(("CVSS:3.0/", "CVSS:3.1/")):
23
+ return None
24
+ try:
25
+ m = dict(part.split(":", 1) for part in vector.split("/")[1:])
26
+ scope_changed = m["S"] == "C"
27
+ iss = 1 - (1 - _CIA[m["C"]]) * (1 - _CIA[m["I"]]) * (1 - _CIA[m["A"]])
28
+ impact = 7.52 * (iss - 0.029) - 3.25 * (iss - 0.02) ** 15 if scope_changed else 6.42 * iss
29
+ pr = (_PR_C if scope_changed else _PR_U)[m["PR"]]
30
+ exploitability = 8.22 * _AV[m["AV"]] * _AC[m["AC"]] * pr * _UI[m["UI"]]
31
+ except (KeyError, ValueError):
32
+ return None
33
+ if impact <= 0:
34
+ return 0.0
35
+ if scope_changed:
36
+ return _roundup(min(1.08 * (impact + exploitability), 10))
37
+ return _roundup(min(impact + exploitability, 10))
38
+
39
+
40
+ def severity_for(score: float) -> str:
41
+ if score >= 9.0:
42
+ return "critical"
43
+ if score >= 7.0:
44
+ return "high"
45
+ if score >= 4.0:
46
+ return "medium"
47
+ if score > 0:
48
+ return "low"
49
+ return "info"