INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Checks that attribute is a valid Attribute() instance.
def SetAttribute(self, attribute): """Checks that attribute is a valid Attribute() instance.""" # Grab the attribute registered for this name self.attribute = attribute self.attribute_obj = Attribute.GetAttributeByName(attribute) if self.attribute_obj is None: raise lexer.ParseError("Attribute...
Sets the operator for this expression.
def SetOperator(self, operator): """Sets the operator for this expression.""" self.operator = operator # Find the appropriate list of operators for this attribute attribute_type = self.attribute_obj.GetRDFValueType() operators = attribute_type.operators # Do we have such an operator? self.n...
Returns the data_store filter implementation from the attribute.
def Compile(self, filter_implemention): """Returns the data_store filter implementation from the attribute.""" return self.operator_method(self.attribute_obj, filter_implemention, *self.args)
Yields RDFURNs of all the children of this object. Args: limit: Total number of items we will attempt to retrieve. age: The age of the items to retrieve. Should be one of ALL_TIMES, NEWEST_TIME or a range in microseconds. Yields: RDFURNs instances of each child.
def ListChildren(self, limit=None, age=NEWEST_TIME): """Yields RDFURNs of all the children of this object. Args: limit: Total number of items we will attempt to retrieve. age: The age of the items to retrieve. Should be one of ALL_TIMES, NEWEST_TIME or a range in microseconds. Yields: ...
Yields AFF4 Objects of all our direct children. This method efficiently returns all attributes for our children directly, in a few data store round trips. We use the directory indexes to query the data store. Args: children: A list of children RDFURNs to open. If None open all our childr...
def OpenChildren(self, children=None, mode="r", limit=None, chunk_limit=100000, age=NEWEST_TIME): """Yields AFF4 Objects of all our direct children. This method efficiently returns all attributes for our children dir...
Returns a pathspec for an aff4 object even if there is none stored.
def real_pathspec(self): """Returns a pathspec for an aff4 object even if there is none stored.""" pathspec = self.Get(self.Schema.PATHSPEC) stripped_components = [] parent = self # TODO(user): this code is potentially slow due to multiple separate # aff4.FACTORY.Open() calls. OTOH the loop be...
Method overriden by subclasses to optimize the MultiStream behavior.
def _MultiStream(cls, fds): """Method overriden by subclasses to optimize the MultiStream behavior.""" for fd in fds: fd.Seek(0) while True: chunk = fd.Read(cls.MULTI_STREAM_CHUNK_SIZE) if not chunk: break yield fd, chunk, None
Effectively streams data from multiple opened AFF4Stream objects. Args: fds: A list of opened AFF4Stream (or AFF4Stream descendants) objects. Yields: Tuples (chunk, fd) where chunk is a binary blob of data and fd is an object from the fds argument. Chunks within one file are not shuffled: ...
def MultiStream(cls, fds): """Effectively streams data from multiple opened AFF4Stream objects. Args: fds: A list of opened AFF4Stream (or AFF4Stream descendants) objects. Yields: Tuples (chunk, fd) where chunk is a binary blob of data and fd is an object from the fds argument. Chunks wi...
Try to load the data from the store.
def Initialize(self): """Try to load the data from the store.""" super(AFF4MemoryStreamBase, self).Initialize() contents = b"" if "r" in self.mode: contents = self.Get(self.Schema.CONTENT).AsBytes() try: if contents is not None: contents = zlib.decompress(contents) e...
Directly overwrite the current contents. Replaces the data currently in the stream with compressed_data, and closes the object. Makes it possible to avoid recompressing the data. Args: compressed_data: The data to write, must be zlib compressed. size: The uncompressed size of the data.
def OverwriteAndClose(self, compressed_data, size): """Directly overwrite the current contents. Replaces the data currently in the stream with compressed_data, and closes the object. Makes it possible to avoid recompressing the data. Args: compressed_data: The data to write, must be zlib comp...
Effectively streams data from multiple opened AFF4ImageBase objects. Args: fds: A list of opened AFF4Stream (or AFF4Stream descendants) objects. Yields: Tuples (chunk, fd, exception) where chunk is a binary blob of data and fd is an object from the fds argument. If one or more chunks ...
def _MultiStream(cls, fds): """Effectively streams data from multiple opened AFF4ImageBase objects. Args: fds: A list of opened AFF4Stream (or AFF4Stream descendants) objects. Yields: Tuples (chunk, fd, exception) where chunk is a binary blob of data and fd is an object from the fds argu...
Build a cache for our chunks.
def Initialize(self): """Build a cache for our chunks.""" super(AFF4ImageBase, self).Initialize() self.offset = 0 # A cache for segments. self.chunk_cache = ChunkCache(self._WriteChunk, 100) if "r" in self.mode: self.size = int(self.Get(self.Schema.SIZE)) # pylint: disable=protected...
Read as much as possible, but not more than length.
def _ReadPartial(self, length): """Read as much as possible, but not more than length.""" chunk = self.offset // self.chunksize chunk_offset = self.offset % self.chunksize available_to_read = min(length, self.chunksize - chunk_offset) retries = 0 while retries < self.NUM_RETRIES: fd = se...
Read a block of data from the file.
def Read(self, length): """Read a block of data from the file.""" result = b"" # The total available size in the file length = int(length) length = min(length, self.size - self.offset) while length > 0: data = self._ReadPartial(length) if not data: break length -= le...
Writes at most one chunk of data.
def _WritePartial(self, data): """Writes at most one chunk of data.""" chunk = self.offset // self.chunksize chunk_offset = self.offset % self.chunksize data = utils.SmartStr(data) available_to_write = min(len(data), self.chunksize - chunk_offset) fd = self._GetChunkForWriting(chunk) fd.s...
Sync the chunk cache to storage.
def Flush(self): """Sync the chunk cache to storage.""" if self._dirty: self.Set(self.Schema.SIZE(self.size)) if self.content_last is not None: self.Set(self.Schema.CONTENT_LAST, self.content_last) # Flushing the cache will write all chunks to the blob store. self.chunk_cache.Flush(...
Encode the value for the attribute.
def Encode(self, attribute, value): """Encode the value for the attribute.""" required_type = self._attribute_types.get(attribute, "bytes") if required_type == "integer": return rdf_structs.SignedVarintEncode(int(value)) elif required_type == "unsigned_integer": return rdf_structs.VarintEnc...
Decode the value to the required type.
def Decode(self, attribute, value): """Decode the value to the required type.""" required_type = self._attribute_types.get(attribute, "bytes") if required_type == "integer": return rdf_structs.SignedVarintReader(value, 0)[0] elif required_type == "unsigned_integer": return rdf_structs.Varint...
Cleans up old hunt data from aff4.
def CleanAff4Hunts(self): """Cleans up old hunt data from aff4.""" hunts_ttl = config.CONFIG["DataRetention.hunts_ttl"] if not hunts_ttl: self.Log("TTL not set - nothing to do...") return exception_label = config.CONFIG["DataRetention.hunts_ttl_exception_label"] hunts_root = aff4.FACT...
Cleans up old cron job data.
def Start(self): """Cleans up old cron job data.""" cron_jobs_ttl = config.CONFIG["DataRetention.cron_jobs_flows_ttl"] if not cron_jobs_ttl: self.Log("TTL not set - nothing to do...") return manager = aff4_cronjobs.GetCronManager() cutoff_timestamp = rdfvalue.RDFDatetime.Now() - cron_jo...
Cleans up old client data from aff4.
def CleanAff4Clients(self): """Cleans up old client data from aff4.""" inactive_client_ttl = config.CONFIG["DataRetention.inactive_client_ttl"] if not inactive_client_ttl: self.Log("TTL not set - nothing to do...") return exception_label = config.CONFIG[ "DataRetention.inactive_cli...
Does basic token validation. Args: token: User's credentials as access_control.ACLToken. targets: List of targets that were meant to be accessed by the token. This is used for logging purposes only. Returns: True if token is valid. Raises: access_control.UnauthorizedAccess: if token is no...
def ValidateToken(token, targets): """Does basic token validation. Args: token: User's credentials as access_control.ACLToken. targets: List of targets that were meant to be accessed by the token. This is used for logging purposes only. Returns: True if token is valid. Raises: access_co...
Does basic requested access validation. Args: requested_access: String consisting or 'r', 'w' and 'q' characters. subjects: A list of subjects that are about to be accessed with a given requested_access. Used for logging purposes only. Returns: True if requested_access is valid. Raises: a...
def ValidateAccessAndSubjects(requested_access, subjects): """Does basic requested access validation. Args: requested_access: String consisting or 'r', 'w' and 'q' characters. subjects: A list of subjects that are about to be accessed with a given requested_access. Used for logging purposes only. ...
Verify that the username has all the authorized_labels set.
def CheckUserForLabels(username, authorized_labels, token=None): """Verify that the username has all the authorized_labels set.""" authorized_labels = set(authorized_labels) try: user = aff4.FACTORY.Open( "aff4:/users/%s" % username, aff4_type=aff4_users.GRRUser, token=token) # Only return if al...
Checks if flow can be started on a particular client. Only flows with a category can bestarted. Having a category means that the flow will be accessible from the UI. Args: flow_name: Name of the flow to check access for. Returns: True if flow is externally accessible. Raises: access_control.Una...
def CheckFlowCanBeStartedOnClient(flow_name): """Checks if flow can be started on a particular client. Only flows with a category can bestarted. Having a category means that the flow will be accessible from the UI. Args: flow_name: Name of the flow to check access for. Returns: True if flow is exte...
Checks if given path pattern fits the subject passed in constructor. Registers "allow" check in this helper. "Allow" check consists of fnmatch path pattern and optional "require" check. *args and *kwargs will be passed to the optional "require" check function. All registered "allow" checks are execute...
def Allow(self, path, require=None, *args, **kwargs): """Checks if given path pattern fits the subject passed in constructor. Registers "allow" check in this helper. "Allow" check consists of fnmatch path pattern and optional "require" check. *args and *kwargs will be passed to the optional "require" c...
Checks for access to given subject with a given token. CheckAccess runs given subject through all "allow" clauses that were previously registered with Allow() calls. It returns True on first match and raises access_control.UnauthorizedAccess if there are no matches or if any of the additional checks fa...
def CheckAccess(self, subject, token): """Checks for access to given subject with a given token. CheckAccess runs given subject through all "allow" clauses that were previously registered with Allow() calls. It returns True on first match and raises access_control.UnauthorizedAccess if there are no...
Checks if user has access to a client under given URN.
def _HasAccessToClient(self, subject, token): """Checks if user has access to a client under given URN.""" client_id, _ = rdfvalue.RDFURN(subject).Split(2) client_urn = rdf_client.ClientURN(client_id) return self.CheckClientAccess(token, client_urn)
Checks user access permissions for paths under aff4:/users.
def _IsHomeDir(self, subject, token): """Checks user access permissions for paths under aff4:/users.""" h = CheckAccessHelper("IsHomeDir") h.Allow("aff4:/users/%s" % token.username) h.Allow("aff4:/users/%s/*" % token.username) try: return h.CheckAccess(subject, token) except access_control...
Creates a CheckAccessHelper for controlling read access. This function and _CreateQueryAccessHelper essentially define GRR's ACL policy. Please refer to these 2 functions to either review or modify GRR's ACLs. Read access gives you the ability to open and read aff4 objects for which you already ha...
def _CreateReadAccessHelper(self): """Creates a CheckAccessHelper for controlling read access. This function and _CreateQueryAccessHelper essentially define GRR's ACL policy. Please refer to these 2 functions to either review or modify GRR's ACLs. Read access gives you the ability to open and read...
Creates a CheckAccessHelper for controlling query access. This function and _CreateReadAccessHelper essentially define GRR's ACL policy. Please refer to these 2 functions to either review or modify GRR's ACLs. Query access gives you the ability to find objects in the tree without knowing their URN...
def _CreateQueryAccessHelper(self): """Creates a CheckAccessHelper for controlling query access. This function and _CreateReadAccessHelper essentially define GRR's ACL policy. Please refer to these 2 functions to either review or modify GRR's ACLs. Query access gives you the ability to find object...
Allow all access if token and requested access are valid.
def CheckDataStoreAccess(self, token, subjects, requested_access="r"): """Allow all access if token and requested access are valid.""" if any(not x for x in subjects): raise ValueError("Subjects list can't contain empty URNs.") subjects = list(map(rdfvalue.RDFURN, subjects)) return (ValidateAcces...
Streams chunks of a given file starting at given offset. Args: filedesc: A `file` object to stream. offset: An integer offset at which the file stream should start on. amount: An upper bound on number of bytes to read. Returns: Generator over `Chunk` instances.
def StreamFile(self, filedesc, offset=0, amount=None): """Streams chunks of a given file starting at given offset. Args: filedesc: A `file` object to stream. offset: An integer offset at which the file stream should start on. amount: An upper bound on number of bytes to read. Returns: ...
Streams chunks of a file located at given path starting at given offset. Args: filepath: A path to the file to stream. offset: An integer offset at which the file stream should start on. amount: An upper bound on number of bytes to read. Yields: `Chunk` instances.
def StreamFilePath(self, filepath, offset=0, amount=None): """Streams chunks of a file located at given path starting at given offset. Args: filepath: A path to the file to stream. offset: An integer offset at which the file stream should start on. amount: An upper bound on number of bytes to...
Streams chunks of memory of a given process starting at given offset. Args: process: A platform-specific `Process` instance. offset: An integer offset at which the memory stream should start on. amount: An upper bound on number of bytes to read. Returns: Generator over `Chunk` instance...
def StreamMemory(self, process, offset=0, amount=None): """Streams chunks of memory of a given process starting at given offset. Args: process: A platform-specific `Process` instance. offset: An integer offset at which the memory stream should start on. amount: An upper bound on number of byt...
Streams chunks of a given file starting at given offset. Args: reader: A `Reader` instance. amount: An upper bound on number of bytes to read. Yields: `Chunk` instances.
def Stream(self, reader, amount=None): """Streams chunks of a given file starting at given offset. Args: reader: A `Reader` instance. amount: An upper bound on number of bytes to read. Yields: `Chunk` instances. """ if amount is None: amount = float("inf") data = reade...
Yields spans occurrences of a given pattern within the chunk. Only matches that span over regular (non-overlapped) chunk bytes are returned. Matches lying completely within the overlapped zone are ought to be returned by the previous chunk. Args: matcher: A `Matcher` instance corresponding to th...
def Scan(self, matcher): """Yields spans occurrences of a given pattern within the chunk. Only matches that span over regular (non-overlapped) chunk bytes are returned. Matches lying completely within the overlapped zone are ought to be returned by the previous chunk. Args: matcher: A `Match...
List all the filesystems mounted on the system.
def GetMountpoints(data=None): """List all the filesystems mounted on the system.""" expiry = 60 # 1 min insert_time = MOUNTPOINT_CACHE[0] if insert_time + expiry > time.time(): return MOUNTPOINT_CACHE[1] devices = {} # Check all the mounted filesystems. if data is None: data = "\n".join( ...
Executes commands on the client. This function is the only place where commands will be executed by the GRR client. This makes sure that all issued commands are compared to a white list and no malicious commands are issued on the client machine. Args: cmd: The command to be executed. args: List of arg...
def Execute(cmd, args, time_limit=-1, bypass_whitelist=False, daemon=False, use_client_context=False, cwd=None): """Executes commands on the client. This function is the only place where commands will be executed by the GRR client. This make...
Executes cmd.
def _Execute(cmd, args, time_limit=-1, use_client_context=False, cwd=None): """Executes cmd.""" run = [cmd] run.extend(args) env = os.environ.copy() if use_client_context: env.pop("LD_LIBRARY_PATH", None) env.pop("PYTHON_PATH", None) context = "client" else: context = "system" logging.info...
Check if a binary and args is whitelisted. Args: cmd: Canonical path to the binary. args: List of arguments to be passed to the binary. Returns: Bool, True if it is whitelisted. These whitelists could also go in the platform specific client files client_utils_<platform>.py. We chose to leave them...
def IsExecutionWhitelisted(cmd, args): """Check if a binary and args is whitelisted. Args: cmd: Canonical path to the binary. args: List of arguments to be passed to the binary. Returns: Bool, True if it is whitelisted. These whitelists could also go in the platform specific client files client...
Updates underlying hashers with file on a given path. Args: path: A path to the file that is going to be fed to the hashers. byte_count: A maximum numbers of bytes that are going to be processed.
def HashFilePath(self, path, byte_count): """Updates underlying hashers with file on a given path. Args: path: A path to the file that is going to be fed to the hashers. byte_count: A maximum numbers of bytes that are going to be processed. """ with open(path, "rb") as fd: self.HashFi...
Updates underlying hashers with a given file. Args: fd: A file object that is going to be fed to the hashers. byte_count: A maximum number of bytes that are going to be processed.
def HashFile(self, fd, byte_count): """Updates underlying hashers with a given file. Args: fd: A file object that is going to be fed to the hashers. byte_count: A maximum number of bytes that are going to be processed. """ while byte_count > 0: buf_size = min(byte_count, constants.CLI...
Updates underlying hashers with a given buffer. Args: buf: A byte buffer (string object) that is going to be fed to the hashers.
def HashBuffer(self, buf): """Updates underlying hashers with a given buffer. Args: buf: A byte buffer (string object) that is going to be fed to the hashers. """ for hasher in itervalues(self._hashers): hasher.update(buf) if self._progress: self._progress() self._bytes_r...
Returns a `Hash` object with appropriate fields filled-in.
def GetHashObject(self): """Returns a `Hash` object with appropriate fields filled-in.""" hash_object = rdf_crypto.Hash() hash_object.num_bytes = self._bytes_read for algorithm in self._hashers: setattr(hash_object, algorithm, self._hashers[algorithm].digest()) return hash_object
Get the set of all label names applied to all clients. Args: token: token to use when opening the index. include_catchall: If true, we include ALL_CLIENTS_LABEL in the results. Returns: set of label name strings, including the catchall "All"
def GetAllClientLabels(token, include_catchall=False): """Get the set of all label names applied to all clients. Args: token: token to use when opening the index. include_catchall: If true, we include ALL_CLIENTS_LABEL in the results. Returns: set of label name strings, including the catchall "All" ...
RDFDatetime at which the object was created.
def age(self): """RDFDatetime at which the object was created.""" # TODO(user) move up to AFF4Object after some analysis of how .age is # used in the codebase. aff4_type = self.Get(self.Schema.TYPE) if aff4_type: return aff4_type.age else: # If there is no type attribute yet, we hav...
Gets a client summary object. Returns: rdf_client.ClientSummary Raises: ValueError: on bad cloud type
def GetSummary(self): """Gets a client summary object. Returns: rdf_client.ClientSummary Raises: ValueError: on bad cloud type """ self.max_age = 0 summary = rdf_client.ClientSummary(client_id=self.urn) summary.system_info.system = self.Get(self.Schema.SYSTEM) summary.system...
Calls the Update() method of a given VFSFile/VFSDirectory object.
def Start(self): """Calls the Update() method of a given VFSFile/VFSDirectory object.""" self.Init() fd = aff4.FACTORY.Open(self.args.vfs_file_urn, mode="rw", token=self.token) # Account for implicit directories. if fd.Get(fd.Schema.TYPE) is None: fd = fd.Upgrade(standard.VFSDirectory) s...
Update an attribute from the client.
def Update(self, attribute=None): """Update an attribute from the client.""" # List the directory on the client currently_running = self.Get(self.Schema.CONTENT_LOCK) # Is this flow still active? if currently_running: flow_obj = aff4.FACTORY.Open(currently_running, token=self.token) if ...
Removes any rules with an expiration date in the past.
def ExpireRules(self): """Removes any rules with an expiration date in the past.""" rules = self.Get(self.Schema.RULES) new_rules = self.Schema.RULES() now = time.time() * 1e6 expired_session_ids = set() for rule in rules: if rule.expires > now: new_rules.Append(rule) else: ...
Will return True if hunt's task was assigned to this client before.
def _CheckIfHuntTaskWasAssigned(self, client_id, hunt_id): """Will return True if hunt's task was assigned to this client before.""" client_urn = rdfvalue.RDFURN(client_id) for _ in aff4.FACTORY.Stat([ client_urn.Add("flows/%s:hunt" % rdfvalue.RDFURN(hunt_id).Basename()) ]): return True ...
Run all the actions specified in the rule. Args: rule: Rule which actions are to be executed. client_id: Id of a client where rule's actions are to be executed. Returns: Number of actions started.
def _RunActions(self, rule, client_id): """Run all the actions specified in the rule. Args: rule: Rule which actions are to be executed. client_id: Id of a client where rule's actions are to be executed. Returns: Number of actions started. """ actions_count = 0 for action in...
Examines our rules and starts up flows based on the client. Args: client_id: Client id of the client for tasks to be assigned. Returns: Number of assigned tasks.
def AssignTasksToClient(self, client_id): """Examines our rules and starts up flows based on the client. Args: client_id: Client id of the client for tasks to be assigned. Returns: Number of assigned tasks. """ rules = self.Get(self.Schema.RULES) if not rules: return 0 i...
Open the delegate object.
def Initialize(self): """Open the delegate object.""" if "r" in self.mode: delegate = self.Get(self.Schema.DELEGATE) if delegate: self.delegate = aff4.FACTORY.Open( delegate, mode=self.mode, token=self.token, age=self.age_policy)
Effectively streams data from multiple opened BlobImage objects. Args: fds: A list of opened AFF4Stream (or AFF4Stream descendants) objects. Yields: Tuples (chunk, fd, exception) where chunk is a binary blob of data and fd is an object from the fds argument. If one or more chunks are ...
def _MultiStream(cls, fds): """Effectively streams data from multiple opened BlobImage objects. Args: fds: A list of opened AFF4Stream (or AFF4Stream descendants) objects. Yields: Tuples (chunk, fd, exception) where chunk is a binary blob of data and fd is an object from the fds argument...
Retrieve the relevant blob from the AFF4 data store or cache.
def _GetChunkForReading(self, chunk): """Retrieve the relevant blob from the AFF4 data store or cache.""" offset = chunk * self._HASH_SIZE self.index.seek(offset) chunk_name = self.index.read(self._HASH_SIZE) try: return self.chunk_cache.Get(chunk_name) except KeyError: pass #...
Create new blob hashes and append to BlobImage. We don't support writing at arbitrary file offsets, but this method provides a convenient way to add blobs for a new file, or append content to an existing one. Args: src_fd: source file handle open for read Raises: IOError: if blob has ...
def AppendContent(self, src_fd): """Create new blob hashes and append to BlobImage. We don't support writing at arbitrary file offsets, but this method provides a convenient way to add blobs for a new file, or append content to an existing one. Args: src_fd: source file handle open for read ...
Add another blob to this image using its hash. Once a blob is added that is smaller than the chunksize we finalize the file, since handling adding more blobs makes the code much more complex. Args: blob_id: rdf_objects.BlobID object. length: int length of blob Raises: IOError: if bl...
def AddBlob(self, blob_id, length): """Add another blob to this image using its hash. Once a blob is added that is smaller than the chunksize we finalize the file, since handling adding more blobs makes the code much more complex. Args: blob_id: rdf_objects.BlobID object. length: int lengt...
Alternate constructor for GRRSignedBlob. Creates a GRRSignedBlob from a content string by chunking it and signing each chunk. Args: content: The data to stored in the GRRSignedBlob. urn: The AFF4 URN to create. chunk_size: Data will be chunked into this size (each chunk is indiv...
def NewFromContent(cls, content, urn, chunk_size=1024, token=None, private_key=None, public_key=None): """Alternate constructor for GRRSignedBlob. Creates a GRRSignedBlob from a content...
Formats given pattern with this substitution environment. A pattern can contain placeholders for variables (`%%foo%%`) and scopes (`%%bar.baz%%`) that are replaced with concrete values in this substiution environment (specified in the constructor). Args: pattern: A pattern with placeholders to s...
def Substitute(self, pattern): """Formats given pattern with this substitution environment. A pattern can contain placeholders for variables (`%%foo%%`) and scopes (`%%bar.baz%%`) that are replaced with concrete values in this substiution environment (specified in the constructor). Args: pat...
Associates a value with given variable. This can be called multiple times to associate multiple values. Args: var_id: A variable id to bind the values to. value: A value to bind to the specified variable. Raises: KeyError: If given variable is not specified in the pattern.
def BindVar(self, var_id, value): """Associates a value with given variable. This can be called multiple times to associate multiple values. Args: var_id: A variable id to bind the values to. value: A value to bind to the specified variable. Raises: KeyError: If given variable is no...
Associates given values with given scope. This can be called multiple times to associate multiple values. Args: scope_id: A scope id to bind the values to. values: A mapping from scope variable ids to values to bind in scope. Raises: KeyError: If given scope or scope variable is not spe...
def BindScope(self, scope_id, values): """Associates given values with given scope. This can be called multiple times to associate multiple values. Args: scope_id: A scope id to bind the values to. values: A mapping from scope variable ids to values to bind in scope. Raises: KeyErro...
Interpolates the pattern. Yields: All possible interpolation results.
def Interpolate(self): """Interpolates the pattern. Yields: All possible interpolation results. """ for var_config in collection.DictProduct(self._var_bindings): for scope_config in collection.DictProduct(self._scope_bindings): subst = Substitution(var_config=var_config, scope_confi...
Registers a report plugin for use in the GRR UI.
def RegisterPlugin(self, report_plugin_cls): """Registers a report plugin for use in the GRR UI.""" name = report_plugin_cls.__name__ if name in self.plugins: raise RuntimeError("Can't register two report plugins with the same " "name. In particular, can't register the same "...
Create the executable template.
def MakeExecutableTemplate(self, output_file=None): """Create the executable template.""" super(DarwinClientBuilder, self).MakeExecutableTemplate(output_file=output_file) self.SetBuildVars() self.MakeBuildDirectory() self.BuildWithPyInstaller() self.CopyMissingModules() self.BuildI...
Add a zip to the end of the .xar containing build.yaml. The build.yaml is already inside the .xar file, but we can't easily open this on linux. To make repacking easier we add a zip to the end of the .xar and add in the build.yaml. The repack step will then look at the build.yaml and insert the config....
def MakeZip(self, xar_file, output_file): """Add a zip to the end of the .xar containing build.yaml. The build.yaml is already inside the .xar file, but we can't easily open this on linux. To make repacking easier we add a zip to the end of the .xar and add in the build.yaml. The repack step will then ...
Builds a package (.pkg) using PackageMaker.
def BuildInstallerPkg(self, output_file): """Builds a package (.pkg) using PackageMaker.""" self.CreateInstallDirs() self.InterpolateFiles() self.RenameGRRPyinstallerBinaries() self.SignGRRPyinstallerBinaries() self.WriteClientConfig() self.Set755Permissions() self.RunPkgBuild() self...
Returns a path-like String of client_path with optional prefix.
def _ClientPathToString(client_path, prefix=""): """Returns a path-like String of client_path with optional prefix.""" return os.path.join(prefix, client_path.client_id, client_path.vfs_path)
Generates description into a MANIFEST file in the archive.
def _GenerateDescription(self): """Generates description into a MANIFEST file in the archive.""" manifest = { "description": self.description, "processed_files": len(self.processed_files), "archived_files": len(self.archived_files), "ignored_files": len(self.ignored_files), ...
Yields chucks of archive information for given client.
def _GenerateClientInfo(self, client_id, client_fd): """Yields chucks of archive information for given client.""" summary_dict = client_fd.ToPrimitiveDict(stringify_leaf_fields=True) summary = yaml.Dump(summary_dict).encode("utf-8") client_info_path = os.path.join(self.prefix, client_id, "client_info.y...
Generates archive from a given collection. Iterates the collection and generates an archive by yielding contents of every referenced AFF4Stream. Args: items: Iterable of rdf_client_fs.StatEntry objects token: User's ACLToken. Yields: Binary chunks comprising the generated archive.
def Generate(self, items, token=None): """Generates archive from a given collection. Iterates the collection and generates an archive by yielding contents of every referenced AFF4Stream. Args: items: Iterable of rdf_client_fs.StatEntry objects token: User's ACLToken. Yields: Bin...
Yields binary chunks, respecting archive file headers and footers. Args: chunk: the StreamedFileChunk to be written
def _WriteFileChunk(self, chunk): """Yields binary chunks, respecting archive file headers and footers. Args: chunk: the StreamedFileChunk to be written """ if chunk.chunk_index == 0: # Make sure size of the original file is passed. It's required # when output_writer is StreamingTarWr...
Add type info definitions from an existing protobuf. We support building this class by copying definitions from an annotated protobuf using the semantic protobuf. This is ideal for interoperability with other languages and non-semantic protobuf implementations. In that case it might be easier to simply annotat...
def DefineFromProtobuf(cls, protobuf): """Add type info definitions from an existing protobuf. We support building this class by copying definitions from an annotated protobuf using the semantic protobuf. This is ideal for interoperability with other languages and non-semantic protobuf implementations. In that...
Sets up all the component in their own threads.
def main(argv): """Sets up all the component in their own threads.""" if flags.FLAGS.version: print("GRR server {}".format(config_server.VERSION["packageversion"])) return # We use .startswith so that multiple copies of services can easily be # created using systemd as worker1 worker2 ... worker25 etc...
Called when at a leaf value. Should yield a value.
def _AtLeaf(self, attr_value): """Called when at a leaf value. Should yield a value.""" if isinstance(attr_value, collections.Mapping): # If the result is a dict, return each key/value pair as a new dict. for k, v in iteritems(attr_value): yield {k: v} else: yield attr_value
Whether x is fully contained in y.
def Operation(self, x, y): """Whether x is fully contained in y.""" if x in y: return True # x might be an iterable # first we need to skip strings or we'll do silly things if isinstance(x, string_types) or isinstance(x, bytes): return False try: for value in x: if va...
Called when at a non-leaf value. Should recurse and yield values.
def _AtNonLeaf(self, attr_value, path): """Called when at a non-leaf value. Should recurse and yield values.""" try: if isinstance(attr_value, collections.Mapping): # If it's dictionary-like, treat the dict key as the attribute.. sub_obj = attr_value.get(path[1]) if len(path) > 2: ...
Compile the binary expression into a filter object.
def Compile(self, filter_implemention): """Compile the binary expression into a filter object.""" operator = self.operator.lower() if operator == "and" or operator == "&&": method = "AndFilter" elif operator == "or" or operator == "||": method = "OrFilter" else: raise ParseError("I...
Insert an arg to the current expression.
def InsertArg(self, string="", **_): """Insert an arg to the current expression.""" if self.state == "LIST_ARG": self.list_args.append(string) elif self.current_expression.AddArg(string): # This expression is complete self.stack.append(self.current_expression) self.current_expression...
Inserts a Float argument.
def InsertFloatArg(self, string="", **_): """Inserts a Float argument.""" try: float_value = float(string) return self.InsertArg(float_value) except (TypeError, ValueError): raise ParseError("%s is not a valid float." % string)
Inserts an Integer in base16 argument.
def InsertInt16Arg(self, string="", **_): """Inserts an Integer in base16 argument.""" try: int_value = int(string, 16) return self.InsertArg(int_value) except (TypeError, ValueError): raise ParseError("%s is not a valid base16 integer." % string)
Escape backslashes found inside a string quote. Backslashes followed by anything other than [\'"rnbt] will raise an Error. Args: string: The string that matched. match: The match object (m.group(1) is the escaped code) Raises: ParseError: For strings other than those used to define a re...
def StringEscape(self, string, match, **_): """Escape backslashes found inside a string quote. Backslashes followed by anything other than [\'"rnbt] will raise an Error. Args: string: The string that matched. match: The match object (m.group(1) is the escaped code) Raises: ParseErro...
Converts a hex escaped string.
def HexEscape(self, string, match, **_): """Converts a hex escaped string.""" hex_string = match.group(1) try: self.string += binascii.unhexlify(hex_string).decode("utf-8") # TODO: In Python 2 `binascii` throws `TypeError` for invalid # input values (for whathever reason). This behaviour is fi...
Generates a CSRF token based on a secret key, id and time.
def GenerateCSRFToken(user_id, time): """Generates a CSRF token based on a secret key, id and time.""" precondition.AssertType(user_id, Text) precondition.AssertOptionalType(time, int) time = time or rdfvalue.RDFDatetime.Now().AsMicrosecondsSinceEpoch() secret = config.CONFIG.Get("AdminUI.csrf_secret_key", ...
Decorator for WSGI handler that inserts CSRF cookie into response.
def StoreCSRFCookie(user, response): """Decorator for WSGI handler that inserts CSRF cookie into response.""" csrf_token = GenerateCSRFToken(user, None) response.set_cookie( "csrftoken", csrf_token, max_age=CSRF_TOKEN_DURATION.seconds)
Decorator for WSGI handler that checks CSRF cookie against the request.
def ValidateCSRFTokenOrRaise(request): """Decorator for WSGI handler that checks CSRF cookie against the request.""" # CSRF check doesn't make sense for GET/HEAD methods, because they can # (and are) used when downloading files through <a href> links - and # there's no way to set X-CSRFToken header in this cas...
Decorator that ensures that HTTP access is logged.
def LogAccessWrapper(func): """Decorator that ensures that HTTP access is logged.""" def Wrapper(request, *args, **kwargs): """Wrapping function.""" try: response = func(request, *args, **kwargs) server_logging.LOGGER.LogHttpAdminUIAccess(request, response) except Exception: # pylint: disa...
Build an ACLToken from the request.
def _BuildToken(self, request, execution_time): """Build an ACLToken from the request.""" token = access_control.ACLToken( username=request.user, reason=request.args.get("reason", ""), process="GRRAdminUI", expiry=rdfvalue.RDFDatetime.Now() + execution_time) for field in ["R...
Renders GRR home page by rendering base.html Jinja template.
def _HandleHomepage(self, request): """Renders GRR home page by rendering base.html Jinja template.""" _ = request env = jinja2.Environment( loader=jinja2.FileSystemLoader(config.CONFIG["AdminUI.template_root"]), autoescape=True) create_time = psutil.Process(os.getpid()).create_time()...
Handles API requests.
def _HandleApi(self, request): """Handles API requests.""" # Checks CSRF token. CSRF token cookie is updated when homepage is visited # or via GetPendingUserNotificationsCount API call. ValidateCSRFTokenOrRaise(request) response = http_api.RenderHttpResponse(request) # GetPendingUserNotificati...
Redirect to GitHub-hosted documentation.
def _RedirectToRemoteHelp(self, path): """Redirect to GitHub-hosted documentation.""" allowed_chars = set(string.ascii_letters + string.digits + "._-/") if not set(path) <= allowed_chars: raise RuntimeError("Unusual chars in path %r - " "possible exploit attempt." % path) ...
Handles help requests.
def _HandleHelp(self, request): """Handles help requests.""" help_path = request.path.split("/", 2)[-1] if not help_path: raise werkzeug_exceptions.Forbidden("Error: Invalid help path.") # Proxy remote documentation. return self._RedirectToRemoteHelp(help_path)
Returns GRR's WSGI handler.
def WSGIHandler(self): """Returns GRR's WSGI handler.""" sdm = werkzeug_wsgi.SharedDataMiddleware(self, { "/": config.CONFIG["AdminUI.document_root"], }) # Use DispatcherMiddleware to make sure that SharedDataMiddleware is not # used at all if the URL path doesn't start with "/static". This ...
Import the plugins once only.
def RunOnce(self): """Import the plugins once only.""" # pylint: disable=unused-variable,g-import-not-at-top from grr_response_server.gui import gui_plugins # pylint: enable=unused-variable,g-import-not-at-top if config.CONFIG.Get("AdminUI.django_secret_key", None): logging.warning( ...
Lists all registered Grr binaries.
def ListGrrBinaries(context=None): """Lists all registered Grr binaries.""" items = context.SendIteratorRequest("ListGrrBinaries", None) return utils.MapItemsIterator( lambda data: GrrBinary(data=data, context=context), items)
This function parses the RDFValue from the server. The Run method will be called with the specified RDFValue. Args: message: The GrrMessage that we are called to process. Returns: Upon return a callback will be called on the server to register the end of the function and pass back...
def Execute(self, message): """This function parses the RDFValue from the server. The Run method will be called with the specified RDFValue. Args: message: The GrrMessage that we are called to process. Returns: Upon return a callback will be called on the server to register th...
Set a status to report back to the server.
def SetStatus(self, status, message="", backtrace=None): """Set a status to report back to the server.""" self.status.status = status self.status.error_message = utils.SmartUnicode(message) if backtrace: self.status.backtrace = utils.SmartUnicode(backtrace)
Indicate progress of the client action. This function should be called periodically during client actions that do not finish instantly. It will notify the nanny that the action is not stuck and avoid the timeout and it will also check if the action has reached its cpu limit. Raises: CPUExcee...
def Progress(self): """Indicate progress of the client action. This function should be called periodically during client actions that do not finish instantly. It will notify the nanny that the action is not stuck and avoid the timeout and it will also check if the action has reached its cpu limit. ...
Send response back to the server.
def SendReply(self, rdf_value=None, session_id=None, message_type=rdf_flows.GrrMessage.Type.MESSAGE): """Send response back to the server.""" # TODO(hanuszczak): This is pretty bad. Here we assume that if the session # id is not none we are "replying" to a wel...