Repository navigation
Expand file tree
/
Copy pathreport_generator.py
More file actions
1460 lines (1256 loc) · 58.5 KB
/
Copy pathreport_generator.py
File metadata and controls
1460 lines (1256 loc) · 58.5 KB
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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Professional Report Generator for Counterscarp Engine
Generates client-ready HTML/Markdown reports with risk ratings and remediation
"""
from __future__ import annotations
import math
import os
import json
from html import escape as html_escape
from typing import Callable, Dict, List, Any, Optional
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
from logger import get_logger
from exceptions import CounterscarpReportError
from counterscarp_core.severity import SEVERITY_RANK
try:
from importlib.metadata import version as _pkg_version
_ENGINE_VERSION = _pkg_version("counterscarp-engine")
except Exception:
_ENGINE_VERSION = "3.4.0"
from counterscarp_core.licensing import LicenseManager, BRANDED_REPORTS
logger = get_logger(__name__)
# Optional attack graph imports (graceful fallback)
try:
from attack_graph import build_graph, export_graph_json, trace_attack_paths
from visualizer import generate_attack_graph_html
ATTACK_GRAPH_AVAILABLE = True
except ImportError:
ATTACK_GRAPH_AVAILABLE = False
build_graph: Optional[Callable[..., Any]] = None # type: ignore[no-redef]
export_graph_json: Optional[Callable[..., Any]] = None # type: ignore[no-redef]
trace_attack_paths: Optional[Callable[..., Any]] = None # type: ignore[no-redef]
generate_attack_graph_html: Optional[Callable[..., Any]] = None # type: ignore[no-redef]
@dataclass
class Finding:
"""Unified finding format across all analyzers.
Attributes:
rule_id: Unique identifier for the rule that triggered.
severity: Severity level (CRITICAL, HIGH, MEDIUM, LOW, INFO).
category: Category of the finding (e.g., "Heuristic", "Slither").
title: Short title describing the finding.
description: Detailed description of the issue.
file: Path to the file where the finding occurred.
line_no: Line number where the finding occurred.
code_snippet: Relevant code snippet.
remediation: Suggested remediation.
references: List of reference URLs.
cwe: Optional CWE identifier.
owasp: Optional OWASP category.
"""
rule_id: str
severity: str # CRITICAL, HIGH, MEDIUM, LOW, INFO
category: str # e.g., "Heuristic", "Liar Detector", "Access Matrix", "Slither", "Aderyn"
title: str
description: str
file: str
line_no: int
code_snippet: str = ""
remediation: str = ""
references: List[str] = field(default_factory=list)
cwe: Optional[str] = None
owasp: Optional[str] = None
similar_locations: List[str] = field(default_factory=list)
duplicate_count: int = 0
confidence: int = 5 # 1-10 confidence score
rag_similar_findings: List[Dict[str, Any]] = field(default_factory=list)
rag_remediation: str = ""
rag_references: List[Dict[str, str]] = field(default_factory=list)
exploit_code: str = "" # Generated exploit PoC source code (Pro)
exploit_path: str = "" # Path to generated exploit file (Pro)
@dataclass
class ReportSection:
"""Represents a section in the final report.
Attributes:
title: Section title.
findings: List of findings in this section.
summary: Optional section summary.
"""
title: str
findings: List[Finding]
summary: str = ""
@dataclass
class AuditReport:
"""Complete audit report structure.
Attributes:
project_name: Name of the audited project.
target_path: Path to the analyzed target.
timestamp: Report generation timestamp.
engine_version: Version of Counterscarp Engine used.
executive_summary: Dict with severity counts.
sections: List of report sections.
risk_score: Overall risk score (0-100).
pass_fail: Pass/fail status (PASS, FAIL, WARNING).
"""
project_name: str
target_path: str
timestamp: str
engine_version: str
executive_summary: Dict[str, int] # {severity: count}
sections: List[ReportSection]
risk_score: float # 0-100
pass_fail: str # PASS, FAIL, WARNING
analyzer_status: Dict[str, Dict[str, Any]] = field(default_factory=dict)
# Severity weights for risk scoring
SEVERITY_WEIGHTS = {
"CRITICAL": 10.0,
"HIGH": 5.0,
"MEDIUM": 2.0,
"LOW": 0.5,
"INFO": 0.1
}
# SARIF severity mapping
SARIF_LEVEL_MAP = {
"CRITICAL": "error",
"HIGH": "error",
"MEDIUM": "warning",
"LOW": "note",
"INFO": "note"
}
# Counterscarp Engine version for SARIF reports
COUNTERSCARP_ENGINE_VERSION = "3.4.0"
COUNTERSCARP_ENGINE_SEMANTIC_VERSION = "3.4.0"
COUNTERSCARP_INFORMATION_URI = "https://github.com/RunTimeAdmin/counterscarp"
# Remediation knowledge base
REMEDIATION_KB = {
# Heuristics
"UNCHECKED_EXTERNAL_CALL": {
"fix": "Always check return values: `(bool success, ) = target.call{value: amount}(data); require(success, \"Call failed\");`",
"references": ["https://consensys.github.io/smart-contract-best-practices/attacks/denial-of-service/"],
"cwe": "CWE-252: Unchecked Return Value"
},
"ORACLE_STALENESS_CHECK": {
"fix": "Check `updatedAt` timestamp: `require(block.timestamp - updatedAt < STALENESS_THRESHOLD, \"Stale price\");`",
"references": ["https://docs.chain.link/data-feeds/price-feeds/historical-data"],
"cwe": "CWE-829: Inclusion of Functionality from Untrusted Control Sphere"
},
"FLASH_LOAN_REENTRANCY": {
"fix": "Add `nonReentrant` modifier from OpenZeppelin ReentrancyGuard to all flash loan callbacks.",
"references": ["https://docs.openzeppelin.com/contracts/4.x/api/security#ReentrancyGuard"],
"cwe": "CWE-841: Improper Enforcement of Behavioral Workflow"
},
"STORAGE_COLLISION_RISK": {
"fix": "Use storage gaps: `uint256[50] private __gap;` and follow OpenZeppelin upgrade guidelines.",
"references": ["https://docs.openzeppelin.com/upgrades-plugins/1.x/writing-upgradeable"],
"cwe": "CWE-664: Improper Control of a Resource Through its Lifetime"
},
"MISSING_SLIPPAGE_PROTECTION": {
"fix": "Set minimum output amount: `swapExactTokensForTokens(amountIn, minAmountOut, path, to, deadline);`",
"references": ["https://docs.uniswap.org/contracts/v2/guides/smart-contract-integration/trading"],
"cwe": "CWE-841: Improper Enforcement of Behavioral Workflow"
},
# Access Control
"TX_ORIGIN_USAGE": {
"fix": "Replace `tx.origin` with `msg.sender` and use role-based access control (AccessControl from OpenZeppelin).",
"references": ["https://consensys.github.io/smart-contract-best-practices/development-recommendations/solidity-specific/tx-origin/"],
"cwe": "CWE-306: Missing Authentication for Critical Function"
},
"EMERGENCY_WITHDRAW_PUBLIC": {
"fix": "Add `onlyOwner` modifier and consider adding a timelock for emergency functions.",
"references": ["https://docs.openzeppelin.com/contracts/4.x/api/access#Ownable"],
"cwe": "CWE-284: Improper Access Control"
},
# Liar Detector
"INTENT_IMPLEMENTATION_MISMATCH": {
"fix": "Add missing access control modifier (onlyOwner, onlyRole) or change visibility to internal/private.",
"references": ["https://docs.soliditylang.org/en/latest/security-considerations.html#visibility"],
"cwe": "CWE-284: Improper Access Control"
},
# Upgrade Safety
"STORAGE_COLLISION": {
"fix": "CRITICAL: Do not reorder or remove storage variables. Only append new variables at the end.",
"references": ["https://docs.openzeppelin.com/upgrades-plugins/1.x/proxies#storage-collisions-between-implementation-versions"],
"cwe": "CWE-664: Improper Control of a Resource Through its Lifetime"
},
"AUTH_REMOVED": {
"fix": "CRITICAL: Restore removed access control modifier or add equivalent check. Audit all callers.",
"references": ["https://docs.openzeppelin.com/contracts/4.x/access-control"],
"cwe": "CWE-284: Improper Access Control"
}
}
def calculate_risk_score(findings: List[Finding]) -> float:
"""Calculate overall risk score (0-100) based on finding severity distribution.
Formula: weighted_sum / (max_possible_weight_for_finding_count)
Args:
findings: List of findings to calculate score from.
Returns:
Risk score between 0 and 100.
"""
if not findings:
return 0.0
total_weight = sum(SEVERITY_WEIGHTS.get(f.severity, 0) for f in findings)
# Normalize to 0-100 scale (assume max 10 critical findings = 100)
max_possible = len(findings) * SEVERITY_WEIGHTS["CRITICAL"]
# Guard against zero division
max_possible = max(max_possible, 1)
score = min(100.0, (total_weight / max_possible) * 100)
# Guard against NaN / infinity from corrupted inputs
if math.isnan(score) or math.isinf(score):
logger.error("Risk score calculation produced invalid result")
score = 50.0 # Default to medium risk
return round(score, 1)
def get_pass_fail_status(findings: List[Finding]) -> str:
"""Determine overall pass/fail status.
Args:
findings: List of findings to evaluate.
Returns:
Status string: "PASS", "FAIL", or "WARNING".
"""
critical_count = sum(1 for f in findings if f.severity == "CRITICAL")
high_count = sum(1 for f in findings if f.severity == "HIGH")
if critical_count > 0:
return "FAIL"
elif high_count > 3: # Configurable threshold
return "FAIL"
elif high_count > 0:
return "WARNING"
else:
return "PASS"
def enrich_finding(finding: Finding) -> Finding:
"""Add remediation advice and references from knowledge base.
Args:
finding: Finding to enrich.
Returns:
Enriched finding with remediation and references.
"""
kb_entry = REMEDIATION_KB.get(finding.rule_id, {})
if kb_entry:
if not finding.remediation:
finding.remediation = str(kb_entry.get("fix", ""))
if not finding.references:
refs = kb_entry.get("references", [])
finding.references = list(refs) if isinstance(refs, list) else []
if not finding.cwe:
cwe_val = kb_entry.get("cwe")
finding.cwe = str(cwe_val) if cwe_val is not None else None
# Fallback generic remediation
if not finding.remediation:
finding.remediation = f"Review and address this {finding.severity} severity issue in {finding.file}."
return finding
def _e(value: Any) -> str:
"""HTML-escape any value for the report. Finding text comes from scanned
code (names, comments, snippets), so none of it may reach the page raw."""
return html_escape(str(value), quote=True)
def _safe_href(url: Any) -> str:
"""Escaped link target, or '#' for anything that is not http(s)."""
text = str(url).strip()
if not text.lower().startswith(("https://", "http://")):
return "#"
return _e(text)
def generate_html_report(report: AuditReport, output_path: str, logo_path: Optional[str] = None, dev_mode: bool = False) -> Optional[str]:
"""Generate professional HTML report.
Args:
report: AuditReport object to generate report from.
output_path: Path to save the HTML file.
logo_path: Optional path to a logo image file to embed in the report.
dev_mode: When True, bypass the Pro license check (for local development).
Returns:
Path to the generated HTML file, or None if pro feature not available.
"""
_license = LicenseManager()
if not (dev_mode or _license.check_pro_feature(BRANDED_REPORTS)):
print(_license.get_upgrade_message(BRANDED_REPORTS))
return None
# Process logo if provided (never crash on logo issues)
logo_html = ""
if logo_path and Path(logo_path).exists():
try:
import base64
with open(logo_path, 'rb') as f:
logo_data = f.read()
logo_b64 = base64.b64encode(logo_data).decode('utf-8')
ext = Path(logo_path).suffix.lower().lstrip('.')
mime = {'png': 'image/png', 'jpg': 'image/jpeg', 'jpeg': 'image/jpeg', 'svg': 'image/svg+xml'}.get(ext, 'image/png')
logo_html = f'<img src="data:{mime};base64,{logo_b64}" alt="Counterscarp Engine" style="height: 60px; margin-right: 15px; vertical-align: middle;">'
except (IOError, OSError, Exception) as e:
logger.warning(f"Failed to load logo from {logo_path}: {e}. Continuing without logo.")
logo_html = ""
# Determine status badge color
if report.pass_fail == "PASS":
status_color = "#28a745"
elif report.pass_fail == "WARNING":
status_color = "#ffc107"
elif report.pass_fail == "FAIL":
status_color = "#dc3545"
else:
status_color = "#6c757d"
# Build HTML
html = f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Security Audit Report - {_e(report.project_name)}</title>
<style>
* {{ margin: 0; padding: 0; box-sizing: border-box; }}
body {{ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; line-height: 1.6; color: #333; background: #f5f5f5; }}
.container {{ max-width: 1200px; margin: 0 auto; padding: 20px; }}
.header {{ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 40px 30px; border-radius: 10px; margin-bottom: 30px; }}
.header h1 {{ font-size: 2.5em; margin-bottom: 10px; }}
.header .meta {{ opacity: 0.9; font-size: 0.95em; }}
.status-badge {{ display: inline-block; padding: 8px 20px; background: {status_color}; color: white; border-radius: 20px; font-weight: bold; margin-top: 15px; }}
.risk-score {{ font-size: 3em; font-weight: bold; margin: 20px 0; }}
.risk-low {{ color: #28a745; }}
.risk-medium {{ color: #ffc107; }}
.risk-high {{ color: #fd7e14; }}
.risk-critical {{ color: #dc3545; }}
.summary {{ background: white; padding: 30px; border-radius: 10px; margin-bottom: 30px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }}
.summary-grid {{ display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 20px; margin-top: 20px; }}
.summary-card {{ text-align: center; padding: 20px; border-radius: 8px; }}
.summary-card.critical {{ background: #fff5f5; border-left: 4px solid #dc3545; }}
.summary-card.high {{ background: #fff8e1; border-left: 4px solid #fd7e14; }}
.summary-card.medium {{ background: #fffbea; border-left: 4px solid #ffc107; }}
.summary-card.low {{ background: #f0f9ff; border-left: 4px solid #17a2b8; }}
.summary-card .count {{ font-size: 2.5em; font-weight: bold; }}
.summary-card .label {{ text-transform: uppercase; font-size: 0.85em; color: #666; margin-top: 5px; }}
.section {{ background: white; padding: 30px; border-radius: 10px; margin-bottom: 30px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }}
.section h2 {{ color: #667eea; border-bottom: 3px solid #667eea; padding-bottom: 10px; margin-bottom: 20px; }}
.finding {{ border-left: 4px solid #ddd; padding: 20px; margin-bottom: 20px; background: #fafafa; border-radius: 5px; }}
.finding.critical {{ border-left-color: #dc3545; background: #fff5f5; }}
.finding.high {{ border-left-color: #fd7e14; background: #fff8e1; }}
.finding.medium {{ border-left-color: #ffc107; background: #fffbea; }}
.finding.low {{ border-left-color: #17a2b8; background: #f0f9ff; }}
.finding-header {{ display: flex; justify-content: space-between; align-items: start; margin-bottom: 15px; }}
.finding-title {{ font-size: 1.2em; font-weight: bold; color: #333; }}
.severity-badge {{ padding: 5px 15px; border-radius: 20px; font-size: 0.85em; font-weight: bold; color: white; }}
.severity-badge.critical {{ background: #dc3545; }}
.severity-badge.high {{ background: #fd7e14; }}
.severity-badge.medium {{ background: #ffc107; color: #333; }}
.severity-badge.low {{ background: #17a2b8; }}
.finding-meta {{ color: #666; font-size: 0.9em; margin-bottom: 10px; }}
.finding-description {{ margin: 15px 0; }}
.code-block {{ background: #2d2d2d; color: #f8f8f2; padding: 15px; border-radius: 5px; overflow-x: auto; font-family: 'Courier New', monospace; font-size: 0.9em; margin: 10px 0; }}
.remediation {{ background: #e8f5e9; border-left: 4px solid #4caf50; padding: 15px; border-radius: 5px; margin: 15px 0; }}
.remediation-title {{ font-weight: bold; color: #2e7d32; margin-bottom: 8px; }}
.references {{ margin-top: 10px; }}
.references a {{ color: #667eea; text-decoration: none; }}
.references a:hover {{ text-decoration: underline; }}
.footer {{ text-align: center; color: #999; margin-top: 50px; padding: 20px; }}
</style>
</head>
<body>
<div class="container">
<div class="header">
{logo_html}<h1 style="display: inline-block; vertical-align: middle;">🛡️ Security Audit Report</h1>
<div class="meta">
<strong>Project:</strong> {_e(report.project_name)}<br>
<strong>Target:</strong> {_e(report.target_path)}<br>
<strong>Generated:</strong> {_e(report.timestamp)}<br>
<strong>Engine:</strong> Counterscarp Engine {_e(report.engine_version)}
</div>
<div class="status-badge">{_e(report.pass_fail)}</div>
</div>
<div class="summary">
<h2>Executive Summary</h2>
<div class="risk-score {"risk-critical" if report.risk_score >= 70 else "risk-high" if report.risk_score >= 40 else "risk-medium" if report.risk_score >= 20 else "risk-low"}">
Risk Score: {report.risk_score}/100
</div>
<div class="summary-grid">
<div class="summary-card critical">
<div class="count">{report.executive_summary.get("CRITICAL", 0)}</div>
<div class="label">Critical</div>
</div>
<div class="summary-card high">
<div class="count">{report.executive_summary.get("HIGH", 0)}</div>
<div class="label">High</div>
</div>
<div class="summary-card medium">
<div class="count">{report.executive_summary.get("MEDIUM", 0)}</div>
<div class="label">Medium</div>
</div>
<div class="summary-card low">
<div class="count">{report.executive_summary.get("LOW", 0)}</div>
<div class="label">Low</div>
</div>
</div>
</div>
"""
# Sections
for section in report.sections:
if not section.findings:
continue
html += f"""
<div class="section">
<h2>{_e(section.title)}</h2>
{f"<p>{_e(section.summary)}</p>" if section.summary else ""}
"""
for finding in section.findings:
severity_class = _e(finding.severity.lower())
html += f"""
<div class="finding {severity_class}">
<div class="finding-header">
<div class="finding-title">{_e(finding.title)}</div>
<span class="severity-badge {severity_class}">{_e(finding.severity)}</span>
</div>
<div class="finding-meta">
<strong>Category:</strong> {_e(finding.category)} |
<strong>Rule:</strong> {_e(finding.rule_id)} |
<strong>Location:</strong> {_e(finding.file)}:{_e(finding.line_no)}
{f" | <strong>CWE:</strong> {_e(finding.cwe)}" if finding.cwe else ""}
| <strong>Confidence:</strong> {_e(getattr(finding, 'confidence', 5))}/10
</div>
<div class="finding-description">{_e(finding.description)}</div>
"""
if finding.code_snippet:
html += f"""
<div class="code-block">{_e(finding.code_snippet)}</div>
"""
if finding.remediation:
html += f"""
<div class="remediation">
<div class="remediation-title">🛠️ Remediation</div>
{_e(finding.remediation)}
</div>
"""
if finding.references:
html += """
<div class="references">
<strong>References:</strong><br>
"""
for ref in finding.references:
html += f' <a href="{_safe_href(ref)}" target="_blank" rel="noopener noreferrer">{_e(ref)}</a><br>\n'
html += " </div>\n"
if finding.duplicate_count > 0:
locations_text = ", ".join(_e(loc) for loc in finding.similar_locations[:5])
if finding.duplicate_count > 5:
locations_text += f" ... and {finding.duplicate_count - 5} more"
html += f'<div class="duplicate-note" style="color:#666;font-size:0.85em;margin-top:4px;">Also found in {finding.duplicate_count} other location(s): {locations_text}</div>'
# RAG: AI Analysis
rag_remediation = getattr(finding, 'rag_remediation', None)
if rag_remediation:
html += f"""
<div style="background:#1a1a2e;border-left:4px solid #7c3aed;padding:12px 16px;margin:10px 0;border-radius:4px;">
<strong style="color:#a78bfa;">AI Analysis</strong>
<p style="color:#e0e0e0;margin:8px 0 0 0;">{_e(rag_remediation)}</p>
</div>
"""
# RAG: Similar Past Findings (top 3)
rag_similar = getattr(finding, 'rag_similar_findings', None)
if rag_similar:
html += """
<div style="margin:10px 0;">
<strong style="color:#94a3b8;">Related Past Findings:</strong>
<ul style="margin:4px 0;">
"""
for entry in rag_similar[:3]:
text = entry.get('text', '')
score = entry.get('similarity', 0.0)
source = entry.get('metadata', {}).get('source', '')
html += f' <li style="color:#cbd5e1;">{_e(text)} <span style="color:#7c3aed;">(similarity: {score:.0%})</span> — <em>{_e(source)}</em></li>\n'
html += """ </ul>
</div>
"""
# RAG: AI References
rag_references = getattr(finding, 'rag_references', None)
if rag_references:
html += """
<div style="margin:10px 0;">
<strong style="color:#94a3b8;">AI References:</strong>
<ul style="margin:4px 0;">
"""
for ref in rag_references:
url = ref.get('url', '#')
source = ref.get('source', url)
html += f' <li><a href="{_safe_href(url)}" rel="noopener noreferrer" style="color:#60a5fa;">{_e(source)}</a></li>\n'
html += """ </ul>
</div>
"""
# Exploit PoC (Pro tier)
exploit_code = getattr(finding, 'exploit_code', '')
exploit_path = getattr(finding, 'exploit_path', '')
if exploit_code:
import html as _html_escape
escaped_code = _html_escape.escape(exploit_code)
path_note = f' <span style="color:#94a3b8;font-size:0.85em;">({_html_escape.escape(exploit_path)})</span>' if exploit_path else ''
html += f"""
<details style="margin:12px 0;">
<summary style="cursor:pointer;background:#1a0a00;border-left:4px solid #f97316;padding:8px 14px;border-radius:4px;color:#fb923c;font-weight:bold;">
💥 Exploit PoC (Foundry){path_note}
</summary>
<div style="background:#120800;border-left:4px solid #f97316;padding:12px 16px;border-radius:0 0 4px 4px;margin-top:2px;">
<p style="color:#94a3b8;font-size:0.85em;margin:0 0 8px 0;">Generated Foundry test — run with <code style="background:#1e1e1e;padding:2px 6px;border-radius:3px;">forge test</code></p>
<pre style="background:#0d0d0d;border:1px solid #374151;border-radius:4px;padding:12px;overflow-x:auto;margin:0;"><code style="color:#e2e8f0;font-size:0.85em;font-family:monospace;">{escaped_code}</code></pre>
</div>
</details>
"""
html += " </div>\n"
html += " </div>\n"
html += """
<div class="footer">
Generated by <strong>Counterscarp Security Engine</strong> • counterscarp.io<br>
For questions or clarifications, contact your security team.
</div>
</div>
</body>
</html>
"""
with open(output_path, 'w', encoding='utf-8') as f:
f.write(html)
return output_path
def generate_pdf_report(
report: AuditReport,
output_path: Optional[str] = None,
logo_path: Optional[str] = None,
dev_mode: bool = False,
) -> Optional[Any]:
"""Generate a PDF audit report by converting the HTML report to PDF.
Requires xhtml2pdf: ``pip install xhtml2pdf`` (or ``pip install counterscarp-engine[pdf]``).
This is a Pro feature — the caller must hold a valid ``BRANDED_REPORTS`` license.
Args:
report: AuditReport object to generate the report from.
output_path: File path to write the PDF to. When provided the function
writes the file and returns the path string. When *None* the raw
PDF bytes are returned so callers can stream it directly.
logo_path: Optional path to a logo image to embed (forwarded to the
underlying HTML generator).
dev_mode: When True, bypass the Pro license check (for local development).
Returns:
* ``str`` — the *output_path* when a path was provided and the file was
written successfully.
* ``bytes`` — raw PDF bytes when *output_path* is ``None``.
* ``None`` — when the feature is unavailable (missing license or missing
``xhtml2pdf`` dependency) or when generation fails.
"""
_license = LicenseManager()
if not (dev_mode or _license.check_pro_feature(BRANDED_REPORTS)):
print(_license.get_upgrade_message(BRANDED_REPORTS))
return None
# ------------------------------------------------------------------ #
# Step 1 – Produce the HTML source via the existing HTML generator. #
# We write to a temp file, read it back, then delete it. #
# ------------------------------------------------------------------ #
import io
import tempfile
try:
with tempfile.NamedTemporaryFile(
suffix=".html", mode="w", delete=False, encoding="utf-8"
) as tmp:
tmp_path = tmp.name
html_result = generate_html_report(report, tmp_path, logo_path=logo_path, dev_mode=dev_mode)
if not html_result:
logger.error("PDF generation failed: HTML generation returned None")
return None
with open(tmp_path, "r", encoding="utf-8") as f:
html_content = f.read()
try:
import os as _os
_os.unlink(tmp_path)
except OSError:
pass
except Exception as e:
logger.error(f"PDF generation failed during HTML phase: {e}")
return None
# ------------------------------------------------------------------ #
# Step 2 – Inject PDF-specific CSS (page size, pagination, breaks). #
# ------------------------------------------------------------------ #
pdf_css = """
<style>
@page {
size: A4;
margin: 2cm;
}
body { font-size: 10pt; background: #fff !important; color: #333 !important; }
.container { max-width: 100% !important; padding: 0 !important; }
.header {
background: #667eea !important;
color: #fff !important;
padding: 20px !important;
border-radius: 6px !important;
margin-bottom: 20px !important;
page-break-inside: avoid;
}
.finding { page-break-inside: avoid; }
.section { page-break-inside: avoid; }
h1, h2, h3 { page-break-after: avoid; }
pre { white-space: pre-wrap !important; word-wrap: break-word !important; font-size: 8pt !important; }
a { color: #667eea !important; }
.code-block { font-size: 8pt !important; }
</style>
"""
if "</head>" in html_content:
pdf_html = html_content.replace("</head>", pdf_css + "</head>", 1)
else:
pdf_html = pdf_css + html_content
# ------------------------------------------------------------------ #
# Step 3 – Convert HTML to PDF via xhtml2pdf (pisa). #
# ------------------------------------------------------------------ #
try:
from xhtml2pdf import pisa
result_buffer = io.BytesIO()
pisa_status = pisa.CreatePDF(pdf_html, dest=result_buffer)
if pisa_status.err:
logger.error(
f"PDF generation failed: xhtml2pdf reported {pisa_status.err} error(s)"
)
return None
pdf_bytes = result_buffer.getvalue()
if output_path:
with open(output_path, "wb") as fout:
fout.write(pdf_bytes)
logger.info(f"PDF report saved: {output_path}")
return output_path
return pdf_bytes
except ImportError:
logger.warning(
"PDF report skipped — install with: pip install counterscarp-engine[pdf]"
)
return None
except Exception as e:
logger.error(f"PDF generation failed: {e}")
return None
def generate_sarif_report(findings: List[Finding], metadata: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
"""Generate a SARIF 2.1.0 compliant report from findings.
Args:
findings: List of Finding objects to include in the report.
metadata: Optional metadata dict with keys like 'project_name', 'target_path'.
Returns:
A dictionary representing a valid SARIF 2.1.0 JSON document.
Always returns a valid SARIF structure with a non-null 'runs' array.
Raises:
CounterscarpReportError: If report generation fails.
Example:
>>> findings = [Finding(...), Finding(...)]
>>> sarif = generate_sarif_report(findings, {"project_name": "MyProject"})
>>> json.dump(sarif, open("report.sarif", "w"))
"""
try:
metadata = metadata or {}
# Build unique rules from findings
rules = []
rule_ids = set()
for finding in findings:
if finding.rule_id not in rule_ids:
rule_ids.add(finding.rule_id)
rule = {
"id": finding.rule_id,
"name": finding.rule_id.replace("_", " ").title(),
"shortDescription": {
"text": finding.title
},
"fullDescription": {
"text": finding.description
},
"defaultConfiguration": {
"level": SARIF_LEVEL_MAP.get(finding.severity, "warning")
}
}
# Add CWE as a tag if available
if finding.cwe:
rule["properties"] = {
"tags": [finding.cwe]
}
rules.append(rule)
# Build results from findings
results = []
for finding in findings:
result: Dict[str, Any] = {
"ruleId": finding.rule_id,
"level": SARIF_LEVEL_MAP.get(finding.severity, "warning"),
"message": {
"text": finding.description
},
"locations": []
}
# Add location if file path is available
if finding.file:
location: Dict[str, Any] = {
"physicalLocation": {
"artifactLocation": {
"uri": finding.file
}
}
}
# Add region if line number is available and valid
if finding.line_no and finding.line_no > 0:
location["physicalLocation"]["region"] = {
"startLine": finding.line_no
}
# Add snippet if available
if finding.code_snippet:
location["physicalLocation"]["region"]["snippet"] = {
"text": finding.code_snippet
}
result["locations"].append(location)
# Add remediation as a related location if available
if finding.remediation:
result["message"]["text"] += f"\n\nRemediation: {finding.remediation}"
# Add RAG-enriched data to properties (SARIF extensibility point)
rag_properties: Dict[str, Any] = {}
rag_remediation = getattr(finding, "rag_remediation", None)
if rag_remediation:
rag_properties["ai_remediation"] = rag_remediation
rag_references = getattr(finding, "rag_references", None)
if rag_references:
urls = [ref.get("url", "") for ref in rag_references if ref.get("url")]
if urls:
rag_properties["ai_references"] = urls
rag_similar = getattr(finding, "rag_similar_findings", None)
if rag_similar:
similar_list = [
{
"text": sf.get("text", ""),
"similarity": round(sf.get("similarity", 0), 3),
"source": sf.get("metadata", {}).get("source", "unknown"),
}
for sf in rag_similar[:3]
]
if similar_list:
rag_properties["similar_findings"] = similar_list
# Exploit PoC (Pro tier)
_exploit_code = getattr(finding, "exploit_code", "")
_exploit_path = getattr(finding, "exploit_path", "")
if _exploit_code:
rag_properties["exploit_code"] = _exploit_code
if _exploit_path:
rag_properties["exploit_path"] = _exploit_path
if rag_properties:
result["properties"] = rag_properties
results.append(result)
# Build the SARIF document - ALWAYS has valid runs array
sarif_doc: Dict[str, Any] = {
"$schema": "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json",
"version": "2.1.0",
"runs": [
{
"tool": {
"driver": {
"name": "Counterscarp Engine",
"version": COUNTERSCARP_ENGINE_VERSION,
"semanticVersion": COUNTERSCARP_ENGINE_SEMANTIC_VERSION,
"informationUri": COUNTERSCARP_INFORMATION_URI,
"rules": rules
}
},
"results": results,
"invocations": [
{
"executionSuccessful": True,
"startTimeUtc": metadata.get("timestamp", datetime.now().isoformat())
}
]
}
]
}
# Add automation details if project name is available
if metadata.get("project_name"):
sarif_doc["runs"][0]["automationDetails"] = {
"id": metadata["project_name"],
"description": {
"text": f"Security audit for {metadata['project_name']}"
}
}
logger.info(f"Generated SARIF report with {len(results)} results and {len(rules)} rules")
return sarif_doc
except Exception as e:
logger.error(f"Failed to generate SARIF report: {e}")
raise CounterscarpReportError(
"Failed to generate SARIF report",
details={"error": str(e), "finding_count": len(findings)}
) from e
def save_sarif_report(findings: List[Finding], output_path: str, metadata: Optional[Dict[str, Any]] = None) -> str:
"""Generate and save a SARIF 2.1.0 report to a file.
ALWAYS produces a valid SARIF file with a non-null 'runs' array, even if
there are no findings or if an error occurs during generation.
Args:
findings: List of Finding objects to include in the report.
output_path: Path where the SARIF JSON file will be written.
metadata: Optional metadata dict with keys like 'project_name', 'target_path'.
Returns:
The output file path.
Raises:
CounterscarpReportError: If the file cannot be written.
Example:
>>> findings = [Finding(...), Finding(...)]
>>> path = save_sarif_report(findings, "report.sarif")
>>> print(f"SARIF report saved to: {path}")
"""
# Default valid SARIF structure as fallback
default_sarif = {
"version": "2.1.0",
"$schema": "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json",
"runs": [
{
"tool": {
"driver": {
"name": "Counterscarp Engine",
"version": COUNTERSCARP_ENGINE_VERSION,
"informationUri": COUNTERSCARP_INFORMATION_URI
}
},
"results": []
}
]
}
try:
sarif_doc = generate_sarif_report(findings, metadata)
# Ensure we always have a valid SARIF structure with runs array
if sarif_doc is None:
sarif_doc = default_sarif
elif not isinstance(sarif_doc, dict):
sarif_doc = default_sarif
elif "runs" not in sarif_doc or sarif_doc["runs"] is None:
sarif_doc["runs"] = default_sarif["runs"]
except Exception as e:
logger.warning(f"SARIF generation failed, using default structure: {e}")
sarif_doc = default_sarif
try:
with open(output_path, 'w', encoding='utf-8') as f:
json.dump(sarif_doc, f, indent=2)
logger.info(f"SARIF report saved to: {output_path}")
return output_path
except Exception as e:
logger.error(f"Failed to save SARIF report to {output_path}: {e}")
# Try to write the default structure as last resort
try:
with open(output_path, 'w', encoding='utf-8') as f:
json.dump(default_sarif, f, indent=2)
logger.info(f"Default SARIF report saved to: {output_path}")
return output_path
except Exception:
pass
raise CounterscarpReportError(
"Failed to save SARIF report",
details={"output_path": output_path, "error": str(e)}
) from e
def generate_markdown_report(report: AuditReport, output_path: str) -> str:
"""Generate Markdown report (GitHub/GitLab friendly).
Args:
report: AuditReport object to generate report from.
output_path: Path to save the Markdown file.
Returns:
Path to the generated Markdown file.
"""
status_emoji = {"PASS": "✅", "WARNING": "⚠️", "FAIL": "❌"}
md = f"""# 🛡️ Security Audit Report
**Project:** `{report.project_name}`
**Target:** `{report.target_path}`
**Generated:** {report.timestamp}
**Engine:** Counterscarp Engine {report.engine_version}
**Status:** {status_emoji.get(report.pass_fail, "❓")} **{report.pass_fail}**
---
## Executive Summary
**Risk Score:** {report.risk_score}/100
| Severity | Count |
|----------|-------|
| 🔴 CRITICAL | {report.executive_summary.get("CRITICAL", 0)} |
| 🟠 HIGH | {report.executive_summary.get("HIGH", 0)} |
| 🟡 MEDIUM | {report.executive_summary.get("MEDIUM", 0)} |
| 🔵 LOW | {report.executive_summary.get("LOW", 0)} |
"""
# Collect top 10 findings across all sections (already sorted by severity)
_top_findings: List[Finding] = []
for _section in report.sections:
for _finding in _section.findings:
if len(_top_findings) < 10:
_top_findings.append(_finding)
if _top_findings:
_severity_emoji_map = {"CRITICAL": "🔴", "HIGH": "🟠", "MEDIUM": "🟡", "LOW": "🔵", "INFO": "ℹ️"}
md += "### Top 10 Priority Issues\n\n"