-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsecurityaudit_win.py
More file actions
1342 lines (1172 loc) Β· 60.8 KB
/
securityaudit_win.py
File metadata and controls
1342 lines (1172 loc) Β· 60.8 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
"""
ββββββββββββββββββββββββββββββββββββββββββββββββ
β WinDNA Security Audit Engine v1.0 β
β Windows Security & Asset Assessment β
β βββββββββββββββββββββββββββββββββββββββββββββββ£
β Author: cyberspartan77 β
ββββββββββββββββββββββββββββββββββββββββββββββββ
"""
import subprocess
import json
import os
import re
import sys
import platform
import datetime
import html as html_mod
from pathlib import Path
# βββββββββββββββββββββββββββββββββββββββββββββββ
# HELPERS
# βββββββββββββββββββββββββββββββββββββββββββββββ
BOLD = "\033[1m"
DIM = "\033[2m"
RESET = "\033[0m"
GREEN = "\033[92m"
RED = "\033[91m"
YELLOW = "\033[93m"
CYAN = "\033[96m"
def spinner_line(msg):
sys.stdout.write(f"\r {YELLOW}~{RESET} {msg}... ")
sys.stdout.flush()
def done_line(msg):
sys.stdout.write(f"\r {GREEN}+{RESET} {msg} \n")
sys.stdout.flush()
def _run(cmd, timeout=30):
try:
r = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=timeout)
return r.stdout.strip()
except Exception:
return ""
def _run_ps(cmd, timeout=30):
try:
r = subprocess.run(
["powershell", "-NoProfile", "-Command", cmd],
capture_output=True, text=True, timeout=timeout
)
return r.stdout.strip()
except Exception:
return ""
def _run_lines(cmd, timeout=30):
out = _run(cmd, timeout)
return [l for l in out.splitlines() if l.strip()] if out else []
def _run_ps_lines(cmd, timeout=30):
out = _run_ps(cmd, timeout)
return [l for l in out.splitlines() if l.strip()] if out else []
def _ps_json(cmd, timeout=30):
"""Run PowerShell command and parse JSON output."""
out = _run_ps(f"{cmd} | ConvertTo-Json -Depth 5 -Compress", timeout)
if not out:
return None
try:
return json.loads(out)
except json.JSONDecodeError:
return None
def is_admin():
try:
import ctypes
return ctypes.windll.shell32.IsUserAnAdmin() != 0
except Exception:
return False
# βββββββββββββββββββββββββββββββββββββββββββββββ
# CONSTANTS
# βββββββββββββββββββββββββββββββββββββββββββββββ
SUSPICIOUS_PORTS = [4444, 5555, 6666, 1337, 31337, 8888, 9999, 12345, 54321, 6667, 6697]
KNOWN_MALWARE_NAMES = [
"mimikatz", "lazagne", "procdump", "psexec", "cobaltstrike",
"meterpreter", "empire", "rubeus", "sharphound", "bloodhound",
"netcat", "ncat", "powercat", "invoke-obfuscation", "certutil",
]
CRYPTO_MINER_NAMES = [
"xmrig", "minerd", "ethminer", "cgminer", "bfgminer",
"cpuminer", "nicehash", "phoenixminer", "t-rex", "nbminer",
]
# βββββββββββββββββββββββββββββββββββββββββββββββ
# SECTION 1: ASSET INTELLIGENCE
# βββββββββββββββββββββββββββββββββββββββββββββββ
def audit_asset_intelligence():
spinner_line("Asset Intelligence β Hardware")
data = {}
# CPU
cpu = _ps_json("Get-CimInstance Win32_Processor | Select-Object Name, NumberOfCores, NumberOfLogicalProcessors, MaxClockSpeed")
if isinstance(cpu, list):
cpu = cpu[0] if cpu else {}
data["cpu"] = cpu or {"Name": "Unknown", "NumberOfCores": 0, "NumberOfLogicalProcessors": 0}
# RAM
ram_raw = _run_ps("(Get-CimInstance Win32_PhysicalMemory | Measure-Object Capacity -Sum).Sum")
try:
data["ram_gb"] = round(int(ram_raw) / (1024**3), 1)
except (ValueError, TypeError):
data["ram_gb"] = 0
# GPU
spinner_line("Asset Intelligence β GPU")
gpu = _ps_json("Get-CimInstance Win32_VideoController | Select-Object Name, DriverVersion, AdapterRAM")
if isinstance(gpu, dict):
gpu = [gpu]
data["gpu"] = gpu or []
# Storage
spinner_line("Asset Intelligence β Storage")
volumes = _ps_json("Get-Volume | Where-Object DriveLetter | Select-Object DriveLetter, FileSystemType, @{N='SizeGB';E={[math]::Round($_.Size/1GB,1)}}, @{N='FreeGB';E={[math]::Round($_.SizeRemaining/1GB,1)}}")
if isinstance(volumes, dict):
volumes = [volumes]
data["storage"] = {"volumes": volumes or []}
disks = _ps_json("Get-PhysicalDisk | Select-Object FriendlyName, MediaType, @{N='SizeGB';E={[math]::Round($_.Size/1GB,1)}}, HealthStatus")
if isinstance(disks, dict):
disks = [disks]
data["storage"]["physical_disks"] = disks or []
# Battery
spinner_line("Asset Intelligence β Battery")
batt = _ps_json("Get-CimInstance Win32_Battery | Select-Object EstimatedChargeRemaining, BatteryStatus, DesignCapacity, FullChargeCapacity")
data["battery"] = batt if batt else {"present": False}
# Display
spinner_line("Asset Intelligence β Display")
display = _ps_json("Get-CimInstance Win32_VideoController | Select-Object Name, CurrentHorizontalResolution, CurrentVerticalResolution, CurrentRefreshRate")
if isinstance(display, dict):
display = [display]
data["displays"] = display or []
# USB
spinner_line("Asset Intelligence β Peripherals")
usb = _ps_json("Get-PnpDevice -Class USB -Status OK -ErrorAction SilentlyContinue | Select-Object FriendlyName, InstanceId")
if isinstance(usb, dict):
usb = [usb]
data["usb_devices"] = usb or []
# Bluetooth
bt = _ps_json("Get-PnpDevice -Class Bluetooth -Status OK -ErrorAction SilentlyContinue | Select-Object FriendlyName")
if isinstance(bt, dict):
bt = [bt]
data["bluetooth_devices"] = bt or []
# Printers
printers = _ps_json("Get-Printer -ErrorAction SilentlyContinue | Select-Object Name, DriverName, PortName")
if isinstance(printers, dict):
printers = [printers]
data["printers"] = printers or []
# BIOS / System
spinner_line("Asset Intelligence β System Identity")
bios = _ps_json("Get-CimInstance Win32_BIOS | Select-Object SerialNumber, SMBIOSBIOSVersion, Manufacturer")
data["bios"] = bios or {}
system = _ps_json("Get-CimInstance Win32_ComputerSystem | Select-Object Model, Manufacturer, TotalPhysicalMemory, Domain, PartOfDomain")
data["system"] = system or {}
# Architecture
data["architecture"] = platform.machine()
data["os_version"] = platform.platform()
done_line("Asset Intelligence")
return data
# βββββββββββββββββββββββββββββββββββββββββββββββ
# SECTION 2: USER ACCOUNTS & ACCESS
# βββββββββββββββββββββββββββββββββββββββββββββββ
def audit_user_accounts():
spinner_line("User Accounts & Access")
data = {}
# Local users
users = _ps_json("Get-LocalUser | Select-Object Name, Enabled, LastLogon, PasswordRequired, PasswordLastSet, Description")
if isinstance(users, dict):
users = [users]
data["local_users"] = users or []
# Admins
spinner_line("User Accounts β Admin Group")
admins = _ps_json("Get-LocalGroupMember -Group Administrators -ErrorAction SilentlyContinue | Select-Object Name, ObjectClass, PrincipalSource")
if isinstance(admins, dict):
admins = [admins]
data["admin_group"] = admins or []
# RDP users
rdp = _ps_json("Get-LocalGroupMember -Group 'Remote Desktop Users' -ErrorAction SilentlyContinue | Select-Object Name, ObjectClass")
if isinstance(rdp, dict):
rdp = [rdp]
data["rdp_users"] = rdp or []
# Scheduled tasks (persistence check)
spinner_line("User Accounts β Scheduled Tasks")
tasks = _ps_json("Get-ScheduledTask | Where-Object {$_.State -eq 'Ready' -and $_.TaskPath -notlike '\\Microsoft\\*'} | Select-Object TaskName, TaskPath, State -First 50")
if isinstance(tasks, dict):
tasks = [tasks]
data["scheduled_tasks_non_microsoft"] = tasks or []
done_line("User Accounts & Access")
return data
# βββββββββββββββββββββββββββββββββββββββββββββββ
# SECTION 3: CERTIFICATES
# βββββββββββββββββββββββββββββββββββββββββββββββ
def audit_certificates():
spinner_line("Certificates β Scanning Stores")
data = {"machine_certs": [], "user_certs": [], "expired": [], "expiring_30d": [], "expiring_90d": [], "self_signed": [], "root_cert_count": 0}
now = datetime.datetime.now()
d30 = now + datetime.timedelta(days=30)
d90 = now + datetime.timedelta(days=90)
# Machine certs
mcerts = _ps_json("Get-ChildItem Cert:\\LocalMachine\\My -ErrorAction SilentlyContinue | Select-Object Subject, Issuer, NotAfter, NotBefore, Thumbprint")
if isinstance(mcerts, dict):
mcerts = [mcerts]
data["machine_certs"] = mcerts or []
# User certs
ucerts = _ps_json("Get-ChildItem Cert:\\CurrentUser\\My -ErrorAction SilentlyContinue | Select-Object Subject, Issuer, NotAfter, NotBefore, Thumbprint")
if isinstance(ucerts, dict):
ucerts = [ucerts]
data["user_certs"] = ucerts or []
# Root cert count
root_count = _run_ps("(Get-ChildItem Cert:\\LocalMachine\\Root -ErrorAction SilentlyContinue).Count")
try:
data["root_cert_count"] = int(root_count)
except (ValueError, TypeError):
data["root_cert_count"] = 0
# Analyze all certs
all_certs = (data["machine_certs"] or []) + (data["user_certs"] or [])
for cert in all_certs:
if not isinstance(cert, dict):
continue
not_after = cert.get("NotAfter", "")
subject = cert.get("Subject", "")
issuer = cert.get("Issuer", "")
# Parse date - PowerShell JSON dates can be various formats
exp_date = None
if not_after:
# Try /Date(timestamp)/ format
m = re.search(r'/Date\((\d+)\)', str(not_after))
if m:
exp_date = datetime.datetime.fromtimestamp(int(m.group(1)) / 1000)
else:
for fmt in ["%Y-%m-%dT%H:%M:%S", "%m/%d/%Y %H:%M:%S", "%Y-%m-%d"]:
try:
exp_date = datetime.datetime.strptime(str(not_after)[:19], fmt)
break
except ValueError:
continue
if exp_date:
if exp_date < now:
data["expired"].append({"subject": subject, "expired": str(exp_date)})
elif exp_date < d30:
data["expiring_30d"].append({"subject": subject, "expires": str(exp_date)})
elif exp_date < d90:
data["expiring_90d"].append({"subject": subject, "expires": str(exp_date)})
# Self-signed check
if subject and issuer and subject == issuer:
data["self_signed"].append({"subject": subject})
data["total_certs"] = len(all_certs)
done_line(f"Certificates β {data['total_certs']} found")
return data
# βββββββββββββββββββββββββββββββββββββββββββββββ
# SECTION 4: NETWORK & CONNECTIONS
# βββββββββββββββββββββββββββββββββββββββββββββββ
def audit_network():
spinner_line("Network β Listening Ports")
data = {}
# Listening TCP
listen = _ps_json("""
Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue |
Select-Object LocalAddress, LocalPort, OwningProcess,
@{N='ProcessName';E={(Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue).ProcessName}} |
Sort-Object LocalPort
""")
if isinstance(listen, dict):
listen = [listen]
data["listening_tcp"] = listen or []
# Established TCP
spinner_line("Network β Active Connections")
established = _ps_json("""
Get-NetTCPConnection -State Established -ErrorAction SilentlyContinue |
Select-Object LocalAddress, LocalPort, RemoteAddress, RemotePort, OwningProcess,
@{N='ProcessName';E={(Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue).ProcessName}} |
Sort-Object RemoteAddress
""")
if isinstance(established, dict):
established = [established]
data["established_tcp"] = established or []
# UDP
spinner_line("Network β UDP Endpoints")
udp = _ps_json("""
Get-NetUDPEndpoint -ErrorAction SilentlyContinue |
Select-Object LocalAddress, LocalPort, OwningProcess,
@{N='ProcessName';E={(Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue).ProcessName}} -First 50
""")
if isinstance(udp, dict):
udp = [udp]
data["udp_endpoints"] = udp or []
# Network Adapters
spinner_line("Network β Adapters")
adapters = _ps_json("Get-NetAdapter -ErrorAction SilentlyContinue | Select-Object Name, InterfaceDescription, Status, MacAddress, LinkSpeed")
if isinstance(adapters, dict):
adapters = [adapters]
data["adapters"] = adapters or []
# IP Addresses
ips = _ps_json("Get-NetIPAddress -ErrorAction SilentlyContinue | Where-Object {$_.AddressFamily -eq 'IPv4' -and $_.IPAddress -ne '127.0.0.1'} | Select-Object InterfaceAlias, IPAddress, PrefixLength")
if isinstance(ips, dict):
ips = [ips]
data["ip_addresses"] = ips or []
# VPN
spinner_line("Network β VPN")
vpn = _ps_json("Get-VpnConnection -ErrorAction SilentlyContinue | Select-Object Name, ServerAddress, ConnectionStatus, TunnelType")
if isinstance(vpn, dict):
vpn = [vpn]
data["vpn_connections"] = vpn or []
# Routes
routes = _ps_json("Get-NetRoute -AddressFamily IPv4 -ErrorAction SilentlyContinue | Where-Object {$_.DestinationPrefix -ne '255.255.255.255/32'} | Select-Object DestinationPrefix, NextHop, InterfaceAlias, RouteMetric -First 30")
if isinstance(routes, dict):
routes = [routes]
data["routes"] = routes or []
# SMB Shares
spinner_line("Network β Shares")
shares = _ps_json("Get-SmbShare -ErrorAction SilentlyContinue | Select-Object Name, Path, Description")
if isinstance(shares, dict):
shares = [shares]
data["smb_shares"] = shares or []
# Firewall profiles
fw = _ps_json("Get-NetFirewallProfile -ErrorAction SilentlyContinue | Select-Object Name, Enabled, DefaultInboundAction, DefaultOutboundAction")
if isinstance(fw, dict):
fw = [fw]
data["firewall_profiles"] = fw or []
done_line("Network & Connections")
return data
# βββββββββββββββββββββββββββββββββββββββββββββββ
# SECTION 5: DOMAIN & MANAGEMENT
# βββββββββββββββββββββββββββββββββββββββββββββββ
def audit_domain_management():
spinner_line("Domain & Management")
data = {}
# Domain status
cs = _ps_json("Get-CimInstance Win32_ComputerSystem | Select-Object Domain, PartOfDomain, DomainRole")
data["computer_system"] = cs or {}
# dsregcmd
spinner_line("Domain & Management β Azure/MDM")
dsreg = _run("dsregcmd /status 2>nul", timeout=15)
parsed = {}
if dsreg:
for line in dsreg.splitlines():
if ":" in line:
parts = line.split(":", 1)
key = parts[0].strip()
val = parts[1].strip()
if key in ["AzureAdJoined", "DomainJoined", "EnterpriseJoined", "DeviceId", "TenantName", "MdmUrl"]:
parsed[key] = val
data["dsregcmd"] = parsed
# Group Policy
spinner_line("Domain & Management β Group Policy")
if is_admin():
gp = _run("gpresult /r 2>nul", timeout=20)
data["group_policy"] = gp.splitlines()[:30] if gp else ["Requires elevation or domain membership"]
else:
data["group_policy"] = ["Requires administrator privileges"]
done_line("Domain & Management")
return data
# βββββββββββββββββββββββββββββββββββββββββββββββ
# SECTION 6: THREAT DETECTION & IOCs
# βββββββββββββββββββββββββββββββββββββββββββββββ
def audit_threat_detection(alert_level="medium"):
spinner_line("Threat Detection β Process Analysis")
data = {
"findings": [],
"severity_counts": {"critical": 0, "warning": 0, "info": 0},
"browser_extensions": {"chrome": [], "firefox": [], "edge": []},
"startup_items": [],
"scheduled_tasks_suspicious": [],
"cron_jobs": [],
"environment_anomalies": [],
"recent_system_modifications": [],
"powershell_policy": "",
}
def add_finding(severity, category, detail):
data["findings"].append({"severity": severity, "category": category, "detail": detail})
data["severity_counts"][severity] += 1
# Get running processes
ps_out = _run_ps("Get-Process | Select-Object ProcessName, Id, Path, CPU | ConvertTo-Csv -NoTypeInformation")
ps_lines = ps_out.splitlines()[1:] if ps_out else []
# 6.1 Reverse shell patterns
wmi_cmdlines = _run_ps_lines("Get-CimInstance Win32_Process | Where-Object {$_.CommandLine -ne $null} | Select-Object -ExpandProperty CommandLine")
rev_shell_patterns = [
r"powershell.*-e\s+[A-Za-z0-9+/=]{20,}", # encoded commands
r"nc\.exe.*-e",
r"ncat.*-e",
r"cmd\.exe.*/c.*powershell.*IEX",
r"Invoke-Expression.*Net\.WebClient",
r"DownloadString\(",
r"System\.Net\.Sockets",
r"TCPClient",
r"bash\s+-i.*>/dev/tcp",
]
for cmdline in wmi_cmdlines:
for pat in rev_shell_patterns:
if re.search(pat, cmdline, re.IGNORECASE):
add_finding("critical", "Reverse Shell", f"Suspicious command line: {cmdline[:120]}")
break
# 6.2 Processes from suspicious paths
spinner_line("Threat Detection β Suspicious Paths")
suspicious_paths = [
os.environ.get("TEMP", "C:\\Temp"),
os.environ.get("TMP", "C:\\Temp"),
"C:\\Users\\Public",
os.path.join(os.environ.get("APPDATA", ""), "..\\Local\\Temp"),
]
for line in ps_lines:
parts = line.replace('"', '').split(',')
if len(parts) >= 3:
proc_path = parts[2]
if proc_path:
for sp in suspicious_paths:
if sp and sp.lower() in proc_path.lower():
add_finding("warning", "Suspicious Process Path", f"{parts[0]} running from {proc_path[:80]}")
break
# 6.3 Unsigned executables with network connections
spinner_line("Threat Detection β Unsigned Network Binaries")
net_procs = _run_ps_lines("""
Get-NetTCPConnection -State Established -ErrorAction SilentlyContinue |
Select-Object -ExpandProperty OwningProcess -Unique |
ForEach-Object { (Get-Process -Id $_ -ErrorAction SilentlyContinue).Path } |
Where-Object { $_ -ne $null } |
Select-Object -Unique -First 20
""")
for proc_path in net_procs:
if proc_path and os.path.isfile(proc_path):
sig = _run_ps(f"(Get-AuthenticodeSignature '{proc_path}').Status", timeout=10)
if sig and "Valid" not in sig:
add_finding("warning", "Unsigned Network Binary", f"{os.path.basename(proc_path)}: Signature={sig}")
# 6.4 Crypto miner indicators
spinner_line("Threat Detection β Crypto Miners")
for line in ps_lines:
lower = line.lower()
for miner in CRYPTO_MINER_NAMES:
if miner in lower:
add_finding("critical", "Crypto Miner", f"Process matching miner pattern: {line[:100]}")
break
# 6.5 Known malware process names
for line in ps_lines:
lower = line.lower()
for mal in KNOWN_MALWARE_NAMES:
if mal in lower:
add_finding("critical", "Known Malware", f"Process matching malware name: {line[:100]}")
break
# 6.6 Non-standard listening ports
spinner_line("Threat Detection β Suspicious Ports")
listen_ports = _run_ps_lines("Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue | Select-Object -ExpandProperty LocalPort")
for port_str in listen_ports:
try:
port = int(port_str.strip())
if port in SUSPICIOUS_PORTS:
proc = _run_ps(f"(Get-Process -Id (Get-NetTCPConnection -LocalPort {port} -State Listen -ErrorAction SilentlyContinue | Select-Object -First 1 -ExpandProperty OwningProcess) -ErrorAction SilentlyContinue).ProcessName")
add_finding("warning", "Suspicious Port", f"Listening on port {port} β process: {proc or 'unknown'}")
except (ValueError, TypeError):
continue
# 6.7 Connections to unusual port ranges
est_ports = _run_ps_lines("Get-NetTCPConnection -State Established -ErrorAction SilentlyContinue | Select-Object -ExpandProperty RemotePort")
for port_str in est_ports:
try:
port = int(port_str.strip())
if port > 10000 and port not in [443, 8443, 10443] and alert_level != "low":
data["severity_counts"]["info"] += 1
except (ValueError, TypeError):
continue
# 6.8 Recently created user accounts
spinner_line("Threat Detection β Recent Accounts")
recent_users = _run_ps_lines("""
Get-LocalUser | Where-Object {
$_.Enabled -eq $true -and
$_.PasswordLastSet -gt (Get-Date).AddDays(-30)
} | Select-Object -ExpandProperty Name
""")
for u in recent_users:
add_finding("info", "Recent Account", f"Account '{u}' created/modified in last 30 days")
# 6.9 Suspicious scheduled tasks
spinner_line("Threat Detection β Scheduled Tasks")
sus_tasks = _run_ps_lines("""
Get-ScheduledTask | Where-Object {
$_.State -eq 'Ready' -and $_.TaskPath -notlike '\\Microsoft\\*'
} | ForEach-Object {
$action = ($_ | Get-ScheduledTaskInfo -ErrorAction SilentlyContinue)
$acts = $_.Actions | Select-Object -First 1
"$($_.TaskName)|$($acts.Execute)|$($acts.Arguments)"
} | Select-Object -First 30
""")
for task in sus_tasks:
parts = task.split("|")
if len(parts) >= 2:
exe = parts[1] if len(parts) > 1 else ""
args = parts[2] if len(parts) > 2 else ""
lower_exe = (exe + args).lower()
if any(s in lower_exe for s in ["temp", "appdata", "encoded", "hidden", "bypass", "-e ", "downloadstring"]):
add_finding("warning", "Suspicious Task", f"Task '{parts[0]}' runs: {exe[:60]} {args[:40]}")
data["scheduled_tasks_suspicious"].append({"name": parts[0], "execute": exe, "args": args})
# 6.10 Startup items
spinner_line("Threat Detection β Startup Items")
startups = _ps_json("Get-CimInstance Win32_StartupCommand -ErrorAction SilentlyContinue | Select-Object Name, Command, Location, User")
if isinstance(startups, dict):
startups = [startups]
data["startup_items"] = startups or []
# 6.11 Browser extensions
spinner_line("Threat Detection β Browser Extensions")
home = os.path.expanduser("~")
local = os.environ.get("LOCALAPPDATA", os.path.join(home, "AppData", "Local"))
roaming = os.environ.get("APPDATA", os.path.join(home, "AppData", "Roaming"))
# Chrome
chrome_ext_dir = os.path.join(local, "Google", "Chrome", "User Data", "Default", "Extensions")
if os.path.isdir(chrome_ext_dir):
for ext_id in os.listdir(chrome_ext_dir):
ext_path = os.path.join(chrome_ext_dir, ext_id)
if os.path.isdir(ext_path):
# Try to read manifest
for ver_dir in os.listdir(ext_path):
manifest = os.path.join(ext_path, ver_dir, "manifest.json")
if os.path.isfile(manifest):
try:
with open(manifest, 'r', encoding='utf-8', errors='ignore') as f:
mdata = json.load(f)
data["browser_extensions"]["chrome"].append({
"name": mdata.get("name", ext_id),
"version": mdata.get("version", "?"),
"id": ext_id,
})
except (json.JSONDecodeError, IOError):
data["browser_extensions"]["chrome"].append({"name": ext_id, "version": "?", "id": ext_id})
break
# Edge
edge_ext_dir = os.path.join(local, "Microsoft", "Edge", "User Data", "Default", "Extensions")
if os.path.isdir(edge_ext_dir):
for ext_id in os.listdir(edge_ext_dir):
ext_path = os.path.join(edge_ext_dir, ext_id)
if os.path.isdir(ext_path):
for ver_dir in os.listdir(ext_path):
manifest = os.path.join(ext_path, ver_dir, "manifest.json")
if os.path.isfile(manifest):
try:
with open(manifest, 'r', encoding='utf-8', errors='ignore') as f:
mdata = json.load(f)
data["browser_extensions"]["edge"].append({
"name": mdata.get("name", ext_id),
"version": mdata.get("version", "?"),
})
except (json.JSONDecodeError, IOError):
data["browser_extensions"]["edge"].append({"name": ext_id, "version": "?"})
break
# Firefox
ff_profiles = os.path.join(roaming, "Mozilla", "Firefox", "Profiles")
if os.path.isdir(ff_profiles):
for profile in os.listdir(ff_profiles):
ext_json = os.path.join(ff_profiles, profile, "extensions.json")
if os.path.isfile(ext_json):
try:
with open(ext_json, 'r', encoding='utf-8', errors='ignore') as f:
ext_data = json.load(f)
for addon in ext_data.get("addons", []):
if addon.get("type") == "extension":
data["browser_extensions"]["firefox"].append({
"name": addon.get("defaultLocale", {}).get("name", addon.get("id", "?")),
"version": addon.get("version", "?"),
"id": addon.get("id", "?"),
})
except (json.JSONDecodeError, IOError):
pass
break
# 6.12 Environment variable anomalies
spinner_line("Threat Detection β Environment")
path_val = os.environ.get("PATH", "")
for entry in path_val.split(";"):
entry_lower = entry.lower().strip()
if any(s in entry_lower for s in ["temp", "tmp", "public", "downloads"]):
if entry_lower and entry_lower not in ["", "."]:
add_finding("warning", "Suspicious PATH", f"PATH contains: {entry[:80]}")
data["environment_anomalies"].append(entry)
# 6.13 Recently modified system files
spinner_line("Threat Detection β Recent System Modifications")
recent = _run_ps_lines("""
Get-ChildItem 'C:\\Windows\\System32' -File -ErrorAction SilentlyContinue |
Where-Object { $_.LastWriteTime -gt (Get-Date).AddDays(-7) } |
Select-Object -ExpandProperty Name -First 30
""")
data["recent_system_modifications"] = recent
# 6.14 PowerShell execution policy & history
data["powershell_policy"] = _run_ps("Get-ExecutionPolicy")
ps_history = os.path.join(roaming, "Microsoft", "Windows", "PowerShell", "PSReadLine", "ConsoleHost_history.txt")
if os.path.isfile(ps_history):
try:
size = os.path.getsize(ps_history)
data["powershell_history_size_kb"] = round(size / 1024, 1)
except OSError:
pass
done_line("Threat Detection & IOCs")
return data
# βββββββββββββββββββββββββββββββββββββββββββββββ
# SECTION 7: EDR / COMPLIANCE POSTURE
# βββββββββββββββββββββββββββββββββββββββββββββββ
def audit_compliance():
spinner_line("Compliance β Security Checks")
checks = []
def add_check(name, status, detail):
checks.append({"check": name, "status": status, "detail": detail})
# BitLocker
bl = _run("manage-bde -status C: 2>nul", timeout=15)
if bl:
if "Percentage Encrypted" in bl and "100" in bl:
add_check("BitLocker", "PASS", "C: drive fully encrypted")
elif "Fully Decrypted" in bl or "Protection Off" in bl:
add_check("BitLocker", "FAIL", "C: drive is NOT encrypted")
else:
add_check("BitLocker", "WARN", f"BitLocker status unclear")
else:
bl_ps = _run_ps("(Get-BitLockerVolume -MountPoint C: -ErrorAction SilentlyContinue).ProtectionStatus")
if bl_ps == "On":
add_check("BitLocker", "PASS", "C: drive encrypted")
elif bl_ps == "Off":
add_check("BitLocker", "FAIL", "C: drive NOT encrypted")
else:
add_check("BitLocker", "WARN", "Cannot determine BitLocker status (may require admin)")
# Windows Defender
spinner_line("Compliance β Defender")
defender = _ps_json("Get-MpComputerStatus -ErrorAction SilentlyContinue | Select-Object RealTimeProtectionEnabled, AntivirusEnabled, AntispywareEnabled, AntivirusSignatureLastUpdated, NISEnabled")
if defender:
if defender.get("RealTimeProtectionEnabled"):
add_check("Defender Real-Time Protection", "PASS", "Real-time protection enabled")
else:
add_check("Defender Real-Time Protection", "FAIL", "Real-time protection DISABLED")
if defender.get("AntivirusEnabled"):
add_check("Defender Antivirus", "PASS", "Antivirus enabled")
else:
add_check("Defender Antivirus", "FAIL", "Antivirus DISABLED")
sig_date = str(defender.get("AntivirusSignatureLastUpdated", ""))
add_check("Defender Signatures", "PASS" if sig_date else "WARN", f"Last updated: {sig_date[:19]}")
else:
add_check("Windows Defender", "WARN", "Cannot query Defender status (may require admin)")
# Firewall β 3 profiles
spinner_line("Compliance β Firewall")
fw_profiles = _ps_json("Get-NetFirewallProfile -ErrorAction SilentlyContinue | Select-Object Name, Enabled")
if isinstance(fw_profiles, dict):
fw_profiles = [fw_profiles]
if fw_profiles:
for prof in fw_profiles:
name = prof.get("Name", "Unknown")
enabled = prof.get("Enabled", False)
# Handle both boolean True and integer 1
is_enabled = enabled is True or enabled == 1 or str(enabled).lower() == "true"
add_check(f"Firewall ({name})", "PASS" if is_enabled else "FAIL",
f"{name} profile: {'Enabled' if is_enabled else 'DISABLED'}")
else:
add_check("Firewall", "WARN", "Cannot query firewall profiles")
# UAC
uac = _run('reg query "HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System" /v EnableLUA 2>nul')
if "0x1" in uac:
add_check("UAC", "PASS", "User Account Control is enabled")
elif "0x0" in uac:
add_check("UAC", "FAIL", "User Account Control is DISABLED")
else:
add_check("UAC", "WARN", "Cannot determine UAC status")
# Secure Boot
spinner_line("Compliance β Secure Boot")
sb = _run_ps("try { Confirm-SecureBootUEFI } catch { 'Error' }", timeout=10)
if sb == "True":
add_check("Secure Boot", "PASS", "Secure Boot is enabled")
elif sb == "False":
add_check("Secure Boot", "FAIL", "Secure Boot is DISABLED")
else:
add_check("Secure Boot", "WARN", "Cannot determine Secure Boot status (legacy BIOS?)")
# Windows Update recency
spinner_line("Compliance β Updates")
hotfix = _run_ps("Get-HotFix -ErrorAction SilentlyContinue | Sort-Object InstalledOn -Descending | Select-Object -First 1 -ExpandProperty InstalledOn")
if hotfix:
add_check("Windows Update", "PASS", f"Last update installed: {hotfix[:10]}")
else:
add_check("Windows Update", "WARN", "Cannot determine last update date")
# SMBv1
smb1 = _run_ps("(Get-WindowsOptionalFeature -Online -FeatureName SMB1Protocol -ErrorAction SilentlyContinue).State")
if smb1:
if "Disabled" in smb1:
add_check("SMBv1", "PASS", "SMBv1 protocol is disabled")
elif "Enabled" in smb1:
add_check("SMBv1", "FAIL", "SMBv1 protocol is ENABLED (vulnerable)")
else:
add_check("SMBv1", "WARN", f"SMBv1 status: {smb1}")
else:
add_check("SMBv1", "WARN", "Cannot query SMBv1 status (may require admin)")
# Remote Desktop
rdp = _run('reg query "HKLM\\SYSTEM\\CurrentControlSet\\Control\\Terminal Server" /v fDenyTSConnections 2>nul')
if "0x1" in rdp:
add_check("Remote Desktop", "PASS", "Remote Desktop is disabled")
elif "0x0" in rdp:
add_check("Remote Desktop", "WARN", "Remote Desktop is ENABLED")
else:
add_check("Remote Desktop", "WARN", "Cannot determine RDP status")
# Guest account
guest = _run_ps("(Get-LocalUser -Name Guest -ErrorAction SilentlyContinue).Enabled")
if guest == "False":
add_check("Guest Account", "PASS", "Guest account is disabled")
elif guest == "True":
add_check("Guest Account", "FAIL", "Guest account is ENABLED")
else:
add_check("Guest Account", "WARN", "Cannot determine guest account status")
# Password policy
spinner_line("Compliance β Password Policy")
net_accts = _run("net accounts 2>nul")
if net_accts:
min_len_match = re.search(r"Minimum password length\s+(\d+)", net_accts)
if min_len_match:
min_len = int(min_len_match.group(1))
if min_len >= 8:
add_check("Password Min Length", "PASS", f"Minimum password length: {min_len}")
else:
add_check("Password Min Length", "FAIL", f"Minimum password length: {min_len} (should be β₯8)")
lockout_match = re.search(r"Lockout threshold\s+(\w+)", net_accts)
if lockout_match:
val = lockout_match.group(1)
if val.lower() == "never":
add_check("Account Lockout", "FAIL", "Account lockout threshold: Never")
else:
add_check("Account Lockout", "PASS", f"Account lockout threshold: {val}")
# Credential Guard
cg = _run('reg query "HKLM\\SYSTEM\\CurrentControlSet\\Control\\DeviceGuard" /v EnableVirtualizationBasedSecurity 2>nul')
if "0x1" in cg:
add_check("Credential Guard", "PASS", "Virtualization-based security enabled")
elif "0x0" in cg:
add_check("Credential Guard", "FAIL", "Virtualization-based security disabled")
else:
add_check("Credential Guard", "WARN", "Cannot determine Credential Guard status")
# Auto-updates
auto_update = _run('reg query "HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU" /v NoAutoUpdate 2>nul')
if "0x0" in auto_update or "not found" in auto_update.lower() or not auto_update:
add_check("Auto-Updates", "PASS", "Automatic updates are enabled")
elif "0x1" in auto_update:
add_check("Auto-Updates", "FAIL", "Automatic updates are DISABLED")
passed = sum(1 for c in checks if c["status"] == "PASS")
failed = sum(1 for c in checks if c["status"] == "FAIL")
warnings = sum(1 for c in checks if c["status"] == "WARN")
done_line("Compliance Posture")
return {
"checks": checks,
"total": len(checks),
"passed": passed,
"failed": failed,
"warnings": warnings,
}
# βββββββββββββββββββββββββββββββββββββββββββββββ
# SECTION 8: LOGS & FORENSIC SNAPSHOT
# βββββββββββββββββββββββββββββββββββββββββββββββ
def audit_logs_forensics():
spinner_line("Logs & Forensics β Event Logs")
data = {}
# 8.1 Failed logins (Event 4625)
failed = _run_ps_lines("""
try {
Get-WinEvent -FilterHashtable @{LogName='Security';Id=4625} -MaxEvents 20 -ErrorAction Stop |
ForEach-Object { "$($_.TimeCreated): $($_.Message.Split([char]10)[0])" }
} catch { 'No events found or access denied' }
""", timeout=20)
data["failed_logins"] = failed or ["No failed logins found or access denied"]
# 8.2 Successful logins (Event 4624)
spinner_line("Logs & Forensics β Login History")
success = _run_ps_lines("""
try {
Get-WinEvent -FilterHashtable @{LogName='Security';Id=4624} -MaxEvents 15 -ErrorAction Stop |
ForEach-Object { "$($_.TimeCreated): $($_.Message.Split([char]10)[0])" }
} catch { 'No events found or access denied' }
""", timeout=20)
data["successful_logins"] = success or ["No data or access denied"]
# 8.3 Privilege escalation (Event 4672)
priv = _run_ps_lines("""
try {
Get-WinEvent -FilterHashtable @{LogName='Security';Id=4672} -MaxEvents 10 -ErrorAction Stop |
ForEach-Object { "$($_.TimeCreated): $($_.Message.Split([char]10)[0])" }
} catch { 'No events found or access denied' }
""", timeout=15)
data["privilege_escalation"] = priv or ["No data or access denied"]
# 8.4 RDP sessions (Events 4778/4779)
spinner_line("Logs & Forensics β RDP Sessions")
rdp = _run_ps_lines("""
try {
Get-WinEvent -FilterHashtable @{LogName='Security';Id=4778,4779} -MaxEvents 10 -ErrorAction Stop |
ForEach-Object { "$($_.TimeCreated) [ID:$($_.Id)]: $($_.Message.Split([char]10)[0])" }
} catch { 'No RDP events found' }
""", timeout=15)
data["rdp_sessions"] = rdp or ["No RDP sessions found"]
# 8.5 Service installs (Event 7045)
spinner_line("Logs & Forensics β Service Installs")
svc = _run_ps_lines("""
try {
Get-WinEvent -FilterHashtable @{LogName='System';Id=7045} -MaxEvents 15 -ErrorAction Stop |
ForEach-Object { "$($_.TimeCreated): $($_.Message.Split([char]10)[0])" }
} catch { 'No service install events found' }
""", timeout=15)
data["service_installs"] = svc or ["No service install events found"]
# 8.6 PowerShell script block logging (Event 4104)
ps_blocks = _run_ps_lines("""
try {
Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-PowerShell/Operational';Id=4104} -MaxEvents 10 -ErrorAction Stop |
ForEach-Object { "$($_.TimeCreated): $($_.Message.Substring(0, [Math]::Min(150, $_.Message.Length)))" }
} catch { 'No PowerShell script block logs found' }
""", timeout=15)
data["powershell_script_blocks"] = ps_blocks or ["No script block logs found"]
# 8.7 Recent downloads
spinner_line("Logs & Forensics β Downloads")
downloads_dir = os.path.join(os.path.expanduser("~"), "Downloads")
recent_downloads = []
if os.path.isdir(downloads_dir):
now = datetime.datetime.now().timestamp()
seven_days = 7 * 86400
try:
for f in os.listdir(downloads_dir):
fp = os.path.join(downloads_dir, f)
if os.path.isfile(fp):
mtime = os.path.getmtime(fp)
if now - mtime < seven_days:
recent_downloads.append({
"name": f,
"size_kb": round(os.path.getsize(fp) / 1024, 1),
"modified": datetime.datetime.fromtimestamp(mtime).strftime("%Y-%m-%d %H:%M"),
})
except OSError:
pass
data["recent_downloads"] = sorted(recent_downloads, key=lambda x: x.get("modified", ""), reverse=True)[:30]
# 8.8 Mounted drives
drives = _ps_json("Get-PSDrive -PSProvider FileSystem -ErrorAction SilentlyContinue | Select-Object Name, Root, @{N='UsedGB';E={[math]::Round($_.Used/1GB,1)}}, @{N='FreeGB';E={[math]::Round($_.Free/1GB,1)}}")
if isinstance(drives, dict):
drives = [drives]
data["mounted_drives"] = drives or []
# Network shares
mappings = _ps_json("Get-SmbMapping -ErrorAction SilentlyContinue | Select-Object LocalPath, RemotePath, Status")
if isinstance(mappings, dict):
mappings = [mappings]
data["network_mappings"] = mappings or []
done_line("Logs & Forensics")
return data
# βββββββββββββββββββββββββββββββββββββββββββββββ
# GUIDANCE & REMEDIATION ENGINE
# βββββββββββββββββββββββββββββββββββββββββββββββ
GUIDANCE_DB = {
"BitLocker": {
"risk": "Unencrypted disk exposes all data if device is lost or stolen.",
"fix": "Enable-BitLocker -MountPoint 'C:' -EncryptionMethod XtsAes256 -UsedSpaceOnly -RecoveryPasswordProtector",
"settings": "Settings > Privacy & Security > Device Encryption",
"cis": "CIS 18.9.11.1",
},
"Defender Real-Time Protection": {
"risk": "Without real-time protection, malware can execute without detection.",
"fix": "Set-MpPreference -DisableRealtimeMonitoring $false",
"settings": "Settings > Privacy & Security > Windows Security > Virus & threat protection",
"cis": "CIS 18.9.47.4.1",
},
"Defender Antivirus": {
"risk": "Disabled antivirus leaves the system vulnerable to all malware types.",
"fix": "Set-MpPreference -DisableRealtimeMonitoring $false",
"settings": "Settings > Privacy & Security > Windows Security > Virus & threat protection",
"cis": "CIS 18.9.47.4.1",
},
"Defender Signatures": {
"risk": "Outdated signatures miss recently discovered threats.",
"fix": "Update-MpSignature",
"settings": "Windows Security > Virus & threat protection > Check for updates",
"cis": "CIS 18.9.47.10",
},
"Firewall (Domain)": {
"risk": "Disabled domain firewall exposes the system to lateral movement attacks.",
"fix": "Set-NetFirewallProfile -Profile Domain -Enabled True",
"settings": "Settings > Privacy & Security > Windows Security > Firewall",
"cis": "CIS 9.1.1",
},
"Firewall (Private)": {
"risk": "Disabled private firewall leaves the system open on trusted networks.",
"fix": "Set-NetFirewallProfile -Profile Private -Enabled True",
"settings": "Settings > Privacy & Security > Windows Security > Firewall",
"cis": "CIS 9.2.1",
},
"Firewall (Public)": {
"risk": "Disabled public firewall exposes the system on untrusted networks.",
"fix": "Set-NetFirewallProfile -Profile Public -Enabled True",
"settings": "Settings > Privacy & Security > Windows Security > Firewall",
"cis": "CIS 9.3.1",
},
"UAC": {
"risk": "Without UAC, all programs run with full admin rights, enabling malware escalation.",