docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Parses the credential options. Args: options (argparse.Namespace): command line arguments. Raises: BadConfigOption: if the options are invalid.
def _ParseCredentialOptions(self, options): credentials = getattr(options, 'credentials', []) if not isinstance(credentials, list): raise errors.BadConfigOption('Unsupported credentials value.') for credential_string in credentials: credential_type, _, credential_data = credential_string.p...
288,270
Parses the source path option. Args: options (argparse.Namespace): command line arguments. Raises: BadConfigOption: if the options are invalid.
def _ParseSourcePathOption(self, options): self._source_path = self.ParseStringOption(options, self._SOURCE_OPTION) if not self._source_path: raise errors.BadConfigOption('Missing source path.') self._source_path = os.path.abspath(self._source_path)
288,271
Parses the storage media options. Args: options (argparse.Namespace): command line arguments. Raises: BadConfigOption: if the options are invalid.
def _ParseStorageMediaOptions(self, options): self._ParseStorageMediaImageOptions(options) self._ParseVSSProcessingOptions(options) self._ParseCredentialOptions(options) self._ParseSourcePathOption(options)
288,272
Parses the storage media image options. Args: options (argparse.Namespace): command line arguments. Raises: BadConfigOption: if the options are invalid.
def _ParseStorageMediaImageOptions(self, options): self._partitions = getattr(options, 'partitions', None) if self._partitions: try: self._ParseVolumeIdentifiersString(self._partitions, prefix='p') except ValueError: raise errors.BadConfigOption('Unsupported partitions') se...
288,273
Parses the VSS processing options. Args: options (argparse.Namespace): command line arguments. Raises: BadConfigOption: if the options are invalid.
def _ParseVSSProcessingOptions(self, options): vss_only = False vss_stores = None self._process_vss = not getattr(options, 'no_vss', False) if self._process_vss: vss_only = getattr(options, 'vss_only', False) vss_stores = getattr(options, 'vss_stores', None) if vss_stores: t...
288,275
Prints an overview of APFS volume identifiers. Args: volume_system (dfvfs.APFSVolumeSystem): volume system. volume_identifiers (list[str]): allowed volume identifiers. Raises: SourceScannerError: if a volume cannot be resolved from the volume identifier.
def _PrintAPFSVolumeIdentifiersOverview( self, volume_system, volume_identifiers): header = 'The following Apple File System (APFS) volumes were found:\n' self._output_writer.Write(header) column_names = ['Identifier', 'Name'] table_view = views.CLITabularTableView(column_names=column_names)...
288,276
Prints an overview of TSK partition identifiers. Args: volume_system (dfvfs.TSKVolumeSystem): volume system. volume_identifiers (list[str]): allowed volume identifiers. Raises: SourceScannerError: if a volume cannot be resolved from the volume identifier.
def _PrintTSKPartitionIdentifiersOverview( self, volume_system, volume_identifiers): header = 'The following partitions were found:\n' self._output_writer.Write(header) column_names = ['Identifier', 'Offset (in bytes)', 'Size (in bytes)'] table_view = views.CLITabularTableView(column_names=c...
288,277
Prints an overview of VSS store identifiers. Args: volume_system (dfvfs.VShadowVolumeSystem): volume system. volume_identifiers (list[str]): allowed volume identifiers. Raises: SourceScannerError: if a volume cannot be resolved from the volume identifier.
def _PrintVSSStoreIdentifiersOverview( self, volume_system, volume_identifiers): header = 'The following Volume Shadow Snapshots (VSS) were found:\n' self._output_writer.Write(header) column_names = ['Identifier', 'Creation Time'] table_view = views.CLITabularTableView(column_names=column_na...
288,278
Prompts the user to provide APFS volume identifiers. Args: volume_system (dfvfs.APFSVolumeSystem): volume system. volume_identifiers (list[str]): volume identifiers including prefix. Returns: list[str]: selected volume identifiers including prefix or None.
def _PromptUserForAPFSVolumeIdentifiers( self, volume_system, volume_identifiers): print_header = True while True: if print_header: self._PrintAPFSVolumeIdentifiersOverview( volume_system, volume_identifiers) print_header = False lines = self._textwrapper.wra...
288,279
Prompts the user to provide partition identifiers. Args: volume_system (dfvfs.TSKVolumeSystem): volume system. volume_identifiers (list[str]): volume identifiers including prefix. Returns: list[str]: selected volume identifiers including prefix or None.
def _PromptUserForPartitionIdentifiers( self, volume_system, volume_identifiers): print_header = True while True: if print_header: self._PrintTSKPartitionIdentifiersOverview( volume_system, volume_identifiers) print_header = False lines = self._textwrapper.wr...
288,280
Reads the selected volumes provided by the user. Args: volume_system (APFSVolumeSystem): volume system. prefix (Optional[str]): volume identifier prefix. Returns: list[str]: selected volume identifiers including prefix. Raises: KeyboardInterrupt: if the user requested to abort. ...
def _ReadSelectedVolumes(self, volume_system, prefix='v'): volume_identifiers_string = self._input_reader.Read() volume_identifiers_string = volume_identifiers_string.strip() if not volume_identifiers_string: return [] selected_volumes = self._ParseVolumeIdentifiersString( volume_id...
288,282
Scans an encrypted volume scan node for volume and file systems. Args: scan_context (SourceScannerContext): source scanner context. scan_node (SourceScanNode): volume scan node. Raises: SourceScannerError: if the format of or within the source is not supported, the scan node is inv...
def _ScanEncryptedVolume(self, scan_context, scan_node): if not scan_node or not scan_node.path_spec: raise errors.SourceScannerError('Invalid or missing scan node.') credentials = credentials_manager.CredentialsManager.GetCredentials( scan_node.path_spec) if not credentials: raise...
288,283
Scans a file system scan node for file systems. Args: scan_node (SourceScanNode): file system scan node. base_path_specs (list[PathSpec]): file system base path specifications. Raises: SourceScannerError: if the scan node is invalid.
def _ScanFileSystem(self, scan_node, base_path_specs): if not scan_node or not scan_node.path_spec: raise errors.SourceScannerError( 'Invalid or missing file system scan node.') base_path_specs.append(scan_node.path_spec)
288,284
Adds the credential options to the argument group. The credential options are use to unlock encrypted volumes. Args: argument_group (argparse._ArgumentGroup): argparse argument group.
def AddCredentialOptions(self, argument_group): argument_group.add_argument( '--credential', action='append', default=[], type=str, dest='credentials', metavar='TYPE:DATA', help=( 'Define a credentials that can be used to unlock encrypted ' 'volumes e.g. BitLocker. The c...
288,285
Adds the storage media image options to the argument group. Args: argument_group (argparse._ArgumentGroup): argparse argument group.
def AddStorageMediaImageOptions(self, argument_group): argument_group.add_argument( '--partitions', '--partition', dest='partitions', action='store', type=str, default=None, help=( 'Define partitions to be processed. A range of ' 'partitions can be defined as: "3..5". Mu...
288,286
Adds the VSS processing options to the argument group. Args: argument_group (argparse._ArgumentGroup): argparse argument group.
def AddVSSProcessingOptions(self, argument_group): argument_group.add_argument( '--no_vss', '--no-vss', dest='no_vss', action='store_true', default=False, help=( 'Do not scan for Volume Shadow Snapshots (VSS). This means that ' 'Volume Shadow Snapshots (VSS) are not proc...
288,287
Scans the source path for volume and file systems. This function sets the internal source path specification and source type values. Args: source_path (str): path to the source. Returns: dfvfs.SourceScannerContext: source scanner context. Raises: SourceScannerError: if the form...
def ScanSource(self, source_path): # Symbolic links are resolved here and not earlier to preserve the user # specified source path in storage and reporting. if os.path.islink(source_path): source_path = os.path.realpath(source_path) if (not source_path.startswith('\\\\.\\') and not o...
288,288
Initializes a Windows Registry file reader object. Args: file_system (dfvfs.FileSystem): file system. mount_point (dfvfs.PathSpec): mount point path specification. environment_variables (Optional[list[EnvironmentVariableArtifact]]): environment variables.
def __init__(self, file_system, mount_point, environment_variables=None): super(FileSystemWinRegistryFileReader, self).__init__() self._file_system = file_system self._path_resolver = self._CreateWindowsPathResolver( file_system, mount_point, environment_variables=environment_variables)
288,289
Create a Windows path resolver and sets the environment variables. Args: file_system (dfvfs.FileSystem): file system. mount_point (dfvfs.PathSpec): mount point path specification. environment_variables (list[EnvironmentVariableArtifact]): environment variables. Returns: dfvfs...
def _CreateWindowsPathResolver( self, file_system, mount_point, environment_variables): if environment_variables is None: environment_variables = [] path_resolver = windows_path_resolver.WindowsPathResolver( file_system, mount_point) for environment_variable in environment_variabl...
288,290
Opens the Windows Registry file specified by the path specification. Args: path_specification (dfvfs.PathSpec): path specification. ascii_codepage (Optional[str]): ASCII string codepage. Returns: WinRegistryFile: Windows Registry file or None.
def _OpenPathSpec(self, path_specification, ascii_codepage='cp1252'): if not path_specification: return None file_entry = self._file_system.GetFileEntryByPathSpec(path_specification) if file_entry is None: return None file_object = file_entry.GetFileObject() if file_object is None...
288,291
Opens the Windows Registry file specified by the path. Args: path (str): path of the Windows Registry file. ascii_codepage (Optional[str]): ASCII string codepage. Returns: WinRegistryFile: Windows Registry file or None.
def Open(self, path, ascii_codepage='cp1252'): path_specification = self._path_resolver.ResolvePath(path) if path_specification is None: return None return self._OpenPathSpec(path_specification)
288,292
Collects values from Windows Registry values. Args: artifacts_registry (artifacts.ArtifactDefinitionsRegistry): artifacts definitions registry. knowledge_base (KnowledgeBase): to fill with preprocessing information. searcher (dfvfs.FileSystemSearcher): file system searcher to preprocess...
def CollectFromFileSystem( cls, artifacts_registry, knowledge_base, searcher, file_system): for preprocess_plugin in cls._file_system_plugins.values(): artifact_definition = artifacts_registry.GetDefinitionByName( preprocess_plugin.ARTIFACT_DEFINITION_NAME) if not artifact_definitio...
288,293
Collects values from knowledge base values. Args: knowledge_base (KnowledgeBase): to fill with preprocessing information.
def CollectFromKnowledgeBase(cls, knowledge_base): for preprocess_plugin in cls._knowledge_base_plugins.values(): logger.debug('Running knowledge base preprocessor plugin: {0:s}'.format( preprocess_plugin.__class__.__name__)) try: preprocess_plugin.Collect(knowledge_base) ex...
288,294
Collects values from Windows Registry values. Args: artifacts_registry (artifacts.ArtifactDefinitionsRegistry): artifacts definitions registry. knowledge_base (KnowledgeBase): to fill with preprocessing information. searcher (dfwinreg.WinRegistrySearcher): Windows Registry searcher to ...
def CollectFromWindowsRegistry( cls, artifacts_registry, knowledge_base, searcher): for preprocess_plugin in cls._windows_registry_plugins.values(): artifact_definition = artifacts_registry.GetDefinitionByName( preprocess_plugin.ARTIFACT_DEFINITION_NAME) if not artifact_definition: ...
288,295
Deregisters an preprocess plugin class. Args: plugin_class (type): preprocess plugin class. Raises: KeyError: if plugin class is not set for the corresponding name. TypeError: if the source type of the plugin class is not supported.
def DeregisterPlugin(cls, plugin_class): name = getattr( plugin_class, 'ARTIFACT_DEFINITION_NAME', plugin_class.__name__) name = name.lower() if name not in cls._plugins: raise KeyError( 'Artifact plugin class not set for name: {0:s}.'.format(name)) del cls._plugins[name] ...
288,296
Registers an preprocess plugin class. Args: plugin_class (type): preprocess plugin class. Raises: KeyError: if plugin class is already set for the corresponding name. TypeError: if the source type of the plugin class is not supported.
def RegisterPlugin(cls, plugin_class): name = getattr( plugin_class, 'ARTIFACT_DEFINITION_NAME', plugin_class.__name__) name = name.lower() if name in cls._plugins: raise KeyError( 'Artifact plugin class already set for name: {0:s}.'.format(name)) preprocess_plugin = plugin...
288,298
Runs the preprocessing plugins. Args: artifacts_registry (artifacts.ArtifactDefinitionsRegistry): artifacts definitions registry. file_system (dfvfs.FileSystem): file system to be preprocessed. mount_point (dfvfs.PathSpec): mount point path specification that refers to the bas...
def RunPlugins( cls, artifacts_registry, file_system, mount_point, knowledge_base): searcher = file_system_searcher.FileSystemSearcher(file_system, mount_point) cls.CollectFromFileSystem( artifacts_registry, knowledge_base, searcher, file_system) # Run the Registry plugins separately so...
288,299
Parses a compound ZIP file-like object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): a file-like object. Raises: UnableToParseFile: when the file cannot be parsed.
def ParseFileObject(self, parser_mediator, file_object): display_name = parser_mediator.GetDisplayName() if not zipfile.is_zipfile(file_object): raise errors.UnableToParseFile( '[{0:s}] unable to parse file: {1:s} with error: {2:s}'.format( self.NAME, display_name, 'Not a Zip...
288,300
Processes a zip file using all compound zip files. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. zip_file (zipfile.ZipFile): the zip file. It should not be closed in this method, but will be closed in P...
def _ProcessZipFileWithPlugins(self, parser_mediator, zip_file): archive_members = zip_file.namelist() for plugin in self._plugins: try: plugin.UpdateChainAndProcess( parser_mediator, zip_file=zip_file, archive_members=archive_members) except errors.WrongCompoundZIPPlugin as...
288,301
Gets the year from a POSIX timestamp The POSIX time is the number of seconds since 1970-01-01 00:00:00 UTC. Args: posix_time: An integer containing the number of seconds since 1970-01-01 00:00:00 UTC. timezone: Optional timezone of the POSIX timestamp. Returns: The year of the POSIX...
def GetYearFromPosixTime(posix_time, timezone=pytz.UTC): datetime_object = datetime.datetime.fromtimestamp(posix_time, tz=timezone) return datetime_object.year
288,302
Parses a log record structure. 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 parsed from the log file.
def ParseRecord(self, parser_mediator, key, structure): if key != 'logline': logger.warning( 'Unable to parse record, unknown structure: {0:s}'.format(key)) return try: timestamp = int(structure.timestamp) except ValueError: logger.debug('Invalid timestamp string {0:s...
288,311
Verify that this file is a XChat scrollback 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 was successfully parsed.
def VerifyStructure(self, parser_mediator, line): structure = self.LOG_LINE try: parsed_structure = structure.parseString(line) except pyparsing.ParseException: logger.debug('Not a XChat scrollback log file') return False try: int(parsed_structure.timestamp, 10) except...
288,312
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): if registry_key is None: return values_dict = {} for value_name in self._VALUE_NAMES: registry_value = registry_key.GetValueByName(value_name) if not registry_value: continue value_data = registry_value....
288,313
Parses a Container_# table. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. table (pyesedb.table): table. container_name (str): container name, which indicates the table type. Raises: ValueError: i...
def _ParseContainerTable(self, parser_mediator, table, container_name): if table is None: raise ValueError('Missing table value.') for record_index, esedb_record in enumerate(table.records): if parser_mediator.abort: break # TODO: add support for: # wpnidm, iecompat, iecom...
288,318
Parses the Containers table. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. database (Optional[pyesedb.file]): ESE database. table (Optional[pyesedb.table]): table. Raises: ValueError: if the data...
def ParseContainersTable( self, parser_mediator, database=None, table=None, **unused_kwargs): if database is None: raise ValueError('Missing database value.') if table is None: raise ValueError('Missing table value.') for esedb_record in table.records: if parser_mediator.abort...
288,319
Parses the LeakFiles table. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. database (Optional[pyesedb.file]): ESE database. table (Optional[pyesedb.table]): table. Raises: ValueError: if the datab...
def ParseLeakFilesTable( self, parser_mediator, database=None, table=None, **unused_kwargs): if database is None: raise ValueError('Missing database value.') if table is None: raise ValueError('Missing table value.') for esedb_record in table.records: if parser_mediator.abort:...
288,320
Parses the Partitions table. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. database (Optional[pyesedb.file]): ESE database. table (Optional[pyesedb.table]): table. Raises: ValueError: if the data...
def ParsePartitionsTable( self, parser_mediator, database=None, table=None, **unused_kwargs): if database is None: raise ValueError('Missing database value.') if table is None: raise ValueError('Missing table value.') for esedb_record in table.records: if parser_mediator.abort...
288,321
Parses a record and produces events. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (file): file-like object. record_offset (int): offset of the record relative to the start of the file...
def _ParseRecord(self, parser_mediator, file_object, record_offset): record_strings_data_offset = file_object.tell() record_strings_data_size = record_offset - record_strings_data_offset record_strings_data = self._ReadData( file_object, record_strings_data_offset, record_strings_data_size) ...
288,324
Parses a record extra field. Args: byte_stream (bytes): byte stream. file_offset (int): offset of the record extra field relative to the start of the file. Returns: asl_record_extra_field: record extra field. Raises: ParseError: if the record extra field cannot be parsed...
def _ParseRecordExtraField(self, byte_stream, file_offset): extra_field_map = self._GetDataTypeMap('asl_record_extra_field') try: record_extra_field = self._ReadStructureFromByteStream( byte_stream, file_offset, extra_field_map) except (ValueError, errors.ParseError) as exception: ...
288,325
Parses a record string. Args: record_strings_data (bytes): record strings data. record_strings_data_offset (int): offset of the record strings data relative to the start of the file. string_offset (int): offset of the string relative to the start of the file. Returns: ...
def _ParseRecordString( self, record_strings_data, record_strings_data_offset, string_offset): if string_offset == 0: return None if string_offset & self._STRING_OFFSET_MSB: if (string_offset >> 60) != 8: raise errors.ParseError('Invalid inline record string flag.') string...
288,326
Parses an ASL file-like object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): file-like object. Raises: UnableToParseFile: when the file cannot be parsed.
def ParseFileObject(self, parser_mediator, file_object): file_header_map = self._GetDataTypeMap('asl_file_header') try: file_header, _ = self._ReadStructureFromFileObject( file_object, 0, file_header_map) except (ValueError, errors.ParseError) as exception: raise errors.UnableToP...
288,327
Initializes and builds the path filter table from a list of paths. Args: paths: a list of strings containing the paths. ignore_list: a list of path segment indexes to ignore, where 0 is the index of the first path segment relative from the root. path_segment_separator: optional...
def __init__(self, paths, ignore_list, path_segment_separator='/'): super(_PathFilterTable, self).__init__() self._path_segment_separator = path_segment_separator self.path_segments_per_index = {} self.paths = list(paths) for path in self.paths: self._AddPathSegments(path, ignore_list)
288,328
Adds the path segments to the table. Args: path: a string containing the path. ignore_list: a list of path segment indexes to ignore, where 0 is the index of the first path segment relative from the root.
def _AddPathSegments(self, path, ignore_list): path_segments = path.split(self._path_segment_separator) for path_segment_index, path_segment in enumerate(path_segments): if path_segment_index not in self.path_segments_per_index: self.path_segments_per_index[path_segment_index] = {} if ...
288,329
Adds a path segment index and sets its weight to 0. Args: path_segment_index: an integer containing the path segment index. Raises: ValueError: if the path segment weights already contains the path segment index.
def AddIndex(self, path_segment_index): if path_segment_index in self._weight_per_index: raise ValueError('Path segment index already set.') self._weight_per_index[path_segment_index] = 0
288,332
Adds a weight for a specific path segment index. Args: path_segment_index: an integer containing the path segment index. weight: an integer containing the weight. Raises: ValueError: if the path segment weights do not contain the path segment index.
def AddWeight(self, path_segment_index, weight): if path_segment_index not in self._weight_per_index: raise ValueError('Path segment index not set.') self._weight_per_index[path_segment_index] += weight if weight not in self._indexes_per_weight: self._indexes_per_weight[weight] = [] ...
288,333
Sets a weight for a specific path segment index. Args: path_segment_index: an integer containing the path segment index. weight: an integer containing the weight. Raises: ValueError: if the path segment weights do not contain the path segment index.
def SetWeight(self, path_segment_index, weight): if path_segment_index not in self._weight_per_index: raise ValueError('Path segment index not set.') self._weight_per_index[path_segment_index] = weight if weight not in self._indexes_per_weight: self._indexes_per_weight[weight] = [] s...
288,334
Initializes and builds a path filter scan tree. Args: paths: a list of strings containing the paths. case_sensitive: optional boolean value to indicate string matches should be case sensitive. path_segment_separator: optional string containing the path segment ...
def __init__(self, paths, case_sensitive=True, path_segment_separator='/'): super(PathFilterScanTree, self).__init__() self._case_sensitive = case_sensitive self._path_segment_separator = path_segment_separator self._root_node = None if not self._case_sensitive: paths = [path.lower() for...
288,336
Retrieves the index of the path segment based on occurrence weights. Args: occurrence_weights: the occurrence weights object (instance of _PathSegmentWeights). value_weights: the value weights object (instance of _PathSegmentWeights). Returns: An integer containing ...
def _GetPathSegmentIndexForOccurrenceWeights( self, occurrence_weights, value_weights): largest_weight = occurrence_weights.GetLargestWeight() if largest_weight > 0: occurrence_weight_indexes = occurrence_weights.GetIndexesForWeight( largest_weight) number_of_occurrence_indexes...
288,339
Retrieves the index of the path segment based on similarity weights. Args: similarity_weights: the similarity weights object (instance of _PathSegmentWeights). occurrence_weights: the occurrence weights object (instance of _PathSegmentWeights). ...
def _GetPathSegmentIndexForSimilarityWeights( self, similarity_weights, occurrence_weights, value_weights): largest_weight = similarity_weights.GetLargestWeight() if largest_weight > 0: similarity_weight_indexes = similarity_weights.GetIndexesForWeight( largest_weight) number_o...
288,340
Retrieves the index of the path segment based on value weights. Args: value_weights: the value weights object (instance of _PathSegmentWeights). Returns: An integer containing the path segment index. Raises: RuntimeError: is no path segment index can be found.
def _GetPathSegmentIndexForValueWeights(self, value_weights): largest_weight = value_weights.GetLargestWeight() if largest_weight > 0: value_weight_indexes = value_weights.GetIndexesForWeight(largest_weight) else: value_weight_indexes = [] if value_weight_indexes: path_segment_i...
288,341
Checks if a path matches the scan tree-based path filter. Args: path: a string containing the path. path_segment_separator: optional string containing the path segment separator. None defaults to the path segment separator that was set when th...
def CheckPath(self, path, path_segment_separator=None): if not self._case_sensitive: path = path.lower() if path_segment_separator is None: path_segment_separator = self._path_segment_separator path_segments = path.split(path_segment_separator) number_of_path_segments = len(path_segme...
288,342
Initializes a path filter scan tree node. Args: path_segment_index: an integer containing the path segment index.
def __init__(self, path_segment_index): super(PathFilterScanTreeNode, self).__init__() self._path_segments = {} self.default_value = None self.parent = None self.path_segment_index = path_segment_index
288,343
Adds a path segment. Args: path_segment: a string containing the path segment. scan_object: a scan object, either a scan tree sub node (instance of PathFilterScanTreeNode) or a string containing a path. Raises: ValueError: if the node already contains a scan object for ...
def AddPathSegment(self, path_segment, scan_object): if path_segment in self._path_segments: raise ValueError('Path segment already set.') if isinstance(scan_object, PathFilterScanTreeNode): scan_object.parent = self self._path_segments[path_segment] = scan_object
288,344
Sets the default (non-match) value. Args: scan_object: a scan object, either a scan tree sub node (instance of PathFilterScanTreeNode) or a string containing a path. Raises: TypeError: if the scan object is of an unsupported type. ValueError: if the default value is alread...
def SetDefaultValue(self, scan_object): if (not isinstance(scan_object, PathFilterScanTreeNode) and not isinstance(scan_object, py2to3.STRING_TYPES)): raise TypeError('Unsupported scan object type.') if self.default_value: raise ValueError('Default value already set.') self.defaul...
288,345
Converts the path filter scan tree node into a debug string. Args: indentation_level: an integer containing the text indentation level. Returns: A string containing a debug representation of the path filter scan tree node.
def ToDebugString(self, indentation_level=1): indentation = ' ' * indentation_level text_parts = ['{0:s}path segment index: {1:d}\n'.format( indentation, self.path_segment_index)] for path_segment, scan_object in self._path_segments.items(): text_parts.append('{0:s}path segment: {1:s}\...
288,346
Parses the MRUListEx value in a given Registry key. Args: registry_key (dfwinreg.WinRegistryKey): Windows Registry key that contains the MRUListEx value. Returns: mrulistex_entries: MRUListEx entries or None if not available.
def _ParseMRUListExValue(self, registry_key): mrulistex_value = registry_key.GetValueByName('MRUListEx') # The key exists but does not contain a value named "MRUList". if not mrulistex_value: return None mrulistex_entries_map = self._GetDataTypeMap('mrulistex_entries') context = dtfabr...
288,348
Extract event objects from a MRUListEx 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. parent_path_segments (list[str]): parent shel...
def _ParseSubKey( self, parser_mediator, registry_key, parent_path_segments, codepage='cp1252'): try: mrulistex = self._ParseMRUListExValue(registry_key) except (ValueError, errors.ParseError) as exception: parser_mediator.ProduceExtractionWarning( 'unable to parse MRUList...
288,349
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. codepage (Optional[str]): extended ASCII string codep...
def ExtractEvents( self, parser_mediator, registry_key, codepage='cp1252', **kwargs): self._ParseSubKey(parser_mediator, registry_key, [], codepage=codepage)
288,350
Initializes an event. Args: timestamp (int): timestamp, which contains the number of microseconds since January 1, 1970, 00:00:00 UTC. timestamp_description (str): description of the meaning of the timestamp value. data_type (Optional[str]): event data type. If the data type i...
def __init__(self, timestamp, timestamp_description, data_type=None): super(TimestampEvent, self).__init__() self.timestamp = timestamp self.timestamp_desc = timestamp_description if data_type: self.data_type = data_type
288,351
Initializes an event. Args: date_time (dfdatetime.DateTimeValues): date and time values. date_time_description (str): description of the meaning of the date and time values. data_type (Optional[str]): event data type. If the data type is not set it is derived from the DATA_TYP...
def __init__( self, date_time, date_time_description, data_type=None, time_zone=None): timestamp = date_time.GetPlasoTimestamp() if date_time.is_local_time and time_zone: timestamp = timelib.Timestamp.LocaltimeToUTC(timestamp, time_zone) super(DateTimeValuesEvent, self).__init__( t...
288,352
Initializes an event. Args: datetime_value (datetime.datetime): date and time values. date_time_description (str): description of the meaning of the date and time values. data_type (Optional[str]): event data type. If the data type is not set it is derived from the DATA_TYPE c...
def __init__( self, datetime_value, date_time_description, data_type=None, time_zone=None): year, month, day_of_month, hours, minutes, seconds, _, _, _ = ( datetime_value.utctimetuple()) time_elements_tuple = ( year, month, day_of_month, hours, minutes, seconds, datetim...
288,353
Extracts relevant MacOS update 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): version = match.get('LastAttemptSystemVersion', 'N/A') pending = match.get('LastUpdatesAvailable', None) event_data = plist_event.PlistTimeEventData() event_data.desc = 'Last MacOS {0:s} full update.'.format(version) event_dat...
288,354
Parses Windows Registry value data for a preprocessing attribute. Args: knowledge_base (KnowledgeBase): to fill with preprocessing information. value_data (object): Windows Registry value data. Raises: errors.PreProcessFail: if the preprocessing fails.
def _ParseValueData(self, knowledge_base, value_data): if not isinstance(value_data, py2to3.UNICODE_TYPE): raise errors.PreProcessFail( 'Unsupported Windows Registry value type: {0:s} for ' 'artifact: {1:s}.'.format( type(value_data), self.ARTIFACT_DEFINITION_NAME)) ...
288,355
Collects values from the knowledge base. Args: knowledge_base (KnowledgeBase): to fill with preprocessing information. Raises: PreProcessFail: if the preprocessing fails.
def Collect(self, knowledge_base): environment_variable = knowledge_base.GetEnvironmentVariable('programdata') allusersappdata = getattr(environment_variable, 'value', None) if not allusersappdata: environment_variable = knowledge_base.GetEnvironmentVariable( 'allusersprofile') a...
288,357
Parses Windows Registry value data for a preprocessing attribute. Args: knowledge_base (KnowledgeBase): to fill with preprocessing information. value_data (object): Windows Registry value data. Raises: errors.PreProcessFail: if the preprocessing fails.
def _ParseValueData(self, knowledge_base, value_data): if not isinstance(value_data, py2to3.UNICODE_TYPE): raise errors.PreProcessFail( 'Unsupported Windows Registry value type: {0:s} for ' 'artifact: {1:s}.'.format( type(value_data), self.ARTIFACT_DEFINITION_NAME)) ...
288,358
Parses Windows Registry value data for a preprocessing attribute. Args: knowledge_base (KnowledgeBase): to fill with preprocessing information. value_data (object): Windows Registry value data. Raises: errors.PreProcessFail: if the preprocessing fails.
def _ParseValueData(self, knowledge_base, value_data): if not isinstance(value_data, py2to3.UNICODE_TYPE): raise errors.PreProcessFail( 'Unsupported Windows Registry value type: {0:s} for ' 'artifact: {1:s}.'.format( type(value_data), self.ARTIFACT_DEFINITION_NAME)) ...
288,359
Collects values from the knowledge base. Args: knowledge_base (KnowledgeBase): to fill with preprocessing information. Raises: PreProcessFail: if the preprocessing fails.
def Collect(self, knowledge_base): environment_variable = knowledge_base.GetEnvironmentVariable( 'programdata') allusersprofile = getattr(environment_variable, 'value', None) if not allusersprofile: environment_variable = knowledge_base.GetEnvironmentVariable( 'allusersprofile'...
288,360
Parses Windows Registry value data for a preprocessing attribute. Args: knowledge_base (KnowledgeBase): to fill with preprocessing information. value_data (object): Windows Registry value data. Raises: errors.PreProcessFail: if the preprocessing fails.
def _ParseValueData(self, knowledge_base, value_data): if not isinstance(value_data, py2to3.UNICODE_TYPE): raise errors.PreProcessFail( 'Unsupported Windows Registry value type: {0:s} for ' 'artifact: {1:s}.'.format( type(value_data), self.ARTIFACT_DEFINITION_NAME)) ...
288,361
Parses Windows Registry value data for a preprocessing attribute. Args: knowledge_base (KnowledgeBase): to fill with preprocessing information. value_data (object): Windows Registry value data. Raises: errors.PreProcessFail: if the preprocessing fails.
def _ParseValueData(self, knowledge_base, value_data): if not isinstance(value_data, py2to3.UNICODE_TYPE): raise errors.PreProcessFail( 'Unsupported Windows Registry value type: {0:s} for ' 'artifact: {1:s}.'.format( type(value_data), self.ARTIFACT_DEFINITION_NAME)) ...
288,362
Retrieves the username from a Windows profile path. Trailing path path segment are ignored. Args: path (str): a Windows path with '\\' as path segment separator. Returns: str: basename which is the last path segment.
def _GetUsernameFromProfilePath(self, path): # Strip trailing key separators. while path and path[-1] == '\\': path = path[:-1] if path: _, _, path = path.rpartition('\\') return path
288,363
Parses a Windows Registry key for a preprocessing attribute. Args: knowledge_base (KnowledgeBase): to fill with preprocessing information. registry_key (dfwinreg.WinRegistryKey): Windows Registry key. value_name (str): name of the Windows Registry value. Raises: errors.PreProcessFail: ...
def _ParseKey(self, knowledge_base, registry_key, value_name): user_account = artifacts.UserAccountArtifact( identifier=registry_key.name, path_separator='\\') registry_value = registry_key.GetValueByName('ProfileImagePath') if registry_value: profile_path = registry_value.GetDataAsObjec...
288,364
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( '--status_view', '--status-view', dest='status_view_mode', choices=['linear', 'none', 'window'], action='store', metavar='TYPE', default=status_view.StatusView.MODE_WINDOW, help=( 'The processing status view...
288,365
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') status_view_mode = cls._ParseStringOption( options, 'status_view_mode', default_...
288,366
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( '--append', dest='append', action='store_true', default=False, required=cls._DEFAULT_APPEND, help=( 'Defines whether the intention is to append to an already ' 'existing database or overwrite it. Default...
288,367
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.
def ParseOptions(cls, options, output_module): if not isinstance(output_module, shared_4n6time.Shared4n6TimeOutputModule): raise errors.BadConfigObject( 'Output module is not an instance of Shared4n6TimeOutputModule') append = getattr(options, 'append', cls._DEFAULT_APPEND) evidence = ...
288,368
Initializes the line reader. Args: file_object (FileIO): a file-like object to read from. end_of_line (Optional[bytes]): end of line indicator.
def __init__(self, file_object, end_of_line=b'\n'): super(BinaryLineReader, self).__init__() self._file_object = file_object self._file_object_size = file_object.get_size() self.end_of_line = end_of_line self._end_of_line_length = len(self.end_of_line) self._lines = [] self._lines_buffe...
288,371
Initializes the delimited separated values reader. Args: binary_line_reader (BinaryLineReader): a binary file reader delimiter (bytes): field delimiter.
def __init__(self, binary_line_reader, delimiter): super(BinaryDSVReader, self).__init__() self._line_reader = binary_line_reader self._delimiter = delimiter
288,374
Parses and validates options. Args: options (argparse.Namespace): parser options. analysis_plugin (OutputModule): analysis_plugin to configure. Raises: BadConfigObject: when the output module object is of the wrong type. BadConfigOption: when a configuration parameter fails validation.
def ParseOptions(cls, options, analysis_plugin): if not isinstance(analysis_plugin, sessionize.SessionizeAnalysisPlugin): raise errors.BadConfigObject( 'Analysis plugin is not an instance of SessionizeAnalysisPlugin') maximum_pause = cls._ParseNumericOption( options, 'sessionize_ma...
288,376
Opens a RPC communication channel to the server. Args: hostname (str): hostname or IP address to connect to for requests. port (int): port to connect to for requests. Returns: bool: True if the communication channel was established.
def Open(self, hostname, port): server_url = 'http://{0:s}:{1:d}'.format(hostname, port) try: self._xmlrpc_proxy = xmlrpclib.ServerProxy( server_url, allow_none=True) except SocketServer.socket.error as exception: logger.warning(( 'Unable to connect to RPC server on {0:...
288,378
Initialize a threaded RPC server. Args: callback (function): callback function to invoke on get status RPC request.
def __init__(self, callback): super(ThreadedXMLRPCServer, self).__init__(callback) self._rpc_thread = None self._xmlrpc_server = None
288,379
Opens the RPC communication channel for clients. Args: hostname (str): hostname or IP address to connect to for requests. port (int): port to connect to for requests. Returns: bool: True if the communication channel was successfully opened.
def _Open(self, hostname, port): try: self._xmlrpc_server = SimpleXMLRPCServer.SimpleXMLRPCServer( (hostname, port), logRequests=False, allow_none=True) except SocketServer.socket.error as exception: logger.warning(( 'Unable to bind a RPC server on {0:s}:{1:d} with error: ' ...
288,380
Starts the process status RPC server. Args: hostname (str): hostname or IP address to connect to for requests. port (int): port to connect to for requests. Returns: bool: True if the RPC server was successfully started.
def Start(self, hostname, port): if not self._Open(hostname, port): return False self._rpc_thread = threading.Thread( name=self._THREAD_NAME, target=self._xmlrpc_server.serve_forever) self._rpc_thread.start() return True
288,381
Retrieves a list of the registered analysis plugins. Args: show_all (Optional[bool]): True if all analysis plugin names should be listed. Returns: list[tuple[str, str, str]]: the name, docstring and type string of each analysis plugin in alphabetical order.
def GetAllPluginInformation(cls, show_all=True): results = [] for plugin_class in iter(cls._plugin_classes.values()): plugin_object = plugin_class() if not show_all and not plugin_class.ENABLE_IN_EXTRACTION: continue # TODO: Use a specific description variable, not the docstring....
288,383
Retrieves the plugin objects. Args: plugin_names (list[str]): names of plugins that should be retrieved. Returns: dict[str, AnalysisPlugin]: analysis plugins per name.
def GetPluginObjects(cls, plugin_names): plugin_objects = {} for plugin_name, plugin_class in iter(cls._plugin_classes.items()): if plugin_name not in plugin_names: continue plugin_objects[plugin_name] = plugin_class() return plugin_objects
288,384
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( '--name', '--timeline_name', '--timeline-name', dest='timeline_name', type=str, action='store', default=cls._DEFAULT_NAME, required=False, help=( 'The name of the timeline in Timesketch. Default: ' ...
288,385
Parses and validates options. Args: options (argparse.Namespace): parser options. output_module (TimesketchOutputModule): output module to configure. Raises: BadConfigObject: when the output module object is of the wrong type. BadConfigOption: when a configuration parameter fails valid...
def ParseOptions(cls, options, output_module): if not isinstance(output_module, timesketch_out.TimesketchOutputModule): raise errors.BadConfigObject( 'Output module is not an instance of TimesketchOutputModule') document_type = cls._ParseStringOption( options, 'document_type', defa...
288,386
Parses a message row. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. query (str): query that created the row. row (sqlite3.Row): row.
def ParseNotificationcenterRow( self, parser_mediator, query, row, **unused_kwargs): query_hash = hash(query) event_data = MacNotificationCenterEventData() event_data.bundle_name = self._GetRowValue(query_hash, row, 'bundle_name') event_data.presented = self._GetRowValue(query_hash, row, 'pr...
288,388
Initializes the CLI tool object. Args: input_reader (Optional[InputReader]): input reader, where None indicates that the stdin input reader should be used. output_writer (Optional[OutputWriter]): output writer, where None indicates that the stdout output writer should be used.
def __init__(self, input_reader=None, output_writer=None): super(PinfoTool, self).__init__( input_reader=input_reader, output_writer=output_writer) self._compare_storage_file_path = None self._output_filename = None self._output_format = None self._process_memory_limit = None self._...
288,390
Calculates the counters of the entire storage. Args: storage_reader (StorageReader): storage reader. Returns: dict[str,collections.Counter]: storage counters.
def _CalculateStorageCounters(self, storage_reader): analysis_reports_counter = collections.Counter() analysis_reports_counter_error = False event_labels_counter = collections.Counter() event_labels_counter_error = False parsers_counter = collections.Counter() parsers_counter_error = False ...
288,391
Compares the contents of two stores. Args: storage_reader (StorageReader): storage reader. compare_storage_reader (StorageReader): storage to compare against. Returns: bool: True if the content of the stores is identical.
def _CompareStores(self, storage_reader, compare_storage_reader): storage_counters = self._CalculateStorageCounters(storage_reader) compare_storage_counters = self._CalculateStorageCounters( compare_storage_reader) # TODO: improve comparison, currently only total numbers are compared. ret...
288,392
Prints the details of the analysis reports. Args: storage_reader (StorageReader): storage reader.
def _PrintAnalysisReportsDetails(self, storage_reader): if not storage_reader.HasAnalysisReports(): self._output_writer.Write('No analysis reports stored.\n\n') return for index, analysis_report in enumerate( storage_reader.GetAnalysisReports()): title = 'Analysis report: {0:d}'....
288,393
Prints a summary of the warnings. Args: storage_counters (dict): storage counters.
def _PrintWarningCounters(self, storage_counters): warnings_by_pathspec = storage_counters.get('warnings_by_path_spec', {}) warnings_by_parser_chain = storage_counters.get( 'warnings_by_parser_chain', {}) if not warnings_by_parser_chain: self._output_writer.Write('No warnings stored.\n\n'...
288,394
Prints the details of the warnings. Args: storage (BaseStore): storage.
def _PrintWarningsDetails(self, storage): if not storage.HasWarnings(): self._output_writer.Write('No warnings stored.\n\n') return for index, warning in enumerate(storage.GetWarnings()): title = 'Warning: {0:d}'.format(index) table_view = views.ViewsFactory.GetTableView( ...
288,395
Prints the event labels counter. Args: event_labels_counter (collections.Counter): number of event tags per label. session_identifier (Optional[str]): session identifier.
def _PrintEventLabelsCounter( self, event_labels_counter, session_identifier=None): if not event_labels_counter: return title = 'Event tags generated per label' if session_identifier: title = '{0:s}: {1:s}'.format(title, session_identifier) table_view = views.ViewsFactory.GetTab...
288,396
Prints the parsers counter Args: parsers_counter (collections.Counter): number of events per parser or parser plugin. session_identifier (Optional[str]): session identifier.
def _PrintParsersCounter(self, parsers_counter, session_identifier=None): if not parsers_counter: return title = 'Events generated per parser' if session_identifier: title = '{0:s}: {1:s}'.format(title, session_identifier) table_view = views.ViewsFactory.GetTableView( self._vi...
288,397
Prints the details of the preprocessing information. Args: storage_reader (StorageReader): storage reader. session_number (Optional[int]): session number.
def _PrintPreprocessingInformation(self, storage_reader, session_number=None): knowledge_base_object = knowledge_base.KnowledgeBase() storage_reader.ReadPreprocessingInformation(knowledge_base_object) # TODO: replace session_number by session_identifier. system_configuration = knowledge_base_obje...
288,398
Prints the details of the sessions. Args: storage_reader (BaseStore): storage.
def _PrintSessionsDetails(self, storage_reader): for session_number, session in enumerate(storage_reader.GetSessions()): session_identifier = uuid.UUID(hex=session.identifier) session_identifier = '{0!s}'.format(session_identifier) start_time = 'N/A' if session.start_time is not None: ...
288,399
Prints a sessions overview. Args: storage_reader (StorageReader): storage reader.
def _PrintSessionsOverview(self, storage_reader): table_view = views.ViewsFactory.GetTableView( self._views_format_type, title='Sessions') for session in storage_reader.GetSessions(): start_time = timelib.Timestamp.CopyToIsoFormat( session.start_time) session_identifier = uui...
288,400
Prints information about the store as human-readable text. Args: storage_reader (StorageReader): storage reader.
def _PrintStorageInformationAsText(self, storage_reader): table_view = views.ViewsFactory.GetTableView( self._views_format_type, title='Plaso Storage Information') table_view.AddRow(['Filename', os.path.basename(self._storage_file_path)]) table_view.AddRow(['Format version', storage_reader.form...
288,401
Writes a summary of sessions as machine-readable JSON. Args: storage_reader (StorageReader): storage reader.
def _PrintStorageInformationAsJSON(self, storage_reader): serializer = json_serializer.JSONAttributeContainerSerializer storage_counters = self._CalculateStorageCounters(storage_reader) storage_counters_json = json.dumps(storage_counters) self._output_writer.Write('{') self._output_writer.Write...
288,402