INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
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_urls"]: result.append(posixpath.dir...
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 system. result.extend(config.CON...
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...
def OpenServerEndpoint(self, path, verify_cb=lambda x: True, data=None, params=None, headers=None, method="GET", timeout=None): """Search thr...
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...
def OpenURL(self, url, verify_cb=lambda x: True, data=None, params=None, headers=None, method="GET", timeout=None): """Get the requested URL. Note that we do not have any concept of timing here - we try to connect...
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...
def _RetryRequest(self, timeout=None, **request_args): """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 thi...
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.heart_beat_cb()
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 slowly at first and fast if no answer. ...
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...
def SendReply(self, rdf_value=None, request_id=None, response_id=None, session_id="W:0", message_type=None, name=None, require_fastpoll=None, ttl=None, blocking=True, ...
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 delivered from the server. Raises: RuntimeError: The client action requested was not found. """ self._is_active = True try: action_cls = actions.ActionPlugin.class...
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., timeout)) timeout -= 1 # If the ...
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. last_request = self.transaction_log.Ge...
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.HandleMessage(message) # Catch a...
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. ...
def Put(self, message, block=True, timeout=1000): """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. ...
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: ...
def GetMessages(self, soft_size_limit=None): """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 messa...
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...
def VerifyServerPEM(self, http_object): """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 ...
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...
def VerifyServerControlResponse(self, http_object): """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 pro...
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 response is as it should be from the control endpoint. respo...
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. if not self._FetchServerCertificate(): self.timer.Wait() return HTTPObject(code=500) # Here we onl...
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.http_manager.OpenServerEndpoint( "server.pem", verify_cb=self.VerifySer...
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 have been more than connection_error_limit failures, the method returns and allows the client to exit. """ while True: if self.http_manager.ErrorLimitReached(): return #...
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 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. """ logging.debug("sending enrollment request") ...
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 InitPrivateKey(self): """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 o...
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.VerificationError as e: self.server_nam...
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...
def ClaimNotificationsForCollection(cls, token=None, start_time=None, lease_time=200, collection=None): """Return unclaimed hunt result notifications for collection...
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...
def ChunkTable(table, max_chunk_size): """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 serialize...
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.OsqueryTable` instance. """ precondition.AssertIterableType(table, dict) result = rdf_osquery.OsqueryTable() result.header = ParseHeader(table) for ...
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_osquery.OsqueryHeader` instance. """ precondition.AssertIterableType(table, dict) prototype = None # type: List[Text] for row in table: columns = list...
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 parsed header describing the row format. row: A row in a "parsed JSON" representation. Returns: A parsed `rdf_osquery.OsqueryRow` instance. """ precondition.AssertDictType(row, Text, Text) result...
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...
def Query(args): """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. E...
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.DomainEmailAddress): address_list = [str(address_list)] elif ...
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 ...
def SendEmail(self, to_addresses, from_address, subject, message, attachments=None, is_html=True, cc_addresses=None, message_id=None, headers=None): """This method sends an...
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: cls = registry.AFF4FlowRegistry.Flo...
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 legacy_name: raise ValueError("legacy_name has to be provided") ...
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...
def CreateJob(self, cron_args=None, job_id=None, token=None, enabled=True): """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...
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_job.Close()
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 True, force a run names: List of job names to run. If unset, run them all """ names = names or self.ListJobs(token=token) urns = [self.CRON_JOBS_PATH....
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 = list(job.ListChildren(age=cutoff_timestamp)) with queue_manager.Qu...
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_thread
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( urn=current_urn, aff4_type=flow.GRRFlow, token=self.token, mod...
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 frequency. """ if self.Get(self.Schema.DISABLED): return False cron_args = self.Get(self.Schema.CRON_ARGS) last_run_time = self.G...
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 start_time = self.Get(self.Schema.LAST_RUN_TIME) lifetime = self.Get(self.Schema.CRON_ARGS).lifetime ela...
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 ...
def Run(self, force=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). ...
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 hash. request.AddRequest( f...
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 flow.FlowError("Could not fingerprin...
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( "_pb2.pyc"): ...
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__)) # Find all the .proto files. protos_to_compile = [] for ...
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 buffer where we are currently pointing self.pr...
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._tokens: # Does the rule apply to us? if token.state_regex an...
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 pop the state but failed - possible rec...
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 to add (string). Returns: True if this arg is the last arg, False otherwise. Raises: ParseError: If there are too many args. """ self.args.append(arg) if len(self.args) > self.number_of...
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 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) """...
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.append(self.current_expression) sel...
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_...
def CreateHunt(flow_name=None, flow_args=None, hunt_runner_args=None, context=None): """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 de...
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): return HuntApproval(data=data, username=context.usern...
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", args) return HuntApproval( data=r...
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 WaitUntilValid(self, timeout=None): """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: PollTi...
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 ValueError("reason can't be empty") if not notified_users: ...
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: args.client_rate = client_rate ...
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.time() - first_attempt_time < wait_time: try: connection_arg...
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 attributes: return if isinsta...
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, _ = self.ExecuteQuery(query, args) for row in result: ...
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.""" result = {} for subject in subjects: values = s...
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._BuildQuery( ...
Set multiple attributes' values for this subject in one operation.
def MultiSet(self, subject, values, timestamp=None, replace=True, sync=True, to_delete=None): """Set multiple attributes' values for this subject in one operation.""" to_delete = set(to_delete or []) # Prepare a bulk ...
Get connection from pool and execute query.
def ExecuteQuery(self, query, args=None): """Get connection from pool and execute query.""" def Action(connection): connection.cursor.execute(query, args) rowcount = connection.cursor.rowcount results = connection.cursor.fetchall() return results, rowcount return self._RetryWrapper...
Get connection from pool and execute transaction.
def _ExecuteTransaction(self, transaction): """Get connection from pool and execute transaction.""" def Action(connection): connection.cursor.execute("START TRANSACTION") for query in transaction: connection.cursor.execute(query["query"], query["args"]) connection.cursor.execute("COMM...
Build a mapping between column names and types.
def _CalculateAttributeStorageTypes(self): """Build a mapping between column names and types.""" self.attribute_types = {} for attribute in itervalues(aff4.Attribute.PREDICATES): self.attribute_types[attribute.predicate] = ( attribute.attribute_type.data_store_type)
Encode the value for the attribute.
def _Encode(self, value): """Encode the value for the attribute.""" try: return value.SerializeToString().encode("hex") except AttributeError: if isinstance(value, (int, long)): return str(value).encode("hex") else: # Types "string" and "bytes" are stored as strings here. ...
Build the SELECT query to be executed.
def _BuildQuery(self, subject, attribute=None, timestamp=None, limit=None, is_prefix=False): """Build the SELECT query to be executed.""" args = [] subject = utils.SmartUnicode(subject) criteria = "WHERE aff4.subje...
Build the DELETE query to be executed.
def _BuildDelete(self, subject, attribute=None, timestamp=None): """Build the DELETE query to be executed.""" subjects_q = { "query": "DELETE subjects FROM subjects WHERE hash=unhex(md5(%s))", "args": [subject] } aff4_q = { "query": "DELETE aff4 FROM aff4 WHERE subject_hash=unhe...
Create a timestamp using a start and end time. Args: start: Start timestamp. end: End timestamp. Returns: A tuple (start, end) of converted timestamps or None for all time.
def _MakeTimestamp(self, start=None, end=None): """Create a timestamp using a start and end time. Args: start: Start timestamp. end: End timestamp. Returns: A tuple (start, end) of converted timestamps or None for all time. """ mysql_unsigned_bigint_max = 18446744073709551615 ...
Remove the lock. Note that this only resets the lock if we actually hold it since lock_expiration == self.expires and lock_owner = self.lock_token.
def Release(self): """Remove the lock. Note that this only resets the lock if we actually hold it since lock_expiration == self.expires and lock_owner = self.lock_token. """ if self.locked: query = ("UPDATE locks SET lock_expiration=0, lock_owner=0 " "WHERE lock_expiration=%s "...
Finds objects associated with keywords. Find the names related to all keywords. Args: keywords: A collection of keywords that we are interested in. start_time: Only considers keywords added at or after this point in time. end_time: Only considers keywords at or before this point in time. ...
def Lookup(self, keywords, start_time=FIRST_TIMESTAMP, end_time=LAST_TIMESTAMP, last_seen_map=None): """Finds objects associated with keywords. Find the names related to all keywords. Args: keywords: A collection of keywords that we are interested ...
Finds all objects associated with any of the keywords. Args: keywords: A collection of keywords that we are interested in. start_time: Only considers keywords added at or after this point in time. end_time: Only considers keywords at or before this point in time. last_seen_map: If present, ...
def ReadPostingLists(self, keywords, start_time=FIRST_TIMESTAMP, end_time=LAST_TIMESTAMP, last_seen_map=None): """Finds all objects associated with any of the keywords. Args: keywords: A collection of keywords tha...
Associates keywords with name. Records that keywords are associated with name. Args: name: A name which should be associated with some keywords. keywords: A collection of keywords to associate with name.
def AddKeywordsForName(self, name, keywords): """Associates keywords with name. Records that keywords are associated with name. Args: name: A name which should be associated with some keywords. keywords: A collection of keywords to associate with name. """ data_store.DB.IndexAddKeyword...
Removes keywords for a name. Args: name: A name which should not be associated with some keywords anymore. keywords: A collection of keywords.
def RemoveKeywordsForName(self, name, keywords): """Removes keywords for a name. Args: name: A name which should not be associated with some keywords anymore. keywords: A collection of keywords. """ data_store.DB.IndexRemoveKeywordsForName(self.urn, name, keywords)
Reads an old config file and imports keys and user accounts.
def ImportConfig(filename, config): """Reads an old config file and imports keys and user accounts.""" sections_to_import = ["PrivateKeys"] entries_to_import = [ "Client.executable_signing_public_key", "CA.certificate", "Frontend.certificate" ] options_imported = 0 old_config = grr_config.CONFIG...
Continually ask a question until the output_re is matched.
def RetryQuestion(question_text, output_re="", default_val=None): """Continually ask a question until the output_re is matched.""" while True: if default_val is not None: new_text = "%s [%s]: " % (question_text, default_val) else: new_text = "%s: " % question_text # pytype: disable=wrong-arg...
This configures the hostnames stored in the config.
def ConfigureHostnames(config, external_hostname = None): """This configures the hostnames stored in the config.""" if not external_hostname: try: external_hostname = socket.gethostname() except (OSError, IOError): print("Sorry, we couldn't guess your hostname.\n") external_hostname = Retry...
Checks whether a connection can be established to MySQL. Args: db_options: A dict mapping GRR MySQL config options to their values. Returns: A boolean indicating whether a connection could be made to a MySQL server instance with the given options.
def CheckMySQLConnection(db_options): """Checks whether a connection can be established to MySQL. Args: db_options: A dict mapping GRR MySQL config options to their values. Returns: A boolean indicating whether a connection could be made to a MySQL server instance with the given options. """ for...
Prompts the user for configuration details for a MySQL datastore.
def ConfigureMySQLDatastore(config): """Prompts the user for configuration details for a MySQL datastore.""" print("GRR will use MySQL as its database backend. Enter connection details:") datastore_init_complete = False db_options = {} while not datastore_init_complete: db_options["Datastore.implementatio...
Guides the user through configuration of the datastore.
def ConfigureDatastore(config): """Guides the user through configuration of the datastore.""" print("\n\n-=GRR Datastore=-\n" "For GRR to work each GRR server has to be able to communicate with\n" "the datastore. To do this we need to configure a datastore.\n") existing_datastore = grr_config.CON...
Guides the user through configuration of various URLs used by GRR.
def ConfigureUrls(config, external_hostname = None): """Guides the user through configuration of various URLs used by GRR.""" print("\n\n-=GRR URLs=-\n" "For GRR to work each client has to be able to communicate with the\n" "server. To do this we normally need a public dns name or IP address\n" ...
Guides the user through email setup.
def ConfigureEmails(config): """Guides the user through email setup.""" print("\n\n-=GRR Emails=-\n" "GRR needs to be able to send emails for various logging and\n" "alerting functions. The email domain will be appended to GRR\n" "usernames when sending emails to users.\n") existing_log_d...