P0 02 Iam Credential Persistence
Query
// Standalone KQL for Analytic Rule: AWS SecOps P0-02 - Coordinated IAM Credential Persistence and Cross-Principal Backdooring
// Rule File: analytics/P0-02-iam-credential-persistence.yaml | Rule ID: REPLACE_WITH_RULE_GUID | Severity: High
// Schedule: 15m / Lookback: 2h | 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 PrivChanges = AWSCloudTrail
| where TimeGenerated > ago(2h) and EventSource == "iam.amazonaws.com"
| where isempty(ErrorCode) and isempty(ErrorMessage)
| where EventName in ("CreateUser", "AttachUserPolicy", "PutUserPolicy", "AddUserToGroup", "UpdateAssumeRolePolicy")
| extend ReqP = parse_json(RequestParameters)
| extend ChangedUser = tolower(tostring(ReqP.userName))
| where isnotempty(ChangedUser)
| summarize PrivChangeEvents=make_set(EventName, 10), FirstPrivChange=min(TimeGenerated)
by RecipientAccountId, ChangedUser;
AWSCloudTrail
| where TimeGenerated > ago(2h)
| where EventSource == "iam.amazonaws.com"
| where isempty(ErrorCode) and isempty(ErrorMessage) and isnotempty(AwsEventId)
| where EventName in (
"CreateLoginProfile", "UpdateLoginProfile", "CreateVirtualMFADevice", "EnableMFADevice",
"ResyncMFADevice", "UploadSigningCertificate", "UploadSSHPublicKey",
"CreateServiceSpecificCredential", "CreateAccessKey")
| extend Req = parse_json(RequestParameters)
| extend TargetPrincipal = coalesce(tostring(Req.userName), tostring(Req.virtualMFADeviceName), ""),
ActorArn = UserIdentityArn,
ActorShort = tostring(split(UserIdentityArn, "/")[-1]),
AWSAccountId = coalesce(RecipientAccountId, UserIdentityAccountId)
| extend IsCrossPrincipalKey = (EventName == "CreateAccessKey" and isnotempty(TargetPrincipal) and tolower(TargetPrincipal) != tolower(ActorShort))
| where EventName != "CreateAccessKey" or IsCrossPrincipalKey
| extend ActorArnLower = tolower(ActorArn), TargetLower = tolower(TargetPrincipal)
| join kind=leftouter ApprovedAutomation on $left.AWSAccountId == $right.AutoAccountId and $left.ActorArnLower == $right.PrincipalArnPattern
| where isnull(ValidFrom) or not(TimeGenerated between (ValidFrom .. ValidTo))
| join kind=leftouter PrivChanges on $left.RecipientAccountId == $right.RecipientAccountId and $left.TargetLower == $right.ChangedUser
| summarize
TimeGenerated = min(TimeGenerated),
LatestIngest = max(ingestion_time()),
PersistenceEvents = make_set(EventName, 15),
CorrelatedPrivChanges = take_any(PrivChangeEvents),
SampleRequestParams = tostring(take_any(RequestParameters)),
MfaContext = tostring(take_any(SessionMfaAuthenticated)),
AwsEventId = take_any(AwsEventId)
by AWSAccountId, AWSRegion, ActorArn, ActorShort, TargetPrincipal, SourceIpAddress, UserAgent
| where LatestIngest > ago(15m)
| extend PersistenceSummary = tostring(PersistenceEvents),
PrivChangeSummary = tostring(coalesce(CorrelatedPrivChanges, dynamic([])))
| project TimeGenerated, AwsEventId, AWSAccountId, AWSRegion, ActorArn, AccountName=ActorShort,
TargetPrincipal, SourceIpAddress, UserAgent, MfaContext, PersistenceSummary,
PrivChangeSummary, SampleRequestParamsExplanation
This KQL query is designed to detect suspicious activities related to IAM credential persistence and cross-principal backdooring in AWS environments. Here's a simplified breakdown of what the query does:
-
Approved Automation List: It first retrieves a list of approved automation principals from a watchlist, filtering for those marked as "true" and extracting relevant details like AWS account ID and principal ARN pattern.
-
Privilege Changes: It checks AWS CloudTrail logs from the past 2 hours for specific IAM events that indicate privilege changes (e.g., creating users, attaching policies). It summarizes these events by account and user, noting the types of privilege changes and the first occurrence time.
-
Credential Persistence Events: The query then looks for IAM events related to credential persistence (e.g., creating login profiles, enabling MFA devices, uploading SSH keys) within the same 2-hour window. It identifies if these events involve cross-principal actions, where the actor and target are different.
-
Cross-Referencing: It cross-references these events with the approved automation list to filter out legitimate automation activities. It also joins with the privilege changes data to correlate persistence events with any recent privilege changes.
-
Summarization: The query summarizes the findings, including the time of the event, AWS account and region, actor and target details, source IP, user agent, and any associated MFA context. It also provides a summary of persistence and privilege change events.
-
Recent Activity Filter: Finally, it filters for events ingested in the last 15 minutes to ensure the data is current.
The query is intended for review only and should not be deployed without proper validation and approval. It is designed to help security teams identify potential security threats related to unauthorized IAM credential changes and cross-principal actions in AWS.