I'll create a Python-based IDOR vulnerability detection tool with the features you've requested. This tool will help identify potential IDOR vulnerabilities by systematically testing API endpoints with modified parameters.
#!/usr/bin/env python3
# IDOR Vulnerability Scanner
# A tool for detecting Insecure Direct Object Reference vulnerabilities in web applications
import argparse
import json
import re
import time
import uuid
import base64
import random
import logging
from urllib.parse import urlparse, parse_qs, urlencode
import requests
from requests.exceptions import RequestException
from concurrent.futures import ThreadPoolExecutor
from typing import Dict, List, Any, Tuple, Set, Optional
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("idor_scanner.log"),
logging.StreamHandler()
]
)
logger = logging.getLogger("idor_scanner")
class IDORScanner:
def __init__(self, config_path: str, urls_path: str, output_path: str = "idor_findings.json"):
self.config = self._load_config(config_path)
self.urls = self._load_urls(urls_path)
self.output_path = output_path
self.findings = []
self.user_agents = [
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.1 Safari/605.1.15",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:94.0) Gecko/20100101 Firefox/94.0"
]
# PII detection patterns
self.pii_patterns = {
"email": r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}',
"phone": r'\b(\+\d{1,2}\s?)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}\b',
"ssn": r'\b\d{3}-\d{2}-\d{4}\b',
"credit_card": r'\b(?:\d{4}[- ]?){3}\d{4}\b',
"address": r'\b\d+\s+[A-Za-z0-9\s,]+(?:Avenue|Lane|Road|Boulevard|Drive|Street|Ave|Dr|Rd|Blvd|Ln|St)\.?\b',
"name": r'\b[A-Z][a-z]+ [A-Z][a-z]+\b'
}
# ID patterns to look for in URLs and JSON bodies
self.id_patterns = [
"id", "user_id", "user", "account", "account_id", "customer", "customer_id",
"order", "order_id", "profile", "profile_id", "object", "object_id", "uid",
"uuid", "document", "doc", "record", "item", "member", "subscription"
]
# Initialize sessions
self.sessions = self._init_sessions()
def _load_config(self, config_path: str) -> Dict:
"""Load configuration from JSON file"""
try:
with open(config_path, 'r') as f:
config = json.load(f)
logger.info(f"Loaded configuration from {config_path}")
return config
except Exception as e:
logger.error(f"Failed to load config: {str(e)}")
raise
def _load_urls(self, urls_path: str) -> List[str]:
"""Load URLs from text file"""
try:
with open(urls_path, 'r') as f:
urls = [line.strip() for line in f if line.strip()]
logger.info(f"Loaded {len(urls)} URLs from {urls_path}")
return urls
except Exception as e:
logger.error(f"Failed to load URLs: {str(e)}")
raise
def _init_sessions(self) -> Dict[str, requests.Session]:
"""Initialize sessions with authentication tokens"""
sessions = {}
for user, auth_data in self.config.get("auth", {}).items():
session = requests.Session()
# Set headers (Bearer token, etc.)
if "headers" in auth_data:
session.headers.update(auth_data["headers"])
# Set cookies
if "cookies" in auth_data:
for name, value in auth_data["cookies"].items():
session.cookies.set(name, value)
sessions[user] = session
logger.info(f"Initialized session for user: {user}")
return sessions
def _extract_ids_from_url(self, url: str) -> List[Tuple[str, str, str]]:
"""Extract potential IDs from URL path and query parameters"""
parsed_url = urlparse(url)
path_segments = parsed_url.path.strip('/').split('/')
query_params = parse_qs(parsed_url.query)
extracted_ids = []
# Check path segments for IDs
for i in range(len(path_segments) - 1):
segment = path_segments[i].lower()
if any(pattern in segment for pattern in self.id_patterns):
if i + 1 < len(path_segments) and path_segments[i + 1].strip():
extracted_ids.append(("path", segment, path_segments[i + 1]))
# Check query parameters for IDs
for param, values in query_params.items():
param_lower = param.lower()
if any(pattern in param_lower for pattern in self.id_patterns) and values:
extracted_ids.append(("query", param, values[0]))
return extracted_ids
def _extract_ids_from_json(self, json_data: Dict) -> List[Tuple[str, str]]:
"""Recursively extract potential IDs from JSON data"""
extracted_ids = []
def extract_from_dict(data, prefix=""):
if not isinstance(data, dict):
return
for key, value in data.items():
current_path = f"{prefix}.{key}" if prefix else key
# Check if this key looks like an ID field
if any(pattern in key.lower() for pattern in self.id_patterns):
if isinstance(value, (str, int)):
extracted_ids.append((current_path, str(value)))
# Recurse into nested objects
if isinstance(value, dict):
extract_from_dict(value, current_path)
elif isinstance(value, list):
for i, item in enumerate(value):
if isinstance(item, dict):
extract_from_dict(item, f"{current_path}[{i}]")
extract_from_dict(json_data)
return extracted_ids
def _generate_mutations(self, original_value: str) -> List[str]:
"""Generate various mutations of the original ID value"""
mutations = []
# Try to convert to int if possible
try:
original_int = int(original_value)
# Increment/decrement
mutations.extend([
str(original_int + 1),
str(original_int - 1),
str(original_int + 10),
str(original_int - 10),
str(original_int + 100),
str(original_int - 100),
"0",
"1",
"99999"
])
# Zero-padded
mutations.append(f"{original_int:08d}")
except ValueError:
# Not an integer, might be UUID or other format
pass
# String variations
if len(original_value) > 0:
# Base64 encode
try:
b64_encoded = base64.b64encode(original_value.encode()).decode()
mutations.append(b64_encoded)
except:
pass
# Quoted version
mutations.append(f'"{original_value}"')
# UUID variations if it looks like a UUID
uuid_pattern = r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'
if re.match(uuid_pattern, original_value.lower()):
mutations.append(str(uuid.uuid4()))
# Add IDs from wordlist if available
if "test_ids" in self.config:
mutations.extend(self.config["test_ids"])
return mutations
def _modify_url(self, url: str, id_location: str, id_name: str, original_value: str, new_value: str) -> str:
"""Modify URL by replacing the specified ID with a new value"""
parsed_url = urlparse(url)
if id_location == "path":
path_segments = parsed_url.path.strip('/').split('/')
for i in range(len(path_segments) - 1):
if path_segments[i].lower() == id_name.lower() and i + 1 < len(path_segments):
if path_segments[i + 1] == original_value:
path_segments[i + 1] = new_value
break
new_path = '/' + '/'.join(path_segments)
return parsed_url._replace(path=new_path).geturl()
elif id_location == "query":
query_params = parse_qs(parsed_url.query)
if id_name in query_params:
query_params[id_name] = [new_value]
new_query = urlencode(query_params, doseq=True)
return parsed_url._replace(query=new_query).geturl()
return url
def _modify_json_body(self, json_body: Dict, id_path: str, new_value: str) -> Dict:
"""Modify JSON body by replacing the specified ID with a new value"""
result = json_body.copy()
# Handle array notation in path like "users[0].id"
parts = []
current_part = ""
array_indices = []
for char in id_path:
if char == '[':
parts.append(current_part)
current_part = ""
elif char == ']':
array_indices.append(int(current_part))
current_part = ""
elif char == '.':
if current_part:
parts.append(current_part)
current_part = ""
else:
current_part += char
if current_part:
parts.append(current_part)
# Navigate to the target location
target = result
for i, part in enumerate(parts[:-1]):
if part in target:
target = target[part]
else:
# Path doesn't exist
return result
# Set the new value
last_part = parts[-1]
if last_part in target:
# Try to maintain the original type
original_value = target[last_part]
if isinstance(original_value, int):
try:
target[last_part] = int(new_value)
except ValueError:
target[last_part] = new_value
else:
target[last_part] = new_value
return result
def _detect_pii(self, response_text: str) -> List[str]:
"""Detect potential PII in response text"""
detected_pii = []
for pii_type, pattern in self.pii_patterns.items():
matches = re.findall(pattern, response_text)
if matches:
detected_pii.append(f"{pii_type}: {', '.join(matches[:3])}")
if len(matches) > 3:
detected_pii[-1] += f" and {len(matches) - 3} more"
return detected_pii
def _compare_responses(self, original: requests.Response, modified: requests.Response) -> Tuple[bool, List[str]]:
"""Compare original and modified responses to detect potential IDOR"""
differences = []
is_suspicious = False
# Check status code
if modified.status_code == 200:
# Different status codes might indicate access control issues
if original.status_code != modified.status_code:
differences.append(f"Status code changed: {original.status_code} -> {modified.status_code}")
is_suspicious = True
# Check response size
size_diff = len(modified.text) - len(original.text)
if abs(size_diff) > 50: # Threshold for significant difference
differences.append(f"Response size changed by {size_diff} bytes")
is_suspicious = True
# Check for PII in response
pii_found = self._detect_pii(modified.text)
if pii_found:
differences.extend(pii_found)
is_suspicious = True
# Try to parse JSON responses and compare
try:
if 'application/json' in modified.headers.get('Content-Type', ''):
original_json = original.json() if 'application/json' in original.headers.get('Content-Type', '') else {}
modified_json = modified.json()
# Check for different keys
orig_keys = set(_flatten_dict(original_json).keys())
mod_keys = set(_flatten_dict(modified_json).keys())
new_keys = mod_keys - orig_keys
if new_keys:
differences.append(f"New JSON fields: {', '.join(list(new_keys)[:5])}")
is_suspicious = True
except:
pass
return is_suspicious, differences
def _flatten_dict(d: Dict, parent_key: str = '') -> Dict:
"""Flatten a nested dictionary"""
items = []
for k, v in d.items():
new_key = f"{parent_key}.{k}" if parent_key else k
if isinstance(v, dict):
items.extend(_flatten_dict(v, new_key).items())
else:
items.append((new_key, v))
return dict(items)
def scan_endpoint(self, url: str) -> List[Dict]:
"""Scan a single endpoint for IDOR vulnerabilities"""
endpoint_findings = []
logger.info(f"Scanning endpoint: {url}")
# Get the primary user session (first one in config)
primary_user = list(self.sessions.keys())[0]
primary_session = self.sessions[primary_user]
# Make the original request to establish baseline
try:
original_headers = primary_session.headers.copy()
original_headers['User-Agent'] = random.choice(self.user_agents)
# Determine HTTP method and body from URL
method = "GET"
json_body = None
# If URL contains method and body info in our custom format
if url.startswith("POST:") or url.startswith("PUT:"):
parts = url.split(":", 2)
method = parts[0]
if len(parts)