
Exploiting Excessive Data Exposure In Api
- 153 installs
- 27.3k repo stars
- Updated August 2, 2026
- mukul975/anthropic-cybersecurity-skills
Helps with backend & apis tasks.
About
exploiting-excessive-data-exposure-in-api is a Claude Code skill in the Backend & APIs category.
- exploiting-excessive-data-exposure-in-api
- Backend & APIs
- AI-coding skill
Exploiting Excessive Data Exposure In Api by the numbers
- 153 all-time installs (skills.sh)
- +13 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #2,434 of 4,347 Backend & APIs skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill exploiting-excessive-data-exposure-in-apiAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 153 |
|---|---|
| repo stars | ★ 27.3k |
| Last updated | August 2, 2026 |
| Repository | mukul975/anthropic-cybersecurity-skills ↗ |
What it does
Helps with backend & apis tasks.
Files
Exploiting Excessive Data Exposure in API
When to Use
- Testing APIs where the frontend displays a subset of data but the API response includes additional fields
- Assessing mobile application APIs where responses are designed for multiple client types and may contain excess data
- Identifying PII leakage in API responses that include email addresses, phone numbers, SSNs, or payment data not shown in the UI
- Testing GraphQL APIs where clients can request arbitrary fields including sensitive attributes
- Evaluating APIs after microservice refactoring where internal service-to-service data leaks into public endpoints
Do not use without written authorization. Data exposure testing involves capturing and analyzing potentially sensitive personal data.
Prerequisites
- Written authorization specifying target API endpoints and scope
- Burp Suite Professional or mitmproxy configured as intercepting proxy
- Two test accounts at different privilege levels (regular user and admin)
- Browser developer tools or mobile proxy setup for traffic capture
- Python 3.10+ with
requestsandjsonlibraries - API documentation (OpenAPI spec) for comparison against actual responses
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: Response Schema Discovery
Compare documented API responses with actual responses:
import requests
import json
BASE_URL = "https://target-api.example.com/api/v1"
headers = {"Authorization": "Bearer <user_token>", "Content-Type": "application/json"}
# Fetch a resource and analyze all returned fields
endpoints_to_test = [
("GET", "/users/me", None),
("GET", "/users/me/orders", None),
("GET", "/products", None),
("GET", "/users/me/settings", None),
("GET", "/transactions", None),
]
for method, path, body in endpoints_to_test:
resp = requests.request(method, f"{BASE_URL}{path}", headers=headers, json=body)
if resp.status_code == 200:
data = resp.json()
# Recursively extract all field names
def extract_fields(obj, prefix=""):
fields = []
if isinstance(obj, dict):
for k, v in obj.items():
full_key = f"{prefix}.{k}" if prefix else k
fields.append(full_key)
fields.extend(extract_fields(v, full_key))
elif isinstance(obj, list) and obj:
fields.extend(extract_fields(obj[0], f"{prefix}[]"))
return fields
all_fields = extract_fields(data)
print(f"\n{method} {path} - {len(all_fields)} fields returned:")
for f in sorted(all_fields):
print(f" {f}")Step 2: Sensitive Data Pattern Detection
Scan API responses for sensitive data patterns:
import re
SENSITIVE_PATTERNS = {
"email": r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}',
"phone": r'(\+?1?\s?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4})',
"ssn": r'\b\d{3}-\d{2}-\d{4}\b',
"credit_card": r'\b(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13})\b',
"password_hash": r'\$2[aby]?\$\d{2}\$[./A-Za-z0-9]{53}',
"api_key": r'(?:api[_-]?key|apikey)["\s:=]+["\']?([a-zA-Z0-9_\-]{20,})',
"internal_ip": r'\b(?:10\.\d{1,3}|172\.(?:1[6-9]|2\d|3[01])|192\.168)\.\d{1,3}\.\d{1,3}\b',
"aws_key": r'AKIA[0-9A-Z]{16}',
"jwt_token": r'eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+',
"uuid": r'[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}',
}
SENSITIVE_FIELD_NAMES = [
"password", "password_hash", "secret", "token", "ssn", "social_security",
"credit_card", "card_number", "cvv", "pin", "private_key", "api_key",
"internal_id", "debug", "trace", "stack_trace", "created_by_ip",
"last_login_ip", "salt", "session_id", "refresh_token", "mfa_secret",
"date_of_birth", "bank_account", "routing_number", "tax_id"
]
def scan_response(endpoint, response_text):
findings = []
# Check for sensitive data patterns in values
for pattern_name, pattern in SENSITIVE_PATTERNS.items():
matches = re.findall(pattern, response_text)
if matches:
findings.append({
"endpoint": endpoint,
"type": "sensitive_value",
"pattern": pattern_name,
"count": len(matches),
"sample": matches[0][:20] + "..." if len(matches[0]) > 20 else matches[0]
})
# Check for sensitive field names
response_lower = response_text.lower()
for field in SENSITIVE_FIELD_NAMES:
if f'"{field}"' in response_lower or f"'{field}'" in response_lower:
findings.append({
"endpoint": endpoint,
"type": "sensitive_field",
"field_name": field
})
return findings
# Scan all endpoint responses
for method, path, body in endpoints_to_test:
resp = requests.request(method, f"{BASE_URL}{path}", headers=headers, json=body)
if resp.status_code == 200:
findings = scan_response(f"{method} {path}", resp.text)
for f in findings:
print(f"[FINDING] {f['endpoint']}: {f['type']} - {f.get('pattern', f.get('field_name'))}")Step 3: Compare UI Display vs API Response
# Fields the UI shows (observed from the frontend application)
ui_displayed_fields = {
"/users/me": {"name", "email", "avatar_url", "role"},
"/users/me/orders": {"order_id", "date", "status", "total"},
"/products": {"id", "name", "price", "image_url", "description"},
}
# Fields the API actually returns
for method, path, body in endpoints_to_test:
resp = requests.request(method, f"{BASE_URL}{path}", headers=headers, json=body)
if resp.status_code == 200:
data = resp.json()
if isinstance(data, list):
actual_fields = set(data[0].keys()) if data else set()
elif isinstance(data, dict):
# Handle paginated responses
items_key = next((k for k in data if isinstance(data[k], list)), None)
if items_key and data[items_key]:
actual_fields = set(data[items_key][0].keys())
else:
actual_fields = set(data.keys())
else:
continue
expected = ui_displayed_fields.get(path, set())
excess = actual_fields - expected
if excess:
print(f"\n{method} {path} - EXCESS FIELDS (not shown in UI):")
for field in sorted(excess):
print(f" - {field}")Step 4: Test User Object Exposure in Related Endpoints
# Many APIs embed full user objects in responses for orders, comments, etc.
endpoints_with_user_objects = [
"/orders", # Each order may include full seller/buyer profile
"/comments", # Comments may include full author profile
"/reviews", # Reviews may expose reviewer details
"/transactions", # Transactions may include counterparty info
"/team/members", # Team listing may expose excessive member data
]
for path in endpoints_with_user_objects:
resp = requests.get(f"{BASE_URL}{path}", headers=headers)
if resp.status_code == 200:
text = resp.text
# Check for user data leakage in nested objects
user_fields_found = []
for field in ["password_hash", "last_login_ip", "mfa_enabled", "phone_number",
"date_of_birth", "ssn", "internal_notes", "salary", "address"]:
if f'"{field}"' in text:
user_fields_found.append(field)
if user_fields_found:
print(f"[EXCESSIVE] {path} exposes user fields: {user_fields_found}")Step 5: GraphQL Over-Fetching Analysis
# GraphQL allows clients to request any available field
GRAPHQL_URL = f"{BASE_URL}/graphql"
# Introspection query to discover all fields on User type
introspection = {
"query": """
{
__type(name: "User") {
fields {
name
type {
name
kind
}
}
}
}
"""
}
resp = requests.post(GRAPHQL_URL, headers=headers, json=introspection)
if resp.status_code == 200:
fields = resp.json().get("data", {}).get("__type", {}).get("fields", [])
print("Available User fields via GraphQL:")
for f in fields:
sensitivity = "SENSITIVE" if f["name"] in SENSITIVE_FIELD_NAMES else "normal"
print(f" {f['name']} ({f['type']['name']}) [{sensitivity}]")
# Try to query sensitive fields
sensitive_query = {
"query": """
query {
users {
id
email
passwordHash
socialSecurityNumber
internalNotes
lastLoginIp
mfaSecret
apiKey
}
}
"""
}
resp = requests.post(GRAPHQL_URL, headers=headers, json=sensitive_query)
if resp.status_code == 200 and "errors" not in resp.json():
print("[CRITICAL] GraphQL exposes sensitive user fields without restriction")Step 6: Debug and Internal Data Leakage
# Test for debug information in responses
debug_headers_to_check = [
"X-Debug-Token", "X-Debug-Info", "Server", "X-Powered-By",
"X-Request-Id", "X-Correlation-Id", "X-Backend-Server",
"X-Runtime", "X-Version", "X-Build-Version"
]
resp = requests.get(f"{BASE_URL}/users/me", headers=headers)
for h in debug_headers_to_check:
if h.lower() in {k.lower(): v for k, v in resp.headers.items()}:
print(f"[INFO LEAK] Header {h}: {resp.headers.get(h)}")
# Test error responses for stack traces
error_payloads = [
("GET", "/users/invalid-id-format", None),
("POST", "/orders", {"invalid": "payload"}),
("GET", "/users/-1", None),
("GET", "/users/0", None),
]
for method, path, body in error_payloads:
resp = requests.request(method, f"{BASE_URL}{path}", headers=headers, json=body)
if resp.status_code >= 400:
text = resp.text.lower()
if any(kw in text for kw in ["stack trace", "traceback", "at com.", "at org.",
"file \"", "line ", "exception", "sql", "query"]):
print(f"[DEBUG LEAK] {method} {path} -> {resp.status_code}: Contains stack trace or query info")Key Concepts
| Term | Definition |
|---|---|
| Excessive Data Exposure | API returns more data fields than the client needs, relying on frontend filtering to hide sensitive information from users |
| Over-Fetching | Requesting or receiving more data than needed for a specific operation, common in REST APIs that return fixed response schemas |
| Response Filtering | Client-side filtering of API response data to display only relevant fields, which provides zero security since the full response is interceptable |
| Object Property Level Authorization | OWASP API3:2023 - ensuring that users can only read/write object properties they are authorized to access |
| PII Leakage | Unintended exposure of Personally Identifiable Information in API responses including names, emails, addresses, SSNs, or financial data |
| Schema Validation | Enforcing that API responses conform to a defined schema, stripping unauthorized fields before transmission |
Tools & Systems
- Burp Suite Professional: Intercept API responses and use the Comparer tool to diff expected vs actual response schemas
- mitmproxy: Scriptable proxy for automated response analysis with Python-based content inspection scripts
- OWASP ZAP: Passive scanner detects information disclosure in headers, error messages, and response bodies
- Postman: Compare documented response schemas against actual API responses using test scripts
- jq: Command-line JSON processor for extracting and analyzing specific fields from API responses
Common Scenarios
Scenario: Mobile Banking API Data Exposure Assessment
Context: A mobile banking application's API returns full account objects to the mobile client, which only displays account nickname and balance. The API is accessed by both iOS and Android apps and a web portal.
Approach: 1. Configure mitmproxy on a test device and authenticate as the test user 2. Capture all API responses during a complete user session (login, view accounts, transfer, logout) 3. Analyze GET /api/v1/accounts response: UI shows 4 fields but API returns 23 fields 4. Discover that the API returns routing_number, account_holder_ssn_last4, internal_risk_score, kyc_verification_status, and linked_external_accounts - none shown in UI 5. Analyze GET /api/v1/transactions response: API returns merchant_id, terminal_id, authorization_code, processor_response fields not needed by the client 6. Check GET /api/v1/users/me: API returns last_login_ip, mfa_backup_codes_remaining, account_officer_name, and credit_score_band 7. Test error responses: POST /api/v1/transfers with invalid payload returns SQL table name in error message
Pitfalls:
- Only checking top-level fields and missing sensitive data in deeply nested objects
- Not testing paginated responses where subsequent pages may include different fields
- Ignoring response headers that may leak server version, backend technology, or internal routing information
- Missing data exposure in error responses which often contain stack traces, SQL queries, or internal paths
- Assuming that HTTPS encryption prevents data exposure (it protects in transit, not from the authenticated client)
Output Format
## Finding: Excessive Data Exposure in Account and Transaction APIs
**ID**: API-DATA-001
**Severity**: High (CVSS 7.1)
**OWASP API**: API3:2023 - Broken Object Property Level Authorization
**Affected Endpoints**:
- GET /api/v1/accounts
- GET /api/v1/transactions
- GET /api/v1/users/me
**Description**:
The API returns full database objects to the client, including sensitive fields
that are not displayed in the mobile application UI. The mobile app filters
these fields client-side, but they are fully accessible by intercepting the
API response. This exposes SSN fragments, internal risk scores, and KYC
verification data for any authenticated user.
**Excess Fields Discovered**:
- /accounts: routing_number, account_holder_ssn_last4, internal_risk_score,
kyc_verification_status, linked_external_accounts (18 excess fields total)
- /transactions: merchant_id, terminal_id, authorization_code,
processor_response (12 excess fields total)
- /users/me: last_login_ip, mfa_backup_codes_remaining, credit_score_band
**Impact**:
An authenticated user can extract sensitive financial data, internal risk
assessments, and PII for their own account that the application is not
intended to reveal. Combined with BOLA vulnerabilities, this data could
be extracted for all users.
**Remediation**:
1. Implement server-side response filtering using DTOs/view models that only include fields needed by the client
2. Use GraphQL field-level authorization or REST response schemas per endpoint per role
3. Remove sensitive fields from API responses at the serialization layer
4. Implement response schema validation in the API gateway to strip undocumented fields
5. Add automated tests that verify response schemas match documentation
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.
API Reference: Excessive Data Exposure (OWASP API3)
OWASP API3:2023 — Broken Object Property Level Authorization
Description
API returns more data than the client needs. Sensitive fields like passwords, tokens, internal IDs, or PII are included in responses without filtering.
Sensitive Field Categories
| Category | Examples |
|---|---|
| Credentials | password, secret, token, api_key |
| PII | ssn, date_of_birth, credit_card |
| Internal | internal_id, debug_info, stack_trace |
| Financial | salary, bank_account, routing_number |
PII Detection Regex Patterns
| Type | Pattern |
|---|---|
[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,} | |
| SSN | \d{3}-\d{2}-\d{4} |
| Credit Card | \d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4} |
| Phone | \+?1?\d{10,15} |
| IP Address | \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} |
Testing Methodology
Step 1: Compare Response to Documentation
# Get actual response
curl -s https://api.target.com/users/me | jq 'keys'
# Compare with OpenAPI spec expected fieldsStep 2: Check for Sensitive Fields
sensitive = ["password", "token", "ssn", "secret"]
for field in response_json:
if any(s in field.lower() for s in sensitive):
print(f"EXPOSED: {field}")Step 3: Test Different Roles
# As regular user, check if admin fields returned
curl -H "Authorization: Bearer $USER_TOKEN" \
https://api.target.com/users/123 | jq '.role, .permissions'Python requests
Fetch and Analyze
resp = requests.get(url, headers={"Authorization": f"Bearer {token}"})
data = resp.json()Remediation Approaches
| Approach | Description |
|---|---|
| Response filtering | Only return fields client needs |
| GraphQL field selection | Let client specify fields |
| View models / DTOs | Map internal model to public API |
| Role-based serialization | Different fields per role |
Tools
Postman Collection Runner
Automate response schema validation across endpoints.
OWASP ZAP — Passive Scanner
Detects sensitive data in responses automatically.
Swagger/OpenAPI Diff
openapi-diff expected-spec.yaml actual-responses.yaml#!/usr/bin/env python3
# For authorized penetration testing and educational environments only.
# Usage against targets without prior mutual consent is illegal.
# It is the end user's responsibility to obey all applicable local, state and federal laws.
"""Agent for detecting excessive data exposure (OWASP API3) in API responses."""
import argparse
import json
import re
from datetime import datetime, timezone
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
SENSITIVE_FIELDS = [
"password", "passwd", "secret", "token", "api_key", "apikey",
"ssn", "social_security", "credit_card", "card_number", "cvv",
"private_key", "secret_key", "access_key", "session_id",
"internal_id", "salary", "bank_account", "routing_number",
"date_of_birth", "dob", "national_id", "passport",
]
PII_PATTERNS = {
"email": r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}',
"phone": r'\+?1?\d{10,15}',
"ssn": r'\d{3}-\d{2}-\d{4}',
"credit_card": r'\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}',
"ip_address": r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}',
}
def analyze_response(response_json, endpoint=""):
"""Analyze API response for excessive data exposure."""
findings = []
def check_fields(obj, path=""):
if isinstance(obj, dict):
for key, value in obj.items():
current_path = f"{path}.{key}" if path else key
key_lower = key.lower()
for sf in SENSITIVE_FIELDS:
if sf in key_lower:
findings.append({
"field": current_path,
"matched_pattern": sf,
"value_type": type(value).__name__,
"value_preview": str(value)[:20] + "..." if len(str(value)) > 20 else str(value),
"severity": "HIGH",
})
break
check_fields(value, current_path)
elif isinstance(obj, list):
for i, item in enumerate(obj[:5]):
check_fields(item, f"{path}[{i}]")
check_fields(response_json)
response_str = json.dumps(response_json)
for pattern_name, pattern in PII_PATTERNS.items():
matches = re.findall(pattern, response_str)
if matches:
findings.append({
"type": "pii_exposure",
"pattern": pattern_name,
"match_count": len(matches),
"samples": matches[:3],
"severity": "HIGH",
})
return findings
def test_endpoint(url, headers=None):
"""Fetch API endpoint and analyze for data exposure."""
if not HAS_REQUESTS:
return {"error": "requests library not available"}
try:
resp = requests.get(url, headers=headers, timeout=15, verify=False)
data = resp.json()
field_count = count_fields(data)
findings = analyze_response(data, url)
return {
"endpoint": url,
"status_code": resp.status_code,
"total_fields": field_count,
"sensitive_fields": len(findings),
"findings": findings,
}
except (requests.RequestException, json.JSONDecodeError) as e:
return {"endpoint": url, "error": str(e)[:200]}
def count_fields(obj, count=0):
"""Count total fields in a JSON response."""
if isinstance(obj, dict):
count += len(obj)
for v in obj.values():
count = count_fields(v, count)
elif isinstance(obj, list):
for item in obj[:10]:
count = count_fields(item, count)
return count
def compare_with_spec(response_json, spec_fields):
"""Compare response fields against expected OpenAPI spec fields."""
actual = set()
def extract_keys(obj, prefix=""):
if isinstance(obj, dict):
for k in obj:
path = f"{prefix}.{k}" if prefix else k
actual.add(path)
extract_keys(obj[k], path)
extract_keys(response_json)
extra = actual - set(spec_fields)
return list(extra)
def main():
parser = argparse.ArgumentParser(
description="Detect excessive data exposure in API responses"
)
parser.add_argument("--url", help="API endpoint to test")
parser.add_argument("--json-file", help="JSON response file to analyze")
parser.add_argument("--token", help="Bearer token for auth")
parser.add_argument("--output", "-o", help="Output JSON report")
args = parser.parse_args()
print("[*] Excessive Data Exposure Detection Agent (OWASP API3)")
report = {"timestamp": datetime.now(timezone.utc).isoformat(), "findings": []}
if args.url:
headers = {"Authorization": f"Bearer {args.token}"} if args.token else {}
result = test_endpoint(args.url, headers)
report["findings"].append(result)
print(f"[*] {args.url}: {result.get('sensitive_fields', 0)} sensitive fields found")
if args.json_file:
with open(args.json_file, "r") as f:
data = json.load(f)
findings = analyze_response(data, args.json_file)
report["findings"].extend(findings)
print(f"[*] File analysis: {len(findings)} sensitive fields found")
report["risk_level"] = "HIGH" if any(
f.get("sensitive_fields", 0) > 0 or f.get("severity") == "HIGH" for f in report["findings"]
) else "LOW"
if args.output:
with open(args.output, "w") as f:
json.dump(report, f, indent=2)
print(f"[*] Report saved to {args.output}")
else:
print(json.dumps(report, indent=2))
if __name__ == "__main__":
main()