regscale-cli 6.27.2.0__py3-none-any.whl → 6.28.0.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.
Potentially problematic release.
This version of regscale-cli might be problematic. Click here for more details.
- regscale/_version.py +1 -1
- regscale/core/app/application.py +1 -0
- regscale/core/app/internal/control_editor.py +73 -21
- regscale/core/app/internal/login.py +4 -1
- regscale/core/app/internal/model_editor.py +219 -64
- regscale/core/app/utils/app_utils.py +11 -2
- regscale/core/login.py +21 -4
- regscale/core/utils/date.py +77 -1
- regscale/dev/cli.py +26 -0
- regscale/dev/version.py +72 -0
- regscale/integrations/commercial/__init__.py +15 -1
- regscale/integrations/commercial/amazon/amazon/__init__.py +0 -0
- regscale/integrations/commercial/amazon/amazon/common.py +204 -0
- regscale/integrations/commercial/amazon/common.py +48 -58
- regscale/integrations/commercial/aws/audit_manager_compliance.py +2671 -0
- regscale/integrations/commercial/aws/cli.py +3093 -55
- regscale/integrations/commercial/aws/cloudtrail_control_mappings.py +333 -0
- regscale/integrations/commercial/aws/cloudtrail_evidence.py +501 -0
- regscale/integrations/commercial/aws/cloudwatch_control_mappings.py +357 -0
- regscale/integrations/commercial/aws/cloudwatch_evidence.py +490 -0
- regscale/integrations/commercial/aws/config_compliance.py +914 -0
- regscale/integrations/commercial/aws/conformance_pack_mappings.py +198 -0
- regscale/integrations/commercial/aws/evidence_generator.py +283 -0
- regscale/integrations/commercial/aws/guardduty_control_mappings.py +340 -0
- regscale/integrations/commercial/aws/guardduty_evidence.py +1053 -0
- regscale/integrations/commercial/aws/iam_control_mappings.py +368 -0
- regscale/integrations/commercial/aws/iam_evidence.py +574 -0
- regscale/integrations/commercial/aws/inventory/__init__.py +223 -22
- regscale/integrations/commercial/aws/inventory/base.py +107 -5
- regscale/integrations/commercial/aws/inventory/resources/audit_manager.py +513 -0
- regscale/integrations/commercial/aws/inventory/resources/cloudtrail.py +315 -0
- regscale/integrations/commercial/aws/inventory/resources/cloudtrail_logs_metadata.py +476 -0
- regscale/integrations/commercial/aws/inventory/resources/cloudwatch.py +191 -0
- regscale/integrations/commercial/aws/inventory/resources/compute.py +66 -9
- regscale/integrations/commercial/aws/inventory/resources/config.py +464 -0
- regscale/integrations/commercial/aws/inventory/resources/containers.py +74 -9
- regscale/integrations/commercial/aws/inventory/resources/database.py +106 -31
- regscale/integrations/commercial/aws/inventory/resources/guardduty.py +286 -0
- regscale/integrations/commercial/aws/inventory/resources/iam.py +470 -0
- regscale/integrations/commercial/aws/inventory/resources/inspector.py +476 -0
- regscale/integrations/commercial/aws/inventory/resources/integration.py +175 -61
- regscale/integrations/commercial/aws/inventory/resources/kms.py +447 -0
- regscale/integrations/commercial/aws/inventory/resources/networking.py +103 -67
- regscale/integrations/commercial/aws/inventory/resources/s3.py +394 -0
- regscale/integrations/commercial/aws/inventory/resources/security.py +268 -72
- regscale/integrations/commercial/aws/inventory/resources/securityhub.py +473 -0
- regscale/integrations/commercial/aws/inventory/resources/storage.py +53 -29
- regscale/integrations/commercial/aws/inventory/resources/systems_manager.py +657 -0
- regscale/integrations/commercial/aws/inventory/resources/vpc.py +655 -0
- regscale/integrations/commercial/aws/kms_control_mappings.py +288 -0
- regscale/integrations/commercial/aws/kms_evidence.py +879 -0
- regscale/integrations/commercial/aws/ocsf/__init__.py +7 -0
- regscale/integrations/commercial/aws/ocsf/constants.py +115 -0
- regscale/integrations/commercial/aws/ocsf/mapper.py +435 -0
- regscale/integrations/commercial/aws/org_control_mappings.py +286 -0
- regscale/integrations/commercial/aws/org_evidence.py +666 -0
- regscale/integrations/commercial/aws/s3_control_mappings.py +356 -0
- regscale/integrations/commercial/aws/s3_evidence.py +632 -0
- regscale/integrations/commercial/aws/scanner.py +853 -205
- regscale/integrations/commercial/aws/security_hub.py +319 -0
- regscale/integrations/commercial/aws/session_manager.py +282 -0
- regscale/integrations/commercial/aws/ssm_control_mappings.py +291 -0
- regscale/integrations/commercial/aws/ssm_evidence.py +492 -0
- regscale/integrations/commercial/synqly/query_builder.py +4 -1
- regscale/integrations/compliance_integration.py +308 -38
- regscale/integrations/control_matcher.py +78 -23
- regscale/integrations/due_date_handler.py +3 -0
- regscale/integrations/public/csam/csam.py +572 -763
- regscale/integrations/public/csam/csam_agency_defined.py +179 -0
- regscale/integrations/public/csam/csam_common.py +154 -0
- regscale/integrations/public/csam/csam_controls.py +432 -0
- regscale/integrations/public/csam/csam_poam.py +124 -0
- regscale/integrations/public/fedramp/click.py +17 -4
- regscale/integrations/public/fedramp/fedramp_cis_crm.py +271 -62
- regscale/integrations/public/fedramp/poam/scanner.py +74 -7
- regscale/integrations/scanner_integration.py +415 -85
- regscale/models/integration_models/cisa_kev_data.json +80 -20
- regscale/models/integration_models/synqly_models/capabilities.json +1 -1
- regscale/models/integration_models/synqly_models/connectors/vulnerabilities.py +44 -3
- regscale/models/integration_models/synqly_models/ocsf_mapper.py +41 -12
- regscale/models/platform.py +3 -0
- regscale/models/regscale_models/__init__.py +5 -0
- regscale/models/regscale_models/assessment.py +2 -1
- regscale/models/regscale_models/component.py +1 -1
- regscale/models/regscale_models/control_implementation.py +55 -24
- regscale/models/regscale_models/control_objective.py +74 -5
- regscale/models/regscale_models/file.py +2 -0
- regscale/models/regscale_models/issue.py +2 -5
- regscale/models/regscale_models/organization.py +3 -0
- regscale/models/regscale_models/regscale_model.py +17 -5
- regscale/models/regscale_models/security_plan.py +1 -0
- regscale/regscale.py +11 -1
- {regscale_cli-6.27.2.0.dist-info → regscale_cli-6.28.0.0.dist-info}/METADATA +1 -1
- {regscale_cli-6.27.2.0.dist-info → regscale_cli-6.28.0.0.dist-info}/RECORD +140 -57
- tests/regscale/core/test_login.py +171 -4
- tests/regscale/integrations/commercial/aws/__init__.py +0 -0
- tests/regscale/integrations/commercial/aws/test_audit_manager_compliance.py +1304 -0
- tests/regscale/integrations/commercial/aws/test_audit_manager_evidence_aggregation.py +341 -0
- tests/regscale/integrations/commercial/aws/test_aws_audit_manager_collector.py +1155 -0
- tests/regscale/integrations/commercial/aws/test_aws_cloudtrail_collector.py +534 -0
- tests/regscale/integrations/commercial/aws/test_aws_config_collector.py +400 -0
- tests/regscale/integrations/commercial/aws/test_aws_guardduty_collector.py +315 -0
- tests/regscale/integrations/commercial/aws/test_aws_iam_collector.py +458 -0
- tests/regscale/integrations/commercial/aws/test_aws_inspector_collector.py +353 -0
- tests/regscale/integrations/commercial/aws/test_aws_inventory_integration.py +530 -0
- tests/regscale/integrations/commercial/aws/test_aws_kms_collector.py +919 -0
- tests/regscale/integrations/commercial/aws/test_aws_s3_collector.py +722 -0
- tests/regscale/integrations/commercial/aws/test_aws_scanner_integration.py +722 -0
- tests/regscale/integrations/commercial/aws/test_aws_securityhub_collector.py +792 -0
- tests/regscale/integrations/commercial/aws/test_aws_systems_manager_collector.py +918 -0
- tests/regscale/integrations/commercial/aws/test_aws_vpc_collector.py +996 -0
- tests/regscale/integrations/commercial/aws/test_cli_evidence.py +431 -0
- tests/regscale/integrations/commercial/aws/test_cloudtrail_control_mappings.py +452 -0
- tests/regscale/integrations/commercial/aws/test_cloudtrail_evidence.py +788 -0
- tests/regscale/integrations/commercial/aws/test_config_compliance.py +298 -0
- tests/regscale/integrations/commercial/aws/test_conformance_pack_mappings.py +200 -0
- tests/regscale/integrations/commercial/aws/test_evidence_generator.py +386 -0
- tests/regscale/integrations/commercial/aws/test_guardduty_control_mappings.py +564 -0
- tests/regscale/integrations/commercial/aws/test_guardduty_evidence.py +1041 -0
- tests/regscale/integrations/commercial/aws/test_iam_control_mappings.py +718 -0
- tests/regscale/integrations/commercial/aws/test_iam_evidence.py +1375 -0
- tests/regscale/integrations/commercial/aws/test_kms_control_mappings.py +656 -0
- tests/regscale/integrations/commercial/aws/test_kms_evidence.py +1163 -0
- tests/regscale/integrations/commercial/aws/test_ocsf_mapper.py +370 -0
- tests/regscale/integrations/commercial/aws/test_org_control_mappings.py +546 -0
- tests/regscale/integrations/commercial/aws/test_org_evidence.py +1240 -0
- tests/regscale/integrations/commercial/aws/test_s3_control_mappings.py +672 -0
- tests/regscale/integrations/commercial/aws/test_s3_evidence.py +987 -0
- tests/regscale/integrations/commercial/aws/test_scanner_evidence.py +373 -0
- tests/regscale/integrations/commercial/aws/test_security_hub_config_filtering.py +539 -0
- tests/regscale/integrations/commercial/aws/test_session_manager.py +516 -0
- tests/regscale/integrations/commercial/aws/test_ssm_control_mappings.py +588 -0
- tests/regscale/integrations/commercial/aws/test_ssm_evidence.py +735 -0
- tests/regscale/integrations/commercial/test_aws.py +55 -56
- tests/regscale/integrations/test_control_matcher.py +24 -0
- tests/regscale/models/test_control_implementation.py +118 -3
- {regscale_cli-6.27.2.0.dist-info → regscale_cli-6.28.0.0.dist-info}/LICENSE +0 -0
- {regscale_cli-6.27.2.0.dist-info → regscale_cli-6.28.0.0.dist-info}/WHEEL +0 -0
- {regscale_cli-6.27.2.0.dist-info → regscale_cli-6.28.0.0.dist-info}/entry_points.txt +0 -0
- {regscale_cli-6.27.2.0.dist-info → regscale_cli-6.28.0.0.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,490 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""AWS CloudWatch Logs Evidence Integration for RegScale Compliance."""
|
|
4
|
+
|
|
5
|
+
import gzip
|
|
6
|
+
import json
|
|
7
|
+
import logging
|
|
8
|
+
import os
|
|
9
|
+
import tempfile
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from datetime import datetime, timedelta
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any, Dict, List, Optional
|
|
14
|
+
|
|
15
|
+
import boto3
|
|
16
|
+
|
|
17
|
+
from regscale.core.app.api import Api
|
|
18
|
+
from regscale.integrations.commercial.aws.cloudwatch_control_mappings import CloudWatchControlMapper
|
|
19
|
+
from regscale.integrations.commercial.aws.inventory.resources.cloudwatch import CloudWatchLogsCollector
|
|
20
|
+
from regscale.integrations.compliance_integration import ComplianceIntegration
|
|
21
|
+
from regscale.models.regscale_models.file import File
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger("regscale")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass
|
|
27
|
+
class CloudWatchEvidenceConfig:
|
|
28
|
+
"""Configuration for AWS CloudWatch Logs evidence collection."""
|
|
29
|
+
|
|
30
|
+
plan_id: int
|
|
31
|
+
region: str = "us-east-1"
|
|
32
|
+
framework: str = "NIST800-53R5"
|
|
33
|
+
create_issues: bool = False
|
|
34
|
+
update_control_status: bool = True
|
|
35
|
+
create_poams: bool = False
|
|
36
|
+
parent_module: str = "securityplans"
|
|
37
|
+
account_id: Optional[str] = None
|
|
38
|
+
tags: Optional[Dict[str, str]] = None
|
|
39
|
+
log_group_prefix: Optional[str] = None
|
|
40
|
+
create_evidence: bool = False
|
|
41
|
+
create_ssp_attachment: bool = True
|
|
42
|
+
evidence_control_ids: Optional[List[str]] = None
|
|
43
|
+
force_refresh: bool = False
|
|
44
|
+
aws_profile: Optional[str] = None
|
|
45
|
+
aws_access_key_id: Optional[str] = None
|
|
46
|
+
aws_secret_access_key: Optional[str] = None
|
|
47
|
+
aws_session_token: Optional[str] = None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class CloudWatchComplianceItem:
|
|
51
|
+
"""Represents CloudWatch Logs configuration for compliance assessment."""
|
|
52
|
+
|
|
53
|
+
def __init__(self, cloudwatch_data: Dict[str, Any]):
|
|
54
|
+
"""
|
|
55
|
+
Initialize CloudWatch compliance item from configuration data.
|
|
56
|
+
|
|
57
|
+
:param Dict cloudwatch_data: CloudWatch Logs data from CloudWatchLogsCollector
|
|
58
|
+
"""
|
|
59
|
+
self.log_groups = cloudwatch_data.get("LogGroups", [])
|
|
60
|
+
self.log_group_metrics = cloudwatch_data.get("LogGroupMetrics", {})
|
|
61
|
+
self.retention_policies = cloudwatch_data.get("RetentionPolicies", {})
|
|
62
|
+
self.raw_data = cloudwatch_data
|
|
63
|
+
|
|
64
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
65
|
+
"""Convert to dictionary representation."""
|
|
66
|
+
return self.raw_data
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class AWSCloudWatchEvidenceIntegration(ComplianceIntegration):
|
|
70
|
+
"""AWS CloudWatch Logs evidence integration for compliance data collection."""
|
|
71
|
+
|
|
72
|
+
def __init__(self, config: CloudWatchEvidenceConfig):
|
|
73
|
+
"""
|
|
74
|
+
Initialize AWS CloudWatch Logs evidence integration.
|
|
75
|
+
|
|
76
|
+
:param CloudWatchEvidenceConfig config: Configuration object containing all parameters
|
|
77
|
+
"""
|
|
78
|
+
super().__init__(
|
|
79
|
+
plan_id=config.plan_id,
|
|
80
|
+
framework=config.framework,
|
|
81
|
+
create_issues=config.create_issues,
|
|
82
|
+
update_control_status=config.update_control_status,
|
|
83
|
+
create_poams=config.create_poams,
|
|
84
|
+
parent_module=config.parent_module,
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
self.plan_id = config.plan_id
|
|
88
|
+
self.region = config.region
|
|
89
|
+
self.title = "AWS CloudWatch Logs"
|
|
90
|
+
self.account_id = config.account_id
|
|
91
|
+
self.tags = config.tags or {}
|
|
92
|
+
self.log_group_prefix = config.log_group_prefix
|
|
93
|
+
self.create_evidence = config.create_evidence
|
|
94
|
+
self.create_ssp_attachment = config.create_ssp_attachment
|
|
95
|
+
self.evidence_control_ids = config.evidence_control_ids or []
|
|
96
|
+
self.force_refresh = config.force_refresh
|
|
97
|
+
|
|
98
|
+
# Initialize control mapper
|
|
99
|
+
self.control_mapper = CloudWatchControlMapper(framework=config.framework)
|
|
100
|
+
|
|
101
|
+
# AWS credentials
|
|
102
|
+
self.aws_profile = config.aws_profile
|
|
103
|
+
self.aws_access_key_id = config.aws_access_key_id
|
|
104
|
+
self.aws_secret_access_key = config.aws_secret_access_key
|
|
105
|
+
self.aws_session_token = config.aws_session_token
|
|
106
|
+
|
|
107
|
+
# Initialize components
|
|
108
|
+
self.api = Api()
|
|
109
|
+
self.session = None
|
|
110
|
+
self.collector = None
|
|
111
|
+
|
|
112
|
+
# Cache configuration
|
|
113
|
+
self.cache_ttl_hours = 4
|
|
114
|
+
self.cache_dir = Path(tempfile.gettempdir()) / "regscale" / "aws_cloudwatch_cache"
|
|
115
|
+
self.cache_dir.mkdir(parents=True, exist_ok=True)
|
|
116
|
+
|
|
117
|
+
# Data storage
|
|
118
|
+
self.raw_cloudwatch_data: Dict[str, Any] = {}
|
|
119
|
+
self.cloudwatch_item: Optional[CloudWatchComplianceItem] = None
|
|
120
|
+
|
|
121
|
+
def _get_cache_file_path(self) -> Path:
|
|
122
|
+
"""Get cache file path for CloudWatch data."""
|
|
123
|
+
cache_key = f"{self.region}_{self.account_id or 'default'}"
|
|
124
|
+
return self.cache_dir / f"cloudwatch_logs_{cache_key}.json"
|
|
125
|
+
|
|
126
|
+
def _is_cache_valid(self) -> bool:
|
|
127
|
+
"""Check if cache is valid and not expired."""
|
|
128
|
+
cache_file = self._get_cache_file_path()
|
|
129
|
+
if not cache_file.exists():
|
|
130
|
+
return False
|
|
131
|
+
|
|
132
|
+
cache_age = datetime.now() - datetime.fromtimestamp(cache_file.stat().st_mtime)
|
|
133
|
+
return cache_age < timedelta(hours=self.cache_ttl_hours)
|
|
134
|
+
|
|
135
|
+
def _save_cache(self, data: Dict[str, Any]) -> None:
|
|
136
|
+
"""Save CloudWatch data to cache."""
|
|
137
|
+
cache_file = self._get_cache_file_path()
|
|
138
|
+
try:
|
|
139
|
+
with open(cache_file, "w", encoding="utf-8") as f:
|
|
140
|
+
json.dump(data, f, default=str)
|
|
141
|
+
logger.debug(f"Saved CloudWatch data to cache: {cache_file}")
|
|
142
|
+
except Exception as e:
|
|
143
|
+
logger.warning(f"Failed to save cache: {e}")
|
|
144
|
+
|
|
145
|
+
def _load_cached_data(self) -> Optional[Dict[str, Any]]:
|
|
146
|
+
"""Load CloudWatch data from cache."""
|
|
147
|
+
cache_file = self._get_cache_file_path()
|
|
148
|
+
try:
|
|
149
|
+
with open(cache_file, encoding="utf-8") as f:
|
|
150
|
+
data = json.load(f)
|
|
151
|
+
|
|
152
|
+
# Validate cache format - must be a dict
|
|
153
|
+
if not isinstance(data, dict):
|
|
154
|
+
logger.warning("Invalid cache format detected (not a dict). Invalidating cache.")
|
|
155
|
+
return None
|
|
156
|
+
|
|
157
|
+
logger.info(f"Loaded CloudWatch data from cache (age: {self._get_cache_age_hours():.1f} hours)")
|
|
158
|
+
return data
|
|
159
|
+
except Exception as e:
|
|
160
|
+
logger.warning(f"Failed to load cache: {e}")
|
|
161
|
+
return None
|
|
162
|
+
|
|
163
|
+
def _get_cache_age_hours(self) -> float:
|
|
164
|
+
"""Get cache age in hours."""
|
|
165
|
+
cache_file = self._get_cache_file_path()
|
|
166
|
+
if not cache_file.exists():
|
|
167
|
+
return float("inf")
|
|
168
|
+
cache_age = datetime.now() - datetime.fromtimestamp(cache_file.stat().st_mtime)
|
|
169
|
+
return cache_age.total_seconds() / 3600
|
|
170
|
+
|
|
171
|
+
def _initialize_aws_session(self) -> None:
|
|
172
|
+
"""Initialize AWS session using provided credentials."""
|
|
173
|
+
if self.aws_access_key_id and self.aws_secret_access_key:
|
|
174
|
+
self.session = boto3.Session(
|
|
175
|
+
aws_access_key_id=self.aws_access_key_id,
|
|
176
|
+
aws_secret_access_key=self.aws_secret_access_key,
|
|
177
|
+
aws_session_token=self.aws_session_token,
|
|
178
|
+
region_name=self.region,
|
|
179
|
+
)
|
|
180
|
+
elif self.aws_profile:
|
|
181
|
+
self.session = boto3.Session(profile_name=self.aws_profile, region_name=self.region)
|
|
182
|
+
else:
|
|
183
|
+
self.session = boto3.Session(region_name=self.region)
|
|
184
|
+
logger.info(f"Initialized AWS session for region: {self.region}")
|
|
185
|
+
|
|
186
|
+
def fetch_compliance_data(self) -> Dict[str, Any]:
|
|
187
|
+
"""
|
|
188
|
+
Fetch CloudWatch Logs configuration data from AWS.
|
|
189
|
+
|
|
190
|
+
:return: CloudWatch Logs configuration data
|
|
191
|
+
:rtype: Dict[str, Any]
|
|
192
|
+
"""
|
|
193
|
+
# Check cache first
|
|
194
|
+
if not self.force_refresh and self._is_cache_valid():
|
|
195
|
+
cached_data = self._load_cached_data()
|
|
196
|
+
if cached_data:
|
|
197
|
+
return cached_data
|
|
198
|
+
|
|
199
|
+
# Fetch fresh data
|
|
200
|
+
return self._fetch_fresh_cloudwatch_data()
|
|
201
|
+
|
|
202
|
+
def _fetch_fresh_cloudwatch_data(self) -> Dict[str, Any]:
|
|
203
|
+
"""
|
|
204
|
+
Fetch fresh CloudWatch Logs data from AWS API.
|
|
205
|
+
|
|
206
|
+
:return: CloudWatch Logs configuration data
|
|
207
|
+
:rtype: Dict[str, Any]
|
|
208
|
+
"""
|
|
209
|
+
logger.info(f"Fetching CloudWatch Logs configurations from AWS region: {self.region}")
|
|
210
|
+
|
|
211
|
+
# Initialize AWS session
|
|
212
|
+
if not self.session:
|
|
213
|
+
self._initialize_aws_session()
|
|
214
|
+
|
|
215
|
+
# Create CloudWatch Logs collector
|
|
216
|
+
self.collector = CloudWatchLogsCollector(
|
|
217
|
+
session=self.session, region=self.region, account_id=self.account_id, tags=self.tags
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
# Collect CloudWatch data
|
|
221
|
+
self.raw_cloudwatch_data = self.collector.collect()
|
|
222
|
+
|
|
223
|
+
# Apply log group prefix filter if specified
|
|
224
|
+
if self.log_group_prefix:
|
|
225
|
+
original_count = len(self.raw_cloudwatch_data.get("LogGroups", []))
|
|
226
|
+
self.raw_cloudwatch_data["LogGroups"] = [
|
|
227
|
+
lg
|
|
228
|
+
for lg in self.raw_cloudwatch_data.get("LogGroups", [])
|
|
229
|
+
if lg.get("logGroupName", "").startswith(self.log_group_prefix)
|
|
230
|
+
]
|
|
231
|
+
filtered_count = len(self.raw_cloudwatch_data["LogGroups"])
|
|
232
|
+
logger.info(
|
|
233
|
+
f"Applied log group prefix filter '{self.log_group_prefix}': {filtered_count}/{original_count} log groups match"
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
log_group_count = len(self.raw_cloudwatch_data.get("LogGroups", []))
|
|
237
|
+
logger.info(f"Collected {log_group_count} CloudWatch log group(s) from region {self.region}")
|
|
238
|
+
|
|
239
|
+
# Save to cache
|
|
240
|
+
self._save_cache(self.raw_cloudwatch_data)
|
|
241
|
+
|
|
242
|
+
return self.raw_cloudwatch_data
|
|
243
|
+
|
|
244
|
+
def sync_compliance_data(self) -> None:
|
|
245
|
+
"""Sync CloudWatch Logs compliance data to RegScale."""
|
|
246
|
+
logger.info("Starting AWS CloudWatch Logs compliance data sync to RegScale")
|
|
247
|
+
|
|
248
|
+
# Fetch CloudWatch data
|
|
249
|
+
cloudwatch_data = self.fetch_compliance_data()
|
|
250
|
+
if not cloudwatch_data or not cloudwatch_data.get("LogGroups"):
|
|
251
|
+
logger.warning("No CloudWatch Logs data to sync")
|
|
252
|
+
return
|
|
253
|
+
|
|
254
|
+
# Convert to compliance item
|
|
255
|
+
self.cloudwatch_item = CloudWatchComplianceItem(cloudwatch_data)
|
|
256
|
+
logger.info(
|
|
257
|
+
f"Processing {len(self.cloudwatch_item.log_groups)} CloudWatch log group(s) for compliance assessment"
|
|
258
|
+
)
|
|
259
|
+
|
|
260
|
+
# Assess compliance
|
|
261
|
+
compliance_results = self._assess_compliance()
|
|
262
|
+
|
|
263
|
+
# Populate control dictionaries for assessment creation
|
|
264
|
+
if self.update_control_status:
|
|
265
|
+
self._populate_control_results(compliance_results["overall"])
|
|
266
|
+
# Create control assessments and update implementation statuses
|
|
267
|
+
self._process_control_assessments()
|
|
268
|
+
|
|
269
|
+
# Create evidence artifacts
|
|
270
|
+
if self.create_evidence or self.create_ssp_attachment:
|
|
271
|
+
self._create_evidence_artifacts(compliance_results)
|
|
272
|
+
|
|
273
|
+
logger.info("AWS CloudWatch Logs compliance sync completed successfully")
|
|
274
|
+
|
|
275
|
+
def create_compliance_item(self, raw_data: Dict[str, Any]):
|
|
276
|
+
"""
|
|
277
|
+
Create a ComplianceItem from raw CloudWatch data.
|
|
278
|
+
|
|
279
|
+
:param Dict[str, Any] raw_data: Raw CloudWatch Logs data
|
|
280
|
+
:return: CloudWatchComplianceItem instance
|
|
281
|
+
:rtype: CloudWatchComplianceItem
|
|
282
|
+
"""
|
|
283
|
+
return CloudWatchComplianceItem(raw_data)
|
|
284
|
+
|
|
285
|
+
def _assess_compliance(self) -> Dict[str, Any]:
|
|
286
|
+
"""
|
|
287
|
+
Assess CloudWatch compliance against NIST controls.
|
|
288
|
+
|
|
289
|
+
:return: Compliance assessment results
|
|
290
|
+
:rtype: Dict[str, Any]
|
|
291
|
+
"""
|
|
292
|
+
logger.info("Assessing CloudWatch Logs compliance against NIST 800-53 R5 controls")
|
|
293
|
+
|
|
294
|
+
# Assess overall compliance
|
|
295
|
+
overall_results = self.control_mapper.assess_cloudwatch_compliance(self.cloudwatch_item.to_dict())
|
|
296
|
+
|
|
297
|
+
# Log summary
|
|
298
|
+
passed_controls = [ctrl for ctrl, result in overall_results.items() if result == "PASS"]
|
|
299
|
+
failed_controls = [ctrl for ctrl, result in overall_results.items() if result == "FAIL"]
|
|
300
|
+
|
|
301
|
+
logger.info("CloudWatch Logs Compliance Assessment Summary:")
|
|
302
|
+
logger.info(f" Total Log Groups: {len(self.cloudwatch_item.log_groups)}")
|
|
303
|
+
logger.info(
|
|
304
|
+
f" Total Stored Bytes: {sum(m.get('StoredBytes', 0) for m in self.cloudwatch_item.log_group_metrics.values())}"
|
|
305
|
+
)
|
|
306
|
+
logger.info(f" Controls Passed: {len(passed_controls)} - {', '.join(passed_controls)}")
|
|
307
|
+
logger.info(f" Controls Failed: {len(failed_controls)} - {', '.join(failed_controls)}")
|
|
308
|
+
|
|
309
|
+
return {"overall": overall_results}
|
|
310
|
+
|
|
311
|
+
def _populate_control_results(self, control_results: Dict[str, str]) -> None:
|
|
312
|
+
"""
|
|
313
|
+
Populate passing_controls and failing_controls dictionaries from assessment results.
|
|
314
|
+
|
|
315
|
+
This method converts the control-level assessment results into the format expected
|
|
316
|
+
by the base class _process_control_assessments() method.
|
|
317
|
+
|
|
318
|
+
:param Dict[str, str] control_results: Control assessment results (e.g., {"AC-2": "PASS", "AC-3": "FAIL"})
|
|
319
|
+
:return: None
|
|
320
|
+
:rtype: None
|
|
321
|
+
"""
|
|
322
|
+
for control_id, result in control_results.items():
|
|
323
|
+
# Normalize control ID to lowercase for consistent lookup
|
|
324
|
+
control_key = control_id.lower()
|
|
325
|
+
|
|
326
|
+
# Create a simple compliance item placeholder for the base class
|
|
327
|
+
# The base class uses these to determine pass/fail status
|
|
328
|
+
if result in self.PASS_STATUSES:
|
|
329
|
+
self.passing_controls[control_key] = self.cloudwatch_item
|
|
330
|
+
elif result in self.FAIL_STATUSES:
|
|
331
|
+
self.failing_controls[control_key] = self.cloudwatch_item
|
|
332
|
+
|
|
333
|
+
logger.debug(
|
|
334
|
+
f"Populated control results: {len(self.passing_controls)} passing, {len(self.failing_controls)} failing"
|
|
335
|
+
)
|
|
336
|
+
|
|
337
|
+
def _create_evidence_artifacts(self, compliance_results: Dict[str, Any]) -> None:
|
|
338
|
+
"""
|
|
339
|
+
Create evidence artifacts in RegScale.
|
|
340
|
+
|
|
341
|
+
:param Dict compliance_results: Compliance assessment results
|
|
342
|
+
"""
|
|
343
|
+
logger.info("Creating CloudWatch Logs evidence artifacts in RegScale")
|
|
344
|
+
|
|
345
|
+
# Create comprehensive evidence file
|
|
346
|
+
evidence_file_path = self._create_evidence_file(compliance_results)
|
|
347
|
+
|
|
348
|
+
if self.create_ssp_attachment:
|
|
349
|
+
self._create_ssp_attachment_with_evidence(evidence_file_path)
|
|
350
|
+
|
|
351
|
+
# Clean up temporary file
|
|
352
|
+
if os.path.exists(evidence_file_path):
|
|
353
|
+
os.remove(evidence_file_path)
|
|
354
|
+
logger.debug(f"Cleaned up temporary evidence file: {evidence_file_path}")
|
|
355
|
+
|
|
356
|
+
def _create_evidence_file(self, compliance_results: Dict[str, Any]) -> str:
|
|
357
|
+
"""
|
|
358
|
+
Create JSONL.GZ evidence file with CloudWatch Logs configuration data.
|
|
359
|
+
|
|
360
|
+
:param Dict compliance_results: Compliance assessment results
|
|
361
|
+
:return: Path to created evidence file
|
|
362
|
+
:rtype: str
|
|
363
|
+
"""
|
|
364
|
+
evidence_file = self._get_evidence_file_path()
|
|
365
|
+
|
|
366
|
+
try:
|
|
367
|
+
with gzip.open(evidence_file, "wt", encoding="utf-8") as f:
|
|
368
|
+
self._write_metadata(f)
|
|
369
|
+
self._write_compliance_summary(f, compliance_results)
|
|
370
|
+
self._write_log_group_configurations(f)
|
|
371
|
+
|
|
372
|
+
logger.info(f"Created evidence file: {evidence_file}")
|
|
373
|
+
return evidence_file
|
|
374
|
+
|
|
375
|
+
except Exception as e:
|
|
376
|
+
logger.error(f"Failed to create evidence file: {e}", exc_info=True)
|
|
377
|
+
raise
|
|
378
|
+
|
|
379
|
+
def _get_evidence_file_path(self) -> str:
|
|
380
|
+
"""Generate evidence file path with timestamp."""
|
|
381
|
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
|
382
|
+
return os.path.join(tempfile.gettempdir(), f"cloudwatch_evidence_{self.region}_{timestamp}.jsonl.gz")
|
|
383
|
+
|
|
384
|
+
def _write_metadata(self, file_handle) -> None:
|
|
385
|
+
"""Write metadata record to evidence file."""
|
|
386
|
+
metadata = {
|
|
387
|
+
"type": "metadata",
|
|
388
|
+
"timestamp": datetime.now().isoformat(),
|
|
389
|
+
"region": self.region,
|
|
390
|
+
"account_id": self.account_id,
|
|
391
|
+
"log_group_count": len(self.cloudwatch_item.log_groups),
|
|
392
|
+
"compliance_framework": "NIST800-53R5",
|
|
393
|
+
}
|
|
394
|
+
file_handle.write(json.dumps(metadata) + "\n")
|
|
395
|
+
|
|
396
|
+
def _write_compliance_summary(self, file_handle, compliance_results: Dict[str, Any]) -> None:
|
|
397
|
+
"""Write compliance summary to evidence file."""
|
|
398
|
+
summary = {"type": "compliance_summary", "results": compliance_results["overall"]}
|
|
399
|
+
file_handle.write(json.dumps(summary) + "\n")
|
|
400
|
+
|
|
401
|
+
def _write_log_group_configurations(self, file_handle) -> None:
|
|
402
|
+
"""Write log group configuration records to evidence file."""
|
|
403
|
+
for log_group in self.cloudwatch_item.log_groups:
|
|
404
|
+
log_group_record = self._build_log_group_record(log_group)
|
|
405
|
+
file_handle.write(json.dumps(log_group_record, default=str) + "\n")
|
|
406
|
+
|
|
407
|
+
def _build_log_group_record(self, log_group: Dict[str, Any]) -> Dict[str, Any]:
|
|
408
|
+
"""Build log group configuration record for evidence file."""
|
|
409
|
+
log_group_name = log_group.get("logGroupName", "")
|
|
410
|
+
metrics = self.cloudwatch_item.log_group_metrics.get(log_group_name, {})
|
|
411
|
+
|
|
412
|
+
return {
|
|
413
|
+
"type": "log_group_configuration",
|
|
414
|
+
"log_group_name": log_group_name,
|
|
415
|
+
"log_group_arn": log_group.get("arn"),
|
|
416
|
+
"creation_time": log_group.get("creationTime"),
|
|
417
|
+
"retention_days": log_group.get("retentionInDays"),
|
|
418
|
+
"stored_bytes": log_group.get("storedBytes", 0),
|
|
419
|
+
"kms_key_id": log_group.get("kmsKeyId"),
|
|
420
|
+
"metric_filter_count": metrics.get("MetricFilterCount", 0),
|
|
421
|
+
"subscription_filter_count": metrics.get("SubscriptionFilterCount", 0),
|
|
422
|
+
"metric_filters": log_group.get("MetricFilters", []),
|
|
423
|
+
"subscription_filters": log_group.get("SubscriptionFilters", []),
|
|
424
|
+
"tags": log_group.get("Tags", {}),
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
def _create_ssp_attachment_with_evidence(self, evidence_file_path: str) -> None:
|
|
428
|
+
"""
|
|
429
|
+
Create SSP attachment with CloudWatch evidence.
|
|
430
|
+
|
|
431
|
+
:param str evidence_file_path: Path to evidence file
|
|
432
|
+
"""
|
|
433
|
+
try:
|
|
434
|
+
date_str = datetime.now().strftime("%Y%m%d")
|
|
435
|
+
file_name_pattern = f"cloudwatch_evidence_{self.region}_{date_str}"
|
|
436
|
+
|
|
437
|
+
# Check if evidence for today already exists using base class method
|
|
438
|
+
if self.check_for_existing_evidence(file_name_pattern):
|
|
439
|
+
logger.info(
|
|
440
|
+
f"Evidence file for CloudWatch Logs in region {self.region} already exists for today. "
|
|
441
|
+
"Skipping upload to avoid duplicates."
|
|
442
|
+
)
|
|
443
|
+
return
|
|
444
|
+
|
|
445
|
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
|
446
|
+
file_name = f"cloudwatch_evidence_{self.region}_{timestamp}.jsonl.gz"
|
|
447
|
+
|
|
448
|
+
# Read the compressed file
|
|
449
|
+
with open(evidence_file_path, "rb") as f:
|
|
450
|
+
file_data = f.read()
|
|
451
|
+
|
|
452
|
+
# Upload file to RegScale
|
|
453
|
+
success = File.upload_file_to_regscale(
|
|
454
|
+
file_name=file_name,
|
|
455
|
+
parent_id=self.plan_id,
|
|
456
|
+
parent_module="securityplans",
|
|
457
|
+
api=self.api,
|
|
458
|
+
file_data=file_data,
|
|
459
|
+
tags="aws,cloudwatch,logs,monitoring,compliance,automated",
|
|
460
|
+
)
|
|
461
|
+
|
|
462
|
+
if success:
|
|
463
|
+
logger.info(f"Successfully uploaded CloudWatch Logs evidence file: {file_name}")
|
|
464
|
+
# Link to controls if specified
|
|
465
|
+
if self.evidence_control_ids:
|
|
466
|
+
# Note: SSP attachments don't have IDs returned by upload_file_to_regscale
|
|
467
|
+
# This would need to be implemented if attachment-to-control linking is required
|
|
468
|
+
pass
|
|
469
|
+
else:
|
|
470
|
+
logger.error("Failed to upload CloudWatch Logs evidence file")
|
|
471
|
+
|
|
472
|
+
except Exception as e:
|
|
473
|
+
logger.error(f"Failed to create SSP attachment: {e}", exc_info=True)
|
|
474
|
+
|
|
475
|
+
def _link_evidence_to_controls(self, evidence_id: int, is_attachment: bool = False) -> None:
|
|
476
|
+
"""
|
|
477
|
+
Link evidence to specified control IDs.
|
|
478
|
+
|
|
479
|
+
:param int evidence_id: Evidence or attachment ID
|
|
480
|
+
:param bool is_attachment: True if linking attachment, False for evidence record
|
|
481
|
+
"""
|
|
482
|
+
try:
|
|
483
|
+
for control_id in self.evidence_control_ids:
|
|
484
|
+
if is_attachment:
|
|
485
|
+
self.api.link_ssp_attachment_to_control(self.plan_id, evidence_id, control_id)
|
|
486
|
+
else:
|
|
487
|
+
self.api.link_evidence_to_control(evidence_id, control_id)
|
|
488
|
+
logger.info(f"Linked evidence {evidence_id} to control {control_id}")
|
|
489
|
+
except Exception as e:
|
|
490
|
+
logger.error(f"Failed to link evidence to controls: {e}", exc_info=True)
|