def getShellbags(computerName,objRegistry,hostPath,registryList): print computerName + " - checking shellbags" userpath2 = "" for hive,username,userpath in registryList: outFile = open(hostPath + "\SHELLBAGS-" + username + "-" + computerName + ".csv", "w") outFile.write("path,created,modified,accessed\n") if hive == _winreg.HKEY_LOCAL_MACHINE: print computerName + " - shellbags: checking logged out user (" + username + ")..." userpath2 = userpath + "2" elif hive == _winreg.HKEY_USERS: print computerName + " - shellbags: checking logged in user (" + username + ")..." userpath2 = userpath + "\Software\Classes" keys = [userpath + "\Software\Microsoft\Windows\Shell", userpath + "\Software\Microsoft\Windows\ShellNoRoam", userpath2 + "\Local Settings\Software\Microsoft\Windows\Shell", userpath2 + "\Local Settings\Software\Microsoft\Windows\ShellNoRoam"] shellbags = [] for key in keys: new_shellbags = get_shellbags(objRegistry,hive,key) shellbags.extend(new_shellbags) for shellbag in shellbags: outFile.write(support.convert_to_string(shellbag["path"]).replace(","," ") + "," + support.convert_to_string(shellbag["crtime"]) + "," + support.convert_to_string(shellbag["mtime"]) + "," + support.convert_to_string(shellbag["atime"]) + "\n") outFile.close()
def getProcesses(computerName, objWMIService, hostPath): print computerName + " - checking processes and process modules" outFile = open(hostPath + "\PROCESSES-" + computerName + ".csv", "w") outFile.write( "process,pid,creation_date,process_owner,threat_count,path,cmd_line,ppid\n" ) outFile2 = open(hostPath + "\PROCESSMODULES-" + computerName + ".csv", "w") outFile2.write("pid,module_path\n") processes = objWMIService.ExecQuery( "select Name,ProcessID,CreationDate,ThreadCount,ExecutablePath,CommandLine,ParentProcessID from Win32_Process" ) #can't get process owner with this method for process in processes: try: owner = process.ExecMethod_("GetOwner") username = support.convert_to_string( owner.Domain) + "\\" + support.convert_to_string(owner.User) except: username = "" processID = process.ProcessID processName = support.convert_to_string(process.Name) processId = support.convert_to_string(process.ProcessId) processCreationDate = support.convertDate( support.convert_to_string(process.CreationDate)) processThreadCount = support.convert_to_string(process.ThreadCount) processExecutablePath = support.convert_to_string( process.ExecutablePath) processCommandLine = support.convert_to_string(process.CommandLine) processParentProcessId = support.convert_to_string( process.ParentProcessId) outFile.write( processName.replace(",", " ") + "," + processId + "," + processCreationDate + "," + username.replace(",", " ") + "," + processThreadCount + "," + processExecutablePath.replace(",", " ") + "," + processCommandLine.replace(",", " ") + "," + processParentProcessId + "\n") modules = objWMIService.ExecQuery( "associators of {win32_process.handle='" + processId + "'} where AssocClass = CIM_ProcessExecutable") try: for module in modules: moduleName = support.convert_to_string(module.Name) outFile2.write(processId + "," + moduleName.replace(",", " ") + "\n") except: pass outFile2.close() outFile.close()
def read_nt5_entries(bin_data, entry, computerName): try: entry_list = [] contains_file_size = False entry_size = entry.size() exec_flag = '' num_entries = struct.unpack('<L', bin_data[4:8])[0] if num_entries == 0: return None # On Windows Server 2008/Vista, the filesize is swapped out of this # structure with two 4-byte flags. Check to see if any of the values in # "dwFileSizeLow" are larger than 2-bits. This indicates the entry contained file sizes. for offset in xrange(CACHE_HEADER_SIZE_NT5_2, (num_entries * entry_size),entry_size): entry.update(bin_data[offset:offset+entry_size]) if entry.dwFileSizeLow > 3: contains_file_size = True break # Now grab all the data in the value. for offset in xrange(CACHE_HEADER_SIZE_NT5_2, (num_entries * entry_size),entry_size): entry.update(bin_data[offset:offset+entry_size]) last_mod_date = convert_filetime(entry.dwLowDateTime, entry.dwHighDateTime) try: last_mod_date = last_mod_date.strftime("%Y/%m/%d %H:%M:%S") except ValueError: last_mod_date = bad_entry_data path = bin_data[entry.Offset:entry.Offset + entry.wLength].decode('utf-16le', 'replace').encode('utf-8') path = path.replace("\\??\\", "") # It contains file size data. if contains_file_size: hit = [last_mod_date, bad_entry_data, support.convert_to_string(path).replace(","," "), str(entry.dwFileSizeLow), bad_entry_data] if hit not in entry_list: entry_list.append(hit) # It contains flags. else: # Check the flag set in CSRSS if (entry.dwFileSizeLow & CSRSS_FLAG): exec_flag = 'True' else: exec_flag = 'False' hit = [last_mod_date, bad_entry_data, support.convert_to_string(path).replace(","," "), bad_entry_data, exec_flag] if hit not in entry_list: entry_list.append(hit) return entry_list except (RuntimeError, ValueError, NameError), err: print computerName + " - error reading shim cache data: %s..." % err return None
def getServiceDLLs(computerName, objRegistry, hostPath): print computerName + " - checking service DLLs" outFile = open(hostPath + "\SERVICEDLLS-" + computerName + ".csv", "w") outFile.write("service,display_name,service_path,service_dll\n") key = "SYSTEM\CurrentControlSet\Services" result, subkeys = objRegistry.EnumKey(hDefKey=_winreg.HKEY_LOCAL_MACHINE, sSubKeyName=key) if result == 0: for subkey in subkeys: display_name = "NULL" service_path = "NULL" service_dll = "NULL" result, valueNames, valueTypes = objRegistry.EnumValues( hDefKey=_winreg.HKEY_LOCAL_MACHINE, sSubKeyName=key + "\\" + subkey) if result == 0: if valueNames != None and len(valueNames) > 0: for value in valueNames: if value.upper() == "DisplayName".upper(): result, display_name = objRegistry.GetStringValue( hDefKey=_winreg.HKEY_LOCAL_MACHINE, sSubKeyName=key + "\\" + subkey, sValueName=value) if result != 0: display_name = "NULL" elif value.upper() == "ImagePath".upper(): result, service_path = objRegistry.GetStringValue( hDefKey=_winreg.HKEY_LOCAL_MACHINE, sSubKeyName=key + "\\" + subkey, sValueName=value) if result != 0: service_path = "NULL" result, service_dll = objRegistry.GetStringValue( hDefKey=_winreg.HKEY_LOCAL_MACHINE, sSubKeyName=key + "\\" + subkey + "\\Parameters", sValueName="ServiceDll") if result != 0: service_dll = "NULL" display_name = support.convert_to_string(display_name) service_path = support.convert_to_string(service_path) service_dll = support.convert_to_string(service_dll) outFile.write( subkey.replace(",", " ") + "," + display_name.replace(",", " ") + "," + service_path.replace(",", " ") + "," + service_dll.replace(",", " ") + "\n") outFile.close()
def getServices(computerName, objWMIService, hostPath): print computerName + " - checking services" outFile = open(hostPath + "\SERVICES-" + computerName + ".csv", "w") outFile.write( "service,path,install_date,pid,start_mode,account,state,description\n") services = objWMIService.ExecQuery( "Select Name,PathName,InstallDate,ProcessId,StartMode,StartName,State,Description from Win32_Service" ) for service in services: serviceName = support.convert_to_string(service.Name) servicePathName = support.convert_to_string(service.PathName) serviceInstallDate = support.convertDate( support.convert_to_string(service.InstallDate)) serviceProcessId = support.convert_to_string(service.ProcessId) serviceStartMode = support.convert_to_string(service.StartMode) serviceStartName = support.convert_to_string(service.StartName) serviceState = support.convert_to_string(service.State) serviceDescription = support.convert_to_string( service.Description).replace("\n", " ") outFile.write( serviceName.replace(",", " ") + "," + servicePathName.replace(",", " ") + "," + serviceInstallDate + "," + serviceProcessId.replace(",", " ") + "," + serviceStartMode.replace(",", " ") + "," + serviceStartName.replace(",", " ") + "," + serviceState.replace(",", " ") + "," + serviceDescription.replace(",", " ") + "\n") outFile.close()
def read_nt6_entries(bin_data, entry, computerName): try: entry_list = [] exec_flag = "" entry_size = entry.size() num_entries = struct.unpack('<L', bin_data[4:8])[0] if num_entries == 0: return None # Walk each entry in the data structure. for offset in xrange(CACHE_HEADER_SIZE_NT6_1,num_entries*entry_size,entry_size): entry.update(bin_data[offset:offset+entry_size]) last_mod_date = convert_filetime(entry.dwLowDateTime,entry.dwHighDateTime) try: last_mod_date = last_mod_date.strftime("%Y/%m/%d %H:%M:%S") except ValueError: last_mod_date = bad_entry_data path = (bin_data[entry.Offset:entry.Offset + entry.wLength].decode('utf-16le','replace').encode('utf-8')) path = path.replace("\\??\\", "") # Test to see if the file may have been executed. if (entry.FileFlags & CSRSS_FLAG): exec_flag = 'True' else: exec_flag = 'False' hit = [last_mod_date, bad_entry_data, support.convert_to_string(path).replace(","," "), bad_entry_data, exec_flag] if hit not in entry_list: entry_list.append(hit) return entry_list except (RuntimeError, ValueError, NameError), err: print computerNAme + " - error reading shim cache data: %s..." % err return None
def read_win8_entries(bin_data, ver_magic, computerName): entry_meta_len = 12 entry_list = [] # Skip past the stats in the header cache_data = bin_data[WIN8_STATS_SIZE:] data = sio.StringIO(cache_data) while data.tell() < len(cache_data): header = data.read(entry_meta_len) # Read in the entry metadata # Note: the crc32 hash is of the cache entry data magic, crc32_hash, entry_len = struct.unpack('<4sLL', header) # Check the magic tag if magic != ver_magic: raise Exception("Invalid version magic tag found: 0x%x" % struct.unpack("<L", magic)[0]) entry_data = sio.StringIO(data.read(entry_len)) # Read the path length path_len = struct.unpack('<H', entry_data.read(2))[0] if path_len == 0: path = 'None' else: path = entry_data.read(path_len).decode('utf-16le', 'replace').encode('utf-8') # Check for package data package_len = struct.unpack('<H', entry_data.read(2))[0] if package_len > 0: # Just skip past the package data if present (for now) entry_data.seek(package_len, 1) # Read the remaining entry data flags, unk_1, low_datetime, high_datetime, unk_2 = struct.unpack( '<LLLLL', entry_data.read(20)) # Check the flag set in CSRSS if (flags & CSRSS_FLAG): exec_flag = 'True' else: exec_flag = 'False' last_mod_date = convert_filetime(low_datetime, high_datetime) try: last_mod_date = last_mod_date.strftime("%Y/%m/%d %H:%M:%S") except ValueError: last_mod_date = bad_entry_data row = [ last_mod_date, bad_entry_data, support.convert_to_string(path).replace(",", " "), bad_entry_data, exec_flag ] entry_list.append(row) return entry_list
def getProcesses(computerName,objWMIService,hostPath): print computerName + " - checking processes and process modules" outFile = open(hostPath + "\PROCESSES-" + computerName + ".csv", "w") outFile.write("process,pid,creation_date,process_owner,threat_count,path,cmd_line,ppid\n") outFile2 = open(hostPath + "\PROCESSMODULES-" + computerName + ".csv", "w") outFile2.write("pid,module_path\n") processes = objWMIService.ExecQuery("select Name,ProcessID,CreationDate,ThreadCount,ExecutablePath,CommandLine,ParentProcessID from Win32_Process") #can't get process owner with this method for process in processes: try: owner = process.ExecMethod_("GetOwner") username = support.convert_to_string(owner.Domain) + "\\" + support.convert_to_string(owner.User) except: username = "" processID = process.ProcessID processName = support.convert_to_string(process.Name) processId = support.convert_to_string(process.ProcessId) processCreationDate = support.convertDate(support.convert_to_string(process.CreationDate)) processThreadCount = support.convert_to_string(process.ThreadCount) processExecutablePath = support.convert_to_string(process.ExecutablePath) processCommandLine = support.convert_to_string(process.CommandLine) processParentProcessId = support.convert_to_string(process.ParentProcessId) outFile.write(processName.replace(","," ") + "," + processId + "," + processCreationDate + "," + username.replace(","," ") + "," + processThreadCount + "," + processExecutablePath.replace(","," ") + "," + processCommandLine.replace(","," ") + "," + processParentProcessId + "\n") modules = objWMIService.ExecQuery("associators of {win32_process.handle='" + processId + "'} where AssocClass = CIM_ProcessExecutable") try: for module in modules: moduleName = support.convert_to_string(module.Name) outFile2.write(processId + "," + moduleName.replace(","," ") + "\n") except: pass outFile2.close() outFile.close()
def read_win8_entries(bin_data, ver_magic, computerName): entry_meta_len = 12 entry_list = [] # Skip past the stats in the header cache_data = bin_data[WIN8_STATS_SIZE:] data = sio.StringIO(cache_data) while data.tell() < len(cache_data): header = data.read(entry_meta_len) # Read in the entry metadata # Note: the crc32 hash is of the cache entry data magic, crc32_hash, entry_len = struct.unpack('<4sLL', header) # Check the magic tag if magic != ver_magic: raise Exception("Invalid version magic tag found: 0x%x" % struct.unpack("<L", magic)[0]) entry_data = sio.StringIO(data.read(entry_len)) # Read the path length path_len = struct.unpack('<H', entry_data.read(2))[0] if path_len == 0: path = 'None' else: path = entry_data.read(path_len).decode('utf-16le', 'replace').encode('utf-8') # Check for package data package_len = struct.unpack('<H', entry_data.read(2))[0] if package_len > 0: # Just skip past the package data if present (for now) entry_data.seek(package_len, 1) # Read the remaining entry data flags, unk_1, low_datetime, high_datetime, unk_2 = struct.unpack('<LLLLL', entry_data.read(20)) # Check the flag set in CSRSS if (flags & CSRSS_FLAG): exec_flag = 'True' else: exec_flag = 'False' last_mod_date = convert_filetime(low_datetime, high_datetime) try: last_mod_date = last_mod_date.strftime("%Y/%m/%d %H:%M:%S") except ValueError: last_mod_date = bad_entry_data row = [last_mod_date, bad_entry_data, support.convert_to_string(path).replace(","," "), bad_entry_data, exec_flag] entry_list.append(row) return entry_list
def getFileList(computerName, objWMIService, hostPath, tmpIndicators): print computerName + " - checking file lists" outFile = open(hostPath + "\FILELIST-" + computerName + ".csv", "w") outFile.write("file,created,modified,last_accessed,size\n") configFile = support.resource_path("config\\FileList.txt") with open(configFile, "r") as scanPathsFile: scanPaths = scanPathsFile.readlines() scanPaths = scanPaths + tmpIndicators for path in scanPaths: path = path.replace("\n", "") if not path.strip(): continue if "\\" != path[-1:]: path = path + "\\" path = path.replace("\\", "\\\\") drivePos = path.find(":") + 1 drive = path[0:drivePos] path = path[drivePos:] query = "Select Name,CreationDate,LastModified,LastAccessed,FileSize From CIM_DataFile Where Path = \"" + path + "\"" if drive: query += " And Drive = \"" + drive + "\"" filelist = objWMIService.ExecQuery(query) for file in filelist: filename = support.convert_to_string(file.Name) filesize = support.convert_to_string(file.FileSize) outFile.write( filename.replace(",", " ") + "," + support.convertDate(file.CreationDate) + "," + support.convertDate(file.LastModified) + "," + support.convertDate(file.LastAccessed) + "," + filesize + "\n") outFile.close()
def getShellbags(computerName, objRegistry, hostPath, registryList): print computerName + " - checking shellbags" userpath2 = "" for hive, username, userpath in registryList: outFile = open( hostPath + "\SHELLBAGS-" + username + "-" + computerName + ".csv", "w") outFile.write("path,created,modified,accessed\n") if hive == _winreg.HKEY_LOCAL_MACHINE: print computerName + " - shellbags: checking logged out user (" + username + ")..." userpath2 = userpath + "2" elif hive == _winreg.HKEY_USERS: print computerName + " - shellbags: checking logged in user (" + username + ")..." userpath2 = userpath + "\Software\Classes" keys = [ userpath + "\Software\Microsoft\Windows\Shell", userpath + "\Software\Microsoft\Windows\ShellNoRoam", userpath2 + "\Local Settings\Software\Microsoft\Windows\Shell", userpath2 + "\Local Settings\Software\Microsoft\Windows\ShellNoRoam" ] shellbags = [] for key in keys: new_shellbags = get_shellbags(objRegistry, hive, key) shellbags.extend(new_shellbags) for shellbag in shellbags: outFile.write( support.convert_to_string(shellbag["path"]).replace(",", " ") + "," + support.convert_to_string(shellbag["crtime"]) + "," + support.convert_to_string(shellbag["mtime"]) + "," + support.convert_to_string(shellbag["atime"]) + "\n") outFile.close()
def getServiceDLLs(computerName,objRegistry,hostPath): print computerName + " - checking service DLLs" outFile = open(hostPath + "\SERVICEDLLS-" + computerName + ".csv", "w") outFile.write("service,display_name,service_path,service_dll\n") key = "SYSTEM\CurrentControlSet\Services" result,subkeys = objRegistry.EnumKey(hDefKey=_winreg.HKEY_LOCAL_MACHINE,sSubKeyName=key) if result == 0: for subkey in subkeys: display_name = "NULL" service_path = "NULL" service_dll = "NULL" result,valueNames,valueTypes = objRegistry.EnumValues(hDefKey=_winreg.HKEY_LOCAL_MACHINE,sSubKeyName=key+"\\"+subkey) if result == 0: if valueNames != None and len(valueNames) > 0: for value in valueNames: if value.upper() == "DisplayName".upper(): result,display_name = objRegistry.GetStringValue(hDefKey=_winreg.HKEY_LOCAL_MACHINE,sSubKeyName=key+"\\"+subkey,sValueName=value) if result != 0: display_name = "NULL" elif value.upper() == "ImagePath".upper(): result,service_path = objRegistry.GetStringValue(hDefKey=_winreg.HKEY_LOCAL_MACHINE,sSubKeyName=key+"\\"+subkey,sValueName=value) if result != 0: service_path = "NULL" result,service_dll = objRegistry.GetStringValue(hDefKey=_winreg.HKEY_LOCAL_MACHINE,sSubKeyName=key+"\\"+subkey+"\\Parameters",sValueName="ServiceDll") if result != 0: service_dll = "NULL" display_name = support.convert_to_string(display_name) service_path = support.convert_to_string(service_path) service_dll = support.convert_to_string(service_dll) outFile.write(subkey.replace(","," ") + "," + display_name.replace(","," ") + "," + service_path.replace(","," ") + "," + service_dll.replace(","," ") + "\n") outFile.close()
def read_winxp_entries(bin_data, computerName): entry_list = [] try: num_entries = struct.unpack('<L', bin_data[8:12])[0] if num_entries == 0: return None for offset in xrange(WINXP_HEADER_SIZE32,(num_entries*WINXP_ENTRY_SIZE32), WINXP_ENTRY_SIZE32): # No size values are included in these entries, so search for utf-16 terminator. path_len = bin_data[offset:offset+(MAX_PATH + 8)].find("\x00\x00") # if path is corrupt, procede to next entry. if path_len == 0: continue path = bin_data[offset:offset+path_len + 1].decode('utf-16le').encode('utf-8') # Clean up the pathname. path = path.replace('\\??\\', '') if len(path) == 0: continue entry_data = (offset+(MAX_PATH+8)) # Get last mod time. last_mod_time = struct.unpack('<2L', bin_data[entry_data:entry_data+8]) try: last_mod_time = convert_filetime(last_mod_time[0],last_mod_time[1]).strftime("%Y/%m/%d %H:%M:%S") except ValueError: last_mod_time = bad_entry_data # Get last file size. file_size = struct.unpack('<2L', bin_data[entry_data + 8:entry_data + 16])[0] if file_size == 0: file_size = bad_entry_data # Get last update time. exec_time = struct.unpack('<2L', bin_data[entry_data + 16:entry_data + 24]) try: exec_time = convert_filetime(exec_time[0],exec_time[1]).strftime("%Y/%m/%d %H:%M:%S") except ValueError: exec_time = bad_entry_data hit = [last_mod_time, exec_time, support.convert_to_string(path).replace(","," "), file_size, bad_entry_data] if hit not in entry_list: entry_list.append(hit) return entry_list except (RuntimeError, ValueError, NameError), err: print computerName + " - error reading shim cache data %s" % err return None
def getFileList(computerName,objWMIService,hostPath,tmpIndicators): print computerName + " - checking file lists" outFile = open(hostPath + "\FILELIST-" + computerName + ".csv", "w") outFile.write("file,created,modified,last_accessed,size\n") configFile = support.resource_path("config\\FileList.txt") with open(configFile, "r") as scanPathsFile: scanPaths = scanPathsFile.readlines() scanPaths = scanPaths + tmpIndicators for path in scanPaths: path = path.replace("\n","") if not path.strip(): continue if "\\" != path[-1:]: path = path + "\\" path = path.replace("\\","\\\\") drivePos = path.find(":")+1 drive = path[0:drivePos] path = path[drivePos:] query = "Select Name,CreationDate,LastModified,LastAccessed,FileSize From CIM_DataFile Where Path = \"" + path + "\"" if drive: query += " And Drive = \"" + drive + "\"" filelist = objWMIService.ExecQuery(query) for file in filelist: filename = support.convert_to_string(file.Name) filesize = support.convert_to_string(file.FileSize) outFile.write(filename.replace(","," ") + "," + support.convertDate(file.CreationDate) + "," + support.convertDate(file.LastModified) + "," + support.convertDate(file.LastAccessed) + "," + filesize + "\n") outFile.close()
def getDirectoryList(computerName, objWMIService, hostPath, tmpIndicators): print computerName + " - enumerating directory lists" outFile = open(hostPath + "\DIRECTORYLIST-" + computerName + ".csv", "w") outFile.write("directory,created,modified,last_accessed\n") configFile = support.resource_path("config\\DirectoryList.txt") with open(configFile, "r") as scanPathsFile: scanPaths = scanPathsFile.readlines() scanPaths = scanPaths + tmpIndicators for path in scanPaths: path = path.replace("\n", "") if not path.strip(): continue if "\\" != path[-1:]: path = path + "\\" path = path.replace("\\", "\\\\") drivePos = path.find(":") + 1 drive = path[0:drivePos] path = path[drivePos:] #path must contain the drive in associators query - for some reason you cant split Path and Drive in this query - also paths must not contain trailing slash #query = "Associators of {Win32_Directory.Name='" + path + "'} WHERE AssocClass = Win32_Subdirectory ResultRole = PartComponent" query = "Select Name,CreationDate,LastModified,LastAccessed From WIN32_Directory Where Path = \"" + path + "\"" if drive: query += " And Drive = \"" + drive + "\"" dirlist = objWMIService.ExecQuery(query) try: for dir in dirlist: dirname = support.convert_to_string(dir.Name) outFile.write( dirname.replace(",", " ") + "," + support.convertDate(dir.CreationDate) + "," + support.convertDate(dir.LastModified) + "," + support.convertDate(dir.LastAccessed) + "\n") except: pass outFile.close()
def read_nt6_entries(bin_data, entry, computerName): try: entry_list = [] exec_flag = "" entry_size = entry.size() num_entries = struct.unpack('<L', bin_data[4:8])[0] if num_entries == 0: return None # Walk each entry in the data structure. for offset in xrange(CACHE_HEADER_SIZE_NT6_1, num_entries * entry_size, entry_size): entry.update(bin_data[offset:offset + entry_size]) last_mod_date = convert_filetime(entry.dwLowDateTime, entry.dwHighDateTime) try: last_mod_date = last_mod_date.strftime("%Y/%m/%d %H:%M:%S") except ValueError: last_mod_date = bad_entry_data path = (bin_data[entry.Offset:entry.Offset + entry.wLength].decode( 'utf-16le', 'replace').encode('utf-8')) path = path.replace("\\??\\", "") # Test to see if the file may have been executed. if (entry.FileFlags & CSRSS_FLAG): exec_flag = 'True' else: exec_flag = 'False' hit = [ last_mod_date, bad_entry_data, support.convert_to_string(path).replace(",", " "), bad_entry_data, exec_flag ] if hit not in entry_list: entry_list.append(hit) return entry_list except (RuntimeError, ValueError, NameError), err: print computerName + " - error reading shim cache data: %s..." % err return None
def getDirectoryList(computerName,objWMIService,hostPath,tmpIndicators): print computerName + " - enumerating directory lists" outFile = open(hostPath + "\DIRECTORYLIST-" + computerName + ".csv", "w") outFile.write("directory,created,modified,last_accessed\n") configFile = support.resource_path("config\\DirectoryList.txt") with open(configFile, "r") as scanPathsFile: scanPaths = scanPathsFile.readlines() scanPaths = scanPaths + tmpIndicators for path in scanPaths: path = path.replace("\n","") if not path.strip(): continue if "\\" != path[-1:]: path = path + "\\" path = path.replace("\\","\\\\") drivePos = path.find(":")+1 drive = path[0:drivePos] path = path[drivePos:] #path must contain the drive in associators query - for some reason you cant split Path and Drive in this query - also paths must not contain trailing slash #query = "Associators of {Win32_Directory.Name='" + path + "'} WHERE AssocClass = Win32_Subdirectory ResultRole = PartComponent" query = "Select Name,CreationDate,LastModified,LastAccessed From WIN32_Directory Where Path = \"" + path + "\"" if drive: query += " And Drive = \"" + drive + "\"" dirlist = objWMIService.ExecQuery(query) try: for dir in dirlist: dirname = support.convert_to_string(dir.Name) outFile.write(dirname.replace(","," ") + "," + support.convertDate(dir.CreationDate) + "," + support.convertDate(dir.LastModified) + "," + support.convertDate(dir.LastAccessed) + "\n") except: pass outFile.close()
def getServices(computerName,objWMIService,hostPath): print computerName + " - checking services" outFile = open(hostPath + "\SERVICES-" + computerName + ".csv", "w") outFile.write("service,path,install_date,pid,start_mode,account,state,description\n") services = objWMIService.ExecQuery("Select Name,PathName,InstallDate,ProcessId,StartMode,StartName,State,Description from Win32_Service") for service in services: serviceName = support.convert_to_string(service.Name) servicePathName = support.convert_to_string(service.PathName) serviceInstallDate = support.convertDate(support.convert_to_string(service.InstallDate)) serviceProcessId = support.convert_to_string(service.ProcessId) serviceStartMode = support.convert_to_string(service.StartMode) serviceStartName = support.convert_to_string(service.StartName) serviceState = support.convert_to_string(service.State) serviceDescription = support.convert_to_string(service.Description).replace("\n"," ") outFile.write(serviceName.replace(","," ") + "," + servicePathName.replace(","," ") + "," + serviceInstallDate + "," + serviceProcessId.replace(","," ") + "," + serviceStartMode.replace(","," ") + "," + serviceStartName.replace(","," ") + "," + serviceState.replace(","," ") + "," + serviceDescription.replace(","," ") + "\n") outFile.close()
def read_winxp_entries(bin_data, computerName): entry_list = [] try: num_entries = struct.unpack('<L', bin_data[8:12])[0] if num_entries == 0: return None for offset in xrange(WINXP_HEADER_SIZE32, (num_entries * WINXP_ENTRY_SIZE32), WINXP_ENTRY_SIZE32): # No size values are included in these entries, so search for utf-16 terminator. path_len = bin_data[offset:offset + (MAX_PATH + 8)].find("\x00\x00") # if path is corrupt, procede to next entry. if path_len == 0: continue path = bin_data[offset:offset + path_len + 1].decode('utf-16le').encode('utf-8') # Clean up the pathname. path = path.replace('\\??\\', '') if len(path) == 0: continue entry_data = (offset + (MAX_PATH + 8)) # Get last mod time. last_mod_time = struct.unpack('<2L', bin_data[entry_data:entry_data + 8]) try: last_mod_time = convert_filetime( last_mod_time[0], last_mod_time[1]).strftime("%Y/%m/%d %H:%M:%S") except ValueError: last_mod_time = bad_entry_data # Get last file size. file_size = struct.unpack('<2L', bin_data[entry_data + 8:entry_data + 16])[0] if file_size == 0: file_size = bad_entry_data # Get last update time. exec_time = struct.unpack( '<2L', bin_data[entry_data + 16:entry_data + 24]) try: exec_time = convert_filetime( exec_time[0], exec_time[1]).strftime("%Y/%m/%d %H:%M:%S") except ValueError: exec_time = bad_entry_data hit = [ last_mod_time, exec_time, support.convert_to_string(path).replace(",", " "), file_size, bad_entry_data ] if hit not in entry_list: entry_list.append(hit) return entry_list except (RuntimeError, ValueError, NameError), err: print computerName + " - error reading shim cache data %s" % err return None
def getLocalAccounts(computerName,objWMIService,hostPath): print computerName + " - checking local accounts" outFile = open(hostPath + "\ACCOUNTS-" + computerName + ".csv", "w") outFile.write("account_type,caption,description,disabled,domain,full_name,local_account,lockout,install_date,name,password_changeable,password_expires,password_required,sid,sid_type,status\n") query = "Select DomainRole From Win32_ComputerSystem" domainRoles = objWMIService.ExecQuery(query) for domainRole in domainRoles: if domainRole.DomainRole == 4 or domainRole.domainRole == 5: outFile.write("This is a domain controller. The local accounts cannot be accessed\n") else: query = "Select InstallDate,AccountType,Caption,Description,Disabled,Domain,FullName,LocalAccount,Lockout,Name,PasswordChangeable,PasswordExpires,PasswordRequired,SID,SIDType,Status from Win32_UserAccount Where LocalAccount = True" accounts = objWMIService.ExecQuery(query) for account in accounts: accountType = support.convert_to_string(account.AccountType) accountCaption = support.convert_to_string(account.Caption) accountDescription = support.convert_to_string(account.Description) accountDisabled = support.convert_to_string(account.Disabled) if accountDisabled.upper() == "TRUE": accountDisabled = "1" else: accountDisabled = "0" accountDomain = support.convert_to_string(account.Domain) accountFullName = support.convert_to_string(account.FullName) accountLocalAccount = support.convert_to_string(account.LocalAccount) if accountLocalAccount.upper() == "TRUE": accountLocalAccount = "1" else: accountLocalAccount = "0" accountLockout = support.convert_to_string(account.Lockout) if accountLockout.upper() == "TRUE": accountLockout = "1" else: accountLockout = "0" accountInstallDate = support.convertDate(support.convert_to_string(account.InstallDate)) accountName = support.convert_to_string(account.Name) accountPasswordChangeable = support.convert_to_string(account.PasswordChangeable) if accountPasswordChangeable.upper() == "TRUE": accountPasswordChangeable = "1" else: accountPasswordChangeable = "0" accountPasswordExpires = support.convert_to_string(account.PasswordExpires) if accountPasswordExpires.upper() == "TRUE": accountPasswordExpires = "1" else: accountPasswordExpires = "0" accountPasswordRequired = support.convert_to_string(account.PasswordRequired) if accountPasswordRequired.upper() == "TRUE": accountPasswordRequired = "1" else: accountPasswordRequired = "0" accountSID = support.convert_to_string(account.SID) accountSIDType = support.convert_to_string(account.SIDType) accountStatus = support.convert_to_string(account.Status) outFile.write(accountType.replace(","," ") + "," + accountCaption.replace(","," ") + "," + accountDescription.replace(","," ") + "," + accountDisabled + "," + accountDomain.replace(","," ") + "," + accountFullName.replace(","," ") + "," + accountLocalAccount + "," + accountLockout + "," + accountInstallDate + "," + accountName.replace(","," ") + "," + accountPasswordChangeable + "," + accountPasswordExpires + "," + accountPasswordRequired + "," + accountSID.replace(","," ") + "," + accountSIDType.replace(","," ") + "," + accountStatus.replace(","," ") + "\n") outFile.close() break outFile = open(hostPath + "\LOCALADMINS-" + computerName + ".csv", "w") outFile.write("domain,user") query = "select * from Win32_GroupUser where GroupComponent = \"Win32_Group.Domain='" + computerName + "',Name='Administrators'\"" admins = objWMIService.ExecQuery(query) for admin in admins: partComponent = support.convert_to_string(admin.PartComponent) domainPos = partComponent.find("Win32_UserAccount.Domain=") + len("Win32_UserAccount.Domain=") if domainPos <= len("Win32_UserAccount.Domain="): domainPos = partComponent.find("Win32_Group.Domain=") + len("Win32_Group.Domain=") namePos = partComponent.find(",Name=",domainPos) if domainPos <= len("Win32_Group.Domain="): domain = "" else: domain = partComponent[domainPos+1:namePos-1] #remove quotes namePos += len(",Name=") if namePos <= len(",Name="): name = "" else: name = partComponent[namePos+1:-1] #remove quotes outFile.write(domain + "," + name + "\n") outFile.close()
def read_nt5_entries(bin_data, entry, computerName): try: entry_list = [] contains_file_size = False entry_size = entry.size() exec_flag = '' num_entries = struct.unpack('<L', bin_data[4:8])[0] if num_entries == 0: return None # On Windows Server 2008/Vista, the filesize is swapped out of this # structure with two 4-byte flags. Check to see if any of the values in # "dwFileSizeLow" are larger than 2-bits. This indicates the entry contained file sizes. for offset in xrange(CACHE_HEADER_SIZE_NT5_2, (num_entries * entry_size), entry_size): entry.update(bin_data[offset:offset + entry_size]) if entry.dwFileSizeLow > 3: contains_file_size = True break # Now grab all the data in the value. for offset in xrange(CACHE_HEADER_SIZE_NT5_2, (num_entries * entry_size), entry_size): entry.update(bin_data[offset:offset + entry_size]) last_mod_date = convert_filetime(entry.dwLowDateTime, entry.dwHighDateTime) try: last_mod_date = last_mod_date.strftime("%Y/%m/%d %H:%M:%S") except ValueError: last_mod_date = bad_entry_data path = bin_data[entry.Offset:entry.Offset + entry.wLength].decode( 'utf-16le', 'replace').encode('utf-8') path = path.replace("\\??\\", "") # It contains file size data. if contains_file_size: hit = [ last_mod_date, bad_entry_data, support.convert_to_string(path).replace(",", " "), str(entry.dwFileSizeLow), bad_entry_data ] if hit not in entry_list: entry_list.append(hit) # It contains flags. else: # Check the flag set in CSRSS if (entry.dwFileSizeLow & CSRSS_FLAG): exec_flag = 'True' else: exec_flag = 'False' hit = [ last_mod_date, bad_entry_data, support.convert_to_string(path).replace(",", " "), bad_entry_data, exec_flag ] if hit not in entry_list: entry_list.append(hit) return entry_list except (RuntimeError, ValueError, NameError), err: print computerName + " - error reading shim cache data: %s..." % err return None
def getTasks(computerName,objWMIService,hostPath): print computerName + " - checking tasks" outFile = open(hostPath + "\TASKS-" + computerName + ".csv", "w") outFile.write("command,days_of_month,days_of_week,description,elapsed_time,install_date,interact_with_desktop,job_id,job_status,name,notify,owner,priority,run_repeatedly,start_time,status,time_submitted,until_time\n") tasks = objWMIService.ExecQuery("Select * from Win32_ScheduledJob") for task in tasks: taskCommand = support.convert_to_string(task.Command) taskDaysOfMonth = support.convert_to_string(task.DaysOfMonth) if taskDaysOfMonth == "None": taskDaysOfMonth = "NULL" taskDaysOfWeek = support.convert_to_string(task.DaysOfWeek) if taskDaysOfWeek == "None": taskDaysOfWeek = "NULL" taskDescription = support.convert_to_string(task.Description) taskElapsedTime = support.convertDate(support.convert_to_string(task.ElapsedTime)) taskInstallDate = support.convertDate(support.convert_to_string(task.InstallDate)) taskInteractWithDesktop = support.convert_to_string(task.InteractWithDesktop) if taskInteractWithDesktop.upper() == "TRUE": taskInteractWithDesktop = "1" else: taskInteractWithDesktop = "0" taskJobId = support.convert_to_string(task.JobId) taskJobStatus = support.convert_to_string(task.JobStatus) taskName = support.convert_to_string(task.Name) taskNotify = support.convert_to_string(task.Notify) taskOwner = support.convert_to_string(task.Owner) taskPriority = support.convert_to_string(task.Priority) if taskPriority == "None": taskPriority = "NULL" taskRunRepeatedly = support.convert_to_string(task.RunRepeatedly) if taskRunRepeatedly.upper() == "TRUE": taskRunRepeatedly = "1" else: taskRunRepeatedly = "0" taskStartTime = support.convertDate(support.convert_to_string(task.StartTime)) taskStatus = support.convert_to_string(task.Status) taskTimeSubmitted = support.convertDate(support.convert_to_string(task.TimeSubmitted)) taskUntilTime = support.convertDate(support.convert_to_string(task.UntilTime)) outFile.write(taskCommand.replace(","," ") + "," + taskDaysOfMonth.replace(","," ") + "," + taskDaysOfWeek.replace(","," ") + "," + taskDescription.replace(","," ") + "," + taskElapsedTime.replace(","," ") + "," + taskInstallDate.replace(","," ") + "," + taskInteractWithDesktop.replace(","," ") + "," + taskJobId.replace(","," ") + "," + taskJobStatus.replace(","," ") + "," + taskName.replace(","," ") + "," + taskNotify.replace(","," ") + "," + taskOwner.replace(","," ") + "," + taskPriority.replace(","," ") + "," + taskRunRepeatedly.replace(","," ") + "," + taskStartTime.replace(","," ") + "," + taskStatus.replace(","," ") + "," + taskTimeSubmitted.replace(","," ") + "," + taskUntilTime.replace(","," ") + "\n") outFile.close()
def getLocalAccounts(computerName, objWMIService, hostPath): print computerName + " - checking local accounts" outFile = open(hostPath + "\ACCOUNTS-" + computerName + ".csv", "w") outFile.write( "account_type,caption,description,disabled,domain,full_name,local_account,lockout,install_date,name,password_changeable,password_expires,password_required,sid,sid_type,status\n" ) query = "Select DomainRole From Win32_ComputerSystem" domainRoles = objWMIService.ExecQuery(query) for domainRole in domainRoles: if domainRole.DomainRole == 4 or domainRole.domainRole == 5: outFile.write( "This is a domain controller. The local accounts cannot be accessed\n" ) else: query = "Select InstallDate,AccountType,Caption,Description,Disabled,Domain,FullName,LocalAccount,Lockout,Name,PasswordChangeable,PasswordExpires,PasswordRequired,SID,SIDType,Status from Win32_UserAccount Where LocalAccount = True" accounts = objWMIService.ExecQuery(query) for account in accounts: accountType = support.convert_to_string(account.AccountType) accountCaption = support.convert_to_string(account.Caption) accountDescription = support.convert_to_string( account.Description) accountDisabled = support.convert_to_string(account.Disabled) if accountDisabled.upper() == "TRUE": accountDisabled = "1" else: accountDisabled = "0" accountDomain = support.convert_to_string(account.Domain) accountFullName = support.convert_to_string(account.FullName) accountLocalAccount = support.convert_to_string( account.LocalAccount) if accountLocalAccount.upper() == "TRUE": accountLocalAccount = "1" else: accountLocalAccount = "0" accountLockout = support.convert_to_string(account.Lockout) if accountLockout.upper() == "TRUE": accountLockout = "1" else: accountLockout = "0" accountInstallDate = support.convertDate( support.convert_to_string(account.InstallDate)) accountName = support.convert_to_string(account.Name) accountPasswordChangeable = support.convert_to_string( account.PasswordChangeable) if accountPasswordChangeable.upper() == "TRUE": accountPasswordChangeable = "1" else: accountPasswordChangeable = "0" accountPasswordExpires = support.convert_to_string( account.PasswordExpires) if accountPasswordExpires.upper() == "TRUE": accountPasswordExpires = "1" else: accountPasswordExpires = "0" accountPasswordRequired = support.convert_to_string( account.PasswordRequired) if accountPasswordRequired.upper() == "TRUE": accountPasswordRequired = "1" else: accountPasswordRequired = "0" accountSID = support.convert_to_string(account.SID) accountSIDType = support.convert_to_string(account.SIDType) accountStatus = support.convert_to_string(account.Status) outFile.write( accountType.replace(",", " ") + "," + accountCaption.replace(",", " ") + "," + accountDescription.replace(",", " ") + "," + accountDisabled + "," + accountDomain.replace(",", " ") + "," + accountFullName.replace(",", " ") + "," + accountLocalAccount + "," + accountLockout + "," + accountInstallDate + "," + accountName.replace(",", " ") + "," + accountPasswordChangeable + "," + accountPasswordExpires + "," + accountPasswordRequired + "," + accountSID.replace(",", " ") + "," + accountSIDType.replace(",", " ") + "," + accountStatus.replace(",", " ") + "\n") outFile.close() break outFile = open(hostPath + "\LOCALADMINS-" + computerName + ".csv", "w") outFile.write("domain,user") query = "select * from Win32_GroupUser where GroupComponent = \"Win32_Group.Domain='" + computerName + "',Name='Administrators'\"" admins = objWMIService.ExecQuery(query) for admin in admins: partComponent = support.convert_to_string(admin.PartComponent) domainPos = partComponent.find("Win32_UserAccount.Domain=") + len( "Win32_UserAccount.Domain=") if domainPos <= len("Win32_UserAccount.Domain="): domainPos = partComponent.find("Win32_Group.Domain=") + len( "Win32_Group.Domain=") namePos = partComponent.find(",Name=", domainPos) if domainPos <= len("Win32_Group.Domain="): domain = "" else: domain = partComponent[domainPos + 1:namePos - 1] #remove quotes namePos += len(",Name=") if namePos <= len(",Name="): name = "" else: name = partComponent[namePos + 1:-1] #remove quotes outFile.write(domain + "," + name + "\n") outFile.close()