cartography 0.106.0rc1__py3-none-any.whl → 0.107.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 cartography might be problematic. Click here for more details.
- cartography/_version.py +2 -2
- cartography/cli.py +131 -2
- cartography/client/core/tx.py +62 -0
- cartography/config.py +42 -0
- cartography/driftdetect/cli.py +3 -2
- cartography/graph/cleanupbuilder.py +47 -0
- cartography/graph/job.py +42 -0
- cartography/graph/querybuilder.py +136 -2
- cartography/graph/statement.py +1 -1
- cartography/intel/airbyte/__init__.py +105 -0
- cartography/intel/airbyte/connections.py +120 -0
- cartography/intel/airbyte/destinations.py +81 -0
- cartography/intel/airbyte/organizations.py +59 -0
- cartography/intel/airbyte/sources.py +78 -0
- cartography/intel/airbyte/tags.py +64 -0
- cartography/intel/airbyte/users.py +106 -0
- cartography/intel/airbyte/util.py +122 -0
- cartography/intel/airbyte/workspaces.py +63 -0
- cartography/intel/aws/__init__.py +1 -0
- cartography/intel/aws/cloudtrail_management_events.py +364 -0
- cartography/intel/aws/cloudwatch.py +77 -0
- cartography/intel/aws/codebuild.py +132 -0
- cartography/intel/aws/ec2/subnets.py +1 -1
- cartography/intel/aws/ecs.py +17 -0
- cartography/intel/aws/efs.py +80 -0
- cartography/intel/aws/inspector.py +80 -61
- cartography/intel/aws/resources.py +4 -0
- cartography/intel/aws/sns.py +62 -2
- cartography/intel/entra/users.py +84 -42
- cartography/intel/scaleway/__init__.py +127 -0
- cartography/intel/scaleway/iam/__init__.py +0 -0
- cartography/intel/scaleway/iam/apikeys.py +71 -0
- cartography/intel/scaleway/iam/applications.py +71 -0
- cartography/intel/scaleway/iam/groups.py +71 -0
- cartography/intel/scaleway/iam/users.py +71 -0
- cartography/intel/scaleway/instances/__init__.py +0 -0
- cartography/intel/scaleway/instances/flexibleips.py +86 -0
- cartography/intel/scaleway/instances/instances.py +92 -0
- cartography/intel/scaleway/projects.py +79 -0
- cartography/intel/scaleway/storage/__init__.py +0 -0
- cartography/intel/scaleway/storage/snapshots.py +86 -0
- cartography/intel/scaleway/storage/volumes.py +84 -0
- cartography/intel/scaleway/utils.py +37 -0
- cartography/intel/sentinelone/__init__.py +69 -0
- cartography/intel/sentinelone/account.py +140 -0
- cartography/intel/sentinelone/agent.py +139 -0
- cartography/intel/sentinelone/api.py +113 -0
- cartography/intel/sentinelone/application.py +248 -0
- cartography/intel/sentinelone/utils.py +28 -0
- cartography/models/airbyte/__init__.py +0 -0
- cartography/models/airbyte/connection.py +138 -0
- cartography/models/airbyte/destination.py +75 -0
- cartography/models/airbyte/organization.py +19 -0
- cartography/models/airbyte/source.py +75 -0
- cartography/models/airbyte/stream.py +74 -0
- cartography/models/airbyte/tag.py +69 -0
- cartography/models/airbyte/user.py +111 -0
- cartography/models/airbyte/workspace.py +46 -0
- cartography/models/aws/cloudtrail/management_events.py +64 -0
- cartography/models/aws/cloudwatch/log_metric_filter.py +79 -0
- cartography/models/aws/codebuild/__init__.py +0 -0
- cartography/models/aws/codebuild/project.py +49 -0
- cartography/models/aws/ec2/networkinterfaces.py +2 -0
- cartography/models/aws/ec2/subnet_instance.py +2 -0
- cartography/models/aws/ec2/subnet_networkinterface.py +2 -0
- cartography/models/aws/ecs/containers.py +19 -0
- cartography/models/aws/ecs/task_definitions.py +38 -0
- cartography/models/aws/ecs/tasks.py +24 -1
- cartography/models/aws/efs/access_point.py +77 -0
- cartography/models/aws/inspector/findings.py +37 -0
- cartography/models/aws/inspector/packages.py +1 -31
- cartography/models/aws/sns/topic_subscription.py +74 -0
- cartography/models/core/common.py +1 -0
- cartography/models/core/relationships.py +44 -0
- cartography/models/entra/user.py +17 -51
- cartography/models/scaleway/__init__.py +0 -0
- cartography/models/scaleway/iam/__init__.py +0 -0
- cartography/models/scaleway/iam/apikey.py +96 -0
- cartography/models/scaleway/iam/application.py +52 -0
- cartography/models/scaleway/iam/group.py +95 -0
- cartography/models/scaleway/iam/user.py +60 -0
- cartography/models/scaleway/instance/__init__.py +0 -0
- cartography/models/scaleway/instance/flexibleip.py +52 -0
- cartography/models/scaleway/instance/instance.py +118 -0
- cartography/models/scaleway/organization.py +19 -0
- cartography/models/scaleway/project.py +48 -0
- cartography/models/scaleway/storage/__init__.py +0 -0
- cartography/models/scaleway/storage/snapshot.py +78 -0
- cartography/models/scaleway/storage/volume.py +51 -0
- cartography/models/sentinelone/__init__.py +1 -0
- cartography/models/sentinelone/account.py +40 -0
- cartography/models/sentinelone/agent.py +50 -0
- cartography/models/sentinelone/application.py +44 -0
- cartography/models/sentinelone/application_version.py +96 -0
- cartography/sync.py +11 -4
- {cartography-0.106.0rc1.dist-info → cartography-0.107.0.dist-info}/METADATA +20 -16
- {cartography-0.106.0rc1.dist-info → cartography-0.107.0.dist-info}/RECORD +101 -36
- {cartography-0.106.0rc1.dist-info → cartography-0.107.0.dist-info}/WHEEL +0 -0
- {cartography-0.106.0rc1.dist-info → cartography-0.107.0.dist-info}/entry_points.txt +0 -0
- {cartography-0.106.0rc1.dist-info → cartography-0.107.0.dist-info}/licenses/LICENSE +0 -0
- {cartography-0.106.0rc1.dist-info → cartography-0.107.0.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import time
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
import requests
|
|
6
|
+
|
|
7
|
+
logger = logging.getLogger(__name__)
|
|
8
|
+
# Connect and read timeouts of 60 seconds each; see https://requests.readthedocs.io/en/master/user/advanced/#timeouts
|
|
9
|
+
_TIMEOUT = (60, 60)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class AirbyteClient:
|
|
13
|
+
"""A client for interacting with the Airbyte API.
|
|
14
|
+
This client handles authentication and provides methods to make GET requests to the Airbyte API.
|
|
15
|
+
It automatically handles pagination for GET requests that return multiple pages of data.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
def __init__(self, base_url: str, client_id: str, client_secret: str) -> None:
|
|
19
|
+
self._client_id = client_id
|
|
20
|
+
self._client_secret = client_secret
|
|
21
|
+
self.base_url = base_url
|
|
22
|
+
self._access_token_expiry: int | None = None
|
|
23
|
+
self._session = requests.Session()
|
|
24
|
+
|
|
25
|
+
def get(self, uri: str, params: dict | None = None, offset: int = 0) -> list[dict]:
|
|
26
|
+
"""Make a GET request to the Airbyte API.
|
|
27
|
+
This method handles authentication and pagination.
|
|
28
|
+
Args:
|
|
29
|
+
uri (str): The URI to make the GET request to.
|
|
30
|
+
params (dict | None): Optional parameters to include in the request.
|
|
31
|
+
offset (int): The offset for pagination, defaults to 0.
|
|
32
|
+
Returns:
|
|
33
|
+
list[dict]: A list of dictionaries containing the data from the response.
|
|
34
|
+
"""
|
|
35
|
+
self.authenticate()
|
|
36
|
+
if params is None:
|
|
37
|
+
params_with_pagination = {}
|
|
38
|
+
else:
|
|
39
|
+
params_with_pagination = params.copy()
|
|
40
|
+
params_with_pagination["offset"] = offset
|
|
41
|
+
response = self._session.get(
|
|
42
|
+
f"{self.base_url}{uri}", params=params_with_pagination, timeout=_TIMEOUT
|
|
43
|
+
)
|
|
44
|
+
response.raise_for_status()
|
|
45
|
+
data = response.json().get("data")
|
|
46
|
+
if response.json().get("next", "") != "":
|
|
47
|
+
data.extend(
|
|
48
|
+
self.get(
|
|
49
|
+
uri,
|
|
50
|
+
params=params,
|
|
51
|
+
offset=offset + len(data),
|
|
52
|
+
)
|
|
53
|
+
)
|
|
54
|
+
return data
|
|
55
|
+
|
|
56
|
+
def authenticate(self) -> None:
|
|
57
|
+
"""Authenticate with the Airbyte API using client credentials.
|
|
58
|
+
This method checks if the access token is still valid and renews it if necessary.
|
|
59
|
+
If the access token is expired or not set, it will make a request to obtain a new access token.
|
|
60
|
+
"""
|
|
61
|
+
if self._access_token_expiry and self._access_token_expiry >= time.time():
|
|
62
|
+
return
|
|
63
|
+
self._session.headers.pop("Authorization", None)
|
|
64
|
+
payload = {
|
|
65
|
+
"grant-type": "client_credentials",
|
|
66
|
+
"client_id": self._client_id,
|
|
67
|
+
"client_secret": self._client_secret,
|
|
68
|
+
}
|
|
69
|
+
response = self._session.post(
|
|
70
|
+
f"{self.base_url}/applications/token", json=payload, timeout=_TIMEOUT
|
|
71
|
+
)
|
|
72
|
+
response.raise_for_status()
|
|
73
|
+
data = response.json()
|
|
74
|
+
self._session.headers["Authorization"] = (
|
|
75
|
+
f"Bearer {data.get('access_token', '')}"
|
|
76
|
+
)
|
|
77
|
+
token_expiry = data.get("expires_in", 0)
|
|
78
|
+
self._access_token_expiry = time.time() + token_expiry
|
|
79
|
+
logger.debug("Access token renewed, expires in %s seconds.", token_expiry)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def normalize_airbyte_config(config: dict[str, Any]) -> dict[str, Any]:
|
|
83
|
+
"""Normalize the Airbyte configuration dictionary.
|
|
84
|
+
This function takes a configuration dictionary and normalizes it by mapping keys to a standard set of keys.
|
|
85
|
+
This is useful for ensuring consistency across different configurations, and will allow to connect to existing nodes.
|
|
86
|
+
Args:
|
|
87
|
+
config (dict[str, Any]): The configuration dictionary to normalize.
|
|
88
|
+
Returns:
|
|
89
|
+
dict[str, Any]: A normalized configuration dictionary with standardized keys.
|
|
90
|
+
"""
|
|
91
|
+
normalized_config = {}
|
|
92
|
+
for key in config:
|
|
93
|
+
if key in ("host", "port", "name", "region", "endpoint", "account", ""):
|
|
94
|
+
normalized_config[key] = config[key]
|
|
95
|
+
elif key in ("aws_region_name", "region_name", "s3_bucket_region"):
|
|
96
|
+
normalized_config["region"] = config[key]
|
|
97
|
+
elif key in ("queue_url", "url", "s3_endpoint"):
|
|
98
|
+
normalized_config["endpoint"] = config[key]
|
|
99
|
+
elif key in ("azure_blob_storage_account_name", "storage_account_name"):
|
|
100
|
+
normalized_config["account"] = config[key]
|
|
101
|
+
elif key in (
|
|
102
|
+
"azure_blob_storage_container_name",
|
|
103
|
+
"bucket",
|
|
104
|
+
"database",
|
|
105
|
+
"s3_bucket_name",
|
|
106
|
+
):
|
|
107
|
+
normalized_config["name"] = config[key]
|
|
108
|
+
return normalized_config
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def list_to_string(lst: list[str]) -> str | None:
|
|
112
|
+
"""Convert a list of strings to a comma-separated string."""
|
|
113
|
+
if len(lst) == 0:
|
|
114
|
+
return None
|
|
115
|
+
# Sublist
|
|
116
|
+
formated_list: list[str] = []
|
|
117
|
+
for item in lst:
|
|
118
|
+
if isinstance(item, list):
|
|
119
|
+
formated_list.append("|".join(item))
|
|
120
|
+
else:
|
|
121
|
+
formated_list.append(str(item))
|
|
122
|
+
return ",".join(formated_list)
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from typing import Any
|
|
3
|
+
from typing import Dict
|
|
4
|
+
from typing import List
|
|
5
|
+
|
|
6
|
+
import neo4j
|
|
7
|
+
|
|
8
|
+
from cartography.client.core.tx import load
|
|
9
|
+
from cartography.graph.job import GraphJob
|
|
10
|
+
from cartography.intel.airbyte.util import AirbyteClient
|
|
11
|
+
from cartography.models.airbyte.workspace import AirbyteWorkspaceSchema
|
|
12
|
+
from cartography.util import timeit
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger(__name__)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@timeit
|
|
18
|
+
def sync(
|
|
19
|
+
neo4j_session: neo4j.Session,
|
|
20
|
+
api_session: AirbyteClient,
|
|
21
|
+
org_id: str,
|
|
22
|
+
common_job_parameters: Dict[str, Any],
|
|
23
|
+
) -> List[Dict[str, Any]]:
|
|
24
|
+
workspaces = get(api_session, org_id)
|
|
25
|
+
load_workspaces(
|
|
26
|
+
neo4j_session, workspaces, org_id, common_job_parameters["UPDATE_TAG"]
|
|
27
|
+
)
|
|
28
|
+
cleanup(neo4j_session, common_job_parameters)
|
|
29
|
+
return workspaces
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@timeit
|
|
33
|
+
def get(
|
|
34
|
+
api_session: AirbyteClient,
|
|
35
|
+
org_id: str,
|
|
36
|
+
) -> List[Dict[str, Any]]:
|
|
37
|
+
return api_session.get("/workspaces", params={"organizationId": org_id})
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@timeit
|
|
41
|
+
def load_workspaces(
|
|
42
|
+
neo4j_session: neo4j.Session,
|
|
43
|
+
data: List[Dict[str, Any]],
|
|
44
|
+
org_id: str,
|
|
45
|
+
update_tag: int,
|
|
46
|
+
) -> None:
|
|
47
|
+
logger.info("Loading %d Airbyte Workspaces into Neo4j.", len(data))
|
|
48
|
+
load(
|
|
49
|
+
neo4j_session,
|
|
50
|
+
AirbyteWorkspaceSchema(),
|
|
51
|
+
data,
|
|
52
|
+
lastupdated=update_tag,
|
|
53
|
+
ORG_ID=org_id,
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@timeit
|
|
58
|
+
def cleanup(
|
|
59
|
+
neo4j_session: neo4j.Session, common_job_parameters: Dict[str, Any]
|
|
60
|
+
) -> None:
|
|
61
|
+
GraphJob.from_node_schema(AirbyteWorkspaceSchema(), common_job_parameters).run(
|
|
62
|
+
neo4j_session
|
|
63
|
+
)
|
|
@@ -310,6 +310,7 @@ def start_aws_ingestion(neo4j_session: neo4j.Session, config: Config) -> None:
|
|
|
310
310
|
common_job_parameters = {
|
|
311
311
|
"UPDATE_TAG": config.update_tag,
|
|
312
312
|
"permission_relationships_file": config.permission_relationships_file,
|
|
313
|
+
"aws_cloudtrail_management_events_lookback_hours": config.aws_cloudtrail_management_events_lookback_hours,
|
|
313
314
|
}
|
|
314
315
|
try:
|
|
315
316
|
boto3_session = boto3.Session()
|
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import logging
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
from datetime import timedelta
|
|
5
|
+
from typing import Any
|
|
6
|
+
from typing import Dict
|
|
7
|
+
from typing import List
|
|
8
|
+
|
|
9
|
+
import boto3
|
|
10
|
+
import neo4j
|
|
11
|
+
|
|
12
|
+
from cartography.client.core.tx import load_matchlinks
|
|
13
|
+
from cartography.graph.job import GraphJob
|
|
14
|
+
from cartography.intel.aws.ec2.util import get_botocore_config
|
|
15
|
+
from cartography.models.aws.cloudtrail.management_events import AssumedRoleMatchLink
|
|
16
|
+
from cartography.util import aws_handle_regions
|
|
17
|
+
from cartography.util import timeit
|
|
18
|
+
|
|
19
|
+
logger = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@timeit
|
|
23
|
+
@aws_handle_regions
|
|
24
|
+
def get_assume_role_events(
|
|
25
|
+
boto3_session: boto3.Session, region: str, lookback_hours: int
|
|
26
|
+
) -> List[Dict[str, Any]]:
|
|
27
|
+
"""
|
|
28
|
+
Fetch CloudTrail AssumeRole events from the specified time period.
|
|
29
|
+
|
|
30
|
+
Focuses specifically on standard AssumeRole events, excluding SAML and WebIdentity variants.
|
|
31
|
+
|
|
32
|
+
:type boto3_session: boto3.Session
|
|
33
|
+
:param boto3_session: The boto3 session to use for API calls
|
|
34
|
+
:type region: str
|
|
35
|
+
:param region: The AWS region to fetch events from
|
|
36
|
+
:type lookback_hours: int
|
|
37
|
+
:param lookback_hours: Number of hours back to retrieve events from
|
|
38
|
+
:rtype: List[Dict[str, Any]]
|
|
39
|
+
:return: List of CloudTrail AssumeRole events
|
|
40
|
+
"""
|
|
41
|
+
client = boto3_session.client(
|
|
42
|
+
"cloudtrail", region_name=region, config=get_botocore_config()
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
# Calculate time range
|
|
46
|
+
end_time = datetime.utcnow()
|
|
47
|
+
start_time = end_time - timedelta(hours=lookback_hours)
|
|
48
|
+
|
|
49
|
+
logger.info(
|
|
50
|
+
f"Fetching CloudTrail AssumeRole events for region '{region}' "
|
|
51
|
+
f"from {start_time} to {end_time} ({lookback_hours} hours)"
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
paginator = client.get_paginator("lookup_events")
|
|
55
|
+
|
|
56
|
+
page_iterator = paginator.paginate(
|
|
57
|
+
LookupAttributes=[
|
|
58
|
+
{"AttributeKey": "EventName", "AttributeValue": "AssumeRole"}
|
|
59
|
+
],
|
|
60
|
+
StartTime=start_time,
|
|
61
|
+
EndTime=end_time,
|
|
62
|
+
PaginationConfig={
|
|
63
|
+
"MaxItems": 10000, # Reasonable limit to prevent excessive API calls
|
|
64
|
+
"PageSize": 50, # CloudTrail API limit per page
|
|
65
|
+
},
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
all_events = []
|
|
69
|
+
for page in page_iterator:
|
|
70
|
+
all_events.extend(page.get("Events", []))
|
|
71
|
+
|
|
72
|
+
logger.info(f"Retrieved {len(all_events)} AssumeRole events from region '{region}'")
|
|
73
|
+
|
|
74
|
+
return all_events
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@timeit
|
|
78
|
+
def transform_assume_role_events_to_role_assumptions(
|
|
79
|
+
events: List[Dict[str, Any]],
|
|
80
|
+
region: str,
|
|
81
|
+
current_aws_account_id: str,
|
|
82
|
+
) -> List[Dict[str, Any]]:
|
|
83
|
+
"""
|
|
84
|
+
Transform raw CloudTrail AssumeRole events into aggregated role assumption relationships.
|
|
85
|
+
|
|
86
|
+
Focuses specifically on standard AssumeRole events, providing optimized processing
|
|
87
|
+
for the most common role assumption scenario.
|
|
88
|
+
|
|
89
|
+
This function performs the complete transformation pipeline:
|
|
90
|
+
1. Extract role assumption events from CloudTrail AssumeRole data
|
|
91
|
+
2. Aggregate events by (source_principal, destination_principal) pairs
|
|
92
|
+
3. Return aggregated relationships ready for loading
|
|
93
|
+
|
|
94
|
+
:type events: List[Dict[str, Any]]
|
|
95
|
+
:param events: List of raw CloudTrail AssumeRole events from lookup_events API
|
|
96
|
+
:type region: str
|
|
97
|
+
:param region: The AWS region where events were retrieved from
|
|
98
|
+
:type current_aws_account_id: str
|
|
99
|
+
:param current_aws_account_id: The AWS account ID being synced
|
|
100
|
+
:rtype: List[Dict[str, Any]]
|
|
101
|
+
:return: List of aggregated role assumption relationships ready for loading
|
|
102
|
+
"""
|
|
103
|
+
aggregated: Dict[tuple, Dict[str, Any]] = {}
|
|
104
|
+
logger.info(
|
|
105
|
+
f"Transforming {len(events)} CloudTrail AssumeRole events to role assumptions for region '{region}'"
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
for event in events:
|
|
109
|
+
|
|
110
|
+
cloudtrail_event = json.loads(event["CloudTrailEvent"])
|
|
111
|
+
|
|
112
|
+
if cloudtrail_event.get("userIdentity", {}).get("arn"):
|
|
113
|
+
source_principal = cloudtrail_event["userIdentity"]["arn"]
|
|
114
|
+
destination_principal = cloudtrail_event["requestParameters"]["roleArn"]
|
|
115
|
+
else:
|
|
116
|
+
logger.debug(
|
|
117
|
+
f"Skipping CloudTrail AssumeRole event due to missing UserIdentity.arn. Event: {event.get('EventId', 'unknown')}"
|
|
118
|
+
)
|
|
119
|
+
continue
|
|
120
|
+
|
|
121
|
+
destination_principal = cloudtrail_event["requestParameters"]["roleArn"]
|
|
122
|
+
|
|
123
|
+
normalized_source_principal = _convert_assumed_role_arn_to_role_arn(
|
|
124
|
+
source_principal
|
|
125
|
+
)
|
|
126
|
+
normalized_destination_principal = _convert_assumed_role_arn_to_role_arn(
|
|
127
|
+
destination_principal
|
|
128
|
+
)
|
|
129
|
+
event_time = event.get("EventTime")
|
|
130
|
+
|
|
131
|
+
key = (normalized_source_principal, normalized_destination_principal)
|
|
132
|
+
|
|
133
|
+
if key in aggregated:
|
|
134
|
+
aggregated[key]["times_used"] += 1
|
|
135
|
+
aggregated[key]["assume_role_count"] += 1 # All events are AssumeRole
|
|
136
|
+
# Handle None values safely for time comparisons
|
|
137
|
+
if event_time:
|
|
138
|
+
existing_first = aggregated[key]["first_seen_in_time_window"]
|
|
139
|
+
existing_last = aggregated[key]["last_used"]
|
|
140
|
+
|
|
141
|
+
if existing_first is None or event_time < existing_first:
|
|
142
|
+
aggregated[key]["first_seen_in_time_window"] = event_time
|
|
143
|
+
if existing_last is None or event_time > existing_last:
|
|
144
|
+
aggregated[key]["last_used"] = event_time
|
|
145
|
+
else:
|
|
146
|
+
aggregated[key] = {
|
|
147
|
+
"source_principal_arn": normalized_source_principal,
|
|
148
|
+
"destination_principal_arn": normalized_destination_principal,
|
|
149
|
+
"times_used": 1,
|
|
150
|
+
"first_seen_in_time_window": event_time,
|
|
151
|
+
"last_used": event_time,
|
|
152
|
+
"event_types": ["AssumeRole"],
|
|
153
|
+
"assume_role_count": 1,
|
|
154
|
+
"saml_count": 0,
|
|
155
|
+
"web_identity_count": 0,
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
return list(aggregated.values())
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
@timeit
|
|
162
|
+
def load_role_assumptions(
|
|
163
|
+
neo4j_session: neo4j.Session,
|
|
164
|
+
aggregated_role_assumptions: List[Dict[str, Any]],
|
|
165
|
+
current_aws_account_id: str,
|
|
166
|
+
aws_update_tag: int,
|
|
167
|
+
) -> None:
|
|
168
|
+
"""
|
|
169
|
+
Load aggregated role assumption relationships into Neo4j using MatchLink pattern.
|
|
170
|
+
|
|
171
|
+
Creates direct ASSUMED_ROLE relationships with aggregated properties:
|
|
172
|
+
(AWSUser|AWSRole|AWSPrincipal)-[:ASSUMED_ROLE {lastused, times_used, first_seen_in_time_window, last_seen}]->(AWSRole)
|
|
173
|
+
|
|
174
|
+
Assumes that both source principals and destination roles already exist in the graph.
|
|
175
|
+
|
|
176
|
+
:type neo4j_session: neo4j.Session
|
|
177
|
+
:param neo4j_session: The Neo4j session to use for database operations
|
|
178
|
+
:type aggregated_role_assumptions: List[Dict[str, Any]]
|
|
179
|
+
:param aggregated_role_assumptions: List of aggregated role assumption relationships from transform function
|
|
180
|
+
:type current_aws_account_id: str
|
|
181
|
+
:param current_aws_account_id: The AWS account ID being synced
|
|
182
|
+
:type aws_update_tag: int
|
|
183
|
+
:param aws_update_tag: Timestamp tag for tracking data freshness
|
|
184
|
+
:rtype: None
|
|
185
|
+
"""
|
|
186
|
+
# Use MatchLink to create relationships between existing nodes
|
|
187
|
+
matchlink_schema = AssumedRoleMatchLink()
|
|
188
|
+
|
|
189
|
+
load_matchlinks(
|
|
190
|
+
neo4j_session,
|
|
191
|
+
matchlink_schema,
|
|
192
|
+
aggregated_role_assumptions,
|
|
193
|
+
lastupdated=aws_update_tag,
|
|
194
|
+
_sub_resource_label="AWSAccount",
|
|
195
|
+
_sub_resource_id=current_aws_account_id,
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
logger.info(
|
|
199
|
+
f"Successfully loaded {len(aggregated_role_assumptions)} role assumption relationships"
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _convert_assumed_role_arn_to_role_arn(assumed_role_arn: str) -> str:
|
|
204
|
+
"""
|
|
205
|
+
Convert an assumed role ARN to the original role ARN.
|
|
206
|
+
|
|
207
|
+
Example:
|
|
208
|
+
Input: "arn:aws:sts::123456789012:assumed-role/MyRole/session-name"
|
|
209
|
+
Output: "arn:aws:iam::123456789012:role/MyRole"
|
|
210
|
+
"""
|
|
211
|
+
|
|
212
|
+
# Split the ARN into parts
|
|
213
|
+
arn_parts = assumed_role_arn.split(":")
|
|
214
|
+
if len(arn_parts) >= 6 and arn_parts[2] == "sts" and "assumed-role" in arn_parts[5]:
|
|
215
|
+
# Extract account ID and role name
|
|
216
|
+
account_id = arn_parts[4]
|
|
217
|
+
resource_part = arn_parts[5] # "assumed-role/MyRole/session-name"
|
|
218
|
+
role_name = resource_part.split("/")[1] # Extract "MyRole"
|
|
219
|
+
|
|
220
|
+
# Construct the IAM role ARN
|
|
221
|
+
return f"arn:aws:iam::{account_id}:role/{role_name}"
|
|
222
|
+
|
|
223
|
+
# Return original ARN if conversion fails
|
|
224
|
+
return assumed_role_arn
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
@timeit
|
|
228
|
+
def cleanup(
|
|
229
|
+
neo4j_session: neo4j.Session, current_aws_account_id: str, update_tag: int
|
|
230
|
+
) -> None:
|
|
231
|
+
"""
|
|
232
|
+
Run CloudTrail management events cleanup job to remove stale ASSUMED_ROLE relationships.
|
|
233
|
+
|
|
234
|
+
:type neo4j_session: neo4j.Session
|
|
235
|
+
:param neo4j_session: The Neo4j session to use for database operations
|
|
236
|
+
:type current_aws_account_id: str
|
|
237
|
+
:param current_aws_account_id: The AWS account ID being synced
|
|
238
|
+
:type update_tag: int
|
|
239
|
+
:param update_tag: Timestamp tag for tracking data freshness
|
|
240
|
+
:rtype: None
|
|
241
|
+
"""
|
|
242
|
+
logger.info("Running CloudTrail management events cleanup job.")
|
|
243
|
+
|
|
244
|
+
matchlink_schema = AssumedRoleMatchLink()
|
|
245
|
+
cleanup_job = GraphJob.from_matchlink(
|
|
246
|
+
matchlink_schema,
|
|
247
|
+
"AWSAccount",
|
|
248
|
+
current_aws_account_id,
|
|
249
|
+
update_tag,
|
|
250
|
+
)
|
|
251
|
+
cleanup_job.run(neo4j_session)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
@timeit
|
|
255
|
+
def sync_assume_role_events(
|
|
256
|
+
neo4j_session: neo4j.Session,
|
|
257
|
+
boto3_session: boto3.Session,
|
|
258
|
+
regions: List[str],
|
|
259
|
+
current_aws_account_id: str,
|
|
260
|
+
update_tag: int,
|
|
261
|
+
common_job_parameters: Dict[str, Any],
|
|
262
|
+
) -> None:
|
|
263
|
+
"""
|
|
264
|
+
Sync CloudTrail management events to create ASSUMED_ROLE relationships.
|
|
265
|
+
|
|
266
|
+
This function orchestrates the complete process:
|
|
267
|
+
1. Fetch CloudTrail management events region by region
|
|
268
|
+
2. Transform events into role assumption records per region
|
|
269
|
+
3. Load role assumption relationships into Neo4j for each region
|
|
270
|
+
4. Run cleanup after processing all regions
|
|
271
|
+
|
|
272
|
+
The resulting graph contains direct relationships like:
|
|
273
|
+
(AWSUser|AWSRole|AWSPrincipal)-[:ASSUMED_ROLE {times_used, first_seen_in_time_window, last_used, lastused}]->(AWSRole)
|
|
274
|
+
|
|
275
|
+
:type neo4j_session: neo4j.Session
|
|
276
|
+
:param neo4j_session: The Neo4j session
|
|
277
|
+
:type boto3_session: boto3.Session
|
|
278
|
+
:param boto3_session: The boto3 session to use for API calls
|
|
279
|
+
:type regions: List[str]
|
|
280
|
+
:param regions: List of AWS regions to sync
|
|
281
|
+
:type current_aws_account_id: str
|
|
282
|
+
:param current_aws_account_id: The AWS account ID being synced
|
|
283
|
+
:type aws_update_tag: int
|
|
284
|
+
:param aws_update_tag: Timestamp tag for tracking data freshness
|
|
285
|
+
:rtype: None
|
|
286
|
+
"""
|
|
287
|
+
# Extract lookback hours from common_job_parameters (set by CLI parameter)
|
|
288
|
+
lookback_hours = common_job_parameters.get(
|
|
289
|
+
"aws_cloudtrail_management_events_lookback_hours"
|
|
290
|
+
)
|
|
291
|
+
|
|
292
|
+
if not lookback_hours:
|
|
293
|
+
logger.info(
|
|
294
|
+
"CloudTrail management events sync skipped - no lookback period specified"
|
|
295
|
+
)
|
|
296
|
+
return
|
|
297
|
+
|
|
298
|
+
logger.info(
|
|
299
|
+
f"Syncing {len(regions)} regions with {lookback_hours} hour lookback period"
|
|
300
|
+
)
|
|
301
|
+
|
|
302
|
+
total_role_assumptions = 0
|
|
303
|
+
|
|
304
|
+
# Process events region by region
|
|
305
|
+
for region in regions:
|
|
306
|
+
logger.info(f"Processing CloudTrail events for region {region}")
|
|
307
|
+
|
|
308
|
+
# Process AssumeRole events specifically
|
|
309
|
+
logger.info(f"Fetching AssumeRole events specifically for region {region}")
|
|
310
|
+
assume_role_events = get_assume_role_events(
|
|
311
|
+
boto3_session=boto3_session,
|
|
312
|
+
region=region,
|
|
313
|
+
lookback_hours=lookback_hours,
|
|
314
|
+
)
|
|
315
|
+
|
|
316
|
+
# Transform AssumeRole events to role assumptions
|
|
317
|
+
assume_role_assumptions = transform_assume_role_events_to_role_assumptions(
|
|
318
|
+
events=assume_role_events,
|
|
319
|
+
region=region,
|
|
320
|
+
current_aws_account_id=current_aws_account_id,
|
|
321
|
+
)
|
|
322
|
+
|
|
323
|
+
# Load AssumeRole assumptions for this region
|
|
324
|
+
load_role_assumptions(
|
|
325
|
+
neo4j_session=neo4j_session,
|
|
326
|
+
aggregated_role_assumptions=assume_role_assumptions,
|
|
327
|
+
current_aws_account_id=current_aws_account_id,
|
|
328
|
+
aws_update_tag=update_tag,
|
|
329
|
+
)
|
|
330
|
+
total_role_assumptions += len(assume_role_assumptions)
|
|
331
|
+
logger.info(
|
|
332
|
+
f"Loaded {len(assume_role_assumptions)} AssumeRole assumptions for region {region}"
|
|
333
|
+
)
|
|
334
|
+
|
|
335
|
+
# Run cleanup for stale relationships after processing all regions
|
|
336
|
+
cleanup(neo4j_session, current_aws_account_id, update_tag)
|
|
337
|
+
|
|
338
|
+
logger.info(
|
|
339
|
+
f"CloudTrail management events sync completed successfully. "
|
|
340
|
+
f"Processed {total_role_assumptions} total role assumption events across {len(regions)} regions."
|
|
341
|
+
)
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
# Main sync function for when we decide to add more event types
|
|
345
|
+
@timeit
|
|
346
|
+
def sync(
|
|
347
|
+
neo4j_session: neo4j.Session,
|
|
348
|
+
boto3_session: boto3.Session,
|
|
349
|
+
regions: List[str],
|
|
350
|
+
current_aws_account_id: str,
|
|
351
|
+
update_tag: int,
|
|
352
|
+
common_job_parameters: Dict[str, Any],
|
|
353
|
+
) -> None:
|
|
354
|
+
"""
|
|
355
|
+
Main sync function for CloudTrail management events.
|
|
356
|
+
"""
|
|
357
|
+
sync_assume_role_events(
|
|
358
|
+
neo4j_session=neo4j_session,
|
|
359
|
+
boto3_session=boto3_session,
|
|
360
|
+
regions=regions,
|
|
361
|
+
current_aws_account_id=current_aws_account_id,
|
|
362
|
+
update_tag=update_tag,
|
|
363
|
+
common_job_parameters=common_job_parameters,
|
|
364
|
+
)
|
|
@@ -9,6 +9,9 @@ import neo4j
|
|
|
9
9
|
from cartography.client.core.tx import load
|
|
10
10
|
from cartography.graph.job import GraphJob
|
|
11
11
|
from cartography.intel.aws.ec2.util import get_botocore_config
|
|
12
|
+
from cartography.models.aws.cloudwatch.log_metric_filter import (
|
|
13
|
+
CloudWatchLogMetricFilterSchema,
|
|
14
|
+
)
|
|
12
15
|
from cartography.models.aws.cloudwatch.loggroup import CloudWatchLogGroupSchema
|
|
13
16
|
from cartography.util import aws_handle_regions
|
|
14
17
|
from cartography.util import timeit
|
|
@@ -31,6 +34,47 @@ def get_cloudwatch_log_groups(
|
|
|
31
34
|
return logGroups
|
|
32
35
|
|
|
33
36
|
|
|
37
|
+
@timeit
|
|
38
|
+
@aws_handle_regions
|
|
39
|
+
def get_cloudwatch_log_metric_filters(
|
|
40
|
+
boto3_session: boto3.Session, region: str
|
|
41
|
+
) -> List[Dict[str, Any]]:
|
|
42
|
+
logs_client = boto3_session.client(
|
|
43
|
+
"logs", region_name=region, config=get_botocore_config()
|
|
44
|
+
)
|
|
45
|
+
paginator = logs_client.get_paginator("describe_metric_filters")
|
|
46
|
+
metric_filters = []
|
|
47
|
+
|
|
48
|
+
for page in paginator.paginate():
|
|
49
|
+
metric_filters.extend(page.get("metricFilters", []))
|
|
50
|
+
|
|
51
|
+
return metric_filters
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def transform_metric_filters(
|
|
55
|
+
metric_filters: List[Dict[str, Any]], region: str
|
|
56
|
+
) -> List[Dict[str, Any]]:
|
|
57
|
+
"""
|
|
58
|
+
Transform CloudWatch log metric filter data for ingestion into Neo4j.
|
|
59
|
+
Ensures that the 'id' field is a unique combination of logGroupName and filterName.
|
|
60
|
+
"""
|
|
61
|
+
transformed_filters = []
|
|
62
|
+
for filter in metric_filters:
|
|
63
|
+
transformed_filter = {
|
|
64
|
+
"id": f"{filter['logGroupName']}:{filter['filterName']}",
|
|
65
|
+
"arn": f"{filter['logGroupName']}:{filter['filterName']}",
|
|
66
|
+
"filterName": filter["filterName"],
|
|
67
|
+
"filterPattern": filter.get("filterPattern"),
|
|
68
|
+
"logGroupName": filter["logGroupName"],
|
|
69
|
+
"metricName": filter["metricTransformations"][0]["metricName"],
|
|
70
|
+
"metricNamespace": filter["metricTransformations"][0]["metricNamespace"],
|
|
71
|
+
"metricValue": filter["metricTransformations"][0]["metricValue"],
|
|
72
|
+
"Region": region,
|
|
73
|
+
}
|
|
74
|
+
transformed_filters.append(transformed_filter)
|
|
75
|
+
return transformed_filters
|
|
76
|
+
|
|
77
|
+
|
|
34
78
|
@timeit
|
|
35
79
|
def load_cloudwatch_log_groups(
|
|
36
80
|
neo4j_session: neo4j.Session,
|
|
@@ -52,6 +96,27 @@ def load_cloudwatch_log_groups(
|
|
|
52
96
|
)
|
|
53
97
|
|
|
54
98
|
|
|
99
|
+
@timeit
|
|
100
|
+
def load_cloudwatch_log_metric_filters(
|
|
101
|
+
neo4j_session: neo4j.Session,
|
|
102
|
+
data: List[Dict[str, Any]],
|
|
103
|
+
region: str,
|
|
104
|
+
current_aws_account_id: str,
|
|
105
|
+
aws_update_tag: int,
|
|
106
|
+
) -> None:
|
|
107
|
+
logger.info(
|
|
108
|
+
f"Loading CloudWatch {len(data)} log metric filters for region '{region}' into graph.",
|
|
109
|
+
)
|
|
110
|
+
load(
|
|
111
|
+
neo4j_session,
|
|
112
|
+
CloudWatchLogMetricFilterSchema(),
|
|
113
|
+
data,
|
|
114
|
+
lastupdated=aws_update_tag,
|
|
115
|
+
Region=region,
|
|
116
|
+
AWS_ID=current_aws_account_id,
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
|
|
55
120
|
@timeit
|
|
56
121
|
def cleanup(
|
|
57
122
|
neo4j_session: neo4j.Session,
|
|
@@ -62,6 +127,9 @@ def cleanup(
|
|
|
62
127
|
CloudWatchLogGroupSchema(), common_job_parameters
|
|
63
128
|
)
|
|
64
129
|
cleanup_job.run(neo4j_session)
|
|
130
|
+
GraphJob.from_node_schema(
|
|
131
|
+
CloudWatchLogMetricFilterSchema(), common_job_parameters
|
|
132
|
+
).run(neo4j_session)
|
|
65
133
|
|
|
66
134
|
|
|
67
135
|
@timeit
|
|
@@ -90,4 +158,13 @@ def sync(
|
|
|
90
158
|
update_tag,
|
|
91
159
|
)
|
|
92
160
|
|
|
161
|
+
metric_filters = get_cloudwatch_log_metric_filters(boto3_session, region)
|
|
162
|
+
transformed_filters = transform_metric_filters(metric_filters, region)
|
|
163
|
+
load_cloudwatch_log_metric_filters(
|
|
164
|
+
neo4j_session,
|
|
165
|
+
transformed_filters,
|
|
166
|
+
region,
|
|
167
|
+
current_aws_account_id,
|
|
168
|
+
update_tag,
|
|
169
|
+
)
|
|
93
170
|
cleanup(neo4j_session, common_job_parameters)
|