IAM in depth: identities, roles and every policy type
Explain IAM users, groups, roles and the root user, read and write policy JSON with confidence, and recognise all nine policy types a request can meet — then audit an account for risky IAM users from C#.
Assumes: .NET 10 LTS · AWS SDK for .NET v4 (AWSSDK.IdentityManagement 4.1.1.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:
- Explain the difference between the root user, IAM users, IAM groups and IAM roles, and say which one a person, an application and an AWS service should use.
- Read any IAM policy document and name each element:
Version,Statement,Sid,Effect,Principal,Action/NotAction,Resource/NotResourceandCondition. - Build and decode ARNs (Amazon Resource Names) for users, roles, assumed-role sessions, buckets and keys.
- List the nine policy types AWS can evaluate — identity-based, resource-based, VPC endpoint, permissions boundary, SCP, RCP, ACL, AWS RAM share and session policy — and say which ones grant access and which ones only limit it.
- Explain why banks give people no IAM users at all, and run a C# audit that finds IAM users, old access keys and missing MFA in an account.
Prerequisites
- Secure your AWS account — you have a sandbox account and the
learn-sandboxSSO profile - Module 1: AWS fundamentals — accounts, Regions, the shared responsibility model
- Tools: AWS CLI v2, .NET 10 SDK, a text editor that formats JSON
Why this matters in banking
Harbourline Bank's internal audit runs a quarterly "joiners, movers, leavers" review. In the on-premises world that meant checking Active Directory groups and SQL Server logins. In AWS the auditor asks three new questions:
- Who can act in this account? Not only people, but Lambda functions, ECS tasks, CI pipelines and third-party tools.
- What exactly can each of them do, and where is that written down?
- Can anyone get more access than they were given?
If the platform team cannot answer from the IAM configuration and CloudTrail, the finding goes to the risk committee. Real incidents at financial firms have followed exactly this pattern: an engineer's long-lived access key leaked from a laptop or a public repository, the key belonged to an IAM user with broad rights, and nobody noticed for weeks. IAM is the control plane for everything else in this module — encryption keys, logs and network rules are all protected by IAM policies — so getting the basics exactly right is not optional.
Security of the cloud vs in the cloud: AWS runs the IAM service itself, keeps it available and evaluates every request correctly. Harbourline is responsible for what it configures: which identities exist, which policies they hold, whether MFA is on and whether old credentials are removed. No AWS certification covers your IAM design.
The idea in plain language
Every request to AWS — a console click, a CLI command, an SDK call from your .NET API — is an HTTP request signed with credentials. AWS asks two questions:
- Authentication — who are you? The signature proves which principal (identity) sent the request.
- Authorisation — are you allowed? AWS collects every policy that applies to this principal, this action and this resource, and evaluates them. The default answer is deny. Only an explicit Allow that is not overruled by any Deny or any limiting policy lets the request through.
There are four kinds of principal you deal with daily:
| Principal | What it is | Credentials | Banking use |
|---|---|---|---|
| Root user | The identity created with the account (an email address) | Password + MFA; access keys should never exist | Break-glass only: a handful of tasks such as closing the account |
| IAM user | A named identity that lives inside one account | Long-lived password and/or long-lived access keys | Almost none. Legacy integrations that cannot use roles, under exception |
| IAM group | A collection of IAM users | None — a group cannot sign in | Attaches policies to users. Not a principal in its own right |
| IAM role | An identity with permissions but no permanent credentials; anyone it trusts can assume it | Temporary credentials from AWS STS (15 minutes to 12 hours) | People (via IAM Identity Center), applications (Lambda, ECS, EC2) and cross-account access |
Analogy: IAM is the bank's keycard system. The root user is the master key sealed in the safe. An IAM user is a permanent keycard with a name on it — if it is lost, it keeps working until somebody notices. A role is a visitor badge issued at reception: you prove who you are, you get a badge that opens specific doors, and it stops working at the end of the shift. Policies are the access rules programmed into each door and each badge.
What problem IAM solves
IAM (AWS Identity and Access Management) is the global, free service that stores identities and policies for an AWS account and evaluates them on every API call. It exists so that one account can be shared safely by many people and systems with different needs.
Honest limitations and sharp edges:
- IAM is per account. A bank with 200 accounts has 200 separate sets of roles and policies. AWS Organizations, IAM Identity Center and infrastructure as code are how you keep them consistent (later lessons).
- Policies are size-limited. A customer managed policy can hold 6,144 characters (white space not counted); all inline policies on one role together 10,240; on a user 2,048. A role can have 20 managed policies attached by default (quota increase to 25). These limits push you towards well-structured policies rather than giant lists.
- Eventual consistency. IAM changes replicate globally and can take a few seconds to apply. Automation that creates a role and uses it immediately sometimes fails on the first try.
- The default role trust policy length is 2,048 characters (adjustable to 8,192). Long lists of trusted principals hit this quickly.
- Errors are terse.
AccessDeniedoften does not say which policy denied you. The next lesson teaches you how to work it out.
Microsoft / Azure comparison
| You know (Microsoft/Azure) | AWS equivalent | What's different |
|---|---|---|
| Entra ID tenant (one directory for many subscriptions) | IAM in each account + IAM Identity Center for people | IAM is per account; Identity Center is the organisation-wide directory for humans |
| Entra ID user | IAM Identity Center user (preferred) or IAM user (avoid) | An IAM user is closer to a local SQL Server login than to an Entra ID user |
| Security group | IAM group | IAM groups only hold users; they cannot be nested and cannot be named in a resource policy |
| Managed identity (system or user assigned) | IAM role assumed by Lambda, ECS, EC2 | Same idea — no secret in code. The role has a trust policy saying which service may use it |
| Azure RBAC role definition | IAM managed policy | AWS policies list API actions (s3:GetObject), not portal operations |
| RBAC role assignment at a scope | Attaching a policy to a role, or a resource policy naming a principal | Scope is expressed by the Resource ARN and Condition, not by the assignment location |
| Deny assignments / Azure Policy deny | Explicit Deny statements, SCPs, RCPs, permissions boundaries | An explicit deny anywhere always wins |
| Global Administrator break-glass | Root user | One root user per account; in an organisation you can remove member-account root credentials centrally |
Resource ID (/subscriptions/.../resourceGroups/...) | ARN (arn:aws:s3:::bucket/key) | ARNs follow one pattern across all services |
Architecture
How a request flows through authentication and authorisation:
Where each policy type attaches:
Security-boundary view: the AWS account is the hard boundary. Inside it, IAM decides everything. Across accounts, access needs both sides to agree: the caller's account must allow the call in its identity policy, and the resource owner must allow it in a resource policy (or a role trust policy). Organisation policies (SCPs and RCPs) sit above both and can only take permissions away.
The policy language
A policy is a JSON document. Here is a realistic identity-based policy for the Accounts API's Lambda role:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ReadAccountsTable",
"Effect": "Allow",
"Action": ["dynamodb:GetItem", "dynamodb:Query"],
"Resource": [
"arn:aws:dynamodb:us-east-1:111122223333:table/hl-m05-accounts",
"arn:aws:dynamodb:us-east-1:111122223333:table/hl-m05-accounts/index/*"
]
},
{
"Sid": "DecryptWithAccountsKeyViaDynamoDbOnly",
"Effect": "Allow",
"Action": "kms:Decrypt",
"Resource": "arn:aws:kms:us-east-1:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab",
"Condition": {
"StringEquals": { "kms:ViaService": "dynamodb.us-east-1.amazonaws.com" }
}
}
]
}Element by element:
| Element | Required? | Meaning |
|---|---|---|
Version | Always use 2012-10-17 | The policy language version. The older 2008-10-17 does not support policy variables such as ${aws:username} |
Statement | Yes | One statement object or an array. Statements are OR-ed together |
Sid | Optional | A label. Use it — auditors and your future self read policies by Sid |
Effect | Yes | Allow or Deny |
Principal | Only in resource-based policies (and trust policies) | Who the statement applies to. Identity policies have no Principal: the principal is whoever the policy is attached to |
Action / NotAction | One of them | API operations in the form service:Operation. Wildcards * and ? allowed. NotAction means "every action except these" — dangerous with Allow |
Resource / NotResource | Required in identity policies | ARNs the statement covers. Some actions (for example s3:ListAllMyBuckets) only work with "*" |
Condition | Optional | Extra tests on the request context: { "Operator": { "key": "value" } }. All conditions in a statement must be true (AND) |
Two rules trip up newcomers:
- Multiple values inside one condition key are OR-ed; multiple keys and operators are AND-ed.
- A condition key that is missing from the request context makes most operators evaluate to false — unless you use the
...IfExistsvariant or theNulloperator. That is why"Bool": {"aws:MultiFactorAuthPresent": "false"}in a Deny does not catch requests made with long-lived access keys (the key is absent); you needBoolIfExists.
ARNs
An ARN uniquely names any AWS resource:
arn:partition:service:region:account-id:resource-type/resource-id| Example | Notes |
|---|---|
arn:aws:iam::111122223333:role/hl-m05-accounts-api | IAM is global, so the Region field is empty |
arn:aws:iam::111122223333:user/legacy-batch | An IAM user |
arn:aws:sts::111122223333:assumed-role/hl-m05-accounts-api/session-42 | A role session — what CloudTrail records when the role is used |
arn:aws:iam::111122223333:root | As a Principal this means "the account" (delegating to its IAM policies), not only the root user |
arn:aws:s3:::hl-m05-statements | S3 bucket ARNs have no Region or account |
arn:aws:s3:::hl-m05-statements/2026/11/* | Objects under a prefix |
arn:aws:kms:us-east-1:111122223333:key/1234abcd-... | A KMS key |
The partition is aws for commercial Regions; it differs for other partitions such as AWS GovCloud (US) and the China Regions (aws-us-gov, aws-cn) — hard-coding arn:aws: in shared libraries is a common portability bug.
The nine policy types
AWS documents nine policy types. Learn which ones grant and which ones only cap:
| # | Policy type | Attached to | Grants? | Typical banking use |
|---|---|---|---|---|
| 1 | Identity-based (AWS managed, customer managed, inline) | User, group, role | ✅ Grants | What the Accounts API role may do |
| 2 | Resource-based (bucket policy, key policy, queue policy, role trust policy…) | Resource | ✅ Grants (incl. cross-account) | Allow the log-archive account's bucket to receive CloudTrail logs |
| 3 | VPC endpoint policy | VPC interface/gateway endpoint | ❌ Caps traffic through the endpoint | Only Harbourline's buckets reachable through the S3 endpoint |
| 4 | Permissions boundary | User or role (a managed policy) | ❌ Caps identity policies | Developers can create roles but never more powerful than the boundary |
| 5 | SCP (service control policy) | Organization root, OU or account | ❌ Caps principals in member accounts (including member root users) | Deny leaving approved Regions; deny disabling CloudTrail |
| 6 | RCP (resource control policy) | Organization root, OU or account | ❌ Caps access to resources in member accounts, whoever the caller is | Deny any principal outside the organisation from reading S3 objects |
| 7 | ACL (access control list) | Some resources (S3 legacy, WAF, VPC) | ✅ Grants cross-account only; not JSON | Disable S3 ACLs (Object Ownership: bucket owner enforced) |
| 8 | AWS RAM resource share | Shared resource | ✅ Grants to other accounts in a managed way | Share Transit Gateway or subnets with workload accounts |
| 9 | Session policy | Passed in an AssumeRole* or GetFederationToken call | ❌ Caps the session | A broker hands a batch job a session limited to one prefix |
How these combine — explicit deny first, SCP and RCP caps, resource policies, boundaries and session policies — is the subject of the next lesson, Policy evaluation logic.
Managed vs inline policies
- AWS managed policies (for example
ReadOnlyAccess) are written and updated by AWS. Convenient, but broad, and AWS can add new actions to them at any time — a bank's change-control process will not see that change. - Customer managed policies are yours, versioned (up to five versions kept), reusable and reviewable. The default for Harbourline.
- Inline policies live inside one identity and are deleted with it. Use them for a strict one-to-one relationship, such as a permission that must never be reused.
Roles: two policies, not one
A role always has:
- A trust policy (a resource-based policy on the role) that says who may assume it — for example
lambda.amazonaws.com, or a specific role in the CI account. - One or more permissions policies that say what the session may do.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": { "Service": "lambda.amazonaws.com" },
"Action": "sts:AssumeRole",
"Condition": {
"StringEquals": { "aws:SourceAccount": "111122223333" }
}
}
]
}The aws:SourceAccount condition is a cheap defence against the confused deputy problem, covered in IAM Identity Center, MFA and temporary credentials.
Why banks avoid IAM users for people
An IAM user's password and access keys are long-lived. They do not expire unless you rotate them, they work from any laptop on the internet unless you add conditions, and they are tied to one account, so a person working in 30 accounts would need 30 users. Joiners/movers/leavers processes in the corporate directory (Active Directory or Entra ID) do not reach them automatically.
Harbourline's standard (and the AWS-recommended practice) is:
- People: IAM Identity Center federated with the corporate directory, MFA enforced, short sessions via permission sets.
- Workloads on AWS: roles for Lambda, ECS tasks and EC2 instance profiles.
- Workloads outside AWS: OIDC federation (for example GitHub Actions) or IAM Roles Anywhere with X.509 certificates.
- IAM users: only by documented exception (for example a vendor appliance that only supports access keys), with key rotation, IP or VPC conditions, and a named owner.
The root user
The root user cannot be limited by identity policies or permissions boundaries in its own account, although SCPs and RCPs do apply to the root user of a member account. AWS now requires MFA for root users of all account types (standalone, management and member accounts); a root user without MFA must register it within 35 days of the first console sign-in attempt. In an organisation you can go further with centralised root access: remove member-account root passwords and access keys entirely, and perform the few root-only tasks from the management account. See Secure your AWS account.
Step-by-step implementation
You will audit your sandbox account for risky IAM users, then create a properly structured role with a customer managed policy.
Sign in with temporary credentials
aws sso login --profile learn-sandbox
aws sts get-caller-identity --profile learn-sandboxThe ARN should look like arn:aws:sts::111122223333:assumed-role/AWSReservedSSO_SandboxAdmin_.../alex.learner — an assumed-role session, not an IAM user. That is what "no IAM users for people" looks like in practice.
Get the account-level IAM summary
Run aws iam get-account-summary (below). Look at AccountMFAEnabled (should be 1), AccountAccessKeysPresent (should be 0 — the root user has no keys) and Users.
Run the C# IAM hygiene report
Create the console project from the Complete code section and run it. It lists every IAM user with their keys, key age, last use and MFA status, and every role whose trust policy names a principal outside the account.
Create a role the right way
Deploy the CDK stack (or Terraform) from Infrastructure as Code. It creates hl-m05-accounts-api with a trust policy for Lambda, one customer managed policy and the mandatory tags.
Read your work back
In the console, open the role and compare the Trust relationships tab with the Permissions tab. Then open Access Advisor — it will be empty because nothing has used the role yet. You will use Access Advisor in Least privilege in practice.
AWS Console instructions
- Console → IAM → Dashboard shows security recommendations: root MFA, root access keys, IAM users without MFA.
- Console → IAM → Users lists IAM users. In a well-run account this list is empty or contains only documented exceptions. Select a user → Security credentials to see access keys and their Last used column.
- Console → IAM → Roles → Create role → Trusted entity type: AWS service → Use case: Lambda → attach your customer managed policy → name
hl-m05-accounts-api→ add the four tags. - Console → IAM → Policies → Create policy → JSON — paste a policy. The policy editor runs IAM Access Analyzer policy validation as you type and shows errors, security warnings and suggestions underneath.
- Console → IAM → Credential report → Download credentials report produces a CSV of every user and their credential status (the root user is included as
<root_account>).
AWS CLI
# Who am I? Always the first command when debugging access.
aws sts get-caller-identity --profile learn-sandbox
# Account-wide counters: users, roles, MFA on root, root access keys present.
aws iam get-account-summary --profile learn-sandbox \
--query "SummaryMap.{Users:Users,Roles:Roles,RootMfa:AccountMFAEnabled,RootKeys:AccountAccessKeysPresent}"
# List IAM users (expect none, or only documented exceptions).
aws iam list-users --profile learn-sandbox --query "Users[].{Name:UserName,Created:CreateDate}"
# Generate and download the credential report (CSV, base64-encoded in the response).
aws iam generate-credential-report --profile learn-sandbox
aws iam get-credential-report --profile learn-sandbox --query Content --output text | base64 --decode > credential-report.csv
# Create the customer managed policy from the JSON file shown earlier.
aws iam create-policy --profile learn-sandbox \
--policy-name hl-m05-accounts-api-read \
--policy-document file://hl-m05-accounts-api-read.json \
--tags Key=Project,Value=cea-lab Key=Lab,Value=m05-iam Key=Environment,Value=learn Key=Owner,Value=alex
# Create the role with the Lambda trust policy, then attach the policy.
aws iam create-role --profile learn-sandbox \
--role-name hl-m05-accounts-api \
--assume-role-policy-document file://trust-policy-lambda.json \
--max-session-duration 3600 \
--tags Key=Project,Value=cea-lab Key=Lab,Value=m05-iam Key=Environment,Value=learn Key=Owner,Value=alex
aws iam attach-role-policy --profile learn-sandbox \
--role-name hl-m05-accounts-api \
--policy-arn arn:aws:iam::111122223333:policy/hl-m05-accounts-api-read
# Show what is attached, inline and trusted.
aws iam list-attached-role-policies --role-name hl-m05-accounts-api --profile learn-sandbox
aws iam get-role --role-name hl-m05-accounts-api --profile learn-sandbox --query "Role.AssumeRolePolicyDocument"Replace 111122223333 with your sandbox account ID and alex with your name. On Windows PowerShell, base64 --decode is not available — use Git Bash, or [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($content)).
Infrastructure as Code
using Amazon.CDK;
using Amazon.CDK.AWS.IAM;
using Constructs;
namespace Harbourline.Security.Infra;
public sealed class IamBasicsStack : Stack
{
public IamBasicsStack(Construct scope, string id, IStackProps? props = null) : base(scope, id, props)
{
// Customer managed policy: one purpose, named statements, exact ARNs.
var readPolicy = new ManagedPolicy(this, "AccountsApiRead", new ManagedPolicyProps
{
ManagedPolicyName = "hl-m05-accounts-api-read",
Statements =
[
new PolicyStatement(new PolicyStatementProps
{
Sid = "ReadAccountsTable",
Effect = Effect.ALLOW,
Actions = ["dynamodb:GetItem", "dynamodb:Query"],
Resources =
[
$"arn:aws:dynamodb:{Region}:{Account}:table/hl-m05-accounts",
$"arn:aws:dynamodb:{Region}:{Account}:table/hl-m05-accounts/index/*"
]
})
]
});
// Role with a service trust policy restricted to this account (confused-deputy defence).
var role = new Role(this, "AccountsApiRole", new RoleProps
{
RoleName = "hl-m05-accounts-api",
AssumedBy = new ServicePrincipal("lambda.amazonaws.com", new ServicePrincipalOpts
{
Conditions = new Dictionary<string, object>
{
["StringEquals"] = new Dictionary<string, object> { ["aws:SourceAccount"] = Account }
}
}),
MaxSessionDuration = Duration.Hours(1),
ManagedPolicies = [readPolicy]
});
// Mandatory tags on every resource in this stack.
Amazon.CDK.Tags.Of(this).Add("Project", "cea-lab");
Amazon.CDK.Tags.Of(this).Add("Lab", "m05-iam");
Amazon.CDK.Tags.Of(this).Add("Environment", "learn");
Amazon.CDK.Tags.Of(this).Add("Owner", "alex");
_ = new CfnOutput(this, "RoleArn", new CfnOutputProps { Value = role.RoleArn });
}
}Complete code
A console app that produces an IAM hygiene report — the kind of evidence an internal auditor asks for. It only reads IAM, so a read-only permission set is enough.
<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.IamAudit</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AWSSDK.IdentityManagement" Version="4.1.1.2" />
<!-- Needed at runtime so IAM Identity Center (SSO) profiles resolve. -->
<PackageReference Include="AWSSDK.SSO" Version="4.1.0.2" />
<PackageReference Include="AWSSDK.SSOOIDC" Version="4.1.0.2" />
</ItemGroup>
</Project>using System.Text.Json;
using Amazon;
using Amazon.IdentityManagement;
using Amazon.IdentityManagement.Model;
using Amazon.Runtime.CredentialManagement;
const int MaxKeyAgeDays = 90;
var profileName = Environment.GetEnvironmentVariable("AWS_PROFILE") ?? "learn-sandbox";
var profiles = new CredentialProfileStoreChain();
if (!profiles.TryGetAWSCredentials(profileName, out var credentials))
{
Console.Error.WriteLine($"Profile '{profileName}' not found. Run: aws sso login --profile {profileName}");
return 2;
}
using var iam = new AmazonIdentityManagementServiceClient(credentials, RegionEndpoint.USEast1);
var findings = new List<string>();
// 1. Account-level checks for the root user.
var summary = await iam.GetAccountSummaryAsync(new GetAccountSummaryRequest());
var map = summary.SummaryMap ?? new Dictionary<string, int>();
if (map.GetValueOrDefault("AccountMFAEnabled") != 1) findings.Add("ROOT: MFA is not enabled on the root user.");
if (map.GetValueOrDefault("AccountAccessKeysPresent") != 0) findings.Add("ROOT: the root user has access keys. Delete them.");
// 2. Every IAM user: keys, key age, last use, MFA.
await foreach (var user in iam.Paginators.ListUsers(new ListUsersRequest()).Users)
{
findings.Add($"USER: '{user.UserName}' exists. People should use IAM Identity Center; document this exception.");
var mfa = await iam.ListMFADevicesAsync(new ListMFADevicesRequest { UserName = user.UserName });
if ((mfa.MFADevices ?? []).Count == 0)
findings.Add($"USER: '{user.UserName}' has no MFA device.");
var keys = await iam.ListAccessKeysAsync(new ListAccessKeysRequest { UserName = user.UserName });
foreach (var key in keys.AccessKeyMetadata ?? [])
{
var ageDays = (int)(DateTime.UtcNow - (key.CreateDate ?? DateTime.UtcNow)).TotalDays;
var used = await iam.GetAccessKeyLastUsedAsync(new GetAccessKeyLastUsedRequest { AccessKeyId = key.AccessKeyId });
var lastUsed = used.AccessKeyLastUsed?.LastUsedDate;
var masked = key.AccessKeyId is { Length: > 8 } id ? $"{id[..4]}...{id[^4..]}" : "(unknown)";
if (ageDays > MaxKeyAgeDays)
findings.Add($"KEY: {masked} for '{user.UserName}' is {ageDays} days old (limit {MaxKeyAgeDays}).");
if (lastUsed is null)
findings.Add($"KEY: {masked} for '{user.UserName}' has never been used. Delete it.");
else if ((DateTime.UtcNow - lastUsed.Value).TotalDays > MaxKeyAgeDays)
findings.Add($"KEY: {masked} for '{user.UserName}' unused since {lastUsed:yyyy-MM-dd}.");
}
}
// 3. Roles whose trust policy names a principal outside this account.
var accountId = await GetAccountIdAsync();
await foreach (var role in iam.Paginators.ListRoles(new ListRolesRequest()).Roles)
{
if (role.Path?.StartsWith("/aws-service-role/") == true) continue; // service-linked roles are managed by AWS
var trustJson = Uri.UnescapeDataString(role.AssumeRolePolicyDocument ?? "{}");
foreach (var principal in ExtractAwsPrincipals(trustJson))
{
if (principal == "*")
findings.Add($"ROLE: '{role.RoleName}' trusts ANY AWS principal (\"*\"). Check its conditions urgently.");
else if (!principal.Contains($":{accountId}:") && principal != accountId)
findings.Add($"ROLE: '{role.RoleName}' trusts external principal {principal}. Confirm it is approved.");
}
}
Console.WriteLine($"IAM hygiene report for account {accountId} — {DateTime.UtcNow:u}");
Console.WriteLine(findings.Count == 0 ? "No findings." : string.Join(Environment.NewLine, findings.Select(f => " - " + f)));
return findings.Count == 0 ? 0 : 1;
async Task<string> GetAccountIdAsync()
{
// The account ID is the 5th field of any ARN in this account; ListRoles always returns at least the SSO roles.
var page = await iam.ListRolesAsync(new ListRolesRequest { MaxItems = 1 });
return page.Roles?.FirstOrDefault()?.Arn.Split(':')[4] ?? "unknown";
}
static IEnumerable<string> ExtractAwsPrincipals(string trustPolicyJson)
{
using var doc = JsonDocument.Parse(trustPolicyJson);
if (!doc.RootElement.TryGetProperty("Statement", out var statements)) yield break;
var list = statements.ValueKind == JsonValueKind.Array ? statements.EnumerateArray().ToList() : [statements];
foreach (var st in list)
{
if (!st.TryGetProperty("Principal", out var p)) continue;
if (p.ValueKind == JsonValueKind.String) { yield return p.GetString()!; continue; }
if (!p.TryGetProperty("AWS", out var aws)) continue;
if (aws.ValueKind == JsonValueKind.String) yield return aws.GetString()!;
else foreach (var a in aws.EnumerateArray()) yield return a.GetString()!;
}
}Expected output in a clean sandbox:
IAM hygiene report for account 111122223333 — 2026-11-17 10:15:02Z
- ROLE: 'OrganizationAccountAccessRole' trusts external principal arn:aws:iam::444455556666:root. Confirm it is approved.That finding is genuine and expected: the role that AWS Organizations creates in member accounts trusts the management account. "Expected" findings like this go on an approved-exceptions list rather than being silently ignored.
Code explained line by line
const int MaxKeyAgeDays = 90;— Harbourline's key-rotation standard. Make it a policy number, not a magic number buried in anif.CredentialProfileStoreChain/TryGetAWSCredentials— loads the named profile from%USERPROFILE%\.aws\config. For an SSO profile the SDK needs theAWSSDK.SSOandAWSSDK.SSOOIDCpackages at runtime, which is why they are referenced even though no code uses them directly.new AmazonIdentityManagementServiceClient(credentials, RegionEndpoint.USEast1)— IAM is a global service whose control plane lives inus-east-1.GetAccountSummaryAsync— returns counters such asAccountMFAEnabledandAccountAccessKeysPresent, which describe the root user.summary.SummaryMap ?? new Dictionary...— in SDK v4, collection properties in responses can benullrather than empty. Always guard with??.iam.Paginators.ListUsers(...).Users— the SDK's paginator follows theMarkerfor you and yields users as anIAsyncEnumerable, soawait foreachworks across pages.ListMFADevicesAsync— empty list means no MFA for that user.ListAccessKeysAsync/GetAccessKeyLastUsedAsync— key metadata (never the secret) and the last time, service and Region where the key was used.key.CreateDate ?? DateTime.UtcNow— v4 makes value-type properties nullable; decide explicitly what a missing value means.masked— never print a full access key ID into logs or tickets. The first four characters (AKIAfor user keys,ASIAfor temporary keys) plus the last four are enough to identify it.role.Path?.StartsWith("/aws-service-role/")— service-linked roles are owned by AWS services and must not be edited; skip them.Uri.UnescapeDataString(role.AssumeRolePolicyDocument)— IAM returns policy documents URL-encoded.ExtractAwsPrincipals— handles the three shapes ofPrincipal: the string"*",{"AWS": "arn"}and{"AWS": ["arn", ...]}. It ignoresServiceandFederatedprincipals, which a fuller audit would also report.return findings.Count == 0 ? 0 : 1;— a non-zero exit code lets a scheduled pipeline fail and raise a ticket.
⚠ Learning shortcut — not for production
This report runs from your laptop against one account. In production, run the same checks centrally: IAM Access Analyzer (external and unused access) across the organisation, AWS Config rules such as iam-user-mfa-enabled and access-keys-rotated, and Security Hub CSPM controls — all covered later in this module — so that evidence is collected continuously rather than when someone remembers.
Security considerations
- No IAM users for people. Use IAM Identity Center. If an IAM user must exist, give it a named owner, an expiry date in a tag, MFA where interactive, and conditions such as
aws:SourceIporaws:SourceVpce. - No root access keys, ever. Check
AccountAccessKeysPresentis 0 in every account, and use centralised root access in organisations. - Prefer customer managed policies over AWS managed policies for production roles, so that changes go through your pull-request review.
- Avoid
NotActionwithAllow,"Action": "*", andiam:PassRoleon"Resource": "*"— the last one lets a principal hand any role (including an admin role) to a service it controls, which is a classic privilege-escalation path. - Restrict service trust policies with
aws:SourceAccountoraws:SourceArn. - Treat IAM changes as production changes. Log them (CloudTrail), review them (pull requests on IaC), and alert on high-risk ones (
CreateAccessKey,AttachRolePolicywithAdministratorAccess) — see CloudTrail for banks.
Banking use case
Harbourline's Payments Service runs as ECS tasks. Each task gets the role hl-payments-task, whose identity policy allows sqs:ReceiveMessage on the payments queue, dynamodb:PutItem on the payments table and kms:GenerateDataKey on the payments key. The payments KMS key policy (a resource-based policy) allows that role and nobody else in the account to use the key for encryption. A permissions boundary on all roles created by the payments team prevents any of them from touching IAM or CloudTrail. The production OU's SCP denies cloudtrail:StopLogging for everyone. When the auditor asks "who can initiate a payment?", the answer is a short list of role ARNs, each traceable in CloudTrail — not "anyone in the Payments AD group, probably".
Whether that design satisfies a specific regulatory requirement (for example PCI DSS requirement 7 on restricting access by business need to know) is a judgement for Harbourline's compliance function and its assessor, not something the configuration proves on its own.
Common mistakes
- Using an IAM user with access keys on a developer laptop → it is the quickest thing to set up → use
aws sso loginand SSO profiles from day one. - Attaching
AdministratorAccess"temporarily" → it never gets removed → grant a scoped policy, and use Access Analyzer unused-access findings to catch leftovers. - Writing
Resource: "*"because the ARN format is unclear → look up the action in the Service Authorization Reference, which lists the resource types and condition keys for every action. - Confusing
arn:aws:iam::111122223333:rootwith "only the root user" → as a principal it means "this account, subject to its own IAM policies". - Forgetting the trust policy → the role has permissions but
AssumeRolefails withAccessDeniedbecause the caller is not trusted. - Forgetting the other side of cross-account access → a bucket policy that allows account B is not enough; B's role also needs an identity policy allowing the action.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
AccessDenied ... is not authorized to perform: iam:ListUsers | Your permission set is too narrow | Use a permission set with IAMReadOnlyAccess or the SecurityAudit managed policy |
The security token included in the request is expired | SSO session expired | aws sso login --profile learn-sandbox |
MalformedPolicyDocument: Has prohibited field Principal | Principal in an identity policy | Remove it; principals belong only in resource-based and trust policies |
MalformedPolicyDocument: Policy document should not specify a principal when creating a role | Trust policy passed to create-policy instead of create-role | Trust policy goes in --assume-role-policy-document |
LimitExceeded: Cannot exceed quota for PolicySize: 6144 | Managed policy too large | Split by resource type; replace long action lists with well-chosen wildcards such as dynamodb:Get* only where safe |
C# app throws AmazonClientException: ... SSO ... assembly | SSO packages missing | Add AWSSDK.SSO and AWSSDK.SSOOIDC |
| New role fails on first use in automation | IAM eventual consistency | Retry with back-off for a few seconds |
Cost and cleanup
IAM, IAM roles, policies, the credential report and get-account-summary are free. This lesson creates no billable resources.
# Detach and delete the policy and role created in this lesson.
aws iam detach-role-policy --role-name hl-m05-accounts-api \
--policy-arn arn:aws:iam::111122223333:policy/hl-m05-accounts-api-read --profile learn-sandbox
aws iam delete-role --role-name hl-m05-accounts-api --profile learn-sandbox
aws iam delete-policy --policy-arn arn:aws:iam::111122223333:policy/hl-m05-accounts-api-read --profile learn-sandbox
# If you used CDK or Terraform instead:
# cdk destroy | terraform destroy
# Confirm nothing tagged for this lab remains.
aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=cea-lab Key=Lab,Values=m05-iam \
--region us-east-1 --profile learn-sandbox --query "ResourceTagMappingList[].ResourceARN"IAM resources are global; the tagging API call above may not list IAM roles in every case, so also run aws iam list-roles --query "Roles[?starts_with(RoleName,'hl-m05')].RoleName".
Exercises
- 🟢 Guided: Run the IAM hygiene report in your sandbox. Then create an IAM user
hl-m05-test-userwith one access key (do not use the key), rerun the report, and confirm it flags the user, the missing MFA and the never-used key. Delete the user. - 🟡 Challenge: Extend the report to flag any role or user with the AWS managed policy
AdministratorAccessattached (ListAttachedRolePolicies,ListAttachedUserPolicies) and any inline policy containing"Action": "*". - 🔴 Live problem: A ticket arrives: "Batch team says their nightly reconciliation job in the data account broke after the security team 'tidied up IAM'. Error: AccessDenied on s3:GetObject for
hl-recon-input. They want AdministratorAccess back on the job's role by tonight." Write the reply you would send, including what you would check, in what order, and what you will not do.
Assignment
Produce a one-page IAM standard for Harbourline workload accounts in your portfolio repository: which principal types are allowed for people, workloads on AWS, workloads outside AWS and third parties; the naming convention (hl-<system>-<purpose>); mandatory tags; banned patterns (with the reason for each); and the exception process for IAM users. Attach the output of your hygiene report as evidence.
Solutions
aws iam create-user --user-name hl-m05-test-user --profile learn-sandbox \
--tags Key=Project,Value=cea-lab Key=Lab,Value=m05-iam Key=Environment,Value=learn Key=Owner,Value=alex
aws iam create-access-key --user-name hl-m05-test-user --profile learn-sandbox --query "AccessKey.AccessKeyId"
dotnet run
# Expect: USER exists, no MFA device, KEY ... has never been used.
aws iam list-access-keys --user-name hl-m05-test-user --profile learn-sandbox --query "AccessKeyMetadata[].AccessKeyId" --output text \
| xargs -n1 aws iam delete-access-key --user-name hl-m05-test-user --profile learn-sandbox --access-key-id
aws iam delete-user --user-name hl-m05-test-user --profile learn-sandboxWhy: the exercise shows that an IAM user with a key is a standing credential the moment it is created, before anybody uses it. Note that create-access-key prints the secret to your terminal — another reason the pattern is banned. Close the terminal and do not save the output.
Add after the key loop for users, and inside the role loop:
var attached = await iam.ListAttachedRolePoliciesAsync(new ListAttachedRolePoliciesRequest { RoleName = role.RoleName });
if ((attached.AttachedPolicies ?? []).Any(p => p.PolicyArn == "arn:aws:iam::aws:policy/AdministratorAccess"))
findings.Add($"ROLE: '{role.RoleName}' has AdministratorAccess.");
await foreach (var name in iam.Paginators.ListRolePolicies(new ListRolePoliciesRequest { RoleName = role.RoleName }).PolicyNames)
{
var inline = await iam.GetRolePolicyAsync(new GetRolePolicyRequest { RoleName = role.RoleName, PolicyName = name });
var json = Uri.UnescapeDataString(inline.PolicyDocument);
if (json.Contains("\"Action\":\"*\"") || json.Contains("\"Action\": \"*\""))
findings.Add($"ROLE: '{role.RoleName}' inline policy '{name}' allows Action '*'.");
}Why: string matching is crude — a statement could be ["*"], or Deny with *. A robust version parses the JSON and checks Effect == "Allow" with an Action of *. The module lab's policy linter (labs/m05-secure-banking-api/src/Harbourline.Security.PolicyLinter) does exactly that. In production you would also expect the SSO administrator roles (AWSReservedSSO_...Admin...) to appear here and treat them as approved.
Reply: "We won't restore AdministratorAccess — it would put an over-privileged role back into an account that holds customer data, and it would undo the reason for the clean-up. We'll fix the specific permission today." Then check, in order:
- CloudTrail for the failed
GetObject(data events, if enabled) or the error message: which role ARN made the call, and does the message mention an SCP, a boundary or a resource policy? - The role's identity policies: was the statement for
hl-recon-inputremoved or narrowed? - The bucket policy and any KMS key policy for the bucket's encryption key (if objects are SSE-KMS,
kms:Decryptis also needed). - Whether the job's role was a different role than the one the team thinks (assumed-role ARN in CloudTrail).
- Add the minimum missing statement through the normal IaC pull request, with an emergency change if needed, and record it.
Why: the request is a classic pressure-driven escalation. The right answer restores service with the smallest change and leaves an audit trail.
Knowledge check
Answer: An IAM role configured as the ECS task role. ECS delivers temporary credentials to the container and the SDK's default credential chain picks them up automatically. An IAM user's access keys in environment variables or appsettings.json would be long-lived secrets — the thing we are trying to eliminate. An IAM group cannot be used by a workload at all.
Answer: Identity-based policies, resource-based policies, ACLs and AWS RAM shares grant. Permissions boundaries, SCPs, RCPs, VPC endpoint policies and session policies only limit (cap). An explicit Deny in any of them always wins.
Answer: The whole account 111122223333. Access is delegated to that account, which must still grant the action to specific users or roles through their identity policies. It does not mean only the root user.
Answer: Requests signed with long-lived access keys do not include the aws:MultiFactorAuthPresent key at all. With the key missing, Bool evaluates to false and the Deny does not apply. Use BoolIfExists so that a missing key is treated as a match.
Answer: SCPs restrict the root user of member accounts. They never restrict the management account (including its root user), which is why workloads must not run there.
Interview questions
- "How would you give 40 engineers access to 25 AWS accounts?" — IAM Identity Center connected to the corporate IdP; groups mapped to permission sets per account; MFA enforced at the IdP or Identity Center; no IAM users; short session durations; access reviews from Identity Center assignments plus CloudTrail.
- "What is the difference between an IAM role and an IAM user?" — A user has long-lived credentials and belongs to one account. A role has no credentials of its own; trusted principals assume it and receive temporary STS credentials that expire. Roles are the default for both people (via Identity Center) and workloads.
- "What is a resource-based policy, and when do you need one?" — A policy attached to the resource that names principals. Needed for cross-account access to that resource and for service principals writing into your resources (for example CloudTrail to S3). A role's trust policy is the IAM example.
- "Name an IAM privilege-escalation path." —
iam:PassRoleon*combined withlambda:CreateFunctionlets a user run code as any role;iam:CreatePolicyVersionlets a user rewrite their own policy;iam:AttachRolePolicyon their own role. Defend with boundaries, scopedPassRoleand alerts.
Certification practice
A bank's .NET batch application runs on EC2 and reads files from S3. A code review finds an access key and secret for an IAM user in appsettings.Production.json. What is the BEST remediation?
A. Move the keys to environment variables on the instance and rotate them every 90 days.
B. Store the keys in AWS Secrets Manager with automatic rotation and read them at start-up.
C. Create an IAM role with the required S3 permissions, attach it to the instance through an instance profile, remove the keys from code and deactivate then delete the IAM user's keys.
D. Encrypt appsettings.Production.json with a KMS key.
Answer: C. An instance profile gives the application temporary, automatically rotated credentials with no secret to manage. A only moves the long-lived secret. B is better than A but still uses a long-lived IAM user credential where a role is available. D protects the file but not the credential's power if it leaks.
Account A (111122223333) runs a reporting role that must read objects from a bucket in account B (777788889999). The bucket policy in account B allows s3:GetObject for arn:aws:iam::111122223333:role/hl-reporting. Calls still fail with AccessDenied. The bucket uses SSE-S3. What is the MOST likely missing piece?
A. An SCP in account B allowing s3:GetObject.
B. An identity-based policy on hl-reporting in account A allowing s3:GetObject on the bucket's objects.
C. A bucket ACL granting read to account A.
D. A permissions boundary on hl-reporting.
Answer: B. Cross-account access needs both sides: the resource policy in B and an identity policy in A. SCPs never grant (A). ACLs are legacy and unnecessary when a bucket policy exists (C). A boundary only limits; it cannot add the missing allow (D).
A company wants 15 developers to access five AWS accounts using their existing corporate credentials, with MFA, and without creating identities in each account. Which solution meets the requirements with the LEAST operational overhead?
A. Create an IAM user for each developer in each account and enforce MFA with an IAM policy. B. Create IAM users in one account and let them switch roles into the other four. C. Enable IAM Identity Center with the corporate identity provider as the identity source, create permission sets and assign groups to the accounts. D. Use Amazon Cognito user pools for the developers.
Answer: C. Identity Center is designed for workforce access to many accounts with an external IdP. A creates 75 users. B still creates 15 long-lived identities. Cognito (D) is for customer-facing application users, not workforce access to AWS accounts.
Completion checklist
- I can explain the difference between a user, a group and a role in two sentences
- I can name all the elements of a policy statement and the nine policy types
- I ran the IAM hygiene report against my sandbox and understood every finding
- I created a role with a scoped trust policy and a customer managed policy, then deleted it
- I confirmed my root user has MFA and no access keys
Key takeaways
- Every AWS request is authenticated, then authorised against all applicable policies; the default is deny and an explicit deny always wins.
- Roles with temporary credentials are the default for people (through IAM Identity Center) and workloads. IAM users are an exception that needs a written justification.
- Identity policies, resource policies, ACLs and RAM shares grant; boundaries, SCPs, RCPs, endpoint policies and session policies only limit.
- A role has two policies: trust (who can assume it) and permissions (what it can do). Restrict service trust with
aws:SourceAccountoraws:SourceArn. - AWS secures the IAM service; Harbourline is responsible for every identity, policy and credential it configures.
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.
Module 5: Security for Banking & Finance
The most important module on the platform: identity, encryption, network protection, detection, incident response and secure delivery on AWS, all through a banking lens. You learn exactly where AWS's responsibility ends and the bank's begins, and you build a secure banking API architecture with an incident-response runbook.
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.