Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /autonomous /subdomain_enum.py
| """ | |
| Subdomain Enumeration Module | |
| Provides subdomain discovery using multiple tools (subfinder, amass, dnsrecon). | |
| Uses ToolExecutor for external tool execution. | |
| """ | |
| import asyncio | |
| import logging | |
| import re | |
| from dataclasses import dataclass, field | |
| from datetime import datetime | |
| from typing import Any, Dict, List, Optional, Set, Tuple | |
| from autonomous.tool_executor import SafetyLevel, ToolExecutor | |
| logger = logging.getLogger(__name__) | |
| class SubdomainResult: | |
| """Result of subdomain enumeration.""" | |
| success: bool | |
| subdomains: List[str] = field(default_factory=list) | |
| sources: Dict[str, List[str]] = field(default_factory=dict) | |
| total_found: int = 0 | |
| unique_count: int = 0 | |
| error_message: Optional[str] = None | |
| execution_time: float = 0.0 | |
| metadata: Dict[str, Any] = field(default_factory=dict) | |
| class SubdomainEnumerator: | |
| """ | |
| Subdomain enumeration using multiple tools. | |
| Safety Level: READ_ONLY (passive reconnaissance) | |
| """ | |
| def __init__(self, timeout: int = 300, threads: int = 10): | |
| """ | |
| Initialize subdomain enumerator. | |
| Args: | |
| timeout: Maximum execution time per tool | |
| threads: Number of concurrent threads | |
| """ | |
| self.timeout = timeout | |
| self.threads = threads | |
| self.logger = logging.getLogger(__name__) | |
| self.executor = ToolExecutor(safety_level=SafetyLevel.READ_ONLY) | |
| async def enumerate( | |
| self, | |
| domain: str, | |
| tools: Optional[List[str]] = None, | |
| use_all: bool = False, | |
| ) -> SubdomainResult: | |
| """ | |
| Enumerate subdomains for a domain. | |
| Args: | |
| domain: Target domain (e.g., "example.com") | |
| tools: List of tools to use (subfinder, amass, dnsrecon) | |
| use_all: Use all available tools | |
| Returns: | |
| SubdomainResult with found subdomains | |
| """ | |
| start_time = datetime.now() | |
| # Validate domain | |
| valid, error = self._validate_domain(domain) | |
| if not valid: | |
| return SubdomainResult( | |
| success=False, | |
| error_message=f"Validation failed: {error}", | |
| execution_time=(datetime.now() - start_time).total_seconds(), | |
| ) | |
| # Determine which tools to use | |
| available_tools = tools or ["subfinder"] | |
| if use_all: | |
| available_tools = ["subfinder", "amass", "dnsrecon"] | |
| all_subdomains: Dict[str, Set[str]] = {} | |
| for tool_name in available_tools: | |
| try: | |
| result = await self._run_tool(tool_name, domain) | |
| if result: | |
| all_subdomains[tool_name] = result | |
| except Exception as e: | |
| self.logger.error(f"Tool {tool_name} failed: {e}") | |
| # Combine results | |
| combined = set() | |
| for tool_subdomains in all_subdomains.values(): | |
| combined.update(tool_subdomains) | |
| execution_time = (datetime.now() - start_time).total_seconds() | |
| return SubdomainResult( | |
| success=len(combined) > 0, | |
| subdomains=sorted(list(combined)), | |
| sources={k: sorted(list(v)) for k, v in all_subdomains.items()}, | |
| total_found=sum(len(v) for v in all_subdomains.values()), | |
| unique_count=len(combined), | |
| execution_time=execution_time, | |
| metadata={ | |
| "domain": domain, | |
| "tools_used": available_tools, | |
| "tool_count": len(all_subdomains), | |
| }, | |
| ) | |
| async def _run_tool(self, tool_name: str, domain: str) -> Optional[Set[str]]: | |
| """Run a specific subdomain enumeration tool.""" | |
| parameters = {"target": domain, "options": f"-t {self.threads}"} | |
| result = await self.executor.execute(tool_name, parameters, timeout=self.timeout) | |
| if not result.success: | |
| self.logger.warning(f"{tool_name} failed: {result.error_message}") | |
| return None | |
| return self._parse_subdomains(result.stdout) | |
| def _validate_domain(self, domain: str) -> Tuple[bool, str]: | |
| """Validate domain format.""" | |
| if not domain: | |
| return False, "Domain cannot be empty" | |
| # Basic domain validation | |
| pattern = r"^[a-zA-Z0-9][-a-zA-Z0-9]*(\.[a-zA-Z0-9][-a-zA-Z0-9]*)+$" | |
| if not re.match(pattern, domain): | |
| return False, "Invalid domain format" | |
| # Check for dangerous characters | |
| if re.search(r"[;&|<>$`]", domain): | |
| return False, "Invalid characters in domain" | |
| return True, "" | |
| def _parse_subdomains(self, output: str) -> Set[str]: | |
| """Parse subdomain output from tools.""" | |
| subdomains = set() | |
| for line in output.split("\n"): | |
| line = line.strip() | |
| if not line: | |
| continue | |
| # Check if line looks like a subdomain | |
| if "." in line and not line.startswith("[") and not line.startswith("http"): | |
| # Clean up the subdomain | |
| subdomain = line.split()[0] if " " in line else line | |
| if self._is_valid_subdomain(subdomain): | |
| subdomains.add(subdomain.lower()) | |
| return subdomains | |
| def _is_valid_subdomain(self, subdomain: str) -> bool: | |
| """Check if string is a valid subdomain.""" | |
| if not subdomain or len(subdomain) > 253: | |
| return False | |
| # Must contain at least one dot | |
| if "." not in subdomain: | |
| return False | |
| # Basic domain name validation | |
| parts = subdomain.split(".") | |
| if len(parts) < 2: | |
| return False | |
| return True | |
| class SubdomainEnumTool: | |
| """Tool wrapper for subdomain enumeration in agent loop.""" | |
| def __init__(self): | |
| self.enumerator = SubdomainEnumerator() | |
| async def execute(self, parameters: Dict[str, Any]) -> Dict[str, Any]: | |
| """Execute subdomain enumeration and return standardized result.""" | |
| domain = parameters.get("domain") | |
| tools = parameters.get("tools", ["subfinder"]) | |
| use_all = parameters.get("use_all", False) | |
| result = await self.enumerator.enumerate(domain, tools=tools, use_all=use_all) | |
| return { | |
| "tool": "subdomain_enum", | |
| "success": result.success, | |
| "subdomains": result.subdomains, | |
| "total_found": result.total_found, | |
| "unique_count": result.unique_count, | |
| "execution_time": result.execution_time, | |
| "error": result.error_message, | |
| "metadata": result.metadata, | |
| } | |
| if __name__ == "__main__": | |
| async def test(): | |
| enumerator = SubdomainEnumerator() | |
| result = await enumerator.enumerate("example.com", tools=["subfinder"]) | |
| print(f"Success: {result.success}") | |
| print(f"Found {result.unique_count} unique subdomains") | |
| for subdomain in result.subdomains[:10]: | |
| print(f" - {subdomain}") | |
| asyncio.run(test()) | |
Xet Storage Details
- Size:
- 7 kB
- Xet hash:
- 17022d3fe4dbc6286f2aef5be7df89be659e2654bad6a93505c9a1bcb99c339d
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.