Hardening Serverless IAM: Least Privilege for AWS Lambda Execution Roles

When a Lambda function boots, it picks up an IAM role that tells it what it can talk to. A lot of teams just slap AdministratorAccess or AWSLambdaFullAccess on those roles to keep the dev cycle painless. The problem? That opens the whole box up for an attacker or a typo in the code. Below is a hands‑on playbook I’ve used in production to tighten those roles, with real commands, a few trade‑offs, and the things that usually trip people up.


Why Least Privilege Matters in Lambda

  • Smaller blast radius – If the Lambda gets hijacked, the damage is limited to what the role can do.
  • Compliance check – NIST SP 800‑53 and similar frameworks expect least privilege for every identity.
  • Operational hygiene – Fewer permissions mean fewer accidental data leaks or service outages.

1. Inventory the Current Role

First, get a bird’s‑eye view of every Lambda execution role:

aws iam list-roles \
  --query "Roles[?contains(RoleName, 'lambda')].{Name:RoleName,Arn:Arn}" \
  --output table

Then drill down on each role:

aws iam list-attached-role-policies --role-name $ROLE_NAME --output json

If you spot a policy that references * or arn:aws:iam::aws:policy/AdministratorAccess, flag it for a deeper look.


2. Map Function Requirements

I usually create a simple spreadsheet or CSV that lists every Lambda and the services it actually touches. Here’s a snippet:

Function S3 DynamoDB SNS KMS CloudWatch Logs
image-resizer R/W None None E/D Write
user-notifier None None Publish None Write

You can populate this by reading the code or by running a static analysis tool. If you’re on AWS SAM or Serverless Framework, there are plugins that parse the deployment package and pull out the IAM statements for you.


3. Draft Minimal Policies

With that matrix in hand, write policies that grant only the necessary actions. For image-resizer, a lean policy looks like:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "s3:GetObject",
        "s3:PutObject",
        "s3:DeleteObject"
      ],
      "Resource": "arn:aws:s3:::my-bucket/*"
    },
    {
      "Effect": "Allow",
      "Action": [
        "kms:Encrypt",
        "kms:Decrypt"
      ],
      "Resource": "arn:aws:kms:us-east-1:123456789012:key/abcd-efgh-ijkl"
    },
    {
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": "arn:aws:logs:us-east-1:*:*"
    }
  ]
}

Trade‑off: Tightening the policy can break a function that suddenly needs a new action. Mitigate this by treating policies as code: keep them in Git, run a CI job that deploys a test function, and assert that the deployment succeeds.


4. Use Managed Policies Sparingly

Managed policies are handy, but most of them are overkill for Lambda. The only truly minimal one is AWSLambdaBasicExecutionRole – it gives the CloudWatch Logs permissions you’ll always need. For any other service, write a custom inline policy unless a managed policy matches your exact action set.


5. Leverage Resource‑Level Conditions

If you can narrow the scope, do it. For example, limit S3 access to a particular prefix:

{
  "Effect": "Allow",
  "Action": "s3:GetObject",
  "Resource": "arn:aws:s3:::my-bucket/prod/*",
  "Condition": {
    "StringLike": {
      "s3:prefix": "prod/*"
    }
  }
}

This stops the Lambda from accidentally touching dev or staging data.


6. Automate Policy Generation

Tools like the IAM Policy Simulator and the open‑source aws-iam-policy-generator can analyze your Lambda code and suggest the minimal policy set. Hook it into your CI pipeline:

steps:
  - name: Generate IAM Policy
    run: |
      aws-iam-policy-generator --lambda-arn $LAMBDA_ARN > generated-policy.json      
  - name: Validate Policy
    run: |
      aws iam simulate-principal-policy \
        --policy-source-arn $ROLE_ARN \
        --action-names s3:GetObject,s3:PutObject \
        --resource-arns arn:aws:s3:::my-bucket/*      

If the simulator flags a denied action, either tweak the policy or adjust the code.


7. Review and Rotate Credentials

Lambda automatically rotates the credentials it uses. But if your inline policy references Secrets Manager or Parameter Store, make sure those secrets are also scoped tightly. For instance, grant secretsmanager:GetSecretValue only to the specific secret ARN your function needs.


8. Monitor for Policy Drift

AWS Config has a rule called iam-policy-no-administrator-access that can surface over‑privileged roles. Pair it with CloudTrail to keep an eye on changes:

aws cloudtrail lookup-events \
  --lookup-attributes AttributeKey=EventName,AttributeValue=AttachRolePolicy \
  --query 'Events[*].{Time:EventTime,Role:Resources[0].ARN,User:Username}' \
  --output table

Set up GuardDuty or Security Hub alerts to flag any role that suddenly gains AdministratorAccess.


9. Practical Troubleshooting

Symptom Likely Cause Fix
Lambda throws AccessDenied on S3 Policy missing s3:GetObject Add that action
Logs don’t appear in CloudWatch logs:PutLogEvents missing Attach AWSLambdaBasicExecutionRole
KMS decrypt fails Key policy blocks Lambda role Update key policy for kms:Decrypt
Unexpected API calls in CloudTrail Role has too many permissions Re‑evaluate and prune unused actions

Always test in a staging account before pushing to prod.


10. Balancing Security and Agility

  • Tight least‑privilege reduces risk but can slow down feature work if developers need to request new permissions.
  • A policy‑as‑code workflow with pull‑request reviews and automated tests keeps the balance.
  • Feature flags can let you temporarily grant broader permissions during a rollout, then tighten them once the feature stabilizes.

11. Real‑World Example: Securing a Payment Processor Lambda

A fintech squad had a Lambda that processed payments and dumped logs into S3. Their role was a vanilla AdministratorAccess. After hardening:

  1. S3 – Only s3:PutObject on the payments-logs/ prefix.
  2. DynamoDB – dynamodb:PutItem on PaymentsTable.
  3. KMS – kms:Encrypt on the key protecting payment data.
  4. CloudWatch – AWSLambdaBasicExecutionRole.

Result? No accidental writes to other buckets, and even if the Lambda code were compromised, the attacker couldn’t exfiltrate user data. The audit team reported a 30 % drop in IAM‑related findings.


12. Next Steps

  • Add policy checks to your CI/CD pipeline.
  • Enable AWS Config rules for IAM.
  • Document role‑to‑function mappings in your architecture diagrams.
  • Review roles quarterly or after major code changes.

Follow these steps and you’ll turn a “give everything” Lambda role into a lean, auditable identity that actually follows least‑privilege.

See also