Spaces:
Runtime error
Runtime error
Download deep_scan.py from asdfnikah/scanner-bot: direct link, hf CLI and curl.
- Browser
- Download file 20.2 kB
-
https://huggingface.co/spaces/asdfnikah/scanner-bot/resolve/main/deep_scan.py
- Command line
-
hf download hf://spaces/asdfnikah/scanner-bot/deep_scan.py
-
curl -L -o deep_scan.py https://huggingface.co/spaces/asdfnikah/scanner-bot/resolve/main/deep_scan.py
20.2 kB
| """Deep non-destructive security assessment scanner. | |
| All checks are READ-ONLY: GET/HEAD/OPTIONS requests, DNS/TLS queries and | |
| public content analysis. No payloads, no writes, no brute force. | |
| Usage: | |
| python deep_scan.py --url https://target.com [--threads 8] [--report out.json] | |
| Output: console summary + optional JSON report. | |
| """ | |
| import argparse | |
| import concurrent.futures | |
| import json | |
| import re | |
| import socket | |
| import ssl | |
| import sys | |
| import time | |
| from dataclasses import dataclass, field | |
| from datetime import datetime | |
| from urllib.parse import urljoin, urlparse | |
| import requests | |
| UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36" | |
| TIMEOUT = 12 | |
| class Finding: | |
| severity: str # CRITICAL / HIGH / MEDIUM / LOW / INFO | |
| check: str | |
| detail: str | |
| class Report: | |
| target: str | |
| started: str | |
| findings: list = field(default_factory=list) | |
| notes: list = field(default_factory=list) | |
| def add(self, sev, check, detail): | |
| self.findings.append(Finding(sev, check, detail)) | |
| print(f"[{sev:8s}] {check}: {detail}") | |
| def info(self, check, detail): | |
| self.notes.append(f"{check}: {detail}") | |
| def http_session(): | |
| s = requests.Session() | |
| s.headers.update({"User-Agent": UA, "Accept": "*/*"}) | |
| s.verify = True | |
| return s | |
| # ---------------------------------------------------------------- modules | |
| def check_headers(sess, base, rep): | |
| r = sess.get(base, timeout=TIMEOUT) | |
| h = r.headers | |
| sev = lambda name: "MEDIUM" if name not in h else None | |
| for name, sev_ in { | |
| "Content-Security-Policy": "MEDIUM", | |
| "Strict-Transport-Security": "HIGH", | |
| "X-Frame-Options": "MEDIUM", | |
| "X-Content-Type-Options": "MEDIUM", | |
| "Referrer-Policy": "LOW", | |
| "Permissions-Policy": "LOW", | |
| }.items(): | |
| if name not in h: | |
| rep.add(sev_, "Missing header", name) | |
| if "Strict-Transport-Security" in h and "preload" not in h["Strict-Transport-Security"]: | |
| rep.info("HSTS", "present but not preload-ready") | |
| if h.get("Server"): | |
| rep.info("Server banner", h["Server"]) | |
| if h.get("X-Powered-By"): | |
| if re.search(r"PHP/[0-9.]+", h["X-Powered-By"]): | |
| ver = re.search(r"PHP/([0-9.]+)", h["X-Powered-By"]).group(1) | |
| major = tuple(int(x) for x in ver.split(".")[:2]) | |
| if major <= (8, 0): | |
| rep.add("HIGH", "EOL PHP version", f"X-Powered-By: PHP/{ver} (end-of-life, no security patches)") | |
| else: | |
| rep.info("PHP version", ver) | |
| for k in ("X-TWO-VERSION", "X-Generator", "X-Drupal-Cache", "X-AspNet-Version"): | |
| if k in h: | |
| rep.info("Tech banner", f"{k}: {h[k]}") | |
| return r | |
| def check_cookies(sess, urls, rep): | |
| seen = set() | |
| for u in urls: | |
| try: | |
| r = sess.get(u, timeout=TIMEOUT) | |
| for c in r.cookies: | |
| key = (c.name, c.domain, c.path) | |
| if key in seen: | |
| continue | |
| seen.add(key) | |
| flags = [] | |
| if not c.secure: | |
| flags.append("missing Secure") | |
| if not c.has_nonstandard_attr("HttpOnly") and not c._rest.get("HttpOnly"): | |
| flags.append("missing HttpOnly") | |
| if not c.has_nonstandard_attr("SameSite") and not c._rest.get("SameSite"): | |
| flags.append("missing SameSite") | |
| if flags: | |
| rep.add("MEDIUM", "Weak cookie flags", f"{c.name} on {u}: {', '.join(flags)}") | |
| else: | |
| rep.info("Cookie", f"{c.name} flags OK") | |
| except Exception: | |
| pass | |
| def check_methods(sess, base, rep): | |
| for m in ("OPTIONS", "TRACE", "PUT", "DELETE"): | |
| try: | |
| r = sess.request(m, base, timeout=TIMEOUT) | |
| allow = r.headers.get("Allow", "") | |
| if m == "TRACE" and r.status_code == 200 and "TRACE" in allow: | |
| rep.add("HIGH", "TRACE enabled", "HTTP TRACE reflected (XST risk)") | |
| elif m == "TRACE": | |
| rep.info("Method", "TRACE blocked") | |
| if m in ("PUT", "DELETE") and r.status_code not in (405, 403, 404, 501): | |
| rep.add("HIGH", "Dangerous method", f"{m} returned {r.status_code}") | |
| except Exception: | |
| pass | |
| def check_tls(host, rep): | |
| ctx = ssl.create_default_context() | |
| try: | |
| with ctx.wrap_socket(socket.socket(), server_hostname=host) as s: | |
| s.settimeout(TIMEOUT) | |
| s.connect((host, 443)) | |
| cert = s.getpeercert() | |
| rep.info("TLS cert", f"issuer={cert.get('issuer')} expires={cert.get('notAfter')}") | |
| san = [] | |
| for ext in cert.get("subjectAltName", []): | |
| san.append(ext[1]) | |
| rep.info("TLS SANs", ", ".join(sorted(san))) | |
| except Exception as e: | |
| rep.add("HIGH", "TLS", f"handshake failed: {e}") | |
| for proto in ("TLSv1.0", "TLSv1.1", "TLSv1.2", "TLSv1.3"): | |
| try: | |
| ctx2 = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) | |
| ctx2.check_hostname = False | |
| ctx2.verify_mode = ssl.CERT_NONE | |
| if proto == "TLSv1.0": | |
| ctx2.minimum_version, ctx2.maximum_version = ssl.TLSVersion.TLSv1, ssl.TLSVersion.TLSv1 | |
| elif proto == "TLSv1.1": | |
| ctx2.minimum_version, ctx2.maximum_version = ssl.TLSVersion.TLSv1_1, ssl.TLSVersion.TLSv1_1 | |
| elif proto == "TLSv1.2": | |
| ctx2.minimum_version, ctx2.maximum_version = ssl.TLSVersion.TLSv1_2, ssl.TLSVersion.TLSv1_2 | |
| else: | |
| ctx2.minimum_version, ctx2.maximum_version = ssl.TLSVersion.TLSv1_3, ssl.TLSVersion.TLSv1_3 | |
| with ctx2.wrap_socket(socket.socket(), server_hostname=host) as s2: | |
| s2.settimeout(8) | |
| s2.connect((host, 443)) | |
| if proto in ("TLSv1.0", "TLSv1.1"): | |
| rep.add("HIGH", "Legacy TLS", f"{proto} accepted") | |
| else: | |
| rep.info("TLS protocol", f"{proto} supported") | |
| except Exception: | |
| if proto in ("TLSv1.2", "TLSv1.3"): | |
| rep.info("TLS protocol", f"{proto} not supported") | |
| def check_dns(host, rep): | |
| try: | |
| import dns.resolver # optional | |
| have_dns = True | |
| except ImportError: | |
| have_dns = False | |
| if not have_dns: | |
| return | |
| for qtype in ("A", "AAAA", "MX", "NS", "TXT", "CNAME"): | |
| try: | |
| ans = dns.resolver.resolve(host, qtype, lifetime=5) | |
| vals = [str(x) for x in ans] | |
| rep.info(f"DNS {qtype}", ", ".join(vals)) | |
| if qtype == "TXT": | |
| for v in vals: | |
| if "spf1" in v: | |
| ips = re.findall(r"ip4:([0-9.]+)", v) | |
| if ips: | |
| rep.add("MEDIUM", "SPF leaks origin IPs", f"{host}: {', '.join(ips)}") | |
| except Exception: | |
| pass | |
| def check_subdomains(host, rep): | |
| try: | |
| r = requests.get(f"https://crt.sh/?q=%25.{host}&output=json", timeout=30, | |
| headers={"User-Agent": UA}) | |
| data = r.json() | |
| names = set() | |
| for e in data: | |
| for n in e.get("name_value", "").split("\n"): | |
| names.add(n.strip().lower()) | |
| names.discard(host) | |
| rep.info("Subdomains (crt.sh)", ", ".join(sorted(names))) | |
| return sorted(names) | |
| except Exception as e: | |
| rep.info("Subdomain enum", f"crt.sh failed: {e}") | |
| return [] | |
| def check_takeover(host, names, rep): | |
| try: | |
| import dns.resolver | |
| except ImportError: | |
| return | |
| for name in list(names)[:40]: | |
| try: | |
| ans = dns.resolver.resolve(f"_dns.cname.{name}" if False else name, "CNAME", lifetime=4) | |
| for a in ans: | |
| target = str(a.target).rstrip(".") | |
| if target.lower().endswith(("github.io", "herokudns.com", "herokuapp.com", | |
| "cloudfront.net", "s3.amazonaws.com", "pantheonsite.io", | |
| "wordpress.com", "netlify.app", "surge.sh", "ghost.io", | |
| "fly.dev", "zeit.co", "vercel.app", "azurewebsites.net")): | |
| rep.add("HIGH", "Subdomain takeover candidate", f"{name} -> {target}") | |
| except Exception: | |
| pass | |
| PATHS = [ | |
| # exposed files | |
| "/.git/HEAD", "/.git/config", "/.env", "/.env.bak", "/.env.old", "/.svn/entries", | |
| "/.DS_Store", "/.htaccess", "/.htpasswd", "/.bash_history", | |
| # wordpress | |
| "/wp-config.php", "/wp-config.php.bak", "/wp-config.php~", "/wp-config.php.save", | |
| "/wp-config.old", "/wp-content/debug.log", "/wp-includes/version.php", "/wp-cron.php", | |
| "/wp-login.php", "/wp-admin/", "/wp-json/", "/xmlrpc.php", "/readme.html", | |
| "/license.txt", "/wp-content/uploads/", "/wp-content/plugins/", "/wp-content/themes/", | |
| "/wp-sitemap.xml", "/sitemap.xml", "/sitemap_index.xml", | |
| # backups / databases | |
| "/backup.zip", "/backup.tar.gz", "/backup.sql", "/db.sql", "/database.sql", | |
| "/dump.sql", "/site.zip", "/www.zip", "/old.zip", "/backup/", "/db_backup.sql", | |
| "/mysql.sql", "/db.sql.gz", | |
| # common apps | |
| "/phpmyadmin/", "/pma/", "/myadmin/", "/adminer.php", "/cpanel", "/webmail", | |
| "/server-status", "/server-info", "/cgi-bin/", "/.well-known/security.txt", | |
| "/phpinfo.php", "/info.php", "/test.php", "/administrator/", "/admin/", | |
| # custom app (newipnow-specific, generic enough) | |
| "/api/", "/api/track", "/health", "/status", "/common.js", | |
| "/order/", "/order/order-completed.php", "/members/", "/members/member-login", | |
| "/public/", "/info.php", "/robots.txt", | |
| ] | |
| WHMCS_PATHS = [ | |
| "/billing/", "/billing/admin/", "/billing/includes/", "/billing/configuration.php", | |
| "/billing/vendor/", "/billing/downloads/", "/billing/attachments/", "/billing/install/", | |
| "/billing/crons/", "/billing/templates_c/", "/billing/register.php", | |
| "/billing/clientarea.php", "/billing/pwreset.php", | |
| ] | |
| def check_paths(sess, base, paths, rep, label): | |
| found = [] | |
| def probe(p): | |
| try: | |
| r = sess.get(urljoin(base, p), timeout=TIMEOUT, allow_redirects=False, | |
| headers={"Range": "bytes=0-100"}) | |
| return p, r.status_code, r.headers.get("Content-Type", "") | |
| except Exception: | |
| return p, 0, "" | |
| with concurrent.futures.ThreadPoolExecutor(max_workers=8) as ex: | |
| for p, code, ct in ex.map(probe, paths): | |
| interesting = code in (200, 301, 302) and not (code == 302 and ct == "") | |
| if code in (200, 403) and ct: | |
| found.append((p, code, ct)) | |
| elif code in (301, 302): | |
| found.append((p, code, ct)) | |
| for p, code, ct in found: | |
| if code in (200, 301, 302) and any(x in p for x in (".git", ".env", ".sql", ".bak", | |
| ".zip", "debug.log", ".htaccess", | |
| ".htpasswd", ".svn", "config", | |
| "phpinfo", "adminer", "info.php", | |
| "version.php", "install")): | |
| sev = "HIGH" if code == 200 else "MEDIUM" | |
| rep.add(sev, f"{label} exposure", f"{p} -> HTTP {code} [{ct}]") | |
| elif code == 403: | |
| rep.add("INFO", f"{label} exists (403)", f"{p}") | |
| else: | |
| rep.add("INFO", f"{label}", f"{p} -> HTTP {code}") | |
| return [p for p, _, _ in found] | |
| def check_cors(sess, base, rep): | |
| for path in ("/", "/wp-login.php", "/billing/clientarea.php", "/members/member-login", "/api/track"): | |
| try: | |
| r = sess.get(urljoin(base, path), timeout=TIMEOUT, | |
| headers={"Origin": "https://evil.example"}) | |
| acao = r.headers.get("Access-Control-Allow-Origin") | |
| if acao and "evil.example" in acao: | |
| rep.add("HIGH", "CORS misconfiguration", f"{path}: reflects arbitrary Origin ({acao})") | |
| elif acao: | |
| rep.info("CORS", f"{path}: ACAO={acao}") | |
| except Exception: | |
| pass | |
| def check_open_redirect(sess, base, rep): | |
| params = ["url", "next", "redirect", "return", "returnUrl", "returnto", "r", "dest", | |
| "destination", "redirect_url", "redirect_uri", "goto", "target", "link"] | |
| parsed = urlparse(base) | |
| candidates = [] | |
| r = sess.get(base, timeout=TIMEOUT) | |
| for m in re.findall(r'(?:href|action)="([^"]+)"', r.text)[:80]: | |
| q = urlparse(urljoin(base, m)) | |
| if q.query: | |
| for k, v in re.findall(r"([\w.]+)=([^&\"']*)", q.query): | |
| if k in params: | |
| candidates.append(urljoin(base, m)) | |
| for c in list(set(candidates))[:15]: | |
| try: | |
| target = c + ("&" if "?" in c else "?") + "next=https://evil.example/" | |
| rr = sess.get(target, timeout=TIMEOUT, allow_redirects=True) | |
| if "evil.example" in rr.url: | |
| rep.add("HIGH", "Open redirect", f"{c} redirects to attacker-controlled URL") | |
| except Exception: | |
| pass | |
| def check_clickjacking(sess, base, rep): | |
| for path in ("/", "/wp-login.php", "/billing/clientarea.php", "/members/member-login"): | |
| try: | |
| r = sess.get(urljoin(base, path), timeout=TIMEOUT) | |
| xfo = r.headers.get("X-Frame-Options") | |
| csp = r.headers.get("Content-Security-Policy", "") | |
| if xfo: | |
| rep.info("Clickjacking", f"{path}: XFO={xfo}") | |
| elif "frame-ancestors" in csp: | |
| rep.info("Clickjacking", f"{path}: protected via CSP frame-ancestors") | |
| else: | |
| rep.add("MEDIUM", "Clickjacking", f"{path}: no X-Frame-Options / frame-ancestors") | |
| except Exception: | |
| pass | |
| def check_directory_listing(sess, base, rep): | |
| for path in ("/wp-content/uploads/", "/billing/downloads/", "/billing/attachments/", | |
| "/public/", "/wp-content/plugins/", "/wp-content/themes/", "/backup/"): | |
| try: | |
| r = sess.get(urljoin(base, path), timeout=TIMEOUT) | |
| if re.search(r"<title>Index of|Parent Directory|\[DIR\]", r.text, re.I): | |
| rep.add("MEDIUM", "Directory listing", f"{path} is browsable") | |
| except Exception: | |
| pass | |
| def check_error_disclosure(sess, base, rep): | |
| for path in ("/nonexistent-xyz123", "/%00", "/index.php%00.png", "/?.html", "/billing/nonexistent.php"): | |
| try: | |
| r = sess.get(urljoin(base, path), timeout=TIMEOUT) | |
| for pat, name in [(r"Stack trace:", "stack trace"), (r"Fatal error", "PHP fatal"), | |
| (r"Warning:", "PHP warning"), (r"SQLSTATE", "SQL error"), | |
| (r"mysql|mysqli", "MySQL"), (r"\.php on line \d+", "file:line disclosure"), | |
| (r"include_path|open_basedir", "path disclosure")]: | |
| if re.search(pat, r.text, re.I): | |
| rep.add("MEDIUM", "Error disclosure", f"{path} leaks: {name}") | |
| break | |
| except Exception: | |
| pass | |
| def check_tech_fingerprint(sess, base, rep): | |
| r = sess.get(base, timeout=TIMEOUT) | |
| meta = re.findall(r'<meta name="generator" content="([^"]+)"', r.text) | |
| for m in meta: | |
| rep.info("Generator meta", m) | |
| scripts = re.findall(r'src="([^"]+)"', r.text) | |
| for s in set(scripts): | |
| if "/plugins/" in s: | |
| m = re.search(r"/wp-content/plugins/([^/]+)", s) | |
| if m: | |
| rep.info("Plugin", m.group(1)) | |
| for word, tech in [("wp-content", "WordPress"), ("whmcs", "WHMCS"), | |
| ("/billing/", "WHMCS"), ("Divi", "Divi theme"), | |
| ("cloudflare", "Cloudflare")]: | |
| if word.lower() in r.text.lower(): | |
| rep.info("Technology", tech) | |
| # extract interesting strings: keys / endpoints / emails | |
| emails = set(re.findall(r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}", r.text)) | |
| for e in emails: | |
| if not e.lower().endswith((".png", ".jpg", ".webp", ".gif", ".svg", ".js", ".css")): | |
| rep.add("LOW", "Email disclosure", e) | |
| def check_forms(sess, base, rep): | |
| r = sess.get(base, timeout=TIMEOUT) | |
| for fm in re.finditer(r"<form[^>]*>", r.text): | |
| tag = fm.group(0) | |
| action = re.search(r'action="([^"]*)"', tag) | |
| method = re.search(r'method="([^"]*)"', tag, re.I) | |
| a = action.group(1) if action else "(same page)" | |
| m = (method.group(1).upper() if method else "GET") | |
| if m == "GET": | |
| rep.add("LOW", "Form uses GET", f"action={a} (sensitive data may leak to logs/referrer)") | |
| else: | |
| rep.info("Form", f"action={a} method={m}") | |
| def check_rate_limit(sess, base, rep): | |
| r = sess.get(base, timeout=TIMEOUT) | |
| if "cf-ray" in r.headers or "cf-cache" in r.headers: | |
| rep.info("WAF/CDN", "Cloudflare detected") | |
| return r | |
| def check_http_https(base, rep): | |
| p = urlparse(base) | |
| try: | |
| r = requests.get(f"http://{p.netloc}/", timeout=TIMEOUT, allow_redirects=False, | |
| headers={"User-Agent": UA}) | |
| if r.status_code in (301, 302, 308) and "https" in r.headers.get("Location", ""): | |
| rep.info("HTTP->HTTPS", "redirects correctly") | |
| elif r.status_code == 200: | |
| rep.add("MEDIUM", "Plain HTTP", "serves content over HTTP without redirect") | |
| except Exception: | |
| rep.info("HTTP->HTTPS", "no plain HTTP response") | |
| def check_hsts_preload(host, rep): | |
| try: | |
| import dns.resolver | |
| ans = dns.resolver.resolve(f"_https.{host}.preload.lst.hsts.preload.org" if False else host, "TXT", lifetime=4) | |
| rep.info("HSTS preload", "listed" if ans else "not listed") | |
| except Exception: | |
| rep.info("HSTS preload", "not listed") | |
| def scan(base, rep, threads=8): | |
| parsed = urlparse(base) | |
| host = parsed.netloc | |
| sess = http_session() | |
| rep.info("Target", f"{base} (host={host})") | |
| check_http_https(base, rep) | |
| check_dns(host, rep) | |
| subs = check_subdomains(host, rep) | |
| check_takeover(host, subs, rep) | |
| check_tls(host, rep) | |
| check_hsts_preload(host, rep) | |
| r = check_headers(sess, base, rep) | |
| check_cookies(sess, [base, urljoin(base, "/wp-login.php"), | |
| urljoin(base, "/billing/clientarea.php"), | |
| urljoin(base, "/members/member-login")], rep) | |
| check_methods(sess, base, rep) | |
| check_cors(sess, base, rep) | |
| check_open_redirect(sess, base, rep) | |
| check_clickjacking(sess, base, rep) | |
| check_directory_listing(sess, base, rep) | |
| check_error_disclosure(sess, base, rep) | |
| check_forms(sess, base, rep) | |
| check_tech_fingerprint(sess, base, rep) | |
| check_rate_limit(sess, base, rep) | |
| check_paths(sess, base, PATHS, rep, "Path") | |
| check_paths(sess, base, WHMCS_PATHS, rep, "WHMCS") | |
| return rep | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--url", required=True) | |
| ap.add_argument("--threads", type=int, default=8) | |
| ap.add_argument("--report", default="") | |
| args = ap.parse_args() | |
| base = args.url if args.url.startswith("http") else "https://" + args.url | |
| rep = Report(target=base, started=datetime.utcnow().isoformat()) | |
| print(f"=== Deep non-destructive scan: {base} ===\n") | |
| t0 = time.time() | |
| scan(base, rep, args.threads) | |
| print(f"\n=== Done in {time.time()-t0:.1f}s: {len(rep.findings)} findings ===") | |
| counts = {} | |
| for f in rep.findings: | |
| counts[f.severity] = counts.get(f.severity, 0) + 1 | |
| print("Severity breakdown:", counts) | |
| if args.report: | |
| with open(args.report, "w", encoding="utf-8") as f: | |
| json.dump({ | |
| "target": rep.target, | |
| "started": rep.started, | |
| "notes": rep.notes, | |
| "findings": [{"severity": x.severity, "check": x.check, | |
| "detail": x.detail} for x in rep.findings], | |
| }, f, indent=2) | |
| print(f"Report saved: {args.report}") | |
| if __name__ == "__main__": | |
| main() | |