⏱ 9 min read 📊 Intermediate 🗓 Updated Jan 2025

⚡ Serverless Security Model

Serverless computing — Lambda, Azure Functions, Cloud Run, Cloudflare Workers — abstracts away the operating system, runtime patching, and server management. But it does not abstract away security. The attack surface changes fundamentally: instead of worrying about SSH access and OS CVEs, you now worry about IAM roles, event injection, dependency vulnerabilities, and the security of every event trigger that can invoke your function.

DimensionTraditional VMContainerServerless
Attack Surface OS, network ports, running processes, SSH, application Container image, exposed ports, K8s API, application Function code, IAM execution role, event triggers, dependencies
Patching Customer responsible for all OS, runtime, app patching Customer responsible for base image and runtime patching Provider patches OS and runtime; customer patches function code and packages
Visibility Full — install any agent, run any tool High — sidecar injection, eBPF, host-level monitoring Limited — ephemeral, millisecond lifetime; no persistent agent possible
IAM Granularity Instance profile; all processes share same IAM identity Pod service account; per-pod IAM possible Per-function execution role; highest IAM granularity — and highest risk if overpermissioned

OWASP Serverless Top 10

The OWASP Serverless Top 10 highlights the unique risks: injection via function event data (SQS, SNS, API Gateway), broken authentication on triggers, insecure third-party dependencies, overpermissioned IAM roles, inadequate logging, insecure secret storage, function execution flow manipulation, over-privileged functions as stepping stones, improper exception handling, and serverless platform-specific vulnerabilities. The common thread is that traditional web app defenses do not fully apply — input can arrive from dozens of event sources, not just HTTP.

🔑 Function IAM & Least Privilege

Overpermissioned Lambda execution roles are the single most common serverless security misconfiguration. Because functions are "small" and "simple," developers often reuse roles with broad permissions across multiple functions — turning a code vulnerability in one function into a full account compromise.

Lambda IAM Anti-Patterns

  • Using a single execution role for all Lambda functions in an account
  • Attaching AdministratorAccess or wildcard S3/DynamoDB permissions
  • Storing secrets in environment variables (visible in Lambda console to anyone with IAM access)
  • Using the same role for development and production Lambdas
  • Not restricting resource-based policies on Lambda (who can invoke it)

Secure Secrets for Serverless

  • AWS SSM Parameter Store: SecureString parameters encrypted with KMS; cheap, simple
  • AWS Secrets Manager: auto-rotation, cross-account access, higher cost; prefer for DB credentials
  • Azure Key Vault + Managed Identity: Functions access Key Vault with no credentials configured
  • GCP Secret Manager + Cloud Run SA: attach SA with secretmanager.secretAccessor role to Cloud Run service
  • Cache secrets in memory for the function lifetime to reduce API calls; re-fetch on rotation

Least-Privilege Lambda Execution Role Policy

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AllowSpecificDynamoDBAccess",
      "Effect": "Allow",
      "Action": [
        "dynamodb:GetItem",
        "dynamodb:PutItem",
        "dynamodb:UpdateItem"
      ],
      "Resource": "arn:aws:dynamodb:us-east-1:123456789012:table/OrdersTable"
    },
    {
      "Sid": "AllowSecretsManagerRead",
      "Effect": "Allow",
      "Action": "secretsmanager:GetSecretValue",
      "Resource": "arn:aws:secretsmanager:us-east-1:123456789012:secret:prod/orders-db-*"
    },
    {
      "Sid": "AllowCloudWatchLogs",
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": "arn:aws:logs:us-east-1:123456789012:log-group:/aws/lambda/order-processor:*"
    },
    {
      "Sid": "AllowXRayTracing",
      "Effect": "Allow",
      "Action": [
        "xray:PutTraceSegments",
        "xray:PutTelemetryRecords"
      ],
      "Resource": "*"
    }
  ]
}

💡 Serverless-Specific Attack Vectors

Serverless applications introduce attack vectors that simply do not exist in traditional web applications. Every event source that can trigger a function is a potential injection point — and functions are often designed to implicitly trust the data in those events, assuming the event bus itself is the security boundary.

Event Injection

Unlike web apps where input arrives over HTTP, serverless functions receive events from queues, streams, databases, and storage buckets. Developers often forget to validate this "trusted" input.

  • SQS/SNS message body containing SQL injection or command injection
  • S3 event notification with a malicious filename triggering path traversal
  • DynamoDB Streams event with crafted data exploiting deserialization flaws
  • API Gateway body is user-controlled — validate schema strictly before processing
  • EventBridge events from third-party SaaS may contain adversary-controlled data

Dependency & Supply Chain Attacks

Lambda deployment packages bundle all dependencies. A single malicious or compromised npm/PyPI package in your function code has the same AWS permissions as your function's execution role.

  • Dependency confusion: attacker publishes malicious package matching internal name
  • Typosquatting: requets instead of requests
  • Compromised maintainer: legitimate package with malicious update
  • Pin all dependencies to specific versions with hash verification (pip --require-hashes)
  • Scan packages with Snyk, OWASP Dependency-Check, or AWS Inspector in CI/CD

Function Abuse & DoS

  • Excessive timeouts: attacker triggers long-running functions to exhaust concurrency limits (Lambda default: 1000 concurrent)
  • Recursive invocation: function mistakenly triggers itself — Lambda has circuit breaker, but costs explode
  • Unauthenticated API Gateway: missing auth → public endpoint → function invocable by anyone
  • Set concurrency limits per function; use reserved concurrency for critical functions
  • API Gateway throttling: set usage plans and rate limits on all public APIs

📊 Serverless Monitoring & Observability

Observability in serverless is harder than in traditional environments. Functions are ephemeral — a 100ms invocation doesn't have time for traditional agent-based monitoring. The goal is to extract maximum signal from logs, traces, and metrics within the constraints of the execution model.

Monitoring NeedAWS ToolAzure ToolGCP Tool
Distributed Tracing AWS X-Ray: trace request flow across Lambda, API Gateway, DynamoDB, SQS Application Insights: distributed tracing with dependency mapping Cloud Trace: distributed tracing integrated with Cloud Run and Cloud Functions
Performance Metrics Lambda Insights (CloudWatch): memory, duration, cold starts, init duration Azure Monitor metrics: function execution, failures, duration dashboards Cloud Monitoring: Cloud Run metrics, Cloud Functions execution metrics
Log Analytics CloudWatch Logs Insights: SQL-like queries across function log groups Log Analytics workspace: KQL queries across all Function App logs Cloud Logging + Log Analytics: BigQuery-backed log analysis
Threat Detection GuardDuty Lambda Protection: detects malicious network calls from Lambda Defender for App Service: anomalous behavior, outbound connections Cloud Run threat detection via SCC Event Threat Detection
Third-Party APM Datadog Serverless, Lumigo (OpenTelemetry-native), Thundra/Catchpoint — all work across clouds; provide cold start analysis, end-to-end tracing, and anomaly detection with no code changes via Lambda extensions or sidecars

Security Logging Requirements

  • Log all function invocations with request ID, source IP (if API-triggered), and caller identity
  • Log all external API calls made by the function with destination, status, and latency
  • Never log secret values, PII, or full request bodies containing sensitive data
  • Enable CloudTrail data events for Lambda invocations for compliance audit trails
  • Set log retention policies — avoid perpetual retention of high-volume function logs

GuardDuty Lambda Protection

GuardDuty Lambda Protection (AWS) analyzes network activity from Lambda functions using VPC Flow Logs. It detects functions making calls to known malicious IPs, C2 servers, or cryptocurrency mining pools — indicating a compromise via code execution from injected event data.

  • Requires enabling Lambda Protection in GuardDuty settings
  • Works with and without VPC-attached Lambda functions
  • Finding: CryptoCurrency:Lambda/BitcoinTool.B
  • Finding: Backdoor:Lambda/C&CActivity.B

✅ Serverless Security Best Practices

Serverless security best practices reflect the shifted responsibility model: you can no longer rely on network perimeter controls or OS hardening. The security controls that matter most are code quality, IAM least privilege, input validation, and dependency integrity.

Function Design Principles

  • One function, one purpose: single responsibility minimizes the blast radius of any execution role
  • Validate all input: treat every event field as untrusted user input — no exceptions
  • Fail fast on schema violation: use JSON Schema or Pydantic to reject malformed events immediately
  • Set tight timeouts: if your function should run in 5s, set timeout to 8s — not 15 minutes
  • Memory limits: right-size memory allocation; Lambda performance scales with memory setting

Dependency Security

  • Pin all package versions — never use >= or * version specifiers in production
  • Use a package lock file and commit it (package-lock.json, poetry.lock, Pipfile.lock)
  • Separate Lambda Layers for runtime dependencies vs application code — easier to patch
  • Scan packages in CI before deploying; block deployment if critical CVEs present
  • Use AWS CodeArtifact, Azure Artifacts, or GCP Artifact Registry as proxy to cache and audit packages

VPC & Network Controls

  • Place Lambda inside a VPC only when it needs to access VPC resources (RDS, ElastiCache)
  • VPC-attached Lambda: use NAT Gateway for outbound internet (not VPC Endpoint for everything)
  • Use VPC Endpoints to access S3, SSM, Secrets Manager without internet traversal
  • Security groups on Lambda ENIs: restrict outbound to only required destinations and ports
  • Cloud Run: use VPC Serverless Access Connector for private resource access

API Gateway Security

  • Require authentication on all API Gateway endpoints — no anonymous invocation
  • Use AWS IAM auth, Lambda authorizers (JWT/OAuth), or Amazon Cognito User Pools
  • Enable API Gateway WAF to filter malicious payloads before they reach Lambda
  • Rate limit per API key and per IP — protect against abuse and DoS
  • Validate request body schema at the API Gateway level using request validators

Security Scanning in CI/CD

  • Checkov: static analysis of Serverless Framework, SAM, CDK templates for IAM misconfigurations
  • Prowler: AWS security checks including Lambda-specific rules
  • Snyk: dependency vulnerability scanning in Lambda packages and container images
  • Semgrep: code-level SAST rules for serverless-specific patterns (hardcoded secrets, unvalidated input)
  • PureSec CLI (now part of Prisma Cloud): serverless-specific static analysis

Serverless Does Not Mean Security-Free

The most dangerous misconception about serverless is that "the cloud provider handles security." AWS manages the runtime, but you own the function code, the IAM role, the event triggers, and every dependency you package. A serverless application with an overpermissioned Lambda role, unvalidated SQS input, and a vulnerable npm package is just as breachable as an unpatched EC2 instance — and often harder to detect because the attack surface is distributed across dozens of event sources rather than a single network endpoint.

AWS Lambda Azure Functions Cloud Run Event Injection IAM Least Privilege GuardDuty Lambda X-Ray OWASP Serverless Top 10