[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6ETFKR7PYA4QJ2QRT3RK8XP":3,"skill-same:01M6ETFKR7PYA4QJ2QRT3RK8XP":96},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":28,"publishedAt":49,"linkOnly":50,"markdownContent":51,"markdownBody":52,"frontMatter":53,"refName":57,"commitSha":58,"skillDirectory":59,"forksCount":60,"repositoryHtmlUrl":61,"repositoryHomepageUrl":6,"ownerHtmlUrl":62,"ownerBlogUrl":6,"ownerDescription":63,"updatedAt":64,"install":65,"resources":78},"01M6ETFKR7PYA4QJ2QRT3RK8XP","detecting-api-enumeration-attacks",null,"Detect and prevent API enumeration attacks including BOLA and IDOR exploitation by monitoring sequential identifier access patterns and authorization failures.","luokai0\u002Fai-agent-skills-by-luo-kai","luokai0","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F266954973?v=4","01M6E16VNT42JB8B3X3254QWJ7","luo kai","01M6E16VTFVP6S5XJF1V1MPV90",14,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F21-external-registries\u002F08-pinkpixel-collection\u002Fdetecting-api-enumeration-attacks\u002FSKILL.md",[18,23],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000010","后端与接口","SCENARIO","使用场景",{"categoryNo":24,"categoryName":25,"taxonomyType":26,"taxonomyTypeDesc":27},"01JBSEEDCAT000000000000030","开发工程师","PROFESSION","适用职业",[29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48],"api","enumeration","detecting api enumeration attacks","broken-object-level-authorization","detect","control","broken","access","owasp-api","rate-limiting","owasp-api-top-10","security","idor","bola","exploitation","owasp","access-control","api-security","monitoring","cybersecurity","2026-11-10 10:12:30",false,"---\nname: detecting-api-enumeration-attacks\ndescription: Detect and prevent API enumeration attacks including BOLA and IDOR exploitation by monitoring sequential identifier access patterns and authorization failures.\ndomain: cybersecurity\nsubdomain: api-security\ntags: [api-security, enumeration, bola, idor, broken-object-level-authorization, owasp-api-top-10, access-control, rate-limiting]\nversion: \"1.0\"\nauthor: mahipal\nlicense: Apache-2.0\n---\n\n# Detecting API Enumeration Attacks\n\n## Overview\n\nAPI 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.\n\n\n## When to Use\n\n- When investigating security incidents that require detecting api enumeration attacks\n- When building detection rules or threat hunting queries for this domain\n- When SOC analysts need structured procedures for this analysis type\n- When validating security monitoring coverage for related attack techniques\n\n## Prerequisites\n\n- API gateway or reverse proxy with logging enabled (Kong, AWS API Gateway, Apigee)\n- SIEM platform (Splunk, Elastic SIEM, or Microsoft Sentinel)\n- Access to API server logs with request details\n- Web Application Firewall (WAF) with API protection capabilities\n- Understanding of the API's authorization model and object identifier schemes\n\n## Attack Patterns to Detect\n\n### 1. Sequential ID Enumeration\n\nAttackers iterate through numeric or predictable identifiers:\n\n```\nGET \u002Fapi\u002Fv1\u002Fusers\u002F1001 -> 200 OK\nGET \u002Fapi\u002Fv1\u002Fusers\u002F1002 -> 200 OK\nGET \u002Fapi\u002Fv1\u002Fusers\u002F1003 -> 403 Forbidden\nGET \u002Fapi\u002Fv1\u002Fusers\u002F1004 -> 200 OK\nGET \u002Fapi\u002Fv1\u002Fusers\u002F1005 -> 200 OK\n...\n```\n\n**Detection Indicators:**\n- Rapid sequential requests to the same endpoint with incrementing IDs\n- Mix of 200\u002F403\u002F401 responses from same source\n- Request rate exceeding normal user behavior\n- Access to resources outside authenticated user's scope\n\n### 2. UUID\u002FGUID Enumeration\n\nEven non-sequential identifiers can be enumerated if leaked through other endpoints:\n\n```\n# Attacker first harvests UUIDs from a list endpoint\nGET \u002Fapi\u002Fv1\u002Fposts?page=1  -> Returns post objects with author UUIDs\n\n# Then uses those UUIDs to access restricted user data\nGET \u002Fapi\u002Fv1\u002Fusers\u002Fa3f2c1e4-... -> Private user profile\nGET \u002Fapi\u002Fv1\u002Fusers\u002Fb7d9e8f1-... -> Private user profile\n```\n\n### 3. Parameter Tampering Enumeration\n\n```\n# Authenticated as user_id=100, attempting to access other users' orders\nGET \u002Fapi\u002Fv1\u002Forders?user_id=101\nGET \u002Fapi\u002Fv1\u002Forders?user_id=102\nGET \u002Fapi\u002Fv1\u002Forders?user_id=103\n```\n\n## Detection Rules\n\n### Splunk Detection Queries\n\n```spl\n# Detect sequential ID enumeration on API endpoints\nindex=api_logs sourcetype=api_access\n| rex field=uri_path \"(?\u003Cendpoint>\u002Fapi\u002Fv\\d+\u002F\\w+\u002F)(?\u003Cobject_id>\\d+)\"\n| stats count as request_count,\n        dc(object_id) as unique_ids,\n        values(status_code) as status_codes,\n        min(_time) as first_seen,\n        max(_time) as last_seen\n  by src_ip, endpoint, user_session\n| eval time_span = last_seen - first_seen\n| eval requests_per_second = request_count \u002F max(time_span, 1)\n| where unique_ids > 20 AND requests_per_second > 2\n| eval severity = case(\n    unique_ids > 100, \"critical\",\n    unique_ids > 50, \"high\",\n    unique_ids > 20, \"medium\",\n    1==1, \"low\"\n  )\n| sort - unique_ids\n| table src_ip, endpoint, unique_ids, request_count, requests_per_second,\n        status_codes, severity\n\n# Detect BOLA via authorization failure patterns\nindex=api_logs sourcetype=api_access status_code IN (401, 403)\n| bin _time span=5m\n| stats count as failure_count,\n        dc(uri_path) as unique_paths,\n        values(uri_path) as attempted_paths\n  by _time, src_ip, user_id\n| where failure_count > 10\n| eval attack_type = if(unique_paths > 5, \"enumeration\", \"brute_force\")\n```\n\n### Elastic SIEM Detection Rules\n\n```json\n{\n  \"rule\": {\n    \"name\": \"API Object Enumeration Detection\",\n    \"description\": \"Detects rapid sequential access to API objects with mixed authorization results\",\n    \"type\": \"threshold\",\n    \"index\": [\"api-access-*\"],\n    \"query\": {\n      \"bool\": {\n        \"must\": [\n          { \"regexp\": { \"url.path\": \"\u002Fapi\u002Fv[0-9]+\u002F[a-z]+\u002F[0-9]+\" } }\n        ],\n        \"should\": [\n          { \"term\": { \"http.response.status_code\": 200 } },\n          { \"term\": { \"http.response.status_code\": 403 } },\n          { \"term\": { \"http.response.status_code\": 401 } }\n        ]\n      }\n    },\n    \"threshold\": {\n      \"field\": [\"source.ip\"],\n      \"value\": 50,\n      \"cardinality\": [\n        { \"field\": \"url.path\", \"value\": 20 }\n      ]\n    },\n    \"schedule\": { \"interval\": \"5m\" },\n    \"severity\": \"high\",\n    \"risk_score\": 73,\n    \"tags\": [\"OWASP-API1\", \"BOLA\", \"Enumeration\"]\n  }\n}\n```\n\n### Custom Detection Script\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"API Enumeration Attack Detector\n\nAnalyzes API access logs to detect enumeration patterns\nincluding BOLA, IDOR, and sequential ID probing.\n\"\"\"\n\nimport re\nimport sys\nimport json\nfrom collections import defaultdict\nfrom datetime import datetime, timedelta\nfrom dataclasses import dataclass, field\nfrom typing import List, Dict, Optional\n\n@dataclass\nclass AccessRecord:\n    timestamp: datetime\n    source_ip: str\n    user_id: Optional[str]\n    method: str\n    path: str\n    status_code: int\n    object_id: Optional[str] = None\n\n@dataclass\nclass EnumerationAlert:\n    source_ip: str\n    user_id: Optional[str]\n    endpoint_pattern: str\n    unique_object_ids: int\n    total_requests: int\n    time_window_seconds: float\n    requests_per_second: float\n    auth_failure_ratio: float\n    severity: str\n    attack_type: str\n    sample_ids: List[str] = field(default_factory=list)\n\nclass EnumerationDetector:\n    # Regex patterns for extracting object IDs from API paths\n    ID_PATTERNS = [\n        re.compile(r'\u002Fapi\u002Fv\\d+\u002F(\\w+)\u002F(\\d+)'),           # Numeric IDs\n        re.compile(r'\u002Fapi\u002Fv\\d+\u002F(\\w+)\u002F([a-f0-9\\-]{36})'), # UUIDs\n        re.compile(r'\u002Fapi\u002Fv\\d+\u002F(\\w+)\u002F([a-zA-Z0-9]{20,})'), # Long alphanumeric IDs\n    ]\n\n    def __init__(self, time_window_minutes: int = 5,\n                 min_unique_ids: int = 15,\n                 max_requests_per_second: float = 5.0):\n        self.time_window = timedelta(minutes=time_window_minutes)\n        self.min_unique_ids = min_unique_ids\n        self.max_rps = max_requests_per_second\n        self.access_log: List[AccessRecord] = []\n\n    def parse_log_line(self, line: str) -> Optional[AccessRecord]:\n        \"\"\"Parse a common log format line into an AccessRecord.\"\"\"\n        log_pattern = re.compile(\n            r'(?P\u003Cip>[\\d.]+)\\s+\\S+\\s+(?P\u003Cuser>\\S+)\\s+'\n            r'\\[(?P\u003Ctime>[^\\]]+)\\]\\s+'\n            r'\"(?P\u003Cmethod>\\w+)\\s+(?P\u003Cpath>\\S+)\\s+\\S+\"\\s+'\n            r'(?P\u003Cstatus>\\d+)'\n        )\n        match = log_pattern.match(line)\n        if not match:\n            return None\n\n        path = match.group('path')\n        object_id = None\n        for pattern in self.ID_PATTERNS:\n            id_match = pattern.search(path)\n            if id_match:\n                object_id = id_match.group(2)\n                break\n\n        return AccessRecord(\n            timestamp=datetime.strptime(match.group('time'), '%d\u002F%b\u002F%Y:%H:%M:%S %z'),\n            source_ip=match.group('ip'),\n            user_id=match.group('user') if match.group('user') != '-' else None,\n            method=match.group('method'),\n            path=path,\n            status_code=int(match.group('status')),\n            object_id=object_id\n        )\n\n    def analyze(self, records: List[AccessRecord]) -> List[EnumerationAlert]:\n        \"\"\"Analyze access records for enumeration patterns.\"\"\"\n        alerts = []\n\n        # Group by source IP and endpoint pattern\n        grouped = defaultdict(list)\n        for record in records:\n            if record.object_id:\n                # Normalize endpoint by removing the specific object ID\n                endpoint = re.sub(r'\u002F[a-f0-9\\-]{36}', '\u002F{id}',\n                         re.sub(r'\u002F\\d+', '\u002F{id}', record.path))\n                key = (record.source_ip, record.user_id, endpoint)\n                grouped[key].append(record)\n\n        for (src_ip, user_id, endpoint), records_group in grouped.items():\n            if len(records_group) \u003C self.min_unique_ids:\n                continue\n\n            # Sort by timestamp\n            records_group.sort(key=lambda r: r.timestamp)\n\n            # Analyze time windows\n            window_start = 0\n            for window_start in range(len(records_group)):\n                window_records = []\n                for r in records_group[window_start:]:\n                    if r.timestamp - records_group[window_start].timestamp \u003C= self.time_window:\n                        window_records.append(r)\n\n                unique_ids = set(r.object_id for r in window_records)\n                if len(unique_ids) \u003C self.min_unique_ids:\n                    continue\n\n                time_span = (window_records[-1].timestamp -\n                           window_records[0].timestamp).total_seconds()\n                rps = len(window_records) \u002F max(time_span, 1)\n\n                auth_failures = sum(1 for r in window_records\n                                   if r.status_code in (401, 403))\n                failure_ratio = auth_failures \u002F len(window_records)\n\n                # Determine severity\n                if len(unique_ids) > 100:\n                    severity = \"critical\"\n                elif len(unique_ids) > 50 or failure_ratio > 0.5:\n                    severity = \"high\"\n                elif len(unique_ids) > 20:\n                    severity = \"medium\"\n                else:\n                    severity = \"low\"\n\n                # Determine attack type\n                ids_list = sorted([r.object_id for r in window_records\n                                  if r.object_id and r.object_id.isdigit()])\n                is_sequential = self._check_sequential(ids_list)\n                attack_type = \"sequential_enumeration\" if is_sequential else \"random_enumeration\"\n\n                alert = EnumerationAlert(\n                    source_ip=src_ip,\n                    user_id=user_id,\n                    endpoint_pattern=endpoint,\n                    unique_object_ids=len(unique_ids),\n                    total_requests=len(window_records),\n                    time_window_seconds=time_span,\n                    requests_per_second=round(rps, 2),\n                    auth_failure_ratio=round(failure_ratio, 2),\n                    severity=severity,\n                    attack_type=attack_type,\n                    sample_ids=list(unique_ids)[:10]\n                )\n                alerts.append(alert)\n                break  # One alert per group\n\n        return alerts\n\n    def _check_sequential(self, ids: List[str]) -> bool:\n        \"\"\"Check if numeric IDs follow a sequential pattern.\"\"\"\n        if len(ids) \u003C 5:\n            return False\n        try:\n            numeric_ids = sorted(int(i) for i in ids)\n            sequential_count = sum(\n                1 for i in range(1, len(numeric_ids))\n                if numeric_ids[i] - numeric_ids[i-1] \u003C= 2\n            )\n            return sequential_count \u002F len(numeric_ids) > 0.7\n        except ValueError:\n            return False\n\n\ndef main():\n    detector = EnumerationDetector(\n        time_window_minutes=5,\n        min_unique_ids=15\n    )\n\n    log_file = sys.argv[1] if len(sys.argv) > 1 else \"\u002Fvar\u002Flog\u002Fapi\u002Faccess.log\"\n    records = []\n    with open(log_file, 'r') as f:\n        for line in f:\n            record = detector.parse_log_line(line.strip())\n            if record:\n                records.append(record)\n\n    alerts = detector.analyze(records)\n\n    if alerts:\n        print(f\"\\n[!] {len(alerts)} enumeration attack(s) detected:\\n\")\n        for alert in alerts:\n            print(f\"  Source IP: {alert.source_ip}\")\n            print(f\"  User ID: {alert.user_id}\")\n            print(f\"  Endpoint: {alert.endpoint_pattern}\")\n            print(f\"  Unique IDs Accessed: {alert.unique_object_ids}\")\n            print(f\"  Requests\u002Fsec: {alert.requests_per_second}\")\n            print(f\"  Auth Failure Ratio: {alert.auth_failure_ratio}\")\n            print(f\"  Attack Type: {alert.attack_type}\")\n            print(f\"  Severity: {alert.severity.upper()}\")\n            print(f\"  Sample IDs: {alert.sample_ids}\")\n            print()\n    else:\n        print(\"[+] No enumeration attacks detected.\")\n\n\nif __name__ == \"__main__\":\n    main()\n```\n\n## Prevention Controls\n\n### Server-Side Authorization Enforcement\n\n```python\n# Always validate object ownership at the data layer\ndef get_user_order(request, order_id):\n    order = Order.objects.get(id=order_id)\n    if order.user_id != request.user.id:\n        raise PermissionDenied(\"Not authorized to access this order\")\n    return order\n```\n\n### Use Unpredictable Identifiers\n\n```python\nimport uuid\n\n# Use UUIDs instead of sequential integers\nclass Order(Model):\n    id = UUIDField(default=uuid.uuid4, primary_key=True)\n```\n\n### Implement Rate Limiting Per Endpoint\n\n```yaml\n# Kong rate limiting per API route\nplugins:\n  - name: rate-limiting\n    config:\n      minute: 30\n      policy: redis\n      limit_by: credential\n```\n\n## References\n\n- OWASP API1:2023 Broken Object Level Authorization: https:\u002F\u002Fowasp.org\u002FAPI-Security\u002Feditions\u002F2023\u002Fen\u002F0xa1-broken-object-level-authorization\u002F\n- Traceable.ai BOLA Deep Dive: https:\u002F\u002Fwww.traceable.ai\u002Fblog-post\u002Fa-deep-dive-on-the-most-critical-api-vulnerability----bola-broken-object-level-authorization\n- Cequence BOLA Prevention: https:\u002F\u002Fwww.cequence.ai\u002Fsolutions\u002Fbola-and-enumeration-attack-prevention\u002F\n- Cloudflare API Shield BOLA Detection: https:\u002F\u002Fcommunity.cloudflare.com\u002Ft\u002Fapi-shield-new-bola-vulnerability-detection-for-api-shield\u002F883021\n- Sycope IDOR Detection via HTTP Traffic Analysis: https:\u002F\u002Fwww.sycope.com\u002Fpost\u002Fidor-vulnerability-how-to-detect-an-attack-on-web-applications-through-http-traffic-analysis\n","# Detecting API Enumeration Attacks\n\n## Overview\n\nAPI 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.\n\n\n## When to Use\n\n- When investigating security incidents that require detecting api enumeration attacks\n- When building detection rules or threat hunting queries for this domain\n- When SOC analysts need structured procedures for this analysis type\n- When validating security monitoring coverage for related attack techniques\n\n## Prerequisites\n\n- API gateway or reverse proxy with logging enabled (Kong, AWS API Gateway, Apigee)\n- SIEM platform (Splunk, Elastic SIEM, or Microsoft Sentinel)\n- Access to API server logs with request details\n- Web Application Firewall (WAF) with API protection capabilities\n- Understanding of the API's authorization model and object identifier schemes\n\n## Attack Patterns to Detect\n\n### 1. Sequential ID Enumeration\n\nAttackers iterate through numeric or predictable identifiers:\n\n```\nGET \u002Fapi\u002Fv1\u002Fusers\u002F1001 -> 200 OK\nGET \u002Fapi\u002Fv1\u002Fusers\u002F1002 -> 200 OK\nGET \u002Fapi\u002Fv1\u002Fusers\u002F1003 -> 403 Forbidden\nGET \u002Fapi\u002Fv1\u002Fusers\u002F1004 -> 200 OK\nGET \u002Fapi\u002Fv1\u002Fusers\u002F1005 -> 200 OK\n...\n```\n\n**Detection Indicators:**\n- Rapid sequential requests to the same endpoint with incrementing IDs\n- Mix of 200\u002F403\u002F401 responses from same source\n- Request rate exceeding normal user behavior\n- Access to resources outside authenticated user's scope\n\n### 2. UUID\u002FGUID Enumeration\n\nEven non-sequential identifiers can be enumerated if leaked through other endpoints:\n\n```\n# Attacker first harvests UUIDs from a list endpoint\nGET \u002Fapi\u002Fv1\u002Fposts?page=1  -> Returns post objects with author UUIDs\n\n# Then uses those UUIDs to access restricted user data\nGET \u002Fapi\u002Fv1\u002Fusers\u002Fa3f2c1e4-... -> Private user profile\nGET \u002Fapi\u002Fv1\u002Fusers\u002Fb7d9e8f1-... -> Private user profile\n```\n\n### 3. Parameter Tampering Enumeration\n\n```\n# Authenticated as user_id=100, attempting to access other users' orders\nGET \u002Fapi\u002Fv1\u002Forders?user_id=101\nGET \u002Fapi\u002Fv1\u002Forders?user_id=102\nGET \u002Fapi\u002Fv1\u002Forders?user_id=103\n```\n\n## Detection Rules\n\n### Splunk Detection Queries\n\n```spl\n# Detect sequential ID enumeration on API endpoints\nindex=api_logs sourcetype=api_access\n| rex field=uri_path \"(?\u003Cendpoint>\u002Fapi\u002Fv\\d+\u002F\\w+\u002F)(?\u003Cobject_id>\\d+)\"\n| stats count as request_count,\n        dc(object_id) as unique_ids,\n        values(status_code) as status_codes,\n        min(_time) as first_seen,\n        max(_time) as last_seen\n  by src_ip, endpoint, user_session\n| eval time_span = last_seen - first_seen\n| eval requests_per_second = request_count \u002F max(time_span, 1)\n| where unique_ids > 20 AND requests_per_second > 2\n| eval severity = case(\n    unique_ids > 100, \"critical\",\n    unique_ids > 50, \"high\",\n    unique_ids > 20, \"medium\",\n    1==1, \"low\"\n  )\n| sort - unique_ids\n| table src_ip, endpoint, unique_ids, request_count, requests_per_second,\n        status_codes, severity\n\n# Detect BOLA via authorization failure patterns\nindex=api_logs sourcetype=api_access status_code IN (401, 403)\n| bin _time span=5m\n| stats count as failure_count,\n        dc(uri_path) as unique_paths,\n        values(uri_path) as attempted_paths\n  by _time, src_ip, user_id\n| where failure_count > 10\n| eval attack_type = if(unique_paths > 5, \"enumeration\", \"brute_force\")\n```\n\n### Elastic SIEM Detection Rules\n\n```json\n{\n  \"rule\": {\n    \"name\": \"API Object Enumeration Detection\",\n    \"description\": \"Detects rapid sequential access to API objects with mixed authorization results\",\n    \"type\": \"threshold\",\n    \"index\": [\"api-access-*\"],\n    \"query\": {\n      \"bool\": {\n        \"must\": [\n          { \"regexp\": { \"url.path\": \"\u002Fapi\u002Fv[0-9]+\u002F[a-z]+\u002F[0-9]+\" } }\n        ],\n        \"should\": [\n          { \"term\": { \"http.response.status_code\": 200 } },\n          { \"term\": { \"http.response.status_code\": 403 } },\n          { \"term\": { \"http.response.status_code\": 401 } }\n        ]\n      }\n    },\n    \"threshold\": {\n      \"field\": [\"source.ip\"],\n      \"value\": 50,\n      \"cardinality\": [\n        { \"field\": \"url.path\", \"value\": 20 }\n      ]\n    },\n    \"schedule\": { \"interval\": \"5m\" },\n    \"severity\": \"high\",\n    \"risk_score\": 73,\n    \"tags\": [\"OWASP-API1\", \"BOLA\", \"Enumeration\"]\n  }\n}\n```\n\n### Custom Detection Script\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"API Enumeration Attack Detector\n\nAnalyzes API access logs to detect enumeration patterns\nincluding BOLA, IDOR, and sequential ID probing.\n\"\"\"\n\nimport re\nimport sys\nimport json\nfrom collections import defaultdict\nfrom datetime import datetime, timedelta\nfrom dataclasses import dataclass, field\nfrom typing import List, Dict, Optional\n\n@dataclass\nclass AccessRecord:\n    timestamp: datetime\n    source_ip: str\n    user_id: Optional[str]\n    method: str\n    path: str\n    status_code: int\n    object_id: Optional[str] = None\n\n@dataclass\nclass EnumerationAlert:\n    source_ip: str\n    user_id: Optional[str]\n    endpoint_pattern: str\n    unique_object_ids: int\n    total_requests: int\n    time_window_seconds: float\n    requests_per_second: float\n    auth_failure_ratio: float\n    severity: str\n    attack_type: str\n    sample_ids: List[str] = field(default_factory=list)\n\nclass EnumerationDetector:\n    # Regex patterns for extracting object IDs from API paths\n    ID_PATTERNS = [\n        re.compile(r'\u002Fapi\u002Fv\\d+\u002F(\\w+)\u002F(\\d+)'),           # Numeric IDs\n        re.compile(r'\u002Fapi\u002Fv\\d+\u002F(\\w+)\u002F([a-f0-9\\-]{36})'), # UUIDs\n        re.compile(r'\u002Fapi\u002Fv\\d+\u002F(\\w+)\u002F([a-zA-Z0-9]{20,})'), # Long alphanumeric IDs\n    ]\n\n    def __init__(self, time_window_minutes: int = 5,\n                 min_unique_ids: int = 15,\n                 max_requests_per_second: float = 5.0):\n        self.time_window = timedelta(minutes=time_window_minutes)\n        self.min_unique_ids = min_unique_ids\n        self.max_rps = max_requests_per_second\n        self.access_log: List[AccessRecord] = []\n\n    def parse_log_line(self, line: str) -> Optional[AccessRecord]:\n        \"\"\"Parse a common log format line into an AccessRecord.\"\"\"\n        log_pattern = re.compile(\n            r'(?P\u003Cip>[\\d.]+)\\s+\\S+\\s+(?P\u003Cuser>\\S+)\\s+'\n            r'\\[(?P\u003Ctime>[^\\]]+)\\]\\s+'\n            r'\"(?P\u003Cmethod>\\w+)\\s+(?P\u003Cpath>\\S+)\\s+\\S+\"\\s+'\n            r'(?P\u003Cstatus>\\d+)'\n        )\n        match = log_pattern.match(line)\n        if not match:\n            return None\n\n        path = match.group('path')\n        object_id = None\n        for pattern in self.ID_PATTERNS:\n            id_match = pattern.search(path)\n            if id_match:\n                object_id = id_match.group(2)\n                break\n\n        return AccessRecord(\n            timestamp=datetime.strptime(match.group('time'), '%d\u002F%b\u002F%Y:%H:%M:%S %z'),\n            source_ip=match.group('ip'),\n            user_id=match.group('user') if match.group('user') != '-' else None,\n            method=match.group('method'),\n            path=path,\n            status_code=int(match.group('status')),\n            object_id=object_id\n        )\n\n    def analyze(self, records: List[AccessRecord]) -> List[EnumerationAlert]:\n        \"\"\"Analyze access records for enumeration patterns.\"\"\"\n        alerts = []\n\n        # Group by source IP and endpoint pattern\n        grouped = defaultdict(list)\n        for record in records:\n            if record.object_id:\n                # Normalize endpoint by removing the specific object ID\n                endpoint = re.sub(r'\u002F[a-f0-9\\-]{36}', '\u002F{id}',\n                         re.sub(r'\u002F\\d+', '\u002F{id}', record.path))\n                key = (record.source_ip, record.user_id, endpoint)\n                grouped[key].append(record)\n\n        for (src_ip, user_id, endpoint), records_group in grouped.items():\n            if len(records_group) \u003C self.min_unique_ids:\n                continue\n\n            # Sort by timestamp\n            records_group.sort(key=lambda r: r.timestamp)\n\n            # Analyze time windows\n            window_start = 0\n            for window_start in range(len(records_group)):\n                window_records = []\n                for r in records_group[window_start:]:\n                    if r.timestamp - records_group[window_start].timestamp \u003C= self.time_window:\n                        window_records.append(r)\n\n                unique_ids = set(r.object_id for r in window_records)\n                if len(unique_ids) \u003C self.min_unique_ids:\n                    continue\n\n                time_span = (window_records[-1].timestamp -\n                           window_records[0].timestamp).total_seconds()\n                rps = len(window_records) \u002F max(time_span, 1)\n\n                auth_failures = sum(1 for r in window_records\n                                   if r.status_code in (401, 403))\n                failure_ratio = auth_failures \u002F len(window_records)\n\n                # Determine severity\n                if len(unique_ids) > 100:\n                    severity = \"critical\"\n                elif len(unique_ids) > 50 or failure_ratio > 0.5:\n                    severity = \"high\"\n                elif len(unique_ids) > 20:\n                    severity = \"medium\"\n                else:\n                    severity = \"low\"\n\n                # Determine attack type\n                ids_list = sorted([r.object_id for r in window_records\n                                  if r.object_id and r.object_id.isdigit()])\n                is_sequential = self._check_sequential(ids_list)\n                attack_type = \"sequential_enumeration\" if is_sequential else \"random_enumeration\"\n\n                alert = EnumerationAlert(\n                    source_ip=src_ip,\n                    user_id=user_id,\n                    endpoint_pattern=endpoint,\n                    unique_object_ids=len(unique_ids),\n                    total_requests=len(window_records),\n                    time_window_seconds=time_span,\n                    requests_per_second=round(rps, 2),\n                    auth_failure_ratio=round(failure_ratio, 2),\n                    severity=severity,\n                    attack_type=attack_type,\n                    sample_ids=list(unique_ids)[:10]\n                )\n                alerts.append(alert)\n                break  # One alert per group\n\n        return alerts\n\n    def _check_sequential(self, ids: List[str]) -> bool:\n        \"\"\"Check if numeric IDs follow a sequential pattern.\"\"\"\n        if len(ids) \u003C 5:\n            return False\n        try:\n            numeric_ids = sorted(int(i) for i in ids)\n            sequential_count = sum(\n                1 for i in range(1, len(numeric_ids))\n                if numeric_ids[i] - numeric_ids[i-1] \u003C= 2\n            )\n            return sequential_count \u002F len(numeric_ids) > 0.7\n        except ValueError:\n            return False\n\n\ndef main():\n    detector = EnumerationDetector(\n        time_window_minutes=5,\n        min_unique_ids=15\n    )\n\n    log_file = sys.argv[1] if len(sys.argv) > 1 else \"\u002Fvar\u002Flog\u002Fapi\u002Faccess.log\"\n    records = []\n    with open(log_file, 'r') as f:\n        for line in f:\n            record = detector.parse_log_line(line.strip())\n            if record:\n                records.append(record)\n\n    alerts = detector.analyze(records)\n\n    if alerts:\n        print(f\"\\n[!] {len(alerts)} enumeration attack(s) detected:\\n\")\n        for alert in alerts:\n            print(f\"  Source IP: {alert.source_ip}\")\n            print(f\"  User ID: {alert.user_id}\")\n            print(f\"  Endpoint: {alert.endpoint_pattern}\")\n            print(f\"  Unique IDs Accessed: {alert.unique_object_ids}\")\n            print(f\"  Requests\u002Fsec: {alert.requests_per_second}\")\n            print(f\"  Auth Failure Ratio: {alert.auth_failure_ratio}\")\n            print(f\"  Attack Type: {alert.attack_type}\")\n            print(f\"  Severity: {alert.severity.upper()}\")\n            print(f\"  Sample IDs: {alert.sample_ids}\")\n            print()\n    else:\n        print(\"[+] No enumeration attacks detected.\")\n\n\nif __name__ == \"__main__\":\n    main()\n```\n\n## Prevention Controls\n\n### Server-Side Authorization Enforcement\n\n```python\n# Always validate object ownership at the data layer\ndef get_user_order(request, order_id):\n    order = Order.objects.get(id=order_id)\n    if order.user_id != request.user.id:\n        raise PermissionDenied(\"Not authorized to access this order\")\n    return order\n```\n\n### Use Unpredictable Identifiers\n\n```python\nimport uuid\n\n# Use UUIDs instead of sequential integers\nclass Order(Model):\n    id = UUIDField(default=uuid.uuid4, primary_key=True)\n```\n\n### Implement Rate Limiting Per Endpoint\n\n```yaml\n# Kong rate limiting per API route\nplugins:\n  - name: rate-limiting\n    config:\n      minute: 30\n      policy: redis\n      limit_by: credential\n```\n\n## References\n\n- OWASP API1:2023 Broken Object Level Authorization: https:\u002F\u002Fowasp.org\u002FAPI-Security\u002Feditions\u002F2023\u002Fen\u002F0xa1-broken-object-level-authorization\u002F\n- Traceable.ai BOLA Deep Dive: https:\u002F\u002Fwww.traceable.ai\u002Fblog-post\u002Fa-deep-dive-on-the-most-critical-api-vulnerability----bola-broken-object-level-authorization\n- Cequence BOLA Prevention: https:\u002F\u002Fwww.cequence.ai\u002Fsolutions\u002Fbola-and-enumeration-attack-prevention\u002F\n- Cloudflare API Shield BOLA Detection: https:\u002F\u002Fcommunity.cloudflare.com\u002Ft\u002Fapi-shield-new-bola-vulnerability-detection-for-api-shield\u002F883021\n- Sycope IDOR Detection via HTTP Traffic Analysis: https:\u002F\u002Fwww.sycope.com\u002Fpost\u002Fidor-vulnerability-how-to-detect-an-attack-on-web-applications-through-http-traffic-analysis\n",{"name":5,"tags":54,"author":55,"domain":48,"license":15,"version":56,"subdomain":46,"description":7},[46,30,42,41,32,39,45,38],"mahipal","1.0","main","4d2fb89cdfb75f3f6fd3c6c5ec9ad90ea129eb3c","ai-agent-skills\u002F21-external-registries\u002F08-pinkpixel-collection\u002Fdetecting-api-enumeration-attacks",2,"https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai","https:\u002F\u002Fgithub.com\u002Fluokai0","a solo builder.","2026-05-06 04:29:04",{"source":8,"skillName":5,"commands":66,"prompt":76,"zipAvailable":77},[67,70,73],{"tool":68,"command":69},"npx","npx skills add luokai0\u002Fai-agent-skills-by-luo-kai --skill detecting-api-enumeration-attacks",{"tool":71,"command":72},"bunx","bunx skills add luokai0\u002Fai-agent-skills-by-luo-kai --skill detecting-api-enumeration-attacks",{"tool":74,"command":75},"pnpm","pnpm dlx skills add luokai0\u002Fai-agent-skills-by-luo-kai --skill detecting-api-enumeration-attacks","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F21-external-registries\u002F08-pinkpixel-collection\u002Fdetecting-api-enumeration-attacks\u002FSKILL.md",true,[79,84,90],{"path":80,"resourceType":80,"resourceTypeDesc":81,"sizeBytes":82,"sourceHtmlUrl":83},"LICENSE","许可证",11255,"https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F21-external-registries\u002F08-pinkpixel-collection\u002Fdetecting-api-enumeration-attacks\u002FLICENSE",{"path":85,"resourceType":86,"resourceTypeDesc":87,"sizeBytes":88,"sourceHtmlUrl":89},"references\u002Fapi-reference.md","REFERENCE","参考文档",1931,"https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F21-external-registries\u002F08-pinkpixel-collection\u002Fdetecting-api-enumeration-attacks\u002Freferences\u002Fapi-reference.md",{"path":91,"resourceType":92,"resourceTypeDesc":93,"sizeBytes":94,"sourceHtmlUrl":95},"scripts\u002Fagent.py","SCRIPT","脚本",6726,"https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F21-external-registries\u002F08-pinkpixel-collection\u002Fdetecting-api-enumeration-attacks\u002Fscripts\u002Fagent.py",[97,125,142,170,203,233],{"skillNo":98,"name":99,"nameZh":6,"description":100,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":101,"licenseFileUrl":6,"sourceHtmlUrl":102,"categories":103,"keywords":104,"publishedAt":49},"01M6F2SKTE208174C7S7JJCZC7","write-contracts","Generates secure Aptos Move V2 smart contracts with Object model, Digital Asset integration, security patterns, and storage type guidance. Includes comprehensive storage decision framework for optimal data structure selection. Triggers on: 'write contract', 'create NFT collection', 'build marketplace', 'implement minting', 'generate Move module', 'create token contract', 'build DAO', 'implement staking'. Ask storage questions when: 'store', 'track', 'registry', 'mapping', 'list', 'collection'.","MIT","https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F22-clawhub-skills\u002Fwrite-contracts\u002FSKILL.md",[],[105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124],"write","contracts","write contracts","storage","secure","create","generate","collection","model","decision","ask","smart-contracts","selection","objects","structure","nft","token","aptos","critical","move",{"skillNo":126,"name":127,"nameZh":6,"description":128,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":101,"licenseFileUrl":6,"sourceHtmlUrl":129,"categories":130,"keywords":131,"publishedAt":49},"01M6F2RFXJ6T9MKW0A7N7GM45B","web-search","通用网络搜索技能，支持多引擎搜索（百度、必应、DuckDuckGo），无需API密钥即可获取实时信息","https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F22-clawhub-skills\u002Fweb-search-ex-skill\u002FSKILL.md",[],[132,133,134,135,136,137,138,139,140,141],"web","search","web search","搜索","baidu","bing","duckduckgo","百度","多引擎","internet",{"skillNo":143,"name":144,"nameZh":6,"description":145,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":101,"licenseFileUrl":6,"sourceHtmlUrl":146,"categories":147,"keywords":151,"publishedAt":49},"01M6F2K968G1FZEZFPW2E6B222","solo-build","Execute implementation plan tasks with TDD workflow, auto-commit, and phase gates. Use when user says \"build it\", \"start building\", \"execute plan\", \"implement tasks\", \"ship it\", or references a track ID. Do NOT use for planning (use \u002Fplan) or scaffolding (use \u002Fscaffold).","https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F22-clawhub-skills\u002Fsolo-build\u002FSKILL.md",[148],{"categoryNo":149,"categoryName":150,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000023","Skill与智能体开发",[152,153,154,155,156,157,158,159,133,160,161,162,105,163,164,165,166,167,168,169],"build","solo","solo build","MCP","workflow","commit","tasks","code","Bash","plan","read","auto","references","context7","query","scaffolding","ship it","project",{"skillNo":171,"name":172,"nameZh":6,"description":173,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":101,"licenseFileUrl":6,"sourceHtmlUrl":174,"categories":175,"keywords":182,"publishedAt":49},"01M6F2GKN39SGHSPWYB3662YC8","react-email","Use when building HTML email templates with React components, adding a visual email editor to an application using the React Email visual editor, rendering emails to HTML, or sending emails with Resend. Covers welcome emails, password resets, notifications, order confirmations, newsletters, transactional emails, and the embeddable email editor component.","https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F22-clawhub-skills\u002Freact-email-skills\u002FSKILL.md",[176,179],{"categoryNo":177,"categoryName":178,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000005","邮件与沟通",{"categoryNo":180,"categoryName":181,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000009","前端开发",[183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202],"react","email","react email","github","editor","components","react components","component","welcome","https","notifications","password","node","use","html","resend","visual","emails","rendering","with",{"skillNo":204,"name":205,"nameZh":6,"description":206,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":101,"licenseFileUrl":6,"sourceHtmlUrl":207,"categories":208,"keywords":215,"publishedAt":49},"01M6F2FBVGVDFSG8SSFJGXA40C","APITester Agent-Driven API Testing","Test API endpoints and document responses. Define tests in plain English, run them, get formatted results. Agent-driven Postman alternative.","https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F22-clawhub-skills\u002Fopenclaw-api-tester\u002FSKILL.md",[209,212,213,214],{"categoryNo":210,"categoryName":211,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000008","测试与质量",{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},{"categoryNo":149,"categoryName":150,"taxonomyType":21,"taxonomyTypeDesc":22},{"categoryNo":24,"categoryName":25,"taxonomyType":26,"taxonomyTypeDesc":27},[216,29,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232],"testing","api testing","driven","APITester Agent Driven API Testing","test","run","postman","results","plain english","tester","endpoints","document","get","define","tests","english","api-tester",{"skillNo":234,"name":235,"nameZh":6,"description":236,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":101,"licenseFileUrl":6,"sourceHtmlUrl":237,"categories":238,"keywords":239,"publishedAt":49},"01M6F273Y3NGAPVJZ608BC0G9G","hubspot-implementation-plan","Generate a phased implementation plan from a HubSpot audit report. Creates prioritized, sequenced cleanup processes with effort estimates, dependencies, and automation feasibility. Use after running \u002Fhubspot-audit.","https:\u002F\u002Fgithub.com\u002Fluokai0\u002Fai-agent-skills-by-luo-kai\u002Fblob\u002Fmain\u002Fai-agent-skills\u002F22-clawhub-skills\u002Fhubspot-implementation-plan\u002FSKILL.md",[],[161,240,241,242,243,244,245,111,246,247,248,249,250,196,251,252,202,253],"implementation","hubspot","hubspot implementation plan","automation","feasibility","cleanup","planning","report","audit","audit report","phased implementation","dependencies","processes","hubspot audit"]