Spaces:
Sleeping

RECONREVANS / app.py
HACKERTONE's picture
Create app.py
766345b verified
Raw History Blame Contribute Delete
56.2 kB
# --- Recon Revan Gradio App v2.2 (Integrated Backend, Enhanced UI/Logic/Viz) ---
import gradio as gr
import requests
import socket
import ssl
import re
import json
import time
import threading
import queue
import ipaddress
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
from bs4 import BeautifulSoup
from urllib.parse import urlparse, urljoin
from datetime import datetime, timezone
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from typing import List, Dict, Tuple, Optional, Any, Union, Set
# --- Configuration ---
DEFAULT_USER_AGENT = 'ReconRevan/1.1 (Security Scanner; +https://example.com/botinfo)'
REQUEST_TIMEOUT = 10
COMMON_SUBDOMAINS_SAMPLE = ['www', 'mail', 'ftp', 'localhost', 'webmail', 'smtp', 'pop', 'ns1', 'ns2', 'admin', 'dev', 'test', 'staging', 'api', 'vpn', 'm', 'shop', 'blog', 'support', 'status', 'internal', 'portal', 'owa', 'cpanel', 'webdisk', 'autodiscover', 'remote', 'internal', 'jira', 'confluence', 'assets', 'cdn', 'static', 'images', 'files', 'download']
COMMON_PORTS_SAMPLE = [21, 22, 23, 25, 53, 80, 110, 111, 135, 139, 143, 443, 445, 993, 995, 1723, 3306, 3389, 5900, 8080, 8443, 8888, 9000, 9443]
MAX_THREADS = 50
SSL_GAUGE_MAX_DAYS = 180
# --- UI Styling Configuration ---
NEO_BORDER_COLOR = "#606060" # Darker grey border
NEO_BORDER_STYLE = f"3px solid {NEO_BORDER_COLOR}"
NEO_BACKGROUND_COLOR = "#181818" # Very dark background
NEO_ACCENT_COLOR = "deepskyblue" # Brighter accent
NEO_SHADOW_COLOR = "#555555" # Shadow color for dark theme
NEO_HARD_SHADOW = f"5px 5px 0px {NEO_SHADOW_COLOR}"
PLOTLY_TEMPLATE = "plotly_dark"
# Suppress InsecureRequestWarning
try:
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
except Exception: pass
# --- Helper Functions ---
def is_ip_address(address: str) -> bool:
if not address: return False
try: ipaddress.ip_address(address.strip()); return True
except ValueError: return False
def sanitize_url(url_string: str) -> Optional[str]:
if not url_string: return None
url_string = url_string.strip()
if '://' not in url_string and '.' in url_string:
if '/' not in url_string or url_string.find('/') > url_string.find('.'):
url_string = "http://" + url_string
try:
parsed = urlparse(url_string)
if parsed.scheme and parsed.netloc: return url_string
elif not parsed.scheme and not parsed.netloc:
path_part = parsed.path.split(':')[0] # Handle potential port in path for domain-only input
if is_ip_address(path_part): return path_part
if '.' in path_part and '/' not in path_part: return path_part
return None
except ValueError: return None
def extract_domain(url_or_domain_or_ip: str) -> Optional[str]:
if not url_or_domain_or_ip: return None
target = url_or_domain_or_ip.strip()
if is_ip_address(target): return target
temp_url = target
if '://' not in temp_url and '.' in temp_url: temp_url = 'http://' + target
try:
parsed_url = urlparse(temp_url)
if parsed_url.netloc: return parsed_url.netloc.split(':')[0].lower()
path_part = parsed_url.path.split(':')[0] # Handle potential port
if not parsed_url.netloc and '.' in path_part and '/' not in path_part: return path_part.lower()
if not parsed_url.netloc and '.' in target and '/' not in target: return target.split(':')[0].lower()
return None
except Exception as e: print(f"Error extracting domain/IP from '{url_or_domain_or_ip}': {e}"); return None
def resolve_domain(domain_or_ip: str) -> Optional[str]:
if not domain_or_ip: return None
target = domain_or_ip.strip()
if is_ip_address(target): return target
try:
# Ensure we handle potential timeouts during DNS lookup
addr_info = socket.getaddrinfo(target, None, socket.AF_INET, socket.SOCK_STREAM, 0, socket.AI_ADDRCONFIG) # Prioritize IPv4
if addr_info: return addr_info[0][4][0]
else:
addr_info_v6 = socket.getaddrinfo(target, None, socket.AF_INET6, socket.SOCK_STREAM, 0, socket.AI_ADDRCONFIG) # Fallback IPv6
if addr_info_v6: return addr_info_v6[0][4][0]
else: print(f"DNS resolution failed for {target}"); return None
except socket.gaierror: print(f"DNS resolution failed for {target} (gaierror)"); return None
except socket.timeout: print(f"DNS resolution timed out for {target}"); return None
except Exception as e: print(f"Error resolving domain {target}: {type(e).__name__} - {e}"); return None
def make_request(url: str, method: str = 'GET', headers: Optional[Dict[str, str]] = None, data: Optional[Dict] = None, allow_redirects: bool = True) -> requests.Response:
sanitized_url = sanitize_url(url)
if not sanitized_url: raise ValueError(f"Invalid URL format for request: {url}")
if '://' not in sanitized_url:
if '.' in sanitized_url and ('/' not in sanitized_url or sanitized_url.find('/') > sanitized_url.find('.')): sanitized_url = "http://" + sanitized_url
else: raise ValueError(f"URL requires a scheme: {sanitized_url}")
url = sanitized_url
request_headers = {'User-Agent': DEFAULT_USER_AGENT}; request_headers.update(headers or {})
try:
response = requests.request(method, url, headers=request_headers, data=data, timeout=REQUEST_TIMEOUT, verify=False, allow_redirects=allow_redirects)
return response
except requests.exceptions.Timeout: raise ConnectionError(f"Timeout ({REQUEST_TIMEOUT}s)")
except requests.exceptions.SSLError as e: error_detail = str(e); raise ConnectionError(f"SSL Error: {error_detail}")
except requests.exceptions.ConnectionError as e: raise ConnectionError(f"Connection Error: {e}")
except requests.exceptions.RequestException as e: raise ConnectionError(f"Request Error: {e}")
# --- Full Backend Recon Functions ---
def fetch_common_files(target_url: str) -> Tuple[str, List[Dict[str, Any]]]:
log_str = f"Checking common files for: {target_url}\n" + "="*20 + "\n"
results_data = []
base_url = sanitize_url(target_url)
if not base_url or '://' not in base_url:
err_msg = "[!] Invalid base URL (requires scheme)."
return err_msg, [{"url": target_url, "status": "Error", "found": False, "error": err_msg}]
common_paths = ['/robots.txt', '/sitemap.xml', '/sitemap.xml.gz', '/security.txt', '/.well-known/security.txt', '/crossdomain.xml', '/humans.txt', '/ads.txt', '/.env', '/.env.sample', '/config.js', '/config.json', '/package.json', '/composer.json', '/README.md', '/LICENSE', '/CHANGELOG.md', '/.git/config', '/.svn/entries', '/.hg/hgrc', '/.bzr/README', '/WEB-INF/web.xml', '/WEB-INF/jboss-web.xml', '/server-status', '/server-info', '/phpinfo.php', '/test.php', '/admin/', '/login/', '/wp-admin/', '/wp-login.php']
parsed_base = urlparse(base_url)
base_url_for_join = base_url + ('/' if not parsed_base.path or parsed_base.path == '/' and not base_url.endswith('/') else '')
for path in common_paths:
url_to_check = urljoin(base_url_for_join, path.lstrip('/'))
file_info = {"url": url_to_check, "status": None, "found": False, "size": None, "content_type": None, "error": None}
log_entry = f"[-] Checking: {url_to_check} ... "
try:
response = make_request(url_to_check, method='GET', allow_redirects=False)
status = response.status_code
content_type = response.headers.get('Content-Type', 'N/A')
size = len(response.content) if hasattr(response, 'content') else None
file_info.update({"status": status, "content_type": content_type, "size": size})
if 200 <= status < 300: file_info["found"] = True; size_str = f"{size} bytes" if size is not None else "Unknown size"; log_entry += f"Found (Status: {status}, Size: {size_str})"
elif 300 <= status < 400: log_entry += f"Redirect ({status}) to {response.headers.get('Location')}"
elif status == 403: log_entry += f"Forbidden (Status: {status}) - May exist but access denied."
elif status == 401: log_entry += f"Unauthorized (Status: {status}) - Likely requires login."
else: log_entry += f"Not Found/Error (Status: {status})"
except ConnectionError as e: file_info["error"] = str(e); log_entry += f"Error ({e})"
except ValueError as e: file_info["error"] = str(e); log_entry += f"Error ({e})"
except Exception as e: file_info["error"] = f"Unexpected: {type(e).__name__}"; log_entry += f"Unexpected Error ({type(e).__name__})"
results_data.append(file_info)
log_str += log_entry + "\n"
time.sleep(0.03) # Slightly faster sleep
return log_str, results_data
def basic_crawl(start_url: str, max_depth_str: str = "1", max_urls_str: str = "50") -> Tuple[str, List[Dict[str, Any]]]:
log_str = ""; results_data = []
try: max_depth = int(max_depth_str); max_urls = int(max_urls_str)
except ValueError: return "Invalid crawl depth/max URLs.", []
if max_depth < 0 or max_urls <= 0: return "Crawl depth must be >= 0, max URLs > 0.", []
sanitized_start_url = sanitize_url(start_url)
if not sanitized_start_url or '://' not in sanitized_start_url: return "Invalid start URL (requires scheme).", []
start_url = sanitized_start_url
start_domain = extract_domain(start_url)
if not start_domain: return "Could not extract domain from start URL.", []
urls_to_visit: queue.Queue[Tuple[str, int]] = queue.Queue(); urls_to_visit.put((start_url, 0))
visited_urls: Set[str] = {start_url}; found_count = 0
log_str += f"Starting crawl from: {start_url} (Scope: {start_domain})\nMax Depth: {max_depth}, Max URLs: {max_urls}\n" + "="*20 + "\n"
while not urls_to_visit.empty() and found_count < max_urls:
try: current_url, current_depth = urls_to_visit.get(timeout=2)
except queue.Empty: continue
if current_depth > max_depth: continue
log_str += f"[{current_depth}] Visiting: {current_url}\n"; found_count += 1
crawl_info = {"url": current_url, "depth": current_depth, "status": None, "content_type": None, "size": None, "links_found": 0, "error": None}
try:
response = make_request(current_url, allow_redirects=True)
final_url = response.url; final_domain = extract_domain(final_url)
if response.history: log_str += f" Redirected to: {final_url}\n"
if final_domain != start_domain:
log_str += f" Redirect out of scope ({final_domain}). Stopping path.\n"
crawl_info.update({"status": response.status_code, "error": f"Redirected out of scope to {final_domain}"})
results_data.append(crawl_info); continue
current_url = final_url # Use final URL for link joining
content_type = response.headers.get('Content-Type', '').lower()
size = len(response.content) if hasattr(response, 'content') else None
crawl_info.update({"status": response.status_code, "content_type": content_type, "size": size})
if response.status_code < 400 and current_depth < max_depth and 'text/html' in content_type:
soup = BeautifulSoup(response.text, 'html.parser'); links_on_page = 0
for link in soup.find_all('a', href=True):
href = link['href'].strip()
if not href or href.startswith(('#', 'mailto:', 'tel:', 'javascript:', 'data:')): continue
try:
absolute_url = urljoin(current_url, href)
parsed_link = urlparse(absolute_url)
scheme = parsed_link.scheme.lower() if parsed_link.scheme else 'http'
absolute_url = f"{scheme}://{parsed_link.netloc}{parsed_link.path}{'?' if parsed_link.query else ''}{parsed_link.query}" # Rebuild without fragment
link_domain = extract_domain(absolute_url)
if link_domain == start_domain and absolute_url not in visited_urls:
if found_count + urls_to_visit.qsize() < max_urls:
visited_urls.add(absolute_url); urls_to_visit.put((absolute_url, current_depth + 1)); links_on_page += 1
except Exception as link_e: log_str += f" [!] Error processing link '{href}': {link_e}\n"
crawl_info["links_found"] = links_on_page
if links_on_page > 0: log_str += f" Found {links_on_page} new in-scope links.\n"
elif response.status_code >= 400: log_str += f" [!] Status {response.status_code}. Not parsing links.\n"; crawl_info["error"] = f"HTTP Status {response.status_code}"
elif 'text/html' not in content_type: log_str += f" Not HTML ({content_type}). Not parsing links.\n"; crawl_info["error"] = "Not HTML content"
except ConnectionError as e: crawl_info["error"] = str(e); log_str += f" [!] Error crawling: {e}\n"
except ValueError as e: crawl_info["error"] = str(e); log_str += f" [!] Error crawling: {e}\n"
except Exception as e: crawl_info["error"] = f"Unexpected: {type(e).__name__}"; log_str += f" [!] Unexpected Error: {type(e).__name__} - {e}\n"
results_data.append(crawl_info)
time.sleep(0.03)
log_str += f"\nCrawl finished. Visited {found_count} URLs within scope '{start_domain}'.\n"
return log_str, results_data
def identify_technologies(target_url: str) -> Tuple[str, Dict[str, Any]]:
log_str = f"Basic Technology Scan for: {target_url}\n" + "="*20 + "\n"
tech_data: Dict[str, Any] = {"headers": {}, "hints": [], "errors": None}
sanitized_url = sanitize_url(target_url)
if not sanitized_url or '://' not in sanitized_url: err_msg = "[!] Invalid URL (requires scheme)."; tech_data["errors"] = err_msg; return err_msg, tech_data
target_url = sanitized_url
try:
response = make_request(target_url)
headers_lower = {k.lower(): v for k, v in response.headers.items()}; tech_data["headers"] = dict(response.headers)
log_str += "Headers (Original Case):\n"; [log_str := log_str + f" {k}: {v}\n" for k, v in tech_data["headers"].items()]
hints: Set[str] = set()
# Header checks
if 'server' in headers_lower: hints.add(f"Server: {headers_lower['server']}")
if 'x-powered-by' in headers_lower: hints.add(f"X-Powered-By: {headers_lower['x-powered-by']}")
if 'x-aspnet-version' in headers_lower: hints.add("ASP.NET")
if 'x-aspnetmvc-version' in headers_lower: hints.add("ASP.NET MVC")
if 'x-drupal-cache' in headers_lower or 'x-drupal-dynamic-cache' in headers_lower or ('x-generator' in headers_lower and 'drupal' in headers_lower['x-generator'].lower()): hints.add("Drupal")
if 'x-joomla-cache' in headers_lower: hints.add("Joomla")
if 'x-magento-cache-debug' in headers_lower or 'x-magento-tags' in headers_lower: hints.add("Magento")
if headers_lower.get('x-generator', '').lower().startswith('wordpress'): hints.add("WordPress")
if 'cf-ray' in headers_lower: hints.add("Cloudflare")
if 'x-amz-cf-id' in headers_lower or 'via' in headers_lower and 'cloudfront' in headers_lower['via'].lower(): hints.add("AWS CloudFront")
if 'x-cache' in headers_lower and ('varnish' in headers_lower['x-cache'].lower() or 'varnish' in headers_lower.get('via','').lower()): hints.add("Varnish Cache")
if 'x-sucuri-id' in headers_lower: hints.add("Sucuri WAF")
# Cookie checks
set_cookie_header = headers_lower.get('set-cookie', '').lower()
if 'phpsessid' in set_cookie_header: hints.add("PHP Session")
if 'jsessionid' in set_cookie_header: hints.add("Java Session")
if 'aspsessionid' in set_cookie_header or 'asp.net' in set_cookie_header: hints.add("ASP/ASP.NET Session")
if '_wp_' in set_cookie_header or 'wordpress_logged_in' in set_cookie_header: hints.add("WordPress Hint (Cookie)")
if 'csrftoken' in set_cookie_header: hints.add("Django Hint (CSRF Token)")
if '_session_id' in set_cookie_header: hints.add("Ruby on Rails Hint (Session Cookie)")
# HTML checks
content_type = headers_lower.get('content-type', '').lower()
if 'text/html' in content_type:
soup = BeautifulSoup(response.text, 'html.parser')
generator_tag = soup.find('meta', attrs={'name': re.compile(r'^generator$', re.I)})
if generator_tag and generator_tag.get('content'):
gen_content = generator_tag['content']; hints.add(f"Generator: {gen_content}")
for tech in ["WordPress", "Joomla", "Drupal", "Wix", "Squarespace", "Shopify", "PrestaShop", "TYPO3 CMS"]:
if tech.lower() in gen_content.lower(): hints.add(tech)
scripts = [s.get('src', '') for s in soup.find_all('script', src=True)]
styles = [l.get('href', '') for l in soup.find_all('link', rel='stylesheet', href=True)]
resources = [r for r in scripts + styles if r]
if any('/wp-content/' in r or '/wp-includes/' in r for r in resources): hints.add("WordPress Hint (Path)")
if any('/sites/default/' in r or '/sites/all/' in r for r in resources): hints.add("Drupal Hint (Path)")
if any('skin/frontend/' in r or '/pub/static/' in r and 'magento' in r.lower() for r in resources): hints.add("Magento Hint (Path)")
if any('cdn.shopify.com' in r for r in resources): hints.add("Shopify Hint (CDN)")
if any('static.wixstatic.com' in r for r in resources): hints.add("Wix Hint (CDN)")
if any('assets.squarespace.com' in r for r in resources): hints.add("Squarespace Hint (CDN)")
if any('react.development.js' in r or 'react.production.min.js' in r or 'react-dom' in r for r in resources): hints.add("React")
if any('vue.js' in r or 'vue.min.js' in r for r in resources): hints.add("Vue.js")
if any('angular.js' in r or 'angular.min.js' in r or 'ng-app' in response.text or 'ng-version' in response.text for r in resources): hints.add("Angular")
if any('jquery.js' in r or 'jquery.min.js' in r or 'jquery-' in r for r in resources): hints.add("jQuery")
if any('bootstrap' in r for r in resources): hints.add("Bootstrap")
if any('google-analytics.com' in r or 'googletagmanager.com' in r for r in resources): hints.add("Google Analytics")
if any('cdnjs.cloudflare.com' in r for r in resources): hints.add("Cloudflare CDN (cdnjs)")
if any('ajax.googleapis.com' in r for r in resources): hints.add("Google Hosted Libraries")
if any('cdn.jsdelivr.net' in r for r in resources): hints.add("jsDelivr CDN")
if any('unpkg.com' in r for r in resources): hints.add("unpkg CDN")
if any('maxcdn.bootstrapcdn.com' in r for r in resources): hints.add("Bootstrap CDN (MaxCDN)")
tech_data["hints"] = sorted(list(hints))
log_str += "\nTechnology Hints Found:\n - " + "\n - ".join(tech_data["hints"]) + "\n" if tech_data["hints"] else "\nNo specific technology hints found.\n"
log_str += "\n(Note: Basic header/HTML analysis only.)\n"
except ConnectionError as e: err_msg = f"[!] Error connecting: {e}"; log_str += err_msg + "\n"; tech_data["errors"] = str(e)
except ValueError as e: err_msg = f"[!] Value Error: {e}"; log_str += err_msg + "\n"; tech_data["errors"] = str(e)
except Exception as e: err_msg = f"[!] Unexpected Error: {type(e).__name__}"; log_str += err_msg + "\n"; tech_data["errors"] = f"Unexpected: {type(e).__name__}"
return log_str, tech_data
def get_ip_and_reverse(domain_or_url_or_ip: str) -> Tuple[str, Dict[str, Any]]:
log_str = ""; network_data = {"input": domain_or_url_or_ip, "domain_or_ip": None, "ip_address": None, "reverse_dns": None, "aliases": [], "error": None}
target = domain_or_url_or_ip.strip()
domain_or_ip = extract_domain(target)
if not domain_or_ip: err_msg = f"Error: Could not extract/validate domain/IP from '{target}'"; network_data["error"] = err_msg; return err_msg, network_data
network_data["domain_or_ip"] = domain_or_ip; log_str += f"Network Info for: {domain_or_ip}\n" + "="*20 + "\n"
ip_address = resolve_domain(domain_or_ip)
network_data["ip_address"] = ip_address
if not ip_address: err_msg = f"[!] Could not resolve {domain_or_ip} to IP."; log_str += err_msg + "\n"; network_data["error"] = "DNS resolution failed"; return log_str, network_data
log_str += f"IP Address: {ip_address}\n"
try:
socket.setdefaulttimeout(5) # Timeout for reverse lookup
hostname, aliaslist, _ = socket.gethostbyaddr(ip_address)
network_data["reverse_dns"] = hostname; network_data["aliases"] = aliaslist
log_str += f"Reverse DNS (PTR): {hostname}\n" + (f"Aliases: {', '.join(aliaslist)}\n" if aliaslist else "")
except socket.herror: log_str += "Reverse DNS (PTR): Not found/failed.\n"; network_data["reverse_dns"] = "Not found"
except socket.timeout: log_str += "Reverse DNS (PTR): Timed out.\n"; network_data["reverse_dns"] = "Timeout"
except Exception as e: err_msg = f"Reverse DNS Error: {type(e).__name__}"; log_str += err_msg + "\n"; network_data["error"] = err_msg if not network_data["error"] else network_data["error"] + " | " + err_msg; network_data["reverse_dns"] = "Error"
finally: socket.setdefaulttimeout(None) # Reset default timeout
return log_str, network_data
def check_user_agent_diff(target_url: str) -> Tuple[str, Dict[str, Dict[str, Any]]]:
log_str = f"Checking User-Agent differences for: {target_url}\n" + "="*20 + "\n"
results_data = {}; sanitized_url = sanitize_url(target_url)
if not sanitized_url or '://' not in sanitized_url: err_msg = "[!] Invalid URL (requires scheme)."; return err_msg, {"error": err_msg}
target_url = sanitized_url
user_agents = {"Desktop Chrome": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36", "Mobile iPhone": "Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.0 Mobile/15E148 Safari/604.1", "Googlebot": "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)", "Bingbot": "Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)", "Curl": "curl/7.81.0", "Python": f"python-requests/{requests.__version__}", "ReconRevan": DEFAULT_USER_AGENT}
base_len, base_status, base_final_url, baseline_ua_name = None, None, None, None
for name, ua_string in user_agents.items():
log_str += f"[*] Testing UA: {name}\n"
ua_result = {'user_agent': name, 'status': None, 'length': -1, 'final_url': None, 'differs_status': None, 'differs_length': None, 'differs_url': None, 'is_baseline': False, 'error': None}
try:
response = make_request(target_url, headers={'User-Agent': ua_string}, allow_redirects=True)
status = response.status_code; content_len = len(response.content) if response.content is not None else -1; final_url = response.url
ua_result.update({'status': status, 'length': content_len, 'final_url': final_url})
log_str += f" Result: Status={status}, Length={content_len}, Final URL={final_url}\n"
if baseline_ua_name is None and status < 500:
base_status, base_len, base_final_url, baseline_ua_name = status, content_len, final_url, name
ua_result['is_baseline'] = True; log_str += f" ^^ Baseline Set ({name}) ^^\n"
if baseline_ua_name is not None and name != baseline_ua_name:
diff_status = (status != base_status); diff_len = (content_len != base_len); diff_url = (final_url != base_final_url)
ua_result['differs_status'] = diff_status; ua_result['differs_length'] = diff_len; ua_result['differs_url'] = diff_url
if diff_status: log_str += f" [!] Status Differs ({status} vs {base_status})\n"
if diff_len:
len_delta = abs(content_len - base_len) if base_len is not None and content_len != -1 else 0
prefix = "[!]" if len_delta > 20 else "[*]"; log_str += f" {prefix} Length Differs ({content_len} vs {base_len})\n"
if diff_url: log_str += f" [!] Final URL Differs\n"
except ConnectionError as e: ua_result['error'] = str(e); log_str += f" [!] Error: {e}\n"
except ValueError as e: ua_result['error'] = str(e); log_str += f" [!] Error: {e}\n"
except Exception as e: ua_result['error'] = f"Unexpected: {type(e).__name__}"; log_str += f" [!] Unexpected Error: {type(e).__name__}\n"
results_data[name] = ua_result; time.sleep(0.03)
if baseline_ua_name is None: log_str += "\n[!] Could not establish a baseline response.\n"
return log_str, results_data
def check_ssl_sans(domain_or_url_or_ip: str) -> Tuple[str, Dict[str, Any]]:
log_str = ""; cert_data = {"input": domain_or_url_or_ip, "domain_or_ip": None, "ip_address": None, "subject": None, "issuer": None, "serial": None, "version": None, "valid_from": None, "valid_to": None, "sans": [], "error": None, "is_expired": None, "days_left": None, "common_name": None, "signature_algorithm": None, "public_key_type": None, "public_key_bits": None}
target = domain_or_url_or_ip.strip(); domain_or_ip = extract_domain(target)
if not domain_or_ip: err_msg = f"Invalid domain/IP '{target}'"; cert_data["error"] = err_msg; return err_msg, cert_data
cert_data["domain_or_ip"] = domain_or_ip; log_str += f"Checking SSL Certificate for: {domain_or_ip}\n" + "="*20 + "\n"
port = 443; context = ssl.create_default_context()
ip_address = resolve_domain(domain_or_ip)
if not ip_address: err_msg = f"Could not resolve {domain_or_ip} to IP"; log_str += err_msg + "\n"; cert_data["error"] = "DNS resolution failed"; return log_str, cert_data
cert_data["ip_address"] = ip_address; sni_host = domain_or_ip if not is_ip_address(domain_or_ip) else None
log_str += f"Connecting to IP: {ip_address} (SNI: {sni_host})\n"
conn_sock, ssl_sock = None, None
try:
conn_sock = socket.create_connection((ip_address, port), timeout=REQUEST_TIMEOUT)
ssl_sock = context.wrap_socket(conn_sock, server_hostname=sni_host)
cert_der = ssl_sock.getpeercert(binary_form=True)
if not cert_der: raise ssl.SSLError("getpeercert returned None")
cert = x509.load_der_x509_certificate(cert_der, default_backend())
subject = cert.subject; issuer = cert.issuer; valid_from = cert.not_valid_before_utc.replace(tzinfo=timezone.utc); valid_to = cert.not_valid_after_utc.replace(tzinfo=timezone.utc)
cn = next((a.value for a in subject.get_attributes_for_oid(x509.NameOID.COMMON_NAME)), None)
now = datetime.now(timezone.utc); expired = now > valid_to; days = (valid_to - now).days if not expired else -1
sig_oid = cert.signature_algorithm_oid; sig_alg = getattr(sig_oid, '_name', sig_oid.dotted_string)
pk = cert.public_key(); pk_type = type(pk).__name__.replace("PublicKey", ""); pk_bits = getattr(pk, 'key_size', None)
cert_data.update({"subject": subject.rfc4514_string(), "issuer": issuer.rfc4514_string(), "common_name": cn, "serial": cert.serial_number, "version": str(cert.version), "valid_from": valid_from.isoformat(), "valid_to": valid_to.isoformat(), "is_expired": expired, "days_left": days, "signature_algorithm": sig_alg, "public_key_type": pk_type, "public_key_bits": pk_bits})
log_str += f"Subject: {cert_data['subject']}\n" + (f"CN: {cn}\n" if cn else "") + f"Issuer: {cert_data['issuer']}\nSerial: {cert.serial_number}\nSig Alg: {sig_alg}\nPubKey: {pk_type} ({pk_bits} bits)\n"
log_str += f"Valid From: {valid_from}\nValid To: {valid_to}\nExpired: {'Yes' if expired else 'No'}" + (f" (Days Left: {days})" if not expired else "") + "\n"
log_str += "\nSANs:\n"; san_list = []
try:
san_ext = cert.extensions.get_extension_for_oid(x509.ExtensionOID.SUBJECT_ALTERNATIVE_NAME)
for name in san_ext.value: type_n = type(name).__name__; val = str(name.value); san_list.append(f"{type_n}: {val}"); log_str += f" {type_n}: {val}\n"
if not san_list: log_str += " (None found)\n"
except x509.ExtensionNotFound: log_str += " (SAN extension not found)\n"
except Exception as e: log_str += f" Error parsing SANs: {e}\n"
cert_data["sans"] = sorted(list(set(san_list)))
except socket.timeout: err = "Timeout"; log_str += f"[!] {err}\n"; cert_data["error"] = err
except ssl.SSLCertVerificationError as e: err = f"Cert Verification Error: {getattr(e, 'reason', str(e))}"; log_str += f"[!] {err}\n"; cert_data["error"] = err
except ssl.SSLError as e: err = f"SSL Error: {getattr(e, 'reason', str(e))}"; log_str += f"[!] {err}\n"; cert_data["error"] = err
except ConnectionRefusedError: err = "Connection refused"; log_str += f"[!] {err}\n"; cert_data["error"] = err
except OSError as e: err = f"OS Error: {e}"; log_str += f"[!] {err}\n"; cert_data["error"] = err
except Exception as e: err = f"Unexpected SSL Error: {type(e).__name__}"; log_str += f"[!] {err}\n"; cert_data["error"] = err
finally:
if ssl_sock: ssl_sock.close()
elif conn_sock: conn_sock.close()
return log_str, cert_data
def find_third_party(target_url: str) -> Tuple[str, Dict[str, Any]]:
log_str = f"Identifying third-party content for: {target_url}\n" + "="*20 + "\n"
third_party_data = {"base_domain": None, "third_party_domains": [], "resources": {'scripts': [], 'stylesheets': [], 'images': [], 'iframes': [], 'links': []}, "error": None}
sanitized_url = sanitize_url(target_url)
if not sanitized_url or '://' not in sanitized_url: err_msg = "[!] Invalid URL (requires scheme)."; third_party_data["error"] = err_msg; return err_msg, third_party_data
target_url = sanitized_url; base_domain = extract_domain(target_url)
if not base_domain: err_msg = f"Could not extract base domain"; third_party_data["error"] = err_msg; return err_msg, third_party_data
third_party_data["base_domain"] = base_domain; log_str += f"Base Domain: {base_domain}\n"; third_party_domains_set: Set[str] = set()
try:
response = make_request(target_url); response.raise_for_status()
content_type = response.headers.get('Content-Type', '').lower()
if 'text/html' not in content_type: err = f"Not HTML ({content_type})"; log_str += err + "\n"; third_party_data["error"] = err; return log_str, third_party_data
soup = BeautifulSoup(response.text, 'html.parser')
tags_attrs = {'scripts': ('script', 'src'), 'stylesheets': ('link', 'href'), 'images': ('img', 'src'), 'iframes': ('iframe', 'src'), 'links': ('a', 'href')}
for res_type, (tag_name, url_attr) in tags_attrs.items():
for tag in soup.find_all(tag_name):
if res_type == 'stylesheets' and tag.get('rel', [''])[0].lower() != 'stylesheet': continue
url = tag.get(url_attr)
if not url or url.lower().startswith(('data:', '#', 'mailto:', 'tel:', 'javascript:')): continue
try:
abs_url = urljoin(target_url, url); domain = extract_domain(abs_url)
if domain and domain != base_domain and not domain.endswith('.' + base_domain):
third_party_domains_set.add(domain); third_party_data["resources"][res_type].append(abs_url)
except Exception as url_e: log_str += f" [!] Error processing resource '{url}': {url_e}\n"
third_party_data["third_party_domains"] = sorted(list(third_party_domains_set))
log_str += f"\nFound {len(third_party_data['third_party_domains'])} unique third-party domains:\n" + "\n".join(f" - {d}" for d in third_party_data["third_party_domains"]) + "\n"
log_str += "\nThird-Party Resources Found (Sample):\n"
for res_type, urls in third_party_data["resources"].items():
if urls: log_str += f" {res_type.capitalize()}:\n" + "\n".join(f" - {u}" for u in urls[:5]) + (f"\n - ... ({len(urls) - 5} more)" if len(urls) > 5 else "") + "\n"
except ConnectionError as e: err = f"Connection Error: {e}"; log_str += f"[!] {err}\n"; third_party_data["error"] = err
except requests.exceptions.HTTPError as e: err = f"HTTP Error: {e.response.status_code}"; log_str += f"[!] {err}\n"; third_party_data["error"] = err
except ValueError as e: err = f"Value Error: {e}"; log_str += f"[!] {err}\n"; third_party_data["error"] = err
except Exception as e: err = f"Unexpected Error: {type(e).__name__}"; log_str += f"[!] {err}\n"; third_party_data["error"] = err
return log_str, third_party_data
def subdomain_enum_basic(domain_or_url_or_ip: str) -> Tuple[str, List[Dict[str, Any]]]:
log_str = ""; results_data = []; thread_logs: queue.Queue[str] = queue.Queue()
target = domain_or_url_or_ip.strip()
if is_ip_address(target): err = "Input is IP, requires domain."; return err, [{"subdomain": "N/A", "ip": None, "error": err}]
domain = extract_domain(target)
if not domain or is_ip_address(domain): err = f"Invalid domain from '{target}'"; return err, [{"subdomain": "Error", "ip": None, "error": err}]
log_str += f"Basic Subdomain Enumeration (DNS) for: {domain}\n(Checking {len(COMMON_SUBDOMAINS_SAMPLE)} common names)\n" + "="*20 + "\n"
found: List[Dict[str, Any]] = []; q: queue.Queue[str] = queue.Queue(); lock = threading.Lock()
def worker():
while True:
try: sub = q.get_nowait()
except queue.Empty: break
target_sub = f"{sub}.{domain}"; info = {"subdomain": target_sub, "ip": None, "error": None}; local_log = f"[-] Checking: {target_sub} ... "
try:
ip = resolve_domain(target_sub)
if ip: info["ip"] = ip; local_log += f"Found -> {ip}"; found.append(info) # No lock needed for list append from different threads apparently
else: local_log += "Not resolved"; info["error"] = "DNS failed"
except Exception as e: info["error"] = f"Unexpected: {type(e).__name__}"; local_log += f"Error ({type(e).__name__})"
thread_logs.put(local_log); q.task_done(); time.sleep(0.01)
for sub in COMMON_SUBDOMAINS_SAMPLE: q.put(sub)
threads = []; num_threads = min(MAX_THREADS, q.qsize())
log_str += f"[*] Starting {num_threads} threads...\n"
for _ in range(num_threads): t = threading.Thread(target=worker, daemon=True); t.start(); threads.append(t)
q.join() # Wait for queue to be processed
while not thread_logs.empty(): log_str += thread_logs.get_nowait() + "\n" # Collect logs
log_str += f"\n[*] Check finished. Found {len(found)} resolvable subdomains.\n"
results_data = sorted(found, key=lambda x: x['subdomain'])
return log_str, results_data
def scan_port(ip: str, port: int, timeout: float = 1.0) -> bool:
sock = None
try:
ip_obj = ipaddress.ip_address(ip); family = socket.AF_INET6 if isinstance(ip_obj, ipaddress.IPv6Address) else socket.AF_INET
sock = socket.socket(family, socket.SOCK_STREAM); sock.settimeout(timeout)
return sock.connect_ex((ip, port)) == 0
except (socket.timeout, socket.error, OSError, ValueError): return False
finally:
if sock: sock.close()
def port_scan_host(domain_or_url_or_ip: str, ports_to_scan: Optional[List[int]] = None) -> Tuple[str, Dict[str, Any]]:
log_str = ""; scan_results = {"input": domain_or_url_or_ip, "ip_address": None, "open_ports": [], "closed_ports_count": 0, "error": None}; thread_logs = queue.Queue()
target = domain_or_url_or_ip.strip(); domain_or_ip = extract_domain(target)
if not domain_or_ip: err = f"Invalid domain/IP from '{target}'"; scan_results["error"] = err; return err, scan_results
ip_address = resolve_domain(domain_or_ip)
if not ip_address: err = f"Could not resolve {domain_or_ip} to IP"; log_str += err + "\n"; scan_results["error"] = "DNS failed"; return log_str, scan_results
scan_results["ip_address"] = ip_address; ports = ports_to_scan or COMMON_PORTS_SAMPLE; port_timeout = max(0.5, REQUEST_TIMEOUT / 10)
log_str += f"Starting Port Scan for: {domain_or_ip} ({ip_address})\nScanning {len(ports)} ports (Timeout: {port_timeout:.1f}s/port)\n" + "="*20 + "\n"
open_ports: List[int] = []; closed_count = 0; port_q: queue.Queue[int] = queue.Queue(); lock = threading.Lock()
def worker():
nonlocal closed_count
while True:
try: port = port_q.get_nowait()
except queue.Empty: break
if scan_port(ip_address, port, port_timeout):
with lock: open_ports.append(port); thread_logs.put(f"[+] Port {port}: Open")
else:
with lock: closed_count += 1 # Count closed non-atomically needs lock
# thread_logs.put(f"[-] Port {port}: Closed") # Optional logging
port_q.task_done(); time.sleep(0.01)
for p in ports: port_q.put(p)
threads = []; num_threads = min(MAX_THREADS, port_q.qsize())
log_str += f"[*] Starting {num_threads} threads...\n"
for _ in range(num_threads): t = threading.Thread(target=worker, daemon=True); t.start(); threads.append(t)
port_q.join()
while not thread_logs.empty(): log_str += thread_logs.get_nowait() + "\n"
scan_results["open_ports"] = sorted(open_ports); scan_results["closed_ports_count"] = closed_count
log_str += f"\n[*] Scan finished. Found {len(open_ports)} open ports ({closed_count} closed/filtered).\n" + (f"Open Ports: {', '.join(map(str, sorted(open_ports)))}\n" if open_ports else "")
return log_str, scan_results
# --- Plotting Functions (Using actual data structures) ---
def create_ssl_gauge(ssl_data: Dict[str, Any]) -> Optional[go.Figure]:
if not isinstance(ssl_data, dict) or ssl_data.get("error") or ssl_data.get("days_left") is None: return None
try:
days_left = int(ssl_data["days_left"]); gauge_value = max(0, days_left); gauge_max = SSL_GAUGE_MAX_DAYS
color = NEO_ACCENT_COLOR # Default blueish
if days_left < 0: color = "#C70039"; gauge_value = 0 # Dark Red
elif days_left < 30: color = "#FFC300" # Amber/Orange
elif days_left < 90: color = "#DAF7A6" # Light Green
fig = go.Figure(go.Indicator(mode="gauge+number", value=gauge_value, domain={'x': [0, 1], 'y': [0, 1]},
title={'text': "SSL Cert Validity (Days Left)", 'font': {'size': 16, 'color': 'white'}},
gauge={'axis': {'range': [0, gauge_max], 'tickwidth': 1, 'tickcolor': "#A0A0A0", 'nticks': 7},
'bar': {'color': color, 'thickness': 0.35}, 'bgcolor': "rgba(0,0,0,0.3)", 'borderwidth': 2, 'bordercolor': NEO_BORDER_COLOR,
'steps': [{'range': [0, 30], 'color': 'rgba(255, 195, 0, 0.3)'}, {'range': [30, 90], 'color': 'rgba(218, 247, 166, 0.2)'}],
'threshold': {'line': {'color': "#C70039", 'width': 4}, 'thickness': 0.8, 'value': 14 }}))
fig.update_layout(paper_bgcolor=NEO_BACKGROUND_COLOR, font={'color': "white", 'family': "IBM Plex Sans"}, margin=dict(l=30, r=30, t=60, b=30))
return fig
except Exception as e: print(f"Error creating SSL gauge: {e}"); return None
def create_findings_radar(results: Dict[str, Any]) -> Optional[go.Figure]:
try:
open_ports_data = results.get("Port Scan", {}).get("open_ports", [])
subdomains_data = results.get("Subdomain Enum", []) # List of dicts
tech_hints_data = results.get("Technology ID", {}).get("hints", [])
common_files_result = results.get("Common Files", []) # List of dicts
third_party_domains_data = results.get("Third-Party", {}).get("third_party_domains", [])
# Ensure data is list before len()
data_sources = {
"Open Ports": open_ports_data if isinstance(open_ports_data, list) else [],
"Subdomains": subdomains_data if isinstance(subdomains_data, list) else [],
"Tech Hints": tech_hints_data if isinstance(tech_hints_data, list) else [],
"Common Files": [f for f in common_files_result if isinstance(f, dict) and f.get("found")],
"3rd Party Domains": third_party_domains_data if isinstance(third_party_domains_data, list) else []
}
categories = list(data_sources.keys())
values = [len(data_sources[cat]) for cat in categories]
if not any(values): print("No data for radar chart."); return None
# Simple scaling: add 1 to avoid log(0) and use log scale for radial axis if values vary wildly
# Or just cap max value visually
max_val = max(1, max(values))
radial_range = [0, max_val]
fig = go.Figure()
fig.add_trace(go.Scatterpolar(r=values, theta=categories, fill='toself', name='Count', line_color=NEO_ACCENT_COLOR, fillcolor=f'{NEO_ACCENT_COLOR}33')) # Accent color with alpha
fig.update_layout(polar=dict(radialaxis=dict(visible=True, range=radial_range, color='white', gridcolor='rgba(255,255,255,0.2)'), angularaxis=dict(color='white', gridcolor='rgba(255,255,255,0.2)')),
showlegend=False, template=PLOTLY_TEMPLATE, paper_bgcolor=NEO_BACKGROUND_COLOR, plot_bgcolor=NEO_BACKGROUND_COLOR,
title=dict(text="Findings Overview", font=dict(color='white', size=18)), font=dict(color='white'), margin=dict(l=50, r=50, t=80, b=50))
return fig
except Exception as e: print(f"Error creating radar chart: {e}"); return None
def create_status_code_bar(common_files_data: List[Dict[str, Any]]) -> Optional[go.Figure]:
if not isinstance(common_files_data, list): return None
try:
status_codes = [item.get("status") for item in common_files_data if isinstance(item, dict) and item.get("status") is not None]
if not status_codes: return None
status_cats = {'2xx': 0, '3xx': 0, '4xx': 0, '5xx': 0, 'Err': 0}
for code in status_codes:
try: code_int = int(code); cat = f"{str(code_int)[0]}xx"; status_cats[cat] = status_cats.get(cat, 0) + 1
except (ValueError, TypeError, IndexError): status_cats['Err'] += 1
cats = list(status_cats.keys()); counts = list(status_cats.values())
filtered_cats = [c for c, n in zip(cats, counts) if n > 0]; filtered_counts = [n for n in counts if n > 0]
if not filtered_counts: return None
colors = px.colors.qualitative.Pastel # Use a different scheme
fig = go.Figure(data=[go.Bar(x=filtered_cats, y=filtered_counts, text=filtered_counts, textposition='outside',
marker_color=[colors[i % len(colors)] for i in range(len(filtered_cats))],
marker_line_color=NEO_BORDER_COLOR, marker_line_width=2, opacity=0.9)])
fig.update_layout(title='Common Files Check - Status Code Distribution', xaxis_title='Status Category', yaxis_title='Count', template=PLOTLY_TEMPLATE,
paper_bgcolor=NEO_BACKGROUND_COLOR, plot_bgcolor=NEO_BACKGROUND_COLOR, font=dict(color='white'), yaxis=dict(gridcolor='rgba(255,255,255,0.1)'),
xaxis=dict(gridcolor='rgba(255,255,255,0.1)'), margin=dict(l=40, r=20, t=50, b=40))
return fig
except Exception as e: print(f"Error creating status bar chart: {e}"); return None
# --- Gradio Orchestration Function ---
def run_all_scans(target_input: str, crawl_depth_str: str, crawl_max_urls_str: str, progress=gr.Progress(track_tqdm=True)):
"""Runs all reconnaissance scans, aggregates results, and generates plots."""
outputs_count = 12 # log, json, 7 DFs, 3 plots
target_input = target_input.strip()
if not target_input: return "Error: Target input cannot be empty.", None, *([None] * (outputs_count - 2))
try: crawl_depth = int(crawl_depth_str); crawl_max_urls = int(crawl_max_urls_str)
except ValueError: return "Error: Crawl depth/max URLs must be numbers.", None, *([None] * (outputs_count - 2))
if crawl_depth < 0 or crawl_max_urls <= 0: return "Error: Invalid crawl parameters.", None, *([None] * (outputs_count - 2))
# --- Define Scan Stages ---
scan_stages = [
("Network Info", get_ip_and_reverse, [target_input]),
("SSL Certificate", check_ssl_sans, [target_input]), # Uses output of Network Info if available
("Common Files", fetch_common_files, [target_input]), # Needs URL
("Technology ID", identify_technologies, [target_input]), # Needs URL
("User-Agent Diff", check_user_agent_diff, [target_input]), # Needs URL
("Third-Party", find_third_party, [target_input]), # Needs URL
("Subdomain Enum", subdomain_enum_basic, [target_input]), # Needs domain
("Port Scan", port_scan_host, [target_input]), # Needs domain/IP from Network Info
("Basic Crawl", basic_crawl, [target_input, str(crawl_depth), str(crawl_max_urls)]), # Needs URL
]
# --- Initialize Results ---
all_logs = f"--- Reconnaissance Report for: {target_input} ---\nTimestamp: {datetime.now(timezone.utc).isoformat()}\n\n"; results = {}
progress(0, desc="Starting Scans...")
network_info_result = None # Store network info to use later
# --- Execute Scans ---
for i, (stage_name, scan_func, args) in enumerate(scan_stages):
progress((i + 1) / len(scan_stages), desc=f"Running: {stage_name}...")
log_str_out = f"--- {i+1}. {stage_name} ---\n"; data_out = None; error_msg = None; skip = False
current_target_arg = args[0] # Original input
# Check prerequisites
if stage_name in ["Port Scan", "SSL Certificate"]:
if not network_info_result or network_info_result.get("error") or not network_info_result.get("domain_or_ip"):
error_msg = f"Skipped (Requires successful Network Info step)"; skip = True
else:
args[0] = network_info_result["domain_or_ip"] # Use resolved domain/IP
elif stage_name in ["Common Files", "Technology ID", "User-Agent Diff", "Third-Party", "Basic Crawl"]:
url_target = sanitize_url(current_target_arg)
if not url_target or '://' not in url_target: error_msg = f"Skipped (Requires valid URL)"; skip = True
else: args[0] = url_target
elif stage_name == "Subdomain Enum":
domain_target = extract_domain(current_target_arg)
if not domain_target or is_ip_address(domain_target): error_msg = f"Skipped (Requires domain name)"; skip = True
else: args[0] = domain_target
if skip: log_str_out += f"{error_msg}\n"; data_out = {"error": error_msg}
else:
try:
log_res, data_res = scan_func(*args)
log_str_out += log_res + "\n"; data_out = data_res
if stage_name == "Network Info": network_info_result = data_res # Store for later stages
except Exception as e:
error_msg = f"[!!!] Stage Error: {type(e).__name__}"; print(f"Error in {stage_name}: {e}")
log_str_out += f"{error_msg} - Check console for details.\n"; data_out = {"error": error_msg}
all_logs += log_str_out
results[stage_name] = data_out if data_out is not None else {"error": "Scan stage error or no data."}
progress(1.0, desc="Processing Results...")
# --- Prepare DataFrames ---
def create_df(data, columns): # Simplified DF creation
fallback = pd.DataFrame(columns=columns)
if not data or isinstance(data, dict) and data.get("error"): return fallback
try:
if isinstance(data, list): df = pd.DataFrame(data if data else [], columns=columns); return df.where(pd.notnull(df), None) # Handle potential None values from backend
elif isinstance(data, dict): # Adapt for specific structures
if 'hints' in data: return pd.DataFrame([{"hint": h} for h in data.get('hints',[])], columns=columns)
if 'open_ports' in data: return pd.DataFrame([{"port": p} for p in data.get('open_ports',[])], columns=columns)
if 'sans' in data: return pd.DataFrame([{"san": s} for s in data.get('sans',[])], columns=columns)
if 'third_party_domains' in data: return pd.DataFrame([{"domain": d} for d in data.get('third_party_domains',[])], columns=columns)
return fallback
except Exception as e: print(f"DF Error {columns}: {e}"); return fallback
common_files_df=create_df(results.get("Common Files"), ["url", "status", "found", "size", "content_type", "error"])
crawl_df=create_df(results.get("Basic Crawl"), ["url", "depth", "status", "content_type", "size", "links_found", "error"])
tech_hints_df=create_df(results.get("Technology ID"), ["hint"])
ssl_sans_df=create_df(results.get("SSL Certificate"), ["san"])
subdomain_df=create_df(results.get("Subdomain Enum"), ["subdomain", "ip", "error"])
open_ports_df=create_df(results.get("Port Scan"), ["port"])
third_party_domains_df=create_df(results.get("Third-Party"), ["domain"])
# --- Create Plots ---
ssl_gauge_fig = create_ssl_gauge(results.get("SSL Certificate", {}))
radar_fig = create_findings_radar(results)
status_bar_fig = create_status_code_bar(results.get("Common Files", []))
# --- Prepare Summary JSON ---
summary_data = {f"{k} Summary": v for k, v in results.items() if isinstance(v, dict) and k not in ["Common Files", "Basic Crawl", "Subdomain Enum"]}
# Clean up summary data if needed
try: summary_json_str = json.dumps(summary_data, indent=2, default=str)
except Exception as e: summary_json_str = f'{{"error": "Failed to serialize summary", "detail": "{str(e)}"}}'
return (all_logs, summary_json_str, common_files_df, tech_hints_df, ssl_sans_df, subdomain_df, open_ports_df, third_party_domains_df, crawl_df, ssl_gauge_fig, radar_fig, status_bar_fig)
# --- Gradio Interface Definition ---
css = f"""
:root {{
--neo-border: {NEO_BORDER_STYLE};
--neo-radius: 0px;
--neo-shadow: {NEO_HARD_SHADOW};
--neo-accent: {NEO_ACCENT_COLOR};
}}
.gradio-container {{ font-family: 'IBM Plex Sans', sans-serif; }}
/* Base element styling */
.gr-input-text input, .gr-textarea textarea, .gr-button, .gr-dataframe table, .gr-tabs button, .gr-accordion, .gr-code, .gr-json, .gr-plot {{
border: var(--neo-border) !important;
border-radius: var(--neo-radius) !important;
background-color: var(--neutral-900); /* Ensure dark background */
color: var(--body-text-color);
}}
.gr-block {{ border: none !important; box-shadow: none !important; }} /* Remove default block borders/shadows */
.gr-input-text, .gr-textarea {{ border: none !important; padding: 0 !important; }} /* Remove wrapper styling */
/* Button styling */
.gr-button {{ background: var(--neo-accent); color: black; font-weight: bold; box-shadow: var(--neo-shadow); }}
.gr-button:hover {{ background: var(--primary-600) !important; color: white; box-shadow: none !important; transform: translate(3px, 3px); }}
/* Tab styling */
.gr-tabs {{ border: var(--neo-border) !important; border-radius: var(--neo-radius) !important; }}
.gr-tabs button {{ background-color: var(--neutral-800); border-right: var(--neo-border) !important; border-bottom: none !important; border-radius: 0 !important; box-shadow: none !important; }}
.gr-tabs button.selected {{ background-color: var(--neutral-950); border: var(--neo-border) !important; border-bottom: 3px solid var(--neo-accent) !important; box-shadow: var(--neo-shadow); transform: translate(-2px, -2px); }}
/* Dataframe styling */
.gr-dataframe {{ padding: 2px !important; background-color: var(--neutral-900) !important; }}
.gr-dataframe table thead th {{ background-color: var(--neutral-800) !important; border: var(--neo-border) !important; font-weight: bold; }}
.gr-dataframe table tbody td {{ border: 1px solid var(--neutral-700) !important; border-radius: 0 !important; }} /* Thinner internal lines */
/* Plotly container */
.gr-plot {{ padding: 5px; background-color: {NEO_BACKGROUND_COLOR} !important; }}
/* Accordion */
.gr-accordion > .label-wrap {{ background-color: var(--neutral-800); border: var(--neo-border) !important; border-radius: 0 !important; padding: 8px; }}
"""
with gr.Blocks(theme=gr.themes.Default(primary_hue="cyan", secondary_hue="neutral", neutral_hue="slate").set(
block_background_fill=NEO_BACKGROUND_COLOR, body_background_fill=NEO_BACKGROUND_COLOR,
button_primary_background_fill=NEO_ACCENT_COLOR, button_primary_text_color="black",
block_border_width="0px", block_shadow="none", input_border_width="0px", input_shadow = "none",
), css=css, title="Recon Revan v2.2") as demo:
gr.Markdown("# Recon Revan v2.2")
gr.Markdown("_Enter a target URL (e.g., `http://example.com`), domain (`example.com`), or IP address (`8.8.8.8`)._")
with gr.Row():
with gr.Column(scale=1):
target = gr.Textbox(label="Target", placeholder="example.com", elem_classes=["gr-input-text"])
with gr.Accordion("Settings", open=False):
crawl_depth_input = gr.Textbox(label="Crawl Depth", value="1", elem_classes=["gr-input-text"])
crawl_urls_input = gr.Textbox(label="Crawl Max URLs", value="50", elem_classes=["gr-input-text"])
submit_btn = gr.Button("▶ Run Scans", variant="primary", size="lg")
with gr.Column(scale=3):
log_output = gr.Textbox(label="Master Log", lines=28, interactive=False, show_copy_button=True, elem_classes=["gr-textarea"])
gr.Markdown("---")
# Use Markdown for a bolder heading
gr.Markdown("### Scan Results")
with gr.Tabs():
with gr.TabItem("Summary"):
summary_output = gr.Code(label="Scan Summaries", language="json", interactive=False)
with gr.TabItem("Visualizations"):
gr.Markdown("Visual overview of findings.")
with gr.Row(equal_height=False):
ssl_gauge_plot = gr.Plot(label="SSL Validity", min_width=250)
radar_plot = gr.Plot(label="Findings Overview", min_width=400)
with gr.Row():
status_bar_plot = gr.Plot(label="Common Files Status Codes", min_width=600)
with gr.TabItem("Common Files"):
files_df_output = gr.DataFrame(label="Common Files Results", interactive=False, wrap=True)
with gr.TabItem("Technology"):
tech_df_output = gr.DataFrame(label="Technology Hints", interactive=False, wrap=True, headers=["Hint"])
with gr.TabItem("SSL SANs"):
ssl_df_output = gr.DataFrame(label="SSL SANs", interactive=False, wrap=True, headers=["SAN Entry"])
with gr.TabItem("Subdomains"):
subdomain_df_output = gr.DataFrame(label="Found Subdomains", interactive=False, wrap=True)
with gr.TabItem("Open Ports"):
ports_df_output = gr.DataFrame(label="Open Ports", interactive=False, wrap=True, headers=["Port"])
with gr.TabItem("Third-Party"):
third_party_df_output = gr.DataFrame(label="Third-Party Domains", interactive=False, wrap=True, headers=["Domain"])
with gr.TabItem("Crawl"):
crawl_df_output = gr.DataFrame(label="Crawled URLs", interactive=False, wrap=True)
outputs_list = [ log_output, summary_output, files_df_output, tech_df_output, ssl_df_output, subdomain_df_output, ports_df_output, third_party_df_output, crawl_df_output, ssl_gauge_plot, radar_plot, status_bar_plot ]
submit_btn.click( fn=run_all_scans, inputs=[target, crawl_depth_input, crawl_urls_input], outputs=outputs_list, api_name="run_scans" )
if __name__ == "__main__":
print("Launching Recon Revan v2.2 Gradio App...")
print("Ensure you have permission to scan the target.")
print("API documentation available via the footer link '/api'.")
print("WARNING: Use auth=() for security if exposing this app.")
demo.launch(debug=False, share=True) # Add auth=("user", "pass") if needed