|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 |
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ WordPress OSINT Inspector Auditoría pasiva de tecnologías WordPress mediante peticiones HTTP GET. No realiza autenticación, POST, explotación ni modificación del servidor. """ import json import re import threading import queue import time from datetime import datetime from urllib.parse import urljoin, urlparse, parse_qs from html.parser import HTMLParser import tkinter as tk from tkinter import ttk, messagebox, filedialog try: import requests except ImportError: raise SystemExit("Falta requests. Instala las dependencias con: python3 -m pip install -r requirements.txt") APP_TITLE = "WordPress OSINT Inspector" USER_AGENT = "WordPressOSINTInspector/1.0 (+passive security assessment)" TIMEOUT = 12 KNOWN_PLUGINS = { "wp-rocket": "WP Rocket", "wordfence": "Wordfence", "wordfence-login-security": "Wordfence Login Security", "sg-security": "SiteGround Security", "wordpress-seo": "Yoast SEO", "wpforms": "WPForms", "generateblocks": "GenerateBlocks", "generateblocks-pro": "GenerateBlocks Pro", "generatepress-pro": "GeneratePress Premium", "advanced-database-cleaner": "Advanced Database Cleaner", "all-in-one-wp-security": "All In One WP Security", "really-simple-ssl": "Really Simple Security", "elementor": "Elementor", "contact-form-7": "Contact Form 7", "woocommerce": "WooCommerce", "akismet": "Akismet", "jetpack": "Jetpack", "updraftplus": "UpdraftPlus", "ithemes-security": "Solid Security", } KNOWN_THEMES = { "generatepress": "GeneratePress", "astra": "Astra", "hello-elementor": "Hello Elementor", "oceanwp": "OceanWP", "kadence": "Kadence", "blocksy": "Blocksy", "divi": "Divi", "flatsome": "Flatsome", "avada": "Avada", } class AssetParser(HTMLParser): def __init__(self): super().__init__() self.assets = [] self.generators = [] self.links = [] def handle_starttag(self, tag, attrs): a = dict(attrs) if tag.lower() == "meta" and a.get("name", "").lower() == "generator": if a.get("content"): self.generators.append(a["content"]) for key in ("src", "href"): value = a.get(key) if value and any(x in value.lower() for x in ( "wp-content", "wp-includes", "wp-admin" )): self.assets.append(value) if tag.lower() == "link" and a.get("rel", "").lower() in ("https://api.w.org/", "api.w.org/"): if a.get("href"): self.links.append(a["href"]) def normalize_domain(value): value = value.strip() if not value: raise ValueError("Introduce un dominio.") if not re.match(r"^https?://", value, re.I): value = "https://" + value parsed = urlparse(value) if not parsed.hostname: raise ValueError("Dominio no válido.") if parsed.scheme not in ("http", "https"): raise ValueError("Solo se admiten HTTP y HTTPS.") return f"{parsed.scheme}://{parsed.netloc}" def safe_get(session, url): try: response = session.get(url, timeout=TIMEOUT, allow_redirects=True) return response except requests.RequestException as exc: return {"error": str(exc)} def version_from_text(text): patterns = [ r"(?im)^\s*Version\s+([0-9]+(?:\.[0-9]+){1,3})", r"(?i)wordpress\s+([0-9]+(?:\.[0-9]+){1,3})", ] for pattern in patterns: match = re.search(pattern, text or "") if match: return match.group(1) return None def unique_append(items, value): if value and value not in items: items.append(value) def inspect_domain(domain, log_callback=None): base_url = normalize_domain(domain) session = requests.Session() session.headers.update({"User-Agent": USER_AGENT, "Accept": "*/*"}) result = { "target": base_url, "scanned_at": datetime.now().astimezone().isoformat(timespec="seconds"), "scope": "Comprobaciones pasivas HTTP GET; sin autenticación ni explotación.", "wordpress": {"detected": False, "version": None, "version_evidence": []}, "http": {}, "generators": [], "plugins": [], "themes": [], "asset_versions": [], "rest_api": {"available": False, "namespaces": [], "name": None, "description": None}, "checks": [], "findings": [], "errors": [], } def log(msg): if log_callback: log_callback(msg) def check(path, label): url = urljoin(base_url + "/", path.lstrip("/")) log(f"GET {url}") resp = safe_get(session, url) if isinstance(resp, dict): result["errors"].append({"url": url, "error": resp["error"]}) item = {"name": label, "url": url, "status": None, "error": resp["error"]} else: item = { "name": label, "url": url, "status": resp.status_code, "content_type": resp.headers.get("Content-Type", ""), "final_url": resp.url, "bytes": len(resp.content), } result["checks"].append(item) return resp # Página principal home = safe_get(session, base_url) if isinstance(home, dict): result["errors"].append({"url": base_url, "error": home["error"]}) raise RuntimeError(f"No se pudo conectar: {home['error']}") result["http"] = { "status": home.status_code, "final_url": home.url, "server": home.headers.get("Server"), "x_powered_by": home.headers.get("X-Powered-By"), "content_type": home.headers.get("Content-Type"), "headers": { k: home.headers.get(k) for k in ( "Server", "X-Powered-By", "X-Frame-Options", "X-Content-Type-Options", "Referrer-Policy", "Content-Security-Policy", "Strict-Transport-Security", "Permissions-Policy" ) if home.headers.get(k) } } html = home.text[:5_000_000] parser = AssetParser() try: parser.feed(html) except Exception: pass # Indicadores de WordPress indicators = [ "wp-content", "wp-includes", "wp-json", "wp-emoji-release", "wordpress" ] found_indicators = [x for x in indicators if x in html.lower()] if found_indicators or "/wp-json/" in home.url: result["wordpress"]["detected"] = True result["wordpress"]["indicators"] = found_indicators for generator in parser.generators: unique_append(result["generators"], generator) match = re.search(r"wordpress\s+([0-9.]+)", generator, re.I) if match: result["wordpress"]["version"] = match.group(1) result["wordpress"]["version_evidence"].append( {"source": "meta generator", "value": match.group(1), "confidence": "alta"} ) # API REST pública api = check("/wp-json/", "API REST de WordPress") if not isinstance(api, dict) and api.status_code == 200: try: data = api.json() if isinstance(data, dict) and ("namespaces" in data or "routes" in data): result["wordpress"]["detected"] = True result["rest_api"]["available"] = True result["rest_api"]["namespaces"] = data.get("namespaces", []) result["rest_api"]["name"] = data.get("name") result["rest_api"]["description"] = data.get("description") for ns in result["rest_api"]["namespaces"]: low = ns.lower() for slug, friendly in KNOWN_PLUGINS.items(): if slug in low: unique_append(result["plugins"], friendly) if "generatepress" in low: unique_append(result["themes"], "GeneratePress") if "generateblocks" in low: unique_append(result["plugins"], "GenerateBlocks") except (ValueError, requests.RequestException): pass # Readme: a veces contiene versión exacta, pero puede estar retirado o modificado readme = check("/readme.html", "readme.html") if not isinstance(readme, dict) and readme.status_code == 200: v = version_from_text(readme.text) if v: result["wordpress"]["version"] = result["wordpress"]["version"] or v result["wordpress"]["version_evidence"].append( {"source": "readme.html", "value": v, "confidence": "media; comprobar que no sea un archivo antiguo"} ) # License: solo disponibilidad, normalmente no revela versión check("/license.txt", "license.txt") # Feed y XML-RPC: comprobación GET no destructiva feed = check("/feed/", "Feed RSS") if not isinstance(feed, dict) and feed.status_code == 200: gen = re.search(r"<generator>(.*?)</generator>", feed.text, re.I | re.S) if gen: value = re.sub(r"<[^>]+>", "", gen.group(1)).strip() unique_append(result["generators"], value) v = version_from_text(value) if v: result["wordpress"]["version"] = result["wordpress"]["version"] or v result["wordpress"]["version_evidence"].append( {"source": "feed generator", "value": v, "confidence": "media"} ) xmlrpc = check("/xmlrpc.php", "XML-RPC (GET)") if not isinstance(xmlrpc, dict): result["checks"][-1]["interpretation"] = ( "Respuesta observada a GET; no confirma que los métodos XML-RPC estén habilitados." ) check("/wp-login.php", "Página de acceso habitual") check("/wp-admin/", "Ruta wp-admin") check("/wp-cron.php", "wp-cron.php (GET)") # Detección de rutas de assets y versiones all_assets = list(parser.assets) # Buscar rutas referenciadas en HTML, también con comillas simples for match in re.findall(r"""(?:src|href)\s*=\s*['"]([^'"]+)['"]""", html, re.I): if any(x in match.lower() for x in ("wp-content", "wp-includes", "wp-admin")): unique_append(all_assets, match) plugin_slugs = set() theme_slugs = set() version_map = {} for asset in all_assets: absolute = urljoin(base_url + "/", asset) parsed = urlparse(absolute) path = parsed.path low = path.lower() m = re.search(r"/wp-content/plugins/([^/]+)", low) if m: slug = m.group(1) plugin_slugs.add(slug) m = re.search(r"/wp-content/themes/([^/]+)", low) if m: theme_slugs.add(m.group(1)) q = parse_qs(parsed.query) for ver in q.get("ver", []): if re.fullmatch(r"[0-9]+(?:\.[0-9]+){0,3}", ver): key = f"{path}?ver={ver}" unique_append(result["asset_versions"], key) if "/wp-includes/" in low: version_map.setdefault(ver, []).append(path) for slug in sorted(plugin_slugs): friendly = KNOWN_PLUGINS.get(slug, slug.replace("-", " ").title()) unique_append(result["plugins"], friendly) for slug in sorted(theme_slugs): friendly = KNOWN_THEMES.get(slug, slug.replace("-", " ").title()) unique_append(result["themes"], friendly) # Versiones de recursos del núcleo: indicios, no prueba concluyente for ver, paths in sorted(version_map.items()): if ver == "0": continue if ver not in ("3.7.1",): # evitar confundir jQuery con WordPress result["wordpress"]["version_evidence"].append({ "source": "parámetro ver de recurso wp-includes", "value": ver, "paths": paths[:5], "confidence": "baja; puede ser versión de recurso o caché" }) if result["wordpress"]["detected"]: result["findings"].append({ "severity": "info", "title": "WordPress identificado", "detail": "Se han encontrado indicadores compatibles con WordPress." }) if result["rest_api"]["available"]: result["findings"].append({ "severity": "info", "title": "API REST accesible públicamente", "detail": f"Se han publicado {len(result['rest_api']['namespaces'])} espacios de nombres. Esto no implica por sí solo una vulnerabilidad." }) if result["plugins"]: result["findings"].append({ "severity": "info", "title": "Plugins identificables", "detail": "Se han reconocido componentes a partir de rutas o namespaces: " + ", ".join(result["plugins"]) }) if result["themes"]: result["findings"].append({ "severity": "info", "title": "Temas identificables", "detail": "Se han reconocido temas a partir de rutas o namespaces: " + ", ".join(result["themes"]) }) if not result["wordpress"]["version"]: result["findings"].append({ "severity": "warning", "title": "Versión exacta no identificada", "detail": "No se ha encontrado una evidencia pública suficientemente fiable. Los parámetros ver= pueden pertenecer a jQuery, plugins, temas o recursos cacheados." }) else: result["findings"].append({ "severity": "info", "title": "Posible versión de WordPress", "detail": f"Versión candidata: {result['wordpress']['version']}. Revisa la evidencia y su nivel de confianza." }) # Cabeceras defensivas: informar de ausencia sin afirmar vulnerabilidad security_headers = { "Strict-Transport-Security": "HSTS", "Content-Security-Policy": "CSP", "X-Content-Type-Options": "X-Content-Type-Options", "Referrer-Policy": "Referrer-Policy", "X-Frame-Options": "X-Frame-Options", } missing = [label for header, label in security_headers.items() if not home.headers.get(header)] if missing: result["findings"].append({ "severity": "review", "title": "Cabeceras de seguridad no observadas", "detail": ", ".join(missing) + ". Su ausencia en esta respuesta merece revisión, pero no demuestra por sí sola una vulnerabilidad." }) return result class App(tk.Tk): def __init__(self): super().__init__() self.title(APP_TITLE) self.geometry("1120x760") self.minsize(900, 620) self.results = None self.worker_queue = queue.Queue() self._build() self.after(150, self._poll_queue) def _build(self): root = ttk.Frame(self, padding=14) root.pack(fill="both", expand=True) header = ttk.Frame(root) header.pack(fill="x") ttk.Label(header, text="WordPress OSINT Inspector", font=("Arial", 20, "bold")).pack(anchor="w") ttk.Label( header, text="Reconocimiento pasivo de WordPress, plugins, temas, API REST y exposición tecnológica.", ).pack(anchor="w", pady=(3, 12)) entryrow = ttk.Frame(root) entryrow.pack(fill="x", pady=(0, 10)) ttk.Label(entryrow, text="Dominio:").pack(side="left") self.domain_var = tk.StringVar(value="https://www.example.com") self.domain_entry = ttk.Entry(entryrow, textvariable=self.domain_var, font=("Arial", 12)) self.domain_entry.pack(side="left", fill="x", expand=True, padx=8) self.scan_button = ttk.Button(entryrow, text="Analizar", command=self.start_scan) self.scan_button.pack(side="left") self.export_txt = ttk.Button(entryrow, text="Exportar TXT", command=self.save_txt, state="disabled") self.export_txt.pack(side="left", padx=(8, 0)) self.export_json = ttk.Button(entryrow, text="Exportar JSON", command=self.save_json, state="disabled") self.export_json.pack(side="left", padx=(8, 0)) self.status_var = tk.StringVar(value="Listo. Analiza únicamente dominios sobre los que tengas autorización.") ttk.Label(root, textvariable=self.status_var).pack(anchor="w", pady=(0, 6)) self.progress = ttk.Progressbar(root, mode="indeterminate") self.progress.pack(fill="x", pady=(0, 10)) paned = ttk.Panedwindow(root, orient="horizontal") paned.pack(fill="both", expand=True) left = ttk.Frame(paned, padding=(0, 0, 8, 0)) right = ttk.Frame(paned) paned.add(left, weight=3) paned.add(right, weight=2) ttk.Label(left, text="Informe de auditoría", font=("Arial", 12, "bold")).pack(anchor="w") self.output = tk.Text(left, wrap="word", font=("Menlo", 10), padx=10, pady=10) self.output.pack(fill="both", expand=True, pady=(6, 0)) self.output.insert("1.0", "Introduce un dominio y pulsa Analizar.\n\n" "La aplicación utiliza peticiones HTTP GET y no realiza pruebas de explotación.\n") self.output.configure(state="disabled") ttk.Label(right, text="Actividad", font=("Arial", 12, "bold")).pack(anchor="w") self.log = tk.Text(right, wrap="word", font=("Menlo", 9), padx=8, pady=8) self.log.pack(fill="both", expand=True, pady=(6, 0)) self.log.configure(state="disabled") footer = ttk.Label( root, text="Nota: la identificación de versiones puede ser inconcluyente si el sitio oculta datos, usa caché o modifica sus recursos.", foreground="#555" ) footer.pack(anchor="w", pady=(9, 0)) def append_log(self, message): self.worker_queue.put(("log", message)) def start_scan(self): domain = self.domain_var.get().strip() if not domain: messagebox.showwarning("Dominio", "Introduce un dominio.") return self.scan_button.configure(state="disabled") self.export_txt.configure(state="disabled") self.export_json.configure(state="disabled") self.results = None self.status_var.set("Analizando...") self.progress.start(10) self._set_text(self.output, "Análisis en curso...\n") self._set_text(self.log, "") threading.Thread(target=self._worker, args=(domain,), daemon=True).start() def _worker(self, domain): try: result = inspect_domain(domain, self.append_log) self.worker_queue.put(("done", result)) except Exception as exc: self.worker_queue.put(("error", str(exc))) def _poll_queue(self): try: while True: kind, payload = self.worker_queue.get_nowait() if kind == "log": self.log.configure(state="normal") self.log.insert("end", payload + "\n") self.log.see("end") self.log.configure(state="disabled") elif kind == "done": self.results = payload self.progress.stop() self.scan_button.configure(state="normal") self.export_txt.configure(state="normal") self.export_json.configure(state="normal") self.status_var.set("Análisis finalizado.") self._set_text(self.output, self.format_report(payload)) elif kind == "error": self.progress.stop() self.scan_button.configure(state="normal") self.status_var.set("El análisis no pudo completarse.") messagebox.showerror("Error de análisis", payload) except queue.Empty: pass self.after(150, self._poll_queue) def _set_text(self, widget, value): widget.configure(state="normal") widget.delete("1.0", "end") widget.insert("1.0", value) widget.configure(state="disabled") def format_report(self, r): lines = [] lines.append("=" * 76) lines.append("INFORME WORDPRESS OSINT") lines.append("=" * 76) lines.append(f"Objetivo: {r['target']}") lines.append(f"Fecha: {r['scanned_at']}") lines.append(f"Alcance: {r['scope']}") lines.append("") lines.append("[1] IDENTIFICACIÓN") lines.append(f"WordPress detectado: {'SÍ' if r['wordpress']['detected'] else 'NO CONFIRMADO'}") lines.append(f"Versión candidata: {r['wordpress']['version'] or 'No identificada'}") if r["wordpress"].get("indicators"): lines.append("Indicadores: " + ", ".join(r["wordpress"]["indicators"])) if r["wordpress"]["version_evidence"]: lines.append("Evidencias de versión:") for ev in r["wordpress"]["version_evidence"]: lines.append(f" - {ev['source']}: {ev['value']} [{ev['confidence']}]") lines.append("") lines.append("[2] SERVIDOR Y CABECERAS") for k, v in r["http"].items(): if k == "headers": lines.append("Cabeceras observadas:") for hk, hv in v.items(): lines.append(f" - {hk}: {hv}") else: lines.append(f"{k}: {v}") lines.append("") lines.append("[3] GENERADORES") lines.extend([f" - {x}" for x in r["generators"]] or [" - No identificados"]) lines.append("") lines.append("[4] PLUGINS IDENTIFICADOS") lines.extend([f" - {x}" for x in sorted(set(r["plugins"]))] or [" - No identificados"]) lines.append("") lines.append("[5] TEMAS IDENTIFICADOS") lines.extend([f" - {x}" for x in sorted(set(r["themes"]))] or [" - No identificados"]) lines.append("") lines.append("[6] API REST") lines.append(f"Disponible: {'SÍ' if r['rest_api']['available'] else 'No confirmada'}") lines.append(f"Nombre del sitio: {r['rest_api']['name']}") lines.append(f"Descripción: {r['rest_api']['description']}") lines.append(f"Namespaces ({len(r['rest_api']['namespaces'])}):") lines.extend([f" - {x}" for x in r["rest_api"]["namespaces"]] or [" - Ninguno"]) lines.append("") lines.append("[7] VERSIONES EN RECURSOS") lines.extend([f" - {x}" for x in r["asset_versions"]] or [" - No encontradas"]) lines.append("") lines.append("[8] COMPROBACIONES HTTP") for c in r["checks"]: lines.append(f" - {c['name']}: HTTP {c.get('status')} | {c['url']}") if c.get("interpretation"): lines.append(f" {c['interpretation']}") lines.append("") lines.append("[9] HALLAZGOS Y RECOMENDACIONES") for f in r["findings"]: lines.append(f" [{f['severity'].upper()}] {f['title']}") lines.append(f" {f['detail']}") if r["errors"]: lines.append("") lines.append("[10] ERRORES") for e in r["errors"]: lines.append(f" - {e['url']}: {e['error']}") lines.append("") lines.append("LIMITACIONES") lines.append("- Un resultado HTTP 200 no significa que una función sea vulnerable.") lines.append("- Los parámetros ver= pueden corresponder a jQuery, plugins, temas o caché.") lines.append("- Los namespaces de la API identifican componentes, no sus versiones ni su estado de seguridad.") lines.append("- No se realizan pruebas de explotación ni comprobaciones autenticadas.") return "\n".join(lines) def save_txt(self): if not self.results: return path = filedialog.asksaveasfilename( defaultextension=".txt", filetypes=[("Texto", "*.txt")], initialfile="informe_wordpress_osint.txt" ) if path: with open(path, "w", encoding="utf-8") as f: f.write(self.format_report(self.results)) messagebox.showinfo("Exportación", f"Informe guardado en:\n{path}") def save_json(self): if not self.results: return path = filedialog.asksaveasfilename( defaultextension=".json", filetypes=[("JSON", "*.json")], initialfile="informe_wordpress_osint.json" ) if path: with open(path, "w", encoding="utf-8") as f: json.dump(self.results, f, indent=2, ensure_ascii=False) messagebox.showinfo("Exportación", f"JSON guardado en:\n{path}") if __name__ == "__main__": App().mainloop() |