
Detecting Api Enumeration Attacks
- 180 installs
- 27.3k repo stars
- Updated August 2, 2026
- mukul975/anthropic-cybersecurity-skills
Helps with backend & apis tasks.
About
detecting-api-enumeration-attacks is a Claude Code skill for backend & apis. It helps solo builders move faster with AI-assisted coding.
- detecting-api-enumeration-attacks
- Backend & APIs
- AI-coding skill
Detecting Api Enumeration Attacks by the numbers
- 180 all-time installs (skills.sh)
- +13 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #2,211 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 detecting-api-enumeration-attacksAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 180 |
|---|---|
| repo stars | ★ 27.3k |
| Last updated | August 2, 2026 |
| Repository | mukul975/anthropic-cybersecurity-skills ↗ |
What it does
Helps with backend & apis tasks.
Files
Detecting API Enumeration Attacks
Overview
API enumeration attacks occur when attackers systematically probe API endpoints with sequential or predictable identifiers to discover and access unauthorized resources. Broken Object Level Authorization (BOLA), ranked as API1:2023 in the OWASP API Security Top 10, is the most critical API vulnerability. Attackers manipulate object identifiers (user IDs, order numbers, account references) in API requests to bypass authorization and access other users' data. Detection requires monitoring for patterns of rapid sequential access attempts, authorization failures, and abnormal API usage behavior.
When to Use
- When investigating security incidents that require detecting api enumeration attacks
- 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
- API gateway or reverse proxy with logging enabled (Kong, AWS API Gateway, Apigee)
- SIEM platform (Splunk, Elastic SIEM, or Microsoft Sentinel)
- Access to API server logs with request details
- Web Application Firewall (WAF) with API protection capabilities
- Understanding of the API's authorization model and object identifier schemes
Attack Patterns to Detect
1. Sequential ID Enumeration
Attackers iterate through numeric or predictable identifiers:
GET /api/v1/users/1001 -> 200 OK
GET /api/v1/users/1002 -> 200 OK
GET /api/v1/users/1003 -> 403 Forbidden
GET /api/v1/users/1004 -> 200 OK
GET /api/v1/users/1005 -> 200 OK
...Detection Indicators:
- Rapid sequential requests to the same endpoint with incrementing IDs
- Mix of 200/403/401 responses from same source
- Request rate exceeding normal user behavior
- Access to resources outside authenticated user's scope
2. UUID/GUID Enumeration
Even non-sequential identifiers can be enumerated if leaked through other endpoints:
# Attacker first harvests UUIDs from a list endpoint
GET /api/v1/posts?page=1 -> Returns post objects with author UUIDs
# Then uses those UUIDs to access restricted user data
GET /api/v1/users/a3f2c1e4-... -> Private user profile
GET /api/v1/users/b7d9e8f1-... -> Private user profile3. Parameter Tampering Enumeration
# Authenticated as user_id=100, attempting to access other users' orders
GET /api/v1/orders?user_id=101
GET /api/v1/orders?user_id=102
GET /api/v1/orders?user_id=103Detection Rules
Splunk Detection Queries
# Detect sequential ID enumeration on API endpoints
index=api_logs sourcetype=api_access
| rex field=uri_path "(?<endpoint>/api/v\d+/\w+/)(?<object_id>\d+)"
| stats count as request_count,
dc(object_id) as unique_ids,
values(status_code) as status_codes,
min(_time) as first_seen,
max(_time) as last_seen
by src_ip, endpoint, user_session
| eval time_span = last_seen - first_seen
| eval requests_per_second = request_count / max(time_span, 1)
| where unique_ids > 20 AND requests_per_second > 2
| eval severity = case(
unique_ids > 100, "critical",
unique_ids > 50, "high",
unique_ids > 20, "medium",
1==1, "low"
)
| sort - unique_ids
| table src_ip, endpoint, unique_ids, request_count, requests_per_second,
status_codes, severity
# Detect BOLA via authorization failure patterns
index=api_logs sourcetype=api_access status_code IN (401, 403)
| bin _time span=5m
| stats count as failure_count,
dc(uri_path) as unique_paths,
values(uri_path) as attempted_paths
by _time, src_ip, user_id
| where failure_count > 10
| eval attack_type = if(unique_paths > 5, "enumeration", "brute_force")Elastic SIEM Detection Rules
{
"rule": {
"name": "API Object Enumeration Detection",
"description": "Detects rapid sequential access to API objects with mixed authorization results",
"type": "threshold",
"index": ["api-access-*"],
"query": {
"bool": {
"must": [
{ "regexp": { "url.path": "/api/v[0-9]+/[a-z]+/[0-9]+" } }
],
"should": [
{ "term": { "http.response.status_code": 200 } },
{ "term": { "http.response.status_code": 403 } },
{ "term": { "http.response.status_code": 401 } }
]
}
},
"threshold": {
"field": ["source.ip"],
"value": 50,
"cardinality": [
{ "field": "url.path", "value": 20 }
]
},
"schedule": { "interval": "5m" },
"severity": "high",
"risk_score": 73,
"tags": ["OWASP-API1", "BOLA", "Enumeration"]
}
}Custom Detection Script
#!/usr/bin/env python3
"""API Enumeration Attack Detector
Analyzes API access logs to detect enumeration patterns
including BOLA, IDOR, and sequential ID probing.
"""
import re
import sys
import json
from collections import defaultdict
from datetime import datetime, timedelta
from dataclasses import dataclass, field
from typing import List, Dict, Optional
@dataclass
class AccessRecord:
timestamp: datetime
source_ip: str
user_id: Optional[str]
method: str
path: str
status_code: int
object_id: Optional[str] = None
@dataclass
class EnumerationAlert:
source_ip: str
user_id: Optional[str]
endpoint_pattern: str
unique_object_ids: int
total_requests: int
time_window_seconds: float
requests_per_second: float
auth_failure_ratio: float
severity: str
attack_type: str
sample_ids: List[str] = field(default_factory=list)
class EnumerationDetector:
# Regex patterns for extracting object IDs from API paths
ID_PATTERNS = [
re.compile(r'/api/v\d+/(\w+)/(\d+)'), # Numeric IDs
re.compile(r'/api/v\d+/(\w+)/([a-f0-9\-]{36})'), # UUIDs
re.compile(r'/api/v\d+/(\w+)/([a-zA-Z0-9]{20,})'), # Long alphanumeric IDs
]
def __init__(self, time_window_minutes: int = 5,
min_unique_ids: int = 15,
max_requests_per_second: float = 5.0):
self.time_window = timedelta(minutes=time_window_minutes)
self.min_unique_ids = min_unique_ids
self.max_rps = max_requests_per_second
self.access_log: List[AccessRecord] = []
def parse_log_line(self, line: str) -> Optional[AccessRecord]:
"""Parse a common log format line into an AccessRecord."""
log_pattern = re.compile(
r'(?P<ip>[\d.]+)\s+\S+\s+(?P<user>\S+)\s+'
r'\[(?P<time>[^\]]+)\]\s+'
r'"(?P<method>\w+)\s+(?P<path>\S+)\s+\S+"\s+'
r'(?P<status>\d+)'
)
match = log_pattern.match(line)
if not match:
return None
path = match.group('path')
object_id = None
for pattern in self.ID_PATTERNS:
id_match = pattern.search(path)
if id_match:
object_id = id_match.group(2)
break
return AccessRecord(
timestamp=datetime.strptime(match.group('time'), '%d/%b/%Y:%H:%M:%S %z'),
source_ip=match.group('ip'),
user_id=match.group('user') if match.group('user') != '-' else None,
method=match.group('method'),
path=path,
status_code=int(match.group('status')),
object_id=object_id
)
def analyze(self, records: List[AccessRecord]) -> List[EnumerationAlert]:
"""Analyze access records for enumeration patterns."""
alerts = []
# Group by source IP and endpoint pattern
grouped = defaultdict(list)
for record in records:
if record.object_id:
# Normalize endpoint by removing the specific object ID
endpoint = re.sub(r'/[a-f0-9\-]{36}', '/{id}',
re.sub(r'/\d+', '/{id}', record.path))
key = (record.source_ip, record.user_id, endpoint)
grouped[key].append(record)
for (src_ip, user_id, endpoint), records_group in grouped.items():
if len(records_group) < self.min_unique_ids:
continue
# Sort by timestamp
records_group.sort(key=lambda r: r.timestamp)
# Analyze time windows
window_start = 0
for window_start in range(len(records_group)):
window_records = []
for r in records_group[window_start:]:
if r.timestamp - records_group[window_start].timestamp <= self.time_window:
window_records.append(r)
unique_ids = set(r.object_id for r in window_records)
if len(unique_ids) < self.min_unique_ids:
continue
time_span = (window_records[-1].timestamp -
window_records[0].timestamp).total_seconds()
rps = len(window_records) / max(time_span, 1)
auth_failures = sum(1 for r in window_records
if r.status_code in (401, 403))
failure_ratio = auth_failures / len(window_records)
# Determine severity
if len(unique_ids) > 100:
severity = "critical"
elif len(unique_ids) > 50 or failure_ratio > 0.5:
severity = "high"
elif len(unique_ids) > 20:
severity = "medium"
else:
severity = "low"
# Determine attack type
ids_list = sorted([r.object_id for r in window_records
if r.object_id and r.object_id.isdigit()])
is_sequential = self._check_sequential(ids_list)
attack_type = "sequential_enumeration" if is_sequential else "random_enumeration"
alert = EnumerationAlert(
source_ip=src_ip,
user_id=user_id,
endpoint_pattern=endpoint,
unique_object_ids=len(unique_ids),
total_requests=len(window_records),
time_window_seconds=time_span,
requests_per_second=round(rps, 2),
auth_failure_ratio=round(failure_ratio, 2),
severity=severity,
attack_type=attack_type,
sample_ids=list(unique_ids)[:10]
)
alerts.append(alert)
break # One alert per group
return alerts
def _check_sequential(self, ids: List[str]) -> bool:
"""Check if numeric IDs follow a sequential pattern."""
if len(ids) < 5:
return False
try:
numeric_ids = sorted(int(i) for i in ids)
sequential_count = sum(
1 for i in range(1, len(numeric_ids))
if numeric_ids[i] - numeric_ids[i-1] <= 2
)
return sequential_count / len(numeric_ids) > 0.7
except ValueError:
return False
def main():
detector = EnumerationDetector(
time_window_minutes=5,
min_unique_ids=15
)
log_file = sys.argv[1] if len(sys.argv) > 1 else "/var/log/api/access.log"
records = []
with open(log_file, 'r') as f:
for line in f:
record = detector.parse_log_line(line.strip())
if record:
records.append(record)
alerts = detector.analyze(records)
if alerts:
print(f"\n[!] {len(alerts)} enumeration attack(s) detected:\n")
for alert in alerts:
print(f" Source IP: {alert.source_ip}")
print(f" User ID: {alert.user_id}")
print(f" Endpoint: {alert.endpoint_pattern}")
print(f" Unique IDs Accessed: {alert.unique_object_ids}")
print(f" Requests/sec: {alert.requests_per_second}")
print(f" Auth Failure Ratio: {alert.auth_failure_ratio}")
print(f" Attack Type: {alert.attack_type}")
print(f" Severity: {alert.severity.upper()}")
print(f" Sample IDs: {alert.sample_ids}")
print()
else:
print("[+] No enumeration attacks detected.")
if __name__ == "__main__":
main()Prevention Controls
Server-Side Authorization Enforcement
# Always validate object ownership at the data layer
def get_user_order(request, order_id):
order = Order.objects.get(id=order_id)
if order.user_id != request.user.id:
raise PermissionDenied("Not authorized to access this order")
return orderUse Unpredictable Identifiers
import uuid
# Use UUIDs instead of sequential integers
class Order(Model):
id = UUIDField(default=uuid.uuid4, primary_key=True)Implement Rate Limiting Per Endpoint
# Kong rate limiting per API route
plugins:
- name: rate-limiting
config:
minute: 30
policy: redis
limit_by: credentialReferences
- OWASP API1:2023 Broken Object Level Authorization: https://owasp.org/API-Security/editions/2023/en/0xa1-broken-object-level-authorization/
- Traceable.ai BOLA Deep Dive: https://www.traceable.ai/blog-post/a-deep-dive-on-the-most-critical-api-vulnerability----bola-broken-object-level-authorization
- Cequence BOLA Prevention: https://www.cequence.ai/solutions/bola-and-enumeration-attack-prevention/
- Cloudflare API Shield BOLA Detection: https://community.cloudflare.com/t/api-shield-new-bola-vulnerability-detection-for-api-shield/883021
- Sycope IDOR Detection via HTTP Traffic Analysis: https://www.sycope.com/post/idor-vulnerability-how-to-detect-an-attack-on-web-applications-through-http-traffic-analysis
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 Enumeration Attack Detection — API Reference
Libraries
| Library | Install | Purpose |
|---|---|---|
| requests | pip install requests | WAF and SIEM API queries |
Detection Techniques
| Technique | Indicator | Severity |
|---|---|---|
| Sequential ID enumeration | /api/users/1, /api/users/2, ... | HIGH |
| Endpoint fuzzing | High 404 rate on /api/* paths | HIGH |
| Rate abuse | >50 API requests/minute from single IP | MEDIUM |
| Path discovery | Requests to /swagger, /api-docs, /graphql | HIGH |
| BOLA/IDOR probing | Access to other users' resource IDs | CRITICAL |
NGINX Combined Log Format
$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent"Common Enumeration Paths
| Pattern | Description |
|---|---|
/api/v1/users/{id} | User ID enumeration |
/api/v1/accounts/{uuid} | Account UUID guessing |
/graphql?query={__schema} | GraphQL introspection |
/swagger/v1/swagger.json | API documentation discovery |
/api-docs, /.well-known | Endpoint discovery |
WAF Rule Categories
| Category | Description |
|---|---|
rate-limit | Request rate exceeds threshold |
api-abuse | Automated API enumeration |
bola | Broken Object Level Authorization |
scanner | Known scanner/fuzzer user-agent |
OWASP API Security Top 10
| ID | Risk |
|---|---|
| API1 | Broken Object Level Authorization |
| API2 | Broken Authentication |
| API3 | Broken Object Property Level Auth |
| API4 | Unrestricted Resource Consumption |
| API5 | Broken Function Level Authorization |
External References
#!/usr/bin/env python3
"""API enumeration attack detection agent."""
import json
import sys
import argparse
import re
from datetime import datetime
from collections import defaultdict
try:
import requests
except ImportError:
print("Install: pip install requests")
sys.exit(1)
ENUMERATION_PATTERNS = [
re.compile(r"/api/v\d+/users/\d+", re.IGNORECASE),
re.compile(r"/api/v\d+/accounts/[a-f0-9-]+", re.IGNORECASE),
re.compile(r"/api/v\d+/orders/\d+", re.IGNORECASE),
re.compile(r"/graphql.*introspection", re.IGNORECASE),
re.compile(r"/(admin|internal|debug|swagger|api-docs)", re.IGNORECASE),
]
SEQUENTIAL_THRESHOLD = 10
RATE_THRESHOLD = 50
def parse_access_log(log_path):
"""Parse NGINX/Apache combined log format for API requests."""
log_pattern = re.compile(
r'(\S+) \S+ \S+ \[([^\]]+)\] "(\S+) (\S+) \S+" (\d+) \d+'
)
entries = []
with open(log_path, "r") as f:
for line in f:
m = log_pattern.match(line)
if m:
entries.append({
"ip": m.group(1),
"timestamp": m.group(2),
"method": m.group(3),
"path": m.group(4),
"status": int(m.group(5)),
})
return entries
def detect_sequential_ids(entries):
"""Detect sequential ID enumeration in API paths."""
id_pattern = re.compile(r"/(\d+)(?:/|$|\?)")
ip_sequences = defaultdict(list)
for entry in entries:
m = id_pattern.search(entry["path"])
if m:
ip_sequences[entry["ip"]].append(int(m.group(1)))
findings = []
for ip, ids in ip_sequences.items():
if len(ids) < SEQUENTIAL_THRESHOLD:
continue
sorted_ids = sorted(ids)
sequential_count = sum(1 for i in range(1, len(sorted_ids))
if sorted_ids[i] - sorted_ids[i-1] == 1)
if sequential_count >= SEQUENTIAL_THRESHOLD:
findings.append({
"ip": ip,
"issue": f"Sequential ID enumeration detected ({sequential_count} sequential IDs)",
"severity": "HIGH",
"sample_ids": sorted_ids[:20],
"total_requests": len(ids),
})
return findings
def detect_rate_anomalies(entries, window_seconds=60):
"""Detect abnormal request rates per IP to API endpoints."""
ip_counts = defaultdict(int)
ip_404s = defaultdict(int)
ip_401s = defaultdict(int)
for entry in entries:
if "/api/" in entry["path"]:
ip_counts[entry["ip"]] += 1
if entry["status"] == 404:
ip_404s[entry["ip"]] += 1
elif entry["status"] == 401:
ip_401s[entry["ip"]] += 1
findings = []
for ip, count in ip_counts.items():
if count > RATE_THRESHOLD:
findings.append({
"ip": ip,
"issue": f"High API request rate ({count} requests)",
"severity": "MEDIUM",
"total_requests": count,
"404_count": ip_404s.get(ip, 0),
"401_count": ip_401s.get(ip, 0),
})
if ip_404s.get(ip, 0) > 20:
findings.append({
"ip": ip,
"issue": f"Excessive 404s on API ({ip_404s[ip]} not-found responses)",
"severity": "HIGH",
"detail": "Possible endpoint discovery/fuzzing",
})
return findings
def detect_path_enumeration(entries):
"""Detect API path/endpoint enumeration patterns."""
ip_paths = defaultdict(set)
for entry in entries:
ip_paths[entry["ip"]].add(entry["path"].split("?")[0])
findings = []
for ip, paths in ip_paths.items():
for pattern in ENUMERATION_PATTERNS:
matched = [p for p in paths if pattern.search(p)]
if len(matched) > 5:
findings.append({
"ip": ip,
"issue": f"Path enumeration pattern: {pattern.pattern}",
"severity": "HIGH",
"matched_paths": len(matched),
"samples": list(matched)[:5],
})
return findings
def query_waf_logs(waf_url, api_key, hours=24):
"""Query WAF API for blocked enumeration attempts."""
headers = {"Authorization": f"Bearer {api_key}"}
try:
resp = requests.get(f"{waf_url}/api/v1/events",
params={"hours": hours, "rule_category": "api-abuse"},
headers=headers, timeout=15)
resp.raise_for_status()
return resp.json().get("events", [])
except Exception as e:
return [{"error": str(e)}]
def run_audit(args):
"""Execute API enumeration detection audit."""
print(f"\n{'='*60}")
print(f" API ENUMERATION ATTACK DETECTION")
print(f" Generated: {datetime.utcnow().isoformat()} UTC")
print(f"{'='*60}\n")
report = {}
if args.log_file:
entries = parse_access_log(args.log_file)
report["total_log_entries"] = len(entries)
print(f"Parsed {len(entries)} log entries from {args.log_file}\n")
seq_findings = detect_sequential_ids(entries)
report["sequential_id_findings"] = seq_findings
print(f"--- SEQUENTIAL ID ENUMERATION ({len(seq_findings)} findings) ---")
for f in seq_findings[:10]:
print(f" [{f['severity']}] {f['ip']}: {f['issue']}")
rate_findings = detect_rate_anomalies(entries)
report["rate_findings"] = rate_findings
print(f"\n--- RATE ANOMALIES ({len(rate_findings)} findings) ---")
for f in rate_findings[:10]:
print(f" [{f['severity']}] {f['ip']}: {f['issue']}")
path_findings = detect_path_enumeration(entries)
report["path_findings"] = path_findings
print(f"\n--- PATH ENUMERATION ({len(path_findings)} findings) ---")
for f in path_findings[:10]:
print(f" [{f['severity']}] {f['ip']}: {f['issue']}")
return report
def main():
parser = argparse.ArgumentParser(description="API Enumeration Detection Agent")
parser.add_argument("--log-file", help="Access log file to analyze")
parser.add_argument("--waf-url", help="WAF API URL for event queries")
parser.add_argument("--waf-key", help="WAF API key")
parser.add_argument("--output", help="Save report to JSON file")
args = parser.parse_args()
report = run_audit(args)
if args.output:
with open(args.output, "w") as f:
json.dump(report, f, indent=2, default=str)
print(f"\n[+] Report saved to {args.output}")
if __name__ == "__main__":
main()