docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Initializes the lexer object. Args: data: optional initial data to be processed by the lexer.
def __init__(self, data=''): super(Lexer, self).__init__() self.buffer = data self.error = 0 self.flags = 0 self.processed = 0 self.processed_buffer = '' self.state = self._INITIAL_STATE self.state_stack = [] self.verbose = 0
287,967
Push the match back on the stream. Args: string: optional data.
def PushBack(self, string='', **unused_kwargs): self.buffer = string + self.buffer self.processed_buffer = self.processed_buffer[:-len(string)]
287,971
Initializes the lexer feeder min object. Args: file_object: Optional file-like object.
def __init__(self, file_object=None): super(SelfFeederMixIn, self).__init__() self.file_object = file_object
287,972
Feed data into the buffer. Args: size: optional data size to read form the file-like object.
def Feed(self, size=512): data = self.file_object.read(size) Lexer.Feed(self, data) return len(data)
287,973
Adds a new argument to this expression. Args: argument (str): argument to add. Returns: True if the argument is the last argument, False otherwise. Raises: ParseError: If there are too many arguments.
def AddArg(self, argument): self.args.append(argument) if len(self.args) > self.number_of_args: raise errors.ParseError('Too many arguments for this expression.') elif len(self.args) == self.number_of_args: return True return False
287,975
Escape backslashes found inside a string quote. Backslashes followed by anything other than ['"rnbt] will just be included in the string. Args: string: The string that matched. match: the match object (instance of re.MatchObject). Where match.group(1) contains the escaped code.
def StringEscape(self, string, match, **unused_kwargs): if match.group(1) in '\'"rnbt': self.string += string.decode('unicode_escape') else: self.string += string
287,983
Initializes a file entry filter. Args: filename (str): name of the file.
def __init__(self, filename): super(FileNameFileEntryFilter, self).__init__() self._filename = filename.lower()
287,987
Determines if a file entry matches the filter. Args: file_entry (dfvfs.FileEntry): a file entry. Returns: bool: True if the file entry matches the filter.
def Match(self, file_entry): if not file_entry: return False filename = file_entry.name.lower() return filename == self._filename
287,988
Enables parser plugins. Args: plugin_includes (list[str]): names of the plugins to enable, where None or an empty list represents all plugins. Note the default plugin, if it exists, is always enabled and cannot be disabled.
def EnablePlugins(self, plugin_includes): self._plugins = [] if not self._plugin_classes: return default_plugin_name = '{0:s}_default'.format(self.NAME) for plugin_name, plugin_class in iter(self._plugin_classes.items()): if plugin_name == default_plugin_name: self._default_plu...
287,990
Retrieves a specific plugin object by its name. Args: plugin_name (str): name of the plugin. Returns: BasePlugin: a plugin object or None if not available.
def GetPluginObjectByName(cls, plugin_name): plugin_class = cls._plugin_classes.get(plugin_name, None) if plugin_class: return plugin_class() return None
287,991
Registers a plugin class. The plugin classes are identified based on their lower case name. Args: plugin_class (type): class of the plugin. Raises: KeyError: if plugin class is already set for the corresponding name.
def RegisterPlugin(cls, plugin_class): plugin_name = plugin_class.NAME.lower() if plugin_name in cls._plugin_classes: raise KeyError(( 'Plugin class already set for name: {0:s}.').format( plugin_class.NAME)) cls._plugin_classes[plugin_name] = plugin_class
287,993
Parsers the file entry and extracts event objects. Args: parser_mediator (ParserMediator): a parser mediator. Raises: UnableToParseFile: when the file cannot be parsed.
def Parse(self, parser_mediator): file_entry = parser_mediator.GetFileEntry() if not file_entry: raise errors.UnableToParseFile('Invalid file entry') parser_mediator.AppendToParserChain(self) try: self.ParseFileEntry(parser_mediator, file_entry) finally: parser_mediator.PopFr...
287,994
Parses a single file-like object. Args: parser_mediator (ParserMediator): a parser mediator. file_object (dvfvs.FileIO): a file-like object to parse. Raises: UnableToParseFile: when the file cannot be parsed.
def Parse(self, parser_mediator, file_object): if not file_object: raise errors.UnableToParseFile('Invalid file object') if self._INITIAL_FILE_OFFSET is not None: file_object.seek(self._INITIAL_FILE_OFFSET, os.SEEK_SET) parser_mediator.AppendToParserChain(self) try: self.ParseFi...
287,995
Extract data from a Windows XML EventLog (EVTX) record. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. record_index (int): event record index. evtx_record (pyevtx.record): event record. recovered (Opti...
def _GetEventData( self, parser_mediator, record_index, evtx_record, recovered=False): event_data = WinEvtxRecordEventData() try: event_data.record_number = evtx_record.identifier except OverflowError as exception: parser_mediator.ProduceExtractionWarning(( 'unable to read ...
287,998
Extract data from a Windows XML EventLog (EVTX) record. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. record_index (int): event record index. evtx_record (pyevtx.record): event record. recovered (Opti...
def _ParseRecord( self, parser_mediator, record_index, evtx_record, recovered=False): event_data = self._GetEventData( parser_mediator, record_index, evtx_record, recovered=recovered) try: written_time = evtx_record.get_written_time_as_integer() except OverflowError as exception: ...
287,999
Parses Windows XML EventLog (EVTX) records. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. evtx_file (pyevt.file): Windows XML EventLog (EVTX) file.
def _ParseRecords(self, parser_mediator, evtx_file): # To handle errors when parsing a Windows XML EventLog (EVTX) file in the # most granular way the following code iterates over every event record. # The call to evt_file.get_record() and access to members of evt_record # should be called within a...
288,000
Parses a Windows XML EventLog (EVTX) file-like object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): a file-like object.
def ParseFileObject(self, parser_mediator, file_object): evtx_file = pyevtx.file() evtx_file.set_ascii_codepage(parser_mediator.codepage) try: evtx_file.open_file_object(file_object) except IOError as exception: parser_mediator.ProduceExtractionWarning( 'unable to open file w...
288,001
Determines the formatted message strings for an event object. Args: formatter_mediator (FormatterMediator): mediates the interactions between formatters and other components, such as storage and Windows EventLog resources. event (EventObject): event. Returns: tuple(str, s...
def GetMessages(self, formatter_mediator, event): if self.DATA_TYPE != event.data_type: raise errors.WrongFormatter('Unsupported data type: {0:s}.'.format( event.data_type)) event_values = event.CopyToDict() read_receipt = event_values.get('read_receipt', None) if read_receipt is ...
288,002
Parses a Windows Prefetch file-like object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): file-like object.
def ParseFileObject(self, parser_mediator, file_object): scca_file = pyscca.file() try: scca_file.open_file_object(file_object) except IOError as exception: parser_mediator.ProduceExtractionWarning( 'unable to open file with error: {0!s}'.format(exception)) return form...
288,005
Adds command line arguments to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper supports. Args: argument_group (argparse._ArgumentGroup|argparse.ArgumentParser): argparse group.
def AddArguments(cls, argument_group): argument_group.add_argument( '--analysis', metavar='PLUGIN_LIST', dest='analysis_plugins', default='', action='store', type=str, help=( 'A comma separated list of analysis plugin names to be loaded ' 'or "--analysis list" to see a l...
288,006
Parses and validates options. Args: options (argparse.Namespace): parser options. configuration_object (CLITool): object to be configured by the argument helper. Raises: BadConfigObject: when the configuration object is of the wrong type.
def ParseOptions(cls, options, configuration_object): if not isinstance(configuration_object, tools.CLITool): raise errors.BadConfigObject( 'Configuration object is not an instance of CLITool') analysis_plugins = cls._ParseStringOption(options, 'analysis_plugins') if analysis_plugins ...
288,007
Parses and validates options. Args: options (argparse.Namespace): parser options. configuration_object (CLITool): object to be configured by the argument helper. Raises: BadConfigObject: when the configuration object is of the wrong type. BadConfigOption: when a configuration...
def ParseOptions(cls, options, configuration_object): if not isinstance(configuration_object, tools.CLITool): raise errors.BadConfigObject( 'Configuration object is not an instance of CLITool') number_of_extraction_workers = cls._ParseNumericOption( options, 'workers', default_valu...
288,008
Parses the UpdateKey value. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_value (dfwinreg.WinRegistryValue): Windows Registry value. key_path (str): Windows Registry key path.
def _ParseUpdateKeyValue(self, parser_mediator, registry_value, key_path): if not registry_value.DataIsString(): parser_mediator.ProduceExtractionWarning( 'unsupported UpdateKey value data type: {0:s}'.format( registry_value.data_type_string)) return date_time_string = ...
288,010
Extracts events from a Windows Registry key. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg.WinRegistryKey): Windows Registry key.
def ExtractEvents(self, parser_mediator, registry_key, **kwargs): values_dict = {} for registry_value in registry_key.GetValues(): if not registry_value.name or not registry_value.data: continue if registry_value.name == 'UpdateKey': self._ParseUpdateKeyValue( parse...
288,011
Sets the hashers that should be enabled. Args: hasher_names_string (str): comma separated names of hashers to enable.
def SetHasherNames(self, hasher_names_string): hasher_names = hashers_manager.HashersManager.GetHasherNamesFromString( hasher_names_string) debug_hasher_names = ', '.join(hasher_names) logger.debug('Got hasher names: {0:s}'.format(debug_hasher_names)) self._hashers = hashers_manager.Hashe...
288,015
Creates a task storage writer. Args: path (str): path to the storage file. task (Task): task. Returns: SQLiteStorageFileWriter: storage writer.
def _CreateTaskStorageWriter(self, path, task): return SQLiteStorageFileWriter( self._session, path, storage_type=definitions.STORAGE_TYPE_TASK, task=task)
288,016
Extracts events from a Windows Registry key. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg.WinRegistryKey): Windows Registry key.
def ExtractEvents(self, parser_mediator, registry_key, **kwargs): values_dict = {} if registry_key.number_of_values > 0: for registry_value in registry_key.GetValues(): value_name = registry_value.name or '(default)' if registry_value.DataIsString(): value_string = '[{0:s}...
288,017
Formats a field. Args: field (str): field value. Returns: str: formatted field value.
def _FormatField(self, field): if self._FIELD_DELIMITER and isinstance(field, py2to3.STRING_TYPES): return field.replace(self._FIELD_DELIMITER, ' ') return field
288,018
Formats the hostname. Args: event (EventObject): event. Returns: str: formatted hostname field.
def _FormatHostname(self, event): hostname = self._output_mediator.GetHostname(event) return self._FormatField(hostname)
288,019
Formats the username. Args: event (EventObject): event. Returns: str: formatted username field.
def _FormatUsername(self, event): username = self._output_mediator.GetUsername(event) return self._FormatField(username)
288,020
Retrieves output values. Args: event (EventObject): event. Returns: list[str]: output values or None if no timestamp was present in the event. Raises: NoFormatterFound: If no event formatter can be found to match the data type in the event.
def _GetOutputValues(self, event): if not hasattr(event, 'timestamp'): logger.error('Unable to output event without timestamp.') return None # TODO: add function to pass event_values to GetFormattedMessages. message, message_short = self._output_mediator.GetFormattedMessages(event) if ...
288,021
Writes values to the output. Args: output_values (list[str]): output values.
def _WriteOutputValues(self, output_values): for index, value in enumerate(output_values): if not isinstance(value, py2to3.STRING_TYPES): value = '' output_values[index] = value.replace(',', ' ') output_line = ','.join(output_values) output_line = '{0:s}\n'.format(output_line) ...
288,022
Writes the body of an event object to the output. Args: event (EventObject): event. Raises: NoFormatterFound: If no event formatter can be found to match the data type in the event object.
def WriteEventBody(self, event): output_values = self._GetOutputValues(event) output_values[3] = self._output_mediator.GetMACBRepresentation(event) output_values[6] = event.timestamp_desc or '-' self._WriteOutputValues(output_values)
288,023
Writes an event MACB group to the output. Args: event_macb_group (list[EventObject]): event MACB group.
def WriteEventMACBGroup(self, event_macb_group): output_values = self._GetOutputValues(event_macb_group[0]) timestamp_descriptions = [ event.timestamp_desc for event in event_macb_group] output_values[3] = ( self._output_mediator.GetMACBRepresentationFromDescriptions( times...
288,024
Parses and validates options. Args: options (argparse.Namespace): parser options. configuration_object (CLITool): object to be configured by the argument helper. Raises: BadConfigObject: when the configuration object is of the wrong type. BadConfigOption: if the required arti...
def ParseOptions(cls, options, configuration_object): if not isinstance(configuration_object, tools.CLITool): raise errors.BadConfigObject( 'Configuration object is not an instance of CLITool') artifact_filters = cls._ParseStringOption(options, 'artifact_filter_string') artifact_filter...
288,027
Extracts events from a Windows Registry key. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg.WinRegistryKey): Windows Registry key.
def ExtractEvents(self, parser_mediator, registry_key, **kwargs): for subkey in registry_key.GetSubkeys(): name = subkey.name if not name: continue values_dict = {} values_dict['Volume'] = name label_value = subkey.GetValueByName('_LabelFromReg') if label_value: ...
288,028
Determines the formatted message strings for an event object. Args: formatter_mediator (FormatterMediator): mediates the interactions between formatters and other components, such as storage and Windows EventLog resources. event (EventObject): event. Returns: tuple(str, s...
def GetMessages(self, formatter_mediator, event): if self.DATA_TYPE != event.data_type: raise errors.WrongFormatter('Unsupported data type: {0:s}.'.format( event.data_type)) event_values = event.CopyToDict() primary_url = event_values['primary_url'] secondary_url = event_values['s...
288,030
Parses and validates options. Args: options (argparse.Namespace): parser options. configuration_object (CLITool): object to be configured by the argument helper. Raises: BadConfigObject: when the configuration object is of the wrong type.
def ParseOptions(cls, options, configuration_object): if not isinstance(configuration_object, tools.CLITool): raise errors.BadConfigObject( 'Configuration object is not an instance of CLITool') storage_file = cls._ParseStringOption(options, 'storage_file') setattr(configuration_object...
288,031
Extract extension installation events. Args: settings_dict (dict[str: object]): settings data from a Preferences file. parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs.
def _ExtractExtensionInstallEvents(self, settings_dict, parser_mediator): for extension_id, extension in sorted(settings_dict.items()): install_time = extension.get('install_time', None) if not install_time: parser_mediator.ProduceExtractionWarning( 'installation time missing fo...
288,036
Extracts site specific events. Args: exceptions_dict (dict): Permission exceptions data from Preferences file. parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs.
def _ExtractContentSettingsExceptions(self, exceptions_dict, parser_mediator): for permission in exceptions_dict: if permission not in self._EXCEPTIONS_KEYS: continue exception_dict = exceptions_dict.get(permission, {}) for urls, url_dict in exception_dict.items(): last_used ...
288,037
Parses a Chrome preferences file-like object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): file-like object. Raises: UnableToParseFile: when the file cannot be parsed.
def ParseFileObject(self, parser_mediator, file_object): # First pass check for initial character being open brace. if file_object.read(1) != b'{': raise errors.UnableToParseFile(( '[{0:s}] {1:s} is not a valid Preference file, ' 'missing opening brace.').format( sel...
288,038
Collects values using a file artifact definition. Args: knowledge_base (KnowledgeBase): to fill with preprocessing information. artifact_definition (artifacts.ArtifactDefinition): artifact definition. searcher (dfvfs.FileSystemSearcher): file system searcher to preprocess the file syste...
def Collect( self, knowledge_base, artifact_definition, searcher, file_system): for source in artifact_definition.sources: if source.type_indicator not in ( artifact_definitions.TYPE_INDICATOR_FILE, artifact_definitions.TYPE_INDICATOR_PATH): continue for path in s...
288,039
Parses a file entry for a preprocessing attribute. Args: knowledge_base (KnowledgeBase): to fill with preprocessing information. file_entry (dfvfs.FileEntry): file entry that contains the artifact value data. Raises: PreProcessFail: if the preprocessing fails.
def _ParseFileEntry(self, knowledge_base, file_entry): file_object = file_entry.GetFileObject() try: self._ParseFileData(knowledge_base, file_object) finally: file_object.close()
288,041
Collects values using a Windows Registry value artifact definition. Args: knowledge_base (KnowledgeBase): to fill with preprocessing information. artifact_definition (artifacts.ArtifactDefinition): artifact definition. searcher (dfwinreg.WinRegistrySearcher): Windows Registry searcher to ...
def Collect( self, knowledge_base, artifact_definition, searcher): for source in artifact_definition.sources: if source.type_indicator not in ( artifact_definitions.TYPE_INDICATOR_WINDOWS_REGISTRY_KEY, artifact_definitions.TYPE_INDICATOR_WINDOWS_REGISTRY_VALUE): continue...
288,042
Parses a Windows Registry key for a preprocessing attribute. Args: knowledge_base (KnowledgeBase): to fill with preprocessing information. registry_key (dfwinreg.WinRegistryKey): Windows Registry key. value_name (str): name of the Windows Registry value. Raises: PreProcessFail: if the ...
def _ParseKey(self, knowledge_base, registry_key, value_name): try: registry_value = registry_key.GetValueByName(value_name) except IOError as exception: raise errors.PreProcessFail(( 'Unable to retrieve Windows Registry key: {0:s} value: {1:s} ' 'with error: {2!s}').format(...
288,043
Parses an F value. Args: registry_key (dfwinreg.WinRegistryKey): Windows Registry key. Returns: f_value: F value stored in the Windows Registry key. Raises: ParseError: if the Windows Registry key does not contain an F value or F value cannot be parsed.
def _ParseFValue(self, registry_key): registry_value = registry_key.GetValueByName('F') if not registry_value: raise errors.ParseError( 'missing value: "F" in Windows Registry key: {0:s}.'.format( registry_key.name)) f_value_map = self._GetDataTypeMap('f_value') try:...
288,045
Parses a V value string. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. data (bytes): Windows Registry V value data. user_information_descriptor (user_information_descriptor): V value user informat...
def _ParseVValueString( self, parser_mediator, data, user_information_descriptor): data_start_offset = ( user_information_descriptor.offset + self._V_VALUE_STRINGS_OFFSET) data_end_offset = data_start_offset + user_information_descriptor.size descriptor_data = data[data_start_offset:data_...
288,046
Extracts events from a Windows Registry key. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg.WinRegistryKey): Windows Registry key.
def ExtractEvents(self, parser_mediator, registry_key, **kwargs): names_key = registry_key.GetSubkeyByName('Names') if not names_key: parser_mediator.ProduceExtractionWarning('missing subkey: Names.') return last_written_time_per_username = { registry_value.name: registry_value.las...
288,047
Parses a visited row. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. query (str): query that created the row. row (sqlite3.Row): row.
def ParsePageVisitRow(self, parser_mediator, query, row, **unused_kwargs): query_hash = hash(query) was_http_non_get = self._GetRowValue(query_hash, row, 'http_non_get') event_data = SafariHistoryPageVisitedEventData() event_data.offset = self._GetRowValue(query_hash, row, 'id') event_data.que...
288,049
Return local path for a given inode. Args: inode (int): inode number for the file. cache (SQLiteCache): cache. database (SQLiteDatabase): database. Returns: str: full path, including the filename of the given inode value.
def GetLocalPath(self, inode, cache, database): local_path = cache.GetResults('local_path') if not local_path: results = database.Query(self.LOCAL_PATH_CACHE_QUERY) cache.CacheQueryResults( results, 'local_path', 'child_inode_number', ('parent_inode_number', 'filename')) ...
288,052
Return cloud path given a resource id. Args: resource_id (str): resource identifier for the file. cache (SQLiteCache): cache. database (SQLiteDatabase): database. Returns: str: full path to the resource value.
def GetCloudPath(self, resource_id, cache, database): cloud_path = cache.GetResults('cloud_path') if not cloud_path: results = database.Query(self.CLOUD_PATH_CACHE_QUERY) cache.CacheQueryResults( results, 'cloud_path', 'resource_id', ('filename', 'parent')) cloud_path = cache.G...
288,053
Parses a cloud entry row. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. query (str): query that created the row. row (sqlite3.Row): row. cache (SQLiteCache): cache. database (SQLiteDatabase): da...
def ParseCloudEntryRow( self, parser_mediator, query, row, cache=None, database=None, **unused_kwargs): query_hash = hash(query) parent_resource_id = self._GetRowValue( query_hash, row, 'parent_resource_id') filename = self._GetRowValue(query_hash, row, 'filename') cloud_path ...
288,054
Parses a local entry row. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. query (str): query that created the row. row (sqlite3.Row): row. cache (Optional[SQLiteCache]): cache. database (Optional[...
def ParseLocalEntryRow( self, parser_mediator, query, row, cache=None, database=None, **unused_kwargs): query_hash = hash(query) inode_number = self._GetRowValue(query_hash, row, 'inode_number') local_path = self.GetLocalPath(inode_number, cache, database) event_data = GoogleDriveSnap...
288,055
Initializes an event source heap. Args: maximum_number_of_items (Optional[int]): maximum number of items in the heap.
def __init__(self, maximum_number_of_items=50000): super(_EventSourceHeap, self).__init__() self._heap = [] self._maximum_number_of_items = maximum_number_of_items
288,056
Pushes an event source onto the heap. Args: event_source (EventSource): event source.
def PushEventSource(self, event_source): if event_source.file_entry_type == ( dfvfs_definitions.FILE_ENTRY_TYPE_DIRECTORY): weight = 1 else: weight = 100 heap_values = (weight, time.time(), event_source) heapq.heappush(self._heap, heap_values)
288,058
Initializes an engine. Args: maximum_number_of_tasks (Optional[int]): maximum number of concurrent tasks, where 0 represents no limit. use_zeromq (Optional[bool]): True if ZeroMQ should be used for queuing instead of Python's multiprocessing queue.
def __init__( self, maximum_number_of_tasks=_MAXIMUM_NUMBER_OF_TASKS, use_zeromq=True): super(TaskMultiProcessEngine, self).__init__() self._enable_sigsegv_handler = False self._filter_find_specs = None self._last_worker_number = 0 self._maximum_number_of_tasks = maximum_number_of_tasks ...
288,059
Fills the event source heap with the available written event sources. Args: storage_writer (StorageWriter): storage writer for a session storage. event_source_heap (_EventSourceHeap): event source heap. start_with_first (Optional[bool]): True if the function should start with the first ...
def _FillEventSourceHeap( self, storage_writer, event_source_heap, start_with_first=False): if self._processing_profiler: self._processing_profiler.StartTiming('fill_event_source_heap') if self._processing_profiler: self._processing_profiler.StartTiming('get_event_source') if start_...
288,060
Merges a task storage with the session storage. This function checks all task stores that are ready to merge and updates the scheduled tasks. Note that to prevent this function holding up the task scheduling loop only the first available task storage is merged. Args: storage_writer (StorageWrite...
def _MergeTaskStorage(self, storage_writer): if self._processing_profiler: self._processing_profiler.StartTiming('merge_check') for task_identifier in storage_writer.GetProcessedTaskIdentifiers(): try: task = self._task_manager.GetProcessedTaskByIdentifier(task_identifier) sel...
288,061
Processes the sources. Args: source_path_specs (list[dfvfs.PathSpec]): path specifications of the sources to process. storage_writer (StorageWriter): storage writer for a session storage. filter_find_specs (Optional[list[dfvfs.FindSpec]]): find specifications used in path spec...
def _ProcessSources( self, source_path_specs, storage_writer, filter_find_specs=None): if self._processing_profiler: self._processing_profiler.StartTiming('process_sources') self._status = definitions.STATUS_INDICATOR_COLLECTING self._number_of_consumed_event_tags = 0 self._number_of_c...
288,062
Schedules a task. Args: task (Task): task. Returns: bool: True if the task was scheduled.
def _ScheduleTask(self, task): if self._processing_profiler: self._processing_profiler.StartTiming('schedule_task') try: self._task_queue.PushItem(task, block=False) is_scheduled = True except errors.QueueFull: is_scheduled = False if self._processing_profiler: self...
288,063
Schedules tasks. Args: storage_writer (StorageWriter): storage writer for a session storage.
def _ScheduleTasks(self, storage_writer): logger.debug('Task scheduler started') self._status = definitions.STATUS_INDICATOR_RUNNING # TODO: make tasks persistent. # TODO: protect task scheduler loop by catch all and # handle abort path. event_source_heap = _EventSourceHeap() self....
288,064
Creates, starts, monitors and registers a worker process. Args: process_name (str): process name. storage_writer (StorageWriter): storage writer for a session storage used to create task storage. Returns: MultiProcessWorkerProcess: extraction worker process or None if the ...
def _StartWorkerProcess(self, process_name, storage_writer): process_name = 'Worker_{0:02d}'.format(self._last_worker_number) logger.debug('Starting worker process {0:s}'.format(process_name)) if self._use_zeromq: queue_name = '{0:s} task queue'.format(process_name) task_queue = zeromq_que...
288,065
Stops the extraction processes. Args: abort (bool): True to indicated the stop is issued on abort.
def _StopExtractionProcesses(self, abort=False): logger.debug('Stopping extraction processes.') self._StopMonitoringProcesses() # Note that multiprocessing.Queue is very sensitive regarding # blocking on either a get or a put. So we try to prevent using # any blocking behavior. if abort: ...
288,067
Determines the formatted message strings for an event object. Args: formatter_mediator (FormatterMediator): mediates the interactions between formatters and other components, such as storage and Windows EventLog resources. event (EventObject): event. Returns: tuple(str, s...
def GetMessages(self, formatter_mediator, event): if self.DATA_TYPE != event.data_type: raise errors.WrongFormatter('Unsupported data type: {0:s}.'.format( event.data_type)) event_values = event.CopyToDict() login_type = event_values.get('type', None) if login_type is None: ...
288,069
Parses a message row. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. query (str): query that created the row. row (sqlite3.Row): row.
def ParseMessageRow(self, parser_mediator, query, row, **unused_kwargs): query_hash = hash(query) event_data = KikIOSMessageEventData() event_data.body = self._GetRowValue(query_hash, row, 'ZBODY') event_data.displayname = self._GetRowValue(query_hash, row, 'ZDISPLAYNAME') event_data.message_s...
288,071
Retrieves event data from the Windows EventLog (EVT) record. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. record_index (int): event record index. evt_record (pyevt.record): event record. recovered (O...
def _GetEventData( self, parser_mediator, record_index, evt_record, recovered=False): event_data = WinEvtRecordEventData() try: event_data.record_number = evt_record.identifier except OverflowError as exception: parser_mediator.ProduceExtractionWarning(( 'unable to read rec...
288,073
Parses a Windows EventLog (EVT) record. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. record_index (int): event record index. evt_record (pyevt.record): event record. recovered (Optional[bool]): True ...
def _ParseRecord( self, parser_mediator, record_index, evt_record, recovered=False): event_data = self._GetEventData( parser_mediator, record_index, evt_record, recovered=recovered) try: creation_time = evt_record.get_creation_time_as_integer() except OverflowError as exception: ...
288,074
Parses Windows EventLog (EVT) records. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. evt_file (pyevt.file): Windows EventLog (EVT) file.
def _ParseRecords(self, parser_mediator, evt_file): # To handle errors when parsing a Windows EventLog (EVT) file in the most # granular way the following code iterates over every event record. The # call to evt_file.get_record() and access to members of evt_record should # be called within a try-e...
288,075
Parses a Windows EventLog (EVT) file-like object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): a file-like object.
def ParseFileObject(self, parser_mediator, file_object): evt_file = pyevt.file() evt_file.set_ascii_codepage(parser_mediator.codepage) try: evt_file.open_file_object(file_object) except IOError as exception: parser_mediator.ProduceExtractionWarning( 'unable to open file with ...
288,076
Verifies whether content corresponds to a Zsh extended_history file. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. lines (str): one or more lines from the text file. Returns: bool: True if the line was...
def VerifyStructure(self, parser_mediator, lines): if self._VERIFICATION_REGEX.match(lines): return True return False
288,078
Retrieves a plist value by path. Args: path_segments (list[str]): path segment strings relative to the root of the plist. Returns: object: The value of the key specified by the path or None.
def GetValueByPath(self, path_segments): key = self.root_key for path_segment in path_segments: if isinstance(key, dict): try: key = key[path_segment] except KeyError: return None elif isinstance(key, list): try: list_index = int(path_segme...
288,079
Reads a plist from a file-like object. Args: file_object (dfvfs.FileIO): a file-like object containing plist data. Raises: IOError: if the plist file-like object cannot be read. OSError: if the plist file-like object cannot be read.
def Read(self, file_object): try: self.root_key = biplist.readPlist(file_object) except ( biplist.NotBinaryPlistException, biplist.InvalidPlistException) as exception: raise IOError(exception)
288,080
Determines the formatted message string. Args: format_string (str): message format string. event_values (dict[str, object]): event values. Returns: str: formatted message string.
def _FormatMessage(self, format_string, event_values): if not isinstance(format_string, py2to3.UNICODE_TYPE): logger.warning('Format string: {0:s} is non-Unicode.'.format( format_string)) # Plaso code files should be in UTF-8 any thus binary strings are # assumed UTF-8. If this is ...
288,081
Determines the formatted message strings. Args: format_string (str): message format string. short_format_string (str): short message format string. event_values (dict[str, object]): event values. Returns: tuple(str, str): formatted message string and short message string.
def _FormatMessages(self, format_string, short_format_string, event_values): message_string = self._FormatMessage(format_string, event_values) if short_format_string: short_message_string = self._FormatMessage( short_format_string, event_values) else: short_message_string = messa...
288,082
Determines the formatted message strings for an event object. Args: formatter_mediator (FormatterMediator): mediates the interactions between formatters and other components, such as storage and Windows EventLog resources. event (EventObject): event. Returns: tuple(str, s...
def GetMessages(self, formatter_mediator, event): if self.DATA_TYPE != event.data_type: raise errors.WrongFormatter('Unsupported data type: {0:s}.'.format( event.data_type)) event_values = event.CopyToDict() return self._FormatMessages( self.FORMAT_STRING, self.FORMAT_STRING_SH...
288,084
Determines the the short and long source for an event object. Args: event (EventObject): event. Returns: tuple(str, str): short and long source string. Raises: WrongFormatter: if the event object cannot be formatted by the formatter.
def GetSources(self, event): if self.DATA_TYPE != event.data_type: raise errors.WrongFormatter('Unsupported data type: {0:s}.'.format( event.data_type)) return self.SOURCE_SHORT, self.SOURCE_LONG
288,085
Determines the conditional formatted message strings. Args: event_values (dict[str, object]): event values. Returns: tuple(str, str): formatted message string and short message string.
def _ConditionalFormatMessages(self, event_values): # Using getattr here to make sure the attribute is not set to None. # if A.b = None, hasattr(A, b) is True but getattr(A, b, None) is False. string_pieces = [] for map_index, attribute_name in enumerate(self._format_string_pieces_map): if no...
288,087
Determines the formatted message strings for an event object. Args: formatter_mediator (FormatterMediator): mediates the interactions between formatters and other components, such as storage and Windows EventLog resources. event (EventObject): event. Returns: tuple(str, s...
def GetMessages(self, formatter_mediator, event): if self.DATA_TYPE != event.data_type: raise errors.WrongFormatter('Unsupported data type: {0:s}.'.format( event.data_type)) event_values = event.CopyToDict() return self._ConditionalFormatMessages(event_values)
288,089
Compares the file entry against the filter. Args: file_entry (dfvfs.FileEntry): file entry to compare. Returns: bool: True if the file entry matches the filter, False if not or None if the filter does not apply.
def Matches(self, file_entry): if not self._date_time_ranges: return None for date_time_range in self._date_time_ranges: time_attribute = self._TIME_VALUE_MAPPINGS.get( date_time_range.time_value, None) if not time_attribute: continue timestamp = getattr(file_ent...
288,091
Prints a human readable version of the filter. Args: output_writer (CLIOutputWriter): output writer.
def Print(self, output_writer): if self._date_time_ranges: for date_time_range in self._date_time_ranges: if date_time_range.start_date_time is None: end_time_string = date_time_range.end_date_time.CopyToDateTimeString() output_writer.Write('\t{0:s} after {1:s}\n'.format( ...
288,092
Initializes an extensions-based file entry filter. An extension is defined as "pdf" as in "document.pdf". Args: extensions (list[str]): a list of extension strings.
def __init__(self, extensions): super(ExtensionsFileEntryFilter, self).__init__() self._extensions = extensions
288,093
Compares the file entry against the filter. Args: file_entry (dfvfs.FileEntry): file entry to compare. Returns: bool: True if the file entry matches the filter, False if not or None if the filter does not apply.
def Matches(self, file_entry): location = getattr(file_entry.path_spec, 'location', None) if not location: return None if '.' not in location: return False _, _, extension = location.rpartition('.') return extension.lower() in self._extensions
288,094
Prints a human readable version of the filter. Args: output_writer (CLIOutputWriter): output writer.
def Print(self, output_writer): if self._extensions: output_writer.Write('\textensions: {0:s}\n'.format( ', '.join(self._extensions)))
288,095
Initializes a names-based file entry filter. Args: names (list[str]): names.
def __init__(self, names): super(NamesFileEntryFilter, self).__init__() self._names = names
288,096
Compares the file entry against the filter. Args: file_entry (dfvfs.FileEntry): file entry to compare. Returns: bool: True if the file entry matches the filter.
def Matches(self, file_entry): if not self._names or not file_entry.IsFile(): return False return file_entry.name.lower() in self._names
288,097
Prints a human readable version of the filter. Args: output_writer (CLIOutputWriter): output writer.
def Print(self, output_writer): if self._names: output_writer.Write('\tnames: {0:s}\n'.format( ', '.join(self._names)))
288,098
Initializes a signature-based file entry filter. Args: specification_store (FormatSpecificationStore): a specification store. signature_identifiers (list[str]): signature identifiers.
def __init__(self, specification_store, signature_identifiers): super(SignaturesFileEntryFilter, self).__init__() self._file_scanner = None self._signature_identifiers = [] self._file_scanner = self._GetScanner( specification_store, signature_identifiers)
288,099
Initializes the scanner form the specification store. Args: specification_store (FormatSpecificationStore): a specification store. signature_identifiers (list[str]): signature identifiers. Returns: pysigscan.scanner: signature scanner or None.
def _GetScanner(self, specification_store, signature_identifiers): if not specification_store: return None scanner_object = pysigscan.scanner() for format_specification in specification_store.specifications: if format_specification.identifier not in signature_identifiers: continue...
288,100
Compares the file entry against the filter. Args: file_entry (dfvfs.FileEntry): file entry to compare. Returns: bool: True if the file entry matches the filter, False if not or None if the filter does not apply.
def Matches(self, file_entry): if not self._file_scanner or not file_entry.IsFile(): return None file_object = file_entry.GetFileObject() if not file_object: return False try: scan_state = pysigscan.scan_state() self._file_scanner.scan_file_object(scan_state, file_object) ...
288,101
Prints a human readable version of the filter. Args: output_writer (CLIOutputWriter): output writer.
def Print(self, output_writer): if self._file_scanner: output_writer.Write('\tsignature identifiers: {0:s}\n'.format( ', '.join(self._signature_identifiers)))
288,102
Compares the file entry against the filter collection. Args: file_entry (dfvfs.FileEntry): file entry to compare. Returns: bool: True if the file entry matches one of the filters. If no filters are provided or applicable the result will be True.
def Matches(self, file_entry): if not self._filters: return True results = [] for file_entry_filter in self._filters: result = file_entry_filter.Matches(file_entry) results.append(result) return True in results or False not in results
288,103
Prints a human readable version of the filter. Args: output_writer (CLIOutputWriter): output writer.
def Print(self, output_writer): if self._filters: output_writer.Write('Filters:\n') for file_entry_filter in self._filters: file_entry_filter.Print(output_writer)
288,104
Extracts events from a Windows Registry key. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg.WinRegistryKey): Windows Registry key.
def ExtractEvents(self, parser_mediator, registry_key, **kwargs): # TODO: Test other Office versions to make sure this plugin is applicable. values_dict = {} for registry_value in registry_key.GetValues(): # Ignore any value not in the form: 'Item [0-9]+'. if not registry_value.name or not ...
288,106
Parses a zeitgeist event row. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. query (str): query that created the row. row (sqlite3.Row): row.
def ParseZeitgeistEventRow( self, parser_mediator, query, row, **unused_kwargs): query_hash = hash(query) event_data = ZeitgeistActivityEventData() event_data.offset = self._GetRowValue(query_hash, row, 'id') event_data.query = query event_data.subject_uri = self._GetRowValue(query_hash,...
288,108
Parses a row from the database. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. query (str): query that created the row. row (sqlite3.Row): row.
def ParseRow(self, parser_mediator, query, row, **unused_kwargs): query_hash = hash(query) event_data = AndroidWebViewCacheEventData() event_data.content_length = self._GetRowValue( query_hash, row, 'contentlength') event_data.query = query event_data.url = self._GetRowValue(query_hash...
288,110
Determines the formatted message strings for an event object. Args: formatter_mediator (FormatterMediator): mediates the interactions between formatters and other components, such as storage and Windows EventLog resources. event (EventObject): event. Returns: tuple(str, s...
def GetMessages(self, formatter_mediator, event): if self.DATA_TYPE != event.data_type: raise errors.WrongFormatter('Unsupported data type: {0:s}.'.format( event.data_type)) event_values = event.CopyToDict() document_type = event_values.get('document_type', None) if document_type:...
288,111
Writes the body of an event object to the output. Args: event (EventObject): event.
def WriteEventBody(self, event): inode = getattr(event, 'inode', None) if inode is None: event.inode = 0 try: message, _ = self._output_mediator.GetFormattedMessages(event) except errors.WrongFormatter: message = None if message: event.message = message json_dict ...
288,112
Parses the registered DLLs that receive event notifications. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg.WinRegistryKey): Windows Registry key.
def _ParseRegisteredDLLs(self, parser_mediator, registry_key): notify_key = registry_key.GetSubkeyByName('Notify') if not notify_key: return for subkey in notify_key.GetSubkeys(): for trigger in self._TRIGGERS: handler_value = subkey.GetValueByName(trigger) if not handler_v...
288,113
Parses the registered logon applications. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg.WinRegistryKey): Windows Registry key.
def _ParseLogonApplications(self, parser_mediator, registry_key): for application in self._LOGON_APPLICATIONS: command_value = registry_key.GetValueByName(application) if not command_value: continue values_dict = { 'Application': application, 'Command': command_va...
288,114
Extracts events from a Windows Registry key. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg.WinRegistryKey): Windows Registry key.
def ExtractEvents(self, parser_mediator, registry_key, **kwargs): self._ParseLogonApplications(parser_mediator, registry_key) self._ParseRegisteredDLLs(parser_mediator, registry_key)
288,115