Catalyst / admin/Synapse-NetscanXi 14.8 GB / 57.8 GB 40.0 GB free
Help Sign in

admin / Synapse-NetscanXi

public

Network Scanning, Vulnerability and Compliance Application

Code Issues Pull requests Pipelines Packages Security Insights Wiki Settings
Synapse-NetscanXi / NetscanXiVersion13 / app / exporter.py 28636 B · main
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
"""Export scan results as CSV, JSON or a branded PDF report (v7)."""

import csv
import io
import json
from datetime import datetime, timezone


def _pesc(text):
    """Escape text for use inside a ReportLab Paragraph (mini-HTML markup)."""
    s = "" if text is None else str(text)
    return (s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;"))


def to_json(scan, hosts, changes, top_vulns):
    return json.dumps({
        "scan": scan,
        "hosts": hosts,
        "changes": changes,
        "top_vulnerabilities": top_vulns,
    }, indent=2, default=str)


def host_to_json(scan, host):
    """v8: single-host focused report as JSON."""
    return json.dumps({
        "scan": {"id": (scan or {}).get("id"),
                 "target": (scan or {}).get("target"),
                 "profile": (scan or {}).get("profile"),
                 "scan_type": (scan or {}).get("scan_type") or "active",
                 "finished": (scan or {}).get("finished")},
        "host": host,
    }, indent=2, default=str)


def scan_type_label(scan):
    """v9: human label for the scan acquisition mode."""
    st = (scan or {}).get("scan_type") or "active"
    return "Passive" if st == "passive" else "Active"


def _container_detail(containers):
    """v12: flatten per-container name/image/IP/ports into one CSV cell.
    Each container rendered as: name[image] ip=<ips> ports=<published;internal>.
    """
    parts = []
    for c in containers or []:
        seg = c.get("name") or c.get("id") or "?"
        if c.get("image"):
            seg += f"[{c['image']}]"
        ips = c.get("ips") or []
        if ips:
            seg += " ip=" + ",".join(ips)
        pub = c.get("ports_published") or []
        intl = c.get("ports_internal") or []
        if not (pub or intl) and c.get("ports"):
            pub = c.get("ports")
        if pub or intl:
            pbits = []
            if pub:
                pbits.append("published " + ",".join(pub))
            if intl:
                pbits.append("internal " + ",".join(intl))
            seg += " ports=" + "; ".join(pbits)
        health = c.get("health")
        if health and health not in ("none", ""):
            seg += f" health={health}"
            if health == "unhealthy" and c.get("health_failing_streak"):
                seg += f"x{c['health_failing_streak']}"
        if c.get("state") and c.get("state") != "running":
            seg += f" ({c['state']})"
        parts.append(seg)
    return " | ".join(parts)


def to_csv(hosts, scan=None):
    buf = io.StringIO()
    w = csv.writer(buf)
    # v9: leading metadata row stating the scan type (Passive vs Active).
    st = scan_type_label(scan)
    w.writerow([f"# NetscanXi report - Scan type: {st}"])
    w.writerow(["Asset ID", "Scan Type", "IP", "Hostname", "Device Type",
                "Docker", "Containers", "Image CVEs", "Image KEV", "CIS Fail",
                "Container Detail",
                "OS", "OS Accuracy",
                "MAC", "Vendor", "Risk", "Open Ports", "Software",
                "Vuln Count", "Vulnerabilities",
                "CVE Descriptions", "Mitigations", "Advertised Services"])
    for h in hosts:
        software = "; ".join(s["name"] for s in h.get("software", []))
        dock = h.get("docker", {}) or {}
        docker_cell = ""
        dsum = dock.get("summary", {}) or {}
        cont_cell = img_cve_cell = img_kev_cell = cis_fail_cell = ""
        cont_detail_cell = ""
        if dock.get("is_docker"):
            docker_cell = f"yes ({dock.get('confidence','')})"
            if dock.get("version"):
                docker_cell += f" v{dock['version']}"
            if dock.get("api_exposed"):
                docker_cell += " API-exposed"
            # v10r1: deep container/image metrics.
            cont_cell = f"{dsum.get('containers_running',0)}/{dsum.get('containers',0)}"
            img_cve_cell = dsum.get("image_vulns", 0)
            img_kev_cell = dsum.get("image_kev", 0)
            cis_fail_cell = dsum.get("cis_fail", 0)
            # v12: per-container detail (name[image] ip=... ports=...).
            cont_detail_cell = _container_detail(dock.get("containers", []))
        vulns = "; ".join(
            f"{v['id']}{('('+str(v['cvss'])+')') if v.get('cvss') else ''}"
            f"{'[KEV]' if v.get('kev') else ''}"
            for v in h.get("vulns", [])
        )
        # v8: dedicated columns for CVE descriptions and remediation guidance.
        descriptions = " | ".join(
            f"{v['id']}: {v['description']}"
            for v in h.get("vulns", []) if v.get("description")
        )
        mitigations = " | ".join(
            f"{v['id']}: {v['mitigation']}"
            for v in h.get("vulns", []) if v.get("mitigation")
        )
        per_host_type = "Passive" if h.get("passive") else st
        risk = h.get("risk")
        risk_cell = "n/a" if risk is None else risk
        w.writerow([
            h.get("asset_id", ""), per_host_type,
            h.get("ip", ""), h.get("hostname", ""), h.get("device_type", ""),
            docker_cell, cont_cell, img_cve_cell, img_kev_cell, cis_fail_cell,
            cont_detail_cell,
            h.get("os", ""), h.get("os_accuracy", ""), h.get("mac", ""),
            h.get("vendor", ""), risk_cell,
            " | ".join(h.get("ports", [])), software,
            h.get("vuln_count", 0), vulns,
            descriptions, mitigations,
            "; ".join(h.get("advertised_services", [])),
        ])
    return buf.getvalue()


# ---------------------------------------------------------------------------
# Branded PDF report (v7)
# ---------------------------------------------------------------------------
BRAND_NAME = "NetscanXi"
BRAND_VERSION = "Version 12"
BRAND_GREEN = None  # set lazily once reportlab colors are available


def pdf_available():
    try:
        import reportlab  # noqa: F401
        return True
    except Exception:
        return False


def to_pdf(scan, hosts, changes, top_vulns, compliance_summary=None):
    """Render a branded PDF report. Returns raw PDF bytes.

    Raises RuntimeError if reportlab isn't installed (caller should fall back).
    """
    try:
        from reportlab.lib import colors
        from reportlab.lib.pagesizes import A4
        from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
        from reportlab.lib.units import mm
        from reportlab.platypus import (SimpleDocTemplate, Paragraph, Spacer,
                                        Table, TableStyle)
    except Exception as e:  # pragma: no cover
        raise RuntimeError(f"reportlab not available: {e}")

    green = colors.HexColor("#3fb950")
    dark = colors.HexColor("#1a212b")
    grey = colors.HexColor("#5a6675")
    danger = colors.HexColor("#d12d24")

    buf = io.BytesIO()
    doc = SimpleDocTemplate(buf, pagesize=A4, topMargin=18 * mm,
                            bottomMargin=16 * mm, leftMargin=15 * mm,
                            rightMargin=15 * mm,
                            title=f"{BRAND_NAME} {BRAND_VERSION} Report")
    styles = getSampleStyleSheet()
    h1 = ParagraphStyle("h1", parent=styles["Heading1"], textColor=dark, fontSize=20)
    h2 = ParagraphStyle("h2", parent=styles["Heading2"], textColor=green, fontSize=13,
                        spaceBefore=10)
    small = ParagraphStyle("small", parent=styles["Normal"], fontSize=8, textColor=grey)
    body = ParagraphStyle("body", parent=styles["Normal"], fontSize=9)

    story = []
    # --- Branded header ---
    story.append(Paragraph(f"{BRAND_NAME} <font color='#3fb950'>{BRAND_VERSION}</font>", h1))
    story.append(Paragraph("Network Security &amp; Compliance Report", body))
    gen = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
    when = "-"
    if scan and scan.get("finished"):
        when = datetime.fromtimestamp(scan["finished"], timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
    target = (scan or {}).get("target", "-")
    st = scan_type_label(scan)
    story.append(Paragraph(
        f"Generated: {gen} &nbsp;|&nbsp; Scan target: {target} &nbsp;|&nbsp; "
        f"Completed: {when}", small))
    story.append(Paragraph(
        f"<b>Scan type: <font color='#3fb950'>{st}</font></b> &nbsp; "
        + ("(passive: observed assets only - no ports/services/vulnerabilities)"
           if st == "Passive" else "(active: probed ports, services and vulnerabilities)"),
        small))
    story.append(Spacer(1, 8))

    # --- Executive summary ---
    story.append(Paragraph("Executive Summary", h2))
    total_vulns = sum(h.get("vuln_count", 0) for h in hosts)
    kev = sum(1 for h in hosts for v in h.get("vulns", []) if v.get("kev"))
    at_risk = (compliance_summary or {}).get("hosts_at_risk", "-")
    summ_rows = [
        ["Hosts discovered", str(len(hosts))],
        ["Total vulnerabilities", str(total_vulns)],
        ["Known-exploited (KEV)", str(kev)],
        ["Hosts at compliance risk", str(at_risk)],
    ]
    t = Table(summ_rows, colWidths=[70 * mm, 100 * mm])
    t.setStyle(TableStyle([
        ("FONTSIZE", (0, 0), (-1, -1), 9),
        ("TEXTCOLOR", (0, 0), (0, -1), grey),
        ("LINEBELOW", (0, 0), (-1, -1), 0.3, colors.HexColor("#d4dae0")),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 4),
        ("TOPPADDING", (0, 0), (-1, -1), 4),
    ]))
    story.append(t)

    # --- Compliance overview ---
    if compliance_summary and compliance_summary.get("frameworks"):
        story.append(Paragraph("Regulatory Compliance", h2))
        rows = [["Framework", "Pass", "Fail"]]
        for fw, d in compliance_summary["frameworks"].items():
            rows.append([fw, str(d.get("pass", 0)), str(d.get("fail", 0))])
        ct = Table(rows, colWidths=[90 * mm, 40 * mm, 40 * mm])
        ct.setStyle(TableStyle([
            ("BACKGROUND", (0, 0), (-1, 0), green),
            ("TEXTCOLOR", (0, 0), (-1, 0), colors.white),
            ("FONTSIZE", (0, 0), (-1, -1), 9),
            ("GRID", (0, 0), (-1, -1), 0.3, colors.HexColor("#d4dae0")),
            ("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.white, colors.HexColor("#f0f3f6")]),
            ("TOPPADDING", (0, 0), (-1, -1), 3),
            ("BOTTOMPADDING", (0, 0), (-1, -1), 3),
        ]))
        story.append(ct)

    # --- Host inventory ---
    story.append(Paragraph("Host Inventory", h2))
    rows = [["Asset ID", "IP", "Hostname", "OS", "Risk", "Vulns", "Compliance"]]
    for h in hosts:
        comp = (h.get("compliance") or {}).get("status", "-")
        risk = h.get("risk")
        risk_cell = "n/a" if risk is None else str(risk)
        comp_cell = "n/a" if comp == "n/a" else ("At risk" if comp == "at_risk" else "OK")
        rows.append([
            h.get("asset_id", ""),
            h.get("ip", ""), (h.get("hostname", "") or "-")[:22],
            (h.get("os", "") or "unknown")[:26], risk_cell,
            str(h.get("vuln_count", 0)), comp_cell,
        ])
    ht = Table(rows, colWidths=[20 * mm, 26 * mm, 30 * mm, 44 * mm, 14 * mm, 14 * mm, 22 * mm],
               repeatRows=1)
    ht.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, 0), dark),
        ("TEXTCOLOR", (0, 0), (-1, 0), colors.white),
        ("FONTSIZE", (0, 0), (-1, -1), 8),
        ("GRID", (0, 0), (-1, -1), 0.25, colors.HexColor("#d4dae0")),
        ("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.white, colors.HexColor("#f0f3f6")]),
        ("TOPPADDING", (0, 0), (-1, -1), 3),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 3),
    ]))
    story.append(ht)

    # --- Certificate expiry (v7) ---
    cert_rows = [["Host", "Port", "Subject", "Expires", "Days", "Status"]]
    for h in hosts:
        for c in h.get("certificates", []):
            if c.get("status") in ("expired", "expiring", "weak"):
                cert_rows.append([
                    h.get("ip", ""), c.get("port", ""),
                    (c.get("subject") or c.get("issuer") or "-")[:26],
                    (c.get("not_after") or "-")[:10],
                    str(c.get("days_left", "")), c.get("status", ""),
                ])
    if len(cert_rows) > 1:
        story.append(Paragraph("TLS Certificates Needing Attention", h2))
        cct = Table(cert_rows,
                    colWidths=[26 * mm, 16 * mm, 52 * mm, 24 * mm, 16 * mm, 22 * mm],
                    repeatRows=1)
        cct.setStyle(TableStyle([
            ("BACKGROUND", (0, 0), (-1, 0), danger),
            ("TEXTCOLOR", (0, 0), (-1, 0), colors.white),
            ("FONTSIZE", (0, 0), (-1, -1), 8),
            ("GRID", (0, 0), (-1, -1), 0.25, colors.HexColor("#d4dae0")),
            ("TOPPADDING", (0, 0), (-1, -1), 3),
            ("BOTTOMPADDING", (0, 0), (-1, -1), 3),
        ]))
        story.append(cct)

    # --- Domain Controllers (v7) ---
    dc_hosts = [h for h in hosts if (h.get("ad") or {}).get("is_dc")]
    if dc_hosts:
        story.append(Paragraph("Active Directory / Domain Controllers", h2))
        for h in dc_hosts:
            ad = h["ad"]
            story.append(Paragraph(
                f"<b>{h.get('ip','')}</b> &nbsp; domain: {ad.get('domain') or '-'} "
                f"&nbsp; forest: {ad.get('forest') or '-'}", body))
            for f in ad.get("findings", []):
                story.append(Paragraph(
                    f"&bull; [{f.get('severity','')}] {f.get('title','')} — "
                    f"{f.get('detail','')}", small))
            story.append(Spacer(1, 4))

    # --- Vulnerability detail: CVE descriptions + mitigations (v8) ---
    cell = ParagraphStyle("cell", parent=styles["Normal"], fontSize=7.5, leading=9.5)
    cell_b = ParagraphStyle("cellb", parent=cell, textColor=colors.white)
    vuln_rows = [[Paragraph("<b>Host</b>", cell_b), Paragraph("<b>CVE / ID</b>", cell_b),
                  Paragraph("<b>CVSS</b>", cell_b), Paragraph("<b>Description</b>", cell_b),
                  Paragraph("<b>Mitigation</b>", cell_b)]]
    for h in hosts:
        for v in h.get("vulns", []):
            vid = v.get("cve") or v.get("id", "")
            tags = " <b>[KEV]</b>" if v.get("kev") else ""
            tags += " [EXPLOIT]" if v.get("exploit") else ""
            vuln_rows.append([
                Paragraph(_pesc(h.get("ip", "")), cell),
                Paragraph(_pesc(vid) + tags, cell),
                Paragraph(str(v.get("cvss", "") or "-"), cell),
                Paragraph(_pesc(v.get("description", "") or "-"), cell),
                Paragraph(_pesc(v.get("mitigation", "") or "-"), cell),
            ])
    if len(vuln_rows) > 1:
        story.append(Paragraph("Vulnerability Detail — CVE Descriptions &amp; Mitigations", h2))
        vt = Table(vuln_rows,
                   colWidths=[22 * mm, 28 * mm, 12 * mm, 60 * mm, 58 * mm],
                   repeatRows=1)
        vt.setStyle(TableStyle([
            ("BACKGROUND", (0, 0), (-1, 0), danger),
            ("GRID", (0, 0), (-1, -1), 0.25, colors.HexColor("#d4dae0")),
            ("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.white, colors.HexColor("#f0f3f6")]),
            ("VALIGN", (0, 0), (-1, -1), "TOP"),
            ("TOPPADDING", (0, 0), (-1, -1), 3),
            ("BOTTOMPADDING", (0, 0), (-1, -1), 3),
        ]))
        story.append(vt)

    story.append(Spacer(1, 10))
    story.append(Paragraph(
        f"{BRAND_NAME} {BRAND_VERSION} — automated report. Findings are advisory "
        "and should be validated before remediation.", small))

    doc.build(story)
    return buf.getvalue()


# ---------------------------------------------------------------------------
# Single-host PDF report (v8)
# ---------------------------------------------------------------------------
def host_to_pdf(scan, host):
    """Render a focused PDF report for ONE host. Returns raw PDF bytes."""
    try:
        from reportlab.lib import colors
        from reportlab.lib.pagesizes import A4
        from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
        from reportlab.lib.units import mm
        from reportlab.platypus import (SimpleDocTemplate, Paragraph, Spacer,
                                        Table, TableStyle)
    except Exception as e:  # pragma: no cover
        raise RuntimeError(f"reportlab not available: {e}")

    green = colors.HexColor("#3fb950")
    dark = colors.HexColor("#1a212b")
    grey = colors.HexColor("#5a6675")
    danger = colors.HexColor("#d12d24")

    buf = io.BytesIO()
    ip = host.get("ip", "-")
    doc = SimpleDocTemplate(buf, pagesize=A4, topMargin=18 * mm,
                            bottomMargin=16 * mm, leftMargin=15 * mm,
                            rightMargin=15 * mm,
                            title=f"{BRAND_NAME} {BRAND_VERSION} Host Report - {ip}")
    styles = getSampleStyleSheet()
    h1 = ParagraphStyle("h1", parent=styles["Heading1"], textColor=dark, fontSize=20)
    h2 = ParagraphStyle("h2", parent=styles["Heading2"], textColor=green, fontSize=13,
                        spaceBefore=10)
    small = ParagraphStyle("small", parent=styles["Normal"], fontSize=8, textColor=grey)
    body = ParagraphStyle("body", parent=styles["Normal"], fontSize=9)

    story = []
    story.append(Paragraph(f"{BRAND_NAME} <font color='#3fb950'>{BRAND_VERSION}</font>", h1))
    story.append(Paragraph(f"Single-Host Report &mdash; {ip}", body))
    gen = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
    when = "-"
    if scan and scan.get("finished"):
        when = datetime.fromtimestamp(scan["finished"], timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
    st = "Passive" if host.get("passive") else scan_type_label(scan)
    story.append(Paragraph(
        f"Generated: {gen} &nbsp;|&nbsp; Scan target: {(scan or {}).get('target','-')} "
        f"&nbsp;|&nbsp; Completed: {when}", small))
    story.append(Paragraph(
        f"<b>Scan type: <font color='#3fb950'>{st}</font></b> &nbsp;|&nbsp; "
        f"Asset ID: <b>{host.get('asset_id','-')}</b>", small))
    story.append(Spacer(1, 8))

    # --- Host overview ---
    story.append(Paragraph("Host Overview", h2))
    dock = host.get("docker", {}) or {}
    overview = [
        ["Asset ID", host.get("asset_id") or "-"],
        ["IP address", ip],
        ["Hostname", host.get("hostname") or "-"],
        ["Device type", host.get("device_type") or "-"],
        ["Operating system", (host.get("os") or "unknown")],
        ["MAC / Vendor", f"{host.get('mac') or '-'} {host.get('vendor') or ''}".strip()],
        ["Risk score", f"{host.get('risk', 0)}/100"],
        ["Open ports", str(len(host.get("ports", [])))],
        ["Vulnerabilities", str(host.get("vuln_count", 0))],
        ["Docker host", "yes" if dock.get("is_docker") else "no"],
    ]
    t = Table(overview, colWidths=[55 * mm, 115 * mm])
    t.setStyle(TableStyle([
        ("FONTSIZE", (0, 0), (-1, -1), 9),
        ("TEXTCOLOR", (0, 0), (0, -1), grey),
        ("LINEBELOW", (0, 0), (-1, -1), 0.3, colors.HexColor("#d4dae0")),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 4),
        ("TOPPADDING", (0, 0), (-1, -1), 4),
    ]))
    story.append(t)

    # --- Open ports / services ---
    pd = host.get("port_details", [])
    if pd:
        story.append(Paragraph("Open Ports &amp; Services", h2))
        rows = [["Port", "Proto", "Service", "Product / Version"]]
        for p in pd:
            rows.append([
                str(p.get("port", "")), p.get("protocol", ""),
                p.get("service", "") or "-",
                (" ".join(x for x in [p.get("product", ""), p.get("version", "")] if x)) or "-",
            ])
        pt = Table(rows, colWidths=[20 * mm, 18 * mm, 40 * mm, 92 * mm], repeatRows=1)
        pt.setStyle(TableStyle([
            ("BACKGROUND", (0, 0), (-1, 0), dark),
            ("TEXTCOLOR", (0, 0), (-1, 0), colors.white),
            ("FONTSIZE", (0, 0), (-1, -1), 8),
            ("GRID", (0, 0), (-1, -1), 0.25, colors.HexColor("#d4dae0")),
            ("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.white, colors.HexColor("#f0f3f6")]),
            ("TOPPADDING", (0, 0), (-1, -1), 3),
            ("BOTTOMPADDING", (0, 0), (-1, -1), 3),
        ]))
        story.append(pt)

    # --- Software ---
    sw = host.get("software", [])
    if sw:
        story.append(Paragraph("Software &amp; Applications", h2))
        rows = [["Application", "Version", "Service", "Port"]]
        for s in sw:
            rows.append([s.get("name", "") or "-", s.get("version", "") or "-",
                         s.get("service", "") or "-", str(s.get("port", ""))])
        swt = Table(rows, colWidths=[70 * mm, 40 * mm, 40 * mm, 20 * mm], repeatRows=1)
        swt.setStyle(TableStyle([
            ("BACKGROUND", (0, 0), (-1, 0), green),
            ("TEXTCOLOR", (0, 0), (-1, 0), colors.white),
            ("FONTSIZE", (0, 0), (-1, -1), 8),
            ("GRID", (0, 0), (-1, -1), 0.25, colors.HexColor("#d4dae0")),
            ("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.white, colors.HexColor("#f0f3f6")]),
            ("TOPPADDING", (0, 0), (-1, -1), 3),
            ("BOTTOMPADDING", (0, 0), (-1, -1), 3),
        ]))
        story.append(swt)

    # --- Vulnerabilities (v8: full CVE description + mitigation) ---
    vulns = host.get("vulns", [])
    if vulns:
        story.append(Paragraph("Vulnerabilities — CVE Descriptions &amp; Mitigations", h2))
        cell = ParagraphStyle("cellH", parent=styles["Normal"], fontSize=7.5, leading=9.5)
        cell_b = ParagraphStyle("cellHb", parent=cell, textColor=colors.white)
        rows = [[Paragraph("<b>CVE / ID</b>", cell_b), Paragraph("<b>CVSS</b>", cell_b),
                 Paragraph("<b>KEV</b>", cell_b), Paragraph("<b>Description</b>", cell_b),
                 Paragraph("<b>Mitigation</b>", cell_b)]]
        for v in vulns:
            vid = v.get("cve") or v.get("id", "")
            tag = " [EXPLOIT]" if v.get("exploit") else ""
            rows.append([
                Paragraph(_pesc(vid) + tag, cell),
                Paragraph(str(v.get("cvss", "") or "-"), cell),
                Paragraph("yes" if v.get("kev") else "—", cell),
                Paragraph(_pesc(v.get("description", "") or "-"), cell),
                Paragraph(_pesc(v.get("mitigation", "") or "-"), cell),
            ])
        vt = Table(rows, colWidths=[30 * mm, 13 * mm, 12 * mm, 65 * mm, 60 * mm],
                   repeatRows=1)
        vt.setStyle(TableStyle([
            ("BACKGROUND", (0, 0), (-1, 0), danger),
            ("GRID", (0, 0), (-1, -1), 0.25, colors.HexColor("#d4dae0")),
            ("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.white, colors.HexColor("#f0f3f6")]),
            ("VALIGN", (0, 0), (-1, -1), "TOP"),
            ("TOPPADDING", (0, 0), (-1, -1), 3),
            ("BOTTOMPADDING", (0, 0), (-1, -1), 3),
        ]))
        story.append(vt)

    # --- v10r1: Docker containers, image CVEs & CIS audit ---
    if dock.get("is_docker") and (dock.get("containers") or dock.get("image_scan", {}).get("ran") or dock.get("cis_audit")):
        dsum = dock.get("summary", {}) or {}
        story.append(Paragraph("Docker / Container Security", h2))
        meta = []
        eng = dock.get("engine", {}) or {}
        if eng.get("version"):
            meta.append(["Engine", f"Docker {eng.get('version')} ({eng.get('storage_driver','')}, {'rootless' if eng.get('rootless') else 'root'})"])
        meta.append(["Containers", f"{dsum.get('containers_running',0)} running / {dsum.get('containers',0)} total"])
        meta.append(["Images", str(dsum.get("images", 0))])
        meta.append(["Image CVEs", f"{dsum.get('image_vulns',0)} ({dsum.get('image_critical',0)} critical, {dsum.get('image_kev',0)} KEV)"])
        meta.append(["Privileged / sock", f"{dsum.get('privileged',0)} privileged, {dsum.get('sock_mounts',0)} docker.sock mounts"])
        meta.append(["CIS audit", f"{dsum.get('cis_fail',0)} fail, {dsum.get('cis_warn',0)} warn"])
        mt = Table(meta, colWidths=[55 * mm, 115 * mm])
        mt.setStyle(TableStyle([
            ("FONTSIZE", (0, 0), (-1, -1), 9),
            ("TEXTCOLOR", (0, 0), (0, -1), grey),
            ("LINEBELOW", (0, 0), (-1, -1), 0.3, colors.HexColor("#d4dae0")),
            ("TOPPADDING", (0, 0), (-1, -1), 4), ("BOTTOMPADDING", (0, 0), (-1, -1), 4),
        ]))
        story.append(mt)
        # Containers table
        conts = dock.get("containers") or []
        if conts:
            ccell = ParagraphStyle("ccell", parent=styles["Normal"], fontSize=7.5, leading=9.5)
            ccellb = ParagraphStyle("ccellb", parent=ccell, textColor=colors.white)
            crows = [[Paragraph("<b>Container</b>", ccellb), Paragraph("<b>Image</b>", ccellb),
                      Paragraph("<b>State</b>", ccellb), Paragraph("<b>Health</b>", ccellb),
                      Paragraph("<b>IP(s)</b>", ccellb),
                      Paragraph("<b>Ports</b>", ccellb), Paragraph("<b>Flags</b>", ccellb)]]
            for c in conts:
                flags = []
                if c.get("privileged"): flags.append("privileged")
                if c.get("docker_sock_mounted"): flags.append("docker.sock")
                if str(c.get("network_mode", "")).lower() == "host": flags.append("host-net")
                health = c.get("health") or "none"
                if health == "unhealthy" and c.get("health_failing_streak"):
                    health += f" x{c['health_failing_streak']}"
                if health == "none":
                    health = "-"
                # v12: per-container IPs and published/internal ports.
                ip_txt = ", ".join(c.get("ips") or []) or "-"
                pbits = []
                if c.get("ports_published"): pbits.append("pub: " + ", ".join(c["ports_published"]))
                if c.get("ports_internal"): pbits.append("int: " + ", ".join(c["ports_internal"]))
                if not pbits and c.get("ports"): pbits.append(", ".join(c["ports"]))
                port_txt = "; ".join(pbits) or "-"
                crows.append([
                    Paragraph(_pesc(c.get("name", "")), ccell),
                    Paragraph(_pesc(c.get("image", "")), ccell),
                    Paragraph(_pesc(c.get("state", "")), ccell),
                    Paragraph(_pesc(health), ccell),
                    Paragraph(_pesc(ip_txt), ccell),
                    Paragraph(_pesc(port_txt), ccell),
                    Paragraph(_pesc(", ".join(flags) or "-"), ccell)])
            ct = Table(crows, colWidths=[26 * mm, 34 * mm, 16 * mm, 18 * mm, 26 * mm, 34 * mm, 18 * mm], repeatRows=1)
            ct.setStyle(TableStyle([
                ("BACKGROUND", (0, 0), (-1, 0), dark),
                ("TEXTCOLOR", (0, 0), (-1, 0), colors.white),
                ("FONTSIZE", (0, 0), (-1, -1), 7.5),
                ("GRID", (0, 0), (-1, -1), 0.25, colors.HexColor("#d4dae0")),
                ("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.white, colors.HexColor("#f0f3f6")]),
                ("VALIGN", (0, 0), (-1, -1), "TOP"),
                ("TOPPADDING", (0, 0), (-1, -1), 3), ("BOTTOMPADDING", (0, 0), (-1, -1), 3),
            ]))
            story.append(ct)
        # CIS findings (fails + warns)
        cis = [x for x in (dock.get("cis_audit") or []) if x.get("status") in ("fail", "warn")]
        if cis:
            cell = ParagraphStyle("cisc", parent=styles["Normal"], fontSize=7.5, leading=9.5)
            cellb = ParagraphStyle("ciscb", parent=cell, textColor=colors.white)
            rows = [[Paragraph("<b>Status</b>", cellb), Paragraph("<b>Check</b>", cellb),
                     Paragraph("<b>Detail</b>", cellb), Paragraph("<b>Ref</b>", cellb)]]
            for x in cis:
                rows.append([Paragraph(x["status"].upper(), cell),
                             Paragraph(_pesc(x.get("check", "")), cell),
                             Paragraph(_pesc(x.get("detail", "")), cell),
                             Paragraph(_pesc(x.get("ref", "")), cell)])
            cist = Table(rows, colWidths=[16 * mm, 40 * mm, 90 * mm, 24 * mm], repeatRows=1)
            cist.setStyle(TableStyle([
                ("BACKGROUND", (0, 0), (-1, 0), dark),
                ("GRID", (0, 0), (-1, -1), 0.25, colors.HexColor("#d4dae0")),
                ("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.white, colors.HexColor("#f0f3f6")]),
                ("VALIGN", (0, 0), (-1, -1), "TOP"),
                ("TOPPADDING", (0, 0), (-1, -1), 3), ("BOTTOMPADDING", (0, 0), (-1, -1), 3),
            ]))
            story.append(cist)

    story.append(Spacer(1, 10))
    story.append(Paragraph(
        f"{BRAND_NAME} {BRAND_VERSION} — single-host report. Findings are advisory "
        "and should be validated before remediation.", small))

    doc.build(story)
    return buf.getvalue()