text
stringlengths
81
112k
A helper for defining boolean options. def DEFINE_bool(self, name, default, help, constant=False): """A helper for defining boolean options.""" self.AddOption( type_info.Bool(name=name, default=default, description=help), constant=constant)
A helper for defining float options. def DEFINE_float(self, name, default, help, constant=False): """A helper for defining float options.""" self.AddOption( type_info.Float(name=name, default=default, description=help), constant=constant)
A helper for defining integer options. def DEFINE_integer(self, name, default, help, constant=False): """A helper for defining integer options.""" self.AddOption( type_info.Integer(name=name, default=default, description=help), constant=constant)
A helper for defining string options. def DEFINE_string(self, name, default, help, constant=False): """A helper for defining string options.""" self.AddOption( type_info.String(name=name, default=default or "", description=help), constant=constant)
A helper for defining choice string options. def DEFINE_choice(self, name, default, choices, help, constant=False): """A helper for defining choice string options.""" self.AddOption( type_info.Choice( name=name, default=default, choices=choices, description=help), constant=constant)
Choose multiple options from a list. def DEFINE_multichoice(self, name, default, choices, help, constant=False): """Choose multiple options from a list.""" self.AddOption( type_info.MultiChoice( name=name, default=default, choices=choices, description=help), constant=constant)
A helper for defining lists of integer options. def DEFINE_integer_list(self, name, default, help, constant=False): """A helper for defining lists of integer options.""" self.AddOption( type_info.List( name=name, default=default, description=help, validat...
A helper for defining lists of strings options. def DEFINE_list(self, name, default, help, constant=False): """A helper for defining lists of strings options.""" self.AddOption( type_info.List( name=name, default=default, description=help, validator=type_...
A helper for defining constant strings. def DEFINE_constant_string(self, name, default, help): """A helper for defining constant strings.""" self.AddOption( type_info.String(name=name, default=default or "", description=help), constant=True)
Yields the valus in each section. def RawData(self): """Yields the valus in each section.""" result = collections.OrderedDict() i = 0 while True: try: name, value, value_type = winreg.EnumValue(self._AccessRootKey(), i) # Only support strings here. if value_type == winreg...
Returns audit entries stored in the database. def ReadAPIAuditEntries(self, username=None, router_method_names=None, min_timestamp=None, max_timestamp=None, cursor=None): """Returns aud...
Returns audit entry counts grouped by user and calendar day. def CountAPIAuditEntriesByUserAndDay(self, min_timestamp=None, max_timestamp=None, cursor=None): """Returns audit entry counts grouped by...
Writes an audit entry to the database. def WriteAPIAuditEntry(self, entry, cursor=None): """Writes an audit entry to the database.""" args = { "username": entry.username, "router_method_name": entry.router_method_name, "details": entry.SerializeToStri...
Show how the last active breakdown evolved over time. def GetReportData(self, get_report_args, token): """Show how the last active breakdown evolved over time.""" report = rdf_report_plugins.ApiReportData( representation_type=rdf_report_plugins.ApiReportData.RepresentationType .LINE_CHART) ...
Extract only the operating system type from the active histogram. def GetReportData(self, get_report_args, token): """Extract only the operating system type from the active histogram.""" report = rdf_report_plugins.ApiReportData( representation_type=rdf_report_plugins.ApiReportData.RepresentationType ...
Start a Windows service with the given name. Args: service_name: string The name of the service to be started. def StartService(service_name): """Start a Windows service with the given name. Args: service_name: string The name of the service to be started. """ try: win32serviceutil.StartService...
Stop a Windows service with the given name. Args: service_name: string The name of the service to be stopped. service_binary_name: string If given, also kill this binary as a best effort fallback solution. def StopService(service_name, service_binary_name=None): """Stop a Windows service with the ...
Stops the Windows service hosting the GRR process. def StopPreviousService(self): """Stops the Windows service hosting the GRR process.""" StopService( service_name=config.CONFIG["Nanny.service_name"], service_binary_name=config.CONFIG["Nanny.service_binary_name"]) if not config.CONFIG["Cl...
Copy the binaries from the temporary unpack location. We need to first stop the running service or we might not be able to write on the binary. We then copy the entire directory where we are running from into the location indicated by "Client.install_path". def RunOnce(self): """Copy the binaries from...
Install the nanny program. def InstallNanny(self): """Install the nanny program.""" # We need to copy the nanny sections to the registry to ensure the # service is correctly configured. new_config = config.CONFIG.MakeNewConfig() new_config.SetWriteBack(config.CONFIG["Config.writeback"]) for op...
Builds a legacy AFF4 urn string for a given subject and approval type. def BuildLegacySubject(subject_id, approval_type): """Builds a legacy AFF4 urn string for a given subject and approval type.""" at = rdf_objects.ApprovalRequest.ApprovalType if approval_type == at.APPROVAL_TYPE_CLIENT: return "aff4:/%s" ...
Checks if a client approval request is granted. def CheckClientApprovalRequest(approval_request): """Checks if a client approval request is granted.""" _CheckExpired(approval_request) _CheckHasEnoughGrants(approval_request) if not client_approval_auth.CLIENT_APPROVAL_AUTH_MGR.IsActive(): return True t...
Checks if an approval request is granted. def CheckApprovalRequest(approval_request): """Checks if an approval request is granted.""" at = rdf_objects.ApprovalRequest.ApprovalType if approval_request.approval_type == at.APPROVAL_TYPE_CLIENT: return CheckClientApprovalRequest(approval_request) elif approv...
Parses YAML data into a list of APIAuthorization objects. def ParseYAMLAuthorizationsList(yaml_data): """Parses YAML data into a list of APIAuthorization objects.""" try: raw_list = yaml.ParseMany(yaml_data) except (ValueError, pyyaml.YAMLError) as e: raise InvalidAPIAuthorization("Invalid YAML...
Creates a router with a given name and params. def _CreateRouter(self, router_cls, params=None): """Creates a router with a given name and params.""" if not router_cls.params_type and params: raise ApiCallRouterDoesNotExpectParameters( "%s is not configurable" % router_cls) rdf_params = No...
Returns a router corresponding to a given username. def GetRouterForUser(self, username): """Returns a router corresponding to a given username.""" for index, router in enumerate(self.routers): router_id = str(index) if self.auth_manager.CheckPermissions(username, router_id): logging.debu...
Create a BigQueryClient. def GetBigQueryClient(service_account_json=None, project_id=None, dataset_id=None): """Create a BigQueryClient.""" service_account_data = ( service_account_json or config.CONFIG["BigQuery.service_acct_json"]) project_id = project_id or co...
Create a dataset. def CreateDataset(self): """Create a dataset.""" body = { "datasetReference": { "datasetId": self.dataset_id, "description": "Data exported from GRR", "friendlyName": "GRRExportData", "projectId": self.project_id } } resu...
Retry the BigQuery upload job. Using the same job id protects us from duplicating data on the server. If we fail all of our retries we raise. Args: job: BigQuery job object job_id: ID string for this upload job error: errors.HttpError object from the first error Returns: API r...
Insert data into a bigquery table. If the table specified doesn't exist, it will be created with the specified schema. Args: table_id: string table id fd: open file descriptor containing the newline separated JSON schema: BigQuery schema dict job_id: string job id Returns: ...
Creates flow arguments object for a flow with a given name. def CreateFlowArgs(self, flow_name=None): """Creates flow arguments object for a flow with a given name.""" if not self._flow_descriptors: self._flow_descriptors = {} result = self._context.SendRequest("ListFlowDescriptors", None) f...
Given a TSK info object make a StatEntry. Note that tsk uses two things to uniquely identify a data stream - the inode object given in tsk_file and the attribute object which may correspond to an ADS of this file for filesystems which support ADS. We store both of these in the stat response. Args:...
Read from the file. def Read(self, length): """Read from the file.""" if not self.IsFile(): raise IOError("%s is not a file." % self.pathspec.last.path) available = min(self.size - self.offset, length) if available > 0: # This raises a RuntimeError in some situations. try: da...
Return a stat of the file. def Stat(self, ext_attrs=None): """Return a stat of the file.""" del ext_attrs # Unused. return self.MakeStatResponse(self.fd, tsk_attribute=self.tsk_attribute)
List all the files in the directory. def ListFiles(self, ext_attrs=None): """List all the files in the directory.""" del ext_attrs # Unused. if not self.IsDirectory(): raise IOError("%s is not a directory" % self.pathspec.CollapsePath()) for f in self.fd.as_directory(): try: name...
Main. def main(args): """Main.""" if args.subparser_name == "version": version = config_server.VERSION["packageversion"] print("GRR configuration updater {}".format(version)) return token = config_updater_util.GetToken() grr_config.CONFIG.AddContext(contexts.COMMAND_LINE_CONTEXT) grr_config.CON...
Sends an email for each response. def ProcessResponse(self, state, response): """Sends an email for each response.""" emails_left = self.args.emails_limit - self.IncrementCounter() if emails_left < 0: return if data_store.RelationalDBEnabled(): client_id = response.source.Basename() ...
Writes new artifact to the database. def WriteArtifact(self, artifact): """Writes new artifact to the database.""" name = str(artifact.name) if name in self.artifacts: raise db.DuplicatedArtifactError(name) self.artifacts[name] = artifact.Copy()
Looks up an artifact with given name from the database. def ReadArtifact(self, name): """Looks up an artifact with given name from the database.""" try: artifact = self.artifacts[name] except KeyError: raise db.UnknownArtifactError(name) return artifact.Copy()
Lists all artifacts that are stored in the database. def ReadAllArtifacts(self): """Lists all artifacts that are stored in the database.""" artifacts = [] for artifact in itervalues(self.artifacts): artifacts.append(artifact.Copy()) return artifacts
Deletes an artifact with given name from the database. def DeleteArtifact(self, name): """Deletes an artifact with given name from the database.""" try: del self.artifacts[name] except KeyError: raise db.UnknownArtifactError(name)
Adds an rdf value the queue. Adds an rdf value to a queue. Does not require that the queue be locked, or even open. NOTE: The caller is responsible for ensuring that the queue exists and is of the correct type. Args: queue_urn: The urn of the queue to add to. rdf_value: The rdf value to a...
Adds an rdf value to the queue. Adds an rdf value to the queue. Does not require that the queue be locked. Args: rdf_value: The rdf value to add to the queue. mutation_pool: A MutationPool object to write to. Raises: ValueError: rdf_value has unexpected type. def Add(self, rdf_value, ...
Returns and claims up to limit unclaimed records for timeout seconds. Returns a list of records which are now "claimed", a claimed record will generally be unavailable to be claimed until the claim times out. Note however that in case of an unexpected timeout or other error a record might be claimed tw...
Refreshes claims on records identified by ids. Args: ids: A list of ids provided by ClaimRecords timeout: The new timeout for these claims. Raises: LockError: If the queue is not locked. def RefreshClaims(self, ids, timeout="30m"): """Refreshes claims on records identified by ids. ...
Delete records identified by ids. Args: ids: A list of ids provided by ClaimRecords. token: The database access token to delete with. Raises: LockError: If the queue is not locked. def DeleteRecords(cls, ids, token): """Delete records identified by ids. Args: ids: A list of i...
Release records identified by subjects. Releases any claim on the records identified by ids. Args: ids: A list of ids provided by ClaimRecords. token: The database access token to write with. Raises: LockError: If the queue is not locked. def ReleaseRecords(cls, ids, token): """Rel...
Parse the History file. def Parse(self, stat, file_object, knowledge_base): """Parse the History file.""" _ = knowledge_base # TODO(user): Convert this to use the far more intelligent plaso parser. chrome = ChromeParser(file_object) for timestamp, entry_type, url, data1, _, _ in chrome.Parse(): ...
Iterator returning a list for each entry in history. We store all the download events in an array (choosing this over visits since there are likely to be less of them). We later interleave them with visit events to get an overall correct time order. Yields: a list of attributes for each entry d...
Parse a string into a client URN. Convert case so that all URNs are of the form C.[0-9a-f]. Args: value: string value to parse def ParseFromUnicode(self, value): """Parse a string into a client URN. Convert case so that all URNs are of the form C.[0-9a-f]. Args: value: string value ...
An alternate constructor which generates a new client id. def FromPublicKey(cls, public_key): """An alternate constructor which generates a new client id.""" # Our CN will be the first 64 bits of the hash of the public key # in MPI format - the length of the key in 4 bytes + the key # prefixed with a 0...
Add a relative stem to the current value and return a new RDFURN. Note that this returns an RDFURN, not a ClientURN since the resulting object would not pass validation. Args: path: A string containing a relative path. age: The age of the object. If None set to current time. Returns: ...
Merge a user into existing users or add new if it doesn't exist. Args: kb_user: A User rdfvalue. Returns: A list of strings with the set attribute names, e.g. ["users.sid"] def MergeOrAddUser(self, kb_user): """Merge a user into existing users or add new if it doesn't exist. Args: ...
Retrieve a User based on sid, uid or username. On windows we first get a SID and use it to find the username. We want to avoid combining users with name collisions, which occur when local users have the same username as domain users (something like Admin is particularly common). So if a SID is provid...
Return a more standard representation of the architecture. def arch(self): """Return a more standard representation of the architecture.""" if self.machine in ["x86_64", "AMD64", "i686"]: # 32 bit binaries running on AMD64 will still have a i386 arch. if self.architecture == "32bit": return...
Fill a Uname from the currently running platform. def FromCurrentSystem(cls): """Fill a Uname from the currently running platform.""" uname = platform.uname() fqdn = socket.getfqdn() system = uname[0] architecture, _ = platform.architecture() if system == "Windows": service_pack = platfor...
Parse the History file. def Parse(self, stat, file_object, knowledge_base): """Parse the History file.""" _, _ = stat, knowledge_base # TODO(user): Convert this to use the far more intelligent plaso parser. ie = IEParser(file_object) for dat in ie.Parse(): yield rdf_webhistory.BrowserHistoryI...
Parse the file. def Parse(self): """Parse the file.""" if not self._file: logging.error("Couldn't open file") return # Limit read size to 5MB. self.input_dat = self._file.read(1024 * 1024 * 5) if not self.input_dat.startswith(self.FILE_HEADER): logging.error("Invalid index.dat fi...
Retrieve a single record from the file. Args: offset: offset from start of input_dat where header starts record_size: length of the header according to file (untrusted) Returns: A dict containing a single browser history record. def _GetRecord(self, offset, record_size): """Retrieve a s...
Parse a file for history records yielding dicts. Yields: Dicts containing browser history def _DoParse(self): """Parse a file for history records yielding dicts. Yields: Dicts containing browser history """ get4 = lambda x: struct.unpack("<L", self.input_dat[x:x + 4])[0] filesize ...
Update a config with a random csrf key. def _GenerateCSRFKey(config): """Update a config with a random csrf key.""" secret_key = config.Get("AdminUI.csrf_secret_key", None) if not secret_key: # TODO(amoser): Remove support for django_secret_key. secret_key = config.Get("AdminUI.django_secret_key", None) ...
Generate the keys we need for a GRR server. def GenerateKeys(config, overwrite_keys=False): """Generate the keys we need for a GRR server.""" if not hasattr(key_utils, "MakeCACert"): raise OpenSourceKeyUtilsRequiredError( "Generate keys can only run with open source key_utils.") if (config.Get("Priva...
Yields all (psutil-) processes that match certain criteria. Args: pids: A list of pids. If given, only the processes with those pids are returned. process_regex_string: If given, only processes whose name matches the regex are returned. ignore_grr_process: If True, the grr process itself will...
Fetch flow's data and return proper Flow object. def Get(self): """Fetch flow's data and return proper Flow object.""" args = flow_pb2.ApiGetFlowArgs( client_id=self.client_id, flow_id=self.flow_id) data = self._context.SendRequest("GetFlow", args) return Flow(data=data, context=self._context)
Wait until the flow completes. Args: timeout: timeout in seconds. None means default timeout (1 hour). 0 means no timeout (wait forever). Returns: Fresh flow object. Raises: PollTimeoutError: if timeout is reached. FlowFailedError: if the flow is not successful. def WaitUn...
Gets the first fingerprint type from the protobuf. def GetFingerprint(self, name): """Gets the first fingerprint type from the protobuf.""" for result in self.results: if result.GetItem("name") == name: return result
Initializes the context of this flow. def InitializeContext(self, args): """Initializes the context of this flow.""" if args is None: args = rdf_flow_runner.FlowRunnerArgs() output_plugins_states = [] for plugin_descriptor in args.output_plugins: if not args.client_id: self.Log( ...
Returns a random session ID for this flow based on the runner args. Returns: A formatted session id URN. def GetNewSessionID(self): """Returns a random session ID for this flow based on the runner args. Returns: A formatted session id URN. """ # Calculate a new session id based on the...
This method is used to schedule a new state on a different worker. This is basically the same as CallFlow() except we are calling ourselves. The state will be invoked at a later time. Args: next_state: The state in this flow to be invoked. start_time: Start the flow at this time. This delays...
Schedules a kill notification for this flow. def ScheduleKillNotification(self): """Schedules a kill notification for this flow.""" # Create a notification for the flow in the future that # indicates that this flow is in progess. We'll delete this # notification when we're done with processing complete...
Go through the list of requests and process the completed ones. We take a snapshot in time of all requests and responses for this flow. We then process as many completed requests as possible. If responses are not quite here we leave it for next time. It is safe to call this function as many times as n...
Does the actual processing of the completed requests. def _ProcessCompletedRequests(self, notification): """Does the actual processing of the completed requests.""" # First ensure that client messages are all removed. NOTE: We make a new # queue manager here because we want only the client messages to be r...
Completes the request by calling the state method. Args: method_name: The name of the state method to call. request: A RequestState protobuf. responses: A list of GrrMessages responding to the request. def RunStateMethod(self, method_name, request=None, responses=None): """Completes the requ...
Calls the client asynchronously. This sends a message to the client to invoke an Action. The run action may send back many responses. These will be queued by the framework until a status message is sent by the client. The status message will cause the entire transaction to be committed to the speci...
Creates a new flow and send its responses to a state. This creates a new flow. The flow may send back many responses which will be queued by the framework until the flow terminates. The final status message will cause the entire transaction to be committed to the specified state. Args: flow_nam...
Allows this flow to send a message to its parent flow. If this flow does not have a parent, the message is ignored. Args: response: An RDFValue() instance to be sent to the parent. tag: If specified, tag the result with the following tag. NOTE: supported in REL_DB implementation only. ...
Terminates this flow with an error. def Error(self, backtrace, client_id=None, status_code=None): """Terminates this flow with an error.""" try: self.queue_manager.DestroyFlowStates(self.session_id) except queue_manager.MoreDataException: pass if not self.IsRunning(): return # S...
Processes replies with output plugins. def ProcessRepliesWithOutputPlugins(self, replies): """Processes replies with output plugins.""" for output_plugin_state in self.context.output_plugins_states: plugin_descriptor = output_plugin_state.plugin_descriptor output_plugin_cls = plugin_descriptor.GetP...
This notifies the parent flow of our termination. def _SendTerminationMessage(self, status=None): """This notifies the parent flow of our termination.""" if not self.runner_args.request_state.session_id: # No parent flow, nothing to do here. return if status is None: status = rdf_flows.G...
Terminates this flow. def Terminate(self, status=None): """Terminates this flow.""" try: self.queue_manager.DestroyFlowStates(self.session_id) except queue_manager.MoreDataException: pass # This flow might already not be running. if not self.IsRunning(): return self._SendTer...
Save cpu and network stats, check limits. def UpdateProtoResources(self, status): """Save cpu and network stats, check limits.""" user_cpu = status.cpu_time_used.user_cpu_time system_cpu = status.cpu_time_used.system_cpu_time self.context.client_resources.cpu_usage.user_cpu_time += user_cpu self.co...
Build a host prefix for a notification message based on a client id. def _HostPrefix(client_id): """Build a host prefix for a notification message based on a client id.""" if not client_id: return "" hostname = None if data_store.RelationalDBEnabled(): client_snapshot = data_store.REL_DB.ReadClientSna...
Maps UserNotification object to legacy GRRUser.Notify arguments. def _MapLegacyArgs(nt, message, ref): """Maps UserNotification object to legacy GRRUser.Notify arguments.""" unt = rdf_objects.UserNotification.Type if nt == unt.TYPE_CLIENT_INTERROGATED: return [ "Discovery", aff4.ROOT_URN.Add...
Schedules a legacy AFF4 user notification. def _NotifyLegacy(username, notification_type, message, object_reference): """Schedules a legacy AFF4 user notification.""" try: with aff4.FACTORY.Open( aff4.ROOT_URN.Add("users").Add(username), aff4_type=aff4_users.GRRUser, mode="rw") as fd: ...
Schedules a new-style REL_DB user notification. def _Notify(username, notification_type, message, object_reference): """Schedules a new-style REL_DB user notification.""" # Do not try to notify system users (e.g. Cron). if username in aff4_users.GRRUser.SYSTEM_USERS: return if object_reference: uc = ...
Adds an rdf value to a collection. Adds an rdf value to a collection. Does not require that the collection be open. NOTE: The caller is responsible for ensuring that the collection exists and is of the correct type. Args: collection_urn: The urn of the collection to add to. rdf_value: The ...
Adds an rdf value to the collection. Adds an rdf value to the collection. Does not require that the collection be locked. Args: rdf_value: The rdf value to add to the collection. timestamp: The timestamp (in microseconds) to store the rdf value at. Defaults to the current time. s...
Scans for stored records. Scans through the collection, returning stored values ordered by timestamp. Args: after_timestamp: If set, only returns values recorded after timestamp. include_suffix: If true, the timestamps returned are pairs of the form (micros_since_epoc, suffix) where suffix...
Lookup multiple values by their record objects. def MultiResolve(self, records): """Lookup multiple values by their record objects.""" for value, timestamp in data_store.DB.CollectionReadItems(records): rdf_value = self.RDF_TYPE.FromSerializedString(value) rdf_value.age = timestamp yield rdf_...
Main loop that usually never terminates. def UpdateLoop(self): """Main loop that usually never terminates.""" while not self.exit_now: with self.cv: while not self.to_process: self.cv.wait() next_update = self.to_process.popleft() if next_update is None: return...
Write index marker i. def _MaybeWriteIndex(self, i, ts, mutation_pool): """Write index marker i.""" if i > self._max_indexed and i % self.INDEX_SPACING == 0: # We only write the index if the timestamp is more than 5 minutes in the # past: hacky defense against a late write changing the count. ...
Scan records starting with index i. def _IndexedScan(self, i, max_records=None): """Scan records starting with index i.""" self._ReadIndex() # The record number that we will read next. idx = 0 # The timestamp that we will start reading from. start_ts = 0 if i >= self._max_indexed: st...
Helper method to add rdfvalues as GrrMessages for testing. def AddAsMessage(self, rdfvalue_in, source, mutation_pool=None): """Helper method to add rdfvalues as GrrMessages for testing.""" self.Add( rdf_flows.GrrMessage(payload=rdfvalue_in, source=source), mutation_pool=mutation_pool)
Parse the passwd file. def Parse(self, stat, file_object, knowledge_base): """Parse the passwd file.""" _, _ = stat, knowledge_base lines = [ l.strip() for l in utils.ReadFileBytesAsUnicode(file_object).splitlines() ] for index, line in enumerate(lines): user = self.ParseLine(...
Parse the wtmp file. def Parse(self, stat, file_object, knowledge_base): """Parse the wtmp file.""" _, _ = stat, knowledge_base users = {} wtmp = file_object.read() while wtmp: try: record = UtmpStruct(wtmp) except utils.ParsingError: break wtmp = wtmp[record.size...
Parse the netgroup file and return User objects. Lines are of the form: group1 (-,user1,) (-,user2,) (-,user3,) Groups are ignored, we return users in lines that match the filter regexes, or all users in the file if no filters are specified. We assume usernames are in the default regex format s...
Identify the type of hash in a hash string. Args: hash_str: A string value that may be a hash. Returns: A string description of the type of hash. def GetHashType(self, hash_str): """Identify the type of hash in a hash string. Args: hash_str: A string value that may be a hash. ...
Process a file line by line. Args: file_obj: The file to parse. line_parser: The parser method used to process and store line content. Raises: parser.ParseError if the parser is unable to process the line. def _ParseFile(self, file_obj, line_parser): """Process a file line by line. ...
Verify that entries that claim to use shadow files have a shadow entry. If the entries of the non-shadowed file indicate that a shadow file is used, check that there is actually an entry for that file in shadow. Args: store_type: The type of password store that should be used (e.g. /etc/shad...
Helper method to perform bidirectional set differences. def MemberDiff(data1, set1_name, data2, set2_name): """Helper method to perform bidirectional set differences.""" set1 = set(data1) set2 = set(data2) diffs = [] msg = "Present in %s, missing in %s: %s" if set1 != set2: in_set1 = set1...