INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Checks if the hunt has expired.
def expired(self): """Checks if the hunt has expired.""" expiry_time = self.expiry_time if expiry_time is not None: return expiry_time < rdfvalue.RDFDatetime.Now() else: return False
Looks for approvals for an object and returns available valid tokens.
def GetApprovalForObject(object_urn, token=None, username=""): """Looks for approvals for an object and returns available valid tokens. Args: object_urn: Urn of the object we want access to. token: The token to use to lookup the ACLs. username: The user to get the approval for, if "" we get...
Enforce a dual approver policy for access.
def CheckAccess(self, token): """Enforce a dual approver policy for access.""" namespace, _ = self.urn.Split(2) if namespace != "ACL": raise access_control.UnauthorizedAccess( "Approval object has invalid urn %s." % self.urn, subject=self.urn, requested_access=token.requ...
Returns a list of usernames of approvers who approved this approval.
def GetNonExpiredApprovers(self): """Returns a list of usernames of approvers who approved this approval.""" lifetime = rdfvalue.Duration( self.Get(self.Schema.LIFETIME) or config.CONFIG["ACL.token_expiry"]) # Check that there are enough approvers. # # TODO(user): approvals have to be open...
Infers user name and subject urn from self. urn.
def InferUserAndSubjectFromUrn(self): """Infers user name and subject urn from self.urn.""" _, client_id, user, _ = self.urn.Split(4) return (user, rdf_client.ClientURN(client_id))
Infers user name and subject urn from self. urn.
def InferUserAndSubjectFromUrn(self): """Infers user name and subject urn from self.urn.""" _, hunts_str, hunt_id, user, _ = self.urn.Split(5) if hunts_str != "hunts": raise access_control.UnauthorizedAccess( "Approval object has invalid urn %s." % self.urn, requested_access=self....
Infers user name and subject urn from self. urn.
def InferUserAndSubjectFromUrn(self): """Infers user name and subject urn from self.urn.""" _, cron_str, cron_job_name, user, _ = self.urn.Split(5) if cron_str != "cron": raise access_control.UnauthorizedAccess( "Approval object has invalid urn %s." % self.urn, requested_access=se...
Encode an approval URN.
def ApprovalUrnBuilder(subject, user, approval_id): """Encode an approval URN.""" return aff4.ROOT_URN.Add("ACL").Add(subject).Add(user).Add(approval_id)
Build an approval symlink URN.
def ApprovalSymlinkUrnBuilder(approval_type, subject_id, user, approval_id): """Build an approval symlink URN.""" return aff4.ROOT_URN.Add("users").Add(user).Add("approvals").Add( approval_type).Add(subject_id).Add(approval_id)
Create the Approval object and notify the Approval Granter.
def Request(self): """Create the Approval object and notify the Approval Granter.""" approval_id = "approval:%X" % random.UInt32() approval_urn = self.BuildApprovalUrn(approval_id) email_msg_id = email.utils.make_msgid() with aff4.FACTORY.Create( approval_urn, self.approval_type, mode="w"...
Create the Approval object and notify the Approval Granter.
def Grant(self): """Create the Approval object and notify the Approval Granter.""" approvals_root_urn = aff4.ROOT_URN.Add("ACL").Add( self.subject_urn.Path()).Add(self.delegate) children_urns = list(aff4.FACTORY.ListChildren(approvals_root_urn)) if not children_urns: raise access_control....
Builds approval object urn.
def BuildApprovalUrn(self, approval_id): """Builds approval object urn.""" event = rdf_events.AuditEvent( user=self.token.username, action="CLIENT_APPROVAL_REQUEST", client=self.subject_urn, description=self.reason) events.Events.PublishEvent("Audit", event, token=self.token)...
Builds list of symlinks URNs for the approval object.
def BuildApprovalSymlinksUrns(self, approval_id): """Builds list of symlinks URNs for the approval object.""" return [ self.ApprovalSymlinkUrnBuilder("cron", self.subject_urn.Basename(), self.token.username, approval_id) ]
Reads given blobs.
def ReadBlobs(self, blob_ids): """Reads given blobs.""" result = {} for blob_id in blob_ids: result[blob_id] = self.blobs.get(blob_id, None) return result
Checks if given blobs exit.
def CheckBlobsExist(self, blob_ids): """Checks if given blobs exit.""" result = {} for blob_id in blob_ids: result[blob_id] = blob_id in self.blobs return result
This function expands paths from the args and returns related stat entries.
def FileFinderOSFromClient(args): """This function expands paths from the args and returns related stat entries. Args: args: An `rdf_file_finder.FileFinderArgs` object. Yields: `rdf_paths.PathSpec` instances. """ stat_cache = filesystem.StatCache() opts = args.action.stat for path in GetExpand...
Expands given path patterns.
def GetExpandedPaths( args): """Expands given path patterns. Args: args: A `FileFinderArgs` instance that dictates the behaviour of the path expansion. Yields: Absolute paths (as string objects) derived from input patterns. Raises: ValueError: For unsupported path types. """ if args...
Fetches a list of mountpoints.
def _GetMountpoints(only_physical=True): """Fetches a list of mountpoints. Args: only_physical: Determines whether only mountpoints for physical devices (e.g. hard disks) should be listed. If false, mountpoints for things such as memory partitions or `/dev/shm` will be returned as well. Returns:...
Builds a list of mountpoints to ignore during recursive searches.
def _GetMountpointBlacklist(xdev): """Builds a list of mountpoints to ignore during recursive searches. Args: xdev: A `XDev` value that determines policy for crossing device boundaries. Returns: A set of mountpoints to ignore. Raises: ValueError: If `xdev` value is invalid. """ if xdev == rdf...
Writes a hunt object to the database.
def WriteHuntObject(self, hunt_obj): """Writes a hunt object to the database.""" if hunt_obj.hunt_id in self.hunts: raise db.DuplicatedHuntError(hunt_id=hunt_obj.hunt_id) clone = self._DeepCopy(hunt_obj) clone.create_time = rdfvalue.RDFDatetime.Now() clone.last_update_time = rdfvalue.RDFDatet...
Updates the hunt object by applying the update function.
def UpdateHuntObject(self, hunt_id, start_time=None, **kwargs): """Updates the hunt object by applying the update function.""" hunt_obj = self.ReadHuntObject(hunt_id) delta_suffix = "_delta" for k, v in kwargs.items(): if v is None: continue if k.endswith(delta_suffix): ke...
Updates hunt output plugin state for a given output plugin.
def UpdateHuntOutputPluginState(self, hunt_id, state_index, update_fn): """Updates hunt output plugin state for a given output plugin.""" if hunt_id not in self.hunts: raise db.UnknownHuntError(hunt_id) try: state = rdf_flow_runner.OutputPluginState.FromSerializedString( self.hunt_ou...
Reads a hunt object from the database.
def ReadHuntObject(self, hunt_id): """Reads a hunt object from the database.""" try: return self._DeepCopy(self.hunts[hunt_id]) except KeyError: raise db.UnknownHuntError(hunt_id)
Reads all hunt objects from the database.
def ReadHuntObjects(self, offset, count, with_creator=None, created_after=None, with_description_match=None): """Reads all hunt objects from the database.""" filter_fns = [] if with_creator is not N...
Reads hunt log entries of a given hunt using given query options.
def ReadHuntLogEntries(self, hunt_id, offset, count, with_substring=None): """Reads hunt log entries of a given hunt using given query options.""" all_entries = [] for flow_obj in self._GetHuntFlows(hunt_id): for entry in self.ReadFlowLogEntries( flow_obj.client_id, flow_obj.flow_i...
Reads hunt results of a given hunt using given query options.
def ReadHuntResults(self, hunt_id, offset, count, with_tag=None, with_type=None, with_substring=None, with_timestamp=None): """Reads hunt results of a given hunt ...
Counts hunt results of a given hunt using given query options.
def CountHuntResults(self, hunt_id, with_tag=None, with_type=None): """Counts hunt results of a given hunt using given query options.""" return len( self.ReadHuntResults( hunt_id, 0, sys.maxsize, with_tag=with_tag, with_type=with_type))
Reads hunt flows matching given conditins.
def ReadHuntFlows(self, hunt_id, offset, count, filter_condition=db.HuntFlowsCondition.UNSET): """Reads hunt flows matching given conditins.""" if filter_condition == db.HuntFlowsCondition.UNSET: filter_fn = lambda _: True ...
Counts hunt flows matching given conditions.
def CountHuntFlows(self, hunt_id, filter_condition=db.HuntFlowsCondition.UNSET): """Counts hunt flows matching given conditions.""" return len( self.ReadHuntFlows( hunt_id, 0, sys.maxsize, filter_condition=filter_condition))
Reads hunt counters.
def ReadHuntCounters(self, hunt_id): """Reads hunt counters.""" num_clients = self.CountHuntFlows(hunt_id) num_successful_clients = self.CountHuntFlows( hunt_id, filter_condition=db.HuntFlowsCondition.SUCCEEDED_FLOWS_ONLY) num_failed_clients = self.CountHuntFlows( hunt_id, filter_conditi...
Read/ calculate hunt client resources stats.
def ReadHuntClientResourcesStats(self, hunt_id): """Read/calculate hunt client resources stats.""" result = rdf_stats.ClientResourcesStats() for f in self._GetHuntFlows(hunt_id): cr = rdf_client_stats.ClientResources( session_id="%s/%s" % (f.client_id, f.flow_id), client_id=f.clie...
Reads hunt flows states and timestamps.
def ReadHuntFlowsStatesAndTimestamps(self, hunt_id): """Reads hunt flows states and timestamps.""" result = [] for f in self._GetHuntFlows(hunt_id): result.append( db.FlowStateAndTimestamps( flow_state=f.flow_state, create_time=f.create_time, last_u...
Reads hunt output plugin log entries.
def ReadHuntOutputPluginLogEntries(self, hunt_id, output_plugin_id, offset, count, with_type=None): """Reads hunt output plugin log...
Counts hunt output plugin log entries.
def CountHuntOutputPluginLogEntries(self, hunt_id, output_plugin_id, with_type=None): """Counts hunt output plugin log entries.""" return len( self.ReadHuntOutputPluginLogEntries( ...
Writes a foreman rule to the database.
def WriteForemanRule(self, rule, cursor=None): """Writes a foreman rule to the database.""" query = ("INSERT INTO foreman_rules " " (hunt_id, expiration_time, rule) " "VALUES (%s, FROM_UNIXTIME(%s), %s) " "ON DUPLICATE KEY UPDATE " " expiration_time=FROM_UNI...
Run the main test harness.
def main(_): """Run the main test harness.""" if flags.FLAGS.version: print("GRR Admin UI {}".format(config_server.VERSION["packageversion"])) return config.CONFIG.AddContext( contexts.ADMIN_UI_CONTEXT, "Context applied when running the admin user interface GUI.") server_startup.Init() ...
Updates the last crash attribute of the client.
def WriteAllCrashDetails(client_id, crash_details, flow_session_id=None, hunt_session_id=None, token=None): """Updates the last crash attribute of the client.""" # AFF4. if data_store.AFF4Enabled(): with aff4.F...
Processes this event.
def ProcessMessages(self, msgs=None, token=None): """Processes this event.""" nanny_msg = "" for crash_details in msgs: client_urn = crash_details.client_id client_id = client_urn.Basename() # The session id of the flow that crashed. session_id = crash_details.session_id # L...
Actually processes the contents of the response.
def ProcessResponse(self, client_id, response): """Actually processes the contents of the response.""" precondition.AssertType(client_id, Text) downsampled = rdf_client_stats.ClientStats.Downsampled(response) if data_store.AFF4Enabled(): urn = rdf_client.ClientURN(client_id).Add("stats") w...
Processes a stats response from the client.
def ProcessMessage(self, message): """Processes a stats response from the client.""" self.ProcessResponse(message.source.Basename(), message.payload)
Run the foreman on the client.
def ProcessMessage(self, message): """Run the foreman on the client.""" # Only accept authenticated messages if (message.auth_state != rdf_flows.GrrMessage.AuthorizationState.AUTHENTICATED): return now = time.time() # Maintain a cache of the foreman with self.lock: if (self...
Processes this event.
def SendEmail(self, client_id, message): """Processes this event.""" logging.info(self.logline, client_id, message) client_info = None hostname = None # Write crash data. if data_store.RelationalDBEnabled(): client = data_store.REL_DB.ReadClientSnapshot(client_id) if client is not ...
Handle a startup event.
def WriteClientStartupInfo(self, client_id, new_si): """Handle a startup event.""" drift = rdfvalue.Duration("5m") if data_store.RelationalDBEnabled(): current_si = data_store.REL_DB.ReadClientStartupInfo(client_id) # We write the updated record if the client_info has any changes # or th...
Writes a list of message handler requests to the database.
def WriteMessageHandlerRequests(self, requests): """Writes a list of message handler requests to the database.""" now = rdfvalue.RDFDatetime.Now() for r in requests: flow_dict = self.message_handler_requests.setdefault(r.handler_name, {}) cloned_request = r.Copy() cloned_request.timestamp ...
Reads all message handler requests from the database.
def ReadMessageHandlerRequests(self): """Reads all message handler requests from the database.""" res = [] leases = self.message_handler_leases for requests in itervalues(self.message_handler_requests): for r in itervalues(requests): res.append(r.Copy()) existing_lease = leases.get...
Deletes a list of message handler requests from the database.
def DeleteMessageHandlerRequests(self, requests): """Deletes a list of message handler requests from the database.""" for r in requests: flow_dict = self.message_handler_requests.get(r.handler_name, {}) if r.request_id in flow_dict: del flow_dict[r.request_id] flow_dict = self.message...
Leases a number of message handler requests up to the indicated limit.
def RegisterMessageHandler(self, handler, lease_time, limit=1000): """Leases a number of message handler requests up to the indicated limit.""" self.UnregisterMessageHandler() self.handler_stop = False self.handler_thread = threading.Thread( name="message_handler", target=self._MessageH...
Unregisters any registered message handler.
def UnregisterMessageHandler(self, timeout=None): """Unregisters any registered message handler.""" if self.handler_thread: self.handler_stop = True self.handler_thread.join(timeout) if self.handler_thread.isAlive(): raise RuntimeError("Message handler thread did not join in time.") ...
Read and lease some outstanding message handler requests.
def _LeaseMessageHandlerRequests(self, lease_time, limit): """Read and lease some outstanding message handler requests.""" leased_requests = [] now = rdfvalue.RDFDatetime.Now() zero = rdfvalue.RDFDatetime.FromSecondsSinceEpoch(0) expiration_time = now + lease_time leases = self.message_handler...
Reads all client action requests available for a given client_id.
def ReadAllClientActionRequests(self, client_id): """Reads all client action requests available for a given client_id.""" res = [] for key, orig_request in iteritems(self.client_action_requests): request_client_id, _, _ = key if request_client_id != client_id: continue request = o...
Leases available client action requests for a client.
def LeaseClientActionRequests(self, client_id, lease_time=None, limit=sys.maxsize): """Leases available client action requests for a client.""" leased_requests = [] now = rdfvalue.RDFDatetime.Now() expirati...
Writes messages that should go to the client to the db.
def WriteClientActionRequests(self, requests): """Writes messages that should go to the client to the db.""" for r in requests: req_dict = self.flow_requests.get((r.client_id, r.flow_id), {}) if r.request_id not in req_dict: request_keys = [(r.client_id, r.flow_id, r.request_id) for r in req...
Writes a flow object to the database.
def WriteFlowObject(self, flow_obj): """Writes a flow object to the database.""" if flow_obj.client_id not in self.metadatas: raise db.UnknownClientError(flow_obj.client_id) clone = flow_obj.Copy() clone.last_update_time = rdfvalue.RDFDatetime.Now() self.flows[(flow_obj.client_id, flow_obj.fl...
Reads a flow object from the database.
def ReadFlowObject(self, client_id, flow_id): """Reads a flow object from the database.""" try: return self.flows[(client_id, flow_id)].Copy() except KeyError: raise db.UnknownFlowError(client_id, flow_id)
Returns all flow objects.
def ReadAllFlowObjects( self, client_id = None, min_create_time = None, max_create_time = None, include_child_flows = True, ): """Returns all flow objects.""" res = [] for flow in itervalues(self.flows): if ((client_id is None or flow.client_id == client_id) and ...
Reads flows that were started by a given flow from the database.
def ReadChildFlowObjects(self, client_id, flow_id): """Reads flows that were started by a given flow from the database.""" res = [] for flow in itervalues(self.flows): if flow.client_id == client_id and flow.parent_flow_id == flow_id: res.append(flow) return res
Marks a flow as being processed on this worker and returns it.
def LeaseFlowForProcessing(self, client_id, flow_id, processing_time): """Marks a flow as being processed on this worker and returns it.""" rdf_flow = self.ReadFlowObject(client_id, flow_id) # TODO(user): remove the check for a legacy hunt prefix as soon as # AFF4 is gone. if rdf_flow.parent_hunt_id...
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): """Updates flow objects in the database.""" for client_id, flow_id in client_id_flow_id_pairs: try: self.UpdateFlow( client_id, flow_id, pending_termination=pe...
Writes a list of flow requests to the database.
def WriteFlowRequests(self, requests): """Writes a list of flow requests to the database.""" flow_processing_requests = [] for request in requests: if (request.client_id, request.flow_id) not in self.flows: raise db.AtLeastOneUnknownFlowError([(request.client_id, ...
Deletes a list of flow requests from the database.
def DeleteFlowRequests(self, requests): """Deletes a list of flow requests from the database.""" for request in requests: if (request.client_id, request.flow_id) not in self.flows: raise db.UnknownFlowError(request.client_id, request.flow_id) for request in requests: key = (request.clie...
Writes FlowMessages and updates corresponding requests.
def WriteFlowResponses(self, responses): """Writes FlowMessages and updates corresponding requests.""" status_available = set() requests_updated = set() task_ids_by_request = {} for response in responses: flow_key = (response.client_id, response.flow_id) if flow_key not in self.flows: ...
Reads all requests and responses for a given flow from the database.
def ReadAllFlowRequestsAndResponses(self, client_id, flow_id): """Reads all requests and responses for a given flow from the database.""" flow_key = (client_id, flow_id) try: self.flows[flow_key] except KeyError: return [] request_dict = self.flow_requests.get(flow_key, {}) response...
Deletes all requests and responses for a given flow from the database.
def DeleteAllFlowRequestsAndResponses(self, client_id, flow_id): """Deletes all requests and responses for a given flow from the database.""" flow_key = (client_id, flow_id) try: self.flows[flow_key] except KeyError: raise db.UnknownFlowError(client_id, flow_id) try: del self.flow...
Reads all requests for a flow that can be processed by the worker.
def ReadFlowRequestsReadyForProcessing(self, client_id, flow_id, next_needed_request=None): """Reads all requests for a flow that can be processed by the worker.""" request_dict = self.flow...
Releases a flow that the worker was processing to the database.
def ReleaseProcessedFlow(self, flow_obj): """Releases a flow that the worker was processing to the database.""" key = (flow_obj.client_id, flow_obj.flow_id) next_id_to_process = flow_obj.next_request_to_process request_dict = self.flow_requests.get(key, {}) if (next_id_to_process in request_dict and...
Writes a list of flow processing requests to the database.
def WriteFlowProcessingRequests(self, requests): """Writes a list of flow processing requests to the database.""" # If we don't have a handler thread running, we might be able to process the # requests inline. If we are not, we start the handler thread for real and # queue the requests normally. if ...
Deletes a list of flow processing requests from the database.
def AckFlowProcessingRequests(self, requests): """Deletes a list of flow processing requests from the database.""" for r in requests: key = (r.client_id, r.flow_id) if key in self.flow_processing_requests: del self.flow_processing_requests[key]
Registers a handler to receive flow processing messages.
def _RegisterFlowProcessingHandler(self, handler): """Registers a handler to receive flow processing messages.""" self.flow_handler_stop = False self.flow_handler_thread = threading.Thread( name="flow_processing_handler", target=self._HandleFlowProcessingRequestLoop, args=(handler,))...
Unregisters any registered flow processing handler.
def UnregisterFlowProcessingHandler(self, timeout=None): """Unregisters any registered flow processing handler.""" self.flow_handler_target = None if self.flow_handler_thread: self.flow_handler_stop = True self.flow_handler_thread.join(timeout) if self.flow_handler_thread.isAlive(): ...
Waits until flow processing thread is done processing flows.
def WaitUntilNoFlowsToProcess(self, timeout=None): """Waits until flow processing thread is done processing flows. Args: timeout: If specified, is a max number of seconds to spend waiting. Raises: TimeOutWhileWaitingForFlowsToBeProcessedError: if timeout is reached. """ t = self.flow_h...
Handler thread for the FlowProcessingRequest queue.
def _HandleFlowProcessingRequestLoop(self, handler): """Handler thread for the FlowProcessingRequest queue.""" while not self.flow_handler_stop: with self.lock: todo = self._GetFlowRequestsReadyForProcessing() for request in todo: self.flow_handler_num_being_processed += 1 ...
Writes flow results for a given flow.
def WriteFlowResults(self, results): """Writes flow results for a given flow.""" for r in results: dest = self.flow_results.setdefault((r.client_id, r.flow_id), []) to_write = r.Copy() to_write.timestamp = rdfvalue.RDFDatetime.Now() dest.append(to_write)
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): """Reads flow results of a given flow using give...
Counts flow results of a given flow using given query options.
def CountFlowResults(self, client_id, flow_id, with_tag=None, with_type=None): """Counts flow results of a given flow using given query options.""" return len( self.ReadFlowResults( client_id, flow_id, 0, sys.maxsize, with_tag=with_tag, ...
Returns counts of flow results grouped by result type.
def CountFlowResultsByType(self, client_id, flow_id): """Returns counts of flow results grouped by result type.""" result = collections.Counter() for hr in self.ReadFlowResults(client_id, flow_id, 0, sys.maxsize): key = compatibility.GetName(hr.payload.__class__) result[key] += 1 return res...
Writes flow output plugin log entries for a given flow.
def WriteFlowLogEntries(self, entries): """Writes flow output plugin log entries for a given flow.""" flow_ids = [(e.client_id, e.flow_id) for e in entries] for f in flow_ids: if f not in self.flows: raise db.AtLeastOneUnknownFlowError(flow_ids) for e in entries: dest = self.flow_lo...
Reads flow log entries of a given flow using given query options.
def ReadFlowLogEntries(self, client_id, flow_id, offset, count, with_substring=None): """Reads flow log entries of a given flow using given query options.""" entries = sorted( sel...
Returns number of flow log entries of a given flow.
def CountFlowLogEntries(self, client_id, flow_id): """Returns number of flow log entries of a given flow.""" return len(self.ReadFlowLogEntries(client_id, flow_id, 0, sys.maxsize))
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): """Returns number of flow output plugin log entries of a given flow...
See db. Database.
def WriteSignedBinaryReferences(self, binary_id, references): """See db.Database.""" self.signed_binary_references[_SignedBinaryKeyFromID(binary_id)] = ( references.Copy(), rdfvalue.RDFDatetime.Now())
See db. Database.
def ReadSignedBinaryReferences( self, binary_id ): """See db.Database.""" binary_key = _SignedBinaryKeyFromID(binary_id) try: references, timestamp = self.signed_binary_references[binary_key] except KeyError: raise db.UnknownSignedBinaryError(binary_id) return references.Copy(), ...
Returns a mapping of SQLite column names to Converter objects.
def _GetSqliteSchema(self, proto_struct_class, prefix=""): """Returns a mapping of SQLite column names to Converter objects.""" schema = collections.OrderedDict() for type_info in proto_struct_class.type_infos: if type_info.__class__ is rdf_structs.ProtoEmbedded: schema.update( sel...
Converts a dict of RDF values into a SQL - ready form.
def _ConvertToCanonicalSqlDict(self, schema, raw_dict, prefix=""): """Converts a dict of RDF values into a SQL-ready form.""" flattened_dict = {} for k, v in iteritems(raw_dict): if isinstance(v, dict): flattened_dict.update( self._ConvertToCanonicalSqlDict( schema,...
Copies rows from the given db into the output file then deletes them.
def _FlushAllRows(self, db_connection, table_name): """Copies rows from the given db into the output file then deletes them.""" for sql in db_connection.iterdump(): if (sql.startswith("CREATE TABLE") or sql.startswith("BEGIN TRANSACTION") or sql.startswith("COMMIT")): # These statements ...
Dumps the given aff4object into a yaml representation.
def YamlDumper(aff4object): """Dumps the given aff4object into a yaml representation.""" aff4object.Flush() result = {} for attribute, values in iteritems(aff4object.synced_attributes): result[attribute.predicate] = [] for value in values: # This value is really a LazyDecoder() instance. We need ...
Load an AFF4 object from a serialized YAML representation.
def YamlLoader(string): """Load an AFF4 object from a serialized YAML representation.""" representation = yaml.Parse(string) result_cls = aff4.FACTORY.AFF4Object(representation["aff4_class"]) aff4_attributes = {} for predicate, values in iteritems(representation["attributes"]): attribute = aff4.Attribute....
Builds ExportedMetadata object for a given client id and ClientFullInfo.
def GetMetadata(client_id, client_full_info): """Builds ExportedMetadata object for a given client id and ClientFullInfo.""" metadata = ExportedMetadata() last_snapshot = None if client_full_info.HasField("last_snapshot"): last_snapshot = client_full_info.last_snapshot metadata.client_urn = client_id ...
Builds ExportedMetadata object for a given client id.
def GetMetadataLegacy(client, token=None): """Builds ExportedMetadata object for a given client id. Note: This is a legacy aff4-only implementation. TODO(user): deprecate as soon as REL_DB migration is done. Args: client: RDFURN of a client or VFSGRRClient object itself. token: Security token. Retu...
Converts a set of RDFValues into a set of export - friendly RDFValues.
def ConvertValuesWithMetadata(metadata_value_pairs, token=None, options=None): """Converts a set of RDFValues into a set of export-friendly RDFValues. Args: metadata_value_pairs: Tuples of (metadata, rdf_value), where metadata is an instance of ExportedMetadata and rdf_value is an RDFValue subclass ...
Converts a set of RDFValues into a set of export - friendly RDFValues.
def ConvertValues(default_metadata, values, token=None, options=None): """Converts a set of RDFValues into a set of export-friendly RDFValues. Args: default_metadata: export.ExportedMetadata instance with basic information about where the values come from. This metadata will be passed to exporters....
Returns all converters that take given value as an input value.
def GetConvertersByClass(value_cls): """Returns all converters that take given value as an input value.""" try: return ExportConverter.converters_cache[value_cls] except KeyError: results = [ cls for cls in itervalues(ExportConverter.classes) if cls.input_rdf_type == value_cl...
Generates flattened RDFValue class definition for the given value.
def MakeFlatRDFClass(self, value): """Generates flattened RDFValue class definition for the given value.""" def Flatten(self, metadata, value_to_flatten): if metadata: self.metadata = metadata for desc in value_to_flatten.type_infos: if desc.name == "metadata": continue ...
Parses signed certificate data and updates result rdfvalue.
def ParseSignedData(signed_data, result): """Parses signed certificate data and updates result rdfvalue.""" try: auth_data except NameError: # Verify_sigs is not available so we can't parse signatures. If you want # this functionality, please install the verify-sigs package: # https:...
Parses Hash rdfvalue into ExportedFile s fields.
def ParseFileHash(hash_obj, result): """Parses Hash rdfvalue into ExportedFile's fields.""" if hash_obj.HasField("md5"): result.hash_md5 = str(hash_obj.md5) if hash_obj.HasField("sha1"): result.hash_sha1 = str(hash_obj.sha1) if hash_obj.HasField("sha256"): result.hash_sha256 = str(ha...
Converts StatEntry to ExportedFile.
def Convert(self, metadata, stat_entry, token=None): """Converts StatEntry to ExportedFile. Does nothing if StatEntry corresponds to a registry entry and not to a file. Args: metadata: ExportedMetadata to be used for conversion. stat_entry: StatEntry to be converted. token: Security toke...
Filter out registry keys to operate on files.
def _RemoveRegistryKeys(self, metadata_value_pairs): """Filter out registry keys to operate on files.""" filtered_pairs = [] for metadata, stat_entry in metadata_value_pairs: # Ignore registry keys. if stat_entry.pathspec.pathtype != rdf_paths.PathSpec.PathType.REGISTRY: filtered_pairs.a...
Open files all at once if necessary.
def _OpenFilesForRead(self, metadata_value_pairs, token): """Open files all at once if necessary.""" aff4_paths = [ result.AFF4Path(metadata.client_urn) for metadata, result in metadata_value_pairs ] fds = aff4.FACTORY.MultiOpen(aff4_paths, mode="r", token=token) fds_dict = dict([(fd...
Add file content from aff4_object to result.
def _ExportFileContent(self, aff4_object, result): """Add file content from aff4_object to result.""" if self.options.export_files_contents: try: result.content = aff4_object.Read(self.MAX_CONTENT_SIZE) result.content_sha256 = hashlib.sha256(result.content).hexdigest() except (IOErro...