Skip to content

Containers and serverlessService 12 of 139 controls

AWS Lambda security hardening

Harden AWS Lambda: least privilege roles, private function policies and URLs, secrets outside environment variables, code signing and supported runtimes.

Published on 10 min readTags:#serverless#iam#compute
On this page

AWS Lambda runs your code without servers to patch, which makes it easy to forget that each function is still a workload with an identity, network reach and a supply chain. The failures seen in practice are not exotic: an execution role with AdministratorAccess copied from a tutorial, a function policy or function URL open to *, database passwords and API keys pasted into environment variables where anyone with read access to Lambda can see them, and functions left on runtimes that stopped receiving patches years ago. Attackers who obtain a role that can call iam:PassRole and lambda:CreateFunction use Lambda as a privilege escalation path, and malware such as Denonia (reported by Cado Security in 2022) was built to mine cryptocurrency inside Lambda; Cado suspected it was deployed with stolen access keys. The controls below cover identity, exposure, secrets, code integrity, runtime lifecycle, network and detection.

Baseline controls

9 controlsCIS numbers refer to the CIS AWS Foundations Benchmark v7.1.0 unless another CIS benchmark is named; Security Hub CSPM IDs are listed where a control exists.
  1. 01One least privilege execution role per function

    A code injection bug hands the attacker exactly the role's permissions, nothing less.

    How to check: aws lambda get-function-configuration --function-name my-fn --query Role
    Mapping: CIS AWS Compute 2.0.0 12.4, CIS Compute 12.5
  2. 02No public resource-based function policies

    A Principal of * lets anyone outside the account invoke the function.

    How to check: aws lambda get-policy --function-name my-fn
    Mapping: Lambda.1, CIS 2.21, CIS Compute 12.6
  3. 03Function URLs use AuthType AWS_IAM

    AuthType NONE turns the function into an unauthenticated public HTTPS endpoint.

    How to check: aws lambda list-function-url-configs --function-name my-fn
    Mapping: CIS Compute 12.16
  4. 04Secrets in Secrets Manager, not environment variables

    Anyone with GetFunctionConfiguration reads environment variables in plaintext.

    How to check: aws lambda get-function-configuration --function-name my-fn --query Environment
    Mapping: CIS Compute 12.3
  5. 05Code signing enforced on production functions

    Only artifacts signed by your pipeline can be deployed, even by an admin.

    How to check: aws lambda get-function-code-signing-config --function-name my-fn
    Mapping: CIS Compute 12.8
  6. 06Functions run on supported runtimes

    Deprecated runtimes stop receiving security patches but keep running.

    How to check: aws lambda list-functions --query 'Functions[].[FunctionName,Runtime]'
    Mapping: Lambda.2, CIS Compute 12.11
  7. 07Functions reaching private data run in a VPC

    VPC attachment lets security groups and endpoints restrict where the function talks.

    How to check: aws lambda get-function-configuration --function-name my-fn --query VpcConfig
    Mapping: Lambda.3, Lambda.5, CIS Compute 12.17
  8. 08Reserved concurrency set on exposed functions

    Caps the cost and blast radius of a flood of invocations or a hijacked function.

    How to check: aws lambda get-function-concurrency --function-name my-fn
  9. 09GuardDuty Lambda Protection enabled

    Flags functions talking to mining pools, C2 servers or known malicious IPs.

    How to check: aws guardduty get-detector --detector-id <id> --query Features

Scope the execution role per function

The execution role is the function's identity. Lambda injects its temporary credentials into the runtime as the AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN environment variables, so any code injection, dependency compromise or server-side request forgery that can read the process environment (for example /proc/self/environ) gets the role. The role's permissions are the blast radius of every bug in the function.

Give each function its own role. Shared roles accumulate permissions from every function that uses them, and you lose the ability to reason about any single one.

# Inventory functions and the role each one uses
aws lambda list-functions \
  --query 'Functions[].[FunctionName,Role]' --output table

# What the role can actually do
aws iam list-attached-role-policies --role-name my-fn-role
aws iam list-role-policies --role-name my-fn-role

A typical least privilege role for a function that reads one DynamoDB table and writes its own logs looks like this:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "ReadOrdersTable",
      "Effect": "Allow",
      "Action": ["dynamodb:GetItem", "dynamodb:Query"],
      "Resource": "arn:aws:dynamodb:eu-west-1:111122223333:table/orders"
    },
    {
      "Sid": "WriteOwnLogs",
      "Effect": "Allow",
      "Action": ["logs:CreateLogStream", "logs:PutLogEvents"],
      "Resource": "arn:aws:logs:eu-west-1:111122223333:log-group:/aws/lambda/orders-reader:*"
    }
  ]
}

Use IAM Access Analyzer policy generation against CloudTrail history to shrink existing roles, and check unused permissions findings regularly. The IAM page covers both.

Control who can pass roles to Lambda

The escalation path documented by Rhino Security Labs is simple: a principal that can pass a powerful role to a new function and invoke it runs code as that role. Restrict iam:PassRole to specific role ARNs and add the iam:PassedToService condition:

{
  "Effect": "Allow",
  "Action": "iam:PassRole",
  "Resource": "arn:aws:iam::111122223333:role/lambda/*",
  "Condition": {
    "StringEquals": { "iam:PassedToService": "lambda.amazonaws.com" }
  }
}

Keep Lambda execution roles under a dedicated path (/lambda/) so this pattern stays enforceable, and make sure no execution role is itself allowed to create or update functions.

Lock down resource-based policies

A function's resource-based policy decides which other accounts and services can invoke it. Security Hub CSPM control Lambda.1 fails when the policy allows public access, including the common case of an S3 trigger granted without an AWS:SourceAccount condition.

aws lambda get-policy --function-name my-fn \
  --query Policy --output text | jq .

When you grant a service permission to invoke the function, always pin the source to prevent confused deputy attacks:

aws lambda add-permission \
  --function-name my-fn \
  --statement-id s3-invoke \
  --action lambda:InvokeFunction \
  --principal s3.amazonaws.com \
  --source-arn arn:aws:s3:::my-upload-bucket \
  --source-account 111122223333

Remove a statement that is too broad with aws lambda remove-permission --function-name my-fn --statement-id <sid>. The policy cannot be edited in the console, only through the API or CLI.

Verify

IAM Access Analyzer external access analyzers report Lambda functions shared outside your zone of trust. With an organization-level analyzer, any function invokable from outside the organization appears as an active finding.

Function URLs: prefer AWS_IAM

A function URL is a dedicated HTTPS endpoint for one function. Its AuthType is either AWS_IAM (requests must be SigV4 signed by a principal allowed to invoke) or NONE (no authentication; the resource-based policy must grant public access, and then anyone with the URL can call it). A NONE URL skips everything an API Gateway or CloudFront front end would give you: no WAF, no throttling per client, no authorizer.

# Find every function URL and its auth type in a Region
for fn in $(aws lambda list-functions --query 'Functions[].FunctionName' --output text); do
  aws lambda list-function-url-configs --function-name "$fn" \
    --query 'FunctionUrlConfigs[].[FunctionArn,AuthType]' --output text
done

Since October 2025, new function URLs require both lambda:InvokeFunctionUrl and lambda:InvokeFunction permissions. Use the lambda:InvokedViaFunctionUrl condition on the InvokeFunction statement so the grant only works through the URL. If you need a public endpoint, put CloudFront with origin access control and AWS WAF in front of an AWS_IAM URL instead of exposing NONE.

Enforce across the organization

The lambda:FunctionUrlAuthType condition key works in SCPs. This one blocks creating or updating any function URL that is not AWS_IAM:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "DenyUnauthenticatedFunctionUrls",
      "Effect": "Deny",
      "Action": [
        "lambda:CreateFunctionUrlConfig",
        "lambda:UpdateFunctionUrlConfig"
      ],
      "Resource": "*",
      "Condition": {
        "StringNotEquals": { "lambda:FunctionUrlAuthType": "AWS_IAM" }
      }
    }
  ]
}

Attach it to workload OUs and carve out a dedicated account if a team genuinely needs public URLs. The Organizations page covers SCP rollout.

Keep secrets out of environment variables

Environment variables are configuration, not a vault. Lambda encrypts them at rest with the AWS managed key aws/lambda, but any principal with lambda:GetFunctionConfiguration gets them back in plaintext, and they show up in infrastructure as code state files, deployment logs and support screenshots. Read only roles and third-party scanners routinely have that permission.

Store credentials in AWS Secrets Manager or Systems Manager Parameter Store and fetch them at runtime. The AWS Parameters and Secrets Lambda Extension caches values locally so you do not pay a network call per invocation. The execution role then needs secretsmanager:GetSecretValue on that one secret ARN (plus kms:Decrypt if the secret uses a customer managed key).

# Look for likely secrets in environment variables across a Region
aws lambda list-functions \
  --query 'Functions[].{fn:FunctionName,vars:Environment.Variables}' --output json \
  | jq -r '.[] | select(.vars != null) | .fn as $f | .vars | keys[]
           | select(test("PASS|SECRET|TOKEN|KEY"; "i")) | "\($f): \(.)"'

Prowler also scans Lambda environment variables and code for secrets with its secret detection checks.

Encrypt environment variables with a customer managed key

For what remains in environment variables, set a customer managed KMS key. With a customer managed key, users need kms:Decrypt on that key to view or manage the variables, so the key policy becomes a second gate in front of GetFunctionConfiguration.

aws lambda update-function-configuration \
  --function-name my-fn \
  --kms-key-arn arn:aws:kms:eu-west-1:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab

The KMS page covers key policies that separate key administrators from key users.

Enforce code signing

Code signing makes Lambda reject deployment packages that were not signed by an approved AWS Signer profile. Even a principal with lambda:UpdateFunctionCode cannot push arbitrary code to a function whose code signing configuration is set to Enforce. It applies to .zip packages; container image functions rely on image signing and registry controls instead.

# Signing profile used by your CI pipeline
aws signer put-signing-profile \
  --profile-name prod_lambda \
  --platform-id AWSLambda-SHA384-ECDSA

# Code signing configuration that rejects unsigned or untrusted code
aws lambda create-code-signing-config \
  --allowed-publishers SigningProfileVersionArns=arn:aws:signer:eu-west-1:111122223333:/signing-profiles/prod_lambda/abcdef1234 \
  --code-signing-policies UntrustedArtifactOnDeployment=Enforce

aws lambda put-function-code-signing-config \
  --function-name my-fn \
  --code-signing-config-arn arn:aws:lambda:eu-west-1:111122223333:code-signing-config:csc-0123456789abcdef0

Warn mode logs a CloudWatch metric and a CloudTrail entry but still deploys; use it during rollout, then switch to Enforce.

Enforce across the organization

The lambda:CodeSigningConfigArn condition key lets an SCP or permissions boundary deny lambda:CreateFunction unless an approved code signing configuration is attached. Combine it with a deny on lambda:DeleteFunctionCodeSigningConfig and lambda:PutFunctionCodeSigningConfig for everyone except the pipeline role so the control cannot simply be removed.

Stay on supported runtimes

Lambda deprecates a runtime when its language version or underlying OS stops receiving security updates. After deprecation, existing functions keep running and invoking normally, which is exactly why they are forgotten: Lambda stops applying security patches, then blocks creating and later updating functions on that runtime. Security Hub CSPM control Lambda.2 fails for functions on runtimes outside the supported list (it ignores container image functions).

aws lambda list-functions \
  --query 'Functions[?PackageType==`Zip`].[FunctionName,Runtime]' \
  --output table

Check the deprecation calendar in the Lambda runtimes documentation twice a year and plan migrations before the "block function update" date. Leave runtime management on Auto so patch releases of the runtime are applied without redeployment:

aws lambda get-runtime-management-config --function-name my-fn
aws lambda put-runtime-management-config \
  --function-name my-fn --update-runtime-on Auto

For container image functions, you own the base image: rebuild on the AWS base image cadence and scan images in Amazon ECR with Amazon Inspector, which also scans .zip Lambda functions for vulnerable dependencies (and, optionally, code).

Attach functions to a VPC when they reach private data

A function outside a VPC has unrestricted outbound internet access and cannot be constrained by security groups. Attaching it to private subnets lets you control egress (NAT with filtering, or no NAT plus VPC endpoints), reach RDS or ElastiCache privately, and apply VPC endpoint policies. Security Hub CSPM control Lambda.3 checks that functions are in a VPC, and Lambda.5 checks that VPC functions span at least two Availability Zones.

aws lambda update-function-configuration \
  --function-name my-fn \
  --vpc-config SubnetIds=subnet-0aaa1111,subnet-0bbb2222,SecurityGroupIds=sg-0ccc3333

Lambda.3 is noisy for functions that only call public AWS APIs; treat it as a decision per function rather than a blanket rule, and suppress findings you have consciously accepted. The execution role needs the ec2:CreateNetworkInterface family of permissions (the AWSLambdaVPCAccessExecutionRole managed policy).

Enforce across the organization

Lambda supports the lambda:VpcIds, lambda:SubnetIds and lambda:SecurityGroupIds condition keys on CreateFunction and UpdateFunctionConfiguration. An SCP can require that functions in sensitive accounts are always attached to approved VPCs. The VPC page covers endpoint policies and egress design.

Cap concurrency

By default all functions in a Region share the account concurrency quota. A public endpoint hammered by bots, a recursive trigger loop, or a hijacked function used for mining can consume the whole pool and run up the bill. Reserved concurrency both guarantees and caps capacity for one function:

aws lambda put-function-concurrency \
  --function-name my-fn \
  --reserved-concurrent-executions 50

Setting reserved concurrency to 0 is also the fastest way to stop a compromised function from running during incident response, without deleting evidence. Keep Lambda recursive loop detection on (the default) so loops between Lambda, SQS, SNS and S3 are stopped automatically.

Logging and detection

Lambda sends function output to CloudWatch Logs under /aws/lambda/<function-name>. That log group never expires by default and is created with whatever the execution role allows. Use the advanced logging controls to emit structured JSON, set log levels, and point functions at a log group you manage with a retention policy and KMS encryption:

aws lambda update-function-configuration \
  --function-name my-fn \
  --logging-config LogFormat=JSON,ApplicationLogLevel=INFO,SystemLogLevel=WARN,LogGroup=/org/lambda/prod

CloudTrail records Lambda control plane calls as management events. Function invocations (Invoke) are data events: enable them on the organization trail for functions that handle sensitive data, using advanced event selectors on resources.type = AWS::Lambda::Function. The CloudTrail page covers trail setup.

Alert with EventBridge on the API calls that change exposure or code:

{
  "source": ["aws.lambda"],
  "detail-type": ["AWS API Call via CloudTrail"],
  "detail": {
    "eventName": [
      { "prefix": "AddPermission" },
      { "prefix": "CreateFunctionUrlConfig" },
      { "prefix": "UpdateFunctionUrlConfig" },
      { "prefix": "UpdateFunctionCode" },
      { "prefix": "DeleteFunctionCodeSigningConfig" }
    ]
  }
}

Lambda API event names in CloudTrail carry version suffixes (for example AddPermission20150331v2), which is why the pattern matches on prefix.

GuardDuty Lambda Protection

GuardDuty Lambda Protection analyzes network activity logs from your functions, including functions not attached to a VPC, and raises findings such as CryptoCurrency:Lambda/BitcoinTool.B, Backdoor:Lambda/C&CActivity.B and UnauthorizedAccess:Lambda/MaliciousIPCaller.Custom. Enable it from the GuardDuty delegated administrator for all member accounts:

aws guardduty update-detector \
  --detector-id <detector-id> \
  --features Name=LAMBDA_NETWORK_LOGS,Status=ENABLED

GuardDuty also raises IAM findings when credentials from a Lambda execution role are used from outside AWS, a strong sign of exfiltrated environment variables. The GuardDuty page covers organization-wide enablement and routing findings.

In Security Hub CSPM, track Lambda.1, Lambda.2, Lambda.3, Lambda.5 and Lambda.7 (X-Ray active tracing, useful for investigations rather than as a security boundary).

Common mistakes

  • One role for every function. A shared execution role ends up with the union of all permissions. A single vulnerable function then reaches everything the others do.
  • Trusting NONE function URLs because the URL is hard to guess. Function URLs show up in browser history, logs, front end bundles and Git history. Treat a NONE URL as public.
  • Secrets in environment variables "because they are encrypted". At rest encryption with the AWS managed key does nothing against a principal that can read the function configuration.
  • S3 or SNS triggers without source conditions. Granting s3.amazonaws.com invoke rights without --source-account and --source-arn fails Lambda.1 and lets other accounts' buckets trigger your function.
  • Code signing in Warn mode forever. Warn mode records unsigned deployments but does not block them. Switch to Enforce once the pipeline signs every artifact.
  • Ignoring deprecated runtimes because the function still works. It works until the block update date, which usually arrives during an incident when you urgently need to patch.
  • Unlimited log retention and no invocation logging. Logs that never expire cost money, and functions with sensitive data but no data events leave no record of who invoked them.

References

Written by

Florian Amette

Security engineer writing practical, benchmark-aligned hardening baselines for AWS services, from the organization and identities to data, networks and workloads.

Related services

All services