INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
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.network_bytes_limit: remaining_netw...
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 _CallFlowLegacy(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. ...
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 _CallFlowRelational(self, flow_name=None, args=None, runner_args=None, client_id=None, **kwargs): """Creates a new flow and send its responses to a state. This creates a new flo...
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...
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 while running in this method. if request.next_state == "Ad...
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: format_str: Format string *args: arguments to the format string Raises: RuntimeError: on parent missing logs_collection """ format_str = utils.SmartUnicode(format_str) status = 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, duration=args.expiry_time, start_time...
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. Returns: a formatted session id string. """ return rdfvalue.SessionID(base="aff4:/hunts", queue=self.runner_args.queue)
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. self.context.duration = self.runner_args.expiry_time # When the...
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(), expiration_time=self.context.init_...
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( "aff4:/foreman", mode="rw", token=self.token) as foreman: ...
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_obj.Flush() self._CreateAuditEvent("HUNT_PAUSED")
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("HUNT_STOPPED") if reason: notification_lib.Notify( ...
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...
def IsHuntStarted(self): """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 cli...
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...
def CallState(self, messages=None, next_state="", client_id=None, request_data=None, start_time=None): """This method is used to asynchronously schedule a new hunt state. The state will be invoked in a later time and receive all th...
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....
def StartClients(cls, hunt_id, client_ids, token=None): """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. ...
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 is stored in the hunt namespace, ...
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. status: The status object returned from the client. """ if hasattr(status, "child_session_id"): flow_path = status.child_session_id e...
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, "COMPLETED": completed, "OUTSTANDING": outstanding ...
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( client_group, mode="r", aff4_type=aff4_grr.VFS...
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, context=context), ...
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("GetClientApproval", args) return ClientApproval( ...
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: request.flow.runner_args.Cop...
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=self._context), items)
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 this client.""" if not reason: raise ValueError("reason...
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_utils.CreateCounterMetadata("grr_decryption_error"), stats_utils....
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.Encrypt(data)
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, comms=None): """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. Retur...
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 ...
def VerifyCipherSignature(self, remote_public_key): """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.Veri...
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 = uncompressed_data compressed_data = zlib.compress(uncomp...
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_public_key = self._GetRemotePublicKey(self.se...
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...
def EncodeMessages(self, message_list, result, destination=None, timestamp=None, api_version=3): """Accepts a list of messages and encodes for transmission. This function signs and then encrypts the payload...
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 encrypted string. Returns: a Packed_Message_List rdfvalue """ try: response_comms = rdf_flows.ClientCommunication.FromSerializedString( ...
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 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. """ com...
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 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. """ # Have ...
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...
def VerifyMessageSignature(self, unused_response_comms, packed_message_list, cipher, cipher_verified, api_version, remote_public_key): """Verify the message list signature. This is the way the messages are verified in the client. In the client we a...
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: DecodeError: If the string can not be parsed. """ if not string: return None match = self.REGEX.match(string.strip().lower()) if not ma...
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 (dropped) """ for regex in self.blacklist_regex: if regex.match(launchditem.get("Label", "")): return True return False
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: pathspecs = rdf_paths.PathSpec( path=persiste...
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. 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. """ limit = max(0, limit) clipping = lst[limit:] del lst[li...
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 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. """ result = {} for item...
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 Batch(items, size): """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 ...
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 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. """ this_iter = ...
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,...
def Unzip(iterable): """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)]) (["f...
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"...
def DictProduct(dictionary): """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]})) ...
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.CONSOLE_CONT...
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 = [arg] return tuple(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 be returned to the string processor. """ for c in self.cont: self._AddToken("FWD", c, None, None) for s in self.sep: self._AddToken("FWD", s...
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) if self.ml_quote: self._AddToke...
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...
def GenCatchallState(self): """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. - ...
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...
def ParseLine(self, line): """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 t...
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 self._repeated: setting = self.section.setdefault(key, []) setting.extend(val) else: self.section.setdefault(...
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 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. """ section...
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. ...
def Parse(self, stat, file_object, knowledge_base): """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 ...
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 entry in self._field_parser.Pars...
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 ...
def ParseAction(self, action): """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: "@@...
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...
def ParseURIFromKeyValues(self, data, separator, uri_key): """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 b...
Given a file, this will return all potenial APT source URIs.
def FindPotentialURIs(self, file_obj): """Given a file, this will return all potenial APT source URIs.""" rfc822_format = "" # will contain all lines not in legacy format uris_to_parse = [] for line in utils.ReadFileBytesAsUnicode(file_obj).splitlines(True): # check if legacy style line - if it ...
Extracts keyword/value settings from the ntpd config. The keyword is always the first entry item. Values are the remainder of the entries. In cases where an ntpd config allows multiple values, these are split according to whitespace or duplicate entries. Keywords and values are normalized. Keyword...
def ParseLine(self, entries): """Extracts keyword/value settings from the ntpd config. The keyword is always the first entry item. Values are the remainder of the entries. In cases where an ntpd config allows multiple values, these are split according to whitespace or duplicate entries. Keywor...
Parse a ntp config into rdf.
def Parse(self, stat, file_object, knowledge_base): """Parse a ntp config into rdf.""" _, _ = stat, knowledge_base # TODO(hanuszczak): This parser only allows single use because it messes # with its state. This should be fixed. field_parser = NtpdFieldParser() for line in field_parser.ParseEntr...
Extract a list from the given fields.
def _ExtractList(self, fields, ignores=(",",), terminators=()): """Extract a list from the given fields.""" extracted = [] i = 0 for i, field in enumerate(fields): # Space-separated comma; ignore, but this is not a finished list. # Similar for any other specified ignores (eg, equals sign). ...
Parse an entry and add it to the given SudoersConfig rdfvalue.
def ParseSudoersEntry(self, entry, sudoers_config): """Parse an entry and add it to the given SudoersConfig rdfvalue.""" key = entry[0] if key in SudoersFieldParser.ALIAS_TYPES: # Alias. alias_entry = rdf_config_file.SudoersAlias( type=SudoersFieldParser.ALIAS_TYPES.get(key), name=ent...
Preprocess the given data, ready for parsing.
def Preprocess(self, data): """Preprocess the given data, ready for parsing.""" # Add whitespace to line continuations. data = data.replace(":\\", ": \\") # Strip comments manually because sudoers has multiple meanings for '#'. data = SudoersFieldParser.COMMENTS_RE.sub("", data) return data
Validate an RDFValue instance. Args: value: An RDFValue instance or something which may be used to instantiate the correct instance. Raises: TypeValueError: If the value is not a valid RDFValue instance or the required type. Returns: A Valid RDFValue instance.
def Validate(self, value): """Validate an RDFValue instance. Args: value: An RDFValue instance or something which may be used to instantiate the correct instance. Raises: TypeValueError: If the value is not a valid RDFValue instance or the required type. Returns: A V...
Validate the value. Args: value: Value is expected to be a dict-like object that a given RDFStruct can be initialized from. Raises: TypeValueError: If the value is not a valid dict-like object that a given RDFStruct can be initialized from. Returns: A valid instance of s...
def Validate(self, value): """Validate the value. Args: value: Value is expected to be a dict-like object that a given RDFStruct can be initialized from. Raises: TypeValueError: If the value is not a valid dict-like object that a given RDFStruct can be initialized from. Re...
Returns a copy of this set with a new element added.
def Add(self, other): """Returns a copy of this set with a new element added.""" new_descriptors = [] for desc in self.descriptors + other.descriptors: if desc not in new_descriptors: new_descriptors.append(desc) return TypeDescriptorSet(*new_descriptors)
Append the descriptor to this set.
def Append(self, desc): """Append the descriptor to this set.""" if desc not in self.descriptors: self.descriptors.append(desc) self.descriptor_map[desc.name] = desc self.descriptor_names.append(desc.name)
Returns a copy of this set without elements with given names.
def Remove(self, *descriptor_names): """Returns a copy of this set without elements with given names.""" new_descriptor_map = self.descriptor_map.copy() for name in descriptor_names: new_descriptor_map.pop(name, None) new_descriptors = [ desc for desc in self.descriptors if desc i...
Parse and validate the args. Note we pop all the args we consume here - so if there are any args we dont know about, args will not be an empty dict after this. This allows the same args to be parsed by several TypeDescriptorSets. Args: args: A dictionary of arguments that this TypeDescriptorSet ...
def ParseArgs(self, args): """Parse and validate the args. Note we pop all the args we consume here - so if there are any args we dont know about, args will not be an empty dict after this. This allows the same args to be parsed by several TypeDescriptorSets. Args: args: A dictionary of argu...
Parse a bool from a string.
def FromString(self, string): """Parse a bool from a string.""" if string.lower() in ("false", "no", "n"): return False if string.lower() in ("true", "yes", "y"): return True raise TypeValueError("%s is not recognized as a boolean value." % string)
Validate a potential list.
def Validate(self, value): """Validate a potential list.""" if isinstance(value, string_types): raise TypeValueError("Value must be an iterable not a string.") elif not isinstance(value, (list, tuple)): raise TypeValueError("%r not a valid List" % value) # Validate each value in the list v...
Adds all known parsers to the registry.
def Register(): """Adds all known parsers to the registry.""" # pyformat: disable # Command parsers. parsers.SINGLE_RESPONSE_PARSER_FACTORY.Register( "Dpkg", linux_cmd_parser.DpkgCmdParser) parsers.SINGLE_RESPONSE_PARSER_FACTORY.Register( "Dmidecode", linux_cmd_parser.DmidecodeCmdParser) parser...
Get the rdfurn of the current audit log.
def _CurrentAuditLog(): """Get the rdfurn of the current audit log.""" now_sec = rdfvalue.RDFDatetime.Now().AsSecondsSinceEpoch() rollover_seconds = AUDIT_ROLLOVER_TIME.seconds # This gives us a filename that only changes every # AUDIT_ROLLOVER_TIfilME seconds, but is still a valid timestamp. current_log = ...
Attempt to coerce string into a unicode object.
def UnicodeFromCodePage(string): """Attempt to coerce string into a unicode object.""" # get the current code page codepage = ctypes.windll.kernel32.GetOEMCP() try: return string.decode("cp%s" % codepage) except UnicodeError: try: return string.decode("utf16", "ignore") except UnicodeError: ...
Enumerate all MAC addresses of all NICs. Args: args: Unused. Yields: `rdf_client_network.Interface` instances.
def EnumerateInterfacesFromClient(args): """Enumerate all MAC addresses of all NICs. Args: args: Unused. Yields: `rdf_client_network.Interface` instances. """ del args # Unused. pythoncom.CoInitialize() for interface in (wmi.WMI().Win32_NetworkAdapterConfiguration() or []): addresses = [] ...
List all local filesystems mounted on this system.
def EnumerateFilesystemsFromClient(args): """List all local filesystems mounted on this system.""" del args # Unused. for drive in win32api.GetLogicalDriveStrings().split("\x00"): if not drive: continue try: volume = win32file.GetVolumeNameForVolumeMountPoint(drive).rstrip("\\") label,...
Query service and get its config.
def QueryService(svc_name): """Query service and get its config.""" hscm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS) result = None try: hs = win32serviceutil.SmartOpenService(hscm, svc_name, win32...
Run the WMI query and return the data.
def WmiQueryFromClient(args): """Run the WMI query and return the data.""" query = args.query base_object = args.base_object or r"winmgmts:\root\cimv2" if not query.upper().startswith("SELECT "): raise RuntimeError("Only SELECT WMI queries allowed.") for response_dict in RunWMIQuery(query, baseobj=base_...
Run a WMI query and return a result. Args: query: the WMI query to run. baseobj: the base object for the WMI query. Yields: rdf_protodict.Dicts containing key value pairs from the resulting COM objects.
def RunWMIQuery(query, baseobj=r"winmgmts:\root\cimv2"): """Run a WMI query and return a result. Args: query: the WMI query to run. baseobj: the base object for the WMI query. Yields: rdf_protodict.Dicts containing key value pairs from the resulting COM objects. """ pythoncom.CoInitialize() ...
Estimate the install date of this system.
def Run(self, unused_args): """Estimate the install date of this system.""" # Don't use winreg.KEY_WOW64_64KEY since it breaks on Windows 2000 subkey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows NT\\CurrentVersion", 0, winr...
This kills us with no cleanups.
def Run(self, unused_arg): """This kills us with no cleanups.""" logging.debug("Disabling service") win32serviceutil.ChangeServiceConfig( None, config.CONFIG["Nanny.service_name"], startType=win32service.SERVICE_DISABLED) svc_config = QueryService(config.CONFIG["Nanny.service_na...
This calls the Windows OpenKeyEx function in a Unicode safe way.
def OpenKey(key, sub_key): """This calls the Windows OpenKeyEx function in a Unicode safe way.""" regopenkeyex = advapi32["RegOpenKeyExW"] regopenkeyex.restype = ctypes.c_long regopenkeyex.argtypes = [ ctypes.c_void_p, ctypes.c_wchar_p, ctypes.c_ulong, ctypes.c_ulong, ctypes.POINTER(ctypes.c_void_p)...
This calls the Windows RegQueryInfoKey function in a Unicode safe way.
def QueryInfoKey(key): """This calls the Windows RegQueryInfoKey function in a Unicode safe way.""" regqueryinfokey = advapi32["RegQueryInfoKeyW"] regqueryinfokey.restype = ctypes.c_long regqueryinfokey.argtypes = [ ctypes.c_void_p, ctypes.c_wchar_p, LPDWORD, LPDWORD, LPDWORD, LPDWORD, LPDWORD, LPDW...
This calls the Windows QueryValueEx function in a Unicode safe way.
def QueryValueEx(key, value_name): """This calls the Windows QueryValueEx function in a Unicode safe way.""" regqueryvalueex = advapi32["RegQueryValueExW"] regqueryvalueex.restype = ctypes.c_long regqueryvalueex.argtypes = [ ctypes.c_void_p, ctypes.c_wchar_p, LPDWORD, LPDWORD, LPBYTE, LPDWORD ] size ...
This calls the Windows RegEnumKeyEx function in a Unicode safe way.
def EnumKey(key, index): """This calls the Windows RegEnumKeyEx function in a Unicode safe way.""" regenumkeyex = advapi32["RegEnumKeyExW"] regenumkeyex.restype = ctypes.c_long regenumkeyex.argtypes = [ ctypes.c_void_p, ctypes.wintypes.DWORD, ctypes.c_wchar_p, LPDWORD, LPDWORD, ctypes.c_wchar_p, LPD...
This calls the Windows RegEnumValue function in a Unicode safe way.
def EnumValue(key, index): """This calls the Windows RegEnumValue function in a Unicode safe way.""" regenumvalue = advapi32["RegEnumValueW"] regenumvalue.restype = ctypes.c_long regenumvalue.argtypes = [ ctypes.c_void_p, ctypes.wintypes.DWORD, ctypes.c_wchar_p, LPDWORD, LPDWORD, LPDWORD, LPBYTE, LP...