Ajoute 16 skills de sécurité (sélection web/API)
Tirés de mukul975/anthropic-cybersecurity-skills (commit 54a7988, Apache-2.0) : contrôle d'accès/IDOR, en-têtes et CSP, CORS, OAuth, JWT, XSS, fonctions serverless, rate limiting, paquets npm, gitleaks, RGPD, OWASP API Top 10. Les 800 autres (offensifs, Windows/AD, forensique…) sont laissés de côté. Voir .claude/skills/README.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YVo1qxKoBQCaMd7Ue8PGbe
This commit is contained in:
74 files changed
+14803
No files matched your search
@@ -0,0 +1,201 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to the Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by the Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding any notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. Please do not remove or change
|
||||
the license header comment from a contributed file except when
|
||||
necessary.
|
||||
|
||||
Copyright 2026 mukul975
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,329 @@
|
||||
---
|
||||
name: securing-serverless-functions
|
||||
description: 'Hardens serverless compute platforms (AWS Lambda, Azure Functions, Google
|
||||
Cloud Functions): least-privilege IAM roles, dependency vulnerability scanning,
|
||||
secrets management integration, input validation, function URL authentication, and
|
||||
runtime monitoring. Use when deploying serverless functions with sensitive access,
|
||||
auditing for overly permissive roles, or adding functions to a DevSecOps pipeline.
|
||||
|
||||
'
|
||||
domain: cybersecurity
|
||||
subdomain: cloud-security
|
||||
tags:
|
||||
- serverless-security
|
||||
- aws-lambda
|
||||
- azure-functions
|
||||
- function-hardening
|
||||
- supply-chain
|
||||
version: 1.0.0
|
||||
author: mahipal
|
||||
license: Apache-2.0
|
||||
nist_csf:
|
||||
- PR.IR-01
|
||||
- ID.AM-08
|
||||
- GV.SC-06
|
||||
- DE.CM-01
|
||||
mitre_attack:
|
||||
- T1078.004
|
||||
- T1530
|
||||
- T1537
|
||||
- T1580
|
||||
- T1003
|
||||
---
|
||||
|
||||
# Securing Serverless Functions
|
||||
|
||||
## When to Use
|
||||
|
||||
- When deploying Lambda functions or Azure Functions with access to sensitive data or cloud APIs
|
||||
- When auditing existing serverless workloads for overly permissive IAM roles
|
||||
- When integrating serverless functions into a DevSecOps pipeline with automated security scanning
|
||||
- When hardcoded secrets or vulnerable dependencies are discovered in function code
|
||||
- When establishing runtime monitoring for serverless workloads to detect injection or credential theft
|
||||
|
||||
**Do not use** for container-based compute security (see securing-kubernetes-on-cloud), for API Gateway configuration (see implementing-cloud-waf-rules), or for serverless architecture design decisions.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- AWS Lambda, Azure Functions, or GCP Cloud Functions with deployment access
|
||||
- CI/CD pipeline with dependency scanning tools (npm audit, Snyk, Dependabot)
|
||||
- AWS Secrets Manager, Azure Key Vault, or HashiCorp Vault for secrets management
|
||||
- CloudWatch, Application Insights, or Cloud Logging for function monitoring
|
||||
|
||||
## Workflow
|
||||
|
||||
### Step 1: Enforce Least Privilege IAM Roles
|
||||
|
||||
Assign each Lambda function a dedicated IAM role with permissions scoped to only the specific resources it accesses. Never share IAM roles across functions.
|
||||
|
||||
```bash
|
||||
# Create a least-privilege role for a specific Lambda function
|
||||
aws iam create-role \
|
||||
--role-name order-processor-lambda-role \
|
||||
--assume-role-policy-document '{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [{
|
||||
"Effect": "Allow",
|
||||
"Principal": {"Service": "lambda.amazonaws.com"},
|
||||
"Action": "sts:AssumeRole"
|
||||
}]
|
||||
}'
|
||||
|
||||
# Attach a scoped policy (not AmazonDynamoDBFullAccess)
|
||||
aws iam put-role-policy \
|
||||
--role-name order-processor-lambda-role \
|
||||
--policy-name order-processor-policy \
|
||||
--policy-document '{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["dynamodb:PutItem", "dynamodb:GetItem"],
|
||||
"Resource": "arn:aws:dynamodb:us-east-1:123456789012:table/Orders"
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents"],
|
||||
"Resource": "arn:aws:logs:us-east-1:123456789012:log-group:/aws/lambda/order-processor:*"
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["secretsmanager:GetSecretValue"],
|
||||
"Resource": "arn:aws:secretsmanager:us-east-1:123456789012:secret:order-api-key-*"
|
||||
}
|
||||
]
|
||||
}'
|
||||
```
|
||||
|
||||
### Step 2: Eliminate Hardcoded Secrets
|
||||
|
||||
Replace plaintext credentials in environment variables with references to secrets management services. Use Lambda extensions or SDK calls to retrieve secrets at runtime.
|
||||
|
||||
```python
|
||||
# INSECURE: Hardcoded credentials in environment variable
|
||||
# DB_PASSWORD = os.environ['DB_PASSWORD'] # Stored as plaintext in Lambda config
|
||||
|
||||
# SECURE: Retrieve from AWS Secrets Manager with caching
|
||||
import boto3
|
||||
from botocore.exceptions import ClientError
|
||||
import json
|
||||
|
||||
_secret_cache = {}
|
||||
|
||||
def get_secret(secret_name):
|
||||
if secret_name in _secret_cache:
|
||||
return _secret_cache[secret_name]
|
||||
|
||||
client = boto3.client('secretsmanager')
|
||||
response = client.get_secret_value(SecretId=secret_name)
|
||||
secret = json.loads(response['SecretString'])
|
||||
_secret_cache[secret_name] = secret
|
||||
return secret
|
||||
|
||||
def lambda_handler(event, context):
|
||||
db_creds = get_secret('production/database/credentials')
|
||||
db_host = db_creds['host']
|
||||
db_password = db_creds['password']
|
||||
# Use credentials securely
|
||||
```
|
||||
|
||||
```bash
|
||||
# Enable encryption at rest for Lambda environment variables
|
||||
aws lambda update-function-configuration \
|
||||
--function-name order-processor \
|
||||
--kms-key-arn arn:aws:kms:us-east-1:123456789012:key/key-id
|
||||
```
|
||||
|
||||
### Step 3: Scan Dependencies for Vulnerabilities
|
||||
|
||||
Integrate automated dependency scanning into the CI/CD pipeline to catch vulnerable packages before deployment.
|
||||
|
||||
```bash
|
||||
# npm audit for Node.js Lambda functions
|
||||
cd lambda-function/
|
||||
npm audit --audit-level=high
|
||||
npm audit fix
|
||||
|
||||
# Snyk scanning in CI/CD pipeline
|
||||
snyk test --severity-threshold=high
|
||||
snyk monitor --project-name=order-processor-lambda
|
||||
|
||||
# pip-audit for Python Lambda functions
|
||||
pip-audit -r requirements.txt --desc on --fix
|
||||
|
||||
# Scan Lambda deployment package with Trivy
|
||||
trivy fs --severity HIGH,CRITICAL ./lambda-package/
|
||||
```
|
||||
|
||||
```yaml
|
||||
# GitHub Actions CI/CD security scanning
|
||||
name: Lambda Security Scan
|
||||
on: [push, pull_request]
|
||||
jobs:
|
||||
security:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
- name: Run npm audit
|
||||
run: npm audit --audit-level=high
|
||||
- name: Snyk vulnerability scan
|
||||
uses: snyk/actions/node@master
|
||||
env:
|
||||
SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
|
||||
- name: Scan with Semgrep for code vulnerabilities
|
||||
uses: returntocorp/semgrep-action@v1
|
||||
with:
|
||||
config: p/owasp-top-ten
|
||||
```
|
||||
|
||||
### Step 4: Implement Input Validation
|
||||
|
||||
Validate and sanitize all event input data to prevent injection attacks including SQL injection, command injection, and NoSQL injection through Lambda event sources.
|
||||
|
||||
```python
|
||||
import re
|
||||
import json
|
||||
from jsonschema import validate, ValidationError
|
||||
|
||||
# Define expected input schema
|
||||
ORDER_SCHEMA = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"orderId": {"type": "string", "pattern": "^[a-zA-Z0-9-]{1,36}$"},
|
||||
"customerId": {"type": "string", "pattern": "^[a-zA-Z0-9]{1,20}$"},
|
||||
"amount": {"type": "number", "minimum": 0.01, "maximum": 999999.99},
|
||||
"currency": {"type": "string", "enum": ["USD", "EUR", "GBP"]}
|
||||
},
|
||||
"required": ["orderId", "customerId", "amount", "currency"],
|
||||
"additionalProperties": False
|
||||
}
|
||||
|
||||
def lambda_handler(event, context):
|
||||
# Validate API Gateway event body
|
||||
try:
|
||||
body = json.loads(event.get('body', '{}'))
|
||||
validate(instance=body, schema=ORDER_SCHEMA)
|
||||
except (json.JSONDecodeError, ValidationError) as e:
|
||||
return {
|
||||
'statusCode': 400,
|
||||
'body': json.dumps({'error': 'Invalid input', 'details': str(e)})
|
||||
}
|
||||
|
||||
# Safe to proceed with validated input
|
||||
order_id = body['orderId']
|
||||
# Use parameterized queries for database operations
|
||||
```
|
||||
|
||||
### Step 5: Configure Function URL and API Gateway Authentication
|
||||
|
||||
Secure function invocation endpoints with proper authentication. Never expose Lambda function URLs without IAM or Cognito authentication.
|
||||
|
||||
```bash
|
||||
# Secure Lambda function URL with IAM auth (not NONE)
|
||||
aws lambda create-function-url-config \
|
||||
--function-name order-processor \
|
||||
--auth-type AWS_IAM \
|
||||
--cors '{
|
||||
"AllowOrigins": ["https://app.company.com"],
|
||||
"AllowMethods": ["POST"],
|
||||
"AllowHeaders": ["Content-Type", "Authorization"],
|
||||
"MaxAge": 3600
|
||||
}'
|
||||
|
||||
# API Gateway with Cognito authorizer
|
||||
aws apigateway create-authorizer \
|
||||
--rest-api-id abc123 \
|
||||
--name CognitoAuth \
|
||||
--type COGNITO_USER_POOLS \
|
||||
--provider-arns "arn:aws:cognito-idp:us-east-1:123456789012:userpool/us-east-1_EXAMPLE"
|
||||
```
|
||||
|
||||
### Step 6: Enable Runtime Monitoring and Logging
|
||||
|
||||
Configure GuardDuty Lambda Network Activity Monitoring and CloudWatch structured logging to detect anomalous function behavior.
|
||||
|
||||
```bash
|
||||
# Enable GuardDuty Lambda protection
|
||||
aws guardduty update-detector \
|
||||
--detector-id <detector-id> \
|
||||
--features '[{"Name": "LAMBDA_NETWORK_ACTIVITY_LOGS", "Status": "ENABLED"}]'
|
||||
|
||||
# Configure Lambda to use structured logging
|
||||
aws lambda update-function-configuration \
|
||||
--function-name order-processor \
|
||||
--logging-config '{"LogFormat": "JSON", "ApplicationLogLevel": "INFO", "SystemLogLevel": "WARN"}'
|
||||
```
|
||||
|
||||
## Key Concepts
|
||||
|
||||
| Term | Definition |
|
||||
|------|------------|
|
||||
| Cold Start | Initial function invocation that includes container provisioning, increasing latency and creating a window where cached secrets may not be available |
|
||||
| Event Injection | Attack where malicious input is embedded in Lambda event data from API Gateway, S3, SQS, or other event sources to exploit the function |
|
||||
| Execution Role | IAM role assumed by Lambda during execution, defining all cloud API permissions the function can use |
|
||||
| Function URL | Direct HTTPS endpoint for Lambda functions that can be configured with IAM or no authentication (NONE is insecure) |
|
||||
| Layer | Lambda deployment package containing shared code or dependencies that should be scanned for vulnerabilities independently |
|
||||
| Reserved Concurrency | Maximum number of concurrent executions for a function, useful for preventing resource exhaustion attacks |
|
||||
| Provisioned Concurrency | Pre-initialized function instances that reduce cold start latency and ensure secrets are cached |
|
||||
|
||||
## Tools & Systems
|
||||
|
||||
- **AWS Lambda Power Tuning**: Open-source tool for optimizing Lambda memory and timeout settings to balance security with performance
|
||||
- **Snyk**: SCA tool scanning Lambda dependencies for known vulnerabilities with automatic fix suggestions
|
||||
- **Semgrep**: SAST tool with serverless-specific rules detecting injection vulnerabilities, hardcoded secrets, and insecure configurations
|
||||
- **GuardDuty Lambda Protection**: AWS service monitoring Lambda network activity for connections to malicious endpoints
|
||||
- **AWS X-Ray**: Distributed tracing service for detecting suspicious external connections and latency anomalies in Lambda invocations
|
||||
|
||||
## Common Scenarios
|
||||
|
||||
### Scenario: SQL Injection via API Gateway to Lambda to RDS
|
||||
|
||||
**Context**: A Lambda function receives user input from API Gateway and constructs SQL queries by string concatenation against an RDS PostgreSQL database. An attacker injects SQL payloads through the API.
|
||||
|
||||
**Approach**:
|
||||
1. Audit the Lambda function code for string concatenation in SQL queries
|
||||
2. Replace all string-formatted queries with parameterized queries using the database driver
|
||||
3. Implement input validation using JSON Schema before any database operation
|
||||
4. Add a WAF rule on API Gateway to block common SQL injection patterns
|
||||
5. Deploy Semgrep in the CI/CD pipeline with the `python.django.security.injection.sql` rule set
|
||||
6. Enable GuardDuty Lambda protection to detect anomalous database connection patterns
|
||||
|
||||
**Pitfalls**: Relying solely on WAF rules without fixing the underlying code vulnerability allows attackers to bypass with encoding tricks. Using ORM methods incorrectly (raw queries) still allows injection.
|
||||
|
||||
## Output Format
|
||||
|
||||
```
|
||||
Serverless Security Assessment Report
|
||||
=======================================
|
||||
Account: 123456789012
|
||||
Functions Assessed: 47
|
||||
Assessment Date: 2025-02-23
|
||||
|
||||
CRITICAL FINDINGS:
|
||||
[SLS-001] order-processor: SQL injection via string concatenation
|
||||
Language: Python 3.12 | Runtime: Lambda
|
||||
Vulnerable Code: f"SELECT * FROM orders WHERE id = '{order_id}'"
|
||||
Remediation: Use parameterized queries with psycopg2
|
||||
|
||||
[SLS-002] payment-handler: Hardcoded Stripe API key in environment variable
|
||||
Key: sk_live_XXXX... (unencrypted)
|
||||
Remediation: Migrate to AWS Secrets Manager with KMS encryption
|
||||
|
||||
HIGH FINDINGS:
|
||||
[SLS-003] 12 functions share the same IAM execution role with s3:*
|
||||
[SLS-004] 8 functions have function URLs with AuthType: NONE
|
||||
[SLS-005] 23 functions have dependencies with known HIGH CVEs
|
||||
|
||||
DEPENDENCY VULNERABILITIES:
|
||||
axios@0.21.1: CVE-2023-45857 (HIGH) - 5 functions affected
|
||||
jsonwebtoken@8.5.1: CVE-2022-23529 (CRITICAL) - 3 functions affected
|
||||
lodash@4.17.15: CVE-2021-23337 (HIGH) - 11 functions affected
|
||||
|
||||
SUMMARY:
|
||||
Critical: 2 | High: 5 | Medium: 12 | Low: 8
|
||||
Functions with Least Privilege: 14/47 (30%)
|
||||
Functions with Secrets Manager: 19/47 (40%)
|
||||
Functions with Input Validation: 22/47 (47%)
|
||||
```
|
||||
@@ -0,0 +1,56 @@
|
||||
# API Reference: Securing Serverless Functions
|
||||
|
||||
## boto3 Lambda Client
|
||||
|
||||
### Installation
|
||||
```bash
|
||||
pip install boto3
|
||||
```
|
||||
|
||||
### Key Methods
|
||||
| Method | Description |
|
||||
|--------|-------------|
|
||||
| `list_functions()` | List all functions with configuration details |
|
||||
| `get_function_configuration()` | Get function config (role, env vars, KMS) |
|
||||
| `get_function_url_config()` | Get function URL and auth type |
|
||||
| `get_function_concurrency()` | Get reserved concurrency settings |
|
||||
| `update_function_configuration()` | Update KMS key, logging, VPC config |
|
||||
| `create_function_url_config()` | Create function URL with auth type |
|
||||
|
||||
### Function Configuration Fields
|
||||
| Field | Security Relevance |
|
||||
|-------|-------------------|
|
||||
| `Role` | Execution role ARN (check for least privilege) |
|
||||
| `Environment.Variables` | May contain hardcoded secrets |
|
||||
| `KMSKeyArn` | Customer-managed KMS key for env encryption |
|
||||
| `VpcConfig` | VPC subnet and security group configuration |
|
||||
| `Timeout` | Max execution time (1-900 seconds) |
|
||||
| `Runtime` | Language runtime (check for EOL versions) |
|
||||
| `Layers` | Shared code layers (scan independently) |
|
||||
|
||||
### Function URL Auth Types
|
||||
| Value | Description |
|
||||
|-------|-------------|
|
||||
| `AWS_IAM` | Requires IAM authentication (secure) |
|
||||
| `NONE` | No authentication required (insecure for sensitive functions) |
|
||||
|
||||
## boto3 IAM Client (Role Checks)
|
||||
| Method | Description |
|
||||
|--------|-------------|
|
||||
| `list_attached_role_policies()` | Check for overly broad managed policies |
|
||||
| `get_role_policy()` | Inspect inline policy for wildcards |
|
||||
| `get_role()` | Check trust policy and permission boundary |
|
||||
|
||||
## GuardDuty Lambda Protection
|
||||
```python
|
||||
gd = boto3.client("guardduty")
|
||||
gd.update_detector(
|
||||
DetectorId="<id>",
|
||||
Features=[{"Name": "LAMBDA_NETWORK_ACTIVITY_LOGS", "Status": "ENABLED"}]
|
||||
)
|
||||
```
|
||||
|
||||
## References
|
||||
- Lambda security best practices: https://docs.aws.amazon.com/lambda/latest/dg/lambda-security.html
|
||||
- Lambda function URLs: https://docs.aws.amazon.com/lambda/latest/dg/lambda-urls.html
|
||||
- GuardDuty Lambda protection: https://docs.aws.amazon.com/guardduty/latest/ug/lambda-protection.html
|
||||
@@ -0,0 +1,171 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Agent for auditing serverless function security across AWS Lambda."""
|
||||
|
||||
import boto3
|
||||
import json
|
||||
import argparse
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
def list_functions(region="us-east-1"):
|
||||
"""List all Lambda functions with security-relevant configuration."""
|
||||
lam = boto3.client("lambda", region_name=region)
|
||||
functions = []
|
||||
paginator = lam.get_paginator("list_functions")
|
||||
for page in paginator.paginate():
|
||||
for f in page["Functions"]:
|
||||
functions.append({
|
||||
"name": f["FunctionName"],
|
||||
"runtime": f.get("Runtime", "N/A"),
|
||||
"role": f["Role"].split("/")[-1],
|
||||
"timeout": f.get("Timeout", 3),
|
||||
"memory": f.get("MemorySize", 128),
|
||||
"kms_key": f.get("KMSKeyArn", "None (default)"),
|
||||
"vpc": bool(f.get("VpcConfig", {}).get("SubnetIds")),
|
||||
})
|
||||
print(f"[*] Found {len(functions)} Lambda functions")
|
||||
for fn in functions:
|
||||
print(f" {fn['name']} | {fn['runtime']} | role={fn['role']} | VPC={fn['vpc']}")
|
||||
return functions
|
||||
|
||||
|
||||
def check_function_urls(region="us-east-1"):
|
||||
"""Check for Lambda function URLs with insecure authentication."""
|
||||
lam = boto3.client("lambda", region_name=region)
|
||||
findings = []
|
||||
paginator = lam.get_paginator("list_functions")
|
||||
for page in paginator.paginate():
|
||||
for f in page["Functions"]:
|
||||
try:
|
||||
url_config = lam.get_function_url_config(FunctionName=f["FunctionName"])
|
||||
auth_type = url_config.get("AuthType", "NONE")
|
||||
if auth_type == "NONE":
|
||||
findings.append({
|
||||
"function": f["FunctionName"],
|
||||
"url": url_config.get("FunctionUrl", ""),
|
||||
"auth_type": auth_type,
|
||||
"severity": "CRITICAL",
|
||||
})
|
||||
print(f" [!] CRITICAL: {f['FunctionName']} has unauthenticated URL: "
|
||||
f"{url_config.get('FunctionUrl', '')}")
|
||||
else:
|
||||
print(f" [+] {f['FunctionName']}: URL auth={auth_type}")
|
||||
except lam.exceptions.ResourceNotFoundException:
|
||||
continue
|
||||
print(f"[*] {len(findings)} functions with unauthenticated URLs")
|
||||
return findings
|
||||
|
||||
|
||||
def check_env_variables(region="us-east-1"):
|
||||
"""Scan Lambda environment variables for potential hardcoded secrets."""
|
||||
lam = boto3.client("lambda", region_name=region)
|
||||
findings = []
|
||||
secret_patterns = ["password", "secret", "api_key", "apikey", "token", "private_key",
|
||||
"access_key", "db_pass", "database_url", "smtp"]
|
||||
paginator = lam.get_paginator("list_functions")
|
||||
for page in paginator.paginate():
|
||||
for f in page["Functions"]:
|
||||
env_vars = f.get("Environment", {}).get("Variables", {})
|
||||
kms_key = f.get("KMSKeyArn")
|
||||
for key, value in env_vars.items():
|
||||
key_lower = key.lower()
|
||||
if any(p in key_lower for p in secret_patterns):
|
||||
has_kms = bool(kms_key)
|
||||
findings.append({
|
||||
"function": f["FunctionName"],
|
||||
"variable": key,
|
||||
"encrypted": has_kms,
|
||||
"severity": "HIGH" if not has_kms else "MEDIUM",
|
||||
})
|
||||
enc_status = "KMS-encrypted" if has_kms else "PLAINTEXT"
|
||||
print(f" [!] {f['FunctionName']}: {key} ({enc_status})")
|
||||
print(f"[*] {len(findings)} potential secrets in environment variables")
|
||||
return findings
|
||||
|
||||
|
||||
def check_shared_roles(region="us-east-1"):
|
||||
"""Identify Lambda functions sharing the same execution role."""
|
||||
lam = boto3.client("lambda", region_name=region)
|
||||
role_map = {}
|
||||
paginator = lam.get_paginator("list_functions")
|
||||
for page in paginator.paginate():
|
||||
for f in page["Functions"]:
|
||||
role = f["Role"]
|
||||
role_name = role.split("/")[-1]
|
||||
if role_name not in role_map:
|
||||
role_map[role_name] = []
|
||||
role_map[role_name].append(f["FunctionName"])
|
||||
findings = []
|
||||
print("\n[*] Checking for shared execution roles...")
|
||||
for role, funcs in role_map.items():
|
||||
if len(funcs) > 1:
|
||||
findings.append({"role": role, "functions": funcs, "count": len(funcs)})
|
||||
print(f" [!] Role '{role}' shared by {len(funcs)} functions: {', '.join(funcs[:5])}")
|
||||
print(f"[*] {len(findings)} shared roles found")
|
||||
return findings
|
||||
|
||||
|
||||
def check_reserved_concurrency(region="us-east-1"):
|
||||
"""Check if functions have reserved concurrency set to prevent resource exhaustion."""
|
||||
lam = boto3.client("lambda", region_name=region)
|
||||
no_concurrency = []
|
||||
paginator = lam.get_paginator("list_functions")
|
||||
for page in paginator.paginate():
|
||||
for f in page["Functions"]:
|
||||
try:
|
||||
conc = lam.get_function_concurrency(FunctionName=f["FunctionName"])
|
||||
reserved = conc.get("ReservedConcurrentExecutions")
|
||||
if reserved is None:
|
||||
no_concurrency.append(f["FunctionName"])
|
||||
except Exception:
|
||||
no_concurrency.append(f["FunctionName"])
|
||||
if no_concurrency:
|
||||
print(f"\n[*] {len(no_concurrency)} functions without reserved concurrency")
|
||||
return no_concurrency
|
||||
|
||||
|
||||
def full_audit(region="us-east-1", output_path="serverless_audit.json"):
|
||||
"""Run comprehensive serverless security audit."""
|
||||
print("[*] Starting serverless security audit...\n")
|
||||
report = {
|
||||
"audit_date": datetime.now().isoformat(),
|
||||
"region": region,
|
||||
"functions": list_functions(region),
|
||||
"unauthenticated_urls": check_function_urls(region),
|
||||
"env_secrets": check_env_variables(region),
|
||||
"shared_roles": check_shared_roles(region),
|
||||
"no_concurrency_limit": check_reserved_concurrency(region),
|
||||
}
|
||||
total_findings = (len(report["unauthenticated_urls"]) + len(report["env_secrets"]) +
|
||||
len(report["shared_roles"]))
|
||||
report["total_findings"] = total_findings
|
||||
with open(output_path, "w") as f:
|
||||
json.dump(report, f, indent=2, default=str)
|
||||
print(f"\n[*] Audit complete: {total_findings} findings")
|
||||
print(f"[*] Report saved to {output_path}")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Serverless Function Security Agent")
|
||||
parser.add_argument("action", choices=["list", "urls", "env-secrets", "shared-roles",
|
||||
"concurrency", "full-audit"])
|
||||
parser.add_argument("--region", default="us-east-1")
|
||||
parser.add_argument("-o", "--output", default="serverless_audit.json")
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.action == "list":
|
||||
list_functions(args.region)
|
||||
elif args.action == "urls":
|
||||
check_function_urls(args.region)
|
||||
elif args.action == "env-secrets":
|
||||
check_env_variables(args.region)
|
||||
elif args.action == "shared-roles":
|
||||
check_shared_roles(args.region)
|
||||
elif args.action == "concurrency":
|
||||
check_reserved_concurrency(args.region)
|
||||
elif args.action == "full-audit":
|
||||
full_audit(args.region, args.output)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user