Buckets:

download
raw
12.7 kB
"""
Subdomain Scanner Module
Provides comprehensive subdomain scanning with HTTP probing and screenshot capabilities.
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, Tuple
from autonomous.tool_executor import SafetyLevel, ToolExecutor
logger = logging.getLogger(__name__)
@dataclass
class SubdomainScanResult:
"""Result of subdomain scan."""
success: bool
subdomain: str = ""
ip_address: Optional[str] = None
http_status: Optional[int] = None
http_title: Optional[str] = None
http_server: Optional[str] = None
technologies: List[str] = field(default_factory=list)
ports: List[int] = field(default_factory=list)
is_alive: bool = False
error_message: Optional[str] = None
execution_time: float = 0.0
metadata: Dict[str, Any] = field(default_factory=dict)
@dataclass
class BatchScanResult:
"""Result of batch subdomain scan."""
success: bool
results: List[SubdomainScanResult] = field(default_factory=list)
total_scanned: int = 0
alive_count: int = 0
error_count: int = 0
execution_time: float = 0.0
metadata: Dict[str, Any] = field(default_factory=dict)
class SubdomainScanner:
"""
Subdomain scanner with HTTP probing and port scanning.
Safety Level: READ_ONLY (passive reconnaissance)
"""
def __init__(self, timeout: int = 30, ports: Optional[List[int]] = None):
"""
Initialize subdomain scanner.
Args:
timeout: HTTP request timeout in seconds
ports: Ports to scan (default: common web ports)
"""
self.timeout = timeout
self.ports = ports or [80, 443, 8080, 8443]
self.logger = logging.getLogger(__name__)
self.executor = ToolExecutor(safety_level=SafetyLevel.READ_ONLY)
async def scan(
self,
subdomain: str,
probe_http: bool = True,
probe_ports: bool = False,
) -> SubdomainScanResult:
"""
Scan a single subdomain.
Args:
subdomain: Subdomain to scan
probe_http: Perform HTTP probing
probe_ports: Perform port scanning
Returns:
SubdomainScanResult with scan results
"""
start_time = datetime.now()
# Validate subdomain
valid, error = self._validate_subdomain(subdomain)
if not valid:
return SubdomainScanResult(
success=False,
subdomain=subdomain,
error_message=f"Validation failed: {error}",
execution_time=(datetime.now() - start_time).total_seconds(),
)
result = SubdomainScanResult(success=True, subdomain=subdomain, is_alive=False)
try:
# DNS resolution
ip = await self._resolve_dns(subdomain)
if ip:
result.ip_address = ip
# HTTP probing
if probe_http:
http_result = await self._probe_http(subdomain)
if http_result:
result.http_status = http_result.get("status")
result.http_title = http_result.get("title")
result.http_server = http_result.get("server")
result.technologies = http_result.get("technologies", [])
result.is_alive = http_result.get("alive", False)
# Port scanning
if probe_ports:
open_ports = await self._scan_ports(subdomain)
result.ports = open_ports
if open_ports:
result.is_alive = True
except Exception as e:
self.logger.error(f"Scan failed for {subdomain}: {e}")
result.error_message = str(e)
result.execution_time = (datetime.now() - start_time).total_seconds()
result.metadata = {
"probe_http": probe_http,
"probe_ports": probe_ports,
}
return result
async def scan_batch(
self,
subdomains: List[str],
max_concurrent: int = 10,
probe_http: bool = True,
probe_ports: bool = False,
) -> BatchScanResult:
"""
Scan multiple subdomains concurrently.
Args:
subdomains: List of subdomains to scan
max_concurrent: Maximum concurrent scans
probe_http: Perform HTTP probing
probe_ports: Perform port scanning
Returns:
BatchScanResult with all scan results
"""
start_time = datetime.now()
if not subdomains:
return BatchScanResult(
success=False,
error_count=0,
execution_time=0,
metadata={"error": "No subdomains provided"},
)
semaphore = asyncio.Semaphore(max_concurrent)
async def scan_with_limit(subdomain: str) -> SubdomainScanResult:
async with semaphore:
return await self.scan(subdomain, probe_http, probe_ports)
tasks = [scan_with_limit(sd) for sd in subdomains]
results = await asyncio.gather(*tasks, return_exceptions=True)
processed_results = []
error_count = 0
alive_count = 0
for result in results:
if isinstance(result, Exception):
error_count += 1
continue
processed_results.append(result)
if result.is_alive:
alive_count += 1
execution_time = (datetime.now() - start_time).total_seconds()
return BatchScanResult(
success=alive_count > 0,
results=processed_results,
total_scanned=len(subdomains),
alive_count=alive_count,
error_count=error_count,
execution_time=execution_time,
metadata={
"probe_http": probe_http,
"probe_ports": probe_ports,
"max_concurrent": max_concurrent,
},
)
async def _resolve_dns(self, subdomain: str) -> Optional[str]:
"""Resolve subdomain to IP address."""
try:
proc = await asyncio.create_subprocess_exec(
"dig",
"+short",
subdomain,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
stdout, _ = await asyncio.wait_for(proc.communicate(), timeout=self.timeout)
output = stdout.decode("utf-8", errors="ignore").strip()
if output:
# Return first IP address
for line in output.split("\n"):
line = line.strip()
if re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", line):
return line
return None
except Exception as e:
self.logger.debug(f"DNS resolution failed for {subdomain}: {e}")
return None
async def _probe_http(self, subdomain: str) -> Optional[Dict[str, Any]]:
"""Probe HTTP/HTTPS endpoints."""
result = {"alive": False, "technologies": []}
# Try HTTPS first, then HTTP
for protocol in ["https", "http"]:
url = f"{protocol}://{subdomain}"
try:
proc = await asyncio.create_subprocess_exec(
"curl",
"-sI",
"-L",
"--max-time",
str(self.timeout),
"-A",
"Mozilla/5.0 (compatible; SubdomainScanner/1.0)",
url,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
stdout, _ = await asyncio.wait_for(proc.communicate(), timeout=self.timeout + 5)
output = stdout.decode("utf-8", errors="ignore")
# Parse status code
status_match = re.search(r"HTTP/\d\.\d\s+(\d{3})", output)
if status_match:
result["status"] = int(status_match.group(1))
result["alive"] = True
# Parse server header
server_match = re.search(r"[Ss]erver:\s*(.+)", output)
if server_match:
result["server"] = server_match.group(1).strip()
# Parse title (would need full page fetch)
# For now, just mark as alive
if result["alive"]:
break
except asyncio.TimeoutError:
continue
except Exception as e:
self.logger.debug(f"HTTP probe failed for {url}: {e}")
continue
return result
async def _scan_ports(self, subdomain: str) -> List[int]:
"""Scan common ports using nmap."""
try:
ports_str = ",".join(map(str, self.ports))
parameters = {
"target": subdomain,
"options": f"-p{ports_str} --open",
}
result = await self.executor.execute("nmap", parameters, timeout=self.timeout * 2)
if not result.success:
return []
open_ports = []
for line in result.stdout.split("\n"):
if "/tcp" in line and "open" in line:
port_match = re.search(r"(\d+)/tcp", line)
if port_match:
open_ports.append(int(port_match.group(1)))
return open_ports
except Exception as e:
self.logger.debug(f"Port scan failed for {subdomain}: {e}")
return []
def _validate_subdomain(self, subdomain: str) -> Tuple[bool, str]:
"""Validate subdomain format."""
if not subdomain:
return False, "Subdomain cannot be empty"
# Check for dangerous characters
if re.search(r"[;&|<>$`]", subdomain):
return False, "Invalid characters in subdomain"
# Basic subdomain validation
if "." not in subdomain:
return False, "Invalid subdomain format"
return True, ""
class SubdomainScanTool:
"""Tool wrapper for subdomain scanning in agent loop."""
def __init__(self):
self.scanner = SubdomainScanner()
async def execute(self, parameters: Dict[str, Any]) -> Dict[str, Any]:
"""Execute subdomain scan and return standardized result."""
subdomains = parameters.get("subdomains", [])
if isinstance(subdomains, str):
subdomains = [subdomains]
probe_http = parameters.get("probe_http", True)
probe_ports = parameters.get("probe_ports", False)
max_concurrent = parameters.get("max_concurrent", 10)
if len(subdomains) == 1:
result = await self.scanner.scan(subdomains[0], probe_http, probe_ports)
return {
"tool": "subdomain_scan",
"success": result.success,
"subdomain": result.subdomain,
"is_alive": result.is_alive,
"http_status": result.http_status,
"ip_address": result.ip_address,
"technologies": result.technologies,
"execution_time": result.execution_time,
"error": result.error_message,
}
else:
result = await self.scanner.scan_batch(subdomains, max_concurrent, probe_http, probe_ports)
return {
"tool": "subdomain_scan_batch",
"success": result.success,
"total_scanned": result.total_scanned,
"alive_count": result.alive_count,
"error_count": result.error_count,
"results": [
{
"subdomain": r.subdomain,
"is_alive": r.is_alive,
"http_status": r.http_status,
"ip_address": r.ip_address,
}
for r in result.results
],
"execution_time": result.execution_time,
}
if __name__ == "__main__":
async def test():
scanner = SubdomainScanner()
result = await scanner.scan("www.example.com", probe_http=True)
print(f"Success: {result.success}")
print(f"Subdomain: {result.subdomain}")
print(f"Alive: {result.is_alive}")
print(f"HTTP Status: {result.http_status}")
print(f"IP: {result.ip_address}")
asyncio.run(test())

Xet Storage Details

Size:
12.7 kB
·
Xet hash:
f18dd367a840b73084af0f24c5ad744dfd430f906046d595f6edf09c97c44594

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.