INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Parses Hash rdfvalue into ExportedFile's fields. | def ParseFileHash(hash_obj, result):
"""Parses Hash rdfvalue into ExportedFile's fields."""
if hash_obj.HasField("md5"):
result.hash_md5 = str(hash_obj.md5)
if hash_obj.HasField("sha1"):
result.hash_sha1 = str(hash_obj.sha1)
if hash_obj.HasField("sha256"):
result.hash_sha256 = str(ha... |
Converts StatEntry to ExportedFile.
Does nothing if StatEntry corresponds to a registry entry and not to a file.
Args:
metadata: ExportedMetadata to be used for conversion.
stat_entry: StatEntry to be converted.
token: Security token.
Returns:
List or generator with resulting RDFV... | def Convert(self, metadata, stat_entry, token=None):
"""Converts StatEntry to ExportedFile.
Does nothing if StatEntry corresponds to a registry entry and not to a file.
Args:
metadata: ExportedMetadata to be used for conversion.
stat_entry: StatEntry to be converted.
token: Security toke... |
Filter out registry keys to operate on files. | def _RemoveRegistryKeys(self, metadata_value_pairs):
"""Filter out registry keys to operate on files."""
filtered_pairs = []
for metadata, stat_entry in metadata_value_pairs:
# Ignore registry keys.
if stat_entry.pathspec.pathtype != rdf_paths.PathSpec.PathType.REGISTRY:
filtered_pairs.a... |
Open files all at once if necessary. | def _OpenFilesForRead(self, metadata_value_pairs, token):
"""Open files all at once if necessary."""
aff4_paths = [
result.AFF4Path(metadata.client_urn)
for metadata, result in metadata_value_pairs
]
fds = aff4.FACTORY.MultiOpen(aff4_paths, mode="r", token=token)
fds_dict = dict([(fd... |
Add file content from aff4_object to result. | def _ExportFileContent(self, aff4_object, result):
"""Add file content from aff4_object to result."""
if self.options.export_files_contents:
try:
result.content = aff4_object.Read(self.MAX_CONTENT_SIZE)
result.content_sha256 = hashlib.sha256(result.content).hexdigest()
except (IOErro... |
Converts a batch of StatEntry value to ExportedFile values at once.
Args:
metadata_value_pairs: a list or a generator of tuples (metadata, value),
where metadata is ExportedMetadata to be used for conversion and value
is a StatEntry to be converted.
token: Security token:
Yields:
... | def BatchConvert(self, metadata_value_pairs, token=None):
"""Converts a batch of StatEntry value to ExportedFile values at once.
Args:
metadata_value_pairs: a list or a generator of tuples (metadata, value),
where metadata is ExportedMetadata to be used for conversion and value
is a StatE... |
Converts StatEntry to ExportedRegistryKey.
Does nothing if StatEntry corresponds to a file and not a registry entry.
Args:
metadata: ExportedMetadata to be used for conversion.
stat_entry: StatEntry to be converted.
token: Security token.
Returns:
List or generator with resulting ... | def Convert(self, metadata, stat_entry, token=None):
"""Converts StatEntry to ExportedRegistryKey.
Does nothing if StatEntry corresponds to a file and not a registry entry.
Args:
metadata: ExportedMetadata to be used for conversion.
stat_entry: StatEntry to be converted.
token: Security ... |
Converts NetworkConnection to ExportedNetworkConnection. | def Convert(self, metadata, conn, token=None):
"""Converts NetworkConnection to ExportedNetworkConnection."""
result = ExportedNetworkConnection(
metadata=metadata,
family=conn.family,
type=conn.type,
local_address=conn.local_address,
remote_address=conn.remote_address,
... |
Converts Process to ExportedProcess. | def Convert(self, metadata, process, token=None):
"""Converts Process to ExportedProcess."""
result = ExportedProcess(
metadata=metadata,
pid=process.pid,
ppid=process.ppid,
name=process.name,
exe=process.exe,
cmdline=" ".join(process.cmdline),
ctime=proc... |
Converts Process to ExportedNetworkConnection. | def Convert(self, metadata, process, token=None):
"""Converts Process to ExportedNetworkConnection."""
conn_converter = NetworkConnectionToExportedNetworkConnectionConverter(
options=self.options)
return conn_converter.BatchConvert(
[(metadata, conn) for conn in process.connections], token=... |
Converts Process to ExportedOpenFile. | def Convert(self, metadata, process, token=None):
"""Converts Process to ExportedOpenFile."""
for f in process.open_files:
yield ExportedOpenFile(metadata=metadata, pid=process.pid, path=f) |
Converts Interface to ExportedNetworkInterfaces. | def Convert(self, metadata, interface, token=None):
"""Converts Interface to ExportedNetworkInterfaces."""
ip4_addresses = []
ip6_addresses = []
for addr in interface.addresses:
if addr.address_type == addr.Family.INET:
ip4_addresses.append(addr.human_readable_address)
elif addr.addr... |
Converts DNSClientConfiguration to ExportedDNSClientConfiguration. | def Convert(self, metadata, config, token=None):
"""Converts DNSClientConfiguration to ExportedDNSClientConfiguration."""
result = ExportedDNSClientConfiguration(
metadata=metadata,
dns_servers=" ".join(config.dns_server),
dns_suffixes=" ".join(config.dns_suffix))
yield result |
Converts ClientSummary to ExportedNetworkInterfaces. | def Convert(self, metadata, client_summary, token=None):
"""Converts ClientSummary to ExportedNetworkInterfaces."""
for interface in client_summary.interfaces:
yield super(ClientSummaryToExportedNetworkInterfaceConverter,
self).Convert(
metadata, interface, token=to... |
Separate files, registry keys, grep matches. | def _SeparateTypes(self, metadata_value_pairs):
"""Separate files, registry keys, grep matches."""
registry_pairs = []
file_pairs = []
match_pairs = []
for metadata, result in metadata_value_pairs:
if (result.stat_entry.pathspec.pathtype ==
rdf_paths.PathSpec.PathType.REGISTRY):
... |
Converts GrrMessage into a set of RDFValues.
Args:
metadata: ExportedMetadata to be used for conversion.
grr_message: GrrMessage to be converted.
token: Security token.
Returns:
List or generator with resulting RDFValues. | def Convert(self, metadata, grr_message, token=None):
"""Converts GrrMessage into a set of RDFValues.
Args:
metadata: ExportedMetadata to be used for conversion.
grr_message: GrrMessage to be converted.
token: Security token.
Returns:
List or generator with resulting RDFValues.
... |
Converts a batch of GrrMessages into a set of RDFValues at once.
Args:
metadata_value_pairs: a list or a generator of tuples (metadata, value),
where metadata is ExportedMetadata to be used for conversion and value
is a GrrMessage to be converted.
token: Security token.
Returns:
... | def BatchConvert(self, metadata_value_pairs, token=None):
"""Converts a batch of GrrMessages into a set of RDFValues at once.
Args:
metadata_value_pairs: a list or a generator of tuples (metadata, value),
where metadata is ExportedMetadata to be used for conversion and value
is a GrrMessa... |
Convert batch of FileStoreHashs. | def BatchConvert(self, metadata_value_pairs, token=None):
"""Convert batch of FileStoreHashs."""
urns = [urn for metadata, urn in metadata_value_pairs]
urns_dict = dict((urn, metadata) for metadata, urn in metadata_value_pairs)
results = []
for hash_urn, client_files in filestore.HashFileStore.Get... |
Converts a single CheckResult.
Args:
metadata: ExportedMetadata to be used for conversion.
checkresult: CheckResult to be converted.
token: Security token.
Yields:
Resulting ExportedCheckResult. Empty list is a valid result and means that
conversion wasn't possible. | def Convert(self, metadata, checkresult, token=None):
"""Converts a single CheckResult.
Args:
metadata: ExportedMetadata to be used for conversion.
checkresult: CheckResult to be converted.
token: Security token.
Yields:
Resulting ExportedCheckResult. Empty list is a valid result a... |
Converts original result via given converter.. | def GetExportedResult(self,
original_result,
converter,
metadata=None,
token=None):
"""Converts original result via given converter.."""
exported_results = list(
converter.Convert(
metadata or Ex... |
Checks if given RDFValue is a registry StatEntry. | def IsRegistryStatEntry(self, original_result):
"""Checks if given RDFValue is a registry StatEntry."""
return (original_result.pathspec.pathtype ==
rdf_paths.PathSpec.PathType.REGISTRY) |
Checks if given RDFValue is a file StatEntry. | def IsFileStatEntry(self, original_result):
"""Checks if given RDFValue is a file StatEntry."""
return (original_result.pathspec.pathtype in [
rdf_paths.PathSpec.PathType.OS, rdf_paths.PathSpec.PathType.TSK
]) |
Converts a single ArtifactFilesDownloaderResult. | def Convert(self, metadata, value, token=None):
"""Converts a single ArtifactFilesDownloaderResult."""
for r in self.BatchConvert([(metadata, value)], token=token):
yield r |
Convert a single YaraProcessScanMatch. | def Convert(self, metadata, yara_match, token=None):
"""Convert a single YaraProcessScanMatch."""
conv = ProcessToExportedProcessConverter(options=self.options)
process = list(
conv.Convert(ExportedMetadata(), yara_match.process, token=token))[0]
seen_rules = set()
for m in yara_match.matc... |
Creates a dynamic RDF proto struct class for given osquery table.
The fields of the proto will correspond to the columns of the table.
Args:
table: An osquery table for which the class is about to be generated.
Returns:
A class object corresponding to the given table. | def _RDFClass(cls, table):
"""Creates a dynamic RDF proto struct class for given osquery table.
The fields of the proto will correspond to the columns of the table.
Args:
table: An osquery table for which the class is about to be generated.
Returns:
A class object corresponding to the giv... |
Returns the path from a client action response as a string.
Args:
response: A client action response.
pathspec_attribute: Specifies the field which stores the pathspec.
Returns:
The path as a string or None if no path is found. | def _ExtractPath(response, pathspec_attribute=None):
"""Returns the path from a client action response as a string.
Args:
response: A client action response.
pathspec_attribute: Specifies the field which stores the pathspec.
Returns:
The path as a string or None if no path is found.
"""
path_sp... |
Returns an `CollectedArtifact` rdf object for the requested artifact. | def _CollectArtifact(self, artifact, apply_parsers):
"""Returns an `CollectedArtifact` rdf object for the requested artifact."""
artifact_result = rdf_artifacts.CollectedArtifact(name=artifact.name)
if apply_parsers:
parser_factory = parsers.ArtifactParserFactory(str(artifact.name))
else:
p... |
Set values in the knowledge base based on responses. | def UpdateKnowledgeBase(self, response, provides):
"""Set values in the knowledge base based on responses."""
if isinstance(response, rdf_anomaly.Anomaly):
return
if isinstance(response, rdf_client.User):
self.knowledge_base.MergeOrAddUser(response)
return
if isinstance(response, rd... |
Iterates through sources yielding action responses. | def _ProcessSources(self, sources, parser_factory):
"""Iterates through sources yielding action responses."""
for source in sources:
for action, request in self._ParseSourceType(source):
yield self._RunClientAction(action, request, parser_factory,
source.path_ty... |
Runs the client action with the request and parses the result. | def _RunClientAction(self, action, request, parser_factory, path_type):
"""Runs the client action with the request and parses the result."""
responses = list(action(request))
if parser_factory is None:
return responses
# parse the responses
parsed_responses = []
for response in respons... |
Calls the correct processing function for the given source. | def _ParseSourceType(self, source):
"""Calls the correct processing function for the given source."""
type_name = rdf_artifacts.ArtifactSource.SourceType
switch = {
type_name.COMMAND: self._ProcessCommandSource,
type_name.DIRECTORY: self._ProcessFileSource,
type_name.FILE: self._Proc... |
Glob for paths in the registry. | def _ProcessRegistryKeySource(self, source):
"""Glob for paths in the registry."""
keys = source.base_source.attributes.get("keys", [])
if not keys:
return
interpolated_paths = artifact_utils.InterpolateListKbAttributes(
input_list=keys,
knowledge_base=self.knowledge_base,
... |
Find files fulfilling regex conditions. | def _ProcessGrepSource(self, source):
"""Find files fulfilling regex conditions."""
attributes = source.base_source.attributes
paths = artifact_utils.InterpolateListKbAttributes(
attributes["paths"], self.knowledge_base,
self.ignore_interpolation_errors)
regex = utils.RegexListDisjunctio... |
Get artifact responses, extract paths and send corresponding files. | def _ProcessArtifactFilesSource(self, source):
"""Get artifact responses, extract paths and send corresponding files."""
if source.path_type != rdf_paths.PathSpec.PathType.OS:
raise ValueError("Only supported path type is OS.")
# TODO(user): Check paths for GlobExpressions.
# If it contains a * ... |
Glob paths and return StatEntry objects. | def _ProcessFileSource(self, source):
"""Glob paths and return StatEntry objects."""
if source.path_type != rdf_paths.PathSpec.PathType.OS:
raise ValueError("Only supported path type is OS.")
paths = artifact_utils.InterpolateListKbAttributes(
source.base_source.attributes["paths"], self.kno... |
Prepare a request for calling the execute command action. | def _ProcessCommandSource(self, source):
"""Prepare a request for calling the execute command action."""
action = standard.ExecuteCommandFromClient
request = rdf_client_action.ExecuteRequest(
cmd=source.base_source.attributes["cmd"],
args=source.base_source.attributes["args"],
)
yiel... |
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 ClientMetadata records for a list of clients. | def MultiReadClientMetadata(self, client_ids, cursor=None):
"""Reads ClientMetadata records for a list of clients."""
ids = [db_utils.ClientIDToInt(client_id) for client_id in client_ids]
query = ("SELECT client_id, fleetspeak_enabled, certificate, "
"UNIX_TIMESTAMP(last_ping), "
"... |
Write new client snapshot. | def WriteClientSnapshot(self, snapshot, cursor=None):
"""Write new client snapshot."""
insert_history_query = (
"INSERT INTO client_snapshot_history(client_id, timestamp, "
"client_snapshot) VALUES (%s, FROM_UNIXTIME(%s), %s)")
insert_startup_query = (
"INSERT INTO client_startup_his... |
Reads the latest client snapshots for a list of clients. | def MultiReadClientSnapshot(self, client_ids, cursor=None):
"""Reads the latest client snapshots for a list of clients."""
int_ids = [db_utils.ClientIDToInt(cid) for cid in client_ids]
query = (
"SELECT h.client_id, h.client_snapshot, UNIX_TIMESTAMP(h.timestamp),"
" s.startup_info "
... |
Reads the full history for a particular client. | def ReadClientSnapshotHistory(self, client_id, timerange=None, cursor=None):
"""Reads the full history for a particular client."""
client_id_int = db_utils.ClientIDToInt(client_id)
query = ("SELECT sn.client_snapshot, st.startup_info, "
" UNIX_TIMESTAMP(sn.timestamp) FROM "
... |
Writes the full history for a particular client. | def WriteClientSnapshotHistory(self, clients, cursor=None):
"""Writes the full history for a particular client."""
client_id = clients[0].client_id
latest_timestamp = max(client.timestamp for client in clients)
query = ""
params = {
"client_id": db_utils.ClientIDToInt(client_id),
"l... |
Writes a new client startup record. | def WriteClientStartupInfo(self, client_id, startup_info, cursor=None):
"""Writes a new client startup record."""
query = """
SET @now = NOW(6);
INSERT INTO client_startup_history (client_id, timestamp, startup_info)
VALUES (%(client_id)s, @now, %(startup_info)s);
UPDATE clients
SE... |
Reads the latest client startup record for a single client. | def ReadClientStartupInfo(self, client_id, cursor=None):
"""Reads the latest client startup record for a single client."""
query = (
"SELECT startup_info, UNIX_TIMESTAMP(timestamp) "
"FROM clients, client_startup_history "
"WHERE clients.last_startup_timestamp=client_startup_history.time... |
Reads the full startup history for a particular client. | def ReadClientStartupInfoHistory(self, client_id, timerange=None,
cursor=None):
"""Reads the full startup history for a particular client."""
client_id_int = db_utils.ClientIDToInt(client_id)
query = ("SELECT startup_info, UNIX_TIMESTAMP(timestamp) "
"FROM c... |
Creates a ClientFullInfo object from a database response. | def _ResponseToClientsFullInfo(self, response):
"""Creates a ClientFullInfo object from a database response."""
c_full_info = None
prev_cid = None
for row in response:
(cid, fs, crt, ping, clk, ip, foreman, first, last_client_ts,
last_crash_ts, last_startup_ts, client_obj, client_startup_ob... |
Reads full client information for a list of clients. | def MultiReadClientFullInfo(self, client_ids, min_last_ping=None,
cursor=None):
"""Reads full client information for a list of clients."""
if not client_ids:
return {}
query = (
"SELECT "
"c.client_id, c.fleetspeak_enabled, c.certificate, "
"UNIX_... |
Reads client ids for all clients in the database. | def ReadClientLastPings(self,
min_last_ping=None,
max_last_ping=None,
fleetspeak_enabled=None,
cursor=None):
"""Reads client ids for all clients in the database."""
query = "SELECT client_id, UNIX_TIMESTAMP(l... |
Associates the provided keywords with the client. | def AddClientKeywords(self, client_id, keywords, cursor=None):
"""Associates the provided keywords with the client."""
cid = db_utils.ClientIDToInt(client_id)
keywords = set(keywords)
args = [(cid, mysql_utils.Hash(kw), kw) for kw in keywords]
args = list(collection.Flatten(args))
query = """
... |
Removes the association of a particular client to a keyword. | def RemoveClientKeyword(self, client_id, keyword, cursor=None):
"""Removes the association of a particular client to a keyword."""
cursor.execute(
"DELETE FROM client_keywords "
"WHERE client_id = %s AND keyword_hash = %s",
[db_utils.ClientIDToInt(client_id),
mysql_utils.Hash(ke... |
Lists the clients associated with keywords. | def ListClientsForKeywords(self, keywords, start_time=None, cursor=None):
"""Lists the clients associated with keywords."""
keywords = set(keywords)
hash_to_kw = {mysql_utils.Hash(kw): kw for kw in keywords}
result = {kw: [] for kw in keywords}
query = """
SELECT keyword_hash, client_id
... |
Attaches a list of user labels to a client. | def AddClientLabels(self, client_id, owner, labels, cursor=None):
"""Attaches a list of user labels to a client."""
cid = db_utils.ClientIDToInt(client_id)
labels = set(labels)
args = [(cid, mysql_utils.Hash(owner), owner, label) for label in labels]
args = list(collection.Flatten(args))
query ... |
Reads the user labels for a list of clients. | def MultiReadClientLabels(self, client_ids, cursor=None):
"""Reads the user labels for a list of clients."""
int_ids = [db_utils.ClientIDToInt(cid) for cid in client_ids]
query = ("SELECT client_id, owner_username, label "
"FROM client_labels "
"WHERE client_id IN ({})").format(",... |
Removes a list of user labels from a given client. | def RemoveClientLabels(self, client_id, owner, labels, cursor=None):
"""Removes a list of user labels from a given client."""
query = ("DELETE FROM client_labels "
"WHERE client_id = %s AND owner_username_hash = %s "
"AND label IN ({})").format(", ".join(["%s"] * len(labels)))
arg... |
Reads the user labels for a list of clients. | def ReadAllClientLabels(self, cursor=None):
"""Reads the user labels for a list of clients."""
cursor.execute("SELECT DISTINCT owner_username, label FROM client_labels")
result = []
for owner, label in cursor.fetchall():
result.append(rdf_objects.ClientLabel(name=label, owner=owner))
result... |
Writes a new client crash record. | def WriteClientCrashInfo(self, client_id, crash_info, cursor=None):
"""Writes a new client crash record."""
query = """
SET @now = NOW(6);
INSERT INTO client_crash_history (client_id, timestamp, crash_info)
VALUES (%(client_id)s, @now, %(crash_info)s);
UPDATE clients
SET last_crash... |
Reads the latest client crash record for a single client. | def ReadClientCrashInfo(self, client_id, cursor=None):
"""Reads the latest client crash record for a single client."""
cursor.execute(
"SELECT UNIX_TIMESTAMP(timestamp), crash_info "
"FROM clients, client_crash_history WHERE "
"clients.client_id = client_crash_history.client_id AND "
... |
Reads the full crash history for a particular client. | def ReadClientCrashInfoHistory(self, client_id, cursor=None):
"""Reads the full crash history for a particular client."""
cursor.execute(
"SELECT UNIX_TIMESTAMP(timestamp), crash_info "
"FROM client_crash_history WHERE "
"client_crash_history.client_id = %s "
"ORDER BY timestamp ... |
Stores a ClientStats instance. | def WriteClientStats(self,
client_id,
stats,
cursor=None):
"""Stores a ClientStats instance."""
try:
cursor.execute(
"""
INSERT INTO client_stats (client_id, payload, timestamp)
VALUES (%s, %s, FROM_UNIXTIM... |
Reads ClientStats for a given client and time range. | def ReadClientStats(self,
client_id,
min_timestamp,
max_timestamp,
cursor=None):
"""Reads ClientStats for a given client and time range."""
cursor.execute(
"""
SELECT payload FROM client_stats
WHERE ... |
Deletes ClientStats older than a given timestamp. | def DeleteOldClientStats(self, yield_after_count,
retention_time
):
"""Deletes ClientStats older than a given timestamp."""
yielded = False
while True:
deleted_count = self._DeleteClientStats(
limit=yield_after_count, retention_time=rete... |
Deletes up to `limit` ClientStats older than `retention_time`. | def _DeleteClientStats(self,
limit,
retention_time,
cursor=None):
"""Deletes up to `limit` ClientStats older than `retention_time`."""
cursor.execute(
"DELETE FROM client_stats WHERE timestamp < FROM_UNIXTIME(%s) LIMIT %s",
... |
Returns client-activity metrics for a given statistic.
Args:
statistic: The name of the statistic, which should also be a column in the
'clients' table.
day_buckets: A set of n-day-active buckets.
cursor: MySQL cursor for executing queries. | def _CountClientStatisticByLabel(self, statistic, day_buckets, cursor):
"""Returns client-activity metrics for a given statistic.
Args:
statistic: The name of the statistic, which should also be a column in the
'clients' table.
day_buckets: A set of n-day-active buckets.
cursor: MySQL... |
Parses string path component to an `PathComponent` instance.
Args:
item: A path component string to be parsed.
opts: A `PathOpts` object.
Returns:
`PathComponent` instance corresponding to given path fragment.
Raises:
ValueError: If the path item contains a recursive component fragment but
... | def ParsePathItem(item, opts=None):
"""Parses string path component to an `PathComponent` instance.
Args:
item: A path component string to be parsed.
opts: A `PathOpts` object.
Returns:
`PathComponent` instance corresponding to given path fragment.
Raises:
ValueError: If the path item contain... |
Parses given path into a stream of `PathComponent` instances.
Args:
path: A path to be parsed.
opts: An `PathOpts` object.
Yields:
`PathComponent` instances corresponding to the components of the given path.
Raises:
ValueError: If path contains more than one recursive component. | def ParsePath(path,
opts = None):
"""Parses given path into a stream of `PathComponent` instances.
Args:
path: A path to be parsed.
opts: An `PathOpts` object.
Yields:
`PathComponent` instances corresponding to the components of the given path.
Raises:
ValueError: If path contai... |
Applies all expansion mechanisms to the given path.
Args:
path: A path to expand.
opts: A `PathOpts` object.
Yields:
All paths possible to obtain from a given path by performing expansions. | def ExpandPath(path, opts=None):
"""Applies all expansion mechanisms to the given path.
Args:
path: A path to expand.
opts: A `PathOpts` object.
Yields:
All paths possible to obtain from a given path by performing expansions.
"""
precondition.AssertType(path, Text)
for grouped_path in ExpandG... |
Performs group expansion on a given path.
For example, given path `foo/{bar,baz}/{quux,norf}` this method will yield
`foo/bar/quux`, `foo/bar/norf`, `foo/baz/quux`, `foo/baz/norf`.
Args:
path: A path to expand.
Yields:
Paths that can be obtained from given path by expanding groups. | def ExpandGroups(path):
"""Performs group expansion on a given path.
For example, given path `foo/{bar,baz}/{quux,norf}` this method will yield
`foo/bar/quux`, `foo/bar/norf`, `foo/baz/quux`, `foo/baz/norf`.
Args:
path: A path to expand.
Yields:
Paths that can be obtained from given path by expandi... |
Performs glob expansion on a given path.
Path can contain regular glob elements (such as `**`, `*`, `?`, `[a-z]`). For
example, having files `foo`, `bar`, `baz` glob expansion of `ba?` will yield
`bar` and `baz`.
Args:
path: A path to expand.
opts: A `PathOpts` object.
Returns:
Generator over a... | def ExpandGlobs(path, opts = None):
"""Performs glob expansion on a given path.
Path can contain regular glob elements (such as `**`, `*`, `?`, `[a-z]`). For
example, having files `foo`, `bar`, `baz` glob expansion of `ba?` will yield
`bar` and `baz`.
Args:
path: A path to expand.
opts: A `PathOpts`... |
Returns children of a given directory.
This function is intended to be used by the `PathComponent` subclasses to get
initial list of potential children that then need to be filtered according to
the rules of a specific component.
Args:
dirpath: A path to the directory.
pathtype: The pathtype to use.
... | def _ListDir(dirpath, pathtype):
"""Returns children of a given directory.
This function is intended to be used by the `PathComponent` subclasses to get
initial list of potential children that then need to be filtered according to
the rules of a specific component.
Args:
dirpath: A path to the directory... |
Gather open network connection stats.
Args:
args: An `rdf_client_action.ListNetworkConnectionArgs` instance.
Yields:
`rdf_client_network.NetworkConnection` instances. | def ListNetworkConnectionsFromClient(args):
"""Gather open network connection stats.
Args:
args: An `rdf_client_action.ListNetworkConnectionArgs` instance.
Yields:
`rdf_client_network.NetworkConnection` instances.
"""
for proc in psutil.process_iter():
try:
connections = proc.connections()... |
Iterates over contents of the intrusive linked list of `ifaddrs`.
Args:
ifaddrs: A pointer to the first node of `ifaddrs` linked list. Can be NULL.
Yields:
Instances of `Ifaddr`. | def IterIfaddrs(ifaddrs):
"""Iterates over contents of the intrusive linked list of `ifaddrs`.
Args:
ifaddrs: A pointer to the first node of `ifaddrs` linked list. Can be NULL.
Yields:
Instances of `Ifaddr`.
"""
precondition.AssertOptionalType(ifaddrs, ctypes.POINTER(Ifaddrs))
while ifaddrs:
... |
Parses contents of the intrusive linked list of `ifaddrs`.
Args:
ifaddrs: A pointer to the first node of `ifaddrs` linked list. Can be NULL.
Returns:
An iterator over instances of `rdf_client_network.Interface`. | def ParseIfaddrs(ifaddrs):
"""Parses contents of the intrusive linked list of `ifaddrs`.
Args:
ifaddrs: A pointer to the first node of `ifaddrs` linked list. Can be NULL.
Returns:
An iterator over instances of `rdf_client_network.Interface`.
"""
precondition.AssertOptionalType(ifaddrs, ctypes.POINTE... |
Enumerate all MAC addresses. | def EnumerateInterfacesFromClient(args):
"""Enumerate all MAC addresses."""
del args # Unused
libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c"))
ifa = Ifaddrs()
p_ifa = ctypes.pointer(ifa)
libc.getifaddrs(ctypes.pointer(p_ifa))
for iface in ParseIfaddrs(p_ifa):
yield iface
libc.freeif... |
List all local filesystems mounted on this system. | def EnumerateFilesystemsFromClient(args):
"""List all local filesystems mounted on this system."""
del args # Unused.
for fs_struct in client_utils_osx.GetFileSystems():
yield rdf_client_fs.Filesystem(
device=fs_struct.f_mntfromname,
mount_point=fs_struct.f_mntonname,
type=fs_struct.f... |
Create the Service protobuf.
Args:
job: Launchdjobdict from servicemanagement framework.
Returns:
sysinfo_pb2.OSXServiceInformation proto | def CreateServiceProto(job):
"""Create the Service protobuf.
Args:
job: Launchdjobdict from servicemanagement framework.
Returns:
sysinfo_pb2.OSXServiceInformation proto
"""
service = rdf_client.OSXServiceInformation(
label=job.get("Label"),
program=job.get("Program"),
sessiontype=... |
Get running launchd jobs.
Args:
args: Unused.
Yields:
`rdf_client.OSXServiceInformation` instances.
Raises:
UnsupportedOSVersionError: for OS X earlier than 10.6. | def OSXEnumerateRunningServicesFromClient(args):
"""Get running launchd jobs.
Args:
args: Unused.
Yields:
`rdf_client.OSXServiceInformation` instances.
Raises:
UnsupportedOSVersionError: for OS X earlier than 10.6.
"""
del args # Unused.
osx_version = client_utils_osx.OSXVersion()
vers... |
This kills us with no cleanups. | def Run(self, unused_arg):
"""This kills us with no cleanups."""
logging.debug("Disabling service")
msg = "Service disabled."
if hasattr(sys, "frozen"):
grr_binary = os.path.abspath(sys.executable)
elif __file__:
grr_binary = os.path.abspath(__file__)
try:
os.remove(grr_binar... |
Sets up remote debugging using pydevd, connecting to localhost:`port`. | def _start_remote_debugging(port):
"""Sets up remote debugging using pydevd, connecting to localhost:`port`."""
try:
print("Connecting to remote debugger on localhost:{}.".format(port))
import pydevd # pylint: disable=g-import-not-at-top
pydevd.settrace(
"localhost",
port=port,
... |
This installer extracts a config file from the .pkg file. | def ExtractConfig(self):
"""This installer extracts a config file from the .pkg file."""
logging.info("Extracting config file from .pkg.")
pkg_path = os.environ.get("PACKAGE_PATH", None)
if pkg_path is None:
logging.error("Could not locate package, giving up.")
return
zf = zipfile.ZipFi... |
Yields all flows for the given client_id and time range.
Args:
client_id: client URN
min_create_time: minimum creation time (inclusive)
token: acl token
Yields: flow_objects.Flow objects | def _LoadFlows(self, client_id, min_create_time, token):
"""Yields all flows for the given client_id and time range.
Args:
client_id: client URN
min_create_time: minimum creation time (inclusive)
token: acl token
Yields: flow_objects.Flow objects
"""
if data_store.RelationalDBEnab... |
Enforce DailyFlowRequestLimit and FlowDuplicateInterval.
Look at the flows that have run on this client recently and check
we aren't exceeding our limits. Raises if limits will be exceeded by running
the specified flow.
Args:
client_id: client URN
user: username string
flow_name: flo... | def EnforceLimits(self, client_id, user, flow_name, flow_args, token=None):
"""Enforce DailyFlowRequestLimit and FlowDuplicateInterval.
Look at the flows that have run on this client recently and check
we aren't exceeding our limits. Raises if limits will be exceeded by running
the specified flow.
... |
Builds a stat entry object from a given path.
Args:
path: A path (string value) to stat.
pathspec: A `PathSpec` corresponding to the `path`.
ext_attrs: Whether to include extended file attributes in the result.
Returns:
`StatEntry` object. | def StatEntryFromPath(path, pathspec, ext_attrs=True):
"""Builds a stat entry object from a given path.
Args:
path: A path (string value) to stat.
pathspec: A `PathSpec` corresponding to the `path`.
ext_attrs: Whether to include extended file attributes in the result.
Returns:
`StatEntry` object... |
Build a stat entry object from a given stat object.
Args:
stat: A `Stat` object.
pathspec: A `PathSpec` from which `stat` was obtained.
ext_attrs: Whether to include extended file attributes in the result.
Returns:
`StatEntry` object. | def StatEntryFromStat(stat,
pathspec,
ext_attrs = True):
"""Build a stat entry object from a given stat object.
Args:
stat: A `Stat` object.
pathspec: A `PathSpec` from which `stat` was obtained.
ext_attrs: Whether to include extended file attributes in the r... |
Returns a `os.stat_result` with most information from `StatEntry`.
This is a lossy conversion, only the 10 first stat_result fields are
populated, because the os.stat_result constructor is inflexible.
Args:
stat_entry: An instance of rdf_client_fs.StatEntry.
Returns:
An instance of `os.stat_result` w... | def StatResultFromStatEntry(
stat_entry):
"""Returns a `os.stat_result` with most information from `StatEntry`.
This is a lossy conversion, only the 10 first stat_result fields are
populated, because the os.stat_result constructor is inflexible.
Args:
stat_entry: An instance of rdf_client_fs.StatEntry... |
Initializes Api(Client|Hunt|CronJob)Approval from an AFF4 object. | def _InitApiApprovalFromAff4Object(api_approval, approval_obj):
"""Initializes Api(Client|Hunt|CronJob)Approval from an AFF4 object."""
api_approval.id = approval_obj.urn.Basename()
api_approval.reason = approval_obj.Get(approval_obj.Schema.REASON)
api_approval.requestor = approval_obj.Get(approval_obj.Schema.... |
Initializes Api(Client|Hunt|CronJob)Approval from the database object. | def _InitApiApprovalFromDatabaseObject(api_approval, db_obj):
"""Initializes Api(Client|Hunt|CronJob)Approval from the database object."""
api_approval.id = db_obj.approval_id
api_approval.requestor = db_obj.requestor_username
api_approval.reason = db_obj.reason
api_approval.notified_users = sorted(db_obj.n... |
Initializes this object from an existing notification.
Args:
notification: A rdfvalues.flows.Notification object.
is_pending: Indicates whether the user has already seen this notification
or not.
Returns:
The current instance. | def InitFromNotification(self, notification, is_pending=False):
"""Initializes this object from an existing notification.
Args:
notification: A rdfvalues.flows.Notification object.
is_pending: Indicates whether the user has already seen this notification
or not.
Returns:
The curr... |
Gets all approvals for a given user and approval type.
Args:
approval_type: The type of approvals to get.
offset: The starting index within the collection.
count: The number of items to return.
filter_func: A predicate function, returning True if a specific approval
should be includ... | def _GetApprovals(self,
approval_type,
offset,
count,
filter_func=None,
token=None):
"""Gets all approvals for a given user and approval type.
Args:
approval_type: The type of approvals to get.
offse... |
Fetches and renders current user's settings. | def Handle(self, unused_args, token=None):
"""Fetches and renders current user's settings."""
result = ApiGrrUser(username=token.username)
if data_store.RelationalDBEnabled():
user_record = data_store.REL_DB.ReadGRRUser(token.username)
result.InitFromDatabaseObject(user_record)
else:
... |
Deletes the notification from the pending notifications. | def Handle(self, args, token=None):
"""Deletes the notification from the pending notifications."""
if data_store.RelationalDBEnabled():
self.HandleRelationalDB(args, token=token)
else:
self.HandleLegacy(args, token=token) |
Starts a new run for the given cron job. | def StartRun(self, wait_for_start_event, signal_event, wait_for_write_event):
"""Starts a new run for the given cron job."""
# Signal that the cron thread has started. This way the cron scheduler
# will know that the task is not sitting in a threadpool queue, but is
# actually executing.
wait_for_st... |
Schedules all system cron jobs. | def ScheduleSystemCronJobs(names=None):
"""Schedules all system cron jobs."""
errors = []
disabled_classes = config.CONFIG["Cron.disabled_cron_jobs"]
for name in disabled_classes:
try:
cls = registry.SystemCronJobRegistry.CronJobClassByName(name)
except ValueError:
errors.append("Cron job n... |
Creates a cron job that runs given flow with a given frequency.
Args:
cron_args: A protobuf of type rdf_cronjobs.CreateCronJobArgs.
job_id: Use this job_id instead of an autogenerated unique name (used for
system cron jobs - we want them to have well-defined persistent name).
enabled: If ... | def CreateJob(self, cron_args=None, job_id=None, enabled=True, token=None):
"""Creates a cron job that runs given flow with a given frequency.
Args:
cron_args: A protobuf of type rdf_cronjobs.CreateCronJobArgs.
job_id: Use this job_id instead of an autogenerated unique name (used for
system... |
Returns a list of ids of all currently running cron jobs. | def ListJobs(self, token=None):
"""Returns a list of ids of all currently running cron jobs."""
del token
return [job.cron_job_id for job in data_store.REL_DB.ReadCronJobs()] |
Tries to lock and run cron jobs.
Args:
names: List of cron jobs to run. If unset, run them all.
token: security token.
Raises:
OneOrMoreCronJobsFailedError: if one or more individual cron jobs fail.
Note: a failure of a single cron job doesn't preclude other cron jobs
from runni... | def RunOnce(self, names=None, token=None):
"""Tries to lock and run cron jobs.
Args:
names: List of cron jobs to run. If unset, run them all.
token: security token.
Raises:
OneOrMoreCronJobsFailedError: if one or more individual cron jobs fail.
Note: a failure of a single cron job... |
Cleans up job state if the last run is stuck. | def TerminateStuckRunIfNeeded(self, job):
"""Cleans up job state if the last run is stuck."""
if job.current_run_id and job.last_run_time and job.lifetime:
now = rdfvalue.RDFDatetime.Now()
# We add additional 10 minutes to give the job run a chance to kill itself
# during one of the HeartBeat ... |
Does the actual work of the Cron, if the job is due to run.
Args:
job: The cronjob rdfvalue that should be run. Must be leased.
Returns:
A boolean indicating if this cron job was started or not. False may
be returned when the threadpool is already full.
Raises:
LockError: if the o... | def RunJob(self, job):
"""Does the actual work of the Cron, if the job is due to run.
Args:
job: The cronjob rdfvalue that should be run. Must be leased.
Returns:
A boolean indicating if this cron job was started or not. False may
be returned when the threadpool is already full.
Rai... |
Determines if the given job is due for another run.
Args:
job: The cron job rdfvalue object.
Returns:
True if it is time to run based on the specified frequency. | def JobDueToRun(self, job):
"""Determines if the given job is due for another run.
Args:
job: The cron job rdfvalue object.
Returns:
True if it is time to run based on the specified frequency.
"""
if not job.enabled:
return False
if job.forced_run_requested:
return Tru... |
Deletes runs that were started before the timestamp given. | def DeleteOldRuns(self, cutoff_timestamp=None):
"""Deletes runs that were started before the timestamp given."""
if cutoff_timestamp is None:
raise ValueError("cutoff_timestamp can't be None")
return data_store.REL_DB.DeleteOldCronJobRuns(
cutoff_timestamp=cutoff_timestamp) |
Writes a list of message handler requests to the database. | def WriteMessageHandlerRequests(self, requests, cursor=None):
"""Writes a list of message handler requests to the database."""
query = ("INSERT IGNORE INTO message_handler_requests "
"(handlername, request_id, request) VALUES ")
value_templates = []
args = []
for r in requests:
a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.