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.
- pentrep/__init__.py +3 -0
- pentrep/__main__.py +6 -0
- pentrep/cli.py +353 -0
- pentrep/cvss.py +313 -0
- pentrep/diagnostics.py +142 -0
- pentrep/loader.py +532 -0
- pentrep/models.py +358 -0
- pentrep/redact.py +320 -0
- pentrep/render/__init__.py +54 -0
- pentrep/render/context.py +200 -0
- pentrep/render/highlight.py +62 -0
- pentrep/render/html.py +34 -0
- pentrep/render/markdown.py +58 -0
- pentrep/render/md.py +172 -0
- pentrep/render/pdf.py +116 -0
- pentrep/scaffold/assets/logo.png +0 -0
- pentrep/scaffold/evidence/pt-001-sqlmap.png +0 -0
- pentrep/scaffold/findings.yaml +119 -0
- pentrep/stats.py +70 -0
- pentrep/themes/classic/fonts/OFL.txt +104 -0
- pentrep/themes/classic/fonts/SourceCodePro-Regular.ttf +0 -0
- pentrep/themes/classic/fonts/SourceSans3-Bold.ttf +0 -0
- pentrep/themes/classic/fonts/SourceSans3-It.ttf +0 -0
- pentrep/themes/classic/fonts/SourceSans3-Regular.ttf +0 -0
- pentrep/themes/classic/fonts.css +7 -0
- pentrep/themes/classic/partials/appendix.html.j2 +38 -0
- pentrep/themes/classic/partials/cover.html.j2 +17 -0
- pentrep/themes/classic/partials/document_control.html.j2 +22 -0
- pentrep/themes/classic/partials/executive_summary.html.j2 +17 -0
- pentrep/themes/classic/partials/finding.html.j2 +56 -0
- pentrep/themes/classic/partials/macros.html.j2 +7 -0
- pentrep/themes/classic/partials/scope.html.j2 +27 -0
- pentrep/themes/classic/partials/summary_table.html.j2 +13 -0
- pentrep/themes/classic/partials/toc.html.j2 +19 -0
- pentrep/themes/classic/report.html.j2 +35 -0
- pentrep/themes/classic/report.md.j2 +187 -0
- pentrep/themes/classic/style.css +97 -0
- pentrep-0.1.0.dist-info/METADATA +142 -0
- pentrep-0.1.0.dist-info/RECORD +42 -0
- pentrep-0.1.0.dist-info/WHEEL +4 -0
- pentrep-0.1.0.dist-info/entry_points.txt +2 -0
- pentrep-0.1.0.dist-info/licenses/LICENSE +21 -0
pentrep/models.py
ADDED
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
"""Pydantic models for ``findings.yaml`` (PRD §4.2.2).
|
|
2
|
+
|
|
3
|
+
Models are strict (no type coercion) and forbid unknown keys. Custom rule violations are raised
|
|
4
|
+
as :class:`PydanticCustomError` whose ``type`` is the pentrep error code (for example ``E105``),
|
|
5
|
+
so the loader can map them to diagnostics.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import datetime as dt
|
|
11
|
+
import os
|
|
12
|
+
import re
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from typing import Annotated, Final, Literal
|
|
15
|
+
|
|
16
|
+
from pydantic import (
|
|
17
|
+
BaseModel,
|
|
18
|
+
BeforeValidator,
|
|
19
|
+
ConfigDict,
|
|
20
|
+
Field,
|
|
21
|
+
ValidationInfo,
|
|
22
|
+
computed_field,
|
|
23
|
+
field_validator,
|
|
24
|
+
)
|
|
25
|
+
from pydantic_core import PydanticCustomError
|
|
26
|
+
|
|
27
|
+
from pentrep.cvss import CvssScore, calculate, parse_vector
|
|
28
|
+
from pentrep.diagnostics import ErrorCode, Level
|
|
29
|
+
from pentrep.redact import BUILTIN_NAMES, NAME_RE
|
|
30
|
+
|
|
31
|
+
ISO_DATE_LENGTH: Final = len("YYYY-MM-DD")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _parse_date(value: object) -> object:
|
|
35
|
+
"""Accept ``date`` objects and ``YYYY-MM-DD`` strings; reject date-times."""
|
|
36
|
+
if isinstance(value, dt.datetime):
|
|
37
|
+
raise ValueError("expected a date (YYYY-MM-DD), not a date and time")
|
|
38
|
+
if isinstance(value, str) and len(value) == ISO_DATE_LENGTH:
|
|
39
|
+
try:
|
|
40
|
+
return dt.date.fromisoformat(value)
|
|
41
|
+
except ValueError:
|
|
42
|
+
return value
|
|
43
|
+
return value
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
IsoDate = Annotated[dt.date, BeforeValidator(_parse_date)]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def default_report_date() -> dt.date:
|
|
50
|
+
"""Today, or the UTC date of ``SOURCE_DATE_EPOCH`` when it is set to an integer (FR-49)."""
|
|
51
|
+
epoch = os.environ.get("SOURCE_DATE_EPOCH", "").strip()
|
|
52
|
+
if epoch.isdigit():
|
|
53
|
+
return dt.datetime.fromtimestamp(int(epoch), tz=dt.UTC).date()
|
|
54
|
+
return dt.datetime.now(tz=dt.UTC).astimezone().date()
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class StrictModel(BaseModel):
|
|
58
|
+
"""Base for all schema models: strict types, unknown keys forbidden, immutable."""
|
|
59
|
+
|
|
60
|
+
model_config = ConfigDict(extra="forbid", strict=True, frozen=True)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class Client(StrictModel):
|
|
64
|
+
"""The client the engagement was performed for."""
|
|
65
|
+
|
|
66
|
+
name: str = Field(min_length=1, max_length=100)
|
|
67
|
+
contact: str | None = Field(default=None, max_length=150)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class Tester(StrictModel):
|
|
71
|
+
"""A member of the testing team."""
|
|
72
|
+
|
|
73
|
+
name: str = Field(min_length=1, max_length=100)
|
|
74
|
+
email: str | None = Field(default=None, pattern=r"^[^@\s]+@[^@\s]+\.[^@\s]+$", max_length=254)
|
|
75
|
+
role: str | None = Field(default=None, max_length=100)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
AssetType = Literal["url", "ip", "cidr", "hostname", "api", "mobile_app", "other"]
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class Asset(StrictModel):
|
|
82
|
+
"""An in-scope or out-of-scope target."""
|
|
83
|
+
|
|
84
|
+
asset: str = Field(min_length=1, max_length=500)
|
|
85
|
+
type: AssetType
|
|
86
|
+
notes: str | None = Field(default=None, max_length=500)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class Scope(StrictModel):
|
|
90
|
+
"""What was (and was not) tested."""
|
|
91
|
+
|
|
92
|
+
in_scope: list[Asset] = Field(min_length=1)
|
|
93
|
+
out_of_scope: list[Asset] = Field(default_factory=list)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class Engagement(StrictModel):
|
|
97
|
+
"""Engagement metadata shown on the cover and in document control."""
|
|
98
|
+
|
|
99
|
+
title: str = Field(min_length=5, max_length=150)
|
|
100
|
+
client: Client
|
|
101
|
+
testers: list[Tester] = Field(min_length=1, max_length=10)
|
|
102
|
+
start_date: IsoDate
|
|
103
|
+
end_date: IsoDate
|
|
104
|
+
report_date: IsoDate = Field(default_factory=default_report_date)
|
|
105
|
+
report_version: str = Field(default="1.0", pattern=r"^\d+\.\d+$")
|
|
106
|
+
classification: str = Field(default="CONFIDENTIAL", min_length=1, max_length=40)
|
|
107
|
+
scope: Scope
|
|
108
|
+
methodology: str = Field(min_length=20)
|
|
109
|
+
executive_summary: str | None = None
|
|
110
|
+
|
|
111
|
+
@field_validator("end_date")
|
|
112
|
+
@classmethod
|
|
113
|
+
def _end_not_before_start(cls, end: dt.date, info: ValidationInfo) -> dt.date:
|
|
114
|
+
start = info.data.get("start_date")
|
|
115
|
+
if isinstance(start, dt.date) and end < start:
|
|
116
|
+
raise PydanticCustomError(
|
|
117
|
+
"E105",
|
|
118
|
+
"end_date {end} is before start_date {start}",
|
|
119
|
+
{"end": end.isoformat(), "start": start.isoformat()},
|
|
120
|
+
)
|
|
121
|
+
return end
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class Branding(StrictModel):
|
|
125
|
+
"""Optional report branding."""
|
|
126
|
+
|
|
127
|
+
company_name: str | None = Field(default=None, min_length=1, max_length=80)
|
|
128
|
+
logo: str | None = Field(default=None, min_length=1)
|
|
129
|
+
accent_color: str = Field(default="#1F4E79", pattern=r"^#[0-9A-Fa-f]{6}$")
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
NonEmptyStr = Annotated[str, Field(min_length=1)]
|
|
133
|
+
HttpUrlStr = Annotated[str, Field(pattern=r"^https?://[^\s/?#]+[^\s]*$", max_length=2000)]
|
|
134
|
+
CweId = Annotated[int, Field(ge=1, le=9999)]
|
|
135
|
+
MAX_EVIDENCE_CONTENT: Final = 200 * 1024
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
class _EvidenceBase(StrictModel):
|
|
139
|
+
caption: str = Field(min_length=3, max_length=200)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
class TextEvidence(_EvidenceBase):
|
|
143
|
+
"""Plain text or code evidence, rendered in a monospaced block."""
|
|
144
|
+
|
|
145
|
+
type: Literal["text"]
|
|
146
|
+
content: str = Field(min_length=1, max_length=MAX_EVIDENCE_CONTENT)
|
|
147
|
+
language: str | None = Field(default=None, min_length=1, max_length=40)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
class HttpEvidence(_EvidenceBase):
|
|
151
|
+
"""An HTTP request/response pair, rendered with HTTP highlighting."""
|
|
152
|
+
|
|
153
|
+
type: Literal["http"]
|
|
154
|
+
content: str = Field(min_length=1, max_length=MAX_EVIDENCE_CONTENT)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class ImageEvidence(_EvidenceBase):
|
|
158
|
+
"""A screenshot or other image, referenced by a path relative to findings.yaml."""
|
|
159
|
+
|
|
160
|
+
type: Literal["image"]
|
|
161
|
+
path: str = Field(min_length=1)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
Evidence = Annotated[TextEvidence | HttpEvidence | ImageEvidence, Field(discriminator="type")]
|
|
165
|
+
EVIDENCE_TYPES: Final = (TextEvidence, HttpEvidence, ImageEvidence)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
class Finding(StrictModel):
|
|
169
|
+
"""One vulnerability. The vector/severity rule (E206) is checked by :func:`cross_checks`."""
|
|
170
|
+
|
|
171
|
+
id: str = Field(pattern=r"^[A-Z]{2,5}-\d{3,4}$")
|
|
172
|
+
title: str = Field(min_length=5, max_length=120)
|
|
173
|
+
cvss_vector: str | None = Field(default=None, min_length=1)
|
|
174
|
+
severity: Literal["informational"] | None = None
|
|
175
|
+
status: Literal["open", "remediated", "risk_accepted"] = "open"
|
|
176
|
+
cwe: list[CweId] = Field(default_factory=list)
|
|
177
|
+
affected_assets: list[NonEmptyStr] = Field(min_length=1)
|
|
178
|
+
description: str = Field(min_length=20)
|
|
179
|
+
impact: str = Field(min_length=20)
|
|
180
|
+
steps_to_reproduce: list[NonEmptyStr] = Field(min_length=1)
|
|
181
|
+
evidence: list[Evidence] = Field(default_factory=list, max_length=30)
|
|
182
|
+
remediation: str = Field(min_length=20)
|
|
183
|
+
references: list[HttpUrlStr] = Field(default_factory=list)
|
|
184
|
+
|
|
185
|
+
@field_validator("cvss_vector")
|
|
186
|
+
@classmethod
|
|
187
|
+
def _valid_vector(cls, value: str | None) -> str | None:
|
|
188
|
+
"""Reject vectors with E2xx errors. All issues (and W201) are reported by the loader."""
|
|
189
|
+
if value is None:
|
|
190
|
+
return None
|
|
191
|
+
errors = [i for i in parse_vector(value).issues if i.code.level is Level.ERROR]
|
|
192
|
+
if errors:
|
|
193
|
+
raise PydanticCustomError(
|
|
194
|
+
errors[0].code.value,
|
|
195
|
+
"{message}",
|
|
196
|
+
{"message": errors[0].message, "hint": errors[0].hint},
|
|
197
|
+
)
|
|
198
|
+
return value
|
|
199
|
+
|
|
200
|
+
@computed_field # type: ignore[prop-decorator] # mypy does not model Pydantic's decorator
|
|
201
|
+
@property
|
|
202
|
+
def cvss(self) -> CvssScore | None:
|
|
203
|
+
"""Base score, sub-scores and severity of ``cvss_vector`` (``None`` if informational)."""
|
|
204
|
+
if self.cvss_vector is None:
|
|
205
|
+
return None
|
|
206
|
+
vector = parse_vector(self.cvss_vector).vector
|
|
207
|
+
return calculate(vector) if vector else None
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _e304(message: str, hint: str) -> PydanticCustomError:
|
|
211
|
+
return PydanticCustomError("E304", "{message}", {"message": message, "hint": hint})
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
class CustomPattern(StrictModel):
|
|
215
|
+
"""A user-defined redaction pattern (FR-33); problems are E304."""
|
|
216
|
+
|
|
217
|
+
name: str
|
|
218
|
+
regex: str
|
|
219
|
+
|
|
220
|
+
@field_validator("name")
|
|
221
|
+
@classmethod
|
|
222
|
+
def _valid_name(cls, name: str) -> str:
|
|
223
|
+
if not NAME_RE.match(name):
|
|
224
|
+
raise _e304(
|
|
225
|
+
f"invalid pattern name {name!r}",
|
|
226
|
+
"names match ^[A-Z][A-Z0-9_]{1,31}$, for example ACME_EMPLOYEE_ID",
|
|
227
|
+
)
|
|
228
|
+
if name in BUILTIN_NAMES:
|
|
229
|
+
raise _e304(
|
|
230
|
+
f"pattern name {name!r} is already used by a built-in pattern",
|
|
231
|
+
"choose another name, for example ACME_" + name,
|
|
232
|
+
)
|
|
233
|
+
return name
|
|
234
|
+
|
|
235
|
+
@field_validator("regex")
|
|
236
|
+
@classmethod
|
|
237
|
+
def _valid_regex(cls, regex: str) -> str:
|
|
238
|
+
try:
|
|
239
|
+
re.compile(regex)
|
|
240
|
+
except re.error as exc:
|
|
241
|
+
raise _e304(
|
|
242
|
+
f"invalid regex: {exc}",
|
|
243
|
+
"use Python re syntax; a (?P<value>...) group redacts only that part",
|
|
244
|
+
) from None
|
|
245
|
+
return regex
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
class Redaction(StrictModel):
|
|
249
|
+
"""Redaction settings (PRD §4.4)."""
|
|
250
|
+
|
|
251
|
+
enabled: bool = True
|
|
252
|
+
apply_to_all_text: bool = False
|
|
253
|
+
custom_patterns: list[CustomPattern] = Field(default_factory=list, max_length=50)
|
|
254
|
+
allowlist: list[str] = Field(default_factory=list, max_length=200)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
SUPPORTED_SCHEMA_VERSIONS: Final = (1,)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
class Report(StrictModel):
|
|
261
|
+
"""The whole ``findings.yaml`` document. Cross-item rules are in :func:`cross_checks`."""
|
|
262
|
+
|
|
263
|
+
schema_version: Literal[1]
|
|
264
|
+
engagement: Engagement
|
|
265
|
+
branding: Branding = Field(default_factory=Branding)
|
|
266
|
+
redaction: Redaction = Field(default_factory=Redaction)
|
|
267
|
+
findings: list[Finding] = Field(min_length=1, max_length=500)
|
|
268
|
+
|
|
269
|
+
@field_validator("schema_version", mode="before")
|
|
270
|
+
@classmethod
|
|
271
|
+
def _supported_version(cls, value: object) -> object:
|
|
272
|
+
if type(value) is not int or value not in SUPPORTED_SCHEMA_VERSIONS:
|
|
273
|
+
raise PydanticCustomError(
|
|
274
|
+
"E106",
|
|
275
|
+
"unsupported schema_version {value}; this pentrep release supports "
|
|
276
|
+
"schema_version: {supported}",
|
|
277
|
+
{"value": repr(value), "supported": ", ".join(map(str, SUPPORTED_SCHEMA_VERSIONS))},
|
|
278
|
+
)
|
|
279
|
+
return value
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
Loc = tuple[str | int, ...]
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
@dataclass(frozen=True)
|
|
286
|
+
class Issue:
|
|
287
|
+
"""A rule violation found outside Pydantic validation, located by ``loc``."""
|
|
288
|
+
|
|
289
|
+
code: ErrorCode
|
|
290
|
+
loc: Loc
|
|
291
|
+
message: str
|
|
292
|
+
hint: str | None = None
|
|
293
|
+
at_key: bool = False # point at the mapping key for ``loc`` rather than its value
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def cross_checks(data: object) -> list[Issue]:
|
|
297
|
+
"""Check rules that span fields or items on raw data: duplicate ids (E104), E206.
|
|
298
|
+
|
|
299
|
+
These run on the raw YAML data rather than inside the models, so they are reported even when
|
|
300
|
+
other fields of the same finding are invalid. Malformed input is skipped silently: the
|
|
301
|
+
models report it.
|
|
302
|
+
"""
|
|
303
|
+
findings = data.get("findings") if isinstance(data, dict) else None
|
|
304
|
+
if not isinstance(findings, list):
|
|
305
|
+
return []
|
|
306
|
+
issues: list[Issue] = []
|
|
307
|
+
first_index: dict[str, int] = {}
|
|
308
|
+
for index, item in enumerate(findings):
|
|
309
|
+
if not isinstance(item, dict):
|
|
310
|
+
continue
|
|
311
|
+
finding_id = item.get("id")
|
|
312
|
+
if isinstance(finding_id, str):
|
|
313
|
+
if finding_id in first_index:
|
|
314
|
+
issues.append(
|
|
315
|
+
Issue(
|
|
316
|
+
ErrorCode.E104,
|
|
317
|
+
("findings", index, "id"),
|
|
318
|
+
f"duplicate finding id '{finding_id}' "
|
|
319
|
+
f"(first used in findings[{first_index[finding_id]}])",
|
|
320
|
+
hint="every finding needs a unique id, for example PT-001, PT-002",
|
|
321
|
+
)
|
|
322
|
+
)
|
|
323
|
+
else:
|
|
324
|
+
first_index[finding_id] = index
|
|
325
|
+
has_vector = "cvss_vector" in item
|
|
326
|
+
has_severity = "severity" in item
|
|
327
|
+
if has_vector and has_severity:
|
|
328
|
+
issues.append(
|
|
329
|
+
Issue(
|
|
330
|
+
ErrorCode.E206,
|
|
331
|
+
("findings", index, "severity"),
|
|
332
|
+
"both 'cvss_vector' and 'severity' are set; use only one",
|
|
333
|
+
hint="'severity: informational' is only for findings without a CVSS vector",
|
|
334
|
+
at_key=True,
|
|
335
|
+
)
|
|
336
|
+
)
|
|
337
|
+
elif not has_vector and not has_severity:
|
|
338
|
+
issues.append(
|
|
339
|
+
Issue(
|
|
340
|
+
ErrorCode.E206,
|
|
341
|
+
("findings", index),
|
|
342
|
+
"finding needs either 'cvss_vector' or 'severity: informational'",
|
|
343
|
+
hint="add a CVSS 3.1 vector, e.g. "
|
|
344
|
+
"'CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H'",
|
|
345
|
+
)
|
|
346
|
+
)
|
|
347
|
+
return issues
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
JSON_SCHEMA_DIALECT: Final = "https://json-schema.org/draft/2020-12/schema"
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def json_schema() -> dict[str, object]:
|
|
354
|
+
"""JSON Schema (draft 2020-12) for findings.yaml, generated from :class:`Report` (FR-04)."""
|
|
355
|
+
schema: dict[str, object] = {"$schema": JSON_SCHEMA_DIALECT}
|
|
356
|
+
schema.update(Report.model_json_schema(mode="validation"))
|
|
357
|
+
schema["title"] = "pentrep findings.yaml" # replaces Pydantic's default title "Report"
|
|
358
|
+
return schema
|
pentrep/redact.py
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
"""Secret and PII redaction for evidence text (PRD §4.4).
|
|
2
|
+
|
|
3
|
+
Redaction is a safety net, not a guarantee: it is regex-based and can miss secrets.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import ipaddress
|
|
9
|
+
import re
|
|
10
|
+
from collections.abc import Callable, Collection, Iterator, Sequence
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from typing import TYPE_CHECKING, Final
|
|
13
|
+
|
|
14
|
+
if TYPE_CHECKING: # models imports this module, so only import it for type checking
|
|
15
|
+
from pentrep.models import Redaction, Report
|
|
16
|
+
|
|
17
|
+
NAME_RE: Final = re.compile(r"^[A-Z][A-Z0-9_]{1,31}$")
|
|
18
|
+
|
|
19
|
+
Span = tuple[int, int]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def token(name: str) -> str:
|
|
23
|
+
"""The replacement text for a redacted value (FR-31)."""
|
|
24
|
+
return f"[REDACTED:{name}]"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True)
|
|
28
|
+
class Pattern:
|
|
29
|
+
"""A named redaction rule. Lower ``priority`` numbers win on overlap (FR-32).
|
|
30
|
+
|
|
31
|
+
If the regex has groups whose names start with ``value``, only the first one that took part
|
|
32
|
+
in the match is redacted; otherwise (or if none took part) the whole match is. ``check`` can
|
|
33
|
+
reject a candidate value (for example a Luhn check), and ``finder`` replaces the regex
|
|
34
|
+
entirely for rules that a single regex cannot express.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
name: str
|
|
38
|
+
regex: re.Pattern[str]
|
|
39
|
+
priority: int
|
|
40
|
+
check: Callable[[str], bool] | None = None
|
|
41
|
+
finder: Callable[[str], Iterator[Span]] | None = None
|
|
42
|
+
|
|
43
|
+
def __post_init__(self) -> None:
|
|
44
|
+
if not NAME_RE.match(self.name):
|
|
45
|
+
raise ValueError(f"invalid pattern name {self.name!r}")
|
|
46
|
+
|
|
47
|
+
def spans(self, text: str) -> Iterator[Span]:
|
|
48
|
+
"""Yield the ``(start, end)`` of every value this pattern would redact."""
|
|
49
|
+
if self.finder is not None:
|
|
50
|
+
yield from self.finder(text)
|
|
51
|
+
return
|
|
52
|
+
value_groups = [g for g in self.regex.groupindex if g.startswith("value")]
|
|
53
|
+
for match in self.regex.finditer(text):
|
|
54
|
+
# A value group that did not take part (another alternative matched) means the
|
|
55
|
+
# whole match is redacted: when in doubt, hide more.
|
|
56
|
+
group = next((g for g in value_groups if match.group(g) is not None), None)
|
|
57
|
+
start, end = match.span(group) if group else match.span()
|
|
58
|
+
if start == end:
|
|
59
|
+
continue
|
|
60
|
+
if self.check is not None and not self.check(text[start:end]):
|
|
61
|
+
continue
|
|
62
|
+
yield start, end
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass(frozen=True)
|
|
66
|
+
class RedactedText:
|
|
67
|
+
"""Redacted text and the pattern name of each replaced value, in text order."""
|
|
68
|
+
|
|
69
|
+
text: str
|
|
70
|
+
names: tuple[str, ...]
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass(frozen=True, order=True)
|
|
74
|
+
class _Candidate:
|
|
75
|
+
priority: int
|
|
76
|
+
start: int
|
|
77
|
+
neg_length: int
|
|
78
|
+
name: str
|
|
79
|
+
keep: bool # allowlisted: protects its characters but is neither replaced nor counted
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def end(self) -> int:
|
|
83
|
+
return self.start - self.neg_length
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def redact_text(
|
|
87
|
+
text: str, patterns: Sequence[Pattern], allowlist: Collection[str] = ()
|
|
88
|
+
) -> RedactedText:
|
|
89
|
+
"""Replace every match with ``[REDACTED:NAME]`` (FR-31, FR-32, FR-34).
|
|
90
|
+
|
|
91
|
+
Candidates are taken by priority, then earliest start, then longest; a candidate that
|
|
92
|
+
overlaps an accepted one is dropped, so each character is redacted at most once. The result
|
|
93
|
+
does not depend on the order of ``patterns``.
|
|
94
|
+
"""
|
|
95
|
+
candidates = sorted(
|
|
96
|
+
_Candidate(p.priority, start, start - end, p.name, text[start:end] in allowlist)
|
|
97
|
+
for p in patterns
|
|
98
|
+
for start, end in p.spans(text)
|
|
99
|
+
)
|
|
100
|
+
accepted: list[_Candidate] = []
|
|
101
|
+
for cand in candidates:
|
|
102
|
+
if all(cand.end <= other.start or cand.start >= other.end for other in accepted):
|
|
103
|
+
accepted.append(cand)
|
|
104
|
+
replaced = sorted((c for c in accepted if not c.keep), key=lambda c: c.start)
|
|
105
|
+
parts: list[str] = []
|
|
106
|
+
position = 0
|
|
107
|
+
for cand in replaced:
|
|
108
|
+
parts += [text[position : cand.start], token(cand.name)]
|
|
109
|
+
position = cand.end
|
|
110
|
+
parts.append(text[position:])
|
|
111
|
+
return RedactedText("".join(parts), tuple(c.name for c in replaced))
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
# --- Built-in patterns (FR-32), in priority order ------------------------------------------------
|
|
115
|
+
|
|
116
|
+
_PRIVATE_KEY_RE: Final = re.compile(
|
|
117
|
+
# An unterminated block (truncated output) is redacted to the end of the text.
|
|
118
|
+
r"-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----"
|
|
119
|
+
r"(?:.*?-----END (?:[A-Z0-9]+ )*PRIVATE KEY-----|.*)",
|
|
120
|
+
re.DOTALL,
|
|
121
|
+
)
|
|
122
|
+
_JWT_RE: Final = re.compile(
|
|
123
|
+
r"(?<![A-Za-z0-9_-])eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*"
|
|
124
|
+
)
|
|
125
|
+
_BEARER_RE: Final = re.compile(
|
|
126
|
+
r"\bauthorization[ \t]*:[ \t]*(?:bearer|basic)[ \t]+(?P<value>[^\s'\"]+)", re.IGNORECASE
|
|
127
|
+
)
|
|
128
|
+
_COOKIE_LINE_RE: Final = re.compile(r"^[ \t]*(?:set-)?cookie[ \t]*:(?P<rest>[^\r\n]*)", re.I | re.M)
|
|
129
|
+
COOKIE_ATTRIBUTES: Final = frozenset(
|
|
130
|
+
("path", "domain", "expires", "max-age", "samesite", "httponly", "secure")
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _cookie_values(text: str) -> Iterator[Span]:
|
|
135
|
+
"""Values of ``name=value`` pairs on Cookie/Set-Cookie lines, keeping names and attributes."""
|
|
136
|
+
for line in _COOKIE_LINE_RE.finditer(text):
|
|
137
|
+
offset = line.start("rest")
|
|
138
|
+
for part in re.finditer(r"[^;]+", line.group("rest")):
|
|
139
|
+
name, sep, value = part.group().partition("=")
|
|
140
|
+
if not sep or name.strip().lower() in COOKIE_ATTRIBUTES or not value.strip():
|
|
141
|
+
continue
|
|
142
|
+
value_start = offset + part.start() + len(name) + 1
|
|
143
|
+
leading = len(value) - len(value.lstrip())
|
|
144
|
+
yield value_start + leading, value_start + len(value.rstrip())
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
_AWS_KEY_RE: Final = re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b")
|
|
148
|
+
_SECRET_RE: Final = re.compile(
|
|
149
|
+
r"(?<![A-Za-z0-9_])" # "-" may precede the key, as in the header X-Api-Key
|
|
150
|
+
r"(?:password|passwd|pwd|secret|api[_-]?key|access_token|refresh_token|client_secret)"
|
|
151
|
+
r"[\"']?[ \t]*[:=][ \t]*"
|
|
152
|
+
r"(?:\"(?P<value>[^\"\r\n]*)\"|'(?P<value2>[^'\r\n]*)'|(?P<value3>[^\s\"'&;,]+))",
|
|
153
|
+
re.IGNORECASE,
|
|
154
|
+
)
|
|
155
|
+
_CARD_RE: Final = re.compile(r"(?<![\d-])(?:\d[ -]?){12,18}\d(?![\d-])")
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def luhn_valid(digits: str) -> bool:
|
|
159
|
+
"""True if the digit string passes the Luhn checksum."""
|
|
160
|
+
total = 0
|
|
161
|
+
for position, char in enumerate(reversed(digits)):
|
|
162
|
+
n = int(char)
|
|
163
|
+
if position % 2:
|
|
164
|
+
n = n * 2 - 9 if n > 4 else n * 2
|
|
165
|
+
total += n
|
|
166
|
+
return total % 10 == 0
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _is_card_number(candidate: str) -> bool:
|
|
170
|
+
digits = re.sub(r"\D", "", candidate)
|
|
171
|
+
return 13 <= len(digits) <= 19 and luhn_valid(digits)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
_EMAIL_RE: Final = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
|
|
175
|
+
_IPV4_RE: Final = re.compile(r"(?<![\d.])(?:\d{1,3}\.){3}\d{1,3}(?!\.?\d)")
|
|
176
|
+
PRIVATE_NETWORKS: Final = tuple(
|
|
177
|
+
ipaddress.IPv4Network(net)
|
|
178
|
+
for net in ("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "169.254.0.0/16")
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _is_private_ip(candidate: str) -> bool:
|
|
183
|
+
"""True for RFC 1918 and link-local addresses (public, loopback and RFC 5737 are kept)."""
|
|
184
|
+
try:
|
|
185
|
+
address = ipaddress.IPv4Address(candidate)
|
|
186
|
+
except ValueError:
|
|
187
|
+
return False
|
|
188
|
+
return any(address in network for network in PRIVATE_NETWORKS)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
BUILTIN_PATTERNS: Final[tuple[Pattern, ...]] = (
|
|
192
|
+
Pattern("PRIVATE_KEY", _PRIVATE_KEY_RE, 1),
|
|
193
|
+
Pattern("JWT", _JWT_RE, 2),
|
|
194
|
+
Pattern("BEARER", _BEARER_RE, 3),
|
|
195
|
+
Pattern("COOKIE", _COOKIE_LINE_RE, 4, finder=_cookie_values),
|
|
196
|
+
Pattern("AWS_KEY", _AWS_KEY_RE, 5),
|
|
197
|
+
Pattern("SECRET", _SECRET_RE, 6),
|
|
198
|
+
Pattern("CARD", _CARD_RE, 7, check=_is_card_number),
|
|
199
|
+
Pattern("EMAIL", _EMAIL_RE, 8),
|
|
200
|
+
Pattern("PRIVATE_IP", _IPV4_RE, 9, check=_is_private_ip),
|
|
201
|
+
)
|
|
202
|
+
BUILTIN_NAMES: Final = frozenset(p.name for p in BUILTIN_PATTERNS)
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
# --- Configured redaction (FR-33, FR-34) -------------------------------------------------------
|
|
206
|
+
|
|
207
|
+
CUSTOM_PRIORITY_START: Final = 100
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def build_patterns(config: Redaction) -> tuple[Pattern, ...]:
|
|
211
|
+
"""Built-in patterns followed by the custom ones, which have lower priority (FR-33)."""
|
|
212
|
+
custom = tuple(
|
|
213
|
+
Pattern(item.name, re.compile(item.regex), CUSTOM_PRIORITY_START + index)
|
|
214
|
+
for index, item in enumerate(config.custom_patterns)
|
|
215
|
+
)
|
|
216
|
+
return BUILTIN_PATTERNS + custom
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
class Redactor:
|
|
220
|
+
"""Redacts text with the patterns and allowlist from a ``redaction`` config."""
|
|
221
|
+
|
|
222
|
+
def __init__(self, config: Redaction) -> None:
|
|
223
|
+
self.patterns = build_patterns(config)
|
|
224
|
+
self.allowlist = frozenset(config.allowlist)
|
|
225
|
+
|
|
226
|
+
def redact(self, text: str) -> RedactedText:
|
|
227
|
+
"""Redact ``text``; allowlisted values are kept and not counted."""
|
|
228
|
+
return redact_text(text, self.patterns, self.allowlist)
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
# --- Whole report (FR-30) ----------------------------------------------------------------------
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
@dataclass(frozen=True)
|
|
235
|
+
class RedactionSummary:
|
|
236
|
+
"""What was redacted: counts per pattern in order of first appearance (FR-35)."""
|
|
237
|
+
|
|
238
|
+
enabled: bool
|
|
239
|
+
counts: tuple[tuple[str, int], ...]
|
|
240
|
+
findings: int # findings with at least one redacted value
|
|
241
|
+
images_not_scanned: int
|
|
242
|
+
|
|
243
|
+
@property
|
|
244
|
+
def values(self) -> int:
|
|
245
|
+
"""Total number of redacted values."""
|
|
246
|
+
return sum(count for _, count in self.counts)
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def redact_report(report: Report, enabled: bool | None = None) -> tuple[Report, RedactionSummary]:
|
|
250
|
+
"""Redact the fields listed in FR-30 and summarise what was replaced.
|
|
251
|
+
|
|
252
|
+
Always: evidence ``content`` (text/http) and ``steps_to_reproduce``. With
|
|
253
|
+
``apply_to_all_text`` also ``description``, ``impact`` and ``remediation``. Metadata, titles,
|
|
254
|
+
affected assets and references are never touched. ``enabled`` overrides the config
|
|
255
|
+
(``--no-redact``). The input report is not modified.
|
|
256
|
+
"""
|
|
257
|
+
config = report.redaction
|
|
258
|
+
images = sum(1 for f in report.findings for e in f.evidence if e.type == "image")
|
|
259
|
+
if not (config.enabled if enabled is None else enabled):
|
|
260
|
+
return report, RedactionSummary(False, (), 0, images)
|
|
261
|
+
redactor = Redactor(config)
|
|
262
|
+
counts: dict[str, int] = {}
|
|
263
|
+
affected = 0
|
|
264
|
+
|
|
265
|
+
def scrub(text: str) -> str:
|
|
266
|
+
result = redactor.redact(text)
|
|
267
|
+
for name in result.names:
|
|
268
|
+
counts[name] = counts.get(name, 0) + 1
|
|
269
|
+
return result.text
|
|
270
|
+
|
|
271
|
+
findings = []
|
|
272
|
+
for finding in report.findings:
|
|
273
|
+
before = sum(counts.values())
|
|
274
|
+
update: dict[str, object] = {}
|
|
275
|
+
if config.apply_to_all_text:
|
|
276
|
+
update["description"] = scrub(finding.description)
|
|
277
|
+
update["impact"] = scrub(finding.impact)
|
|
278
|
+
update["steps_to_reproduce"] = [scrub(step) for step in finding.steps_to_reproduce]
|
|
279
|
+
update["evidence"] = [
|
|
280
|
+
item
|
|
281
|
+
if item.type == "image"
|
|
282
|
+
else item.model_copy(update={"content": scrub(item.content)})
|
|
283
|
+
for item in finding.evidence
|
|
284
|
+
]
|
|
285
|
+
if config.apply_to_all_text:
|
|
286
|
+
update["remediation"] = scrub(finding.remediation)
|
|
287
|
+
affected += sum(counts.values()) > before
|
|
288
|
+
findings.append(finding.model_copy(update=update))
|
|
289
|
+
redacted = report.model_copy(update={"findings": findings})
|
|
290
|
+
return redacted, RedactionSummary(True, tuple(counts.items()), affected, images)
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _plural(n: int, noun: str) -> str:
|
|
294
|
+
return f"{n} {noun}" if n == 1 else f"{n} {noun}s"
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def format_summary(summary: RedactionSummary, preview: bool = False) -> list[str]:
|
|
298
|
+
"""Summary lines for the CLI (FR-35). Only pattern names and counts, never values.
|
|
299
|
+
|
|
300
|
+
``preview`` words it for ``validate``, which redacts nothing.
|
|
301
|
+
"""
|
|
302
|
+
counts = ", ".join(f"{name}×{count}" for name, count in summary.counts)
|
|
303
|
+
where = f"{_plural(summary.values, 'value')} in {_plural(summary.findings, 'finding')}"
|
|
304
|
+
if not summary.enabled:
|
|
305
|
+
if preview:
|
|
306
|
+
return ["Redaction preview: redaction is disabled (redaction.enabled: false)"]
|
|
307
|
+
return ["Redaction is disabled: the report is an UNREDACTED DRAFT"]
|
|
308
|
+
if preview:
|
|
309
|
+
lines = [
|
|
310
|
+
f"Redaction preview: {where} would be redacted: {counts}"
|
|
311
|
+
if summary.values
|
|
312
|
+
else "Redaction preview: no values would be redacted"
|
|
313
|
+
]
|
|
314
|
+
else:
|
|
315
|
+
lines = [f"Redacted {where}: {counts}" if summary.values else "No values were redacted"]
|
|
316
|
+
if summary.images_not_scanned:
|
|
317
|
+
items = _plural(summary.images_not_scanned, "image evidence item")
|
|
318
|
+
verb = "was" if summary.images_not_scanned == 1 else "were"
|
|
319
|
+
lines.append(f"Note: {items} {verb} not scanned (image redaction is not supported in v0.1)")
|
|
320
|
+
return lines
|