File size: 9,371 Bytes
955a66f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 | from __future__ import annotations
from typing import Any
from src.domain import ActorKind, ChangeType
from src.redaction import (
alias_account,
alias_actor,
alias_ip,
alias_resource,
compact_json,
looks_sensitive,
normalize_id,
redact_text,
)
from src.ruleset import classify_event, flags_from_request
def _as_dict(value: Any) -> dict[str, Any]:
return value if isinstance(value, dict) else {}
def _identity(row: dict[str, Any]) -> dict[str, Any]:
nested = row.get("userIdentity")
if isinstance(nested, dict):
return nested
return {
"type": row.get("userIdentity.type") or row.get("user_type") or row.get("actor_kind") or "",
"userName": row.get("userIdentity.userName") or row.get("userName") or row.get("user_name") or "",
"arn": row.get("userIdentity.arn") or row.get("arn") or "",
"accountId": row.get("userIdentity.accountId") or row.get("accountId") or row.get("account_id") or "",
"principalId": row.get("userIdentity.principalId") or "",
"invokedBy": row.get("userIdentity.invokedBy") or "",
"sessionContext": row.get("userIdentity.sessionContext") or {},
}
def actor_kind_of(identity: dict[str, Any]) -> str:
raw = normalize_id(identity.get("type")).lower()
if raw == "root":
return ActorKind.ROOT.value
if raw == "awsservice":
return ActorKind.AWS_SERVICE.value
if raw == "assumedrole":
return ActorKind.SERVICE.value
if raw == "iamuser":
return ActorKind.HUMAN.value
hinted = normalize_id(identity.get("actor_kind") or "").lower()
if hinted in {item.value for item in ActorKind}:
return hinted
return ActorKind.UNKNOWN.value
def actor_name_of(identity: dict[str, Any]) -> str:
session = _as_dict(identity.get("sessionContext"))
issuer = _as_dict(session.get("sessionIssuer"))
return (
normalize_id(identity.get("userName"))
or normalize_id(issuer.get("userName"))
or normalize_id(identity.get("invokedBy"))
or normalize_id(str(identity.get("arn") or "").rsplit("/", 1)[-1])
or "unknown"
)
def actor_role_of(kind: str, name: str) -> str:
lowered = name.lower()
if kind == ActorKind.ROOT.value:
return "root"
if "terraform" in lowered:
return "terraform"
if lowered.startswith("ci") or "github" in lowered:
return "ci"
if "rotator" in lowered or "lambda" in lowered:
return "rotator"
if lowered in {"alice", "dave"} or "admin" in lowered or "security" in lowered:
return "cloud-admin" if lowered == "alice" else ("security" if lowered == "dave" else "operator")
if lowered == "bob" or "dev" in lowered:
return "developer"
if lowered == "carol" or "contract" in lowered:
return "contractor"
if kind == ActorKind.SERVICE.value:
return "service"
if kind == ActorKind.HUMAN.value:
return "human"
return "unknown"
def _request(row: dict[str, Any]) -> Any:
if "requestParameters" in row:
return row.get("requestParameters")
if "request_parameters" in row:
return row.get("request_parameters")
return row.get("request") or {}
def _response(row: dict[str, Any]) -> Any:
if "responseElements" in row:
return row.get("responseElements")
if "response_elements" in row:
return row.get("response_elements")
return row.get("response") or {}
def resource_from(event_name: str, request: Any, row: dict[str, Any]) -> tuple[str, str]:
params = request if isinstance(request, dict) else {}
resources = row.get("resources") if isinstance(row.get("resources"), list) else []
candidates = [
("bucket", params.get("bucketName") or params.get("bucket")),
("role", params.get("roleName") or params.get("roleArn")),
("user", params.get("userName") or params.get("userArn")),
("security-group", params.get("groupId") or params.get("groupName")),
("trail", params.get("name") or params.get("trailName")),
("kms-key", params.get("keyId") or params.get("keyArn")),
("instance", params.get("instanceId")),
("detector", params.get("detectorId")),
("config", params.get("configRuleName") or params.get("roleARN")),
]
for kind, value in candidates:
if value:
return kind, normalize_id(value).split("/")[-1]
if resources:
first = resources[0] if isinstance(resources[0], dict) else {}
arn = normalize_id(first.get("ARN") or first.get("arn"))
return normalize_id(first.get("type") or "resource"), arn.rsplit("/", 1)[-1] or arn
existing = normalize_id(row.get("resource_alias") or row.get("resource"))
if existing:
return normalize_id(row.get("resource_kind") or "resource"), existing
return "account", event_name or "unknown"
def user_agent_class(value: Any) -> str:
text = normalize_id(value).lower()
if "console.amazonaws.com" in text or "signin.amazonaws.com" in text:
return "console"
if "terraform" in text:
return "terraform"
if "aws-cli" in text or "awscli" in text:
return "cli"
if "boto" in text or "sdk" in text:
return "sdk"
if not text:
return "unknown"
return "other"
def normalize_event(row: dict[str, Any]) -> dict[str, Any]:
identity = _identity(row)
request = _request(row)
response = _response(row)
incomplete = request in (None, "", {}) and not row.get("request_summary")
kind = actor_kind_of(identity) if not row.get("actor_kind") else normalize_id(row.get("actor_kind"))
name = actor_name_of(identity) if not row.get("actor_alias") else normalize_id(row.get("actor_alias"))
account = alias_account(
identity.get("accountId")
or row.get("recipientAccountId")
or row.get("account_alias")
or row.get("account")
)
event_name = normalize_id(row.get("eventName") or row.get("event_name"))
event_source = normalize_id(row.get("eventSource") or row.get("event_source") or "")
change_type = classify_event(event_name, kind, request)
if row.get("change_type") and normalize_id(row.get("change_type")) in {item.value for item in ChangeType}:
change_type = ChangeType(normalize_id(row.get("change_type")))
flags = flags_from_request(change_type.value, event_name, request, kind)
resource_kind, resource_name = resource_from(event_name, request, row)
request_text = redact_text(compact_json(request) or normalize_id(row.get("request_summary")))
response_text = redact_text(compact_json(response) or normalize_id(row.get("response_summary")))
error_code = normalize_id(row.get("errorCode") or row.get("error_code"))
read_only = row.get("readOnly") if "readOnly" in row else row.get("read_only", False)
if isinstance(read_only, str):
read_only = read_only.lower() in {"1", "true", "yes"}
actor_alias = alias_actor(kind, name, account)
return {
"event_id": normalize_id(row.get("eventID") or row.get("event_id") or row.get("eventId")),
"timestamp": normalize_id(row.get("eventTime") or row.get("timestamp") or row.get("time")),
"account_alias": account,
"actor_alias": actor_alias,
"actor_kind": kind,
"actor_role": normalize_id(row.get("actor_role")) or actor_role_of(kind, name),
"event_source": event_source,
"event_name": event_name,
"change_type": change_type.value,
"region": normalize_id(row.get("awsRegion") or row.get("region") or "us-east-1"),
"resource_alias": alias_resource(resource_kind, resource_name),
"resource_kind": resource_kind,
"read_only": bool(read_only),
"error_code": error_code,
"console": user_agent_class(row.get("userAgent") or row.get("user_agent")) == "console",
"user_agent_class": user_agent_class(row.get("userAgent") or row.get("user_agent")),
"source_ip_alias": alias_ip(row.get("sourceIPAddress") or row.get("source_ip") or row.get("ip")),
"request_summary": request_text[:500],
"response_summary": response_text[:400],
"change_ticket": normalize_id(row.get("change_ticket") or row.get("ticket") or ""),
"lab_event_id": normalize_id(row.get("lab_event_id") or ""),
"lab_family": normalize_id(row.get("lab_family") or ""),
"split": normalize_id(row.get("split") or ""),
"incomplete": bool(incomplete or row.get("incomplete")),
"cidr_open": flags["cidr_open"],
"policy_public": flags["policy_public"],
"admin_policy": flags["admin_policy"],
"logging_off": flags["logging_off"],
"detector_off": flags["detector_off"],
"wildcard_trust": flags["wildcard_trust"],
"hardening": flags["hardening"],
"redacted": looks_sensitive(row),
"raw_redacted": {
"eventName": event_name,
"eventSource": event_source,
"eventTime": normalize_id(row.get("eventTime") or row.get("timestamp")),
"userIdentity": {
"type": identity.get("type"),
"userName": actor_alias,
"accountId": account,
},
"requestParameters": request_text[:500],
"errorCode": error_code or None,
},
}
|