domain_intel.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. #!/usr/bin/env python3
  2. """
  3. Domain Intelligence — Passive OSINT via Python stdlib.
  4. Usage:
  5. python domain_intel.py subdomains example.com
  6. python domain_intel.py ssl example.com
  7. python domain_intel.py whois example.com
  8. python domain_intel.py dns example.com
  9. python domain_intel.py available example.com
  10. python domain_intel.py bulk example.com github.com google.com --checks ssl,dns
  11. All output is structured JSON. No dependencies beyond Python stdlib.
  12. Works on Linux, macOS, and Windows.
  13. """
  14. import json
  15. import re
  16. import socket
  17. import ssl
  18. import sys
  19. import urllib.request
  20. import urllib.parse
  21. from concurrent.futures import ThreadPoolExecutor, as_completed
  22. from datetime import datetime, timezone, UTC
  23. # ─── Subdomain Discovery (crt.sh) ──────────────────────────────────────────
  24. def subdomains(domain, include_expired=False, limit=200):
  25. """Find subdomains via Certificate Transparency logs."""
  26. url = f"https://crt.sh/?q=%25.{urllib.parse.quote(domain)}&output=json"
  27. req = urllib.request.Request(url, headers={
  28. "User-Agent": "domain-intel-skill/1.0", "Accept": "application/json",
  29. })
  30. with urllib.request.urlopen(req, timeout=15) as r:
  31. entries = json.loads(r.read().decode())
  32. seen, results = set(), []
  33. now = datetime.now(UTC)
  34. for e in entries:
  35. not_after = e.get("not_after", "")
  36. if not include_expired and not_after:
  37. try:
  38. dt = datetime.strptime(not_after[:19], "%Y-%m-%dT%H:%M:%S").replace(tzinfo=UTC)
  39. if dt <= now:
  40. continue
  41. except ValueError:
  42. pass
  43. for name in e.get("name_value", "").splitlines():
  44. name = name.strip().lower()
  45. if name and name not in seen:
  46. seen.add(name)
  47. results.append({
  48. "subdomain": name,
  49. "issuer": e.get("issuer_name", ""),
  50. "not_after": not_after,
  51. })
  52. results.sort(key=lambda r: (r["subdomain"].startswith("*"), r["subdomain"]))
  53. return {"domain": domain, "count": min(len(results), limit), "subdomains": results[:limit]}
  54. # ─── SSL Certificate Inspection ────────────────────────────────────────────
  55. def check_ssl(host, port=443, timeout=10):
  56. """Inspect the TLS certificate of a host."""
  57. def flat(rdns):
  58. r = {}
  59. for rdn in rdns:
  60. for item in rdn:
  61. if isinstance(item, (list, tuple)) and len(item) == 2:
  62. r[item[0]] = item[1]
  63. return r
  64. def parse_date(s):
  65. for fmt in ("%b %d %H:%M:%S %Y %Z", "%b %d %H:%M:%S %Y %Z"):
  66. try:
  67. return datetime.strptime(s, fmt).replace(tzinfo=UTC)
  68. except ValueError:
  69. pass
  70. return None
  71. warning = None
  72. try:
  73. ctx = ssl.create_default_context()
  74. with socket.create_connection((host, port), timeout=timeout) as sock:
  75. with ctx.wrap_socket(sock, server_hostname=host) as s:
  76. cert, cipher, proto = s.getpeercert(), s.cipher(), s.version()
  77. except ssl.SSLCertVerificationError as e:
  78. warning = str(e)
  79. ctx = ssl.create_default_context()
  80. ctx.check_hostname = False
  81. ctx.verify_mode = ssl.CERT_NONE
  82. with socket.create_connection((host, port), timeout=timeout) as sock:
  83. with ctx.wrap_socket(sock, server_hostname=host) as s:
  84. cert, cipher, proto = s.getpeercert(), s.cipher(), s.version()
  85. not_after = parse_date(cert.get("notAfter", ""))
  86. now = datetime.now(UTC)
  87. days = (not_after - now).days if not_after else None
  88. is_expired = days is not None and days < 0
  89. if is_expired:
  90. status = f"EXPIRED ({abs(days)} days ago)"
  91. elif days is not None and days <= 14:
  92. status = f"CRITICAL — {days} day(s) left"
  93. elif days is not None and days <= 30:
  94. status = f"WARNING — {days} day(s) left"
  95. else:
  96. status = f"OK — {days} day(s) remaining" if days is not None else "unknown"
  97. return {
  98. "host": host, "port": port,
  99. "subject": flat(cert.get("subject", [])),
  100. "issuer": flat(cert.get("issuer", [])),
  101. "subject_alt_names": [f"{t}:{v}" for t, v in cert.get("subjectAltName", [])],
  102. "not_before": parse_date(cert.get("notBefore", "")).isoformat() if parse_date(cert.get("notBefore", "")) else "",
  103. "not_after": not_after.isoformat() if not_after else "",
  104. "days_remaining": days, "is_expired": is_expired, "expiry_status": status,
  105. "tls_version": proto,
  106. "cipher_suite": cipher[0] if cipher else None,
  107. "serial_number": cert.get("serialNumber", ""),
  108. "verification_warning": warning,
  109. }
  110. # ─── WHOIS Lookup ──────────────────────────────────────────────────────────
  111. WHOIS_SERVERS = {
  112. "com": "whois.verisign-grs.com", "net": "whois.verisign-grs.com",
  113. "org": "whois.pir.org", "io": "whois.nic.io", "co": "whois.nic.co",
  114. "ai": "whois.nic.ai", "dev": "whois.nic.google", "app": "whois.nic.google",
  115. "tech": "whois.nic.tech", "shop": "whois.nic.shop", "store": "whois.nic.store",
  116. "online": "whois.nic.online", "site": "whois.nic.site", "cloud": "whois.nic.cloud",
  117. "digital": "whois.nic.digital", "media": "whois.nic.media", "blog": "whois.nic.blog",
  118. "info": "whois.afilias.net", "biz": "whois.biz", "me": "whois.nic.me",
  119. "tv": "whois.nic.tv", "cc": "whois.nic.cc", "ws": "whois.website.ws",
  120. "uk": "whois.nic.uk", "co.uk": "whois.nic.uk", "de": "whois.denic.de",
  121. "nl": "whois.domain-registry.nl", "fr": "whois.nic.fr", "it": "whois.nic.it",
  122. "es": "whois.nic.es", "pl": "whois.dns.pl", "ru": "whois.tcinet.ru",
  123. "se": "whois.iis.se", "no": "whois.norid.no", "fi": "whois.fi",
  124. "ch": "whois.nic.ch", "at": "whois.nic.at", "be": "whois.dns.be",
  125. "cz": "whois.nic.cz", "br": "whois.registro.br", "ca": "whois.cira.ca",
  126. "mx": "whois.mx", "au": "whois.auda.org.au", "jp": "whois.jprs.jp",
  127. "cn": "whois.cnnic.cn", "in": "whois.inregistry.net", "kr": "whois.kr",
  128. "sg": "whois.sgnic.sg", "hk": "whois.hkirc.hk", "tr": "whois.nic.tr",
  129. "ae": "whois.aeda.net.ae", "za": "whois.registry.net.za",
  130. "space": "whois.nic.space", "zone": "whois.nic.zone", "ninja": "whois.nic.ninja",
  131. "guru": "whois.nic.guru", "rocks": "whois.nic.rocks", "live": "whois.nic.live",
  132. "game": "whois.nic.game", "games": "whois.nic.games",
  133. }
  134. def whois_lookup(domain):
  135. """Query WHOIS servers for domain registration info."""
  136. parts = domain.split(".")
  137. server = WHOIS_SERVERS.get(".".join(parts[-2:])) or WHOIS_SERVERS.get(parts[-1])
  138. if not server:
  139. return {"error": f"No WHOIS server for .{parts[-1]}"}
  140. try:
  141. with socket.create_connection((server, 43), timeout=10) as s:
  142. s.sendall((domain + "\r\n").encode())
  143. chunks = []
  144. while True:
  145. c = s.recv(4096)
  146. if not c:
  147. break
  148. chunks.append(c)
  149. raw = b"".join(chunks).decode("utf-8", errors="replace")
  150. except Exception as e:
  151. return {"error": str(e)}
  152. patterns = {
  153. "registrar": r"(?:Registrar|registrar):\s*(.+)",
  154. "creation_date": r"(?:Creation Date|Created|created):\s*(.+)",
  155. "expiration_date": r"(?:Registry Expiry Date|Expiration Date|Expiry Date):\s*(.+)",
  156. "updated_date": r"(?:Updated Date|Last Modified):\s*(.+)",
  157. "name_servers": r"(?:Name Server|nserver):\s*(.+)",
  158. "status": r"(?:Domain Status|status):\s*(.+)",
  159. "dnssec": r"DNSSEC:\s*(.+)",
  160. }
  161. result = {"domain": domain, "whois_server": server}
  162. for key, pat in patterns.items():
  163. matches = re.findall(pat, raw, re.IGNORECASE)
  164. if matches:
  165. if key in {"name_servers", "status"}:
  166. result[key] = list(dict.fromkeys(m.strip().lower() for m in matches))
  167. else:
  168. result[key] = matches[0].strip()
  169. for field in ("creation_date", "expiration_date", "updated_date"):
  170. if field in result:
  171. for fmt in ("%Y-%m-%dT%H:%M:%S", "%Y-%m-%dT%H:%M:%SZ", "%Y-%m-%d %H:%M:%S", "%Y-%m-%d"):
  172. try:
  173. dt = datetime.strptime(result[field][:19], fmt).replace(tzinfo=UTC)
  174. result[field] = dt.isoformat()
  175. if field == "expiration_date":
  176. days = (dt - datetime.now(UTC)).days
  177. result["expiration_days_remaining"] = days
  178. result["is_expired"] = days < 0
  179. break
  180. except ValueError:
  181. pass
  182. return result
  183. # ─── DNS Records ───────────────────────────────────────────────────────────
  184. def dns_records(domain, types=None):
  185. """Resolve DNS records using system DNS + Google DoH."""
  186. if not types:
  187. types = ["A", "AAAA", "MX", "NS", "TXT", "CNAME"]
  188. records = {}
  189. for qtype in types:
  190. if qtype == "A":
  191. try:
  192. records["A"] = list(dict.fromkeys(
  193. i[4][0] for i in socket.getaddrinfo(domain, None, socket.AF_INET)
  194. ))
  195. except Exception:
  196. records["A"] = []
  197. elif qtype == "AAAA":
  198. try:
  199. records["AAAA"] = list(dict.fromkeys(
  200. i[4][0] for i in socket.getaddrinfo(domain, None, socket.AF_INET6)
  201. ))
  202. except Exception:
  203. records["AAAA"] = []
  204. else:
  205. url = f"https://dns.google/resolve?name={urllib.parse.quote(domain)}&type={qtype}"
  206. try:
  207. req = urllib.request.Request(url, headers={"User-Agent": "domain-intel-skill/1.0"})
  208. with urllib.request.urlopen(req, timeout=10) as r:
  209. data = json.loads(r.read())
  210. records[qtype] = [
  211. a.get("data", "").strip().rstrip(".")
  212. for a in data.get("Answer", []) if a.get("data")
  213. ]
  214. except Exception:
  215. records[qtype] = []
  216. return {"domain": domain, "records": records}
  217. # ─── Domain Availability Check ─────────────────────────────────────────────
  218. def check_available(domain):
  219. """Check domain availability using passive signals (DNS + WHOIS + SSL)."""
  220. signals = {}
  221. # DNS
  222. try:
  223. a = [i[4][0] for i in socket.getaddrinfo(domain, None, socket.AF_INET)]
  224. except Exception:
  225. a = []
  226. try:
  227. ns_url = f"https://dns.google/resolve?name={urllib.parse.quote(domain)}&type=NS"
  228. req = urllib.request.Request(ns_url, headers={"User-Agent": "domain-intel-skill/1.0"})
  229. with urllib.request.urlopen(req, timeout=10) as r:
  230. ns = [x.get("data", "") for x in json.loads(r.read()).get("Answer", [])]
  231. except Exception:
  232. ns = []
  233. signals["dns_a"] = a
  234. signals["dns_ns"] = ns
  235. dns_exists = bool(a or ns)
  236. # SSL
  237. ssl_up = False
  238. try:
  239. ctx = ssl.create_default_context()
  240. ctx.check_hostname = False
  241. ctx.verify_mode = ssl.CERT_NONE
  242. with socket.create_connection((domain, 443), timeout=3) as s:
  243. with ctx.wrap_socket(s, server_hostname=domain):
  244. ssl_up = True
  245. except Exception:
  246. pass
  247. signals["ssl_reachable"] = ssl_up
  248. # WHOIS (quick check)
  249. tld = domain.rsplit(".", 1)[-1]
  250. server = WHOIS_SERVERS.get(tld)
  251. whois_avail = None
  252. whois_note = ""
  253. if server:
  254. try:
  255. with socket.create_connection((server, 43), timeout=10) as s:
  256. s.sendall((domain + "\r\n").encode())
  257. raw = b""
  258. while True:
  259. c = s.recv(4096)
  260. if not c:
  261. break
  262. raw += c
  263. raw = raw.decode("utf-8", errors="replace").lower()
  264. if any(p in raw for p in ["no match", "not found", "no data found", "status: free"]):
  265. whois_avail = True
  266. whois_note = "WHOIS: not found"
  267. elif "registrar:" in raw or "creation date:" in raw:
  268. whois_avail = False
  269. whois_note = "WHOIS: registered"
  270. else:
  271. whois_note = "WHOIS: inconclusive"
  272. except Exception as e:
  273. whois_note = f"WHOIS error: {e}"
  274. signals["whois_available"] = whois_avail
  275. signals["whois_note"] = whois_note
  276. if not dns_exists and whois_avail is True:
  277. verdict, conf = "LIKELY AVAILABLE", "high"
  278. elif dns_exists or whois_avail is False or ssl_up:
  279. verdict, conf = "REGISTERED / IN USE", "high"
  280. elif not dns_exists and whois_avail is None:
  281. verdict, conf = "POSSIBLY AVAILABLE", "medium"
  282. else:
  283. verdict, conf = "UNCERTAIN", "low"
  284. return {"domain": domain, "verdict": verdict, "confidence": conf, "signals": signals}
  285. # ─── Bulk Analysis ─────────────────────────────────────────────────────────
  286. COMMAND_MAP = {
  287. "subdomains": subdomains,
  288. "ssl": check_ssl,
  289. "whois": whois_lookup,
  290. "dns": dns_records,
  291. "available": check_available,
  292. }
  293. def bulk_check(domains, checks=None, max_workers=5):
  294. """Run multiple checks across multiple domains in parallel."""
  295. if not checks:
  296. checks = ["ssl", "whois", "dns"]
  297. def run_one(d):
  298. entry = {"domain": d}
  299. for check in checks:
  300. fn = COMMAND_MAP.get(check)
  301. if fn:
  302. try:
  303. entry[check] = fn(d)
  304. except Exception as e:
  305. entry[check] = {"error": str(e)}
  306. return entry
  307. results = []
  308. with ThreadPoolExecutor(max_workers=min(max_workers, 10)) as ex:
  309. futures = {ex.submit(run_one, d): d for d in domains[:20]}
  310. for f in as_completed(futures):
  311. results.append(f.result())
  312. return {"total": len(results), "checks": checks, "results": results}
  313. # ─── CLI Entry Point ───────────────────────────────────────────────────────
  314. def main():
  315. if len(sys.argv) < 3:
  316. print(__doc__)
  317. sys.exit(1)
  318. command = sys.argv[1].lower()
  319. args = sys.argv[2:]
  320. if command == "bulk":
  321. # Parse --checks flag
  322. checks = None
  323. domains = []
  324. i = 0
  325. while i < len(args):
  326. if args[i] == "--checks" and i + 1 < len(args):
  327. checks = [c.strip() for c in args[i + 1].split(",")]
  328. i += 2
  329. else:
  330. domains.append(args[i])
  331. i += 1
  332. result = bulk_check(domains, checks)
  333. elif command in COMMAND_MAP:
  334. result = COMMAND_MAP[command](args[0])
  335. else:
  336. print(f"Unknown command: {command}")
  337. print(f"Available: {', '.join(COMMAND_MAP.keys())}, bulk")
  338. sys.exit(1)
  339. print(json.dumps(result, indent=2))
  340. if __name__ == "__main__":
  341. main()