pentrep 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.
Files changed (42) hide show
  1. pentrep/__init__.py +3 -0
  2. pentrep/__main__.py +6 -0
  3. pentrep/cli.py +353 -0
  4. pentrep/cvss.py +313 -0
  5. pentrep/diagnostics.py +142 -0
  6. pentrep/loader.py +532 -0
  7. pentrep/models.py +358 -0
  8. pentrep/redact.py +320 -0
  9. pentrep/render/__init__.py +54 -0
  10. pentrep/render/context.py +200 -0
  11. pentrep/render/highlight.py +62 -0
  12. pentrep/render/html.py +34 -0
  13. pentrep/render/markdown.py +58 -0
  14. pentrep/render/md.py +172 -0
  15. pentrep/render/pdf.py +116 -0
  16. pentrep/scaffold/assets/logo.png +0 -0
  17. pentrep/scaffold/evidence/pt-001-sqlmap.png +0 -0
  18. pentrep/scaffold/findings.yaml +119 -0
  19. pentrep/stats.py +70 -0
  20. pentrep/themes/classic/fonts/OFL.txt +104 -0
  21. pentrep/themes/classic/fonts/SourceCodePro-Regular.ttf +0 -0
  22. pentrep/themes/classic/fonts/SourceSans3-Bold.ttf +0 -0
  23. pentrep/themes/classic/fonts/SourceSans3-It.ttf +0 -0
  24. pentrep/themes/classic/fonts/SourceSans3-Regular.ttf +0 -0
  25. pentrep/themes/classic/fonts.css +7 -0
  26. pentrep/themes/classic/partials/appendix.html.j2 +38 -0
  27. pentrep/themes/classic/partials/cover.html.j2 +17 -0
  28. pentrep/themes/classic/partials/document_control.html.j2 +22 -0
  29. pentrep/themes/classic/partials/executive_summary.html.j2 +17 -0
  30. pentrep/themes/classic/partials/finding.html.j2 +56 -0
  31. pentrep/themes/classic/partials/macros.html.j2 +7 -0
  32. pentrep/themes/classic/partials/scope.html.j2 +27 -0
  33. pentrep/themes/classic/partials/summary_table.html.j2 +13 -0
  34. pentrep/themes/classic/partials/toc.html.j2 +19 -0
  35. pentrep/themes/classic/report.html.j2 +35 -0
  36. pentrep/themes/classic/report.md.j2 +187 -0
  37. pentrep/themes/classic/style.css +97 -0
  38. pentrep-0.1.0.dist-info/METADATA +142 -0
  39. pentrep-0.1.0.dist-info/RECORD +42 -0
  40. pentrep-0.1.0.dist-info/WHEEL +4 -0
  41. pentrep-0.1.0.dist-info/entry_points.txt +2 -0
  42. pentrep-0.1.0.dist-info/licenses/LICENSE +21 -0
pentrep/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """pentrep: turn findings.yaml into professional pentest reports."""
2
+
3
+ __version__ = "0.1.0"
pentrep/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ """Allow running pentrep as ``python -m pentrep``."""
2
+
3
+ from pentrep.cli import main
4
+
5
+ if __name__ == "__main__":
6
+ main()
pentrep/cli.py ADDED
@@ -0,0 +1,353 @@
1
+ """Command-line interface for pentrep."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ import shutil
8
+ import sys
9
+ from collections.abc import Sequence
10
+ from dataclasses import dataclass
11
+ from enum import StrEnum
12
+ from importlib import resources
13
+ from pathlib import Path
14
+ from typing import Annotated, Final
15
+
16
+ import typer
17
+
18
+ from pentrep import __version__
19
+ from pentrep.diagnostics import ExitCode, format_json, format_text
20
+ from pentrep.loader import load_report
21
+ from pentrep.models import json_schema
22
+ from pentrep.redact import format_summary, redact_report
23
+ from pentrep.stats import breakdown, compute_stats
24
+
25
+
26
+ @dataclass
27
+ class _State:
28
+ """Per-invocation global options."""
29
+
30
+ debug: bool = False
31
+
32
+
33
+ _state = _State()
34
+
35
+ app = typer.Typer(
36
+ name="pentrep",
37
+ help="Turn findings.yaml into professional pentest reports (HTML, PDF, Markdown).",
38
+ no_args_is_help=True,
39
+ add_completion=False,
40
+ pretty_exceptions_enable=False,
41
+ )
42
+
43
+
44
+ def _version_callback(value: bool) -> None:
45
+ """Print the version and exit when --version is given."""
46
+ if value:
47
+ typer.echo(f"pentrep {__version__}")
48
+ raise typer.Exit()
49
+
50
+
51
+ @app.callback()
52
+ def root(
53
+ version: bool = typer.Option(
54
+ False,
55
+ "--version",
56
+ callback=_version_callback,
57
+ is_eager=True,
58
+ help="Show the pentrep version and exit.",
59
+ ),
60
+ debug: bool = typer.Option(
61
+ False, "--debug", help="Show full tracebacks for unexpected errors."
62
+ ),
63
+ ) -> None:
64
+ """Turn findings.yaml into professional pentest reports (HTML, PDF, Markdown)."""
65
+ _state.debug = debug
66
+
67
+
68
+ CURRENT_DIR: Final = Path(".")
69
+ SCAFFOLD_FILES: Final = ("findings.yaml", "assets/logo.png", "evidence/pt-001-sqlmap.png")
70
+
71
+
72
+ def _fail(message: str, code: ExitCode) -> typer.Exit:
73
+ """Print ``message`` to stderr and return an Exit to raise."""
74
+ typer.echo(message, err=True)
75
+ return typer.Exit(code)
76
+
77
+
78
+ @app.command()
79
+ def init(
80
+ directory: Annotated[
81
+ Path, typer.Argument(help="Directory to create the project in (created if missing).")
82
+ ] = CURRENT_DIR,
83
+ force: Annotated[
84
+ bool, typer.Option("--force", help="Overwrite files that already exist.")
85
+ ] = False,
86
+ ) -> None:
87
+ """Create an example findings.yaml with a logo and an evidence image (FR-01)."""
88
+ targets = [directory / name for name in SCAFFOLD_FILES]
89
+ conflicts = [t for t in targets if t.exists() or t.is_symlink()]
90
+ if conflicts and not force:
91
+ listing = "\n".join(f" {c}" for c in conflicts)
92
+ raise _fail(
93
+ f"error: these files already exist (use --force to overwrite):\n{listing}",
94
+ ExitCode.VALIDATION_FAILED,
95
+ )
96
+ scaffold = resources.files("pentrep") / "scaffold"
97
+ try:
98
+ for name, target in zip(SCAFFOLD_FILES, targets, strict=True):
99
+ target.parent.mkdir(parents=True, exist_ok=True)
100
+ target.write_bytes(scaffold.joinpath(name).read_bytes())
101
+ typer.echo(f"Created {target}")
102
+ except OSError as exc:
103
+ raise _fail(f"error: cannot write to {directory}: {exc}", ExitCode.RENDER_ERROR) from None
104
+ typer.echo(f"Next: pentrep validate {targets[0]}")
105
+
106
+
107
+ class OutputFormat(StrEnum):
108
+ """Output formats for ``validate``."""
109
+
110
+ TEXT = "text"
111
+ JSON = "json"
112
+
113
+
114
+ def _count(n: int, noun: str) -> str:
115
+ return f"{n} {noun}" if n == 1 else f"{n} {noun}s"
116
+
117
+
118
+ @app.command()
119
+ def validate(
120
+ file: Annotated[
121
+ Path,
122
+ typer.Argument(
123
+ help="The findings.yaml file to check.", exists=True, dir_okay=False, readable=True
124
+ ),
125
+ ],
126
+ strict: Annotated[bool, typer.Option("--strict", help="Treat warnings as errors.")] = False,
127
+ output_format: Annotated[
128
+ OutputFormat,
129
+ typer.Option("--format", help="Print diagnostics as text (stderr) or JSON (stdout)."),
130
+ ] = OutputFormat.TEXT,
131
+ ) -> None:
132
+ """Check FILE against the schema and report every error and warning (FR-02)."""
133
+ name = str(file)
134
+ result = load_report(file, display=name)
135
+ errors, warnings = len(result.errors), len(result.warnings)
136
+ failed = bool(errors) or (strict and bool(warnings))
137
+ if output_format is OutputFormat.JSON:
138
+ typer.echo(format_json(result.diagnostics))
139
+ else:
140
+ for diagnostic in result.diagnostics:
141
+ typer.echo(format_text(diagnostic), err=True)
142
+ summary = f"{_count(errors, 'error')}, {_count(warnings, 'warning')}"
143
+ if failed:
144
+ note = " (--strict treats warnings as errors)" if not errors else ""
145
+ typer.echo(f"✗ {name} is invalid: {summary}{note}", err=True)
146
+ else:
147
+ report_findings = result.report.findings if result.report else []
148
+ findings = _count(len(report_findings), "finding")
149
+ if report_findings:
150
+ findings += f" ({breakdown(compute_stats(report_findings))})"
151
+ typer.echo(f"✓ {name} is valid: {findings}, {_count(warnings, 'warning')}")
152
+ if result.report is not None:
153
+ _, redaction = redact_report(result.report)
154
+ for line in format_summary(redaction, preview=True):
155
+ typer.echo(line)
156
+ if failed:
157
+ raise typer.Exit(ExitCode.VALIDATION_FAILED)
158
+
159
+
160
+ @app.command()
161
+ def schema(
162
+ output: Annotated[
163
+ Path | None,
164
+ typer.Option("--output", "-o", help="Write the schema to FILE instead of stdout."),
165
+ ] = None,
166
+ ) -> None:
167
+ """Print the JSON Schema (draft 2020-12) for findings.yaml (FR-04)."""
168
+ text = json.dumps(json_schema(), indent=2, ensure_ascii=False) + "\n"
169
+ if output is None:
170
+ typer.echo(text, nl=False)
171
+ return
172
+ try:
173
+ output.write_text(text, encoding="utf-8")
174
+ except OSError as exc:
175
+ raise _fail(f"error: cannot write {output}: {exc}", ExitCode.RENDER_ERROR) from None
176
+ typer.echo(f"Wrote {output}")
177
+
178
+
179
+ class BuildFormat(StrEnum):
180
+ """Output formats for ``build`` (FR-03)."""
181
+
182
+ HTML = "html"
183
+ PDF = "pdf"
184
+ MD = "md"
185
+ ALL = "all"
186
+
187
+
188
+ class Paper(StrEnum):
189
+ """PDF page sizes (``--paper``)."""
190
+
191
+ A4 = "a4"
192
+ LETTER = "letter"
193
+
194
+
195
+ NAME_RE: Final = re.compile(r"^[A-Za-z0-9._-]{1,100}$")
196
+ DEFAULT_OUTPUT_DIR: Final = Path("report")
197
+ DRAFT_WARNING: Final = (
198
+ "warning: redaction is disabled; the report is marked UNREDACTED DRAFT \N{EN DASH} "
199
+ "DO NOT DISTRIBUTE"
200
+ )
201
+
202
+
203
+ def _check_name(name: str) -> str:
204
+ if not NAME_RE.match(name) or name in {".", ".."}:
205
+ raise typer.BadParameter("must match ^[A-Za-z0-9._-]{1,100}$")
206
+ return name
207
+
208
+
209
+ def _size(n: int) -> str:
210
+ return f"{n} B" if n < 1024 else f"{n / 1024:.1f} KB"
211
+
212
+
213
+ @app.command()
214
+ def build(
215
+ file: Annotated[
216
+ Path,
217
+ typer.Argument(
218
+ help="The findings.yaml file to render.", exists=True, dir_okay=False, readable=True
219
+ ),
220
+ ],
221
+ formats: Annotated[
222
+ list[BuildFormat] | None,
223
+ typer.Option("--format", "-f", help="html, pdf, md or all; repeatable. Default: all."),
224
+ ] = None,
225
+ output_dir: Annotated[
226
+ Path, typer.Option("--output-dir", "-o", help="Directory for the report files.")
227
+ ] = DEFAULT_OUTPUT_DIR,
228
+ name: Annotated[
229
+ str,
230
+ typer.Option(
231
+ "--name", "-n", callback=_check_name, help="Output file name without extension."
232
+ ),
233
+ ] = "pentest-report",
234
+ template_dir: Annotated[
235
+ Path | None,
236
+ typer.Option(
237
+ "--template-dir",
238
+ exists=True,
239
+ file_okay=False,
240
+ help="Templates that override the theme.",
241
+ ),
242
+ ] = None,
243
+ paper: Annotated[Paper, typer.Option("--paper", help="PDF page size.")] = Paper.A4,
244
+ no_redact: Annotated[
245
+ bool, typer.Option("--no-redact", help="Disable redaction (marks an UNREDACTED DRAFT).")
246
+ ] = False,
247
+ strict: Annotated[bool, typer.Option("--strict", help="Fail on validation warnings.")] = False,
248
+ quiet: Annotated[bool, typer.Option("--quiet", "-q", help="Print only errors.")] = False,
249
+ ) -> None:
250
+ """Validate FILE and render the report as HTML, Markdown and PDF (FR-03)."""
251
+ import jinja2 # imported lazily so --help stays fast (NFR-04)
252
+
253
+ from pentrep.render.html import render_html
254
+ from pentrep.render.md import render_md
255
+ from pentrep.render.pdf import RenderError, render_pdf
256
+
257
+ wanted = set(formats or [BuildFormat.ALL])
258
+ if BuildFormat.ALL in wanted:
259
+ wanted = {BuildFormat.HTML, BuildFormat.MD, BuildFormat.PDF}
260
+
261
+ result = load_report(file, display=str(file))
262
+ failed = bool(result.errors) or (strict and bool(result.warnings))
263
+ for diagnostic in result.diagnostics:
264
+ if failed or not quiet or diagnostic.code.level.value == "error":
265
+ typer.echo(format_text(diagnostic), err=True)
266
+ if failed or result.report is None:
267
+ errors, warnings = len(result.errors), len(result.warnings)
268
+ typer.echo(
269
+ f"✗ {file} is invalid: {_count(errors, 'error')}, {_count(warnings, 'warning')}",
270
+ err=True,
271
+ )
272
+ raise typer.Exit(ExitCode.VALIDATION_FAILED)
273
+
274
+ report, summary = redact_report(result.report, enabled=False if no_redact else None)
275
+ if not summary.enabled:
276
+ typer.echo(DRAFT_WARNING, err=True)
277
+ base_dir = file.parent
278
+ outputs: list[tuple[Path, bytes]] = []
279
+ copies: list[tuple[Path, Path]] = []
280
+ html = ""
281
+ try:
282
+ if wanted & {BuildFormat.HTML, BuildFormat.PDF}:
283
+ html = render_html(report, summary, base_dir, template_dir)
284
+ if BuildFormat.HTML in wanted:
285
+ outputs.append((output_dir / f"{name}.html", html.encode("utf-8")))
286
+ if BuildFormat.MD in wanted:
287
+ markdown = render_md(report, summary, base_dir, template_dir)
288
+ outputs.append((output_dir / f"{name}.md", markdown.text.encode("utf-8")))
289
+ copies.extend((source, output_dir / relative) for source, relative in markdown.assets)
290
+ except jinja2.TemplateError as exc:
291
+ raise _fail(f"error: template error: {exc}", ExitCode.RENDER_ERROR) from None
292
+ written = _write_outputs(outputs, copies, output_dir)
293
+ pdf_error: RenderError | None = None
294
+ if BuildFormat.PDF in wanted:
295
+ try:
296
+ pdf_bytes = render_pdf(html, paper=paper.value)
297
+ except RenderError as exc:
298
+ pdf_error = exc
299
+ else:
300
+ written += _write_outputs([(output_dir / f"{name}.pdf", pdf_bytes)], [], output_dir)
301
+ if not quiet:
302
+ for path in written:
303
+ typer.echo(f"Wrote {path.as_posix()} ({_size(path.stat().st_size)})")
304
+ for line in format_summary(summary):
305
+ typer.echo(line)
306
+ if pdf_error is not None:
307
+ written_note = " (the other requested formats were written)" if written else ""
308
+ raise _fail(
309
+ f"error: {pdf_error}{written_note}\n hint: {pdf_error.hint}", ExitCode.RENDER_ERROR
310
+ )
311
+
312
+
313
+ def _write_outputs(
314
+ outputs: list[tuple[Path, bytes]], copies: list[tuple[Path, Path]], output_dir: Path
315
+ ) -> list[Path]:
316
+ """Write files and copy assets; an OSError becomes exit code 3."""
317
+ written: list[Path] = []
318
+ try:
319
+ for path, data in outputs:
320
+ path.parent.mkdir(parents=True, exist_ok=True)
321
+ path.write_bytes(data)
322
+ written.append(path)
323
+ for source, target in copies:
324
+ target.parent.mkdir(parents=True, exist_ok=True)
325
+ shutil.copyfile(source, target)
326
+ written.append(target)
327
+ except OSError as exc:
328
+ raise _fail(f"error: cannot write to {output_dir}: {exc}", ExitCode.RENDER_ERROR) from None
329
+ return written
330
+
331
+
332
+ def run(cli_app: typer.Typer, argv: Sequence[str]) -> int:
333
+ """Run ``cli_app`` with ``argv`` and return its exit code (FR-00c, FR-00d).
334
+
335
+ Unexpected exceptions become exit code 3 with a one-line message, unless
336
+ ``--debug`` was given, in which case they propagate with a full traceback.
337
+ """
338
+ _state.debug = False
339
+ try:
340
+ cli_app(args=list(argv), prog_name="pentrep")
341
+ except SystemExit as exc:
342
+ return exc.code if isinstance(exc.code, int) else ExitCode.OK
343
+ except Exception as exc:
344
+ if _state.debug:
345
+ raise
346
+ typer.echo(f"internal error: {exc} (re-run with --debug for details)", err=True)
347
+ return ExitCode.RENDER_ERROR
348
+ return ExitCode.OK # pragma: no cover - Click's standalone mode always raises SystemExit
349
+
350
+
351
+ def main() -> None:
352
+ """Console-script entry point."""
353
+ sys.exit(run(app, sys.argv[1:]))
pentrep/cvss.py ADDED
@@ -0,0 +1,313 @@
1
+ """CVSS 3.1 base score calculator (FIRST specification, PRD §4.3). No third-party CVSS code."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from dataclasses import dataclass
7
+ from enum import Enum
8
+ from typing import Final
9
+
10
+ from pentrep.diagnostics import ErrorCode, Level
11
+
12
+
13
+ def roundup(value: float) -> float:
14
+ """Round up to one decimal using the integer algorithm from spec Appendix A.
15
+
16
+ Working on ``round(value * 100000)`` removes floating-point noise, so 4.000000000000001
17
+ rounds to 4.0 instead of 4.1.
18
+ """
19
+ integer = round(value * 100_000)
20
+ if integer % 10_000 == 0:
21
+ return integer / 100_000
22
+ return (math.floor(integer / 10_000) + 1) / 10
23
+
24
+
25
+ # --- Vector parsing (FR-21) ---------------------------------------------------------------------
26
+
27
+ PREFIX: Final = "CVSS:3.1/"
28
+ EXAMPLE_VECTOR: Final = "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H"
29
+
30
+ _IMPACT_VALUES: Final = {"H": "High", "L": "Low", "N": "None"}
31
+ # Base metrics in specification order, each with its values (in spec order) and their names.
32
+ BASE_METRICS: Final[dict[str, dict[str, str]]] = {
33
+ "AV": {"N": "Network", "A": "Adjacent", "L": "Local", "P": "Physical"},
34
+ "AC": {"L": "Low", "H": "High"},
35
+ "PR": {"N": "None", "L": "Low", "H": "High"},
36
+ "UI": {"N": "None", "R": "Required"},
37
+ "S": {"U": "Unchanged", "C": "Changed"},
38
+ "C": _IMPACT_VALUES,
39
+ "I": _IMPACT_VALUES,
40
+ "A": _IMPACT_VALUES,
41
+ }
42
+ IGNORED_METRICS: Final = frozenset(
43
+ ("E", "RL", "RC", "CR", "IR", "AR", "MAV", "MAC", "MPR", "MUI", "MS", "MC", "MI", "MA")
44
+ )
45
+ _BASE_LIST: Final = ", ".join(BASE_METRICS)
46
+
47
+
48
+ def _values_hint(metric: str) -> str:
49
+ choices = ", ".join(f"{code} ({name})" for code, name in BASE_METRICS[metric].items())
50
+ return f"{metric} must be one of {choices}"
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class CvssIssue:
55
+ """A problem found while parsing a vector: an E2xx error or the W201 warning."""
56
+
57
+ code: ErrorCode
58
+ message: str
59
+ hint: str | None = None
60
+
61
+
62
+ @dataclass(frozen=True)
63
+ class CvssVector:
64
+ """A valid CVSS 3.1 base vector: one value for each of the 8 base metrics."""
65
+
66
+ values: tuple[tuple[str, str], ...] # (metric, value) in specification order
67
+
68
+ def __getitem__(self, metric: str) -> str:
69
+ """The value of a base metric, for example ``vector["AV"] == "N"``."""
70
+ return dict(self.values)[metric]
71
+
72
+ def canonical(self) -> str:
73
+ """The vector with metrics in specification order and ignored metrics removed (FR-25)."""
74
+ return PREFIX + "/".join(f"{metric}:{value}" for metric, value in self.values)
75
+
76
+
77
+ @dataclass(frozen=True)
78
+ class ParseResult:
79
+ """The parsed vector (``None`` if there is any error) and every issue found."""
80
+
81
+ vector: CvssVector | None
82
+ issues: tuple[CvssIssue, ...]
83
+
84
+
85
+ def _prefix_issue(text: str) -> CvssIssue | None:
86
+ if text.startswith(PREFIX):
87
+ return None
88
+ version = text.split("/", 1)[0].removeprefix("CVSS:") if text.startswith("CVSS:") else None
89
+ if version == "3.0":
90
+ return CvssIssue(
91
+ ErrorCode.E201,
92
+ "CVSS version 3.0 is not supported",
93
+ "change the prefix to 'CVSS:3.1/'; the 3.0 and 3.1 base metrics are the same",
94
+ )
95
+ if version is not None:
96
+ return CvssIssue(
97
+ ErrorCode.E201,
98
+ f"unsupported CVSS version '{version}'",
99
+ f"only CVSS 3.1 vectors are supported, for example {EXAMPLE_VECTOR}",
100
+ )
101
+ return CvssIssue(
102
+ ErrorCode.E201, f"vector must start with '{PREFIX}'", f"for example {EXAMPLE_VECTOR}"
103
+ )
104
+
105
+
106
+ def parse_vector(text: str) -> ParseResult:
107
+ """Parse a CVSS 3.1 vector, collecting every E201-E205 error and the W201 warning (FR-21)."""
108
+ text = text.strip()
109
+ prefix_issue = _prefix_issue(text)
110
+ if prefix_issue:
111
+ return ParseResult(None, (prefix_issue,))
112
+ issues: list[CvssIssue] = []
113
+ found: dict[str, str] = {}
114
+ accounted: set[str] = set() # base metrics present (even with a bad value or wrong case)
115
+ ignored: list[str] = []
116
+ rest = text[len(PREFIX) :]
117
+ reported_empty = False
118
+ for segment in rest.split("/") if rest else []:
119
+ metric, sep, value = segment.partition(":")
120
+ if not sep or not metric:
121
+ if segment or not reported_empty:
122
+ shown = f"'{segment}'" if segment else "empty metric (double or trailing '/')"
123
+ issues.append(
124
+ CvssIssue(
125
+ ErrorCode.E202,
126
+ f"malformed metric {shown}; expected METRIC:VALUE",
127
+ f"base metrics are {_BASE_LIST}",
128
+ )
129
+ )
130
+ reported_empty = reported_empty or not segment
131
+ continue
132
+ if metric in IGNORED_METRICS:
133
+ if metric not in ignored:
134
+ ignored.append(metric)
135
+ elif metric not in BASE_METRICS:
136
+ hint = f"base metrics are {_BASE_LIST}"
137
+ if metric.upper() in BASE_METRICS:
138
+ hint = f"metric names are case-sensitive: did you mean '{metric.upper()}'?"
139
+ accounted.add(metric.upper())
140
+ issues.append(CvssIssue(ErrorCode.E202, f"unknown CVSS metric '{metric}'", hint))
141
+ elif metric in accounted:
142
+ issues.append(
143
+ CvssIssue(
144
+ ErrorCode.E205,
145
+ f"duplicate CVSS metric '{metric}'",
146
+ "each metric may appear only once",
147
+ )
148
+ )
149
+ else:
150
+ accounted.add(metric)
151
+ if value in BASE_METRICS[metric]:
152
+ found[metric] = value
153
+ else:
154
+ issues.append(
155
+ CvssIssue(
156
+ ErrorCode.E203,
157
+ f"invalid value '{value}' for metric '{metric}'",
158
+ _values_hint(metric),
159
+ )
160
+ )
161
+ missing = [m for m in BASE_METRICS if m not in accounted]
162
+ if len(missing) == 1:
163
+ issues.append(
164
+ CvssIssue(
165
+ ErrorCode.E204, f"missing CVSS base metric '{missing[0]}'", _values_hint(missing[0])
166
+ )
167
+ )
168
+ elif missing:
169
+ issues.append(
170
+ CvssIssue(
171
+ ErrorCode.E204,
172
+ f"missing CVSS base metrics: {', '.join(missing)}",
173
+ "a base vector needs all of AV, AC, PR, UI, S, C, I and A",
174
+ )
175
+ )
176
+ if ignored:
177
+ issues.append(
178
+ CvssIssue(
179
+ ErrorCode.W201,
180
+ f"temporal/environmental metrics are ignored in v0.1: {', '.join(ignored)}",
181
+ "only the base score is calculated; remove them to silence this warning",
182
+ )
183
+ )
184
+ has_error = any(i.code.level is Level.ERROR for i in issues)
185
+ vector = None if has_error else CvssVector(tuple((m, found[m]) for m in BASE_METRICS))
186
+ return ParseResult(vector, tuple(issues))
187
+
188
+
189
+ # --- Severity (FR-24) ---------------------------------------------------------------------------
190
+
191
+
192
+ class Severity(Enum):
193
+ """Qualitative severity. None and Informational share the lowest rank."""
194
+
195
+ NONE = ("None", 0)
196
+ INFORMATIONAL = ("Informational", 0)
197
+ LOW = ("Low", 1)
198
+ MEDIUM = ("Medium", 2)
199
+ HIGH = ("High", 3)
200
+ CRITICAL = ("Critical", 4)
201
+
202
+ def __init__(self, label: str, rank: int) -> None:
203
+ self.label = label
204
+ self.rank = rank
205
+
206
+ def __str__(self) -> str:
207
+ return self.label
208
+
209
+ @classmethod
210
+ def from_score(cls, score: float) -> Severity:
211
+ """The severity band of a base score (0.0 is None)."""
212
+ if not 0.0 <= score <= 10.0:
213
+ raise ValueError(f"CVSS score must be between 0.0 and 10.0, got {score}")
214
+ if score == 0.0:
215
+ return cls.NONE
216
+ if score < 4.0:
217
+ return cls.LOW
218
+ if score < 7.0:
219
+ return cls.MEDIUM
220
+ if score < 9.0:
221
+ return cls.HIGH
222
+ return cls.CRITICAL
223
+
224
+ def __lt__(self, other: object) -> bool:
225
+ if not isinstance(other, Severity):
226
+ return NotImplemented
227
+ return self.rank < other.rank
228
+
229
+ def __le__(self, other: object) -> bool:
230
+ if not isinstance(other, Severity):
231
+ return NotImplemented
232
+ return self.rank <= other.rank
233
+
234
+ def __gt__(self, other: object) -> bool:
235
+ if not isinstance(other, Severity):
236
+ return NotImplemented
237
+ return self.rank > other.rank
238
+
239
+ def __ge__(self, other: object) -> bool:
240
+ if not isinstance(other, Severity):
241
+ return NotImplemented
242
+ return self.rank >= other.rank
243
+
244
+
245
+ # --- Scoring (FR-22, FR-23) ---------------------------------------------------------------------
246
+
247
+ _WEIGHTS: Final[dict[str, dict[str, float]]] = {
248
+ "AV": {"N": 0.85, "A": 0.62, "L": 0.55, "P": 0.20},
249
+ "AC": {"L": 0.77, "H": 0.44},
250
+ "PR": {"N": 0.85, "L": 0.62, "H": 0.27},
251
+ "UI": {"N": 0.85, "R": 0.62},
252
+ "C": {"H": 0.56, "L": 0.22, "N": 0.0},
253
+ "I": {"H": 0.56, "L": 0.22, "N": 0.0},
254
+ "A": {"H": 0.56, "L": 0.22, "N": 0.0},
255
+ }
256
+ _PR_CHANGED_SCOPE: Final = {"N": 0.85, "L": 0.68, "H": 0.50}
257
+ SCOPE_COEFFICIENT: Final = 1.08
258
+
259
+
260
+ def weights(vector: CvssVector) -> dict[str, float]:
261
+ """Numeric weight of each metric except S. PR depends on scope (FR-22)."""
262
+ result = {metric: table[vector[metric]] for metric, table in _WEIGHTS.items()}
263
+ if vector["S"] == "C":
264
+ result["PR"] = _PR_CHANGED_SCOPE[vector["PR"]]
265
+ return result
266
+
267
+
268
+ def round_one_decimal(value: float) -> float:
269
+ """Round half up to one decimal (for sub-scores), ignoring float noise like Roundup does."""
270
+ integer = round(value * 100_000)
271
+ return math.floor((integer + 5_000) / 10_000) / 10
272
+
273
+
274
+ @dataclass(frozen=True)
275
+ class CvssScore:
276
+ """The base score and sub-scores of a vector (FR-23, FR-25)."""
277
+
278
+ vector: CvssVector
279
+ base_score: float
280
+ iss: float
281
+ impact_raw: float
282
+ exploitability_raw: float
283
+
284
+ @property
285
+ def severity(self) -> Severity:
286
+ """Severity band of the base score."""
287
+ return Severity.from_score(self.base_score)
288
+
289
+ @property
290
+ def impact(self) -> float:
291
+ """Impact sub-score, one decimal; a negative value is shown as 0.0."""
292
+ return round_one_decimal(max(self.impact_raw, 0.0))
293
+
294
+ @property
295
+ def exploitability(self) -> float:
296
+ """Exploitability sub-score, one decimal."""
297
+ return round_one_decimal(self.exploitability_raw)
298
+
299
+
300
+ def calculate(vector: CvssVector) -> CvssScore:
301
+ """Compute the CVSS 3.1 base score with the equations of spec Section 7.1."""
302
+ w = weights(vector)
303
+ iss = 1 - (1 - w["C"]) * (1 - w["I"]) * (1 - w["A"])
304
+ changed = vector["S"] == "C"
305
+ impact = 7.52 * (iss - 0.029) - 3.25 * (iss - 0.02) ** 15 if changed else 6.42 * iss
306
+ exploitability = 8.22 * w["AV"] * w["AC"] * w["PR"] * w["UI"]
307
+ if impact <= 0:
308
+ base = 0.0
309
+ elif changed:
310
+ base = roundup(min(SCOPE_COEFFICIENT * (impact + exploitability), 10))
311
+ else:
312
+ base = roundup(min(impact + exploitability, 10))
313
+ return CvssScore(vector, base, iss, impact, exploitability)