docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Signal handler for the SIGSEGV signal. Args: signal_number (int): numeric representation of the signal. stack_frame (frame): current stack frame or None.
def _SigSegvHandler(self, signal_number, stack_frame): self._OnCriticalError() # Note that the original SIGSEGV handler can be 0. if self._original_sigsegv_handler is not None: # Let the original SIGSEGV handler take over. signal.signal(signal.SIGSEGV, self._original_sigsegv_handler) ...
289,164
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(...
289,166
Parses a data object. Args: file_object (dfvfs.FileIO): a file-like object. file_offset (int): offset of the data object relative to the start of the file-like object. Returns: bytes: data. Raises: ParseError: if the data object cannot be parsed.
def _ParseDataObject(self, file_object, file_offset): data_object_map = self._GetDataTypeMap('systemd_journal_data_object') try: data_object, _ = self._ReadStructureFromFileObject( file_object, file_offset, data_object_map) except (ValueError, errors.ParseError) as exception: rai...
289,172
Parses an entry array object. Args: file_object (dfvfs.FileIO): a file-like object. file_offset (int): offset of the entry array object relative to the start of the file-like object. Returns: systemd_journal_entry_array_object: entry array object. Raises: ParseError: if ...
def _ParseEntryArrayObject(self, file_object, file_offset): entry_array_object_map = self._GetDataTypeMap( 'systemd_journal_entry_array_object') try: entry_array_object, _ = self._ReadStructureFromFileObject( file_object, file_offset, entry_array_object_map) except (ValueError,...
289,173
Parses an entry object. Args: file_object (dfvfs.FileIO): a file-like object. file_offset (int): offset of the entry object relative to the start of the file-like object. Returns: systemd_journal_entry_object: entry object. Raises: ParseError: if the entry object cannot ...
def _ParseEntryObject(self, file_object, file_offset): entry_object_map = self._GetDataTypeMap('systemd_journal_entry_object') try: entry_object, _ = self._ReadStructureFromFileObject( file_object, file_offset, entry_object_map) except (ValueError, errors.ParseError) as exception: ...
289,174
Parses entry array objects for the offset of the entry objects. Args: file_object (dfvfs.FileIO): a file-like object. file_offset (int): offset of the first entry array object relative to the start of the file-like object. Returns: list[int]: offsets of the entry objects.
def _ParseEntryObjectOffsets(self, file_object, file_offset): entry_array_object = self._ParseEntryArrayObject(file_object, file_offset) entry_object_offsets = list(entry_array_object.entry_object_offsets) while entry_array_object.next_entry_array_offset != 0: entry_array_object = self._ParseEnt...
289,175
Parses a journal entry. This method will generate an event per ENTRY object. Args: file_object (dfvfs.FileIO): a file-like object. file_offset (int): offset of the entry object relative to the start of the file-like object. Returns: dict[str, objects]: entry items per key. ...
def _ParseJournalEntry(self, file_object, file_offset): entry_object = self._ParseEntryObject(file_object, file_offset) # The data is read separately for performance reasons. entry_item_map = self._GetDataTypeMap('systemd_journal_entry_item') file_offset += 64 data_end_offset = file_offset + ...
289,176
Parses a Systemd journal file-like object. Args: parser_mediator (ParserMediator): parser mediator. file_object (dfvfs.FileIO): a file-like object. Raises: UnableToParseFile: when the header cannot be parsed.
def ParseFileObject(self, parser_mediator, file_object): file_header_map = self._GetDataTypeMap('systemd_journal_file_header') try: file_header, _ = self._ReadStructureFromFileObject( file_object, 0, file_header_map) except (ValueError, errors.ParseError) as exception: raise erro...
289,177
Retrieves a string representation of the event type. Args: event_type (int): event type. Returns: str: description of the event type.
def GetEventTypeString(self, event_type): if 0 <= event_type < len(self._EVENT_TYPES): return self._EVENT_TYPES[event_type] return 'Unknown {0:d}'.format(event_type)
289,179
Retrieves a string representation of the severity. Args: severity (int): severity. Returns: str: description of the event severity.
def GetSeverityString(self, severity): if 0 <= severity < len(self._SEVERITY): return self._SEVERITY[severity] return 'Unknown {0:d}'.format(severity)
289,180
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() event_type = event_values.get('event_type', None) if event_type is not No...
289,181
Initializes the output module object. Args: output_mediator (OutputMediator): mediates interactions between output modules and other components, such as storage and dfvfs.
def __init__(self, output_mediator): super(JSONOutputModule, self).__init__(output_mediator) self._event_counter = 0
289,182
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 json_dict = self._JSON_SERIALIZER.WriteSerializedDict(event) json_string = json.dumps(json_dict, sort_keys=True) if self._event_counter != 0: self._output_writer.Write(', ') ...
289,183
Retrieves the row cache for a specific query. The row cache is a set that contains hashes of values in a row. The row cache is used to find duplicate row when a database and a database with a WAL file is parsed. Args: query (str): query. Returns: set: hashes of the rows that have been...
def GetRowCache(self, query): query_hash = hash(query) if query_hash not in self._row_caches: self._row_caches[query_hash] = set() return self._row_caches[query_hash]
289,185
Initializes the database object. Args: filename (str): name of the file entry. temporary_directory (Optional[str]): path of the directory for temporary files.
def __init__(self, filename, temporary_directory=None): self._database = None self._filename = filename self._is_open = False self._temp_db_file_path = '' self._temporary_directory = temporary_directory self._temp_wal_file_path = '' self.schema = {}
289,186
Copies the contents of the file-like object to a temporary file. Args: file_object (dfvfs.FileIO): file-like object. temporary_file (file): temporary file.
def _CopyFileObjectToTemporaryFile(self, file_object, temporary_file): file_object.seek(0, os.SEEK_SET) data = file_object.read(self._READ_BUFFER_SIZE) while data: temporary_file.write(data) data = file_object.read(self._READ_BUFFER_SIZE)
289,187
Queries the database. Args: query (str): SQL query. Returns: sqlite3.Cursor: results. Raises: sqlite3.DatabaseError: if querying the database fails.
def Query(self, query): cursor = self._database.cursor() cursor.execute(query) return cursor
289,190
Parses a SQLite database file entry. Args: parser_mediator (ParserMediator): parser mediator. file_entry (dfvfs.FileEntry): file entry to be parsed. Raises: UnableToParseFile: when the file cannot be parsed.
def ParseFileEntry(self, parser_mediator, file_entry): filename = parser_mediator.GetFilename() database = SQLiteDatabase( filename, temporary_directory=parser_mediator.temporary_directory) file_object = file_entry.GetFileObject() try: database.Open(file_object) except (IOError,...
289,192
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(): values_dict = {} values_dict['subkey_name'] = subkey.name name_values = subkey.name.split('&') number_of_name_values = len(name_values) # Normally we expect 4 fields here h...
289,193
Parses a C string from the page data. Args: page_data (bytes): page data. string_offset (int): offset of the string relative to the start of the page. Returns: str: string. Raises: ParseError: when the string cannot be parsed.
def _ParseCString(self, page_data, string_offset): cstring_map = self._GetDataTypeMap('cstring') try: value_string = self._ReadStructureFromByteStream( page_data[string_offset:], string_offset, cstring_map) except (ValueError, errors.ParseError) as exception: raise errors.ParseEr...
289,196
Parses a page. Args: parser_mediator (ParserMediator): parser mediator. file_offset (int): offset of the data relative from the start of the file-like object. page_data (bytes): page data. Raises: ParseError: when the page cannot be parsed.
def _ParsePage(self, parser_mediator, file_offset, page_data): page_header_map = self._GetDataTypeMap('binarycookies_page_header') try: page_header = self._ReadStructureFromByteStream( page_data, file_offset, page_header_map) except (ValueError, errors.ParseError) as exception: r...
289,197
Parses a record from the page data. Args: parser_mediator (ParserMediator): parser mediator. page_data (bytes): page data. record_offset (int): offset of the record relative to the start of the page. Raises: ParseError: when the record cannot be parsed.
def _ParseRecord(self, parser_mediator, page_data, record_offset): record_header_map = self._GetDataTypeMap('binarycookies_record_header') try: record_header = self._ReadStructureFromByteStream( page_data[record_offset:], record_offset, record_header_map) except (ValueError, errors.Par...
289,198
Parses a Safari binary cookie file-like object. Args: parser_mediator (ParserMediator): parser mediator. file_object (dfvfs.FileIO): file-like object to be parsed. Raises: UnableToParseFile: when the file cannot be parsed, this will signal the event extractor to apply other parsers...
def ParseFileObject(self, parser_mediator, file_object): file_header_map = self._GetDataTypeMap('binarycookies_file_header') try: file_header, file_header_data_size = self._ReadStructureFromFileObject( file_object, 0, file_header_map) except (ValueError, errors.ParseError) as exception...
289,199
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( '--disable_zeromq', '--disable-zeromq', action='store_false', dest='use_zeromq', default=True, help=( 'Disable queueing using ZeroMQ. A Multiprocessing queue will be ' 'used instead.'))
289,200
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') use_zeromq = getattr(options, 'use_zeromq', True) setattr(configuration_object, '_use_zerom...
289,201
Initializes a dynamic fields helper. Args: output_mediator (OutputMediator): output mediator.
def __init__(self, output_mediator): super(DynamicFieldsHelper, self).__init__() self._output_mediator = output_mediator
289,202
Formats the date. Args: event (EventObject): event. Returns: str: date field.
def _FormatDate(self, event): # TODO: preserve dfdatetime as an object. # TODO: add support for self._output_mediator.timezone date_time = dfdatetime_posix_time.PosixTimeInMicroseconds( timestamp=event.timestamp) year, month, day_of_month = date_time.GetDate() try: return '{0:04d...
289,203
Formats the date and time in ISO 8601 format. Args: event (EventObject): event. Returns: str: date and time field.
def _FormatDateTime(self, event): try: return timelib.Timestamp.CopyToIsoFormat( event.timestamp, timezone=self._output_mediator.timezone, raise_error=True) except (OverflowError, ValueError) as exception: self._ReportEventError(event, ( 'unable to copy timestamp:...
289,204
Formats the inode. Args: event (EventObject): event. Returns: str: inode field.
def _FormatInode(self, event): inode = event.inode if inode is None: if hasattr(event, 'pathspec') and hasattr(event.pathspec, 'image_inode'): inode = event.pathspec.image_inode if inode is None: inode = '-' return inode
289,205
Formats the message. Args: event (EventObject): event. Returns: str: message field. Raises: NoFormatterFound: if no event formatter can be found to match the data type in the event.
def _FormatMessage(self, event): message, _ = self._output_mediator.GetFormattedMessages(event) if message is None: data_type = getattr(event, 'data_type', 'UNKNOWN') raise errors.NoFormatterFound( 'Unable to find event formatter for: {0:s}.'.format(data_type)) return message
289,206
Formats the short message. Args: event (EventObject): event. Returns: str: short message field. Raises: NoFormatterFound: if no event formatter can be found to match the data type in the event.
def _FormatMessageShort(self, event): _, message_short = self._output_mediator.GetFormattedMessages(event) if message_short is None: data_type = getattr(event, 'data_type', 'UNKNOWN') raise errors.NoFormatterFound( 'Unable to find event formatter for: {0:s}.'.format(data_type)) r...
289,207
Formats the source. Args: event (EventObject): event. Returns: str: source field. Raises: NoFormatterFound: if no event formatter can be found to match the data type in the event.
def _FormatSource(self, event): _, source = self._output_mediator.GetFormattedSources(event) if source is None: data_type = getattr(event, 'data_type', 'UNKNOWN') raise errors.NoFormatterFound( 'Unable to find event formatter for: {0:s}.'.format(data_type)) return source
289,208
Formats the short source. Args: event (EventObject): event. Returns: str: short source field. Raises: NoFormatterFound: If no event formatter can be found to match the data type in the event.
def _FormatSourceShort(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)) retur...
289,209
Formats the event tag. Args: event (EventObject): event. Returns: str: event tag field.
def _FormatTag(self, event): tag = getattr(event, 'tag', None) if not tag: return '-' return ' '.join(tag.labels)
289,210
Formats the specified field. Args: event (EventObject): event. field_name (str): name of the field. Returns: str: value of the field.
def GetFormattedField(self, event, field_name): callback_name = self._FIELD_FORMAT_CALLBACKS.get(field_name, None) callback_function = None if callback_name: callback_function = getattr(self, callback_name, None) if callback_function: output_value = callback_function(event) else: ...
289,211
Initializes an output module object. Args: output_mediator (OutputMediator): an output mediator.
def __init__(self, output_mediator): super(DynamicOutputModule, self).__init__(output_mediator) self._dynamic_fields_helper = DynamicFieldsHelper(output_mediator) self._field_delimiter = self._DEFAULT_FIELD_DELIMITER self._fields = self._DEFAULT_FIELDS
289,212
Sanitizes a field for output. This method replaces any field delimiters with a space. Args: field (str): name of the field to sanitize. Returns: str: value of the field.
def _SanitizeField(self, field): if self._field_delimiter and isinstance(field, py2to3.STRING_TYPES): return field.replace(self._field_delimiter, ' ') return field
289,213
Writes the body of an event to the output. Args: event (EventObject): event.
def WriteEventBody(self, event): output_values = [] for field_name in self._fields: output_value = self._dynamic_fields_helper.GetFormattedField( event, field_name) output_value = self._SanitizeField(output_value) output_values.append(output_value) output_line = '{0:s}\n'....
289,214
Retrieves a specific serialized attribute container from the list. Args: index (int): attribute container index. Returns: bytes: serialized attribute container data or None if not available. Raises: IndexError: if the index is less than zero.
def GetAttributeContainerByIndex(self, index): if index < 0: raise IndexError( 'Unsupported negative index value: {0:d}.'.format(index)) if index < len(self._list): return self._list[index] return None
289,217
Pushes a serialized attribute container onto the list. Args: serialized_data (bytes): serialized attribute container data.
def PushAttributeContainer(self, serialized_data): self._list.append(serialized_data) self.data_size += len(serialized_data) self.next_sequence_number += 1
289,219
Deserializes an attribute container. Args: container_type (str): attribute container type. serialized_data (bytes): serialized attribute container data. Returns: AttributeContainer: attribute container or None. Raises: IOError: if the serialized data cannot be decoded. OSErr...
def _DeserializeAttributeContainer(self, container_type, serialized_data): if not serialized_data: return None if self._serializers_profiler: self._serializers_profiler.StartTiming(container_type) try: serialized_string = serialized_data.decode('utf-8') except UnicodeDecodeError...
289,222
Retrieves a specific serialized attribute container. Args: container_type (str): attribute container type. index (int): attribute container index. Returns: bytes: serialized attribute container data or None if not available.
def _GetSerializedAttributeContainerByIndex(self, container_type, index): container_list = self._GetSerializedAttributeContainerList(container_type) return container_list.GetAttributeContainerByIndex(index)
289,223
Retrieves a serialized attribute container list. Args: container_type (str): attribute container type. Returns: SerializedAttributeContainerList: serialized attribute container list.
def _GetSerializedAttributeContainerList(self, container_type): container_list = self._serialized_attribute_containers.get( container_type, None) if not container_list: container_list = SerializedAttributeContainerList() self._serialized_attribute_containers[container_type] = container_...
289,224
Serializes an attribute container. Args: attribute_container (AttributeContainer): attribute container. Returns: bytes: serialized attribute container. Raises: IOError: if the attribute container cannot be serialized. OSError: if the attribute container cannot be serialized.
def _SerializeAttributeContainer(self, attribute_container): if self._serializers_profiler: self._serializers_profiler.StartTiming( attribute_container.CONTAINER_TYPE) try: attribute_container_data = self._serializer.WriteSerialized( attribute_container) if not attrib...
289,225
Initializes a storage merge reader. Args: storage_writer (StorageWriter): storage writer.
def __init__(self, storage_writer): super(StorageMergeReader, self).__init__() self._storage_writer = storage_writer
289,226
Initializes a storage merge reader. Args: storage_writer (StorageWriter): storage writer.
def __init__(self, storage_writer): super(StorageFileMergeReader, self).__init__(storage_writer) self._serializer = json_serializer.JSONAttributeContainerSerializer self._serializers_profiler = None
289,227
Initializes a storage reader. Args: path (str): path to the input file.
def __init__(self, path): super(StorageFileReader, self).__init__() self._path = path self._storage_file = None
289,228
Initializes a storage writer. Args: session (Session): session the storage changes are part of. storage_type (Optional[str]): storage type. task(Optional[Task]): task.
def __init__( self, session, storage_type=definitions.STORAGE_TYPE_SESSION, task=None): super(StorageWriter, self).__init__() self._first_written_event_source_index = 0 self._serializers_profiler = None self._session = session self._storage_profiler = None self._storage_type = storage...
289,229
Initializes a storage writer. Args: session (Session): session the storage changes are part of. output_file (str): path to the output file. storage_type (Optional[str]): storage type. task(Optional[Task]): task.
def __init__( self, session, output_file, storage_type=definitions.STORAGE_TYPE_SESSION, task=None): super(StorageFileWriter, self).__init__( session, storage_type=storage_type, task=task) self._merge_task_storage_path = '' self._output_file = output_file self._processed_task_st...
289,230
Retrieves the path of a task storage file in the merge directory. Args: task (Task): task. Returns: str: path of a task storage file file in the merge directory.
def _GetMergeTaskStorageFilePath(self, task): filename = '{0:s}.plaso'.format(task.identifier) return os.path.join(self._merge_task_storage_path, filename)
289,231
Retrieves the path of a task storage file in the processed directory. Args: task (Task): task. Returns: str: path of a task storage file in the processed directory.
def _GetProcessedStorageFilePath(self, task): filename = '{0:s}.plaso'.format(task.identifier) return os.path.join(self._processed_task_storage_path, filename)
289,232
Retrieves the path of a task storage file in the temporary directory. Args: task (Task): task. Returns: str: path of a task storage file in the temporary directory.
def _GetTaskStorageFilePath(self, task): filename = '{0:s}.plaso'.format(task.identifier) return os.path.join(self._task_storage_path, filename)
289,233
Updates the counters. Args: event (EventObject): event.
def _UpdateCounters(self, event): self._session.parsers_counter['total'] += 1 # Here we want the name of the parser or plugin not the parser chain. parser_name = getattr(event, 'parser', '') _, _, parser_name = parser_name.rpartition('/') if not parser_name: parser_name = 'N/A' self....
289,234
Adds an analysis report. Args: analysis_report (AnalysisReport): analysis report. Raises: IOError: when the storage writer is closed. OSError: when the storage writer is closed.
def AddAnalysisReport(self, analysis_report): self._RaiseIfNotWritable() self._storage_file.AddAnalysisReport(analysis_report) report_identifier = analysis_report.plugin_name self._session.analysis_reports_counter['total'] += 1 self._session.analysis_reports_counter[report_identifier] += 1 ...
289,235
Adds an warning. Args: warning (ExtractionWarning): an extraction warning. Raises: IOError: when the storage writer is closed. OSError: when the storage writer is closed.
def AddWarning(self, warning): self._RaiseIfNotWritable() self._storage_file.AddWarning(warning) self.number_of_warnings += 1
289,236
Adds an event. Args: event (EventObject): an event. Raises: IOError: when the storage writer is closed. OSError: when the storage writer is closed.
def AddEvent(self, event): self._RaiseIfNotWritable() self._storage_file.AddEvent(event) self.number_of_events += 1 self._UpdateCounters(event)
289,237
Adds an event source. Args: event_source (EventSource): an event source. Raises: IOError: when the storage writer is closed. OSError: when the storage writer is closed.
def AddEventSource(self, event_source): self._RaiseIfNotWritable() self._storage_file.AddEventSource(event_source) self.number_of_event_sources += 1
289,238
Adds an event tag. Args: event_tag (EventTag): an event tag. Raises: IOError: when the storage writer is closed. OSError: when the storage writer is closed.
def AddEventTag(self, event_tag): self._RaiseIfNotWritable() self._storage_file.AddEventTag(event_tag) self._session.event_labels_counter['total'] += 1 for label in event_tag.labels: self._session.event_labels_counter[label] += 1 self.number_of_event_tags += 1
289,239
Checks if a task is ready for merging with this session storage. If the task is ready to be merged, this method also sets the task's storage file size. Args: task (Task): task. Returns: bool: True if the task is ready to be merged. Raises: IOError: if the storage type is not su...
def CheckTaskReadyForMerge(self, task): if self._storage_type != definitions.STORAGE_TYPE_SESSION: raise IOError('Unsupported storage type.') if not self._processed_task_storage_path: raise IOError('Missing processed task storage path.') processed_storage_file_path = self._GetProcessedSto...
289,240
Creates a task storage. The task storage is used to store attributes created by the task. Args: task(Task): task. Returns: StorageWriter: storage writer. Raises: IOError: if the storage type is not supported. OSError: if the storage type is not supported.
def CreateTaskStorage(self, task): if self._storage_type != definitions.STORAGE_TYPE_SESSION: raise IOError('Unsupported storage type.') storage_file_path = self._GetTaskStorageFilePath(task) return self._CreateTaskStorageWriter(storage_file_path, task)
289,241
Retrieves the events in increasing chronological order. This includes all events written to the storage including those pending being flushed (written) to the storage. Args: time_range (Optional[TimeRange]): time range used to filter events that fall in a specific period. Returns: ...
def GetSortedEvents(self, time_range=None): if not self._storage_file: raise IOError('Unable to read from closed storage writer.') return self._storage_file.GetSortedEvents(time_range=time_range)
289,245
Finalizes a processed task storage. Moves the task storage file from its temporary directory to the processed directory. Args: task (Task): task. Raises: IOError: if the storage type is not supported or if the storage file cannot be renamed. OSError: if the storage type is...
def FinalizeTaskStorage(self, task): if self._storage_type != definitions.STORAGE_TYPE_SESSION: raise IOError('Unsupported storage type.') storage_file_path = self._GetTaskStorageFilePath(task) processed_storage_file_path = self._GetProcessedStorageFilePath(task) try: os.rename(storag...
289,246
Prepares a task storage for merging. Moves the task storage file from the processed directory to the merge directory. Args: task (Task): task. Raises: IOError: if the storage type is not supported or if the storage file cannot be renamed. OSError: if the storage type is no...
def PrepareMergeTaskStorage(self, task): if self._storage_type != definitions.STORAGE_TYPE_SESSION: raise IOError('Unsupported storage type.') merge_storage_file_path = self._GetMergeTaskStorageFilePath(task) processed_storage_file_path = self._GetProcessedStorageFilePath(task) task.storage...
289,248
Reads preprocessing information. The preprocessing information contains the system configuration which contains information about various system specific configuration data, for example the user accounts. Args: knowledge_base (KnowledgeBase): is used to store the preprocessing informat...
def ReadPreprocessingInformation(self, knowledge_base): if not self._storage_file: raise IOError('Unable to read from closed storage writer.') self._storage_file.ReadPreprocessingInformation(knowledge_base)
289,249
Removes a processed task storage. Args: task (Task): task. Raises: IOError: if the storage type is not supported or if the storage file cannot be removed. OSError: if the storage type is not supported or if the storage file cannot be removed.
def RemoveProcessedTaskStorage(self, task): if self._storage_type != definitions.STORAGE_TYPE_SESSION: raise IOError('Unsupported storage type.') processed_storage_file_path = self._GetProcessedStorageFilePath(task) try: os.remove(processed_storage_file_path) except OSError as excepti...
289,250
Sets the serializers profiler. Args: serializers_profiler (SerializersProfiler): serializers profiler.
def SetSerializersProfiler(self, serializers_profiler): self._serializers_profiler = serializers_profiler if self._storage_file: self._storage_file.SetSerializersProfiler(serializers_profiler)
289,251
Sets the storage profiler. Args: storage_profiler (StorageProfiler): storage profiler.
def SetStorageProfiler(self, storage_profiler): self._storage_profiler = storage_profiler if self._storage_file: self._storage_file.SetStorageProfiler(storage_profiler)
289,252
Removes the temporary path for the task storage. The results of tasks will be lost on abort. Args: abort (bool): True to indicate the stop is issued on abort. Raises: IOError: if the storage type is not supported. OSError: if the storage type is not supported.
def StopTaskStorage(self, abort=False): if self._storage_type != definitions.STORAGE_TYPE_SESSION: raise IOError('Unsupported storage type.') if os.path.isdir(self._merge_task_storage_path): if abort: shutil.rmtree(self._merge_task_storage_path) else: os.rmdir(self._merge...
289,255
Writes session completion information. Args: aborted (Optional[bool]): True if the session was aborted. Raises: IOError: if the storage type is not supported or when the storage writer is closed. OSError: if the storage type is not supported or when the storage writer is ...
def WriteSessionCompletion(self, aborted=False): self._RaiseIfNotWritable() if self._storage_type != definitions.STORAGE_TYPE_SESSION: raise IOError('Unsupported storage type.') self._session.aborted = aborted session_completion = self._session.CreateSessionCompletion() self._storage_fi...
289,256
Writes task completion information. Args: aborted (Optional[bool]): True if the session was aborted. Raises: IOError: if the storage type is not supported or when the storage writer is closed. OSError: if the storage type is not supported or when the storage writer is clo...
def WriteTaskCompletion(self, aborted=False): self._RaiseIfNotWritable() if self._storage_type != definitions.STORAGE_TYPE_TASK: raise IOError('Unsupported storage type.') self._task.aborted = aborted task_completion = self._task.CreateTaskCompletion() self._storage_file.WriteTaskComple...
289,258
Parses a line of the log file and produces events. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. row_offset (int): line number of the row. row (dict[str, str]): fields of a single row, as specified in COLUM...
def ParseRow(self, parser_mediator, row_offset, row): try: timestamp = self._ConvertToTimestamp( row['date'], row['time'], parser_mediator.timezone) except errors.TimestampError as exception: parser_mediator.ProduceExtractionWarning( 'Unable to parse time string: [{0:s} {1:s...
289,262
Verifies if a line of the file is in the expected format. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. row (dict[str, str]): fields of a single row, as specified in COLUMNS. Returns: bool: True if thi...
def VerifyRow(self, parser_mediator, row): if len(row) != 8: return False # This file can have a UTF-8 byte-order-marker at the beginning of # the first row. # TODO: Find out all the code pages this can have. Asked McAfee 10/31. row_bytes = codecs.encode(row['date'], parser_mediator.cod...
289,263
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): report_text = [ 'Sessionize plugin identified {0:d} sessions and ' 'applied {1:d} tags.'.format( len(self._events_per_session), self._number_of_event_tags)] for session, event_count in enumerate(self._events_per_session): report_text.appe...
289,265
Analyzes an EventObject and tags it as part of a session. 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): if self._session_end_timestamp is None: self._session_end_timestamp = ( event.timestamp + self._maximum_pause_microseconds) self._events_per_session.append(0) if event.timestamp > self._session_end_timestamp: self._session_counter += 1 ...
289,266
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() file_entry_type = event_values.get('file_entry_type', None) if file_entry...
289,267
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)) file_system_type = getattr(event, 'file_system_type', 'UNKNOWN') timestamp_desc = getattr(event, 'timestamp_desc', 'Time') source...
289,268
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() attribute_type = event_values.get('attribute_type', 0) event_values['attr...
289,269
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() file_reference = event_values.get('file_reference', None) if file_referen...
289,270
Initializes a multi-processing queue. Args: maximum_number_of_queued_items (Optional[int]): maximum number of queued items, where 0 represents no limit. timeout (Optional[float]): number of seconds for the get to time out, where None will block until a new item is put onto the queue...
def __init__(self, maximum_number_of_queued_items=0, timeout=None): super(MultiProcessingQueue, self).__init__() self._timeout = timeout # maxsize contains the maximum number of items allowed to be queued, # where 0 represents unlimited. # We need to check that we aren't asking for a bigger q...
289,271
Closes the queue. This needs to be called from any process or thread putting items onto the queue. Args: abort (Optional[bool]): True if the close was issued on abort.
def Close(self, abort=False): if abort: # Prevent join_thread() from blocking. self._queue.cancel_join_thread() self._queue.close() self._queue.join_thread()
289,272
Pushes an item onto the queue. Args: item (object): item to add. block (Optional[bool]): True to block the process when the queue is full. Raises: QueueFull: if the item could not be pushed the queue because it's full.
def PushItem(self, item, block=True): try: self._queue.put(item, block=block) except Queue.Full as exception: raise errors.QueueFull(exception)
289,273
Initializes a storage writer object. Args: session (Session): session the storage changes are part of. storage_type (Optional[str]): storage type. task(Optional[Task]): task.
def __init__( self, session, storage_type=definitions.STORAGE_TYPE_SESSION, task=None): super(FakeStorageWriter, self).__init__( session, storage_type=storage_type, task=task) self._event_data = {} self._event_sources = [] self._event_tags = [] self._events = [] self._warnings...
289,275
Prepares an attribute container for storage. Args: attribute_container (AttributeContainer): attribute container. Returns: AttributeContainer: copy of the attribute container to store in the fake storage.
def _PrepareAttributeContainer(self, attribute_container): attribute_values_hash = hash(attribute_container.GetAttributeValuesString()) identifier = identifiers.FakeIdentifier(attribute_values_hash) attribute_container.SetIdentifier(identifier) # Make sure the fake storage preserves the state of t...
289,276
Reads the data into the event. This function is intended to offer backwards compatible event behavior. Args: event (EventObject): event.
def _ReadEventDataIntoEvent(self, event): if self._storage_type != definitions.STORAGE_TYPE_SESSION: return event_data_identifier = event.GetEventDataIdentifier() if event_data_identifier: lookup_key = event_data_identifier.CopyToString() event_data = self._event_data[lookup_key] ...
289,277
Adds an analysis report. Args: analysis_report (AnalysisReport): analysis report. Raises: IOError: when the storage writer is closed. OSError: when the storage writer is closed.
def AddAnalysisReport(self, analysis_report): self._RaiseIfNotWritable() analysis_report = self._PrepareAttributeContainer(analysis_report) self.analysis_reports.append(analysis_report)
289,278
Adds an event. Args: event (EventObject): event. Raises: IOError: when the storage writer is closed or if the event data identifier type is not supported. OSError: when the storage writer is closed or if the event data identifier type is not supported.
def AddEvent(self, event): self._RaiseIfNotWritable() # TODO: change to no longer allow event_data_identifier is None # after refactoring every parser to generate event data. event_data_identifier = event.GetEventDataIdentifier() if event_data_identifier: if not isinstance(event_data_ide...
289,279
Adds event data. Args: event_data (EventData): event data. Raises: IOError: when the storage writer is closed. OSError: when the storage writer is closed.
def AddEventData(self, event_data): self._RaiseIfNotWritable() event_data = self._PrepareAttributeContainer(event_data) identifier = event_data.GetIdentifier() lookup_key = identifier.CopyToString() self._event_data[lookup_key] = event_data
289,280
Adds an event source. Args: event_source (EventSource): event source. Raises: IOError: when the storage writer is closed. OSError: when the storage writer is closed.
def AddEventSource(self, event_source): self._RaiseIfNotWritable() event_source = self._PrepareAttributeContainer(event_source) self._event_sources.append(event_source) self.number_of_event_sources += 1
289,281
Adds an event tag. Args: event_tag (EventTag): event tag. Raises: IOError: when the storage writer is closed. OSError: when the storage writer is closed.
def AddEventTag(self, event_tag): self._RaiseIfNotWritable() event_identifier = event_tag.GetEventIdentifier() if not isinstance(event_identifier, identifiers.FakeIdentifier): raise IOError('Unsupported event identifier type: {0:s}'.format( type(event_identifier))) event_tag = sel...
289,282
Adds a warnings. Args: warning (ExtractionWarning): warning. Raises: IOError: when the storage writer is closed. OSError: when the storage writer is closed.
def AddWarning(self, warning): self._RaiseIfNotWritable() warning = self._PrepareAttributeContainer(warning) self._warnings.append(warning) self.number_of_warnings += 1
289,283
Creates a task storage. Args: task (Task): task. Returns: FakeStorageWriter: storage writer. Raises: IOError: if the task storage already exists. OSError: if the task storage already exists.
def CreateTaskStorage(self, task): if task.identifier in self._task_storage_writers: raise IOError('Storage writer for task: {0:s} already exists.'.format( task.identifier)) storage_writer = FakeStorageWriter( self._session, storage_type=definitions.STORAGE_TYPE_TASK, task=task) ...
289,284
Retrieves the events in increasing chronological order. Args: time_range (Optional[TimeRange]): time range used to filter events that fall in a specific period. Returns: generator(EventObject): event generator. Raises: IOError: when the storage writer is closed. OSError:...
def GetSortedEvents(self, time_range=None): if not self._is_open: raise IOError('Unable to read from closed storage writer.') event_heap = event_heaps.EventHeap() for event in self._events: if (time_range and ( event.timestamp < time_range.start_timestamp or event.time...
289,287
Finalizes a processed task storage. Args: task (Task): task. Raises: IOError: if the task storage does not exist. OSError: if the task storage does not exist.
def FinalizeTaskStorage(self, task): if task.identifier not in self._task_storage_writers: raise IOError('Storage writer for task: {0:s} does not exist.'.format( task.identifier))
289,288
Prepares a task storage for merging. Args: task (Task): task. Raises: IOError: if the task storage does not exist. OSError: if the task storage does not exist.
def PrepareMergeTaskStorage(self, task): if task.identifier not in self._task_storage_writers: raise IOError('Storage writer for task: {0:s} does not exist.'.format( task.identifier))
289,290
Removes a processed task storage. Args: task (Task): task. Raises: IOError: if the task storage does not exist. OSError: if the task storage does not exist.
def RemoveProcessedTaskStorage(self, task): if task.identifier not in self._task_storage_writers: raise IOError('Storage writer for task: {0:s} does not exist.'.format( task.identifier)) del self._task_storage_writers[task.identifier]
289,292
Writes preprocessing information. Args: knowledge_base (KnowledgeBase): used to store the preprocessing information. Raises: IOError: if the storage type does not support writing preprocessing information or when the storage writer is closed. OSError: if the storage type ...
def WritePreprocessingInformation(self, knowledge_base): self._RaiseIfNotWritable() if self._storage_type != definitions.STORAGE_TYPE_SESSION: raise IOError('Preprocessing information not supported by storage type.')
289,293
Retrieves a value from a parsed log line, removing empty results. Args: structure (pyparsing.ParseResults): parsed log line. key (str): results key to retrieve from the parsed log line. Returns: type or None: the value of the named key in the parsed log line, or None if the value is ...
def _GetStructureValue(self, structure, key): value = structure.get(key) return value if not isinstance(value, pyparsing.ParseResults) else None
289,296
Parse a comment and store appropriate attributes. Args: structure (pyparsing.ParseResults): parsed log line.
def _ParseCommentRecord(self, structure): comment = structure[1] if comment.startswith('Version'): _, _, self._version = comment.partition(':') elif comment.startswith('Software'): _, _, self._software = comment.partition(':') elif comment.startswith('Time'): _, _, time_format = c...
289,297
Parse a single log line and and produce an event object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. structure (pyparsing.ParseResults): structure of tokens derived from a line of a text file.
def _ParseLogLine(self, parser_mediator, structure): try: date_time = dfdatetime_time_elements.TimeElements( time_elements_tuple=structure.date_time) date_time.is_local_time = True except ValueError: parser_mediator.ProduceExtractionWarning( 'invalid date time value: {...
289,298
Creates a service object from an event. Args: service_event (EventObject): event to create a new service object from. Returns: WindowsService: service.
def FromEvent(cls, service_event): _, _, name = service_event.key_path.rpartition( WindowsService._REGISTRY_KEY_PATH_SEPARATOR) service_type = service_event.regvalue.get('Type', '') image_path = service_event.regvalue.get('ImagePath', '') start_type = service_event.regvalue.get('Start', '')...
289,301