-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.py
More file actions
7734 lines (6317 loc) · 437 KB
/
Copy pathMain.py
File metadata and controls
7734 lines (6317 loc) · 437 KB
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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import time
import sys
import ctypes
import shutil
import socket
import platform
import subprocess
import threading
import winreg
import csv
import urllib.request
import urllib.parse
import json
import secrets
import string
import tkinter as tk
from tkinter import simpledialog
import customtkinter as ctk
import urllib.request
import webbrowser
from tkinter import messagebox
class LinuxToolkit:
@staticmethod
def ejecutar_comando(comando):
try:
resultado = subprocess.run(comando, shell=True, capture_output=True, text=True, check=True)
return resultado.stdout
except subprocess.CalledProcessError as e:
return f"❌ Error al ejecutar:\n{e.stderr}"
@staticmethod
def listar_avanzado(ruta="."): return LinuxToolkit.ejecutar_comando(f"ls -lah {ruta}")
@staticmethod
def analizar_espacio_disco(): return LinuxToolkit.ejecutar_comando("df -h")
@staticmethod
def ver_interfaces_red(): return LinuxToolkit.ejecutar_comando("ip a | grep inet")
@staticmethod
def probar_conectividad(host="google.com"): return LinuxToolkit.ejecutar_comando(f"ping -c 4 {host}")
@staticmethod
def abrir_monitor_htop():
try:
subprocess.Popen(["gnome-terminal", "--", "htop"])
return "✅ Monitor de recursos (htop) abierto en una nueva ventana."
except FileNotFoundError:
return "❌ No se encontró una terminal compatible. Instala htop o gnome-terminal."
def notificar_voz(mensaje):
"""Reproduce el mensaje por los altavoces de forma segura."""
try:
import pyttsx3
motor = pyttsx3.init()
# El número 150 es la velocidad. Puedes subirlo o bajarlo luego si quieres.
motor.setProperty('rate', 150)
motor.say(mensaje)
motor.runAndWait()
except ImportError:
print("[-] Módulo pyttsx3 no instalado. Silenciando notificación.")
except Exception as e:
print(f"[-] No se pudo reproducir la voz: {e}")
# Define la versión de este archivo físico
VERSION_ACTUAL = "3.2"
# ============================================================================
# 0. ESCUDO DE ADMINISTRADOR AUTOMÁTICO (UAC)
# ============================================================================
def is_admin():
try: return ctypes.windll.shell32.IsUserAnAdmin()
except: return False
if not is_admin():
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, f'"{sys.argv[0]}"', None, 1)
sys.exit()
# ============================================================================
# 1. MOTOR DE ADAPTABILIDAD FLUIDA (LIQUID UI)
# ============================================================================
ctk.set_appearance_mode("dark")
ctk.set_default_color_theme("blue")
app = ctk.CTk()
# 1. Analizamos el hardware de la pantalla en tiempo real
ancho_pantalla = app.winfo_screenwidth()
alto_pantalla = app.winfo_screenheight()
# 2. Geometría porcentual: La app ocupará el 85% de la pantalla (se auto-acopla)
factor_escala = 0.85
ancho_app = int(ancho_pantalla * factor_escala)
alto_app = int(alto_pantalla * factor_escala)
app.geometry(f"{ancho_app}x{alto_app}")
# 3. Centramos la ventana automáticamente en cualquier monitor
x_pos = int((ancho_pantalla - ancho_app) / 2)
y_pos = int((alto_pantalla - alto_app) / 2)
app.geometry(f"+{x_pos}+{y_pos}")
app.title("TREMEND Toolkit V3.2 [ESTABLE Y BLINDADO]")
# ============================================================================
# 2. MOTOR DE TERMINAL NATIVA Y EJECUCIÓN (SEGURO CONTRA CRASHES)
# ============================================================================
def abrir_consola_y_ejecutar(titulo, funcion_python_nativa):
global app
win_term = ctk.CTkToplevel(app)
win_term.title(f"Terminal TREMEND: {titulo}")
win_term.geometry("950x650")
# --- FIX: FORZAR LA VENTANA AL FRENTE SIEMPRE ---
win_term.lift() # Levanta la ventana en la jerarquía del sistema
win_term.attributes("-topmost", True) # La bloquea arriba de todo
# Soltamos el bloqueo después de 100 milisegundos para que no estorbe a otras apps
win_term.after(100, lambda: win_term.attributes("-topmost", False))
win_term.focus_force()
# --- BARRA SUPERIOR DE HERRAMIENTAS (HEADER) ---
top_frame = ctk.CTkFrame(win_term, fg_color="transparent")
top_frame.pack(fill="x", padx=10, pady=(10, 0))
lbl_estado = ctk.CTkLabel(top_frame, text="⚡ ESTADO: En Ejecución...", font=("Consolas", 14, "bold"), text_color="#F59E0B")
lbl_estado.pack(side="left")
def copiar_log():
win_term.clipboard_clear()
win_term.clipboard_append(txt_consola.get("1.0", "end"))
btn_copiar.configure(text="✔️ ¡Copiado!", text_color="#10B981")
win_term.after(2000, lambda: btn_copiar.configure(text="📋 Copiar Registro", text_color="#FFFFFF"))
btn_copiar = ctk.CTkButton(top_frame, text="📋 Copiar Registro", width=120, fg_color="#334155", hover_color="#475569", command=copiar_log)
btn_copiar.pack(side="right")
# --- LA CONSOLA TIPO MATRIX ---
txt_consola = ctk.CTkTextbox(win_term, width=930, height=560, fg_color="#0A0A0A", text_color="#00FFCC", font=("Consolas", 13), wrap="word", border_width=1, border_color="#334155")
txt_consola.pack(padx=10, pady=10, fill="both", expand=True)
# NUEVO: Menú Contextual Elegante (Click Derecho)
def menu_click_derecho(event):
menu = tk.Menu(win_term, tearoff=0, bg="#0A0A0A", fg="#00FFCC", activebackground="#334155", activeforeground="white")
def copiar_seleccion():
try:
texto_seleccionado = txt_consola.selection_get()
win_term.clipboard_clear()
win_term.clipboard_append(texto_seleccionado)
except: pass
def limpiar_pantalla():
txt_consola.configure(state="normal")
txt_consola.delete("1.0", "end")
txt_consola.insert("end", "[*] Consola limpiada por el usuario.\n" + "="*85 + "\n")
txt_consola.configure(state="disabled")
menu.add_command(label="📋 Copiar Selección", command=copiar_seleccion)
menu.add_separator()
menu.add_command(label="🧹 Limpiar Consola", command=limpiar_pantalla)
menu.tk_popup(event.x_root, event.y_root)
txt_consola.bind("<Button-3>", menu_click_derecho)
# Inyección asíncrona de la UI
# Inyección asíncrona de la UI
def log(texto):
def update_ui():
# ESCUDO: Solo escribe si la ventana de la consola sigue abierta
if txt_consola.winfo_exists():
txt_consola.configure(state="normal")
txt_consola.insert("end", str(texto) + "\n")
txt_consola.see("end")
txt_consola.configure(state="disabled")
app.after(0, update_ui)
def correr_proceso():
try: funcion_python_nativa(log)
except Exception as e: log(f"\n[!] ERROR CRÍTICO: {e}")
log("\n" + "="*85 + "\n[+] SECUENCIA FINALIZADA. Puedes cerrar esta ventana.")
# Actualizar el indicador de estado al terminar
def finalizar_ui():
# ESCUDO: Solo actualiza el estado si la etiqueta sigue existiendo
if lbl_estado.winfo_exists():
lbl_estado.configure(text="✅ ESTADO: Finalizado", text_color="#10B981")
app.after(0, finalizar_ui)
import threading
threading.Thread(target=correr_proceso, daemon=True).start()
def run_cmd(log, comando_str):
log(f"\n[TREMEND]> {comando_str}")
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
try:
proceso = subprocess.Popen(comando_str, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True, encoding='cp850', errors='ignore', startupinfo=startupinfo)
for linea in proceso.stdout:
if linea.strip(): log(linea.strip())
proceso.wait()
except Exception as e: log(f"[-] Error CMD: {e}")
def run_ps_script(log, script_str):
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
try:
proceso = subprocess.Popen(["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", script_str],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True, encoding='cp850', errors='ignore', startupinfo=startupinfo)
for linea in proceso.stdout:
if linea.strip(): log(linea.strip())
proceso.wait()
except Exception as e: log(f"[-] Error PS: {e}")
# ============================================================================
# 3. LÓGICA DE HERRAMIENTAS (CEREBRO)
# ============================================================================
# --- CATEGORÍA 1: REDES ---
def logica_info_red(log):
hostname = socket.gethostname()
log(f"[*] Equipo: {hostname} | IP Local: {socket.gethostbyname(hostname)}")
try:
ip_publica = urllib.request.urlopen('https://api.ipify.org', timeout=5).read().decode('utf8')
log(f"[*] IP Pública: {ip_publica}")
except: log("[-] Error IP Pública.")
run_cmd(log, "ipconfig /all")
def logica_reparacion_red(log):
import subprocess
log("[*] Iniciando Diagnóstico y Reparación Profunda de Red...")
# 1. Nivel Básico (Liberar y Renovar IP)
log("[*] Liberando direcciones IP actuales (ipconfig /release)...")
subprocess.run("ipconfig /release", shell=True, capture_output=True)
log("[*] Vaciando caché de resolución DNS (ipconfig /flushdns)...")
subprocess.run("ipconfig /flushdns", shell=True, capture_output=True)
log("[*] Solicitando nueva asignación IP al router (ipconfig /renew)...")
log("[!] Esto puede tardar unos segundos, la red parpadeará...")
subprocess.run("ipconfig /renew", shell=True, capture_output=True)
# 2. Restauración Profunda
log("[*] Restableciendo el catálogo Winsock (netsh winsock reset)...")
subprocess.run("netsh winsock reset", shell=True, capture_output=True)
log("[*] Restableciendo la pila TCP/IP a valores de fábrica (netsh int ip reset)...")
subprocess.run("netsh int ip reset", shell=True, capture_output=True)
# 2.5 Destrucción de Proxies Maliciosos y Restauración de Hosts (NUEVO)
log("[*] Purgando configuraciones de servidores Proxy inyectados por malware...")
subprocess.run('reg add "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v ProxyEnable /t REG_DWORD /d 0 /f', shell=True, capture_output=True)
subprocess.run("netsh winhttp reset proxy", shell=True, capture_output=True)
log("[*] Restaurando el archivo 'Hosts' a sus valores de fábrica...")
hosts_path = r"C:\Windows\System32\drivers\etc\hosts"
try:
if os.path.exists(hosts_path): os.remove(hosts_path)
with open(hosts_path, "w") as f:
f.write("# Archivo HOSTS restaurado por TREMEND Toolkit\n# localhost name resolution is handled within DNS itself.\n#\t127.0.0.1 localhost\n#\t::1 localhost\n")
except: log("[-] No se pudo restaurar el archivo Hosts (Posible bloqueo por Antivirus).")
# 3. Forzado Autónomo de DHCP (Detección automática)
log("[*] Escaneando adaptadores de red activos para forzar modo Automático (DHCP)...")
try:
ps_script = "Get-NetAdapter | Where-Object {$_.Status -eq 'Up'} | Select-Object -ExpandProperty Name"
resultado = subprocess.run(["powershell", "-NoProfile", "-Command", ps_script], capture_output=True, text=True)
interfaces = resultado.stdout.strip().split('\n')
if not interfaces or interfaces == ['']:
log("[-] No se detectaron adaptadores de red activos.")
else:
for iface in interfaces:
nombre_red = iface.strip()
if nombre_red:
log(f" -> Configurando IPv4 y DNS por DHCP en: '{nombre_red}'")
subprocess.run(f'netsh interface ip set address name="{nombre_red}" source=dhcp', shell=True, capture_output=True)
subprocess.run(f'netsh interface ip set dns name="{nombre_red}" source=dhcp', shell=True, capture_output=True)
except Exception as e:
log(f"[-] Error al configurar el DHCP automático: {e}")
log("\n=======================================================")
log(" ✅ REPARACIÓN DE RED COMPLETADA CON ÉXITO ")
log("=======================================================")
log("[!] NOTA: Para que los cambios en Winsock surtan efecto total, debes reiniciar la computadora.")
def logica_visibilidad_lan(log):
log("\n[*] Forzando configuración de Visibilidad de Red (Network Discovery)...")
log("[*] Iniciando servicios de descubrimiento PnP y UPnP...")
servicios = ["fdPHost", "FDResPub", "upnphost", "lmhosts"]
for s in servicios:
run_cmd(log, f"sc config {s} start= auto")
run_cmd(log, f"net start {s}")
log("[*] Modificando reglas del Firewall para permitir detección...")
run_cmd(log, 'netsh advfirewall firewall set rule group="Detección de redes" new enable=Yes')
run_cmd(log, 'netsh advfirewall firewall set rule group="Network Discovery" new enable=Yes')
run_cmd(log, 'netsh advfirewall firewall set rule group="Compartir archivos e impresoras" new enable=Yes')
run_cmd(log, 'netsh advfirewall firewall set rule group="File and Printer Sharing" new enable=Yes')
log("[+] ¡ÉXITO! El equipo ahora debería ser visible para otros computadores en la red local.")
def logica_geolocalizar_ip(log, ip_objetivo=""):
import urllib.request, json, os, webbrowser
# Si no se provee IP, la API devuelve los datos de la IP pública actual
url = f"http://ip-api.com/json/{ip_objetivo}?fields=status,message,country,countryCode,region,regionName,city,zip,lat,lon,timezone,isp,org,as,query"
log(f"\n[*] Triangulando coordenadas para la IP: {ip_objetivo if ip_objetivo else 'PROPIA (Local)'}...")
log("[*] Interrogando bases de datos globales y registros BGP/ASN...")
try:
req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
datos = json.loads(urllib.request.urlopen(req, timeout=10).read().decode('utf8'))
if datos.get("status") == "success":
ip = datos.get('query')
pais = f"{datos.get('country')} ({datos.get('countryCode')})"
region = f"{datos.get('regionName')} / {datos.get('city')}"
zip_code = datos.get('zip', 'N/A')
lat, lon = datos.get('lat'), datos.get('lon')
tz = datos.get('timezone')
isp = datos.get('isp')
org = datos.get('org')
asn = datos.get('as')
# 1. Consola estilo Hacker (Inspirado en la infografía)
log("\n" + "="*60)
log(f" 🎯 REPORTE DE INTELIGENCIA (OSINT): {ip}")
log("="*60)
log(f" 🌍 UBICACIÓN : {region}, {pais}")
log(f" 📮 CÓDIGO POSTAL : {zip_code}")
log(f" 🧭 COORDENADAS : {lat}, {lon}")
log(f" 🕒 ZONA HORARIA : {tz}")
log(f" 🏢 PROVEEDOR ISP : {isp}")
log(f" 🏛️ ORGANIZACIÓN : {org}")
log(f" 📡 SIST. AUTÓNOMO: {asn}")
log("="*60)
# 2. Generar el Mapa Interactivo en HTML (Leaflet.js en Modo Oscuro)
log("\n[*] Generando interfaz satelital interactiva (Mapa HTML)...")
html_mapa = f"""
<!DOCTYPE html>
<html lang="es">
<head>
<title>TREMEND - Radar OSINT ({ip})</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<style>
body {{ margin: 0; padding: 0; background-color: #0f172a; color: #38bdf8; font-family: 'Consolas', monospace; }}
#header {{ padding: 15px; text-align: center; background-color: #1e293b; border-bottom: 2px solid #00ffcc; }}
h2 {{ margin: 0; color: #00ffcc; text-transform: uppercase; letter-spacing: 2px; }}
p {{ margin: 5px 0 0 0; color: #94a3b8; font-size: 14px; }}
#map {{ height: calc(100vh - 80px); width: 100%; }}
.leaflet-popup-content-wrapper {{ background-color: #1e293b; color: #00ffcc; border: 1px solid #38bdf8; font-family: 'Consolas', monospace; }}
.leaflet-popup-tip {{ background-color: #1e293b; }}
</style>
</head>
<body>
<div id="header">
<h2>🌐 INTELIGENCIA DE RED - OBJETIVO: {ip}</h2>
<p>ISP: {isp} | Ubicación: {region}, {pais} | Coord: {lat}, {lon}</p>
</div>
<div id="map"></div>
<script>
var map = L.map('map').setView([{lat}, {lon}], 12);
// Capa de mapa estilo Cyberpunk/Dark
L.tileLayer('https://{{s}}.basemaps.cartocdn.com/dark_all/{{z}}/{{x}}/{{y}}{{r}}.png', {{
attribution: '© OpenStreetMap contributors © CARTO',
subdomains: 'abcd',
maxZoom: 20
}}).addTo(map);
var marker = L.marker([{lat}, {lon}]).addTo(map);
marker.bindPopup("<b>🎯 OBJETIVO FIJADO</b><br>IP: {ip}<br>ORG: {org}").openPopup();
</script>
</body>
</html>
"""
# Encontramos el escritorio seguro
escritorio = os.path.join(os.environ.get("USERPROFILE"), "Desktop")
if not os.path.exists(escritorio):
escritorio = os.path.join(os.environ.get("USERPROFILE"), "Escritorio")
ruta_mapa = os.path.join(escritorio, f"TREMEND_RadarIP_{ip.replace('.', '_')}.html")
try:
with open(ruta_mapa, "w", encoding="utf-8") as f:
f.write(html_mapa)
log(f"[+] ¡ÉXITO! Mapa táctico exportado a tu Escritorio.")
# Abrir en el navegador predeterminado
webbrowser.open(f"file:///{ruta_mapa.replace(chr(92), '/')}")
except Exception as e:
log(f"[-] Error al guardar el mapa HTML: {e}")
else:
log(f"[-] Error de la API al buscar la IP: {datos.get('message', 'Desconocido')}")
except Exception as e:
log(f"[-] Error de conexión o límite de peticiones alcanzado: {e}")
def logica_geowifi_bssid(log, bssid_raw):
import urllib.request, json, os, webbrowser, re, subprocess, concurrent.futures
log(f"\n" + "="*75)
log(f" 📡 INICIANDO RASTREO SATELITAL FORENSE (GeoWiFi V2.0) ")
log("="*75)
bssids_objetivos = []
# --- 1. MÓDULO DE AUTO-DETECCIÓN DE ENJAMBRE (NUEVO) ---
if not bssid_raw or bssid_raw.strip().lower() == "auto":
log("[*] Búsqueda automática detectada. Escaneando el espectro Wi-Fi actual...")
try:
# Consultamos TODAS las redes visibles, no solo la conectada
out = subprocess.run('netsh wlan show networks mode=bssid', shell=True, capture_output=True, text=True, encoding='cp850', errors='ignore').stdout
for linea in out.splitlines():
if "BSSID" in linea and not "SSID" in linea.replace("BSSID", ""):
bssid_encontrado = linea.split(":", 1)[1].strip().upper()
if bssid_encontrado not in bssids_objetivos:
bssids_objetivos.append(bssid_encontrado)
if bssids_objetivos:
log(f"[+] ¡Enjambre detectado! Se encontraron {len(bssids_objetivos)} BSSIDs en tu zona.")
if len(bssids_objetivos) > 10:
bssids_objetivos = bssids_objetivos[:10] # Top 10 para no saturar la API
else:
log("[-] Falló la auto-detección. No se encontraron redes Wi-Fi cercanas.")
return
except Exception as e:
log(f"[-] Error en el motor de auto-detección: {e}")
return
else:
# Búsqueda manual de un solo BSSID
mac_limpia = re.sub(r'[^a-fA-F0-9]', '', bssid_raw).upper()
if len(mac_limpia) != 12:
log(f"[-] Error: La dirección '{bssid_raw}' es inválida.")
log(" -> Una dirección MAC debe contener exactamente 12 caracteres hexadecimales.")
return
bssid_final = ":".join([mac_limpia[i:i+2] for i in range(0, 12, 2)])
bssids_objetivos.append(bssid_final)
log(f"[*] Objetivo fijado y formateado a nivel de máquina: {bssid_final}")
log("[*] Interrogando bases de datos de telemetría global (OSINT) de forma concurrente...")
coordenadas_validas = []
# --- 2. MOTOR DE TRIANGULACIÓN (NUEVO) ---
def consultar_api(bssid):
url = f"https://api.mylnikov.org/geolocation/wifi?v=1.1&data=open&bssid={bssid}"
try:
req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
respuesta = urllib.request.urlopen(req, timeout=5).read().decode('utf8')
datos = json.loads(respuesta)
if datos.get("result") == 200 and "data" in datos:
lat = datos["data"].get("lat")
lon = datos["data"].get("lon")
return (bssid, lat, lon)
except urllib.error.HTTPError as e:
return (bssid, "ERROR", e.code)
except: pass
return (bssid, None, None)
errores_523 = 0
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as ejecutor:
futuros = [ejecutor.submit(consultar_api, b) for b in bssids_objetivos]
for futuro in concurrent.futures.as_completed(futuros):
bssid, lat, lon = futuro.result()
if lat == "ERROR":
errores_523 += 1
elif lat and lon:
log(f" [+] BSSID {bssid} localizado -> {lat}, {lon}")
coordenadas_validas.append((bssid, lat, lon))
else:
log(f" [-] BSSID {bssid} no figura en la base de datos.")
# --- 3. MANEJO INTELIGENTE DE ERRORES (Anti 523) ---
if errores_523 > 0 and len(coordenadas_validas) == 0:
log("\n[-] ALERTA DE SERVIDOR OSINT: La base de datos satelital gratuita está bajo mantenimiento (Error 523/502).")
log(" -> TREMEND ha contenido el error para evitar bloqueos en tu sistema.")
log("\n [💡] Alternativa Forense (Opcional):")
log(" Si posees una cuenta de investigador, puedes triangular la señal manualmente copiando este enlace:")
if len(bssids_objetivos) == 1:
log(f" 🔗 https://wigle.net/search?mac={bssids_objetivos[0]}")
else:
log(" 🔗 https://wigle.net/")
log(f" Y busca manualmente una de estas MACs: {', '.join(bssids_objetivos[:3])}")
log("\n[-] Operación abortada con seguridad. Inténtalo más tarde cuando el servidor público se restablezca.")
return
# --- 4. CÁLCULO DEL EPICENTRO (PROMEDIO) ---
lat_promedio = sum([c[1] for c in coordenadas_validas]) / len(coordenadas_validas)
lon_promedio = sum([c[2] for c in coordenadas_validas]) / len(coordenadas_validas)
log(f"\n[*] Triangulación completada. Compilando {len(coordenadas_validas)} nodos en Mapa Táctico HTML...")
# Generación de Marcadores en JS
marcadores_js = ""
for bssid, lat, lon in coordenadas_validas:
marcadores_js += f"""
var marker = L.marker([{lat}, {lon}]).addTo(map);
marker.bindPopup("<b>🎯 NODO DETECTADO</b><br>BSSID: {bssid}");
"""
html_mapa = f"""
<!DOCTYPE html>
<html lang="es">
<head>
<title>TREMEND - Radar Wi-Fi OSINT V2</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<style>
body {{ margin: 0; padding: 0; background-color: #0f172a; color: #a855f7; font-family: 'Consolas', monospace; }}
#header {{ padding: 15px; text-align: center; background-color: #1e293b; border-bottom: 2px solid #a855f7; }}
h2 {{ margin: 0; color: #00ffcc; text-transform: uppercase; letter-spacing: 2px; }}
p {{ margin: 5px 0 0 0; color: #94a3b8; font-size: 14px; }}
#map {{ height: calc(100vh - 80px); width: 100%; }}
.leaflet-popup-content-wrapper {{ background-color: #1e293b; color: #a855f7; border: 1px solid #38bdf8; font-family: 'Consolas', monospace; }}
.leaflet-popup-tip {{ background-color: #1e293b; }}
</style>
</head>
<body>
<div id="header">
<h2>📡 RASTREO FORENSE MULTI-NODO (ENJAMBRE WI-FI)</h2>
<p>Nodos Localizados: {len(coordenadas_validas)} | Epicentro Calculado: {lat_promedio:.5f}, {lon_promedio:.5f}</p>
</div>
<div id="map"></div>
<script>
var map = L.map('map').setView([{lat_promedio}, {lon_promedio}], 16);
L.tileLayer('https://{{s}}.basemaps.cartocdn.com/dark_all/{{z}}/{{x}}/{{y}}{{r}}.png', {{
maxZoom: 20
}}).addTo(map);
// Círculo de Triangulación
L.circle([{lat_promedio}, {lon_promedio}], {{
color: '#00ffcc',
fillColor: '#00ffcc',
fillOpacity: 0.1,
radius: 100
}}).addTo(map).bindPopup("<b>📍 EPICENTRO TRIANGULADO</b>");
// Marcadores individuales
{marcadores_js}
</script>
</body>
</html>
"""
escritorio = os.path.join(os.environ.get("USERPROFILE"), "Desktop")
if not os.path.exists(escritorio):
escritorio = os.path.join(os.environ.get("USERPROFILE"), "Escritorio")
nombre_archivo = "TREMEND_GeoWiFi_Enjambre.html" if len(bssids_objetivos) > 1 else f"TREMEND_GeoWiFi_{bssids_objetivos[0].replace(':', '')}.html"
ruta_mapa = os.path.join(escritorio, nombre_archivo)
with open(ruta_mapa, "w", encoding="utf-8") as f:
f.write(html_mapa)
log(f"[+] ¡ÉXITO! Mapa táctico exportado a tu Escritorio.")
webbrowser.open(f"file:///{ruta_mapa.replace(chr(92), '/')}")
try: notificar_voz("El Rastreo Satelital Geo Wi Fi ha terminado.")
except: pass
def logica_wifi_forense(log, accion):
import subprocess, os, re, hashlib, urllib.request
# --- MOTOR DE INTELIGENCIA DE CONTRASEÑAS ---
def auditar_seguridad(pwd):
if not pwd or pwd == "SIN CLAVE / RED ABIERTA": return "🔴 NINGUNA"
if len(pwd) < 8: return "🟠 BAJA"
score = sum([bool(re.search(r"[A-Z]", pwd)), bool(re.search(r"[a-z]", pwd)),
bool(re.search(r"[0-9]", pwd)), bool(re.search(r"[!@#$%^&*(),.?\":{}|<>]", pwd))])
if score >= 3 and len(pwd) >= 12: return "🟢 ALTA"
if score >= 2: return "🟡 MEDIA"
return "🟠 BAJA"
def comprobar_filtracion(pwd):
if not pwd or pwd == "SIN CLAVE / RED ABIERTA": return "N/A"
try:
# Encriptamos la clave en SHA-1 (Requisito de ciberseguridad)
sha1 = hashlib.sha1(pwd.encode('utf-8')).hexdigest().upper()
prefix, suffix = sha1[:5], sha1[5:]
# Consultamos la base de datos global de HaveIBeenPwned (Pwned Passwords API)
req = urllib.request.Request(f"https://api.pwnedpasswords.com/range/{prefix}", headers={'User-Agent': 'TREMEND-Toolkit'})
res = urllib.request.urlopen(req, timeout=5).read().decode('utf-8')
for linea in res.splitlines():
if linea.startswith(suffix):
veces = int(linea.split(':')[1])
return f"⚠️ FILTRADA ({veces} veces)"
return "✅ SEGURA"
except: return "Desconocido (Sin Red)"
# --- EJECUCIÓN LÓGICA ---
if accion == '1':
log("\n[*] Iniciando Extracción y Auditoría Forense de Credenciales Wi-Fi...")
log("[*] Conectando con bases de datos de brechas de seguridad (HaveIBeenPwned API)...")
try:
out = subprocess.run('netsh wlan show profiles', shell=True, capture_output=True, text=True, encoding='cp850', errors='ignore').stdout
perfiles = [line.split(":")[1].strip() for line in out.splitlines() if ("Perfil" in line or "Profile" in line) and ":" in line]
if not perfiles:
log("[-] La base de datos WLAN está vacía. No hay redes guardadas.")
return
log(f"[*] Se detectaron {len(perfiles)} redes en este equipo.\n")
# Interfaz de Tabla Hack/Forense
log("="*95)
log(f"{'RED WI-FI (SSID)'.ljust(25)} | {'CONTRASEÑA'.ljust(20)} | {'SEGURIDAD'.ljust(12)} | {'ESTADO EN INTERNET'}")
log("="*95)
texto_portapapeles = "REPORTE FORENSE WI-FI - TREMEND TOOLKIT\n" + "="*95 + "\n"
for p in perfiles:
detalles = subprocess.run(f'netsh wlan show profile name="{p}" key=clear', shell=True, capture_output=True, text=True, encoding='cp850', errors='ignore').stdout
clave = "SIN CLAVE / RED ABIERTA"
for line in detalles.splitlines():
if ("Contenido de la clave" in line or "Key Content" in line) and ":" in line:
clave = line.split(":")[1].strip()
break
seguridad = auditar_seguridad(clave)
filtracion = comprobar_filtracion(clave)
linea_tabla = f"{p[:24].ljust(25)} | {clave[:19].ljust(20)} | {seguridad.ljust(12)} | {filtracion}"
log(linea_tabla)
texto_portapapeles += linea_tabla + "\n"
log("="*95)
try:
app.clipboard_clear()
app.clipboard_append(texto_portapapeles)
log("\n[+] ¡Tabla de contraseñas copiada automáticamente a tu portapapeles!")
except: pass
except Exception as e: log(f"[-] Error de extracción: {e}")
elif accion == '2':
log("\n[*] Exportando perfiles Wi-Fi (Backup para migración)...")
ruta_backup = os.path.join(os.environ.get("USERPROFILE"), "Desktop", "TREMEND_WiFi_Backup")
if not os.path.exists(ruta_backup): os.makedirs(ruta_backup)
run_cmd(log, f'netsh wlan export profile key=clear folder="{ruta_backup}"')
log(f"[+] Backup completado. Archivos XML guardados en el Escritorio: {ruta_backup}")
elif accion == '3':
log("\n[*] Importando perfiles Wi-Fi desde el Backup...")
ruta_backup = os.path.join(os.environ.get("USERPROFILE"), "Desktop", "TREMEND_WiFi_Backup")
if not os.path.exists(ruta_backup):
log("[-] No se encontró la carpeta 'TREMEND_WiFi_Backup' en el Escritorio."); return
script = f"Get-ChildItem -Path '{ruta_backup}' -Filter '*.xml' | ForEach-Object {{ netsh wlan add profile filename=$_.FullName }}"
run_ps_script(log, script)
log("[+] Perfiles inyectados exitosamente en el sistema.")
def logica_optimizar_dns(log, opcion):
log("\n[*] Reconfigurando la resolución de nombres de dominio (DNS) en todos los adaptadores activos...")
# --- MATRIZ DE SERVIDORES DNS (NIVEL INGENIERO) ---
dns_map = {
# --- MÁXIMA VELOCIDAD ---
'1': ("1.1.1.1, 1.0.0.1", "Cloudflare (Rápido y Privado)"),
'2': ("8.8.8.8, 8.8.4.4", "Google (Alta Estabilidad y Resolución)"),
# --- BLOQUEO DE ANUNCIOS Y RASTREADORES ---
'3': ("94.140.14.14, 94.140.15.15", "AdGuard (Bloqueo de Anuncios y Trackers)"),
'4': ("194.242.2.3, 194.242.2.4", "Mullvad (Cero Rastreadores y Anti-Ads)"),
# --- CIBERSEGURIDAD (ANTI-MALWARE / PHISHING) ---
'5': ("9.9.9.9, 149.112.112.112", "Quad9 (Bloqueo Nativo de Malware)"),
'6': ("1.1.1.2, 1.0.0.2", "Cloudflare Security (Bloqueo de Malware)"),
'7': ("76.76.2.1, 76.76.2.0", "ControlD (Bloqueo de Malware y Phishing)"),
# --- FILTRO FAMILIAR (ANTI-ADULTO / PORNO) ---
'8': ("1.1.1.3, 1.0.0.3", "Cloudflare Family (Malware + Contenido Adulto)"),
'9': ("185.228.168.168, 185.228.169.168", "CleanBrowsing (Filtro Familiar Estricto)"),
'10': ("94.140.14.15, 94.140.15.16", "AdGuard Family (Anuncios + Contenido Adulto)"),
'11': ("208.67.222.123, 208.67.220.123", "OpenDNS Family Shield (Contenido Adulto)")
}
if opcion in dns_map:
ips, nombre = dns_map[opcion]
log(f"[*] Inyectando Servidores: {nombre}")
log(f" -> IPs Objetivo: {ips}")
run_ps_script(log, f'Get-NetAdapter | Where-Object {{$_.Status -eq "Up"}} | Set-DnsClientServerAddress -ServerAddresses {ips}')
log(f"[+] Servidores DNS cambiados a {ips} exitosamente.")
run_cmd(log, "ipconfig /flushdns")
log("[+] Caché DNS purgada para aplicar los nuevos filtros inmediatamente.")
elif opcion == '12':
log("[*] Restaurando DNS Automático (DHCP por defecto)...")
run_ps_script(log, 'Get-NetAdapter | Where-Object {{$_.Status -eq "Up"}} | Set-DnsClientServerAddress -ResetServerAddresses')
log("[+] DNS restaurados a la configuración de fábrica de tu proveedor de internet.")
run_cmd(log, "ipconfig /flushdns")
else:
log("[-] Operación cancelada u opción inválida.")
def logica_reinicio_bios(log):
log("\n[*] Iniciando secuencia de reinicio forzado hacia la BIOS/UEFI...")
log("[!] ATENCIÓN: El equipo se reiniciará INMEDIATAMENTE. Cierra tus trabajos.")
script_ps = """
try {
Write-Host "[*] Comprobando compatibilidad de firmware de la Placa Base..."
# Verifica si el sistema arranca con UEFI (Requisito para el reinicio remoto a BIOS)
if (Test-Path "HKLM:\\System\\CurrentControlSet\\Control\\SecureBoot\\State") {
Write-Host "[+] Sistema UEFI detectado. Ejecutando reinicio en 3 segundos..." -ForegroundColor Green
Start-Sleep -Seconds 3
shutdown.exe /r /fw /t 0
} else {
Write-Host "[-] Tu sistema utiliza BIOS Legacy antigua." -ForegroundColor Red
Write-Host "[-] El salto directo a BIOS solo es soportado por placas base UEFI modernas." -ForegroundColor Yellow
}
} catch {
Write-Host "[-] Error al invocar el comando de energía."
}
"""
run_ps_script(log, script_ps)
def logica_limpiar_arp(log):
log("\n[*] Purgando caché de enrutamiento (ARP)...")
run_cmd(log, "arp -d *")
log("[+] Tabla ARP destruida. La red se re-descubrirá automáticamente.")
def logica_ping_tcp(log, destino, puerto):
log(f"\n[*] Ejecutando prueba de conectividad hacia: {destino}")
if puerto:
log(f"[*] Escaneando puerto TCP {puerto}...")
run_ps_script(log, f"Test-NetConnection -ComputerName '{destino}' -Port {puerto} | Format-List")
else:
run_cmd(log, f"ping {destino} -n 4")
notificar_voz("La Prueba De Conectividad ha terminado.")
def logica_puerto_proceso(log, puerto):
log(f"\n[*] Mapeando procesos en el puerto local {puerto}...")
script = f"""
try {{
$conex = Get-NetTCPConnection -LocalPort {puerto} -ErrorAction Stop
Write-Host '[+] Procesos ocupando el puerto {puerto}:' -ForegroundColor Green
$conex | ForEach-Object {{ Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue }} | Select-Object Id, ProcessName, Path -Unique | Format-List
}} catch {{ Write-Host '[-] Ningun proceso activo en ese puerto.' }}
"""
run_ps_script(log, script)
def logica_generador_qr(log, tipo, dato1, dato2=""):
import random
log(f"\n[*] Iniciando Motor Universal de Códigos QR...")
try:
if tipo == '1':
log(f"[*] Compilando protocolo de red para Wi-Fi: {dato1}")
formato = f"WIFI:T:WPA;S:{urllib.parse.quote(dato1)};P:{urllib.parse.quote(dato2)};;" if dato2 else f"WIFI:T:nopass;S:{urllib.parse.quote(dato1)};P:;;"
nombre_archivo = f"QR_WiFi_{dato1.replace(' ', '_')[:10]}.png"
else:
log(f"[*] Procesando URL o Texto libre...")
formato = urllib.parse.quote(dato1)
nombre_archivo = f"QR_Personalizado_{random.randint(1000,9999)}.png"
url = f"https://api.qrserver.com/v1/create-qr-code/?size=500x500&data={formato}"
# Encontramos el escritorio sin importar el idioma de Windows
escritorio = os.path.join(os.environ.get("USERPROFILE"), "Desktop")
if not os.path.exists(escritorio):
escritorio = os.path.join(os.environ.get("USERPROFILE"), "Escritorio")
ruta_qr = os.path.join(escritorio, nombre_archivo)
log("[*] Renderizando matriz gráfica en alta calidad...")
urllib.request.urlretrieve(url, ruta_qr)
log("\n=======================================================")
log(f" [+] ¡ÉXITO! Código QR guardado en tu Escritorio.")
log(f" [+] Archivo: {nombre_archivo}")
log("=======================================================")
os.startfile(ruta_qr)
except Exception as e:
log(f"[-] Error al generar QR: {e}")
def logica_reporte_wifi(log):
log("\n[*] Generando Reporte de Diagnóstico Wi-Fi de Windows (WlanReport)...")
run_cmd(log, "netsh wlan show wlanreport")
ruta = r"C:\ProgramData\Microsoft\Windows\WlanReport\wlan-report-latest.html"
if os.path.exists(ruta): log(f"[+] Reporte generado en: {ruta}"); os.startfile(ruta)
else: log("[-] No se pudo generar el reporte.")
notificar_voz("El Reporte De WIfi ha terminado.")
def logica_resolucion_dns(log, dominio):
log(f"\n[*] Interrogando servidores raíz para el dominio: {dominio}")
run_ps_script(log, f"Resolve-DnsName -Name '{dominio}' -ErrorAction Stop | Select-Object Name, Type, IPAddress, NameHost | Format-Table -AutoSize")
def logica_bloquear_web(log, accion, dominio=""):
import os
hosts_path = r"C:\Windows\System32\drivers\etc\hosts"
if accion == '1':
log(f"\n[*] Inyectando regla de bloqueo (loopback) para: {dominio}")
dominio_limpio = dominio.replace("http://", "").replace("https://", "").replace("www.", "").strip("/")
try:
with open(hosts_path, "a") as f:
f.write(f"\n0.0.0.0 {dominio_limpio}\n0.0.0.0 www.{dominio_limpio}\n")
run_cmd(log, "ipconfig /flushdns")
log(f"[+] Dominio '{dominio_limpio}' bloqueado exitosamente.")
except Exception as e:
log(f"[-] Error de permisos: {e}")
elif accion == '2':
log(f"\n[*] Buscando y removiendo bloqueos para: {dominio}")
dominio_limpio = dominio.replace("http://", "").replace("https://", "").replace("www.", "").strip("/")
try:
with open(hosts_path, "r") as f:
lineas = f.readlines()
with open(hosts_path, "w") as f:
removidos = 0
for linea in lineas:
# Si la línea contiene el dominio y es una regla de bloqueo, la omitimos (la borramos)
if dominio_limpio in linea and "0.0.0.0" in linea:
removidos += 1
continue
f.write(linea)
run_cmd(log, "ipconfig /flushdns")
if removidos > 0:
log(f"[+] Se eliminaron {removidos} reglas de bloqueo. El dominio '{dominio_limpio}' ha sido restaurado.")
else:
log(f"[-] El dominio '{dominio_limpio}' no estaba bloqueado en el sistema.")
except Exception as e:
log(f"[-] Error de permisos: {e}")
elif accion == '3':
log("\n[*] Purgando TODAS las reglas del archivo Hosts...")
try:
with open(hosts_path, "w") as f:
f.write("# Archivo HOSTS restaurado por TREMEND Toolkit\n# localhost name resolution is handled within DNS itself.\n#\t127.0.0.1 localhost\n#\t::1 localhost\n")
run_cmd(log, "ipconfig /flushdns")
log("[+] Archivo Hosts restaurado a fábrica. Todas las páginas web han sido desbloqueadas.")
except Exception as e:
log(f"[-] Error de permisos: {e}")
try: notificar_voz("El Gestor Avanzado de Hosts ha terminado.")
except: pass
def logica_abrir_puerto(log, puerto, proto):
log(f"\n[*] Abriendo puerto {puerto} ({proto}) en el Firewall...")
run_cmd(log, f'netsh advfirewall firewall add rule name="TREMEND: Puerto {puerto} {proto}" dir=in action=allow protocol={proto} localport={puerto}')
def logica_purgar_wifi_historial(log):
log("\n[*] Purgando todo el historial inalambrico del sistema...")
run_cmd(log, "netsh wlan delete profile name=* i=*")
def logica_reset_firewall(log):
log("\n[*] Restaurando Firewall a fábrica...")
run_cmd(log, "netsh advfirewall reset")
def logica_conexiones_tcp(log):
log("\n[*] Mapeando conexiones TCP establecidas y puertos activos...")
run_ps_script(log, 'Get-NetTCPConnection | Where-Object State -eq "Established" | Select-Object RemoteAddress, RemotePort, @{Name="Programa";Expression={(Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue).Name}} | Format-Table -AutoSize')
def logica_sesiones_smb(log):
log("\n[*] Auditando sesiones conectadas a esta máquina (SMB/Carpetas Compartidas)...")
run_ps_script(log, 'Get-SmbSession | Select-Object ClientComputerName, ClientUserName, NumOpens | Out-GridView -Title "Sesiones Activas en tu Red"')
log("[+] Volcado de sesiones completado. Si ves usuarios desconocidos, revisa tus carpetas compartidas.")
def logica_radar_wifi(log):
log("\n[*] Iniciando Radar Wi-Fi de Espectro (5 Barridos)...")
import time
for i in range(5):
log(f"\n--- BARRIDO {i+1}/5 ---")
run_cmd(log, 'netsh wlan show networks mode=bssid | findstr "SSID Señal Canal"')
time.sleep(2)
log("\n[+] Análisis de espectro finalizado.")
notificar_voz("El Radar Wi-Fi ha terminado.")
def logica_auditoria_latencia(log, destino):
import time, datetime
log(f"\n[*] Iniciando Auditoría de Latencia Continua hacia {destino} (10 paquetes con reloj atómico)...")
for i in range(10):
hora = datetime.datetime.now().strftime("%H:%M:%S")
respuesta = subprocess.run(f"ping -n 1 -w 1000 {destino}", shell=True, capture_output=True, text=True, encoding='cp850').stdout
if "TTL=" in respuesta:
tiempo = respuesta.split("tiempo")[1].split("ms")[0].replace("=", "").replace("<", "").strip()
log(f"[{hora}] -> Respuesta de {destino}: {tiempo} ms")
else:
log(f"[{hora}] -> [!] TIEMPO DE ESPERA AGOTADO (Microcorte detectado)")
time.sleep(1)
log("[+] Auditoría finalizada.")
notificar_voz("La Prueba De Latencia ha terminado.")
def logica_escaner_puertos_python(log, objetivo):
import socket
import concurrent.futures
log(f"\n[*] Preparando Escáner de Puertos Avanzado (Motor Asíncrono Multihilo)")
# 1. Traductor DNS inteligente (Convierte dominios en IP automáticamente)
try:
ip_objetivo = socket.gethostbyname(objetivo)
if objetivo != ip_objetivo:
log(f"[*] Objetivo fijado: {objetivo} -> {ip_objetivo}")
else:
log(f"[*] Objetivo fijado: {ip_objetivo}")
except socket.gaierror:
log(f"[-] Error crítico: No se pudo resolver el dominio o IP '{objetivo}'.")
return
# Añadimos puertos más letales (SQL, VNC, Web Alterno)
puertos_comunes = {
21: "FTP", 22: "SSH", 23: "Telnet", 25: "SMTP", 53: "DNS",
80: "HTTP", 110: "POP3", 135: "RPC", 139: "NetBIOS",
443: "HTTPS", 445: "SMB", 1433: "SQL Server", 3306: "MySQL",
3389: "RDP", 5900: "VNC", 8080: "HTTP Alterno"
}
abiertos = 0
log("[*] Lanzando enjambre de hilos (Reconocimiento simultáneo ultrarrápido)...")
def escanear_puerto(puerto, servicio):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(0.6) # Timeout letal pero seguro
resultado = s.connect_ex((ip_objetivo, puerto))
s.close()
if resultado == 0:
return puerto, servicio, True
except: pass
return puerto, servicio, False
# 2. ATAQUE MULTIHILO: Escanea los 16 puertos a la vez en paralelo
with concurrent.futures.ThreadPoolExecutor(max_workers=16) as ejecutor:
futuros = [ejecutor.submit(escanear_puerto, p, s) for p, s in puertos_comunes.items()]
for futuro in concurrent.futures.as_completed(futuros):
puerto, servicio, abierto = futuro.result()
if abierto:
log(f" [+] PUERTO ABIERTO: {puerto} ({servicio}) -> ¡Posible vector de ataque!")
abiertos += 1
if abiertos == 0:
log("\n[-] La máquina parece estar blindada o apagada. No hay puertos expuestos.")
else:
log(f"\n[!] ALERTA CRÍTICA: Se detectaron {abiertos} puertos vulnerables.")
log("[+] Escaneo finalizado.")
try: notificar_voz("El Escáner de Puertos ha terminado.")
except: pass
def logica_auditor_web(log, objetivo):
import urllib.request
import socket
import ssl
import time
log(f"\n" + "="*75)
log(f" 🌐 INICIANDO AUDITORÍA WEB FORENSE (OBJETIVO: {objetivo}) ")
log(f"="*75)
# Limpiar el objetivo
objetivo = objetivo.replace("http://", "").replace("https://", "").strip("/")
log("\n[1] FASE DE RECONOCIMIENTO (BANNER GRABBING)...")
puertos_web = [80, 443]
for puerto in puertos_web:
protocolo = "HTTP" if puerto == 80 else "HTTPS"
log(f"[*] Evaluando puerto {puerto} ({protocolo})...")
try:
# Sockets para un timeout súper agresivo
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2.0)
resultado = s.connect_ex((objetivo, puerto))
if resultado == 0:
log(f" [+] Puerto {puerto} ABIERTO.")
# Extracción de Cabeceras
req_url = f"http://{objetivo}" if puerto == 80 else f"https://{objetivo}"
try:
req = urllib.request.Request(req_url, headers={'User-Agent': 'Mozilla/5.0'}, method='HEAD')
context = ssl._create_unverified_context() if puerto == 443 else None
with urllib.request.urlopen(req, timeout=3, context=context) as response:
server_header = response.headers.get('Server', 'Desconocido / Oculto')
x_powered_by = response.headers.get('X-Powered-By', 'No especificado')
log(f" -> Servidor (Engine): {server_header}")
log(f" -> Tecnología base : {x_powered_by}")
except urllib.error.URLError as e:
# Si da 403 Forbidden o 401, el puerto está abierto pero bloqueado
log(f" -> Servidor vivo pero con restricciones (Código: {e.code if hasattr(e, 'code') else e.reason})")
except Exception as e:
log(f" [-] Error al extraer cabeceras HTTP: {e}")