text
stringlengths
81
112k
Check all queued up hashes for existence in file store. Hashes which do not exist in the file store will be downloaded. This function flushes the entire queue (self.state.pending_hashes) in order to minimize the round trips to the file store. If a file was found in the file store it is not scheduled f...
Adds the block hash to the file tracker responsible for this vfs URN. def CheckHash(self, responses): """Adds the block hash to the file tracker responsible for this vfs URN.""" index = responses.request_data["index"] if index not in self.state.pending_files: # This is a blobhash for a file we alrea...
Fetch as much as the file's content as possible. This drains the pending_files store by checking which blobs we already have in the store and issuing calls to the client to receive outstanding blobs. def FetchFileContent(self): """Fetch as much as the file's content as possible. This drains the pendi...
Write the hash received to the blob image. def WriteBuffer(self, responses): """Write the hash received to the blob image.""" index = responses.request_data["index"] if index not in self.state.pending_files: return # Failed to read the file - ignore it. if not responses.success: self....
Process the new file and add to the file store. def ProcessMessages(self, msgs=None, token=None): """Process the new file and add to the file store.""" if not data_store.AFF4Enabled(): return filestore_fd = aff4.FACTORY.Create( legacy_filestore.FileStore.PATH, legacy_filestore.FileSt...
Create the hunt, in the paused state. def Start(self): """Create the hunt, in the paused state.""" # Anyone can create the hunt but it will be created in the paused # state. Permissions are required to actually start it. with implementation.StartHunt( runner_args=self.args.hunt_runner_args, ...
Stores the responses. def StoreResults(self, responses): """Stores the responses.""" client_id = responses.request.client_id if responses.success: logging.info("Client %s has a file %s.", client_id, self.args.filename) else: logging.info("Client %s has no file %s.", client_id, self.args.fi...
Returns the session IDs of all the flows we launched. Args: flow_type: The type of flows to fetch. Can be "all", "outstanding" or "finished". Returns: A list of flow URNs. def GetLaunchedFlows(self, flow_type="outstanding"): """Returns the session IDs of all the flows we launched. ...
Mark a client as done. def MarkDone(self, responses): """Mark a client as done.""" client_id = responses.request.client_id self.AddResultsToCollection(responses, client_id) self.MarkClientDone(client_id)
Schedule all flows without using the Foreman. Since we know all the client ids to run on we might as well just schedule all the flows and wait for the results. Args: token: A datastore access token. def ManuallyScheduleClients(self, token=None): """Schedule all flows without using the Foreman. ...
Test to see if we're on a cloud machine. def IsCloud(self, request, bios_version, services): """Test to see if we're on a cloud machine.""" if request.bios_version_regex and bios_version: if re.match(request.bios_version_regex, bios_version): return True if request.service_name_regex and serv...
Get metadata from local metadata server. Any failed URL check will fail the whole action since our bios/service checks may not always correctly identify cloud machines. We don't want to wait on multiple DNS timeouts. Args: request: CloudMetadataRequest object Returns: rdf_cloud.CloudMe...
Try and give a 'stat' for something not in the data store. Args: fd: The object with no stat. Returns: A dictionary corresponding to what we'll say the 'stat' is for objects which are not actually files, so have no OS level stat. def MakePartialStat(self, fd): """Try and give a 'stat' f...
Reads a directory given by path. Args: path: The path to list children of. fh: A file handler. Not used. Yields: A generator of filenames. Raises: FuseOSError: If we try and list a file. def Readdir(self, path, fh=None): """Reads a directory given by path. Args: pa...
Performs a stat on a file or directory. Args: path: The path to stat. fh: A file handler. Not used. Returns: A dictionary mapping st_ names to their values. Raises: FuseOSError: When a path is supplied that grr doesn't know about, ie an invalid file path. ValueError: I...
Reads data from a file. Args: path: The path to the file to read. length: How many bytes to read. offset: Offset in bytes from which reading should start. fh: A file handler. Not used. Returns: A string containing the file contents requested. Raises: FuseOSError: If we...
True if we need to update this path from the client. Args: path: The path relative to the root to check freshness of. last: An aff4:last attribute to check freshness of. At least one of path or last must be supplied. Returns: True if the path hasn't been updated in the last self...
Runs a flow on the client, and waits for it to finish. def _RunAndWaitForVFSFileUpdate(self, path): """Runs a flow on the client, and waits for it to finish.""" client_id = rdf_client.GetClientURNFromPath(path) # If we're not actually in a directory on a client, no need to run a flow. if client_id is...
Updates the directory listing from the client. Args: path: The path to the directory to update. Client is inferred from this. fh: A file handler. Not used. Returns: A list of filenames. def Readdir(self, path, fh=None): """Updates the directory listing from the client. Args: ...
Return which chunks a file doesn't have. Specifically, we return a list of the chunks specified by a length-offset range which are not in the datastore. Args: fd: The database object to read chunks from. length: Length to read. offset: File offset to read from. Returns: A list...
This reads the OSX system configuration and gets the proxies. def FindProxies(): """This reads the OSX system configuration and gets the proxies.""" sc = objc.SystemConfiguration() # Get the dictionary of network proxy settings settings = sc.dll.SCDynamicStoreCopyProxies(None) if not settings: return [...
List all the filesystems mounted on the system. def GetMountpoints(): """List all the filesystems mounted on the system.""" devices = {} for filesys in GetFileSystems(): devices[filesys.f_mntonname] = (filesys.f_mntfromname, filesys.f_fstypename) return devices
Make syscalls to get the mounted filesystems. Returns: A list of Struct objects. Based on the information for getfsstat http://developer.apple.com/library/mac/#documentation/Darwin/ Reference/ManPages/man2/getfsstat.2.html def GetFileSystems(): """Make syscalls to get the mounted filesystems. ...
Take the struct type and parse it into a list of structs. def ParseFileSystemsStruct(struct_class, fs_count, data): """Take the struct type and parse it into a list of structs.""" results = [] cstr = lambda x: x.split(b"\x00", 1)[0] for count in range(0, fs_count): struct_size = struct_class.GetSize() ...
Resolve the raw device that contains the path. def GetRawDevice(path): """Resolve the raw device that contains the path.""" device_map = GetMountpoints() path = utils.SmartUnicode(path) mount_point = path = utils.NormalizePath(path, "/") result = rdf_paths.PathSpec(pathtype=rdf_paths.PathSpec.PathType.OS) ...
Calls into the IOKit to load a kext by file-system path. Apple kext API doco here: http://developer.apple.com/library/mac/#documentation/IOKit/Reference/ KextManager_header_reference/Reference/reference.html Args: kext_path: Absolute or relative POSIX path to the kext. Raises: OSError: On fai...
Calls into the IOKit to unload a kext by its name. Args: bundle_name: The bundle identifier of the kernel extension as defined in Info.plist field CFBundleIdentifier. Returns: The error code from the library call. objc.OS_SUCCESS if successfull. def UninstallDriver(bundle_name): """Call...
Validates a sequence of path infos. def _ValidatePathInfos(path_infos): """Validates a sequence of path infos.""" precondition.AssertIterableType(path_infos, rdf_objects.PathInfo) validated = set() for path_info in path_infos: _ValidatePathInfo(path_info) path_key = (path_info.path_type, path_info.Ge...
Parses a timerange argument and always returns non-None timerange. def _ValidateTimeRange(timerange): """Parses a timerange argument and always returns non-None timerange.""" if len(timerange) != 2: raise ValueError("Timerange should be a sequence with 2 items.") (start, end) = timerange precondition.Asse...
Checks that a time-range has both start and end timestamps set. def _ValidateClosedTimeRange(time_range): """Checks that a time-range has both start and end timestamps set.""" time_range_start, time_range_end = time_range _ValidateTimestamp(time_range_start) _ValidateTimestamp(time_range_end) if time_range_s...
Write metadata about the client. Updates one or more client metadata fields for the given client_id. Any of the data fields can be left as None, and in this case are not changed. Args: client_id: A GRR client id string, e.g. "C.ea3b2b71840d6fa7". certificate: If set, should be an rdfvalues.cry...
Reads the ClientMetadata record for a single client. Args: client_id: A GRR client id string, e.g. "C.ea3b2b71840d6fa7". Returns: An rdfvalues.object.ClientMetadata object. Raises: UnknownClientError: if no client with corresponding id was found. def ReadClientMetadata(self, client_id)...
Reads full client information for a single client. Args: client_id: A GRR client id string, e.g. "C.ea3b2b71840d6fa7". Returns: A `ClientFullInfo` instance for given client. Raises: UnknownClientError: if no client with such id was found. def ReadClientFullInfo(self, client_id): ""...
Iterates over all available clients and yields full info protobufs. Args: min_last_ping: If not None, only the clients with last-ping timestamps newer than (or equal to) min_last_ping will be returned. batch_size: Always reads <batch_size> client full infos at a time. Yields: An rdfv...
Iterates over all available clients and yields client snapshot objects. Args: min_last_ping: If provided, only snapshots for clients with last-ping timestamps newer than (or equal to) the given value will be returned. batch_size: Always reads <batch_size> snapshots at a time. Yields: ...
Lists path info records that correspond to children of given path. Args: client_id: An identifier string for a client. path_type: A type of a path to retrieve path information for. components: A tuple of path components of a path to retrieve child path information for. timestamp: If...
Initializes a collection of path info records for a client. Unlike `WritePathInfo`, this method clears stat and hash histories of paths associated with path info records. This method is intended to be used only in the data migration scripts. Args: client_id: A client identifier for which the pat...
Writes a collection of `StatEntry` observed for particular path. Args: client_path: A `ClientPath` instance. stat_entries: A dictionary with timestamps as keys and `StatEntry` instances as values. def WritePathStatHistory(self, client_path, stat_entries): """Writes a collection of `StatEnt...
Writes a collection of `Hash` observed for particular path. Args: client_path: A `ClientPath` instance. hash_entries: A dictionary with timestamps as keys and `Hash` instances as values. def WritePathHashHistory(self, client_path, hash_entries): """Writes a collection of `Hash` observed fo...
Reads a collection of hash and stat entry for given path. Args: client_id: An identifier string for a client. path_type: A type of a path to retrieve path history for. components: A tuple of path components corresponding to path to retrieve information for. Returns: A list of `...
Updates run information for an existing cron job. Args: cronjob_id: The id of the cron job to update. last_run_status: A CronJobRunStatus object. last_run_time: The last time a run was started for this cron job. current_run_id: The id of the currently active run. state: The state dict...
Updates flow objects in the database. Args: client_id: The client id on which this flow is running. flow_id: The id of the flow to update. flow_obj: An updated rdf_flow_objects.Flow object. flow_state: An update rdf_flow_objects.Flow.FlowState value. client_crash_info: A rdf_client.Cl...
Updates the hunt object by applying the update function. Each keyword argument when set to None, means that that corresponding value shouldn't be updated. Args: hunt_id: Id of the hunt to be updated. duration: A maximum allowed running time duration of the flow. client_rate: Number corre...
Updates the hunt object by applying the update function. def UpdateHuntObject(self, hunt_id, duration=None, client_rate=None, client_limit=None, hunt_state=None, hunt_state_comment=...
Processes the tasks. def ProcessTask(self, target, args, name, queueing_time): """Processes the tasks.""" if self.pool.name: time_in_queue = time.time() - queueing_time stats_collector_instance.Get().RecordEvent( _QUEUEING_TIME_METRIC, time_in_queue, fields=[self.pool.name]) start...
Remove ourselves from the pool. Returns: True if removal was possible, and False if it was not possible. def _RemoveFromPool(self): """Remove ourselves from the pool. Returns: True if removal was possible, and False if it was not possible. """ with self.pool.lock: # Pool is shu...
This overrides the Thread.run method. This method checks in an endless loop if new tasks are available in the queue and processes them. def run(self): """This overrides the Thread.run method. This method checks in an endless loop if new tasks are available in the queue and processes them. """...
Creates a new thread pool with the given name. If the thread pool of this name already exist, we just return the existing one. This allows us to have different pools with different characteristics used by different parts of the code, at the same time. Args: name: The name of the required pool. ...
This starts the worker threads. def Start(self): """This starts the worker threads.""" if not self.started: self.started = True for _ in range(self.min_threads): self._AddWorker()
This stops all the worker threads. def Stop(self, join_timeout=600): """This stops all the worker threads.""" if not self.started: logging.warning("Tried to stop a thread pool that was not running.") return # Remove all workers from the pool. workers = list(itervalues(self._workers)) s...
Adds a task to be processed later. Args: target: A callable which should be processed by one of the workers. args: A tuple of arguments to target. name: The name of this task. Used to identify tasks in the log. blocking: If True we block until the task is finished, otherwise we raise ...
Waits until all outstanding tasks are completed. def Join(self): """Waits until all outstanding tasks are completed.""" for _ in range(self.JOIN_TIMEOUT_DECISECONDS): if self._queue.empty() and not self.busy_threads: return time.sleep(0.1) raise ValueError("Timeout during Join() for t...
Converts given collection to exported values. This method uses a threadpool to do the conversion in parallel. It blocks for up to one hour until everything is converted. Args: values: Iterable object with values to convert. start_index: Start from this index in the collection. end_index:...
Spawns a process. def SpawnProcess(popen_args, passwd=None): """Spawns a process.""" if passwd is not None: # We send the password via pipe to avoid creating a process with the # password as an argument that will get logged on some systems. p = subprocess.Popen(popen_args, stdin=subprocess.PIPE) p....
Write client config to filename. def GetClientConfig(filename): """Write client config to filename.""" config_lib.SetPlatformArchContext() config_lib.ParseConfigCommandLine() context = list(grr_config.CONFIG.context) context.append("Client Context") deployer = build.ClientRepacker() # Disable timestampin...
Launch the appropriate builder. def main(args): """Launch the appropriate builder.""" grr_config.CONFIG.AddContext(contexts.CLIENT_BUILD_CONTEXT) if args.subparser_name == "generate_client_config": # We don't need a full init to just build a config. GetClientConfig(args.client_config_output) return...
Get instance of builder class based on flags. def GetBuilder(self, context, fleetspeak_service_config): """Get instance of builder class based on flags.""" try: if "Target:Darwin" in context: return builders.DarwinClientBuilder( context=context, fleetspeak_service_config=f...
Find template builder and call it. def BuildTemplate(self, context=None, output=None, fleetspeak_service_config=None): """Find template builder and call it.""" context = context or [] context.append("Arch:%s" % self.GetArch()) # Platform conte...
Add the repack config filename onto the base output directory. This allows us to repack lots of different configs to the same installer name and still be able to distinguish them. Args: base_dir: output directory string config_filename: the secondary config filename string Returns: ...
Call repacker in a subprocess. def RepackTemplates(self, repack_configs, templates, output_dir, config=None, sign=False, signed_template=False): """Call repacker in a subprocess.""" ...
Run all startup routines for the client. def ClientInit(): """Run all startup routines for the client.""" metric_metadata = client_metrics.GetMetadata() metric_metadata.extend(communicator.GetMetricMetadata()) stats_collector_instance.Set( default_stats_collector.DefaultStatsCollector(metric_metadata)) ...
Parse the sysctl output. def Parse(self, cmd, args, stdout, stderr, return_val, time_taken, knowledge_base): """Parse the sysctl output.""" _ = stderr, time_taken, args, knowledge_base # Unused. self.CheckReturn(cmd, return_val) result = rdf_protodict.AttributedDict() # The KeyValuePar...
Parse the key currentcontrolset output. def Parse(self, stat, unused_knowledge_base): """Parse the key currentcontrolset output.""" value = stat.registry_data.GetValue() if not str(value).isdigit() or int(value) > 999 or int(value) < 0: raise parser.ParseError( "Invalid value for CurrentCo...
Expand any variables in the value. def Parse(self, stat, knowledge_base): """Expand any variables in the value.""" value = stat.registry_data.GetValue() if not value: raise parser.ParseError("Invalid value for key %s" % stat.pathspec.path) value = artifact_utils.ExpandWindowsEnvironmentVariables(...
Parses a SystemDrive environment variable. def Parse(self, stat, _): """Parses a SystemDrive environment variable.""" if isinstance(stat, rdf_client_fs.StatEntry): value = stat.registry_data.GetValue() elif isinstance(stat, rdfvalue.RDFString): value = stat if not value: raise parser....
Parse each returned registry value. def Parse(self, stat, knowledge_base): """Parse each returned registry value.""" _ = knowledge_base # Unused. sid_str = stat.pathspec.Dirname().Basename() if SID_RE.match(sid_str): kb_user = rdf_client.User() kb_user.sid = sid_str if stat.pathspec...
Parse each returned registry value. def ParseMultiple(self, stats, knowledge_base): """Parse each returned registry value.""" user_dict = {} for stat in stats: sid_str = stat.pathspec.path.split("/", 3)[2] if SID_RE.match(sid_str): if sid_str not in user_dict: user_dict[sid_s...
Parse Service registry keys and return WindowsServiceInformation. def ParseMultiple(self, stats, knowledge_base): """Parse Service registry keys and return WindowsServiceInformation.""" _ = knowledge_base services = {} field_map = { "Description": "description", "DisplayName": "display_...
Convert the timezone to Olson format. def Parse(self, stat, knowledge_base): """Convert the timezone to Olson format.""" _ = knowledge_base value = stat.registry_data.GetValue() result = ZONE_LIST.get(value.strip()) if not result: yield rdfvalue.RDFString("Unknown (%s)" % value.strip()) ...
Converts a generator with approval rows into ApprovalRequest objects. def _ResponseToApprovalsWithGrants(response): """Converts a generator with approval rows into ApprovalRequest objects.""" prev_triplet = None cur_approval_request = None for (approval_id_int, approval_timestamp, approval_request_bytes, ...
Writes user object for a user with a given name. def WriteGRRUser(self, username, password=None, ui_mode=None, canary_mode=None, user_type=None, cursor=None): """Writes user object for a user with a gi...
Creates a GRR user object from a database result row. def _RowToGRRUser(self, row): """Creates a GRR user object from a database result row.""" username, password, ui_mode, canary_mode, user_type = row result = rdf_objects.GRRUser( username=username, ui_mode=ui_mode, canary_mode=can...
Reads a user object corresponding to a given name. def ReadGRRUser(self, username, cursor=None): """Reads a user object corresponding to a given name.""" cursor.execute( "SELECT username, password, ui_mode, canary_mode, user_type " "FROM grr_users WHERE username_hash = %s", [mysql_utils.Hash(us...
Reads GRR users with optional pagination, sorted by username. def ReadGRRUsers(self, offset=0, count=None, cursor=None): """Reads GRR users with optional pagination, sorted by username.""" if count is None: count = 18446744073709551615 # 2^64-1, as suggested by MySQL docs cursor.execute( "S...
Deletes the user and all related metadata with the given username. def DeleteGRRUser(self, username, cursor=None): """Deletes the user and all related metadata with the given username.""" cursor.execute("DELETE FROM grr_users WHERE username_hash = %s", (mysql_utils.Hash(username),)) if ...
Writes an approval request object. def WriteApprovalRequest(self, approval_request, cursor=None): """Writes an approval request object.""" # Copy the approval_request to ensure we don't modify the source object. approval_request = approval_request.Copy() # Generate random approval id. approval_id_i...
Grants approval for a given request. def _GrantApproval(self, requestor_username, approval_id, grantor_username, cursor): """Grants approval for a given request.""" grant_args = { "username_hash": mysql_utils.Hash(requestor_username), "approval_id": approval_id, "gr...
Grants approval for a given request using given username. def GrantApproval(self, requestor_username, approval_id, grantor_username, cursor=None): """Grants approval for a given request using given username.""" self._GrantApproval(...
Reads an approval request object with a given id. def ReadApprovalRequest(self, requestor_username, approval_id, cursor=None): """Reads an approval request object with a given id.""" query = (""" SELECT ar.approval_id, UNIX_TIMESTAMP(ar.timestamp), ar.approval_reque...
Reads approval requests of a given type for a given user. def ReadApprovalRequests(self, requestor_username, approval_type, subject_id=None, include_expired=False, cursor=None): ""...
Writes a notification for a given user. def WriteUserNotification(self, notification, cursor=None): """Writes a notification for a given user.""" # Copy the notification to ensure we don't modify the source object. args = { "username_hash": mysql_utils.Hash(notification.username), ...
Reads notifications scheduled for a user within a given timerange. def ReadUserNotifications(self, username, state=None, timerange=None, cursor=None): """Reads notifications scheduled for a user within a...
Updates existing user notification objects. def UpdateUserNotifications(self, username, timestamps, state=None, cursor=None): """Updates existing user notification objects.""" query = ("UPDA...
Splits strings into space-separated components. The difference between SplitIntoComponents and .split(" ") is that the former tries to respect single and double quotes and strip them using lexical rules typically used in command line interpreters. Args: str_in: Source string to be split into components. ...
Detects paths in a given string. Args: str_in: String where the paths should be detected. Returns: A list of paths (as strings) detected inside the given string. def Detect(self, str_in): """Detects paths in a given string. Args: str_in: String where the paths should be detected. ...
Register all known vfs handlers to open a pathspec types. def Init(): """Register all known vfs handlers to open a pathspec types.""" VFS_HANDLERS.clear() _VFS_VIRTUALROOTS.clear() vfs_virtualroots = config.CONFIG["Client.vfs_virtualroots"] VFS_HANDLERS[files.File.supported_pathtype] = files.File VFS_HAND...
Expands pathspec to return an expanded Path. A pathspec is a specification of how to access the file by recursively opening each part of the path by different drivers. For example the following pathspec: pathtype: OS path: "/dev/sda1" nested_path { pathtype: TSK path: "/home/image2.img" nested...
Opens multiple files specified by given path-specs. See documentation for `VFSOpen` for more information. Args: pathspecs: A list of pathspec instances of files to open. progress_callback: A callback function to call to notify about progress Returns: A context manager yielding file-like objects. d...
Read from the VFS and return the contents. Args: pathspec: path to read from offset: number of bytes to skip length: number of bytes to read progress_callback: A callback to indicate that the open call is still working but needs more time. Returns: VFS file contents def ReadVFS(pathspec...
Writes a single row to the underlying buffer. Args: values: A list of string values to be inserted into the CSV output. def WriteRow(self, values): """Writes a single row to the underlying buffer. Args: values: A list of string values to be inserted into the CSV output. """ preconditi...
Writes a single row to the underlying buffer. Args: values: A dictionary mapping column names to values to be inserted into the CSV output. def WriteRow(self, values): """Writes a single row to the underlying buffer. Args: values: A dictionary mapping column names to values to be inse...
Returns True if the last run failed. def _IsCronJobFailing(self, cron_job): """Returns True if the last run failed.""" status = cron_job.Get(cron_job.Schema.LAST_RUN_STATUS) if status is None: return False return status.status != rdf_cronjobs.CronJobRunStatus.Status.OK
Shortcut method for easy legacy cron jobs support. def InitFromApiFlow(self, f, cron_job_id=None): """Shortcut method for easy legacy cron jobs support.""" if f.flow_id: self.run_id = f.flow_id elif f.urn: self.run_id = f.urn.Basename() self.started_at = f.started_at self.cron_job_id = ...
Parses a timerange argument and always returns non-None timerange. def _ParseTimeRange(self, timerange): """Parses a timerange argument and always returns non-None timerange.""" if timerange is None: timerange = (None, None) from_time, to_time = timerange if not from_time: from_time = rdfv...
Creates an object copy by serializing/deserializing it. RDFStruct.Copy() doesn't deep-copy repeated fields which may lead to hard to catch bugs. Args: obj: RDFValue to be copied. Returns: A deep copy of the passed RDFValue. def _DeepCopy(self, obj): """Creates an object copy by seria...
Returns audit entries stored in the database. def ReadAPIAuditEntries(self, username=None, router_method_names=None, min_timestamp=None, max_timestamp=None): """Returns audit entries stored in the database.""" ...
Returns audit entry counts grouped by user and calendar day. def CountAPIAuditEntriesByUserAndDay(self, min_timestamp=None, max_timestamp=None): """Returns audit entry counts grouped by user and calendar day.""" results = collections...
Writes an audit entry to the database. def WriteAPIAuditEntry(self, entry): """Writes an audit entry to the database.""" copy = entry.Copy() copy.timestamp = rdfvalue.RDFDatetime.Now() self.api_audit_entries.append(copy)
Applies instant output plugin to a multi-type collection. Args: plugin: InstantOutputPlugin instance. output_collection: MultiTypeCollection instance. source_urn: If not None, override source_urn for collection items. This has to be used when exporting flow results - their GrrMessages don't have ...
Applies instant output plugin to a collection of results. Args: plugin: InstantOutputPlugin instance. type_names: List of type names (strings) to be processed. fetch_fn: Function that takes a type name as an argument and returns available items (FlowResult) corresponding to this type. Items are ...