-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit-audit-script.py
More file actions
2730 lines (2417 loc) · 115 KB
/
git-audit-script.py
File metadata and controls
2730 lines (2417 loc) · 115 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
"""
GitHub Security Scanner
This script handles repository scanning and report processing
for comprehensive security analysis using Gitleaks and Trivy.
"""
import argparse
import json
import os
import sys
import tempfile
import logging
import subprocess
from datetime import datetime, timezone
from typing import Dict, List, Optional, Any
import html
import requests
GITHUB_TOKEN = os.environ.get("GITHUB_TOKEN")
GITHUB_OWNER = os.environ.get("GITHUB_OWNER")
GITHUB_REPO = os.environ.get("GITHUB_REPO")
GITHUB_ORG = os.environ.get("GITHUB_ORG")
SCAN_ALL_REPOS = os.environ.get("SCAN_ALL_REPOS", "false").lower() == "true"
SCAN_ORG_REPOS = os.environ.get("SCAN_ORG_REPOS", "false").lower() == "true"
MAX_REPOS = int(os.environ.get("MAX_REPOS", "50"))
GITHUB_API_BASE_URL = "https://api.github.com"
REPO_PATH_FROM_ARGS = None
class CleanFormatter(logging.Formatter):
"""Custom formatter to remove redundant prefixes and clean up output"""
def format(self, record):
if record.levelno == logging.INFO:
return record.getMessage()
elif record.levelno == logging.WARNING:
return f"WARNING: {record.getMessage()}"
elif record.levelno == logging.ERROR:
return f"ERROR: {record.getMessage()}"
else:
return super().format(record)
logging.basicConfig(
level=logging.INFO, format="%(message)s", handlers=[logging.StreamHandler()]
)
for handler in logging.root.handlers:
handler.setFormatter(CleanFormatter())
logger = logging.getLogger(__name__)
def get_current_utc_time() -> datetime:
return datetime.now(timezone.utc)
def safe_remove_if_exists(path_to_remove: str) -> None:
try:
if os.path.isfile(path_to_remove):
os.remove(path_to_remove)
logger.debug(f"Removed existing file: {path_to_remove}")
elif os.path.isdir(path_to_remove):
import shutil
shutil.rmtree(path_to_remove)
logger.debug(f"Removed existing directory: {path_to_remove}")
except Exception as e:
logger.warning(f"Could not remove {path_to_remove}: {e}")
def get_github_auth() -> Optional[str]:
if not GITHUB_TOKEN:
logger.warning(
"GITHUB_TOKEN environment variable is not set. GitHub API calls will fail."
)
return None
return GITHUB_TOKEN
def make_github_request(endpoint: str, params: Optional[Dict] = None) -> Dict:
url = f"{GITHUB_API_BASE_URL}/{endpoint}"
token = get_github_auth()
headers = {}
if token:
headers["Authorization"] = f"token {token}"
headers["Accept"] = "application/vnd.github.v3+json"
try:
response = requests.get(url, headers=headers, params=params, timeout=30)
response.raise_for_status()
return response.json()
except requests.exceptions.HTTPError as e:
status_code = e.response.status_code if e.response is not None else "unknown"
logger.error(
f"HTTP Error making GitHub request to {url}: {e} (Status Code: {status_code})"
)
if e.response is not None and e.response.content:
logger.error(
f"Response content: {e.response.content.decode('utf-8', errors='ignore')}"
)
return {}
except requests.exceptions.RequestException as e:
logger.error(f"Request Error making GitHub request to {url}: {e}")
return {}
except json.JSONDecodeError as e:
logger.error(f"JSON Decode Error from GitHub request to {url}: {e}")
return {}
def get_paginated_results(
endpoint: str, params: Optional[Dict] = None, max_pages: int = 100
) -> List[Dict]:
"""Get paginated results from GitHub API"""
token = get_github_auth()
headers = {}
if token:
headers["Authorization"] = f"token {token}"
headers["Accept"] = "application/vnd.github.v3+json"
all_results = []
page = 1
next_url: Optional[str] = f"{GITHUB_API_BASE_URL}/{endpoint}"
while next_url and page <= max_pages:
try:
if params is None:
params = {}
params["page"] = page
params["per_page"] = 100
response = requests.get(
next_url, headers=headers, params=params, timeout=30
)
response.raise_for_status()
results = response.json()
if isinstance(results, list):
all_results.extend(results)
else:
all_results.append(results)
if "next" in response.links:
next_url = response.links["next"]["url"]
page += 1
else:
next_url = None
except Exception as e:
logger.error(f"Error fetching page {page} from {endpoint}: {e}")
break
return all_results
def get_organization_repositories(org: str) -> List[Dict]:
"""Get all repositories in a GitHub organization"""
return get_paginated_results(f"orgs/{org}/repos")
def get_user_repositories(owner: str) -> List[Dict]:
"""Get all repositories for a GitHub user"""
return get_paginated_results(f"users/{owner}/repos")
def run_scan_command(scan_type: str, repo_path: str, output_path: str) -> int:
"""Run a specific security scan command"""
ensure_dir_exists(output_path)
if scan_type == "gitleaks":
return run_gitleaks_scan(repo_path, output_path)
elif scan_type == "trivy-fs":
return run_trivy_fs_scan(repo_path, output_path)
elif scan_type == "trivy-config":
return run_trivy_config_scan(repo_path, output_path)
else:
logger.error(f"Unknown scan type: {scan_type}")
return 1
def run_gitleaks_scan(repo_path: str, output_path: str) -> int:
"""Run Gitleaks secret detection scan"""
report_file = os.path.join(output_path, "gitleaks-report.json")
config_path = "/app/gitleaks.toml"
logger.info(f"Running Gitleaks scan on: {repo_path}")
logger.info(f"Using config: {config_path}")
safe_remove_if_exists(report_file)
cmd = [
"gitleaks",
"detect",
"--source",
repo_path,
"--config",
config_path,
"--report-path",
report_file,
"--report-format",
"json",
"--exit-code",
"0",
]
try:
subprocess.run(cmd, capture_output=True, text=True, timeout=300)
if os.path.exists(report_file):
with open(report_file, "r") as f:
try:
data = json.load(f)
if isinstance(data, dict) and "findings" in data:
findings_count = len(data["findings"])
elif isinstance(data, list):
findings_count = len(data)
else:
findings_count = 0
logger.info(
f"Gitleaks scan complete. Found {findings_count} potential issues."
)
except json.JSONDecodeError:
logger.warning("Gitleaks report is not valid JSON")
else:
logger.info("Gitleaks scan complete. No issues found.")
# Create empty report
with open(report_file, "w") as f:
json.dump([], f)
return 0
except subprocess.TimeoutExpired:
logger.error("Gitleaks scan timed out")
return 1
except subprocess.CalledProcessError as e:
logger.error(f"Gitleaks scan failed: {e}")
return e.returncode
except Exception as e:
logger.error(f"Unexpected error during Gitleaks scan: {e}")
return 1
def run_trivy_fs_scan(repo_path: str, output_path: str) -> int:
"""Run Trivy filesystem vulnerability scan"""
report_file = os.path.join(output_path, "trivy-fs-report.json")
logger.info(f"Running Trivy filesystem scan on: {repo_path}")
safe_remove_if_exists(report_file)
cmd = [
"trivy",
"fs",
"--format",
"json",
"--output",
report_file,
"--severity",
"UNKNOWN,LOW,MEDIUM,HIGH,CRITICAL",
repo_path,
]
try:
subprocess.run(cmd, capture_output=True, text=True, timeout=600)
if os.path.exists(report_file):
with open(report_file, "r") as f:
try:
data = json.load(f)
if "Results" in data:
total_vulns = sum(
len(result.get("Vulnerabilities", []))
for result in data["Results"]
)
logger.info(
f"Trivy filesystem scan complete. Found {total_vulns} vulnerabilities."
)
else:
logger.info(
"Trivy filesystem scan complete. No vulnerabilities found."
)
except json.JSONDecodeError:
logger.warning("Trivy filesystem report is not valid JSON")
else:
logger.info("Trivy filesystem scan complete. No vulnerabilities found.")
with open(report_file, "w") as f:
json.dump({"Results": []}, f)
return 0
except subprocess.TimeoutExpired:
logger.error("Trivy filesystem scan timed out")
return 1
except subprocess.CalledProcessError as e:
logger.error(f"Trivy filesystem scan failed: {e}")
return e.returncode
except Exception as e:
logger.error(f"Unexpected error during Trivy filesystem scan: {e}")
return 1
def run_trivy_config_scan(repo_path: str, output_path: str) -> int:
"""Run Trivy configuration scan"""
report_file = os.path.join(output_path, "trivy-config-report.json")
logger.info(f"Running Trivy configuration scan on: {repo_path}")
safe_remove_if_exists(report_file)
cmd = [
"trivy",
"config",
"--format",
"json",
"--output",
report_file,
"--severity",
"UNKNOWN,LOW,MEDIUM,HIGH,CRITICAL",
repo_path,
]
try:
subprocess.run(cmd, capture_output=True, text=True, timeout=300)
if os.path.exists(report_file):
with open(report_file, "r") as f:
try:
data = json.load(f)
if "Results" in data:
total_misconfigs = sum(
len(result.get("Misconfigurations", []))
for result in data["Results"]
)
logger.info(
f"Trivy configuration scan complete. Found {total_misconfigs} misconfigurations."
)
else:
logger.info(
"Trivy configuration scan complete. No misconfigurations found."
)
except json.JSONDecodeError:
logger.warning("Trivy configuration report is not valid JSON")
else:
logger.info(
"Trivy configuration scan complete. No misconfigurations found."
)
with open(report_file, "w") as f:
json.dump({"Results": []}, f)
return 0
except subprocess.TimeoutExpired:
logger.error("Trivy configuration scan timed out")
return 1
except subprocess.CalledProcessError as e:
logger.error(f"Trivy configuration scan failed: {e}")
return e.returncode
except Exception as e:
logger.error(f"Unexpected error during Trivy configuration scan: {e}")
return 1
def ensure_dir_exists(path: str) -> None:
"""Ensure directory exists"""
os.makedirs(path, exist_ok=True)
def generate_dynamic_recommendations(detailed_reports: Dict) -> Dict:
"""Generate dynamic security recommendations based on scan results"""
recommendations = {"critical": [], "high": [], "medium": [], "low": [], "info": []}
# Gitleaks recommendations
if "gitleaks" in detailed_reports:
gitleaks_data = detailed_reports["gitleaks"]
if isinstance(gitleaks_data, list) and len(gitleaks_data) > 0:
recommendations["critical"].append(
"🔴 CRITICAL: Secrets detected in repository. Immediately rotate all exposed credentials and review access controls."
)
recommendations["high"].append(
"🔴 HIGH: Implement secret scanning in CI/CD pipeline to prevent future secret commits."
)
recommendations["medium"].append(
"🟡 MEDIUM: Review and update .gitignore to exclude sensitive files."
)
# Trivy vulnerability recommendations
if "trivy-fs" in detailed_reports:
trivy_data = detailed_reports["trivy-fs"]
if isinstance(trivy_data, dict) and "Results" in trivy_data:
critical_vulns = 0
high_vulns = 0
for result in trivy_data["Results"]:
for vuln in result.get("Vulnerabilities", []):
if vuln.get("Severity") == "CRITICAL":
critical_vulns += 1
elif vuln.get("Severity") == "HIGH":
high_vulns += 1
if critical_vulns > 0:
recommendations["critical"].append(
f"🔴 CRITICAL: {critical_vulns} critical vulnerabilities detected. Update dependencies immediately."
)
if high_vulns > 0:
recommendations["high"].append(
f"🔴 HIGH: {high_vulns} high severity vulnerabilities detected. Plan updates within 30 days."
)
if "trivy-config" in detailed_reports:
trivy_config_data = detailed_reports["trivy-config"]
if isinstance(trivy_config_data, dict) and "Results" in trivy_config_data:
misconfigs = sum(
len(result.get("Misconfigurations", []))
for result in trivy_config_data["Results"]
)
if misconfigs > 0:
recommendations["high"].append(
f"🔴 HIGH: {misconfigs} security misconfigurations detected. Review and fix configuration issues."
)
if not any(recommendations.values()):
recommendations["info"].append(
"✅ No security issues detected. Continue monitoring and maintain security best practices."
)
return recommendations
def generate_combined_report(
owner: str,
repo_slug: str,
scan_results_summary: Dict,
detailed_reports_data: Optional[Dict] = None,
branch: str = None,
) -> Dict:
"""Generate a comprehensive security report combining all scan results"""
current_time_obj = get_current_utc_time()
current_date = current_time_obj.strftime("%Y-%m-%d")
current_time = current_time_obj.strftime("%H:%M:%S UTC")
# Get actual metadata from environment or use provided values
actual_owner = os.environ.get("GITHUB_OWNER")
actual_repo_slug = os.environ.get("GITHUB_REPO")
actual_branch = (
branch
or os.environ.get("GITHUB_REF_NAME")
or os.environ.get("GIT_BRANCH")
or os.environ.get("BRANCH_NAME")
)
repo_full_name = os.environ.get("GITHUB_REPOSITORY")
if not actual_owner:
actual_owner = owner or "unknown-owner"
if not actual_repo_slug:
actual_repo_slug = repo_slug or "unknown-repo"
if actual_owner == "local_scan" or actual_repo_slug == "scan_target":
actual_owner = "local-scan"
actual_repo_slug = "local-repository"
if repo_full_name and "/" in repo_full_name:
parts = repo_full_name.split("/")
if len(parts) >= 2:
if actual_owner in ["unknown-owner", "local-scan"]:
actual_owner = parts[0]
if actual_repo_slug in ["unknown-repo", "local-repository"]:
actual_repo_slug = parts[1]
logger.info(
f"Report metadata - Owner: {actual_owner}, Repo: {actual_repo_slug}, Branch: {actual_branch}"
)
gitleaks_findings = scan_results_summary.get("gitleaks", {}).get(
"findings_count", 0
)
trivy_vulnerabilities = scan_results_summary.get("trivy-fs", {}).get(
"vulnerabilities_count", 0
)
trivy_misconfigurations = scan_results_summary.get("trivy-fs", {}).get(
"misconfigurations_count", 0
)
total_issues = gitleaks_findings + trivy_vulnerabilities + trivy_misconfigurations
secret_risk = "CRITICAL" if gitleaks_findings > 0 else "LOW"
vuln_risk = (
"CRITICAL"
if trivy_vulnerabilities > 10
else "HIGH"
if trivy_vulnerabilities > 5
else "MEDIUM"
if trivy_vulnerabilities > 0
else "LOW"
)
config_risk = (
"HIGH"
if trivy_misconfigurations > 5
else "MEDIUM"
if trivy_misconfigurations > 0
else "LOW"
)
overall_risk = (
"CRITICAL"
if gitleaks_findings > 0 or total_issues > 25
else "HIGH"
if total_issues > 15
else "MEDIUM"
if total_issues > 8
else "LOW"
if total_issues > 0
else "INFO"
)
combined_report = {
"metadata": {
"scan_date": current_date,
"scan_time": current_time,
"owner": actual_owner,
"repository": actual_repo_slug,
"branch": actual_branch,
"full_name": repo_full_name or f"{actual_owner}/{actual_repo_slug}",
"scan_tools": ["gitleaks", "trivy-fs"],
},
"executive_summary": {
"total_issues": total_issues,
"risk_level": overall_risk,
"secret_exposure_risk": secret_risk,
"vulnerability_risk": vuln_risk,
"configuration_risk": config_risk,
"gitleaks_secrets_found": gitleaks_findings,
"trivy_vulnerabilities_found": trivy_vulnerabilities,
"trivy_misconfigurations_found": trivy_misconfigurations,
"quick_stats": {
"gitleaks": {"secrets_found": gitleaks_findings},
"trivy": {
"vulnerabilities_found": trivy_vulnerabilities,
"misconfigurations_found": trivy_misconfigurations,
},
},
},
"detailed_results": detailed_reports_data,
"recommendations": generate_dynamic_recommendations(
detailed_reports_data or {}
),
"scan_details": {
"gitleaks": {"findings": gitleaks_findings, "risk_level": secret_risk},
"trivy_vulnerabilities": {
"findings": trivy_vulnerabilities,
"risk_level": vuln_risk,
},
"trivy_misconfigurations": {
"findings": trivy_misconfigurations,
"risk_level": config_risk,
},
},
}
if total_issues > 0:
combined_report["executive_summary"]["description"] = (
f"Security scan completed for {actual_owner}/{actual_repo_slug}. Total issues found: {total_issues}. Overall risk level: {overall_risk}."
)
else:
combined_report["executive_summary"]["description"] = (
f"Security scan completed for {actual_owner}/{actual_repo_slug}. No issues found by automated scanners. Overall risk level: INFO."
)
return combined_report
def get_report_css() -> str:
"""Return the CSS styles for the HTML report"""
return """
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; margin: 0; padding: 20px; background: #f5f5f5; }
.container { max-width: 1200px; margin: 0 auto; background: white; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); overflow: hidden; }
.header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; text-align: center; }
.header h1 { margin: 0; font-size: 2.5em; font-weight: 300; }
.header .subtitle { margin-top: 10px; opacity: 0.9; font-size: 1.1em; }
.content { padding: 30px; }
.section { margin-bottom: 30px; }
.section h2 { color: #333; border-bottom: 2px solid #667eea; padding-bottom: 10px; margin-bottom: 20px; }
.meta-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin-bottom: 20px; }
.meta-item { background: #f8f9fa; padding: 15px; border-radius: 6px; border-left: 4px solid #667eea; }
.meta-item strong { display: block; color: #495057; margin-bottom: 5px; }
.risk-badge { display: inline-block; padding: 4px 12px; border-radius: 20px; font-weight: bold; font-size: 0.9em; text-transform: uppercase; }
.risk-critical { background: #dc3545; color: white; }
.risk-high { background: #fd7e14; color: white; }
.risk-medium { background: #ffc107; color: #212529; }
.risk-low { background: #28a745; color: white; }
.risk-info { background: #17a2b8; color: white; }
.stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 15px; margin: 20px 0; }
.stat-card { background: white; border: 1px solid #dee2e6; border-radius: 8px; padding: 20px; text-align: center; box-shadow: 0 2px 4px rgba(0,0,0,0.05); cursor: pointer; transition: all 0.3s ease; }
.stat-card:hover { transform: translateY(-2px); box-shadow: 0 4px 8px rgba(0,0,0,0.1); }
.stat-card.clickable { border-color: #667eea; }
.stat-number { font-size: 2em; font-weight: bold; color: #495057; }
.stat-number.critical { color: #dc3545; }
.stat-number.high { color: #fd7e14; }
.stat-number.medium { color: #ffc107; }
.stat-number.low { color: #28a745; }
.stat-number.zero { color: #6c757d; }
.stat-label { color: #6c757d; margin-top: 5px; }
.recommendations { margin-top: 20px; }
.rec-category { margin-bottom: 20px; }
.rec-category h3 { margin-bottom: 10px; color: #495057; }
.rec-item { background: #f8f9fa; padding: 15px; margin-bottom: 10px; border-radius: 6px; border-left: 4px solid #667eea; }
.rec-critical { border-left-color: #dc3545; }
.rec-high { border-left-color: #fd7e14; }
.rec-medium { border-left-color: #ffc107; }
.rec-low { border-left-color: #28a745; }
.rec-info { border-left-color: #17a2b8; }
.footer { background: #f8f9fa; padding: 20px; text-align: center; color: #6c757d; border-top: 1px solid #dee2e6; }
.findings-section { margin-top: 30px; }
.findings-tool { margin-bottom: 25px; }
.findings-tool h3 { background: #e9ecef; padding: 10px 15px; margin: 0 0 15px 0; border-left: 4px solid #667eea; }
.finding-item { background: white; border: 1px solid #dee2e6; border-radius: 6px; margin-bottom: 15px; padding: 15px; }
.finding-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; }
.finding-title { font-weight: bold; color: #495057; flex-grow: 1; }
.finding-severity { font-size: 0.85em; padding: 3px 8px; border-radius: 12px; font-weight: bold; }
.severity-critical { background: #dc3545; color: white; }
.severity-high { background: #fd7e14; color: white; }
.severity-medium { background: #ffc107; color: #212529; }
.severity-low { background: #28a745; color: white; }
.severity-unknown { background: #6c757d; color: white; }
.finding-details { margin-top: 10px; }
.finding-detail-row { margin-bottom: 8px; }
.finding-label { font-weight: bold; color: #495057; display: inline-block; min-width: 80px; }
.finding-value { color: #6c757d; }
.code-snippet { background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 4px; padding: 10px; font-family: monospace; font-size: 0.9em; margin: 8px 0; overflow-x: auto; }
.remediation-box { background: #e7f3ff; border: 1px solid #bee5eb; border-radius: 6px; padding: 15px; margin-top: 10px; }
.remediation-title { font-weight: bold; color: #0c5460; margin-bottom: 8px; }
.remediation-text { color: #0c5460; line-height: 1.5; }
"""
def convert_json_to_html(report_data: Dict[str, Any]) -> str:
"""Convert the JSON report to a formatted HTML report"""
def esc(text: Any) -> str:
return html.escape(str(text))
meta = report_data.get("metadata", {})
exec_summary = report_data.get("executive_summary", {})
recommendations = report_data.get("recommendations", {})
scan_details = report_data.get("scan_details", {})
detailed_results = report_data.get("detailed_results", {})
html_content = f"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Security Report - {esc(meta.get("owner", "N/A"))}/{esc(meta.get("repository", "N/A"))}</title>
<style>
{get_report_css()}
</style>
<script>
function scrollToSection(sectionId) {{
const element = document.getElementById(sectionId);
if (element) {{
element.scrollIntoView({{ behavior: 'smooth', block: 'start' }});
element.style.backgroundColor = '#fff3cd';
setTimeout(() => element.style.backgroundColor = '', 2000);
}}
}}
</script>
</head>
<body>
<div class="container">
<div class="header">
<h1>🛡️ Security Report</h1>
<div class="subtitle">{esc(meta.get("owner", "N/A"))}/{esc(meta.get("repository", "N/A"))}</div>
</div>
<div class="content">
<div class="section">
<h2>📊 Executive Summary</h2>
<div class="meta-grid">
<div class="meta-item">
<strong>Repository</strong>
{esc(meta.get("owner", "N/A"))}/{esc(meta.get("repository", "N/A"))}
</div>
<div class="meta-item">
<strong>Branch</strong>
{esc(meta.get("branch", "N/A"))}
</div>
<div class="meta-item">
<strong>Scan Date</strong>
{esc(meta.get("scan_date", "N/A"))}
</div>
<div class="meta-item">
<strong>Scan Time</strong>
{esc(meta.get("scan_time", "N/A"))}
</div>
</div>
<div class="stats-grid">
<div class="stat-card clickable" onclick="scrollToSection('detailed-findings')">
<div class="stat-number {("critical" if exec_summary.get("total_issues", 0) > 20 else "high" if exec_summary.get("total_issues", 0) > 10 else "medium" if exec_summary.get("total_issues", 0) > 0 else "zero")}">{exec_summary.get("total_issues", 0)}</div>
<div class="stat-label">Total Issues</div>
</div>
<div class="stat-card clickable" onclick="scrollToSection('gitleaks-findings')">
<div class="stat-number {("critical" if exec_summary.get("gitleaks_secrets_found", 0) > 0 else "zero")}">{exec_summary.get("gitleaks_secrets_found", 0)}</div>
<div class="stat-label">Secrets Found</div>
</div>
<div class="stat-card clickable" onclick="scrollToSection('trivy-vulnerabilities')">
<div class="stat-number {("critical" if exec_summary.get("trivy_vulnerabilities_found", 0) > 10 else "high" if exec_summary.get("trivy_vulnerabilities_found", 0) > 5 else "medium" if exec_summary.get("trivy_vulnerabilities_found", 0) > 0 else "zero")}">{exec_summary.get("trivy_vulnerabilities_found", 0)}</div>
<div class="stat-label">Vulnerabilities</div>
</div>
<div class="stat-card clickable" onclick="scrollToSection('trivy-misconfigurations')">
<div class="stat-number {("high" if exec_summary.get("trivy_misconfigurations_found", 0) > 5 else "medium" if exec_summary.get("trivy_misconfigurations_found", 0) > 0 else "zero")}">{exec_summary.get("trivy_misconfigurations_found", 0)}</div>
<div class="stat-label">Misconfigurations</div>
</div>
</div>
<div style="text-align: center; margin: 20px 0;">
<span class="risk-badge risk-{exec_summary.get("risk_level", "info").lower()}">
Overall Risk: {esc(exec_summary.get("risk_level", "INFO"))}
</span>
</div>
<p style="color: #495057; line-height: 1.6; margin: 20px 0;">
{esc(exec_summary.get("description", "No description available."))}
</p>
</div>
<div class="section">
<h2>🔍 Scan Details</h2>
<div class="stats-grid">
<div class="stat-card clickable" onclick="scrollToSection('gitleaks-findings')">
<div class="stat-number {("critical" if scan_details.get("gitleaks", {}).get("findings", 0) > 0 else "zero")}">{scan_details.get("gitleaks", {}).get("findings", 0)}</div>
<div class="stat-label">Gitleaks Findings</div>
<div class="risk-badge risk-{scan_details.get("gitleaks", {}).get("risk_level", "info").lower()}" style="margin-top: 10px;">
{esc(scan_details.get("gitleaks", {}).get("risk_level", "INFO"))}
</div>
</div>
<div class="stat-card clickable" onclick="scrollToSection('trivy-vulnerabilities')">
<div class="stat-number {("critical" if scan_details.get("trivy_vulnerabilities", {}).get("findings", 0) > 10 else "high" if scan_details.get("trivy_vulnerabilities", {}).get("findings", 0) > 5 else "medium" if scan_details.get("trivy_vulnerabilities", {}).get("findings", 0) > 0 else "zero")}">{scan_details.get("trivy_vulnerabilities", {}).get("findings", 0)}</div>
<div class="stat-label">Trivy Vulnerabilities</div>
<div class="risk-badge risk-{scan_details.get("trivy_vulnerabilities", {}).get("risk_level", "info").lower()}" style="margin-top: 10px;">
{esc(scan_details.get("trivy_vulnerabilities", {}).get("risk_level", "INFO"))}
</div>
</div>
<div class="stat-card clickable" onclick="scrollToSection('trivy-misconfigurations')">
<div class="stat-number {("high" if scan_details.get("trivy_misconfigurations", {}).get("findings", 0) > 5 else "medium" if scan_details.get("trivy_misconfigurations", {}).get("findings", 0) > 0 else "zero")}">{scan_details.get("trivy_misconfigurations", {}).get("findings", 0)}</div>
<div class="stat-label">Trivy Misconfigurations</div>
<div class="risk-badge risk-{scan_details.get("trivy_misconfigurations", {}).get("risk_level", "info").lower()}" style="margin-top: 10px;">
{esc(scan_details.get("trivy_misconfigurations", {}).get("risk_level", "INFO"))}
</div>
</div>
</div>
</div>
<div class="section">
<h2>💡 Recommendations</h2>
<div class="recommendations">
"""
# Add recommendations by priority
for priority in ["critical", "high", "medium", "low", "info"]:
recs = recommendations.get(priority, [])
if recs:
html_content += f"""
<div class="rec-category">
<h3>{priority.title()} Priority</h3>
"""
for rec in recs:
html_content += f"""
<div class="rec-item rec-{priority}">{esc(rec)}</div>
"""
html_content += """
</div>
"""
html_content += """
</div>
</div>
<div class="section" id="detailed-findings">
<h2>🔍 Detailed Findings</h2>
<div class="findings-section">
"""
gitleaks_data = detailed_results.get("gitleaks", {})
if gitleaks_data and (isinstance(gitleaks_data, list) and len(gitleaks_data) > 0):
html_content += """
<div class="findings-tool" id="gitleaks-findings">
<h3>🔐 Gitleaks - Secret Detection</h3>
"""
for finding in gitleaks_data:
if isinstance(finding, dict):
description = finding.get("Description", "Secret detected")
file_path = finding.get("File", "Unknown file")
line_number = finding.get("StartLine", "Unknown line")
rule_id = finding.get("RuleID", "Unknown rule")
secret = finding.get("Secret", "")
masked_secret = (
secret[:4] + "*" * (len(secret) - 8) + secret[-4:]
if len(secret) > 8
else "*" * len(secret)
)
html_content += f"""
<div class="finding-item">
<div class="finding-header">
<div class="finding-title">{esc(description)}</div>
<div class="finding-severity severity-critical">CRITICAL</div>
</div>
<div class="finding-details">
<div class="finding-detail-row">
<span class="finding-label">File:</span>
<span class="finding-value">{esc(file_path)}</span>
</div>
<div class="finding-detail-row">
<span class="finding-label">Line:</span>
<span class="finding-value">{esc(str(line_number))}</span>
</div>
<div class="finding-detail-row">
<span class="finding-label">Rule:</span>
<span class="finding-value">{esc(rule_id)}</span>
</div>
<div class="finding-detail-row">
<span class="finding-label">Secret:</span>
<span class="finding-value code-snippet">{esc(masked_secret)}</span>
</div>
</div>
<div class="remediation-box">
<div class="remediation-title">🛠️ Remediation</div>
<div class="remediation-text">
1. Immediately rotate the exposed credential<br>
2. Remove the secret from git history using tools like git-filter-repo<br>
3. Store secrets in environment variables or secure vaults<br>
4. Add .gitignore rules to prevent future secret commits<br>
5. Implement pre-commit hooks for secret scanning
</div>
</div>
</div>
"""
html_content += """
</div>
"""
trivy_fs_data = detailed_results.get("trivy-fs", {})
if (
trivy_fs_data
and isinstance(trivy_fs_data, dict)
and trivy_fs_data.get("Results")
):
html_content += """
<div class="findings-tool" id="trivy-vulnerabilities">
<h3>🐛 Trivy - Vulnerability Scan</h3>
"""
for result in trivy_fs_data.get("Results", []):
if isinstance(result, dict) and result.get("Vulnerabilities"):
target = result.get("Target", "Unknown target")
for vuln in result.get("Vulnerabilities", []):
if isinstance(vuln, dict):
vuln_id = vuln.get("VulnerabilityID", "Unknown ID")
pkg_name = vuln.get("PkgName", "Unknown package")
installed_version = vuln.get(
"InstalledVersion", "Unknown version"
)
fixed_version = vuln.get("FixedVersion", "No fix available")
severity = vuln.get("Severity", "UNKNOWN")
title = vuln.get("Title", "Unknown vulnerability")
description = vuln.get(
"Description", "No description available"
)
html_content += f"""
<div class="finding-item">
<div class="finding-header">
<div class="finding-title">{esc(vuln_id)}: {esc(title)}</div>
<div class="finding-severity severity-{severity.lower()}">{esc(severity)}</div>
</div>
<div class="finding-details">
<div class="finding-detail-row">
<span class="finding-label">Package:</span>
<span class="finding-value">{esc(pkg_name)}</span>
</div>
<div class="finding-detail-row">
<span class="finding-label">Version:</span>
<span class="finding-value">{esc(installed_version)}</span>
</div>
<div class="finding-detail-row">
<span class="finding-label">Fixed In:</span>
<span class="finding-value">{esc(fixed_version)}</span>
</div>
<div class="finding-detail-row">
<span class="finding-label">Target:</span>
<span class="finding-value">{esc(target)}</span>
</div>
<div class="finding-detail-row">
<span class="finding-label">Description:</span>
<div class="finding-value">{esc(description[:200])}{"..." if len(description) > 200 else ""}</div>
</div>
</div>
<div class="remediation-box">
<div class="remediation-title">🛠️ Remediation</div>
<div class="remediation-text">
{"Update package to version " + esc(fixed_version) + " or later" if fixed_version != "No fix available" else "No fix currently available - monitor for updates"}
</div>
</div>
</div>
"""
html_content += """
</div>
"""
trivy_fs_data = detailed_results.get("trivy-fs", {})
if (
trivy_fs_data
and isinstance(trivy_fs_data, dict)
and trivy_fs_data.get("Results")
):
html_content += """
<div class="findings-tool" id="trivy-misconfigurations">
<h3>⚙️ Trivy - Misconfigurations</h3>
"""
for result in trivy_fs_data.get("Results", []):
if isinstance(result, dict) and result.get("Misconfigurations"):
target = result.get("Target", "Unknown target")
for misconfig in result.get("Misconfigurations", []):
if isinstance(misconfig, dict):
check_id = misconfig.get("ID", "Unknown ID")
title = misconfig.get("Title", "Unknown misconfiguration")
description = misconfig.get(
"Description", "No description available"
)
severity = misconfig.get("Severity", "UNKNOWN")
message = misconfig.get("Message", "No message available")
resolution = misconfig.get(
"Resolution", "No resolution provided"
)
html_content += f"""
<div class="finding-item">
<div class="finding-header">
<div class="finding-title">{esc(check_id)}: {esc(title)}</div>
<div class="finding-severity severity-{severity.lower()}">{esc(severity)}</div>
</div>
<div class="finding-details">
<div class="finding-detail-row">
<span class="finding-label">Target:</span>
<span class="finding-value">{esc(target)}</span>
</div>
<div class="finding-detail-row">
<span class="finding-label">Message:</span>
<div class="finding-value">{esc(message)}</div>
</div>
<div class="finding-detail-row">
<span class="finding-label">Description:</span>
<div class="finding-value">{esc(description[:200])}{"..." if len(description) > 200 else ""}</div>
</div>
</div>
<div class="remediation-box">
<div class="remediation-title">🛠️ Remediation</div>
<div class="remediation-text">
{esc(resolution) if resolution != "No resolution provided" else "Review configuration settings and apply security best practices"}
</div>
</div>
</div>
"""
html_content += """
</div>
"""
if not any(
[
gitleaks_data
and (isinstance(gitleaks_data, list) and len(gitleaks_data) > 0),
trivy_fs_data
and isinstance(trivy_fs_data, dict)
and trivy_fs_data.get("Results"),
]
):
html_content += """
<div style="text-align: center; padding: 40px; color: #6c757d;">
<h3>✅ No Security Issues Found</h3>
<p>All automated security scans completed without finding any issues.</p>
</div>
"""
footer_date = esc(meta.get("scan_date", "N/A"))
footer_time = esc(meta.get("scan_time", "N/A"))
footer_html = f"""
</div>
</div>
</div>
<div class="footer">
<p>Generated by GitHub Security Scanner | {footer_date} {footer_time}</p>
</div>
</div>
</body>
</html>
"""
html_content += footer_html
return html_content
def convert_consolidated_report_to_html(consolidated_report: Dict) -> str:
"""Convert consolidated organization report to HTML"""
def esc(text: Any) -> str:
return html.escape(str(text))
meta = consolidated_report.get("metadata", {})
exec_summary = consolidated_report.get("executive_summary", {})
recommendations = consolidated_report.get("recommendations", {})
top_repos = consolidated_report.get("top_repositories", {})
all_repos = consolidated_report.get("all_repositories", [])
html_content = f"""
<!DOCTYPE html>