INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Lists all registered GRR users.
def ListGrrUsers(self): """Lists all registered GRR users.""" args = user_management_pb2.ApiListGrrUsersArgs() items = self._context.SendIteratorRequest("ListGrrUsers", args) return utils.MapItemsIterator( lambda data: GrrUser(data=data, context=self._context), items)
Return all audit log entries between now-offset and now. Args: offset: rdfvalue.Duration how far back to look in time now: rdfvalue.RDFDatetime for current time token: GRR access token Yields: AuditEvents created during the time range
def GetAuditLogEntries(offset, now, token): """Return all audit log entries between now-offset and now. Args: offset: rdfvalue.Duration how far back to look in time now: rdfvalue.RDFDatetime for current time token: GRR access token Yields: AuditEvents created during the time range """ start_t...
Fetches client data from the relational db. Args: recency_window: An rdfvalue.Duration specifying a window of last-ping timestamps to consider. Clients that haven't communicated with GRR servers longer than the given period will be skipped. If recency_window is None, all clients will be iterate...
def _IterateAllClients(recency_window=None): """Fetches client data from the relational db. Args: recency_window: An rdfvalue.Duration specifying a window of last-ping timestamps to consider. Clients that haven't communicated with GRR servers longer than the given period will be skipped. If recency...
Adds another instance of this category into the active_days counter. We automatically count the event towards all relevant active_days. For example, if the category "Windows" was seen 8 days ago it will be counted towards the 30 day active, 14 day active but not against the 7 and 1 day actives. Ar...
def Add(self, category, label, age): """Adds another instance of this category into the active_days counter. We automatically count the event towards all relevant active_days. For example, if the category "Windows" was seen 8 days ago it will be counted towards the 30 day active, 14 day active but not ...
Generate a histogram object and store in the specified attribute.
def Save(self, token=None): """Generate a histogram object and store in the specified attribute.""" graph_series_by_label = {} for active_time in self.active_days: for label in self.categories[active_time]: graphs_for_label = graph_series_by_label.setdefault( label, rdf_stats.Clien...
Retrieve all the clients for the AbstractClientStatsCollectors.
def Run(self): """Retrieve all the clients for the AbstractClientStatsCollectors.""" try: self.stats = {} self.BeginProcessing() processed_count = 0 for client_info_batch in _IterateAllClients( recency_window=self.recency_window): for client_info in client_info_batc...
Retrieve all the clients for the AbstractClientStatsCollectors.
def Start(self): """Retrieve all the clients for the AbstractClientStatsCollectors.""" try: self.stats = {} self.BeginProcessing() processed_count = 0 if data_store.RelationalDBEnabled(): for client_info_batch in _IterateAllClients( recency_window=self.recency_win...
Update counters for system, version and release attributes.
def ProcessLegacyClient(self, ping, client): """Update counters for system, version and release attributes.""" labels = self._GetClientLabelsList(client) system = client.Get(client.Schema.SYSTEM, "Unknown") uname = client.Get(client.Schema.UNAME, "Unknown") self._Process(labels, ping, system, uname...
Starts an interrogation hunt on all available clients.
def StartInterrogationHunt(self): """Starts an interrogation hunt on all available clients.""" flow_name = compatibility.GetName(flows_discovery.Interrogate) flow_args = flows_discovery.InterrogateArgs(lightweight=False) description = "Interrogate run by cron to keep host info fresh." if data_store...
Does the work.
def ProcessClients(self, responses): """Does the work.""" del responses end = rdfvalue.RDFDatetime.Now() - db.CLIENT_STATS_RETENTION client_urns = export_utils.GetAllClients(token=self.token) for batch in collection.Batch(client_urns, 10000): with data_store.DB.GetMutationPool() as mutation_...
Checks if requester and approvers have approval privileges for labels. Checks against list of approvers for each label defined in approvers.yaml to determine if the list of approvers is sufficient. Args: token: user token client_urn: ClientURN object of the client requester: username str...
def CheckApproversForLabel(self, token, client_urn, requester, approvers, label): """Checks if requester and approvers have approval privileges for labels. Checks against list of approvers for each label defined in approvers.yaml to determine if the list of approvers is suffici...
Checks that the directory exists and has the correct permissions set.
def EnsureTempDirIsSane(directory): """Checks that the directory exists and has the correct permissions set.""" if not os.path.isabs(directory): raise ErrorBadPath("Directory %s is not absolute" % directory) if os.path.isdir(directory): # The temp dir already exists, we probably created it already but ...
Open file with GRR prefix in directory to allow easy deletion. Missing parent dirs will be created. If an existing directory is specified its permissions won't be modified to avoid breaking system functionality. Permissions on the destination file will be set to root/SYSTEM rw. On windows the file is created,...
def CreateGRRTempFile(filename=None, lifetime=0, mode="w+b", suffix=""): """Open file with GRR prefix in directory to allow easy deletion. Missing parent dirs will be created. If an existing directory is specified its permissions won't be modified to avoid breaking system functionality. Permissions on the dest...
Creates a GRR VFS temp file. This function is analogous to CreateGRRTempFile but returns an open VFS handle to the newly created file. Arguments are the same as for CreateGRRTempFile: Args: filename: The name of the file to use. Note that setting both filename and directory name is not allowed. ...
def CreateGRRTempFileVFS(filename=None, lifetime=0, mode="w+b", suffix=""): """Creates a GRR VFS temp file. This function is analogous to CreateGRRTempFile but returns an open VFS handle to the newly created file. Arguments are the same as for CreateGRRTempFile: Args: filename: The name of the file to use...
Checks if given path is valid for deletion.
def _CheckIfPathIsValidForDeletion(path, prefix=None, directories=None): """Checks if given path is valid for deletion.""" precondition.AssertType(path, Text) precondition.AssertType(prefix, Text) if prefix and os.path.basename(path).startswith(prefix): return True path = path.lower() for directory in...
Delete a GRR temp file. To limit possible damage the path must be absolute and either the file must be within any of the Client.tempdir_roots or the file name must begin with Client.tempfile_prefix. Args: path: path string to file to be deleted. Raises: OSError: Permission denied, or file not found...
def DeleteGRRTempFile(path): """Delete a GRR temp file. To limit possible damage the path must be absolute and either the file must be within any of the Client.tempdir_roots or the file name must begin with Client.tempfile_prefix. Args: path: path string to file to be deleted. Raises: OSError: Pe...
Delete all the GRR temp files in path. If path is a directory, look in the top level for filenames beginning with Client.tempfile_prefix, and delete them. If path is a regular file and starts with Client.tempfile_prefix delete it. Args: args: pathspec pointing to directory containing temp files...
def Run(self, args): """Delete all the GRR temp files in path. If path is a directory, look in the top level for filenames beginning with Client.tempfile_prefix, and delete them. If path is a regular file and starts with Client.tempfile_prefix delete it. Args: args: pathspec pointing to dir...
Issue a request to list the directory.
def Start(self): """Issue a request to list the directory.""" self.CallClient( server_stubs.PlistQuery, request=self.args.request, next_state="Receive")
Returns JSON format mode corresponding to a given request and method.
def GetRequestFormatMode(request, method_metadata): """Returns JSON format mode corresponding to a given request and method.""" if request.path.startswith("/api/v2/"): return JsonMode.PROTO3_JSON_MODE if request.args.get("strip_type_info", ""): return JsonMode.GRR_TYPE_STRIPPED_JSON_MODE for http_meth...
Renders HTTP response to a given HTTP request.
def RenderHttpResponse(request): """Renders HTTP response to a given HTTP request.""" start_time = time.time() response = HTTP_REQUEST_HANDLER.HandleRequest(request) total_time = time.time() - start_time method_name = response.headers.get("X-API-Method", "unknown") if response.status_code == 200: stat...
Builds a werkzeug routing map out of a given router class.
def _BuildHttpRoutingMap(self, router_cls): """Builds a werkzeug routing map out of a given router class.""" if not issubclass(router_cls, api_call_router.ApiCallRouter): raise ValueError("Router has to be an instance of ApiCallRouter.") routing_map = routing.Map() # Note: we traverse methods of...
Returns a routing map for a given router instance.
def _GetRoutingMap(self, router): """Returns a routing map for a given router instance.""" try: routing_map = self._routing_maps_cache.Get(router.__class__) except KeyError: routing_map = self._BuildHttpRoutingMap(router.__class__) self._routing_maps_cache.Put(router.__class__, routing_ma...
Sets fields on the arg rdfvalue object.
def _SetField(self, args, type_info, value): """Sets fields on the arg rdfvalue object.""" if hasattr(type_info, "enum"): try: coerced_obj = type_info.enum[value.upper()] except KeyError: # A bool is an enum but serializes to "1" / "0" which are both not in # enum or reverse_...
Builds args struct out of HTTP request.
def _GetArgsFromRequest(self, request, method_metadata, route_args): """Builds args struct out of HTTP request.""" format_mode = GetRequestFormatMode(request, method_metadata) if request.method in ["GET", "HEAD"]: if method_metadata.args_type: unprocessed_request = request.args if has...
Returns a router for a given HTTP request.
def MatchRouter(self, request): """Returns a router for a given HTTP request.""" router = api_auth_manager.API_AUTH_MGR.GetRouterForUser(request.user) routing_map = self._GetRoutingMap(router) matcher = routing_map.bind( "%s:%s" % (request.environ["SERVER_NAME"], request.environ["SERVER...
Build an ACLToken from the request.
def BuildToken(request, execution_time): """Build an ACLToken from the request.""" # The request.args dictionary will also be filled on HEAD calls. if request.method in ["GET", "HEAD"]: reason = request.args.get("reason", "") elif request.method in ["POST", "DELETE", "PATCH"]: # The header ...
Handles API call to a given handler with given args and token.
def CallApiHandler(handler, args, token=None): """Handles API call to a given handler with given args and token.""" result = handler.Handle(args, token=token) expected_type = handler.result_type if expected_type is None: expected_type = None.__class__ if result.__class__ != expected_type: ...
Builds HTTPResponse object from rendered data and HTTP status.
def _BuildResponse(self, status, rendered_data, method_name=None, headers=None, content_length=None, token=None, no_audit_log=False): """Builds HTTPResponse object from ...
Builds HTTPResponse object for streaming.
def _BuildStreamingResponse(self, binary_stream, method_name=None): """Builds HTTPResponse object for streaming.""" precondition.AssertType(method_name, Text) # We get a first chunk of the output stream. This way the likelihood # of catching an exception that may happen during response generation #...
Handles given HTTP request.
def HandleRequest(self, request): """Handles given HTTP request.""" impersonated_username = config.CONFIG["AdminUI.debug_impersonate_user"] if impersonated_username: logging.info("Overriding user as %s", impersonated_username) request.user = config.CONFIG["AdminUI.debug_impersonate_user"] i...
Returns the provided token or the default token. Args: token: A token or None. Raises: access_control.UnauthorizedAccess: no token was provided.
def GetDefaultToken(token): """Returns the provided token or the default token. Args: token: A token or None. Raises: access_control.UnauthorizedAccess: no token was provided. """ if token is None: token = default_token if not isinstance(token, access_control.ACLToken): raise access_contr...
Flushing actually applies all the operations in the pool.
def Flush(self): """Flushing actually applies all the operations in the pool.""" DB.DeleteSubjects(self.delete_subject_requests, sync=False) for req in self.delete_attributes_requests: subject, attributes, start, end = req DB.DeleteAttributes(subject, attributes, start=start, end=end, sync=Fals...
Claims records from a queue. See server/aff4_objects/queue.py.
def QueueClaimRecords(self, queue_id, item_rdf_type, limit=10000, timeout="30m", start_time=None, record_filter=lambda x: False, max_filtered=1000): ...
Removes the given tasks from the queue.
def QueueDeleteTasks(self, queue, tasks): """Removes the given tasks from the queue.""" predicates = [] for task in tasks: task_id = getattr(task, "task_id", None) or int(task) predicates.append(DataStore.QueueTaskIdToColumn(task_id)) self.DeleteAttributes(queue, predicates)
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. timestamp: Range of times for consideration. Returns: A list of GrrMessage() objects leased.
def QueueQueryAndOwn(self, queue, lease_seconds, limit, timestamp): """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. timestamp: Range of times for consider...
Business logic helper for QueueQueryAndOwn().
def _QueueQueryAndOwn(self, subject, lease_seconds=100, limit=1, timestamp=None): """Business logic helper for QueueQueryAndOwn().""" tasks = [] lease = int(lease_seconds * 1e6) # Only grab attributes with ...
Adds a child to the specified parent.
def AFF4AddChild(self, subject, child, extra_attributes=None): """Adds a child to the specified parent.""" precondition.AssertType(child, Text) attributes = { DataStore.AFF4_INDEX_DIR_TEMPLATE % child: [DataStore.EMPTY_DATA_PLACEHOLDER] } if extra_attributes: attributes.update...
Start the thread that registers the size of the DataStore.
def InitializeMonitorThread(self): """Start the thread that registers the size of the DataStore.""" if self.monitor_thread: return self.monitor_thread = utils.InterruptableThread( name="DataStore monitoring thread", target=self._RegisterSize, sleep_time=60) self.monitor_thr...
Delete multiple subjects at once.
def DeleteSubjects(self, subjects, sync=False): """Delete multiple subjects at once.""" for subject in subjects: self.DeleteSubject(subject, sync=sync)
Retry a DBSubjectLock until it succeeds. Args: subject: The subject which the lock applies to. retrywrap_timeout: How long to wait before retrying the lock. retrywrap_max_timeout: The maximum time to wait for a retry until we raise. blocking: If False, raise on first lock failure. ...
def LockRetryWrapper(self, subject, retrywrap_timeout=1, retrywrap_max_timeout=10, blocking=True, lease_time=None): """Retry a DBSubjectLock until it succeeds. Args: subject: The subject whi...
Set multiple attributes' values for this subject in one operation. Args: subject: The subject this applies to. values: A dict with keys containing attributes and values, serializations to be set. values can be a tuple of (value, timestamp). Value must be one of the supported types. ...
def MultiSet(self, subject, values, timestamp=None, replace=True, sync=True, to_delete=None): """Set multiple attributes' values for this subject in one operation. Args: subject: The subject this applies to. v...
Remove all specified attributes from a list of subjects. Args: subjects: The list of subjects that will have these attributes removed. attributes: A list of attributes. start: A timestamp, attributes older than start will not be deleted. end: A timestamp, attributes newer than end will not ...
def MultiDeleteAttributes(self, subjects, attributes, start=None, end=None, sync=True): """Remove all specified attributes from a list of subjects. Args: subjects: T...
Retrieve a value set for a subject's attribute. This method is easy to use but always gets the latest version of the attribute. It is more flexible and efficient to use the other Resolve methods. Args: subject: The subject URN. attribute: The attribute. Returns: A (value, timest...
def Resolve(self, subject, attribute): """Retrieve a value set for a subject's attribute. This method is easy to use but always gets the latest version of the attribute. It is more flexible and efficient to use the other Resolve methods. Args: subject: The subject URN. attribute: The a...
Retrieve a set of value matching for this subject's attribute. Args: subject: The subject that we will search. attribute_prefix: The attribute prefix. timestamp: A range of times for consideration (In microseconds). Can be a constant such as ALL_TIMESTAMPS or NEWEST_TIMESTAMP or a tuple o...
def ResolvePrefix(self, subject, attribute_prefix, timestamp=None, limit=None): """Retrieve a set of value matching for this subject's attribute. Args: subject: The subject that we will search. attribute_prefix: The attribute prefix. timestamp: A range of times for conside...
Fetches all Requests and Responses for a given session_id.
def ReadRequestsAndResponses(self, session_id, timestamp=None, request_limit=None, response_limit=None): """Fetches all Requests and Responses for a given session_id.""" subject = session_...
Fetches all the requests with a status message queued for them.
def ReadCompletedRequests(self, session_id, timestamp=None, limit=None): """Fetches all the requests with a status message queued for them.""" subject = session_id.Add("state") requests = {} status = {} for predicate, serialized, _ in self.ResolvePrefix( subject, [self.FLOW_REQUEST_PREFIX, ...
Reads responses for one request. Args: session_id: The session id to use. request_id: The id of the request. timestamp: A timestamp as used in the data store. Yields: fetched responses for the request
def ReadResponsesForRequestId(self, session_id, request_id, timestamp=None): """Reads responses for one request. Args: session_id: The session id to use. request_id: The id of the request. timestamp: A timestamp as used in the data store. Yields: fetched responses for the request ...
Reads responses for multiple requests at the same time. Args: request_list: The list of requests the responses should be fetched for. timestamp: A timestamp as used in the data store. Yields: tuples (request, lists of fetched responses for the request)
def ReadResponses(self, request_list, timestamp=None): """Reads responses for multiple requests at the same time. Args: request_list: The list of requests the responses should be fetched for. timestamp: A timestamp as used in the data store. Yields: tuples (request, lists of fetched resp...
Stores new flow requests and responses to the data store. Args: new_requests: A list of tuples (request, timestamp) to store in the data store. new_responses: A list of tuples (response, timestamp) to store in the data store. requests_to_delete: A list of requests that should be d...
def StoreRequestsAndResponses(self, new_requests=None, new_responses=None, requests_to_delete=None): """Stores new flow requests and responses to the data store. Args: new_requests: A list of tuples (request, ...
Checks if there is a status message queued for a number of requests.
def CheckRequestsForCompletion(self, requests): """Checks if there is a status message queued for a number of requests.""" subjects = [r.session_id.Add("state") for r in requests] statuses_found = {} for subject, result in self.MultiResolvePrefix(subjects, ...
Deletes all requests and responses for the given flows. Args: session_ids: A lists of flows to destroy. request_limit: A limit on the number of requests to delete. Returns: A list of requests that were deleted.
def MultiDestroyFlowStates(self, session_ids, request_limit=None): """Deletes all requests and responses for the given flows. Args: session_ids: A lists of flows to destroy. request_limit: A limit on the number of requests to delete. Returns: A list of requests that were deleted. """...
Finds all objects associated with any of the keywords. Args: index_urn: The base urn of the index. 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 poin...
def IndexReadPostingLists(self, index_urn, keywords, start_time, end_time, last_seen_map=None): """Finds all objects associated with any of the keywords. Args: index...
Reads all index entries for the given collection. Args: collection_id: ID of the collection for which the indexes should be retrieved. Yields: Tuples (index, ts, suffix).
def CollectionReadIndex(self, collection_id): """Reads all index entries for the given collection. Args: collection_id: ID of the collection for which the indexes should be retrieved. Yields: Tuples (index, ts, suffix). """ for (attr, value, ts) in self.ResolvePrefix(c...
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. Ret...
def QueueQueryTasks(self, queue, limit=1): """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...
Search the index for matches starting with target_prefix. Args: subject: The index to use. Should be a urn that points to the sha256 namespace. target_prefix: The prefix to match against the index. limit: Either a tuple of (start, limit) or a maximum number of results to retu...
def FileHashIndexQuery(self, subject, target_prefix, limit=100): """Search the index for matches starting with target_prefix. Args: subject: The index to use. Should be a urn that points to the sha256 namespace. target_prefix: The prefix to match against the index. limit: Either a...
Initialize the data_store.
def Run(self): """Initialize the data_store.""" global DB # pylint: disable=global-statement global REL_DB # pylint: disable=global-statement global BLOBS # pylint: disable=global-statement if flags.FLAGS.list_storage: self._ListStorageOptions() sys.exit(0) try: cls = Data...
Download an aff4 file to the local filesystem overwriting it if it exists. Args: file_obj: An aff4 object that supports the file interface (Read, Seek) target_path: Full path of file to write to. buffer_size: Read in chunks this size.
def DownloadFile(file_obj, target_path, buffer_size=BUFFER_SIZE): """Download an aff4 file to the local filesystem overwriting it if it exists. Args: file_obj: An aff4 object that supports the file interface (Read, Seek) target_path: Full path of file to write to. buffer_size: Read in chunks this size....
Recursively downloads a file entry to the target path. Args: dir_obj: An aff4 object that contains children. target_dir: Full path of the directory to write to. max_depth: Depth to download to. 1 means just the directory itself. depth: Current depth of recursion. overwrite: Should we overwrite fi...
def RecursiveDownload(dir_obj, target_dir, max_depth=10, depth=1, overwrite=False, max_threads=10): """Recursively downloads a file entry to the target path. Args: dir_obj: An aff4 object that contains...
Tries to open various types of collections at the given path.
def _OpenCollectionPath(coll_path): """Tries to open various types of collections at the given path.""" hunt_collection = results.HuntResultCollection(coll_path) if hunt_collection and hunt_collection[0].payload: return hunt_collection indexed_collection = sequential_collection.GeneralIndexedCollection(col...
Iterate through a Collection object downloading all files. Args: coll_path: Path to an AFF4 collection. target_path: Base directory to write to. token: Token for access. overwrite: If True, overwrite existing files. dump_client_info: If True, this will detect client paths, and dump a yaml v...
def DownloadCollection(coll_path, target_path, token=None, overwrite=False, dump_client_info=False, flatten=False, max_threads=10): """Iterate through a Collection object downloadi...
Copy an AFF4 object that supports a read interface to local filesystem. Args: aff4_urn: URN of thing to copy. target_dir: Directory to copy the file to. token: Auth token. overwrite: If True overwrite the file if it exists. Returns: If aff4_urn points to a file, returns path to the downloaded ...
def CopyAFF4ToLocal(aff4_urn, target_dir, token=None, overwrite=False): """Copy an AFF4 object that supports a read interface to local filesystem. Args: aff4_urn: URN of thing to copy. target_dir: Directory to copy the file to. token: Auth token. overwrite: If True overwrite the file if it exists. ...
Dump a yaml file containing client info.
def DumpClientYaml(client_urn, target_dir, token=None, overwrite=False): """Dump a yaml file containing client info.""" fd = aff4.FACTORY.Open(client_urn, aff4_grr.VFSGRRClient, token=token) dirpath = os.path.join(target_dir, fd.urn.Split()[0]) try: # Due to threading this can actually be created by another...
Yield client urns.
def GetInput(self): """Yield client urns.""" clients = GetAllClients(token=self.token) logging.debug("Got %d clients", len(clients)) return clients
Run the iteration.
def Run(self): """Run the iteration.""" count = 0 for count, input_data in enumerate(self.GetInput()): if count % 2000 == 0: logging.debug("%d processed.", count) args = (input_data, self.out_queue, self.token) self.thread_pool.AddTask( target=self.IterFunction, args=args...
Yield client urns.
def GetInput(self): """Yield client urns.""" client_list = GetAllClients(token=self.token) logging.debug("Got %d clients", len(client_list)) for client_group in collection.Batch(client_list, self.client_chunksize): for fd in aff4.FACTORY.MultiOpen( client_group, mode="r", ...
Interpolate all knowledgebase attributes in pattern. Args: pattern: A string with potential interpolation markers. For example: "/home/%%users.username%%/Downloads/" knowledge_base: The knowledge_base to interpolate parameters from. ignore_errors: Set this to true to log errors instead of raising. ...
def InterpolateKbAttributes(pattern, knowledge_base, ignore_errors=False): """Interpolate all knowledgebase attributes in pattern. Args: pattern: A string with potential interpolation markers. For example: "/home/%%users.username%%/Downloads/" knowledge_base: The knowledge_base to interpolate paramet...
Return a dictionary of environment variables and their values. Implementation maps variables mentioned in https://en.wikipedia.org/wiki/Environment_variable#Windows to known KB definitions. Args: knowledge_base: A knowledgebase object. Returns: A dictionary built from a given knowledgebase object w...
def GetWindowsEnvironmentVariablesMap(knowledge_base): """Return a dictionary of environment variables and their values. Implementation maps variables mentioned in https://en.wikipedia.org/wiki/Environment_variable#Windows to known KB definitions. Args: knowledge_base: A knowledgebase object. Returns...
r"""Take a string and expand any windows environment variables. Args: data_string: A string, e.g. "%SystemRoot%\\LogFiles" knowledge_base: A knowledgebase object. Returns: A string with available environment variables expanded. If we can't expand we just return the string with the original variabl...
def ExpandWindowsEnvironmentVariables(data_string, knowledge_base): r"""Take a string and expand any windows environment variables. Args: data_string: A string, e.g. "%SystemRoot%\\LogFiles" knowledge_base: A knowledgebase object. Returns: A string with available environment variables expanded. If w...
Check if a condition matches an object. Args: condition: A string condition e.g. "os == 'Windows'" check_object: Object to validate, e.g. an rdf_client.KnowledgeBase() Returns: True or False depending on whether the condition matches. Raises: ConditionError: If condition is bad.
def CheckCondition(condition, check_object): """Check if a condition matches an object. Args: condition: A string condition e.g. "os == 'Windows'" check_object: Object to validate, e.g. an rdf_client.KnowledgeBase() Returns: True or False depending on whether the condition matches. Raises: Co...
r"""Take a string and expand windows user environment variables based. Args: data_string: A string, e.g. "%TEMP%\\LogFiles" knowledge_base: A knowledgebase object. sid: A Windows SID for a user to expand for. username: A Windows user name to expand for. Returns: A string with available environ...
def ExpandWindowsUserEnvironmentVariables(data_string, knowledge_base, sid=None, username=None): r"""Take a string and expand windows user environment variables based. Args: data_string...
Fetches extended file attributes. Args: filepath: A path to the file. Yields: `ExtAttr` pairs.
def GetExtAttrs(filepath): """Fetches extended file attributes. Args: filepath: A path to the file. Yields: `ExtAttr` pairs. """ path = CanonicalPathToLocalPath(filepath) try: attr_names = xattr.listxattr(path) except (IOError, OSError, UnicodeDecodeError) as error: msg = "Failed to ret...
Sleep a given time in 1 second intervals. When a machine is suspended during a time.sleep(n) call for more than n seconds, sometimes the sleep is interrupted and all threads wake up at the same time. This leads to race conditions between the threads issuing the heartbeat and the one checking for it. By...
def Sleep(self, seconds): """Sleep a given time in 1 second intervals. When a machine is suspended during a time.sleep(n) call for more than n seconds, sometimes the sleep is interrupted and all threads wake up at the same time. This leads to race conditions between the threads issuing the heartbea...
Write the message into the transaction log.
def Write(self, grr_message): """Write the message into the transaction log.""" grr_message = grr_message.SerializeToString() try: with io.open(self.logfile, "wb") as fd: fd.write(grr_message) except (IOError, OSError): # Check if we're missing directories and try to create them. ...
Wipes the transaction log.
def Clear(self): """Wipes the transaction log.""" try: with io.open(self.logfile, "wb") as fd: fd.write(b"") except (IOError, OSError): pass
Return a GrrMessage instance from the transaction log or None.
def Get(self): """Return a GrrMessage instance from the transaction log or None.""" try: with io.open(self.logfile, "rb") as fd: data = fd.read(self.max_log_size) except (IOError, OSError): return try: if data: return rdf_flows.GrrMessage.FromSerializedString(data) ...
Remove a specific symbol from a fn_table.
def FilterFnTable(fn_table, symbol): """Remove a specific symbol from a fn_table.""" new_table = list() for entry in fn_table: # symbol[0] is a str with the symbol name if entry[0] != symbol: new_table.append(entry) return new_table
Set function argument types and return types for an ObjC library. Args: libname: Library name string fn_table: List of (function, [arg types], return types) tuples Returns: ctypes.CDLL with types set according to fn_table Raises: ErrorLibNotFound: Can't find specified lib
def SetCTypesForLibrary(libname, fn_table): """Set function argument types and return types for an ObjC library. Args: libname: Library name string fn_table: List of (function, [arg types], return types) tuples Returns: ctypes.CDLL with types set according to fn_table Raises: ErrorLibNotFound: ...
Package a CoreFoundation object in a Python wrapper. Args: obj: The CoreFoundation object. Returns: One of CFBoolean, CFNumber, CFString, CFDictionary, CFArray. Raises: TypeError: If the type is not supported.
def WrapCFTypeInPython(self, obj): """Package a CoreFoundation object in a Python wrapper. Args: obj: The CoreFoundation object. Returns: One of CFBoolean, CFNumber, CFString, CFDictionary, CFArray. Raises: TypeError: If the type is not supported. """ obj_type = self.dll.CFGet...
Copy all Job Dictionaries from the ServiceManagement. Args: domain: The name of a constant in Foundation referencing the domain. Will copy all launchd services by default. Returns: A marshalled python list of dicts containing the job dictionaries.
def SMGetJobDictionaries(self, domain='kSMDomainSystemLaunchd'): """Copy all Job Dictionaries from the ServiceManagement. Args: domain: The name of a constant in Foundation referencing the domain. Will copy all launchd services by default. Returns: A marshalled python list of dic...
Returns dictionary values or default. Args: key: string. Dictionary key to look up. default: string. Return this value if key not found. stringify: bool. Force all return values to string for compatibility reasons. Returns: python-wrapped CF object or default if not fou...
def get(self, key, default='', stringify=True): """Returns dictionary values or default. Args: key: string. Dictionary key to look up. default: string. Return this value if key not found. stringify: bool. Force all return values to string for compatibility reasons. Return...
Load the kextmanager, replacing unavailable symbols.
def SafeLoadKextManager(self, fn_table): """Load the kextmanager, replacing unavailable symbols.""" dll = None try: dll = SetCTypesForLibrary('IOKit', fn_table) except AttributeError as ae: if 'KextManagerUnloadKextWithIdentifier' in str(ae): # Try without this symbol, as it is not a...
Load a kext by forking into kextload.
def LegacyKextload(self, cf_bundle_url, dependency_kext): """Load a kext by forking into kextload.""" _ = dependency_kext error_code = OS_SUCCESS cf_path = self.dll.CFURLCopyFileSystemPath(cf_bundle_url, POSIX_PATH_STYLE) path = self.CFStringToPystring(cf_path) self.dll.CFRelease(cf_path) tr...
Unload a kext by forking into kextunload.
def LegacyKextunload(self, cf_bundle_identifier): """Unload a kext by forking into kextunload.""" error_code = OS_SUCCESS bundle_identifier = self.CFStringToPystring(cf_bundle_identifier) try: subprocess.check_call(['/sbin/kextunload', '-b', bundle_identifier]) except subprocess.CalledProcessE...
Retrieves a path info record for a given path.
def ReadPathInfo(self, client_id, path_type, components, timestamp=None, cursor=None): """Retrieves a path info record for a given path.""" if timestamp is None: path_infos = self.ReadPathInfos(client_id, path_t...
Retrieves path info records for given paths.
def ReadPathInfos(self, client_id, path_type, components_list, cursor=None): """Retrieves path info records for given paths.""" if not components_list: return {} path_ids = list(map(rdf_objects.PathID.FromComponents, components_list)) path_infos = {components: None for components in components_...
Writes a collection of path_info records for a client.
def WritePathInfos(self, client_id, path_infos): """Writes a collection of path_info records for a client.""" try: self._MultiWritePathInfos({client_id: path_infos}) except MySQLdb.IntegrityError as error: raise db.UnknownClientError(client_id=client_id, cause=error)
Writes a collection of path info records for specified clients.
def MultiWritePathInfos(self, path_infos): """Writes a collection of path info records for specified clients.""" try: self._MultiWritePathInfos(path_infos) except MySQLdb.IntegrityError as error: client_ids = list(iterkeys(path_infos)) raise db.AtLeastOneUnknownClientError(client_ids=clien...
Writes a collection of path info records for specified clients.
def _MultiWritePathInfos(self, path_infos, connection=None): """Writes a collection of path info records for specified clients.""" query = "" path_info_count = 0 path_info_values = [] parent_path_info_count = 0 parent_path_info_values = [] has_stat_entries = False has_hash_entries = F...
Lists path info records that correspond to descendants of given path.
def ListDescendentPathInfos(self, client_id, path_type, components, timestamp=None, max_depth=None, cursor=None): """Lists path info rec...
Reads a collection of hash and stat entries for given paths.
def ReadPathInfosHistories(self, client_id, path_type, components_list, cursor=None): """Reads a collection of hash and stat entries for given paths.""" # MySQL does not handle well empty `IN` cla...
Enumerate all interfaces and collect their MAC addresses.
def EnumerateInterfacesFromClient(args): """Enumerate all interfaces and collect their MAC addresses.""" del args # Unused libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) ifa = Ifaddrs() p_ifa = ctypes.pointer(ifa) libc.getifaddrs(ctypes.pointer(p_ifa)) addresses = {} macs = {} ifs = ...
Enumerates all the users on this system.
def EnumerateUsersFromClient(args): """Enumerates all the users on this system.""" del args # Unused users = _ParseWtmp() for user, last_login in iteritems(users): # Lose the null termination username, _ = user.split(b"\x00", 1) username = username.decode("utf-8") if username: # Someh...
Parses the currently mounted devices.
def CheckMounts(filename): """Parses the currently mounted devices.""" with io.open(filename, "r") as fd: for line in fd: try: device, mnt_point, fs_type, _ = line.split(" ", 3) except ValueError: continue if fs_type in ACCEPTABLE_FILESYSTEMS: if os.path.exists(device):...
List all the filesystems mounted on the system.
def EnumerateFilesystemsFromClient(args): """List all the filesystems mounted on the system.""" del args # Unused. filenames = ["/proc/mounts", "/etc/mtab"] for filename in filenames: for device, fs_type, mnt_point in CheckMounts(filename): yield rdf_client_fs.Filesystem( mount_point=mnt_...
Parse wtmp and utmp and extract the last logon time.
def _ParseWtmp(): """Parse wtmp and utmp and extract the last logon time.""" users = {} wtmp_struct_size = UtmpStruct.GetSize() filenames = glob.glob("/var/log/wtmp*") + ["/var/run/utmp"] for filename in filenames: try: wtmp = open(filename, "rb").read() except IOError: continue for...
Client update for rpm based distros. Upgrading rpms is a bit more tricky than upgrading deb packages since there is a preinstall script that kills the running GRR daemon and, thus, also the installer process. We need to make sure we detach the child process properly and therefore cannot use client_util...
def _InstallRpm(self, path): """Client update for rpm based distros. Upgrading rpms is a bit more tricky than upgrading deb packages since there is a preinstall script that kills the running GRR daemon and, thus, also the installer process. We need to make sure we detach the child process properly ...
Returns a default root path for storing temporary files.
def _TempRootPath(): """Returns a default root path for storing temporary files.""" # `FLAGS.test_tmpdir` is defined only in test environment, so we can't expect # for it to be always defined. test_tmpdir = ( compatibility.Environ("TEST_TMPDIR", default=None) or FLAGS.get_flag_value("test_tmpdir", d...
Creates a temporary directory based on the environment configuration. The directory will be placed in folder as specified by the `TEST_TMPDIR` environment variable if available or fallback to `Test.tmpdir` of the current configuration if not. Args: suffix: A suffix to end the directory name with. pref...
def TempDirPath(suffix = "", prefix = "tmp"): """Creates a temporary directory based on the environment configuration. The directory will be placed in folder as specified by the `TEST_TMPDIR` environment variable if available or fallback to `Test.tmpdir` of the current configuration if not. Args: suffix...
Creates a temporary file based on the environment configuration. If no directory is specified the file will be placed in folder as specified by the `TEST_TMPDIR` environment variable if available or fallback to `Test.tmpdir` of the current configuration if not. If directory is specified it must be part of the...
def TempFilePath(suffix = "", prefix = "tmp", dir = None): # pylint: disable=redefined-builtin """Creates a temporary file based on the environment configuration. If no directory is specified the file will be placed in folder as specified by the `TEST_TMPDIR` environment variable if available o...
Return the best available name for this volume.
def Name(self): """Return the best available name for this volume.""" return (self.name or self.device_path or self.windowsvolume.drive_letter or self.unixvolume.mount_point or None)