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,306 @@
|
||||
---
|
||||
name: performing-serverless-function-security-review
|
||||
description: 'Performing security reviews of serverless functions across AWS Lambda,
|
||||
Azure Functions, and GCP Cloud Functions to identify overly permissive execution
|
||||
roles, insecure environment variables, injection vulnerabilities, and missing runtime
|
||||
protections.
|
||||
|
||||
'
|
||||
domain: cybersecurity
|
||||
subdomain: cloud-security
|
||||
tags:
|
||||
- cloud-security
|
||||
- serverless
|
||||
- lambda
|
||||
- azure-functions
|
||||
- cloud-functions
|
||||
- security-review
|
||||
version: '1.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
|
||||
- T1055
|
||||
---
|
||||
|
||||
# Performing Serverless Function Security Review
|
||||
|
||||
## When to Use
|
||||
|
||||
- When auditing serverless applications before production deployment
|
||||
- When investigating potential data exposure through function environment variables or logs
|
||||
- When assessing the blast radius of a compromised serverless function execution role
|
||||
- When compliance reviews require documentation of serverless security controls
|
||||
- When building secure-by-default templates for serverless deployments
|
||||
|
||||
**Do not use** for container or VM security assessments (use container scanning tools), for API security testing (use DAST tools on the API Gateway layer), or for real-time serverless threat detection (use AWS Lambda Extensions with security agents).
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- AWS CLI, Azure CLI, and gcloud CLI configured with appropriate permissions
|
||||
- Access to read function configurations, policies, and execution roles
|
||||
- Prowler or Checkov for automated serverless security scanning
|
||||
- SAM CLI or Serverless Framework for local function analysis
|
||||
- CloudTrail, Azure Monitor, or Cloud Audit Logs enabled for function invocation monitoring
|
||||
|
||||
## Workflow
|
||||
|
||||
### Step 1: Enumerate All Serverless Functions and Configurations
|
||||
|
||||
List all functions across cloud providers with their runtime, memory, timeout, and network settings.
|
||||
|
||||
```bash
|
||||
# AWS Lambda: List all functions with key security attributes
|
||||
aws lambda list-functions \
|
||||
--query 'Functions[*].[FunctionName,Runtime,MemorySize,Timeout,Role,VpcConfig.VpcId,Layers[*].Arn]' \
|
||||
--output table
|
||||
|
||||
# Check for functions using deprecated runtimes
|
||||
aws lambda list-functions \
|
||||
--query 'Functions[?Runtime==`python3.7` || Runtime==`nodejs14.x` || Runtime==`dotnetcore3.1`].[FunctionName,Runtime]' \
|
||||
--output table
|
||||
|
||||
# Azure Functions: List all function apps
|
||||
az functionapp list \
|
||||
--query "[].{Name:name, Runtime:siteConfig.linuxFxVersion, ResourceGroup:resourceGroup, HttpsOnly:httpsOnly}" \
|
||||
-o table
|
||||
|
||||
# GCP Cloud Functions: List all functions
|
||||
gcloud functions list \
|
||||
--format="table(name, runtime, status, httpsTrigger.url, serviceAccountEmail, vpcConnector)"
|
||||
```
|
||||
|
||||
### Step 2: Audit Execution Role Permissions
|
||||
|
||||
Review IAM roles attached to functions for overly permissive policies.
|
||||
|
||||
```bash
|
||||
# AWS: Check each Lambda function's execution role
|
||||
for func in $(aws lambda list-functions --query 'Functions[*].FunctionName' --output text); do
|
||||
role_arn=$(aws lambda get-function-configuration --function-name "$func" --query 'Role' --output text)
|
||||
role_name=$(echo "$role_arn" | awk -F'/' '{print $NF}')
|
||||
echo "=== $func -> $role_name ==="
|
||||
|
||||
# List attached policies
|
||||
aws iam list-attached-role-policies --role-name "$role_name" \
|
||||
--query 'AttachedPolicies[*].[PolicyName,PolicyArn]' --output table
|
||||
|
||||
# Check for wildcard actions
|
||||
for policy_arn in $(aws iam list-attached-role-policies --role-name "$role_name" --query 'AttachedPolicies[*].PolicyArn' --output text); do
|
||||
version=$(aws iam get-policy --policy-arn "$policy_arn" --query 'Policy.DefaultVersionId' --output text)
|
||||
aws iam get-policy-version --policy-arn "$policy_arn" --version-id "$version" \
|
||||
--query 'PolicyVersion.Document' --output json | python3 -c "
|
||||
import json, sys
|
||||
doc = json.load(sys.stdin)
|
||||
for stmt in doc.get('Statement', []):
|
||||
actions = stmt.get('Action', [])
|
||||
if isinstance(actions, str): actions = [actions]
|
||||
resources = stmt.get('Resource', [])
|
||||
if isinstance(resources, str): resources = [resources]
|
||||
if '*' in actions or any(a.endswith(':*') for a in actions):
|
||||
print(f' WARNING: {stmt[\"Effect\"]} {actions} on {resources}')
|
||||
" 2>/dev/null
|
||||
done
|
||||
done
|
||||
```
|
||||
|
||||
### Step 3: Check Environment Variables for Secrets
|
||||
|
||||
Scan function environment variables for hardcoded credentials, API keys, and database connection strings.
|
||||
|
||||
```bash
|
||||
# AWS Lambda: Extract environment variables
|
||||
for func in $(aws lambda list-functions --query 'Functions[*].FunctionName' --output text); do
|
||||
envvars=$(aws lambda get-function-configuration --function-name "$func" \
|
||||
--query 'Environment.Variables' --output json 2>/dev/null)
|
||||
if [ "$envvars" != "null" ] && [ -n "$envvars" ]; then
|
||||
echo "=== $func ==="
|
||||
echo "$envvars" | python3 -c "
|
||||
import json, sys, re
|
||||
vars = json.load(sys.stdin)
|
||||
sensitive_patterns = [
|
||||
r'(?i)(password|secret|key|token|credential|api.?key)',
|
||||
r'(?i)(aws.?access|aws.?secret)',
|
||||
r'(?i)(database.?url|connection.?string|db.?pass)',
|
||||
r'AKIA[0-9A-Z]{16}'
|
||||
]
|
||||
for key, value in vars.items():
|
||||
for pattern in sensitive_patterns:
|
||||
if re.search(pattern, key) or re.search(pattern, str(value)):
|
||||
masked = value[:4] + '****' + value[-4:] if len(value) > 8 else '****'
|
||||
print(f' SENSITIVE: {key} = {masked}')
|
||||
break
|
||||
"
|
||||
fi
|
||||
done
|
||||
|
||||
# Azure Functions: Check app settings
|
||||
for app in $(az functionapp list --query "[].name" -o tsv); do
|
||||
rg=$(az functionapp show --name "$app" --query "resourceGroup" -o tsv)
|
||||
echo "=== $app ==="
|
||||
az functionapp config appsettings list \
|
||||
--name "$app" --resource-group "$rg" \
|
||||
--query "[?contains(name,'KEY') || contains(name,'SECRET') || contains(name,'PASSWORD')].{Name:name}" \
|
||||
-o table 2>/dev/null
|
||||
done
|
||||
```
|
||||
|
||||
### Step 4: Review Function Triggers and Access Controls
|
||||
|
||||
Verify that function triggers have appropriate authentication and authorization.
|
||||
|
||||
```bash
|
||||
# AWS: Check for unauthenticated Lambda function URLs
|
||||
aws lambda list-function-url-configs \
|
||||
--function-name FUNCTION_NAME \
|
||||
--query 'FunctionUrlConfigs[*].[FunctionUrl,AuthType,Cors]' --output table
|
||||
|
||||
# Check for resource-based policies allowing public invocation
|
||||
for func in $(aws lambda list-functions --query 'Functions[*].FunctionName' --output text); do
|
||||
policy=$(aws lambda get-policy --function-name "$func" --query 'Policy' --output text 2>/dev/null)
|
||||
if [ -n "$policy" ]; then
|
||||
echo "$policy" | python3 -c "
|
||||
import json, sys
|
||||
doc = json.loads(sys.stdin.read())
|
||||
for stmt in doc.get('Statement', []):
|
||||
principal = stmt.get('Principal', {})
|
||||
if principal == '*' or principal == {'AWS': '*'}:
|
||||
print(f'WARNING: $func has public invoke policy: {stmt.get(\"Sid\", \"unnamed\")}')" 2>/dev/null
|
||||
fi
|
||||
done
|
||||
|
||||
# GCP: Check for unauthenticated Cloud Functions
|
||||
gcloud functions list --format=json | python3 -c "
|
||||
import json, sys
|
||||
functions = json.load(sys.stdin)
|
||||
for func in functions:
|
||||
name = func.get('name', '').split('/')[-1]
|
||||
trigger = func.get('httpsTrigger', {})
|
||||
if trigger and func.get('ingressSettings') == 'ALLOW_ALL':
|
||||
print(f'WARNING: {name} allows all ingress traffic')
|
||||
"
|
||||
```
|
||||
|
||||
### Step 5: Analyze Function Code for Security Vulnerabilities
|
||||
|
||||
Review function code for common serverless security issues.
|
||||
|
||||
```bash
|
||||
# Download Lambda function code for review
|
||||
aws lambda get-function --function-name FUNCTION_NAME \
|
||||
--query 'Code.Location' --output text | xargs curl -o function.zip
|
||||
unzip function.zip -d function-code/
|
||||
|
||||
# Scan with Bandit (Python) or ESLint security plugin (Node.js)
|
||||
# Python functions
|
||||
pip install bandit
|
||||
bandit -r function-code/ -f json -o bandit-results.json
|
||||
|
||||
# Node.js functions
|
||||
npm install -g eslint @microsoft/eslint-plugin-sdl
|
||||
eslint --ext .js function-code/
|
||||
|
||||
# Check for common serverless vulnerabilities:
|
||||
# 1. SQL injection in database queries
|
||||
# 2. Command injection via os.system or subprocess
|
||||
# 3. Insecure deserialization
|
||||
# 4. Event data injection (untrusted event parameters)
|
||||
# 5. Excessive function permissions
|
||||
grep -rn "os.system\|subprocess\|eval(\|exec(" function-code/ || echo "No obvious injection patterns"
|
||||
grep -rn "pickle.loads\|yaml.load\b" function-code/ || echo "No deserialization risks"
|
||||
```
|
||||
|
||||
### Step 6: Run Automated Serverless Security Scanning
|
||||
|
||||
Execute Checkov and Prowler for automated compliance checks on serverless resources.
|
||||
|
||||
```bash
|
||||
# Checkov scan for serverless frameworks
|
||||
checkov -d ./serverless-project/ \
|
||||
--framework serverless \
|
||||
--output json > checkov-serverless.json
|
||||
|
||||
# Prowler Lambda-specific checks
|
||||
prowler aws \
|
||||
--checks lambda_function_no_secrets_in_variables \
|
||||
lambda_function_url_auth_type \
|
||||
lambda_function_using_supported_runtimes \
|
||||
lambda_function_not_publicly_accessible \
|
||||
-M json-ocsf \
|
||||
-o ./prowler-lambda/
|
||||
```
|
||||
|
||||
## Key Concepts
|
||||
|
||||
| Term | Definition |
|
||||
|------|------------|
|
||||
| Execution Role | IAM role assumed by a serverless function during execution that defines what AWS/cloud resources the function can access |
|
||||
| Event Injection | Serverless-specific attack where untrusted data in the event trigger payload is used unsafely in function logic |
|
||||
| Function URL | Direct HTTP(S) endpoint for invoking Lambda functions without API Gateway, which may be configured without authentication |
|
||||
| Cold Start | Initial function execution that includes container provisioning, during which security agents and extensions must initialize |
|
||||
| Resource-Based Policy | Policy attached to the function itself that defines who can invoke it, separate from the execution role |
|
||||
| Secrets Manager Integration | Pattern of retrieving sensitive configuration from a secrets management service rather than storing in environment variables |
|
||||
|
||||
## Tools & Systems
|
||||
|
||||
- **AWS Lambda**: Primary serverless compute platform with execution roles, layers, and resource policies
|
||||
- **Checkov**: Static analysis tool for infrastructure-as-code with serverless-specific security policies
|
||||
- **Prowler**: Cloud security tool with Lambda-specific checks for permissions, public access, and runtime versions
|
||||
- **Bandit**: Python static analysis tool for detecting security issues in function source code
|
||||
- **OWASP Serverless Top 10**: Security risk framework specific to serverless architectures
|
||||
|
||||
## Common Scenarios
|
||||
|
||||
### Scenario: Lambda Function with Admin Role Leaking Secrets via Environment Variables
|
||||
|
||||
**Context**: A security review discovers a Lambda function with `AdministratorAccess` execution role and database credentials stored in plaintext environment variables visible in CloudWatch logs.
|
||||
|
||||
**Approach**:
|
||||
1. Enumerate the function's execution role and discover `AdministratorAccess` managed policy
|
||||
2. Check environment variables and find `DB_PASSWORD`, `API_KEY`, and `STRIPE_SECRET_KEY` in plaintext
|
||||
3. Review CloudWatch logs and find credentials printed in debug log statements
|
||||
4. Create a scoped IAM policy granting only the specific DynamoDB and S3 actions needed
|
||||
5. Migrate secrets to AWS Secrets Manager and update function to retrieve at runtime
|
||||
6. Remove debug logging that outputs sensitive data
|
||||
7. Rotate all exposed credentials and enable Lambda function encryption with KMS
|
||||
|
||||
**Pitfalls**: Changing a function's execution role can break it if the new role is too restrictive. Test in a staging environment first. Environment variable changes trigger a new function version, so ensure aliases and triggers are updated. Secrets Manager calls add latency; cache secrets within the execution context to avoid per-invocation lookups.
|
||||
|
||||
## Output Format
|
||||
|
||||
```
|
||||
Serverless Function Security Review
|
||||
=======================================
|
||||
Account: 123456789012
|
||||
Functions Reviewed: 34
|
||||
Review Date: 2026-02-23
|
||||
|
||||
CRITICAL FINDINGS:
|
||||
[SRVL-001] Overly Permissive Execution Role
|
||||
Function: payment-processor
|
||||
Role: AdministratorAccess (full AWS access)
|
||||
Required Permissions: DynamoDB:PutItem, S3:GetObject (2 actions)
|
||||
Remediation: Create scoped policy with only required permissions
|
||||
|
||||
[SRVL-002] Secrets in Environment Variables
|
||||
Function: payment-processor
|
||||
Variables: DB_PASSWORD, STRIPE_SECRET_KEY, API_KEY
|
||||
Risk: Visible in console, API, and CloudWatch logs
|
||||
Remediation: Migrate to Secrets Manager, remove from env vars
|
||||
|
||||
SUMMARY:
|
||||
Functions with admin roles: 3 / 34
|
||||
Functions with secrets in env vars: 8 / 34
|
||||
Functions with deprecated runtimes: 5 / 34
|
||||
Functions with public access: 2 / 34
|
||||
Functions without VPC: 28 / 34
|
||||
Functions with wildcard permissions: 12 / 34
|
||||
```
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
# API Reference: Serverless Function Security Review
|
||||
|
||||
## Overview
|
||||
|
||||
Agent automates Lambda security reviews using boto3 to audit execution roles, environment variable secrets, deprecated runtimes, and public access configurations.
|
||||
|
||||
## Dependencies
|
||||
|
||||
| Package | Version | Purpose |
|
||||
|---------|---------|---------|
|
||||
| boto3 | >= 1.28 | AWS SDK for Lambda and IAM API calls |
|
||||
| botocore | >= 1.31 | Exception handling for AWS API errors |
|
||||
|
||||
## Core Functions
|
||||
|
||||
### `list_all_functions(client)`
|
||||
Paginates through all Lambda functions in the region.
|
||||
- **Parameters**: `client` - boto3 Lambda client
|
||||
- **Returns**: `list[dict]` - full function configuration objects
|
||||
|
||||
### `check_deprecated_runtime(runtime)`
|
||||
Checks if a Lambda runtime is end-of-life.
|
||||
- **Parameters**: `runtime` (str) - Lambda runtime identifier
|
||||
- **Returns**: `bool` - True if deprecated
|
||||
|
||||
### `audit_execution_role(iam, role_arn)`
|
||||
Inspects attached IAM policies for wildcard actions and AdministratorAccess.
|
||||
- **Parameters**: `iam` - boto3 IAM client, `role_arn` (str)
|
||||
- **Returns**: `list[str]` - finding descriptions
|
||||
|
||||
### `check_env_secrets(env_vars)`
|
||||
Scans environment variables for sensitive patterns (passwords, API keys, AWS credentials).
|
||||
- **Parameters**: `env_vars` (dict) - Lambda environment variables
|
||||
- **Returns**: `list[str]` - masked sensitive variable findings
|
||||
|
||||
### `check_public_access(client, function_name)`
|
||||
Checks resource-based policies and function URLs for unauthenticated access.
|
||||
- **Parameters**: `client` - boto3 Lambda client, `function_name` (str)
|
||||
- **Returns**: `list[str]` - public access findings
|
||||
|
||||
### `run_review(region="us-east-1")`
|
||||
Orchestrates the full review across all functions. Returns structured report dict.
|
||||
|
||||
## AWS API Calls Used
|
||||
|
||||
| API Call | Service | Purpose |
|
||||
|----------|---------|---------|
|
||||
| `list_functions` | Lambda | Enumerate all Lambda functions |
|
||||
| `get_policy` | Lambda | Retrieve resource-based policy |
|
||||
| `list_function_url_configs` | Lambda | Check function URL auth type |
|
||||
| `list_attached_role_policies` | IAM | Get policies on execution role |
|
||||
| `get_policy_version` | IAM | Read policy document for wildcards |
|
||||
|
||||
## Environment Variables
|
||||
|
||||
| Variable | Required | Description |
|
||||
|----------|----------|-------------|
|
||||
| `AWS_ACCESS_KEY_ID` | Yes | AWS credential (or use IAM role) |
|
||||
| `AWS_SECRET_ACCESS_KEY` | Yes | AWS credential (or use IAM role) |
|
||||
| `AWS_DEFAULT_REGION` | No | Defaults to us-east-1 |
|
||||
|
||||
## Output Schema
|
||||
|
||||
```json
|
||||
{
|
||||
"total_functions": 34,
|
||||
"deprecated_runtimes": [{"function": "name", "runtime": "python3.7"}],
|
||||
"role_findings": ["CRITICAL: Role X has AdministratorAccess"],
|
||||
"secret_findings": [{"function": "name", "finding": "SENSITIVE: DB_PASSWORD = prod****word"}],
|
||||
"public_access_findings": ["PUBLIC ACCESS: func allows public invocation"]
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,153 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Serverless function security review agent using boto3."""
|
||||
|
||||
import json
|
||||
import re
|
||||
import boto3
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
|
||||
def get_lambda_client(region="us-east-1"):
|
||||
return boto3.client("lambda", region_name=region)
|
||||
|
||||
|
||||
def get_iam_client(region="us-east-1"):
|
||||
return boto3.client("iam", region_name=region)
|
||||
|
||||
|
||||
def list_all_functions(client):
|
||||
functions = []
|
||||
paginator = client.get_paginator("list_functions")
|
||||
for page in paginator.paginate():
|
||||
functions.extend(page["Functions"])
|
||||
return functions
|
||||
|
||||
|
||||
def check_deprecated_runtime(runtime):
|
||||
deprecated = [
|
||||
"python2.7", "python3.6", "python3.7", "nodejs10.x",
|
||||
"nodejs12.x", "nodejs14.x", "dotnetcore2.1", "dotnetcore3.1",
|
||||
"ruby2.5", "java8", "go1.x",
|
||||
]
|
||||
return runtime in deprecated
|
||||
|
||||
|
||||
def audit_execution_role(iam, role_arn):
|
||||
findings = []
|
||||
role_name = role_arn.split("/")[-1]
|
||||
try:
|
||||
attached = iam.list_attached_role_policies(RoleName=role_name)
|
||||
for policy in attached["AttachedPolicies"]:
|
||||
if policy["PolicyName"] == "AdministratorAccess":
|
||||
findings.append(f"CRITICAL: Role {role_name} has AdministratorAccess")
|
||||
version_id = iam.get_policy(PolicyArn=policy["PolicyArn"])["Policy"]["DefaultVersionId"]
|
||||
doc = iam.get_policy_version(
|
||||
PolicyArn=policy["PolicyArn"], VersionId=version_id
|
||||
)["PolicyVersion"]["Document"]
|
||||
for stmt in doc.get("Statement", []):
|
||||
actions = stmt.get("Action", [])
|
||||
if isinstance(actions, str):
|
||||
actions = [actions]
|
||||
if "*" in actions or any(a.endswith(":*") for a in actions):
|
||||
findings.append(
|
||||
f"WARNING: {role_name} has wildcard action: {actions} "
|
||||
f"on {stmt.get('Resource', '*')}"
|
||||
)
|
||||
except ClientError as e:
|
||||
findings.append(f"ERROR auditing role {role_name}: {e}")
|
||||
return findings
|
||||
|
||||
|
||||
SENSITIVE_PATTERNS = [
|
||||
re.compile(r"(?i)(password|secret|key|token|credential|api.?key)"),
|
||||
re.compile(r"(?i)(aws.?access|aws.?secret)"),
|
||||
re.compile(r"(?i)(database.?url|connection.?string|db.?pass)"),
|
||||
re.compile(r"AKIA[0-9A-Z]{16}"),
|
||||
]
|
||||
|
||||
|
||||
def check_env_secrets(env_vars):
|
||||
findings = []
|
||||
if not env_vars:
|
||||
return findings
|
||||
for key, value in env_vars.items():
|
||||
for pattern in SENSITIVE_PATTERNS:
|
||||
if pattern.search(key) or pattern.search(str(value)):
|
||||
masked = value[:4] + "****" + value[-4:] if len(value) > 8 else "****"
|
||||
findings.append(f"SENSITIVE: {key} = {masked}")
|
||||
break
|
||||
return findings
|
||||
|
||||
|
||||
def check_public_access(client, function_name):
|
||||
findings = []
|
||||
try:
|
||||
policy = client.get_policy(FunctionName=function_name)
|
||||
doc = json.loads(policy["Policy"])
|
||||
for stmt in doc.get("Statement", []):
|
||||
principal = stmt.get("Principal", {})
|
||||
if principal == "*" or principal == {"AWS": "*"}:
|
||||
findings.append(
|
||||
f"PUBLIC ACCESS: {function_name} allows public invocation "
|
||||
f"(statement: {stmt.get('Sid', 'unnamed')})"
|
||||
)
|
||||
except ClientError:
|
||||
pass
|
||||
try:
|
||||
urls = client.list_function_url_configs(FunctionName=function_name)
|
||||
for url_cfg in urls.get("FunctionUrlConfigs", []):
|
||||
if url_cfg.get("AuthType") == "NONE":
|
||||
findings.append(
|
||||
f"UNAUTHENTICATED URL: {function_name} -> {url_cfg['FunctionUrl']}"
|
||||
)
|
||||
except ClientError:
|
||||
pass
|
||||
return findings
|
||||
|
||||
|
||||
def run_review(region="us-east-1"):
|
||||
lam = get_lambda_client(region)
|
||||
iam = get_iam_client(region)
|
||||
functions = list_all_functions(lam)
|
||||
report = {
|
||||
"total_functions": len(functions),
|
||||
"deprecated_runtimes": [],
|
||||
"role_findings": [],
|
||||
"secret_findings": [],
|
||||
"public_access_findings": [],
|
||||
}
|
||||
for func in functions:
|
||||
name = func["FunctionName"]
|
||||
runtime = func.get("Runtime", "unknown")
|
||||
if check_deprecated_runtime(runtime):
|
||||
report["deprecated_runtimes"].append({"function": name, "runtime": runtime})
|
||||
report["role_findings"].extend(audit_execution_role(iam, func["Role"]))
|
||||
env = func.get("Environment", {}).get("Variables", {})
|
||||
secrets = check_env_secrets(env)
|
||||
if secrets:
|
||||
report["secret_findings"].extend(
|
||||
[{"function": name, "finding": s} for s in secrets]
|
||||
)
|
||||
report["public_access_findings"].extend(check_public_access(lam, name))
|
||||
return report
|
||||
|
||||
|
||||
def print_report(report):
|
||||
print("Serverless Function Security Review")
|
||||
print("=" * 40)
|
||||
print(f"Functions Reviewed: {report['total_functions']}")
|
||||
for section, label in [
|
||||
("deprecated_runtimes", "Deprecated Runtimes"),
|
||||
("role_findings", "Role Issues"),
|
||||
("secret_findings", "Secrets in Env Vars"),
|
||||
("public_access_findings", "Public Access"),
|
||||
]:
|
||||
items = report[section]
|
||||
print(f"\n{label}: {len(items)} finding(s)")
|
||||
for item in items:
|
||||
print(f" - {item}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
result = run_review()
|
||||
print_report(result)
|
||||
Reference in new issue
Block a user