cloudg 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. cloudg/__init__.py +21 -0
  2. cloudg/api.py +613 -0
  3. cloudg/cli.py +934 -0
  4. cloudg/collectors/__init__.py +5 -0
  5. cloudg/collectors/aws.py +830 -0
  6. cloudg/collectors/azure.py +362 -0
  7. cloudg/collectors/base.py +44 -0
  8. cloudg/collectors/gcp.py +170 -0
  9. cloudg/collectors/multi.py +329 -0
  10. cloudg/config.py +261 -0
  11. cloudg/coverage.py +93 -0
  12. cloudg/credentials.py +451 -0
  13. cloudg/graph/__init__.py +6 -0
  14. cloudg/graph/builder.py +336 -0
  15. cloudg/graph/ontology.py +914 -0
  16. cloudg/graph/rag_export.py +533 -0
  17. cloudg/graph/reachability.py +237 -0
  18. cloudg/normaliser.py +390 -0
  19. cloudg/policies/custodian-aws-security.yml +139 -0
  20. cloudg/policies/custodian-azure.yml +95 -0
  21. cloudg/policies/custodian-gcp.yml +87 -0
  22. cloudg/policies/custodian.yml +131 -0
  23. cloudg/region_discovery.py +330 -0
  24. cloudg/registry.py +142 -0
  25. cloudg/renderers/__init__.py +1 -0
  26. cloudg/renderers/html_report.py +430 -0
  27. cloudg/renderers/json_export.py +65 -0
  28. cloudg/renderers/svg.py +689 -0
  29. cloudg/renderers/terraform_export.py +666 -0
  30. cloudg/retry.py +103 -0
  31. cloudg/rules/cis_aws_v3.yaml +148 -0
  32. cloudg/rules/cis_azure_v2.yaml +142 -0
  33. cloudg/rules/cis_gcp_v3.yaml +133 -0
  34. cloudg/rules/frameworks/aws_foundational_security_best_practices_aws.yaml +1286 -0
  35. cloudg/rules/frameworks/cis_5.0_aws.yaml +280 -0
  36. cloudg/rules/frameworks/cis_5.0_azure.yaml +475 -0
  37. cloudg/rules/frameworks/cis_5.0_gcp.yaml +327 -0
  38. cloudg/rules/frameworks/gdpr_aws.yaml +95 -0
  39. cloudg/rules/frameworks/hipaa_aws.yaml +461 -0
  40. cloudg/rules/frameworks/hipaa_azure.yaml +504 -0
  41. cloudg/rules/frameworks/hipaa_gcp.yaml +211 -0
  42. cloudg/rules/frameworks/iso27001_2022_aws.yaml +789 -0
  43. cloudg/rules/frameworks/iso27001_2022_azure.yaml +477 -0
  44. cloudg/rules/frameworks/iso27001_2022_gcp.yaml +240 -0
  45. cloudg/rules/frameworks/mitre_attack_aws.yaml +596 -0
  46. cloudg/rules/frameworks/mitre_attack_azure.yaml +418 -0
  47. cloudg/rules/frameworks/mitre_attack_gcp.yaml +300 -0
  48. cloudg/rules/frameworks/nist_800_53_revision_5_aws.yaml +3234 -0
  49. cloudg/rules/frameworks/nist_csf_2.0_aws.yaml +828 -0
  50. cloudg/rules/frameworks/pci_4.0_aws.yaml +7108 -0
  51. cloudg/rules/frameworks/pci_4.0_azure.yaml +4696 -0
  52. cloudg/rules/frameworks/pci_4.0_gcp.yaml +5405 -0
  53. cloudg/rules/frameworks/soc2_aws.yaml +421 -0
  54. cloudg/rules/frameworks/soc2_azure.yaml +477 -0
  55. cloudg/rules/frameworks/soc2_gcp.yaml +342 -0
  56. cloudg/rules/gdpr.yaml +56 -0
  57. cloudg/rules/hipaa_security_rule.yaml +83 -0
  58. cloudg/rules/iso_27001_2022.yaml +88 -0
  59. cloudg/rules/nist_800_53.yaml +134 -0
  60. cloudg/rules/pci_dss_v4.yaml +108 -0
  61. cloudg/rules/soc2_tsc.yaml +93 -0
  62. cloudg/scanners/__init__.py +1 -0
  63. cloudg/scanners/checkov.py +174 -0
  64. cloudg/scanners/iam_linter.py +200 -0
  65. cloudg/scanners/prowler.py +237 -0
  66. cloudg/scanners/scoutsuite.py +163 -0
  67. cloudg/scanners/trivy.py +339 -0
  68. cloudg/schema/__init__.py +25 -0
  69. cloudg/schema/models.py +260 -0
  70. cloudg/templates/report.html.j2 +828 -0
  71. cloudg-0.3.0.dist-info/METADATA +330 -0
  72. cloudg-0.3.0.dist-info/RECORD +75 -0
  73. cloudg-0.3.0.dist-info/WHEEL +4 -0
  74. cloudg-0.3.0.dist-info/entry_points.txt +14 -0
  75. cloudg-0.3.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,237 @@
1
+ """BFS-based network reachability analysis."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from typing import Any
7
+
8
+ import networkx as nx
9
+
10
+ from cloudg.schema.models import AssetType, Finding, Severity
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+ # Ports that are considered sensitive when exposed to the internet
15
+ SENSITIVE_PORTS = {
16
+ 22: "SSH",
17
+ 3389: "RDP",
18
+ 3306: "MySQL",
19
+ 5432: "PostgreSQL",
20
+ 1433: "MSSQL",
21
+ 27017: "MongoDB",
22
+ 6379: "Redis",
23
+ 9200: "Elasticsearch",
24
+ 5601: "Kibana",
25
+ 8080: "HTTP-Alt",
26
+ 8443: "HTTPS-Alt",
27
+ }
28
+
29
+ # Asset types that should NOT be internet-exposed
30
+ SENSITIVE_ASSET_TYPES = {
31
+ AssetType.RDS_INSTANCE,
32
+ AssetType.AURORA_CLUSTER,
33
+ AssetType.AZURE_SQL,
34
+ AssetType.CLOUD_SQL,
35
+ AssetType.DYNAMODB_TABLE,
36
+ }
37
+
38
+ # Asset types where internet exposure is expected
39
+ EXPECTED_EXPOSED_TYPES = {
40
+ AssetType.LOAD_BALANCER,
41
+ AssetType.CLOUDFRONT,
42
+ AssetType.CDN,
43
+ AssetType.INTERNET_GATEWAY,
44
+ }
45
+
46
+
47
+ class ReachabilityAnalyzer:
48
+ """Analyses network reachability via BFS on the infrastructure graph.
49
+
50
+ 1. Find all nodes reachable from 0.0.0.0/0 → "internet-exposed"
51
+ 2. From each exposed node, BFS to find internally-reachable resources → "blast radius"
52
+ 3. Cross-reference with asset type to generate severity-scored findings.
53
+ """
54
+
55
+ def __init__(self, graph: nx.DiGraph) -> None:
56
+ self._graph = graph
57
+
58
+ def find_internet_exposed(self) -> set[str]:
59
+ """Find all nodes reachable from internet-facing entry points (0.0.0.0/0).
60
+
61
+ Returns:
62
+ Set of node IDs that are internet-exposed.
63
+ """
64
+ internet_nodes = set()
65
+
66
+ # Find all nodes that represent internet CIDR sources
67
+ for node_id, data in self._graph.nodes(data=True):
68
+ name = data.get("name", node_id)
69
+ if name in ("0.0.0.0/0", "::/0") or data.get("is_external"):
70
+ internet_nodes.add(node_id)
71
+
72
+ # Also find edges with internet CIDRs
73
+ for source, target, data in self._graph.edges(data=True):
74
+ cidr = data.get("cidr", "")
75
+ if cidr in ("0.0.0.0/0", "::/0"):
76
+ internet_nodes.add(source)
77
+
78
+ # BFS from all internet entry points
79
+ exposed: set[str] = set()
80
+ for entry_point in internet_nodes:
81
+ reachable = nx.descendants(self._graph, entry_point)
82
+ exposed.update(reachable)
83
+
84
+ # Mark nodes in graph
85
+ for node_id in exposed:
86
+ if node_id in self._graph:
87
+ self._graph.nodes[node_id]["is_internet_exposed"] = True
88
+
89
+ logger.info("Found %d internet-exposed nodes", len(exposed))
90
+ return exposed
91
+
92
+ def compute_blast_radius(self, node_id: str) -> dict[str, Any]:
93
+ """Compute blast radius: all nodes reachable from a given node.
94
+
95
+ Args:
96
+ node_id: Starting node for BFS.
97
+
98
+ Returns:
99
+ Dict with 'reachable_nodes', 'depth', and 'risk_score'.
100
+ """
101
+ if node_id not in self._graph:
102
+ return {"reachable_nodes": [], "depth": 0, "risk_score": 0.0}
103
+
104
+ reachable = nx.descendants(self._graph, node_id)
105
+ bfs_tree = nx.bfs_tree(self._graph, node_id)
106
+
107
+ # Calculate max depth
108
+ if len(bfs_tree) > 1:
109
+ lengths = nx.single_source_shortest_path_length(bfs_tree, node_id)
110
+ max_depth = max(lengths.values()) if lengths else 0
111
+ else:
112
+ max_depth = 0
113
+
114
+ # Risk score based on number of reachable nodes and their types
115
+ risk_score = min(10.0, len(reachable) * 0.5)
116
+
117
+ # Increase risk if sensitive assets are reachable
118
+ for r_node in reachable:
119
+ node_data = self._graph.nodes.get(r_node, {})
120
+ asset_type_str = node_data.get("asset_type", "")
121
+ try:
122
+ asset_type = AssetType(asset_type_str)
123
+ if asset_type in SENSITIVE_ASSET_TYPES:
124
+ risk_score = min(10.0, risk_score + 2.0)
125
+ except ValueError:
126
+ pass
127
+
128
+ return {
129
+ "reachable_nodes": list(reachable),
130
+ "depth": max_depth,
131
+ "risk_score": round(risk_score, 1),
132
+ }
133
+
134
+ def generate_findings(self) -> list[Finding]:
135
+ """Generate security findings based on reachability analysis.
136
+
137
+ Returns:
138
+ List of Finding objects for reachability-related security issues.
139
+ """
140
+ findings: list[Finding] = []
141
+ exposed_nodes = self.find_internet_exposed()
142
+
143
+ for node_id in exposed_nodes:
144
+ node_data = self._graph.nodes.get(node_id, {})
145
+ asset_type_str = node_data.get("asset_type", "")
146
+ name = node_data.get("name", node_id)
147
+ arn = node_data.get("arn", "")
148
+
149
+ # Skip external/placeholder nodes
150
+ if node_data.get("is_external"):
151
+ continue
152
+
153
+ try:
154
+ asset_type = AssetType(asset_type_str)
155
+ except ValueError:
156
+ continue
157
+
158
+ # Check for sensitive asset types exposed to internet
159
+ if asset_type in SENSITIVE_ASSET_TYPES:
160
+ findings.append(
161
+ Finding(
162
+ resource_id=node_id,
163
+ resource_arn=arn,
164
+ severity=Severity.CRITICAL,
165
+ title=f"Internet-exposed {asset_type.value}: {name}",
166
+ description=(
167
+ f"The {asset_type.value} resource '{name}' is reachable "
168
+ f"from the internet (0.0.0.0/0). Database and data-store "
169
+ f"resources should never be directly internet-accessible."
170
+ ),
171
+ evidence=f"BFS reachability from 0.0.0.0/0 reaches node {node_id}",
172
+ remediation=(
173
+ "Restrict security group / NSG / firewall rules to remove "
174
+ "internet access. Place behind a private subnet with NAT "
175
+ "gateway or VPN."
176
+ ),
177
+ source_tool="cloudg-reachability",
178
+ compliance_frameworks=["CIS", "NIST-800-53"],
179
+ )
180
+ )
181
+ elif asset_type not in EXPECTED_EXPOSED_TYPES:
182
+ # Non-database but unexpected exposure
183
+ findings.append(
184
+ Finding(
185
+ resource_id=node_id,
186
+ resource_arn=arn,
187
+ severity=Severity.HIGH,
188
+ title=f"Unexpected internet-exposed resource: {name}",
189
+ description=(
190
+ f"The {asset_type.value} resource '{name}' is reachable "
191
+ f"from the internet. Verify this exposure is intentional."
192
+ ),
193
+ evidence=f"BFS reachability from 0.0.0.0/0 reaches node {node_id}",
194
+ remediation=(
195
+ "Review security group / NSG rules. If exposure is not "
196
+ "required, restrict to specific CIDR ranges or VPN."
197
+ ),
198
+ source_tool="cloudg-reachability",
199
+ )
200
+ )
201
+
202
+ # Check for sensitive port exposure on security group edges
203
+ for source, target, data in self._graph.edges(data=True):
204
+ cidr = data.get("cidr", "")
205
+ if cidr not in ("0.0.0.0/0", "::/0"):
206
+ continue
207
+
208
+ ports = data.get("ports", [])
209
+ port_range = data.get("port_range", "")
210
+
211
+ for port, service in SENSITIVE_PORTS.items():
212
+ if port in ports or str(port) in port_range:
213
+ target_data = self._graph.nodes.get(target, {})
214
+ findings.append(
215
+ Finding(
216
+ resource_id=target,
217
+ resource_arn=target_data.get("arn", ""),
218
+ severity=Severity.CRITICAL,
219
+ title=f"Security group allows {service} (port {port}) from 0.0.0.0/0",
220
+ description=(
221
+ f"A security group rule allows inbound traffic on "
222
+ f"port {port} ({service}) from 0.0.0.0/0. This is a "
223
+ f"common attack vector."
224
+ ),
225
+ evidence=f"Edge from {source} to {target}, port {port}, cidr {cidr}",
226
+ remediation=(
227
+ f"Restrict port {port} ({service}) access to specific "
228
+ f"IP ranges. Use a bastion host or VPN for "
229
+ f"administrative access."
230
+ ),
231
+ source_tool="cloudg-reachability",
232
+ compliance_frameworks=["CIS", "NIST-800-53", "PCI-DSS"],
233
+ )
234
+ )
235
+
236
+ logger.info("Generated %d reachability findings", len(findings))
237
+ return findings
cloudg/normaliser.py ADDED
@@ -0,0 +1,390 @@
1
+ """Findings normaliser — pass-through aggregator using scanner-native compliance mappings.
2
+
3
+ Primary: Extracts compliance IDs from scanner-native fields (Prowler ASFF, Checkov, etc.)
4
+ Secondary: Loads external rulesets from YAML files in rules/ directory
5
+ Fallback: Pattern-matching rules for untagged findings only
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import logging
11
+ import re
12
+ from collections import defaultdict
13
+ from datetime import datetime
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from cloudg.schema.models import (
18
+ ComplianceResult,
19
+ ComplianceStatus,
20
+ Finding,
21
+ ScanResult,
22
+ Severity,
23
+ )
24
+
25
+ logger = logging.getLogger(__name__)
26
+
27
+
28
+ # ─────────────────────────────────────────────────────────────────
29
+ # FALLBACK ONLY — used when scanners don't emit compliance metadata.
30
+ # All real compliance mappings come from scanner-native outputs.
31
+ # ─────────────────────────────────────────────────────────────────
32
+ _FALLBACK_RULES: dict[str, list[dict[str, str]]] = {
33
+ "CIS": [
34
+ {"pattern": r"s3.*public", "control": "CIS-2.1.2"},
35
+ {"pattern": r"root.*mfa", "control": "CIS-1.5"},
36
+ {"pattern": r"cloudtrail", "control": "CIS-3.1"},
37
+ {"pattern": r"flow.*log", "control": "CIS-3.9"},
38
+ {"pattern": r"encryption", "control": "CIS-2.1"},
39
+ {"pattern": r"access.*key.*rotat", "control": "CIS-1.4"},
40
+ ],
41
+ "NIST-800-53": [
42
+ {"pattern": r"access.*control", "control": "AC-2"},
43
+ {"pattern": r"encryption", "control": "SC-28"},
44
+ {"pattern": r"logging", "control": "AU-2"},
45
+ {"pattern": r"mfa", "control": "IA-2"},
46
+ {"pattern": r"network", "control": "SC-7"},
47
+ ],
48
+ "PCI-DSS": [
49
+ {"pattern": r"encryption", "control": "PCI-3.4"},
50
+ {"pattern": r"firewall", "control": "PCI-1.1"},
51
+ {"pattern": r"access", "control": "PCI-7.1"},
52
+ {"pattern": r"logging", "control": "PCI-10.1"},
53
+ ],
54
+ "GDPR": [
55
+ {"pattern": r"encryption", "control": "GDPR-32"},
56
+ {"pattern": r"access.*control", "control": "GDPR-25"},
57
+ {"pattern": r"logging", "control": "GDPR-30"},
58
+ ],
59
+ "SOC2": [
60
+ {"pattern": r"access.*control", "control": "SOC2-CC6.1"},
61
+ {"pattern": r"encryption", "control": "SOC2-CC6.7"},
62
+ {"pattern": r"monitoring|logging", "control": "SOC2-CC7.2"},
63
+ ],
64
+ "HIPAA": [
65
+ {"pattern": r"encryption", "control": "HIPAA-164.312(a)(2)(iv)"},
66
+ {"pattern": r"access.*control", "control": "HIPAA-164.312(a)(1)"},
67
+ {"pattern": r"audit|log", "control": "HIPAA-164.312(b)"},
68
+ ],
69
+ }
70
+
71
+
72
+ def _load_external_rulesets(rules_dir: str | Path) -> dict[str, list[dict[str, Any]]]:
73
+ """Load YAML rulesets from the rules directory.
74
+
75
+ Each YAML file should have:
76
+ framework: str
77
+ controls:
78
+ - id: str
79
+ patterns: list[str]
80
+ severity: str (optional)
81
+ """
82
+ rules_path = Path(rules_dir)
83
+ rulesets: dict[str, list[dict[str, Any]]] = {}
84
+
85
+ if not rules_path.exists():
86
+ return rulesets
87
+
88
+ try:
89
+ import yaml
90
+ except ImportError:
91
+ logger.debug("PyYAML not installed, skipping external rulesets")
92
+ return rulesets
93
+
94
+ for yaml_file in sorted(rules_path.rglob("*.yaml")):
95
+ try:
96
+ with open(yaml_file) as f:
97
+ data = yaml.safe_load(f) or {}
98
+
99
+ framework = data.get("framework", yaml_file.stem)
100
+ controls = data.get("controls", [])
101
+ if controls:
102
+ # Merge: several files may extend the same framework
103
+ # (e.g. hand-written patterns + generated check mappings)
104
+ rulesets.setdefault(framework, []).extend(controls)
105
+ logger.debug("Loaded %d rules from %s", len(controls), yaml_file.name)
106
+
107
+ except Exception as exc:
108
+ logger.warning("Failed to load ruleset %s: %s", yaml_file, exc)
109
+
110
+ return rulesets
111
+
112
+
113
+ class FindingsNormaliser:
114
+ """Pass-through aggregator: merges findings from all scanners.
115
+
116
+ Compliance mapping priority:
117
+ 1. Scanner-native fields (Prowler ASFF RelatedRequirements, Checkov check_id, etc.)
118
+ 2. Exact check-ID lookup against ruleset `checks` lists (generated from
119
+ Prowler's public compliance data — see scripts/import_prowler_compliance.py)
120
+ 3. External YAML ruleset regex patterns from the rules/ directory
121
+ 4. Fallback regex patterns for untagged findings
122
+
123
+ Deduplication key: (resource_arn, title)
124
+ Scoring: composite of severity + CVSS
125
+ """
126
+
127
+ def __init__(self, rules_dir: str | Path | None = None) -> None:
128
+ if rules_dir is None:
129
+ from cloudg.config import _default_rules_dir
130
+
131
+ rules_dir = _default_rules_dir()
132
+ self._findings: list[Finding] = []
133
+ self._compliance: list[ComplianceResult] = []
134
+ self._external_rules = _load_external_rulesets(rules_dir)
135
+ # Exact-match index: scanner check ID -> [(framework, control_id, title)]
136
+ self._check_index: dict[str, list[tuple[str, str, str]]] = {}
137
+ for framework, controls in self._external_rules.items():
138
+ for control in controls:
139
+ for check in control.get("checks", []) or []:
140
+ self._check_index.setdefault(check, []).append(
141
+ (framework, str(control.get("id", "")), control.get("title", ""))
142
+ )
143
+ # Per-finding exact matches recorded during scoring, keyed by finding id
144
+ self._exact_matches: dict[str, list[tuple[str, str, str]]] = {}
145
+
146
+ def normalise(
147
+ self,
148
+ *finding_lists: list[Finding],
149
+ assets: list | None = None,
150
+ ) -> ScanResult:
151
+ """Merge, deduplicate, score, and map findings to compliance.
152
+
153
+ Args:
154
+ finding_lists: Variable number of finding lists from different sources.
155
+ assets: Optional asset list for the ScanResult container.
156
+
157
+ Returns:
158
+ ScanResult with normalised findings and compliance mappings.
159
+ """
160
+ # Merge all findings
161
+ all_findings: list[Finding] = []
162
+ for finding_list in finding_lists:
163
+ all_findings.extend(finding_list)
164
+
165
+ logger.info(
166
+ "Normalising %d total findings from %d sources",
167
+ len(all_findings),
168
+ len(finding_lists),
169
+ )
170
+
171
+ # Deduplicate
172
+ deduplicated = self._deduplicate(all_findings)
173
+ logger.info("After deduplication: %d findings", len(deduplicated))
174
+
175
+ # Score findings
176
+ scored = self._score_findings(deduplicated)
177
+
178
+ # Sort by severity
179
+ severity_order = {
180
+ Severity.CRITICAL: 0,
181
+ Severity.HIGH: 1,
182
+ Severity.MEDIUM: 2,
183
+ Severity.LOW: 3,
184
+ Severity.INFO: 4,
185
+ }
186
+ scored.sort(key=lambda f: severity_order.get(f.severity, 5))
187
+
188
+ # Map to compliance frameworks
189
+ compliance = self._map_compliance(scored)
190
+
191
+ self._findings = scored
192
+ self._compliance = compliance
193
+
194
+ return ScanResult(
195
+ assets=assets or [],
196
+ findings=scored,
197
+ compliance=compliance,
198
+ completed_at=datetime.utcnow(),
199
+ )
200
+
201
+ def _deduplicate(self, findings: list[Finding]) -> list[Finding]:
202
+ """Deduplicate findings by (resource_arn, title) key.
203
+
204
+ When duplicates are found, keep the highest-severity one and
205
+ merge source tools.
206
+ """
207
+ seen: dict[tuple[str, str], Finding] = {}
208
+
209
+ for finding in findings:
210
+ key = (finding.resource_arn or finding.resource_id, finding.title)
211
+
212
+ if key in seen:
213
+ existing = seen[key]
214
+ # Keep higher severity
215
+ severity_rank = {
216
+ Severity.CRITICAL: 0,
217
+ Severity.HIGH: 1,
218
+ Severity.MEDIUM: 2,
219
+ Severity.LOW: 3,
220
+ Severity.INFO: 4,
221
+ }
222
+ if severity_rank.get(finding.severity, 5) < severity_rank.get(existing.severity, 5):
223
+ # Merge source info and compliance frameworks
224
+ merged_tool = f"{existing.source_tool}, {finding.source_tool}"
225
+ merged_frameworks = list(
226
+ set(existing.compliance_frameworks + finding.compliance_frameworks)
227
+ )
228
+ finding.source_tool = merged_tool
229
+ finding.compliance_frameworks = merged_frameworks
230
+ seen[key] = finding
231
+ else:
232
+ existing.source_tool = f"{existing.source_tool}, {finding.source_tool}"
233
+ existing.compliance_frameworks = list(
234
+ set(existing.compliance_frameworks + finding.compliance_frameworks)
235
+ )
236
+ else:
237
+ seen[key] = finding
238
+
239
+ return list(seen.values())
240
+
241
+ def _score_findings(self, findings: list[Finding]) -> list[Finding]:
242
+ """Apply composite scoring to findings."""
243
+ for finding in findings:
244
+ # CVSS-based adjustment
245
+ if finding.cvss_score is not None and finding.cvss_score >= 9.0:
246
+ finding.severity = Severity.CRITICAL
247
+ elif finding.cvss_score is not None and finding.cvss_score >= 7.0:
248
+ if finding.severity not in (Severity.CRITICAL,):
249
+ finding.severity = Severity.HIGH
250
+
251
+ # Enrich compliance frameworks:
252
+ # 1. Scanner-native frameworks are already on the finding (primary)
253
+ # 2. Exact check-ID lookup (high precision, always applied)
254
+ # 3. External YAML ruleset regex patterns (secondary)
255
+ # 4. Fallback regex (last resort)
256
+ exact = self._match_check_ids(finding)
257
+ if exact:
258
+ self._exact_matches[finding.id] = exact
259
+ for fw, _control_id, _title in exact:
260
+ if fw not in finding.compliance_frameworks:
261
+ finding.compliance_frameworks.append(fw)
262
+
263
+ if not finding.compliance_frameworks:
264
+ # Only apply pattern tiers if nothing else provided a mapping
265
+ additional = self._map_from_external_rulesets(finding)
266
+ if not additional:
267
+ additional = self._map_from_fallback_rules(finding)
268
+ for fw in additional:
269
+ if fw not in finding.compliance_frameworks:
270
+ finding.compliance_frameworks.append(fw)
271
+
272
+ return findings
273
+
274
+ def _match_check_ids(self, finding: Finding) -> list[tuple[str, str, str]]:
275
+ """Match a finding's scanner check ID against ruleset `checks` lists.
276
+
277
+ Prowler ASFF finding IDs embed the check name between dashes
278
+ (e.g. "prowler-aws-iam_root_hardware_mfa_enabled-123-eu-west-1-..."),
279
+ and check names themselves never contain dashes, so splitting the
280
+ source ID on separators yields the check name as one token.
281
+ """
282
+ if not self._check_index:
283
+ return []
284
+
285
+ src = finding.source_finding_id or ""
286
+ matches: list[tuple[str, str, str]] = []
287
+ seen: set[tuple[str, str]] = set()
288
+ for token in re.split(r"[-/:\s]", src):
289
+ for fw, control_id, title in self._check_index.get(token, []):
290
+ if (fw, control_id) not in seen:
291
+ seen.add((fw, control_id))
292
+ matches.append((fw, control_id, title))
293
+ return matches
294
+
295
+ def _map_from_external_rulesets(self, finding: Finding) -> list[str]:
296
+ """Map finding to compliance frameworks using external YAML rulesets."""
297
+ frameworks: list[str] = []
298
+ text = f"{finding.title} {finding.description}".lower()
299
+
300
+ for framework, controls in self._external_rules.items():
301
+ for control in controls:
302
+ patterns = control.get("patterns", [])
303
+ for pattern in patterns:
304
+ if re.search(pattern, text, re.IGNORECASE):
305
+ if framework not in frameworks:
306
+ frameworks.append(framework)
307
+ break
308
+
309
+ return frameworks
310
+
311
+ def _map_from_fallback_rules(self, finding: Finding) -> list[str]:
312
+ """FALLBACK: Map finding to frameworks when no scanner-native or external match."""
313
+ frameworks: list[str] = []
314
+ text = f"{finding.title} {finding.description}".lower()
315
+
316
+ for framework, rules in _FALLBACK_RULES.items():
317
+ for rule in rules:
318
+ if re.search(rule["pattern"], text, re.IGNORECASE):
319
+ if framework not in frameworks:
320
+ frameworks.append(framework)
321
+ break
322
+
323
+ return frameworks
324
+
325
+ def _map_compliance(self, findings: list[Finding]) -> list[ComplianceResult]:
326
+ """Generate per-control ComplianceResult entries from findings."""
327
+ # Group findings by (framework, control_id). Exact check-ID matches
328
+ # (from ruleset `checks` lists) give the real control ID and title;
329
+ # everything else falls back to parsing source_finding_id.
330
+ control_findings: dict[tuple[str, str], list[str]] = defaultdict(list)
331
+ control_titles: dict[tuple[str, str], str] = {}
332
+
333
+ for finding in findings:
334
+ exact = self._exact_matches.get(finding.id, [])
335
+ exact_frameworks = set()
336
+ for fw, control_id, title in exact:
337
+ control_findings[(fw, control_id)].append(finding.id)
338
+ if title:
339
+ control_titles[(fw, control_id)] = title
340
+ exact_frameworks.add(fw)
341
+
342
+ for fw in finding.compliance_frameworks:
343
+ if fw in exact_frameworks:
344
+ continue
345
+ # Use scanner-native control ID if available in source_finding_id
346
+ control_id = self._extract_control_id(finding, fw)
347
+ control_findings[(fw, control_id)].append(finding.id)
348
+
349
+ results: list[ComplianceResult] = []
350
+ for (framework, control_id), finding_ids in control_findings.items():
351
+ results.append(
352
+ ComplianceResult(
353
+ framework=framework,
354
+ control_id=control_id,
355
+ control_title=control_titles.get(
356
+ (framework, control_id), f"{framework} — {control_id}"
357
+ ),
358
+ status=ComplianceStatus.FAIL if finding_ids else ComplianceStatus.PASS,
359
+ finding_ids=finding_ids,
360
+ )
361
+ )
362
+
363
+ return results
364
+
365
+ @staticmethod
366
+ def _extract_control_id(finding: Finding, framework: str) -> str:
367
+ """Extract a control ID from the scanner-native finding ID.
368
+
369
+ Prowler example source_finding_id: "prowler-aws-iam_root_hardware_mfa_enabled-..."
370
+ Checkov example: "CKV_AWS_18"
371
+
372
+ Falls back to framework-aggregate if no specific ID found.
373
+ """
374
+ src_id = finding.source_finding_id or ""
375
+
376
+ # Prowler: extract check name from ASFF Id
377
+ if "prowler" in finding.source_tool.lower() and "-" in src_id:
378
+ parts = src_id.split("-")
379
+ if len(parts) >= 4:
380
+ return f"{framework}/{'-'.join(parts[2:4])}"
381
+
382
+ # Checkov: check_id is typically "CKV_AWS_XX"
383
+ if "checkov" in finding.source_tool.lower() and src_id.startswith("CKV"):
384
+ return f"{framework}/{src_id}"
385
+
386
+ # Trivy: CVE IDs
387
+ if "trivy" in finding.source_tool.lower() and src_id.startswith("CVE"):
388
+ return f"{framework}/{src_id}"
389
+
390
+ return f"{framework}-aggregate"