docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Analyzes events in a plaso storage. Args: storage_writer (StorageWriter): storage writer. analysis_plugins (dict[str, AnalysisPlugin]): analysis plugins that should be run and their names. event_filter (Optional[FilterObject]): event filter. Returns: collections.Counter: coun...
def _AnalyzeEvents(self, storage_writer, analysis_plugins, event_filter=None): self._status = definitions.STATUS_INDICATOR_RUNNING self._number_of_consumed_events = 0 self._number_of_consumed_reports = 0 self._number_of_consumed_sources = 0 self._number_of_consumed_warnings = 0 self._number...
287,818
Checks the status of an analysis process. Args: pid (int): process ID (PID) of a registered analysis process. Raises: KeyError: if the process is not registered with the engine.
def _CheckStatusAnalysisProcess(self, pid): # TODO: Refactor this method, simplify and separate concerns (monitoring # vs management). self._RaiseIfNotRegistered(pid) if pid in self._completed_analysis_processes: status_indicator = definitions.STATUS_INDICATOR_COMPLETED process_status ...
287,819
Exports an event using an output module. Args: output_module (OutputModule): output module. event (EventObject): event. deduplicate_events (Optional[bool]): True if events should be deduplicated.
def _ExportEvent(self, output_module, event, deduplicate_events=True): if event.timestamp != self._export_event_timestamp: self._FlushExportBuffer( output_module, deduplicate_events=deduplicate_events) self._export_event_timestamp = event.timestamp self._export_event_heap.PushEvent(e...
287,820
Flushes buffered events and writes them to the output module. Args: output_module (OutputModule): output module. deduplicate_events (Optional[bool]): True if events should be deduplicated.
def _FlushExportBuffer(self, output_module, deduplicate_events=True): last_macb_group_identifier = None last_content_identifier = None macb_group = [] generator = self._export_event_heap.PopEvents() for macb_group_identifier, content_identifier, event in generator: if deduplicate_events...
287,822
Merges an event tag with the last stored event tag. If there is an existing event the provided event tag is updated with the contents of the existing one. After which the event tag index is updated. Args: storage_writer (StorageWriter): storage writer. attribute_container (AttributeContain...
def _MergeEventTag(self, storage_writer, attribute_container): if attribute_container.CONTAINER_TYPE != 'event_tag': return event_identifier = attribute_container.GetEventIdentifier() if not event_identifier: return # Check if the event has already been tagged on a previous occasion, ...
287,823
Starts the analysis processes. Args: storage_writer (StorageWriter): storage writer. analysis_plugins (dict[str, AnalysisPlugin]): analysis plugins that should be run and their names.
def _StartAnalysisProcesses(self, storage_writer, analysis_plugins): logger.info('Starting analysis plugins.') for analysis_plugin in analysis_plugins.values(): self._analysis_plugins[analysis_plugin.NAME] = analysis_plugin process = self._StartWorkerProcess(analysis_plugin.NAME, storage_writ...
287,824
Stops the analysis processes. Args: abort (bool): True to indicated the stop is issued on abort.
def _StopAnalysisProcesses(self, abort=False): logger.debug('Stopping analysis 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: ...
287,826
Updates the processing status. Args: pid (int): process identifier (PID) of the worker process. process_status (dict[str, object]): status values received from the worker process. used_memory (int): size of used memory in bytes. Raises: KeyError: if the process is not registe...
def _UpdateProcessingStatus(self, pid, process_status, used_memory): self._RaiseIfNotRegistered(pid) if not process_status: return process = self._processes_per_pid[pid] status_indicator = process_status.get('processing_status', None) self._RaiseIfNotMonitored(pid) display_name =...
287,828
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 on error.
def _StartWorkerProcess(self, process_name, storage_writer): analysis_plugin = self._analysis_plugins.get(process_name, None) if not analysis_plugin: logger.error('Missing analysis plugin: {0:s}'.format(process_name)) return None if self._use_zeromq: queue_name = '{0:s} output event ...
287,829
Determines the linked path. Args: event (EventObject): event that contains a linked path. Returns: str: linked path.
def _GetLinkedPath(self, event): if hasattr(event, 'local_path'): return event.local_path if hasattr(event, 'network_path'): return event.network_path if hasattr(event, 'relative_path'): paths = [] if hasattr(event, 'working_directory'): paths.append(event.working_dire...
287,832
Initializes a mount point. Args: mount_path (Optional[str]): path where the path specification is mounted, such as "/mnt/image" or "C:\\". path_specification (Optional[dfvfs.PathSpec]): path specification.
def __init__(self, mount_path=None, path_specification=None): super(MountPoint, self).__init__() self.mount_path = mount_path self.path_specification = path_specification
287,834
Decodes the URL, replaces %XX to their corresponding characters. Args: url (str): encoded URL. Returns: str: decoded URL.
def _DecodeURL(self, url): if not url: return '' decoded_url = urlparse.unquote(url) if isinstance(decoded_url, py2to3.BYTES_TYPE): try: decoded_url = decoded_url.decode('utf-8') except UnicodeDecodeError as exception: decoded_url = decoded_url.decode('utf-8', errors=...
287,836
Extracts a search query from a GMail search URL. GMail: https://mail.google.com/mail/u/0/#search/query[/?] Args: url (str): URL. Returns: str: search query or None if no query was found.
def _ExtractGMailSearchQuery(self, url): if 'search/' not in url: return None _, _, line = url.partition('search/') line, _, _ = line.partition('/') line, _, _ = line.partition('?') return line.replace('+', ' ')
287,837
Extracts a search query from a Google docs URL. Google Docs: https://docs.google.com/.*/u/0/?q=query Args: url (str): URL. Returns: str: search query or None if no query was found.
def _ExtractGoogleDocsSearchQuery(self, url): if 'q=' not in url: return None line = self._GetBetweenQEqualsAndAmpersand(url) if not line: return None return line.replace('+', ' ')
287,838
Extracts a search query from a Google URL. Google Drive: https://drive.google.com/drive/search?q=query Google Search: https://www.google.com/search?q=query Google Sites: https://sites.google.com/site/.*/system/app/pages/ search?q=query Args: url (str): URL. Returns: ...
def _ExtractGoogleSearchQuery(self, url): if 'search' not in url or 'q=' not in url: return None line = self._GetBetweenQEqualsAndAmpersand(url) if not line: return None return line.replace('+', ' ')
287,839
Extracts a search query from a Yahoo search URL. Examples: https://search.yahoo.com/search?p=query https://search.yahoo.com/search;?p=query Args: url (str): URL. Returns: str: search query or None if no query was found.
def _ExtractYahooSearchQuery(self, url): if 'p=' not in url: return None _, _, line = url.partition('p=') before_and, _, _ = line.partition('&') if not before_and: return None yahoo_search_url = before_and.split()[0] return yahoo_search_url.replace('+', ' ')
287,840
Extracts a search query from a Yandex search URL. Yandex: https://www.yandex.com/search/?text=query Args: url (str): URL. Returns: str: search query or None if no query was found.
def _ExtractYandexSearchQuery(self, url): if 'text=' not in url: return None _, _, line = url.partition('text=') before_and, _, _ = line.partition('&') if not before_and: return None yandex_search_url = before_and.split()[0] return yandex_search_url.replace('+', ' ')
287,841
Retrieves the substring between the substrings 'q=' and '&'. Args: url (str): URL. Returns: str: search query, the value between 'q=' and '&' or None if no query was found.
def _GetBetweenQEqualsAndAmpersand(self, url): # Make sure we're analyzing the query part of the URL. _, _, url = url.partition('?') # Look for a key value pair named 'q'. _, _, url = url.partition('q=') if not url: return '' # Strip additional key value pairs. url, _, _ = url.pa...
287,842
Compiles an analysis report. Args: mediator (AnalysisMediator): mediates interactions between analysis plugins and other components, such as storage and dfvfs. Returns: AnalysisReport: analysis report.
def CompileReport(self, mediator): results = {} for key, count in iter(self._counter.items()): search_engine, _, search_term = key.partition(':') results.setdefault(search_engine, {}) results[search_engine][search_term] = count lines_of_text = [] for search_engine, terms in sorte...
287,843
Analyzes an event. Args: mediator (AnalysisMediator): mediates interactions between analysis plugins and other components, such as storage and dfvfs. event (EventObject): event to examine.
def ExamineEvent(self, mediator, event): # This event requires an URL attribute. url = getattr(event, 'url', None) if not url: return # TODO: refactor this the source should be used in formatting only. # Check if we are dealing with a web history event. source, _ = formatters_manager...
287,844
Parses a conversation 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 resulting from query.
def ParseConversationRow(self, parser_mediator, query, row, **unused_kwargs): query_hash = hash(query) event_data = TangoAndroidConversationEventData() event_data.conversation_identifier = self._GetRowValue( query_hash, row, 'conv_id') # TODO: payload is a base64 encoded binary blob, we n...
287,848
Parses a message 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 resulting from query.
def ParseMessageRow(self, parser_mediator, query, row, **unused_kwargs): query_hash = hash(query) event_data = TangoAndroidMessageEventData() event_data.message_identifier = self._GetRowValue( query_hash, row, 'msg_id') # TODO: payload is a base64 encoded binary blob, we need to find the ...
287,849
Parses a contact 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 resulting from query.
def ParseContactRow(self, parser_mediator, query, row, **unused_kwargs): query_hash = hash(query) event_data = TangoAndroidContactEventData() first_name = self._GetRowValue(query_hash, row, 'first_name') try: decoded_text = base64_decode(first_name) event_data.first_name = codecs.deco...
287,850
Retrieves a string representation of the event. Args: event (EventObject): event. Returns: str: string representation of the event.
def GetFormattedEventObject(cls, event): time_string = timelib.Timestamp.CopyToIsoFormat(event.timestamp) lines_of_text = [ '+-' * 40, '[Timestamp]:', ' {0:s}'.format(time_string)] pathspec = getattr(event, 'pathspec', None) if pathspec: lines_of_text.append('[Paths...
287,851
Writes the body of an event to the output. Args: event (EventObject): event.
def WriteEventBody(self, event): output_string = NativePythonFormatterHelper.GetFormattedEventObject(event) self._output_writer.Write(output_string)
287,852
Initializes the RPC server object. Args: callback (function): callback to invoke on get status RPC request.
def __init__(self, callback): super(RPCServer, self).__init__() self._callback = callback
287,853
Pushes a task onto the heap. Args: task (Task): task. Raises: ValueError: if the size of the storage file is not set in the task.
def PushTask(self, task): storage_file_size = getattr(task, 'storage_file_size', None) if not storage_file_size: raise ValueError('Task storage file size not set.') if task.file_entry_type == dfvfs_definitions.FILE_ENTRY_TYPE_DIRECTORY: weight = 1 else: weight = storage_file_size...
287,856
Updates the latest processing time of the task manager from the task. This method does not lock the manager and should be called by a method holding the manager lock. Args: task (Task): task to update the processing time of.
def _UpdateLatestProcessingTime(self, task): self._latest_task_processing_time = max( self._latest_task_processing_time, task.last_processing_time)
287,860
Checks if the task should be merged. Args: task (Task): task. Returns: bool: True if the task should be merged. Raises: KeyError: if the task was not queued, processing or abandoned.
def CheckTaskToMerge(self, task): with self._lock: is_abandoned = task.identifier in self._tasks_abandoned is_processing = task.identifier in self._tasks_processing is_queued = task.identifier in self._tasks_queued if not is_queued and not is_processing and not is_abandoned: ra...
287,861
Creates a task. Args: session_identifier (str): the identifier of the session the task is part of. Returns: Task: task attribute container.
def CreateTask(self, session_identifier): task = tasks.Task(session_identifier) logger.debug('Created task: {0:s}.'.format(task.identifier)) with self._lock: self._tasks_queued[task.identifier] = task self._total_number_of_tasks += 1 self.SampleTaskStatus(task, 'created') retur...
287,863
Completes a task. The task is complete and can be removed from the task manager. Args: task (Task): task. Raises: KeyError: if the task was not merging.
def CompleteTask(self, task): with self._lock: if task.identifier not in self._tasks_merging: raise KeyError('Task {0:s} was not merging.'.format(task.identifier)) self.SampleTaskStatus(task, 'completed') del self._tasks_merging[task.identifier] logger.debug('Completed task {...
287,864
Retrieves a task that has been processed. Args: task_identifier (str): unique identifier of the task. Returns: Task: a task that has been processed. Raises: KeyError: if the task was not processing, queued or abandoned.
def GetProcessedTaskByIdentifier(self, task_identifier): with self._lock: task = self._tasks_processing.get(task_identifier, None) if not task: task = self._tasks_queued.get(task_identifier, None) if not task: task = self._tasks_abandoned.get(task_identifier, None) if no...
287,866
Retrieves the first task that is pending merge or has a higher priority. This function will check if there is a task with a higher merge priority than the current_task being merged. If so, that task with the higher priority is returned. Args: current_task (Task): current task being merged or Non...
def GetTaskPendingMerge(self, current_task): next_task = self._tasks_pending_merge.PeekTask() if not next_task: return None if current_task and next_task.merge_priority > current_task.merge_priority: return None with self._lock: next_task = self._tasks_pending_merge.PopTask() ...
287,868
Removes an abandoned task. Args: task (Task): task. Raises: KeyError: if the task was not abandoned or the task was abandoned and was not retried.
def RemoveTask(self, task): with self._lock: if task.identifier not in self._tasks_abandoned: raise KeyError('Task {0:s} was not abandoned.'.format(task.identifier)) if not task.has_retry: raise KeyError( 'Will not remove a task {0:s} without retry task.'.format( ...
287,870
Takes a sample of the status of the task for profiling. Args: task (Task): a task. status (str): status.
def SampleTaskStatus(self, task, status): if self._tasks_profiler: self._tasks_profiler.Sample(task, status)
287,871
Starts profiling. Args: configuration (ProfilingConfiguration): profiling configuration. identifier (str): identifier of the profiling session used to create the sample filename.
def StartProfiling(self, configuration, identifier): if not configuration: return if configuration.HaveProfileTasks(): self._tasks_profiler = profilers.TasksProfiler(identifier, configuration) self._tasks_profiler.Start()
287,872
Updates the task manager to reflect the task is ready to be merged. Args: task (Task): task. Raises: KeyError: if the task was not queued, processing or abandoned, or the task was abandoned and has a retry task.
def UpdateTaskAsPendingMerge(self, task): with self._lock: is_abandoned = task.identifier in self._tasks_abandoned is_processing = task.identifier in self._tasks_processing is_queued = task.identifier in self._tasks_queued if not is_queued and not is_processing and not is_abandoned: ...
287,873
Updates the task manager to reflect the task is processing. Args: task_identifier (str): unique identifier of the task. Raises: KeyError: if the task is not known to the task manager.
def UpdateTaskAsProcessingByIdentifier(self, task_identifier): with self._lock: task_processing = self._tasks_processing.get(task_identifier, None) if task_processing: task_processing.UpdateProcessingTime() self._UpdateLatestProcessingTime(task_processing) return task...
287,874
Parses an SMS 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 ParseSmsRow(self, parser_mediator, query, row, **unused_kwargs): query_hash = hash(query) sms_read = self._GetRowValue(query_hash, row, 'read') sms_type = self._GetRowValue(query_hash, row, 'type') event_data = AndroidSMSEventData() event_data.address = self._GetRowValue(query_hash, row, ...
287,876
Extracts event objects from a Explorer ProgramsCache value data. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg.WinRegistryKey): Windows Registry key. registry_value (dfwinreg.WinRegis...
def _ParseValueData(self, parser_mediator, registry_key, registry_value): value_data = registry_value.data value_data_size = len(value_data) if value_data_size < 4: return header_map = self._GetDataTypeMap('programscache_header') try: header = self._ReadStructureFromByteStream( ...
287,877
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): registry_value = registry_key.GetValueByName('ProgramsCache') if registry_value: self._ParseValueData(parser_mediator, registry_key, registry_value) registry_value = registry_key.GetValueByName('ProgramsCacheSMP') if registry_...
287,878
Initializes the CLI tool object. Args: input_reader (Optional[InputReader]): input reader, where None indicates that the stdin input reader should be used. output_writer (Optional[OutputWriter]): output writer, where None indicates that the stdout output writer should be used.
def __init__(self, input_reader=None, output_writer=None): super(PstealTool, self).__init__( input_reader=input_reader, output_writer=output_writer) self._artifacts_registry = None self._command_line_arguments = None self._deduplicate_events = True self._enable_sigsegv_handler = False ...
287,880
Parses tool specific options. Args: options (argparse.Namespace): command line arguments. Raises: BadConfigOption: if the options are invalid.
def ParseOptions(self, options): # The extraction options are dependent on the data location. helpers_manager.ArgumentHelperManager.ParseOptions( options, self, names=['data_location']) self._ReadParserPresetsFromFile() # The output modules options are dependent on the preferred language ...
287,884
Formats the description. Args: event (EventObject): event. Returns: str: formatted description field.
def _FormatDescription(self, event): date_time_string = timelib.Timestamp.CopyToIsoFormat( event.timestamp, timezone=self._output_mediator.timezone) timestamp_description = event.timestamp_desc or 'UNKNOWN' message, _ = self._output_mediator.GetFormattedMessages(event) if message is None: ...
287,885
Formats the hostname. Args: event (EventObject): event. Returns: str: formatted hostname field.
def _FormatHostname(self, event): hostname = self._output_mediator.GetHostname(event) return self._SanitizeField(hostname)
287,886
Formats the source. Args: event (EventObject): event. Returns: str: formatted source field.
def _FormatSource(self, event): source_short, _ = self._output_mediator.GetFormattedSources(event) if source_short is None: data_type = getattr(event, 'data_type', 'UNKNOWN') raise errors.NoFormatterFound( 'Unable to find event formatter for: {0:s}.'.format(data_type)) return sel...
287,887
Formats the username. Args: event (EventObject): event. Returns: str: formatted username field.
def _FormatUsername(self, event): username = self._output_mediator.GetUsername(event) return self._SanitizeField(username)
287,888
Sanitizes a field for output. This method removes the field delimiter from the field string. Args: field (str): field value. Returns: str: formatted field value.
def _SanitizeField(self, field): if self._FIELD_DELIMITER and isinstance(field, py2to3.STRING_TYPES): return field.replace(self._FIELD_DELIMITER, ' ') return field
287,889
Formats the notes. Args: event (EventObject): event. Returns: str: formatted notes field.
def _FormatNotes(self, event): inode = event.inode if inode is None: inode = '-' notes = getattr(event, 'notes', '') if not notes: display_name = getattr(event, 'display_name', '') notes = 'File: {0:s} inode: {1!s}'.format(display_name, inode) return self._SanitizeField(notes...
287,890
Writes the body of an event object to the output. Args: event (EventObject): event.
def WriteEventBody(self, event): if not hasattr(event, 'timestamp'): return # TODO: preserve dfdatetime as an object. date_time = dfdatetime_posix_time.PosixTimeInMicroseconds( timestamp=event.timestamp) posix_timestamp = date_time.CopyToPosixTimestamp() if not posix_timestamp: ...
287,891
Parses a search 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 resulting from query.
def ParseSearchRow(self, parser_mediator, query, row, **unused_kwargs): query_hash = hash(query) event_data = TwitterAndroidSearchEventData() event_data.query = query event_data.name = self._GetRowValue(query_hash, row, 'name') event_data.search_query = self._GetRowValue(query_hash, row, 'quer...
287,895
Parses a status 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 resulting from query.
def ParseStatusRow(self, parser_mediator, query, row, **unused_kwargs): query_hash = hash(query) event_data = TwitterAndroidStatusEventData() event_data.query = query event_data.identifier = self._GetRowValue(query_hash, row, '_id') event_data.author_identifier = self._GetRowValue( que...
287,896
Parses a status 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 resulting from query.
def ParseContactRow(self, parser_mediator, query, row, **unused_kwargs): query_hash = hash(query) event_data = TwitterAndroidContactEventData() event_data.query = query event_data.identifier = self._GetRowValue(query_hash, row, '_id') event_data.user_identifier = self._GetRowValue(query_hash, ...
287,897
Converts an attribute value into a JSON dictionary. Args: attribute_value (object): an attribute value. Returns: dict|list: The JSON serialized object which can be a dictionary or a list.
def _ConvertAttributeValueToDict(cls, attribute_value): if isinstance(attribute_value, py2to3.BYTES_TYPE): encoded_value = binascii.b2a_qp(attribute_value) encoded_value = codecs.decode(encoded_value, 'ascii') attribute_value = { '__type__': 'bytes', 'stream': '{0:s}'.form...
287,899
Converts a JSON list into an object. Args: json_list (list[object]): JSON serialized objects. Returns: list[object]: a deserialized list.
def _ConvertListToObject(cls, json_list): list_value = [] for json_list_element in json_list: if isinstance(json_list_element, dict): list_value.append(cls._ConvertDictToObject(json_list_element)) elif isinstance(json_list_element, list): list_value.append(cls._ConvertListToObj...
287,903
Reads an attribute container from serialized form. Args: json_string (str): JSON serialized attribute container. Returns: AttributeContainer: attribute container or None.
def ReadSerialized(cls, json_string): # pylint: disable=arguments-differ if json_string: json_dict = json.loads(json_string) return cls.ReadSerializedDict(json_dict) return None
287,906
Reads an attribute container from serialized dictionary form. Args: json_dict (dict[str, object]): JSON serialized objects. Returns: AttributeContainer: attribute container or None. Raises: TypeError: if the serialized dictionary does not contain an AttributeContainer.
def ReadSerializedDict(cls, json_dict): if json_dict: json_object = cls._ConvertDictToObject(json_dict) if not isinstance(json_object, containers_interface.AttributeContainer): raise TypeError('{0:s} is not an attribute container type.'.format( type(json_object))) return j...
287,907
Writes an attribute container to serialized form. Args: attribute_container (AttributeContainer): attribute container. Returns: str: A JSON string containing the serialized form.
def WriteSerialized(cls, attribute_container): json_dict = cls.WriteSerializedDict(attribute_container) return json.dumps(json_dict)
287,908
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') process_memory_limit = cls._ParseNumericOption( options, 'process_memory_limit') if...
287,909
Initializes an output module. Args: output_mediator (OutputMediator): mediates interactions between output modules and other components, such as storage and dfvfs. Raises: ValueError: when there are unused keyword arguments.
def __init__(self, output_mediator): super(OutputModule, self).__init__() self._output_mediator = output_mediator
287,910
Reports an event related error. Args: event (EventObject): event. error_message (str): error message.
def _ReportEventError(self, event, error_message): event_identifier = event.GetIdentifier() event_identifier_string = event_identifier.CopyToString() display_name = getattr(event, 'display_name', None) or 'N/A' parser_chain = getattr(event, 'parser', None) or 'N/A' error_message = ( 'Ev...
287,911
Writes the event to the output. Args: event (EventObject): event.
def WriteEvent(self, event): self.WriteEventStart() try: self.WriteEventBody(event) except errors.NoFormatterFound as exception: error_message = 'unable to retrieve formatter with error: {0!s}'.format( exception) self._ReportEventError(event, error_message) except err...
287,912
Initializes a linear output module. Args: output_mediator (OutputMediator): mediates interactions between output modules and other components, such as storage and dfvfs. Raises: ValueError: if the output writer is missing.
def __init__(self, output_mediator): super(LinearOutputModule, self).__init__(output_mediator) self._output_writer = None
287,913
Parses a contact 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 resulting from query.
def ParseContactRow(self, parser_mediator, query, row, **unused_kwargs): query_hash = hash(query) event_data = TwitterIOSContactEventData() event_data.description = self._GetRowValue(query_hash, row, 'description') event_data.followers_count = self._GetRowValue( query_hash, row, 'followers...
287,916
Parses a contact 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 resulting from query.
def ParseStatusRow(self, parser_mediator, query, row, **unused_kwargs): query_hash = hash(query) event_data = TwitterIOSStatusEventData() event_data.favorite_count = self._GetRowValue( query_hash, row, 'favoriteCount') event_data.favorited = self._GetRowValue(query_hash, row, 'favorited') ...
287,917
Parses a structure of tokens derived from a line of a text file. Args: parser_mediator (ParserMediator): parser mediator. key (str): identifier of the structure of tokens. structure (pyparsing.ParseResults): structure of tokens derived from a line of a text file. Raises: Pars...
def ParseRecord(self, parser_mediator, key, structure): if key != 'line': raise errors.ParseError( 'Unable to parse record, unknown structure: {0:s}'.format(key)) try: date_time = dfdatetime_time_elements.TimeElements( time_elements_tuple=structure.date_time) except Val...
287,919
Verifies if a line from a text file is in the expected format. Args: parser_mediator (ParserMediator): parser mediator. line (str): line from a text file. Returns: bool: True if the line is in the expected format, False if not.
def VerifyStructure(self, parser_mediator, line): try: structure = self._DPKG_LOG_LINE.parseString(line) except pyparsing.ParseException as exception: logger.debug( 'Unable to parse Debian dpkg.log file with error: {0!s}'.format( exception)) return False retur...
287,920
Reads an operating system artifact from a dictionary. Args: operating_system_values (dict[str, object]): operating system values. Returns: OperatingSystemArtifact: an operating system artifact attribute container. Raises: MalformedPresetError: if the format of the operating system value...
def _ReadOperatingSystemArtifactValues(self, operating_system_values): if not operating_system_values: raise errors.MalformedPresetError('Missing operating system values.') family = operating_system_values.get('family', None) product = operating_system_values.get('product', None) version = o...
287,922
Reads a parser preset from a dictionary. Args: preset_definition_values (dict[str, object]): preset definition values. Returns: ParserPreset: a parser preset. Raises: MalformedPresetError: if the format of the preset definition is not set or incorrect, or the preset of a speci...
def _ReadParserPresetValues(self, preset_definition_values): if not preset_definition_values: raise errors.MalformedPresetError('Missing preset definition values.') name = preset_definition_values.get('name', None) if not name: raise errors.MalformedPresetError( 'Invalid preset d...
287,923
Reads parser and parser plugin presets from a file-like object. Args: file_object (file): file-like object containing the parser and parser plugin presets definitions. Yields: ParserPreset: a parser preset. Raises: MalformedPresetError: if one or more plugin preset definitions...
def _ReadPresetsFromFileObject(self, file_object): yaml_generator = yaml.safe_load_all(file_object) last_preset_definition = None for yaml_definition in yaml_generator: try: preset_definition = self._ReadParserPresetValues(yaml_definition) except errors.MalformedPresetError as exce...
287,924
Retrieves a specific preset definition by name. Args: name (str): name of the preset. Returns: ParserPreset: a parser preset or None if not available.
def GetPresetByName(self, name): name = name.lower() return self._definitions.get(name, None)
287,925
Retrieves preset definitions for a specific operating system. Args: operating_system (OperatingSystemArtifact): an operating system artifact attribute container. Returns: list[PresetDefinition]: preset definition that correspond with the operating system.
def GetPresetsByOperatingSystem(self, operating_system): preset_definitions = [] for preset_definition in self._definitions.values(): for preset_operating_system in preset_definition.operating_systems: if preset_operating_system.IsEquivalent(operating_system): preset_definitions.app...
287,926
Reads parser and parser plugin presets from a file. Args: path (str): path of file that contains the the parser and parser plugin presets configuration. Raises: MalformedPresetError: if one or more plugin preset definitions are malformed.
def ReadFromFile(self, path): self._definitions = {} with open(path, 'r') as file_object: for preset_definition in self._ReadPresetsFromFileObject(file_object): self._definitions[preset_definition.name] = preset_definition
287,927
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() visit_type = event_values.get('visit_type', 0) transition = self._URL_TRA...
287,928
Adds command line arguments the helper supports 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 grou...
def AddArguments(cls, argument_group): argument_group.add_argument( '--virustotal-api-key', '--virustotal_api_key', dest='virustotal_api_key', type=str, action='store', default=None, metavar='API_KEY', help=( 'Specify the API key for use with VirusTotal.')) argument_gro...
287,929
Parses and validates options. Args: options (argparse.Namespace): parser options. analysis_plugin (VirusTotalAnalysisPlugin): analysis plugin to configure. Raises: BadConfigObject: when the output module object is of the wrong type. BadConfigOption: when a configuration parameter fails...
def ParseOptions(cls, options, analysis_plugin): if not isinstance(analysis_plugin, virustotal.VirusTotalAnalysisPlugin): raise errors.BadConfigObject( 'Analysis plugin is not an instance of VirusTotalAnalysisPlugin') api_key = cls._ParseStringOption(options, 'virustotal_api_key') if n...
287,930
Processes a path specification. Args: extraction_worker (worker.ExtractionWorker): extraction worker. parser_mediator (ParserMediator): parser mediator. path_spec (dfvfs.PathSpec): path specification.
def _ProcessPathSpec(self, extraction_worker, parser_mediator, path_spec): self._current_display_name = parser_mediator.GetDisplayNameForPathSpec( path_spec) try: extraction_worker.ProcessPathSpec(parser_mediator, path_spec) except dfvfs_errors.CacheFullError: # TODO: signal engin...
287,934
Processes a task. Args: task (Task): task.
def _ProcessTask(self, task): logger.debug('Started processing task: {0:s}.'.format(task.identifier)) if self._tasks_profiler: self._tasks_profiler.Sample(task, 'processing_started') self._task = task storage_writer = self._storage_writer.CreateTaskStorage(task) if self._serializers_p...
287,935
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( '--preferred_year', '--preferred-year', dest='preferred_year', type=int, action='store', default=None, metavar='YEAR', help=( 'When a format\'s timestamp does not include a year, e.g. ' 'syslog, use this...
287,937
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') preferred_year = cls._ParseNumericOption(options, 'preferred_year') process_archives = geta...
287,938
Initializes an environment variable artifact. Args: case_sensitive (Optional[bool]): True if environment variable name is case sensitive. name (Optional[str]): environment variable name. value (Optional[str]): environment variable value.
def __init__(self, case_sensitive=True, name=None, value=None): super(EnvironmentVariableArtifact, self).__init__() self.case_sensitive = case_sensitive self.name = name self.value = value
287,939
Initializes a hostname artifact. Args: name (Optional[str]): name of the host according to the naming schema. schema (Optional[str]): naming schema.
def __init__(self, name=None, schema='DNS'): super(HostnameArtifact, self).__init__() self.name = name self.schema = schema
287,940
Determines if 2 operating system artifacts are equivalent. This function compares the operating systems based in order of: * name derived from product * family and version * family Args: other (OperatingSystemArtifact): operating system artifact attribute container to compare with....
def IsEquivalent(self, other): if self.name and other.name: return self.name == other.name if self.name: self_family, self_version_tuple = self._FAMILY_AND_VERSION_PER_NAME.get( self.name, self._DEFAULT_FAMILY_AND_VERSION) return ( self_family == other.family and ...
287,944
Initializes a system configuration artifact. Args: code_page (Optional[str]): system code page. time_zone (Optional[str]): system time zone.
def __init__(self, code_page=None, time_zone=None): super(SystemConfigurationArtifact, self).__init__() self.code_page = code_page self.hostname = None self.keyboard_layout = None self.operating_system = None self.operating_system_product = None self.operating_system_version = None ...
287,945
Initializes an user artifact. Args: full_name (Optional[str]): name describing the user e.g. full name. group_identifier (Optional[str]): identifier of the primary group the user is part of. identifier (Optional[str]): user identifier. path_separator (Optional[str]): path segment ...
def __init__( self, full_name=None, group_identifier=None, identifier=None, path_separator='/', user_directory=None, username=None): super(UserAccountArtifact, self).__init__() self._path_separator = path_separator self.full_name = full_name self.group_identifier = group_identifier ...
287,946
Tries to determine the underlying operating system. Args: searcher (dfvfs.FileSystemSearcher): file system searcher. Returns: str: operating system for example "Windows". This should be one of the values in definitions.OPERATING_SYSTEM_FAMILIES.
def _DetermineOperatingSystem(self, searcher): find_specs = [ file_system_searcher.FindSpec( location='/etc', case_sensitive=False), file_system_searcher.FindSpec( location='/System/Library', case_sensitive=False), file_system_searcher.FindSpec( locat...
287,948
Starts profiling. Args: configuration (ProfilingConfiguration): profiling configuration.
def _StartProfiling(self, configuration): if not configuration: return if configuration.HaveProfileMemoryGuppy(): self._guppy_memory_profiler = profilers.GuppyMemoryProfiler( self._name, configuration) self._guppy_memory_profiler.Start() if configuration.HaveProfileMemory(...
287,949
Preprocesses the sources. Args: artifacts_registry_object (artifacts.ArtifactDefinitionsRegistry): artifact definitions registry. source_path_specs (list[dfvfs.PathSpec]): path specifications of the sources to process. resolver_context (Optional[dfvfs.Context]): resolver conte...
def PreprocessSources( self, artifacts_registry_object, source_path_specs, resolver_context=None): detected_operating_systems = [] for source_path_spec in source_path_specs: try: file_system, mount_point = self.GetSourceFileSystem( source_path_spec, resolver_context=re...
287,951
Build Find Specs from artifacts or filter file if available. Args: artifact_definitions_path (str): path to artifact definitions file. custom_artifacts_path (str): path to custom artifact definitions file. Returns: artifacts.ArtifactDefinitionsRegistry: artifact definitions registry. ...
def BuildArtifactsRegistry( cls, artifact_definitions_path, custom_artifacts_path): if artifact_definitions_path and not os.path.isdir( artifact_definitions_path): raise errors.BadConfigOption( 'No such artifacts filter file: {0:s}.'.format( artifact_definitions_path...
287,953
Retrieves the timestamps from an OLECF item. Args: olecf_item (pyolecf.item): OLECF item. Returns: tuple[int, int]: creation and modification FILETIME timestamp.
def _GetTimestamps(self, olecf_item): if not olecf_item: return None, None try: creation_time = olecf_item.get_creation_time_as_integer() except OverflowError as exception: logger.warning( 'Unable to read the creation time with error: {0!s}'.format( exception)...
287,954
Retrieves a list of a hasher names from a comma separated string. Takes a string of comma separated hasher names transforms it to a list of hasher names. Args: hasher_names_string (str): comma separated names of hashers to enable, the string 'all' to enable all hashers or 'none' to disable...
def GetHasherNamesFromString(cls, hasher_names_string): hasher_names = [] if not hasher_names_string or hasher_names_string.strip() == 'none': return hasher_names if hasher_names_string.strip() == 'all': return cls.GetHasherNames() for hasher_name in hasher_names_string.split(','): ...
287,955
Retrieves an instance of a specific hasher. Args: hasher_name (str): the name of the hasher to retrieve. Returns: BaseHasher: hasher. Raises: KeyError: if hasher class is not set for the corresponding name.
def GetHasher(cls, hasher_name): hasher_name = hasher_name.lower() if hasher_name not in cls._hasher_classes: raise KeyError( 'hasher class not set for name: {0:s}.'.format(hasher_name)) hasher_class = cls._hasher_classes[hasher_name] return hasher_class()
287,957
Retrieves instances for all the specified hashers. Args: hasher_names (list[str]): names of the hashers to retrieve. Returns: list[BaseHasher]: hashers.
def GetHashers(cls, hasher_names): hashers = [] for hasher_name, hasher_class in iter(cls._hasher_classes.items()): if hasher_name in hasher_names: hashers.append(hasher_class()) return hashers
287,958
Retrieves the registered hashers. Args: hasher_names (list[str]): names of the hashers to retrieve. Yields: tuple: containing: str: parser name type: next hasher class.
def GetHasherClasses(cls, hasher_names=None): for hasher_name, hasher_class in iter(cls._hasher_classes.items()): if not hasher_names or hasher_name in hasher_names: yield hasher_name, hasher_class
287,959
Registers a hasher class. The hasher classes are identified based on their lower case name. Args: hasher_class (type): class object of the hasher. Raises: KeyError: if hasher class is already set for the corresponding name.
def RegisterHasher(cls, hasher_class): hasher_name = hasher_class.NAME.lower() if hasher_name in cls._hasher_classes: raise KeyError(( 'hasher class already set for name: {0:s}.').format( hasher_class.NAME)) cls._hasher_classes[hasher_name] = hasher_class
287,960
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 collection fi...
def ParseOptions(cls, options, configuration_object): if not isinstance(configuration_object, tools.CLITool): raise errors.BadConfigObject( 'Configuration object is not an instance of CLITool') filter_file = cls._ParseStringOption(options, 'file_filter') # Search the data location for...
287,961
Retrieves an ISO8601 date time string from the structure. The date and time values in the SCCM log are formatted as: time="19:33:19.766-330" date="11-28-2014" Args: structure (pyparsing.ParseResults): structure of tokens derived from a line of a text file. Returns: str: ISO 8601...
def _GetISO8601String(self, structure): fraction_of_second_length = len(structure.fraction_of_second) if fraction_of_second_length not in (3, 6, 7): raise ValueError( 'unsupported time fraction of second length: {0:d}'.format( fraction_of_second_length)) try: fracti...
287,963
Parse the record and return an SCCM log event object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. key (str): name of the parsed structure. structure (pyparsing.ParseResults): structure of tokens derived f...
def ParseRecord(self, parser_mediator, key, structure): if key not in ( 'log_entry', 'log_entry_at_end', 'log_entry_offset', 'log_entry_offset_at_end'): raise errors.ParseError( 'Unable to parse record, unknown structure: {0:s}'.format(key)) try: date_time_string = se...
287,964
Verifies whether content corresponds to an SCCM log 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 this is the correct par...
def VerifyStructure(self, parser_mediator, lines): # Identify the token to which we attempt a match. match = self._PARSING_COMPONENTS['msg_left_delimiter'].match # Because logs files can lead with a partial event, # we can't assume that the first character (post-BOM) # in the file is the begin...
287,965
Initializes the token object. Args: state_regex: If this regular expression matches the current state this rule is considered. regex: A regular expression to try and match from the current point. actions: A command separated list of method names in the Lexer to call. nex...
def __init__(self, state_regex, regex, actions, next_state, flags=re.I): self.state_regex = re.compile( state_regex, re.DOTALL | re.M | re.S | re.U | flags) self.regex = re.compile(regex, re.DOTALL | re.M | re.S | re.U | flags) self.re_str = regex self.actions = [] if actions: sel...
287,966