text
stringlengths
81
112k
Fetch only completed requests and responses up to a limit. def FetchCompletedResponses(self, session_id, timestamp=None, limit=10000): """Fetch only completed requests and responses up to a limit.""" if timestamp is None: timestamp = (0, self.frozen_timestamp or rdfvalue.RDFDatetime.Now()) completed...
Fetches all outstanding requests and responses for this flow. We first cache all requests and responses for this flow in memory to prevent round trips. Args: session_id: The session_id to get the requests/responses for. timestamp: Tuple (start, end) with a time range. Fetched requests and ...
Deletes the request and all its responses from the flow state queue. def DeleteRequest(self, request): """Deletes the request and all its responses from the flow state queue.""" self.requests_to_delete.append(request) if request and request.HasField("request"): self.DeQueueClientRequest(request.requ...
Deletes all states in multiple flows and dequeues all client messages. def MultiDestroyFlowStates(self, session_ids): """Deletes all states in multiple flows and dequeues all client messages.""" deleted_requests = self.data_store.MultiDestroyFlowStates( session_ids, request_limit=self.request_limit) ...
Writes the changes in this object to the datastore. def Flush(self): """Writes the changes in this object to the datastore.""" self.data_store.StoreRequestsAndResponses( new_requests=self.request_queue, new_responses=self.response_queue, requests_to_delete=self.requests_to_delete) ...
Queues the message on the flow's state. def QueueResponse(self, response, timestamp=None): """Queues the message on the flow's state.""" if timestamp is None: timestamp = self.frozen_timestamp self.response_queue.append((response, timestamp))
Queues a notification for a flow. def QueueNotification(self, notification=None, timestamp=None, **kw): """Queues a notification for a flow.""" if notification is None: notification = rdf_flows.GrrNotification(**kw) session_id = notification.session_id if session_id: if timestamp is None...
Removes the tasks from the queue. Note that tasks can already have been removed. It is not an error to re-delete an already deleted task. Args: queue: A queue to clear. tasks: A list of tasks to remove. Tasks may be Task() instances or integers representing the task_id. mutation_pool...
Schedule a set of Task() instances. def Schedule(self, tasks, mutation_pool, timestamp=None): """Schedule a set of Task() instances.""" non_fleetspeak_tasks = [] for queue, queued_tasks in iteritems( collection.Group(tasks, lambda x: x.queue)): if not queue: continue client_id ...
Returns all queue notifications. def GetNotifications(self, queue): """Returns all queue notifications.""" queue_shard = self.GetNotificationShard(queue) return self._GetUnsortedNotifications(queue_shard).values()
Returns notifications for all shards of a queue at once. Used by worker_test_lib.MockWorker to cover all shards with a single worker. Args: queue: usually rdfvalue.RDFURN("aff4:/W") Returns: List of rdf_flows.GrrNotification objects def GetNotificationsForAllShards(self, queue): """Retur...
Returns all the available notifications for a queue_shard. Args: queue_shard: urn of queue shard notifications_by_session_id: store notifications in this dict rather than creating a new one Returns: dict of notifications. keys are session ids. def _GetUnsortedNotifications(self, ...
This signals that there are new messages available in a queue. def NotifyQueue(self, notification, **kwargs): """This signals that there are new messages available in a queue.""" self._MultiNotifyQueue(notification.session_id.Queue(), [notification], **kwargs)
This is the same as NotifyQueue but for several session_ids at once. Args: notifications: A list of notifications. mutation_pool: A MutationPool object to schedule Notifications on. Raises: RuntimeError: An invalid session_id was passed. def MultiNotifyQueue(self, notifications, mutation_po...
Does the actual queuing. def _MultiNotifyQueue(self, queue, notifications, mutation_pool=None): """Does the actual queuing.""" notification_list = [] now = rdfvalue.RDFDatetime.Now() for notification in notifications: if not notification.first_queued: notification.first_queued = ( ...
This deletes the notification when all messages have been processed. def DeleteNotifications(self, session_ids, start=None, end=None): """This deletes the notification when all messages have been processed.""" if not session_ids: return for session_id in session_ids: if not isinstance(session_...
Retrieves tasks from a queue without leasing them. This is good for a read only snapshot of the tasks. Args: queue: The task queue that this task belongs to, usually client.Queue() where client is the ClientURN object you want to schedule msgs on. limit: Number of values to fetch. ...
Returns a list of Tasks leased for a certain time. Args: queue: The queue to query from. lease_seconds: The tasks will be leased for this long. limit: Number of values to fetch. Returns: A list of GrrMessage() objects leased. def QueryAndOwn(self, queue, lease_seconds=10, limit=1): ...
Retrieves responses for a well known flow. Args: session_id: The session_id to get the requests/responses for. Yields: The retrieved responses. def FetchResponses(self, session_id): """Retrieves responses for a well known flow. Args: session_id: The session_id to get the requests/r...
Migrate one Artifact from AFF4 to REL_DB. def _MigrateArtifact(artifact): """Migrate one Artifact from AFF4 to REL_DB.""" name = Text(artifact.name) try: logging.info("Migating %s", name) data_store.REL_DB.WriteArtifact(artifact) logging.info(" Wrote %s", name) except db.DuplicatedArtifactError: ...
Migrates Artifacts from AFF4 to REL_DB. def MigrateArtifacts(): """Migrates Artifacts from AFF4 to REL_DB.""" # First, delete all existing artifacts in REL_DB. artifacts = data_store.REL_DB.ReadAllArtifacts() if artifacts: logging.info("Deleting %d artifacts from REL_DB.", len(artifacts)) for artifact...
Gathers a list of base URLs we will try. def _GetBaseURLs(self): """Gathers a list of base URLs we will try.""" result = config.CONFIG["Client.server_urls"] if not result: # Backwards compatibility - deduce server_urls from Client.control_urls. for control_url in config.CONFIG["Client.control_u...
Gather a list of proxies to use. def _GetProxies(self): """Gather a list of proxies to use.""" # Detect proxies from the OS environment. result = client_utils.FindProxies() # Also try to connect directly if all proxies fail. result.append("") # Also try all proxies configured in the config sy...
Search through all the base URLs to connect to one that works. This is a thin wrapper around requests.request() so most parameters are documented there. Args: path: The URL path to access in this endpoint. verify_cb: A callback which should return True if the response is reasonable. Th...
Get the requested URL. Note that we do not have any concept of timing here - we try to connect through all proxies as fast as possible until one works. Timing and poll frequency is left to the calling code. Args: url: The URL to fetch verify_cb: An optional callback which can be used to va...
Retry the request a few times before we determine it failed. Sometimes the frontend becomes loaded and issues a 500 error to throttle the clients. We wait Client.error_poll_min seconds between each attempt to back off the frontend. Note that this does not affect any timing algorithm in the client itsel...
Wait for the specified timeout. def Wait(self, timeout): """Wait for the specified timeout.""" time.sleep(timeout - int(timeout)) # Split a long sleep interval into 1 second intervals so we can heartbeat. for _ in range(int(timeout)): time.sleep(1) if self.heart_beat_cb: self.hear...
Wait until the next action is needed. def Wait(self): """Wait until the next action is needed.""" time.sleep(self.sleep_time - int(self.sleep_time)) # Split a long sleep interval into 1 second intervals so we can heartbeat. for _ in range(int(self.sleep_time)): time.sleep(1) # Back off slow...
Pushes the Serialized Message on the output queue. def QueueResponse(self, message, blocking=True): """Pushes the Serialized Message on the output queue.""" self._out_queue.Put(message, block=blocking)
Push messages to the input queue. def QueueMessages(self, messages): """Push messages to the input queue.""" # Push all the messages to our input queue for message in messages: self._in_queue.put(message, block=True)
Send the protobuf to the server. Args: rdf_value: The RDFvalue to return. request_id: The id of the request this is a response to. response_id: The id of this response. session_id: The session id of the flow. message_type: The contents of this message, MESSAGE, STATUS or RDF_V...
Entry point for processing jobs. Args: message: The GrrMessage that was delivered from the server. Raises: RuntimeError: The client action requested was not found. def HandleMessage(self, message): """Entry point for processing jobs. Args: message: The GrrMessage that was del...
Returns True if our memory footprint is too large. def MemoryExceeded(self): """Returns True if our memory footprint is too large.""" rss_size = self.proc.memory_info().rss return rss_size // 1024 // 1024 > config.CONFIG["Client.rss_max"]
Sleeps the calling thread with heartbeat. def Sleep(self, timeout): """Sleeps the calling thread with heartbeat.""" if self.nanny_controller: self.nanny_controller.Heartbeat() # Split a long sleep interval into 1 second intervals so we can heartbeat. while timeout > 0: time.sleep(min(1., t...
A handler that is called on client startup. def OnStartup(self): """A handler that is called on client startup.""" # We read the transaction log and fail any requests that are in it. If there # is anything in the transaction log we assume its there because we crashed # last time and let the server know...
Main thread for processing messages. def run(self): """Main thread for processing messages.""" self.OnStartup() try: while True: message = self._in_queue.get() # A message of None is our terminal message. if message is None: break try: self.Hand...
Put a message on the queue, blocking if it is too full. Blocks when the queue contains more than the threshold. Args: message: rdf_flows.GrrMessage The message to put. block: bool If True, we block and wait for the queue to have more space. Otherwise, if the queue is full, we raise. ...
Retrieves and removes the messages from the queue. Args: soft_size_limit: int If there is more data in the queue than soft_size_limit bytes, the returned list of messages will be approximately this large. If None (default), returns all messages currently on the queue. Returns: ...
Check the server PEM for validity. This is used to determine connectivity to the server. Sometimes captive portals return a valid HTTP status, but the data is corrupted. Args: http_object: The response received from the server. Returns: True if the response contains a valid server certifi...
Verify the server response to a 'control' endpoint POST message. We consider the message correct if and only if we can decrypt it properly. Note that in practice we can not use the HTTP status to figure out if the request worked because captive proxies have a habit of lying and returning a HTTP success...
Make a HTTP Post request to the server 'control' endpoint. def MakeRequest(self, data): """Make a HTTP Post request to the server 'control' endpoint.""" stats_collector_instance.Get().IncrementCounter("grr_client_sent_bytes", len(data)) # Verify the resp...
Makes a single request to the GRR server. Returns: A Status() object indicating how the last POST went. def RunOnce(self): """Makes a single request to the GRR server. Returns: A Status() object indicating how the last POST went. """ # Attempt to fetch and load server certificate. ...
Attempts to fetch the server cert. Returns: True if we succeed. def _FetchServerCertificate(self): """Attempts to fetch the server cert. Returns: True if we succeed. """ # Certificate is loaded and still valid. if self.server_certificate: return True response = self.htt...
The main run method of the client. This method does not normally return. Only if there have been more than connection_error_limit failures, the method returns and allows the client to exit. def Run(self): """The main run method of the client. This method does not normally return. Only if there ha...
Initiate the enrollment process. We do not sent more than one enrollment request every 10 minutes. Note that we still communicate to the server in fast poll mode, but these requests are not carrying any payload. def InitiateEnrolment(self): """Initiate the enrollment process. We do not sent more ...
Makes sure this client has a private key set. It first tries to load an RSA key from the certificate. If no certificate is found, or it is invalid, we make a new random RSA key, and store it as our certificate. Returns: An RSA key - either from the certificate or a new random key. def InitPriv...
Return our CSR. def GetCSR(self): """Return our CSR.""" return rdf_crypto.CertificateSigningRequest( common_name=self.common_name, private_key=self.private_key)
Store the new private key on disk. def SavePrivateKey(self, private_key): """Store the new private key on disk.""" self.private_key = private_key config.CONFIG.Set("Client.private_key", self.private_key.SerializeToString()) config.CONFIG.Write()
Loads and verifies the server certificate. def LoadServerCertificate(self, server_certificate=None, ca_certificate=None): """Loads and verifies the server certificate.""" # Check that the server certificate verifies try: server_certificate.Verify(ca_certificate.GetPublicKey()) except rdf_crypto.V...
Return unclaimed hunt result notifications for collection. Args: token: The security token to perform database operations with. start_time: If set, an RDFDateTime indicating at what point to start claiming notifications. Only notifications with a timestamp after this point will be claim...
Chunks given table into multiple smaller ones. Tables that osquery yields can be arbitrarily large. Because GRR's messages cannot be arbitrarily large, it might happen that the table has to be split into multiple smaller ones. Note that that serialized response protos are going to be slightly bigger than th...
Parses table of osquery output. Args: table: A table in a "parsed JSON" representation. Returns: A parsed `rdf_osquery.OsqueryTable` instance. def ParseTable(table): """Parses table of osquery output. Args: table: A table in a "parsed JSON" representation. Returns: A parsed `rdf_osquery.O...
Parses header of osquery output. Args: table: A table in a "parsed JSON" representation. Returns: A parsed `rdf_osquery.OsqueryHeader` instance. def ParseHeader(table): """Parses header of osquery output. Args: table: A table in a "parsed JSON" representation. Returns: A parsed `rdf_osque...
Parses a single row of osquery output. Args: header: A parsed header describing the row format. row: A row in a "parsed JSON" representation. Returns: A parsed `rdf_osquery.OsqueryRow` instance. def ParseRow(header, row): """Parses a single row of osquery output. Args: header: A...
Calls osquery with given query and returns its output. Args: args: A query to call osquery with. Returns: A "parsed JSON" representation of the osquery output. Raises: QueryError: If the query is incorrect. TimeoutError: If a call to the osquery executable times out. Error: If anything else...
Search the text for our value. def Search(self, text): """Search the text for our value.""" if isinstance(text, rdfvalue.RDFString): text = str(text) return self._regex.search(text)
Splits a string of comma-separated emails, appending default domain. def SplitEmailsAndAppendEmailDomain(self, address_list): """Splits a string of comma-separated emails, appending default domain.""" result = [] # Process email addresses, and build up a list. if isinstance(address_list, rdf_standard.D...
This method sends an email notification. Args: to_addresses: blah@mycompany.com string, list of addresses as csv string, or rdf_standard.DomainEmailAddress from_address: blah@mycompany.com string subject: email subject string message: message contents string, as HTML or ...
Schedule all the SystemCronFlows found. def ScheduleSystemCronFlows(names=None, token=None): """Schedule all the SystemCronFlows found.""" if data_store.RelationalDBEnabled(): return cronjobs.ScheduleSystemCronJobs(names=names) errors = [] for name in config.CONFIG["Cron.disabled_system_jobs"]: try: ...
Decorator that creates AFF4 and RELDB cronjobs from a given mixin. def DualDBSystemCronJob(legacy_name=None, stateful=False): """Decorator that creates AFF4 and RELDB cronjobs from a given mixin.""" def Decorator(cls): """Decorator producing 2 classes: legacy style one and a new style one.""" if not legac...
Creates a cron job that runs given flow with a given frequency. Args: cron_args: A protobuf of type rdf_cronjobs.CreateCronJobArgs. job_id: Use this job_id instead of an autogenerated unique name (used for system cron jobs - we want them to have well-defined persistent name). token: Secur...
Returns a list of all currently running cron jobs. def ListJobs(self, token=None): """Returns a list of all currently running cron jobs.""" job_root = aff4.FACTORY.Open(self.CRON_JOBS_PATH, token=token) return [urn.Basename() for urn in job_root.ListChildren()]
Enable cron job with the given URN. def EnableJob(self, job_id, token=None): """Enable cron job with the given URN.""" job_urn = self.CRON_JOBS_PATH.Add(job_id) cron_job = aff4.FACTORY.Open( job_urn, mode="rw", aff4_type=CronJob, token=token) cron_job.Set(cron_job.Schema.DISABLED(0)) cron_j...
Deletes cron job with the given URN. def DeleteJob(self, job_id, token=None): """Deletes cron job with the given URN.""" job_urn = self.CRON_JOBS_PATH.Add(job_id) aff4.FACTORY.Delete(job_urn, token=token)
Tries to lock and run cron jobs. Args: token: security token force: If True, force a run names: List of job names to run. If unset, run them all def RunOnce(self, token=None, force=False, names=None): """Tries to lock and run cron jobs. Args: token: security token force: If...
Deletes flows initiated by the job that are older than specified. def DeleteOldRuns(self, job, cutoff_timestamp=None, token=None): """Deletes flows initiated by the job that are older than specified.""" if cutoff_timestamp is None: raise ValueError("cutoff_timestamp can't be None") child_flows = lis...
Runs a working thread and returns immediately. def RunAsync(self): """Runs a working thread and returns immediately.""" self.running_thread = threading.Thread( name=self.thread_name, target=self._RunLoop) self.running_thread.daemon = True self.running_thread.start() return self.running_thre...
Returns True if there's a currently running iteration of this job. def IsRunning(self): """Returns True if there's a currently running iteration of this job.""" current_urn = self.Get(self.Schema.CURRENT_FLOW_URN) if not current_urn: return False try: current_flow = aff4.FACTORY.Open( ...
Called periodically by the cron daemon, if True Run() will be called. Returns: True if it is time to run based on the specified frequency. def DueToRun(self): """Called periodically by the cron daemon, if True Run() will be called. Returns: True if it is time to run based on the specified...
Disable cron flow if it has exceeded CRON_ARGS.lifetime. Returns: bool: True if the flow is was killed. def KillOldFlows(self): """Disable cron flow if it has exceeded CRON_ARGS.lifetime. Returns: bool: True if the flow is was killed. """ if not self.IsRunning(): return False ...
Do the actual work of the Cron. Will first check if DueToRun is True. CronJob object must be locked (i.e. opened via OpenWithLock) for Run() to be called. Args: force: If True, the job will run no matter what (i.e. even if DueToRun() returns False). Raises: LockError: if the ...
Main CronHook method. def RunOnce(self): """Main CronHook method.""" # Start the cron thread if configured to. if config.CONFIG["Cron.active"]: self.cron_worker = CronWorker() self.cron_worker.RunAsync()
Launch a fingerprint client action. def FingerprintFile(self, pathspec, max_filesize=None, request_data=None): """Launch a fingerprint client action.""" request = rdf_client_action.FingerprintRequest(pathspec=pathspec) if max_filesize is not None: request.max_filesize = max_filesize # Generic ha...
Store the fingerprint response. def ProcessFingerprint(self, responses): """Store the fingerprint response.""" if not responses.success: # Its better to raise rather than merely logging since it will make it to # the flow's protobuf and users can inspect the reason this flow failed. raise flo...
Clean out compiled protos. def Clean(): """Clean out compiled protos.""" # Find all the compiled proto files and unlink them. for (root, _, files) in os.walk(ROOT): for filename in files: full_filename = os.path.join(root, filename) if full_filename.endswith("_pb2.py") or full_filename.endswith( ...
Make sure our protos have been compiled to python libraries. def MakeProto(): """Make sure our protos have been compiled to python libraries.""" # Start running from one directory above the grr directory which is found by # this scripts's location as __file__. cwd = os.path.dirname(os.path.abspath(__file__)) ...
Reset the lexer to process a new data feed. def Reset(self): """Reset the lexer to process a new data feed.""" # The first state self.state = "INITIAL" self.state_stack = [] # The buffer we are parsing now self.buffer = "" self.error = 0 self.verbose = 0 # The index into the buffe...
Fetch the next token by trying to match any of the regexes in order. def NextToken(self): """Fetch the next token by trying to match any of the regexes in order.""" # Nothing in the input stream - no token can match. if not self.buffer: return current_state = self.state for token in self._to...
Push the current state on the state stack. def PushState(self, **_): """Push the current state on the state stack.""" if self.verbose: logging.debug("Storing state %r", self.state) self.state_stack.append(self.state)
Pop the previous state from the stack. def PopState(self, **_): """Pop the previous state from the stack.""" try: self.state = self.state_stack.pop() if self.verbose: logging.debug("Returned state to %s", self.state) return self.state except IndexError: self.Error("Tried to...
Push the match back on the stream. def PushBack(self, string="", **_): """Push the match back on the stream.""" precondition.AssertType(string, Text) self.buffer = string + self.buffer self.processed_buffer = self.processed_buffer[:-len(string)]
Adds a new arg to this expression. Args: arg: The argument to add (string). Returns: True if this arg is the last arg, False otherwise. Raises: ParseError: If there are too many args. def AddArg(self, arg): """Adds a new arg to this expression. Args: arg: The argument ...
Escape backslashes found inside a string quote. Backslashes followed by anything other than ['"rnbt] will just be included in the string. Args: string: The string that matched. match: The match object (m.group(1) is the escaped code) def StringEscape(self, string, match, **_): """Escape...
Insert an arg to the current expression. def InsertArg(self, string="", **_): """Insert an arg to the current expression.""" if self.verbose: logging.debug("Storing Argument %s", utils.SmartUnicode(string)) # This expression is complete if self.current_expression.AddArg(string): self.stack...
Creates a new hunt. Args: flow_name: String with a name of a flow that will run on all the clients in the hunt. flow_args: Flow arguments to be used. A proto, that depends on a flow. hunt_runner_args: flows_pb2.HuntRunnerArgs instance. Used to specify description, client_rule_set, output_...
List all GRR hunts. def ListHunts(context=None): """List all GRR hunts.""" items = context.SendIteratorRequest("ListHunts", hunt_pb2.ApiListHuntsArgs()) return utils.MapItemsIterator(lambda data: Hunt(data=data, context=context), items)
List all hunt approvals belonging to requesting user. def ListHuntApprovals(context=None): """List all hunt approvals belonging to requesting user.""" items = context.SendIteratorRequest("ListHuntApprovals", hunt_pb2.ApiListHuntApprovalsArgs()) def MapHuntApproval(data): ...
Fetch and return a proper HuntApproval object. def Get(self): """Fetch and return a proper HuntApproval object.""" args = user_pb2.ApiGetHuntApprovalArgs( hunt_id=self.hunt_id, approval_id=self.approval_id, username=self.username) result = self._context.SendRequest("GetHuntApproval...
Wait until the approval is valid (i.e. - approved). Args: timeout: timeout in seconds. None means default timeout (1 hour). 0 means no timeout (wait forever). Returns: Operation object with refreshed target_file. Raises: PollTimeoutError: if timeout is reached. def WaitUnt...
Returns a reference to an approval. def Approval(self, username, approval_id): """Returns a reference to an approval.""" return HuntApprovalRef( hunt_id=self.hunt_id, username=username, approval_id=approval_id, context=self._context)
Create a new approval for the current user to access this hunt. def CreateApproval(self, reason=None, notified_users=None, email_cc_addresses=None): """Create a new approval for the current user to access this hunt.""" if not reason: raise V...
Modifies a number of hunt arguments. def Modify(self, client_limit=None, client_rate=None, duration=None): """Modifies a number of hunt arguments.""" args = hunt_pb2.ApiModifyHuntArgs(hunt_id=self.hunt_id) if client_limit is not None: args.client_limit = client_limit if client_rate is not None:...
Fetch hunt's data and return proper Hunt object. def Get(self): """Fetch hunt's data and return proper Hunt object.""" args = hunt_pb2.ApiGetHuntArgs(hunt_id=self.hunt_id) data = self._context.SendRequest("GetHunt", args) return Hunt(data=data, context=self._context)
Repeat connection attempts to server until we get a valid connection. def _MakeConnection(self, database=""): """Repeat connection attempts to server until we get a valid connection.""" first_attempt_time = time.time() wait_time = config.CONFIG["Mysql.max_connect_wait"] while wait_time == 0 or time.tim...
Attempt to cleanly drop the connection. def DropConnection(self, connection): """Attempt to cleanly drop the connection.""" try: connection.cursor.close() except MySQLdb.Error: pass try: connection.dbh.close() except MySQLdb.Error: pass
Drop all existing tables. def DropTables(self): """Drop all existing tables.""" rows, _ = self.ExecuteQuery( "SELECT table_name FROM information_schema.tables " "WHERE table_schema='%s'" % self.database_name) for row in rows: self.ExecuteQuery("DROP TABLE `%s`" % row["table_name"])
Remove some attributes from a subject. def DeleteAttributes(self, subject, attributes, start=None, end=None, sync=True): """Remove some attributes from a subject.""" _ = sync # Unused if not ...
Resolves multiple attributes at once for one subject. def ResolveMulti(self, subject, attributes, timestamp=None, limit=None): """Resolves multiple attributes at once for one subject.""" for attribute in attributes: query, args = self._BuildQuery(subject, attribute, timestamp, limit) result, _ = se...
Result multiple subjects using one or more attribute regexps. def MultiResolvePrefix(self, subjects, attribute_prefix, timestamp=None, limit=None): """Result multiple subjects using one or more attribute regexps."""...
ResolvePrefix. def ResolvePrefix(self, subject, attribute_prefix, timestamp=None, limit=None): """ResolvePrefix.""" if isinstance(attribute_prefix, string_types): attribute_prefix = [attribute_prefix] results = [] for prefix in attribute_prefix: query, args = self._Bui...