text stringlengths 81 112k |
|---|
Validates an AFF4 type.
def _ValidateAFF4Type(aff4_type):
"""Validates an AFF4 type."""
if aff4_type is None:
return
if not isinstance(aff4_type, type):
raise TypeError("aff4_type=%s must be a type" % aff4_type)
if not issubclass(aff4_type, AFF4Object):
raise TypeError("aff4_type=%s must be a subc... |
Opens the named object.
DeletionPool will only open the object if it's not in the pool already.
Otherwise it will just return the cached version. Objects are cached
based on their urn and mode. I.e. same object opened with mode="r" and
mode="rw" will be actually opened two times and cached separately.
... |
Opens many urns efficiently, returning cached objects when possible.
def MultiOpen(self, urns, aff4_type=None, mode="r"):
"""Opens many urns efficiently, returning cached objects when possible."""
not_opened_urns = []
_ValidateAFF4Type(aff4_type)
for urn in urns:
key = self._ObjectKey(urn, mode)... |
Lists children of a given urn. Resulting list is cached.
def ListChildren(self, urn):
"""Lists children of a given urn. Resulting list is cached."""
result = self.MultiListChildren([urn])
try:
return result[urn]
except KeyError:
return [] |
Lists children of a bunch of given urns. Results are cached.
def MultiListChildren(self, urns):
"""Lists children of a bunch of given urns. Results are cached."""
result = {}
not_listed_urns = []
for urn in urns:
try:
result[urn] = self._children_lists_cache[urn]
except KeyError:
... |
Recursively lists given urns. Results are cached.
def RecursiveMultiListChildren(self, urns):
"""Recursively lists given urns. Results are cached."""
result = {}
checked_urns = set()
not_cached_urns = []
urns_to_check = urns
while True:
found_children = []
for urn in urns_to_check... |
Marks multiple urns (and their children) for deletion.
def MultiMarkForDeletion(self, urns):
"""Marks multiple urns (and their children) for deletion."""
all_children_urns = self.RecursiveMultiListChildren(urns)
urns.extend(collection.Flatten(itervalues(all_children_urns)))
self._urns_for_deletion.upd... |
Roots of the graph of urns marked for deletion.
def root_urns_for_deletion(self):
"""Roots of the graph of urns marked for deletion."""
roots = set()
for urn in self._urns_for_deletion:
new_root = True
str_urn = utils.SmartUnicode(urn)
fake_roots = []
for root in roots:
str... |
Parses an aff4 age and returns a datastore age specification.
def ParseAgeSpecification(cls, age):
"""Parses an aff4 age and returns a datastore age specification."""
try:
return (0, int(age))
except (ValueError, TypeError):
pass
if age == NEWEST_TIME:
return data_store.DB.NEWEST_TIM... |
Retrieves all the attributes for all the urns.
def GetAttributes(self, urns, age=NEWEST_TIME):
"""Retrieves all the attributes for all the urns."""
urns = set([utils.SmartUnicode(u) for u in urns])
to_read = {urn: self._MakeCacheInvariant(urn, age) for urn in urns}
# Urns not present in the cache we n... |
Sets the attributes in the data store.
def SetAttributes(self,
urn,
attributes,
to_delete,
add_child_index=True,
mutation_pool=None):
"""Sets the attributes in the data store."""
attributes[AFF4Object.SchemaCls... |
Update the child indexes.
This function maintains the index for direct child relations. When we set
an AFF4 path, we always add an attribute like
index:dir/%(childname)s to its parent. This is written
asynchronously to its parent.
In order to query for all direct children of an AFF4 object, we the... |
Returns an invariant key for an AFF4 object.
The object will be cached based on this key. This function is specifically
extracted to ensure that we encapsulate all security critical aspects of the
AFF4 object so that objects do not leak across security boundaries.
Args:
urn: The urn of the obje... |
Creates a new object and locks it.
Similar to OpenWithLock below, this creates a locked object. The difference
is that when you call CreateWithLock, the object does not yet have to exist
in the data store.
Args:
urn: The object to create.
aff4_type: The desired type for this object.
... |
Open given urn and locks it.
Opens an object and locks it for 'lease_time' seconds. OpenWithLock can
only be used in 'with ...' statement. The lock is released when code
execution leaves 'with ...' block.
The urn is always opened in "rw" mode. Symlinks are not followed in
OpenWithLock() due to pos... |
This actually acquires the lock for a given URN.
def _AcquireLock(self,
urn,
blocking=None,
blocking_lock_timeout=None,
lease_time=None,
blocking_sleep_interval=None):
"""This actually acquires the lock for a given URN."... |
Make a copy of one AFF4 object to a different URN.
def Copy(self,
old_urn,
new_urn,
age=NEWEST_TIME,
limit=None,
update_timestamps=False):
"""Make a copy of one AFF4 object to a different URN."""
new_urn = rdfvalue.RDFURN(new_urn)
if update_timestamps... |
Checks if an object with a given URN and type exists in the datastore.
Args:
urn: The urn to check.
aff4_type: Expected object type.
follow_symlinks: If object opened is a symlink, follow it.
age: The age policy used to check this object. Should be either
NEWEST_TIME or a time range... |
Opens the named object.
This instantiates the object from the AFF4 data store.
Note that the root aff4:/ object is a container for all other
objects. Opening it for reading will instantiate a AFF4Volume instance, even
if the row does not exist.
The mode parameter specifies, how the object should b... |
Opens a bunch of urns efficiently.
def MultiOpen(self,
urns,
mode="rw",
token=None,
aff4_type=None,
age=NEWEST_TIME,
follow_symlinks=True):
"""Opens a bunch of urns efficiently."""
if not data_store.AFF4Enabled():
... |
Opens many URNs and returns handles in the same order.
`MultiOpen` can return file handles in arbitrary order. This makes it more
efficient and in most cases the order does not matter. However, there are
cases where order is important and this function should be used instead.
Args:
urns: A list ... |
Returns all the versions of the object as AFF4 objects.
This iterates through versions of an object, returning the newest version
first, then each older version until the beginning of time.
Note that versions are defined by changes to the TYPE attribute, and this
takes the version between two TYPE att... |
Returns metadata about all urns.
Currently the metadata include type, and last update time.
Args:
urns: The urns of the objects to open.
Yields:
A dict of metadata.
Raises:
ValueError: A string was passed instead of an iterable.
def Stat(self, urns):
"""Returns metadata about ... |
Creates the urn if it does not already exist, otherwise opens it.
If the urn exists and is of a different type, this will also promote it to
the specified type.
Args:
urn: The object to create.
aff4_type: The desired type for this object.
mode: The desired mode for this object.
tok... |
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:
ValueError: If one of the urns is too short. This ... |
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,
NEWEST_TIME or a range.
Yields:
Tuples of Subjects and a list of... |
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:
RDFURNs instances of each child.
def ListChildren(self, urn, limi... |
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,
NEWEST_TIME or a range.
Yields:
(subject<->children urns) tuples... |
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 Att... |
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 or Array.
field_names: A list of strings in... |
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... |
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 ... |
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 timestamp of this attribute.
def DecodeValueFromAttribute(self, attribu... |
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.
attrib... |
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 OpenWithLock().
See flows/hunts locking for an ... |
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.pare... |
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.
def Close(self):
"""Close and destroy the object.
This is similar to Flush... |
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(... |
Sync the new attributes to the synced attribute cache.
This maintains object validity.
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_attri... |
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 of type Attribute().
def _CheckAttribute(self, attri... |
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 RDFValue derived from the attribute.
value: The value the a... |
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.
#... |
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(attribut... |
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 "
"ob... |
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
object.
Note: It is not allowed to dow... |
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_typ... |
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... |
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.attrib... |
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
#... |
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(sel... |
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... |
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 t... |
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:
brea... |
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:
... |
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:
conten... |
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... |
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 ... |
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))
... |
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 = ... |
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 da... |
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.... |
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 ... |
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... |
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_i... |
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... |
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 = rdfval... |
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.CONFI... |
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... |
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... |
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_t... |
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... |
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... |
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... |
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_ur... |
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:
r... |
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... |
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... |
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... |
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, fi... |
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(s... |
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... |
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:
r... |
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... |
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 filesyste... |
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... |
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"... |
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... |
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.
... |
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 objec... |
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.
"... |
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._hashe... |
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):
""... |
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:
... |
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 = r... |
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... |
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(currentl... |
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.ex... |
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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.