Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 38 ยท Container and Serverless Security

Serverless Security

Secure serverless functions: per-function least privilege, event input validation, secrets, dependency risk, denial of wallet and logging, with runnable examples.

Serverless platforms such as AWS Lambda, Azure Functions and Google Cloud Functions run your code in response to events without you managing servers. The provider patches the operating system, isolates tenants and scales for you. That removes a whole class of work, but not the risks that live in your code, your permissions and your configuration. Attackers simply shift their focus: instead of attacking a server, they attack the function's inputs, its role and its dependencies.

In this lesson you will see how responsibility is split, what the main serverless risks are and how to reduce each of them. Cloud configuration is shown as read-only examples; the runnable code is Python that you can try in the browser.

All examples use made-up resources and run only in your browser. Test serverless functions only in accounts you own or are authorised to assess.

What changes with serverless

You no longer manage You still manage
Operating system patches Function code and dependencies
Host hardening The function's IAM role (permissions)
Capacity and scaling Event sources and who can trigger the function
Runtime isolation Secrets and configuration
Logging, alerting and cost controls

Many triggers also widen the attack surface: an HTTP gateway, a queue message, a file uploaded to object storage, a database change stream, a scheduled timer. Each of these is an input that an attacker may influence, directly or through someone else's data.

flowchart LR
    E1["HTTP API"] --> F["Function"]
    E2["Queue message"] --> F
    E3["File upload event"] --> F
    E4["Schedule"] --> F
    F --> D[("Database")]
    F --> S["Object storage"]
    F --> X["Other cloud APIs"]

Every trigger is an input to validate; every arrow out is a permission to limit.

Risk 1: over-privileged roles

The most common serverless weakness is a role that is far broader than the function needs. A function that reads one table does not need dynamodb:* on every table, and it never needs iam:*. If the function is compromised (through a vulnerable dependency or an injection bug), its role defines the blast radius.

Give every function its own role, grant only the actions it needs and scope them to specific resources. A read-only example in AWS IAM syntax:

JSON
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": ["dynamodb:GetItem", "dynamodb:Query"],
      "Resource": "arn:aws:dynamodb:eu-west-1:111122223333:table/orders"
    }
  ]
}

For more on policy design, see the identity and access chapter of this course (track page).

Try it: an over-permission checker

This stand-in reads a policy (as Python data) and flags wildcards and dangerous actions, as a policy analyser would.

Python Flag overly broad function permissions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Statement 1 is clean. Statements 2 and 3 produce findings: full S3 access to everything, and actions that let a compromised function create new access keys or pass roles to other services.

Risk 2: event injection

Because functions do not sit behind a classic web server, developers sometimes forget that event data is untrusted. A filename from a storage event, a JSON field from a queue message or a query string parameter can carry SQL, shell commands or path tricks. The classic fix applies: validate input against an allow-list and use safe APIs (parameterised queries, no shell calls, no string-built paths).

Try it: validating an event

Python Validate an event before using it

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Three of the four events are rejected for different reasons: an injection attempt in order_id, a path traversal in filename and an unexpected key plus an unsupported action. This is exactly why shift-left practices include input validation tests in the pipeline.

Risk 3: dependencies and the supply chain

A small function often imports dozens of packages. One compromised or vulnerable package runs with the function's role. Pin versions with a lock file, scan dependencies on every build, keep the dependency list small and remove unused packages. Layers and shared libraries need the same care. More in supply chain and SBOM.

Risk 4: secrets and configuration

Do not put secrets in environment variables that are visible to everyone who can read the function configuration, and never in code. Fetch them at start-up from a secret manager (AWS Secrets Manager, Azure Key Vault, Google Secret Manager) using the function's role, cache them for the life of the container and rotate them. Encrypt environment variables with a customer-managed key when they must hold sensitive values.

Risk 5: denial of wallet and abuse

Serverless scales automatically, so an attacker or a runaway loop can scale your bill instead of crashing your server. Put limits in place:

  • Concurrency limits per function and per account.
  • Throttling and quotas at the API gateway; authentication on every route that is not meant to be public.
  • Timeouts and memory set as low as the function really needs.
  • Budget alarms with alerts and, where possible, automatic action.
  • Loop protection: a function that writes to the bucket that triggers it will trigger itself endlessly. Use separate buckets or prefix filters.

Risk 6: logging and visibility

Short-lived functions leave no host to inspect afterwards, so logs are your evidence. Send logs to a central, protected place, include a request ID in every line, never log secrets or full personal data, and enable the provider's audit trail for configuration changes. See cloud logging and audit trails.

A hardening checklist for every function

  1. One role per function, with specific actions and resources.
  2. Validate every event field; reject by default.
  3. Authenticate and authorise API calls; do not rely on obscure URLs.
  4. Pin and scan dependencies; keep the package small.
  5. Load secrets from a secret manager; keep them out of code and logs.
  6. Set timeout, memory and concurrency limits and a budget alarm.
  7. Keep functions in a private network (VPC) only when they must reach private resources, and then restrict egress.
  8. Ship logs centrally and alert on errors, throttles and unusual invocations.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Who patches the operating system under a serverless function?

    The provider manages the OS and runtime host. You remain responsible for code, dependencies, permissions and configuration.
  2. 2. Why should every function have its own IAM role?

    A shared role accumulates the permissions of every function that uses it. A per-function role keeps permissions minimal and limits damage.
  3. 3. A storage event passes a filename to your function. How should you treat it?

    The content of events, such as filenames, can be chosen by an attacker. Validate against an allow-list and avoid shell commands and string-built paths.
  4. 4. What is a 'denial of wallet' attack?

    Automatic scaling means abusive traffic costs money instead of causing an outage. Concurrency limits, throttling and budgets reduce the risk.

Summary

  • Serverless moves OS and host security to the provider; code, roles, events, secrets and cost controls remain yours.
  • Give each function a minimal, resource-scoped role and look for wildcards and escalation actions.
  • Treat every event field as untrusted input and validate it with allow-lists.
  • Scan and pin dependencies, store secrets in a manager and set limits against denial of wallet.
  • Log centrally so short-lived functions still leave evidence.

Next: Cloud Logging and Audit Trails