AWS SecOps P0-03 - Trust Policy Backdoor, Inline Escalation and Sensitive PassRole Abuse
P0 03 Iam Privesc Trust Passrole Inline
Query
// REVIEW ONLY. Validate AWSCloudTrail schema first via discovery/D02-awscloudtrail-schema-and-dataevents-check.kql
let ApprovedAutomation = _GetWatchlist('AWS_ApprovedAutomationPrincipals')
| where tolower(tostring(column_ifexists("Verified", ""))) == "true"
| project AutoAccountId=tostring(column_ifexists("AWSAccountId", "")), PrincipalArnPattern=tolower(tostring(column_ifexists("PrincipalArnPattern", ""))),
ValidFrom=todatetime(column_ifexists("ValidFromUtc", "")), ValidTo=todatetime(column_ifexists("ValidToUtc", ""));
let SensitiveCatalog = _GetWatchlist('AWS_SensitiveRolesAndPolicies')
| where tolower(tostring(column_ifexists("Verified", ""))) == "true"
| project CatAccountId=tostring(column_ifexists("AWSAccountId", "")), ResourceArnPattern=tolower(tostring(column_ifexists("ResourceArnPattern", ""))),
Criticality=tostring(column_ifexists("Criticality", "")), AdminEquivalent=tolower(tostring(column_ifexists("AdminEquivalent", "")));
AWSCloudTrail
| where TimeGenerated > ago(1h)
| where isempty(ErrorCode) and isempty(ErrorMessage) and isnotempty(AwsEventId)
| where EventSource in ("iam.amazonaws.com", "ec2.amazonaws.com", "lambda.amazonaws.com", "ecs.amazonaws.com", "cloudformation.amazonaws.com")
| where EventName in (
"UpdateAssumeRolePolicy", "PutUserPolicy", "PutRolePolicy", "PutGroupPolicy",
"CreatePolicyVersion", "AddUserToGroup", "RunInstances",
"CreateFunction20150331", "UpdateFunctionConfiguration20150331v2", "RegisterTaskDefinition", "CreateStack")
| extend Req = parse_json(RequestParameters),
AWSAccountId = coalesce(RecipientAccountId, UserIdentityAccountId),
ActorArnLower = tolower(UserIdentityArn)
| extend PolicyDoc = coalesce(tostring(Req.assumeRolePolicyDocument), tostring(Req.policyDocument), ""),
TargetPrincipal = coalesce(
tostring(Req.roleName), tostring(Req.userName), tostring(Req.groupName),
tostring(Req.role), tostring(Req.roleARN), tostring(Req.executionRoleArn),
tostring(Req.iamInstanceProfile.arn), tostring(Req.policyArn), ""),
SetAsDefault = tobool(Req.setAsDefault)
| extend TargetKey = tolower(TargetPrincipal)
| join kind=leftouter SensitiveCatalog on $left.AWSAccountId == $right.CatAccountId and $left.TargetKey == $right.ResourceArnPattern
| join kind=leftouter ApprovedAutomation on $left.AWSAccountId == $right.AutoAccountId and $left.ActorArnLower == $right.PrincipalArnPattern
| where isnull(ValidFrom) or not(TimeGenerated between (ValidFrom .. ValidTo))
| extend EscalationVector = case(
EventName == "UpdateAssumeRolePolicy" and (PolicyDoc matches regex @"arn:aws[a-z-]*:iam::[0-9]{12}:root|""AWS""\s*:\s*""\*""|Federated|oidc" or AdminEquivalent == "true"),
"TrustPolicyBackdoorOrExternalPrincipal",
EventName in ("PutUserPolicy", "PutRolePolicy", "PutGroupPolicy") and PolicyDoc matches regex @"(?i)""Effect""\s*:\s*""Allow""[\s\S]{0,500}(""Action""\s*:\s*""\*""|iam:|sts:AssumeRole|secretsmanager:|kms:Decrypt)",
"InlinePolicyPrivilegeEscalation",
EventName == "CreatePolicyVersion" and SetAsDefault == true and PolicyDoc matches regex @"(?i)""Effect""\s*:\s*""Allow""[\s\S]{0,500}(""Action""\s*:\s*""\*""|iam:|sts:AssumeRole)",
"DefaultPolicyVersionEscalation",
EventName == "AddUserToGroup" and (AdminEquivalent == "true" or TargetKey has_any ("admin", "poweruser", "security", "prod")),
"PrivilegedGroupAddition",
EventName in ("RunInstances", "CreateFunction20150331", "UpdateFunctionConfiguration20150331v2", "RegisterTaskDefinition", "CreateStack") and isnotempty(TargetPrincipal) and AdminEquivalent == "true",
"SensitiveRolePassRoleExecution",
"")
| where isnotempty(EscalationVector)
| summarize
TimeGenerated = min(TimeGenerated),
LatestIngest = max(ingestion_time()),
ActionCount = count(),
Vectors = make_set(EscalationVector, 10),
Events = make_set(EventName, 10),
SampleRequestParams = tostring(take_any(RequestParameters)),
MfaContext = tostring(take_any(SessionMfaAuthenticated)),
AwsEventId = take_any(AwsEventId)
by AWSAccountId, AWSRegion, UserIdentityArn, TargetPrincipal, SourceIpAddress, UserAgent, Criticality
| where LatestIngest > ago(15m)
| extend AccountName = tostring(split(UserIdentityArn, "/")[-1]),
DynamicSeverity = iff(Criticality =~ "Critical" or tostring(Vectors) has "TrustPolicyBackdoor", "Critical", "High"),
VectorSummary = tostring(Vectors),
EventSummary = tostring(Events)
| project TimeGenerated, AwsEventId, AWSAccountId, AWSRegion, AccountName, UserIdentityArn,
TargetPrincipal, VectorSummary, EventSummary, ActionCount, SourceIpAddress, UserAgent,
MfaContext, SampleRequestParams, DynamicSeverityExplanation
This query is designed to detect potential privilege escalation activities in AWS environments by analyzing AWS CloudTrail logs. Here's a simplified breakdown of what the query does:
-
Purpose: The query aims to identify suspicious activities that could indicate privilege escalation attempts, such as unauthorized changes to IAM policies or roles, and the use of sensitive roles by unapproved entities.
-
Data Source: It uses data from AWS CloudTrail, which logs API calls and activities within AWS accounts.
-
Frequency and Period: The query runs every 15 minutes and looks back over the past hour of data.
-
Detection Logic:
- It checks for specific AWS API calls related to IAM and compute services, such as
UpdateAssumeRolePolicy,PutUserPolicy,RunInstances, etc. - It identifies activities that involve adding external accounts or wildcard principals to trust policies, creating or updating policies with broad permissions, adding users to privileged groups, and executing roles with sensitive permissions.
- It cross-references these activities against watchlists of approved automation principals and sensitive roles/policies to filter out legitimate actions.
- It checks for specific AWS API calls related to IAM and compute services, such as
-
Escalation Vectors: The query categorizes detected activities into different escalation vectors, such as:
- Trust policy backdoors or external principal additions.
- Inline policy privilege escalation.
- Default policy version escalation.
- Privileged group additions.
- Sensitive role execution by unapproved principals.
-
Alerting: If any suspicious activity is detected, an alert is generated with details such as the AWS account, region, user identity, target principal, and a summary of the escalation vector and events.
-
Severity: The alert severity is dynamically set based on the criticality of the detected activity, with "Critical" or "High" as possible levels.
-
Incident Management: The query is configured to create incidents in a security information and event management (SIEM) system, grouping related alerts by account and IP address for easier investigation.
Overall, this query helps security teams monitor and respond to potential security threats related to privilege escalation in AWS environments.