INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Reads all message handler requests from the database.
def ReadMessageHandlerRequests(self, cursor=None): """Reads all message handler requests from the database.""" query = ("SELECT UNIX_TIMESTAMP(timestamp), request," " UNIX_TIMESTAMP(leased_until), leased_by " "FROM message_handler_requests " "ORDER BY timestamp DESC...
Deletes a list of message handler requests from the database.
def DeleteMessageHandlerRequests(self, requests, cursor=None): """Deletes a list of message handler requests from the database.""" query = "DELETE FROM message_handler_requests WHERE request_id IN ({})" request_ids = set([r.request_id for r in requests]) query = query.format(",".join(["%s"] * len(reque...
Leases a number of message handler requests up to the indicated limit.
def _LeaseMessageHandlerRequests(self, lease_time, limit, cursor=None): """Leases a number of message handler requests up to the indicated limit.""" now = rdfvalue.RDFDatetime.Now() now_str = mysql_utils.RDFDatetimeToTimestamp(now) expiry = now + lease_time expiry_str = mysql_utils.RDFDatetimeToTi...
Reads all client messages available for a given client_id.
def ReadAllClientActionRequests(self, client_id, cursor=None): """Reads all client messages available for a given client_id.""" query = ("SELECT request, UNIX_TIMESTAMP(leased_until), leased_by, " "leased_count " "FROM client_action_requests " "WHERE client_id = %s") ...
Deletes a list of client messages from the db.
def DeleteClientActionRequests(self, requests): """Deletes a list of client messages from the db.""" if not requests: return to_delete = [] for r in requests: to_delete.append((r.client_id, r.flow_id, r.request_id)) if len(set(to_delete)) != len(to_delete): raise ValueError( ...
Leases available client messages for the client with the given id.
def LeaseClientActionRequests(self, client_id, lease_time=None, limit=None, cursor=None): """Leases available client messages for the client with the given id.""" now = rdfvalue.RDFDa...
Writes messages that should go to the client to the db.
def WriteClientActionRequests(self, requests, cursor=None): """Writes messages that should go to the client to the db.""" query = ("INSERT IGNORE INTO client_action_requests " "(client_id, flow_id, request_id, timestamp, request) " "VALUES %s ON DUPLICATE KEY UPDATE " "ti...
Writes a flow object to the database.
def WriteFlowObject(self, flow_obj, cursor=None): """Writes a flow object to the database.""" query = """ INSERT INTO flows (client_id, flow_id, long_flow_id, parent_flow_id, parent_hunt_id, flow, flow_state, next_request_to_process, pending_termination, timest...
Generates a flow object from a database row.
def _FlowObjectFromRow(self, row): """Generates a flow object from a database row.""" flow, fs, cci, pt, nr, pd, po, ps, uct, sct, nbs, nrs, ts, lut = row flow_obj = rdf_flow_objects.Flow.FromSerializedString(flow) if fs not in [None, rdf_flow_objects.Flow.FlowState.UNSET]: flow_obj.flow_state =...
Reads a flow object from the database.
def ReadFlowObject(self, client_id, flow_id, cursor=None): """Reads a flow object from the database.""" query = ("SELECT " + self.FLOW_DB_FIELDS + "FROM flows WHERE client_id=%s AND flow_id=%s") cursor.execute( query, [db_utils.ClientIDToInt(client_id), db_utils.FlowIDT...
Returns all flow objects.
def ReadAllFlowObjects(self, client_id = None, min_create_time = None, max_create_time = None, include_child_flows = True, cursor=None): """Returns all flow objects.""" conditions = [] ...
Reads flows that were started by a given flow from the database.
def ReadChildFlowObjects(self, client_id, flow_id, cursor=None): """Reads flows that were started by a given flow from the database.""" query = ("SELECT " + self.FLOW_DB_FIELDS + "FROM flows WHERE client_id=%s AND parent_flow_id=%s") cursor.execute( query, [db_utils.ClientIDToIn...
Marks a flow as being processed on this worker and returns it.
def LeaseFlowForProcessing(self, client_id, flow_id, processing_time, cursor=None): """Marks a flow as being processed on this worker and returns it.""" query = ("SELECT " + self.FLOW_DB_FIELDS + ...
Updates flow objects in the database.
def UpdateFlow(self, client_id, flow_id, flow_obj=db.Database.unchanged, flow_state=db.Database.unchanged, client_crash_info=db.Database.unchanged, pending_termination=db.Database.unchanged, processing...
Updates flow objects in the database.
def UpdateFlows(self, client_id_flow_id_pairs, pending_termination=db.Database.unchanged, cursor=None): """Updates flow objects in the database.""" if pending_termination == db.Database.unchanged: return serialized_termination = pending_terminati...
Returns a (query, args) tuple that inserts the given requests.
def _WriteFlowProcessingRequests(self, requests, cursor): """Returns a (query, args) tuple that inserts the given requests.""" templates = [] args = [] for req in requests: templates.append("(%s, %s, %s, FROM_UNIXTIME(%s))") args.append(db_utils.ClientIDToInt(req.client_id)) args.appen...
Writes a list of flow requests to the database.
def WriteFlowRequests(self, requests, cursor=None): """Writes a list of flow requests to the database.""" args = [] templates = [] flow_keys = [] needs_processing = {} for r in requests: if r.needs_processing: needs_processing.setdefault((r.client_id, r.flow_id), []).append(r) ...
Builds the writes to store the given responses in the db.
def _WriteResponses(self, responses, cursor): """Builds the writes to store the given responses in the db.""" query = ("INSERT IGNORE INTO flow_responses " "(client_id, flow_id, request_id, response_id, " "response, status, iterator, timestamp) VALUES ") templates = [] args =...
Builds deletes for client messages.
def _DeleteClientActionRequest(self, to_delete, cursor=None): """Builds deletes for client messages.""" query = "DELETE FROM client_action_requests WHERE " conditions = [] args = [] for client_id, flow_id, request_id in to_delete: conditions.append("(client_id=%s AND flow_id=%s AND request_id...
Writes a flow responses and updates flow requests expected counts.
def _WriteFlowResponsesAndExpectedUpdates(self, responses, cursor=None): """Writes a flow responses and updates flow requests expected counts.""" self._WriteResponses(responses, cursor) query = """ UPDATE flow_requests SET responses_expected=%(responses_expected)s WHERE client_id...
Reads counts of responses for the given requests.
def _ReadFlowResponseCounts(self, request_keys, cursor=None): """Reads counts of responses for the given requests.""" query = """ SELECT flow_requests.client_id, flow_requests.flow_id, flow_requests.request_id, COUNT(*) FROM flow_responses, flow_requests WHERE ({conditions}) A...
Reads and locks the next_request_to_process for a number of flows.
def _ReadAndLockNextRequestsToProcess(self, flow_keys, cursor): """Reads and locks the next_request_to_process for a number of flows.""" query = """ SELECT client_id, flow_id, next_request_to_process FROM flows WHERE {conditions} FOR UPDATE """ condition_template = "(client_id =...
Reads, locks, and updates completed requests.
def _ReadLockAndUpdateCompletedRequests(self, request_keys, response_counts, cursor): """Reads, locks, and updates completed requests.""" condition_template = """ (flow_requests.client_id = %s AND flow_requests.flow_id = %s AND flow_requests.request...
Updates requests and writes FlowProcessingRequests if needed.
def _UpdateRequestsAndScheduleFPRs(self, responses, cursor=None): """Updates requests and writes FlowProcessingRequests if needed.""" request_keys = set( (r.client_id, r.flow_id, r.request_id) for r in responses) flow_keys = set((r.client_id, r.flow_id) for r in responses) response_counts = se...
Writes FlowMessages and updates corresponding requests.
def WriteFlowResponses(self, responses): """Writes FlowMessages and updates corresponding requests.""" if not responses: return for batch in collection.Batch(responses, self._WRITE_ROWS_BATCH_SIZE): self._WriteFlowResponsesAndExpectedUpdates(batch) completed_requests = self._UpdateRequ...
Deletes a list of flow requests from the database.
def DeleteFlowRequests(self, requests, cursor=None): """Deletes a list of flow requests from the database.""" if not requests: return conditions = [] args = [] for r in requests: conditions.append("(client_id=%s AND flow_id=%s AND request_id=%s)") args.append(db_utils.ClientIDToIn...
Deletes all requests and responses for a given flow from the database.
def DeleteAllFlowRequestsAndResponses(self, client_id, flow_id, cursor=None): """Deletes all requests and responses for a given flow from the database.""" args = [db_utils.ClientIDToInt(client_id), db_utils.FlowIDToInt(flow_id)] res_query = "DELETE FROM flow_responses WHERE client_id=%s AND flow_id=%s" ...
Reads all requests for a flow that can be processed by the worker.
def ReadFlowRequestsReadyForProcessing(self, client_id, flow_id, next_needed_request, cursor=None): """Reads all requests for a flow that can be process...
Releases a flow that the worker was processing to the database.
def ReleaseProcessedFlow(self, flow_obj, cursor=None): """Releases a flow that the worker was processing to the database.""" update_query = """ UPDATE flows LEFT OUTER JOIN ( SELECT client_id, flow_id, needs_processing FROM flow_requests WHERE client_id = %(client_id)s AND ...
Reads all flow processing requests from the database.
def ReadFlowProcessingRequests(self, cursor=None): """Reads all flow processing requests from the database.""" query = ("SELECT request, UNIX_TIMESTAMP(timestamp) " "FROM flow_processing_requests") cursor.execute(query) res = [] for serialized_request, ts in cursor.fetchall(): re...
Deletes a list of flow processing requests from the database.
def AckFlowProcessingRequests(self, requests, cursor=None): """Deletes a list of flow processing requests from the database.""" if not requests: return query = "DELETE FROM flow_processing_requests WHERE " conditions = [] args = [] for r in requests: conditions.append( "(...
Leases a number of flow processing requests.
def _LeaseFlowProcessingReqests(self, cursor=None): """Leases a number of flow processing requests.""" now = rdfvalue.RDFDatetime.Now() expiry = now + rdfvalue.Duration("10m") query = """ UPDATE flow_processing_requests SET leased_until=FROM_UNIXTIME(%(expiry)s), leased_by=%(id)s WHER...
The main loop for the flow processing request queue.
def _FlowProcessingRequestHandlerLoop(self, handler): """The main loop for the flow processing request queue.""" while not self.flow_processing_request_handler_stop: try: msgs = self._LeaseFlowProcessingReqests() if msgs: for m in msgs: self.flow_processing_request_ha...
Registers a handler to receive flow processing messages.
def RegisterFlowProcessingHandler(self, handler): """Registers a handler to receive flow processing messages.""" self.UnregisterFlowProcessingHandler() if handler: self.flow_processing_request_handler_stop = False self.flow_processing_request_handler_thread = threading.Thread( name="f...
Unregisters any registered flow processing handler.
def UnregisterFlowProcessingHandler(self, timeout=None): """Unregisters any registered flow processing handler.""" if self.flow_processing_request_handler_thread: self.flow_processing_request_handler_stop = True self.flow_processing_request_handler_thread.join(timeout) if self.flow_processing_...
Writes flow results for a given flow.
def WriteFlowResults(self, results, cursor=None): """Writes flow results for a given flow.""" query = ("INSERT INTO flow_results " "(client_id, flow_id, hunt_id, timestamp, payload, type, tag) " "VALUES ") templates = [] args = [] for r in results: templates.append("...
Reads flow results of a given flow using given query options.
def ReadFlowResults(self, client_id, flow_id, offset, count, with_tag=None, with_type=None, with_substring=None, cursor=None): """Reads flow...
Counts flow results of a given flow using given query options.
def CountFlowResults(self, client_id, flow_id, with_tag=None, with_type=None, cursor=None): """Counts flow results of a given flow using given query options.""" query = ("SELECT COUNT(*) " ...
Returns counts of flow results grouped by result type.
def CountFlowResultsByType(self, client_id, flow_id, cursor=None): """Returns counts of flow results grouped by result type.""" query = ("SELECT type, COUNT(*) FROM flow_results " "FORCE INDEX (flow_results_by_client_id_flow_id_timestamp) " "WHERE client_id = %s AND flow_id = %s " ...
Reads flow log entries of a given flow using given query options.
def ReadFlowLogEntries(self, client_id, flow_id, offset, count, with_substring=None, cursor=None): """Reads flow log entries of a given flow using given query options...
Returns number of flow log entries of a given flow.
def CountFlowLogEntries(self, client_id, flow_id, cursor=None): """Returns number of flow log entries of a given flow.""" query = ("SELECT COUNT(*) " "FROM flow_log_entries " "FORCE INDEX (flow_log_entries_by_flow) " "WHERE client_id = %s AND flow_id = %s ") args = [d...
Writes flow output plugin log entries for a given flow.
def WriteFlowOutputPluginLogEntries(self, entries, cursor=None): """Writes flow output plugin log entries for a given flow.""" query = ("INSERT INTO flow_output_plugin_log_entries " "(client_id, flow_id, hunt_id, output_plugin_id, " "log_entry_type, message) " "VALUES ") ...
Reads flow output plugin log entries.
def ReadFlowOutputPluginLogEntries(self, client_id, flow_id, output_plugin_id, offset, count, with...
Returns number of flow output plugin log entries of a given flow.
def CountFlowOutputPluginLogEntries(self, client_id, flow_id, output_plugin_id, with_type=None, cursor=None): """Returns numbe...
Evaluates rules held in the rule set. Args: client_obj: Either an aff4 client object or a client_info dict as returned by ReadFullInfoClient if the relational db is used for reading. Returns: A bool value of the evaluation. Raises: ValueError: The match mode is of unknown value.
def Evaluate(self, client_obj): """Evaluates rules held in the rule set. Args: client_obj: Either an aff4 client object or a client_info dict as returned by ReadFullInfoClient if the relational db is used for reading. Returns: A bool value of the evaluation. Raises: ValueErr...
Writes user object for a user with a given name.
def WriteGRRUser(self, username, password=None, ui_mode=None, canary_mode=None, user_type=None): """Writes user object for a user with a given name.""" u = self.users.setdefault(username, rdf_objects.GRRUser(username=...
Reads a user object corresponding to a given name.
def ReadGRRUser(self, username): """Reads a user object corresponding to a given name.""" try: return self.users[username].Copy() except KeyError: raise db.UnknownGRRUserError(username)
Reads GRR users with optional pagination, sorted by username.
def ReadGRRUsers(self, offset=0, count=None): """Reads GRR users with optional pagination, sorted by username.""" if count is None: count = len(self.users) users = sorted(self.users.values(), key=lambda user: user.username) return [user.Copy() for user in users[offset:offset + count]]
Deletes the user and all related metadata with the given username.
def DeleteGRRUser(self, username): """Deletes the user and all related metadata with the given username.""" try: del self.approvals_by_username[username] except KeyError: pass # No approvals to delete for this user. for approvals in itervalues(self.approvals_by_username): for approva...
Writes an approval request object.
def WriteApprovalRequest(self, approval_request): """Writes an approval request object.""" approvals = self.approvals_by_username.setdefault( approval_request.requestor_username, {}) approval_id = str(os.urandom(16).encode("hex")) cloned_request = approval_request.Copy() cloned_request.time...
Reads an approval request object with a given id.
def ReadApprovalRequest(self, requestor_username, approval_id): """Reads an approval request object with a given id.""" try: return self.approvals_by_username[requestor_username][approval_id] except KeyError: raise db.UnknownApprovalRequestError("Can't find approval with id: %s" % ...
Reads approval requests of a given type for a given user.
def ReadApprovalRequests(self, requestor_username, approval_type, subject_id=None, include_expired=False): """Reads approval requests of a given type for a given user.""" now = rdfvalue.RDFDatetime.Now() ...
Grants approval for a given request using given username.
def GrantApproval(self, requestor_username, approval_id, grantor_username): """Grants approval for a given request using given username.""" try: approval = self.approvals_by_username[requestor_username][approval_id] approval.grants.append( rdf_objects.ApprovalGrant( grantor_u...
Writes a notification for a given user.
def WriteUserNotification(self, notification): """Writes a notification for a given user.""" if notification.username not in self.users: raise db.UnknownGRRUserError(notification.username) cloned_notification = notification.Copy() if not cloned_notification.timestamp: cloned_notification.ti...
Reads notifications scheduled for a user within a given timerange.
def ReadUserNotifications(self, username, state=None, timerange=None): """Reads notifications scheduled for a user within a given timerange.""" from_time, to_time = self._ParseTimeRange(timerange) result = [] for n in self.notifications_by_username.get(username, []): if from_time <= n.timestamp <...
Updates existing user notification objects.
def UpdateUserNotifications(self, username, timestamps, state=None): """Updates existing user notification objects.""" if not timestamps: return for n in self.notifications_by_username.get(username, []): if n.timestamp in timestamps: n.state = state
Converts FileFinderSizeConditions to RegistryFinderConditions.
def _ConditionsToFileFinderConditions(conditions): """Converts FileFinderSizeConditions to RegistryFinderConditions.""" ff_condition_type_cls = rdf_file_finder.FileFinderCondition.Type result = [] for c in conditions: if c.condition_type == RegistryFinderCondition.Type.MODIFICATION_TIME: result.append...
Strips type information from rendered data. Useful for debugging.
def StripTypeInfo(rendered_data): """Strips type information from rendered data. Useful for debugging.""" if isinstance(rendered_data, (list, tuple)): return [StripTypeInfo(d) for d in rendered_data] elif isinstance(rendered_data, dict): if "value" in rendered_data and "type" in rendered_data: retu...
Render given RDFValue as plain old python objects.
def RenderValue(value, limit_lists=-1): """Render given RDFValue as plain old python objects.""" if value is None: return None renderer = ApiValueRenderer.GetRendererForValueOrClass( value, limit_lists=limit_lists) return renderer.RenderValue(value)
Returns renderer corresponding to a given value and rendering args.
def GetRendererForValueOrClass(cls, value, limit_lists=-1): """Returns renderer corresponding to a given value and rendering args.""" if inspect.isclass(value): value_cls = value else: value_cls = value.__class__ cache_key = "%s_%d" % (value_cls.__name__, limit_lists) try: render...
Renders default value of a given class. Args: value_cls: Default value of this class will be rendered. This class has to be (or to be a subclass of) a self.value_class (i.e. a class that this renderer is capable of rendering). Returns: An initialized default value. Raises: ...
def BuildDefaultValue(self, value_cls): """Renders default value of a given class. Args: value_cls: Default value of this class will be rendered. This class has to be (or to be a subclass of) a self.value_class (i.e. a class that this renderer is capable of rendering). Returns: ...
Renders metadata of a given value class. Args: value_cls: Metadata of this class will be rendered. This class has to be (or to be a subclass of) a self.value_class (i.e. a class that this renderer is capable of rendering). Returns: Dictionary with class metadata.
def BuildTypeDescriptor(self, value_cls): """Renders metadata of a given value class. Args: value_cls: Metadata of this class will be rendered. This class has to be (or to be a subclass of) a self.value_class (i.e. a class that this renderer is capable of rendering). Returns: D...
Renders GrrMessage payload and renames args_rdf_name field.
def RenderPayload(self, result, value): """Renders GrrMessage payload and renames args_rdf_name field.""" if "args_rdf_name" in result: result["payload_type"] = result["args_rdf_name"] del result["args_rdf_name"] if "args" in result: result["payload"] = self._PassThrough(value.payload) ...
Payload-aware metadata processor.
def AdjustDescriptor(self, fields): """Payload-aware metadata processor.""" for f in fields: if f.name == "args_rdf_name": f.name = "payload_type" if f.name == "args": f.name = "payload" return fields
Takes the plist contents generated by binplist and returns a plain dict. binplist uses rich types to express some of the plist types. We need to convert them to types that RDFValueArray will be able to transport. Args: plist: A plist to convert. Returns: A simple python type.
def PlistValueToPlainValue(plist): """Takes the plist contents generated by binplist and returns a plain dict. binplist uses rich types to express some of the plist types. We need to convert them to types that RDFValueArray will be able to transport. Args: plist: A plist to convert. Returns: A simp...
StringFinish doesn't act on ATTRIBUTEs here.
def StringFinish(self, **_): """StringFinish doesn't act on ATTRIBUTEs here.""" if self.state == "ARG": return self.InsertArg(string=self.string)
Adds a path component to the current attribute.
def AddAttributePath(self, **_): """Adds a path component to the current attribute.""" attribute_path = self.current_expression.attribute if not attribute_path: attribute_path = [] attribute_path.append(self.string) self.current_expression.SetAttribute(attribute_path)
Makes dictionaries expandable when dealing with plists.
def _AtNonLeaf(self, attr_value, path): """Makes dictionaries expandable when dealing with plists.""" if isinstance(attr_value, dict): for value in self.Expand(attr_value, path[1:]): yield value else: for v in objectfilter.ValueExpander._AtNonLeaf(self, attr_value, path): yield v
Returns a list of MetricMetadata for GRR server components.
def GetMetadata(): """Returns a list of MetricMetadata for GRR server components.""" return [ # GRR user-management metrics. stats_utils.CreateEventMetadata( "acl_check_time", fields=[("check_type", str)]), stats_utils.CreateCounterMetadata( "approval_searches", field...
Parses a YAML source into a Python object. Args: text: A YAML source to parse. Returns: A Python data structure corresponding to the YAML source.
def Parse(text): """Parses a YAML source into a Python object. Args: text: A YAML source to parse. Returns: A Python data structure corresponding to the YAML source. """ precondition.AssertType(text, Text) if compatibility.PY2: text = text.encode("utf-8") return yaml.safe_load(text)
Parses many YAML documents into a list of Python objects. Args: text: A YAML source with multiple documents embedded. Returns: A list of Python data structures corresponding to the YAML documents.
def ParseMany(text): """Parses many YAML documents into a list of Python objects. Args: text: A YAML source with multiple documents embedded. Returns: A list of Python data structures corresponding to the YAML documents. """ precondition.AssertType(text, Text) if compatibility.PY2: text = tex...
Reads a Python object stored in a specified YAML file. Args: filepath: A filepath to the YAML file. Returns: A Python data structure corresponding to the YAML in the given file.
def ReadFromPath(filepath): """Reads a Python object stored in a specified YAML file. Args: filepath: A filepath to the YAML file. Returns: A Python data structure corresponding to the YAML in the given file. """ with io.open(filepath, mode="r", encoding="utf-8") as filedesc: return ReadFromFile...
Reads a Python object stored in a specified YAML file. Args: filepath: A filepath to the YAML file. Returns: A Python data structure corresponding to the YAML in the given file.
def ReadManyFromPath(filepath): """Reads a Python object stored in a specified YAML file. Args: filepath: A filepath to the YAML file. Returns: A Python data structure corresponding to the YAML in the given file. """ with io.open(filepath, mode="r", encoding="utf-8") as filedesc: return ReadMany...
Stringifies a Python object into its YAML representation. Args: obj: A Python object to convert to YAML. Returns: A YAML representation of the given object.
def Dump(obj): """Stringifies a Python object into its YAML representation. Args: obj: A Python object to convert to YAML. Returns: A YAML representation of the given object. """ text = yaml.safe_dump(obj, default_flow_style=False, allow_unicode=True) if compatibility.PY2: text = text.decode(...
Stringifies a sequence of Python objects to a multi-document YAML. Args: objs: An iterable of Python objects to convert to YAML. Returns: A multi-document YAML representation of the given objects.
def DumpMany(objs): """Stringifies a sequence of Python objects to a multi-document YAML. Args: objs: An iterable of Python objects to convert to YAML. Returns: A multi-document YAML representation of the given objects. """ precondition.AssertIterableType(objs, object) text = yaml.safe_dump_all(o...
Serializes and writes given Python object to the specified YAML file. Args: obj: A Python object to serialize. filepath: A path to the file into which the object is to be written.
def WriteToPath(obj, filepath): """Serializes and writes given Python object to the specified YAML file. Args: obj: A Python object to serialize. filepath: A path to the file into which the object is to be written. """ with io.open(filepath, mode="w", encoding="utf-8") as filedesc: WriteToFile(obj,...
Serializes and writes given Python objects to a multi-document YAML file. Args: objs: An iterable of Python objects to serialize. filepath: A path to the file into which the object is to be written.
def WriteManyToPath(objs, filepath): """Serializes and writes given Python objects to a multi-document YAML file. Args: objs: An iterable of Python objects to serialize. filepath: A path to the file into which the object is to be written. """ with io.open(filepath, mode="w", encoding="utf-8") as filede...
Creates Windows paths detector. Commandline strings can be space separated and contain options. e.g. C:\\Program Files\\ACME Corporation\\wiz.exe /quiet /blah See here for microsoft doco on commandline parsing: http://msdn.microsoft.com/en-us/library/windows/desktop/ms682425(v=vs.85).aspx Args: vars_ma...
def CreateWindowsRegistryExecutablePathsDetector(vars_map=None): """Creates Windows paths detector. Commandline strings can be space separated and contain options. e.g. C:\\Program Files\\ACME Corporation\\wiz.exe /quiet /blah See here for microsoft doco on commandline parsing: http://msdn.microsoft.com/en-...
Detects paths in a list of Windows Registry strings. Args: source_values: A list of strings to detect paths in. vars_map: Dictionary of "string" -> "string|list", i.e. a mapping of environment variables names to their suggested values or to lists of their suggested values. Yields: ...
def DetectExecutablePaths(source_values, vars_map=None): """Detects paths in a list of Windows Registry strings. Args: source_values: A list of strings to detect paths in. vars_map: Dictionary of "string" -> "string|list", i.e. a mapping of environment variables names to their suggested values or...
Extracts interesting paths from a given path. Args: components: Source string represented as a list of components. Returns: A list of extracted paths (as strings).
def Extract(self, components): """Extracts interesting paths from a given path. Args: components: Source string represented as a list of components. Returns: A list of extracted paths (as strings). """ rundll_index = -1 for index, component in enumerate(components): if compo...
Extracts interesting paths from a given path. Args: components: Source string represented as a list of components. Returns: A list of extracted paths (as strings).
def Extract(self, components): """Extracts interesting paths from a given path. Args: components: Source string represented as a list of components. Returns: A list of extracted paths (as strings). """ for index, component in enumerate(components): if component.lower().endswith(...
Processes a given path. Args: path: Path (as a string) to post-process. Returns: A list of paths with environment variables replaced with their values. If the mapping had a list of values for a particular variable, instead of just one value, then all possible replacements will be ...
def Process(self, path): """Processes a given path. Args: path: Path (as a string) to post-process. Returns: A list of paths with environment variables replaced with their values. If the mapping had a list of values for a particular variable, instead of just one value, then all pos...
The main entry point for checking access to AFF4 resources. Args: token: An instance of ACLToken security token. subjects: The list of subject URNs which the user is requesting access to. If any of these fail, the whole request is denied. requested_access: A string specifying the desir...
def CheckDataStoreAccess(self, token, subjects, requested_access="r"): """The main entry point for checking access to AFF4 resources. Args: token: An instance of ACLToken security token. subjects: The list of subject URNs which the user is requesting access to. If any of these fail, the w...
Writes hunt results from a given client as part of a given hunt.
def WriteHuntResults(client_id, hunt_id, responses): """Writes hunt results from a given client as part of a given hunt.""" if not hunt.IsLegacyHunt(hunt_id): data_store.REL_DB.WriteFlowResults(responses) hunt.StopHuntIfCPUOrNetworkLimitsExceeded(hunt_id) return hunt_id_urn = rdfvalue.RDFURN("hunts...
Processes error and status message for a given hunt-induced flow.
def ProcessHuntFlowError(flow_obj, error_message=None, backtrace=None, status_msg=None): """Processes error and status message for a given hunt-induced flow.""" if not hunt.IsLegacyHunt(flow_obj.parent_hunt_id): hunt.StopHuntIfCPUOrNetw...
Notifis hunt about a given hunt-induced flow completion.
def ProcessHuntFlowDone(flow_obj, status_msg=None): """Notifis hunt about a given hunt-induced flow completion.""" if not hunt.IsLegacyHunt(flow_obj.parent_hunt_id): hunt_obj = hunt.StopHuntIfCPUOrNetworkLimitsExceeded( flow_obj.parent_hunt_id) hunt.CompleteHuntIfExpirationTimeReached(hunt_obj) ...
Processes log message from a given hunt-induced flow.
def ProcessHuntFlowLog(flow_obj, log_msg): """Processes log message from a given hunt-induced flow.""" if not hunt.IsLegacyHunt(flow_obj.parent_hunt_id): return hunt_urn = rdfvalue.RDFURN("hunts").Add(flow_obj.parent_hunt_id) flow_urn = hunt_urn.Add(flow_obj.flow_id) log_entry = rdf_flows.FlowLog( ...
Processes client crash triggerted by a given hunt-induced flow.
def ProcessHuntClientCrash(flow_obj, client_crash_info): """Processes client crash triggerted by a given hunt-induced flow.""" if not hunt.IsLegacyHunt(flow_obj.parent_hunt_id): hunt.StopHuntIfCrashLimitExceeded(flow_obj.parent_hunt_id) return hunt_urn = rdfvalue.RDFURN("hunts").Add(flow_obj.parent_hunt...
Validates a VFS path.
def ValidateVfsPath(path): """Validates a VFS path.""" components = (path or "").lstrip("/").split("/") if not components: raise ValueError("Empty path is not a valid path: %s." % utils.SmartStr(path)) if components[0] not in ROOT_FILES_WHITELIST: raise ValueError( "First ...
Generate file details based on path infos history.
def _GenerateApiFileDetails(path_infos): """Generate file details based on path infos history.""" type_attrs = [] hash_attrs = [] size_attrs = [] stat_attrs = [] pathspec_attrs = [] def _Value(age, value): """Generate ApiAff4ObjectAttributeValue from an age and a value.""" v = ApiAff4ObjectAttr...
Retrieves the total size in bytes of an AFF4 object. Args: aff4_obj: An AFF4 stream instance to retrieve size for. Returns: An integer representing number of bytes. Raises: TypeError: If `aff4_obj` is not an instance of AFF4 stream.
def _Aff4Size(aff4_obj): """Retrieves the total size in bytes of an AFF4 object. Args: aff4_obj: An AFF4 stream instance to retrieve size for. Returns: An integer representing number of bytes. Raises: TypeError: If `aff4_obj` is not an instance of AFF4 stream. """ if not isinstance(aff4_obj, ...
Reads contents of given AFF4 file. Args: aff4_obj: An AFF4 stream instance to retrieve contents for. offset: An offset to start the reading from. length: A number of bytes to read. Reads the whole file if 0. Returns: Contents of specified AFF4 stream. Raises: TypeError: If `aff4_obj` is not...
def _Aff4Read(aff4_obj, offset, length): """Reads contents of given AFF4 file. Args: aff4_obj: An AFF4 stream instance to retrieve contents for. offset: An offset to start the reading from. length: A number of bytes to read. Reads the whole file if 0. Returns: Contents of specified AFF4 stream. ...
Gets timeline entries from AFF4.
def _GetTimelineStatEntriesLegacy(client_id, file_path, with_history=True): """Gets timeline entries from AFF4.""" folder_urn = aff4.ROOT_URN.Add(str(client_id)).Add(file_path) child_urns = [] for _, children in aff4.FACTORY.RecursiveMultiListChildren([folder_urn]): child_urns.extend(children) if with_...
Gets timeline entries from REL_DB.
def _GetTimelineStatEntriesRelDB(api_client_id, file_path, with_history=True): """Gets timeline entries from REL_DB.""" path_type, components = rdf_objects.ParseCategorizedPath(file_path) client_id = str(api_client_id) try: root_path_info = data_store.REL_DB.ReadPathInfo(client_id, path_type, ...
Gets timeline entries from the appropriate data source (AFF4 or REL_DB).
def _GetTimelineStatEntries(client_id, file_path, with_history=True): """Gets timeline entries from the appropriate data source (AFF4 or REL_DB).""" if data_store.RelationalDBEnabled(): fn = _GetTimelineStatEntriesRelDB else: fn = _GetTimelineStatEntriesLegacy for v in fn(client_id, file_path, with_hi...
Gets timeline items for a given client id and path.
def _GetTimelineItems(client_id, file_path): """Gets timeline items for a given client id and path.""" items = [] for file_path, stat_entry, _ in _GetTimelineStatEntries( client_id, file_path, with_history=True): # It may be that for a given timestamp only hash entry is available, we're # skippin...
Initializes the current instance from an Aff4Object. Iterates over all attributes of the Aff4Object defined by a given class and adds a representation of them to the current instance. Args: aff4_obj: An Aff4Object to take the attributes from. aff4_cls: A class in the inheritance hierarchy of t...
def InitFromAff4Object(self, aff4_obj, aff4_cls, attr_blacklist): """Initializes the current instance from an Aff4Object. Iterates over all attributes of the Aff4Object defined by a given class and adds a representation of them to the current instance. Args: aff4_obj: An Aff4Object to take the a...
Initializes the current instance from an Aff4Object. Iterates the inheritance hierarchy of the given Aff4Object and adds a ApiAff4ObjectType for each class found in the hierarchy. Args: aff4_obj: An Aff4Object as source for the initialization. Returns: A reference to the current instance.
def InitFromAff4Object(self, aff4_obj): """Initializes the current instance from an Aff4Object. Iterates the inheritance hierarchy of the given Aff4Object and adds a ApiAff4ObjectType for each class found in the hierarchy. Args: aff4_obj: An Aff4Object as source for the initialization. Retu...
Initializes the current instance from an Aff4Stream. Args: file_obj: An Aff4Stream representing a file. stat_entry: An optional stat entry object to be used. If none is provided, the one stored in the AFF4 data store is used. hash_entry: An optional hash entry object to be used. If none i...
def InitFromAff4Object(self, file_obj, stat_entry=None, hash_entry=None, with_details=False): """Initializes the current instance from an Aff4Stream. Args: file_obj: An Aff4Stream representing a file. ...
Decode data with the given codec name.
def _Decode(self, codec_name, data): """Decode data with the given codec name.""" try: return data.decode(codec_name, "replace") except LookupError: raise RuntimeError("Codec could not be found.") except AssertionError: raise RuntimeError("Codec failed to decode")