-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathBlackBerryC2_server.py
More file actions
executable file
·7985 lines (6842 loc) · 353 KB
/
Copy pathBlackBerryC2_server.py
File metadata and controls
executable file
·7985 lines (6842 loc) · 353 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
# BlackBerryC2Server v2.0
import socket
import threading
from contextlib import contextmanager
@contextmanager
def _null_context():
"""Context manager no-op para cuando no hay send_lock disponible."""
yield
import os
import struct
import time
import logging
import hashlib
import subprocess
import sys
import tempfile
import atexit
import shlex
import select
import json
import re
import getpass
# ── Suprimir tracebacks en consola ──────────────────────────────────────────
# Los errores completos van al log; en pantalla solo el mensaje limpio.
def _bb_excepthook(exc_type, exc_value, exc_tb):
# Mostrar solo el tipo y mensaje, no el traceback completo
msg = str(exc_value) if str(exc_value) else exc_type.__name__
print(f"\033[91mBlackBerry ✗ {msg}\033[0m")
# Guardar traceback completo en el log
logging.critical("Excepción no capturada", exc_info=(exc_type, exc_value, exc_tb))
sys.excepthook = _bb_excepthook
# ────────────────────────────────────────────────────────────────────────────
from queue import Queue, Empty
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives.asymmetric import ec, dsa, rsa
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
import hmac as hmac_module
import secrets
import base64
from colores import *
from collections import defaultdict, deque
import zlib
import argparse
from datetime import datetime
# Zstandard para archivos grandes (opcional pero recomendado)
try:
import zstandard as zstd
ZSTD_AVAILABLE = True
except ImportError:
ZSTD_AVAILABLE = False
print(f"{YELLOW}[!] zstandard no disponible. Instala con: pip install zstandard{RESET}")
print(f"{YELLOW} (Recomendado para transferencias >1GB){RESET}")
# Importar prompt_toolkit (opcional)
try:
from prompt_toolkit import PromptSession
from prompt_toolkit.completion import Completer, WordCompleter, Completion, PathCompleter, merge_completers
from prompt_toolkit.history import FileHistory
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit.styles import Style
from prompt_toolkit.document import Document
from prompt_toolkit.patch_stdout import patch_stdout as _pt_patch_stdout
from prompt_toolkit.formatted_text import ANSI as PT_ANSI
PROMPT_TOOLKIT_AVAILABLE = True
except ImportError:
PROMPT_TOOLKIT_AVAILABLE = False
_pt_patch_stdout = None
PT_ANSI = None
print(f"{ALERT} {YELLOW}prompt_toolkit no disponible, usando input() básico{RESET}")
# ==================== IMPORT DEL PROXY v2.1 ====================
import multiprocessing
try:
from BlackBerryHTTPs_TLSProxyDaemon import BlackBerryProxy
PROXY_AVAILABLE = True
except ImportError:
PROXY_AVAILABLE = False
print(f"{YELLOW}[!] BlackBerryHTTPs_TLSProxyDaemon no disponible{RESET}")
# Variables globales del proxy
tls_proxy = None # Instancia del proxy daemon
tls_proxy_gui_process = None # Proceso del GUI
# Variables globales para control de verbosidad
VERBOSE_MODE = 0
# Clave AES-256 para cifrar sessions.jsonl — None = texto plano
_SESSION_LOG_KEY: bytes | None = None
_SERVER_LOG_KEY: bytes | None = None # clave del BlackBerryC2_enc.log
ENABLE_COMPRESSION = True
COMPRESSION_LEVEL = 9
CHUNK_SIZE = 64 * 1024
# ==================== DYNAMIC FILE TRANSFER ====================
FILE_TIMEOUT_BASE = 90
FILE_TIMEOUT_PER_MB = 20
FILE_MAX_TIMEOUT = 7200
FILE_MIN_TIMEOUT = 45
FILE_RETRY_COUNT = 3
FILE_CHUNK_REPORT_INTERVAL = 100
FILE_VERIFICATION_RETRIES = 2
LARGE_FILE_THRESHOLD = 1024 * 1024 * 1024 # 1GB
script_dir = os.path.dirname(__file__)
tls_proxy = None
# Módulo de Detección de Escaneos y Seguridad
SCAN_WINDOW = 60
MAX_CONNECTIONS_IN_WINDOW = 20
MAX_FAILED_HANDSHAKES = 2
MAX_BANNER_GRABS = 2
TEMP_BAN_DURATION = 1000
rejection_counters = defaultdict(lambda: {'count': 0, 'last_log': 0})
rejection_lock = threading.Lock()
REJECTION_LOG_THRESHOLD = 60
connection_behavior = defaultdict(lambda: {
'timestamps': deque(maxlen=MAX_CONNECTIONS_IN_WINDOW * 2),
'failed_handshakes': 0,
'banner_grabs': 0
})
behavior_lock = threading.Lock()
temp_bans = {}
temp_bans_lock = threading.Lock()
from collections import defaultdict
rejection_counters = defaultdict(lambda: {
"count": 0,
"suggested": False
})
def log_rejection_smart(ip, reason):
try:
with rejection_lock:
# Inicializa datos por IP si no existen
data = rejection_counters.setdefault(ip, {
"count": 0,
"relaxed_printed": 0, # cuántas veces imprimió modo relajado
"suggested": False # si ya mostró sugerencia
})
# Aumenta contador
data["count"] += 1
count = data["count"]
# Log interno siempre
logging.info(f"Conexión #{count} rechazada de {ip} ({reason})")
# ===== MODO RELAJADO =====
if VERBOSE_MODE == 2:
if data["relaxed_printed"] < 3:
print(f"Conexión #{count} rechazada de {ip} ({reason})")
data["relaxed_printed"] += 1
elif data["relaxed_printed"] == 3:
print(f"IP {ip}: Suprimiendo logs posteriores")
data["relaxed_printed"] += 1 # solo imprime esta línea una vez
# ===== MODO SILENCIOSO =====
elif VERBOSE_MODE == 1:
if count == 1:
print(f"Conexión rechazada de {ip} ({reason})")
# ===== SUGERENCIA SOLO UNA VEZ + CADA 1000 =====
if (not data["suggested"]) or count % 1000 == 0:
msg = (
f"IP {ip} rechazada {count} veces ({reason}). "
f"Bloqueo sugerido: sudo iptables -A INPUT -s {ip} -j DROP"
)
logging.warning(msg)
print(f"{YELLOW}{msg}{RESET}")
data["suggested"] = True
except Exception as e:
logging.exception(f"Error en log_rejection_smart para {ip}: {e}")
def check_suspicious_behavior(ip):
"""Analiza el comportamiento de una IP y la bloquea temporalmente si es sospechoso."""
try:
with behavior_lock, temp_bans_lock:
now = time.time()
if ip in temp_bans and temp_bans[ip] > now:
return
behavior = connection_behavior[ip]
recent_timestamps = [ts for ts in behavior['timestamps'] if now - ts <= SCAN_WINDOW]
if len(recent_timestamps) > MAX_CONNECTIONS_IN_WINDOW:
msg = f"DETECCIÓN DE ESCANEO: Posible Connect Scan/Flood desde {ip} ({len(recent_timestamps)} conexiones en {SCAN_WINDOW}s)."
logging.warning(msg)
temp_bans[ip] = now + TEMP_BAN_DURATION
logging.error(f"SEGURIDAD: IP {ip} bloqueada temporalmente por {TEMP_BAN_DURATION} segundos.")
behavior['timestamps'].clear()
behavior['failed_handshakes'] = 0
behavior['banner_grabs'] = 0
return
if behavior['failed_handshakes'] > MAX_FAILED_HANDSHAKES:
msg = f"DETECCIÓN DE ESCANEO: Posible escaneo de protocolo desde {ip} ({behavior['failed_handshakes']} handshakes fallidos)."
logging.warning(msg)
temp_bans[ip] = now + TEMP_BAN_DURATION
logging.error(f"SEGURIDAD: IP {ip} bloqueada temporalmente por {TEMP_BAN_DURATION} segundos.")
behavior['timestamps'].clear()
behavior['failed_handshakes'] = 0
return
if behavior['banner_grabs'] > MAX_BANNER_GRABS:
msg = f"DETECCIÓN DE ESCANEO: Posible Banner Grabbing desde {ip} ({behavior['banner_grabs']} desconexiones tras recibir banner)."
logging.warning(msg)
temp_bans[ip] = now + TEMP_BAN_DURATION
logging.error(f"SEGURIDAD: IP {ip} bloqueada temporalmente por {TEMP_BAN_DURATION} segundos.")
behavior['timestamps'].clear()
behavior['banner_grabs'] = 0
return
except Exception as e:
logging.exception(f"Error en check_suspicious_behavior para {ip}: {e}")
connection_attempts = defaultdict(lambda: deque(maxlen=10))
MAX_ATTEMPTS = 5
WINDOW_TIME = 10
blocked_ips = set()
BLOCKED_IPS_FILE = os.path.join(script_dir, "blacklist_ips.json")
blocked_ips_lock = threading.Lock()
SERVICE_BANNER = "SSH-2.0-9.39 FlowSsh: Bitvise SSH Server (WinSSHD) 9.39: free only for personal non-commercial use"
SERVICE_BANNER_FILE = os.path.join(script_dir, "sVbanner.txt")
# ==================== SECURITY HARDENING CONSTANTS ====================
# Protección contra downgrade criptográfico
MIN_AES_KEY_SIZE = 32 # Rechazar claves AES menores a 256 bits (AES-256)
# ==================== HMAC CLIENT AUTHENTICATION ====================
# Token pre-compartido para autenticar clientes en el handshake ECDHE.
# Se genera aleatoriamente en cada inicio (12 chars hex). Pasar al cliente con --hmac
HMAC_PRE_SHARED_SECRET: bytes = secrets.token_bytes(20) # 20 bytes → token hex de 40 chars
NO_SECURE_MODE = False # Si True, acepta cualquier cliente ECDHE sin verificar HMAC
# Protección contra DoS
MAX_MESSAGE_SIZE = 10 * 1024 * 1024 # 10MB máximo por mensaje
# Protección contra heartbeat flood
HEARTBEAT_MIN_INTERVAL = 3.0 # Mínimo 3 segundos entre heartbeats
# Protección contra timing attacks
RESPONSE_JITTER_MIN_MS = 10 # Jitter mínimo en milisegundos
RESPONSE_JITTER_MAX_MS = 50 # Jitter máximo en milisegundos
# ==================== PASSPHRASE PARA CLAVE PERSISTENTE ====================
# Se pide en tiempo de arranque cuando se usa -p; nunca se almacena en disco.
ECDHE_KEY_PASSPHRASE: bytes | None = None # se rellena en main()
# ==================== SPA / PORT-KNOCKING ====================
# Dos modos (configurados por argumentos):
#
# "spa" → un solo paquete UDP firmado con HMAC-SHA256
# token = HMAC(HMAC_SECRET, f"{ip}:{ventana_30s}")
# Anti-replay por ventana de tiempo + dedup en memoria
#
# "knock" → secuencia de puertos UDP en orden estricto dentro de N segundos
# Si la secuencia se completa, la IP queda autorizada
#
# En ambos modos, la IP autorizada tiene un TTL de SPA_AUTHZ_TTL segundos.
# Si SPA_ENABLED=False, no se aplica ningún control de pre-autenticación.
SPA_ENABLED = False # se activa con --spa
SPA_MODE = "spa" # "spa" | "knock"
SPA_UDP_PORT = 7331 # puerto UDP donde escucha el daemon SPA
KNOCK_SEQUENCE = [7001, 7002, 7003] # puertos para modo knock (configurable)
KNOCK_TIMEOUT = 10.0 # segundos para completar la secuencia
SPA_AUTHZ_TTL = 60 # segundos que la IP queda autorizada tras knock/spa
# ==================== BERRYTRANSFER MODE ====================
# Modo transfer-only tipo scp. Solo activo cuando el servidor
# arranca con --berrytransfer. Los clientes normales son rechazados.
BERRYTRANSFER_MODE = False
BERRYTRANSFER_ROOT = "./berry_transfers"
BT_AUTO_CONFIRM = False # --auto-confirm: aprueba descargas automáticamente
# ── Sistema de confirmación de descargas ─────────────────────
# Cada GET del cliente crea una entrada aquí; el operador
# escribe "confirm <ID>" o "deny <ID>" en la shell BT.
import threading as _bt_threading
bt_pending_confirms: dict = {} # ID -> {"event","approved","ip","filename","size"}
bt_pending_lock = _bt_threading.Lock()
bt_confirm_counter_val = 0
bt_confirm_counter_lock = _bt_threading.Lock()
def _bt_next_confirm_id() -> str:
global bt_confirm_counter_val
with bt_confirm_counter_lock:
bt_confirm_counter_val += 1
return f"DL{bt_confirm_counter_val}"
# ── Log de transferencias ────────────────────────────────────
# Formato CSV-like con columnas fijas para fácil lectura y parseo:
# TIMESTAMP | OP | STATUS | IP | HOST | FILE | SIZE | SPEED | ELAPSED | NOTE
# ── Ruta del log de transferencias BerryTransfer ────────────────────────────
# Siempre en logs/ (mismo directorio que sessions.jsonl y BlackBerryC2_enc.log)
BT_LOG_PATH = os.path.join(script_dir, "logs", "bt_transfer.jsonl")
def bt_log_transfer(direction: str, ip: str, hostname: str,
filename: str, size: int, ok: bool, extra: str = "",
elapsed: float = 0.0):
"""
Guarda un evento de transferencia en logs/bt_transfer.jsonl.
Formato de cada línea: JSON compacto (una entrada por línea = JSONL).
Si _SESSION_LOG_KEY está activo cada línea se cifra con AES-256-GCM antes
de escribirse — idéntico al mecanismo de sessions.jsonl.
Campos del registro:
ts – timestamp ISO "2026-02-23 21:39:13"
op – "GET" | "PUT"
status – "OK" | "FAIL" | "DENY" | "CANC" | "404"
ip – IP del cliente
host – hostname del cliente
file – nombre del archivo / directorio
size – tamaño en bytes (-1 = desconocido)
elapsed – segundos de transferencia (0.0 = N/A)
speed_bps – bytes/s (-1 = N/A)
note – nota libre (extra)
"""
try:
log_path = BT_LOG_PATH
os.makedirs(os.path.dirname(log_path), exist_ok=True)
if ok:
status = "OK"
elif extra in ("denied", "operator_denied", "denied_or_timeout"):
status = "DENY"
elif extra == "not_found":
status = "404"
elif extra == "cancelled":
status = "CANC"
else:
status = "FAIL"
speed_bps = int(size / elapsed) if (ok and elapsed > 0 and size > 0) else -1
rec = {
"ts": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"op": "GET" if direction == "download" else "PUT",
"status": status,
"ip": ip,
"host": hostname,
"file": filename,
"size": size if size > 0 else -1,
"elapsed": round(elapsed, 2) if elapsed > 0 else 0.0,
"speed_bps": speed_bps,
"note": extra if extra else "-",
}
line = json.dumps(rec, ensure_ascii=False)
# ── Cifrado AES-256-GCM si hay clave activa ──────────────────────────
if _SESSION_LOG_KEY:
_nonce = secrets.token_bytes(12)
_ciph = AESGCM(_SESSION_LOG_KEY).encrypt(_nonce, line.encode('utf-8'), None)
line = base64.b64encode(_nonce + _ciph).decode('ascii')
with open(log_path, 'a', encoding='utf-8') as f:
f.write(line + "\n")
except Exception as e:
logging.debug(f"[BerryTransfer] bt_log_transfer error: {e}")
# ============================================================
# Estado en memoria (thread-safe)
spa_authorized_ips: dict[str, float] = {} # ip -> expiry_timestamp
spa_authz_lock = threading.Lock()
spa_used_tokens: dict = {} # anti-replay: {token_key: timestamp}
spa_tokens_lock = threading.Lock()
knock_partial: dict[str, dict] = {} # ip -> {idx, ts} progreso knock
knock_partial_lock = threading.Lock()
# ============================================================
# BACKGROUND TRANSFER MANAGER
# ============================================================
class BackgroundTransfer:
"""Representa una transferencia de archivo en background."""
def __init__(self, tid: str, direction: str, session_cid: int,
remote_name: str, local_path: str):
self.id = tid # "T1", "T2", …
self.direction = direction # "get" | "put"
self.session_cid = session_cid
self.remote_name = remote_name # ruta en el cliente
self.local_path = local_path # ruta local final
self.partial_path = local_path + ".partial" # fichero temporal
self.resume_file = local_path + ".resume" # JSON con metadatos
self.total_bytes = 0
self.bytes_done = 0
self.status = "pending" # pending|running|done|failed|cancelled
self.start_time: float | None = None
self.end_time: float | None = None
self.thread: threading.Thread | None = None
self.cancel_evt = threading.Event()
self.error: str | None = None
# ── helpers ──────────────────────────────────────────────
def speed_str(self) -> str:
if not self.start_time or not self.bytes_done:
return "—"
elapsed = (self.end_time or time.time()) - self.start_time
if elapsed <= 0:
return "—"
return format_speed(self.bytes_done / elapsed)
def eta_str(self) -> str:
if not self.start_time or self.total_bytes <= 0:
return "—"
elapsed = time.time() - self.start_time
if elapsed <= 0 or self.bytes_done <= 0:
return "—"
rate = self.bytes_done / elapsed
return estimate_time_remaining(self.total_bytes - self.bytes_done, rate)
def pct(self) -> float:
if self.total_bytes <= 0:
return 0.0
return min(100.0, self.bytes_done / self.total_bytes * 100)
def status_line(self) -> str:
"""Línea de resumen para el comando 'transfers'."""
direction_arrow = "⬇ GET" if self.direction == "get" else "⬆ PUT"
name = os.path.basename(self.remote_name)
sz = f"{format_bytes(self.bytes_done)}/{format_bytes(self.total_bytes)}"
if self.status == "running":
bar_w = 20
filled = int(bar_w * self.pct() / 100)
bar = "█" * filled + "░" * (bar_w - filled)
return (f" [{self.id}] #{self.session_cid} {direction_arrow} {name}"
f" |{bar}| {self.pct():.0f}% {sz}"
f" {self.speed_str()} ETA {self.eta_str()}")
elif self.status == "done":
elapsed = (self.end_time or time.time()) - (self.start_time or time.time())
return (f" [{self.id}] #{self.session_cid} {direction_arrow} {name}"
f" ✓ {format_bytes(self.total_bytes)}"
f" en {elapsed:.1f}s ({self.speed_str()})")
elif self.status == "failed":
return (f" [{self.id}] #{self.session_cid} {direction_arrow} {name}"
f" ✗ {self.error or 'error desconocido'}")
elif self.status == "cancelled":
return (f" [{self.id}] #{self.session_cid} {direction_arrow} {name}"
f" ⊘ cancelado ({format_bytes(self.bytes_done)} transferidos)")
return f" [{self.id}] #{self.session_cid} {direction_arrow} {name} ({self.status})"
def save_resume_meta(self):
"""Guarda metadatos de reanudación."""
try:
meta = {
"id": self.id,
"direction": self.direction,
"session_cid": self.session_cid,
"remote_name": self.remote_name,
"local_path": self.local_path,
"total_bytes": self.total_bytes,
"bytes_done": self.bytes_done,
"timestamp": time.time(),
}
with open(self.resume_file, 'w') as f:
json.dump(meta, f, indent=2)
except Exception as e:
logging.debug(f"[BG] Error guardando .resume: {e}")
def load_resume_offset(self) -> int:
"""Devuelve el offset para reanudar (0 si no hay fichero parcial)."""
try:
if os.path.exists(self.partial_path):
return os.path.getsize(self.partial_path)
except Exception:
pass
return 0
def cleanup_resume_files(self):
for path in (self.partial_path, self.resume_file):
try:
if os.path.exists(path):
os.remove(path)
except Exception:
pass
# Estado global de transferencias en background
_bg_transfers: dict[str, BackgroundTransfer] = {}
_bg_transfers_lock = threading.Lock()
_bg_transfer_counter = 0
_bg_counter_lock = threading.Lock()
# ── Cola thread-safe para mensajes de workers en segundo plano ────────────
# Usada cuando patch_stdout NO está activo (fallback input() básico).
_bg_log_queue: Queue = Queue(maxsize=500)
def bg_print(msg: str) -> None:
"""
Print thread-safe desde workers de background.
- Con prompt_toolkit activo: print() directo (patch_stdout lo maneja).
- Sin prompt_toolkit: encola para que interactive_shell lo muestre antes del prompt.
"""
if PROMPT_TOOLKIT_AVAILABLE:
# patch_stdout (activo dentro de interactive_shell) intercepta sys.stdout
# y muestra el mensaje ENCIMA del prompt sin corromperlo.
print(msg)
else:
try:
_bg_log_queue.put_nowait(msg)
except Exception:
pass # Cola llena: descartar antes que bloquear el worker
def _drain_bg_log() -> None:
"""Drena y muestra mensajes en cola. Solo para el fallback sin prompt_toolkit."""
while True:
try:
msg = _bg_log_queue.get_nowait()
print(msg)
except Exception:
break
def _bg_next_id() -> str:
global _bg_transfer_counter
with _bg_counter_lock:
_bg_transfer_counter += 1
return f"T{_bg_transfer_counter}"
def bg_register(xfer: BackgroundTransfer):
with _bg_transfers_lock:
_bg_transfers[xfer.id] = xfer
def bg_get(tid: str) -> BackgroundTransfer | None:
with _bg_transfers_lock:
return _bg_transfers.get(tid)
def bg_all() -> list[BackgroundTransfer]:
with _bg_transfers_lock:
return list(_bg_transfers.values())
def _bg_get_worker(xfer: BackgroundTransfer, session):
"""
Worker para GET en background.
Usa bg_get_lock para serializar — solo un GET activo por sesión.
"""
sock = session.socket
aes_key = session.aes_key
xfer.status = "running"
xfer.start_time = time.time()
acquired = session.bg_get_lock.acquire(timeout=FILE_MAX_TIMEOUT)
if not acquired:
xfer.status = "failed"
xfer.error = "No se pudo adquirir bg_get_lock"
bg_print(f"\n\033[91m[{xfer.id}] ✗ GET '{xfer.remote_name}' — otra transferencia activa bloqueó el inicio\033[0m")
return
try:
local_path = xfer.local_path
# ── Preparar destino y evento ────────────────────────────────────
session.file_error = None
session.expected_file = os.path.basename(xfer.remote_name)
session.expected_file_dest = local_path
session.file_event.clear()
session.file_result = None
# ── Enviar GET_FILE al cliente ───────────────────────────────────
cmd = f"GET_FILE {xfer.remote_name}"
if not send_encrypted_message(sock, cmd, aes_key, timeout=10, session=session):
raise RuntimeError("No se pudo enviar GET_FILE al cliente")
# ── Esperar resultado de handle_client ───────────────────────────
if not session.file_event.wait(timeout=FILE_MAX_TIMEOUT):
raise RuntimeError(f"Timeout esperando respuesta del cliente")
if not session.file_result:
err = getattr(session, 'file_error', None) or "Transferencia fallida"
raise RuntimeError(err)
# ── Éxito ────────────────────────────────────────────────────────
xfer.status = "done"
xfer.end_time = time.time()
elapsed = xfer.end_time - xfer.start_time
try:
size = os.path.getsize(xfer.local_path)
except Exception:
size = 0
xfer.total_bytes = size
xfer.bytes_done = size
avg_speed = size / elapsed if elapsed > 0 else 0
bg_print(f"\n\033[92m[{xfer.id}] ✓ GET '{os.path.basename(xfer.remote_name)}' completado "
f"— {format_bytes(size)} en {elapsed:.1f}s "
f"({format_speed(avg_speed)}) → {xfer.local_path}\033[0m")
except Exception as e:
xfer.status = "failed"
xfer.error = str(e)
xfer.end_time = time.time()
bg_print(f"\n\033[91m[{xfer.id}] ✗ GET '{xfer.remote_name}' falló — {e}\033[0m")
logging.error(f"[BG-GET {xfer.id}] Error: {e}")
finally:
session.expected_file = None
session.expected_file_dest = None
session.file_error = None
session.bg_get_lock.release()
def _bg_put_worker(xfer: BackgroundTransfer, session):
"""
Worker para PUT en background.
PUT solo ESCRIBE al socket (no lee), por lo que no compite con
handle_client que solo lee. No necesita transfer_hijack.
Envía SIZE + chunks directamente; espera confirmación via response_queue.
"""
sock = session.socket
aes_key = session.aes_key
xfer.status = "running"
xfer.start_time = time.time()
try:
if not os.path.isfile(xfer.local_path):
raise RuntimeError(f"Archivo no encontrado: {xfer.local_path}")
xfer.total_bytes = os.path.getsize(xfer.local_path)
timeout_dyn = calculate_file_timeout(xfer.total_bytes)
# Calcular hash del archivo
sha = hashlib.sha256()
with open(xfer.local_path, 'rb') as fh:
for chunk in iter(lambda: fh.read(65536), b""):
sha.update(chunk)
file_hash = sha.hexdigest()
# Enviar header SIZE
header = f"SIZE {xfer.total_bytes} {file_hash}"
if not send_encrypted_message(sock, header, aes_key,
timeout=timeout_dyn, session=session):
raise RuntimeError("Error enviando header SIZE")
# ── Enviar chunks ─────────────────────────────────────
bytes_sent = 0
with open(xfer.local_path, 'rb') as fh:
while True:
if xfer.cancel_evt.is_set():
xfer.status = "cancelled"
bg_print(f"\n\033[93m[{xfer.id}] ⊘ PUT '{os.path.basename(xfer.local_path)}' cancelado "
f"({format_bytes(bytes_sent)} enviados)\033[0m")
return
chunk = fh.read(CHUNK_SIZE)
if not chunk:
break
flag = 0
data = chunk
try:
comp = zlib.compress(chunk, level=COMPRESSION_LEVEL)
if len(comp) < len(chunk):
data = comp
flag = 1
except Exception:
pass
aesgcm = AESGCM(aes_key)
nonce = os.urandom(12)
ct = aesgcm.encrypt(nonce, data, None)
packet = bytes([flag]) + nonce + ct
full = struct.pack('!I', len(packet)) + packet
sock.settimeout(timeout_dyn)
sock.sendall(full)
bytes_sent += len(chunk)
xfer.bytes_done = bytes_sent
# Esperar confirmación del cliente via response_queue (handle_client la leerá)
try:
conf = session.response_queue.get(timeout=60)
except Exception:
conf = None
xfer.status = "done"
xfer.end_time = time.time()
elapsed = xfer.end_time - xfer.start_time
avg_speed = bytes_sent / elapsed if elapsed > 0 else 0
bg_print(f"\n\033[92m[{xfer.id}] ✓ PUT '{os.path.basename(xfer.local_path)}' completado "
f"— {format_bytes(bytes_sent)} en {elapsed:.1f}s "
f"({format_speed(avg_speed)})\033[0m")
if conf:
bg_print(f"\033[92m[{xfer.id}] Confirmación: {conf.strip()}\033[0m")
except Exception as e:
xfer.status = "failed"
xfer.error = str(e)
xfer.end_time = time.time()
bg_print(f"\n\033[91m[{xfer.id}] ✗ PUT '{xfer.remote_name}' falló — {e}\033[0m")
logging.error(f"[BG-PUT {xfer.id}] Error: {e}")
def bg_start_get(session, cid: int, remote_name: str, local_path: str) -> BackgroundTransfer:
"""Crea y arranca una transferencia GET en background."""
tid = _bg_next_id()
xfer = BackgroundTransfer(tid, "get", cid, remote_name, local_path)
bg_register(xfer)
t = threading.Thread(
target=_bg_get_worker,
args=(xfer, session),
daemon=True,
name=f"BB-BG-GET-{tid}"
)
xfer.thread = t
t.start()
return xfer
def bg_start_put(session, cid: int, local_path: str, remote_name: str) -> BackgroundTransfer:
"""Crea y arranca una transferencia PUT en background."""
tid = _bg_next_id()
xfer = BackgroundTransfer(tid, "put", cid, remote_name, local_path)
bg_register(xfer)
t = threading.Thread(
target=_bg_put_worker,
args=(xfer, session),
daemon=True,
name=f"BB-BG-PUT-{tid}"
)
xfer.thread = t
t.start()
return xfer
def bg_cancel(tid: str) -> bool:
"""Cancela una transferencia por ID. Devuelve True si existía y estaba activa."""
xfer = bg_get(tid)
if not xfer:
return False
if xfer.status == "running":
xfer.cancel_evt.set()
return True
return False
# ──────────────────────────────────────────────────────────────────────────
# WORKER RECURSIVO EN BACKGROUND (usa transfer_hijack completo)
# ──────────────────────────────────────────────────────────────────────────
def _bg_recursive_worker(xfer_stub: BackgroundTransfer, session,
remote_files: list, local_base: str, target_norm: str):
"""
Worker para descarga recursiva. Usa bg_get_lock para serializar —
solo un GET activo por sesión; evita que dos workers pisen expected_file_dest.
"""
sock = session.socket
aes_key = session.aes_key
tid = xfer_stub.id
total = len(remote_files)
downloaded = 0
failed = 0
failed_list = []
xfer_stub.status = "running"
xfer_stub.start_time = time.time()
xfer_stub.total_bytes = total
acquired = session.bg_get_lock.acquire(timeout=60)
if not acquired:
xfer_stub.status = "failed"
xfer_stub.error = "Otra descarga activa bloquea el inicio"
bg_print(f"\n\033[91m[{xfer_stub.id}] ✗ Recursivo abortado — otra descarga GET activa en esta sesión\033[0m")
return
try:
for idx, remote_file in enumerate(remote_files, 1):
# ── Cancelación ──────────────────────────────────────────────────
if xfer_stub.cancel_evt.is_set():
bg_print(f"\n\033[93m[{tid}] ⊘ Recursivo cancelado "
f"({downloaded}/{total} completados)\033[0m")
xfer_stub.status = "cancelled"
xfer_stub.end_time = time.time()
return
# ── Calcular ruta local ──────────────────────────────────────────
if (remote_file.startswith(target_norm + '/') or
remote_file.startswith(target_norm + os.sep)):
rel_path = remote_file[len(target_norm):].lstrip('/\\')
else:
rel_path = os.path.relpath(remote_file, target_norm)
if rel_path.startswith('..'):
rel_path = os.path.basename(remote_file)
local_file = os.path.join(local_base, rel_path)
try:
os.makedirs(os.path.dirname(local_file), exist_ok=True)
except Exception:
pass
# ── Descargar via file_event (sin hijack) ────────────────────────
try:
session.file_error = None
session.expected_file = os.path.basename(local_file)
session.expected_file_dest = local_file
session.file_event.clear()
session.file_result = None
if not send_encrypted_message(sock, f"GET_FILE {remote_file}",
aes_key, timeout=10, session=session):
raise RuntimeError("No se pudo enviar GET_FILE")
dyn_timeout = FILE_MAX_TIMEOUT
if not session.file_event.wait(timeout=dyn_timeout):
raise RuntimeError(f"Timeout esperando {rel_path}")
if not session.file_result:
err = getattr(session, 'file_error', None) or f"Transferencia fallida"
raise RuntimeError(err)
downloaded += 1
xfer_stub.bytes_done = downloaded
except Exception as e:
if xfer_stub.cancel_evt.is_set():
bg_print(f"\n\033[93m[{tid}] ⊘ Recursivo cancelado "
f"({downloaded}/{total} completados)\033[0m")
xfer_stub.status = "cancelled"
xfer_stub.end_time = time.time()
return
failed_list.append(rel_path)
failed += 1
logging.warning(f"[{tid}] ✗ {rel_path}: {e}")
try:
if os.path.exists(local_file):
os.remove(local_file)
except Exception:
pass
finally:
session.expected_file = None
session.expected_file_dest = None
session.file_error = None
# ── Resumen final ────────────────────────────────────────────────────
xfer_stub.end_time = time.time()
elapsed = xfer_stub.end_time - xfer_stub.start_time
if failed == 0:
xfer_stub.status = "done"
bg_print(f"\n\033[92m[{tid}] ✓ Recursivo completado: "
f"{downloaded}/{total} archivos en {elapsed:.1f}s "
f"→ {local_base}\033[0m")
else:
xfer_stub.status = "failed"
bg_print(f"\n\033[93m[{tid}] ⚠ Recursivo completado con errores: "
f"{downloaded} ok / {failed} fallidos en {elapsed:.1f}s "
f"→ {local_base}\033[0m")
if failed_list:
bg_print(f"\033[91m[{tid}] Fallidos: "
+ ", ".join(failed_list[:10])
+ ("..." if len(failed_list) > 10 else "")
+ "\033[0m")
except Exception as e:
xfer_stub.status = "failed"
xfer_stub.error = str(e)
xfer_stub.end_time = time.time()
bg_print(f"\n\033[91m[{tid}] ✗ Descarga recursiva falló: {e}\033[0m")
logging.error(f"[BG-RECUR {tid}] Error: {e}")
finally:
session.expected_file = None
session.expected_file_dest = None
if acquired:
session.bg_get_lock.release()
def print_transfers(show_done=True):
"""Imprime la tabla de transferencias activas y recientes."""
all_xfers = bg_all()
if not all_xfers:
print(f"\033[93m Sin transferencias registradas\033[0m")
return
running = [x for x in all_xfers if x.status == "running"]
done = [x for x in all_xfers if x.status in ("done", "failed", "cancelled")]
if running:
print(f"\033[96m ── En progreso ─────────────────────────────────────────\033[0m")
for x in running:
print(f"\033[96m{x.status_line()}\033[0m")
if show_done and done:
print(f"\033[90m ── Completadas ──────────────────────────────────────────\033[0m")
for x in done[-10:]: # Mostrar solo las últimas 10
color = "\033[92m" if x.status == "done" else ("\033[91m" if x.status == "failed" else "\033[93m")
print(f"{color}{x.status_line()}\033[0m")
if not running and not done:
print(f"\033[93m Sin transferencias\033[0m")
def try_resume_transfer(session, cid: int, local_path: str) -> bool:
"""
Comprueba si existe un .partial + .resume para `local_path`
y si es así, lanza automáticamente la reanudación.
Devuelve True si se inició la reanudación.
"""
resume_file = local_path + ".resume"
partial_file = local_path + ".partial"
if not (os.path.exists(resume_file) and os.path.exists(partial_file)):
return False
try:
with open(resume_file) as f:
meta = json.load(f)
remote_name = meta.get("remote_name", "")
direction = meta.get("direction", "get")
if not remote_name:
return False
if direction == "get":
xfer = bg_start_get(session, cid, remote_name, local_path)
print(f"\033[96m[{xfer.id}] Reanudando GET '{remote_name}' en background\033[0m")
else:
xfer = bg_start_put(session, cid, local_path, remote_name)
print(f"\033[96m[{xfer.id}] Reanudando PUT '{remote_name}' en background\033[0m")
return True
except Exception as e:
logging.debug(f"Error leyendo .resume: {e}")
return False
# ============================================================
# FIN BACKGROUND TRANSFER MANAGER
# ============================================================
# ==================== PROTECCIÓN CONTRA COMMAND FLOOD ====================
MAX_RESPONSE_QUEUE_SIZE = 1000 # Máximo de respuestas en cola antes de desechar
MAX_COMMANDS_PER_SECOND = 50 # Máximo de comandos por segundo permitidos
COMMAND_FLOOD_WINDOW = 1.0 # Ventana de tiempo para medir rate (1 segundo)
MAX_FLOOD_VIOLATIONS = 3 # Número de violaciones antes de desconectar
# ==================== ORIGINAL TIMEOUTS ====================
HEARTBEAT_TIMEOUT = 180
COMMAND_TIMEOUT = 60
INTERACTIVE_TIMEOUT = 300
os.makedirs(f"{script_dir}/logs", exist_ok=True)
TEMP_HISTORY_FILE = None
# Variable global para mantener el directorio de trabajo actual
CURRENT_WORKING_DIR = os.getcwd()
def calculate_file_timeout(file_size_bytes):
"""Calcula timeout dinámico basado en tamaño de archivo."""
try:
size_mb = file_size_bytes / (1024 * 1024)
timeout = FILE_TIMEOUT_BASE + (size_mb * FILE_TIMEOUT_PER_MB)
timeout = max(FILE_MIN_TIMEOUT, min(timeout, FILE_MAX_TIMEOUT))
logging.debug(f"Timeout calculado para {format_bytes(file_size_bytes)}: {timeout:.1f}s")
return timeout
except Exception as e:
logging.exception(f"Error calculando timeout: {e}")
return FILE_TIMEOUT_BASE
def format_bytes(bytes_count):
"""Formatea bytes a formato legible"""