Apply Serverless Function Security
Validate all event data at function entry regardless of trigger source, prevent execution flow manipulation by isolating functions to single responsibilities, and return generic error messages — preventing injection attacks that exploit the expanded attack surface of serverless event sources.
Why This Is Best Practice
Adopted by: OWASP Serverless Top 10 SLS-1 (Function Event Data Injection), SLS-9 (Serverless Function Execution Flow Manipulation), and SLS-10 (Improper Exception Handling). AWS Lambda security documentation mandates input validation for all event sources. Palo Alto Unit 42's "Serverless Security: A Deep Dive" (2021) identified event injection as the primary novel attack vector in serverless architectures. Netflix, Airbnb, and Capital One — all heavy Lambda users — treat Lambda event payloads as untrusted input from their first public serverless security guidance.
Impact: Unlike web applications where requests come through a single HTTP gateway, Lambda functions receive events from S3, SQS, SNS, DynamoDB Streams, API Gateway, EventBridge, and IoT — each with a different event schema and different injection surfaces. Palo Alto Unit 42 demonstrated SQL injection via S3 object key names that triggered Lambda functions. The 2022 Lacework serverless threat report found 35% of Lambda vulnerabilities were injection flaws introduced through non-HTTP event sources that developers didn't treat as attack vectors.
Why best: Traditional web input validation (request body + query params) misses serverless-specific injection paths: filenames in S3 events, message bodies in SQS, record data in DynamoDB Streams, and environment variable injection. Treating every event field as untrusted and validating schema at function entry closes these gaps vs. validating only API Gateway parameters.
Sources: OWASP Serverless Top 10 SLS-1, SLS-9, SLS-10; AWS Lambda security best practices; Palo Alto Unit 42 Serverless Security (2021); Lacework Cloud Security Report (2022)
Steps
Validate all event fields regardless of trigger source:
import json
import re
from pydantic import BaseModel, validator
# S3 trigger — validate object key before using in file operations
class S3EventRecord(BaseModel):
bucket_name: str
object_key: str
@validator("object_key")
def no_path_traversal(cls, v):
# S3 keys can contain ../ sequences — validate before using as filesystem path
if ".." in v or v.startswith("/"):
raise ValueError("Invalid object key")
if not re.match(r'^[\w\-./]+$', v):
raise ValueError("Object key contains invalid characters")
return v
def lambda_handler(event, context):
for record in event.get("Records", []):
if record.get("eventSource") == "aws:s3":
try:
validated = S3EventRecord(
bucket_name=record["s3"]["bucket"]["name"],
object_key=record["s3"]["object"]["key"]
)
except Exception as e:
# Log detail internally, return generic error externally
print(f"[ERROR] Invalid S3 event: {e}")
return {"statusCode": 400, "body": "Invalid event"}
process_s3_object(validated.bucket_name, validated.object_key)
Validate SQS message bodies as untrusted input:
import json
from pydantic import BaseModel, constr
class OrderMessage(BaseModel):
order_id: constr(pattern=r'^[0-9a-f-]{36}$') # UUID format only
amount: float
currency: constr(max_length=3, pattern=r'^[A-Z]{3}$')
# Explicit constraint — prevent numeric overflow
@validator("amount")
def amount_range(cls, v):
if v <= 0 or v > 1_000_000:
raise ValueError("Amount out of range")
return v
def process_sqs_event(event, context):
for record in event["Records"]:
try:
body = json.loads(record["body"])
order = OrderMessage(**body)
except Exception as e:
print(f"[ERROR] Malformed SQS message: {e}, MessageId: {record['messageId']}")
# Don't raise — let SQS retry; log for investigation
continue
process_order(order)
Prevent execution flow manipulation — one function, one responsibility:
# BAD — function accepts a "mode" parameter to switch behavior
# Attacker controls execution path
def lambda_handler(event, context):
mode = event.get("mode", "read")
if mode == "admin": # attacker sets mode=admin
return admin_operation()
elif mode == "read":
return read_operation()
# GOOD — separate Lambda functions per operation; API GW route determines which executes
# Function: read-user-lambda (only reads)
def lambda_handler(event, context):
user_id = validate_uuid(event["pathParameters"]["userId"])
return {"statusCode": 200, "body": json.dumps(get_user(user_id))}
# Function: update-user-lambda (only updates, separate IAM role)
def lambda_handler(event, context):
user_id = validate_uuid(event["pathParameters"]["userId"])
body = UserUpdateSchema(**json.loads(event["body"]))
update_user(user_id, body)
return {"statusCode": 200, "body": "{}"}
Secure error handling — no stack traces or internals in responses:
import uuid
import traceback
def lambda_handler(event, context):
error_id = str(uuid.uuid4())
try:
return handle_request(event)
except ValidationError as e:
# User-facing: generic message
return {
"statusCode": 400,
"body": json.dumps({"error": "Invalid request", "error_id": error_id})
}
except Exception as e:
# Internal: full detail to CloudWatch Logs only
print(f"[ERROR] Unhandled exception error_id={error_id}: {traceback.format_exc()}")
return {
"statusCode": 500,
"body": json.dumps({"error": "Internal server error", "error_id": error_id})
}
# error_id lets support correlate logs without exposing internals
Set function timeout and memory to prevent resource exhaustion:
# SAM template / CloudFormation
ProcessOrderFunction:
Type: AWS::Serverless::Function
Properties:
Timeout: 30 # max 30s — prevent hanging on slow upstream
MemorySize: 256 # sufficient for task; prevents runaway memory use
ReservedConcurrencyLimit: 100 # cap concurrent executions
Environment:
Variables:
LOG_LEVEL: INFO # never DEBUG in production
Rules
- Every Lambda trigger source (S3, SQS, SNS, DynamoDB Streams, EventBridge, IoT, Cognito) is an untrusted input surface — validate schema before processing.
- Never use event fields directly in shell commands, SQL queries, or file paths without validation —
subprocess.run(event["command"]) is direct command injection.
- Dead Letter Queues (DLQ) must be configured for async invocations — without DLQ, failed events are silently dropped.
- Function names, ARNs, and environment variable names must not be included in error responses — they aid enumeration.
Common Mistakes
- Validating only API Gateway events — S3, SQS, and DynamoDB Stream events are equally injectable; treat all event sources as untrusted.
- Catching
Exception and returning str(e) — Python exception messages often contain table names, file paths, or SQL snippets; log internally, return generic message externally.
- No DLQ on async-triggered functions — if an S3-triggered Lambda fails, the event is silently lost; configure DLQ to SQS for investigation.
- Large monolithic functions with many code paths — a single Lambda doing read/write/admin based on an event field is SLS-9 (execution flow manipulation); split into separate functions.
1---2name: apply-serverless-function-security3description: Use when writing serverless functions (AWS Lambda, Google Cloud Functions, Azure Functions) — validating event data from all trigger sources, preventing execution flow manipulation, and securing error handling.4source: 'OWASP Serverless Top 10 SLS-1 SLS-9 SLS-10 (owasp.org/www-project-serverless-top-10/); AWS Lambda security documentation; Palo Alto Unit 42 serverless research'5tags: [security, owasp, serverless, lambda, event-injection, cloud, developer]6metadata:7 source: https://skillmd.com/skills/jeffreytse/apply-serverless-function-security8---910# Apply Serverless Function Security1112Validate all event data at function entry regardless of trigger source, prevent execution flow manipulation by isolating functions to single responsibilities, and return generic error messages — preventing injection attacks that exploit the expanded attack surface of serverless event sources.1314## Why This Is Best Practice1516**Adopted by:** OWASP Serverless Top 10 SLS-1 (Function Event Data Injection), SLS-9 (Serverless Function Execution Flow Manipulation), and SLS-10 (Improper Exception Handling). AWS Lambda security documentation mandates input validation for all event sources. Palo Alto Unit 42's "Serverless Security: A Deep Dive" (2021) identified event injection as the primary novel attack vector in serverless architectures. Netflix, Airbnb, and Capital One — all heavy Lambda users — treat Lambda event payloads as untrusted input from their first public serverless security guidance.17**Impact:** Unlike web applications where requests come through a single HTTP gateway, Lambda functions receive events from S3, SQS, SNS, DynamoDB Streams, API Gateway, EventBridge, and IoT — each with a different event schema and different injection surfaces. Palo Alto Unit 42 demonstrated SQL injection via S3 object key names that triggered Lambda functions. The 2022 Lacework serverless threat report found 35% of Lambda vulnerabilities were injection flaws introduced through non-HTTP event sources that developers didn't treat as attack vectors.18**Why best:** Traditional web input validation (request body + query params) misses serverless-specific injection paths: filenames in S3 events, message bodies in SQS, record data in DynamoDB Streams, and environment variable injection. Treating every event field as untrusted and validating schema at function entry closes these gaps vs. validating only API Gateway parameters.1920Sources: OWASP Serverless Top 10 SLS-1, SLS-9, SLS-10; AWS Lambda security best practices; Palo Alto Unit 42 Serverless Security (2021); Lacework Cloud Security Report (2022)2122## Steps23241. **Validate all event fields regardless of trigger source**:2526 ```python27 import json28 import re29 from pydantic import BaseModel, validator3031 # S3 trigger — validate object key before using in file operations32 class S3EventRecord(BaseModel):33 bucket_name: str34 object_key: str3536 @validator("object_key")37 def no_path_traversal(cls, v):38 # S3 keys can contain ../ sequences — validate before using as filesystem path39 if ".." in v or v.startswith("/"):40 raise ValueError("Invalid object key")41 if not re.match(r'^[\w\-./]+$', v):42 raise ValueError("Object key contains invalid characters")43 return v4445 def lambda_handler(event, context):46 for record in event.get("Records", []):47 if record.get("eventSource") == "aws:s3":48 try:49 validated = S3EventRecord(50 bucket_name=record["s3"]["bucket"]["name"],51 object_key=record["s3"]["object"]["key"]52 )53 except Exception as e:54 # Log detail internally, return generic error externally55 print(f"[ERROR] Invalid S3 event: {e}")56 return {"statusCode": 400, "body": "Invalid event"}57 process_s3_object(validated.bucket_name, validated.object_key)58 ```59602. **Validate SQS message bodies as untrusted input**:6162 ```python63 import json64 from pydantic import BaseModel, constr6566 class OrderMessage(BaseModel):67 order_id: constr(pattern=r'^[0-9a-f-]{36}$') # UUID format only68 amount: float69 currency: constr(max_length=3, pattern=r'^[A-Z]{3}$')7071 # Explicit constraint — prevent numeric overflow72 @validator("amount")73 def amount_range(cls, v):74 if v <= 0 or v > 1_000_000:75 raise ValueError("Amount out of range")76 return v7778 def process_sqs_event(event, context):79 for record in event["Records"]:80 try:81 body = json.loads(record["body"])82 order = OrderMessage(**body)83 except Exception as e:84 print(f"[ERROR] Malformed SQS message: {e}, MessageId: {record['messageId']}")85 # Don't raise — let SQS retry; log for investigation86 continue87 process_order(order)88 ```89903. **Prevent execution flow manipulation — one function, one responsibility**:9192 ```python93 # BAD — function accepts a "mode" parameter to switch behavior94 # Attacker controls execution path95 def lambda_handler(event, context):96 mode = event.get("mode", "read")97 if mode == "admin": # attacker sets mode=admin98 return admin_operation()99 elif mode == "read":100 return read_operation()101102 # GOOD — separate Lambda functions per operation; API GW route determines which executes103 # Function: read-user-lambda (only reads)104 def lambda_handler(event, context):105 user_id = validate_uuid(event["pathParameters"]["userId"])106 return {"statusCode": 200, "body": json.dumps(get_user(user_id))}107108 # Function: update-user-lambda (only updates, separate IAM role)109 def lambda_handler(event, context):110 user_id = validate_uuid(event["pathParameters"]["userId"])111 body = UserUpdateSchema(**json.loads(event["body"]))112 update_user(user_id, body)113 return {"statusCode": 200, "body": "{}"}114 ```1151164. **Secure error handling — no stack traces or internals in responses**:117118 ```python119 import uuid120 import traceback121122 def lambda_handler(event, context):123 error_id = str(uuid.uuid4())124 try:125 return handle_request(event)126 except ValidationError as e:127 # User-facing: generic message128 return {129 "statusCode": 400,130 "body": json.dumps({"error": "Invalid request", "error_id": error_id})131 }132 except Exception as e:133 # Internal: full detail to CloudWatch Logs only134 print(f"[ERROR] Unhandled exception error_id={error_id}: {traceback.format_exc()}")135 return {136 "statusCode": 500,137 "body": json.dumps({"error": "Internal server error", "error_id": error_id})138 }139 # error_id lets support correlate logs without exposing internals140 ```1411425. **Set function timeout and memory to prevent resource exhaustion**:143144 ```yaml145 # SAM template / CloudFormation146 ProcessOrderFunction:147 Type: AWS::Serverless::Function148 Properties:149 Timeout: 30 # max 30s — prevent hanging on slow upstream150 MemorySize: 256 # sufficient for task; prevents runaway memory use151 ReservedConcurrencyLimit: 100 # cap concurrent executions152 Environment:153 Variables:154 LOG_LEVEL: INFO # never DEBUG in production155 ```156157## Rules158159- Every Lambda trigger source (S3, SQS, SNS, DynamoDB Streams, EventBridge, IoT, Cognito) is an untrusted input surface — validate schema before processing.160- Never use event fields directly in shell commands, SQL queries, or file paths without validation — `subprocess.run(event["command"])` is direct command injection.161- Dead Letter Queues (DLQ) must be configured for async invocations — without DLQ, failed events are silently dropped.162- Function names, ARNs, and environment variable names must not be included in error responses — they aid enumeration.163164## Common Mistakes165166- **Validating only API Gateway events** — S3, SQS, and DynamoDB Stream events are equally injectable; treat all event sources as untrusted.167- **Catching `Exception` and returning `str(e)`** — Python exception messages often contain table names, file paths, or SQL snippets; log internally, return generic message externally.168- **No DLQ on async-triggered functions** — if an S3-triggered Lambda fails, the event is silently lost; configure DLQ to SQS for investigation.169- **Large monolithic functions with many code paths** — a single Lambda doing read/write/admin based on an event field is SLS-9 (execution flow manipulation); split into separate functions.