Skip to Content
Cloud Engineering Academy
5. Security for Banking & Finance

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#.

beginner⏱ 1 h 30 min🟢 FreeSCS-C03SAA-C03CLF-C02

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/NotResource and Condition.
  • 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

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:

  1. Who can act in this account? Not only people, but Lambda functions, ECS tasks, CI pipelines and third-party tools.
  2. What exactly can each of them do, and where is that written down?
  3. 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:

  1. Authentication — who are you? The signature proves which principal (identity) sent the request.
  2. 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:

PrincipalWhat it isCredentialsBanking use
Root userThe identity created with the account (an email address)Password + MFA; access keys should never existBreak-glass only: a handful of tasks such as closing the account
IAM userA named identity that lives inside one accountLong-lived password and/or long-lived access keysAlmost none. Legacy integrations that cannot use roles, under exception
IAM groupA collection of IAM usersNone — a group cannot sign inAttaches policies to users. Not a principal in its own right
IAM roleAn identity with permissions but no permanent credentials; anyone it trusts can assume itTemporary 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. AccessDenied often 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 equivalentWhat's different
Entra ID tenant (one directory for many subscriptions)IAM in each account + IAM Identity Center for peopleIAM is per account; Identity Center is the organisation-wide directory for humans
Entra ID userIAM 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 groupIAM groupIAM 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, EC2Same idea — no secret in code. The role has a trust policy saying which service may use it
Azure RBAC role definitionIAM managed policyAWS policies list API actions (s3:GetObject), not portal operations
RBAC role assignment at a scopeAttaching a policy to a role, or a resource policy naming a principalScope is expressed by the Resource ARN and Condition, not by the assignment location
Deny assignments / Azure Policy denyExplicit Deny statements, SCPs, RCPs, permissions boundariesAn explicit deny anywhere always wins
Global Administrator break-glassRoot userOne 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:

hl-m05-accounts-api-read.json
{
  "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:

ElementRequired?Meaning
VersionAlways use 2012-10-17The policy language version. The older 2008-10-17 does not support policy variables such as ${aws:username}
StatementYesOne statement object or an array. Statements are OR-ed together
SidOptionalA label. Use it — auditors and your future self read policies by Sid
EffectYesAllow or Deny
PrincipalOnly 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 / NotActionOne of themAPI operations in the form service:Operation. Wildcards * and ? allowed. NotAction means "every action except these" — dangerous with Allow
Resource / NotResourceRequired in identity policiesARNs the statement covers. Some actions (for example s3:ListAllMyBuckets) only work with "*"
ConditionOptionalExtra 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 ...IfExists variant or the Null operator. 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 need BoolIfExists.

ARNs

An ARN uniquely names any AWS resource:

arn:partition:service:region:account-id:resource-type/resource-id
ExampleNotes
arn:aws:iam::111122223333:role/hl-m05-accounts-apiIAM is global, so the Region field is empty
arn:aws:iam::111122223333:user/legacy-batchAn IAM user
arn:aws:sts::111122223333:assumed-role/hl-m05-accounts-api/session-42A role session — what CloudTrail records when the role is used
arn:aws:iam::111122223333:rootAs a Principal this means "the account" (delegating to its IAM policies), not only the root user
arn:aws:s3:::hl-m05-statementsS3 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 typeAttached toGrants?Typical banking use
1Identity-based (AWS managed, customer managed, inline)User, group, role✅ GrantsWhat the Accounts API role may do
2Resource-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
3VPC endpoint policyVPC interface/gateway endpoint❌ Caps traffic through the endpointOnly Harbourline's buckets reachable through the S3 endpoint
4Permissions boundaryUser or role (a managed policy)❌ Caps identity policiesDevelopers can create roles but never more powerful than the boundary
5SCP (service control policy)Organization root, OU or account❌ Caps principals in member accounts (including member root users)Deny leaving approved Regions; deny disabling CloudTrail
6RCP (resource control policy)Organization root, OU or account❌ Caps access to resources in member accounts, whoever the caller isDeny any principal outside the organisation from reading S3 objects
7ACL (access control list)Some resources (S3 legacy, WAF, VPC)✅ Grants cross-account only; not JSONDisable S3 ACLs (Object Ownership: bucket owner enforced)
8AWS RAM resource shareShared resource✅ Grants to other accounts in a managed wayShare Transit Gateway or subnets with workload accounts
9Session policyPassed in an AssumeRole* or GetFederationToken call❌ Caps the sessionA 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:

  1. 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.
  2. One or more permissions policies that say what the session may do.
trust-policy-lambda.json
{
  "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-sandbox

The 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

infra/IamBasicsStack.cs
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.

Harbourline.Security.IamAudit.csproj
<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>
Program.cs
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

  1. const int MaxKeyAgeDays = 90; — Harbourline's key-rotation standard. Make it a policy number, not a magic number buried in an if.
  2. CredentialProfileStoreChain / TryGetAWSCredentials — loads the named profile from %USERPROFILE%\.aws\config. For an SSO profile the SDK needs the AWSSDK.SSO and AWSSDK.SSOOIDC packages at runtime, which is why they are referenced even though no code uses them directly.
  3. new AmazonIdentityManagementServiceClient(credentials, RegionEndpoint.USEast1) — IAM is a global service whose control plane lives in us-east-1.
  4. GetAccountSummaryAsync — returns counters such as AccountMFAEnabled and AccountAccessKeysPresent, which describe the root user.
  5. summary.SummaryMap ?? new Dictionary... — in SDK v4, collection properties in responses can be null rather than empty. Always guard with ??.
  6. iam.Paginators.ListUsers(...).Users — the SDK's paginator follows the Marker for you and yields users as an IAsyncEnumerable, so await foreach works across pages.
  7. ListMFADevicesAsync — empty list means no MFA for that user.
  8. ListAccessKeysAsync / GetAccessKeyLastUsedAsync — key metadata (never the secret) and the last time, service and Region where the key was used.
  9. key.CreateDate ?? DateTime.UtcNow — v4 makes value-type properties nullable; decide explicitly what a missing value means.
  10. masked — never print a full access key ID into logs or tickets. The first four characters (AKIA for user keys, ASIA for temporary keys) plus the last four are enough to identify it.
  11. role.Path?.StartsWith("/aws-service-role/") — service-linked roles are owned by AWS services and must not be edited; skip them.
  12. Uri.UnescapeDataString(role.AssumeRolePolicyDocument) — IAM returns policy documents URL-encoded.
  13. ExtractAwsPrincipals — handles the three shapes of Principal: the string "*", {"AWS": "arn"} and {"AWS": ["arn", ...]}. It ignores Service and Federated principals, which a fuller audit would also report.
  14. 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:SourceIp or aws:SourceVpce.
  • No root access keys, ever. Check AccountAccessKeysPresent is 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 NotAction with Allow, "Action": "*", and iam:PassRole on "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:SourceAccount or aws:SourceArn.
  • Treat IAM changes as production changes. Log them (CloudTrail), review them (pull requests on IaC), and alert on high-risk ones (CreateAccessKey, AttachRolePolicy with AdministratorAccess) — 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 login and 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:root with "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 AssumeRole fails with AccessDenied because 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

SymptomLikely causeFix
AccessDenied ... is not authorized to perform: iam:ListUsersYour permission set is too narrowUse a permission set with IAMReadOnlyAccess or the SecurityAudit managed policy
The security token included in the request is expiredSSO session expiredaws sso login --profile learn-sandbox
MalformedPolicyDocument: Has prohibited field PrincipalPrincipal in an identity policyRemove it; principals belong only in resource-based and trust policies
MalformedPolicyDocument: Policy document should not specify a principal when creating a roleTrust policy passed to create-policy instead of create-roleTrust policy goes in --assume-role-policy-document
LimitExceeded: Cannot exceed quota for PolicySize: 6144Managed policy too largeSplit by resource type; replace long action lists with well-chosen wildcards such as dynamodb:Get* only where safe
C# app throws AmazonClientException: ... SSO ... assemblySSO packages missingAdd AWSSDK.SSO and AWSSDK.SSOOIDC
New role fails on first use in automationIAM eventual consistencyRetry 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-user with 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 AdministratorAccess attached (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

Knowledge check

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:PassRole on * combined with lambda:CreateFunction lets a user run code as any role; iam:CreatePolicyVersion lets a user rewrite their own policy; iam:AttachRolePolicy on their own role. Defend with boundaries, scoped PassRole and alerts.

Certification practice

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:SourceAccount or aws: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.

On this page