INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Drop all the information about given objects. | def MultiDelete(self, urns, token=None):
"""Drop all the information about given objects.
DANGEROUS! This recursively deletes all objects contained within the
specified URN.
Args:
urns: Urns of objects to remove.
token: The Security Token to use for opening this item.
Raises:
Va... |
Lists bunch of directories efficiently. | def MultiListChildren(self, urns, limit=None, age=NEWEST_TIME):
"""Lists bunch of directories efficiently.
Args:
urns: List of urns to list children.
limit: Max number of children to list (NOTE: this is per urn).
age: The age of the items to retrieve. Should be one of ALL_TIMES,
NEWES... |
Lists bunch of directories efficiently. | def ListChildren(self, urn, limit=None, age=NEWEST_TIME):
"""Lists bunch of directories efficiently.
Args:
urn: Urn to list children.
limit: Max number of children to list.
age: The age of the items to retrieve. Should be one of ALL_TIMES,
NEWEST_TIME or a range.
Returns:
R... |
Recursively lists bunch of directories. | def RecursiveMultiListChildren(self, urns, limit=None, age=NEWEST_TIME):
"""Recursively lists bunch of directories.
Args:
urns: List of urns to list children.
limit: Max number of children to list (NOTE: this is per urn).
age: The age of the items to retrieve. Should be one of ALL_TIMES,
... |
Return a copy without registering in the attribute registry. | def Copy(self):
"""Return a copy without registering in the attribute registry."""
return Attribute(
self.predicate,
self.attribute_type,
self.description,
self.name,
_copy=True) |
Returns this attribute s RDFValue class. | def GetRDFValueType(self):
"""Returns this attribute's RDFValue class."""
result = self.attribute_type
for field_name in self.field_names:
# Support the new semantic protobufs.
try:
result = result.type_infos.get(field_name).type
except AttributeError:
raise AttributeError(... |
Gets all the subfields indicated by field_names. | def GetSubFields(self, fd, field_names):
"""Gets all the subfields indicated by field_names.
This resolves specifications like "Users.special_folders.app_data" where for
each entry in the Users protobuf the corresponding app_data folder entry
should be returned.
Args:
fd: The base RDFValue o... |
Return the values for this attribute as stored in an AFF4Object. | def GetValues(self, fd):
"""Return the values for this attribute as stored in an AFF4Object."""
result = None
for result in fd.new_attributes.get(self, []):
# We need to interpolate sub fields in this rdfvalue.
if self.field_names:
for x in self.GetSubFields(result, self.field_names):
... |
Returns a default attribute if it is not set. | def GetDefault(self, fd=None, default=None):
"""Returns a default attribute if it is not set."""
if callable(self.default):
return self.default(fd)
if self.default is not None:
# We can't return mutable objects here or the default might change for all
# objects of this class.
if isi... |
Given a serialized value decode the attribute. | def DecodeValueFromAttribute(self, attribute_name, value, ts):
"""Given a serialized value, decode the attribute.
Only attributes which have been previously defined are permitted.
Args:
attribute_name: The string name of the attribute.
value: The serialized attribute value.
ts: The ti... |
Helper to add a new attribute to a cache. | def _AddAttributeToCache(self, attribute_name, value, cache):
"""Helper to add a new attribute to a cache."""
# If there's another value in cache with the same timestamp, the last added
# one takes precedence. This helps a lot in tests that use FakeTime.
attribute_list = cache.setdefault(attribute_name,... |
Updates the lease and flushes the object. | def UpdateLease(self, duration):
"""Updates the lease and flushes the object.
The lease is set to expire after the "duration" time from the present
moment.
This method is supposed to be used when operation that requires locking
may run for a time that exceeds the lease time specified in OpenWithLoc... |
Syncs this object with the data store maintaining object validity. | def Flush(self):
"""Syncs this object with the data store, maintaining object validity."""
if self.locked and self.CheckLease() == 0:
self._RaiseLockError("Flush")
self._WriteAttributes()
self._SyncAttributes()
if self.parent:
self.parent.Flush() |
Close and destroy the object. | def Close(self):
"""Close and destroy the object.
This is similar to Flush, but does not maintain object validity. Hence the
object should not be interacted with after Close().
Raises:
LockError: The lease for this object has expired.
"""
if self.locked and self.CheckLease() == 0:
... |
Write the dirty attributes to the data store. | def _WriteAttributes(self):
"""Write the dirty attributes to the data store."""
# If the object is not opened for writing we do not need to flush it to the
# data_store.
if "w" not in self.mode:
return
if self.urn is None:
raise ValueError("Storing of anonymous AFF4 objects not supporte... |
Sync the new attributes to the synced attribute cache. | def _SyncAttributes(self):
"""Sync the new attributes to the synced attribute cache.
This maintains object validity.
"""
# This effectively moves all the values from the new_attributes to the
# synced_attributes caches.
for attribute, value_array in iteritems(self.new_attributes):
if not ... |
Check that the value is of the expected type. | def _CheckAttribute(self, attribute, value):
"""Check that the value is of the expected type.
Args:
attribute: An instance of Attribute().
value: An instance of RDFValue.
Raises:
ValueError: when the value is not of the expected type.
AttributeError: When the attribute is not o... |
Add an additional attribute to this object. | def AddAttribute(self, attribute, value=None, age=None):
"""Add an additional attribute to this object.
If value is None, attribute is expected to be already initialized with a
value. For example:
fd.AddAttribute(fd.Schema.CONTAINS("some data"))
Args:
attribute: The attribute name or an RD... |
Clears the attribute from this object. | def DeleteAttribute(self, attribute):
"""Clears the attribute from this object."""
if "w" not in self.mode:
raise IOError("Deleting attribute %s from read only object." % attribute)
# Check if this object should be locked in order to delete the attribute.
# NOTE: We don't care about locking when ... |
Gets the attribute from this object. | def Get(self, attribute, default=None):
"""Gets the attribute from this object."""
if attribute is None:
return default
# Allow the user to specify the attribute by name.
elif isinstance(attribute, str):
attribute = Attribute.GetAttributeByName(attribute)
# We can't read attributes fro... |
Returns a list of values from this attribute. | def GetValuesForAttribute(self, attribute, only_one=False):
"""Returns a list of values from this attribute."""
if not only_one and self.age_policy == NEWEST_TIME:
raise ValueError("Attempting to read all attribute versions for an "
"object opened for NEWEST_TIME. This is probably "... |
Upgrades this object to the type specified. | def Upgrade(self, aff4_class):
"""Upgrades this object to the type specified.
AFF4 Objects can be upgraded on the fly to other type - As long as the new
type is derived from the current type. This feature allows creation of
placeholder objects which can later be upgraded to the fully featured
objec... |
Add labels to the AFF4Object. | def AddLabels(self, labels_names, owner=None):
"""Add labels to the AFF4Object."""
if owner is None and not self.token:
raise ValueError("Can't set label: No owner specified and "
"no access token available.")
if isinstance(labels_names, string_types):
raise ValueError("La... |
Remove specified labels from the AFF4Object. | def RemoveLabels(self, labels_names, owner=None):
"""Remove specified labels from the AFF4Object."""
if owner is None and not self.token:
raise ValueError("Can't remove label: No owner specified and "
"no access token available.")
if isinstance(labels_names, string_types):
... |
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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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... |
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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.