text
stringlengths
81
112k
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...
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, r...
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 s...
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 No...
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...
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 accou...
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(":"))) use...
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/extr...
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...
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...
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 cu...
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...
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...
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: ...
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: ...
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_hand...
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: ...
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: ...
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 ...
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 ...
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 keyword...
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...
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...
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.c...
Get current network limit for subflows. def _GetSubFlowNetworkLimit(self): """Get current network limit for subflows.""" subflow_network_limit = None if self.runner_args.per_client_network_limit_bytes: subflow_network_limit = self.runner_args.per_client_network_limit_bytes if self.runner_args....
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...
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...
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...
Hunts process all responses concurrently in a threadpool. def _Process(self, request, responses, thread_pool=None, events=None): """Hunts process all responses concurrently in a threadpool.""" # This function is called and runs within the main processing thread. We do # not need to lock the hunt object whi...
Logs the message using the hunt's standard logging. Args: format_str: Format string *args: arguments to the format string Raises: RuntimeError: on parent missing logs_collection def Log(self, format_str, *args): """Logs the message using the hunt's standard logging. Args: for...
Logs an error for a client but does not terminate the hunt. def Error(self, backtrace, client_id=None): """Logs an error for a client but does not terminate the hunt.""" logging.error("Hunt Error: %s", backtrace) self.hunt_obj.LogClientError(client_id, backtrace=backtrace)
Update the resource usage of the hunt. def SaveResourceUsage(self, client_id, status): """Update the resource usage of the hunt.""" # Per client stats. self.hunt_obj.ProcessClientResourcesStats(client_id, status) # Overall hunt resource usage. self.UpdateProtoResources(status)
Initializes the context of this hunt. def InitializeContext(self, args): """Initializes the context of this hunt.""" if args is None: args = rdf_hunts.HuntRunnerArgs() context = rdf_hunts.HuntContext( create_time=rdfvalue.RDFDatetime.Now(), creator=self.token.username, durati...
Returns a random integer session ID for this hunt. All hunts are created under the aff4:/hunts namespace. Returns: a formatted session id string. def GetNewSessionID(self, **_): """Returns a random integer session ID for this hunt. All hunts are created under the aff4:/hunts namespace. Re...
This uploads the rules to the foreman and, thus, starts the hunt. def Start(self): """This uploads the rules to the foreman and, thus, starts the hunt.""" # We are already running. if self.hunt_obj.Get(self.hunt_obj.Schema.STATE) == "STARTED": return # Determine when this hunt will expire. s...
Adds a foreman rule for this hunt. def _AddForemanRule(self): """Adds a foreman rule for this hunt.""" if data_store.RelationalDBEnabled(): # Relational DB uses ForemanCondition objects. foreman_condition = foreman_rules.ForemanCondition( creation_time=rdfvalue.RDFDatetime.Now(), ...
Removes the foreman rule corresponding to this hunt. def _RemoveForemanRule(self): """Removes the foreman rule corresponding to this hunt.""" if data_store.RelationalDBEnabled(): data_store.REL_DB.RemoveForemanRule(hunt_id=self.session_id.Basename()) return with aff4.FACTORY.Open( "aff...
Marks the hunt as completed. def _Complete(self): """Marks the hunt as completed.""" self._RemoveForemanRule() if "w" in self.hunt_obj.mode: self.hunt_obj.Set(self.hunt_obj.Schema.STATE("COMPLETED")) self.hunt_obj.Flush()
Pauses the hunt (removes Foreman rules, does not touch expiry time). def Pause(self): """Pauses the hunt (removes Foreman rules, does not touch expiry time).""" if not self.IsHuntStarted(): return self._RemoveForemanRule() self.hunt_obj.Set(self.hunt_obj.Schema.STATE("PAUSED")) self.hunt_ob...
Cancels the hunt (removes Foreman rules, resets expiry time to 0). def Stop(self, reason=None): """Cancels the hunt (removes Foreman rules, resets expiry time to 0).""" self._RemoveForemanRule() self.hunt_obj.Set(self.hunt_obj.Schema.STATE("STOPPED")) self.hunt_obj.Flush() self._CreateAuditEvent("...
Is this hunt considered started? This method is used to check if new clients should be processed by this hunt. Note that child flow responses are always processed but new clients are not allowed to be scheduled unless the hunt is started. Returns: If a new client is allowed to be scheduled o...
This method is used to asynchronously schedule a new hunt state. The state will be invoked in a later time and receive all the messages we send. Args: messages: A list of rdfvalues to send. If the last one is not a GrrStatus, we append an OK Status. next_state: The state in this hunt t...
Make a new runner. def CreateRunner(self, **kw): """Make a new runner.""" self.runner = HuntRunner(self, token=self.token, **kw) return self.runner
This method is called by the foreman for each client it discovers. Note that this function is performance sensitive since it is called by the foreman for every client which needs to be scheduled. Args: hunt_id: The hunt to schedule. client_ids: List of clients that should be added to the hunt....
Create a new child flow from a hunt. def CallFlow(self, flow_name=None, next_state=None, request_data=None, client_id=None, **kwargs): """Create a new child flow from a hunt.""" base_session_id = None if client_id: # The flow ...
Initializes this hunt from arguments. def Start(self): """Initializes this hunt from arguments.""" with data_store.DB.GetMutationPool() as mutation_pool: self.CreateCollections(mutation_pool) if not self.runner_args.description: self.SetDescription()
Logs an error for a client. def LogClientError(self, client_id, log_message=None, backtrace=None): """Logs an error for a client.""" self.RegisterClientError( client_id, log_message=log_message, backtrace=backtrace)
Process status message from a client and update the stats. Args: client_id: Client id. status: The status object returned from the client. def ProcessClientResourcesStats(self, client_id, status): """Process status message from a client and update the stats. Args: client_id: Client id. ...
Get all the clients in a dict of {status: [client_list]}. def GetClientsByStatus(self): """Get all the clients in a dict of {status: [client_list]}.""" started = self.GetClients() completed = self.GetCompletedClients() outstanding = started - completed return { "STARTED": started, ...
Take in a client list and return dicts with their age and hostname. def GetClientStates(self, client_list, client_chunk=50): """Take in a client list and return dicts with their age and hostname.""" for client_group in collection.Batch(client_list, client_chunk): for fd in aff4.FACTORY.MultiOpen( ...
List clients conforming to a givent query. def SearchClients(query=None, context=None): """List clients conforming to a givent query.""" args = client_pb2.ApiSearchClientsArgs(query=query) items = context.SendIteratorRequest("SearchClients", args) return utils.MapItemsIterator(lambda data: Client(data=data, ...
Fetch and return a proper ClientApproval object. def Get(self): """Fetch and return a proper ClientApproval object.""" args = user_pb2.ApiGetClientApprovalArgs( client_id=self.client_id, approval_id=self.approval_id, username=self.username) result = self._context.SendRequest("GetCl...
Returns a reference to a file with a given path on client's VFS. def File(self, path): """Returns a reference to a file with a given path on client's VFS.""" return vfs.FileRef( client_id=self.client_id, path=path, context=self._context)
Return a reference to a flow with a given id on this client. def Flow(self, flow_id): """Return a reference to a flow with a given id on this client.""" return flow.FlowRef( client_id=self.client_id, flow_id=flow_id, context=self._context)
Create new flow on this client. def CreateFlow(self, name=None, args=None, runner_args=None): """Create new flow on this client.""" if not name: raise ValueError("name can't be empty") request = flow_pb2.ApiCreateFlowArgs(client_id=self.client_id) request.flow.name = name if runner_args: ...
List flows that ran on this client. def ListFlows(self): """List flows that ran on this client.""" args = flow_pb2.ApiListFlowsArgs(client_id=self.client_id) items = self._context.SendIteratorRequest("ListFlows", args) return utils.MapItemsIterator( lambda data: flow.Flow(data=data, context=s...
Returns a reference to an approval. def Approval(self, username, approval_id): """Returns a reference to an approval.""" return ClientApprovalRef( client_id=self.client_id, username=username, approval_id=approval_id, context=self._context)
Create a new approval for the current user to access this client. def CreateApproval(self, reason=None, notified_users=None, email_cc_addresses=None, keep_client_alive=False): """Create a new approval for the current user to access...
Fetch client's data and return a proper Client object. def Get(self): """Fetch client's data and return a proper Client object.""" args = client_pb2.ApiGetClientArgs(client_id=self.client_id) result = self._context.SendRequest("GetClient", args) return Client(data=result, context=self._context)
Returns a list of MetricMetadata for communicator-related metrics. def GetMetricMetadata(): """Returns a list of MetricMetadata for communicator-related metrics.""" return [ stats_utils.CreateCounterMetadata("grr_client_unknown"), stats_utils.CreateCounterMetadata("grr_decoding_error"), stats_uti...
Symmetrically encrypt the data using the optional iv. def Encrypt(self, data, iv=None): """Symmetrically encrypt the data using the optional iv.""" if iv is None: iv = rdf_crypto.EncryptionKey.GenerateKey(length=128) cipher = rdf_crypto.AES128CBCCipher(self.cipher.key, iv) return iv, cipher.Encry...
Symmetrically decrypt the data. def Decrypt(self, data, iv): """Symmetrically decrypt the data.""" key = rdf_crypto.EncryptionKey(self.cipher.key) iv = rdf_crypto.EncryptionKey(iv) return rdf_crypto.AES128CBCCipher(key, iv).Decrypt(data)
Verifies the HMAC. This method raises a DecryptionError if the received HMAC does not verify. If the HMAC verifies correctly, True is returned. Args: comms: The comms RdfValue to verify. Raises: DecryptionError: The HMAC did not verify. Returns: True def _VerifyHMAC(self, comm...
Verifies the signature on the encrypted cipher block. This method returns True if the signature verifies correctly with the key given. Args: remote_public_key: The remote public key. Returns: None Raises: rdf_crypto.VerificationError: A signature and a key were both given but ...
Encode the MessageList into the packed_message_list rdfvalue. def EncodeMessageList(cls, message_list, packed_message_list): """Encode the MessageList into the packed_message_list rdfvalue.""" # By default uncompress uncompressed_data = message_list.SerializeToString() packed_message_list.message_list ...
Returns the cipher for self.server_name. def _GetServerCipher(self): """Returns the cipher for self.server_name.""" if self.server_cipher is not None: expiry = self.server_cipher_age + rdfvalue.Duration("1d") if expiry > rdfvalue.RDFDatetime.Now(): return self.server_cipher remote_pub...
Accepts a list of messages and encodes for transmission. This function signs and then encrypts the payload. Args: message_list: A MessageList rdfvalue containing a list of GrrMessages. result: A ClientCommunication rdfvalue which will be filled in. destination: The CN of the remote system...
Decrypt the serialized, encrypted string. Args: encrypted_response: A serialized and encrypted string. Returns: a Packed_Message_List rdfvalue def DecryptMessage(self, encrypted_response): """Decrypt the serialized, encrypted string. Args: encrypted_response: A serialized and en...
Decompress the message data from packed_message_list. Args: packed_message_list: A PackedMessageList rdfvalue with some data in it. Returns: a MessageList rdfvalue. Raises: DecodingError: If decompression fails. def DecompressMessageList(cls, packed_message_list): """Decompress the...
Extract and verify server message. Args: response_comms: A ClientCommunication rdfvalue Returns: list of messages and the CN where they came from. Raises: DecryptionError: If the message failed to decrypt properly. def DecodeMessages(self, response_comms): """Extract and verify...
Verify the message list signature. This is the way the messages are verified in the client. In the client we also check that the nonce returned by the server is correct (the timestamp doubles as a nonce). If the nonce fails we deem the response unauthenticated since it might have resulted from a repla...
Registers a callback to be invoked when the RDFValue named is declared. def RegisterLateBindingCallback(target_name, callback, **kwargs): """Registers a callback to be invoked when the RDFValue named is declared.""" _LATE_BINDING_STORE.setdefault(target_name, []).append((callback, kwargs))
Parse a human readable string of a byte string. Args: string: The string to parse. Raises: DecodeError: If the string can not be parsed. def ParseFromHumanReadable(self, string): """Parse a human readable string of a byte string. Args: string: The string to parse. Raises: ...
Should this job be filtered. Args: launchditem: job NSCFDictionary Returns: True if the item should be filtered (dropped) def FilterItem(self, launchditem): """Should this job be filtered. Args: launchditem: job NSCFDictionary Returns: True if the item should be filtered (...
Convert persistence collector output to downloadable rdfvalues. def Parse(self, persistence, knowledge_base, download_pathtype): """Convert persistence collector output to downloadable rdfvalues.""" pathspecs = [] if isinstance(persistence, rdf_client.OSXServiceInformation): if persistence.program: ...
Trims a given list so that it is not longer than given limit. Args: lst: A list to trim. limit: A maximum number of elements in the list after trimming. Returns: A suffix of the input list that was trimmed. def Trim(lst, limit): """Trims a given list so that it is not longer than given limit. Ar...
Groups items by given key function. Args: items: An iterable or an iterator of items. key: A function which given each item will return the key. Returns: A dict with keys being each unique key and values being a list of items of that key. def Group(items, key): """Groups items by given key func...
Divide items into batches of specified size. In case where number of items is not evenly divisible by the batch size, the last batch is going to be shorter. Args: items: An iterable or an iterator of items. size: A size of the returned batches. Yields: Lists of items with specified size. def Bat...
Checks whether an items of one iterable are a prefix of another. Args: this: An iterable that needs to be checked. that: An iterable of which items must match the prefix of `this`. Returns: `True` if `that` is a prefix of `this`, `False` otherwise. def StartsWith(this, that): """Checks whether an i...
Unzips specified iterable of pairs to pair of two iterables. This function is an inversion of the standard `zip` function and the following hold: * ∀ l, r. l, r == unzip(zip(l, r)) * ∀ p. p == zip(unzip(p)) Examples: >>> Unzip([("foo", 1), ("bar", 2), ("baz", 3)]) (["foo", "bar", "baz"], [1, 2,...
Computes a cartesian product of dict with iterable values. This utility function, accepts a dictionary with iterable values, computes cartesian products of these values and yields dictionaries of expanded values. Examples: >>> list(DictProduct({"a": [1, 2], "b": [3, 4]})) [{"a": 1, "b": 3}, {"a": 1, "b"...
Main. def main(argv): """Main.""" del argv # Unused. if flags.FLAGS.version: print("GRR console {}".format(config_server.VERSION["packageversion"])) return banner = ("\nWelcome to the GRR console\n") config.CONFIG.AddContext(contexts.COMMAND_LINE_CONTEXT) config.CONFIG.AddContext(contexts.CONSO...
Encapsulates an argument in a tuple, if it's not already iterable. def AsIter(arg): """Encapsulates an argument in a tuple, if it's not already iterable.""" if isinstance(arg, string_types): rslt = [arg] elif isinstance(arg, collections.Iterable): rslt = arg elif not arg: rslt = [] else: rslt...
Generate the lexer states. def _GenStates(self): """Generate the lexer states.""" self.GenCommentState() self.GenFwdState() self.GenQuotedState() self.GenCatchallState()
Generates forwarding state rules. The lexer will fast forward until there is string content. The string content will be returned to the string processor. def GenFwdState(self): """Generates forwarding state rules. The lexer will fast forward until there is string content. The string content will ...
Generate string matching state rules. def GenQuotedState(self): """Generate string matching state rules.""" for i, q in enumerate(self.quot): label = "%s_STRING" % i escaped = re.escape(q) self._AddToken(label, escaped, "PopState", None) self._AddToken(label, q, "PopState", None) ...
Generate string matching state rules. This sets up initial state handlers that cover both the 'INITIAL' state and the intermediate content between fields. The lexer acts on items with precedence: - continuation characters: use the fast forward state rules. - field separators: finalize processi...
Extracts keyword/value settings from the sshd config. The keyword is always the first string item. Values are the remainder of the string. In cases where an sshd config allows multiple values, these are split according to whatever separator(s) sshd_config permits for that value. Keywords and value...
Adds an entry for a configuration setting. Args: key: The name of the setting. val: The value of the setting. def _ParseEntry(self, key, val): """Adds an entry for a configuration setting. Args: key: The name of the setting. val: The value of the setting. """ if key in sel...
Adds valid match group parameters to the configuration. def _ParseMatchGrp(self, key, val): """Adds valid match group parameters to the configuration.""" if key in self._match_keywords: self._ParseEntry(key, val)
Create a new configuration section for each match clause. Each match clause is added to the main config, and the criterion that will trigger the match is recorded, as is the configuration. Args: val: The value following the 'match' keyword. def _NewMatchSection(self, val): """Create a new confi...
Parse the sshd configuration. Process each of the lines in the configuration file. Assembes an sshd_config file into a dictionary with the configuration keyword as the key, and the configuration settings as value(s). Args: stat: unused file_object: An open configuration file object. ...
Parse the mount command output. def Parse(self, cmd, args, stdout, stderr, return_val, time_taken, knowledge_base): """Parse the mount command output.""" _ = stderr, time_taken, args, knowledge_base # Unused. self.CheckReturn(cmd, return_val) result = rdf_protodict.AttributedDict() for...
Extract log configuration data from rsyslog actions. Actions have the format: <facility>/<severity> <type_def><destination>;<template> e.g. *.* @@loghost.example.com.:514;RSYSLOG_ForwardFormat Actions are selected by a type definition. These include: "@@": TCP syslog "@": UDP syslog ...
Parse key/value formatted source listing and return potential URLs. The fundamental shape of this format is as follows: key: value # here : = separator key : value URI: [URL] # here URI = uri_key [URL] # this is where it becomes trickey because [URL] [URL] # can contain 'separ...