98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285 | @dataclass
class DocxTplPerVulnBackend(ReportBackend):
"""
Render a main template and append a per-vulnerability template for each vuln.
Uses docxtpl + docxcompose.
Example:
>>> from wintermute.reports import Report, ReportSpec
>>> from wintermute.backends.docx_reports import DocxTplPerVulnBackend
>>> from wintermute.basemodels import CloudAccount, Peripheral
>>> from wintermute.findings import Vulnerability, ReproductionStep, Risk
>>> Report.register_backend(
... "word_tpl_per_vuln",
... DocxTplPerVulnBackend(
... template_dir="templates",
... main_template="report_main.docx",
... vuln_template="report_vuln.docx",
... ),
... make_default=True,
... )
>>> acct = CloudAccount(
>>> name="aws-prod",
... vulnerabilities=[
... Vulnerability(
... title="S3 bucket public",
... description="Bucket allows public read",
... risk=Risk(likelihood="High", impact="Medium", severity="High"),
... reproduction_steps=[
... ReproductionStep(title="List objects", tool="aws", action="s3 ls", arguments=["s3://bucket"])
... ],
... verified=True,
... )
... ],
... )
>>> periph = Peripheral(
... name="UART0",
... pType="UART",
... vulnerabilities=[
... Vulnerability(
... title="No console auth",
... description="UART console lacks auth",
... cvss=6,
... verified=False,
... )
... ],
... )
>>> spec = ReportSpec(
... title="Security Assessment – Q4",
... author="Enrique",
... summary="Overall posture is improving. Top issues: public S3 access, UART console auth.",
... )
>>> Report.save(spec, [acct, periph], "out.docx")
Attributes:
template_dir: Directory containing the docx templates.
main_template: Filename of the main report template.
vuln_template: Filename of the per-vulnerability template.
"""
template_dir: str
main_template: str = "report_main.docx"
vuln_template: str = "report_vuln.docx"
test_run_template: str = "report_test_run.docx"
_spec: Optional[ReportSpec] = None
_summary: str = ""
_vuln_contexts: List[Dict[str, Any]] = None # type: ignore[assignment]
_run_contexts: List[Dict[str, Any]] = None # type: ignore[assignment]
def __post_init__(self) -> None:
if self._vuln_contexts is None:
self._vuln_contexts = []
if self._run_contexts is None:
self._run_contexts = []
def begin(self, spec: ReportSpec) -> None:
self._spec = spec
self._summary = spec.summary or ""
self._vuln_contexts = []
self._run_contexts = []
def add_summary(self, text: str) -> None:
self._summary = text
def add_test_run(
self,
run: TestCaseRun,
test_case: Optional[TestCase] = None,
*,
context_path: Optional[str] = None,
) -> None:
# Helper to convert TestCaseRun to dict for docxtpl
d = run.to_dict()
d["context_path"] = context_path or ""
safe = _run_to_context(run, test_case, context_path)
self._run_contexts.append(safe)
def add_vulnerability(
self, vuln: Vulnerability, *, context_path: Optional[str] = None
) -> None:
self._vuln_contexts.append(_vuln_to_context(vuln, context_path))
# --- internal rendering helpers ---
def _render_main(self) -> DocxDocument:
assert self._spec is not None
tdir = Path(self.template_dir)
tpl = DocxTemplate(str(tdir / self.main_template))
context: Dict[str, Any] = {
"title": self._spec.title,
"author": self._spec.author or "",
"created_at": self._spec.created_at.strftime("%B %d, %Y"),
"summary": self._summary,
"options": self._spec.options,
}
tpl.render(context)
log.debug("Rendered main template with context: %s", context)
# Save to memory and re-open as python-docx Document for composition
bio = BytesIO()
tpl.save(bio)
bio.seek(0)
doc: DocxDocument = _DocxDocumentFactory(bio)
log.info("Main report document rendered successfully.")
return doc
def _render_content_docs(self) -> List[DocxDocument]:
tdir = Path(self.template_dir)
results: List[DocxDocument] = []
# Render whichever list has content based on the spec type
if self._spec and self._spec.report_type == ReportType.VULNERABILITY:
for ctx in self._vuln_contexts:
results.append(
self._render_single_template(tdir / self.vuln_template, ctx)
)
elif self._spec and self._spec.report_type == ReportType.TEST_PLAN:
for ctx in self._run_contexts:
results.append(
self._render_single_template(tdir / self.test_run_template, ctx)
)
return results
def _render_single_template(
self, tpl_path: Path, context: Dict[str, Any]
) -> DocxDocument:
tpl = DocxTemplate(str(tpl_path))
tpl.render(context)
bio = BytesIO()
tpl.save(bio)
bio.seek(0)
return _DocxDocumentFactory(bio)
def _compose(self) -> DocxDocument:
base = self._render_main()
comp = Composer(base)
header_text = None
assert self._spec is not None
if self._spec.report_type == ReportType.TEST_PLAN and self._run_contexts:
header_text = "Test Case Executions"
elif self._vuln_contexts:
header_text = "Vulnerabilities"
if header_text:
comp.doc.add_page_break()
comp.doc.add_heading(header_text, level=2)
for d in self._render_content_docs():
comp.append(d)
log.info("Composed final document with all content.")
return base
# --- public API ---
def finalize(self) -> bytes:
doc = self._compose() # DocxDocument (non-Optional)
out = BytesIO()
doc.save(out)
log.info("Finalized report document in memory.")
return out.getvalue()
def save(self, path: str) -> None:
doc = self._compose() # DocxDocument (non-Optional)
doc.save(path)
log.info(f"Saved report document to {path}")
|