docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Extracts relevant Airport 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): if 'RememberedNetworks' not in match: return for wifi in match['RememberedNetworks']: ssid = wifi.get('SSIDString', 'UNKNOWN_SSID') security_type = wifi.get('SecurityType', 'UNKNOWN_SECURITY_TYPE') event_data = pl...
287,670
Converts a specific value of the row to an integer. Args: row (dict[str, str]): fields of a single row, as specified in COLUMNS. value_name (str): name of the value within the row. Returns: int: value or None if the value cannot be converted.
def _GetIntegerValue(self, row, value_name): value = row.get(value_name, None) try: return int(value, 10) except (TypeError, ValueError): return None
287,672
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): number of the corresponding line. row (dict[str, str]): fields of a single row, as specifie...
def ParseRow(self, parser_mediator, row_offset, row): filename = row.get('name', None) md5_hash = row.get('md5', None) mode = row.get('mode_as_string', None) inode_number = row.get('inode', None) if '-' in inode_number: inode_number, _, _ = inode_number.partition('-') try: ino...
287,673
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): # Sleuthkit version 3 format: # MD5|name|inode|mode_as_string|UID|GID|size|atime|mtime|ctime|crtime # 0|/lost+found|11|d/drwx------|0|0|12288|1337961350|1337961350|1337961350|0 if row['md5'] != '0' and not self._MD5_RE.match(row['md5']): return Fals...
287,674
Parses an autofill entry 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 ParseAutofillRow( self, parser_mediator, query, row, **unused_kwargs): query_hash = hash(query) event_data = ChromeAutofillEventData() event_data.field_name = self._GetRowValue(query_hash, row, 'name') event_data.value = self._GetRowValue(query_hash, row, 'value') event_data.usage_co...
287,676
Aborts all registered processes by joining with the parent process. Args: timeout (int): number of seconds to wait for processes to join, where None represents no timeout.
def _AbortJoin(self, timeout=None): for pid, process in iter(self._processes_per_pid.items()): logger.debug('Waiting for process: {0:s} (PID: {1:d}).'.format( process.name, pid)) process.join(timeout=timeout) if not process.is_alive(): logger.debug('Process {0:s} (PID: {1:d}...
287,678
Checks the status of a worker process. If a worker process is not responding the process is terminated and a replacement process is started. Args: pid (int): process ID (PID) of a registered worker process. Raises: KeyError: if the process is not registered with the engine.
def _CheckStatusWorkerProcess(self, pid): # TODO: Refactor this method, simplify and separate concerns (monitoring # vs management). self._RaiseIfNotRegistered(pid) process = self._processes_per_pid[pid] process_status = self._QueryProcessStatus(process) if process_status is None: p...
287,681
Issues a SIGKILL or equivalent to the process. Args: pid (int): process identifier (PID).
def _KillProcess(self, pid): if sys.platform.startswith('win'): process_terminate = 1 handle = ctypes.windll.kernel32.OpenProcess( process_terminate, False, pid) ctypes.windll.kernel32.TerminateProcess(handle, -1) ctypes.windll.kernel32.CloseHandle(handle) else: try...
287,682
Queries a process to determine its status. Args: process (MultiProcessBaseProcess): process to query for its status. Returns: dict[str, str]: status values received from the worker process.
def _QueryProcessStatus(self, process): process_is_alive = process.is_alive() if process_is_alive: rpc_client = self._rpc_clients_per_pid.get(process.pid, None) process_status = rpc_client.CallFunction() else: process_status = None return process_status
287,683
Registers a process with the engine. Args: process (MultiProcessBaseProcess): process. Raises: KeyError: if the process is already registered with the engine. ValueError: if the process is missing.
def _RegisterProcess(self, process): if process is None: raise ValueError('Missing process.') if process.pid in self._processes_per_pid: raise KeyError( 'Already managing process: {0!s} (PID: {1:d})'.format( process.name, process.pid)) self._processes_per_pid[proce...
287,684
Starts monitoring a process. Args: process (MultiProcessBaseProcess): process. Raises: IOError: if the RPC client cannot connect to the server. KeyError: if the process is not registered with the engine or if the process is already being monitored. OSError: if the RPC client ...
def _StartMonitoringProcess(self, process): if process is None: raise ValueError('Missing process.') pid = process.pid if pid in self._process_information_per_pid: raise KeyError( 'Already monitoring process (PID: {0:d}).'.format(pid)) if pid in self._rpc_clients_per_pid: ...
287,685
Stops monitoring a process. Args: process (MultiProcessBaseProcess): process. Raises: KeyError: if the process is not monitored. ValueError: if the process is missing.
def _StopMonitoringProcess(self, process): if process is None: raise ValueError('Missing process.') pid = process.pid self._RaiseIfNotMonitored(pid) del self._process_information_per_pid[pid] rpc_client = self._rpc_clients_per_pid.get(pid, None) if rpc_client: rpc_client.Clo...
287,687
Terminate a process that's monitored by the engine. Args: pid (int): process identifier (PID). Raises: KeyError: if the process is not registered with and monitored by the engine.
def _TerminateProcessByPid(self, pid): self._RaiseIfNotRegistered(pid) process = self._processes_per_pid[pid] self._TerminateProcess(process) self._StopMonitoringProcess(process)
287,690
Terminate a process. Args: process (MultiProcessBaseProcess): process to terminate.
def _TerminateProcess(self, process): pid = process.pid logger.warning('Terminating process: (PID: {0:d}).'.format(pid)) process.terminate() # Wait for the process to exit. process.join(timeout=self._PROCESS_JOIN_TIMEOUT) if process.is_alive(): logger.warning('Killing process: (PID:...
287,691
Adds command line arguments to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper supports. Args: argument_group (argparse._ArgumentGroup|argparse.ArgumentParser): argparse group.
def AddArguments(cls, argument_group): argument_group.add_argument( '-o', '--output_format', '--output-format', metavar='FORMAT', dest='output_format', default='dynamic', help=( 'The output format. Use "-o list" to see a list of available ' 'output formats.')) argum...
287,692
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') output_format = getattr(options, 'output_format', 'dynamic') output_filename = getattr(optio...
287,693
Verify that a number is within a defined range. This is a callback method for pyparsing setParseAction that verifies that a read number is within a certain range. To use this method it needs to be defined as a callback method in setParseAction with the upper and lower bound set as parameters. Args: low...
def PyParseRangeCheck(lower_bound, upper_bound): # pylint: disable=unused-argument def CheckRange(string, location, tokens): try: check_number = tokens[0] except IndexError: check_number = -1 if check_number < lower_bound: raise pyparsing.ParseException( 'Value: {0:d...
287,694
Return an integer from a string. This is a pyparsing callback method that converts the matched string into an integer. The method modifies the content of the tokens list and converts them all to an integer value. Args: string (str): original string. location (int): location in the string where the ...
def PyParseIntCast(string, location, tokens): # Cast the regular tokens. for index, token in enumerate(tokens): try: tokens[index] = int(token) except ValueError: logger.error('Unable to cast [{0:s}] to an int, setting to 0'.format( token)) tokens[index] = 0 # We also need ...
287,695
Return a joined token from a list of tokens. This is a callback method for pyparsing setParseAction that modifies the returned token list to join all the elements in the list to a single token. Args: string (str): original string. location (int): location in the string where the match was made. to...
def PyParseJoinList(string, location, tokens): join_list = [] for token in tokens: try: join_list.append(str(token)) except UnicodeDecodeError: join_list.append(repr(token)) tokens[0] = ''.join(join_list) del tokens[1:]
287,696
Parses a text file-like object using a pyparsing definition. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): file-like object. Raises: UnableToParseFile: when the file cannot ...
def ParseFileObject(self, parser_mediator, file_object): # TODO: self._line_structures is a work-around and this needs # a structural fix. if not self._line_structures: raise errors.UnableToParseFile( 'Line structure undeclared, unable to proceed.') encoding = self._ENCODING or par...
287,700
Initializes the encoded text reader object. Args: encoding (str): encoding. buffer_size (Optional[int]): buffer size.
def __init__(self, encoding, buffer_size=2048): super(EncodedTextReader, self).__init__() self._buffer = '' self._buffer_size = buffer_size self._current_offset = 0 self._encoding = encoding self.lines = ''
287,701
Reads a line from the file object. Args: file_object (dfvfs.FileIO): file-like object. Returns: str: line read from the file-like object.
def _ReadLine(self, file_object): if len(self._buffer) < self._buffer_size: content = file_object.read(self._buffer_size) content = content.decode(self._encoding) self._buffer = ''.join([self._buffer, content]) line, new_line, self._buffer = self._buffer.partition('\n') if not line a...
287,702
Reads a line. Args: file_object (dfvfs.FileIO): file-like object. Returns: str: line read from the lines buffer.
def ReadLine(self, file_object): line, _, self.lines = self.lines.partition('\n') if not line: self.ReadLines(file_object) line, _, self.lines = self.lines.partition('\n') return line
287,703
Reads lines into the lines buffer. Args: file_object (dfvfs.FileIO): file-like object.
def ReadLines(self, file_object): lines_size = len(self.lines) if lines_size < self._buffer_size: lines_size = self._buffer_size - lines_size while lines_size > 0: line = self._ReadLine(file_object) if not line: break self.lines = ''.join([self.lines, line]) ...
287,704
Skips ahead a number of characters. Args: file_object (dfvfs.FileIO): file-like object. number_of_characters (int): number of characters.
def SkipAhead(self, file_object, number_of_characters): lines_size = len(self.lines) while number_of_characters >= lines_size: number_of_characters -= lines_size self.lines = '' self.ReadLines(file_object) lines_size = len(self.lines) if lines_size == 0: return s...
287,705
Parses a text file-like object using a pyparsing definition. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): file-like object. Raises: UnableToParseFile: when the file cannot ...
def ParseFileObject(self, parser_mediator, file_object): if not self.LINE_STRUCTURES: raise errors.UnableToParseFile('Missing line structures.') encoding = self._ENCODING or parser_mediator.codepage text_reader = EncodedTextReader( encoding, buffer_size=self.BUFFER_SIZE) text_reader...
287,707
Extracts Safari history items. 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): format_version = match.get('WebHistoryFileVersion', None) if format_version != 1: parser_mediator.ProduceExtractionWarning( 'unsupported Safari history version: {0!s}'.format(format_version)) return if 'WebHistor...
287,711
Deregisters a analyzer class. The analyzer classes are identified based on their lower case name. Args: analyzer_class (type): class object of the analyzer. Raises: KeyError: if analyzer class is not set for the corresponding name.
def DeregisterAnalyzer(cls, analyzer_class): analyzer_name = analyzer_class.NAME.lower() if analyzer_name not in cls._analyzer_classes: raise KeyError('analyzer class not set for name: {0:s}'.format( analyzer_class.NAME)) del cls._analyzer_classes[analyzer_name]
287,712
Retrieves an instance of a specific analyzer. Args: analyzer_name (str): name of the analyzer to retrieve. Returns: BaseAnalyzer: analyzer instance. Raises: KeyError: if analyzer class is not set for the corresponding name.
def GetAnalyzerInstance(cls, analyzer_name): analyzer_name = analyzer_name.lower() if analyzer_name not in cls._analyzer_classes: raise KeyError( 'analyzer class not set for name: {0:s}.'.format(analyzer_name)) analyzer_class = cls._analyzer_classes[analyzer_name] return analyzer_c...
287,714
Retrieves instances for all the specified analyzers. Args: analyzer_names (list[str]): names of the analyzers to retrieve. Returns: list[BaseAnalyzer]: analyzer instances.
def GetAnalyzerInstances(cls, analyzer_names): analyzer_instances = [] for analyzer_name, analyzer_class in iter(cls.GetAnalyzers()): if analyzer_name in analyzer_names: analyzer_instances.append(analyzer_class()) return analyzer_instances
287,715
Analyzes an event and creates extracts hashes as required. Args: mediator (AnalysisMediator): mediates interactions between analysis plugins and other components, such as storage and dfvfs. event (EventObject): event to examine.
def ExamineEvent(self, mediator, event): pathspec = getattr(event, 'pathspec', None) if pathspec is None: return if self._paths_with_hashes.get(pathspec, None): # We've already processed an event with this pathspec and extracted the # hashes from it. return hash_attributes =...
287,717
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): lines_of_text = ['Listing file paths and hashes'] for pathspec, hashes in sorted( self._paths_with_hashes.items(), key=lambda tuple: tuple[0].comparable): path_string = self._GeneratePathString(mediator, pathspec, hashes) lines_of_text.append(...
287,719
Parses the event data form a variable-length data section. Args: variable_length_section (job_variable_length_data_section): a Windows Scheduled Task job variable-length data section. Returns: WinJobEventData: event data of the job file.
def _ParseEventData(self, variable_length_section): event_data = WinJobEventData() event_data.application = ( variable_length_section.application_name.rstrip('\x00')) event_data.comment = variable_length_section.comment.rstrip('\x00') event_data.parameters = ( variable_length_sectio...
287,721
Parses the last run time from a fixed-length data section. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. fixed_length_section (job_fixed_length_data_section): a Windows Scheduled Task job fixed-length d...
def _ParseLastRunTime(self, parser_mediator, fixed_length_section): systemtime_struct = fixed_length_section.last_run_time system_time_tuple = ( systemtime_struct.year, systemtime_struct.month, systemtime_struct.weekday, systemtime_struct.day_of_month, systemtime_struct.hours, syste...
287,722
Parses the end time from a trigger. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. trigger (job_trigger): a trigger. Returns: dfdatetime.DateTimeValues: last run date and time or None if not a...
def _ParseTriggerEndTime(self, parser_mediator, trigger): time_elements_tuple = ( trigger.end_date.year, trigger.end_date.month, trigger.end_date.day_of_month, 0, 0, 0) date_time = None if time_elements_tuple != (0, 0, 0, 0, 0, 0): try: date_time = dfdatetime_time_element...
287,723
Parses the start time from a trigger. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. trigger (job_trigger): a trigger. Returns: dfdatetime.DateTimeValues: last run date and time or None if not ...
def _ParseTriggerStartTime(self, parser_mediator, trigger): time_elements_tuple = ( trigger.start_date.year, trigger.start_date.month, trigger.start_date.day_of_month, trigger.start_time.hours, trigger.start_time.minutes, 0) date_time = None if time_elements_tuple != (0, 0, 0, ...
287,724
Parses a Windows job 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): fixed_section_data_map = self._GetDataTypeMap( 'job_fixed_length_data_section') try: fixed_length_section, file_offset = self._ReadStructureFromFileObject( file_object, 0, fixed_section_data_map) except (ValueError, error...
287,725
Parses and validates options. Args: options (argparse.Namespace): parser options. analysis_plugin (AnalysisPlugin): analysis plugin to configure. Raises: BadConfigObject: when the output module object is of the wrong type. BadConfigOption: when a configuration parameter fails validatio...
def ParseOptions(cls, options, analysis_plugin): if not isinstance(analysis_plugin, tagging.TaggingAnalysisPlugin): raise errors.BadConfigObject( 'Analysis plugin is not an instance of TaggingAnalysisPlugin') tagging_file = cls._ParseStringOption(options, 'tagging_file') if not tagging...
287,726
Initializes a circular buffer object. Args: size (int): number of elements in the buffer.
def __init__(self, size): super(CircularBuffer, self).__init__() self._index = 0 self._list = [] self._size = size
287,727
Add an item to the list. Args: item (object): item.
def Append(self, item): if self._index >= self._size: self._index = self._index % self._size try: self._list[self._index] = item except IndexError: self._list.append(item) self._index += 1
287,729
Initializes an event data attribute container. Args: data_type (Optional[str]): event data type indicator.
def __init__(self, data_type=None): super(EventData, self).__init__() self.data_type = data_type self.offset = None self.query = None
287,732
Initializes an event tag attribute container. Args: comment (Optional[str]): comments.
def __init__(self, comment=None): super(EventTag, self).__init__() self._event_identifier = None self.comment = comment self.event_entry_index = None self.event_row_identifier = None self.event_stream_number = None self.labels = []
287,734
Adds a comment to the event tag. Args: comment (str): comment.
def AddComment(self, comment): if not comment: return if not self.comment: self.comment = comment else: self.comment = ''.join([self.comment, comment])
287,735
Adds a label to the event tag. Args: label (str): label. Raises: TypeError: if the label provided is not a string. ValueError: if a label is malformed.
def AddLabel(self, label): if not isinstance(label, py2to3.STRING_TYPES): raise TypeError('label is not a string type. Is {0:s}'.format( type(label))) if not self._VALID_LABEL_REGEX.match(label): raise ValueError(( 'Unsupported label: "{0:s}". A label must only consist of ' ...
287,736
Adds labels to the event tag. Args: labels (list[str]): labels. Raises: ValueError: if a label is malformed.
def AddLabels(self, labels): for label in labels: if not self._VALID_LABEL_REGEX.match(label): raise ValueError(( 'Unsupported label: "{0:s}". A label must only consist of ' 'alphanumeric characters or underscores.').format(label)) for label in labels: if label ...
287,737
Copies a string to a label. A label only supports a limited set of characters therefore unsupported characters are replaced with an underscore. Args: text (str): label text. prefix (Optional[str]): label prefix. Returns: str: label.
def CopyTextToLabel(cls, text, prefix=''): text = '{0:s}{1:s}'.format(prefix, text) return cls._INVALID_LABEL_CHARACTERS_REGEX.sub('_', text)
287,739
Parses a FILETIME date and time value from a byte stream. Args: byte_stream (bytes): byte stream. Returns: dfdatetime.Filetime: FILETIME date and time value or None if no value is set. Raises: ParseError: if the FILETIME could not be parsed.
def _ParseFiletime(self, byte_stream): filetime_map = self._GetDataTypeMap('filetime') try: filetime = self._ReadStructureFromByteStream( byte_stream, 0, filetime_map) except (ValueError, errors.ParseError) as exception: raise errors.ParseError( 'Unable to parse FILETIM...
287,743
Extracts events from a ShutdownTime Windows Registry value. 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): shutdown_value = registry_key.GetValueByName('ShutdownTime') if not shutdown_value: return try: date_time = self._ParseFiletime(shutdown_value.data) except errors.ParseError as exception: parser_mediator.ProduceExt...
287,744
Parses a Windows Shortcut (LNK) 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): display_name = parser_mediator.GetDisplayName() self.ParseFileLNKFile(parser_mediator, file_object, display_name)
287,746
Parses a Windows Shortcut (LNK) 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. display_name (str): display name.
def ParseFileLNKFile( self, parser_mediator, file_object, display_name): lnk_file = pylnk.file() lnk_file.set_ascii_codepage(parser_mediator.codepage) try: lnk_file.open_file_object(file_object) except IOError as exception: parser_mediator.ProduceExtractionWarning( 'una...
287,747
Adds command line arguments to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper supports. Args: argument_group (argparse._ArgumentGroup|argparse.ArgumentParser): argparse group.
def AddArguments(cls, argument_group): argument_group.add_argument( '--slice', metavar='DATE', dest='slice', type=str, default='', action='store', help=( 'Create a time slice around a certain date. This parameter, if ' 'defined will display all events that happened X min...
287,749
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. BadConfigOption: when a configuration...
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_expression = cls._ParseStringOption(options, 'filter') filter_object = None if f...
287,750
Initializes a log2timeline 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(Log2TimelineTool, self).__init__( input_reader=input_reader, output_writer=output_writer) self._command_line_arguments = None self._enable_sigsegv_handler = False self._number_of_extraction_workers = 0 self._storage_serial...
287,751
Parses the options. Args: options (argparse.Namespace): command line arguments. Raises: BadConfigOption: if the options are invalid.
def ParseOptions(self, options): # The extraction options are dependent on the data location. helpers_manager.ArgumentHelperManager.ParseOptions( options, self, names=['data_location']) self._ReadParserPresetsFromFile() # Check the list options first otherwise required options will raise....
287,754
Parses an Android usage-history 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): data = file_object.read(self._HEADER_READ_SIZE) if not data.startswith(b'<?xml'): raise errors.UnableToParseFile( 'Not an Android usage history file [not XML]') _, _, data = data.partition(b'\n') if not data.startswith(b'<usa...
287,758
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. BadConfigOption: if the required arti...
def ParseOptions(cls, options, configuration_object): if not isinstance(configuration_object, tools.CLITool): raise errors.BadConfigObject( 'Configuration object is not an instance of CLITool') artifacts_path = getattr(options, 'artifact_definitions_path', None) data_location = getatt...
287,759
Parses and validates options. Args: options (argparse.Namespace): parser options. analysis_plugin (WindowsServicePlugin): analysis plugin to configure. Raises: BadConfigObject: when the output module object is of the wrong type.
def ParseOptions(cls, options, analysis_plugin): if not isinstance( analysis_plugin, windows_services.WindowsServicesAnalysisPlugin): raise errors.BadConfigObject(( 'Analysis plugin is not an instance of ' 'WindowsServicesAnalysisPlugin')) output_format = cls._ParseString...
287,760
Opens a Windows Registry file-like object. Args: file_object (dfvfs.FileIO): Windows Registry file-like object. ascii_codepage (Optional[str]): ASCII string codepage. Returns: WinRegistryFile: Windows Registry file or None.
def Open(self, file_object, ascii_codepage='cp1252'): registry_file = dfwinreg_regf.REGFWinRegistryFile( ascii_codepage=ascii_codepage) # We don't catch any IOErrors here since we want to produce a parse error # from the parser if this happens. registry_file.Open(file_object) return r...
287,761
Determines if a plugin can process a Windows Registry key or its values. Args: registry_key (dfwinreg.WinRegistryKey): Windows Registry key. plugin (WindowsRegistryPlugin): Windows Registry plugin. Returns: bool: True if the Registry key can be processed with the plugin.
def _CanProcessKeyWithPlugin(self, registry_key, plugin): for registry_key_filter in plugin.FILTERS: # Skip filters that define key paths since they are already # checked by the path filter. if getattr(registry_key_filter, 'key_paths', []): continue if registry_key_filter.Match...
287,763
Parses the Registry key with a specific plugin. Args: parser_mediator (ParserMediator): parser mediator. registry_key (dfwinreg.WinRegistryKey): Windwos Registry key. plugin (WindowsRegistryPlugin): Windows Registry plugin.
def _ParseKeyWithPlugin(self, parser_mediator, registry_key, plugin): try: plugin.UpdateChainAndProcess(parser_mediator, registry_key) except (IOError, dfwinreg_errors.WinRegistryValueError) as exception: parser_mediator.ProduceExtractionWarning( 'in key: {0:s} error: {1!s}'.format(re...
287,764
Normalizes a Windows Registry key path. Args: key_path (str): Windows Registry key path. Returns: str: normalized Windows Registry key path.
def _NormalizeKeyPath(self, key_path): normalized_key_path = key_path.lower() # The Registry key path should start with: # HKEY_LOCAL_MACHINE\System\ControlSet followed by 3 digits # which makes 39 characters. if (len(normalized_key_path) < 39 or not normalized_key_path.startswith(self....
287,765
Parses the Registry key with a specific plugin. Args: parser_mediator (ParserMediator): parser mediator. registry_key (dfwinreg.WinRegistryKey): Windwos Registry key.
def _ParseKey(self, parser_mediator, registry_key): matching_plugin = None normalized_key_path = self._NormalizeKeyPath(registry_key.path) if self._path_filter.CheckPath(normalized_key_path): matching_plugin = self._plugin_per_key_path[normalized_key_path] else: for plugin in self._plu...
287,766
Parses the Registry keys recursively. Args: parser_mediator (ParserMediator): parser mediator. root_key (dfwinreg.WinRegistryKey): root Windows Registry key.
def _ParseRecurseKeys(self, parser_mediator, root_key): for registry_key in root_key.RecurseKeys(): if parser_mediator.abort: break self._ParseKey(parser_mediator, registry_key)
287,767
Parses the Registry keys from FindSpecs. Args: parser_mediator (ParserMediator): parser mediator. win_registry (dfwinreg.WinRegistryKey): root Windows Registry key. find_specs (dfwinreg.FindSpecs): Keys to search for.
def _ParseKeysFromFindSpecs(self, parser_mediator, win_registry, find_specs): searcher = dfwinreg_registry_searcher.WinRegistrySearcher(win_registry) for registry_key_path in iter(searcher.Find(find_specs=find_specs)): if parser_mediator.abort: break registry_key = searcher.GetKeyByPat...
287,768
Parses a Windows Registry file-like object. Args: parser_mediator (ParserMediator): parser mediator. file_object (dfvfs.FileIO): a file-like object.
def ParseFileObject(self, parser_mediator, file_object): win_registry_reader = FileObjectWinRegistryFileReader() try: registry_file = win_registry_reader.Open(file_object) except IOError as exception: parser_mediator.ProduceExtractionWarning( 'unable to open Windows Registry file...
287,769
Creates a storage reader based on the file. Args: path (str): path to the storage file. Returns: StorageReader: a storage reader or None if the storage file cannot be opened or the storage format is not supported.
def CreateStorageReaderForFile(cls, path): if sqlite_file.SQLiteStorageFile.CheckSupportedFormat( path, check_readable_only=True): return sqlite_reader.SQLiteStorageFileReader(path) return None
287,770
Creates a storage writer. Args: session (Session): session the storage changes are part of. path (str): path to the storage file. storage_format (str): storage format. Returns: StorageWriter: a storage writer or None if the storage file cannot be opened or the storage format ...
def CreateStorageWriter(cls, storage_format, session, path): if storage_format == definitions.STORAGE_FORMAT_SQLITE: return sqlite_writer.SQLiteStorageFileWriter(session, path) return None
287,771
Creates a storage writer based on the file. Args: session (Session): session the storage changes are part of. path (str): path to the storage file. Returns: StorageWriter: a storage writer or None if the storage file cannot be opened or the storage format is not supported.
def CreateStorageWriterForFile(cls, session, path): if sqlite_file.SQLiteStorageFile.CheckSupportedFormat(path): return sqlite_writer.SQLiteStorageFileWriter(session, path) return None
287,772
Initializes the output module object. Args: output_mediator (OutputMediator): mediates interactions between output modules and other components, such as storage and dfvfs.
def __init__(self, output_mediator): super(MySQL4n6TimeOutputModule, self).__init__(output_mediator) self._connection = None self._count = None self._cursor = None self._dbname = 'log2timeline' self._host = 'localhost' self._password = 'forensic' self._port = None self._user = '...
287,773
Sets the database credentials. Args: password (Optional[str]): password to access the database. username (Optional[str]): username to access the database.
def SetCredentials(self, password=None, username=None): if password: self._password = password if username: self._user = username
287,775
Sets the server information. Args: server (str): hostname or IP address of the database server. port (int): port number of the database server.
def SetServerInformation(self, server, port): self._host = server self._port = port
287,776
Writes the body of an event object to the output. Args: event (EventObject): event.
def WriteEventBody(self, event): if not hasattr(event, 'timestamp'): return row = self._GetSanitizedEventValues(event) try: self._cursor.execute(self._INSERT_QUERY, row) except MySQLdb.Error as exception: logger.warning( 'Unable to insert into database with error: {0!s}...
287,777
Initializes a table view. Args: column_names (Optional[list[str]]): column names. title (Optional[str]): title.
def __init__(self, column_names=None, title=None): super(BaseTableView, self).__init__() self._columns = column_names or [] self._number_of_columns = len(self._columns) self._rows = [] self._title = title
287,779
Adds a row of values. Args: values (list[object]): values. Raises: ValueError: if the number of values is out of bounds.
def AddRow(self, values): if self._number_of_columns and len(values) != self._number_of_columns: raise ValueError('Number of values is out of bounds.') self._rows.append(values) if not self._number_of_columns: self._number_of_columns = len(values)
287,780
Initializes a command line table view. Args: column_names (Optional[list[str]]): column names. title (Optional[str]): title.
def __init__(self, column_names=None, title=None): super(CLITableView, self).__init__(column_names=column_names, title=title) if self._columns: self._column_width = len(self._columns[0]) else: self._column_width = 0
287,781
Writes a header. Args: output_writer (OutputWriter): output writer.
def _WriteHeader(self, output_writer): header_string = '' if self._title: header_string = ' {0:s} '.format(self._title) header_string = self._HEADER_FORMAT_STRING.format(header_string) output_writer.Write(header_string)
287,782
Writes a row of values aligned to the column width. Args: output_writer (OutputWriter): output writer. values (list[object]): values.
def _WriteRow(self, output_writer, values): maximum_row_width = self._MAXIMUM_WIDTH - self._column_width - 3 # The format string of the first line of the column value. primary_format_string = '{{0:>{0:d}s}} : {{1:s}}\n'.format( self._column_width) # The format string of successive lines o...
287,783
Adds a row of values. Args: values (list[object]): values. Raises: ValueError: if the number of values is out of bounds.
def AddRow(self, values): super(CLITableView, self).AddRow(values) value_length = len(values[0]) if value_length > self._column_width: self._column_width = value_length
287,784
Writes the table to the output writer. Args: output_writer (OutputWriter): output writer. Raises: RuntimeError: if the title exceeds the maximum width or if the table has more than 2 columns or if the column width is out of bounds.
def Write(self, output_writer): if self._title and len(self._title) > self._MAXIMUM_WIDTH: raise RuntimeError('Title length out of bounds.') if self._number_of_columns not in (0, 2): raise RuntimeError('Unsupported number of columns: {0:d}.'.format( self._number_of_columns)) if ...
287,785
Initializes a command line table view. Args: column_names (Optional[list[str]]): column names. column_sizes (Optional[list[int]]): minimum column sizes, in number of characters. If a column name or row value is larger than the minimum column size the column will be enlarged. Note th...
def __init__(self, column_names=None, column_sizes=None, title=None): super(CLITabularTableView, self).__init__( column_names=column_names, title=title) self._column_sizes = column_sizes or []
287,786
Adds a row of values. Args: values (list[object]): values. Raises: ValueError: if the number of values is out of bounds.
def AddRow(self, values): if self._number_of_columns and len(values) != self._number_of_columns: raise ValueError('Number of values is out of bounds.') if not self._column_sizes and self._columns: self._column_sizes = [len(column) for column in self._columns] value_strings = [] for va...
287,787
Writes the table to the output writer. Args: output_writer (OutputWriter): output writer.
def Write(self, output_writer): if self._title: output_writer.Write('### {0:s}\n\n'.format(self._title)) if not self._columns: self._columns = ['' for _ in range(0, self._number_of_columns)] output_writer.Write(' | '.join(self._columns)) output_writer.Write('\n') output_writer.Wr...
287,788
Retrieves a table view. Args: format_type (str): table view format type. column_names (Optional[list[str]]): column names. title (Optional[str]): title. Returns: BaseTableView: table view. Raises: ValueError: if the format type is not supported.
def GetTableView(cls, format_type, column_names=None, title=None): view_class = cls._TABLE_VIEW_FORMAT_CLASSES.get(format_type, None) if not view_class: raise ValueError('Unsupported format type: {0:s}'.format(format_type)) return view_class(column_names=column_names, title=title)
287,789
Retrieves a data type map defined by the definition file. The data type maps are cached for reuse. Args: name (str): name of the data type as defined by the definition file. Returns: dtfabric.DataTypeMap: data type map which contains a data type definition, such as a structure, that...
def _GetDataTypeMap(self, name): data_type_map = self._data_type_maps.get(name, None) if not data_type_map: data_type_map = self._fabric.CreateDataTypeMap(name) self._data_type_maps[name] = data_type_map return data_type_map
287,791
Reads a dtFabric definition file. Args: filename (str): name of the dtFabric definition file. Returns: dtfabric.DataTypeFabric: data type fabric which contains the data format data type maps of the data type definition, such as a structure, that can be mapped onto binary data o...
def _ReadDefinitionFile(self, filename): if not filename: return None path = os.path.join(self._DEFINITION_FILES_PATH, filename) with open(path, 'rb') as file_object: definition = file_object.read() return dtfabric_fabric.DataTypeFabric(yaml_definition=definition)
287,792
Parses URIs containing .md and replaces them with their HTML page. Args: node(node): docutils node. Returns: node: docutils node.
def find_and_replace(self, node): if isinstance(node, nodes.reference) and 'refuri' in node: reference_uri = node['refuri'] if reference_uri.endswith('.md') and not reference_uri.startswith('http'): reference_uri = reference_uri[:-3] + '.html' node['refuri'] = reference_uri el...
287,796
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( '--fields', dest='fields', type=str, action='store', default=cls._DEFAULT_FIELDS, help=( 'Defines which fields should be included in the output.')) argument_group.add_argument( '--additional_fields', des...
287,798
Parses and validates options. Args: options (argparse.Namespace): parser options. output_module (XLSXOutputModule): 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, xlsx.XLSXOutputModule): raise errors.BadConfigObject( 'Output module is not an instance of XLSXOutputModule') fields = cls._ParseStringOption( options, 'fields', default_value=cls._DEFAULT_FIELDS) ...
287,799
Build a dictionary of the value in the strings table. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. table (pyesedb.table): strings table. Returns: dict[str,object]: values per column name.
def _GetDictFromStringsTable(self, parser_mediator, table): if not table: return {} record_values = {} for record in table.records: if parser_mediator.abort: break if record.get_number_of_values() != 2: continue identification = self._GetRecordValue(record, 0)...
287,803
Parses the namespace table. 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. table (Optional[pyesedb.table]): table. ...
def ParseNameSpace( self, parser_mediator, cache=None, database=None, table=None, **unused_kwargs): if database is None: raise ValueError('Missing database value.') if table is None: raise ValueError('Missing table value.') strings = cache.GetResults('strings') if not stri...
287,804
Initializes a date and time range. The timestamp are integers containing the number of microseconds since January 1, 1970, 00:00:00 UTC. Args: start_timestamp (int): timestamp that marks the start of the range. end_timestamp (int): timestamp that marks the end of the range. Raises: ...
def __init__(self, start_timestamp, end_timestamp): if start_timestamp is None or end_timestamp is None: raise ValueError( 'Time range must have either a start and an end timestamp.') if start_timestamp > end_timestamp: raise ValueError( 'Invalid start must be earlier than ...
287,805
Initializes an analysis plugin mediator. Args: storage_writer (StorageWriter): storage writer. knowledge_base (KnowledgeBase): contains information from the source data needed for analysis. data_location (Optional[str]): location of data files used during analysis.
def __init__(self, storage_writer, knowledge_base, data_location=None): super(AnalysisMediator, self).__init__() self._abort = False self._data_location = data_location self._event_filter_expression = None self._knowledge_base = knowledge_base self._mount_path = None self._storage_write...
287,806
Retrieves the display name for a path specification. Args: path_spec (dfvfs.PathSpec): path specification. Returns: str: human readable version of the path specification.
def GetDisplayNameForPathSpec(self, path_spec): return path_helper.PathHelper.GetDisplayNameForPathSpec( path_spec, mount_path=self._mount_path, text_prepend=self._text_prepend)
287,807
Produces an analysis report. Args: plugin (AnalysisPlugin): plugin.
def ProduceAnalysisReport(self, plugin): analysis_report = plugin.CompileReport(self) if not analysis_report: return analysis_report.time_compiled = timelib.Timestamp.GetNow() plugin_name = getattr(analysis_report, 'plugin_name', plugin.plugin_name) if plugin_name: analysis_report...
287,808
Produces an event tag. Args: event_tag (EventTag): event tag.
def ProduceEventTag(self, event_tag): self._storage_writer.AddEventTag(event_tag) self.number_of_produced_event_tags += 1 self.last_activity_timestamp = time.time()
287,809
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): event_values = event.CopyToDict() # TODO: clean up the default formatter and add a test to make sure # it is clear how it is intended to work. text_pieces = [] for key, value in event_values.items(): if key in definitions.RESERVED_VARIABL...
287,810
Adds command line arguments to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper supports. Args: argument_group (argparse._ArgumentGroup|argparse.ArgumentParser): argparse group.
def AddArguments(cls, argument_group): argument_group.add_argument( '--language', metavar='LANGUAGE', dest='preferred_language', default='en-US', type=str, help=( 'The preferred language identifier for Windows Event Log message ' 'strings. Use "--language list" to see a ...
287,811
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') preferred_language = cls._ParseStringOption( options, 'preferred_language', default_valu...
287,812
Pushes an event onto the heap. Args: event (EventObject): event.
def PushEvent(self, event): macb_group_identifier, content_identifier = self._GetEventIdentifiers(event) # We can ignore the timestamp here because the psort engine only stores # events with the same timestamp in the event heap. heap_values = (macb_group_identifier or '', content_identifier, event...
287,816
Initializes an engine object. Args: use_zeromq (Optional[bool]): True if ZeroMQ should be used for queuing instead of Python's multiprocessing queue.
def __init__(self, use_zeromq=True): super(PsortMultiProcessEngine, self).__init__() self._analysis_plugins = {} self._completed_analysis_processes = set() self._data_location = None self._event_filter_expression = None self._event_queues = {} self._event_tag_index = event_tag_index.Eve...
287,817