INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
See db.Database.
def WriteClientGraphSeries(self, graph_series, client_label, timestamp): """See db.Database.""" series_key = (client_label, graph_series.report_type, timestamp.Copy()) self.client_graph_series[series_key] = graph_series.Copy()
See db.Database.
def ReadAllClientGraphSeries( self, client_label, report_type, time_range = None, ): """See db.Database.""" series_with_timestamps = {} for series_key, series in iteritems(self.client_graph_series): series_label, series_type, timestamp = series_key if series_label == cl...
See db.Database.
def ReadMostRecentClientGraphSeries(self, client_label, report_type ): """See db.Database.""" series_with_timestamps = self.ReadAllClientGraphSeries( client_label, report_type) if not series_with_timestamps: return None...
Set the value into the data store.
def Set(self, subject, attribute, value, timestamp=None, replace=True, sync=True): """Set the value into the data store.""" subject = utils.SmartUnicode(subject) _ = sync attribute = utils.SmartUnicode(attribute) if timestamp is None or t...
Resolve all attributes for a subject starting with a prefix.
def ResolvePrefix(self, subject, attribute_prefix, timestamp=None, limit=None): """Resolve all attributes for a subject starting with a prefix.""" subject = utils.SmartUnicode(subject) if timestamp in [None, self.NEWEST_TIMESTAMP, self.ALL_TIMESTAMPS]: start, end = 0, (2**63) - 1 ...
Processes a single fleetspeak message.
def Process(self, fs_msg, context): """Processes a single fleetspeak message.""" try: if fs_msg.message_type == "GrrMessage": grr_message = rdf_flows.GrrMessage.FromSerializedString( fs_msg.data.value) self._ProcessGRRMessages(fs_msg.source.client_id, [grr_message]) elif ...
Handles messages from GRR clients received via Fleetspeak. This method updates the last-ping timestamp of the client before beginning processing. Args: fs_client_id: The Fleetspeak client-id for the client. grr_messages: An Iterable of GrrMessages.
def _ProcessGRRMessages(self, fs_client_id, grr_messages): """Handles messages from GRR clients received via Fleetspeak. This method updates the last-ping timestamp of the client before beginning processing. Args: fs_client_id: The Fleetspeak client-id for the client. grr_messages: An Iter...
Perform all checks on a host using acquired artifacts. Checks are selected based on the artifacts available and the host attributes (e.g. os_name/cpe/labels) provided as either parameters, or in the knowledgebase artifact. A KnowledgeBase artifact should be provided that contains, at a minimum: - OS - Hos...
def CheckHost(host_data, os_name=None, cpe=None, labels=None, exclude_checks=None, restrict_checks=None): """Perform all checks on a host using acquired artifacts. Checks are selected based on the artifacts available and the host attributes (e...
Load a single check from a file.
def LoadCheckFromFile(file_path, check_id, overwrite_if_exists=True): """Load a single check from a file.""" configs = LoadConfigsFromFile(file_path) conf = configs.get(check_id) check = Check(**conf) check.Validate() CheckRegistry.RegisterCheck( check, source="file:%s" % file_path, overwr...
Load the checks defined in the specified files.
def LoadChecksFromFiles(file_paths, overwrite_if_exists=True): """Load the checks defined in the specified files.""" loaded = [] for file_path in file_paths: configs = LoadConfigsFromFile(file_path) for conf in itervalues(configs): check = Check(**conf) # Validate will raise if the check doesn...
Processes data according to formatting rules.
def Render(self, rdf_data): """Processes data according to formatting rules.""" report_data = rdf_data[:self.max_results] results = [self.hinter.Render(rdf) for rdf in report_data] extra = len(rdf_data) - len(report_data) if extra > 0: results.append("...plus another %d issues." % extra) r...
Process rdf data through the filter. Filters sift data according to filter rules. Data that passes the filter rule is kept, other data is dropped. If no filter method is provided, the data is returned as a list. Otherwise, a items that meet filter conditions are returned in a list. Args: rd...
def Parse(self, rdf_data): """Process rdf data through the filter. Filters sift data according to filter rules. Data that passes the filter rule is kept, other data is dropped. If no filter method is provided, the data is returned as a list. Otherwise, a items that meet filter conditions are retur...
The filter exists, and has valid filter and hint expressions.
def Validate(self): """The filter exists, and has valid filter and hint expressions.""" if self.type not in filters.Filter.classes: raise DefinitionError("Undefined filter type %s" % self.type) self._filter.Validate(self.expression) Validate(self.hint, "Filter has invalid hint")
Process rdf data through filters. Test if results match expectations. Processing of rdf data is staged by a filter handler, which manages the processing of host data. The output of the filters are compared against expected results. Args: rdf_data: An list containing 0 or more rdf values. Re...
def Parse(self, rdf_data): """Process rdf data through filters. Test if results match expectations. Processing of rdf data is staged by a filter handler, which manages the processing of host data. The output of the filters are compared against expected results. Args: rdf_data: An list contai...
Check the test set is well constructed.
def Validate(self): """Check the test set is well constructed.""" Validate(self.target, "Probe has invalid target") self.baseliner.Validate() self.handler.Validate() self.hint.Validate()
Runs probes that evaluate whether collected data has an issue. Args: conditions: The trigger conditions. host_data: A map of artifacts and rdf data. Returns: Anomalies if an issue exists.
def Parse(self, conditions, host_data): """Runs probes that evaluate whether collected data has an issue. Args: conditions: The trigger conditions. host_data: A map of artifacts and rdf data. Returns: Anomalies if an issue exists. """ processed = [] probes = self.triggers.Cal...
Check the Method is well constructed.
def Validate(self): """Check the Method is well constructed.""" ValidateMultiple(self.probe, "Method has invalid probes") Validate(self.target, "Method has invalid target") Validate(self.hint, "Method has invalid hint")
Merge anomalies from another CheckResult.
def ExtendAnomalies(self, other): """Merge anomalies from another CheckResult.""" for o in other: if o is not None: self.anomaly.Extend(list(o.anomaly))
Determines if the check uses the specified artifact. Args: artifacts: Either a single artifact name, or a list of artifact names Returns: True if the check uses a specific artifact.
def UsesArtifact(self, artifacts): """Determines if the check uses the specified artifact. Args: artifacts: Either a single artifact name, or a list of artifact names Returns: True if the check uses a specific artifact. """ # If artifact is a single string, see if it is in the list of ...
Runs methods that evaluate whether collected host_data has an issue. Args: conditions: A list of conditions to determine which Methods to trigger. host_data: A map of artifacts and rdf data. Returns: A CheckResult populated with Anomalies if an issue exists.
def Parse(self, conditions, host_data): """Runs methods that evaluate whether collected host_data has an issue. Args: conditions: A list of conditions to determine which Methods to trigger. host_data: A map of artifacts and rdf data. Returns: A CheckResult populated with Anomalies if an ...
Check the method is well constructed.
def Validate(self): """Check the method is well constructed.""" if not self.check_id: raise DefinitionError("Check has missing check_id value") cls_name = self.check_id if not self.method: raise DefinitionError("Check %s has no methods" % cls_name) ValidateMultiple(self.method, ...
Run host_data through detectors and return them if a detector triggers. Args: baseline: The base set of rdf values used to evaluate whether an issue exists. host_data: The rdf values passed back by the filters. Returns: A CheckResult message containing anomalies if any detectors iden...
def Detect(self, baseline, host_data): """Run host_data through detectors and return them if a detector triggers. Args: baseline: The base set of rdf values used to evaluate whether an issue exists. host_data: The rdf values passed back by the filters. Returns: A CheckResult mess...
Collect anomalous findings into a CheckResult. Comparisons with anomalous conditions collect anomalies into a single CheckResult message. The contents of the result varies depending on whether the method making the comparison is a Check, Method or Probe. - Probes evaluate raw host data and generate Ano...
def Issue(self, state, results): """Collect anomalous findings into a CheckResult. Comparisons with anomalous conditions collect anomalies into a single CheckResult message. The contents of the result varies depending on whether the method making the comparison is a Check, Method or Probe. - Probes...
Anomaly if baseline vs result counts differ, an empty list otherwise.
def GotAll(self, baseline, results): """Anomaly if baseline vs result counts differ, an empty list otherwise.""" num_base = len(baseline) num_rslt = len(results) if num_rslt > num_base: raise ProcessingError("Filter generated more results than base data: " "%s > %s" % (...
Adds a check to the registry, refresh the trigger to check map.
def RegisterCheck(cls, check, source="unknown", overwrite_if_exists=False): """Adds a check to the registry, refresh the trigger to check map.""" if not overwrite_if_exists and check.check_id in cls.checks: raise DefinitionError( "Check named %s already exists and " "overwrite_if_exist...
Encapsulates an argument in a list, if it's not already iterable.
def _AsList(arg): """Encapsulates an argument in a list, if it's not already iterable.""" if (isinstance(arg, string_types) or not isinstance(arg, collections.Iterable)): return [arg] else: return list(arg)
Provide a series of condition tuples. A Target can specify multiple artifact, os_name, cpe or label entries. These are expanded to all distinct tuples. When an entry is undefined or None, it is treated as a single definition of None, meaning that the condition does not apply. Args: artifact:...
def Conditions(cls, artifact=None, os_name=None, cpe=None, labels=None): """Provide a series of condition tuples. A Target can specify multiple artifact, os_name, cpe or label entries. These are expanded to all distinct tuples. When an entry is undefined or None, it is treated as a single definition of...
Takes targeting info, identifies relevant checks. FindChecks will return results when a host has the conditions necessary for a check to occur. Conditions with partial results are not returned. For example, FindChecks will not return checks that if a check targets os_name=["Linux"], labels=["foo"] and ...
def FindChecks(cls, artifact=None, os_name=None, cpe=None, labels=None, restrict_checks=None): """Takes targeting info, identifies relevant checks. FindChecks will return results when a host has the conditions necessary for ...
Runs checks over all host data. Args: host_data: The data collected from a host, mapped to artifact name. os_name: 0+ OS names. cpe: 0+ CPE identifiers. labels: 0+ GRR labels. exclude_checks: A list of check ids not to run. A check id in this list will not get ru...
def Process(cls, host_data, os_name=None, cpe=None, labels=None, exclude_checks=None, restrict_checks=None): """Runs checks over all host data. Args: host_data: The data collected from a host, mapped to artifact name. ...
Returns a pseudo-random 32-bit unsigned integer.
def UInt32(): """Returns a pseudo-random 32-bit unsigned integer.""" with _mutex: try: return _random_buffer.pop() except IndexError: data = os.urandom(struct.calcsize("=L") * _random_buffer_size) _random_buffer.extend( struct.unpack("=" + "L" * _random_buffer_size, data)) ...
Set up some vars for the directories we use.
def SetupVars(self): """Set up some vars for the directories we use.""" # Python paths chosen to match appveyor: # http://www.appveyor.com/docs/installed-software#python self.python_dir_64 = args.python64_dir self.python_dir_32 = args.python32_dir self.virtualenv_bin64 = os.path.join(self.pyth...
Clean the build environment.
def Clean(self): """Clean the build environment.""" # os.unlink doesn't work effectively, use the shell to delete. if os.path.exists(args.build_dir): subprocess.call("rd /s /q %s" % args.build_dir, shell=True) if os.path.exists(args.output_dir): subprocess.call("rd /s /q %s" % args.output_di...
Installs GRR.
def InstallGRR(self, path): """Installs GRR.""" cmd64 = [self.pip64, "install"] cmd32 = [self.pip32, "install"] if args.wheel_dir: cmd64 += ["--no-index", r"--find-links=file:///%s" % args.wheel_dir] cmd32 += ["--no-index", r"--find-links=file:///%s" % args.wheel_dir] cmd64.append(pat...
Builds the client templates. We dont need to run special compilers so just enter the virtualenv and build. Python will already find its own MSVC for python compilers.
def BuildTemplates(self): """Builds the client templates. We dont need to run special compilers so just enter the virtualenv and build. Python will already find its own MSVC for python compilers. """ if args.config: build_args = [ "--verbose", "--config", args.config, "build", "--ou...
Install the installer built by RepackTemplates.
def _InstallInstallers(self): """Install the installer built by RepackTemplates.""" # 32 bit binary will refuse to install on a 64bit system so we only install # the 64 bit version installer_amd64 = glob.glob( os.path.join(args.output_dir, "dbg_*_amd64.exe")).pop() self._CleanupInstall() ...
Cleanup from any previous installer enough for _CheckInstallSuccess.
def _CleanupInstall(self): """Cleanup from any previous installer enough for _CheckInstallSuccess.""" if os.path.exists(self.install_path): shutil.rmtree(self.install_path) if os.path.exists(self.install_path): raise RuntimeError("Install path still exists: %s" % self.install_path) # De...
Checks if the installer installed correctly.
def _CheckInstallSuccess(self): """Checks if the installer installed correctly.""" if not os.path.exists(self.install_path): raise RuntimeError("Install failed, no files at: %s" % self.install_path) try: output = subprocess.check_output(["sc", "query", self.service_name]) service_running ...
Repack templates with a dummy config.
def _RepackTemplates(self): """Repack templates with a dummy config.""" dummy_config = os.path.join( args.grr_src, "grr/test/grr_response_test/test_data/dummyconfig.yaml") if args.build_32: template_i386 = glob.glob(os.path.join(args.output_dir, "*_...
Ensures that given value has certain type. Args: value: A value to assert the type for. expected_type: An expected type for the given value. Raises: TypeError: If given value does not have the expected type.
def AssertType(value, expected_type): """Ensures that given value has certain type. Args: value: A value to assert the type for. expected_type: An expected type for the given value. Raises: TypeError: If given value does not have the expected type. """ if not isinstance(value, expected_type): ...
Build templates.
def Build(self): """Build templates.""" self.SetupVars() self.Clean() if not os.path.exists(args.grr_src): self.GitCheckoutGRR() proto_sdist = self.MakeProtoSdist() core_sdist = self.MakeCoreSdist() client_sdist = self.MakeClientSdist() client_builder_sdist = self.MakeClientBuilde...
Ensures that given iterable container has certain type. Args: iterable: An iterable container to assert the type for. expected_item_type: An expected type of the container items. Raises: TypeError: If given container does is not an iterable or its items do not have the expected type.
def AssertIterableType(iterable, expected_item_type): """Ensures that given iterable container has certain type. Args: iterable: An iterable container to assert the type for. expected_item_type: An expected type of the container items. Raises: TypeError: If given container does is not an iterable or...
Ensures that given dictionary is actually a dictionary of specified type. Args: dct: A dictionary to assert the type for. expected_key_type: An expected type for dictionary keys. expected_value_type: An expected type for dictionary values. Raises: TypeError: If given dictionary is not really a dic...
def AssertDictType(dct, expected_key_type, expected_value_type): """Ensures that given dictionary is actually a dictionary of specified type. Args: dct: A dictionary to assert the type for. expected_key_type: An expected type for dictionary keys. expected_value_type: An expected type for dictionary val...
Run the single hook specified by resolving all its prerequisites.
def _RunSingleHook(self, hook_cls, executed_set, required=None): """Run the single hook specified by resolving all its prerequisites.""" # If we already ran do nothing. if hook_cls in executed_set: return # Ensure all the pre execution hooks are run. for pre_hook in hook_cls.pre: self._...
Initialize API hunt object from a database hunt object. Args: hunt_obj: rdf_hunt_objects.Hunt to read the data from. hunt_counters: Optional db.HuntCounters object with counters information. with_full_summary: if True, hunt_runner_args, completion counts and a few other fields will be fil...
def InitFromHuntObject(self, hunt_obj, hunt_counters=None, with_full_summary=False): """Initialize API hunt object from a database hunt object. Args: hunt_obj: rdf_hunt_objects.Hunt to read the data from. hunt_counters: Opti...
Init from GrrMessage rdfvalue.
def InitFromGrrMessage(self, message): """Init from GrrMessage rdfvalue.""" if message.source: self.client_id = message.source.Basename() self.payload_type = compatibility.GetName(message.payload.__class__) self.payload = message.payload self.timestamp = message.age return self
Init from rdf_flow_objects.FlowResult.
def InitFromFlowResult(self, flow_result): """Init from rdf_flow_objects.FlowResult.""" self.payload_type = compatibility.GetName(flow_result.payload.__class__) self.payload = flow_result.payload self.client_id = flow_result.client_id self.timestamp = flow_result.timestamp return self
Init from FlowLogEntry rdfvalue.
def InitFromFlowLogEntry(self, fle): """Init from FlowLogEntry rdfvalue.""" # TODO(user): putting this stub value for backwards compatibility. # Remove as soon as AFF4 is gone. self.flow_name = "GenericHunt" self.client_id = fle.client_id self.flow_id = fle.flow_id self.timestamp = fle.tim...
Initialize from rdf_flow_objects.Flow corresponding to a failed flow.
def InitFromFlowObject(self, fo): """Initialize from rdf_flow_objects.Flow corresponding to a failed flow.""" self.client_id = fo.client_id if fo.HasField("backtrace"): self.backtrace = fo.backtrace self.log_message = fo.error_message self.timestamp = fo.last_update_time return self
Check that this approval applies to the given token. Args: start_stats: A list of lists, each containing two values (a timestamp and the number of clients started at this time). complete_stats: A list of lists, each containing two values (a timestamp and the number of clients completed ...
def InitFromDataPoints(self, start_stats, complete_stats): """Check that this approval applies to the given token. Args: start_stats: A list of lists, each containing two values (a timestamp and the number of clients started at this time). complete_stats: A list of lists, each containing tw...
Resamples the stats to have a specific number of data points.
def _Resample(self, stats, target_size): """Resamples the stats to have a specific number of data points.""" t_first = stats[0][0] t_last = stats[-1][0] interval = (t_last - t_first) / target_size result = [] current_t = t_first current_v = 0 i = 0 while i < len(stats): stat_...
Retrieves the stats for a hunt.
def _HandleLegacy(self, args, token=None): """Retrieves the stats for a hunt.""" hunt_obj = aff4.FACTORY.Open( args.hunt_id.ToURN(), aff4_type=implementation.GRRHunt, token=token) stats = hunt_obj.GetRunner().context.usage_stats return ApiGetHuntStatsResult(stats=stats)
Retrieves the clients for a hunt.
def _HandleLegacy(self, args, token=None): """Retrieves the clients for a hunt.""" hunt_urn = args.hunt_id.ToURN() hunt_obj = aff4.FACTORY.Open( hunt_urn, aff4_type=implementation.GRRHunt, token=token) clients_by_status = hunt_obj.GetClientsByStatus() hunt_clients = clients_by_status[args.c...
Retrieves the context for a hunt.
def _HandleLegacy(self, args, token=None): """Retrieves the context for a hunt.""" hunt_obj = aff4.FACTORY.Open( args.hunt_id.ToURN(), aff4_type=implementation.GRRHunt, token=token) if isinstance(hunt_obj.context, rdf_hunts.HuntContext): # New style hunt. # TODO(amoser): Hunt state will go ...
Creates a new hunt.
def _HandleLegacy(self, args, token=None): """Creates a new hunt.""" # We only create generic hunts with /hunts/create requests. generic_hunt_args = rdf_hunts.GenericHuntArgs() generic_hunt_args.flow_runner_args.flow_name = args.flow_name generic_hunt_args.flow_args = args.flow_args # Clear al...
Registers a new constructor in the factory. Args: name: A name associated with given constructor. constructor: A constructor function that creates instances. Raises: ValueError: If there already is a constructor associated with given name.
def Register(self, name, constructor): """Registers a new constructor in the factory. Args: name: A name associated with given constructor. constructor: A constructor function that creates instances. Raises: ValueError: If there already is a constructor associated with given name. ""...
Unregisters a constructor. Args: name: A name of the constructor to unregister. Raises: ValueError: If constructor with specified name has never been registered.
def Unregister(self, name): """Unregisters a constructor. Args: name: A name of the constructor to unregister. Raises: ValueError: If constructor with specified name has never been registered. """ precondition.AssertType(name, Text) try: del self._constructors[name] exce...
Creates a new instance. Args: name: A name identifying the constructor to use for instantiation. Returns: An instance of the type that the factory supports.
def Create(self, name): """Creates a new instance. Args: name: A name identifying the constructor to use for instantiation. Returns: An instance of the type that the factory supports. """ precondition.AssertType(name, Text) try: constructor = self._constructors[name] exc...
Registers stat entry at a given timestamp.
def AddStatEntry(self, stat_entry, timestamp): """Registers stat entry at a given timestamp.""" if timestamp in self._stat_entries: message = ("Duplicated stat entry write for path '%s' of type '%s' at " "timestamp '%s'. Old: %s. New: %s.") message %= ("/".join(self._components), s...
Registers hash entry at a given timestamp.
def AddHashEntry(self, hash_entry, timestamp): """Registers hash entry at a given timestamp.""" if timestamp in self._hash_entries: message = ("Duplicated hash entry write for path '%s' of type '%s' at " "timestamp '%s'. Old: %s. New: %s.") message %= ("/".join(self._components), s...
Updates existing path information of the path record.
def AddPathInfo(self, path_info): """Updates existing path information of the path record.""" if self._path_type != path_info.path_type: message = "Incompatible path types: `%s` and `%s`" raise ValueError(message % (self._path_type, path_info.path_type)) if self._components != path_info.compone...
Makes the path aware of some child.
def AddChild(self, path_info): """Makes the path aware of some child.""" if self._path_type != path_info.path_type: message = "Incompatible path types: `%s` and `%s`" raise ValueError(message % (self._path_type, path_info.path_type)) if self._components != path_info.components[:-1]: messa...
Generates a summary about the path record. Args: timestamp: A point in time from which the data should be retrieved. Returns: A `rdf_objects.PathInfo` instance.
def GetPathInfo(self, timestamp=None): """Generates a summary about the path record. Args: timestamp: A point in time from which the data should be retrieved. Returns: A `rdf_objects.PathInfo` instance. """ path_info_timestamp = self._LastEntryTimestamp(self._path_infos, timestamp) ...
Searches for greatest timestamp lower than the specified one. Args: dct: A dictionary from timestamps to some items. upper_bound_timestamp: An upper bound for timestamp to be returned. Returns: Greatest timestamp that is lower than the specified one. If no such value exists, `None` is ...
def _LastEntryTimestamp(dct, upper_bound_timestamp): """Searches for greatest timestamp lower than the specified one. Args: dct: A dictionary from timestamps to some items. upper_bound_timestamp: An upper bound for timestamp to be returned. Returns: Greatest timestamp that is lower than ...
Retrieves a path info record for a given path.
def ReadPathInfo(self, client_id, path_type, components, timestamp=None): """Retrieves a path info record for a given path.""" try: path_record = self.path_records[(client_id, path_type, components)] return path_record.GetPathInfo(timestamp=timestamp) except KeyError: raise db.UnknownPathE...
Retrieves path info records for given paths.
def ReadPathInfos(self, client_id, path_type, components_list): """Retrieves path info records for given paths.""" result = {} for components in components_list: try: path_record = self.path_records[(client_id, path_type, components)] result[components] = path_record.GetPathInfo() ...
Lists path info records that correspond to children of given path.
def ListDescendentPathInfos(self, client_id, path_type, components, timestamp=None, max_depth=None): """Lists path info records that correspond to children of given p...
Writes a single path info record for given client.
def _WritePathInfo(self, client_id, path_info): """Writes a single path info record for given client.""" if client_id not in self.metadatas: raise db.UnknownClientError(client_id) path_record = self._GetPathRecord(client_id, path_info) path_record.AddPathInfo(path_info) parent_path_info = pa...
Clears path history for specified paths of given clients.
def MultiClearPathHistory(self, path_infos): """Clears path history for specified paths of given clients.""" for client_id, client_path_infos in iteritems(path_infos): self.ClearPathHistory(client_id, client_path_infos)
Clears path history for specified paths of given client.
def ClearPathHistory(self, client_id, path_infos): """Clears path history for specified paths of given client.""" for path_info in path_infos: path_record = self._GetPathRecord(client_id, path_info) path_record.ClearHistory()
Writes a collection of hash and stat entries observed for given paths.
def MultiWritePathHistory(self, client_path_histories): """Writes a collection of hash and stat entries observed for given paths.""" for client_path, client_path_history in iteritems(client_path_histories): if client_path.client_id not in self.metadatas: raise db.UnknownClientError(client_path.cli...
Reads a collection of hash and stat entries for given paths.
def ReadPathInfosHistories(self, client_id, path_type, components_list): """Reads a collection of hash and stat entries for given paths.""" results = {} for components in components_list: try: path_record = self.path_records[(client_id, path_type, components)] except KeyError: r...
Turn supported_os into a condition.
def ConvertSupportedOSToConditions(src_object): """Turn supported_os into a condition.""" if src_object.supported_os: conditions = " OR ".join("os == '%s'" % o for o in src_object.supported_os) return conditions
Prepare bundle of artifacts and their dependencies for the client. Args: flow_args: An `ArtifactCollectorFlowArgs` instance. knowledge_base: contains information about the client Returns: rdf value object containing a list of extended artifacts and the knowledge base
def GetArtifactCollectorArgs(flow_args, knowledge_base): """Prepare bundle of artifacts and their dependencies for the client. Args: flow_args: An `ArtifactCollectorFlowArgs` instance. knowledge_base: contains information about the client Returns: rdf value object containing a list of extended artif...
Check conditions on the source.
def MeetsConditions(knowledge_base, source): """Check conditions on the source.""" source_conditions_met = True os_conditions = ConvertSupportedOSToConditions(source) if os_conditions: source.conditions.append(os_conditions) for condition in source.conditions: source_conditions_met &= artifact_utils.C...
Wrapper for the ArtifactArranger. Extend the artifact list by dependencies and sort the artifacts to resolve the dependencies. Args: os_name: String specifying the OS name. artifact_list: List of requested artifact names. Returns: A list of artifacts such that if they are collected in the given o...
def GetArtifactsForCollection(os_name, artifact_list): """Wrapper for the ArtifactArranger. Extend the artifact list by dependencies and sort the artifacts to resolve the dependencies. Args: os_name: String specifying the OS name. artifact_list: List of requested artifact names. Returns: A list...
Expand artifact by extending its sources. This method takes as input an rdf artifact object and returns a rdf expanded artifact. It iterates through the list of sources processing them by type. Each source of the original artifact can lead to one or more (in case of artifact groups and files where the ...
def Expand(self, rdf_artifact, requested): """Expand artifact by extending its sources. This method takes as input an rdf artifact object and returns a rdf expanded artifact. It iterates through the list of sources processing them by type. Each source of the original artifact can lead to one or more (i...
Recursively expands an artifact group source.
def _ExpandArtifactGroupSource(self, source, requested): """Recursively expands an artifact group source.""" artifact_list = [] if "names" in source.attributes: artifact_list = source.attributes["names"] for artifact_name in artifact_list: if artifact_name in self.processed_artifacts: ...
Recursively expands an artifact files source.
def _ExpandArtifactFilesSource(self, source, requested): """Recursively expands an artifact files source.""" expanded_source = rdf_artifacts.ExpandedSource(base_source=source) sub_sources = [] artifact_list = [] if "artifact_list" in source.attributes: artifact_list = source.attributes["artifa...
Creates the nodes and directed edges of the dependency graph. Args: os_name: String specifying the OS name. artifact_list: List of requested artifact names.
def _InitializeGraph(self, os_name, artifact_list): """Creates the nodes and directed edges of the dependency graph. Args: os_name: String specifying the OS name. artifact_list: List of requested artifact names. """ dependencies = artifact_registry.REGISTRY.SearchDependencies( os_na...
Add the attribute nodes to the graph. For every attribute that is required for the collection of requested artifacts, add a node to the dependency graph. An attribute node will have incoming edges from the artifacts that provide this attribute and outgoing edges to the artifacts that depend on it. ...
def _AddAttributeNodes(self, attribute_names): """Add the attribute nodes to the graph. For every attribute that is required for the collection of requested artifacts, add a node to the dependency graph. An attribute node will have incoming edges from the artifacts that provide this attribute and outgo...
Add the artifact nodes to the graph. For every artifact that has to be collected, add a node to the dependency graph. The edges represent the dependencies. An artifact has outgoing edges to the attributes it provides and incoming edges from attributes it depends on. Initially, only artifacts witho...
def _AddArtifactNodesAndEdges(self, artifact_names): """Add the artifact nodes to the graph. For every artifact that has to be collected, add a node to the dependency graph. The edges represent the dependencies. An artifact has outgoing edges to the attributes it provides and incoming edges from a...
Add an edge for every dependency of the given artifact. This method gets the attribute names for a given artifact and for every attribute it adds a directed edge from the attribute node to the artifact node. If an artifact does not have any dependencies it is added to the set of reachable nodes. A...
def _AddDependencyEdges(self, rdf_artifact): """Add an edge for every dependency of the given artifact. This method gets the attribute names for a given artifact and for every attribute it adds a directed edge from the attribute node to the artifact node. If an artifact does not have any dependencies i...
Add an edge for every attribute the given artifact provides. This method adds a directed edge from the artifact node to every attribute this artifact provides. Args: rdf_artifact: The artifact object.
def _AddProvidesEdges(self, rdf_artifact): """Add an edge for every attribute the given artifact provides. This method adds a directed edge from the artifact node to every attribute this artifact provides. Args: rdf_artifact: The artifact object. """ for attribute in rdf_artifact.provide...
Add a directed edge to the graph. Add the end to the list of outgoing nodes of the start and the start to the list of incoming nodes of the end node. Args: start_node: name of the start node end_node: name of the end node
def _AddEdge(self, start_node, end_node): """Add a directed edge to the graph. Add the end to the list of outgoing nodes of the start and the start to the list of incoming nodes of the end node. Args: start_node: name of the start node end_node: name of the end node """ self.graph...
Bring the artifacts in a linear order that resolves dependencies. This method obtains a linear ordering of the nodes and then returns the list of artifact names. Returns: A list of `ArtifactName` instances such that if they are collected in the given order their dependencies are resolved.
def GetArtifactsInProperOrder(self): """Bring the artifacts in a linear order that resolves dependencies. This method obtains a linear ordering of the nodes and then returns the list of artifact names. Returns: A list of `ArtifactName` instances such that if they are collected in the given...
Consumes an entire range, or part thereof. If the finger has no ranges left, or the curent range start is higher than the end of the consumed block, nothing happens. Otherwise, the current range is adjusted for the consumed block, or removed, if the entire block is consumed. For things to work, the con...
def ConsumeRange(self, start, end): """Consumes an entire range, or part thereof. If the finger has no ranges left, or the curent range start is higher than the end of the consumed block, nothing happens. Otherwise, the current range is adjusted for the consumed block, or removed, if the entire blo...
Returns the next Range of the file that is to be hashed. For all fingers, inspect their next expected range, and return the lowest uninterrupted range of interest. If the range is larger than BLOCK_SIZE, truncate it. Returns: Next range of interest in a Range namedtuple.
def _GetNextInterval(self): """Returns the next Range of the file that is to be hashed. For all fingers, inspect their next expected range, and return the lowest uninterrupted range of interest. If the range is larger than BLOCK_SIZE, truncate it. Returns: Next range of interest in a Range n...
_HashBlock feeds data blocks into the hashers of fingers. This function must be called before adjusting fingers for next interval, otherwise the lack of remaining ranges will cause the block not to be hashed for a specific finger. Start and end are used to validate the expected ranges, to catch un...
def _HashBlock(self, block, start, end): """_HashBlock feeds data blocks into the hashers of fingers. This function must be called before adjusting fingers for next interval, otherwise the lack of remaining ranges will cause the block not to be hashed for a specific finger. Start and end are used ...
Finalizing function for the Fingerprint class. This method applies all the different hash functions over the previously specified different ranges of the input file, and computes the resulting hashes. After calling HashIt, the state of the object is reset to its initial state, with no fingers defi...
def HashIt(self): """Finalizing function for the Fingerprint class. This method applies all the different hash functions over the previously specified different ranges of the input file, and computes the resulting hashes. After calling HashIt, the state of the object is reset to its initial st...
Causes the entire file to be hashed by the given hash functions. This sets up a 'finger' for fingerprinting, where the entire file is passed through a pre-defined (or user defined) set of hash functions. Args: hashers: An iterable of hash classes (e.g. out of hashlib) which will be in...
def EvalGeneric(self, hashers=None): """Causes the entire file to be hashed by the given hash functions. This sets up a 'finger' for fingerprinting, where the entire file is passed through a pre-defined (or user defined) set of hash functions. Args: hashers: An iterable of hash classes (e.g. out...
Parses PECOFF headers. Reads header magic and some data structures in a file to determine if it is a valid PECOFF header, and figure out the offsets at which relevant data is stored. While this code contains multiple seeks and small reads, that is compensated by the underlying libc buffering mechan...
def _PecoffHeaderParser(self): """Parses PECOFF headers. Reads header magic and some data structures in a file to determine if it is a valid PECOFF header, and figure out the offsets at which relevant data is stored. While this code contains multiple seeks and small reads, that is compensated b...
Extracts signedData blob from PECOFF binary and parses first layer.
def _CollectSignedData(self, extent): """Extracts signedData blob from PECOFF binary and parses first layer.""" start, length = extent self.file.seek(start, os.SEEK_SET) buf = self.file.read(length) signed_data = [] # This loop ignores trailing cruft, or too-short signedData chunks. while l...
If the file is a PE/COFF file, computes authenticode hashes on it. This checks if the input file is a valid PE/COFF image file (e.g. a Windows binary, driver, or DLL) and if yes, sets up a 'finger' for fingerprinting in Authenticode style. If available, the 'SignedData' section of the image file is ret...
def EvalPecoff(self, hashers=None): """If the file is a PE/COFF file, computes authenticode hashes on it. This checks if the input file is a valid PE/COFF image file (e.g. a Windows binary, driver, or DLL) and if yes, sets up a 'finger' for fingerprinting in Authenticode style. If available, the 'S...
Parse the History file.
def Parse(self, stat, file_object, knowledge_base): """Parse the History file.""" _, _ = stat, knowledge_base # TODO(user): Convert this to use the far more intelligent plaso parser. ff = Firefox3History(file_object) for timestamp, unused_entry_type, url, title in ff.Parse(): yield rdf_webhist...
Iterator returning dict for each entry in history.
def Parse(self): """Iterator returning dict for each entry in history.""" for timestamp, url, title in self.Query(self.VISITS_QUERY): if not isinstance(timestamp, (long, int)): timestamp = 0 yield [timestamp, "FIREFOX3_VISIT", url, title]
Read a tag from the buffer, and return a (tag_bytes, new_pos) tuple.
def ReadTag(buf, pos): """Read a tag from the buffer, and return a (tag_bytes, new_pos) tuple.""" try: start = pos while ORD_MAP_AND_0X80[buf[pos]]: pos += 1 pos += 1 return (buf[start:pos], pos) except IndexError: raise ValueError("Invalid tag")
Convert an integer to a varint and write it using the write function.
def VarintEncode(value): """Convert an integer to a varint and write it using the write function.""" result = b"" if value < 0: raise ValueError("Varint can not encode a negative number.") bits = value & 0x7f value >>= 7 while value: result += HIGH_CHR_MAP[bits] bits = value & 0x7f value >...
Encode a signed integer as a zigzag encoded signed integer.
def SignedVarintEncode(value): """Encode a signed integer as a zigzag encoded signed integer.""" result = b"" if value < 0: value += (1 << 64) bits = value & 0x7f value >>= 7 while value: result += HIGH_CHR_MAP[bits] bits = value & 0x7f value >>= 7 result += CHR_MAP[bits] return result
A 64 bit decoder from google.protobuf.internal.decoder.
def VarintReader(buf, pos=0): """A 64 bit decoder from google.protobuf.internal.decoder.""" result = 0 shift = 0 while 1: b = buf[pos] result |= (ORD_MAP_AND_0X7F[b] << shift) pos += 1 if not ORD_MAP_AND_0X80[b]: return (result, pos) shift += 7 if shift >= 64: raise rdfvalue...
Parses the buffer as a prototypes. Args: buff: The buffer to parse. index: The position to start parsing. length: Optional length to parse until. Yields: Splits the buffer into tuples of strings: (encoded_tag, encoded_length, wire_format).
def SplitBuffer(buff, index=0, length=None): """Parses the buffer as a prototypes. Args: buff: The buffer to parse. index: The position to start parsing. length: Optional length to parse until. Yields: Splits the buffer into tuples of strings: (encoded_tag, encoded_length, wire_format). ...