Least Privilege from Access Logs and Access Analysis
"Grant only what is needed" is easy to say and hard to do on day one, because nobody knows exactly which API calls an application will make. The practical route runs the other way: start from what is granted, observe what is used, and remove the rest. Cloud providers have built tools around this loop (AWS IAM Access Analyzer's unused-access findings and policy generation, last-accessed data, Azure's and GCP's role recommendations), and an auditor uses the same data to put a number on how much excess access an account carries. Excess access is what turns one stolen credential into a breach: the attacker gets everything that was granted, not just what the application happened to use.
Three kinds of evidence
| Evidence | AWS | Azure | Google Cloud |
|---|---|---|---|
| When was a service or action last used by this principal? | IAM last-accessed information (service level; action level for some services) | sign-in and activity logs | Policy Intelligence / activity analysis |
| Which permissions are unused over a period? | Access Analyzer unused access findings (roles, users, keys, passwords, permissions) | Entra ID access reviews, Defender for Cloud recommendations | IAM recommender (role recommendations) |
| What policy would cover the observed calls? | Access Analyzer policy generation from CloudTrail | (custom roles from activity, by hand) | recommender proposes smaller predefined roles |
| Who outside can reach a resource? | Access Analyzer external access findings | (Defender for Cloud, Azure Policy) | Policy Analyzer |
The mechanics are the same everywhere: compare the granted set with the used set over a window, and look hard at the difference.
A least-privilege report
The program expands each principal's granted actions against a small catalogue of real action names, reads 90 days of synthetic CloudTrail-style usage, and prints the unused share plus a generated policy. Real catalogues have tens of thousands of actions; the arithmetic is the same.
from fnmatch import fnmatchcase
from collections import defaultdict
CATALOGUE = {
"s3": ["GetObject", "PutObject", "DeleteObject", "ListBucket", "GetBucketPolicy", "PutBucketPolicy", "DeleteBucket", "PutBucketAcl"],
"ec2": ["DescribeInstances", "RunInstances", "TerminateInstances", "StartInstances", "StopInstances", "CreateSnapshot"],
"logs": ["CreateLogStream", "PutLogEvents", "DeleteLogGroup"],
"dynamodb": ["GetItem", "PutItem", "Query", "DeleteTable", "Scan"],
"kms": ["Decrypt", "Encrypt", "GenerateDataKey", "ScheduleKeyDeletion"],
}
ALL = [f"{svc}:{a}" for svc, acts in CATALOGUE.items() for a in acts]
def expand(patterns):
return {a for a in ALL if any(fnmatchcase(a.lower(), p.lower()) for p in patterns)}
granted = {
"app-role": ["s3:*", "dynamodb:*", "logs:*", "kms:Decrypt", "kms:GenerateDataKey"],
"ci-deploy": ["ec2:*", "s3:*"],
"report-job": ["s3:GetObject", "s3:ListBucket", "dynamodb:Query"],
}
# (principal, eventSource, eventName, days ago) - management events plus S3/DynamoDB data events
events = [
("app-role", "s3.amazonaws.com", "PutObject", 1), ("app-role", "s3.amazonaws.com", "GetObject", 1),
("app-role", "dynamodb.amazonaws.com", "GetItem", 2), ("app-role", "dynamodb.amazonaws.com", "PutItem", 2),
("app-role", "dynamodb.amazonaws.com", "Query", 5), ("app-role", "logs.amazonaws.com", "CreateLogStream", 3),
("app-role", "logs.amazonaws.com", "PutLogEvents", 1), ("app-role", "kms.amazonaws.com", "GenerateDataKey", 1),
("app-role", "kms.amazonaws.com", "Decrypt", 1),
("ci-deploy", "ec2.amazonaws.com", "DescribeInstances", 1), ("ci-deploy", "ec2.amazonaws.com", "RunInstances", 4),
("ci-deploy", "ec2.amazonaws.com", "TerminateInstances", 4), ("ci-deploy", "s3.amazonaws.com", "PutObject", 4),
("report-job", "s3.amazonaws.com", "GetObject", 30), ("report-job", "s3.amazonaws.com", "ListBucket", 30),
("report-job", "dynamodb.amazonaws.com", "Query", 30),
]
WINDOW = 90
used = defaultdict(set)
for who, source, name, ago in events:
if ago <= WINDOW:
used[who].add(f"{source.split('.')[0]}:{name}")
for who, patterns in granted.items():
g = expand(patterns)
u = used[who] & g
unused = sorted(g - u)
print(f"{who}: granted {len(g)}, used {len(u)} in {WINDOW} days, unused {len(unused)} ({100 * len(unused) // len(g)} %)")
risky = [a for a in unused if a.split(":")[1].startswith(("Delete", "Put", "Terminate", "Schedule"))]
if risky:
print(" unused and destructive:", ", ".join(risky))
by_svc = defaultdict(list)
for a in sorted(u):
svc, act = a.split(":")
by_svc[svc].append(act)
print(" generated Action list:", [f"{s}:{a}" for s, acts in by_svc.items() for a in acts])app-role: granted 18, used 9 in 90 days, unused 9 (50 %)
unused and destructive: dynamodb:DeleteTable, logs:DeleteLogGroup, s3:DeleteBucket, s3:DeleteObject, s3:PutBucketAcl, s3:PutBucketPolicy
generated Action list: ['dynamodb:GetItem', 'dynamodb:PutItem', 'dynamodb:Query', 'kms:Decrypt', 'kms:GenerateDataKey', 'logs:CreateLogStream', 'logs:PutLogEvents', 's3:GetObject', 's3:PutObject']
ci-deploy: granted 14, used 4 in 90 days, unused 10 (71 %)
unused and destructive: s3:DeleteBucket, s3:DeleteObject, s3:PutBucketAcl, s3:PutBucketPolicy
generated Action list: ['ec2:DescribeInstances', 'ec2:RunInstances', 'ec2:TerminateInstances', 's3:PutObject']
report-job: granted 3, used 3 in 90 days, unused 0 (0 %)
generated Action list: ['dynamodb:Query', 's3:GetObject', 's3:ListBucket']
app-role uses 9 of the 18 actions it holds; its unused half includes s3:DeleteBucket, s3:PutBucketPolicy, dynamodb:DeleteTable and every other destructive action of the services it touches. ci-deploy is worse in proportion (71 % unused), and its unused part includes deleting buckets and rewriting bucket policies. If app-role's credentials are stolen through the application (metadata credential theft), those are what the attacker gets for free. report-job is already tight: nothing to remove.
The generated list is only the action half of a policy. A good generated policy also narrows resources (the exact table and bucket ARNs seen in the events) and keeps any conditions the old policy had.
How excess access is detected
- Unused-access findings per role, user and key, with the "last used" date. Roles unused for 90 days or more are candidates for deletion, not just trimming.
- Ratio metrics for the account: unused share of granted actions, number of principals with destructive permissions they never use, number of active long-lived keys. Track them over time like vulnerability counts.
- External access findings: anything shared outside the organisation (roles, buckets, keys, snapshots) that isn't on the approved list.
How it is fixed
- Generate a policy from at least one full business cycle of activity (90 days is common; include month-end and quarter-end jobs).
- Review it: add resource ARNs and conditions, remove anything that looks like an attacker's or a mistake's activity, and add rare-but-needed actions (disaster recovery, yearly rotations) explicitly with a comment in the policy's source.
- Deploy it through IaC, watch CloudTrail for new
AccessDeniederrors from that principal for a week, and fix forward. - Repeat on a schedule. Permissions grow back.
Pitfalls
- Data events are not logged by default. CloudTrail records management events (
RunInstances,PutBucketPolicy) unless told otherwise, but S3 object reads and writes and DynamoDB item calls are data events that must be enabled per trail. A policy generated without them silently dropss3:GetObject, and the application breaks; the lab events above include them on purpose. - Trimming to the observed set before the window covers rare jobs.
- Counting actions without weighting them: one unused
iam:PassRolematters more than twenty unusedDescribe*calls.
Practice
1. Remove every S3 and DynamoDB event from events (as if data events were off). What would the generated list for app-role be, and what would break?
Only logs:CreateLogStream, logs:PutLogEvents, kms:Decrypt and kms:GenerateDataKey. Deploying it would break every upload and database call of the application. Enable data events (at least for the sensitive buckets and tables) before generating policies from logs.
2. Write the least-privilege policy for ci-deploy with resources, assuming its instances are tagged owner=ci and it writes to lab-artifacts/builds/*.
ec2:DescribeInstances on * (Describe calls don't support resource-level permissions); ec2:RunInstances on the instance, subnet, security group, AMI and volume ARNs it needs, with aws:RequestTag/owner = ci; ec2:TerminateInstances with ec2:ResourceTag/owner = ci; s3:PutObject on arn:aws:s3:::lab-artifacts/builds/*.
3. Change WINDOW to 7. What happens to report-job, and what is the lesson?
It shows 0 used actions and 100 % unused, because it runs monthly. A short window makes legitimate rare jobs look like excess access; choose the window from the job's schedule.
Test yourself
Why is unused access a security problem, not just untidiness?
- It costs money
- A stolen credential carries everything granted, not just what the workload uses
- It slows down API calls
- It breaks CloudTrail
In the program, how many of app-role's granted actions were used in 90 days?
- 18
- 9
- 4
- 3
Why can a policy generated from CloudTrail miss s3:GetObject?
- S3 is not logged at all
- Object-level S3 calls are data events, not logged unless enabled on the trail
- GetObject is free
- Access Analyzer ignores S3