Least privilege in practice with IAM Access Analyzer
Run a repeatable least-privilege workflow: start narrow, use condition keys and ABAC, generate policies from CloudTrail activity, remove unused access, and gate every policy change with IAM Access Analyzer checks from C#.
Assumes: .NET 10 LTS · AWS SDK for .NET v4 (AWSSDK.AccessAnalyzer 4.1.0.2) · AWS CLI v2 · Region us-east-1. Verified against official sources on 2026-11-17.
Learning objectives
By the end of this lesson you can:
- Describe a least-privilege lifecycle — design, generate, validate, deploy, monitor, trim — and who owns each step in a bank.
- Use the condition keys that do most of the work in financial-services policies:
aws:PrincipalOrgID,aws:ResourceOrgID,aws:SourceVpce,aws:SourceVpc,aws:MultiFactorAuthPresent,aws:PrincipalTagandaws:ResourceTag(ABAC). - Use IAM Access Analyzer for external access, internal access and unused access findings, policy validation, custom policy checks and policy generation — and say which of these cost money.
- Read last accessed information (Access Advisor) to remove permissions nobody uses.
- Build a C# policy gate that fails a pipeline when a policy has errors, security warnings, or grants a forbidden action.
Prerequisites
- IAM in depth — policy grammar and the nine policy types
- Policy evaluation logic — how allows and denies combine
- A CloudTrail trail in the sandbox account is needed only for the policy-generation step (see CloudTrail for banks); the first management-events trail is free
- Tools: AWS CLI v2, .NET 10 SDK,
learn-sandboxprofile
Why this matters in banking
Harbourline's Accounts API team asked for "S3 full access" two years ago because a deadline was close. The role still has it. Nobody remembers why. Today that role could delete statement archives, change bucket policies to public, or read the data platform's customer extracts. Nothing bad has happened — yet — but the internal auditor's finding is blunt: "Access is not restricted to business need; no evidence of periodic review."
Least privilege is the principle that every identity holds only the permissions it needs for its job, for as long as it needs them. Regulators and standards bodies expect it (PCI DSS, for example, has a whole requirement on restricting access by business need to know). The hard part is not agreeing with the principle; it is doing it continuously across hundreds of roles without breaking production. That is what this lesson is about.
Security of vs in the cloud: AWS provides the tools (Access Analyzer, last accessed data, condition keys). Choosing, reviewing and trimming permissions is entirely Harbourline's responsibility.
The idea in plain language
Least privilege is not a one-off clean-up; it is a loop:
- Start narrow. Write the smallest policy you can justify from the design: specific actions, specific resource ARNs, and conditions on where and how the request may come from.
- Generate from evidence. If you inherit a broad role, let AWS tell you what it actually used (CloudTrail-based policy generation and last accessed data).
- Validate before deploy. Automatically check every policy for mistakes and for forbidden permissions in the pipeline.
- Monitor. Get findings when something is shared outside the organisation, or when granted permissions go unused.
- Trim. Remove what is unused, through the normal change process, and record the review as evidence.
Analogy: A new branch employee does not get a master key "in case they need it". They get the keys for their counter. Every quarter the branch manager reviews the key log: keys that were never used are collected, and any key found in another branch's lock triggers an investigation. IAM Access Analyzer is the key log reviewer that never takes a holiday.
What problem IAM Access Analyzer solves
IAM Access Analyzer is a feature set inside IAM that uses automated reasoning (mathematical analysis of policies, not sampling) and activity data to answer "who can access what?" It has six capabilities:
| Capability | Question it answers | Scope | Cost (checked 2026-11-17) |
|---|---|---|---|
| External access analyzer | Which of my resources can a principal outside my zone of trust (account or organisation) reach? | Resource-based policies of S3 buckets, IAM role trust policies, KMS keys, Lambda, SQS, SNS, Secrets Manager, EBS/RDS snapshots, ECR, EFS, DynamoDB tables and streams and more; per Region | No additional charge |
| Internal access analyzer | Which principals inside my organisation or account can reach my selected critical resources? | Selected S3 buckets, DynamoDB tables and streams, RDS snapshots | Charged per monitored resource per Region per month (about USD 9 at the time of writing ⚠ VERIFY on the pricing page) |
| Unused access analyzer | Which roles, users, access keys, passwords, services and actions have not been used for N days? | All IAM roles and users in the account or organisation; not Region-specific | USD 0.20 per IAM role or user analysed per analyzer per month; service-linked roles are not counted |
| Policy validation | Does this policy have grammar errors, security warnings or best-practice issues? | Any policy you submit | No additional charge |
| Custom policy checks | Does this policy grant new access compared with the old one? Does it grant any of these forbidden actions? Could this resource policy allow public access? | Any policy you submit | USD 0.0020 per API call |
| Policy generation | What did this role actually do over the last N days? | Up to 90 days of CloudTrail management events | No additional charge (standard S3 request charges for reading the logs) |
Limitations to know before you rely on it:
- External access analyzers are Regional. Create one in every Region you use (or let your organisation-level automation do it).
- Policy generation does not see data events (for example
s3:GetObject) at action level, and never seesiam:PassRole, because CloudTrail does not record it as a separate event. You must add these by hand. - Policy generation cannot read the CloudTrail bucket that AWS Control Tower creates in the log-archive account, because of Control Tower's own guardrails. Use a separate trail for generation if you run Control Tower.
- Findings are only as good as your zone of trust. An analyzer for the account treats other accounts in your organisation as external; an organisation analyzer does not.
Microsoft / Azure comparison
| You know (Microsoft/Azure) | AWS equivalent | What's different |
|---|---|---|
| Entra ID access reviews | Access Analyzer unused access findings + Identity Center assignment reviews | AWS findings are generated automatically from activity; the review decision is still yours |
| Entra Permissions Management (CIEM) | Access Analyzer unused access + policy generation | Native, per account or organisation; no separate product to license |
| Azure Policy "audit" for public storage | Access Analyzer external access findings, S3 Block Public Access | Analyzer reasons over the policy logic, not just a flag |
Azure RBAC custom roles with NotActions | Policies with specific Action lists; avoid NotAction with Allow | AWS has thousands of actions; wildcards like s3:Get* are common but must be deliberate |
| Conditional Access (location, MFA) | Global condition keys: aws:SourceIp, aws:SourceVpce, aws:MultiFactorAuthPresent | Conditions are part of each policy statement, evaluated per API call |
| ABAC with Azure attributes in role assignment conditions | ABAC with aws:PrincipalTag / aws:ResourceTag | Works across most services; tags on sessions can come from the IdP |
Architecture
The least-privilege lifecycle at Harbourline:
Where Access Analyzer sits in an organisation:
Security-boundary view: the organisation is the zone of trust. Anything that lets a principal outside it reach a resource inside it is a finding to review. Inside the organisation, unused access findings and internal access analysis find the "too much access" problems that external analysis cannot see.
Condition keys that do the heavy lifting
Most of a bank's least-privilege value comes from a small number of global condition keys:
| Key | Use it to… | Example |
|---|---|---|
aws:PrincipalOrgID | Allow only principals from your organisation in a resource policy | Bucket policy that lets any Harbourline account write logs, but nobody else |
aws:ResourceOrgID | Allow your principals to reach only resources owned by your organisation | Endpoint or identity policy that stops data being copied to a personal bucket |
aws:SourceVpce / aws:SourceVpc | Require that a request arrives through your VPC endpoint | Statements bucket readable only from the private network |
aws:SourceIp | Restrict by public IP — only meaningful for requests that come over the internet | Legacy IAM user restricted to the data centre egress range |
aws:MultiFactorAuthPresent, aws:MultiFactorAuthAge | Require MFA (and recent MFA) for sensitive actions | Deny kms:ScheduleKeyDeletion without MFA |
aws:PrincipalTag/…, aws:ResourceTag/…, aws:RequestTag/…, aws:TagKeys | Attribute-based access control (ABAC) | A team=payments session can only touch resources tagged team=payments |
aws:SourceAccount, aws:SourceArn | Stop a service principal acting for someone else (confused deputy) | CloudTrail may write to the bucket only for your trail |
kms:ViaService, kms:EncryptionContext:… | Allow key use only through a specific service or for a specific context | Decrypt allowed only via DynamoDB in us-east-1 |
A data-perimeter bucket policy for Harbourline's statement archive combines several of them:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "DenyOutsideOrganisation",
"Effect": "Deny",
"Principal": "*",
"Action": "s3:*",
"Resource": ["arn:aws:s3:::hl-m05-statements", "arn:aws:s3:::hl-m05-statements/*"],
"Condition": {
"StringNotEqualsIfExists": { "aws:PrincipalOrgID": "o-exampleorgid" },
"BoolIfExists": { "aws:PrincipalIsAWSService": "false" }
}
},
{
"Sid": "DenyObjectReadsOutsideVpcEndpoint",
"Effect": "Deny",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::hl-m05-statements/*",
"Condition": {
"StringNotEquals": { "aws:SourceVpce": "vpce-0a1b2c3d4e5f67890" }
}
},
{
"Sid": "DenyInsecureTransport",
"Effect": "Deny",
"Principal": "*",
"Action": "s3:*",
"Resource": ["arn:aws:s3:::hl-m05-statements", "arn:aws:s3:::hl-m05-statements/*"],
"Condition": { "Bool": { "aws:SecureTransport": "false" } }
}
]
}Read it as three fences: nobody outside the organisation (except AWS services acting on your behalf), no object reads except through the bank's VPC endpoint, and no unencrypted HTTP. None of these statements grants anything — the Accounts API role still needs an identity policy allowing s3:GetObject. That separation (resource policy fences, identity policy grants) keeps the bucket policy short and stable.
ABAC in two statements
Role-based access control (RBAC) needs a new policy for every team and resource. Attribute-based access control (ABAC) writes one policy that compares tags:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ManageOwnTeamsQueues",
"Effect": "Allow",
"Action": ["sqs:SendMessage", "sqs:ReceiveMessage", "sqs:DeleteMessage", "sqs:GetQueueAttributes"],
"Resource": "arn:aws:sqs:us-east-1:111122223333:hl-*",
"Condition": {
"StringEquals": { "aws:ResourceTag/team": "${aws:PrincipalTag/team}" }
}
},
{
"Sid": "DenyChangingTeamTag",
"Effect": "Deny",
"Action": ["sqs:TagQueue", "sqs:UntagQueue"],
"Resource": "*",
"Condition": { "ForAnyValue:StringEquals": { "aws:TagKeys": ["team"] } }
}
]
}The second statement matters: if people can change the team tag on a resource, they can grant themselves access. ABAC is only as strong as the governance of the tags — who can set them, and an SCP or tag policy that protects them.
Step-by-step implementation
Turn on an external access analyzer
Create an account-level external access analyzer in us-east-1 (free). Within about 30 minutes it reports any existing resource shared outside the account. In the sandbox, the OrganizationAccountAccessRole trust policy (trusting the management account) is a typical first finding — archive it with a note, because it is intended.
Create something that should be flagged
Create a bucket hl-m05-share-test-<yourname> and add a bucket policy granting s3:GetObject to a made-up external account arn:aws:iam::999988887777:root. Leave Block Public Access on. Within minutes Access Analyzer reports a cross-account finding. Delete the policy and choose Rescan: the finding moves to Resolved.
Read last accessed information
Pick any role you have used in the sandbox (for example the SSO role) and open Access Advisor. Note services granted but never used. Then generate an action-level report with the CLI (generate-service-last-accessed-details --granularity ACTION_LEVEL).
(Optional, credits) Create an unused access analyzer
An unused access analyzer costs USD 0.20 per role or user analysed per month. A sandbox with 15 roles costs about USD 3 per month while it exists; delete it the same day. It shows unused roles, unused services and actions per role, and unused credentials.
Generate a policy from activity
If you have a CloudTrail trail, generate a policy for a role you have used today (time range: the last day). Compare the generated template with the role's current policy. Add resource ARNs where the template has placeholders.
Add the policy gate
Build the C# policy gate from Complete code and run it against the good and bad policies. In your pipeline, the gate runs on every change to an IAM policy file.
AWS Console instructions
- Console → IAM → Access analyzer → Analyzer settings → Create analyzer → Finding type: External access analysis → Zone of trust: Current account → name
hl-m05-external. - Console → IAM → Access analyzer → Resource analysis (external and internal findings) and Unused access list findings. Choose a finding to see the principal, the access level and the policy statement that grants it. Archive with a reason for intended access; set up archive rules for patterns you accept organisation-wide.
- Console → IAM → Roles → (role) → Access Advisor shows each service with Last accessed; for some services (for example EC2, IAM, Lambda, S3) it drills down to actions.
- Console → IAM → Roles → (role) → Permissions → Generate policy based on CloudTrail events → choose up to 90 days, the trail and a service role → Generate policy. The generated template is viewable for 7 days.
- Console → IAM → Policies → (policy) → Edit → JSON shows Policy validation results live. The Check for new access tab runs a custom policy check (charged per check).
AWS CLI
# 1. External access analyzer for this account (free).
aws accessanalyzer create-analyzer --profile learn-sandbox --region us-east-1 \
--analyzer-name hl-m05-external --type ACCOUNT \
--tags Project=cea-lab,Lab=m05-least-privilege,Environment=learn,Owner=alex
# 2. List active findings (v2 API covers all finding types).
ANALYZER_ARN=$(aws accessanalyzer get-analyzer --analyzer-name hl-m05-external \
--profile learn-sandbox --region us-east-1 --query analyzer.arn --output text)
aws accessanalyzer list-findings-v2 --analyzer-arn "$ANALYZER_ARN" \
--filter '{"status":{"eq":["ACTIVE"]}}' --profile learn-sandbox --region us-east-1
# 3. (Credits) Unused access analyzer: report anything unused for 30+ days.
aws accessanalyzer create-analyzer --profile learn-sandbox --region us-east-1 \
--analyzer-name hl-m05-unused --type ACCOUNT_UNUSED_ACCESS \
--configuration '{"unusedAccess":{"unusedAccessAge":30}}' \
--tags Project=cea-lab,Lab=m05-least-privilege,Environment=learn,Owner=alex
# 4. Last accessed data, action level, for one role (free, asynchronous job).
JOB_ID=$(aws iam generate-service-last-accessed-details --profile learn-sandbox \
--arn arn:aws:iam::111122223333:role/hl-m05-accounts-api --granularity ACTION_LEVEL \
--query JobId --output text)
aws iam get-service-last-accessed-details --job-id "$JOB_ID" --profile learn-sandbox \
--query "ServicesLastAccessed[].{Service:ServiceNamespace,Last:LastAuthenticated}"
# 5. Validate a policy (free): errors, security warnings, warnings, suggestions.
aws accessanalyzer validate-policy --profile learn-sandbox --region us-east-1 \
--policy-type IDENTITY_POLICY --policy-document file://candidate-policy.json \
--query "findings[].{Type:findingType,Code:issueCode,Detail:findingDetails}"
# 6. Custom check (USD 0.002 per call): does the policy grant any forbidden action?
aws accessanalyzer check-access-not-granted --profile learn-sandbox --region us-east-1 \
--policy-type IDENTITY_POLICY --policy-document file://candidate-policy.json \
--access '[{"actions":["kms:ScheduleKeyDeletion","cloudtrail:StopLogging","iam:CreateAccessKey"]}]'
# 7. Custom check: does the new version grant anything the old one did not?
aws accessanalyzer check-no-new-access --profile learn-sandbox --region us-east-1 \
--policy-type IDENTITY_POLICY \
--existing-policy-document file://current-policy.json --new-policy-document file://candidate-policy.json
# 8. Policy generation from CloudTrail (free; needs a trail and a service role).
aws accessanalyzer start-policy-generation --profile learn-sandbox --region us-east-1 \
--policy-generation-details principalArn=arn:aws:iam::111122223333:role/hl-m05-accounts-api \
--cloud-trail-details '{
"trails":[{"cloudTrailArn":"arn:aws:cloudtrail:us-east-1:111122223333:trail/hl-m05-trail","allRegions":true}],
"accessRole":"arn:aws:iam::111122223333:role/service-role/AccessAnalyzerMonitorServiceRole_hlm05",
"startTime":"2026-11-16T00:00:00Z"}'
aws accessanalyzer get-generated-policy --job-id <job-id-from-previous-output> \
--profile learn-sandbox --region us-east-1The --filter syntax for list-findings-v2 and the exact JSON shape of --cloud-trail-details are worth checking with aws accessanalyzer <command> help if your CLI version differs ⚠ VERIFY.
Infrastructure as Code
using Amazon.CDK;
using Amazon.CDK.AWS.AccessAnalyzer;
using Constructs;
namespace Harbourline.Security.Infra;
public sealed class AccessAnalyzerStack : Stack
{
public AccessAnalyzerStack(Construct scope, string id, IStackProps? props = null) : base(scope, id, props)
{
// External access analyzer: free, one per Region you use.
_ = new CfnAnalyzer(this, "External", new CfnAnalyzerProps
{
AnalyzerName = "hl-m05-external",
Type = "ACCOUNT", // "ORGANIZATION" from the delegated administrator account
// Union-typed CDK properties are 'object' in C#, so use explicit arrays, not collection expressions.
ArchiveRules = new[]
{
// Intended: the management account may assume OrganizationAccountAccessRole.
new CfnAnalyzer.ArchiveRuleProperty
{
RuleName = "org-access-role",
Filter = new[]
{
new CfnAnalyzer.FilterProperty { Property = "resource", Contains = new[] { "OrganizationAccountAccessRole" } }
}
}
}
});
// Unused access analyzer: charged per role/user analysed per month. Off by default in labs.
if (Node.TryGetContext("enableUnusedAccess") as string == "true")
{
_ = new CfnAnalyzer(this, "Unused", new CfnAnalyzerProps
{
AnalyzerName = "hl-m05-unused",
Type = "ACCOUNT_UNUSED_ACCESS",
AnalyzerConfiguration = new CfnAnalyzer.AnalyzerConfigurationProperty
{
UnusedAccessConfiguration = new CfnAnalyzer.UnusedAccessConfigurationProperty
{
UnusedAccessAge = 30
}
}
});
}
Amazon.CDK.Tags.Of(this).Add("Project", "cea-lab");
Amazon.CDK.Tags.Of(this).Add("Lab", "m05-least-privilege");
Amazon.CDK.Tags.Of(this).Add("Environment", "learn");
Amazon.CDK.Tags.Of(this).Add("Owner", "alex");
}
}Deploy with cdk deploy -c enableUnusedAccess=false (the default) to stay free.
Complete code
A pipeline policy gate: it reads every *.json policy in a folder, runs free validation, then a paid CheckAccessNotGranted for Harbourline's forbidden actions, and exits non-zero on any failure. It needs a role with access-analyzer:ValidatePolicy and access-analyzer:CheckAccessNotGranted (both support only "Resource": "*").
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<RootNamespace>Harbourline.Security.PolicyGate</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AWSSDK.AccessAnalyzer" Version="4.1.0.2" />
<PackageReference Include="AWSSDK.SSO" Version="4.1.0.2" />
<PackageReference Include="AWSSDK.SSOOIDC" Version="4.1.0.2" />
</ItemGroup>
</Project>using Amazon;
using Amazon.AccessAnalyzer;
using Amazon.AccessAnalyzer.Model;
// Usage: dotnet run -- <folder-with-identity-policies> [--skip-paid-checks]
if (args.Length == 0 || !Directory.Exists(args[0]))
{
Console.Error.WriteLine("Usage: dotnet run -- <policy-folder> [--skip-paid-checks]");
return 2;
}
var skipPaid = args.Contains("--skip-paid-checks");
// Actions no workload policy at Harbourline may grant. Owned by the security team.
string[] forbiddenActions =
[
"iam:CreateAccessKey", "iam:CreateUser", "iam:PutRolePolicy", "iam:AttachRolePolicy",
"kms:ScheduleKeyDeletion", "kms:PutKeyPolicy",
"cloudtrail:StopLogging", "cloudtrail:DeleteTrail",
"s3:PutBucketPolicy", "s3:DeleteBucketPolicy", "s3:PutBucketPublicAccessBlock"
];
// The SDK uses the default credential chain: AWS_PROFILE=learn-sandbox locally, the pipeline role in CI.
using var analyzer = new AmazonAccessAnalyzerClient(RegionEndpoint.USEast1);
var failed = false;
foreach (var file in Directory.EnumerateFiles(args[0], "*.json").Order())
{
var document = await File.ReadAllTextAsync(file);
Console.WriteLine($"== {Path.GetFileName(file)}");
// 1. Free: grammar and best-practice validation (follows pagination).
var findings = new List<ValidatePolicyFinding>();
await foreach (var f in analyzer.Paginators.ValidatePolicy(new ValidatePolicyRequest
{
PolicyDocument = document,
PolicyType = PolicyType.IDENTITY_POLICY
}).Findings)
{
findings.Add(f);
}
foreach (var f in findings)
{
var blocking = f.FindingType == ValidatePolicyFindingType.ERROR
|| f.FindingType == ValidatePolicyFindingType.SECURITY_WARNING;
failed |= blocking;
Console.WriteLine($" {(blocking ? "FAIL" : "info")} {f.FindingType} {f.IssueCode}: {f.FindingDetails}");
}
if (skipPaid) continue;
// 2. Paid (USD 0.002 per call): does the policy grant any forbidden action?
var check = await analyzer.CheckAccessNotGrantedAsync(new CheckAccessNotGrantedRequest
{
PolicyDocument = document,
PolicyType = AccessCheckPolicyType.IDENTITY_POLICY,
Access = [new Access { Actions = [.. forbiddenActions] }]
});
if (check.Result == CheckAccessNotGrantedResult.FAIL)
{
failed = true;
Console.WriteLine($" FAIL forbidden access: {check.Message}");
foreach (var reason in check.Reasons ?? [])
Console.WriteLine($" statement {reason.StatementIndex} ({reason.StatementId}): {reason.Description}");
}
else
{
Console.WriteLine(" pass no forbidden actions granted");
}
}
Console.WriteLine(failed ? "Policy gate: FAILED" : "Policy gate: passed");
return failed ? 1 : 0;Two sample inputs to try:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ReadAccounts",
"Effect": "Allow",
"Action": ["dynamodb:GetItem", "dynamodb:Query"],
"Resource": "arn:aws:dynamodb:us-east-1:111122223333:table/hl-m05-accounts"
}
]
}{
"Version": "2012-10-17",
"Statement": [
{ "Effect": "Allow", "Action": "iam:PassRole", "Resource": "*" },
{ "Effect": "Allow", "Action": ["kms:*", "s3:Put*"], "Resource": "*" }
]
}Expected output (abridged):
== bad-ops-helper.json
FAIL SECURITY_WARNING PASS_ROLE_WITH_STAR_IN_RESOURCE: Using the iam:PassRole action with wildcards (*) in the resource can be overly permissive ...
FAIL forbidden access: The policy document grants access to perform one or more of the listed actions.
statement 1 (): ...
== good-accounts-api.json
pass no forbidden actions granted
Policy gate: FAILEDThe exact issue codes and wording come from AWS and may change; do not match on message text in automation — match on FindingType and Result.
Code explained line by line
skipPaid— lets developers run the free checks locally as often as they like and leave the paid check to the pipeline.forbiddenActions— a short, security-owned list. These actions are reserved for the platform and security pipelines; a workload role that gets one of them has a privilege-escalation path.new AmazonAccessAnalyzerClient(RegionEndpoint.USEast1)— no explicit credentials: the default chain usesAWS_PROFILEon your laptop and the pipeline's OIDC role in CI. Never put credentials in this tool.analyzer.Paginators.ValidatePolicy(...)— validation can return many findings; the paginator followsNextToken.PolicyType.IDENTITY_POLICY— validation rules differ forRESOURCE_POLICYandSERVICE_CONTROL_POLICY; choose the type matching the file. A real gate would read the type from the folder name.ERRORandSECURITY_WARNINGblock;WARNINGandSUGGESTIONare printed for the reviewer. That split keeps the gate strict without being noisy.CheckAccessNotGrantedAsyncwithAccess = [new Access { Actions = [...] }]— automated reasoning proves whether any statement in the policy could allow any listed action, including through wildcards such askms:*. That is why the bad policy fails even though it never spells outkms:ScheduleKeyDeletion.check.Reasons— points to the statement index that grants the access, so the developer knows what to fix. In SDK v4 the list may benull, hence?? [].return failed ? 1 : 0;— a non-zero exit fails the pipeline step.
⚠ Learning shortcut — not for production
The gate checks identity policies only and treats every file the same. A production gate also validates resource policies (RESOURCE_POLICY with the matching ValidatePolicyResourceType), SCPs and RCPs, runs CheckNoNewAccess against the deployed version so reviewers see exactly what is being added, and runs CheckNoPublicAccess on bucket and key policies. Many teams run the same checks on synthesised CloudFormation templates with the open-source IAM Policy Validator for CloudFormation and Terraform. Keep the forbidden list in a separate, security-owned repository so a workload team cannot edit it in the same pull request.
Security considerations
- Archive findings with a reason, never just dismiss them. Archive rules are themselves evidence: "we accept that the management account can assume this role, because…".
- Look at the trend, not only the backlog. A rising count of unused-access findings means roles are being created faster than they are reviewed.
- Least privilege includes time. Short session durations and just-in-time elevation (see IAM Identity Center, MFA and temporary credentials) reduce exposure as much as narrow actions do.
- Do not trust generated policies blindly. They reflect what happened, including mistakes and misuse during the window. Review them and add resource ARNs and conditions.
- Protect the tags that ABAC depends on with deny statements and SCPs.
- Use guardrails as a backstop. Even with perfect workload policies, SCPs deny the catastrophic actions organisation-wide (see Permission boundaries, SCPs, RCPs and resource policies).
Banking use case
Harbourline's quarterly access review for the Payments account used to be a spreadsheet exercise. Now:
- The unused access analyzer (organisation-wide, run from the security tooling account) lists roles unused for 90 days and services unused within active roles. Findings flow into Security Hub.
- Each team receives a generated report and must either remove the unused permission through a pull request or record why it is needed (for example, a disaster-recovery role exercised only during the annual test).
- The pull request passes through the policy gate.
CheckNoNewAccessproves the change only removes access. - The review record, the findings export and the merged pull requests form the evidence pack for internal audit.
Whether this process satisfies a particular regulatory access-review requirement is for Harbourline's compliance team and auditors to confirm.
Common mistakes
- Starting broad "and tightening later" → later never comes → start narrow; let developers request additions with justification.
- Using
aws:SourceIpfor requests that come through a VPC endpoint → requests through an endpoint carry a private address, not your public IP → useaws:SourceVpceoraws:SourceVpcfor private traffic. - Forgetting
IfExistson organisation conditions → AWS service principals do not haveaws:PrincipalOrgID, so the deny blocks CloudTrail or Config from writing → combine withaws:PrincipalIsAWSServiceas in the bucket policy above. - Generating a policy over a window that missed the month-end batch → production breaks on the first of the month → choose a window that covers a full business cycle, or add known periodic actions by hand.
- Leaving the unused access analyzer running in a sandbox → small but recurring charge → delete it after the lab.
- Treating Access Analyzer's external findings as covering identity policies → it analyses resource policies; over-broad identity policies show up in unused-access findings and policy checks instead.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| No findings in the analyzer after creating a shared bucket | Wrong Region, or the analysis has not run yet | Analyzers are Regional; wait up to about 30 minutes or use Rescan |
| Policy generation fails with an access error to the trail bucket | Service role lacks s3:GetObject/kms:Decrypt, or logs are in another account | Fix the service role; for cross-account trails update the bucket and key policy as documented |
Generated policy has only service-level entries (s3:* placeholders) | Action-level data not available for that service | Choose actions by hand from the Service Authorization Reference |
ValidatePolicy returns ERROR MISSING_VERSION | No Version element | Add "Version": "2012-10-17" |
CheckAccessNotGranted returns FAIL for a policy that "doesn't mention" the action | A wildcard (kms:*, *:*) or NotAction covers it | Replace the wildcard with explicit actions |
| Unused access finding for a role you know is used | The role is used only through a service that does not report last accessed data, or less often than the threshold | Increase the threshold, or archive with a reason |
Cost and cleanup
| Item | Cost |
|---|---|
| External access analyzer, policy validation, policy generation | No additional charge |
| Custom policy checks | USD 0.002 per call — the gate above costs well under one cent per run |
| Unused access analyzer | USD 0.20 per role/user analysed per month (optional step) |
| Internal access analyzer | Charged per monitored resource per Region per month — not used in this lab |
| CloudTrail first management-events trail | Free; S3 storage for the logs is a few cents |
Free alternative for the optional steps: use Access Advisor (last accessed data) and --skip-paid-checks.
# Delete analyzers created in this lesson.
aws accessanalyzer delete-analyzer --analyzer-name hl-m05-unused --profile learn-sandbox --region us-east-1
aws accessanalyzer delete-analyzer --analyzer-name hl-m05-external --profile learn-sandbox --region us-east-1
# Remove the test bucket (and its policy) from the guided steps.
aws s3 rb s3://hl-m05-share-test-alex --force --profile learn-sandbox
# Confirm nothing tagged for this lab remains.
aws resourcegroupstaggingapi get-resources --tag-filters Key=Lab,Values=m05-least-privilege \
--region us-east-1 --profile learn-sandbox --query "ResourceTagMappingList[].ResourceARN"Many organisations keep the free external access analyzer running permanently in every Region — that is a sensible production choice, not a leftover.
Exercises
- 🟢 Guided: Create the external analyzer, produce a cross-account finding with a test bucket policy, archive it with a rule, then remove the policy and confirm the finding is resolved.
- 🟡 Challenge: Extend the policy gate to call
CheckNoNewAccess: compare each file inpolicies/with the version on themainbranch (git show main:policies/<file>) and print the statements that add access. - 🔴 Live problem: The data platform team's Glue job role has
AmazonS3FullAccessandAWSGlueServiceRole. They are about to process card-transaction extracts. You have one week, no downtime allowed, and the team says "we don't know which buckets the job touches". Plan the reduction.
Assignment
Add labs/m05-secure-banking-api/policies/-style samples to your own repository: three good and three bad identity policies for Harbourline workloads, the policy gate, and a GitHub Actions job that runs it with --skip-paid-checks on pull requests and the full gate on main. Document the forbidden-actions list and who owns it.
Solutions
aws s3api create-bucket --bucket hl-m05-share-test-alex --profile learn-sandbox --region us-east-1
cat > share.json <<'EOF'
{"Version":"2012-10-17","Statement":[{"Sid":"TestShare","Effect":"Allow",
"Principal":{"AWS":"arn:aws:iam::999988887777:root"},"Action":"s3:GetObject",
"Resource":"arn:aws:s3:::hl-m05-share-test-alex/*"}]}
EOF
aws s3api put-bucket-policy --bucket hl-m05-share-test-alex --policy file://share.json --profile learn-sandbox
# Wait a few minutes, then:
aws accessanalyzer list-findings-v2 --analyzer-arn "$ANALYZER_ARN" --profile learn-sandbox --region us-east-1 \
--query "findings[?resource=='arn:aws:s3:::hl-m05-share-test-alex']"
aws s3api delete-bucket-policy --bucket hl-m05-share-test-alex --profile learn-sandbox
aws accessanalyzer start-resource-scan --analyzer-arn "$ANALYZER_ARN" \
--resource-arn arn:aws:s3:::hl-m05-share-test-alex --profile learn-sandbox --region us-east-1Why: Block Public Access does not stop cross-account grants to a named account — it blocks public access. Access Analyzer catches both. The rescan shows that remediation is verified, not assumed.
var existing = await RunGitAsync($"show main:{Path.GetRelativePath(repoRoot, file).Replace('\\', '/')}");
if (existing is not null)
{
var noNew = await analyzer.CheckNoNewAccessAsync(new CheckNoNewAccessRequest
{
ExistingPolicyDocument = existing,
NewPolicyDocument = document,
PolicyType = AccessCheckPolicyType.IDENTITY_POLICY
});
if (noNew.Result == CheckNoNewAccessResult.FAIL)
foreach (var r in noNew.Reasons ?? [])
Console.WriteLine($" NEW ACCESS in statement {r.StatementIndex}: {r.Description}");
}
static async Task<string?> RunGitAsync(string arguments)
{
var psi = new System.Diagnostics.ProcessStartInfo("git", arguments) { RedirectStandardOutput = true, RedirectStandardError = true };
using var p = System.Diagnostics.Process.Start(psi)!;
var output = await p.StandardOutput.ReadToEndAsync();
await p.WaitForExitAsync();
return p.ExitCode == 0 ? output : null; // new file: nothing to compare
}Why: "New access" is the most useful signal for a reviewer. A pull request that only removes permissions can be approved quickly; one that adds access deserves a closer look and a justification. Set repoRoot to the repository root (for example from git rev-parse --show-toplevel).
- Day 1: confirm a CloudTrail trail exists and enable S3 data events for the candidate buckets (management events alone will not show which objects are read). Pull Access Advisor action-level data for the role.
- Days 1–5: let the job run its normal schedule. Meanwhile add a permissions boundary or an explicit deny for clearly out-of-scope actions (
s3:PutBucketPolicy,s3:DeleteBucket, access to other teams' buckets byaws:ResourceTag/team) — this reduces risk immediately without guessing what is needed. - Day 5: generate a policy from CloudTrail; add
s3:GetObject/PutObjecton the specific prefixes seen in data events,kms:Decrypt/GenerateDataKeyon the specific keys, andiam:PassRoleonly if needed (not visible in generated policies). - Day 6: deploy the new customer managed policy alongside the old one in a non-production run, then remove
AmazonS3FullAccessand verify a full run. - Day 7: remove the old policy in production during a normal run window with a rollback plan, and set an unused-access finding threshold for the role.
Why: you reduce risk early (guardrails), gather evidence before narrowing, and change production only when you have proof the new policy works for a full cycle. Card data adds PCI DSS scope questions: involve the compliance team about where these extracts may live at all (PCI DSS on AWS).
Knowledge check
Answer: External access analysis, policy validation and policy generation. Unused access analysis is charged per role or user analysed per month, internal access analysis per monitored resource, and custom policy checks per API call.
Answer: It only reflects the chosen time window (up to 90 days), it does not give action-level detail for data events such as S3 object reads, and it never includes iam:PassRole. Periodic jobs that did not run in the window are also missing.
Answer: Requests from AWS service principals do not carry aws:PrincipalOrgID, so the deny matches them. Add BoolIfExists aws:PrincipalIsAWSService false (or use aws:SourceOrgID/aws:SourceAccount for service principals) so service deliveries are not blocked.
Answer: A principal could add its own team tag to a resource and gain access. Deny changes to access-control tag keys (aws:TagKeys) except for a controlled automation role, and protect them with SCPs.
Answer: A resource in a Region without an analyzer is not analysed. Create analyzers in every Region you use (organisation-level automation usually does this) and deny unused Regions with an SCP so nothing hides there.
Interview questions
- "How do you implement least privilege across 100 roles you inherited?" — Guardrails first (SCPs, boundaries) to stop the worst; gather evidence (CloudTrail including data events, last accessed data, unused-access findings); generate and review policies; deploy through a gated pipeline; repeat on a schedule; measure the backlog.
- "What is the difference between
aws:SourceIpandaws:SourceVpce?" —SourceIpis the public IP of internet-routed requests; requests through a VPC endpoint carry private addresses, so you restrict those withSourceVpceorSourceVpc. - "How would you stop a developer's pull request from granting
iam:PassRoleon*?" — Policy validation flags it as a security warning;CheckAccessNotGrantedblocks forbidden actions; reviewers seeCheckNoNewAccessoutput; an SCP or boundary is the runtime backstop. - "What is ABAC and when would you not use it?" — Permissions based on matching tags on principals and resources. Avoid it when tag governance is weak or when auditors need a simple list of "who can access X" — RBAC is easier to explain.
Certification practice
A financial company has a Lambda role with AmazonDynamoDBFullAccess. The security team must reduce it to the permissions actually used, with minimal risk of breaking the function. A CloudTrail trail has been logging management events for six months. What should they do?
A. Replace the policy with AmazonDynamoDBReadOnlyAccess and monitor for errors.
B. Use IAM Access Analyzer to generate a policy from the role's CloudTrail activity over the last 90 days, review it, add resource ARNs, and deploy it after testing.
C. Enable an external access analyzer and remove any permission it reports.
D. Use the IAM policy simulator to test every DynamoDB action.
Answer: B. Policy generation is built for exactly this, from real activity. A guesses and will break any write path. C reports resources shared outside the zone of trust, not unused identity permissions. D tests what a policy allows, not what the function needs.
A bank wants every IAM policy change in its CI/CD pipeline to be blocked automatically if the policy would allow kms:ScheduleKeyDeletion or cloudtrail:StopLogging, including through wildcards. Which solution is MOST effective?
A. A regular-expression check for those action names in the pipeline.
B. IAM Access Analyzer CheckAccessNotGranted with the two actions, failing the build on a FAIL result.
C. An AWS Config rule that detects the policies after deployment.
D. IAM Access Analyzer policy validation, failing on SUGGESTION findings.
Answer: B. CheckAccessNotGranted reasons over wildcards and NotAction, so kms:* is caught. A regex misses wildcards (A). Config is detective and acts after deployment (C). Policy validation checks grammar and best practices, not your specific forbidden actions (D).
An application in private subnets reads objects from an S3 bucket through a gateway VPC endpoint. The company requires that objects can be read only through that endpoint. What should the bucket policy contain?
A. A Deny for s3:GetObject when aws:SourceIp is not the VPC CIDR.
B. A Deny for s3:GetObject when aws:SourceVpce is not the endpoint ID.
C. An Allow for s3:GetObject with aws:SourceVpc equal to the VPC ID and no Deny.
D. An Allow for the endpoint's ARN as Principal.
Answer: B. Requests through a gateway endpoint are identified by aws:SourceVpce. aws:SourceIp does not carry private addresses for endpoint traffic (A). An Allow alone does not stop other paths that are allowed elsewhere (C). An endpoint is not a principal (D).
Completion checklist
- I can describe the six-step least-privilege lifecycle and who owns each step
- I created an external access analyzer, produced a finding, archived and resolved it
- I read last accessed information for a role
- I ran the policy gate against a good and a bad policy
- I deleted any unused access analyzer and test bucket
Key takeaways
- Least privilege is a loop — design, generate, validate, deploy, monitor, trim — not a project.
- Resource policies fence (
aws:PrincipalOrgID,aws:SourceVpce,aws:SecureTransport); identity policies grant specific actions on specific ARNs. - IAM Access Analyzer gives you external, internal and unused access findings, free validation, paid custom checks and free policy generation — know which costs money.
- Generated policies reflect history, not need; review them and add
iam:PassRoleand data-event actions by hand. - Automate the gate in the pipeline so least privilege does not depend on reviewers spotting wildcards.
Further reading
Independent learning resource — not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.
Policy evaluation logic
Predict exactly how AWS decides allow or deny when identity policies, resource policies, permissions boundaries, SCPs, RCPs and session policies all apply, and debug an AccessDenied from the error message, CloudTrail and the IAM policy simulator.
IAM Identity Center, MFA and temporary credentials
Give people short-lived, MFA-protected access through IAM Identity Center permission sets, and make applications assume roles safely with STS — external IDs, source identity, session tags and the one-hour role-chaining limit — from the CLI and from C#.