Skip to content

LearnCloud

Cloud persistence audit: AWS and Entra ID

Brief

An attacker who expects to be found leaves something that survives the clean-up: an access key on a quiet user, an outside account in a role's trust policy, a rule that recreates either, a secret on a service principal or a guest with a role. This audit looks for each one and reads the audit trail that shows who made it and when.

Track
Cloud
Stage
Persistence
Reviewed
On this page
  1. Check first
  2. AWS
  3. Azure
  4. The defender sees
  5. Done when
  6. Not covered
  7. Tools
  8. Related research
  9. Where this page fits
  10. Reviewed

All commands

Situation
Read-only review roles in the AWS accounts and Entra ID tenant in scope, with CloudTrail event history, IAM, Lambda and EventBridge read in AWS, and Application.Read.All, RoleManagement.Read.Directory, User.Read.All and AuditLog.Read.All in Entra ID. It runs after a suspected compromise or as the persistence stage of an engagement. Every command is a read: we report what looks like a foothold, with its creation event, and the client removes it, so evidence is preserved and nothing breaks a workload. Only the accounts, regions and tenant the scope letter names are audited.
Goal
A foothold list: each unexpected key, user, trust relationship, trigger, credential and guest role, with the event that created it, the identity that made it and the time.
Outputs
Representative examples on placeholder hosts, trimmed to the lines that matter. Not captured from a public fixture yet.

Check first

  • The window to audit, and the dates of any known or suspected compromise.
  • The client's lists of expected IAM users, external accounts, app registrations and guests, to compare against.
  • How far back the logs reach: CloudTrail event history keeps 90 days, and Entra ID keeps audit logs 7 or 30 days by licence unless they are exported.
  • The regions in use, since Lambda and EventBridge are regional.
  • Who acts on a finding: we report a suspected foothold and change nothing ourselves.

Steps

AWS

Which IAM users and access keys appeared in the window?

aws iam list-users | jq -r '.Users[] | select(.CreateDate >= "2026-09-28") | [.UserName, .CreateDate] | @tsv'
for e in CreateUser CreateAccessKey CreateLoginProfile; do
  aws cloudtrail lookup-events --region us-east-1 --start-time 2026-09-28 \
    --lookup-attributes AttributeKey=EventName,AttributeValue=$e \
    | jq -r '.Events[].CloudTrailEvent | fromjson
        | [.eventTime, .eventName, .userIdentity.arn, .requestParameters.userName] | @tsv'
done

Expected output

svc-backup2	2026-10-21T03:12:44+00:00
2026-10-21T03:12:44Z	CreateUser	arn:aws:iam::111122223333:user/ci-deploy	svc-backup2
2026-10-21T03:13:02Z	CreateAccessKey	arn:aws:iam::111122223333:user/ci-deploy	svc-backup2   # <- the CI user made a user and gave it a key

A new key on an existing user is the quieter version, so the event loop matters more than the user list. IAM is global and its events are recorded in us-east-1; event history reaches back 90 days, and anything older is read from the organization trail in S3 or CloudTrail Lake. The access key id is an identifier, not a secret, so it can go in the report.

Negative result. Every user and key created in the window matches a change record.

Fix. Deactivate an unexplained key first, which is reversible, then investigate what it did. Prefer roles to IAM users, and deny iam:CreateUser and iam:CreateAccessKey outside the platform role with an SCP.

Which role trust policies changed?

aws cloudtrail lookup-events --region us-east-1 --start-time 2026-09-28 \
  --lookup-attributes AttributeKey=EventName,AttributeValue=UpdateAssumeRolePolicy \
  | jq -r '.Events[].CloudTrailEvent | fromjson | [.eventTime, .userIdentity.arn, .requestParameters.roleName] | @tsv'
aws iam get-role --role-name ops-audit --query 'Role.AssumeRolePolicyDocument.Statement[].Principal'

Expected output

2026-10-21T03:15:40Z	arn:aws:iam::111122223333:user/ci-deploy	ops-audit
[
    {
        "AWS": "arn:aws:iam::999988887777:root"   # <- an account outside the organization can assume this role
    }
]

Editing the trust of an existing role keeps a familiar name in the console while letting an outside account in. We compare every account id in trust policies with the organization's account list and the client's vendor list.

Negative result. No trust changes outside change records, and every external principal is a known vendor with an sts:ExternalId condition.

Fix. Restore the trust policy from infrastructure code, turn on an organization-wide Access Analyzer for external access, and alert on UpdateAssumeRolePolicy.

Which rules and functions run on their own?

aws events list-rules --region eu-west-1 --query 'Rules[].[Name,State,ScheduleExpression]' --output text
aws events list-targets-by-rule --region eu-west-1 --rule iam-sync --query 'Targets[].Arn' --output text
aws cloudtrail lookup-events --region eu-west-1 --start-time 2026-09-28 \
  --lookup-attributes AttributeKey=EventSource,AttributeValue=lambda.amazonaws.com \
  --query 'Events[].[EventTime,EventName,Username]' --output text | grep -vE 'Get|List'

Expected output

iam-sync	ENABLED	None   # <- no schedule, so an event pattern fires it; read the pattern
nightly-report	ENABLED	cron(0 2 * * ? *)
arn:aws:lambda:eu-west-1:111122223333:function:iam-sync
2026-10-21T03:20:11+00:00	CreateFunction20150331	ci-deploy
2026-10-21T03:20:48+00:00	AddPermission20150331v2	ci-deploy   # <- EventBridge allowed to invoke a function made in the window

A rule that fires on IAM events or a schedule, pointing at a function whose role can write IAM, recreates a deleted key minutes after the clean-up. Lambda event names carry an API version suffix, which is why the search goes by event source. We run this per region and read each suspicious rule's pattern with describe-rule.

Negative result. Every rule and function maps to a known deployment, and no function role created in the window can write IAM.

Fix. Preserve the function code and rule, then remove them together. Deploy rules and functions only through the pipeline, and alert on PutRule, PutTargets and CreateFunction from any other identity.

Azure

Which apps and service principals gained credentials?

Connect-MgGraph -Scopes 'Application.Read.All','AuditLog.Read.All' -NoWelcome
$since = (Get-Date).AddDays(-30)
$objects = @(Get-MgApplication -All -Property DisplayName,PasswordCredentials,KeyCredentials) +
           @(Get-MgServicePrincipal -All -Property DisplayName,PasswordCredentials,KeyCredentials)
foreach ($o in $objects) {
  @($o.PasswordCredentials) + @($o.KeyCredentials) | Where-Object { $_.StartDateTime -gt $since } |
    ForEach-Object { [pscustomobject]@{ Object = $o.DisplayName; Kind = $o.GetType().Name; Start = $_.StartDateTime; End = $_.EndDateTime } }
}
Get-MgAuditLogDirectoryAudit -Filter "activityDisplayName eq 'Add service principal credentials'" -Top 20 |
  Select-Object ActivityDateTime, @{n='Target';e={$_.TargetResources[0].DisplayName}}

Expected output

Object            Kind                            Start                  End
------            ----                            -----                  ---
backup-connector  MicrosoftGraphServicePrincipal  10/21/2026 3:14:09 AM  10/21/2028 3:14:09 AM   # <- a two-year secret on the service principal
ActivityDateTime       Target
----------------       ------
10/21/2026 3:14:09 AM  backup-connector   # <- the audit event that added it

A secret added to a service principal rather than its app registration does not appear on the app registration's certificates and secrets page, so it survives a review done there. The selected properties never include the secret's hint or value. The audit event's InitiatedBy names the account or app that added it, which leads to the next foothold.

Negative result. Every credential that started in the window matches a change record.

Fix. Record the credential's key id, remove it, and review what the app signed in to since. Limit who can manage app credentials, and use an app management policy to block password credentials on service principals.

Which guests hold directory roles?

Connect-MgGraph -Scopes 'RoleManagement.Read.Directory','User.Read.All' -NoWelcome
$roles = @{}; Get-MgRoleManagementDirectoryRoleDefinition -All | ForEach-Object { $roles[$_.Id] = $_.DisplayName }
Get-MgRoleManagementDirectoryRoleAssignment -All -ExpandProperty Principal |
  Where-Object { $_.Principal.AdditionalProperties.userPrincipalName -like '*#EXT#*' } |
  ForEach-Object { [pscustomobject]@{ Role = $roles[$_.RoleDefinitionId];
    GuestDomain = ($_.Principal.AdditionalProperties.mail -split '@')[1] } }

Expected output

Role                       GuestDomain
----                       -----------
Application Administrator  partner.example   # <- a guest who can add credentials to any app

Guests are reviewed less often than staff, so a guest with a role survives a reset of every internal account. We print the role and the guest's mail domain, not the person. The audit log shows the Invite external user and Add member to role events behind each one.

Negative result. No guest holds a directory role, and every guest added in the window matches an invitation the client sent.

Fix. Remove directory roles from guests, run access reviews on guests, limit who can invite them, and alert on a role assignment to any #EXT# account.

The defender sees

Our own reads show up too: LookupEvents and the IAM, EventBridge and Lambda reads in CloudTrail under the review role, and our sign-in to Microsoft Graph PowerShell in the Entra sign-in log. The more useful question is whether the defender saw the footholds when they were made. Each one above has a creation event, CreateAccessKey, UpdateAssumeRolePolicy, AddPermission20150331v2, Add service principal credentials and Add member to role, and each should have raised an alert at the time. Where the client finds them only because we looked, the missing alert is a finding beside the foothold, and the AWS IAM privilege escalation checks show which of those identities could have made more.

Done when

Users and keys created in the window are matched to change records, every role whose trust changed is listed with its external principals, every rule and function created in the window is tied to a deployment or reported, every credential added to an app or service principal is explained, and every guest with a directory role is listed.

Not covered

Endpoint and Windows persistence (see the Windows persistence audit), stolen user sessions (see stolen token response), Google Cloud and OCI, and removing what is found; the outputs shown are representative examples on placeholder accounts and tenants, not captured runs.