INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
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.debug("Matched router %s to user %s", router.__class__.__...
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 config.CONFIG["BigQuery.proj...
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 } } result = self.service.d...
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...
def RetryUpload(self, job, job_id, error): """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 obj...
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: ...
def InsertData(self, table_id, fd, schema, job_id): """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: BigQuer...
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 = _DecodeUTF8WithWarning(f.info.name....
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() client = data_store.REL_DB.ReadClie...
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) for item in result.items: self._flow_descriptors[item....
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)
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)
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
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()
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, mutation_pool=None): """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_...
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...
def ClaimRecords(self, limit=10000, timeout="30m", start_time=None, record_filter=lambda x: False, max_filtered=1000): """Returns and claims up to limit unclaimed records for timeout seconds. Returns a list of record...
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. Args: ids: A list of ids provided by ClaimRecords timeout: The new timeout for these claims. Raises: LockError: If the queue is not locked. """ with data_store.DB.GetMutationPool() as...
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...
def StaticAdd(cls, queue_urn, rdf_value, mutation_pool=None): """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:...
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 ids provided by ClaimRecords. token: The database access token to delete with. Raises: LockError: If the queue is not locked. """ with data_store.DB.GetMutationPool() as mutation_pool: ...
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): """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. ...
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(): if entry_type == "CHRO...
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
def Parse(self): """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 attr...
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 to parse """ precondition.AssertType(value, Text) value = value.strip() super(ClientURN, self).ParseFromUnicode(value) mat...
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. This weird format is an artifact from the way # M2Cry...
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: ...
def Add(self, path, age=None): """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 s...
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: kb_user: A User rdfvalue. Returns: A list of strings with the set attribute names, e.g. ["users.sid"] """ user = self.GetUser( sid=kb_user.sid, uid=kb_user.uid, usernam...
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...
def GetUser(self, sid=None, uid=None, username=None): """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 l...
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 "i386" return "amd64" elif self.machine == "x86"...
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 = platform.win32_ver()[2] kernel = uname[3] # 5.1.260...
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.BrowserHistoryItem( url=dat["u...
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 file %s", self._fil...
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 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. """ r...
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 = get4(0x1c) offset = get4(0x20) coffset = offset while coffset < filesize: etype = ...
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) if secret_key: config.Set("Admi...
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("PrivateKeys.server_key", default=None) and n...
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...
def ProcessIterator(pids, process_regex_string, ignore_grr_process, error_list): """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 ...
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 WaitUntilDone(self, timeout=None): """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. FlowFailedErr...
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( "Not initializing output plug...
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 flow args. Note that our caller # can specify the base path to the session id, but they can not influence # ...
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...
def CallState(self, next_state="", start_time=None): """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....
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 completed # requests. If we're stuck for some reas...
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...
def ProcessCompletedRequests(self, notification, unused_thread_pool=None): """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 w...
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 removed # ASAP. This must happen before we actually ...
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 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. """ if self...
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...
def CallClient(self, action_cls, request=None, next_state=None, request_data=None, **kwargs): """Calls the client asynchronously. This sends a message to the client to invoke an Action. The run action may send back many re...
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...
def CallFlow(self, flow_name=None, next_state=None, request_data=None, client_id=None, base_session_id=None, **kwargs): """Creates a new flow and send its responses to a state. This creates a new flow. The flow may send b...
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. ...
def SendReply(self, response, tag=None): """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: suppo...
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 # Set an error status reply = rdf_fl...
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.GetPluginClass() output_plugin = outpu...
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.GrrStatus() client_resources = self.context.cli...
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._SendTerminationMessage(status=...
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.context.client_resources.cpu_usage.system_cpu...
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.ReadClientSnapshot(client_id) if client_snapshot: hostname = client_snaps...
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: args = _MapLegacyArgs(notification_ty...
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(ref.client.client_id), _HostPrefix(ref.client.client_id) ...
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 = object_reference.UnionCast() if hasattr(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 ...
def StaticAdd(cls, collection_urn, rdf_value, timestamp=None, suffix=None, mutation_pool=None): """Adds an rdf value to a collection. Adds an rdf value to a collection. Does not require that the collection be open. NOTE: The ca...
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...
def Add(self, rdf_value, timestamp=None, suffix=None, mutation_pool=None): """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 micr...
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...
def Scan(self, after_timestamp=None, include_suffix=False, max_records=None): """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 times...
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_value
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 now = time.time() next_cls =...
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. if ts[0] < (rdfvalue.R...
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: start_ts = max((0, 0), (self._index[sel...
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(index, line) if us...
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:] # Users only ...
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...
def Parse(self, stat, file_object, knowledge_base): """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....
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. Returns: A string description of the type of hash. """ # Return the type of the first matching hash. for hash_type, hash_re in self.hashes: if ha...
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. 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. """ lines = [ l.st...
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...
def ReconcileShadow(self, store_type): """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 sto...
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 - set2 in_set2 = set2 - set1 if in_set1: ...
Process files together.
def ParseMultiple(self, stats, file_objs, kb): """Process files together.""" fileset = {stat.pathspec.path: obj for stat, obj in zip(stats, file_objs)} return self.ParseFileset(fileset)
Extract the members of each group from /etc/gshadow. Identifies the groups in /etc/gshadow and several attributes of the group, including how the password is crypted (if set). gshadow files have the format group_name:passwd:admins:members admins are both group members and can manage passwords and memb...
def ParseGshadowEntry(self, line): """Extract the members of each group from /etc/gshadow. Identifies the groups in /etc/gshadow and several attributes of the group, including how the password is crypted (if set). gshadow files have the format group_name:passwd:admins:members admins are both group...
Extract the members of a group from /etc/group.
def ParseGroupEntry(self, line): """Extract the members of a group from /etc/group.""" fields = ("name", "passwd", "gid", "members") if line: rslt = dict(zip(fields, line.split(":"))) name = rslt["name"] group = self.entry.setdefault(name, rdf_client.Group(name=name)) group.pw_entry....
Add shadow group members to the group if gshadow is used. Normally group and shadow should be in sync, but no guarantees. Merges the two stores as membership in either file may confer membership.
def MergeMembers(self): """Add shadow group members to the group if gshadow is used. Normally group and shadow should be in sync, but no guarantees. Merges the two stores as membership in either file may confer membership. """ for group_name, members in iteritems(self.gshadow_members): group ...
Process linux system group and gshadow files. Orchestrates collection of account entries from /etc/group and /etc/gshadow. The group and gshadow entries are reconciled and member users are added to the entry. Args: fileset: A dict of files mapped from path to an open file. Yields: - A...
def ParseFileset(self, fileset=None): """Process linux system group and gshadow files. Orchestrates collection of account entries from /etc/group and /etc/gshadow. The group and gshadow entries are reconciled and member users are added to the entry. Args: fileset: A dict of files mapped from...
Identify any anomalous group attributes or memberships.
def FindAnomalies(self): """Identify any anomalous group attributes or memberships.""" for grp_name, group in iteritems(self.entry): shadow = self.shadow.get(grp_name) gshadows = self.gshadow_members.get(grp_name, []) if shadow is not None: diff = self.MemberDiff(group.members, "group"...
Extract the user accounts in /etc/shadow. Identifies the users in /etc/shadow and several attributes of their account, including how their password is crypted and password aging characteristics. Args: line: An entry of the shadow file.
def ParseShadowEntry(self, line): """Extract the user accounts in /etc/shadow. Identifies the users in /etc/shadow and several attributes of their account, including how their password is crypted and password aging characteristics. Args: line: An entry of the shadow file. """ fields = ("...
Process the passwd entry fields and primary group memberships.
def ParsePasswdEntry(self, line): """Process the passwd entry fields and primary group memberships.""" fields = ("uname", "passwd", "uid", "gid", "fullname", "homedir", "shell") if line: rslt = dict(zip(fields, line.split(":"))) user = self.entry.setdefault(rslt["uname"], rdf_client.User()) ...
Unify members of a group and accounts with the group as primary gid.
def _Members(self, group): """Unify members of a group and accounts with the group as primary gid.""" group.members = set(group.members).union(self.gids.get(group.gid, [])) return group
Adds aggregate group membership from group, gshadow and passwd.
def AddGroupMemberships(self): """Adds aggregate group membership from group, gshadow and passwd.""" self.groups = {g.name: self._Members(g) for g in itervalues(self.groups)} # Map the groups a user is a member of, irrespective of primary/extra gid. for g in itervalues(self.groups): for user in g....
Identify anomalies in the password/shadow and group/gshadow data.
def FindAnomalies(self): """Identify anomalies in the password/shadow and group/gshadow data.""" # Find anomalous group entries. findings = [] group_entries = {g.gid for g in itervalues(self.groups)} for gid in set(self.gids) - group_entries: undefined = ",".join(self.gids.get(gid, [])) ...
Add the passwd entries to the shadow store.
def AddPassword(self, fileset): """Add the passwd entries to the shadow store.""" passwd = fileset.get("/etc/passwd") if passwd: self._ParseFile(passwd, self.ParsePasswdEntry) else: logging.debug("No /etc/passwd file.")
Add the shadow entries to the shadow store.
def AddShadow(self, fileset): """Add the shadow entries to the shadow store.""" shadow = fileset.get("/etc/shadow") if shadow: self._ParseFile(shadow, self.ParseShadowEntry) else: logging.debug("No /etc/shadow file.")
Process linux system login files. Orchestrates collection of account entries from /etc/passwd and /etc/shadow. The passwd and shadow entries are reconciled and group memberships are mapped to the account. Args: fileset: A dict of files mapped from path to an open file. Yields: - A se...
def ParseFileset(self, fileset=None): """Process linux system login files. Orchestrates collection of account entries from /etc/passwd and /etc/shadow. The passwd and shadow entries are reconciled and group memberships are mapped to the account. Args: fileset: A dict of files mapped from pa...
Extract path information, interpolating current path values as needed.
def _ExpandPath(self, target, vals, paths): """Extract path information, interpolating current path values as needed.""" if target not in self._TARGETS: return expanded = [] for val in vals: # Null entries specify the current directory, so :a::b:c: is equivalent # to .:a:.:b:c:. ...
Extract env_var and path values from sh derivative shells. Iterates over each line, word by word searching for statements that set the path. These are either variables, or conditions that would allow a variable to be set later in the line (e.g. export). Args: lines: A list of lines, each of whic...
def _ParseShVariables(self, lines): """Extract env_var and path values from sh derivative shells. Iterates over each line, word by word searching for statements that set the path. These are either variables, or conditions that would allow a variable to be set later in the line (e.g. export). Args:...
Extract env_var and path values from csh derivative shells. Path attributes can be set several ways: - setenv takes the form "setenv PATH_NAME COLON:SEPARATED:LIST" - set takes the form "set path_name=(space separated list)" and is automatically exported for several types of files. The first ent...
def _ParseCshVariables(self, lines): """Extract env_var and path values from csh derivative shells. Path attributes can be set several ways: - setenv takes the form "setenv PATH_NAME COLON:SEPARATED:LIST" - set takes the form "set path_name=(space separated list)" and is automatically exported fo...
Identifies the paths set within a file. Expands paths within the context of the file, but does not infer fully expanded paths from external states. There are plenty of cases where path attributes are unresolved, e.g. sourcing other files. Lines are not handled literally. A field parser is used to: ...
def Parse(self, stat, file_obj, knowledge_base): """Identifies the paths set within a file. Expands paths within the context of the file, but does not infer fully expanded paths from external states. There are plenty of cases where path attributes are unresolved, e.g. sourcing other files. Lines a...
Seek to an offset in the file.
def Seek(self, offset, whence=os.SEEK_SET): """Seek to an offset in the file.""" if whence == os.SEEK_SET: self.offset = offset elif whence == os.SEEK_CUR: self.offset += offset elif whence == os.SEEK_END: self.offset = self.size + offset else: raise ValueError("Illegal whenc...
Guesses a container from the current object.
def OpenAsContainer(self): """Guesses a container from the current object.""" if self.IsDirectory(): return self # TODO(user): Add support for more containers here (e.g. registries, zip # files etc). else: # For now just guess TSK. tsk_handler = self._handlers[rdf_paths.PathSpec.PathTy...
Returns the name of the component which matches best our base listing. In order to do the best case insensitive matching we list the files in the base handler and return the base match for this component. Args: component: A component name which should be present in this directory. Returns: ...
def MatchBestComponentName(self, component): """Returns the name of the component which matches best our base listing. In order to do the best case insensitive matching we list the files in the base handler and return the base match for this component. Args: component: A component name which sho...
Try to correct the casing of component. This method is called when we failed to open the component directly. We try to transform the component into something which is likely to work. In this implementation, we correct the case of the component until we can not open the path any more. Args: ...
def Open(cls, fd, component, handlers, pathspec=None, progress_callback=None): """Try to correct the casing of component. This method is called when we failed to open the component directly. We try to transform the component into something which is likely to work. In this implementation, we correct th...
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 ...
def StaticAdd(cls, collection_urn, rdf_value, timestamp=None, suffix=None, mutation_pool=None): """Adds an rdf value to a collection. Adds an rdf value to a collection. Does not require that the collection be open. NOTE: The ca...
Scans for stored records. Scans through the collection, returning stored values ordered by timestamp. Args: type_name: Type of the records to scan. after_timestamp: If set, only returns values recorded after timestamp. include_suffix: If true, the timestamps returned are pairs of the form ...
def ScanByType(self, type_name, after_timestamp=None, include_suffix=False, max_records=None): """Scans for stored records. Scans through the collection, returning stored values ordered by timestamp. Args: type_name: Type of the rec...
This class method creates new hunts.
def StartHunt(args=None, runner_args=None, token=None, **kwargs): """This class method creates new hunts.""" # If no token is specified, raise. if not token: raise access_control.UnauthorizedAccess("A token must be specified.") # Build the runner args from the keywords. if runner_args is None: runne...
Go through the list of requests and process the completed ones. We take a snapshot in time of all requests and responses for this hunt. We then process as many completed requests as possible. If responses are not quite here we leave it for next time. Args: notification: The notification object t...
def ProcessCompletedRequests(self, notification, thread_pool): """Go through the list of requests and process the completed ones. We take a snapshot in time of all requests and responses for this hunt. We then process as many completed requests as possible. If responses are not quite here we leave it f...
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. event: A threading.Event() instance to signal completion of this request. direct_re...
def RunStateMethod(self, method_name, request=None, responses=None, event=None, direct_response=None): """Completes the request by calling the state method. Args: method_name: The name of the state me...
Sends the message to event listeners.
def Publish(self, event_name, msg, delay=0): """Sends the message to event listeners.""" events_lib.Events.PublishEvent(event_name, msg, delay=delay)
Get current CPU limit for subflows.
def _GetSubFlowCPULimit(self): """Get current CPU limit for subflows.""" subflow_cpu_limit = None if self.runner_args.per_client_cpu_limit: subflow_cpu_limit = self.runner_args.per_client_cpu_limit if self.runner_args.cpu_limit: cpu_usage_data = self.context.client_resources.cpu_usage ...