from fastapi import APIRouter, HTTPException, Query import subprocess import platform import dns.resolver from mac_vendor_lookup import MacLookup import socket import asyncio import hashlib from datetime import datetime, timezone import subprocess import re import ssl import httpx from cryptography import x509 from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import rsa, ec, dsa router = APIRouter() from fastapi import APIRouter, HTTPException, Query import subprocess import platform import dns.resolver from mac_vendor_lookup import MacLookup import socket import asyncio import hashlib from datetime import datetime, timezone import subprocess import re import ssl import httpx from cryptography import x509 from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import rsa, ec, dsa router = APIRouter() # Function to convert timezone-aware datetime to naive def convert_to_naive(dt: datetime) -> datetime: if dt.tzinfo is not None: return dt.astimezone(timezone.utc).replace(tzinfo=None) # Convert to naive return dt # Already naive, no changes needed # Function to fetch certificate chain (simplified) def fetch_certificate_chain(domain: str): ctx = ssl.create_default_context() cert_chain = [] try: with socket.create_connection((domain, 443)) as sock: with ctx.wrap_socket(sock, server_hostname=domain) as ssock: cert_bin = ssock.getpeercert(binary_form=True) cert = x509.load_der_x509_certificate(cert_bin, default_backend()) cert_chain.append(cert) # Add intermediate certs and root certs here if available except Exception as e: return {"error": f"Failed to fetch certificate chain: {str(e)}"} return cert_chain # Consolidated endpoint for SSL, OCSP, Certificate Chain, Protocols and Ciphers @router.get("/decoderssh") async def ssl_details(domain: str = Query(...)): ctx = ssl.create_default_context() try: clean_domain = domain.replace("https://", "").replace("http://", "").split('/')[0].split(':')[0] # Establish a connection and fetch certificate with socket.create_connection((clean_domain, 443), timeout=5) as sock: with ctx.wrap_socket(sock, server_hostname=clean_domain) as ssock: cert_bin = ssock.getpeercert(binary_form=True) cert = x509.load_der_x509_certificate(cert_bin, default_backend()) # Fingerprints and Public Key Details sha256 = hashlib.sha256(cert_bin).hexdigest().upper() sha1 = hashlib.sha1(cert_bin).hexdigest().upper() pub_key = cert.public_key() key_size = getattr(pub_key, 'key_size', 'Unknown') key_type = pub_key.__class__.__name__.replace('RSAPublicKey', 'RSA').replace('EllipticCurvePublicKey', 'EC') # Extended Key Usage and Revocation Check extended_key_usage = [] try: eku_ext = cert.extensions.get_extension_for_oid(x509.ExtensionOID.EXTENDED_KEY_USAGE) extended_key_usage = eku_ext.value except Exception: pass # Convert to naive datetime objects to avoid timezone issues not_before_naive = convert_to_naive(cert.not_valid_before_utc) not_after_naive = convert_to_naive(cert.not_valid_after_utc) # Get certificate chain cert_chain = fetch_certificate_chain(domain) if "error" in cert_chain: raise HTTPException(status_code=400, detail=cert_chain["error"]) # Get protocols and ciphers with socket.create_connection((clean_domain, 443)) as sock: with ctx.wrap_socket(sock, server_hostname=clean_domain) as ssock: supported_protocol = ssock.version() supported_ciphers = ssock.cipher() # Placeholder for OCSP status (to be improved with real OCSP checks) ocsp_status = "OCSP Status: Valid" # Return detailed certificate info return { "domain": domain, "subject": {attr.oid._name: str(attr.value) for attr in cert.subject}, "issuer": {attr.oid._name: str(attr.value) for attr in cert.issuer}, "validity": { "notBefore": not_before_naive.isoformat(), "notAfter": not_after_naive.isoformat(), "days_remaining": (not_after_naive - datetime.now()).days }, "serialNumber": format(cert.serial_number, 'X'), "fingerprints": {"sha256": sha256, "sha1": sha1}, "key_info": f"{key_type} {key_size} bits", "extendedKeyUsage": [str(eku) for eku in extended_key_usage], "certificateChain": [str(cert.subject) for cert in cert_chain], "revocationStatus": ocsp_status, "protocols": supported_protocol, "ciphers": supported_ciphers } except Exception as e: raise HTTPException(status_code=400, detail=f"Failed to fetch certificate details: {str(e)}") @router.get("/mac-lookup") async def mac_address_lookup(mac: str = Query(...)): try: url = f"https://api.macvendors.com/{mac}" async with httpx.AsyncClient(timeout=10) as client: r = await client.get(url) if r.status_code == 200: vendor = r.text else: vendor = "Private / Randomized MAC" return { "mac": mac, "vendor": vendor } except Exception: return { "mac": mac, "vendor": "Lookup failed" } @router.get("/ping") async def ping_host(host: str = Query(...)): try: # Windows vs Linux ping command param = "-n" if platform.system().lower() == "windows" else "-c" cmd = ["ping", param, "4", host] result = subprocess.run( cmd, capture_output=True, text=True, timeout=10 ) return { "pingResult": result.stdout or result.stderr } except Exception: raise HTTPException( status_code=500, detail="Ping failed" ) @router.get("/dns-lookup") async def dns_lookup(domain: str = Query(...), type: str = Query("A")): try: answers = dns.resolver.resolve(domain, type) records = [str(r.to_text()) for r in answers] return { "recordType": type, "records": records } except dns.resolver.NoAnswer: return { "recordType": type, "records": [], "message": "No records found for this type" } except Exception: raise HTTPException( status_code=400, detail="DNS lookup failed" ) # Safe predefined ports (web / mail / ssh etc.) COMMON_PORTS = [ 21, 22, 25, 53, 80, 110, 143, 443, 465, 587, 993, 995, 3306, 3389, 8080, 8443 ] async def scan_port(host: str, port: int): try: conn = asyncio.open_connection(host, port) reader, writer = await asyncio.wait_for(conn, timeout=1) writer.close() return port except: return None @router.get("/port-scan") async def port_scan(host: str = Query(...)): try: tasks = [scan_port(host, p) for p in COMMON_PORTS] results = await asyncio.gather(*tasks) open_ports = [p for p in results if p] if not open_ports: output = "No common open ports detected." else: output = "Open ports:\n" + "\n".join(str(p) for p in open_ports) return { "host": host, "open_ports": open_ports, "scanResult": output } except Exception: raise HTTPException( status_code=400, detail="Unable to scan host" ) @router.get("/ssl-check") async def ssl_check(domain: str = Query(...)): ctx = ssl.create_default_context() try: with ctx.wrap_socket(socket.socket(), server_hostname=domain) as s: s.settimeout(5) s.connect((domain, 443)) cert = s.getpeercert() except Exception: raise HTTPException( status_code=400, detail="Unable to fetch SSL certificate" ) issuer = dict(x[0] for x in cert.get("issuer", [])) subject = dict(x[0] for x in cert.get("subject", [])) return { "domain": domain, "issuer": issuer.get("organizationName", "Unknown"), "subject": subject.get("commonName", "Unknown"), "validFrom": cert.get("notBefore"), "validTo": cert.get("notAfter") } @router.get("/traceroute") async def traceroute(host: str = Query(...)): try: # run traceroute safely result = subprocess.run( ["traceroute", "-m", "20", host], capture_output=True, text=True, timeout=25 ) if result.returncode != 0: raise HTTPException( status_code=400, detail="Traceroute failed" ) return { "traceResult": result.stdout } except subprocess.TimeoutExpired: raise HTTPException( status_code=400, detail="Traceroute timeout" ) @router.get("/whois") async def whois_lookup(domain: str = Query(...)): # basic validation (important) if not re.match(r"^[a-zA-Z0-9\.\-]+$", domain): raise HTTPException(status_code=400, detail="Invalid domain") try: result = subprocess.run( ["whois", domain], capture_output=True, text=True, timeout=20 ) if result.returncode != 0: raise HTTPException(status_code=400, detail="WHOIS lookup failed") return { "whoisRecord": result.stdout } except subprocess.TimeoutExpired: raise HTTPException(status_code=400, detail="WHOIS timeout")