Apply Serverless Least Privilege
Assign per-function IAM roles with resource-level permissions, disable unused event source mappings, require authentication on function URLs, and restrict deployment configuration — preventing lateral movement when any single function is compromised.
Why This Is Best Practice
Adopted by: OWASP Serverless Top 10 SLS-4 (Over-Privileged Function Permissions), SLS-3 (Insecure Serverless Deployment Configuration), and SLS-2 (Broken Authentication). CIS AWS Foundations Benchmark v3.0 requires per-function execution roles and denies wildcard IAM actions. AWS Well-Architected Security Pillar mandates least-privilege IAM for all Lambda functions. Netflix's "Chaos Engineering for Serverless" (2022) found over-privileged Lambda roles as the most common critical finding in their Lambda security reviews.
Impact: Palo Alto Unit 42 (2022) found 70% of Lambda functions in production have excessive IAM permissions — most commonly s3:* on * resources when the function only needs s3:GetObject on one bucket. The 2022 Codecov incident (pipeline compromise, $hundreds of millions in remediation across affected organizations) occurred because CI functions had write access to all repos. A single Lambda with iam:* or sts:AssumeRole on * allows complete account takeover from that one function's compromise.
Why best: Shared execution roles across multiple functions are operationally convenient but mean that compromising any function exposes all resources accessible to that role. Per-function roles limit blast radius — a compromised order-processing Lambda can only access the order database, not payment records or user credentials.
Sources: OWASP Serverless Top 10 SLS-2, SLS-3, SLS-4; CIS AWS Foundations Benchmark v3.0; AWS Lambda security documentation; Netflix serverless security guidance (2022)
Steps
Create per-function execution roles — never share roles across functions:
# SAM / CloudFormation: separate role per function
ReadOrdersFunction:
Type: AWS::Serverless::Function
Properties:
Role: !GetAtt ReadOrdersRole.Arn
ReadOrdersRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
Policies:
- PolicyDocument:
Statement:
# Specific table, specific actions only
- Effect: Allow
Action:
- dynamodb:GetItem
- dynamodb:Query
Resource: !GetAtt OrdersTable.Arn
# CloudWatch Logs — required for all functions
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource: !Sub "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/ReadOrders*"
Use resource-level permissions — never Resource: "*":
# Terraform example — specific ARN permissions
resource "aws_iam_role_policy" "process_payment" {
role = aws_iam_role.process_payment_lambda.id
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Effect = "Allow"
Action = ["secretsmanager:GetSecretValue"]
Resource = aws_secretsmanager_secret.payment_api_key.arn
# NOT: Resource = "*"
},
{
Effect = "Allow"
Action = ["sqs:ReceiveMessage", "sqs:DeleteMessage", "sqs:GetQueueAttributes"]
Resource = aws_sqs_queue.payment_queue.arn
# Specific queue, not all SQS
},
{
Effect = "Allow"
Action = ["kms:Decrypt"]
Resource = aws_kms_key.payment_key.arn
# Only the payment KMS key
}
]
})
}
Require authentication on all invocation paths:
# API Gateway: require Cognito or IAM auth on all routes
# BAD — no auth
Events:
ApiEvent:
Type: Api
Properties:
Path: /orders
Method: GET
# Auth: NONE — anyone can call
# GOOD — require JWT authorization
Events:
ApiEvent:
Type: HttpApi
Properties:
Path: /orders
Method: GET
Auth:
Authorizer: CognitoAuthorizer
# For Lambda Function URLs — require IAM auth (not NONE)
FunctionUrlConfig:
AuthType: AWS_IAM # NOT: AuthType: NONE
Cors:
AllowOrigins:
- "https://app.company.com" # specific origin, not "*"
Disable unused event source mappings and triggers:
# List all event source mappings for a function
aws lambda list-event-source-mappings --function-name my-function
# Disable unused mappings (don't delete — may be needed again)
aws lambda update-event-source-mapping \
--uuid <mapping-uuid> \
--enabled false
# Review Lambda resource-based policies — remove stale invoke permissions
aws lambda get-policy --function-name my-function
aws lambda remove-permission \
--function-name my-function \
--statement-id old-s3-trigger
Restrict deployment: prevent unauthorized function code updates:
# IAM policy for deployment role — only CI/CD service account has lambda:UpdateFunctionCode
DeploymentPolicy:
Statement:
- Effect: Allow
Action:
- lambda:UpdateFunctionCode
- lambda:UpdateFunctionConfiguration
Resource: "arn:aws:lambda:*:*:function:*"
Condition:
StringEquals:
aws:PrincipalTag/Role: "cicd-deployer"
# Enable Lambda code signing — only signed deployments accepted
aws lambda create-code-signing-config \
--description "production-signing" \
--allowed-publishers "SigningProfileVersionArns=arn:aws:signer:..."
--code-signing-policies "UntrustedArtifactOnDeployment=Enforce"
aws lambda put-function-code-signing-config \
--function-name my-function \
--code-signing-config-arn arn:aws:lambda:...
Use IAM Access Analyzer to detect over-permissive policies:
# Scan Lambda execution roles for unused permissions
aws accessanalyzer validate-policy \
--policy-document file://lambda-role-policy.json \
--policy-type IDENTITY_POLICY
# Generate least-privilege policy from CloudTrail activity
aws iam generate-service-last-accessed-details \
--arn arn:aws:iam::123456789:role/MyLambdaRole
# Use this output to prune permissions not used in last 90 days
Rules
- Never attach
AdministratorAccess or AWSLambdaFullAccess managed policies to a Lambda execution role.
- Lambda Function URLs with
AuthType: NONE are publicly callable by anyone on the internet — require IAM or implement custom authorizer.
- Remove
lambda:InvokeFunction resource-based policy statements for services no longer triggering the function — stale principals can still invoke.
- Enable AWS CloudTrail for all regions to audit Lambda invocations and IAM role assumptions.
Common Mistakes
- One shared execution role for all Lambda functions — common in starter templates (
LambdaExecutionRole used everywhere); creates shared blast radius.
s3:* on * because "Lambda needs S3 access" — specify the exact bucket ARN and limit to the actions the function actually performs (GetObject, PutObject, etc.).
logs:* on * — Lambda only needs logs permissions for its own log group; scope to /aws/lambda/FunctionName*.
- Not monitoring for IAM privilege escalation — a Lambda with
iam:AttachRolePolicy or iam:PutRolePolicy on * can grant itself admin; use IAM Access Analyzer to detect these.
1---2name: apply-serverless-least-privilege3description: Use when writing serverless functions — assigning per-function IAM execution roles with minimal permissions, disabling unused triggers, and securing function URLs and API authentication.4source: 'OWASP Serverless Top 10 SLS-2 SLS-3 SLS-4 (owasp.org/www-project-serverless-top-10/); AWS IAM best practices; CIS AWS Foundations Benchmark; Palo Alto Unit 42 serverless research'5tags: [security, owasp, serverless, lambda, iam, least-privilege, cloud, developer]6metadata:7 source: https://skillmd.com/skills/jeffreytse/apply-serverless-least-privilege8---910# Apply Serverless Least Privilege1112Assign per-function IAM roles with resource-level permissions, disable unused event source mappings, require authentication on function URLs, and restrict deployment configuration — preventing lateral movement when any single function is compromised.1314## Why This Is Best Practice1516**Adopted by:** OWASP Serverless Top 10 SLS-4 (Over-Privileged Function Permissions), SLS-3 (Insecure Serverless Deployment Configuration), and SLS-2 (Broken Authentication). CIS AWS Foundations Benchmark v3.0 requires per-function execution roles and denies wildcard IAM actions. AWS Well-Architected Security Pillar mandates least-privilege IAM for all Lambda functions. Netflix's "Chaos Engineering for Serverless" (2022) found over-privileged Lambda roles as the most common critical finding in their Lambda security reviews.17**Impact:** Palo Alto Unit 42 (2022) found 70% of Lambda functions in production have excessive IAM permissions — most commonly `s3:*` on `*` resources when the function only needs `s3:GetObject` on one bucket. The 2022 Codecov incident (pipeline compromise, $hundreds of millions in remediation across affected organizations) occurred because CI functions had write access to all repos. A single Lambda with `iam:*` or `sts:AssumeRole` on `*` allows complete account takeover from that one function's compromise.18**Why best:** Shared execution roles across multiple functions are operationally convenient but mean that compromising any function exposes all resources accessible to that role. Per-function roles limit blast radius — a compromised order-processing Lambda can only access the order database, not payment records or user credentials.1920Sources: OWASP Serverless Top 10 SLS-2, SLS-3, SLS-4; CIS AWS Foundations Benchmark v3.0; AWS Lambda security documentation; Netflix serverless security guidance (2022)2122## Steps23241. **Create per-function execution roles — never share roles across functions**:2526 ```yaml27 # SAM / CloudFormation: separate role per function28 ReadOrdersFunction:29 Type: AWS::Serverless::Function30 Properties:31 Role: !GetAtt ReadOrdersRole.Arn3233 ReadOrdersRole:34 Type: AWS::IAM::Role35 Properties:36 AssumeRolePolicyDocument:37 Statement:38 - Effect: Allow39 Principal:40 Service: lambda.amazonaws.com41 Action: sts:AssumeRole42 Policies:43 - PolicyDocument:44 Statement:45 # Specific table, specific actions only46 - Effect: Allow47 Action:48 - dynamodb:GetItem49 - dynamodb:Query50 Resource: !GetAtt OrdersTable.Arn51 # CloudWatch Logs — required for all functions52 - Effect: Allow53 Action:54 - logs:CreateLogGroup55 - logs:CreateLogStream56 - logs:PutLogEvents57 Resource: !Sub "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/ReadOrders*"58 ```59602. **Use resource-level permissions — never `Resource: "*"`**:6162 ```python63 # Terraform example — specific ARN permissions64 resource "aws_iam_role_policy" "process_payment" {65 role = aws_iam_role.process_payment_lambda.id66 policy = jsonencode({67 Version = "2012-10-17"68 Statement = [69 {70 Effect = "Allow"71 Action = ["secretsmanager:GetSecretValue"]72 Resource = aws_secretsmanager_secret.payment_api_key.arn73 # NOT: Resource = "*"74 },75 {76 Effect = "Allow"77 Action = ["sqs:ReceiveMessage", "sqs:DeleteMessage", "sqs:GetQueueAttributes"]78 Resource = aws_sqs_queue.payment_queue.arn79 # Specific queue, not all SQS80 },81 {82 Effect = "Allow"83 Action = ["kms:Decrypt"]84 Resource = aws_kms_key.payment_key.arn85 # Only the payment KMS key86 }87 ]88 })89 }90 ```91923. **Require authentication on all invocation paths**:9394 ```yaml95 # API Gateway: require Cognito or IAM auth on all routes96 # BAD — no auth97 Events:98 ApiEvent:99 Type: Api100 Properties:101 Path: /orders102 Method: GET103 # Auth: NONE — anyone can call104105 # GOOD — require JWT authorization106 Events:107 ApiEvent:108 Type: HttpApi109 Properties:110 Path: /orders111 Method: GET112 Auth:113 Authorizer: CognitoAuthorizer114115 # For Lambda Function URLs — require IAM auth (not NONE)116 FunctionUrlConfig:117 AuthType: AWS_IAM # NOT: AuthType: NONE118 Cors:119 AllowOrigins:120 - "https://app.company.com" # specific origin, not "*"121 ```1221234. **Disable unused event source mappings and triggers**:124125 ```bash126 # List all event source mappings for a function127 aws lambda list-event-source-mappings --function-name my-function128129 # Disable unused mappings (don't delete — may be needed again)130 aws lambda update-event-source-mapping \131 --uuid <mapping-uuid> \132 --enabled false133134 # Review Lambda resource-based policies — remove stale invoke permissions135 aws lambda get-policy --function-name my-function136 aws lambda remove-permission \137 --function-name my-function \138 --statement-id old-s3-trigger139 ```1401415. **Restrict deployment: prevent unauthorized function code updates**:142143 ```yaml144 # IAM policy for deployment role — only CI/CD service account has lambda:UpdateFunctionCode145 DeploymentPolicy:146 Statement:147 - Effect: Allow148 Action:149 - lambda:UpdateFunctionCode150 - lambda:UpdateFunctionConfiguration151 Resource: "arn:aws:lambda:*:*:function:*"152 Condition:153 StringEquals:154 aws:PrincipalTag/Role: "cicd-deployer"155 ```156157 ```bash158 # Enable Lambda code signing — only signed deployments accepted159 aws lambda create-code-signing-config \160 --description "production-signing" \161 --allowed-publishers "SigningProfileVersionArns=arn:aws:signer:..."162 --code-signing-policies "UntrustedArtifactOnDeployment=Enforce"163164 aws lambda put-function-code-signing-config \165 --function-name my-function \166 --code-signing-config-arn arn:aws:lambda:...167 ```1681696. **Use IAM Access Analyzer to detect over-permissive policies**:170171 ```bash172 # Scan Lambda execution roles for unused permissions173 aws accessanalyzer validate-policy \174 --policy-document file://lambda-role-policy.json \175 --policy-type IDENTITY_POLICY176177 # Generate least-privilege policy from CloudTrail activity178 aws iam generate-service-last-accessed-details \179 --arn arn:aws:iam::123456789:role/MyLambdaRole180181 # Use this output to prune permissions not used in last 90 days182 ```183184## Rules185186- Never attach `AdministratorAccess` or `AWSLambdaFullAccess` managed policies to a Lambda execution role.187- Lambda Function URLs with `AuthType: NONE` are publicly callable by anyone on the internet — require IAM or implement custom authorizer.188- Remove `lambda:InvokeFunction` resource-based policy statements for services no longer triggering the function — stale principals can still invoke.189- Enable AWS CloudTrail for all regions to audit Lambda invocations and IAM role assumptions.190191## Common Mistakes192193- **One shared execution role for all Lambda functions** — common in starter templates (`LambdaExecutionRole` used everywhere); creates shared blast radius.194- **`s3:*` on `*` because "Lambda needs S3 access"** — specify the exact bucket ARN and limit to the actions the function actually performs (GetObject, PutObject, etc.).195- **`logs:*` on `*`** — Lambda only needs logs permissions for its own log group; scope to `/aws/lambda/FunctionName*`.196- **Not monitoring for IAM privilege escalation** — a Lambda with `iam:AttachRolePolicy` or `iam:PutRolePolicy` on `*` can grant itself admin; use IAM Access Analyzer to detect these.