docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Creates an object that reads lines from a text file. The line reader is advanced to the beginning of the DSV content, skipping any header lines. Args: file_object (dfvfs.FileIO): file-like object. Returns: TextFile|BinaryLineReader: an object that implements an iterator over lin...
def _CreateLineReader(self, file_object): # The Python 2 csv module reads bytes and the Python 3 csv module Unicode # reads strings. if py2to3.PY_3: line_reader = text_file.TextFile( file_object, encoding=self._encoding, end_of_line=self._end_of_line) # pylint: disable=protected-...
288,678
Determines if a file begins with lines of the expected length. As we know the maximum length of valid lines in the DSV file, the presence of lines longer than this indicates that the file will not be parsed successfully, without reading excessive data from a large file. Args: file_object (dfvfs....
def _HasExpectedLineLength(self, file_object): original_file_position = file_object.tell() line_reader = self._CreateLineReader(file_object) for _ in range(0, 20): # Attempt to read a line that is longer than any line that should be in # the file. sample_line = line_reader.readline(se...
288,679
Parses a DSV text 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): # TODO: Replace this with detection of the file encoding via byte-order # marks. Also see: https://github.com/log2timeline/plaso/issues/1971 if not self._encoding: self._encoding = parser_mediator.codepage try: if not self._HasEx...
288,680
Parses an Amcache.hve file for events. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): file-like object.
def ParseFileObject(self, parser_mediator, file_object): regf_file = pyregf.file() # pylint: disable=no-member try: regf_file.open_file_object(file_object) except IOError: # The error is currently ignored -> see TODO above related to the # fixing of handling multiple parsers for the s...
288,683
Parses an Amcache Root/Programs key for events. Args: am_entry (pyregf.key): amcache Programs key. parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs.
def _ProcessAMCacheProgramKey(self, am_entry, parser_mediator): amcache_datetime = am_entry.get_value_by_name( self._AMCACHE_P_INSTALLDATE).get_data_as_integer() event_data = AmcacheProgramEventData() name = am_entry.get_value_by_name(self._AMCACHE_P_NAME) if name: event_data.name = ...
288,684
Parses an Amcache Root/File key for events. Args: am_entry (pyregf.key): amcache File key. parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs.
def _ProcessAMCacheFileKey(self, am_entry, parser_mediator): amcache_datetime = am_entry.get_value_by_name( self._AMCACHE_DATETIME).get_data_as_integer() event_data = AmcacheEventData() event_data.full_path = am_entry.get_value_by_name( self._AMCACHE_FULL_PATH).get_data_as_string() ...
288,685
Initializes an nsrlsvr analyzer thread. Args: hash_queue (Queue.queue): contains hashes to be analyzed. hash_analysis_queue (Queue.queue): that the analyzer will append HashAnalysis objects this queue.
def __init__(self, hash_queue, hash_analysis_queue, **kwargs): super(NsrlsvrAnalyzer, self).__init__( hash_queue, hash_analysis_queue, **kwargs) self._host = None self._port = None self.hashes_per_batch = 100
288,686
Queries nsrlsvr for a specific hash. Args: nsrl_socket (socket._socketobject): socket of connection to nsrlsvr. digest (str): hash to look up. Returns: bool: True if the hash was found, False if not or None on error.
def _QueryHash(self, nsrl_socket, digest): try: query = 'QUERY {0:s}\n'.format(digest).encode('ascii') except UnicodeDecodeError: logger.error('Unable to encode digest: {0!s} to ASCII.'.format(digest)) return False response = None try: nsrl_socket.sendall(query) resp...
288,688
Looks up hashes in nsrlsvr. Args: hashes (list[str]): hash values to look up. Returns: list[HashAnalysis]: analysis results, or an empty list on error.
def Analyze(self, hashes): logger.debug( 'Opening connection to {0:s}:{1:d}'.format(self._host, self._port)) nsrl_socket = self._GetSocket() if not nsrl_socket: self.SignalAbort() return [] hash_analyses = [] for digest in hashes: response = self._QueryHash(nsrl_sock...
288,689
Extracts relevant TimeMachine 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): backup_alias_map = self._GetDataTypeMap('timemachine_backup_alias') destinations = match.get('Destinations', []) for destination in destinations: backup_alias_data = destination.get('BackupAlias', b'') try: backup_...
288,691
Retrieves the Id value from Task Cache Tree key. Args: registry_key (dfwinreg.WinRegistryKey): Windows Registry key. Yields: tuple: containing: dfwinreg.WinRegistryKey: Windows Registry key. dfwinreg.WinRegistryValue: Windows Registry value.
def _GetIdValue(self, registry_key): id_value = registry_key.GetValueByName('Id') if id_value: yield registry_key, id_value for sub_key in registry_key.GetSubkeys(): for value_key, id_value in self._GetIdValue(sub_key): yield value_key, id_value
288,693
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): dynamic_info_size_error_reported = False tasks_key = registry_key.GetSubkeyByName('Tasks') tree_key = registry_key.GetSubkeyByName('Tree') if not tasks_key or not tree_key: parser_mediator.ProduceExtractionWarning( ...
288,694
Verifies a PLS Recall record. Args: pls_record (pls_recall_record): a PLS Recall record to verify. Returns: bool: True if this is a valid PLS Recall record, False otherwise.
def _VerifyRecord(self, pls_record): # Verify that the timestamp is no more than six years into the future. # Six years is an arbitrary time length just to evaluate the timestamp # against some value. There is no guarantee that this will catch everything. # TODO: Add a check for similarly valid val...
288,696
Parses a PLSRecall.dat 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): file_offset = 0 file_size = file_object.get_size() record_map = self._GetDataTypeMap('pls_recall_record') while file_offset < file_size: try: pls_record, record_data_size = self._ReadStructureFromFileObject( file_ob...
288,697
Determines the formatted message strings for an event object. Args: formatter_mediator (FormatterMediator): mediates the interactions between formatters and other components, such as storage and Windows EventLog resources. event (EventObject): event. Returns: tuple(str, s...
def GetMessages(self, formatter_mediator, event): if self.DATA_TYPE != event.data_type: raise errors.WrongFormatter('Unsupported data type: {0:s}.'.format( event.data_type)) event_values = event.CopyToDict() regvalue = event_values.get('regvalue', {}) string_parts = [] for key...
288,698
Determines the the short and long source for an event object. Args: event (EventObject): event. Returns: tuple(str, str): short and long source string. Raises: WrongFormatter: if the event object cannot be formatted by the formatter.
def GetSources(self, event): if self.DATA_TYPE != event.data_type: raise errors.WrongFormatter('Unsupported data type: {0:s}.'.format( event.data_type)) source_long = getattr(event, 'source_long', 'UNKNOWN') source_append = getattr(event, 'source_append', None) if source_append: ...
288,699
Analyzes an event and extracts domains from it. We only evaluate straightforward web history events, not visits which can be inferred by TypedURLs, cookies or other means. Args: mediator (AnalysisMediator): mediates interactions between analysis plugins and other components, such as storag...
def ExamineEvent(self, mediator, event): if event.data_type not in self._DATATYPES: return url = getattr(event, 'url', None) if url is None: return parsed_url = urlparse.urlparse(url) domain = getattr(parsed_url, 'netloc', None) if domain in self._domains: # We've already...
288,700
Compiles an analysis report. Args: mediator (AnalysisMediator): mediates interactions between analysis plugins and other components, such as storage and dfvfs. Returns: AnalysisReport: the analysis report.
def CompileReport(self, mediator): lines_of_text = ['Listing domains visited by all users'] for domain in sorted(self._domains): lines_of_text.append(domain) lines_of_text.append('') report_text = '\n'.join(lines_of_text) return reports.AnalysisReport(plugin_name=self.NAME, text=report_t...
288,701
Determines if a Windows Registry key matches the filter. Args: registry_key (dfwinreg.WinRegistryKey): Windows Registry key. Returns: bool: True if the Windows Registry key matches the filter.
def Match(self, registry_key): key_path_upper = registry_key.path.upper() # Prevent this filter matching non-string MRUListEx values. for ignore_key_path_suffix in self._IGNORE_KEY_PATH_SUFFIXES: if key_path_upper.endswith(ignore_key_path_suffix): return False for ignore_key_path_seg...
288,702
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. codepage (Optional[str]): extended ASCII stri...
def _ParseMRUListExKey( self, parser_mediator, registry_key, codepage='cp1252'): try: mrulistex = self._ParseMRUListExValue(registry_key) except (ValueError, errors.ParseError) as exception: parser_mediator.ProduceExtractionWarning( 'unable to parse MRUListEx value with error: {...
288,703
Parses the MRUListEx entry value. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg.WinRegistryKey): Windows Registry key that contains the MRUListEx value. entry_index (int): ...
def _ParseMRUListExEntryValue( self, parser_mediator, registry_key, entry_index, entry_number, **kwargs): value_string = '' value = registry_key.GetValueByName('{0:d}'.format(entry_number)) if value is None: parser_mediator.ProduceExtractionWarning( 'missing MRUListEx value: {0:d...
288,704
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._ParseMRUListExKey(parser_mediator, registry_key, codepage=codepage)
288,705
Parses the MRUListEx entry value. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg.WinRegistryKey): Windows Registry key that contains the MRUListEx value. entry_index (int): ...
def _ParseMRUListExEntryValue( self, parser_mediator, registry_key, entry_index, entry_number, codepage='cp1252', **kwargs): value_string = '' value = registry_key.GetValueByName('{0:d}'.format(entry_number)) if value is None: parser_mediator.ProduceExtractionWarning( 'miss...
288,706
Parses the MRUListEx entry value. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg.WinRegistryKey): Windows Registry key that contains the MRUListEx value. entry_index (int): ...
def _ParseMRUListExEntryValue( self, parser_mediator, registry_key, entry_index, entry_number, codepage='cp1252', **kwargs): value_string = '' value = registry_key.GetValueByName('{0:d}'.format(entry_number)) if value is None: parser_mediator.ProduceExtractionWarning( 'miss...
288,707
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._ParseMRUListExKey(parser_mediator, registry_key, codepage=codepage) if registry_key.name == 'RecentDocs': # For the RecentDocs MRUListEx we also need to parse its subkeys # since the Registry key ...
288,708
Parses a comment. Args: structure (pyparsing.ParseResults): structure parsed from the log file.
def _ParseComment(self, structure): if structure[1] == 'Date:': self._year, self._month, self._day_of_month, _, _, _ = structure.date_time elif structure[1] == 'Fields:': self._ParseFieldsMetadata(structure)
288,710
Parses the fields metadata and updates the log line definition to match. Args: structure (pyparsing.ParseResults): structure parsed from the log file.
def _ParseFieldsMetadata(self, structure): fields = structure.fields.split(' ') log_line_structure = pyparsing.Empty() if fields[0] == 'date' and fields[1] == 'time': log_line_structure += self.DATE_TIME.setResultsName('date_time') fields = fields[2:] for member in fields: log_l...
288,711
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. structure (pyparsing.ParseResults): structure parsed from the log file.
def _ParseLogLine(self, parser_mediator, structure): if structure.date_time: time_elements_tuple = structure.date_time elif structure.date and structure.time: year, month, day_of_month = structure.date hours, minutes, seconds = structure.time time_elements_tuple = (year, month, day...
288,712
Verify that this file is an IIS 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): # TODO: self._line_structures is a work-around and this needs # a structural fix. self._line_structures = self.LINE_STRUCTURES self._day_of_month = None self._month = None self._year = None # TODO: Examine other versions of the file fo...
288,713
Extracts a container or a graph ID from a JSON file's path. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. Returns: str: container or graph identifier.
def _GetIdentifierFromPath(self, parser_mediator): file_entry = parser_mediator.GetFileEntry() path = file_entry.path_spec.location file_system = file_entry.GetFileSystem() path_segments = file_system.SplitPath(path) return path_segments[-2]
288,717
Extracts events from a Docker filesystem layer configuration file. The path of each filesystem layer config file is: DOCKER_DIR/graph/<layer_id>/json Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_ob...
def _ParseLayerConfigJSON(self, parser_mediator, file_object): file_content = file_object.read() file_content = codecs.decode(file_content, self._ENCODING) json_dict = json.loads(file_content) if 'docker_version' not in json_dict: raise errors.UnableToParseFile( 'not a valid Docke...
288,718
Extracts events from a Docker container configuration file. The path of each container config file is: DOCKER_DIR/containers/<container_id>/config.json Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_...
def _ParseContainerConfigJSON(self, parser_mediator, file_object): file_content = file_object.read() file_content = codecs.decode(file_content, self._ENCODING) json_dict = json.loads(file_content) if 'Driver' not in json_dict: raise errors.UnableToParseFile( 'not a valid Docker co...
288,719
Extract events from a Docker container log files. The format is one JSON formatted log message per line. The path of each container log file (which logs the container stdout and stderr) is: DOCKER_DIR/containers/<container_id>/<container_id>-json.log Args: parser_mediator (ParserMediator): ...
def _ParseContainerLogJSON(self, parser_mediator, file_object): container_id = self._GetIdentifierFromPath(parser_mediator) text_file_object = text_file.TextFile(file_object) for log_line in text_file_object: json_log_line = json.loads(log_line) time = json_log_line.get('time', None) ...
288,720
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 ParseMessageRow(self, parser_mediator, query, row, **unused_kwargs): query_hash = hash(query) event_data = IMessageEventData() event_data.attachment_location = self._GetRowValue( query_hash, row, 'attachment_location') event_data.imessage_id = self._GetRowValue(query_hash, row, 'imessa...
288,723
Converts a binary data value into an integer. Args: value (bytes): binary data value containing an unsigned 64-bit big-endian integer. Returns: int: integer representation of binary data value or None if value is not set. Raises: ParseError: if the integer value cann...
def _ConvertValueBinaryDataToUBInt64(self, value): if not value: return None integer_map = self._GetDataTypeMap('uint64be') try: return self._ReadStructureFromByteStream(value, 0, integer_map) except (ValueError, errors.ParseError) as exception: raise errors.ParseError( ...
288,725
Retrieves a specific value from the record. Args: record (pyesedb.record): ESE record. value_entry (int): value entry. Returns: object: value. Raises: ValueError: if the value is not supported.
def _GetRecordValue(self, record, value_entry): column_type = record.get_column_type(value_entry) long_value = None if record.is_long_value(value_entry): long_value = record.get_value_data_as_long_value(value_entry) if record.is_multi_value(value_entry): # TODO: implement raise ...
288,726
Retrieves the values from the record. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. table_name (str): name of the table. record (pyesedb.record): ESE record. value_mappings (Optional[dict[str, str]): ...
def _GetRecordValues( self, parser_mediator, table_name, record, value_mappings=None): record_values = {} for value_entry in range(0, record.number_of_values): if parser_mediator.abort: break column_name = record.get_column_name(value_entry) if column_name in record_values...
288,727
Extracts event objects from the database. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. cache (Optional[ESEDBCache]): cache. database (Optional[pyesedb.file]): ESE database. Raises: ValueError: I...
def GetEntries(self, parser_mediator, cache=None, database=None, **kwargs): if database is None: raise ValueError('Invalid database.') for table_name, callback_method in iter(self._tables.items()): if parser_mediator.abort: break if not callback_method: # Table names wit...
288,728
Determines if this is the appropriate plugin for the database. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. cache (Optional[ESEDBCache]): cache. database (Optional[pyesedb.file]): ESE database. Raises...
def Process(self, parser_mediator, cache=None, database=None, **kwargs): if database is None: raise ValueError('Invalid database.') # This will raise if unhandled keyword arguments are passed. super(ESEDBPlugin, self).Process(parser_mediator) self.GetEntries( parser_mediator, cache=...
288,729
Simple method to exact date values from a Plist. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. top_level (dict[str, object]): plist top-level key.
def GetEntries(self, parser_mediator, top_level=None, **unused_kwargs): for root, key, datetime_value in interface.RecurseKey(top_level): if not isinstance(datetime_value, datetime.datetime): continue event_data = plist_event.PlistTimeEventData() event_data.key = key event_data...
288,730
Parses a record and produces a Bash history event. 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. ...
def ParseRecord(self, parser_mediator, key, structure): if key != 'log_entry': raise errors.ParseError( 'Unable to parse record, unknown structure: {0:s}'.format(key)) event_data = BashHistoryEventData() event_data.command = structure.command date_time = dfdatetime_posix_time.Posi...
288,733
Verifies that this is a bash history file. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. lines (str): one or more lines from the text file. Returns: bool: True if this is the correct parser, False othe...
def VerifyStructure(self, parser_mediator, lines): match_generator = self._VERIFICATION_GRAMMAR.scanString(lines, maxMatches=1) return bool(list(match_generator))
288,734
Retrieves the network info within the signatures subkey. Args: signatures_key (dfwinreg.WinRegistryKey): a Windows Registry key. Returns: dict[str, tuple]: a tuple of default_gateway_mac and dns_suffix per profile identifier (GUID).
def _GetNetworkInfo(self, signatures_key): network_info = {} for category in signatures_key.GetSubkeys(): for signature in category.GetSubkeys(): profile_guid_value = signature.GetValueByName('ProfileGuid') if profile_guid_value: profile_guid = profile_guid_value.GetDataAsOb...
288,736
Parses a SYSTEMTIME date and time value from a byte stream. Args: byte_stream (bytes): byte stream. Returns: dfdatetime.Systemtime: SYSTEMTIME date and time value or None if no value is set. Raises: ParseError: if the SYSTEMTIME could not be parsed.
def _ParseSystemTime(self, byte_stream): systemtime_map = self._GetDataTypeMap('systemtime') try: systemtime = self._ReadStructureFromByteStream( byte_stream, 0, systemtime_map) except (ValueError, errors.ParseError) as exception: raise errors.ParseError( 'Unable to par...
288,737
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): network_info = {} signatures = registry_key.GetSubkeyByName('Signatures') if signatures: network_info = self._GetNetworkInfo(signatures) profiles = registry_key.GetSubkeyByName('Profiles') if not profiles: return ...
288,738
Determines the formatted message strings for an event object. Args: formatter_mediator (FormatterMediator): mediates the interactions between formatters and other components, such as storage and Windows EventLog resources. event (EventObject): event. Returns: tuple(str, s...
def GetMessages(self, formatter_mediator, event): if self.DATA_TYPE != event.data_type: raise errors.WrongFormatter('Unsupported data type: {0:s}.'.format( event.data_type)) event_values = event.CopyToDict() message_type = event_values.get('message_type', None) if message_type is ...
288,739
Initializes a task attribute container. Args: session_identifier (Optional[str]): identifier of the session the task is part of.
def __init__(self, session_identifier=None): super(Task, self).__init__() self.aborted = False self.completion_time = None self.file_entry_type = None self.has_retry = False self.identifier = '{0:s}'.format(uuid.uuid4().hex) self.last_processing_time = None self.merge_priority = Non...
288,740
Initializes a task completion attribute container. Args: identifier (Optional[str]): unique identifier of the task. The identifier should match that of the corresponding task start information. session_identifier (Optional[str]): identifier of the session the task is part ...
def __init__(self, identifier=None, session_identifier=None): super(TaskCompletion, self).__init__() self.aborted = False self.identifier = identifier self.session_identifier = session_identifier self.timestamp = None
288,744
Initializes a task start attribute container. Args: identifier (Optional[str]): unique identifier of the task. The identifier should match that of the corresponding task completion information. session_identifier (Optional[str]): identifier of the session the task is part ...
def __init__(self, identifier=None, session_identifier=None): super(TaskStart, self).__init__() self.identifier = identifier self.session_identifier = session_identifier self.timestamp = None
288,745
Get the Service DLL for a service, if it exists. Checks for a ServiceDLL for in the Parameters subkey of a service key in the Registry. Args: key (dfwinreg.WinRegistryKey): a Windows Registry key. Returns: str: path of the service DLL or None.
def GetServiceDll(self, key): parameters_key = key.GetSubkeyByName('Parameters') if not parameters_key: return None service_dll = parameters_key.GetValueByName('ServiceDll') if not service_dll: return None return service_dll.GetDataAsObject()
288,746
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): values_dict = {} service_type_value = registry_key.GetValueByName('Type') service_start_value = registry_key.GetValueByName('Start') # Grab the ServiceDLL value if it exists. if service_type_value and service_start_value: ...
288,747
Initializes a format specification. Args: identifier (str): unique name for the format. text_format (Optional[bool]): True if the format is a text format, False otherwise.
def __init__(self, identifier, text_format=False): super(FormatSpecification, self).__init__() self._text_format = text_format self.identifier = identifier self.signatures = []
288,749
Adds a signature. Args: pattern (bytes): pattern of the signature. offset (int): offset of the signature. None is used to indicate the signature has no offset. A positive offset is relative from the start of the data a negative offset is relative from the end of the data.
def AddNewSignature(self, pattern, offset=None): self.signatures.append(Signature(pattern, offset=offset))
288,750
Adds a new format specification. Args: identifier (str): format identifier, which should be unique for the store. Returns: FormatSpecification: format specification. Raises: KeyError: if the store already contains a specification with the same identifier.
def AddNewSpecification(self, identifier): if identifier in self._format_specifications: raise KeyError( 'Format specification {0:s} is already defined in store.'.format( identifier)) self._format_specifications[identifier] = FormatSpecification(identifier) return self._...
288,752
Adds a format specification. Args: specification (FormatSpecification): format specification. Raises: KeyError: if the store already contains a specification with the same identifier.
def AddSpecification(self, specification): if specification.identifier in self._format_specifications: raise KeyError( 'Format specification {0:s} is already defined in store.'.format( specification.identifier)) self._format_specifications[specification.identifier] = specific...
288,753
Parses an OLE Compound File (OLECF) file-like object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): file-like object.
def ParseFileObject(self, parser_mediator, file_object): olecf_file = pyolecf.file() olecf_file.set_ascii_codepage(parser_mediator.codepage) try: olecf_file.open_file_object(file_object) except IOError as exception: parser_mediator.ProduceExtractionWarning( 'unable to open fi...
288,755
Determines the formatted message strings for an event object. Args: formatter_mediator (FormatterMediator): mediates the interactions between formatters and other components, such as storage and Windows EventLog resources. event (EventObject): event. Returns: tuple(str, s...
def GetMessages(self, formatter_mediator, event): if self.DATA_TYPE != event.data_type: raise errors.WrongFormatter('Unsupported data type: {0:s}.'.format( event.data_type)) event_values = event.CopyToDict() event = event_values.get('event', None) if event: event_values['eve...
288,756
Extract device information from the iPod plist. 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): devices = match.get('Devices', {}) for device_identifier, device_information in iter(devices.items()): datetime_value = device_information.get('Connected', None) if not datetime_value: continue event_data = IPodP...
288,758
Initializes a credential configuration object. Args: credential_data (Optional[bytes]): credential data. credential_type (Optional[str]): credential type. path_spec (Optional[dfvfs.PathSpec]): path specification.
def __init__( self, credential_data=None, credential_type=None, path_spec=None): super(CredentialConfiguration, self).__init__() self.credential_data = credential_data self.credential_type = credential_type self.path_spec = path_spec
288,759
Initializes an output mediator. Args: knowledge_base (KnowledgeBase): knowledge base. formatter_mediator (FormatterMediator): formatter mediator. fields_filter (Optional[FilterObject]): filter object that indicates which fields to output. preferred_encoding (Optional[str]): prefer...
def __init__( self, knowledge_base, formatter_mediator, fields_filter=None, preferred_encoding='utf-8'): super(OutputMediator, self).__init__() self._formatter_mediator = formatter_mediator self._knowledge_base = knowledge_base self._preferred_encoding = preferred_encoding self._tim...
288,764
Retrieves the event formatter for a specific event type. Args: event (EventObject): event. Returns: EventFormatter: event formatter or None.
def GetEventFormatter(self, event): data_type = getattr(event, 'data_type', None) if not data_type: return None return formatters_manager.FormattersManager.GetFormatterObject( event.data_type)
288,765
Retrieves the formatted messages related to the event. Args: event (EventObject): event. Returns: tuple: containing: str: full message string or None if no event formatter was found. str: short message string or None if no event formatter was found.
def GetFormattedMessages(self, event): event_formatter = self.GetEventFormatter(event) if not event_formatter: return None, None return event_formatter.GetMessages(self._formatter_mediator, event)
288,766
Retrieves the formatted sources related to the event. Args: event (EventObject): event. Returns: tuple: containing: str: full source string or None if no event formatter was found. str: short source string or None if no event formatter was found.
def GetFormattedSources(self, event): event_formatter = self.GetEventFormatter(event) if not event_formatter: return None, None return event_formatter.GetSources(event)
288,767
Retrieves the attribute names in the format string. Args: event (EventObject): event. Returns: list[str]: list containing the attribute names. If no event formatter to match the event can be found the function returns None.
def GetFormatStringAttributeNames(self, event): event_formatter = self.GetEventFormatter(event) if not event_formatter: return None return event_formatter.GetFormatStringAttributeNames()
288,768
Retrieves the hostname related to the event. Args: event (EventObject): event. default_hostname (Optional[str]): default hostname. Returns: str: hostname.
def GetHostname(self, event, default_hostname='-'): hostname = getattr(event, 'hostname', None) if hostname: return hostname session_identifier = event.GetSessionIdentifier() if session_identifier is None: return default_hostname hostname = self._knowledge_base.GetHostname( ...
288,769
Retrieves the MACB representation. Args: event (EventObject): event. Returns: str: MACB representation.
def GetMACBRepresentation(self, event): data_type = getattr(event, 'data_type', None) if not data_type: return '....' # The filestat parser is somewhat limited. if data_type == 'fs:stat': descriptions = event.timestamp_desc.split(';') return_characters = ['.', '.', '.', '.'] ...
288,770
Retrieves the username related to the event. Args: event (EventObject): event. default_username (Optional[str]): default username. Returns: str: username.
def GetUsername(self, event, default_username='-'): username = getattr(event, 'username', None) if username and username != '-': return username session_identifier = event.GetSessionIdentifier() if session_identifier is None: return default_username user_sid = getattr(event, 'user...
288,772
Sets the timezone. Args: timezone (str): timezone. Raises: ValueError: if the timezone is not supported.
def SetTimezone(self, timezone): if not timezone: return try: self._timezone = pytz.timezone(timezone) except pytz.UnknownTimeZoneError: raise ValueError('Unsupported timezone: {0:s}'.format(timezone))
288,773
Deregisters an attribute container class. The attribute container classes are identified based on their lower case container type. Args: attribute_container_class (type): attribute container class. Raises: KeyError: if attribute container class is not set for the correspon...
def DeregisterAttributeContainer(cls, attribute_container_class): container_type = attribute_container_class.CONTAINER_TYPE.lower() if container_type not in cls._attribute_container_classes: raise KeyError( 'Attribute container class not set for container type: ' '{0:s}.'.format(a...
288,774
Parses and validates options. Args: options (argparse.Namespace): parser options. output_module (OutputModule): output module to configure. Raises: BadConfigObject: when the output module object is of the wrong type. BadConfigOption: when the output filename was not provided.
def ParseOptions(cls, options, output_module): if not isinstance(output_module, sqlite_4n6time.SQLite4n6TimeOutputModule): raise errors.BadConfigObject( 'Output module is not an instance of SQLite4n6TimeOutputModule') shared_4n6time_output.Shared4n6TimeOutputArgumentsHelper.ParseOptions( ...
288,776
Determines which events are indicated by a set of fsevents flags. Args: flags (int): fsevents record flags. Returns: str: a comma separated string containing descriptions of the flag values stored in an fsevents record.
def _GetFlagValues(self, flags): event_types = [] for event_flag, description in self._FLAG_VALUES.items(): if event_flag & flags: event_types.append(description) return ', '.join(event_types)
288,777
Parses an OLECF item. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. olecf_item (pyolecf.item): OLECF item. Returns: bool: True if an event was produced.
def _ParseItem(self, parser_mediator, olecf_item): result = False event_data = OLECFItemEventData() event_data.name = olecf_item.name event_data.offset = 0 event_data.size = olecf_item.size creation_time, modification_time = self._GetTimestamps(olecf_item) if creation_time: date...
288,779
Parses an OLECF file. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. root_item (Optional[pyolecf.item]): root item of the OLECF file. Raises: ValueError: If the root item is not set.
def Process(self, parser_mediator, root_item=None, **kwargs): # This will raise if unhandled keyword arguments are passed. super(DefaultOLECFPlugin, self).Process(parser_mediator, **kwargs) if not root_item: raise ValueError('Root item not set.') if not self._ParseItem(parser_mediator, root...
288,780
Initializes a tagging file. Args: path (str): path to a file that contains one or more event tagging rules.
def __init__(self, path): super(TaggingFile, self).__init__() self._path = path
288,781
Retrieves a specific string value from the data dict. Args: data_dict (dict[str, list[str]): values per name. name (str): name of the value to retrieve. default_value (Optional[object]): value to return if the name has no value set in data_dict. Returns: str: value represente...
def _GetStringValue(self, data_dict, name, default_value=None): values = data_dict.get(name, None) if not values: return default_value for index, value in enumerate(values): if ',' in value: values[index] = '"{0:s}"'.format(value) return ', '.join(values)
288,785
Parses a CUPS IPP attribute from a file-like object. Args: file_object (dfvfs.FileIO): file-like object. Returns: tuple[str, object]: attribute name and value. Raises: ParseError: if the attribute cannot be parsed.
def _ParseAttribute(self, file_object): file_offset = file_object.tell() attribute_map = self._GetDataTypeMap('cups_ipp_attribute') try: attribute, _ = self._ReadStructureFromFileObject( file_object, file_offset, attribute_map) except (ValueError, errors.ParseError) as exception: ...
288,786
Parses a CUPS IPP attributes group from a file-like object. Args: file_object (dfvfs.FileIO): file-like object. Yields: tuple[str, object]: attribute name and value. Raises: ParseError: if the attributes group cannot be parsed.
def _ParseAttributesGroup(self, file_object): tag_value_map = self._GetDataTypeMap('int8') tag_value = 0 while tag_value != self._DELIMITER_TAG_END_OF_ATTRIBUTES: file_offset = file_object.tell() tag_value, _ = self._ReadStructureFromFileObject( file_object, file_offset, tag_val...
288,787
Parses a boolean value. Args: byte_stream (bytes): byte stream. Returns: bool: boolean value. Raises: ParseError: when the boolean value cannot be parsed.
def _ParseBooleanValue(self, byte_stream): if byte_stream == b'\x00': return False if byte_stream == b'\x01': return True raise errors.ParseError('Unsupported boolean value.')
288,788
Parses a CUPS IPP RFC2579 date-time value from a byte stream. Args: byte_stream (bytes): byte stream. file_offset (int): offset of the attribute data relative to the start of the file-like object. Returns: dfdatetime.RFC2579DateTime: RFC2579 date-time stored in the value. Rais...
def _ParseDateTimeValue(self, byte_stream, file_offset): datetime_value_map = self._GetDataTypeMap('cups_ipp_datetime_value') try: value = self._ReadStructureFromByteStream( byte_stream, file_offset, datetime_value_map) except (ValueError, errors.ParseError) as exception: raise e...
288,789
Parses an integer value. Args: byte_stream (bytes): byte stream. file_offset (int): offset of the attribute data relative to the start of the file-like object. Returns: int: integer value. Raises: ParseError: when the integer value cannot be parsed.
def _ParseIntegerValue(self, byte_stream, file_offset): data_type_map = self._GetDataTypeMap('int32be') try: return self._ReadStructureFromByteStream( byte_stream, file_offset, data_type_map) except (ValueError, errors.ParseError) as exception: raise errors.ParseError( ...
288,790
Parses a CUPS IPP header from a 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 header cannot be parsed...
def _ParseHeader(self, parser_mediator, file_object): header_map = self._GetDataTypeMap('cups_ipp_header') try: header, _ = self._ReadStructureFromFileObject(file_object, 0, header_map) except (ValueError, errors.ParseError) as exception: raise errors.UnableToParseFile( '[{0:s}] ...
288,791
Parses a CUPS IPP 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): self._last_charset_attribute = 'ascii' self._ParseHeader(parser_mediator, file_object) data_dict = {} time_dict = {} try: for name, value in self._ParseAttributesGroup(file_object): name = self._ATTRIBUTE_NAME_TRANSLATION...
288,792
Creates an event tag. Args: event (EventObject): event to tag. comment (str): event tag comment. labels (list[str]): event tag labels. Returns: EventTag: the event tag.
def _CreateEventTag(self, event, comment, labels): event_identifier = event.GetIdentifier() event_tag = events.EventTag(comment=comment) event_tag.SetEventIdentifier(event_identifier) event_tag.AddLabels(labels) event_identifier_string = event_identifier.CopyToString() logger.debug('Creat...
288,794
Initializes a hash tagging analysis plugin. Args: analyzer_class (type): a subclass of HashAnalyzer that will be instantiated by the plugin.
def __init__(self, analyzer_class): super(HashTaggingAnalysisPlugin, self).__init__() self._analysis_queue_timeout = self.DEFAULT_QUEUE_TIMEOUT self._analyzer_started = False self._comment = 'Tag applied by {0:s} analysis plugin'.format(self.NAME) self._event_identifiers_by_pathspec = collectio...
288,795
Evaluates whether an event contains the right data for a hash lookup. Args: mediator (AnalysisMediator): mediates interactions between analysis plugins and other components, such as storage and dfvfs. event (EventObject): event.
def ExamineEvent(self, mediator, event): self._EnsureRequesterStarted() path_spec = event.pathspec event_identifiers = self._event_identifiers_by_pathspec[path_spec] event_identifier = event.GetIdentifier() event_identifiers.append(event_identifier) if event.data_type not in self.DATA_TY...
288,798
Compiles an analysis report. Args: mediator (AnalysisMediator): mediates interactions between analysis plugins and other components, such as storage and dfvfs. Returns: AnalysisReport: report.
def CompileReport(self, mediator): # TODO: refactor to update the counter on demand instead of # during reporting. path_specs_per_labels_counter = collections.Counter() tags = [] while self._ContinueReportCompilation(): try: self._LogProgressUpdateIfReasonable() hash_analy...
288,801
Initializes a hash analyzer. Args: hash_queue (Queue.queue): contains hashes to be analyzed. hash_analysis_queue (Queue.queue): queue that the analyzer will append HashAnalysis objects to. hashes_per_batch (Optional[int]): number of hashes to analyze at once. lookup_hash (Optional...
def __init__( self, hash_queue, hash_analysis_queue, hashes_per_batch=1, lookup_hash='sha256', wait_after_analysis=0): super(HashAnalyzer, self).__init__() self._abort = False self._hash_queue = hash_queue self._hash_analysis_queue = hash_analysis_queue self.analyses_performed = 0 ...
288,803
Retrieves a list of items from a queue. Args: target_queue (Queue.queue): queue to retrieve hashes from. max_hashes (int): maximum number of items to retrieve from the target_queue. Returns: list[object]: list of at most max_hashes elements from the target_queue. The list...
def _GetHashes(self, target_queue, max_hashes): hashes = [] for _ in range(0, max_hashes): try: item = target_queue.get_nowait() except Queue.Empty: continue hashes.append(item) return hashes
288,804
Sets the hash to query. Args: lookup_hash (str): name of the hash attribute to look up. Raises: ValueError: if the lookup hash is not supported.
def SetLookupHash(self, lookup_hash): if lookup_hash not in self.SUPPORTED_HASHES: raise ValueError('Unsupported lookup hash: {0!s}'.format(lookup_hash)) self.lookup_hash = lookup_hash
288,806
Initializes a HTTP hash analyzer. Args: hash_queue (Queue.queue): a queue that contains hashes to be analyzed. hash_analysis_queue (Queue.queue): queue that the analyzer will append HashAnalysis objects to.
def __init__(self, hash_queue, hash_analysis_queue, **kwargs): super(HTTPHashAnalyzer, self).__init__( hash_queue, hash_analysis_queue, **kwargs) self._checked_for_old_python_version = False
288,807
Initializes analysis information about a hash. Args: subject_hash (str): hash that the hash_information relates to. hash_information (object): information about the hash. This object will be used by the GenerateLabels method in the HashTaggingAnalysisPlugin to tag events that relate...
def __init__(self, subject_hash, hash_information): self.hash_information = hash_information self.subject_hash = subject_hash
288,810
Parses an application usage 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 ParseApplicationUsageRow( self, parser_mediator, query, row, **unused_kwargs): query_hash = hash(query) # TODO: replace usage by definition(s) in eventdata. Not sure which values # it will hold here. application_name = self._GetRowValue(query_hash, row, 'event') usage = 'Application ...
288,812
Initializes the time slice. Args: event_timestamp (int): event timestamp of the time slice or None. duration (Optional[int]): duration of the time slice in minutes. The default is 5, which represent 2.5 minutes before and 2.5 minutes after the event timestamp.
def __init__(self, event_timestamp, duration=5): super(TimeSlice, self).__init__() self.duration = duration self.event_timestamp = event_timestamp
288,813
Processes a file-like object with analyzers. Args: mediator (ParserMediator): mediates the interactions between parsers and other components, such as storage and abort signals. file_object (dfvfs.FileIO): file-like object to process.
def _AnalyzeFileObject(self, mediator, file_object): maximum_read_size = max([ analyzer_object.SIZE_LIMIT for analyzer_object in self._analyzers]) hashers_only = True for analyzer_object in self._analyzers: if not isinstance(analyzer_object, hashing_analyzer.HashingAnalyzer): has...
288,818
Determines if analysis and extraction of a data stream can be skipped. This is used to prevent Plaso trying to run analyzers or extract content from a pipe or socket it encounters while processing a mounted filesystem. Args: file_entry (dfvfs.FileEntry): file entry to consider for skipping. da...
def _CanSkipDataStream(self, file_entry, data_stream): if file_entry.IsFile(): return False if data_stream.IsDefault(): return True return False
288,819
Determines if content extraction of a file entry can be skipped. Args: file_entry (dfvfs.FileEntry): file entry of which to determine content extraction can be skipped. Returns: bool: True if content extraction can be skipped.
def _CanSkipContentExtraction(self, file_entry): # TODO: make this filtering solution more generic. Also see: # https://github.com/log2timeline/plaso/issues/467 location = getattr(file_entry.path_spec, 'location', None) if not location: return False data_stream_name = getattr(file_entry....
288,820
Extracts content from a data stream. Args: mediator (ParserMediator): mediates the interactions between parsers and other components, such as storage and abort signals. file_entry (dfvfs.FileEntry): file entry to extract its content. data_stream_name (str): name of the data stream whose...
def _ExtractContentFromDataStream( self, mediator, file_entry, data_stream_name): self.processing_status = definitions.STATUS_INDICATOR_EXTRACTING if self._processing_profiler: self._processing_profiler.StartTiming('extracting') self._event_extractor.ParseDataStream( mediator, fil...
288,821
Extracts metadata from 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 to extract metadata from. data_stream (dfvfs.DataStream): data stream or None...
def _ExtractMetadataFromFileEntry(self, mediator, file_entry, data_stream): # Do not extract metadata from the root file entry when it is virtual. if file_entry.IsRoot() and file_entry.type_indicator not in ( self._TYPES_WITH_ROOT_METADATA): return # We always want to extract the file en...
288,822
Determines if a data stream contains an archive 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 of the data stream. Returns: list[...
def _GetArchiveTypes(self, mediator, path_spec): try: type_indicators = analyzer.Analyzer.GetArchiveTypeIndicators( path_spec, resolver_context=mediator.resolver_context) except IOError as exception: type_indicators = [] warning_message = ( 'analyzer failed to determi...
288,823
Determines if a data stream contains a compressed stream such as: gzip. Args: mediator (ParserMediator): mediates the interactions between parsers and other components, such as storage and abort signals. path_spec (dfvfs.PathSpec): path specification of the data stream. Returns: li...
def _GetCompressedStreamTypes(self, mediator, path_spec): try: type_indicators = analyzer.Analyzer.GetCompressedStreamTypeIndicators( path_spec, resolver_context=mediator.resolver_context) except IOError as exception: type_indicators = [] warning_message = ( 'analyzer...
288,824