docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Initializes a storage merge reader. Args: storage_writer (StorageWriter): storage writer. path (str): path to the input file. Raises: IOError: if the input file cannot be opened. RuntimeError: if an add container method is missing.
def __init__(self, storage_writer, path): super(SQLiteStorageMergeReader, self).__init__(storage_writer) self._active_container_type = None self._active_cursor = None self._add_active_container_method = None self._add_container_type_methods = {} self._compression_format = definitions.COMPRE...
288,986
Adds an event. Args: event (EventObject): event.
def _AddEvent(self, event): if hasattr(event, 'event_data_row_identifier'): event_data_identifier = identifiers.SQLTableIdentifier( self._CONTAINER_TYPE_EVENT_DATA, event.event_data_row_identifier) lookup_key = event_data_identifier.CopyToString() event_data_identifier = ...
288,987
Adds event data. Args: event_data (EventData): event data.
def _AddEventData(self, event_data): identifier = event_data.GetIdentifier() lookup_key = identifier.CopyToString() self._storage_writer.AddEventData(event_data) identifier = event_data.GetIdentifier() self._event_data_identifier_mappings[lookup_key] = identifier
288,988
Parse the well known actions for easy reading. Args: action (str): the function or action called by the agent. text (str): mac Wifi log text. Returns: str: a formatted string representing the known (or common) action. If the action is not known the original log text is returned.
def _GetAction(self, action, text): # TODO: replace "x in y" checks by startswith if possible. if 'airportdProcessDLILEvent' in action: interface = text.split()[0] return 'Interface {0:s} turn up.'.format(interface) if 'doAutoJoin' in action: match = self._CONNECTED_RE.match(text) ...
288,996
Parse a single log line and produce an 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 fr...
def _ParseLogLine(self, parser_mediator, key, structure): time_elements_tuple = self._GetTimeElementsTuple(key, structure) try: date_time = dfdatetime_time_elements.TimeElementsInMilliseconds( time_elements_tuple=time_elements_tuple) except ValueError: parser_mediator.ProduceExtr...
288,998
Parses a log record structure and produces events. 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 from...
def ParseRecord(self, parser_mediator, key, structure): if key not in self._SUPPORTED_KEYS: raise errors.ParseError( 'Unable to parse record, unknown structure: {0:s}'.format(key)) self._ParseLogLine(parser_mediator, key, structure)
288,999
Verify that this file is a Mac Wifi log file. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. 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): self._last_month = 0 self._year_use = parser_mediator.GetEstimatedYear() key = 'header' try: structure = self._MAC_WIFI_HEADER.parseString(line) except pyparsing.ParseException: structure = None if not structure: key = '...
289,000
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() trigger_type = event_values.get('trigger_type', None) if trigger_type is ...
289,001
Extracts data from a Distributed Tracking identifier. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. uuid_object (uuid.UUID): UUID of the Distributed Tracking identifier. origin (str): origin of the event (e...
def _ParseDistributedTrackingIdentifier( self, parser_mediator, uuid_object, origin): if uuid_object.version == 1: event_data = windows_events.WindowsDistributedLinkTrackingEventData( uuid_object, origin) date_time = dfdatetime_uuid_time.UUIDTime(timestamp=uuid_object.time) ev...
289,003
Parses the DestList OLECF item. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. olecf_item (pyolecf.item): OLECF item. Raises: UnableToParseFile: if the DestList cannot be parsed.
def ParseDestList(self, parser_mediator, olecf_item): header_map = self._GetDataTypeMap('dest_list_header') try: header, entry_offset = self._ReadStructureFromFileObject( olecf_item, 0, header_map) except (ValueError, errors.ParseError) as exception: raise errors.UnableToParseFil...
289,004
Parses an OLECF file. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. root_item (Optional[pyolecf.item]): root item of the OLECF file. Raises: ValueError: If the root_item is not set.
def Process(self, parser_mediator, root_item=None, **kwargs): # This will raise if unhandled keyword arguments are passed. super(AutomaticDestinationsOLECFPlugin, self).Process( parser_mediator, **kwargs) if not root_item: raise ValueError('Root item not set.') for item in root_item...
289,005
Retrieves the inode from the inode value. Args: inode_value (int|str): inode, such as 1 or '27-128-1'. Returns: int: inode or -1 if the inode value cannot be converted to an integer.
def _GetInode(self, inode_value): if isinstance(inode_value, py2to3.INTEGER_TYPES): return inode_value if isinstance(inode_value, float): return int(inode_value) if not isinstance(inode_value, py2to3.STRING_TYPES): return -1 if b'-' in inode_value: inode_value, _, _ = ino...
289,008
Adds an attribute that will be set on all events produced. Setting attributes using this method will cause events produced via this mediator to have an attribute with the provided name set with the provided value. Args: attribute_name (str): name of the attribute to add. attribute_value (s...
def AddEventAttribute(self, attribute_name, attribute_value): if attribute_name in self._extra_event_attributes: raise KeyError('Event attribute {0:s} already set'.format( attribute_name)) self._extra_event_attributes[attribute_name] = attribute_value
289,010
Retrieves the display name for a file entry. Args: file_entry (Optional[dfvfs.FileEntry]): file entry object, where None will return the display name of self._file_entry. Returns: str: human readable string that describes the path to the file entry. Raises: ValueError: if the ...
def GetDisplayName(self, file_entry=None): if file_entry is None: file_entry = self._file_entry if file_entry is None: raise ValueError('Missing file entry') path_spec = getattr(file_entry, 'path_spec', None) relative_path = path_helper.PathHelper.GetRelativePathForPathSpec( ...
289,011
Produces an event source. Args: event_source (EventSource): an event source. Raises: RuntimeError: when storage writer is not set.
def ProduceEventSource(self, event_source): if not self._storage_writer: raise RuntimeError('Storage writer not set.') self._storage_writer.AddEventSource(event_source) self._number_of_event_sources += 1 self.last_activity_timestamp = time.time()
289,016
Produces an event. Args: event (EventObject): event. event_data (EventData): event data. Raises: InvalidEvent: if the event timestamp value is not set or out of bounds.
def ProduceEventWithEventData(self, event, event_data): if event.timestamp is None: raise errors.InvalidEvent('Event timestamp value not set.') if event.timestamp < self._INT64_MIN or event.timestamp > self._INT64_MAX: raise errors.InvalidEvent('Event timestamp value out of bounds.') even...
289,017
Produces an extraction warning. Args: message (str): message of the warning. path_spec (Optional[dfvfs.PathSpec]): path specification, where None will use the path specification of current file entry set in the mediator. Raises: RuntimeError: when storage writer is not se...
def ProduceExtractionWarning(self, message, path_spec=None): if not self._storage_writer: raise RuntimeError('Storage writer not set.') if not path_spec and self._file_entry: path_spec = self._file_entry.path_spec parser_chain = self.GetParserChain() warning = warnings.ExtractionWarni...
289,018
Removes an attribute from being set on all events produced. Args: attribute_name (str): name of the attribute to remove. Raises: KeyError: if the event attribute is not set.
def RemoveEventAttribute(self, attribute_name): if attribute_name not in self._extra_event_attributes: raise KeyError('Event attribute: {0:s} not set'.format(attribute_name)) del self._extra_event_attributes[attribute_name]
289,019
Takes a sample of the memory usage for profiling. Args: parser_name (str): name of the parser.
def SampleMemoryUsage(self, parser_name): if self._memory_profiler: used_memory = self._process_information.GetUsedMemory() or 0 self._memory_profiler.Sample(parser_name, used_memory)
289,020
Sets the input source configuration settings. Args: configuration (InputSourceConfiguration): input source configuration.
def SetInputSourceConfiguration(self, configuration): mount_path = configuration.mount_path # Remove a trailing path separator from the mount path so the relative # paths will start with a path separator. if mount_path and mount_path.endswith(os.sep): mount_path = mount_path[:-1] self._...
289,021
Sets the storage writer. Args: storage_writer (StorageWriter): storage writer.
def SetStorageWriter(self, storage_writer): self._storage_writer = storage_writer # Reset the last event data information. Each storage file should # contain event data for their events. self._last_event_data_hash = None self._last_event_data_identifier = None
289,022
Starts profiling. Args: configuration (ProfilingConfiguration): profiling configuration. identifier (str): identifier of the profiling session used to create the sample filename. process_information (ProcessInfo): process information.
def StartProfiling(self, configuration, identifier, process_information): if not configuration: return if configuration.HaveProfileParsers(): identifier = '{0:s}-parsers'.format(identifier) self._cpu_time_profiler = profilers.CPUTimeProfiler( identifier, configuration) s...
289,023
Compiles the filter expression. The filter expression contains an object filter expression. Args: filter_expression (str): filter expression. Raises: ParseError: if the filter expression cannot be parsed.
def CompileFilter(self, filter_expression): filter_parser = pfilter.BaseParser(filter_expression).Parse() matcher = filter_parser.Compile(pfilter.PlasoAttributeFilterImplementation) self._filter_expression = filter_expression self._matcher = matcher
289,025
Determines if an event matches the filter. Args: event (EventObject): an event. Returns: bool: True if the event matches the filter.
def Match(self, event): if not self._matcher: return True self._decision = self._matcher.Matches(event) return self._decision
289,026
Parses a structure of tokens derived from a line of a text file. 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 token...
def ParseRecord(self, parser_mediator, key, structure): if key != 'line': raise errors.ParseError( 'Unable to parse record, unknown structure: {0:s}'.format(key)) msg_value = structure.get('msg') if not msg_value: parser_mediator.ProduceExtractionWarning( 'missing msg v...
289,028
Initializes a status view. Args: output_writer (OutputWriter): output writer. tool_name (str): namd of the tool.
def __init__(self, output_writer, tool_name): super(StatusView, self).__init__() self._artifact_filters = None self._filter_file = None self._have_ansi_support = not win32console self._mode = self.MODE_WINDOW self._output_writer = output_writer self._source_path = None self._source_...
289,029
Adds an analysis process status table row. Args: process_status (ProcessStatus): processing status. table_view (CLITabularTableView): table view.
def _AddsAnalysisProcessStatusTableRow(self, process_status, table_view): used_memory = self._FormatSizeInUnitsOf1024(process_status.used_memory) events = '' if (process_status.number_of_consumed_events is not None and process_status.number_of_consumed_events_delta is not None): events =...
289,030
Adds an extraction process status table row. Args: process_status (ProcessStatus): processing status. table_view (CLITabularTableView): table view.
def _AddExtractionProcessStatusTableRow(self, process_status, table_view): used_memory = self._FormatSizeInUnitsOf1024(process_status.used_memory) sources = '' if (process_status.number_of_produced_sources is not None and process_status.number_of_produced_sources_delta is not None): sour...
289,031
Represents a number of bytes in units of 1024. Args: size (int): size in bytes. Returns: str: human readable string of the size.
def _FormatSizeInUnitsOf1024(self, size): magnitude_1024 = 0 used_memory_1024 = float(size) while used_memory_1024 >= 1024: used_memory_1024 /= 1024 magnitude_1024 += 1 if 0 < magnitude_1024 <= 7: return '{0:.1f} {1:s}'.format( used_memory_1024, self._UNITS_1024[magnitu...
289,033
Prints the analysis status header. Args: processing_status (ProcessingStatus): processing status.
def _PrintAnalysisStatusHeader(self, processing_status): self._output_writer.Write( 'Storage file\t\t: {0:s}\n'.format(self._storage_file_path)) self._PrintProcessingTime(processing_status) if processing_status and processing_status.events_status: self._PrintEventsStatus(processing_stat...
289,034
Prints an analysis status update in linear mode. Args: processing_status (ProcessingStatus): processing status.
def _PrintAnalysisStatusUpdateLinear(self, processing_status): for worker_status in processing_status.workers_status: status_line = ( '{0:s} (PID: {1:d}) - events consumed: {2:d} - running: ' '{3!s}\n').format( worker_status.identifier, worker_status.pid, w...
289,035
Prints an analysis status update in window mode. Args: processing_status (ProcessingStatus): processing status.
def _PrintAnalysisStatusUpdateWindow(self, processing_status): if self._stdout_output_writer: self._ClearScreen() output_text = 'plaso - {0:s} version {1:s}\n\n'.format( self._tool_name, plaso.__version__) self._output_writer.Write(output_text) self._PrintAnalysisStatusHeader(proces...
289,036
Prints an extraction status update in linear mode. Args: processing_status (ProcessingStatus): processing status.
def _PrintExtractionStatusUpdateLinear(self, processing_status): for worker_status in processing_status.workers_status: status_line = ( '{0:s} (PID: {1:d}) - events produced: {2:d} - file: {3:s} ' '- running: {4!s}\n').format( worker_status.identifier, worker_status.pid,...
289,037
Prints an extraction status update in window mode. Args: processing_status (ProcessingStatus): processing status.
def _PrintExtractionStatusUpdateWindow(self, processing_status): if self._stdout_output_writer: self._ClearScreen() output_text = 'plaso - {0:s} version {1:s}\n\n'.format( self._tool_name, plaso.__version__) self._output_writer.Write(output_text) self.PrintExtractionStatusHeader(pro...
289,038
Prints the status of the events. Args: events_status (EventsStatus): events status.
def _PrintEventsStatus(self, events_status): if events_status: table_view = views.CLITabularTableView( column_names=['Events:', 'Filtered', 'In time slice', 'Duplicates', 'MACB grouped', 'Total'], column_sizes=[15, 15, 15, 15, 15, 0]) table_view.AddRow([...
289,039
Prints the processing time. Args: processing_status (ProcessingStatus): processing status.
def _PrintProcessingTime(self, processing_status): if not processing_status: processing_time = '00:00:00' else: processing_time = time.time() - processing_status.start_time time_struct = time.gmtime(processing_time) processing_time = time.strftime('%H:%M:%S', time_struct) self....
289,040
Prints the status of the tasks. Args: processing_status (ProcessingStatus): processing status.
def _PrintTasksStatus(self, processing_status): if processing_status and processing_status.tasks_status: tasks_status = processing_status.tasks_status table_view = views.CLITabularTableView( column_names=['Tasks:', 'Queued', 'Processing', 'Merging', 'Abandoned', '...
289,041
Prints the extraction status header. Args: processing_status (ProcessingStatus): processing status.
def PrintExtractionStatusHeader(self, processing_status): self._output_writer.Write( 'Source path\t\t: {0:s}\n'.format(self._source_path)) self._output_writer.Write( 'Source type\t\t: {0:s}\n'.format(self._source_type)) if self._artifact_filters: artifacts_string = ', '.join(self...
289,044
Prints a summary of the extraction. Args: processing_status (ProcessingStatus): processing status.
def PrintExtractionSummary(self, processing_status): if not processing_status: self._output_writer.Write( 'WARNING: missing processing status information.\n') elif not processing_status.aborted: if processing_status.error_path_specs: self._output_writer.Write('Processing comp...
289,045
Sets the source information. Args: source_path (str): path of the source. source_type (str): source type. artifact_filters (Optional[list[str]]): names of artifact definitions to use as filters. filter_file (Optional[str]): filter file.
def SetSourceInformation( self, source_path, source_type, artifact_filters=None, filter_file=None): self._artifact_filters = artifact_filters self._filter_file = filter_file self._source_path = source_path self._source_type = self._SOURCE_TYPES.get(source_type, 'UNKNOWN')
289,046
Parses a cookie row. Args: parser_mediator (ParserMediator): parser mediator. query (str): query that created the row. row (sqlite3.Row): row resulting from the query.
def ParseCookieRow(self, parser_mediator, query, row, **unused_kwargs): query_hash = hash(query) cookie_name = self._GetRowValue(query_hash, row, 'name') cookie_data = self._GetRowValue(query_hash, row, 'value') hostname = self._GetRowValue(query_hash, row, 'host_key') if hostname.startswith(...
289,049
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): default_fields = ','.join(cls._DEFAULT_FIELDS) argument_group.add_argument( '--fields', dest='fields', type=str, action='store', default=default_fields, help=( 'Defines which fields should be included in the output.')) default_fields =...
289,050
Parses and validates options. Args: options (argparse.Namespace): parser options. output_module (OutputModule): output module to configure. Raises: BadConfigObject: when the output module object is of the wrong type. BadConfigOption: when the output filename was not provided.
def ParseOptions(cls, options, output_module): # pylint: disable=arguments-differ if not isinstance(output_module, dynamic.DynamicOutputModule): raise errors.BadConfigObject( 'Output module is not an instance of DynamicOutputModule') default_fields = ','.join(cls._DEFAULT_FIELDS) fiel...
289,051
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(): drive_letter = subkey.name if not drive_letter: continue values_dict = { 'DriveLetter': drive_letter, 'Type': 'Mapped Drive'} # Get the remote path if...
289,052
Builds the event tag index. Args: storage_file (BaseStorageFile): storage file.
def _Build(self, storage_file): self._index = {} for event_tag in storage_file.GetEventTags(): self.SetEventTag(event_tag)
289,054
Retrieves the most recently updated event tag for an event. Args: storage_file (BaseStorageFile): storage file. event_identifier (AttributeContainerIdentifier): event attribute container identifier. Returns: EventTag: event tag or None if the event has no event tag.
def GetEventTagByIdentifier(self, storage_file, event_identifier): if not self._index: self._Build(storage_file) lookup_key = event_identifier.CopyToString() event_tag_identifier = self._index.get(lookup_key, None) if not event_tag_identifier: return None return storage_file.GetEv...
289,055
Sets an event tag in the index. Args: event_tag (EventTag): event tag.
def SetEventTag(self, event_tag): event_identifier = event_tag.GetEventIdentifier() lookup_key = event_identifier.CopyToString() self._index[lookup_key] = event_tag.GetIdentifier()
289,056
Expands a path to contain all users home or profile directories. Expands the artifacts path variable "%%users.homedir%%" or "%%users.userprofile%%". Args: path_segments (list[str]): path segments. path_separator (str): path segment separator. user_accounts (list[UserAccountArtifact]): us...
def _ExpandUsersHomeDirectoryPathSegments( cls, path_segments, path_separator, user_accounts): if not path_segments: return [] user_paths = [] first_path_segment = path_segments[0].lower() if first_path_segment not in ('%%users.homedir%%', '%%users.userprofile%%'): if cls._IsWin...
289,057
Expands path segments with a users variable, e.g. %%users.homedir%%. Args: path_segments (list[str]): path segments. path_separator (str): path segment separator. user_accounts (list[UserAccountArtifact]): user accounts. Returns: list[str]: paths for which the users variables have been...
def _ExpandUsersVariablePathSegments( cls, path_segments, path_separator, user_accounts): if not path_segments: return [] path_segments_lower = [ path_segment.lower() for path_segment in path_segments] if path_segments_lower[0] in ('%%users.homedir%%', '%%users.userprofile%%'): ...
289,058
Determines if the path segment contains a Windows Drive indicator. A drive indicator can be a drive letter or %SystemDrive%. Args: path_segment (str): path segment. Returns: bool: True if the path segment contains a Windows Drive indicator.
def _IsWindowsDrivePathSegment(cls, path_segment): if (len(path_segment) == 2 and path_segment[1] == ':' and path_segment[0].isalpha()): return True path_segment = path_segment.upper() return path_segment in ('%%ENVIRON_SYSTEMDRIVE%%', '%SYSTEMDRIVE%')
289,059
Expands a path with a users variable, e.g. %%users.homedir%%. Args: path (str): path with users variable. path_separator (str): path segment separator. user_accounts (list[UserAccountArtifact]): user accounts. Returns: list[str]: paths for which the users variables have been expanded.
def ExpandUsersVariablePath(cls, path, path_separator, user_accounts): path_segments = path.split(path_separator) return cls._ExpandUsersVariablePathSegments( path_segments, path_separator, user_accounts)
289,062
Expands a Windows path containing environment variables. Args: path (str): Windows path with environment variables. environment_variables (list[EnvironmentVariableArtifact]): environment variables. Returns: str: expanded Windows path.
def ExpandWindowsPath(cls, path, environment_variables): if environment_variables is None: environment_variables = [] lookup_table = {} if environment_variables: for environment_variable in environment_variables: attribute_name = environment_variable.name.upper() attribute_...
289,063
Attempts to convert the argument to a Unicode string. Args: value (list|int|bytes|str): value to convert. Returns: str: string representation of the argument.
def GetUnicodeString(value): if isinstance(value, list): value = [GetUnicodeString(item) for item in value] return ''.join(value) if isinstance(value, py2to3.INTEGER_TYPES): value = '{0:d}'.format(value) if not isinstance(value, py2to3.UNICODE_TYPE): return codecs.decode(value, 'utf8', 'ignor...
289,066
Constructor. Args: arguments: Arguments to the filter. value_expander: A callable that will be used to expand values for the objects passed to this filter. Implementations expanders are provided by subclassing ValueExpander. Raises: ValueError: If the given value_expander is not ...
def __init__(self, arguments=None, value_expander=None): self.value_expander = None self.value_expander_cls = value_expander if self.value_expander_cls: if not issubclass(self.value_expander_cls, ValueExpander): raise ValueError('{0:s} is not a valid value expander'.format( se...
289,067
Escape backslashes found inside a string quote. Backslashes followed by anything other than [\'"rnbt.ws] will raise an Error. Args: string: The string that matched. match: the match object (instance of re.MatchObject). Where match.group(1) contains the escaped code. Raises: ...
def StringEscape(self, string, match, **unused_kwargs): if match.group(1) in '\\\'"rnbt\\.ws': self.string += codecs.decode(string, 'unicode_escape') else: raise errors.ParseError('Invalid escape character {0:s}.'.format(string))
289,092
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() page_transition_type = event_values.get('page_transition_type', None) if ...
289,097
Extract data from a MSIE Cache Files (MSIECF) leak item. Every item is stored as an event object, one for each timestamp. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. cache_directories (list[str]): cache di...
def _ParseLeak( self, parser_mediator, cache_directories, msiecf_item, recovered=False): # TODO: add support for possible last cache synchronization date and time. date_time = dfdatetime_semantic_time.SemanticTime('Not set') event_data = MSIECFLeakEventData() event_data.cached_filename = msi...
289,101
Parses a MSIE Cache File (MSIECF) items. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. msiecf_file (pymsiecf.file): MSIECF file.
def _ParseItems(self, parser_mediator, msiecf_file): format_version = msiecf_file.format_version decode_error = False cache_directories = [] for cache_directory_name in iter(msiecf_file.cache_directories): try: cache_directory_name = cache_directory_name.decode('ascii') except ...
289,102
Extract data from a MSIE Cache Files (MSIECF) redirected item. Every item is stored as an event object, one for each timestamp. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. msiecf_item (pymsiecf.redirected)...
def _ParseRedirected( self, parser_mediator, msiecf_item, recovered=False): date_time = dfdatetime_semantic_time.SemanticTime('Not set') event_data = MSIECFRedirectedEventData() event_data.offset = msiecf_item.offset event_data.recovered = recovered event_data.url = msiecf_item.location ...
289,103
Parses a MSIE Cache File (MSIECF) 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): msiecf_file = pymsiecf.file() msiecf_file.set_ascii_codepage(parser_mediator.codepage) try: msiecf_file.open_file_object(file_object) except IOError as exception: parser_mediator.ProduceExtractionWarning( 'unable to ope...
289,105
Extracts relevant Spotlight entries. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. match (Optional[dict[str: object]]): keys extracted from PLIST_KEYS.
def GetEntries(self, parser_mediator, match=None, **unused_kwargs): shortcuts = match.get('UserShortcuts', {}) for search_text, data in iter(shortcuts.items()): datetime_value = data.get('LAST_USED', None) if not datetime_value: continue display_name = data.get('DISPLAY_NAME', '<...
289,106
Retrieves a value from the row. Args: query_hash (int): hash of the query, that uniquely identifies the query that produced the row. row (sqlite3.Row): row. value_name (str): name of the value. Returns: object: value.
def _GetRowValue(self, query_hash, row, value_name): keys_name_to_index_map = self._keys_per_query.get(query_hash, None) if not keys_name_to_index_map: keys_name_to_index_map = { name: index for index, name in enumerate(row.keys())} self._keys_per_query[query_hash] = keys_name_to_inde...
289,107
Hashes the given row. Args: row (sqlite3.Row): row. Returns: int: hash value of the given row.
def _HashRow(cls, row): values = [] for value in row: try: value = '{0!s}'.format(value) except UnicodeDecodeError: # In Python 2, blobs are "read-write buffer" and will cause a # UnicodeDecodeError exception if we try format it as a string. # Since Python 3 does...
289,108
Queries a database and parses the results. Args: parser_mediator (ParserMediator): parser mediator. database (SQLiteDatabase): database. query (str): query. callback (function): function to invoke to parse an individual row. cache (SQLiteCache): cache.
def _ParseQuery(self, parser_mediator, database, query, callback, cache): row_cache = cache.GetRowCache(query) try: rows = database.Query(query) except sqlite3.DatabaseError as exception: parser_mediator.ProduceExtractionWarning( 'unable to run query: {0:s} on database with erro...
289,109
Checks the schema of a database with that defined in the plugin. Args: database (SQLiteDatabase): database. Returns: bool: True if the schema of the database matches that defined by the plugin, or False if the schemas do not match or no schema is defined by the plugin.
def CheckSchema(self, database): schema_match = False if self.SCHEMAS: for schema in self.SCHEMAS: if database and database.schema == schema: schema_match = True return schema_match
289,110
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 ParseCookieRow(self, parser_mediator, query, row, **unused_kwargs): query_hash = hash(query) cookie_name = self._GetRowValue(query_hash, row, 'name') cookie_value = self._GetRowValue(query_hash, row, 'value') path = self._GetRowValue(query_hash, row, 'path') hostname = self._GetRowValue(q...
289,114
Parses a Windows Restore Point (rp.log) log 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...
def ParseFileObject(self, parser_mediator, file_object): file_size = file_object.get_size() file_header_map = self._GetDataTypeMap('rp_log_file_header') try: file_header, _ = self._ReadStructureFromFileObject( file_object, 0, file_header_map) except (ValueError, errors.ParseError)...
289,116
Initializes a store. Args: maximum_buffer_size (Optional[int]): maximum size of a single storage stream. A value of 0 indicates the limit is _MAXIMUM_BUFFER_SIZE. storage_type (Optional[str]): storage type. Raises: ValueError: if the maximum buffer size value is out of bo...
def __init__( self, maximum_buffer_size=0, storage_type=definitions.STORAGE_TYPE_SESSION): if (maximum_buffer_size < 0 or maximum_buffer_size > self._MAXIMUM_BUFFER_SIZE): raise ValueError('Maximum buffer size value out of bounds.') if not maximum_buffer_size: maximum_buffe...
289,117
Adds an attribute container. Args: container_type (str): attribute container type. attribute_container (AttributeContainer): attribute container. Raises: IOError: if the attribute container cannot be serialized. OSError: if the attribute container cannot be serialized.
def _AddAttributeContainer(self, container_type, attribute_container): container_list = self._GetSerializedAttributeContainerList(container_type) identifier = identifiers.SQLTableIdentifier( container_type, container_list.next_sequence_number + 1) attribute_container.SetIdentifier(identifier) ...
289,118
Adds an serialized event. Args: event (EventObject): event. Raises: IOError: if the event cannot be serialized. OSError: if the event cannot be serialized.
def _AddSerializedEvent(self, event): identifier = identifiers.SQLTableIdentifier( self._CONTAINER_TYPE_EVENT, self._serialized_event_heap.number_of_events + 1) event.SetIdentifier(identifier) serialized_data = self._SerializeAttributeContainer(event) self._serialized_event_heap.P...
289,119
Checks the storage metadata. Args: metadata_values (dict[str, str]): metadata values per key. check_readable_only (Optional[bool]): whether the store should only be checked to see if it can be read. If False, the store will be checked to see if it can be read and written to. Ra...
def _CheckStorageMetadata(cls, metadata_values, check_readable_only=False): format_version = metadata_values.get('format_version', None) if not format_version: raise IOError('Missing format version.') try: format_version = int(format_version, 10) except (TypeError, ValueError): ...
289,120
Counts the number of attribute containers of the given type. Args: container_type (str): attribute container type. Returns: int: number of attribute containers of the given type. Raises: ValueError: if an unsupported container_type is provided.
def _CountStoredAttributeContainers(self, container_type): if not container_type in self._CONTAINER_TYPES: raise ValueError('Attribute container type {0:s} is not supported'.format( container_type)) if not self._HasTable(container_type): return 0 # Note that this is SQLite speci...
289,121
Retrieves a specific attribute container. Args: container_type (str): attribute container type. index (int): attribute container index. Returns: AttributeContainer: attribute container or None if not available. Raises: IOError: when there is an error querying the storage file. ...
def _GetAttributeContainerByIndex(self, container_type, index): sequence_number = index + 1 query = 'SELECT _data FROM {0:s} WHERE rowid = {1:d}'.format( container_type, sequence_number) try: self._cursor.execute(query) except sqlite3.OperationalError as exception: raise IOErro...
289,122
Retrieves a specific type of stored attribute containers. Args: container_type (str): attribute container type. filter_expression (Optional[str]): expression to filter results by. order_by (Optional[str]): name of a column to order the results by. Yields: AttributeContainer: attribute ...
def _GetAttributeContainers( self, container_type, filter_expression=None, order_by=None): query = 'SELECT _identifier, _data FROM {0:s}'.format(container_type) if filter_expression: query = '{0:s} WHERE {1:s}'.format(query, filter_expression) if order_by: query = '{0:s} ORDER BY {1:s...
289,123
Determines if a specific table exists. Args: table_name (str): name of the table. Returns: bool: True if the table exists, false otherwise.
def _HasTable(self, table_name): query = self._HAS_TABLE_QUERY.format(table_name) self._cursor.execute(query) return bool(self._cursor.fetchone())
289,124
Reads storage metadata and checks that the values are valid. Args: check_readable_only (Optional[bool]): whether the store should only be checked to see if it can be read. If False, the store will be checked to see if it can be read and written to.
def _ReadAndCheckStorageMetadata(self, check_readable_only=False): query = 'SELECT key, value FROM metadata' self._cursor.execute(query) metadata_values = {row[0]: row[1] for row in self._cursor.fetchall()} self._CheckStorageMetadata( metadata_values, check_readable_only=check_readable_on...
289,125
Writes an attribute container. The table for the container type must exist. Args: attribute_container (AttributeContainer): attribute container.
def _WriteAttributeContainer(self, attribute_container): if attribute_container.CONTAINER_TYPE == self._CONTAINER_TYPE_EVENT: timestamp, serialized_data = self._serialized_event_heap.PopEvent() else: serialized_data = self._SerializeAttributeContainer(attribute_container) if self.compressi...
289,126
Writes a serialized attribute container list. Args: container_type (str): attribute container type.
def _WriteSerializedAttributeContainerList(self, container_type): if container_type == self._CONTAINER_TYPE_EVENT: if not self._serialized_event_heap.data_size: return number_of_attribute_containers = ( self._serialized_event_heap.number_of_events) else: container_list...
289,127
Adds an warning. Args: warning (ExtractionWarning): warning. Raises: IOError: when the storage file is closed or read-only. OSError: when the storage file is closed or read-only.
def AddWarning(self, warning): self._RaiseIfNotWritable() self._AddAttributeContainer( self._CONTAINER_TYPE_EXTRACTION_WARNING, warning)
289,129
Adds an event. Args: event (EventObject): event. Raises: IOError: when the storage file is closed or read-only or if the event data identifier type is not supported. OSError: when the storage file is closed or read-only or if the event data identifier type is not supporte...
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,130
Adds event data. Args: event_data (EventData): event data. Raises: IOError: when the storage file is closed or read-only. OSError: when the storage file is closed or read-only.
def AddEventData(self, event_data): self._RaiseIfNotWritable() self._AddAttributeContainer(self._CONTAINER_TYPE_EVENT_DATA, event_data)
289,131
Adds an event source. Args: event_source (EventSource): event source. Raises: IOError: when the storage file is closed or read-only. OSError: when the storage file is closed or read-only.
def AddEventSource(self, event_source): self._RaiseIfNotWritable() self._AddAttributeContainer( self._CONTAINER_TYPE_EVENT_SOURCE, event_source)
289,132
Adds an event tag. Args: event_tag (EventTag): event tag. Raises: IOError: when the storage file is closed or read-only or if the event identifier type is not supported. OSError: when the storage file is closed or read-only or if the event identifier type is not supported...
def AddEventTag(self, event_tag): self._RaiseIfNotWritable() event_identifier = event_tag.GetEventIdentifier() if not isinstance(event_identifier, identifiers.SQLTableIdentifier): raise IOError('Unsupported event identifier type: {0:s}'.format( type(event_identifier))) event_tag.e...
289,133
Adds event tags. Args: event_tags (list[EventTag]): event tags. Raises: IOError: when the storage file is closed or read-only or if the event tags cannot be serialized. OSError: when the storage file is closed or read-only or if the event tags cannot be serialized.
def AddEventTags(self, event_tags): self._RaiseIfNotWritable() for event_tag in event_tags: self.AddEventTag(event_tag)
289,134
Checks if the storage file format is supported. Args: path (str): path to the storage file. check_readable_only (Optional[bool]): whether the store should only be checked to see if it can be read. If False, the store will be checked to see if it can be read and written to. Retu...
def CheckSupportedFormat(cls, path, check_readable_only=False): try: connection = sqlite3.connect( path, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES) cursor = connection.cursor() query = 'SELECT * FROM metadata' cursor.execute(query) metadata_values = ...
289,135
Retrieves a specific event tag. Args: identifier (SQLTableIdentifier): event tag identifier. Returns: EventTag: event tag or None if not available.
def GetEventTagByIdentifier(self, identifier): event_tag = self._GetAttributeContainerByIndex( self._CONTAINER_TYPE_EVENT_TAG, identifier.row_identifier - 1) if event_tag: event_identifier = identifiers.SQLTableIdentifier( self._CONTAINER_TYPE_EVENT, event_tag.event_row_identifier) ...
289,140
Retrieves the events in increasing chronological order. Args: time_range (Optional[TimeRange]): time range used to filter events that fall in a specific period. Yield: EventObject: event.
def GetSortedEvents(self, time_range=None): filter_expression = None if time_range: filter_expression = [] if time_range.start_timestamp: filter_expression.append( '_timestamp >= {0:d}'.format(time_range.start_timestamp)) if time_range.end_timestamp: filter_e...
289,144
Opens the storage. Args: path (Optional[str]): path to the storage file. read_only (Optional[bool]): True if the file should be opened in read-only mode. Raises: IOError: if the storage file is already opened or if the database cannot be connected. OSError: if the s...
def Open(self, path=None, read_only=True, **unused_kwargs): if self._is_open: raise IOError('Storage file already opened.') if not path: raise ValueError('Missing path.') path = os.path.abspath(path) connection = sqlite3.connect( path, detect_types=sqlite3.PARSE_DECLTYPES|sql...
289,146
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): generator = self._GetAttributeContainers( self._CONTAINER_TYPE_SYSTEM_CONFIGURATION) for stream_number, system_configuration in enumerate(generator): # TODO: replace stream_number by session_identifier. knowledge_base.ReadSystemCon...
289,147
Writes preprocessing information. Args: knowledge_base (KnowledgeBase): contains the preprocessing information. Raises: IOError: if the storage type does not support writing preprocess information or the storage file is closed or read-only. OSError: if the storage type does not sup...
def WritePreprocessingInformation(self, knowledge_base): self._RaiseIfNotWritable() if self.storage_type != definitions.STORAGE_TYPE_SESSION: raise IOError('Preprocess information not supported by storage type.') system_configuration = knowledge_base.GetSystemConfigurationArtifact() self._...
289,148
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( '--viper-hash', '--viper_hash', dest='viper_hash', type=str, action='store', choices=viper.ViperAnalyzer.SUPPORTED_HASHES, default=cls._DEFAULT_HASH, metavar='HASH', help=( 'Type of hash to use to query the ...
289,149
Parses and validates options. Args: options (argparse.Namespace): parser options. analysis_plugin (ViperAnalysisPlugin): analysis plugin to configure. Raises: BadConfigObject: when the output module object is of the wrong type. BadConfigOption: when unable to connect to Viper instance.
def ParseOptions(cls, options, analysis_plugin): if not isinstance(analysis_plugin, viper.ViperAnalysisPlugin): raise errors.BadConfigObject( 'Analysis plugin is not an instance of ViperAnalysisPlugin') lookup_hash = cls._ParseStringOption( options, 'viper_hash', default_value=cls....
289,150
Parses a bookmark annotation 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 ParseBookmarkAnnotationRow( self, parser_mediator, query, row, **unused_kwargs): query_hash = hash(query) event_data = FirefoxPlacesBookmarkAnnotationEventData() event_data.content = self._GetRowValue(query_hash, row, 'content') event_data.offset = self._GetRowValue(query_hash, row, 'id'...
289,156
Parses a bookmark folder 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 ParseBookmarkFolderRow( self, parser_mediator, query, row, **unused_kwargs): query_hash = hash(query) title = self._GetRowValue(query_hash, row, 'title') event_data = FirefoxPlacesBookmarkFolderEventData() event_data.offset = self._GetRowValue(query_hash, row, 'id') event_data.query...
289,157
Parses a bookmark 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 ParseBookmarkRow( self, parser_mediator, query, row, **unused_kwargs): query_hash = hash(query) rev_host = self._GetRowValue(query_hash, row, 'rev_host') bookmark_type = self._GetRowValue(query_hash, row, 'type') event_data = FirefoxPlacesBookmarkEventData() event_data.host = rev_ho...
289,158
Parses a page 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. cache (Optional[SQLiteCache]): cache. database (Optional...
def ParsePageVisitedRow( self, parser_mediator, query, row, cache=None, database=None, **unused_kwargs): query_hash = hash(query) from_visit = self._GetRowValue(query_hash, row, 'from_visit') hidden = self._GetRowValue(query_hash, row, 'hidden') rev_host = self._GetRowValue(query_hash,...
289,159
Reverses the hostname and strips the leading dot. The hostname entry is reversed: moc.elgoog.www. Should be: www.google.com Args: hostname (str): reversed hostname. Returns: str: hostname without a leading dot.
def _ReverseHostname(self, hostname): if not hostname: return '' if len(hostname) <= 1: return hostname if hostname[-1] == '.': return hostname[::-1][1:] return hostname[::-1][0:]
289,160
Retrieves an URL from a reference to an entry in the from_visit table. Args: url_id (str): identifier of the visited URL. cache (SQLiteCache): cache. database (SQLiteDatabase): database. Returns: str: URL and hostname.
def _GetUrl(self, url_id, cache, database): url_cache_results = cache.GetResults('url') if not url_cache_results: result_set = database.Query(self.URL_CACHE_QUERY) cache.CacheQueryResults( result_set, 'url', 'id', ('url', 'rev_host')) url_cache_results = cache.GetResults('url')...
289,161
Parses a downloads 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 ParseDownloadsRow( self, parser_mediator, query, row, **unused_kwargs): query_hash = hash(query) event_data = FirefoxDownloadEventData() event_data.full_path = self._GetRowValue(query_hash, row, 'target') event_data.mime_type = self._GetRowValue(query_hash, row, 'mimeType') event_dat...
289,162
Initializes a process. Args: processing_configuration (ProcessingConfiguration): processing configuration. enable_sigsegv_handler (Optional[bool]): True if the SIGSEGV handler should be enabled. kwargs (dict[str,object]): keyword arguments to pass to multiprocessing....
def __init__( self, processing_configuration, enable_sigsegv_handler=False, **kwargs): super(MultiProcessBaseProcess, self).__init__(**kwargs) self._debug_output = False self._enable_sigsegv_handler = enable_sigsegv_handler self._guppy_memory_profiler = None self._log_filename = None ...
289,163