P0 03 Iam Privesc Trust Passrole Inline
Query
// Standalone KQL for Analytic Rule: AWS SecOps P0-03 - Trust Policy Backdoor, Inline Escalation and Sensitive PassRole Abuse
// Rule File: analytics/P0-03-iam-privesc-trust-passrole-inline.yaml | Rule ID: REPLACE_WITH_RULE_GUID | Severity: High
// Schedule: 15m / Lookback: 1h | REVIEW ONLY - Do not deploy/schedule without approval.
// 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 KQL query is designed to detect potential security threats in AWS environments by analyzing AWS CloudTrail logs. Here's a simplified breakdown of what the query does:
-
Watchlist Preparation:
- It retrieves two watchlists: one for approved automation principals and another for sensitive roles and policies. These lists help identify legitimate actions and sensitive resources.
-
Data Filtering:
- The query looks at AWS CloudTrail logs from the past hour, focusing on specific AWS services like IAM, EC2, Lambda, ECS, and CloudFormation.
- It filters out logs with errors and ensures that the event ID is present.
-
Event Analysis:
- It examines specific AWS actions that could indicate privilege escalation or misuse, such as updating role policies, creating policy versions, adding users to groups, and executing roles with sensitive permissions.
- The query checks if these actions involve sensitive roles or are performed by approved automation principals.
-
Escalation Detection:
- It identifies potential security threats by checking for patterns in policy documents and actions that suggest privilege escalation or backdoor creation.
- Various escalation vectors are defined, such as "TrustPolicyBackdoorOrExternalPrincipal" and "InlinePolicyPrivilegeEscalation."
-
Summary and Output:
- The query summarizes the findings by grouping events based on AWS account, region, user identity, and other factors.
- It calculates the number of actions, lists the types of escalation vectors and events detected, and provides a sample of request parameters.
- The severity of each finding is dynamically determined based on the criticality of the resources involved.
-
Final Projection:
- The output includes details like the time of the event, AWS account and region, user identity, target principal, source IP, user agent, and the dynamic severity of the threat.
Overall, this query is part of an analytic rule designed to identify and summarize potential security threats related to privilege escalation and misuse of sensitive roles in AWS environments.