INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Resolve the raw device that contains the path. | def GetRawDevice(path):
"""Resolve the raw device that contains the path."""
device_map = GetMountpoints()
path = utils.SmartUnicode(path)
mount_point = path = utils.NormalizePath(path, "/")
result = rdf_paths.PathSpec(pathtype=rdf_paths.PathSpec.PathType.OS)
# Assign the most specific mount point to the... |
Calls into the IOKit to load a kext by file - system path. | def InstallDriver(kext_path):
"""Calls into the IOKit to load a kext by file-system path.
Apple kext API doco here:
http://developer.apple.com/library/mac/#documentation/IOKit/Reference/
KextManager_header_reference/Reference/reference.html
Args:
kext_path: Absolute or relative POSIX path to the k... |
Calls into the IOKit to unload a kext by its name. | def UninstallDriver(bundle_name):
"""Calls into the IOKit to unload a kext by its name.
Args:
bundle_name: The bundle identifier of the kernel extension as defined in
Info.plist field CFBundleIdentifier.
Returns:
The error code from the library call. objc.OS_SUCCESS if successfull.
"""... |
Validates a sequence of path infos. | def _ValidatePathInfos(path_infos):
"""Validates a sequence of path infos."""
precondition.AssertIterableType(path_infos, rdf_objects.PathInfo)
validated = set()
for path_info in path_infos:
_ValidatePathInfo(path_info)
path_key = (path_info.path_type, path_info.GetPathID())
if path_key in validat... |
Parses a timerange argument and always returns non - None timerange. | def _ValidateTimeRange(timerange):
"""Parses a timerange argument and always returns non-None timerange."""
if len(timerange) != 2:
raise ValueError("Timerange should be a sequence with 2 items.")
(start, end) = timerange
precondition.AssertOptionalType(start, rdfvalue.RDFDatetime)
precondition.AssertOpt... |
Checks that a time - range has both start and end timestamps set. | def _ValidateClosedTimeRange(time_range):
"""Checks that a time-range has both start and end timestamps set."""
time_range_start, time_range_end = time_range
_ValidateTimestamp(time_range_start)
_ValidateTimestamp(time_range_end)
if time_range_start > time_range_end:
raise ValueError("Invalid time-range: ... |
Write metadata about the client. | def WriteClientMetadata(self,
client_id,
certificate=None,
fleetspeak_enabled=None,
first_seen=None,
last_ping=None,
last_clock=None,
last... |
Reads the ClientMetadata record for a single client. | def ReadClientMetadata(self, client_id):
"""Reads the ClientMetadata record for a single client.
Args:
client_id: A GRR client id string, e.g. "C.ea3b2b71840d6fa7".
Returns:
An rdfvalues.object.ClientMetadata object.
Raises:
UnknownClientError: if no client with corresponding id was... |
Reads full client information for a single client. | def ReadClientFullInfo(self, client_id):
"""Reads full client information for a single client.
Args:
client_id: A GRR client id string, e.g. "C.ea3b2b71840d6fa7".
Returns:
A `ClientFullInfo` instance for given client.
Raises:
UnknownClientError: if no client with such id was found.
... |
Iterates over all available clients and yields full info protobufs. | def IterateAllClientsFullInfo(self, min_last_ping=None, batch_size=50000):
"""Iterates over all available clients and yields full info protobufs.
Args:
min_last_ping: If not None, only the clients with last-ping timestamps
newer than (or equal to) min_last_ping will be returned.
batch_size:... |
Iterates over all available clients and yields client snapshot objects. | def IterateAllClientSnapshots(self, min_last_ping=None, batch_size=50000):
"""Iterates over all available clients and yields client snapshot objects.
Args:
min_last_ping: If provided, only snapshots for clients with last-ping
timestamps newer than (or equal to) the given value will be returned.
... |
Lists path info records that correspond to children of given path. | def ListChildPathInfos(self, client_id, path_type, components,
timestamp=None):
"""Lists path info records that correspond to children of given path.
Args:
client_id: An identifier string for a client.
path_type: A type of a path to retrieve path information for.
comp... |
Initializes a collection of path info records for a client. | def InitPathInfos(self, client_id, path_infos):
"""Initializes a collection of path info records for a client.
Unlike `WritePathInfo`, this method clears stat and hash histories of paths
associated with path info records. This method is intended to be used only
in the data migration scripts.
Args:... |
Writes a collection of StatEntry observed for particular path. | def WritePathStatHistory(self, client_path, stat_entries):
"""Writes a collection of `StatEntry` observed for particular path.
Args:
client_path: A `ClientPath` instance.
stat_entries: A dictionary with timestamps as keys and `StatEntry`
instances as values.
"""
client_path_history ... |
Writes a collection of Hash observed for particular path. | def WritePathHashHistory(self, client_path, hash_entries):
"""Writes a collection of `Hash` observed for particular path.
Args:
client_path: A `ClientPath` instance.
hash_entries: A dictionary with timestamps as keys and `Hash` instances as
values.
"""
client_path_history = ClientPa... |
Reads a collection of hash and stat entry for given path. | def ReadPathInfoHistory(self, client_id, path_type, components):
"""Reads a collection of hash and stat entry for given path.
Args:
client_id: An identifier string for a client.
path_type: A type of a path to retrieve path history for.
components: A tuple of path components corresponding to p... |
Updates run information for an existing cron job. | def UpdateCronJob(self,
cronjob_id,
last_run_status=unchanged,
last_run_time=unchanged,
current_run_id=unchanged,
state=unchanged,
forced_run_requested=unchanged):
"""Updates run information for a... |
Updates flow objects in the database. | def UpdateFlow(self,
client_id,
flow_id,
flow_obj=unchanged,
flow_state=unchanged,
client_crash_info=unchanged,
pending_termination=unchanged,
processing_on=unchanged,
processing_since... |
Updates the hunt object by applying the update function. | def UpdateHuntObject(self,
hunt_id,
duration=None,
client_rate=None,
client_limit=None,
hunt_state=None,
hunt_state_comment=None,
start_time=None,
... |
Updates the hunt object by applying the update function. | def UpdateHuntObject(self,
hunt_id,
duration=None,
client_rate=None,
client_limit=None,
hunt_state=None,
hunt_state_comment=None,
start_time=None,
... |
Processes the tasks. | def ProcessTask(self, target, args, name, queueing_time):
"""Processes the tasks."""
if self.pool.name:
time_in_queue = time.time() - queueing_time
stats_collector_instance.Get().RecordEvent(
_QUEUEING_TIME_METRIC, time_in_queue, fields=[self.pool.name])
start_time = time.time()
... |
Remove ourselves from the pool. | def _RemoveFromPool(self):
"""Remove ourselves from the pool.
Returns:
True if removal was possible, and False if it was not possible.
"""
with self.pool.lock:
# Pool is shutting down, we can't interfere.
if not self.pool.started:
return False
# Keep a minimum number o... |
This overrides the Thread. run method. | def run(self):
"""This overrides the Thread.run method.
This method checks in an endless loop if new tasks are available
in the queue and processes them.
"""
while True:
if self.pool.name:
self.idle = True
try:
# Wait 60 seconds for a message, otherwise exit. This ensur... |
Creates a new thread pool with the given name. | def Factory(cls, name, min_threads, max_threads=None):
"""Creates a new thread pool with the given name.
If the thread pool of this name already exist, we just return the existing
one. This allows us to have different pools with different characteristics
used by different parts of the code, at the same... |
This starts the worker threads. | def Start(self):
"""This starts the worker threads."""
if not self.started:
self.started = True
for _ in range(self.min_threads):
self._AddWorker() |
This stops all the worker threads. | def Stop(self, join_timeout=600):
"""This stops all the worker threads."""
if not self.started:
logging.warning("Tried to stop a thread pool that was not running.")
return
# Remove all workers from the pool.
workers = list(itervalues(self._workers))
self._workers = {}
self._workers_... |
Adds a task to be processed later. | def AddTask(self,
target,
args=(),
name="Unnamed task",
blocking=True,
inline=True):
"""Adds a task to be processed later.
Args:
target: A callable which should be processed by one of the workers.
args: A tuple of arguments to ta... |
Waits until all outstanding tasks are completed. | def Join(self):
"""Waits until all outstanding tasks are completed."""
for _ in range(self.JOIN_TIMEOUT_DECISECONDS):
if self._queue.empty() and not self.busy_threads:
return
time.sleep(0.1)
raise ValueError("Timeout during Join() for threadpool %s." % self.name) |
Converts given collection to exported values. | def Convert(self, values, start_index=0, end_index=None):
"""Converts given collection to exported values.
This method uses a threadpool to do the conversion in parallel. It
blocks for up to one hour until everything is converted.
Args:
values: Iterable object with values to convert.
start... |
Spawns a process. | def SpawnProcess(popen_args, passwd=None):
"""Spawns a process."""
if passwd is not None:
# We send the password via pipe to avoid creating a process with the
# password as an argument that will get logged on some systems.
p = subprocess.Popen(popen_args, stdin=subprocess.PIPE)
p.communicate(input=p... |
Write client config to filename. | def GetClientConfig(filename):
"""Write client config to filename."""
config_lib.SetPlatformArchContext()
config_lib.ParseConfigCommandLine()
context = list(grr_config.CONFIG.context)
context.append("Client Context")
deployer = build.ClientRepacker()
# Disable timestamping so we can get a reproducible and... |
Launch the appropriate builder. | def main(args):
"""Launch the appropriate builder."""
grr_config.CONFIG.AddContext(contexts.CLIENT_BUILD_CONTEXT)
if args.subparser_name == "generate_client_config":
# We don't need a full init to just build a config.
GetClientConfig(args.client_config_output)
return
# TODO(user): Find out if add... |
Get instance of builder class based on flags. | def GetBuilder(self, context, fleetspeak_service_config):
"""Get instance of builder class based on flags."""
try:
if "Target:Darwin" in context:
return builders.DarwinClientBuilder(
context=context,
fleetspeak_service_config=fleetspeak_service_config)
elif "Target:Wi... |
Find template builder and call it. | def BuildTemplate(self,
context=None,
output=None,
fleetspeak_service_config=None):
"""Find template builder and call it."""
context = context or []
context.append("Arch:%s" % self.GetArch())
# Platform context has common platform settings, Tar... |
Add the repack config filename onto the base output directory. | def GetOutputDir(self, base_dir, config_filename):
"""Add the repack config filename onto the base output directory.
This allows us to repack lots of different configs to the same installer
name and still be able to distinguish them.
Args:
base_dir: output directory string
config_filename:... |
Call repacker in a subprocess. | def RepackTemplates(self,
repack_configs,
templates,
output_dir,
config=None,
sign=False,
signed_template=False):
"""Call repacker in a subprocess."""
pool = multiprocessing.Pool(p... |
Run all startup routines for the client. | def ClientInit():
"""Run all startup routines for the client."""
metric_metadata = client_metrics.GetMetadata()
metric_metadata.extend(communicator.GetMetricMetadata())
stats_collector_instance.Set(
default_stats_collector.DefaultStatsCollector(metric_metadata))
config_lib.SetPlatformArchContext()
co... |
Parse the sysctl output. | def Parse(self, cmd, args, stdout, stderr, return_val, time_taken,
knowledge_base):
"""Parse the sysctl output."""
_ = stderr, time_taken, args, knowledge_base # Unused.
self.CheckReturn(cmd, return_val)
result = rdf_protodict.AttributedDict()
# The KeyValueParser generates an ordered d... |
Parse the key currentcontrolset output. | def Parse(self, stat, unused_knowledge_base):
"""Parse the key currentcontrolset output."""
value = stat.registry_data.GetValue()
if not str(value).isdigit() or int(value) > 999 or int(value) < 0:
raise parser.ParseError(
"Invalid value for CurrentControlSet key %s" % value)
yield rdfva... |
Expand any variables in the value. | def Parse(self, stat, knowledge_base):
"""Expand any variables in the value."""
value = stat.registry_data.GetValue()
if not value:
raise parser.ParseError("Invalid value for key %s" % stat.pathspec.path)
value = artifact_utils.ExpandWindowsEnvironmentVariables(
value, knowledge_base)
... |
Parses a SystemDrive environment variable. | def Parse(self, stat, _):
"""Parses a SystemDrive environment variable."""
if isinstance(stat, rdf_client_fs.StatEntry):
value = stat.registry_data.GetValue()
elif isinstance(stat, rdfvalue.RDFString):
value = stat
if not value:
raise parser.ParseError("Invalid value for key %s" % stat... |
Parse each returned registry value. | def Parse(self, stat, knowledge_base):
"""Parse each returned registry value."""
_ = knowledge_base # Unused.
sid_str = stat.pathspec.Dirname().Basename()
if SID_RE.match(sid_str):
kb_user = rdf_client.User()
kb_user.sid = sid_str
if stat.pathspec.Basename() == "ProfileImagePath":
... |
Parse each returned registry value. | def ParseMultiple(self, stats, knowledge_base):
"""Parse each returned registry value."""
user_dict = {}
for stat in stats:
sid_str = stat.pathspec.path.split("/", 3)[2]
if SID_RE.match(sid_str):
if sid_str not in user_dict:
user_dict[sid_str] = rdf_client.User(sid=sid_str)
... |
Parse Service registry keys and return WindowsServiceInformation. | def ParseMultiple(self, stats, knowledge_base):
"""Parse Service registry keys and return WindowsServiceInformation."""
_ = knowledge_base
services = {}
field_map = {
"Description": "description",
"DisplayName": "display_name",
"Group": "group_name",
"DriverPackageId": "d... |
Convert the timezone to Olson format. | def Parse(self, stat, knowledge_base):
"""Convert the timezone to Olson format."""
_ = knowledge_base
value = stat.registry_data.GetValue()
result = ZONE_LIST.get(value.strip())
if not result:
yield rdfvalue.RDFString("Unknown (%s)" % value.strip())
yield rdfvalue.RDFString(result) |
Converts a generator with approval rows into ApprovalRequest objects. | def _ResponseToApprovalsWithGrants(response):
"""Converts a generator with approval rows into ApprovalRequest objects."""
prev_triplet = None
cur_approval_request = None
for (approval_id_int, approval_timestamp, approval_request_bytes,
grantor_username, grant_timestamp) in response:
cur_triplet = (a... |
Writes user object for a user with a given name. | def WriteGRRUser(self,
username,
password=None,
ui_mode=None,
canary_mode=None,
user_type=None,
cursor=None):
"""Writes user object for a user with a given name."""
values = {"username": username, ... |
Creates a GRR user object from a database result row. | def _RowToGRRUser(self, row):
"""Creates a GRR user object from a database result row."""
username, password, ui_mode, canary_mode, user_type = row
result = rdf_objects.GRRUser(
username=username,
ui_mode=ui_mode,
canary_mode=canary_mode,
user_type=user_type)
if password... |
Reads a user object corresponding to a given name. | def ReadGRRUser(self, username, cursor=None):
"""Reads a user object corresponding to a given name."""
cursor.execute(
"SELECT username, password, ui_mode, canary_mode, user_type "
"FROM grr_users WHERE username_hash = %s", [mysql_utils.Hash(username)])
row = cursor.fetchone()
if row is... |
Reads GRR users with optional pagination sorted by username. | def ReadGRRUsers(self, offset=0, count=None, cursor=None):
"""Reads GRR users with optional pagination, sorted by username."""
if count is None:
count = 18446744073709551615 # 2^64-1, as suggested by MySQL docs
cursor.execute(
"SELECT username, password, ui_mode, canary_mode, user_type "
... |
Deletes the user and all related metadata with the given username. | def DeleteGRRUser(self, username, cursor=None):
"""Deletes the user and all related metadata with the given username."""
cursor.execute("DELETE FROM grr_users WHERE username_hash = %s",
(mysql_utils.Hash(username),))
if cursor.rowcount == 0:
raise db.UnknownGRRUserError(username) |
Writes an approval request object. | def WriteApprovalRequest(self, approval_request, cursor=None):
"""Writes an approval request object."""
# Copy the approval_request to ensure we don't modify the source object.
approval_request = approval_request.Copy()
# Generate random approval id.
approval_id_int = random.UInt64()
grants = a... |
Grants approval for a given request. | def _GrantApproval(self, requestor_username, approval_id, grantor_username,
cursor):
"""Grants approval for a given request."""
grant_args = {
"username_hash": mysql_utils.Hash(requestor_username),
"approval_id": approval_id,
"grantor_username_hash": mysql_utils.Hash... |
Grants approval for a given request using given username. | def GrantApproval(self,
requestor_username,
approval_id,
grantor_username,
cursor=None):
"""Grants approval for a given request using given username."""
self._GrantApproval(
requestor_username, _ApprovalIDToInt(approval_id),... |
Reads an approval request object with a given id. | def ReadApprovalRequest(self, requestor_username, approval_id, cursor=None):
"""Reads an approval request object with a given id."""
query = ("""
SELECT
ar.approval_id,
UNIX_TIMESTAMP(ar.timestamp),
ar.approval_request,
u.username,
UNIX_TIMEST... |
Reads approval requests of a given type for a given user. | def ReadApprovalRequests(self,
requestor_username,
approval_type,
subject_id=None,
include_expired=False,
cursor=None):
"""Reads approval requests of a given type for a given user."... |
Writes a notification for a given user. | def WriteUserNotification(self, notification, cursor=None):
"""Writes a notification for a given user."""
# Copy the notification to ensure we don't modify the source object.
args = {
"username_hash":
mysql_utils.Hash(notification.username),
"notification_state":
int(... |
Reads notifications scheduled for a user within a given timerange. | def ReadUserNotifications(self,
username,
state=None,
timerange=None,
cursor=None):
"""Reads notifications scheduled for a user within a given timerange."""
query = ("SELECT UNIX_TIMESTAMP(timestamp)... |
Updates existing user notification objects. | def UpdateUserNotifications(self,
username,
timestamps,
state=None,
cursor=None):
"""Updates existing user notification objects."""
query = ("UPDATE user_notification "
"SET noti... |
Splits strings into space - separated components. | def SplitIntoComponents(str_in):
"""Splits strings into space-separated components.
The difference between SplitIntoComponents and .split(" ") is that
the former tries to respect single and double quotes and strip them
using lexical rules typically used in command line interpreters.
Args:
str_in: Source... |
Detects paths in a given string. | def Detect(self, str_in):
"""Detects paths in a given string.
Args:
str_in: String where the paths should be detected.
Returns:
A list of paths (as strings) detected inside the given string.
"""
components = SplitIntoComponents(str_in)
extracted_paths = set()
for extractor in... |
Register all known vfs handlers to open a pathspec types. | def Init():
"""Register all known vfs handlers to open a pathspec types."""
VFS_HANDLERS.clear()
_VFS_VIRTUALROOTS.clear()
vfs_virtualroots = config.CONFIG["Client.vfs_virtualroots"]
VFS_HANDLERS[files.File.supported_pathtype] = files.File
VFS_HANDLERS[files.TempFile.supported_pathtype] = files.TempFile
... |
Expands pathspec to return an expanded Path. | def VFSOpen(pathspec,
progress_callback = None
):
"""Expands pathspec to return an expanded Path.
A pathspec is a specification of how to access the file by recursively opening
each part of the path by different drivers. For example the following
pathspec:
pathtype: OS
path: "/dev/s... |
Opens multiple files specified by given path - specs. | def VFSMultiOpen(pathspecs, progress_callback=None):
"""Opens multiple files specified by given path-specs.
See documentation for `VFSOpen` for more information.
Args:
pathspecs: A list of pathspec instances of files to open.
progress_callback: A callback function to call to notify about progress
Ret... |
Read from the VFS and return the contents. | def ReadVFS(pathspec, offset, length, progress_callback=None):
"""Read from the VFS and return the contents.
Args:
pathspec: path to read from
offset: number of bytes to skip
length: number of bytes to read
progress_callback: A callback to indicate that the open call is still
working but need... |
Writes a single row to the underlying buffer. | def WriteRow(self, values):
"""Writes a single row to the underlying buffer.
Args:
values: A list of string values to be inserted into the CSV output.
"""
precondition.AssertIterableType(values, text)
if compatibility.PY2:
self._csv.writerow([value.encode("utf-8") for value in values])... |
Writes a single row to the underlying buffer. | def WriteRow(self, values):
"""Writes a single row to the underlying buffer.
Args:
values: A dictionary mapping column names to values to be inserted into
the CSV output.
"""
precondition.AssertDictType(values, text, text)
row = []
for column in self._columns:
try:
... |
Returns True if the last run failed. | def _IsCronJobFailing(self, cron_job):
"""Returns True if the last run failed."""
status = cron_job.Get(cron_job.Schema.LAST_RUN_STATUS)
if status is None:
return False
return status.status != rdf_cronjobs.CronJobRunStatus.Status.OK |
Shortcut method for easy legacy cron jobs support. | def InitFromApiFlow(self, f, cron_job_id=None):
"""Shortcut method for easy legacy cron jobs support."""
if f.flow_id:
self.run_id = f.flow_id
elif f.urn:
self.run_id = f.urn.Basename()
self.started_at = f.started_at
self.cron_job_id = cron_job_id
flow_state_enum = api_plugins_flow.... |
Parses a timerange argument and always returns non - None timerange. | def _ParseTimeRange(self, timerange):
"""Parses a timerange argument and always returns non-None timerange."""
if timerange is None:
timerange = (None, None)
from_time, to_time = timerange
if not from_time:
from_time = rdfvalue.RDFDatetime().FromSecondsSinceEpoch(0)
if not to_time:
... |
Creates an object copy by serializing/ deserializing it. | def _DeepCopy(self, obj):
"""Creates an object copy by serializing/deserializing it.
RDFStruct.Copy() doesn't deep-copy repeated fields which may lead to
hard to catch bugs.
Args:
obj: RDFValue to be copied.
Returns:
A deep copy of the passed RDFValue.
"""
precondition.AssertT... |
Returns audit entries stored in the database. | def ReadAPIAuditEntries(self,
username=None,
router_method_names=None,
min_timestamp=None,
max_timestamp=None):
"""Returns audit entries stored in the database."""
results = []
for entry in self.api_audi... |
Returns audit entry counts grouped by user and calendar day. | def CountAPIAuditEntriesByUserAndDay(self,
min_timestamp=None,
max_timestamp=None):
"""Returns audit entry counts grouped by user and calendar day."""
results = collections.Counter()
for entry in self.api_audit_entries:
if m... |
Writes an audit entry to the database. | def WriteAPIAuditEntry(self, entry):
"""Writes an audit entry to the database."""
copy = entry.Copy()
copy.timestamp = rdfvalue.RDFDatetime.Now()
self.api_audit_entries.append(copy) |
Applies instant output plugin to a multi - type collection. | def ApplyPluginToMultiTypeCollection(plugin, output_collection,
source_urn=None):
"""Applies instant output plugin to a multi-type collection.
Args:
plugin: InstantOutputPlugin instance.
output_collection: MultiTypeCollection instance.
source_urn: If not None, overr... |
Applies instant output plugin to a collection of results. | def ApplyPluginToTypedCollection(plugin, type_names, fetch_fn):
"""Applies instant output plugin to a collection of results.
Args:
plugin: InstantOutputPlugin instance.
type_names: List of type names (strings) to be processed.
fetch_fn: Function that takes a type name as an argument and returns
a... |
Name of the file where plugin s output should be written to. | def output_file_name(self):
"""Name of the file where plugin's output should be written to."""
safe_path = re.sub(r":|/", "_", self.source_urn.Path().lstrip("/"))
return "results_%s%s" % (safe_path, self.output_file_extension) |
Fetches metadata for a given list of clients. | def _GetMetadataForClients(self, client_urns):
"""Fetches metadata for a given list of clients."""
result = {}
metadata_to_fetch = set()
for urn in client_urns:
try:
result[urn] = self._cached_metadata[urn]
except KeyError:
metadata_to_fetch.add(urn)
if metadata_to_fet... |
Yields responses of a given type only. | def _GenerateSingleTypeIteration(self, next_types, processed_types,
converted_responses):
"""Yields responses of a given type only.
_GenerateSingleTypeIteration iterates through converted_responses and
only yields responses of the same type. The type is either popped from... |
Generates converted values using given converter from given messages. | def _GenerateConvertedValues(self, converter, grr_messages):
"""Generates converted values using given converter from given messages.
Groups values in batches of BATCH_SIZE size and applies the converter
to each batch.
Args:
converter: ExportConverter instance.
grr_messages: An iterable (a... |
Parses a categorized path string into type and list of components. | def ParseCategorizedPath(path):
"""Parses a categorized path string into type and list of components."""
components = tuple(component for component in path.split("/") if component)
if components[0:2] == ("fs", "os"):
return PathInfo.PathType.OS, components[2:]
elif components[0:2] == ("fs", "tsk"):
retu... |
Translates a path type and a list of components to a categorized path. | def ToCategorizedPath(path_type, components):
"""Translates a path type and a list of components to a categorized path."""
try:
prefix = {
PathInfo.PathType.OS: ("fs", "os"),
PathInfo.PathType.TSK: ("fs", "tsk"),
PathInfo.PathType.REGISTRY: ("registry",),
PathInfo.PathType.TEMP: ... |
Returns the client installation - name and GRR version as a string. | def GetGRRVersionString(self):
"""Returns the client installation-name and GRR version as a string."""
client_info = self.startup_info.client_info
client_name = client_info.client_description or client_info.client_name
if client_info.client_version > 0:
client_version = str(client_info.client_vers... |
MAC addresses from all interfaces. | def GetMacAddresses(self):
"""MAC addresses from all interfaces."""
result = set()
for interface in self.interfaces:
if (interface.mac_address and
interface.mac_address != b"\x00" * len(interface.mac_address)):
result.add(Text(interface.mac_address.human_readable_address))
return... |
IP addresses from all interfaces. | def GetIPAddresses(self):
"""IP addresses from all interfaces."""
result = []
filtered_ips = ["127.0.0.1", "::1", "fe80::1"]
for interface in self.interfaces:
for address in interface.addresses:
if address.human_readable_address not in filtered_ips:
result.append(Text(address.hu... |
Gets a client summary object. | def GetSummary(self):
"""Gets a client summary object.
Returns:
rdf_client.ClientSummary
Raises:
ValueError: on bad cloud type
"""
summary = rdf_client.ClientSummary()
summary.client_id = self.client_id
summary.timestamp = self.timestamp
summary.system_info.release = self.o... |
Constructs a path info corresponding to the parent of current path. | def GetParent(self):
"""Constructs a path info corresponding to the parent of current path.
The root path (represented by an empty list of components, corresponds to
`/` on Unix-like systems) does not have a parent.
Returns:
Instance of `rdf_objects.PathInfo` or `None` if parent does not exist.
... |
Yields all ancestors of a path. | def GetAncestors(self):
"""Yields all ancestors of a path.
The ancestors are returned in order from closest to the farthest one.
Yields:
Instances of `rdf_objects.PathInfo`.
"""
current = self
while True:
current = current.GetParent()
if current is None:
return
... |
Merge path info records. | def UpdateFrom(self, src):
"""Merge path info records.
Merges src into self.
Args:
src: An rdfvalues.objects.PathInfo record, will be merged into self.
Raises:
ValueError: If src does not represent the same path.
"""
if not isinstance(src, PathInfo):
raise TypeError("expected... |
Converts a reference into an URN. | def ToURN(self):
"""Converts a reference into an URN."""
if self.path_type in [PathInfo.PathType.OS, PathInfo.PathType.TSK]:
return rdfvalue.RDFURN(self.client_id).Add("fs").Add(
self.path_type.name.lower()).Add("/".join(self.path_components))
elif self.path_type == PathInfo.PathType.REGIST... |
Converts a reference into a VFS file path. | def ToPath(self):
"""Converts a reference into a VFS file path."""
if self.path_type == PathInfo.PathType.OS:
return os.path.join("fs", "os", *self.path_components)
elif self.path_type == PathInfo.PathType.TSK:
return os.path.join("fs", "tsk", *self.path_components)
elif self.path_type == P... |
Configure the logging subsystem. | def LogInit():
"""Configure the logging subsystem."""
logging.debug("Initializing client logging subsystem.")
# The root logger.
logger = logging.getLogger()
memory_handlers = [
m for m in logger.handlers
if m.__class__.__name__ == "PreLoggingMemoryHandler"
]
# Clear all handers.
logger.ha... |
Updates ApiClient records to include info from Fleetspeak. | def UpdateClientsFromFleetspeak(clients):
"""Updates ApiClient records to include info from Fleetspeak."""
if not fleetspeak_connector.CONN or not fleetspeak_connector.CONN.outgoing:
# FS not configured, or an outgoing connection is otherwise unavailable.
return
id_map = {}
for client in clients:
if... |
Removes labels with given names from a given client object. | def RemoveClientLabels(self, client, labels_names):
"""Removes labels with given names from a given client object."""
affected_owners = set()
for label in client.GetLabels():
if label.name in labels_names and label.owner != "GRR":
affected_owners.add(label.owner)
for owner in affected_ow... |
Normalize a time to be an int measured in microseconds. | def _NormalizeTime(self, time):
"""Normalize a time to be an int measured in microseconds."""
if isinstance(time, rdfvalue.RDFDatetime):
return time.AsMicrosecondsSinceEpoch()
if isinstance(time, rdfvalue.Duration):
return time.microseconds
return int(time) |
Adds value at timestamp. | def Append(self, value, timestamp):
"""Adds value at timestamp.
Values must be added in order of increasing timestamp.
Args:
value: An observed value.
timestamp: The timestamp at which value was observed.
Raises:
RuntimeError: If timestamp is smaller than the previous timstamp.
... |
Adds multiple value< - > timestamp pairs. | def MultiAppend(self, value_timestamp_pairs):
"""Adds multiple value<->timestamp pairs.
Args:
value_timestamp_pairs: Tuples of (value, timestamp).
"""
for value, timestamp in value_timestamp_pairs:
self.Append(value, timestamp) |
Filter the series to lie between start_time and stop_time. | def FilterRange(self, start_time=None, stop_time=None):
"""Filter the series to lie between start_time and stop_time.
Removes all values of the series which are outside of some time range.
Args:
start_time: If set, timestamps before start_time will be dropped.
stop_time: If set, timestamps at ... |
Normalize the series to have a fixed period over a fixed time range. | def Normalize(self, period, start_time, stop_time, mode=NORMALIZE_MODE_GAUGE):
"""Normalize the series to have a fixed period over a fixed time range.
Supports two modes, depending on the type of data:
NORMALIZE_MODE_GAUGE: support gauge values. If multiple original data
points lie within an out... |
Makes the time series increasing. | def MakeIncreasing(self):
"""Makes the time series increasing.
Assumes that series is based on a counter which is occasionally reset, and
using this assumption converts the sequence to estimate the total number of
counts which occurred.
NOTE: Could give inacurate numbers in either of the following... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.