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,330 @@
1
+ """Auto-discovery of cloud provider regions.
2
+
3
+ Queries each provider's APIs to enumerate available regions/locations,
4
+ with static fallbacks for air-gapped or credential-less environments.
5
+
6
+ Usage:
7
+ discovery = RegionDiscovery()
8
+ aws_regions = await discovery.discover_aws(session)
9
+ azure_regions = await discovery.discover_azure(credential, subscription_id)
10
+ gcp_regions = await discovery.discover_gcp(credentials, project_id)
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import logging
16
+ from typing import Any
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+
21
+ # ---------------------------------------------------------------------------
22
+ # Static fallback lists (updated periodically)
23
+ # ---------------------------------------------------------------------------
24
+
25
+ AWS_REGIONS_FALLBACK: list[str] = [
26
+ "us-east-1",
27
+ "us-east-2",
28
+ "us-west-1",
29
+ "us-west-2",
30
+ "af-south-1",
31
+ "ap-east-1",
32
+ "ap-south-1",
33
+ "ap-south-2",
34
+ "ap-southeast-1",
35
+ "ap-southeast-2",
36
+ "ap-southeast-3",
37
+ "ap-southeast-4",
38
+ "ap-northeast-1",
39
+ "ap-northeast-2",
40
+ "ap-northeast-3",
41
+ "ca-central-1",
42
+ "ca-west-1",
43
+ "eu-central-1",
44
+ "eu-central-2",
45
+ "eu-west-1",
46
+ "eu-west-2",
47
+ "eu-west-3",
48
+ "eu-south-1",
49
+ "eu-south-2",
50
+ "eu-north-1",
51
+ "il-central-1",
52
+ "me-south-1",
53
+ "me-central-1",
54
+ "sa-east-1",
55
+ ]
56
+
57
+ AZURE_LOCATIONS_FALLBACK: list[str] = [
58
+ "eastus",
59
+ "eastus2",
60
+ "westus",
61
+ "westus2",
62
+ "westus3",
63
+ "centralus",
64
+ "northcentralus",
65
+ "southcentralus",
66
+ "westcentralus",
67
+ "canadacentral",
68
+ "canadaeast",
69
+ "brazilsouth",
70
+ "brazilsoutheast",
71
+ "northeurope",
72
+ "westeurope",
73
+ "uksouth",
74
+ "ukwest",
75
+ "francecentral",
76
+ "francesouth",
77
+ "germanywestcentral",
78
+ "germanynorth",
79
+ "switzerlandnorth",
80
+ "switzerlandwest",
81
+ "norwayeast",
82
+ "norwaywest",
83
+ "swedencentral",
84
+ "polandcentral",
85
+ "italynorth",
86
+ "spaincentral",
87
+ "eastasia",
88
+ "southeastasia",
89
+ "japaneast",
90
+ "japanwest",
91
+ "koreacentral",
92
+ "koreasouth",
93
+ "centralindia",
94
+ "southindia",
95
+ "westindia",
96
+ "australiaeast",
97
+ "australiasoutheast",
98
+ "australiacentral",
99
+ "uaenorth",
100
+ "uaecentral",
101
+ "southafricanorth",
102
+ "southafricawest",
103
+ "qatarcentral",
104
+ "israelcentral",
105
+ ]
106
+
107
+ GCP_REGIONS_FALLBACK: list[str] = [
108
+ "us-central1",
109
+ "us-east1",
110
+ "us-east4",
111
+ "us-east5",
112
+ "us-south1",
113
+ "us-west1",
114
+ "us-west2",
115
+ "us-west3",
116
+ "us-west4",
117
+ "northamerica-northeast1",
118
+ "northamerica-northeast2",
119
+ "southamerica-east1",
120
+ "southamerica-west1",
121
+ "europe-central2",
122
+ "europe-north1",
123
+ "europe-southwest1",
124
+ "europe-west1",
125
+ "europe-west2",
126
+ "europe-west3",
127
+ "europe-west4",
128
+ "europe-west6",
129
+ "europe-west8",
130
+ "europe-west9",
131
+ "europe-west10",
132
+ "europe-west12",
133
+ "asia-east1",
134
+ "asia-east2",
135
+ "asia-northeast1",
136
+ "asia-northeast2",
137
+ "asia-northeast3",
138
+ "asia-south1",
139
+ "asia-south2",
140
+ "asia-southeast1",
141
+ "asia-southeast2",
142
+ "australia-southeast1",
143
+ "australia-southeast2",
144
+ "me-central1",
145
+ "me-central2",
146
+ "me-west1",
147
+ "africa-south1",
148
+ ]
149
+
150
+
151
+ # ---------------------------------------------------------------------------
152
+ # Region Discovery
153
+ # ---------------------------------------------------------------------------
154
+
155
+
156
+ class RegionDiscovery:
157
+ """Auto-discovers available regions for each cloud provider.
158
+
159
+ Falls back to static lists when APIs are unavailable.
160
+ """
161
+
162
+ async def discover_aws(self, session: Any = None) -> list[str]:
163
+ """Discover all enabled AWS regions.
164
+
165
+ Args:
166
+ session: boto3.Session (optional). If None, uses default.
167
+
168
+ Returns:
169
+ List of region names (e.g. ['us-east-1', 'eu-west-1', ...]).
170
+ """
171
+ try:
172
+ import boto3
173
+
174
+ sess = session or boto3.Session()
175
+ ec2 = sess.client("ec2", region_name="us-east-1")
176
+ response = ec2.describe_regions(
177
+ Filters=[{"Name": "opt-in-status", "Values": ["opt-in-not-required", "opted-in"]}]
178
+ )
179
+ regions = [r["RegionName"] for r in response.get("Regions", [])]
180
+ if regions:
181
+ logger.info("Discovered %d AWS regions via API", len(regions))
182
+ return sorted(regions)
183
+ except ImportError:
184
+ logger.warning("boto3 not installed, using fallback AWS regions")
185
+ except Exception as exc:
186
+ logger.warning("AWS region discovery failed (%s), using fallback", exc)
187
+
188
+ logger.info("Using %d fallback AWS regions", len(AWS_REGIONS_FALLBACK))
189
+ return AWS_REGIONS_FALLBACK
190
+
191
+ async def discover_azure(
192
+ self,
193
+ credential: Any = None,
194
+ subscription_id: str | None = None,
195
+ ) -> list[str]:
196
+ """Discover all Azure locations for a subscription.
197
+
198
+ Args:
199
+ credential: Azure credential object (optional).
200
+ subscription_id: Azure subscription ID (optional).
201
+
202
+ Returns:
203
+ List of location names (e.g. ['eastus', 'westeurope', ...]).
204
+ """
205
+ try:
206
+ from azure.identity import DefaultAzureCredential
207
+ from azure.mgmt.resource import SubscriptionClient
208
+
209
+ cred = credential or DefaultAzureCredential()
210
+ client = SubscriptionClient(cred)
211
+
212
+ if subscription_id:
213
+ locations = client.subscriptions.list_locations(subscription_id)
214
+ locs = [loc.name for loc in locations if loc.name]
215
+ else:
216
+ # If no subscription, try to get the first one
217
+ subs = list(client.subscriptions.list())
218
+ if subs:
219
+ sub_id = subs[0].subscription_id
220
+ locations = client.subscriptions.list_locations(sub_id)
221
+ locs = [loc.name for loc in locations if loc.name]
222
+ else:
223
+ locs = []
224
+
225
+ if locs:
226
+ logger.info("Discovered %d Azure locations via API", len(locs))
227
+ return sorted(locs)
228
+ except ImportError:
229
+ logger.warning("azure-mgmt-resource not installed, using fallback Azure locations")
230
+ except Exception as exc:
231
+ logger.warning("Azure location discovery failed (%s), using fallback", exc)
232
+
233
+ logger.info("Using %d fallback Azure locations", len(AZURE_LOCATIONS_FALLBACK))
234
+ return AZURE_LOCATIONS_FALLBACK
235
+
236
+ async def discover_gcp(
237
+ self,
238
+ credentials: Any = None,
239
+ project_id: str | None = None,
240
+ ) -> list[str]:
241
+ """Discover all GCP regions for a project.
242
+
243
+ Args:
244
+ credentials: Google auth credentials (optional).
245
+ project_id: GCP project ID (optional).
246
+
247
+ Returns:
248
+ List of region names (e.g. ['us-central1', 'europe-west1', ...]).
249
+ """
250
+ try:
251
+ from googleapiclient import discovery as gcp_discovery
252
+ import google.auth
253
+
254
+ creds = credentials
255
+ pid = project_id
256
+
257
+ if not creds:
258
+ creds, default_project = google.auth.default()
259
+ pid = pid or default_project
260
+
261
+ if not pid:
262
+ raise ValueError("GCP project ID required for region discovery")
263
+
264
+ service = gcp_discovery.build("compute", "v1", credentials=creds)
265
+ request = service.regions().list(project=pid)
266
+ response = request.execute()
267
+
268
+ regions = [r["name"] for r in response.get("items", []) if r.get("status") == "UP"]
269
+
270
+ if regions:
271
+ logger.info("Discovered %d GCP regions via API", len(regions))
272
+ return sorted(regions)
273
+ except ImportError:
274
+ logger.warning("google-api-python-client not installed, using fallback GCP regions")
275
+ except Exception as exc:
276
+ logger.warning("GCP region discovery failed (%s), using fallback", exc)
277
+
278
+ logger.info("Using %d fallback GCP regions", len(GCP_REGIONS_FALLBACK))
279
+ return GCP_REGIONS_FALLBACK
280
+
281
+ async def discover_all(
282
+ self,
283
+ providers: list[str],
284
+ aws_session: Any = None,
285
+ azure_credential: Any = None,
286
+ azure_subscription_id: str | None = None,
287
+ gcp_credentials: Any = None,
288
+ gcp_project_id: str | None = None,
289
+ ) -> dict[str, list[str]]:
290
+ """Discover regions for all specified providers.
291
+
292
+ Args:
293
+ providers: List of provider names ('aws', 'azure', 'gcp').
294
+
295
+ Returns:
296
+ Dict mapping provider name → list of regions.
297
+ """
298
+ import asyncio
299
+
300
+ result: dict[str, list[str]] = {}
301
+ tasks: dict[str, Any] = {}
302
+
303
+ if "aws" in providers:
304
+ tasks["aws"] = self.discover_aws(aws_session)
305
+ if "azure" in providers:
306
+ tasks["azure"] = self.discover_azure(azure_credential, azure_subscription_id)
307
+ if "gcp" in providers:
308
+ tasks["gcp"] = self.discover_gcp(gcp_credentials, gcp_project_id)
309
+
310
+ if tasks:
311
+ gathered = await asyncio.gather(*tasks.values(), return_exceptions=True)
312
+ for provider, regions_or_exc in zip(tasks.keys(), gathered):
313
+ if isinstance(regions_or_exc, Exception):
314
+ logger.error("Region discovery failed for %s: %s", provider, regions_or_exc)
315
+ # Use fallback
316
+ fallbacks = {
317
+ "aws": AWS_REGIONS_FALLBACK,
318
+ "azure": AZURE_LOCATIONS_FALLBACK,
319
+ "gcp": GCP_REGIONS_FALLBACK,
320
+ }
321
+ result[provider] = fallbacks.get(provider, [])
322
+ else:
323
+ result[provider] = regions_or_exc
324
+
325
+ return result
326
+
327
+
328
+ def is_all_regions(regions: list[str]) -> bool:
329
+ """Check if the region list is the 'ALL' sentinel."""
330
+ return len(regions) == 1 and regions[0].upper() == "ALL"
cloudg/registry.py ADDED
@@ -0,0 +1,142 @@
1
+ """Plugin registry — discovers collectors and scanners via entry_points."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import importlib
6
+ import logging
7
+ from importlib.metadata import entry_points
8
+ from typing import Any, Type
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+ # Entry point group names
13
+ COLLECTOR_GROUP = "cloudg.collectors"
14
+ SCANNER_GROUP = "cloudg.scanners"
15
+
16
+ # Built-in fallback mappings (used when no entry_points are registered)
17
+ _BUILTIN_COLLECTORS: dict[str, str] = {
18
+ "aws": "cloudg.collectors.aws:AsyncAWSCollector",
19
+ "azure": "cloudg.collectors.azure:AzureCollector",
20
+ "gcp": "cloudg.collectors.gcp:GCPCollector",
21
+ }
22
+
23
+ _BUILTIN_SCANNERS: dict[str, str] = {
24
+ "prowler": "cloudg.scanners.prowler:ProwlerScanner",
25
+ "scoutsuite": "cloudg.scanners.scoutsuite:ScoutSuiteScanner",
26
+ "checkov": "cloudg.scanners.checkov:CheckovScanner",
27
+ "trivy": "cloudg.scanners.trivy:TrivyScanner",
28
+ "iam": "cloudg.scanners.iam_linter:IAMLinter",
29
+ }
30
+
31
+
32
+ def _load_class(dotted_path: str) -> Type[Any]:
33
+ """Import a class from a 'module.path:ClassName' string."""
34
+ module_path, class_name = dotted_path.rsplit(":", 1)
35
+ module = importlib.import_module(module_path)
36
+ return getattr(module, class_name)
37
+
38
+
39
+ class PluginRegistry:
40
+ """Discovers and loads plugins via setuptools entry_points.
41
+
42
+ Falls back to built-in mappings when no entry_points are found.
43
+
44
+ Usage:
45
+ registry = PluginRegistry()
46
+ collector_cls = registry.get_collector("aws")
47
+ scanner_cls = registry.get_scanner("prowler")
48
+ """
49
+
50
+ def __init__(self) -> None:
51
+ self._collectors: dict[str, Type[Any]] = {}
52
+ self._scanners: dict[str, Type[Any]] = {}
53
+ self._discovered = False
54
+
55
+ def _discover(self) -> None:
56
+ """Discover plugins from entry_points (lazy, runs once)."""
57
+ if self._discovered:
58
+ return
59
+ self._discovered = True
60
+
61
+ # Discover collectors
62
+ try:
63
+ eps = entry_points()
64
+ collector_eps = (
65
+ eps.select(group=COLLECTOR_GROUP)
66
+ if hasattr(eps, "select")
67
+ else eps.get(COLLECTOR_GROUP, [])
68
+ )
69
+ for ep in collector_eps:
70
+ try:
71
+ self._collectors[ep.name] = ep.load()
72
+ logger.debug("Loaded collector plugin: %s", ep.name)
73
+ except Exception as exc:
74
+ logger.warning("Failed to load collector plugin %s: %s", ep.name, exc)
75
+ except Exception:
76
+ pass
77
+
78
+ # Discover scanners
79
+ try:
80
+ eps = entry_points()
81
+ scanner_eps = (
82
+ eps.select(group=SCANNER_GROUP)
83
+ if hasattr(eps, "select")
84
+ else eps.get(SCANNER_GROUP, [])
85
+ )
86
+ for ep in scanner_eps:
87
+ try:
88
+ self._scanners[ep.name] = ep.load()
89
+ logger.debug("Loaded scanner plugin: %s", ep.name)
90
+ except Exception as exc:
91
+ logger.warning("Failed to load scanner plugin %s: %s", ep.name, exc)
92
+ except Exception:
93
+ pass
94
+
95
+ # Fill in built-in defaults for any not discovered
96
+ for name, path in _BUILTIN_COLLECTORS.items():
97
+ if name not in self._collectors:
98
+ try:
99
+ self._collectors[name] = _load_class(path)
100
+ except Exception as exc:
101
+ logger.debug("Built-in collector %s not available: %s", name, exc)
102
+
103
+ for name, path in _BUILTIN_SCANNERS.items():
104
+ if name not in self._scanners:
105
+ try:
106
+ self._scanners[name] = _load_class(path)
107
+ except Exception as exc:
108
+ logger.debug("Built-in scanner %s not available: %s", name, exc)
109
+
110
+ logger.info(
111
+ "Plugin registry: %d collectors, %d scanners",
112
+ len(self._collectors),
113
+ len(self._scanners),
114
+ )
115
+
116
+ def get_collector(self, name: str) -> Type[Any]:
117
+ """Get a collector class by name."""
118
+ self._discover()
119
+ if name not in self._collectors:
120
+ raise KeyError(
121
+ f"No collector registered for '{name}'. Available: {list(self._collectors.keys())}"
122
+ )
123
+ return self._collectors[name]
124
+
125
+ def get_scanner(self, name: str) -> Type[Any]:
126
+ """Get a scanner class by name."""
127
+ self._discover()
128
+ if name not in self._scanners:
129
+ raise KeyError(
130
+ f"No scanner registered for '{name}'. Available: {list(self._scanners.keys())}"
131
+ )
132
+ return self._scanners[name]
133
+
134
+ def list_collectors(self) -> list[str]:
135
+ """List registered collector names."""
136
+ self._discover()
137
+ return list(self._collectors.keys())
138
+
139
+ def list_scanners(self) -> list[str]:
140
+ """List registered scanner names."""
141
+ self._discover()
142
+ return list(self._scanners.keys())
@@ -0,0 +1 @@
1
+ """Renderers package."""