예제 #1
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)
예제 #2
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)
예제 #3
0
def getUACLevel():
    if sys.platform != 'win32':
        return 'N/A'
    i, consentPromptBehaviorAdmin, enableLUA, promptOnSecureDesktop = 0, None, None, None
    try:
        Registry = ConnectRegistry(None, HKEY_LOCAL_MACHINE)
        RawKey = OpenKey(
            Registry,
            r'SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System')
    except:
        return "?"
    while True:
        try:
            name, value, type = EnumValue(RawKey, i)
            if name == "ConsentPromptBehaviorAdmin":
                consentPromptBehaviorAdmin = value
            elif name == "EnableLUA":
                enableLUA = value
            elif name == "PromptOnSecureDesktop":
                promptOnSecureDesktop = value
            i += 1
        except WindowsError:
            break

    if consentPromptBehaviorAdmin == 2 and enableLUA == 1 and promptOnSecureDesktop == 1:
        return "3/3"
    elif consentPromptBehaviorAdmin == 5 and enableLUA == 1 and promptOnSecureDesktop == 1:
        return "2/3"
    elif consentPromptBehaviorAdmin == 5 and enableLUA == 1 and promptOnSecureDesktop == 0:
        return "1/3"
    elif enableLUA == 0:
        return "0/3"
    else:
        return "?"
예제 #4
0
def registry_values(key) :
	ret = dict()
	subkeys, subvals, mtime = QueryInfoKey(key)
	for i in range(subvals) :
		name,data,type = EnumValue(key,i)
		ret[name]=data
	return ret
예제 #5
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)
예제 #6
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
예제 #7
0
def readValues(keyPath):
	# return Dict of name:value from key
	explorer = OpenKey(HKEY_LOCAL_MACHINE, keyPath, 0, KEY_READ | KEY_WOW64_64KEY)
	valuesDict = {}
	for i in range(QueryInfoKey(explorer)[1]):
		name, value, type = EnumValue(explorer, i)
		valuesDict[name] = value
	return valuesDict
def enum_keys(user=True):
    key = OpenKey(HKEY_CURRENT_USER, 'Environment', 0, KEY_ALL_ACCESS)
    _, n, _ = QueryInfoKey(key)
    values = {}
    for i in range(n):
        k, v, _ = EnumValue(key, i)
        values[k] = v
    return values
예제 #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)
예제 #10
0
파일: win.py 프로젝트: joamatab/mimeopen
def get_open_with_progs(ext):
    """get the open with progids

    @params
        ext -- file extention
    @return
        name progrid command
    """
    import re

    # find all keys
    key = OpenKey(HKEY_CLASSES_ROOT, None)
    key_no = QueryInfoKey(key)[0]

    all_keys = []
    for index in xrange(key_no):
        all_keys.append(EnumKey(key, index))

    # try to find open with progids
    sub_key = '\\'.join([ext, 'OpenWithProgids'])

    try:
        key = OpenKey(HKEY_CLASSES_ROOT, sub_key)
    except WindowsError:
        return None

    # add default program
    progids = []

    logger.debug('current ext: %s', ext)
    logger.debug('all key number: %s', len(all_keys))

    # enum value under the key
    value_no = QueryInfoKey(key)[1]
    for index in xrange(value_no):
        value = EnumValue(key, index)[0]
        value and logger.debug('find progid: %s', value)
        if value and value in all_keys:
            progids.append(value)

    logger.debug('open with progrids: %s', progids)

    # get the information about the progids
    exes = []
    for progid in progids:
        name = get_prog_name(progid)
        command = get_prog_command(progid)
        if name and command:
            exes.append((name, progid, command))
        if command and not name:
            match = re.search(u'.+\\\\(\w+)\.exe',
                              command,
                              flags=re.IGNORECASE)
            if match:
                name = match.group(1)
                exes.append((name, progid, command))
    return exes
예제 #11
0
 def test_dynamic_key(self):
     from _winreg import EnumValue, QueryValueEx, HKEY_PERFORMANCE_DATA
     try:
         EnumValue(HKEY_PERFORMANCE_DATA, 0)
     except WindowsError, e:
         import errno
         if e.errno in (errno.EPERM, errno.EACCES):
             skip("access denied to registry key "
                  "(are you running in a non-interactive session?)")
         raise
예제 #12
0
파일: environ.py 프로젝트: koll00/Gui_SM
 def get_user_env():
     """Return HKCU (current user) environment variables"""
     reg = dict()
     key = OpenKey(HKEY_CURRENT_USER, "Environment")
     for index in range(0, QueryInfoKey(key)[1]):
         try:
             value = EnumValue(key, index)
             reg[value[0]] = value[1]
         except:
             break
     return envdict2listdict(reg)
예제 #13
0
def print_networks(username=None, password=None):
    net = "SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkList\Signatures\Unmanaged"
    key = OpenKey(HKEY_LOCAL_MACHINE, net)

    print '\n[*] Networks You have Joined.'

    for i in range(100):
        try:
            guid = EnumKey(key, i)
            netKey = OpenKey(key, str(guid))
            (n, addr, t) = EnumValue(netKey, 5)
            (n, name, t) = EnumValue(netKey, 4)

            mac = binary2mac(addr)
            net_name = str(name)

            print '[+] ' + net_name + ' ' + mac
            wigle_print(username, password, mac)
            CloseKey(netKey)
        except:
            break
예제 #14
0
 def test_readValues(self):
     from _winreg import OpenKey, EnumValue, QueryValueEx, EnumKey
     key = OpenKey(self.root_key, self.test_key_name)
     sub_key = OpenKey(key, "sub_key")
     index = 0
     while 1:
         try:
             data = EnumValue(sub_key, index)
         except EnvironmentError, e:
             break
         assert data in self.test_data
         index = index + 1
예제 #15
0
def getStartUpFolder():
    shellFolders = OpenKey(
        HKEY_CURRENT_USER,
        'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders', 0,
        KEY_READ)
    try:
        count = 0
        while True:
            name, value, type = EnumValue(shellFolders, count)
            if name == 'Startup':
                return value
            count = count + 1
    except WindowsError:
        pass
예제 #16
0
 def _get_reg_values(path, root=HKEY_LOCAL_MACHINE):
     """ Return {value_name, value_data} dict for the registry key located
     at 'path'. First try to lookup the key in the 64-bit registry view,
     otherwise look it up in the 32-bit registry view.
     The 'root' argument can be an already open key, or any one of the pre-
     defined HKEY_* constants (default is HKEY_LOCAL_MACHINE).
     """
     try:
         k = OpenKey(root, path, 0, KEY_READ | KEY_WOW64_64KEY)
     except WindowsError:
         try:
             k = OpenKey(root, path, 0, KEY_READ | KEY_WOW64_32KEY)
         except WindowsError:
             return
     return dict([EnumValue(k, i)[:2] for i in range(QueryInfoKey(k)[1])])
예제 #17
0
def reload_windows_env(keys_white_list=default_whitelist):
    root = HKEY_LOCAL_MACHINE
    subkey = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
    key = OpenKey(root, subkey, 0, KEY_READ)
    finish = False
    index = 0
    while not finish:
        try:
            _key, _value, _ = EnumValue(key, index)
            if (_key in keys_white_list):
                os.environ[_key] = _value
        except WindowsError:
            finish = True
        index += 1
    CloseKey(key)
예제 #18
0
	def __print_regkey_values_csv(self, bKey, date_last_mod, hive_name, key_path, csv_writer, additional_data=None, optional_function=None):
		''' Get the registry values and write those in the output file '''
		for i in range(QueryInfoKey(bKey)[1]): # the number of values
			try:
				value_name=EnumValue(bKey,i)
				subkey_path = key_path + value_name[0].replace(b'\xa0', b' ')
				node_type = ''
				values = []
				if value_name[2] == REG_MULTI_SZ: # the value is a list
					node_type = 'REG_MULTI_SZ'
					values += value_name[1] # concat both lists
				elif value_name[2] == REG_QWORD: # the value is a list
					node_type = 'REG_QWORD'
					hex_str = '0x'
					for c in value_name[1]:
						hex_str += c.encode('hex') 
					values.append(hex_str) # get hexadecimal from string
				elif value_name[2] == REG_BINARY:
					node_type = 'REG_BINARY'
					if optional_function:
						res = optional_function(value_name[0], value_name[1])
						if res:
							values += res
					else:
						values.append('')
				else:
					if value_name[2] == REG_SZ:
						node_type = 'REG_SZ'
					elif value_name[2] == REG_DWORD:
						node_type = 'REG_DWORD'
					values.append(unicode(value_name[1])) # just add the element to the list
				for value in values:
					'''if node_type != 'REG_BINARY':
						value_tmp = value.replace('","', '_')
					else:
						value_tmp = value'''
					if isinstance(value, list):
						# we want to concat list for the csv, so if it is not a list, put it in a list...
						value_tmp = value
					else:
						value_tmp = [value]
					if additional_data:
						arr_output = [self.computer_name, additional_data, date_last_mod, hive_name+'\\'+subkey_path, node_type] + value_tmp
						write_to_csv(arr_output, csv_writer)
					else:
						write_to_csv([self.computer_name, date_last_mod, hive_name+'\\'+subkey_path, node_type] + value_tmp, csv_writer)
			except EnvironmentError:
				break
예제 #19
0
 def read_reg(reg_key, reg_val):
     """
     Fetch registry given the reg key+value combo
     :param reg_key:
     :param reg_val:
     :return:
     """
     ret = None
     with OpenKey(HKEY_LOCAL_MACHINE, reg_key, 0, KEY_READ |
             KEY_WOW64_64KEY) \
             as key:
         desc, i = None, 0
         while not desc or desc[0] != reg_val:
             desc = EnumValue(key, i)
             i += 1
         ret = desc[1]
     return ret
예제 #20
0
def settingsDirectory():
    # Find the directory with Paratext 8 projects using the windows registry
    from _winreg import OpenKey, EnumValue, HKEY_LOCAL_MACHINE

    strPath = r"SOFTWARE\WOW6432Node\Paratext\8"
    try:
        aKey = OpenKey(HKEY_LOCAL_MACHINE, strPath)
        for i in [0, 1, 2, 3, 4, 5]:
            aName, aValue, irrelevant = EnumValue(aKey, i)
            if aName == 'Settings_Directory':
                return aValue + '\\'
        return None

    except WindowsError:
        # The registry key was not found
        return None
    except:
        raise
예제 #21
0
 def enumerate_ports(self):
     SER2PL32 = 'SYSTEM\\CurrentControlSet\\Services\\Ser2pl\\Enum'
     SER2PL64 = 'SYSTEM\\CurrentControlSet\\Services\\Ser2pl64\\Enum'
     
     try:
         # 32-bit Prolific driver
         self.arch = 32
         self.prolific_path = OpenKey(HKEY_LOCAL_MACHINE, SER2PL32)
     except WindowsError:
         try:
             # 64-bit
             self.arch = 64
             self.prolific_path = OpenKey(HKEY_LOCAL_MACHINE, SER2PL64)
         except WindowsError:
             eg.PrintNotice(self.text.info2 % self.info.eventPrefix)
             return []
     ports, type = QueryValueEx(self.prolific_path, 'Count')
     if ports is 0:
         return []
     coms = [0] * ports
     ENUM = 'SYSTEM\\CurrentControlSet\\Enum\\'
     try:
         i = 0
         j = 0
         while 1:
             name, string, type = EnumValue(self.prolific_path, i)
             if type == 1: # 1 is for 'REG_SZ', 'A null-terminated string'
                 sn = search('(?<=[\][0-9]&)\w+',string)
                 offset = 0
                 try:
                     serint = ENUM + string + '\\Device Parameters'
                     serial_path = OpenKey(HKEY_LOCAL_MACHINE,serint)
                     port, type = QueryValueEx(serial_path, 'PortName')
                     coms[j] = int(str(port)[3:]) - 1
                     j += 1
                 except WindowsError:
                     pass
             i += 1
     except WindowsError:
         pass
     return coms
예제 #22
0
def get_userprofiles_from_reg():
    ''' Retrieves and returns the userprofiles from the registry '''
    # SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList contains a list of subkeys representing SIDs
    aReg = ConnectRegistry(None, HKEY_LOCAL_MACHINE)
    str_userprofiles = 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList\\'
    reg_profile_list = OpenKey(aReg, str_userprofiles)
    list_profiles = []
    for index_sid in range(
            QueryInfoKey(reg_profile_list)[0]):  # the number of subkeys
        sid = EnumKey(reg_profile_list, index_sid)
        reg_sid = OpenKey(aReg, str_userprofiles + sid)
        # now get the value from the SID subkey
        for index_value in range(
                QueryInfoKey(reg_sid)[1]):  # the number of values
            value_sid = EnumValue(reg_sid, index_value)
            if value_sid[0] == 'ProfileImagePath':
                list_profiles.append(value_sid[1])
                break
        CloseKey(reg_sid)
    CloseKey(reg_profile_list)
    CloseKey(aReg)
    return list_profiles
예제 #23
0
파일: os_windows.py 프로젝트: miili/KiCost
 def reg_enum_values(path, key=HKEY_CURRENT_USER):
     # Read variable from Windows Registry.
     try:
         reg = ConnectRegistry(None, key)
         try:
             registry_key = OpenKey(reg, path, 0, KEY_READ)
         except OpenKeyError:
             registry_key = OpenKey(reg, path, 0, KEY_READ | KEY_WOW64_64KEY)
         values = ()
         try:
             idx = 0
             while 1:
                 values.append(EnumValue(registry_key, idx))
                 idx = idx + 1
         except WindowsError:
             pass
         return values
         # TODO this portion of code was unreachable, remove?
         # CloseKey(reg)
         # return value
     except WindowsError:
         return None
예제 #24
0
    def test_readValues(self):
        from _winreg import OpenKey, EnumValue, QueryValueEx, EnumKey
        from _winreg import REG_SZ, REG_EXPAND_SZ
        key = OpenKey(self.root_key, self.test_key_name)
        sub_key = OpenKey(key, "sub_key")
        index = 0
        while 1:
            try:
                data = EnumValue(sub_key, index)
            except EnvironmentError as e:
                break
            assert data in self.test_data
            index = index + 1
        assert index == len(self.test_data)

        for name, value, type in self.test_data:
            result = QueryValueEx(sub_key, name)
            assert result == (value, type)
            if type == REG_SZ or type == REG_EXPAND_SZ:
                assert isinstance(result[0], unicode)  # not string

        assert EnumKey(key, 0) == "sub_key"
        raises(EnvironmentError, EnumKey, key, 1)
예제 #25
0
        def zune():
            """ Uses the ZuneNowPlaying.exe app to get the songname + artist """
            if not Constants.ZUNESTARTED:
                Constants.SUBP = subprocess.Popen(
                    [resource_path('ZuneNowPlaying.exe')])
                Constants.ZUNESTARTED = True
            try:
                exp = OpenKey(HKEY_CURRENT_USER, r"Software\ZuneNowPlaying")
                # list values owned by this registry key
                try:
                    i = 0
                    while 1:
                        name, value, type = EnumValue(exp, i)
                        i += 1
                except WindowsError:
                    pass
                title, type = QueryValueEx(exp, "Title")
                artist, type = QueryValueEx(exp, "Artist")

                returnstr = title + ' - ' + artist
                return returnstr
            except Exception, err:
                logging.exception(err)
                return False
예제 #26
0
 def get_value(self, index):
     return RegValue(EnumValue(self.key, index), self.path)
예제 #27
0
파일: disguise.py 프로젝트: nakagit/CAPE
    def set_office_mrus(self):
        """Adds randomized MRU's to Office software(s).
        Occasionally used by macros to detect sandbox environments.
        """
        baseOfficeKeyPath = r"Software\Microsoft\Office"
        installedVersions = list()
        basePaths = [
            "C:\\",
            "C:\\Windows\\Logs\\",
            "C:\\Windows\\Temp\\",
            "C:\\Program Files\\",
        ]
        extensions = {
            "Word": ["doc", "docx", "docm", "rtf"],
            "Excel": ["xls", "xlsx", "csv"],
            "PowerPoint": ["ppt", "pptx"],
        }
        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:
            for software in extensions:
                values = list()
                mruKeyPath = r"{0}\{1}\{2}\File MRU".format(
                    baseOfficeKeyPath, oVersion, software)
                try:
                    mruKey = OpenKey(HKEY_CURRENT_USER, mruKeyPath, 0,
                                     KEY_READ)
                    displayValue = False
                    for mruKeyInfo in xrange(0, QueryInfoKey(mruKey)[1]):
                        currentValue = EnumValue(mruKey, mruKeyInfo)
                        if currentValue[0] == "Max Display":
                            displayValue = True
                        values.append(currentValue)
                    CloseKey(mruKey)

                except WindowsError:
                    # An Office version was found in the registry but the
                    # software (Word/Excel/PowerPoint) was not installed.
                    values = "notinstalled"

                if values != "notinstalled" and len(values) < 5:
                    mruKey = OpenKey(HKEY_CURRENT_USER, mruKeyPath, 0,
                                     KEY_SET_VALUE)
                    if not displayValue:
                        SetValueEx(mruKey, "Max Display", 0, REG_DWORD, 25)

                    for i in xrange(1, randint(10, 30)):
                        rString = random_string(minimum=11,
                                                charset="0123456789ABCDEF")
                        if i % 2:
                            baseId = "T01D1C" + rString
                        else:
                            baseId = "T01D1D" + rString
                        setVal = "[F00000000][{0}][O00000000]*{1}{2}.{3}".format(
                            baseId, basePaths[randint(0,
                                                      len(basePaths) - 1)],
                            random_string(
                                minimum=3,
                                maximum=15,
                                charset="abcdefghijkLMNOPQURSTUVwxyz_0369"),
                            extensions[software][randint(
                                0,
                                len(extensions[software]) - 1)])
                        name = "Item {0}".format(i)
                        SetValueEx(mruKey, name, 0, REG_SZ, setVal)
                    CloseKey(mruKey)
예제 #28
0
    def extract_info(key):
        try:
            h = OpenKey(HKEY_USERS, key)
        except WindowsError:
            return {}

        alias = key.split('\\')[-1]

        info = {}

        if '@' in alias:
            user, alias = alias.split('@', 1)
            info['user'] = user
            if ':' in alias:
                maybe_alias, maybe_port = alias.rsplit(':', 1)
                try:
                    maybe_port = int(maybe_port)
                    if maybe_port > 0 and maybe_port < 65536:
                        alias = maybe_alias
                        info['port'] = maybe_port

                except ValueError:
                    pass

            info['hostname'] = alias
        elif alias == 'Default%20Settings':
            alias = '*'

        try:
            idx = 0
            while True:
                try:
                    name, value, _ = EnumValue(h, idx)
                except WindowsError:
                    break

                if type(value) in (str, unicode):
                    new_value = unquote(value)
                    if new_value != value:
                        if type(new_value) == unicode:
                            try:
                                new_value = new_value.encode('latin1')
                                value = bin_decode(new_value)
                            except UnicodeEncodeError:
                                value = new_value

                name = name.lower()
                if name in PROPERTIES_MAPPING:
                    if name == 'publickeyfile':
                        info[PROPERTIES_MAPPING[name]] = [value]
                    else:
                        info[PROPERTIES_MAPPING[name]] = value

                idx += 1

        finally:
            CloseKey(h)

        if info and (alias == '*' or info.get('hostname')):
            return {alias: info}

        return {}
예제 #29
0
 def get_value_by_name(self, name):
     for i in range(self.get_number_of_values()):
         value = EnumValue(self.key, i)
         if name == value[0]:
             return RegValue(value, name)
     return None
예제 #30
0
 def test_dynamic_key(self):
     from _winreg import EnumValue, QueryValueEx, HKEY_PERFORMANCE_DATA
     EnumValue(HKEY_PERFORMANCE_DATA, 0)
     QueryValueEx(HKEY_PERFORMANCE_DATA, None)