python
#!/usr/bin/env python3
import os
import sys
import json
import re
import socket
import concurrent.futures
from urllib.parse import urlparse, parse_qs
from typing import List, Dict, Set
from pathlib import Path
import requests
from bs4 import BeautifulSoup
import dns.resolver
import typer
from rich.console import Console
from rich.progress import Progress, SpinnerColumn, TextColumn
console = Console()
app = typer.Typer(help="Automated Bug Bounty Recon Tool")
# Constants
WORDLIST_URL = "https://raw.githubusercontent.com/danielmiessler/SecLists/master/Discovery/DNS/subdomains-top1million-5000.txt"
WORDLIST_PATH = Path("/tmp/subdomains.txt")
MAX_THREADS = 50
TIMEOUT = 5
USER_AGENT = "Mozilla/5.0 (compatible; ReconTool/1.0)"
# Modular Functions
def download_wordlist() -> None:
if not WORDLIST_PATH.exists():
console.print("[yellow]Downloading wordlist...[/yellow]")
response = requests.get(WORDLIST_URL, timeout=TIMEOUT)
response.raise_for_status()
WORDLIST_PATH.write_text(response.text)
console.print("[green]Wordlist downloaded.[/green]")
def get_subdomains_from_crtsh(domain: str) -> Set[str]:
subdomains = set()
url = f"https://crt.sh/?q=%.{domain}&output=json"
try:
response = requests.get(url, headers={"User-Agent": USER_AGENT}, timeout=TIMEOUT)
response.raise_for_status()
data = json.loads(response.text.replace('{"', '[{').replace('"}', '}]').replace('\\n', ''))
for entry in data:
name = entry.get("name_value", "").lower()
if name.endswith(f".{domain}"):
subdomains.add(name)
except Exception as e:
console.print(f"[red]Error fetching from crt.sh: {e}[/red]")
return subdomains
def dns_brute(domain: str) -> Set[str]:
download_wordlist()
subdomains = set()
words = WORDLIST_PATH.read_text().splitlines()
def check_sub(sub: str) -> str | None:
try:
full = f"{sub}.{domain}"
dns.resolver.resolve(full, "A")
return full
except Exception:
return None
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_THREADS) as executor:
futures = [executor.submit(check_sub, word) for word in words]
for future in concurrent.futures.as_completed(futures):
result = future.result()
if result:
subdomains.add(result)
return subdomains
def discover_subdomains(domain: str) -> Set[str]:
with Progress(SpinnerColumn(), TextColumn("[progress.description]{task.description}"), console=console, transient=True) as progress:
task = progress.add_task("Discovering subdomains...", total=None)
crt_subs = get_subdomains_from_crtsh(domain)
brute_subs = dns_brute(domain)
all_subs = crt_subs.union(brute_subs)
progress.update(task, completed=True)
console.print(f"[green]Found {len(all_subs)} unique subdomains.[/green]")
return all_subs
def probe_live_subdomains(subdomains: Set[str]) -> Dict[str, int]:
live = {}
def probe(sub: str) -> tuple[str, int] | None:
for scheme in ["https", "http"]:
url = f"{scheme}://{sub}"
try:
response = requests.get(url, timeout=TIMEOUT, allow_redirects=False, headers={"User-Agent": USER_AGENT})
return sub, response.status_code
except requests.exceptions.SSLError:
continue
except Exception:
pass
return None
with Progress(SpinnerColumn(), TextColumn("[progress.description]{task.description}"), console=console, transient=True) as progress:
task = progress.add_task("Probing live subdomains...", total=len(subdomains))
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_THREADS) as executor:
futures = {executor.submit(probe, sub): sub for sub in subdomains}
for future in concurrent.futures.as_completed(futures):
result = future.result()
if result:
sub, code = result
live[sub] = code
progress.update(task, advance=1)
console.print(f"[green]Found {len(live)} live subdomains.[/green]")
return live
def crawl_links(domain: str, live_subs: Dict[str, int]) -> Dict[str, Set[str]]:
all_links = {"internal": set(), "external": set()}
def crawl(sub: str) -> tuple[Set[str], Set[str]]:
int_links, ext_links = set(), set()
url = f"https://{sub}" if live_subs[sub] < 400 else f"http://{sub}"
try:
response = requests.get(url, timeout=TIMEOUT, headers={"User-Agent": USER_AGENT})
response.raise_for_status()
soup = BeautifulSoup(response.text, "html.parser")
for link in soup.find_all("a", href=True):
href = link["href"]
parsed = urlparse(href)
if not parsed.netloc:
href = f"{urlparse(url).scheme}://{urlparse(url).netloc}{href}"
if domain in urlparse(href).netloc:
int_links.add(href)
else:
ext_links.add(href)
except Exception:
pass
return int_links, ext_links
with Progress(SpinnerColumn(), TextColumn("[progress.description]{task.description}"), console=console, transient=True) as progress:
task = progress.add_task("Crawling links...", total=len(live_subs))
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_THREADS) as executor:
futures = {executor.submit(crawl, sub): sub for sub in live_subs}
for future in concurrent.futures.as_completed(futures):
int_l, ext_l = future.result()
all_links["internal"].update(int_l)
all_links["external"].update(ext_l)
progress.update(task, advance=1)
console.print(f"[green]Found {len(all_links['internal'])} internal and {len(all_links['external'])} external links.[/green]")
return all_links
def analyze_js_files(links: Set[str]) -> Dict[str, Dict[str, str | List[str]]]:
js_files = {}
def analyze(url: str) -> tuple[str, Dict[str, str | List[str]]] | None:
try:
response = requests.get(url, timeout=TIMEOUT, headers={"User-Agent": USER_AGENT})
response.raise_for_status()
content = response.text
endpoints = re.findall(r'/(?:api|endpoint|rest)/[\w/]+', content)
secrets = re.findall(r'(?i)(?:api_key|token|secret|password|aws_access_key_id)=["\']?([\w\-]+)["\']?', content)
return url, {"content": content[:1000] + "...", "endpoints": endpoints, "potential_secrets": secrets}
except Exception:
return None
js_links = {link for link in links if link.endswith(".js")}
with Progress(SpinnerColumn(), TextColumn("[progress.description]{task.description}"), console=console, transient=True) as progress:
task = progress.add_task("Analyzing JS files...", total=len(js_links))
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_THREADS) as executor:
futures = [executor.submit(analyze, link) for link in js_links]
for future in concurrent.futures.as_completed(futures):
result = future.result()
if result:
url, data = result
js_files[url] = data
progress.update(task, advance=1)
console.print(f"[green]Analyzed {len(js_files)} JS files.[/green]")
return js_files
def get_wayback_urls(domain: str) -> Set[str]:
urls = set()
cdx_url = f"http://web.archive.org/cdx/search/cdx?url=*.{domain}/*&output=json&fl=original&collapse=digest"
try:
response = requests.get(cdx_url, timeout=TIMEOUT, headers={"User-Agent": USER_AGENT})
response.raise_for_status()
data = json.loads(response.text)
for entry in data[1:]: # Skip header
urls.add(entry[0])
except Exception as e:
console.print(f"[red]Error fetching from Wayback: {e}[/red]")
console.print(f"[green]Found {len(urls)} archived URLs.[/green]")
return urls
def extract_params_and_paths(urls: Set[str]) -> Dict[str, Set[str]]:
params = set()
paths = set()
exposed_files = set()
for url in urls:
parsed = urlparse(url)
paths.add(parsed.path)
for key in parse_qs(parsed.query).keys():
params.add(key)
if parsed.path in ["/robots.txt", "/sitemap.xml", "/.well-known/security.txt"]:
exposed_files.add(url)
return {"params": params, "paths": paths, "exposed_files": exposed_files}
def generate_html_report(domain: str, data: Dict) -> str:
html = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Recon Report for {domain}</title>
<style>
body {{ font-family: Arial, sans-serif; background-color: #f4f4f4; color: #333; margin: 20px; }}
h1 {{ color: #007bff; }}
h2 {{ color: #28a745; }}
table {{ border-collapse: collapse; width: 100%; margin-bottom: 20px; }}
th, td {{ border: 1px solid #ddd; padding: 8px; text-align: left; }}
th {{ background-color: #007bff; color: white; }}
ul {{ list-style-type: none; padding: 0; }}
li {{ background: #fff; margin: 5px 0; padding: 10px; border: 1px solid #ddd; }}
.section {{ background: #fff; padding: 20px; margin-bottom: 20px; border: 1px solid #ddd; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }}
</style>
</head>
<body>
<h1>Recon Report for {domain}</h1>
<div class="section">
a: Subdomains (live: {num_live})
<h2>Live Subdomains</h2>
<table>
<tr><th>Subdomain</th><th>Status Code</th></tr>
{sub_rows}
</table>
</div>
<div class="section">
<h2>Links</h2>
<h3>Internal Links ({num_int})</h3>
<ul>{int_links}</ul>
<h3>External Links ({num_ext})</h3>
<ul>{ext_links}</ul>
</div>
<div class="section">
<h2>JS Files Analysis ({num_js})</h2>
{js_analysis}
</div>
<div class="section">
<h2>Wayback Archived URLs ({num_wayback})</h2>
<ul>{wayback_urls}</ul>
</div>
<div class="section">
<h2>Extracted Data</h2>
<h3>Parameters ({num_params})</h3>
<ul>{params}</ul>
<h3>Paths ({num_paths})</h3>
<ul>{paths}</ul>
<h3>Exposed Files ({num_exposed})</h3>
<ul>{exposed}</ul>
</div>
</body>
</html>
"""
sub_rows = "".join(f"<tr><td>{sub}</td><td>{code}</td></tr>" for sub, code in data["live_subs"].items())
int_links = "".join(f"<li>{link}</li>" for link in data["links"]["internal"])
ext_links = "".join(f"<li>{link}</li>" for link in data["links"]["external"])
js_analysis = "".join(
f"<h3>{url}</h3><p>Endpoints: {', '.join(data['endpoints'])}</p><p>Potential Secrets: {', '.join(data['potential_secrets'])}</p><pre>{data['content']}</pre>"
for url, data in data["js_files"].items()
)
wayback_urls = "".join(f"<li>{url}</li>" for url in data["wayback"])
params = "".join(f"<li>{p}</li>" for p in data["extracted"]["params"])
paths = "".join(f"<li>{p}</li>" for p in data["extracted"]["paths"])
exposed = "".join(f"<li>{f}</li>" for f in data["extracted"]["exposed_files"])
return html.format(
domain=domain,
num_live=len(data["live_subs"]),
sub_rows=sub_rows,
num_int=len(data["links"]["internal"]),
int_links=int_links,
num_ext=len(data["links"]["external"]),
ext_links=ext_links,
num_js=len(data["js_files"]),
js_analysis=js_analysis,
num_wayback=len(data["wayback"]),
wayback_urls=wayback_urls,
num_params=len(data["extracted"]["params"]),
params=params,
num_paths=len(data["extracted"]["paths"]),
paths=paths,
num_exposed=len(data["extracted"]["exposed_files"]),
exposed=exposed
)
@app.command()
def recon(domain: str, output: str = "report.html"):
console.print(f"[bold blue]Starting recon for {domain}[/bold blue]")
subs = discover_subdomains(domain)
live_subs = probe_live_subdomains(subs)
links = crawl_links(domain, live_subs)
js_files = analyze_js_files(links["internal"].union(links["external"]))
wayback = get_wayback_urls(domain)
all_urls = links["internal"].union(wayback)
extracted = extract_params_and_paths(all_urls)
data = {
"live_subs": live_subs,
"links": links,
"js_files": js_files,
"wayback": wayback,
"extracted": extracted
}
report = generate_html_report(domain, data)
Path(output).write_text(report)
console.print(f"[green]Report generated: {output}[/green]")
if __name__ == "__main__":
app()