[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M71GPBKFKPKDCA0DYC3XQ2R3":3,"skill-same:01M71GPBKFKPKDCA0DYC3XQ2R3":103},{"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":76,"commitSha":77,"skillDirectory":78,"forksCount":14,"repositoryHtmlUrl":79,"repositoryHomepageUrl":6,"ownerHtmlUrl":80,"ownerBlogUrl":6,"ownerDescription":81,"updatedAt":82,"install":83,"resources":96},"01M71GPBKFKPKDCA0DYC3XQ2R3","api-enumeration-enum",null,"Detect and prevent API enumeration attacks including BOLA and IDOR exploitation by monitoring sequential identifier access patterns and authorization failures.","DCx7C5\u002Fai-marketplace","DCx7C5","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F42419559?v=4","01M71C01G2AZV3NTNGWAWSHJPP","DC","01M71C01GQW6G50S2BYMS7PP3E",0,"MIT","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fweb-application\u002Fapi\u002Fenumeration\u002Fenum\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 enum","enum","enumeration","api","broken","rate","top","sonnet","de","patterns","cm","read","security","access","Bash","owasp-api","owasp","api-security","monitoring","cybersecurity","2026-11-10 10:12:30",false,"---\nname: api-enumeration-enum\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:\n- api-security\n- enumeration\n- bola\n- idor\n- broken-object-level-authorization\n- owasp-api-top-10\n- access-control\n- rate-limiting\nnist_csf:\n- PR.PS-01\n- ID.RA-01\n- PR.DS-10\n- DE.CM-01\nmodel: sonnet\nmaxTurns: 20\ntools: [Read, Bash, Glob, Grep]\nmitre_attack:\n- T1562.001\ncwe:\n- CWE-639\ncapec: []\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",{"cwe":54,"name":5,"tags":56,"capec":63,"model":36,"tools":64,"domain":48,"maxTurns":68,"nist_csf":69,"subdomain":46,"description":7,"mitre_attack":74},[55],"CWE-639",[46,31,57,58,59,60,61,62],"bola","idor","broken-object-level-authorization","owasp-api-top-10","access-control","rate-limiting",[],[65,43,66,67],"Read","Glob","Grep",20,[70,71,72,73],"PR.PS-01","ID.RA-01","PR.DS-10","DE.CM-01",[75],"T1562.001","main","a91f1293287ffa9f4f1b8f486cd6e835a1568c84","skills\u002Fweb-application\u002Fapi\u002Fenumeration\u002Fenum","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace","https:\u002F\u002Fgithub.com\u002FDCx7C5","#Python","2026-09-01 11:21:00",{"source":8,"skillName":5,"commands":84,"prompt":94,"zipAvailable":95},[85,88,91],{"tool":86,"command":87},"npx","npx skills add DCx7C5\u002Fai-marketplace --skill api-enumeration-enum",{"tool":89,"command":90},"bunx","bunx skills add DCx7C5\u002Fai-marketplace --skill api-enumeration-enum",{"tool":92,"command":93},"pnpm","pnpm dlx skills add DCx7C5\u002Fai-marketplace --skill api-enumeration-enum","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fweb-application\u002Fapi\u002Fenumeration\u002Fenum\u002FSKILL.md",true,[97],{"path":98,"resourceType":99,"resourceTypeDesc":100,"sizeBytes":101,"sourceHtmlUrl":102},"index.json","REFERENCE","参考文档",650,"https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fweb-application\u002Fapi\u002Fenumeration\u002Fenum\u002Findex.json",[104,127,148,169,191,206],{"skillNo":105,"name":106,"nameZh":6,"description":107,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":108,"categories":109,"keywords":110,"publishedAt":49},"01M71HAPZ01KQ30RKTB0FFSQ05","services-wmi-persistence-detect","Detect WMI event subscription persistence by enumerating ActiveScriptEventConsumer, CommandLineEventConsumer, and permanent subscriptions in the WMI repository.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fservices\u002Fwmi\u002Fpersistence\u002Fdetect\u002FSKILL.md",[],[111,112,113,114,115,37,39,116,117,118,119,120,121,122,123,124,125,48,126],"services","detect","services wmi persistence detect","wmi","persistence","process","activescript","event","subscriptions","commandline-consumer","repository","subscription","event-subscription","t1546.003","forensics","process-forensics",{"skillNo":128,"name":129,"nameZh":6,"description":130,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":131,"categories":132,"keywords":133,"publishedAt":49},"01M71HAK6JTTTS229T17WJMMCG","services-wmi-exec-exploit","Perform lateral movement across Windows networks using WMI-based remote execution techniques including Impacket wmiexec.py, CrackMapExec, and native WMI commands for stealthy post-exploitation during red team engagements.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fservices\u002Fwmi\u002Fexec\u002Fexploit\u002FSKILL.md",[],[134,111,135,114,136,137,138,48,43,139,140,141,142,143,37,144,145,40,146,147],"exploit","services wmi exec exploit","exec","remote","traffic","analysis","team","across","crackmapexec","native","command","lateral movement","lateral-movement","Impacket",{"skillNo":149,"name":150,"nameZh":6,"description":151,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":152,"categories":153,"keywords":154,"publishedAt":49},"01M71HAG6MHKNQV8KDZKMT4886","registry-artifact-extract","Extract and analyze Windows Registry hives to uncover user activity, installed software, autostart entries, and evidence of system compromise.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fregistry\u002Fartifact\u002Fextract\u002FSKILL.md",[],[155,156,157,158,159,160,48,43,161,139,162,163,37,40,164,165,166,167,168,36],"artifact","registry","registry artifact extract","extract","evidence-collection","artifact-analysis","collection","analyze","uncover","software","activity","digital-forensics","windows-registry","regripper",{"skillNo":170,"name":171,"nameZh":6,"description":172,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":173,"categories":174,"keywords":175,"publishedAt":49},"01M71HACR4A8XTWTTSXK4124AA","processes-token-impersonate-detect","Detect Windows token impersonation and privilege abuse including SeImpersonatePrivilege exploitation via Potato attacks and token stealing techniques.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fprocesses\u002Ftoken\u002Fimpersonate\u002Fdetect\u002FSKILL.md",[],[112,176,177,178,179,180,181,39,182,48,126,183,184,185,186,187,188,189,190,37],"processes token impersonate detect","token","processes","attacks","windows","escalation","techniques","privilege-escalation","seimpersonate","token-impersonation","printspoofer","exploitation","potato","impersonation","via",{"skillNo":192,"name":193,"nameZh":6,"description":194,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":195,"categories":196,"keywords":197,"publishedAt":49},"01M71HAABSB4Z6QFSXEG00R4RK","processes-thread-injection-detect","Detect Windows thread injection techniques including CreateRemoteThread, QueueUserAPC, NtCreateThreadEx, and thread hijacking via process memory analysis.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fprocesses\u002Fthread\u002Finjection\u002Fdetect\u002FSKILL.md",[],[198,199,112,200,178,180,201,39,202,182,48,126,139,32,203,204,205,190,37,116],"thread","processes thread injection detect","injection","memory","process-injection","apc-injection","thread-injection","nt-api",{"skillNo":207,"name":208,"nameZh":6,"description":209,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":210,"categories":211,"keywords":212,"publishedAt":49},"01M71HA7H311V5G14WMX58HQSS","processes-hollow-technique-detect","Detect process hollowing (RunPE) by identifying processes with mismatched image paths between PEB and VAD tree, or unmapped PE headers in memory.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fprocesses\u002Fhollow\u002Ftechnique\u002Fdetect\u002FSKILL.md",[],[213,112,178,214,201,39,215,216,48,126,217,218,219,220,221,222,37,116,223,224],"processes hollow technique detect","tree","memory-forensics","process-hollow","peb","runpe","image","pe-header","in memory","with","mismatched","headers"]