docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
Determines if the file entry is a metadata file.
Args:
file_entry (dfvfs.FileEntry): a file entry object.
Returns:
bool: True if the file entry is a metadata file. | def _IsMetadataFile(self, file_entry):
if (file_entry.type_indicator == dfvfs_definitions.TYPE_INDICATOR_TSK and
file_entry.path_spec.location in self._METADATA_FILE_LOCATIONS_TSK):
return True
return False | 288,825 |
Processes a data stream containing archive types such as: TAR or ZIP.
Args:
mediator (ParserMediator): mediates the interactions between
parsers and other components, such as storage and abort signals.
path_spec (dfvfs.PathSpec): path specification.
type_indicators(list[str]): dfVFS arc... | def _ProcessArchiveTypes(self, mediator, path_spec, type_indicators):
number_of_type_indicators = len(type_indicators)
if number_of_type_indicators == 0:
return
self.processing_status = definitions.STATUS_INDICATOR_COLLECTING
if number_of_type_indicators > 1:
display_name = mediator.G... | 288,826 |
Processes a data stream containing compressed stream types such as: bz2.
Args:
mediator (ParserMediator): mediates the interactions between
parsers and other components, such as storage and abort signals.
path_spec (dfvfs.PathSpec): path specification.
type_indicators(list[str]): dfVFS ... | def _ProcessCompressedStreamTypes(self, mediator, path_spec, type_indicators):
number_of_type_indicators = len(type_indicators)
if number_of_type_indicators == 0:
return
self.processing_status = definitions.STATUS_INDICATOR_COLLECTING
if number_of_type_indicators > 1:
display_name = m... | 288,827 |
Processes a directory file entry.
Args:
mediator (ParserMediator): mediates the interactions between
parsers and other components, such as storage and abort signals.
file_entry (dfvfs.FileEntry): file entry of the directory. | def _ProcessDirectory(self, mediator, file_entry):
self.processing_status = definitions.STATUS_INDICATOR_COLLECTING
if self._processing_profiler:
self._processing_profiler.StartTiming('collecting')
for sub_file_entry in file_entry.sub_file_entries:
if self._abort:
break
try... | 288,828 |
Processes a file entry.
Args:
mediator (ParserMediator): mediates the interactions between
parsers and other components, such as storage and abort signals.
file_entry (dfvfs.FileEntry): file entry. | def _ProcessFileEntry(self, mediator, file_entry):
display_name = mediator.GetDisplayName()
logger.debug(
'[ProcessFileEntry] processing file entry: {0:s}'.format(display_name))
reference_count = mediator.resolver_context.GetFileObjectReferenceCount(
file_entry.path_spec)
try:
... | 288,829 |
Processes a specific data stream of a file entry.
Args:
mediator (ParserMediator): mediates the interactions between
parsers and other components, such as storage and abort signals.
file_entry (dfvfs.FileEntry): file entry containing the data stream.
data_stream (dfvfs.DataStream): data... | def _ProcessFileEntryDataStream(self, mediator, file_entry, data_stream):
display_name = mediator.GetDisplayName()
data_stream_name = getattr(data_stream, 'name', '') or ''
logger.debug((
'[ProcessFileEntryDataStream] processing data stream: "{0:s}" of '
'file entry: {1:s}').format(data... | 288,830 |
Processes a metadata file.
Args:
mediator (ParserMediator): mediates the interactions between
parsers and other components, such as storage and abort signals.
file_entry (dfvfs.FileEntry): file entry of the metadata file. | def _ProcessMetadataFile(self, mediator, file_entry):
self.processing_status = definitions.STATUS_INDICATOR_EXTRACTING
self._event_extractor.ParseFileEntryMetadata(mediator, file_entry)
for data_stream in file_entry.data_streams:
if self._abort:
break
self.last_activity_timestamp =... | 288,831 |
Sets the hasher names.
Args:
hasher_names_string (str): comma separated names of the hashers
to enable, where 'none' disables the hashing analyzer. | def _SetHashers(self, hasher_names_string):
if not hasher_names_string or hasher_names_string == 'none':
return
analyzer_object = analyzers_manager.AnalyzersManager.GetAnalyzerInstance(
'hashing')
analyzer_object.SetHasherNames(hasher_names_string)
self._analyzers.append(analyzer_obj... | 288,832 |
Sets the Yara rules.
Args:
yara_rules_string (str): unparsed Yara rule definitions. | def _SetYaraRules(self, yara_rules_string):
if not yara_rules_string:
return
analyzer_object = analyzers_manager.AnalyzersManager.GetAnalyzerInstance(
'yara')
analyzer_object.SetRules(yara_rules_string)
self._analyzers.append(analyzer_object) | 288,833 |
Processes a path specification.
Args:
mediator (ParserMediator): mediates the interactions between
parsers and other components, such as storage and abort signals.
path_spec (dfvfs.PathSpec): path specification. | def ProcessPathSpec(self, mediator, path_spec):
self.last_activity_timestamp = time.time()
self.processing_status = definitions.STATUS_INDICATOR_RUNNING
file_entry = path_spec_resolver.Resolver.OpenFileEntry(
path_spec, resolver_context=mediator.resolver_context)
if file_entry is None:
... | 288,834 |
Sets the extraction configuration settings.
Args:
configuration (ExtractionConfiguration): extraction configuration. | def SetExtractionConfiguration(self, configuration):
self._hasher_file_size_limit = configuration.hasher_file_size_limit
self._SetHashers(configuration.hasher_names_string)
self._process_archives = configuration.process_archives
self._process_compressed_streams = configuration.process_compressed_st... | 288,835 |
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): identifier of the structure of tokens.
structure (pyparsing.ParseResults): structure of tokens d... | def _ParseLogLine(self, parser_mediator, structure, key):
time_elements_tuple = self._GetTimeElementsTuple(structure)
try:
date_time = dfdatetime_time_elements.TimeElements(
time_elements_tuple=time_elements_tuple)
except ValueError:
parser_mediator.ProduceExtractionWarning(
... | 288,838 |
Verify that this file is a Mac AppFirewall 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... | def VerifyStructure(self, parser_mediator, line):
self._last_month = 0
self._year_use = parser_mediator.GetEstimatedYear()
try:
structure = self.FIREWALL_LINE.parseString(line)
except pyparsing.ParseException as exception:
logger.debug((
'Unable to parse file as a Mac AppFire... | 288,839 |
Determines if a parser can process a file entry.
Args:
file_entry (dfvfs.FileEntry): file entry.
parser (BaseParser): parser.
Returns:
bool: True if the file entry can be processed by the parser object. | def _CheckParserCanProcessFileEntry(self, parser, file_entry):
for filter_object in parser.FILTERS:
if filter_object.Match(file_entry):
return True
return False | 288,841 |
Determines if a file-like object matches one of the known signatures.
Args:
file_object (file): file-like object whose contents will be checked
for known signatures.
Returns:
list[str]: parser names for which the contents of the file-like object
matches their known signatures. | def _GetSignatureMatchParserNames(self, file_object):
parser_names = []
scan_state = pysigscan.scan_state()
self._file_scanner.scan_file_object(scan_state, file_object)
for scan_result in iter(scan_state.scan_results):
format_specification = (
self._formats_with_signatures.GetSpeci... | 288,842 |
Parses a data stream of a file entry with a specific parser.
Args:
parser_mediator (ParserMediator): parser mediator.
parser (BaseParser): parser.
file_entry (dfvfs.FileEntry): file entry.
data_stream_name (str): data stream name.
Raises:
RuntimeError: if the file-like object is ... | def _ParseDataStreamWithParser(
self, parser_mediator, parser, file_entry, data_stream_name):
file_object = file_entry.GetFileObject(data_stream_name=data_stream_name)
if not file_object:
raise RuntimeError(
'Unable to retrieve file-like object from file entry.')
try:
self.... | 288,844 |
Parses a data stream of a file entry with the enabled parsers.
Args:
parser_mediator (ParserMediator): parser mediator.
file_entry (dfvfs.FileEntry): file entry.
data_stream_name (str): data stream name.
Raises:
RuntimeError: if the file-like object or the parser object is missing. | def ParseDataStream(self, parser_mediator, file_entry, data_stream_name):
file_object = file_entry.GetFileObject(data_stream_name=data_stream_name)
if not file_object:
raise RuntimeError(
'Unable to retrieve file-like object from file entry.')
try:
parser_names = self._GetSignatu... | 288,847 |
Parses the file entry metadata e.g. file system data.
Args:
parser_mediator (ParserMediator): parser mediator.
file_entry (dfvfs.FileEntry): file entry. | def ParseFileEntryMetadata(self, parser_mediator, file_entry):
if self._filestat_parser:
self._ParseFileEntryWithParser(
parser_mediator, self._filestat_parser, file_entry) | 288,848 |
Parses a metadata file.
Args:
parser_mediator (ParserMediator): parser mediator.
file_entry (dfvfs.FileEntry): file entry.
data_stream_name (str): data stream name. | def ParseMetadataFile(
self, parser_mediator, file_entry, data_stream_name):
parent_path_spec = getattr(file_entry.path_spec, 'parent', None)
filename_upper = file_entry.name.upper()
if (self._mft_parser and parent_path_spec and
filename_upper in ('$MFT', '$MFTMIRR') and not data_stream_n... | 288,849 |
Initializes a path specification extractor.
The source collector discovers all the file entries in the source.
The source can be a single file, directory or a volume within
a storage media image or device.
Args:
duplicate_file_check (Optional[bool]): True if duplicate files should
be i... | def __init__(self, duplicate_file_check=False):
super(PathSpecExtractor, self).__init__()
self._duplicate_file_check = duplicate_file_check
self._hashlist = {} | 288,850 |
Calculates an MD5 from the date and time value of a NTFS file entry.
Args:
file_entry (dfvfs.FileEntry): file entry.
Returns:
str: hexadecimal representation of the MD5 hash value of the date and
time values of the file entry. | def _CalculateNTFSTimeHash(self, file_entry):
date_time_values = []
access_time = getattr(file_entry, 'access_time', None)
if access_time:
date_time_string = access_time.CopyToDateTimeString()
date_time_values.append('atime:{0:s}'.format(date_time_string))
creation_time = getattr(file... | 288,851 |
Extracts path specification from a directory.
Args:
file_entry (dfvfs.FileEntry): file entry that refers to the directory.
depth (Optional[int]): current depth where 0 represents the file system
root.
Yields:
dfvfs.PathSpec: path specification of a file entry found in the directory... | def _ExtractPathSpecsFromDirectory(self, file_entry, depth=0):
if depth >= self._MAXIMUM_DEPTH:
raise errors.MaximumRecursionDepth('Maximum recursion depth reached.')
# Need to do a breadth-first search otherwise we'll hit the Python
# maximum recursion depth.
sub_directories = []
for s... | 288,853 |
Extracts path specification from a file.
Args:
file_entry (dfvfs.FileEntry): file entry that refers to the file.
Yields:
dfvfs.PathSpec: path specification of a file entry found in the file. | def _ExtractPathSpecsFromFile(self, file_entry):
produced_main_path_spec = False
for data_stream in file_entry.data_streams:
# Make a copy so we don't make the changes on a path specification
# directly. Otherwise already produced path specifications can be
# altered in the process.
... | 288,854 |
Extracts path specification from a specific source.
Args:
path_specs (Optional[list[dfvfs.PathSpec]]): path specifications.
find_specs (Optional[list[dfvfs.FindSpec]]): find specifications.
recurse_file_system (Optional[bool]): True if extraction should
recurse into a file system.
... | def ExtractPathSpecs(
self, path_specs, find_specs=None, recurse_file_system=True,
resolver_context=None):
for path_spec in path_specs:
for extracted_path_spec in self._ExtractPathSpecs(
path_spec, find_specs=find_specs,
recurse_file_system=recurse_file_system,
r... | 288,856 |
Initialize an OLECF property set stream.
Args:
olecf_item (pyolecf.property_set_stream): OLECF item. | def __init__(self, olecf_item):
super(OLECFPropertySetStream, self).__init__()
self._properties = {}
self.date_time_properties = {}
self._ReadPropertySet(olecf_item.set) | 288,857 |
Retrieves the property value as a Python object.
Args:
property_value (pyolecf.property_value): OLECF property value.
Returns:
object: property value as a Python object. | def _GetValueAsObject(self, property_value):
if property_value.type == pyolecf.value_types.BOOLEAN:
return property_value.data_as_boolean
if property_value.type in self._INTEGER_TYPES:
return property_value.data_as_integer
if property_value.type in self._STRING_TYPES:
return propert... | 288,858 |
Reads properties from a property set.
Args:
property_set (pyolecf.property_set): OLECF property set. | def _ReadPropertySet(self, property_set):
# Combine the values of multiple property sections
# but do not override properties that are already set.
for property_section in property_set.sections:
if property_section.class_identifier != self._CLASS_IDENTIFIER:
continue
for property_v... | 288,859 |
Retrieves the properties as event data.
Args:
data_type (str): event data type.
Returns:
EventData: event data. | def GetEventData(self, data_type):
event_data = events.EventData(data_type=data_type)
for property_name, property_value in iter(self._properties.items()):
if isinstance(property_value, py2to3.BYTES_TYPE):
property_value = repr(property_value)
setattr(event_data, property_name, property_... | 288,860 |
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. | def __init__(self, date_time, date_time_description):
super(OLECFDocumentSummaryInformationEvent, self).__init__(
date_time, date_time_description)
self.name = 'Document Summary Information' | 288,861 |
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. | def __init__(self, date_time, date_time_description):
super(OLECFSummaryInformationEvent, self).__init__(
date_time, date_time_description)
self.name = 'Summary Information' | 288,862 |
Parses a document summary information OLECF item.
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 ... | def Process(self, parser_mediator, root_item=None, **kwargs):
# This will raise if unhandled keyword arguments are passed.
super(DocumentSummaryInformationOLECFPlugin, self).Process(
parser_mediator, **kwargs)
if not root_item:
raise ValueError('Root item not set.')
root_creation_ti... | 288,863 |
Parses a summary information OLECF item.
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(SummaryInformationOLECFPlugin, self).Process(
parser_mediator, **kwargs)
if not root_item:
raise ValueError('Root item not set.')
root_creation_time, root... | 288,864 |
Initializes an artifact definitions filter helper.
Args:
artifacts_registry (artifacts.ArtifactDefinitionsRegistry): artifact
definitions registry.
knowledge_base (KnowledgeBase): contains information from the source
data needed for filtering. | def __init__(self, artifacts_registry, knowledge_base):
super(ArtifactDefinitionsFilterHelper, self).__init__()
self._artifacts_registry = artifacts_registry
self._knowledge_base = knowledge_base
self.file_system_artifact_names = set()
self.file_system_find_specs = []
self.registry_artifac... | 288,867 |
Checks if a Windows Registry key path is supported by dfWinReg.
Args:
key_path (str): path of the Windows Registry key.
Returns:
bool: True if key is compatible or False if not. | def CheckKeyCompatibility(cls, key_path):
key_path_upper = key_path.upper()
for key_path_prefix in cls._COMPATIBLE_REGISTRY_KEY_PATH_PREFIXES:
if key_path_upper.startswith(key_path_prefix):
return True
logger.warning('Key path: "{0:s}" is currently not supported'.format(
key_path... | 288,868 |
Builds find specifications from artifact definitions.
Args:
artifact_filter_names (list[str]): names of artifact definitions that are
used for filtering file system and Windows Registry key paths.
environment_variables (Optional[list[EnvironmentVariableArtifact]]):
environment varia... | def BuildFindSpecs(self, artifact_filter_names, environment_variables=None):
find_specs = []
for name in artifact_filter_names:
definition = self._artifacts_registry.GetDefinitionByName(name)
if not definition:
logger.debug('undefined artifact definition: {0:s}'.format(name))
co... | 288,869 |
Builds find specifications from an artifact definition.
Args:
definition (artifacts.ArtifactDefinition): artifact definition.
environment_variables (list[EnvironmentVariableArtifact]):
environment variables.
Returns:
list[dfvfs.FindSpec|dfwinreg.FindSpec]: dfVFS or dfWinReg find
... | def _BuildFindSpecsFromArtifact(self, definition, environment_variables):
find_specs = []
for source in definition.sources:
if source.type_indicator == artifact_types.TYPE_INDICATOR_FILE:
for path_entry in set(source.paths):
specifications = self._BuildFindSpecsFromFileSourcePath(
... | 288,870 |
Builds find specifications from a artifact group name.
Args:
group_name (str): artifact group name.
environment_variables (list[str]): environment variable attributes used to
dynamically populate environment variables in file and registry
artifacts.
Returns:
list[dfwinreg... | def _BuildFindSpecsFromGroupName(self, group_name, environment_variables):
definition = self._artifacts_registry.GetDefinitionByName(group_name)
if not definition:
return None
return self._BuildFindSpecsFromArtifact(definition, environment_variables) | 288,871 |
Build find specifications from a Windows Registry source type.
Args:
key_path (str): Windows Registry key path defined by the source.
Returns:
list[dfwinreg.FindSpec]: find specifications for the Windows Registry
source type. | def _BuildFindSpecsFromRegistrySourceKey(self, key_path):
find_specs = []
for key_path_glob in path_helper.PathHelper.ExpandRecursiveGlobs(
key_path, '\\'):
logger.debug('building find spec from key path glob: {0:s}'.format(
key_path_glob))
key_path_glob_upper = key_path_glob... | 288,873 |
Retrieves the page for the extension from the Chrome store website.
Args:
extension_identifier (str): Chrome extension identifier.
Returns:
str: page content or None. | def _GetChromeWebStorePage(self, extension_identifier):
web_store_url = self._WEB_STORE_URL.format(xid=extension_identifier)
try:
response = requests.get(web_store_url)
except (requests.ConnectionError, requests.HTTPError) as exception:
logger.warning((
'[{0:s}] unable to retriev... | 288,875 |
Given a path give back the path separator as a best guess.
Args:
path (str): path.
Returns:
str: path segment separator. | def _GetPathSegmentSeparator(self, path):
if path.startswith('\\') or path[1:].startswith(':\\'):
return '\\'
if path.startswith('/'):
return '/'
if '/' and '\\' in path:
# Let's count slashes and guess which one is the right one.
forward_count = len(path.split('/'))
bac... | 288,876 |
Retrieves the name of the extension from the Chrome store website.
Args:
extension_identifier (str): Chrome extension identifier.
Returns:
str: name of the extension or None. | def _GetTitleFromChromeWebStore(self, extension_identifier):
# Check if we have already looked this extension up.
if extension_identifier in self._extensions:
return self._extensions.get(extension_identifier)
page_content = self._GetChromeWebStorePage(extension_identifier)
if not page_conten... | 288,877 |
Compiles an analysis report.
Args:
mediator (AnalysisMediator): mediates interactions between analysis
plugins and other components, such as storage and dfvfs.
Returns:
AnalysisReport: analysis report. | def CompileReport(self, mediator):
lines_of_text = []
for user, extensions in sorted(self._results.items()):
lines_of_text.append(' == USER: {0:s} =='.format(user))
for extension, extension_identifier in sorted(extensions):
lines_of_text.append(' {0:s} [{1:s}]'.format(
exte... | 288,878 |
Analyzes an event.
Args:
mediator (AnalysisMediator): mediates interactions between analysis
plugins and other components, such as storage and dfvfs.
event (EventObject): event to examine. | def ExamineEvent(self, mediator, event):
# Only interested in filesystem events.
if event.data_type != 'fs:stat':
return
filename = getattr(event, 'filename', None)
if not filename:
return
# Determine if we have a Chrome extension ID.
if 'chrome' not in filename.lower():
... | 288,879 |
Returns a properly formatted message string.
Args:
event_object: the event object (instance od EventObject).
Returns:
A formatted message string. | def _GetMessage(self, event_object):
# TODO: move this somewhere where the mediator can be instantiated once.
formatter_mediator = formatters_mediator.FormatterMediator()
result = ''
try:
result, _ = formatters_manager.FormattersManager.GetMessageStrings(
formatter_mediator, event_... | 288,882 |
Returns properly formatted source strings.
Args:
event_object: the event object (instance od EventObject). | def _GetSources(self, event_object):
try:
source_short, source_long = (
formatters_manager.FormattersManager.GetSourceStrings(event_object))
except KeyError as exception:
logging.warning(
'Unable to correctly assemble event with error: {0!s}'.format(
exception)... | 288,883 |
Compiles the filter implementation.
Args:
filter_implementation: a filter object (instance of objectfilter.TODO).
Returns:
A filter operator (instance of TODO).
Raises:
ParserError: if an unknown operator is provided. | def Compile(self, filter_implementation):
self.attribute = self.swap_source.get(self.attribute, self.attribute)
arguments = [self.attribute]
op_str = self.operator.lower()
operator = filter_implementation.OPS.get(op_str, None)
if not operator:
raise errors.ParseError('Unknown operator {0... | 288,885 |
Take a date object and use that for comparison.
Args:
data: A string, datetime object or an integer containing the number
of micro seconds since January 1, 1970, 00:00:00 UTC.
Raises:
ValueError: if the date string is invalid. | def __init__(self, data):
if isinstance(data, py2to3.INTEGER_TYPES):
self.data = data
self.text = '{0:d}'.format(data)
elif isinstance(data, float):
self.data = py2to3.LONG_TYPE(data)
self.text = '{0:f}'.format(data)
elif isinstance(data, py2to3.STRING_TYPES):
if isinsta... | 288,886 |
Parses a log line.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
structure (pyparsing.ParseResults): structure of tokens derived from
a line of a text file. | def _ParseLogLine(self, parser_mediator, structure):
try:
date_time = dfdatetime_time_elements.TimeElements(
time_elements_tuple=structure.date_time)
# TODO: check if date and time values are local time or in UTC.
date_time.is_local_time = True
except ValueError:
parser_me... | 288,892 |
Verify that this file is a Sophos Anti-Virus 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 ... | def VerifyStructure(self, parser_mediator, line):
try:
structure = self._LOG_LINE.parseString(line)
except pyparsing.ParseException:
logger.debug('Not a Sophos Anti-Virus log file')
return False
# Expect spaces at position 9 and 16.
if ' ' not in (line[8], line[15]):
logger... | 288,893 |
Retrieves a property value.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
properties (dict[str, object]): properties.
property_name (str): name of the property.
Returns:
str: property value. | def _GetPropertyValue(self, parser_mediator, properties, property_name):
property_value = properties.get(property_name, None)
if isinstance(property_value, py2to3.BYTES_TYPE):
try:
# TODO: get encoding form XML metadata.
property_value = property_value.decode('utf-8')
except Uni... | 288,895 |
Formats a camel case property name as snake case.
Args:
property_name (str): property name in camel case.
Returns:
str: property name in snake case. | def _FormatPropertyName(self, property_name):
# TODO: Add Unicode support.
fix_key = re.sub(r'(.)([A-Z][a-z]+)', r'\1_\2', property_name)
return re.sub(r'([a-z0-9])([A-Z])', r'\1_\2', fix_key).lower() | 288,896 |
Parses a properties XML file.
Args:
xml_data (bytes): data of a _rels/.rels XML file.
Returns:
dict[str, object]: properties.
Raises:
zipfile.BadZipfile: if the properties XML file cannot be read. | def _ParsePropertiesXMLFile(self, xml_data):
xml_root = ElementTree.fromstring(xml_data)
properties = {}
for xml_element in xml_root.iter():
if not xml_element.text:
continue
# The property name is formatted as: {URL}name
# For example: {http://purl.org/dc/terms/}modified
... | 288,897 |
Parses the relationships XML file (_rels/.rels).
Args:
xml_data (bytes): data of a _rels/.rels XML file.
Returns:
list[str]: property file paths. The path is relative to the root of
the ZIP file.
Raises:
zipfile.BadZipfile: if the relationship XML file cannot be read. | def _ParseRelationshipsXMLFile(self, xml_data):
xml_root = ElementTree.fromstring(xml_data)
property_files = []
for xml_element in xml_root.iter():
type_attribute = xml_element.get('Type')
if 'properties' in repr(type_attribute):
target_attribute = xml_element.get('Target')
... | 288,898 |
Parses an OXML file-like object.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
zip_file (zipfile.ZipFile): the zip file containing OXML content. It is
not be closed in this method, but will be closed by... | def InspectZipFile(self, parser_mediator, zip_file):
try:
xml_data = zip_file.read('_rels/.rels')
property_files = self._ParseRelationshipsXMLFile(xml_data)
except (IndexError, IOError, KeyError, OverflowError, ValueError,
zipfile.BadZipfile) as exception:
parser_mediator.Prod... | 288,900 |
Copies the attribute container from a dictionary.
Args:
attributes (dict[str, object]): attribute values per name. | def CopyFromDict(self, attributes):
for attribute_name, attribute_value in attributes.items():
# Not using startswith to improve performance.
if attribute_name[0] == '_':
continue
setattr(self, attribute_name, attribute_value) | 288,903 |
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):
installation_value = None
string_values = {}
for registry_value in registry_key.GetValues():
# Ignore the default value.
if not registry_value.name:
continue
if (registry_value.name == 'InstallDate' and
... | 288,908 |
Parses a matching entry.
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): elements parsed from the file.
Raises:
ParseError... | 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))
if key == 'quota_exceeded_line':
# skip this line
return
date_time = dfdatetime_time_element... | 288,912 |
Attempts to send an item to a ZeroMQ socket.
Args:
zmq_socket (zmq.Socket): used to the send the item.
item (object): sent on the queue. Will be pickled prior to sending.
block (Optional[bool]): whether the push should be performed in blocking
or non-blocking mode.
Returns:
b... | def _SendItem(self, zmq_socket, item, block=True):
try:
logger.debug('{0:s} sending item'.format(self.name))
if block:
zmq_socket.send_pyobj(item)
else:
zmq_socket.send_pyobj(item, zmq.DONTWAIT)
logger.debug('{0:s} sent item'.format(self.name))
return True
exc... | 288,914 |
Attempts to receive an item from a ZeroMQ socket.
Args:
zmq_socket (zmq.Socket): used to the receive the item.
Returns:
object: item from the socket.
Raises:
QueueEmpty: if no item could be received within the timeout.
zmq.error.ZMQError: if an error occurs in ZeroMQ | def _ReceiveItemOnActivity(self, zmq_socket):
events = zmq_socket.poll(
self._ZMQ_SOCKET_RECEIVE_TIMEOUT_MILLISECONDS)
if events:
try:
received_object = self._zmq_socket.recv_pyobj()
return received_object
except zmq.error.Again:
logger.error(
'{0:s}... | 288,915 |
Closes the queue.
Args:
abort (Optional[bool]): whether the Close is the result of an abort
condition. If True, queue contents may be lost.
Raises:
QueueAlreadyClosed: if the queue is not started, or has already been
closed.
RuntimeError: if closed or terminate event is m... | def Close(self, abort=False):
if not self._closed_event or not self._terminate_event:
raise RuntimeError('Missing closed or terminate event.')
if not abort and self._closed_event.is_set():
raise errors.QueueAlreadyClosed()
self._closed_event.set()
if abort:
if not self._closed_... | 288,918 |
Closes the queue.
Args:
abort (Optional[bool]): whether the Close is the result of an abort
condition. If True, queue contents may be lost.
Raises:
QueueAlreadyClosed: if the queue is not started, or has already been
closed.
RuntimeError: if closed or terminate event is m... | def Close(self, abort=False):
if not self._closed_event or not self._terminate_event:
raise RuntimeError('Missing closed or terminate event.')
if not abort and self._closed_event.is_set():
raise errors.QueueAlreadyClosed()
self._closed_event.set()
if abort:
if not self._closed_... | 288,924 |
Listens for requests and replies to clients.
Args:
source_queue (Queue.queue): queue to use to pull items from.
Raises:
RuntimeError: if closed or terminate event is missing. | def _ZeroMQResponder(self, source_queue):
if not self._closed_event or not self._terminate_event:
raise RuntimeError('Missing closed or terminate event.')
logger.debug('{0:s} responder thread started'.format(self.name))
item = None
while not self._terminate_event.is_set():
if not item... | 288,925 |
Deregisters an output class.
The output classes are identified based on their NAME attribute.
Args:
output_class (type): output module class.
Raises:
KeyError: if output class is not set for the corresponding data type. | def DeregisterOutput(cls, output_class):
output_class_name = output_class.NAME.lower()
if output_class_name in cls._disabled_output_classes:
class_dict = cls._disabled_output_classes
else:
class_dict = cls._output_classes
if output_class_name not in class_dict:
raise KeyError(
... | 288,927 |
Retrieves the output class for a specific name.
Args:
name (str): name of the output module.
Returns:
type: output module class.
Raises:
KeyError: if there is no output class found with the supplied name.
ValueError: if name is not a string. | def GetOutputClass(cls, name):
if not isinstance(name, py2to3.STRING_TYPES):
raise ValueError('Name attribute is not a string.')
name = name.lower()
if name not in cls._output_classes:
raise KeyError(
'Name: [{0:s}] not registered as an output module.'.format(name))
return c... | 288,929 |
Determines if a specific output class is registered with the manager.
Args:
name (str): name of the output module.
Returns:
bool: True if the output class is registered. | def HasOutputClass(cls, name):
if not isinstance(name, py2to3.STRING_TYPES):
return False
return name.lower() in cls._output_classes | 288,931 |
Determines if a specific output class is a linear output module.
Args:
name (str): name of the output module.
Returns:
True: if the output module is linear. | def IsLinearOutputModule(cls, name):
name = name.lower()
output_class = cls._output_classes.get(name, None)
if not output_class:
output_class = cls._disabled_output_classes.get(name, None)
if output_class:
return issubclass(output_class, interface.LinearOutputModule)
return False | 288,932 |
Creates a new output module object for the specified output format.
Args:
name (str): name of the output module.
output_mediator (OutputMediator): output mediator.
Returns:
OutputModule: output module.
Raises:
KeyError: if there is no output class found with the supplied name.
... | def NewOutputModule(cls, name, output_mediator):
output_class = cls.GetOutputClass(name)
return output_class(output_mediator) | 288,933 |
Registers an output class.
The output classes are identified based on their NAME attribute.
Args:
output_class (type): output module class.
disabled (Optional[bool]): True if the output module is disabled due to
the module not loading correctly or not.
Raises:
KeyError: if out... | def RegisterOutput(cls, output_class, disabled=False):
output_name = output_class.NAME.lower()
if disabled:
class_dict = cls._disabled_output_classes
else:
class_dict = cls._output_classes
if output_name in class_dict:
raise KeyError((
'Output class already set for nam... | 288,934 |
Registers output classes.
The output classes are identified based on their NAME attribute.
Args:
output_classes (list[type]): output module classes.
disabled (Optional[bool]): True if the output module is disabled due to
the module not loading correctly or not.
Raises:
KeyErro... | def RegisterOutputs(cls, output_classes, disabled=False):
for output_class in output_classes:
cls.RegisterOutput(output_class, disabled) | 288,935 |
Initializes a sample file profiler.
Sample files are gzip compressed UTF-8 encoded CSV files.
Args:
identifier (str): identifier of the profiling session used to create
the sample filename.
configuration (ProfilingConfiguration): profiling configuration. | def __init__(self, identifier, configuration):
super(SampleFileProfiler, self).__init__()
self._identifier = identifier
self._path = configuration.directory
self._profile_measurements = {}
self._sample_file = None
self._start_time = None | 288,939 |
Writes a string to the sample file.
Args:
content (str): content to write to the sample file. | def _WritesString(self, content):
content_bytes = codecs.encode(content, 'utf-8')
self._sample_file.write(content_bytes) | 288,940 |
Starts timing CPU time.
Args:
profile_name (str): name of the profile to sample. | def StartTiming(self, profile_name):
if profile_name not in self._profile_measurements:
self._profile_measurements[profile_name] = CPUTimeMeasurement()
self._profile_measurements[profile_name].SampleStart() | 288,942 |
Stops timing CPU time.
Args:
profile_name (str): name of the profile to sample. | def StopTiming(self, profile_name):
measurements = self._profile_measurements.get(profile_name)
if measurements:
measurements.SampleStop()
sample = '{0:f}\t{1:s}\t{2:f}\n'.format(
measurements.start_sample_time, profile_name,
measurements.total_cpu_time)
self._WritesS... | 288,943 |
Initializes a memory profiler.
Args:
identifier (str): unique name of the profile.
configuration (ProfilingConfiguration): profiling configuration. | def __init__(self, identifier, configuration):
super(GuppyMemoryProfiler, self).__init__()
self._identifier = identifier
self._path = configuration.directory
self._profiling_sample = 0
self._profiling_sample_rate = configuration.sample_rate
self._heapy = None
self._sample_file = '{0!s}.... | 288,944 |
Takes a sample for profiling.
Args:
profile_name (str): name of the profile to sample.
used_memory (int): amount of used memory in bytes. | def Sample(self, profile_name, used_memory):
sample_time = time.time()
sample = '{0:f}\t{1:s}\t{2:d}\n'.format(
sample_time, profile_name, used_memory)
self._WritesString(sample) | 288,947 |
Takes a sample of data read or written for profiling.
Args:
operation (str): operation, either 'read' or 'write'.
description (str): description of the data read.
data_size (int): size of the data read in bytes.
compressed_data_size (int): size of the compressed data read in bytes. | def Sample(self, operation, description, data_size, compressed_data_size):
sample_time = time.time()
sample = '{0:f}\t{1:s}\t{2:s}\t{3:d}\t{4:d}\n'.format(
sample_time, operation, description, data_size, compressed_data_size)
self._WritesString(sample) | 288,948 |
Takes a sample of the status of queued tasks for profiling.
Args:
tasks_status (TasksStatus): status information about tasks. | def Sample(self, tasks_status):
sample_time = time.time()
sample = '{0:f}\t{1:d}\t{2:d}\t{3:d}\t{4:d}\t{5:d}\n'.format(
sample_time, tasks_status.number_of_queued_tasks,
tasks_status.number_of_tasks_processing,
tasks_status.number_of_tasks_pending_merge,
tasks_status.number_... | 288,949 |
Takes a sample of the status of a task for profiling.
Args:
task (Task): a task.
status (str): status. | def Sample(self, task, status):
sample_time = time.time()
sample = '{0:f}\t{1:s}\t{2:s}\n'.format(
sample_time, task.identifier, status)
self._WritesString(sample) | 288,950 |
Initializes a Timesketch output module.
Args:
output_mediator (OutputMediator): mediates interactions between output
modules and other components, such as storage and dfvfs. | def __init__(self, output_mediator):
hostname = output_mediator.GetStoredHostname()
if hostname:
logger.debug('Hostname: {0:s}'.format(hostname))
super(TimesketchOutputModule, self).__init__(output_mediator)
self._timeline_name = hostname
self._timeline_owner = None
self._timesketch ... | 288,951 |
Sets the timeline name.
Args:
timeline_name (str): timeline name. | def SetTimelineName(self, timeline_name):
self._timeline_name = timeline_name
logger.info('Timeline name: {0:s}'.format(self._timeline_name)) | 288,953 |
Sets the username of the user that should own the timeline.
Args:
username (str): username. | def SetTimelineOwner(self, username):
self._timeline_owner = username
logger.info('Owner of the timeline: {0!s}'.format(self._timeline_owner)) | 288,954 |
Extract relevant information from HTTP header.
Args:
header_data (bytes): HTTP header data.
offset (int): offset of the cache record, relative to the start of
the Firefox cache file.
display_name (str): display name of the Firefox cache file.
Returns:
tuple: containing:
... | def _ParseHTTPHeaders(self, header_data, offset, display_name):
header_string = header_data.decode('ascii', errors='replace')
try:
http_header_start = header_string.index('request-method')
except ValueError:
logger.debug('No request method in header: "{0:s}"'.format(header_string))
r... | 288,957 |
Determine cache file block size.
Args:
file_object (dfvfs.FileIO): a file-like object.
display_name (str): display name.
Returns:
firefox_cache_config: namedtuple containing the block size and first
record offset.
Raises:
UnableToParseFile: if no valid cache record could... | def _GetFirefoxConfig(self, file_object, display_name):
# There ought to be a valid record within the first 4 MiB. We use this
# limit to prevent reading large invalid files.
to_read = min(file_object.get_size(), self._INITIAL_CACHE_FILE_SIZE)
while file_object.get_offset() < to_read:
offset... | 288,958 |
Parses a cache entry.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
file_object (dfvfs.FileIO): a file-like object.
display_name (str): display name.
block_size (int): block size. | def _ParseCacheEntry(
self, parser_mediator, file_object, display_name, block_size):
cache_entry, event_data = self._ReadCacheEntry(
file_object, display_name, block_size)
date_time = dfdatetime_posix_time.PosixTime(
timestamp=cache_entry.last_fetched_time)
event = time_events.Da... | 288,959 |
Determines whether the values in the cache entry header are valid.
Args:
cache_entry_header (firefox_cache1_entry_header): cache entry header.
Returns:
bool: True if the cache entry header is valid. | def _ValidateCacheEntryHeader(self, cache_entry_header):
return (
cache_entry_header.request_size > 0 and
cache_entry_header.request_size < self._MAXIMUM_URL_LENGTH and
cache_entry_header.major_format_version == 1 and
cache_entry_header.last_fetched_time > 0 and
cache_en... | 288,961 |
Parses a Firefox cache 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):
filename = parser_mediator.GetFilename()
if (not self._CACHE_FILENAME_RE.match(filename) and
not filename.startswith('_CACHE_00')):
raise errors.UnableToParseFile('Not a Firefox cache1 file.')
display_name = parser_mediator.GetDis... | 288,962 |
Determines the offset of the cache file metadata header.
This method is inspired by the work of James Habben:
https://github.com/JamesHabben/FirefoxCache2
Args:
file_object (dfvfs.FileIO): a file-like object.
Returns:
int: offset of the file cache metadata header relative to the start
... | def _GetCacheFileMetadataHeaderOffset(self, file_object):
file_object.seek(-4, os.SEEK_END)
file_offset = file_object.tell()
metadata_size_map = self._GetDataTypeMap('uint32be')
try:
metadata_size, _ = self._ReadStructureFromFileObject(
file_object, file_offset, metadata_size_map)... | 288,963 |
Determines whether the cache file metadata header is valid.
Args:
cache_file_metadata_header (firefox_cache2_file_metadata_header): cache
file metadata header.
Returns:
bool: True if the cache file metadata header is valid. | def _ValidateCacheFileMetadataHeader(self, cache_file_metadata_header):
# TODO: add support for format version 2 and 3
return (
cache_file_metadata_header.key_size > 0 and
cache_file_metadata_header.key_size < self._MAXIMUM_URL_LENGTH and
cache_file_metadata_header.format_version ==... | 288,964 |
Parses a Firefox cache 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):
filename = parser_mediator.GetFilename()
if not self._CACHE_FILENAME_RE.match(filename):
raise errors.UnableToParseFile('Not a Firefox cache2 file.')
# The file needs to be at least 36 bytes in size for it to contain
# a cache2 file me... | 288,965 |
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(PsortTool, self).__init__(
input_reader=input_reader, output_writer=output_writer)
self._analysis_manager = analysis_manager.AnalysisPluginManager
self._analysis_plugins = None
self._analysis_plugins_output_format = None
s... | 288,966 |
Checks if the storage file path is valid.
Args:
storage_file_path (str): path of the storage file.
Raises:
BadConfigOption: if the storage file path is invalid. | def _CheckStorageFile(self, storage_file_path): # pylint: disable=arguments-differ
if os.path.exists(storage_file_path):
if not os.path.isfile(storage_file_path):
raise errors.BadConfigOption(
'Storage file: {0:s} already exists and is not a file.'.format(
storage_fil... | 288,967 |
Retrieves analysis plugins.
Args:
analysis_plugins_string (str): comma separated names of analysis plugins
to enable.
Returns:
list[AnalysisPlugin]: analysis plugins. | def _GetAnalysisPlugins(self, analysis_plugins_string):
if not analysis_plugins_string:
return []
analysis_plugins_list = [
name.strip() for name in analysis_plugins_string.split(',')]
analysis_plugins = self._analysis_manager.GetPluginObjects(
analysis_plugins_list)
return ... | 288,968 |
Parses the analysis plugin options.
Args:
options (argparse.Namespace): command line arguments. | def _ParseAnalysisPluginOptions(self, options):
# Get a list of all available plugins.
analysis_plugin_info = self._analysis_manager.GetAllPluginInformation()
# Use set-comprehension to create a set of the analysis plugin names.
analysis_plugin_names = {
name.lower() for name, _, _ in analy... | 288,969 |
Parses the filter options.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid. | def _ParseFilterOptions(self, options):
self._event_filter_expression = self.ParseStringOption(options, 'filter')
if self._event_filter_expression:
self._event_filter = event_filter.EventObjectFilter()
try:
self._event_filter.CompileFilter(self._event_filter_expression)
except er... | 288,970 |
Parses the informational options.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid. | def _ParseInformationalOptions(self, options):
super(PsortTool, self)._ParseInformationalOptions(options)
self._quiet_mode = getattr(options, 'quiet', False)
helpers_manager.ArgumentHelperManager.ParseOptions(
options, self, names=['status_view']) | 288,971 |
Parses the processing options.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid. | def _ParseProcessingOptions(self, options):
argument_helper_names = [
'process_resources', 'temporary_directory', 'zeromq']
helpers_manager.ArgumentHelperManager.ParseOptions(
options, self, names=argument_helper_names)
worker_memory_limit = getattr(options, 'worker_memory_limit', None... | 288,972 |
Adds processing options to the argument group
Args:
argument_group (argparse._ArgumentGroup): argparse argument group. | def AddProcessingOptions(self, argument_group):
argument_helper_names = ['temporary_directory', 'zeromq']
if self._CanEnforceProcessMemoryLimit():
argument_helper_names.append('process_resources')
helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
argument_group, names=argumen... | 288,973 |
Parses the options.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid. | def ParseOptions(self, options):
# The output modules options are dependent on the preferred language
# and preferred time zone options.
self._ParseTimezoneOption(options)
names = ['analysis_plugins', 'language', 'profiling']
helpers_manager.ArgumentHelperManager.ParseOptions(
options,... | 288,975 |
Initializes an event object.
Args:
uuid (uuid.UUID): UUID.
origin (str): origin of the event (event source).
E.g. the path of the corresponding LNK file or file reference
MFT entry with the corresponding NTFS $OBJECT_ID attribute.
Raises:
ValueError: if the UUID version i... | def __init__(self, uuid, origin):
if uuid.version != 1:
raise ValueError('Unsupported UUID version.')
mac_address = '{0:s}:{1:s}:{2:s}:{3:s}:{4:s}:{5:s}'.format(
uuid.hex[20:22], uuid.hex[22:24], uuid.hex[24:26], uuid.hex[26:28],
uuid.hex[28:30], uuid.hex[30:32])
super(WindowsDi... | 288,977 |
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')
yara_rules_string = None
path = getattr(options, 'yara_rules_path', None)
if path:
... | 288,985 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.