docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Prints information about the tasks. Args: storage_reader (StorageReader): storage reader.
def _PrintTasksInformation(self, storage_reader): table_view = views.ViewsFactory.GetTableView( self._views_format_type, title='Tasks') for task_start, _ in storage_reader.GetSessions(): start_time = timelib.Timestamp.CopyToIsoFormat( task_start.timestamp) task_identifier = u...
288,403
Parses the options. Args: options (argparse.Namespace): command line arguments. Raises: BadConfigOption: if the options are invalid.
def ParseOptions(self, options): self._ParseInformationalOptions(options) self._verbose = getattr(options, 'verbose', False) self._output_filename = getattr(options, 'write', None) argument_helper_names = ['process_resources', 'storage_file'] helpers_manager.ArgumentHelperManager.ParseOption...
288,406
Retrieves the file system type indicator of a file entry. Args: file_entry (dfvfs.FileEntry): a file entry. Returns: str: file system type.
def _GetFileSystemTypeFromFileEntry(self, file_entry): if file_entry.type_indicator != dfvfs_definitions.TYPE_INDICATOR_TSK: return file_entry.type_indicator # TODO: Implement fs_type in dfVFS and remove this implementation # once that is in place. file_system = file_entry.GetFileSystem() ...
288,409
Parses a file entry. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_entry (dfvfs.FileEntry): a file entry.
def ParseFileEntry(self, parser_mediator, file_entry): stat_object = file_entry.GetStat() if not stat_object: return file_system_type = self._GetFileSystemTypeFromFileEntry(file_entry) event_data = FileStatEventData() event_data.file_entry_type = stat_object.type event_data.file_siz...
288,410
Formats an argument token as a dictionary of values. Args: token_data (bsm_token_data_arg32|bsm_token_data_arg64): AUT_ARG32 or AUT_ARG64 token data. Returns: dict[str, str]: token values.
def _FormatArgToken(self, token_data): return { 'string': token_data.argument_value.rstrip('\x00'), 'num_arg': token_data.argument_index, 'is': token_data.argument_name}
288,412
Formats an attribute token as a dictionary of values. Args: token_data (bsm_token_data_attr32|bsm_token_data_attr64): AUT_ATTR32 or AUT_ATTR64 token data. Returns: dict[str, str]: token values.
def _FormatAttrToken(self, token_data): return { 'mode': token_data.file_mode, 'uid': token_data.user_identifier, 'gid': token_data.group_identifier, 'system_id': token_data.file_system_identifier, 'node_id': token_data.file_identifier, 'device': token_data.devic...
288,413
Formats a data token as a dictionary of values. Args: token_data (bsm_token_data_data): AUT_DATA token data. Returns: dict[str, str]: token values.
def _FormatDataToken(self, token_data): format_string = bsmtoken.BSM_TOKEN_DATA_PRINT.get( token_data.data_format, 'UNKNOWN') if token_data.data_format == 4: data = bytes(bytearray(token_data.data)).split(b'\x00')[0] data = data.decode('utf-8') else: data = ''.join(['{0:02x}'...
288,414
Formats an extended IPv4 address token as a dictionary of values. Args: token_data (bsm_token_data_in_addr_ex): AUT_IN_ADDR_EX token data. Returns: dict[str, str]: token values.
def _FormatInAddrExToken(self, token_data): protocol = bsmtoken.BSM_PROTOCOLS.get(token_data.net_type, 'UNKNOWN') if token_data.net_type == 4: ip_address = self._FormatPackedIPv6Address(token_data.ip_address[:4]) elif token_data.net_type == 16: ip_address = self._FormatPackedIPv6Address(tok...
288,415
Formats an IPC permissions token as a dictionary of values. Args: token_data (bsm_token_data_ipc_perm): AUT_IPC_PERM token data. Returns: dict[str, str]: token values.
def _FormatIPCPermToken(self, token_data): return { 'user_id': token_data.user_identifier, 'group_id': token_data.group_identifier, 'creator_user_id': token_data.creator_user_identifier, 'creator_group_id': token_data.creator_group_identifier, 'access': token_data.access...
288,416
Formats an IPv4 packet header token as a dictionary of values. Args: token_data (bsm_token_data_ip): AUT_IP token data. Returns: dict[str, str]: token values.
def _FormatIPToken(self, token_data): data = ''.join(['{0:02x}'.format(byte) for byte in token_data.data]) return {'IPv4_Header': data}
288,417
Formats an opaque token as a dictionary of values. Args: token_data (bsm_token_data_opaque): AUT_OPAQUE token data. Returns: dict[str, str]: token values.
def _FormatOpaqueToken(self, token_data): data = ''.join(['{0:02x}'.format(byte) for byte in token_data.data]) return {'data': data}
288,418
Formats an other file token as a dictionary of values. Args: token_data (bsm_token_data_other_file32): AUT_OTHER_FILE32 token data. Returns: dict[str, str]: token values.
def _FormatOtherFileToken(self, token_data): # TODO: if this timestamp is useful, it must be extracted as a separate # event object. timestamp = token_data.microseconds + ( token_data.timestamp * definitions.MICROSECONDS_PER_SECOND) date_time = dfdatetime_posix_time.PosixTimeInMicroseconds(...
288,419
Formats a return or exit token as a dictionary of values. Args: token_data (bsm_token_data_exit|bsm_token_data_return32| bsm_token_data_return64): AUT_EXIT, AUT_RETURN32 or AUT_RETURN64 token data. Returns: dict[str, str]: token values.
def _FormatReturnOrExitToken(self, token_data): error_string = bsmtoken.BSM_ERRORS.get(token_data.status, 'UNKNOWN') return { 'error': error_string, 'token_status': token_data.status, 'call_status': token_data.return_value}
288,420
Formats an extended socket token as a dictionary of values. Args: token_data (bsm_token_data_socket_ex): AUT_SOCKET_EX token data. Returns: dict[str, str]: token values.
def _FormatSocketExToken(self, token_data): if token_data.socket_domain == 10: local_ip_address = self._FormatPackedIPv6Address( token_data.local_ip_address) remote_ip_address = self._FormatPackedIPv6Address( token_data.remote_ip_address) else: local_ip_address = self....
288,421
Formats an Internet socket token as a dictionary of values. Args: token_data (bsm_token_data_sockinet32): AUT_SOCKINET32 token data. Returns: dict[str, str]: token values.
def _FormatSocketInet32Token(self, token_data): protocol = bsmtoken.BSM_PROTOCOLS.get(token_data.socket_family, 'UNKNOWN') ip_address = self._FormatPackedIPv4Address(token_data.ip_addresss) return { 'protocols': protocol, 'family': token_data.socket_family, 'port': token_data.po...
288,422
Formats an Internet socket token as a dictionary of values. Args: token_data (bsm_token_data_sockinet64): AUT_SOCKINET128 token data. Returns: dict[str, str]: token values.
def _FormatSocketInet128Token(self, token_data): protocol = bsmtoken.BSM_PROTOCOLS.get(token_data.socket_family, 'UNKNOWN') ip_address = self._FormatPackedIPv6Address(token_data.ip_addresss) return { 'protocols': protocol, 'family': token_data.socket_family, 'port': token_data.p...
288,423
Formats an Unix socket token as a dictionary of values. Args: token_data (bsm_token_data_sockunix): AUT_SOCKUNIX token data. Returns: dict[str, str]: token values.
def _FormatSocketUnixToken(self, token_data): protocol = bsmtoken.BSM_PROTOCOLS.get(token_data.socket_family, 'UNKNOWN') return { 'protocols': protocol, 'family': token_data.socket_family, 'path': token_data.socket_path}
288,424
Formats a subject or process token as a dictionary of values. Args: token_data (bsm_token_data_subject32|bsm_token_data_subject64): AUT_SUBJECT32, AUT_PROCESS32, AUT_SUBJECT64 or AUT_PROCESS64 token data. Returns: dict[str, str]: token values.
def _FormatSubjectOrProcessToken(self, token_data): ip_address = self._FormatPackedIPv4Address(token_data.ip_address) return { 'aid': token_data.audit_user_identifier, 'euid': token_data.effective_user_identifier, 'egid': token_data.effective_group_identifier, 'uid': token_d...
288,425
Formats a subject or process token as a dictionary of values. Args: token_data (bsm_token_data_subject32_ex|bsm_token_data_subject64_ex): AUT_SUBJECT32_EX, AUT_PROCESS32_EX, AUT_SUBJECT64_EX or AUT_PROCESS64_EX token data. Returns: dict[str, str]: token values.
def _FormatSubjectExOrProcessExToken(self, token_data): if token_data.net_type == 4: ip_address = self._FormatPackedIPv4Address(token_data.ip_address) elif token_data.net_type == 16: ip_address = self._FormatPackedIPv6Address(token_data.ip_address) else: ip_address = 'unknown' re...
288,426
Formats the token data as a dictionary of values. Args: token_type (int): token type. token_data (object): token data. Returns: dict[str, str]: formatted token values or an empty dictionary if no formatted token values could be determined.
def _FormatTokenData(self, token_type, token_data): token_data_format_function = self._TOKEN_DATA_FORMAT_FUNCTIONS.get( token_type) if token_data_format_function: token_data_format_function = getattr( self, token_data_format_function, None) if not token_data_format_function: ...
288,427
Parses an event record. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): file-like object. Raises: ParseError: if the event record cannot be read.
def _ParseRecord(self, parser_mediator, file_object): header_record_offset = file_object.tell() # Check the header token type before reading the token data to prevent # variable size tokens to consume a large amount of memory. token_type = self._ParseTokenType(file_object, header_record_offset) ...
288,428
Parses a token. Args: file_object (dfvfs.FileIO): file-like object. file_offset (int): offset of the token relative to the start of the file-like object. Returns: tuple: containing: int: token type object: token data or None if the token type is not supported.
def _ParseToken(self, file_object, file_offset): token_type = self._ParseTokenType(file_object, file_offset) token_data = None token_data_map_name = self._DATA_TYPE_MAP_PER_TOKEN_TYPE.get( token_type, None) if token_data_map_name: token_data_map = self._GetDataTypeMap(token_data_map_...
288,429
Parses a token type. Args: file_object (dfvfs.FileIO): file-like object. file_offset (int): offset of the token relative to the start of the file-like object. Returns: int: token type
def _ParseTokenType(self, file_object, file_offset): token_type_map = self._GetDataTypeMap('uint8') token_type, _ = self._ReadStructureFromFileObject( file_object, file_offset, token_type_map) return token_type
288,430
Parses a BSM 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 = file_object.get_offset() file_size = file_object.get_size() while file_offset < file_size: try: self._ParseRecord(parser_mediator, file_object) except errors.ParseError as exception: if file_offset == 0: ...
288,431
Parses a line of the log file and produces events. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. row_offset (int): line number of the row. row (dict[str, str]): fields of a single row, as specified in COLUM...
def ParseRow(self, parser_mediator, row_offset, row): time_elements_tuple = self._GetTimeElementsTuple(row['time']) try: date_time = dfdatetime_time_elements.TimeElements( time_elements_tuple=time_elements_tuple) date_time.is_local_time = True except ValueError: parser_medi...
288,434
Verifies if a line of the file is in the expected format. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. row (dict[str, str]): fields of a single row, as specified in COLUMNS. Returns: bool: True if thi...
def VerifyRow(self, parser_mediator, row): try: time_elements_tuple = self._GetTimeElementsTuple(row['time']) except (TypeError, ValueError): return False try: dfdatetime_time_elements.TimeElements( time_elements_tuple=time_elements_tuple) except ValueError: retur...
288,435
Extracts relevant Volume Configuration Spotlight entries. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. match (Optional[dict[str: object]]): keys extracted from PLIST_KEYS.
def GetEntries(self, parser_mediator, match=None, **unused_kwargs): stores = match.get('Stores', {}) for volume_name, volume in iter(stores.items()): datetime_value = volume.get('CreationDate', None) if not datetime_value: continue partial_path = volume['PartialPath'] even...
288,436
Initializes Windows Registry key filter. Args: user_assist_guid (str): UserAssist GUID.
def __init__(self, user_assist_guid): key_path = self._KEY_PATH_FORMAT.format(user_assist_guid) super(UserAssistWindowsRegistryKeyPathFilter, self).__init__(key_path)
288,438
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): version_value = registry_key.GetValueByName('Version') count_subkey = registry_key.GetSubkeyByName('Count') if not version_value: parser_mediator.ProduceExtractionWarning('missing version value') return if not version_v...
288,439
Initializes an CLI tool. 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(ExtractionTool, self).__init__( input_reader=input_reader, output_writer=output_writer) self._artifacts_registry = None self._buffer_size = 0 self._mount_path = None self._operating_system = None self._parser_filter_ex...
288,442
Creates a processing configuration. Args: knowledge_base (KnowledgeBase): contains information from the source data needed for parsing. Returns: ProcessingConfiguration: processing configuration. Raises: BadConfigOption: if more than 1 parser and parser plugins preset ...
def _CreateProcessingConfiguration(self, knowledge_base): # TODO: pass preferred_encoding. configuration = configurations.ProcessingConfiguration() configuration.artifact_filters = self._artifact_filters configuration.credentials = self._credential_configurations configuration.debug_output = se...
288,443
Parses the performance options. Args: options (argparse.Namespace): command line arguments. Raises: BadConfigOption: if the options are invalid.
def _ParsePerformanceOptions(self, options): self._buffer_size = getattr(options, 'buffer_size', 0) if self._buffer_size: # TODO: turn this into a generic function that supports more size # suffixes both MB and MiB and also that does not allow m as a valid # indicator for MiB since m repr...
288,444
Parses the processing options. Args: options (argparse.Namespace): command line arguments. Raises: BadConfigOption: if the options are invalid.
def _ParseProcessingOptions(self, options): self._single_process_mode = getattr(options, 'single_process', False) argument_helper_names = [ 'process_resources', 'temporary_directory', 'workers', 'zeromq'] helpers_manager.ArgumentHelperManager.ParseOptions( options, self, names=argument...
288,445
Preprocesses the sources. Args: extraction_engine (BaseEngine): extraction engine to preprocess the sources.
def _PreprocessSources(self, extraction_engine): logger.debug('Starting preprocessing.') try: artifacts_registry = engine.BaseEngine.BuildArtifactsRegistry( self._artifact_definitions_path, self._custom_artifacts_path) extraction_engine.PreprocessSources( artifacts_registry...
288,446
Sets the parsers and plugins before extraction. Args: configuration (ProcessingConfiguration): processing configuration. session (Session): session.
def _SetExtractionParsersAndPlugins(self, configuration, session): names_generator = parsers_manager.ParsersManager.GetParserAndPluginNames( parser_filter_expression=configuration.parser_filter_expression) session.enabled_parser_names = list(names_generator) session.parser_filter_expression = ...
288,448
Sets the preferred time zone before extraction. Args: knowledge_base (KnowledgeBase): contains information from the source data needed for parsing.
def _SetExtractionPreferredTimeZone(self, knowledge_base): # Note session.preferred_time_zone will default to UTC but # self._preferred_time_zone is None when not set. if self._preferred_time_zone: try: knowledge_base.SetTimeZone(self._preferred_time_zone) except ValueError: ...
288,449
Adds the performance options to the argument group. Args: argument_group (argparse._ArgumentGroup): argparse argument group.
def AddPerformanceOptions(self, argument_group): argument_group.add_argument( '--buffer_size', '--buffer-size', '--bs', dest='buffer_size', action='store', default=0, help=( 'The buffer size for the output (defaults to 196MiB).')) argument_group.add_argument( '--queue_s...
288,450
Adds the processing options to the argument group. Args: argument_group (argparse._ArgumentGroup): argparse argument group.
def AddProcessingOptions(self, argument_group): argument_group.add_argument( '--single_process', '--single-process', dest='single_process', action='store_true', default=False, help=( 'Indicate that the tool should run in a single process.')) argument_helper_names = ['temporary_...
288,451
Initializes event data. Args: cookie_identifier (str): unique identifier of the cookie.
def __init__(self, cookie_identifier): data_type = '{0:s}:{1:s}'.format(self.DATA_TYPE, cookie_identifier) super(GoogleAnalyticsEventData, self).__init__(data_type=data_type) self.cookie_name = None self.domain_hash = None self.pages_viewed = None self.sessions = None self.sources = No...
288,453
Extracts event objects from the cookie. Args: parser_mediator (ParserMediator): parser mediator. cookie_data (str): cookie data. url (str): URL or path where the cookie got set.
def GetEntries( self, parser_mediator, cookie_data=None, url=None, **kwargs): fields = cookie_data.split('.') number_of_fields = len(fields) if number_of_fields not in (1, 6): parser_mediator.ProduceExtractionWarning( 'unsupported number of fields: {0:d} in cookie: {1:s}'.format(...
288,454
Extracts event objects from the cookie. Args: parser_mediator (ParserMediator): parser mediator. cookie_data (bytes): cookie data. url (str): URL or path where the cookie got set.
def GetEntries( self, parser_mediator, cookie_data=None, url=None, **kwargs): fields = cookie_data.split('.') number_of_fields = len(fields) if number_of_fields not in (1, 4): parser_mediator.ProduceExtractionWarning( 'unsupported number of fields: {0:d} in cookie: {1:s}'.format(...
288,455
Extracts event objects from the cookie. Args: parser_mediator (ParserMediator): parser mediator. cookie_data (bytes): cookie data. url (str): URL or path where the cookie got set.
def GetEntries( self, parser_mediator, cookie_data=None, url=None, **kwargs): fields = cookie_data.split('.') number_of_fields = len(fields) if number_of_fields != 1: parser_mediator.ProduceExtractionWarning( 'unsupported number of fields: {0:d} in cookie: {1:s}'.format( ...
288,456
Extracts event objects from the cookie. Args: parser_mediator (ParserMediator): parser mediator. cookie_data (str): cookie data. url (str): URL or path where the cookie got set.
def GetEntries( self, parser_mediator, cookie_data=None, url=None, **kwargs): fields = cookie_data.split('.') number_of_fields = len(fields) if number_of_fields > 5: variables = '.'.join(fields[4:]) fields = fields[0:4] fields.append(variables) number_of_fields = len(fiel...
288,457
Parses a Java WebStart Cache IDX file-like object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dvfvs.FileIO): a file-like object to parse. Raises: UnableToParseFile: when the file cannot...
def ParseFileObject(self, parser_mediator, file_object): file_header_map = self._GetDataTypeMap('java_idx_file_header') try: file_header, file_offset = self._ReadStructureFromFileObject( file_object, 0, file_header_map) except (ValueError, errors.ParseError) as exception: raise e...
288,459
Parses a log header. 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 _ParseHeader(self, parser_mediator, structure): _, month, day, hours, minutes, seconds, year = structure.date_time month = timelib.MONTH_DICT.get(month.lower(), 0) time_elements_tuple = (year, month, day, hours, minutes, seconds) try: date_time = dfdatetime_time_elements.TimeElements( ...
288,462
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): if not self._xchat_year: return time_elements_tuple = self._GetTimeElementsTuple(structure) try: date_time = dfdatetime_time_elements.TimeElements( time_elements_tuple=time_elements_tuple) date_time.is_local_time = True ...
288,463
Parses a log record structure and produces events. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. key (str): identifier of the structure of tokens. structure (pyparsing.ParseResults): structure of tokens der...
def ParseRecord(self, parser_mediator, key, structure): if key not in ('header', 'header_signature', 'logline'): raise errors.ParseError( 'Unable to parse record, unknown structure: {0:s}'.format(key)) if key == 'logline': self._ParseLogLine(parser_mediator, structure) elif key ...
288,464
Verify that this file is a XChat log file. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. line (str): line from a text file. Returns: bool: True if the line is in the expected format, False if not.
def VerifyStructure(self, parser_mediator, line): try: structure = self._HEADER.parseString(line) except pyparsing.ParseException: logger.debug('Not a XChat log file') return False _, month, day, hours, minutes, seconds, year = structure.date_time month = timelib.MONTH_DICT.get(...
288,465
Adds command line arguments the helper supports to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper supports. Args: argument_group (argparse._ArgumentGroup|argparse.ArgumentParser): argparse grou...
def AddArguments(cls, argument_group): argument_group.add_argument( '--user', dest='username', type=str, action='store', default=cls._DEFAULT_USERNAME, metavar='USERNAME', required=False, help='The username used to connect to the database.') argument_group.add_argument( '--p...
288,466
Parses and validates options. Args: options (argparse.Namespace): parser options. output_module (OutputModule): output module to configure. Raises: BadConfigObject: when the output module object does not have the SetCredentials or SetDatabaseName methods.
def ParseOptions(cls, options, output_module): if not hasattr(output_module, 'SetCredentials'): raise errors.BadConfigObject('Unable to set username information.') if not hasattr(output_module, 'SetDatabaseName'): raise errors.BadConfigObject('Unable to set database information.') usernam...
288,467
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') filter_collection = getattr( configuration_object, '_filter_collection', None) if no...
288,468
Parses a .customDestinations-ms 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_entry = parser_mediator.GetFileEntry() display_name = parser_mediator.GetDisplayName() file_header_map = self._GetDataTypeMap('custom_file_header') try: file_header, file_offset = self._ReadStructureFromFileObject( file...
288,470
Parses an Messages 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 ParseMessagesRow(self, parser_mediator, query, row, **unused_kwargs): query_hash = hash(query) event_data = HangoutsMessageData() event_data.sender = self._GetRowValue(query_hash, row, 'full_name') event_data.body = self._GetRowValue(query_hash, row, 'text') event_data.offset = self._GetRo...
288,472
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') temporary_directory = getattr(options, 'temporary_directory', None) if temporary_directory a...
288,473
Initializes an Elasticsearch output module. Args: output_mediator (OutputMediator): mediates interactions between output modules and other components, such as storage and dfvfs.
def __init__(self, output_mediator): super(SharedElasticsearchOutputModule, self).__init__(output_mediator) self._client = None self._document_type = self._DEFAULT_DOCUMENT_TYPE self._event_documents = [] self._flush_interval = self._DEFAULT_FLUSH_INTERVAL self._host = None self._index_...
288,474
Creates an Elasticsearch index if it does not exist. Args: index_name (str): mame of the index. mappings (dict[str, object]): mappings of the index. Raises: RuntimeError: if the Elasticsearch index cannot be created.
def _CreateIndexIfNotExists(self, index_name, mappings): try: if not self._client.indices.exists(index_name): self._client.indices.create( body={'mappings': mappings}, index=index_name) except elasticsearch.exceptions.ConnectionError as exception: raise RuntimeError( ...
288,476
Inserts an event. Events are buffered in the form of documents and inserted to Elasticsearch when either forced to flush or when the flush interval (threshold) has been reached. Args: event (EventObject): event. force_flush (bool): True if buffered event documents should be inserted ...
def _InsertEvent(self, event, force_flush=False): if event: event_document = {'index': { '_index': self._index_name, '_type': self._document_type}} event_values = self._GetSanitizedEventValues(event) self._event_documents.append(event_document) self._event_documents.append(ev...
288,479
Sets the document type. Args: document_type (str): document type.
def SetDocumentType(self, document_type): self._document_type = document_type logger.debug('Elasticsearch document type: {0:s}'.format(document_type))
288,480
Set the flush interval. Args: flush_interval (int): number of events to buffer before doing a bulk insert.
def SetFlushInterval(self, flush_interval): self._flush_interval = flush_interval logger.debug('Elasticsearch flush interval: {0:d}'.format(flush_interval))
288,481
Set the index name. Args: index_name (str): name of the index.
def SetIndexName(self, index_name): self._index_name = index_name logger.debug('Elasticsearch index name: {0:s}'.format(index_name))
288,482
Set the server information. Args: server (str): IP address or hostname of the server. port (int): Port number of the server.
def SetServerInformation(self, server, port): self._host = server self._port = port logger.debug('Elasticsearch server: {0!s} port: {1:d}'.format( server, port))
288,483
Sets the username. Args: username (str): username to authenticate with.
def SetUsername(self, username): self._username = username logger.debug('Elasticsearch username: {0!s}'.format(username))
288,484
Sets the use of ssl. Args: use_ssl (bool): enforces use of ssl.
def SetUseSSL(self, use_ssl): self._use_ssl = use_ssl logger.debug('Elasticsearch use_ssl: {0!s}'.format(use_ssl))
288,485
Sets the path to the CA certificates. Args: ca_certificates_path (str): path to file containing a list of root certificates to trust. Raises: BadConfigOption: if the CA certificates file does not exist.
def SetCACertificatesPath(self, ca_certificates_path): if not ca_certificates_path: return if not os.path.exists(ca_certificates_path): raise errors.BadConfigOption( 'No such certificate file: {0:s}.'.format(ca_certificates_path)) self._ca_certs = ca_certificates_path logger...
288,486
Parses a launch services quarantine event 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 ParseLSQuarantineRow( self, parser_mediator, query, row, **unused_kwargs): query_hash = hash(query) event_data = LsQuarantineEventData() event_data.agent = self._GetRowValue(query_hash, row, 'Agent') event_data.data = self._GetRowValue(query_hash, row, 'Data') event_data.query = quer...
288,488
Retrieves a time elements tuple from the structure. Args: structure (pyparsing.ParseResults): structure of tokens derived from a line of a text file. Returns: tuple: containing: year (int): year. month (int): month, where 1 represents January. day_of_month (int): ...
def _GetTimeElementsTuple(self, structure): month, day, hours, minutes, seconds = structure.date_time # Note that dfdatetime_time_elements.TimeElements will raise ValueError # for an invalid month. month = timelib.MONTH_DICT.get(month.lower(), 0) if month != 0 and month < self._last_month: ...
288,491
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 of tokens derived from a line of a text file. key (...
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,492
Verify that this file is a securityd log file. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. line (str): line from a text file. Returns: bool: True if the line is in the expected format, False if not.
def VerifyStructure(self, parser_mediator, line): self._last_month = 0 self._year_use = parser_mediator.GetEstimatedYear() try: structure = self.SECURITYD_LINE.parseString(line) except pyparsing.ParseException: logger.debug('Not a MacOS securityd log file') return False time...
288,493
Initializes a formatter mediator object. Args: data_location (str): path of the formatter data files.
def __init__(self, data_location=None): super(FormatterMediator, self).__init__() self._data_location = data_location self._language_identifier = self.DEFAULT_LANGUAGE_IDENTIFIER self._lcid = self.DEFAULT_LCID self._winevt_database_reader = None
288,494
Retrieves the message string for a specific Windows Event Log source. Args: log_source (str): Event Log source, such as "Application Error". message_identifier (int): message identifier. Returns: str: message string or None if not available.
def GetWindowsEventMessage(self, log_source, message_identifier): database_reader = self._GetWinevtRcDatabaseReader() if not database_reader: return None if self._lcid != self.DEFAULT_LCID: message_string = database_reader.GetMessage( log_source, self.lcid, message_identifier) ...
288,496
Sets the preferred language identifier. Args: language_identifier (str): language identifier string such as "en-US" for US English or "is-IS" for Icelandic. Raises: KeyError: if the language identifier is not defined. ValueError: if the language identifier is not a string type.
def SetPreferredLanguageIdentifier(self, language_identifier): if not isinstance(language_identifier, py2to3.STRING_TYPES): raise ValueError('Language identifier is not a string.') values = language_ids.LANGUAGE_IDENTIFIERS.get( language_identifier.lower(), None) if not values: rai...
288,497
Deregisters a helper class. The helper classes are identified based on their lower case name. Args: helper_class (type): class object of the argument helper. Raises: KeyError: if helper class is not set for the corresponding name.
def DeregisterHelper(cls, helper_class): helper_name = helper_class.NAME.lower() if helper_name not in cls._helper_classes: raise KeyError('Helper class not set for name: {0:s}.'.format( helper_class.NAME)) del cls._helper_classes[helper_name]
288,499
Initializes a Viper hash analyzer. 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(ViperAnalyzer, self).__init__( hash_queue, hash_analysis_queue, **kwargs) self._checked_for_old_python_version = False self._host = None self._port = None self._protocol = None self._url = None
288,502
Queries the Viper Server for a specfic hash. Args: digest (str): hash to look up. Returns: dict[str, object]: JSON response or None on error.
def _QueryHash(self, digest): if not self._url: self._url = '{0:s}://{1:s}:{2:d}/file/find'.format( self._protocol, self._host, self._port) request_data = {self.lookup_hash: digest} try: json_response = self.MakeRequestAndDecodeJSON( self._url, 'POST', data=request_dat...
288,503
Looks up hashes in Viper using the Viper HTTP API. Args: hashes (list[str]): hashes to look up. Returns: list[HashAnalysis]: hash analysis. Raises: RuntimeError: If no host has been set for Viper.
def Analyze(self, hashes): hash_analyses = [] for digest in hashes: json_response = self._QueryHash(digest) hash_analysis = interface.HashAnalysis(digest, json_response) hash_analyses.append(hash_analysis) return hash_analyses
288,504
Sets the protocol that will be used to query Viper. Args: protocol (str): protocol to use to query Viper. Either 'http' or 'https'. Raises: ValueError: if the protocol is not supported.
def SetProtocol(self, protocol): if protocol not in self.SUPPORTED_PROTOCOLS: raise ValueError('Unsupported protocol: {0!s}'.format(protocol)) self._protocol = protocol
288,505
Generates a list of strings that will be used in the event tag. Args: hash_information (dict[str, object]): JSON decoded contents of the result of a Viper lookup, as produced by the ViperAnalyzer. Returns: list[str]: list of labels to apply to events.
def GenerateLabels(self, hash_information): if not hash_information: return ['viper_not_present'] projects = [] tags = [] for project, entries in iter(hash_information.items()): if not entries: continue projects.append(project) for entry in entries: if ent...
288,507
Sets the protocol that will be used to query Viper. Args: protocol (str): protocol to use to query Viper. Either 'http' or 'https'. Raises: ValueError: If an invalid protocol is selected.
def SetProtocol(self, protocol): protocol = protocol.lower().strip() if protocol not in ['http', 'https']: raise ValueError('Invalid protocol specified for Viper lookup') self._analyzer.SetProtocol(protocol)
288,508
Processes a path specification. Args: extraction_worker (worker.ExtractionWorker): extraction worker. parser_mediator (ParserMediator): parser mediator. path_spec (dfvfs.PathSpec): path specification.
def _ProcessPathSpec(self, extraction_worker, parser_mediator, path_spec): self._current_display_name = parser_mediator.GetDisplayNameForPathSpec( path_spec) try: extraction_worker.ProcessPathSpec(parser_mediator, path_spec) except KeyboardInterrupt: self._abort = True self...
288,510
Processes the sources. Args: source_path_specs (list[dfvfs.PathSpec]): path specifications of the sources to process. extraction_worker (worker.ExtractionWorker): extraction worker. parser_mediator (ParserMediator): parser mediator. storage_writer (StorageWriter): storage writer f...
def _ProcessSources( self, source_path_specs, extraction_worker, parser_mediator, storage_writer, filter_find_specs=None): if self._processing_profiler: self._processing_profiler.StartTiming('process_sources') number_of_consumed_sources = 0 self._UpdateStatus( definitions.ST...
288,511
Updates the processing status. Args: status (str): human readable status of the processing e.g. 'Idle'. display_name (str): human readable of the file entry currently being processed. number_of_consumed_sources (int): number of consumed sources. storage_writer (StorageWriter): sto...
def _UpdateStatus( self, status, display_name, number_of_consumed_sources, storage_writer, force=False): current_timestamp = time.time() if not force and current_timestamp < ( self._last_status_update_timestamp + self._STATUS_UPDATE_INTERVAL): return if status == definitions....
288,512
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( 'Invalid event object - unsupported data type: {0:s}'.format( event.data_type)) event_values = event.CopyToDict() number_of_volumes = event_values.get('nu...
288,514
Reads the file header. Args: file_object (file): file-like object. Returns: keychain_file_header: file header. Raises: ParseError: if the file header cannot be read.
def _ReadFileHeader(self, file_object): data_type_map = self._GetDataTypeMap('keychain_file_header') file_header, _ = self._ReadStructureFromFileObject( file_object, 0, data_type_map) if file_header.signature != self._FILE_SIGNATURE: raise errors.ParseError('Unsupported file signature.'...
288,522
Reads the record. Args: tables (dict[int, KeychainDatabaseTable]): tables per identifier. file_object (file): file-like object. record_offset (int): offset of the record relative to the start of the file. record_type (int): record type, which should correspond to a relation ...
def _ReadRecord(self, tables, file_object, record_offset, record_type): table = tables.get(record_type, None) if not table: raise errors.ParseError( 'Missing table for relation identifier: 0x{0:08}'.format(record_type)) record_header = self._ReadRecordHeader(file_object, record_offset)...
288,523
Reads the record attribute value offsets. Args: file_object (file): file-like object. file_offset (int): offset of the record attribute values offsets relative to the start of the file. number_of_attribute_values (int): number of attribute values. Returns: keychain_record_att...
def _ReadRecordAttributeValueOffset( self, file_object, file_offset, number_of_attribute_values): offsets_data_size = number_of_attribute_values * 4 offsets_data = file_object.read(offsets_data_size) context = dtfabric_data_maps.DataTypeMapContext(values={ 'number_of_attribute_values': ...
288,524
Reads the record header. Args: file_object (file): file-like object. record_header_offset (int): offset of the record header relative to the start of the file. Returns: keychain_record_header: record header. Raises: ParseError: if the record header cannot be read.
def _ReadRecordHeader(self, file_object, record_header_offset): data_type_map = self._GetDataTypeMap('keychain_record_header') record_header, _ = self._ReadStructureFromFileObject( file_object, record_header_offset, data_type_map) return record_header
288,525
Reads a schema attributes (CSSM_DL_DB_SCHEMA_ATTRIBUTES) record. Args: tables (dict[int, KeychainDatabaseTable]): tables per identifier. file_object (file): file-like object. record_offset (int): offset of the record relative to the start of the file. Raises: ParseError: if t...
def _ReadRecordSchemaAttributes(self, tables, file_object, record_offset): record_header = self._ReadRecordHeader(file_object, record_offset) attribute_value_offsets = self._ReadRecordAttributeValueOffset( file_object, record_offset + 24, 6) file_offset = file_object.tell() attribute_valu...
288,526
Reads a schema indexes (CSSM_DL_DB_SCHEMA_INDEXES) record. Args: tables (dict[int, KeychainDatabaseTable]): tables per identifier. file_object (file): file-like object. record_offset (int): offset of the record relative to the start of the file. Raises: ParseError: if the rec...
def _ReadRecordSchemaIndexes(self, tables, file_object, record_offset): _ = self._ReadRecordHeader(file_object, record_offset) attribute_value_offsets = self._ReadRecordAttributeValueOffset( file_object, record_offset + 24, 5) if attribute_value_offsets != (0x2d, 0x31, 0x35, 0x39, 0x3d): ...
288,527
Reads a schema information (CSSM_DL_DB_SCHEMA_INFO) record. Args: tables (dict[int, KeychainDatabaseTable]): tables per identifier. file_object (file): file-like object. record_offset (int): offset of the record relative to the start of the file. Raises: ParseError: if the re...
def _ReadRecordSchemaInformation(self, tables, file_object, record_offset): _ = self._ReadRecordHeader(file_object, record_offset) attribute_value_offsets = self._ReadRecordAttributeValueOffset( file_object, record_offset + 24, 2) if attribute_value_offsets != (0x21, 0x25): raise errors...
288,528
Reads the table. Args: tables (dict[int, KeychainDatabaseTable]): tables per identifier. file_object (file): file-like object. table_offset (int): offset of the table relative to the start of the file. Raises: ParseError: if the table cannot be read.
def _ReadTable(self, tables, file_object, table_offset): table_header = self._ReadTableHeader(file_object, table_offset) for record_offset in table_header.record_offsets: if record_offset == 0: continue record_offset += table_offset if table_header.record_type == self._RECORD_T...
288,529
Reads the table header. Args: file_object (file): file-like object. table_header_offset (int): offset of the tables header relative to the start of the file. Returns: keychain_table_header: table header. Raises: ParseError: if the table header cannot be read.
def _ReadTableHeader(self, file_object, table_header_offset): data_type_map = self._GetDataTypeMap('keychain_table_header') table_header, _ = self._ReadStructureFromFileObject( file_object, table_header_offset, data_type_map) return table_header
288,530
Reads the tables array. Args: file_object (file): file-like object. tables_array_offset (int): offset of the tables array relative to the start of the file. Returns: dict[int, KeychainDatabaseTable]: tables per identifier. Raises: ParseError: if the tables array cannot b...
def _ReadTablesArray(self, file_object, tables_array_offset): # TODO: implement https://github.com/libyal/dtfabric/issues/12 and update # keychain_tables_array definition. data_type_map = self._GetDataTypeMap('keychain_tables_array') tables_array, _ = self._ReadStructureFromFileObject( fi...
288,531
Parses a date time value. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. date_time_value (str): date time value (CSSM_DB_ATTRIBUTE_FORMAT_TIME_DATE) in the format: "YYYYMMDDhhmmssZ". Returns: ...
def _ParseDateTimeValue(self, parser_mediator, date_time_value): if date_time_value[14] != 'Z': parser_mediator.ProduceExtractionWarning( 'invalid date and time value: {0!s}'.format(date_time_value)) return None try: year = int(date_time_value[0:4], 10) month = int(date_t...
288,532
Parses a binary data value as string Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. binary_data_value (bytes): binary data value (CSSM_DB_ATTRIBUTE_FORMAT_BLOB) Returns: str: binary data value...
def _ParseBinaryDataAsString(self, parser_mediator, binary_data_value): if not binary_data_value: return None try: return binary_data_value.decode('utf-8') except UnicodeDecodeError: parser_mediator.ProduceExtractionWarning( 'invalid binary data string value: {0:s}'.format(...
288,533
Extracts the information from an application password record. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. record (dict[str, object]): database record. Raises: ParseError: if Internet password record ...
def _ParseApplicationPasswordRecord(self, parser_mediator, record): key = record.get('_key_', None) if not key or not key.startswith(b'ssgp'): raise errors.ParseError(( 'Unsupported application password record key value does not start ' 'with: "ssgp".')) event_data = Keychain...
288,534
Extracts the information from an Internet password record. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. record (dict[str, object]): database record. Raises: ParseError: if Internet password record can...
def _ParseInternetPasswordRecord(self, parser_mediator, record): key = record.get('_key_', None) if not key or not key.startswith(b'ssgp'): raise errors.ParseError(( 'Unsupported Internet password record key value does not start ' 'with: "ssgp".')) protocol_string = codecs.de...
288,535
Parses a MacOS keychain 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): try: file_header = self._ReadFileHeader(file_object) except (ValueError, errors.ParseError): raise errors.UnableToParseFile('Unable to parse file header.') tables = self._ReadTablesArray(file_object, file_header.tables_array_offset) ...
288,536
Initializes the output module object. Args: output_mediator (OutputMediator): mediates interactions between output modules and other components, such as storage and dfvfs. Raises: ValueError: when there are unused keyword arguments.
def __init__(self, output_mediator): super(Shared4n6TimeOutputModule, self).__init__(output_mediator) self._append = False self._evidence = '-' self._fields = self._DEFAULT_FIELDS self._set_status = None
288,537
Formats the date and time. Args: event (EventObject): event. Returns: str: date and time string or "N/A" if no event timestamp is available.
def _FormatDateTime(self, event): if not event.timestamp: return 'N/A' # TODO: preserve dfdatetime as an object. # TODO: add support for self._output_mediator.timezone date_time = dfdatetime_posix_time.PosixTimeInMicroseconds( timestamp=event.timestamp) year, month, day_of_month...
288,538
Sanitizes the event for use in 4n6time. Args: event (EventObject): event. Returns: dict[str, object]: dictionary containing the sanitized event values. Raises: NoFormatterFound: If no event formatter can be found to match the data type in the event object.
def _GetSanitizedEventValues(self, event): data_type = getattr(event, 'data_type', 'UNKNOWN') event_formatter = self._output_mediator.GetEventFormatter(event) if not event_formatter: raise errors.NoFormatterFound( 'Unable to find event formatter for: {0:s}.'.format(data_type)) mes...
288,539