0Pricing
Cloud & IT Cert Prep · Lesson

Serverless and Function Security

Identify the unique attack surface of serverless functions (over-privileged IAM roles, event injection, dependency risks) and apply least-privilege and input validation controls.

Serverless and Function Security is a free Cloud & IT Cert Prep lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Cloud & IT Cert Prep learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What Is Serverless Computing?

Serverless computing (Functions as a Service, FaaS) allows developers to deploy individual functions that are invoked by events — HTTP requests, queue messages, database triggers, or scheduled timers — without managing the underlying servers. Leading platforms include AWS Lambda, Google Cloud Functions, and Azure Functions. The cloud provider manages patching, scaling, and infrastructure. While this reduces operational burden, it shifts the security responsibility model: the provider secures the runtime, but the developer is solely responsible for function code, permissions, and configuration.

Unique Serverless Attack Surface

Serverless functions present a distinct attack surface compared to traditional applications: functions are typically short-lived (seconds to minutes), making traditional EDR and network monitoring less effective; they are event-driven, meaning many different input sources (S3 events, API Gateway, SNS) can trigger execution; they often run with IAM permissions that can access other cloud resources; and they consume third-party dependencies (npm, pip packages) that may contain malicious code. The attack surface is defined by event inputs, IAM permissions, and dependency trust chains.

Over-Privileged IAM Roles: The Top Threat

The most common serverless security vulnerability is over-privileged IAM roles. When developers need a function to access one S3 bucket, it is tempting to assign s3:* (full S3 access) to avoid permission errors. A compromised or vulnerable function with this role can then read, write, or delete any bucket in the account. The defense is strict least-privilege IAM roles: each function should have a dedicated role granting only the minimum permissions required for that specific function's specific tasks. Tools like AWS IAM Access Analyzer and Cloudsplaining identify over-privileged Lambda roles automatically.

# IAM policy: least privilege for specific Lambda function
{
  'Version': '2012-10-17',
  'Statement': [{
    'Effect': 'Allow',
    'Action': ['s3:GetObject'],
    'Resource': 'arn:aws:s3:::my-specific-bucket/uploads/*'
  }]
}

Event Injection Attacks

Event injection occurs when attacker-controlled data in an event payload is processed unsafely by the function code. Since serverless functions can be triggered by many event sources — HTTP headers, query parameters, database change records, queue message bodies, email content — any of these can carry malicious payloads. Common injection types include: SQL injection if the function queries a database using event data, NoSQL injection (MongoDB operators in JSON payloads), command injection if event data is used in OS commands, and SSRF (Server-Side Request Forgery) if URLs from event data are fetched. Input validation and parameterized queries are essential defenses.

# Vulnerable: event data used directly in shell command
# const filename = event.filename;
# exec('convert ' + filename + ' output.jpg');

# Safe: validate and sanitize input
# const filename = path.basename(event.filename);
# if (!/^[a-z0-9_-]+\.(jpg|png)$/i.test(filename)) throw new Error('Invalid');
# execFile('convert', [filename, 'output.jpg']);

Dependency Risk: Third-Party Packages

Serverless functions frequently depend on dozens of third-party packages. These dependencies introduce supply chain risk: a malicious or compromised package can execute arbitrary code within the function's execution environment, access environment variables (which often contain secrets), make outbound network connections, and use the function's IAM role to access cloud resources. High-profile attacks like the event-stream npm package compromise (2018) and numerous typosquatting packages demonstrate this risk. Defenses include dependency pinning, SCA scanning in CI/CD, and minimal dependency footprints.

Secrets in Serverless: Environment Variables

Serverless functions often receive secrets through environment variables configured in the cloud console. These environment variables are visible to anyone with IAM access to the Lambda configuration and can be accessed by any code running within the function. Best practices: avoid storing secrets directly as plaintext environment variables; instead, store ARNs or secret names and retrieve secrets at runtime from AWS Secrets Manager or Parameter Store; enable KMS encryption for Lambda environment variables at rest; and never log environment variables (many debug loggers dump all env vars on error).

# Retrieve secret at runtime instead of hardcoding
# Using AWS SDK in Lambda
# const secretsClient = new SecretsManagerClient({});
# const response = await secretsClient.send(
#   new GetSecretValueCommand({ SecretId: 'prod/myapp/db-password' })
# );
# const dbPassword = response.SecretString;

Function Timeout and Concurrency Limits

Denial of service against serverless functions can take the form of invocation flooding — an attacker who can trigger a function repeatedly may exhaust the account's concurrency limit (Lambda's default is 1,000 concurrent executions per region), making other functions in the account unable to execute. Functions processing user-controlled input should implement rate limiting at the API Gateway level, validate payload size limits, and set appropriate timeout values to prevent runaway executions. Functions can also be targeted by Billion Laughs-style expansion attacks in XML/YAML parsing if input is not size-limited.

# AWS Lambda: set reserved concurrency to prevent account-wide DoS
aws lambda put-function-concurrency \
  --function-name my-api-handler \
  --reserved-concurrent-executions 100

VPC Integration and Network Isolation

By default, AWS Lambda functions run in an AWS-managed VPC with internet access but no access to resources in your private VPC (RDS databases, ElastiCache, private APIs). To access private resources, Lambda must be configured to run inside your VPC with specific subnets and security groups. However, VPC-attached Lambda functions do not have internet access by default — they need a NAT Gateway for outbound internet. Security groups attached to Lambda functions should follow least-privilege rules: allow only the specific ports and destinations required. Avoid using 0.0.0.0/0 outbound rules on production function security groups.

Monitoring Serverless Functions

Monitoring serverless security requires different approaches than traditional host monitoring. Since functions are ephemeral, host-based agents are impractical. Effective monitoring uses: AWS CloudTrail to log all Lambda API calls (invocations, configuration changes, role assumptions); CloudWatch Logs Insights to query function execution logs for anomalous patterns; Amazon GuardDuty for threat detection including unusual Lambda network activity; and commercial serverless-native security tools like Protego (now part of Check Point) or Datadog's serverless monitoring that instrument functions via layers to provide runtime visibility.

# Query CloudWatch Logs for Lambda errors and anomalies
aws logs start-query \
  --log-group-name '/aws/lambda/my-function' \
  --start-time $(date -d '-1 hour' +%s) \
  --end-time $(date +%s) \
  --query-string 'fields @timestamp, @message | filter @message like /ERROR|WARN|credential/'

Serverless Security Testing

Testing serverless security requires specific tooling: PureSec CLI (now Check Point) and Prowler scan cloud configurations for serverless misconfigurations; DAST tools can test HTTP-triggered functions for injection vulnerabilities; static analysis of function code with tools like Bandit (Python) or ESLint security plugins catches insecure coding patterns; and manual testing should enumerate all event sources that can trigger each function and test each with malformed and malicious payloads. The OWASP Serverless Top 10 provides a comprehensive vulnerability checklist specific to serverless architectures.

# Prowler: check Lambda security posture
prowler aws --service lambda
# Checks: public URL, over-privileged roles, unencrypted env vars,
# outdated runtime, missing VPC config, excessive timeout

Shared Responsibility in Serverless

Serverless computing extends the shared responsibility model further toward the provider. The cloud provider is responsible for: the function runtime environment, OS patches, underlying infrastructure security, and physical facilities. The customer remains responsible for: function code security, IAM permission design, secret management, input validation, dependency management, logging configuration, and network policies. The reduced infrastructure responsibility does not mean reduced security responsibility — it merely shifts where security investment should focus, primarily toward application-level and IAM security.

Quick Check

Test your understanding of CompTIA Security+ (SY0-701) concepts from this lesson.

Lesson Recap

In this lesson you learned: over-privileged IAM roles are the primary serverless risk — each function needs a dedicated least-privilege role, event injection attacks exploit any event source that delivers attacker-controlled data to functions lacking input validation, and dependency supply chain risk from third-party packages can compromise function execution with access to IAM credentials and secrets. Next up we explore Infrastructure as Code security scanning to catch misconfigurations before deployment.

Frequently asked questions

Is the “Serverless and Function Security” lesson free?

Yes — the full text of “Serverless and Function Security” is free to read here on the web, and the Cloud & IT Cert Prep course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Cloud & IT Cert Prep course, upgrade to CoddyKit PRO.

What will I learn in “Serverless and Function Security”?

Identify the unique attack surface of serverless functions (over-privileged IAM roles, event injection, dependency risks) and apply least-privilege and input validation controls. You practise Cloud & IT Cert Prep with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Cloud & IT Cert Prep?

No prior experience is required. Cloud & IT Cert Prep on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Serverless and Function Security” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Cloud & IT Cert Prep lesson?

Yes. Every Cloud & IT Cert Prep lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Container Security: Image Hardening and Runtime Protection
  2. Kubernetes Security: RBAC, Network Policies, and Pod Security
  3. Serverless and Function Security
  4. Infrastructure as Code Security Scanning
← Back to Cloud & IT Cert Prep