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)
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
def get_win_proxies(): try: from _winreg import EnumKey, OpenKey, CloseKey, QueryValueEx from _winreg import HKEY_LOCAL_MACHINE, HKEY_USERS, KEY_QUERY_VALUE except: return duplicates = set() i = 0 while True: try: user = EnumKey(HKEY_USERS, i) i += 1 except: break if user.endswith('_classes'): continue try: key = '{}\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings'.format(user) aKey = OpenKey(HKEY_USERS, key, 0, KEY_QUERY_VALUE) value = QueryValueEx(aKey, 'ProxyServer')[0] if value: for p in parse_win_proxy(value): if p not in duplicates: yield p duplicates.add(p) except Exception: pass finally: CloseKey(aKey)
def GetTypelibVersions(IID): """ Returns the list of installed versions of a given typelib. Versions are returned as a list of two element tuples of the form (major, minor) where major, minor are integers. """ versions = [] with OpenKey(HKEY_CLASSES_ROOT, 'Typelib\\' + IID) as key: subkeycount, _, _ = QueryInfoKey(key) for i in range(subkeycount): rawversion = EnumKey(key, i) # We're only interested in subkeys of the form # MAJORVERSION.MINORVERSION if rawversion.count('.') != 1: continue rawmajor, rawminor = rawversion.split('.') # Versions are expressed in hex. major, minor = int(rawmajor, 16), int(rawminor, 16) versions.append((major, minor)) return versions
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)
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
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)
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)
def get_sub_key(self, index): try: if self.path != "": return RegistryKey(self.hive, self.path + "\\" + EnumKey(self.key, index)) else: return RegistryKey(self.hive, EnumKey(self.key, index)) except WindowsError: return None
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)
def get_open_with_list(ext): """get open with list of an ext find all the exe programs and direct program @params: ext -- file extention """ import re sub_key = '\\'.join([ ext, 'OpenWithList' ]) try: key = OpenKey(HKEY_CLASSES_ROOT, sub_key) except WindowsError: return None key_no = QueryInfoKey(key)[0] exes = [] for index in xrange(key_no): exe = EnumKey(key, index) if exe.lower().endswith('.exe'): command = get_exe_command(exe) if not command: continue match = re.search(u'.+\\\\(.+)\\\\(\w+)\.exe', command, flags=re.IGNORECASE) if match: name = match.group(2) progid = '.'.join([name, 'edo']) exes.append((name, progid, command)) else: sub_key = '\\'.join([ exe, 'shell', 'edit', 'command' ]) edit_command = get_command(key, sub_key) sub_key = '\\'.join([ exe, 'shell', 'open', 'command' ]) open_command = get_command(key, sub_key) if not (open_command or edit_command): continue command = edit_command or open_command match = re.search(u'.+\\\\(.+)\\\\(\w+)\.exe', command, flags=re.IGNORECASE) if match: name = match.group(2) progid = '.'.join([name, 'edo']) exes.append((name, progid, command)) return exes
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)
def get_open_with_list(ext): """get open with list of an ext find all the exe programs and direct program @params: ext -- file extention """ import re sub_key = '\\'.join([ext, 'OpenWithList']) try: key = OpenKey(HKEY_CLASSES_ROOT, sub_key) except WindowsError: return None key_no = QueryInfoKey(key)[0] exes = [] for index in xrange(key_no): exe = EnumKey(key, index) if exe.lower().endswith('.exe'): command = get_exe_command(exe) if not command: continue match = re.search(u'.+\\\\(.+)\\\\(\w+)\.exe', command, flags=re.IGNORECASE) if match: name = match.group(2) progid = '.'.join([name, 'edo']) exes.append((name, progid, command)) else: sub_key = '\\'.join([exe, 'shell', 'edit', 'command']) edit_command = get_command(key, sub_key) sub_key = '\\'.join([exe, 'shell', 'open', 'command']) open_command = get_command(key, sub_key) if not (open_command or edit_command): continue command = edit_command or open_command match = re.search(u'.+\\\\(.+)\\\\(\w+)\.exe', command, flags=re.IGNORECASE) if match: name = match.group(2) progid = '.'.join([name, 'edo']) exes.append((name, progid, command)) return exes
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
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
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
def search_name(locals, prog_path): """use the prog_path to find out the program display name locals: -- (main_key, sub_key) prog_path: -- program execute path return prog_name """ for local in locals: key = OpenKey(*local) key_no = QueryInfoKey(key)[0] for index in xrange(key_no): key_name = EnumKey(key, index) app_key = OpenKey(key, key_name) for value_name in ('InstallLocation', 'LocationRoot', 'UninstallString'): try: value_data = QueryValueEx(app_key, value_name)[0] if value_data and (value_data.startswith(prog_path) or prog_path.startswith(value_data)): prog_name = QueryValueEx(app_key, 'DisplayName')[0] return prog_name except WindowsError: pass return None
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
def getCustomLogDir(self): if platform == 'win32': from _winreg import OpenKey, EnumKey, QueryValueEx, HKEY_LOCAL_MACHINE aKey = OpenKey( HKEY_LOCAL_MACHINE, r"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall" ) try: i = 0 while True: asubkey = OpenKey(aKey, EnumKey(aKey, i)) try: if QueryValueEx( asubkey, "Publisher")[0] == "Frontier Developments": custpath = join( QueryValueEx(asubkey, "InstallLocation")[0], "Products") if isdir(custpath): for d in listdir(custpath): if d.startswith("FORC-FDEV-D-1") and isdir( join(custpath, d, "Logs")): asubkey.Close() aKey.Close() return join(custpath, d, "Logs") except: pass asubkey.Close() i += 1 except: aKey.Close() return None
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)
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)
def registry_subkeys(key) : ret = list() subkeys, subvals, mtime = QueryInfoKey(key) for i in range(subkeys) : name = EnumKey(key,i) ret.append(name) return ret
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)
def __print_regkey_csv(self, bKey, key_path, csv_writer, is_recursive, subkey_type_to_query, additional_info_function): ''' Recursive method that will parse the registry and write in the output file ''' ''' The subkey_type_to_query is a string that will be checked against the subkeys name if it is not None ''' for i in range(QueryInfoKey(bKey)[0]): try: subkey_name = EnumKey(bKey, i) if subkey_type_to_query is None or subkey_type_to_query in subkey_name: # if it is None, then we go inside no matter what, else we check if it is in the name key_info = '' if additional_info_function: # this function is a parameter, it is None by default key_info = additional_info_function(subkey_name) subkey = OpenKey(bKey, subkey_name) subkey_path = key_path + subkey_name + '\\' node_type = 'Key' date_last_mod = convert_windate(QueryInfoKey(subkey)[2]) #self.logger.info(date_last_mod + ' : ' + subkey_name) write_to_csv([ self.computer_name, date_last_mod, 'HKEY_LOCAL_MACHINE', subkey_path, node_type, key_info ], csv_writer) if is_recursive: self.__print_regkey_values_csv( subkey, date_last_mod, 'HKEY_LOCAL_MACHINE', subkey_path, csv_writer, is_recursive, subkey_type_to_query) # print the values first self.__print_regkey_csv( subkey, subkey_path, csv_writer) # and then go deeper in the tree except EnvironmentError: break
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)
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)
def readKeys(keyPath): # return list of Keys explorer = OpenKey(HKEY_LOCAL_MACHINE, keyPath, 0, KEY_READ | KEY_WOW64_64KEY) KeysList = [] for i in xrange(QueryInfoKey(explorer)[0]): name = EnumKey(explorer, i) KeysList.append(name) return KeysList
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
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
def enum_keys(key): #enumerate through sub-keys of key #yields the sub-key name try: for i in itertools.count(): name = EnumKey(key, i) yield name except WindowsError as e: if e.winerror != 259: #errno 259 is "No More Data Available" raise
def get_win_proxies(): try: from _winreg import EnumKey, OpenKey, CloseKey, QueryValueEx from _winreg import HKEY_USERS, KEY_QUERY_VALUE except: return duplicates = set() i = 0 while True: try: user = EnumKey(HKEY_USERS, i) i += 1 except: break if user.endswith('_classes'): continue aKey = None try: key = '{}\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings'.format( user) aKey = OpenKey(HKEY_USERS, key, 0, KEY_QUERY_VALUE) value = QueryValueEx(aKey, 'ProxyServer')[0] if value: for p in parse_win_proxy(value): if p not in duplicates: logger.debug('Proxy found via Internet Settings: %s', p) yield p duplicates.add(p) except Exception: pass finally: if aKey: CloseKey(aKey)
def _iter_log_names(self): dups = set() if self._source: yield self._source.split('/', 1)[0] return for well_known in ('Application', 'Security', 'System'): dups.add(well_known) yield well_known key = OpenKeyEx(HKEY_LOCAL_MACHINE, ur'SYSTEM\CurrentControlSet\Services\EventLog', 0, KEY_READ) try: idx = 0 while idx < self._max_iters: try: source = EnumKey(key, idx) if source in dups: continue dups.add(source) if type(source) == str: source = source.decode(getdefaultencoding()) yield source except WindowsError: break finally: idx += 1 finally: CloseKey(key)
def remove_all_registry_entries(): """ Removes all related registry entries. """ main_key = None try: main_key = OpenKey(HKEY_CURRENT_USER, r'Software\Classes\*\shell', 0, KEY_ALL_ACCESS) count = 0 while 1: try: key_name = EnumKey(main_key, count) if key_name.find('DiWaCS') > -1: key = OpenKey(main_key, key_name, 0, KEY_ALL_ACCESS) subkey_count = 0 while 1: try: subkey_name = EnumKey(key, subkey_count) DeleteKey(key, subkey_name) subkey_count += 1 except WindowsError: break CloseKey(key) try: DeleteKey(main_key, key_name) except WindowsError: count += 1 else: count += 1 except WindowsError: break except Exception as excp: excp_string = 'Exception in remove_all_registry_entries: {0!s}' _logger().exception(excp_string.format(excp)) if main_key: CloseKey(main_key)
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 = "" productPath = r"{0}\{1}\{2}".format(baseOfficeKeyPath, oVersion, software) try: productKey = OpenKey(HKEY_CURRENT_USER, productPath, 0, KEY_READ) CloseKey(productKey) mruKeyPath = r"{0}\File MRU".format(productPath) try: mruKey = OpenKey(HKEY_CURRENT_USER, mruKeyPath, 0, KEY_READ) except WindowsError: mruKey = CreateKeyEx(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)