INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Write newline separated JSON dicts for each value.
def WriteValuesToJSONFile(self, state, values): """Write newline separated JSON dicts for each value. We write each dict separately so we don't have to hold all of the output streams in memory. We open and close the JSON array manually with []. Args: state: rdf_protodict.AttributedDict with the ...
Assign kwargs to the protobuf and remove them from the kwargs dict.
def FilterArgsFromSemanticProtobuf(protobuf, kwargs): """Assign kwargs to the protobuf, and remove them from the kwargs dict.""" for descriptor in protobuf.type_infos: value = kwargs.pop(descriptor.name, None) if value is not None: setattr(protobuf, descriptor.name, value)
Initializes state for a list of output plugins.
def GetOutputPluginStates(output_plugins, source=None, token=None): """Initializes state for a list of output plugins.""" output_plugins_states = [] for plugin_descriptor in output_plugins: plugin_class = plugin_descriptor.GetPluginClass() try: _, plugin_state = plugin_class.CreatePluginAndDefaultSt...
The main factory function for creating and executing a new flow.
def StartAFF4Flow(args=None, runner_args=None, parent_flow=None, sync=True, token=None, **kwargs): """The main factory function for creating and executing a new flow. Args: args: An arg protocol buffer which is an instanc...
The main factory function for creating and executing a new flow.
def StartFlow(client_id=None, cpu_limit=None, creator=None, flow_args=None, flow_cls=None, network_bytes_limit=None, original_flow=None, output_plugins=None, start_at=None, parent_flow_obj=None,...
Flushes the flow/ hunt and all its requests to the data_store.
def Flush(self): """Flushes the flow/hunt and all its requests to the data_store.""" self._CheckLeaseAndFlush() self.Load() super(FlowBase, self).Flush() # Writing the messages queued in the queue_manager of the runner always has # to be the last thing that happens or we will have a race conditi...
Flushes the flow and all its requests to the data_store.
def Close(self): """Flushes the flow and all its requests to the data_store.""" self._CheckLeaseAndFlush() super(FlowBase, self).Close() # Writing the messages queued in the queue_manager of the runner always has # to be the last thing that happens or we will have a race condition. self.FlushMes...
The initialization method.
def Initialize(self): """The initialization method.""" super(GRRFlow, self).Initialize() self._client_version = None self._client_os = None self._client_knowledge_base = None if "r" in self.mode: state = self.Get(self.Schema.FLOW_STATE_DICT) self.context = self.Get(self.Schema.FLOW_...
Make a new runner.
def CreateRunner(self, **kw): """Make a new runner.""" self.runner = flow_runner.FlowRunner(self, token=self.token, **kw) return self.runner
Send out a final notification about the end of this flow.
def NotifyAboutEnd(self): """Send out a final notification about the end of this flow.""" flow_ref = None if self.runner_args.client_id: flow_ref = rdf_objects.FlowReference( client_id=self.client_id, flow_id=self.urn.Basename()) num_results = len(self.ResultCollection()) notificati...
Mark the flow for termination as soon as any of its states are called.
def MarkForTermination(cls, flow_urn, reason=None, mutation_pool=None): """Mark the flow for termination as soon as any of its states are called.""" # Doing a blind write here using low-level data store API. Accessing # the flow via AFF4 is not really possible here, because it forces a state # to be wri...
Terminate a flow.
def TerminateAFF4Flow(cls, flow_id, reason=None, status=None, token=None): """Terminate a flow. Args: flow_id: The flow session_id to terminate. reason: A reason to log. status: Status code used in the generated status message. token: The access token to be used for this request. R...
Returns the ResultCollection for the flow with a given flow_id.
def ResultCollectionForFID(cls, flow_id): """Returns the ResultCollection for the flow with a given flow_id. Args: flow_id: The id of the flow, a RDFURN of the form aff4:/flows/F:123456. Returns: The collection containing the results for the flow identified by the id. """ # TODO: Disal...
Get instances of all well known flows.
def GetAllWellKnownFlows(cls, token=None): """Get instances of all well known flows.""" well_known_flows = {} for cls in itervalues(registry.AFF4FlowRegistry.FLOW_REGISTRY): if issubclass(cls, WellKnownFlow) and cls.well_known_session_id: well_known_flow = cls(cls.well_known_session_id, mode="...
Removes WellKnownFlow messages from the queue and returns them.
def FetchAndRemoveRequestsAndResponses(self, session_id): """Removes WellKnownFlow messages from the queue and returns them.""" messages = [] with queue_manager.WellKnownQueueManager(token=self.token) as manager: for response in manager.FetchResponses(session_id): messages.append(response) ...
For WellKnownFlows we receive these messages directly.
def ProcessResponses(self, responses, thread_pool): """For WellKnownFlows we receive these messages directly.""" for response in responses: thread_pool.AddTask( target=self._SafeProcessMessage, args=(response,), name=self.__class__.__name__)
Returns the IP as an IPAddress object ( if packed bytes are defined ).
def AsIPAddr(self): """Returns the IP as an `IPAddress` object (if packed bytes are defined).""" if self.packed_bytes is None: return None packed_bytes = self.packed_bytes.AsBytes() if self.address_type == NetworkAddress.Family.INET: return ipaddress.IPv4Address(packed_bytes) if self.a...
Return a list of IP addresses.
def GetIPAddresses(self): """Return a list of IP addresses.""" results = [] for address in self.addresses: human_readable_address = address.human_readable_address if human_readable_address is not None: results.append(human_readable_address) return results
Checks all content_conditions until one yields no matches.
def _CheckConditionsShortCircuit(content_conditions, pathspec): """Checks all `content_conditions` until one yields no matches.""" matches = [] for cond in content_conditions: with vfs.VFSOpen(pathspec) as vfs_file: cur_matches = list(cond.Search(vfs_file)) if cur_matches: matches.extend(cur_m...
Yields all possible expansions from given path patterns.
def _GetExpandedPaths(args): """Yields all possible expansions from given path patterns.""" opts = globbing.PathOpts( follow_links=args.follow_links, pathtype=args.pathtype) for path in args.paths: for expanded_path in globbing.ExpandPath(str(path), opts): yield expanded_path
This function expands paths from the args and returns registry keys.
def RegistryKeyFromClient(args): """This function expands paths from the args and returns registry keys. Args: args: An `rdf_file_finder.FileFinderArgs` object. Yields: `rdf_client_fs.StatEntry` instances. """ for path in _GetExpandedPaths(args): pathspec = rdf_paths.PathSpec( path=path,...
Returns last known GRR version that the client used.
def GetClientVersion(client_id, token=None): """Returns last known GRR version that the client used.""" if data_store.RelationalDBEnabled(): sinfo = data_store.REL_DB.ReadClientStartupInfo(client_id=client_id) if sinfo is not None: return sinfo.client_info.client_version else: return config....
Returns last known operating system name that the client used.
def GetClientOs(client_id, token=None): """Returns last known operating system name that the client used.""" if data_store.RelationalDBEnabled(): kb = data_store.REL_DB.ReadClientSnapshot(client_id).knowledge_base else: with aff4.FACTORY.Open(client_id, token=token) as client: kb = client.Get(client...
Returns an rdf_crypto. Hash instance for given AFF4 file descriptor.
def GetFileHashEntry(fd): """Returns an `rdf_crypto.Hash` instance for given AFF4 file descriptor.""" # Hash file store is not migrated to RELDB just yet, hence the first check. if (not fd.urn.Path().startswith("/files/hash/generic") and data_store.RelationalDBEnabled()): return GetUrnHashEntry(fd.urn) ...
Returns an rdf_crypto. Hash instance for given URN of an AFF4 file.
def GetUrnHashEntry(urn, token=None): """Returns an `rdf_crypto.Hash` instance for given URN of an AFF4 file.""" if data_store.RelationalDBEnabled(): client_id, vfs_path = urn.Split(2) path_type, components = rdf_objects.ParseCategorizedPath(vfs_path) path_info = data_store.REL_DB.ReadPathInfo(client_i...
Enumerate all modules which match the patterns MODULE_PATTERNS.
def EnumMissingModules(): """Enumerate all modules which match the patterns MODULE_PATTERNS. PyInstaller often fails to locate all dlls which are required at runtime. We import all the client modules here, we simply introspect all the modules we have loaded in our current running process, and all the ones ma...
Read a file from a ZipFile and write it to a new ZipFile.
def CopyFileInZip(from_zip, from_name, to_zip, to_name=None): """Read a file from a ZipFile and write it to a new ZipFile.""" data = from_zip.read(from_name) if to_name is None: to_name = from_name to_zip.writestr(to_name, data)
Use VS2010 to build the windows Nanny service.
def BuildNanny(self): """Use VS2010 to build the windows Nanny service.""" # When running under cygwin, the following environment variables are not set # (since they contain invalid chars). Visual Studio requires these or it # will fail. os.environ["ProgramFiles(x86)"] = r"C:\Program Files (x86)" ...
Windows templates also include the nanny.
def MakeExecutableTemplate(self, output_file=None): """Windows templates also include the nanny.""" super(WindowsClientBuilder, self).MakeExecutableTemplate(output_file=output_file) self.MakeBuildDirectory() self.BuildWithPyInstaller() # Get any dll's that pyinstaller forgot: for mod...
Check password with legacy crypt based method.
def _CheckLegacyPassword(self, password): """Check password with legacy crypt based method.""" # This import will fail on Windows. import crypt # pylint: disable=g-import-not-at-top salt = self._value[:2] return crypt.crypt(password, salt) == self._value
Send an AFF4 - based notification to the user in the UI.
def Notify(self, message_type, subject, msg, source): """Send an AFF4-based notification to the user in the UI. Args: message_type: One of aff4_grr.Notification.notification_types e.g. "ViewObject", "HostInformation", "GrantAccess" or the same with an added ":[new-style notification type]...
Deletes the pending notification with the given timestamp.
def DeletePendingNotification(self, timestamp): """Deletes the pending notification with the given timestamp. Args: timestamp: The timestamp of the notification. Assumed to be unique. Raises: UniqueKeyError: Raised if multiple notifications have the timestamp. """ shown_notifications =...
A generator of current notifications.
def ShowNotifications(self, reset=True): """A generator of current notifications.""" shown_notifications = self.Schema.SHOWN_NOTIFICATIONS() # Pending notifications first pending = self.Get(self.Schema.PENDING_NOTIFICATIONS, []) for notification in pending: shown_notifications.Append(notifica...
Return a description of this user.
def Describe(self): """Return a description of this user.""" result = ["\nUsername: %s" % self.urn.Basename()] labels = [l.name for l in self.GetLabels()] result.append("Labels: %s" % ",".join(labels)) if self.Get(self.Schema.PASSWORD) is None: result.append("Password: not set") else: ...
Gets the metric value corresponding to the given field values.
def Get(self, fields=None): """Gets the metric value corresponding to the given field values.""" if not self._field_defs and fields: raise ValueError("Metric was registered without fields, " "but following fields were provided: %s." % (fields,)) if self._field_defs and not fiel...
Increments counter value by a given delta.
def Increment(self, delta, fields=None): """Increments counter value by a given delta.""" if delta < 0: raise ValueError( "Counter increment should not be < 0 (received: %d)" % delta) self._metric_values[_FieldsToKey(fields)] = self.Get(fields=fields) + delta
Records the given observation in a distribution.
def Record(self, value, fields=None): """Records the given observation in a distribution.""" key = _FieldsToKey(fields) metric_value = self._metric_values.get(key) if metric_value is None: metric_value = self._DefaultValue() self._metric_values[key] = metric_value metric_value.Record(val...
Sets the metric s current value.
def Set(self, value, fields=None): """Sets the metric's current value.""" self._metric_values[_FieldsToKey(fields)] = self._value_type(value)
Returns current metric s value ( executing a callback if needed ).
def Get(self, fields=None): """Returns current metric's value (executing a callback if needed).""" result = super(_GaugeMetric, self).Get(fields=fields) if callable(result): return result() else: return result
See base class.
def _InitializeMetric(self, metadata): """See base class.""" field_defs = stats_utils.FieldDefinitionTuplesFromProtos( metadata.fields_defs) if metadata.metric_type == rdf_stats.MetricMetadata.MetricType.COUNTER: self._counter_metrics[metadata.varname] = _CounterMetric(field_defs) elif met...
See base class.
def IncrementCounter(self, metric_name, delta=1, fields=None): """See base class.""" if delta < 0: raise ValueError("Invalid increment for counter: %d." % delta) self._counter_metrics[metric_name].Increment(delta, fields)
See base class.
def RecordEvent(self, metric_name, value, fields=None): """See base class.""" self._event_metrics[metric_name].Record(value, fields)
See base class.
def SetGaugeValue(self, metric_name, value, fields=None): """See base class.""" self._gauge_metrics[metric_name].Set(value, fields)
See base class.
def SetGaugeCallback(self, metric_name, callback, fields=None): """See base class.""" self._gauge_metrics[metric_name].SetCallback(callback, fields)
Fetches the metric object corresponding to the given name.
def _GetMetric(self, metric_name): """Fetches the metric object corresponding to the given name.""" if metric_name in self._counter_metrics: return self._counter_metrics[metric_name] elif metric_name in self._event_metrics: return self._event_metrics[metric_name] elif metric_name in self._ga...
Parse the yum output.
def Parse(self, cmd, args, stdout, stderr, return_val, time_taken, knowledge_base): """Parse the yum output.""" _ = stderr, time_taken, args, knowledge_base # Unused. self.CheckReturn(cmd, return_val) packages = [] for line in stdout.decode("utf-8").splitlines()[1:]: # Ignore first lin...
Parse the yum repolist output.
def Parse(self, cmd, args, stdout, stderr, return_val, time_taken, knowledge_base): """Parse the yum repolist output.""" _ = stderr, time_taken, args, knowledge_base # Unused. self.CheckReturn(cmd, return_val) output = iter(stdout.decode("utf-8").splitlines()) repo_regexes = { ...
Parse the rpm - qa output.
def Parse(self, cmd, args, stdout, stderr, return_val, time_taken, knowledge_base): """Parse the rpm -qa output.""" _ = time_taken, args, knowledge_base # Unused. rpm_re = re.compile(r"^(\w[-\w\+]+?)-(\d.*)$") self.CheckReturn(cmd, return_val) packages = [] for line in stdout.splitl...
Parse the dpkg output.
def Parse(self, cmd, args, stdout, stderr, return_val, time_taken, knowledge_base): """Parse the dpkg output.""" _ = stderr, time_taken, args, knowledge_base # Unused. self.CheckReturn(cmd, return_val) column_lengths = [] i = 0 for i, line in enumerate(stdout.decode("utf-8").splitli...
Parse the dmidecode output. All data is parsed into a dictionary.
def Parse(self, cmd, args, stdout, stderr, return_val, time_taken, knowledge_base): """Parse the dmidecode output. All data is parsed into a dictionary.""" _ = stderr, time_taken, args, knowledge_base # Unused. self.CheckReturn(cmd, return_val) output = iter(stdout.decode("utf-8").splitline...
Parse the ps output.
def Parse(self, cmd, args, stdout, stderr, return_val, time_taken, knowledge_base): """Parse the ps output. Note that cmdline consumes every field up to the end of line and as it is string, we can't perfectly see what the arguments on the command line really were. We just assume a space is ...
Validates an IAP JWT for your ( Compute|Container ) Engine service.
def ValidateIapJwtFromComputeEngine(iap_jwt, cloud_project_number, backend_service_id): """Validates an IAP JWT for your (Compute|Container) Engine service. Args: iap_jwt: The contents of the X-Goog-IAP-JWT-Assertion header. cloud_project_number: The project *number* for...
Validates an IAP JWT.
def ValidateIapJwt(iap_jwt, expected_audience): """Validates an IAP JWT.""" try: key_id = jwt.get_unverified_header(iap_jwt).get("kid") if not key_id: raise IAPValidationFailedError("No key ID") key = GetIapKey(key_id) decoded_jwt = jwt.decode( iap_jwt, key, algorithms=["ES256"], audi...
Retrieves a public key from the list published by Identity - Aware Proxy.
def GetIapKey(key_id): """Retrieves a public key from the list published by Identity-Aware Proxy. The key file is re-fetched if necessary. Args: key_id: Key id. Returns: String with a key. Raises: KeyNotFoundError: if the key is not found in the key file. KeysCanNotBeFetchedError: if the k...
Inits an GRR API object with a HTTP connector.
def InitHttp(api_endpoint=None, page_size=None, auth=None, proxies=None, verify=None, cert=None, trust_env=True): """Inits an GRR API object with a HTTP connector.""" connector = http_connector.HttpConnector( api_endpoint=api_endpo...
Changes interface to a staticly set IP.
def NetshStaticIp(interface, ip=u'127.0.0.9', subnet=u'255.255.255.255', gw=u'127.0.0.1'): """Changes interface to a staticly set IP. Sets IP configs to local if no paramaters passed. Args: interface: Name of the interface. ip: IP address. subnet...
Tries to disable an interface. Only works on Vista and 7.
def DisableInterfaces(interface): """Tries to disable an interface. Only works on Vista and 7. Args: interface: Name of the interface to disable. Returns: res which is a tuple of (stdout, stderr, exit_status, time_taken). """ set_tested_versions = ['vista', '2008'] set_args = ['/c', 'netsh', 'set...
Gives a list of enabled interfaces. Should work on all windows versions.
def GetEnabledInterfaces(): """Gives a list of enabled interfaces. Should work on all windows versions. Returns: interfaces: Names of interfaces found enabled. """ interfaces = [] show_args = ['/c', 'netsh', 'show', 'interface'] # pylint: disable=undefined-variable res = client_utils_common.Execute( ...
Sends a message to a user.
def MsgUser(msg): """Sends a message to a user. Args: msg: Message to be displaied to user. Returns: res which is a tuple of (stdout, stderr, exit_status, time_taken). """ msg_tested_versions = ['xp', 'vista', '2008', '2003'] msg_args = ['/c', '%SystemRoot%\\System32\\msg.exe', '*', '/TIME:0'] h...
Apply build. yaml settings from the template.
def GetConfigFromTemplate(self, template_path): """Apply build.yaml settings from the template.""" with zipfile.ZipFile(template_path) as template_zip: build_yaml = None for name in template_zip.namelist(): if name.endswith("build.yaml"): build_yaml = name break if ...
Get the appropriate client deployer based on the selected flags.
def GetRepacker(self, context, signer=None): """Get the appropriate client deployer based on the selected flags.""" if "Target:Darwin" in context: deployer_class = build.DarwinClientRepacker elif "Target:Windows" in context: deployer_class = build.WindowsClientRepacker elif "Target:LinuxDeb"...
Repack binaries based on the configuration.
def RepackTemplate(self, template_path, output_dir, upload=False, token=None, sign=False, context=None, signed_template=False): """Repack binaries based on the configura...
Repack all the templates in ClientBuilder. template_dir.
def RepackAllTemplates(self, upload=False, token=None): """Repack all the templates in ClientBuilder.template_dir.""" for template in os.listdir(config.CONFIG["ClientBuilder.template_dir"]): template_path = os.path.join(config.CONFIG["ClientBuilder.template_dir"], templa...
Build metadata requests list from collection maps.
def _MakeArgs(amazon_collection_map, google_collection_map): """Build metadata requests list from collection maps.""" request_list = [] for url, label in iteritems(amazon_collection_map): request_list.append( CloudMetadataRequest( bios_version_regex=AMAZON_BIOS_REGEX, service_n...
Make the google unique ID of zone/ project/ id.
def MakeGoogleUniqueID(cloud_instance): """Make the google unique ID of zone/project/id.""" if not (cloud_instance.zone and cloud_instance.project_id and cloud_instance.instance_id): raise ValueError("Bad zone/project_id/id: '%s/%s/%s'" % (cloud_instance.zone, cloud_instance.proje...
Build the standard set of cloud metadata to collect during interrogate.
def BuildCloudMetadataRequests(): """Build the standard set of cloud metadata to collect during interrogate.""" amazon_collection_map = { "/".join((AMAZON_URL_BASE, "instance-id")): "instance_id", "/".join((AMAZON_URL_BASE, "ami-id")): "ami_id", "/".join((AMAZON_URL_BASE, "hostname")): "hostname",...
Convert CloudMetadataResponses to CloudInstance proto.
def ConvertCloudMetadataResponsesToCloudInstance(metadata_responses): """Convert CloudMetadataResponses to CloudInstance proto. Ideally we'd just get the client to fill out a CloudInstance proto, but we need to keep the flexibility of collecting new metadata and creating new fields without a client push. So in...
Records given value.
def Record(self, value): """Records given value.""" self.sum += value self.count += 1 pos = bisect.bisect(self.bins, value) - 1 if pos < 0: pos = 0 elif pos == len(self.bins): pos = len(self.bins) - 1 self.heights[pos] += 1
Puts a given value into an appropriate bin.
def RegisterValue(self, value): """Puts a given value into an appropriate bin.""" if self.bins: for b in self.bins: if b.range_max_value > value: b.num += 1 return self.bins[-1].num += 1
Update stats with info about resources consumed by a single client.
def RegisterResources(self, client_resources): """Update stats with info about resources consumed by a single client.""" self.user_cpu_stats.RegisterValue(client_resources.cpu_usage.user_cpu_time) self.system_cpu_stats.RegisterValue( client_resources.cpu_usage.system_cpu_time) self.network_bytes...
Extracts and returns the serialized object.
def payload(self): """Extracts and returns the serialized object.""" try: rdf_cls = self.classes.get(self.name) if rdf_cls: value = rdf_cls.FromSerializedString(self.data) value.age = self.embedded_age return value except TypeError: return None
Receives a value and fills it into a DataBlob.
def SetValue(self, value, raise_on_error=True): """Receives a value and fills it into a DataBlob. Args: value: value to set raise_on_error: if True, raise if we can't serialize. If False, set the key to an error string. Returns: self Raises: TypeError: if the value can...
Extracts and returns a single value from a DataBlob.
def GetValue(self, ignore_error=True): """Extracts and returns a single value from a DataBlob.""" if self.HasField("none"): return None field_names = [ "integer", "string", "data", "boolean", "list", "dict", "rdf_value", "float", "set" ] values = [getattr(self, x) for x in fi...
Add another member to the array.
def Append(self, value=None, **kwarg): """Add another member to the array. Args: value: The new data to append to the array. **kwarg: Create a new element from these keywords. Returns: The value which was added. This can be modified further by the caller and changes will be propag...
Constructs a single sample that best represents a list of samples.
def FromMany(cls, samples): """Constructs a single sample that best represents a list of samples. Args: samples: An iterable collection of `CpuSample` instances. Returns: A `CpuSample` instance representing `samples`. Raises: ValueError: If `samples` is empty. """ if not sam...
Constructs a single sample that best represents a list of samples.
def FromMany(cls, samples): """Constructs a single sample that best represents a list of samples. Args: samples: An iterable collection of `IOSample` instances. Returns: An `IOSample` instance representing `samples`. Raises: ValueError: If `samples` is empty. """ if not samp...
Constructs a copy of given stats but downsampled to given interval.
def Downsampled(cls, stats, interval=None): """Constructs a copy of given stats but downsampled to given interval. Args: stats: A `ClientStats` instance. interval: A downsampling interval. Returns: A downsampled `ClientStats` instance. """ interval = interval or cls.DEFAULT_SAMPL...
Get a User protobuf for a specific user.
def GetUserInfo(knowledge_base, user): # TODO: This docstring cannot be a raw literal because there are # issues with raw unicode literals on Python 2. Once support for Python 2 is # dropped, it can be made raw again. # pylint: disable=g-docstring-has-escape """Get a User protobuf for a specific user. Args...
Waits for a file to be updated on the client.
def UpdateVFSFileAndWait(client_id, vfs_file_urn, token=None, timeout=DEFAULT_TIMEOUT): """Waits for a file to be updated on the client. Calls the UpdateVFSFile flow on a urn and waits for both it and the ListDirectory flow it calls to fi...
Waits for a flow to finish polling while we wait.
def WaitForFlow(flow_urn, token=None, timeout=DEFAULT_TIMEOUT, max_sleep_time=1, min_sleep_time=0.2, dampening_multiplier=0.9): """Waits for a flow to finish, polling while we wait. Args: flow_urn: The urn of the flow to wait for. ...
Runs a flow and waits for it to finish.
def StartFlowAndWait(client_id, token=None, timeout=DEFAULT_TIMEOUT, **flow_args): """Runs a flow and waits for it to finish. Args: client_id: The client id of the client to run on. token: The datastore access token. timeout: How long to wa...
Take a string as a path on a client and interpolate with client data.
def InterpolatePath(path, knowledge_base, users=None, path_args=None, depth=0): """Take a string as a path on a client and interpolate with client data. Args: path: A single string/unicode to be interpolated. knowledge_base: An rdf_client.KnowledgeBase object. users: A list of string usernames, or None...
A recursive generator of files.
def ListDirectory(self, pathspec, depth=0): """A recursive generator of files.""" # Limit recursion depth if depth >= self.request.max_depth: return try: fd = vfs.VFSOpen(pathspec, progress_callback=self.Progress) files = fd.ListFiles(ext_attrs=self.request.collect_ext_attrs) exce...
Parses request and returns a list of filter callables.
def BuildChecks(self, request): """Parses request and returns a list of filter callables. Each callable will be called with the StatEntry and returns True if the entry should be suppressed. Args: request: A FindSpec that describes the search. Returns: a list of callables which return ...
Runs the Find action.
def Run(self, request): """Runs the Find action.""" self.request = request filters = self.BuildChecks(request) files_checked = 0 for f in self.ListDirectory(request.pathspec): self.Progress() # Ignore this file if any of the checks fail. if not any((check(f) for check in filters...
Search the data for a hit.
def FindRegex(self, regex, data): """Search the data for a hit.""" for match in re.finditer(regex, data, flags=re.I | re.S | re.M): yield (match.start(), match.end())
Search the data for a hit.
def FindLiteral(self, pattern, data): """Search the data for a hit.""" pattern = utils.Xor(pattern, self.xor_in_key) offset = 0 while 1: # We assume here that data.find does not make a copy of pattern. offset = data.find(pattern, offset) if offset < 0: break yield (off...
Search the file for the pattern.
def Run(self, args): """Search the file for the pattern. This implements the grep algorithm used to scan files. It reads the data in chunks of BUFF_SIZE (10 MB currently) and can use different functions to search for matching patterns. In every step, a buffer that is a bit bigger than the block siz...
Stops the hunt if number of crashes exceeds the limit.
def StopHuntIfCrashLimitExceeded(hunt_id): """Stops the hunt if number of crashes exceeds the limit.""" hunt_obj = data_store.REL_DB.ReadHuntObject(hunt_id) # Do nothing if the hunt is already stopped. if hunt_obj.hunt_state == rdf_hunt_objects.Hunt.HuntState.STOPPED: return hunt_obj if hunt_obj.crash_l...
Stops the hunt if average limites are exceeded.
def StopHuntIfCPUOrNetworkLimitsExceeded(hunt_id): """Stops the hunt if average limites are exceeded.""" hunt_obj = data_store.REL_DB.ReadHuntObject(hunt_id) # Do nothing if the hunt is already stopped. if hunt_obj.hunt_state == rdf_hunt_objects.Hunt.HuntState.STOPPED: return hunt_obj hunt_counters = da...
Marks the hunt as complete if it s past its expiry time.
def CompleteHuntIfExpirationTimeReached(hunt_obj): """Marks the hunt as complete if it's past its expiry time.""" # TODO(hanuszczak): This should not set the hunt state to `COMPLETED` but we # should have a sparate `EXPIRED` state instead and set that. if (hunt_obj.hunt_state not in [ rdf_hunt_objects.Hun...
Creates a hunt using a given hunt object.
def CreateHunt(hunt_obj): """Creates a hunt using a given hunt object.""" data_store.REL_DB.WriteHuntObject(hunt_obj) if hunt_obj.HasField("output_plugins"): output_plugins_states = flow.GetOutputPluginStates( hunt_obj.output_plugins, source="hunts/%s" % hunt_obj.hunt_id, token=access...
Creates and starts a new hunt.
def CreateAndStartHunt(flow_name, flow_args, creator, **kwargs): """Creates and starts a new hunt.""" # This interface takes a time when the hunt expires. However, the legacy hunt # starting interface took an rdfvalue.Duration object which was then added to # the current time to get the expiry. This check exis...
Adds foreman rules for a generic hunt.
def _ScheduleGenericHunt(hunt_obj): """Adds foreman rules for a generic hunt.""" # TODO: Migrate foreman conditions to use relation expiration # durations instead of absolute timestamps. foreman_condition = foreman_rules.ForemanCondition( creation_time=rdfvalue.RDFDatetime.Now(), expiration_time=hun...
Schedules flows for a variable hunt.
def _ScheduleVariableHunt(hunt_obj): """Schedules flows for a variable hunt.""" if hunt_obj.client_rate != 0: raise VariableHuntCanNotHaveClientRateError(hunt_obj.hunt_id, hunt_obj.client_rate) seen_clients = set() for flow_group in hunt_obj.args.variable.flo...
Starts a hunt with a given id.
def StartHunt(hunt_id): """Starts a hunt with a given id.""" hunt_obj = data_store.REL_DB.ReadHuntObject(hunt_id) num_hunt_clients = data_store.REL_DB.CountHuntFlows(hunt_id) if hunt_obj.hunt_state != hunt_obj.HuntState.PAUSED: raise OnlyPausedHuntCanBeStartedError(hunt_obj) data_store.REL_DB.UpdateHun...
Pauses a hunt with a given id.
def PauseHunt(hunt_id, reason=None): """Pauses a hunt with a given id.""" hunt_obj = data_store.REL_DB.ReadHuntObject(hunt_id) if hunt_obj.hunt_state != hunt_obj.HuntState.STARTED: raise OnlyStartedHuntCanBePausedError(hunt_obj) data_store.REL_DB.UpdateHuntObject( hunt_id, hunt_state=hunt_obj.HuntSt...
Stops a hunt with a given id.
def StopHunt(hunt_id, reason=None): """Stops a hunt with a given id.""" hunt_obj = data_store.REL_DB.ReadHuntObject(hunt_id) if hunt_obj.hunt_state not in [ hunt_obj.HuntState.STARTED, hunt_obj.HuntState.PAUSED ]: raise OnlyStartedOrPausedHuntCanBeStoppedError(hunt_obj) data_store.REL_DB.UpdateHun...
Updates a hunt ( it must be paused to be updated ).
def UpdateHunt(hunt_id, client_limit=None, client_rate=None, duration=None): """Updates a hunt (it must be paused to be updated).""" hunt_obj = data_store.REL_DB.ReadHuntObject(hunt_id) if hunt_obj.hunt_state != hunt_obj.HuntState.PAUSED: raise OnlyPausedHuntCanBeModifiedError(hunt_obj) data_store.REL_DB....
Starts a flow corresponding to a given hunt on a given client.
def StartHuntFlowOnClient(client_id, hunt_id): """Starts a flow corresponding to a given hunt on a given client.""" hunt_obj = data_store.REL_DB.ReadHuntObject(hunt_id) hunt_obj = CompleteHuntIfExpirationTimeReached(hunt_obj) # There may be a little race between foreman rules being removed and # foreman sche...