INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Test if host data should trigger a check. | def Match(self, artifact=None, os_name=None, cpe=None, label=None):
"""Test if host data should trigger a check.
Args:
artifact: An artifact name.
os_name: An OS string.
cpe: A CPE string.
label: A label string.
Returns:
A list of conditions that match.
"""
return [
... |
Find the host attributes that trigger data collection. | def Search(self, artifact=None, os_name=None, cpe=None, label=None):
"""Find the host attributes that trigger data collection.
Args:
artifact: An artifact name.
os_name: An OS string.
cpe: A CPE string.
label: A label string.
Returns:
A list of conditions that contain the spe... |
Find the artifacts that correspond with other trigger conditions. | def Artifacts(self, os_name=None, cpe=None, label=None):
"""Find the artifacts that correspond with other trigger conditions.
Args:
os_name: An OS string.
cpe: A CPE string.
label: A label string.
Returns:
A list of artifacts to be processed.
"""
return [
c.artifact... |
Find the methods that evaluate data that meets this condition. | def Calls(self, conditions=None):
"""Find the methods that evaluate data that meets this condition.
Args:
conditions: A tuple of (artifact, os_name, cpe, label)
Returns:
A list of methods that evaluate the data.
"""
results = set()
if conditions is None:
conditions = [None]
... |
Returns plugins metadata in ApiReportDescriptor. | def GetReportDescriptor(cls):
"""Returns plugins' metadata in ApiReportDescriptor."""
if cls.TYPE is None:
raise ValueError("%s.TYPE is unintialized." % cls)
if cls.TITLE is None:
raise ValueError("%s.TITLE is unintialized." % cls)
if cls.SUMMARY is None:
raise ValueError("%s.SUMMARY... |
Make a cert and sign it with the CA s private key. | def MakeCASignedCert(common_name,
private_key,
ca_cert,
ca_private_key,
serial_number=2):
"""Make a cert and sign it with the CA's private key."""
public_key = private_key.GetPublicKey()
builder = x509.CertificateBuilder()
bui... |
Generate a CA certificate. | def MakeCACert(private_key,
common_name=u"grr",
issuer_cn=u"grr_test",
issuer_c=u"US"):
"""Generate a CA certificate.
Args:
private_key: The private key to use.
common_name: Name for cert.
issuer_cn: Name for issuer.
issuer_c: Country for issuer.
Retu... |
Returns AuditEvents for given handlers actions and timerange. | def _LoadAuditEvents(handlers,
get_report_args,
actions=None,
token=None,
transformers=None):
"""Returns AuditEvents for given handlers, actions, and timerange."""
if transformers is None:
transformers = {}
if data_store.Rela... |
Converts an APIAuditEntry to a legacy AuditEvent. | def _EntryToEvent(entry, handlers, transformers):
"""Converts an APIAuditEntry to a legacy AuditEvent."""
event = rdf_events.AuditEvent(
timestamp=entry.timestamp,
user=entry.username,
action=handlers[entry.router_method_name])
for fn in transformers:
fn(entry, event)
return event |
Extracts a Client ID from an APIAuditEntry s HTTP request path. | def _ExtractClientIdFromPath(entry, event):
"""Extracts a Client ID from an APIAuditEntry's HTTP request path."""
match = re.match(r".*(C\.[0-9a-fA-F]{16}).*", entry.http_request_path)
if match:
event.client = match.group(1) |
Extracts a CronJob ID from an APIAuditEntry s HTTP request path. | def _ExtractCronJobIdFromPath(entry, event):
"""Extracts a CronJob ID from an APIAuditEntry's HTTP request path."""
match = re.match(r".*cron-job/([^/]+).*", entry.http_request_path)
if match:
event.urn = "aff4:/cron/{}".format(match.group(1)) |
Extracts a Hunt ID from an APIAuditEntry s HTTP request path. | def _ExtractHuntIdFromPath(entry, event):
"""Extracts a Hunt ID from an APIAuditEntry's HTTP request path."""
match = re.match(r".*hunt/([^/]+).*", entry.http_request_path)
if match:
event.urn = "aff4:/hunts/{}".format(match.group(1)) |
Filter the cron job approvals in the given timerange. | def GetReportData(self, get_report_args, token=None):
"""Filter the cron job approvals in the given timerange."""
ret = rdf_report_plugins.ApiReportData(
representation_type=RepresentationType.AUDIT_CHART,
audit_chart=rdf_report_plugins.ApiAuditChartReportData(
used_fields=self.USED_... |
Filter the last week of user actions. | def GetReportData(self, get_report_args, token):
"""Filter the last week of user actions."""
ret = rdf_report_plugins.ApiReportData(
representation_type=RepresentationType.PIE_CHART)
counts = self._GetUserCounts(get_report_args, token)
for username in aff4_users.GRRUser.SYSTEM_USERS:
del ... |
Filter the last week of user actions. | def GetReportData(self, get_report_args, token):
"""Filter the last week of user actions."""
ret = rdf_report_plugins.ApiReportData(
representation_type=RepresentationType.STACK_CHART)
week_duration = rdfvalue.Duration("7d")
num_weeks = math.ceil(get_report_args.duration.seconds /
... |
Returns the corresponding AFF4 attribute for the given report type. | def _GetAFF4AttributeForReportType(report_type
):
"""Returns the corresponding AFF4 attribute for the given report type."""
if report_type == rdf_stats.ClientGraphSeries.ReportType.GRR_VERSION:
return aff4_stats.ClientFleetStats.SchemaCls.GRRVERSION_HISTOGRAM
elif report_type... |
Writes graph series for a particular client label to the DB. | def WriteGraphSeries(graph_series,
label,
token = None):
"""Writes graph series for a particular client label to the DB.
Args:
graph_series: A series of rdf_stats.Graphs containing aggregated data for a
particular report-type.
label: Client label by which dat... |
Fetches graph series for the given label and report - type from the DB. | def FetchAllGraphSeries(
label,
report_type,
period = None,
token = None
):
"""Fetches graph series for the given label and report-type from the DB.
Args:
label: Client label to fetch data for.
report_type: rdf_stats.ClientGraphSeries.ReportType to fetch data for.
period: rdfvalue.Durat... |
Fetches graph - series from the legacy DB [ see FetchAllGraphSeries () ]. | def _FetchAllGraphSeriesFromTheLegacyDB(
label,
report_type,
period = None,
token = None
):
"""Fetches graph-series from the legacy DB [see FetchAllGraphSeries()]."""
if period is None:
time_range = aff4.ALL_TIMES
else:
range_end = rdfvalue.RDFDatetime.Now()
time_range = (range_end - p... |
Fetches the latest graph series for a client label from the DB. | def FetchMostRecentGraphSeries(label,
report_type,
token = None
):
"""Fetches the latest graph series for a client label from the DB.
Args:
label: Client label to fetch data for.
report_type: rdf_stats.ClientGraphSe... |
Fetches the latest graph - series for a client label from the legacy DB. | def _FetchMostRecentGraphSeriesFromTheLegacyDB(
label,
report_type,
token = None
):
"""Fetches the latest graph-series for a client label from the legacy DB.
Args:
label: Client label to fetch data for.
report_type: rdf_stats.ClientGraphSeries.ReportType to fetch data for.
token: ACL token ... |
Generates a new unique task_id. | def GenerateTaskID(self):
"""Generates a new, unique task_id."""
# Random number can not be zero since next_id_base must increment.
random_number = random.PositiveUInt16()
# 16 bit random numbers
with GrrMessage.lock:
next_id_base = GrrMessage.next_id_base
id_base = (next_id_base + ran... |
The payload property automatically decodes the encapsulated data. | def payload(self):
"""The payload property automatically decodes the encapsulated data."""
if self.args_rdf_name:
# Now try to create the correct RDFValue.
result_cls = self.classes.get(self.args_rdf_name, rdfvalue.RDFString)
result = result_cls.FromSerializedString(
self.Get("args"... |
Automatically encode RDFValues into the message. | def payload(self, value):
"""Automatically encode RDFValues into the message."""
if not isinstance(value, rdfvalue.RDFValue):
raise RuntimeError("Payload must be an RDFValue.")
self.Set("args", value.SerializeToString())
# pylint: disable=protected-access
if value._age is not None:
sel... |
Adds new files consisting of given blob references. | def AddFilesWithUnknownHashes(
client_path_blob_refs,
use_external_stores = True
):
"""Adds new files consisting of given blob references.
Args:
client_path_blob_refs: A dictionary mapping `db.ClientPath` instances to
lists of blob references.
use_external_stores: A flag indicating if the fil... |
Add a new file consisting of given blob IDs. | def AddFileWithUnknownHash(client_path, blob_refs, use_external_stores=True):
"""Add a new file consisting of given blob IDs."""
precondition.AssertType(client_path, db.ClientPath)
precondition.AssertIterableType(blob_refs, rdf_objects.BlobReference)
return AddFilesWithUnknownHashes(
{client_path: blob_re... |
Checks if files with given hashes are present in the file store. | def CheckHashes(hash_ids):
"""Checks if files with given hashes are present in the file store.
Args:
hash_ids: A list of SHA256HashID objects.
Returns:
A dict where SHA256HashID objects are keys. Corresponding values
may be False (if hash id is not present) or True if it is not present.
"""
retu... |
Opens latest content of a given file for reading. | def OpenFile(client_path, max_timestamp=None):
"""Opens latest content of a given file for reading.
Args:
client_path: A db.ClientPath object describing path to a file.
max_timestamp: If specified, will open the last collected version with a
timestamp equal or lower than max_timestamp. If not specifi... |
Streams contents of given files. | def StreamFilesChunks(client_paths, max_timestamp=None, max_size=None):
"""Streams contents of given files.
Args:
client_paths: db.ClientPath objects describing paths to files.
max_timestamp: If specified, then for every requested file will open the
last collected version of the file with a timestamp... |
Adds multiple files to the file store. | def AddFiles(self, hash_id_metadatas):
"""Adds multiple files to the file store.
Args:
hash_id_metadatas: A dictionary mapping hash ids to file metadata (a tuple
of hash client path and blob references).
"""
for hash_id, metadata in iteritems(hash_id_metadatas):
self.AddFile(hash_id... |
Fetches a chunk corresponding to the current offset. | def _GetChunk(self):
"""Fetches a chunk corresponding to the current offset."""
found_ref = None
for ref in self._blob_refs:
if self._offset >= ref.offset and self._offset < (ref.offset + ref.size):
found_ref = ref
break
if not found_ref:
return None, None
# If self._c... |
Reads data. | def Read(self, length=None):
"""Reads data."""
if length is None:
length = self._length - self._offset
if length > self._max_unbound_read:
raise OversizedReadError("Attempted to read %d bytes when "
"Server.max_unbound_read_size is %d" %
... |
Moves the reading cursor. | def Seek(self, offset, whence=os.SEEK_SET):
"""Moves the reading cursor."""
if whence == os.SEEK_SET:
self._offset = offset
elif whence == os.SEEK_CUR:
self._offset += offset
elif whence == os.SEEK_END:
self._offset = self._length + offset
else:
raise ValueError("Invalid whe... |
Uploads chunks of a file on a given path to the transfer store flow. | def UploadFilePath(self, filepath, offset=0, amount=None):
"""Uploads chunks of a file on a given path to the transfer store flow.
Args:
filepath: A path to the file to upload.
offset: An integer offset at which the file upload should start on.
amount: An upper bound on number of bytes to str... |
Uploads chunks of a given file descriptor to the transfer store flow. | def UploadFile(self, fd, offset=0, amount=None):
"""Uploads chunks of a given file descriptor to the transfer store flow.
Args:
fd: A file descriptor to upload.
offset: An integer offset at which the file upload should start on.
amount: An upper bound on number of bytes to stream. If it is `N... |
Uploads a single chunk to the transfer store flow. | def _UploadChunk(self, chunk):
"""Uploads a single chunk to the transfer store flow.
Args:
chunk: A chunk to upload.
Returns:
A `BlobImageChunkDescriptor` object.
"""
blob = _CompressedDataBlob(chunk)
self._action.ChargeBytesToSession(len(chunk.data))
self._action.SendReply(bl... |
Instantiate a rdf_stats. Distribution from a Prometheus Histogram. | def _DistributionFromHistogram(metric, values_by_suffix):
"""Instantiate a rdf_stats.Distribution from a Prometheus Histogram.
Prometheus Histogram uses cumulative "buckets" lower or equal to an upper
bound. At instantiation, +Inf is implicitly appended to the upper bounds.
The delimiters [0.0, 0.1, 0.2 (, +In... |
Parse the crontab file. | def Parse(self, stat, file_object, knowledge_base):
"""Parse the crontab file."""
_ = knowledge_base
entries = []
crondata = file_object.read().decode("utf-8")
jobs = crontab.CronTab(tab=crondata)
for job in jobs:
entries.append(
rdf_cronjobs.CronTabEntry(
minute=... |
Parses the file finder condition types into the condition objects. | def Parse(conditions):
"""Parses the file finder condition types into the condition objects.
Args:
conditions: An iterator over `FileFinderCondition` objects.
Yields:
`MetadataCondition` objects that correspond to the file-finder conditions.
"""
kind = rdf_file_finder.FileFinderConditi... |
Parses the file finder condition types into the condition objects. | def Parse(conditions):
"""Parses the file finder condition types into the condition objects.
Args:
conditions: An iterator over `FileFinderCondition` objects.
Yields:
`ContentCondition` objects that correspond to the file-finder conditions.
"""
kind = rdf_file_finder.FileFinderConditio... |
Scans given file searching for occurrences of given pattern. | def Scan(self, fd,
matcher):
"""Scans given file searching for occurrences of given pattern.
Args:
fd: A file descriptor of the file that needs to be searched.
matcher: A matcher object specifying a pattern to search for.
Yields:
`BufferReference` objects pointing to file part... |
Initialize the server logging configuration. | def ServerLoggingStartupInit():
"""Initialize the server logging configuration."""
global LOGGER
if local_log:
logging.debug("Using local LogInit from %s", local_log)
local_log.LogInit()
logging.debug("Using local AppLogInit from %s", local_log)
LOGGER = local_log.AppLogInit()
else:
LogInit(... |
Return a unique Event ID string. | def GetNewEventId(self, event_time=None):
"""Return a unique Event ID string."""
if event_time is None:
event_time = int(time.time() * 1e6)
return "%s:%s:%s" % (event_time, socket.gethostname(), os.getpid()) |
Log an http based api call. | def LogHttpAdminUIAccess(self, request, response):
"""Log an http based api call.
Args:
request: A WSGI request object.
response: A WSGI response object.
"""
# TODO(user): generate event_id elsewhere and use it for all the log
# messages that have to do with handling corresponding reque... |
Write a log entry for a Frontend or UI Request. | def LogHttpFrontendAccess(self, request, source=None, message_count=None):
"""Write a log entry for a Frontend or UI Request.
Args:
request: A HttpRequest protobuf.
source: Client id of the client initiating the request. Optional.
message_count: Number of messages received from the client. Op... |
A wrapper for the pkg_resource. resource_filename function. | def _GetPkgResources(package_name, filepath):
"""A wrapper for the `pkg_resource.resource_filename` function."""
requirement = pkg_resources.Requirement.parse(package_name)
try:
return pkg_resources.resource_filename(requirement, filepath)
except pkg_resources.DistributionNotFound:
# It may be that the ... |
Computes a path to the specified package resource. | def ResourcePath(package_name, filepath):
"""Computes a path to the specified package resource.
Args:
package_name: A name of the package where the resource is located.
filepath: A path to the resource relative to the package location.
Returns:
A path to the resource or `None` if the resource cannot... |
Computes a path to the specified module. | def ModulePath(module_name):
"""Computes a path to the specified module.
Args:
module_name: A name of the module to get the path for.
Returns:
A path to the specified module.
Raises:
ImportError: If specified module cannot be imported.
"""
module = importlib.import_module(module_name)
path ... |
Function call rate - limiting decorator. | def WithLimitedCallFrequency(min_time_between_calls):
"""Function call rate-limiting decorator.
This decorator ensures that the wrapped function will be called at most
once in min_time_between_calls time for the same set of arguments. For all
excessive calls a previous cached return value will be returned.
... |
Converts ( field - name type ) tuples to MetricFieldDefinition protos. | def FieldDefinitionProtosFromTuples(field_def_tuples):
"""Converts (field-name, type) tuples to MetricFieldDefinition protos."""
# TODO: This needs fixing for Python 3.
field_def_protos = []
for field_name, field_type in field_def_tuples:
if field_type in (int, long):
field_type = rdf_stats.MetricFiel... |
Converts MetricFieldDefinition protos to ( field - name type ) tuples. | def FieldDefinitionTuplesFromProtos(field_def_protos):
"""Converts MetricFieldDefinition protos to (field-name, type) tuples."""
# TODO: This needs fixing for Python 3.
field_def_tuples = []
for proto in field_def_protos:
if proto.field_type == rdf_stats.MetricFieldDefinition.FieldType.INT:
field_type... |
Converts Python types to MetricMetadata. ValueType enum values. | def MetricValueTypeFromPythonType(python_type):
"""Converts Python types to MetricMetadata.ValueType enum values."""
if python_type in (int, long):
return rdf_stats.MetricMetadata.ValueType.INT
elif python_type == float:
return rdf_stats.MetricMetadata.ValueType.FLOAT
else:
raise ValueError("Invalid... |
Converts MetricMetadata. ValueType enums to corresponding Python types. | def PythonTypeFromMetricValueType(value_type):
"""Converts MetricMetadata.ValueType enums to corresponding Python types."""
if value_type == rdf_stats.MetricMetadata.ValueType.INT:
return int
elif value_type == rdf_stats.MetricMetadata.ValueType.FLOAT:
return float
else:
raise ValueError("Unknown va... |
Helper function for creating MetricMetadata for counter metrics. | def CreateCounterMetadata(metric_name, fields=None, docstring=None, units=None):
"""Helper function for creating MetricMetadata for counter metrics."""
return rdf_stats.MetricMetadata(
varname=metric_name,
metric_type=rdf_stats.MetricMetadata.MetricType.COUNTER,
value_type=rdf_stats.MetricMetadata... |
Helper function for creating MetricMetadata for event metrics. | def CreateEventMetadata(metric_name,
bins=None,
fields=None,
docstring=None,
units=None):
"""Helper function for creating MetricMetadata for event metrics."""
return rdf_stats.MetricMetadata(
varname=metric_name,
... |
Helper function for creating MetricMetadata for gauge metrics. | def CreateGaugeMetadata(metric_name,
value_type,
fields=None,
docstring=None,
units=None):
"""Helper function for creating MetricMetadata for gauge metrics."""
return rdf_stats.MetricMetadata(
varname=metric_name,
... |
Import hashes from filename into store. | def ImportFile(store, filename, start):
"""Import hashes from 'filename' into 'store'."""
with io.open(filename, "r") as fp:
reader = csv.Reader(fp.read())
i = 0
current_row = None
product_code_list = []
op_system_code_list = []
for row in reader:
# Skip first row.
i += 1
i... |
Main. | def main(argv):
"""Main."""
del argv # Unused.
server_startup.Init()
filename = flags.FLAGS.filename
if not os.path.exists(filename):
print("File %s does not exist" % filename)
return
with aff4.FACTORY.Create(
filestore.NSRLFileStore.PATH,
filestore.NSRLFileStore,
mode="rw",
... |
r Converts the canonical paths as used by GRR to OS specific paths. | def CanonicalPathToLocalPath(path):
r"""Converts the canonical paths as used by GRR to OS specific paths.
Due to the inconsistencies between handling paths in windows we need to
convert a path to an OS specific version prior to using it. This function
should be called just before any OS specific functions.
... |
Converts path from the local system s convention to the canonical. | def LocalPathToCanonicalPath(path):
"""Converts path from the local system's convention to the canonical."""
path_components = path.split("/")
result = []
for component in path_components:
# Devices must maintain their \\ so they do not get broken up.
m = re.match(r"\\\\.\\", component)
# The compo... |
Provide chmod - like functionality for windows. | def WinChmod(filename, acl_list, user=None):
"""Provide chmod-like functionality for windows.
Doco links:
goo.gl/n7YR1
goo.gl/rDv81
goo.gl/hDobb
Args:
filename: target filename for acl
acl_list: list of ntsecuritycon acl strings to be applied with bitwise OR.
e.g. ["FILE_GENER... |
Tries to find proxies by interrogating all the user s settings. | def FindProxies():
"""Tries to find proxies by interrogating all the user's settings.
This function is a modified urillib.getproxies_registry() from the
standard library. We just store the proxy value in the environment
for urllib to find it.
TODO(user): Iterate through all the possible values if one proxy
... |
Resolves the raw device that contains the path. | def GetRawDevice(path):
"""Resolves the raw device that contains the path.
Args:
path: A path to examine.
Returns:
A pathspec to read the raw device as well as the modified path to read
within the raw device. This is usually the path without the mount point.
Raises:
IOError: if the path does ... |
Returns the service key. | def _GetServiceKey():
"""Returns the service key."""
global _service_key
if _service_key is None:
hive = getattr(winreg, config.CONFIG["Client.config_hive"])
path = config.CONFIG["Client.config_key"]
# Don't use winreg.KEY_WOW64_64KEY since it breaks on Windows 2000
_service_key = winreg.CreateK... |
Wraps the lowlevel RtlGetVersion routine. | def RtlGetVersion(os_version_info_struct):
"""Wraps the lowlevel RtlGetVersion routine.
Args:
os_version_info_struct: instance of either a RTL_OSVERSIONINFOW structure
or a RTL_OSVERSIONINFOEXW structure,
ctypes.Structure-wrapped, with the
... |
Gets the kernel version as string eg. 5. 1. 2600. | def KernelVersion():
"""Gets the kernel version as string, eg. "5.1.2600".
Returns:
The kernel version, or "unknown" in the case of failure.
"""
rtl_osversioninfoexw = RtlOSVersionInfoExw()
try:
RtlGetVersion(rtl_osversioninfoexw)
except OSError:
return "unknown"
return "%d.%d.%d" % (rtl_osv... |
Writes a heartbeat to the registry. | def Heartbeat(self):
"""Writes a heartbeat to the registry."""
service_key = _GetServiceKey()
try:
winreg.SetValueEx(service_key, "Nanny.heartbeat", 0, winreg.REG_DWORD,
int(time.time()))
except OSError as e:
logging.debug("Failed to heartbeat nanny at %s: %s", servic... |
Write the message into the transaction log. | def Write(self, grr_message):
"""Write the message into the transaction log.
Args:
grr_message: A GrrMessage instance.
"""
grr_message = grr_message.SerializeToString()
try:
winreg.SetValueEx(_GetServiceKey(), "Transaction", 0, winreg.REG_BINARY,
grr_message)
... |
Return a GrrMessage instance from the transaction log or None. | def Get(self):
"""Return a GrrMessage instance from the transaction log or None."""
try:
value, reg_type = winreg.QueryValueEx(_GetServiceKey(), "Transaction")
except OSError:
return
if reg_type != winreg.REG_BINARY:
return
try:
return rdf_flows.GrrMessage.FromSerializedStr... |
Returns stat information about the given OS path calling os. [ l ] stat. | def FromPath(cls, path, follow_symlink = True):
"""Returns stat information about the given OS path, calling os.[l]stat.
Args:
path: A path to perform `stat` on.
follow_symlink: True if `stat` of a symlink should be returned instead of
a file that it points to. For non-symlinks this setting... |
Fetches Linux extended file flags. | def _FetchLinuxFlags(self):
"""Fetches Linux extended file flags."""
if platform.system() != "Linux":
return 0
# Since we open a file in the next step we do not want to open a symlink.
# `lsattr` returns an error when trying to check flags of a symlink, so we
# assume that symlinks cannot hav... |
Stats given file or returns a cached result if available. | def Get(self, path, follow_symlink = True):
"""Stats given file or returns a cached result if available.
Args:
path: A path to the file to perform `stat` on.
follow_symlink: True if `stat` of a symlink should be returned instead of
a file that it points to. For non-symlinks this setting has... |
Get the classes that support parsing a given artifact. | def GetClassesByArtifact(cls, artifact_name):
"""Get the classes that support parsing a given artifact."""
return [
cls.classes[c]
for c in cls.classes
if artifact_name in cls.classes[c].supported_artifacts
] |
Generate RDFs for the fully expanded configs. | def EnumerateAllConfigs(self, stats, file_objects):
"""Generate RDFs for the fully expanded configs.
Args:
stats: A list of RDF StatEntries corresponding to the file_objects.
file_objects: A list of file handles.
Returns:
A tuple of a list of RDFValue PamConfigEntries found & a list of s... |
Return PamConfigEntries it finds as it recursively follows PAM configs. | def EnumerateConfig(self, service, path, cache, filter_type=None):
"""Return PamConfigEntries it finds as it recursively follows PAM configs.
Args:
service: A string containing the service name we are processing.
path: A string containing the file path name we want.
cache: A dictionary keyed ... |
Fingerprint a file. | def Run(self, args):
"""Fingerprint a file."""
with vfs.VFSOpen(
args.pathspec, progress_callback=self.Progress) as file_obj:
fingerprinter = Fingerprinter(self.Progress, file_obj)
response = rdf_client_action.FingerprintResponse()
response.pathspec = file_obj.pathspec
if args.tu... |
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 subclass of AFF4Object." %
... |
Opens the named object. | def Open(self, urn, aff4_type=None, mode="r"):
"""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" wil... |
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)
try:
result = self._objects_cache[key]
if aff4_... |
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:
not_listed_urns.append(urn)
if not_listed_urns:
... |
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:
try:
children = result[urn] = s... |
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.update(urns)
for obj in self.MultiOpen(urns):
ob... |
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_root = utils.SmartUnicode(root)
if 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_TIMESTAMP
elif age == ALL_TIMES:
return data_store.DB.AL... |
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 need to get from the database.
if to_read:
... |
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.LAST] = [
rdfvalue.RDFDatetime.... |
Update the child indexes. | def _UpdateChildIndex(self, urn, mutation_pool):
"""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... |
Returns an invariant key for an AFF4 object. | def _MakeCacheInvariant(self, urn, age):
"""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 bounda... |
Creates a new object and locks it. | def CreateWithLock(self,
urn,
aff4_type,
token=None,
age=NEWEST_TIME,
force_new_version=True,
blocking=True,
blocking_lock_timeout=10,
blocking_sleep_in... |
Open given urn and locks it. | def OpenWithLock(self,
urn,
aff4_type=None,
token=None,
age=NEWEST_TIME,
blocking=True,
blocking_lock_timeout=10,
blocking_sleep_interval=1,
lease_time=100):
"""Ope... |
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."""
if urn is None:
raise ValueError("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 and age != NEWEST_TIME:
raise ValueError(
... |
Checks if an object with a given URN and type exists in the datastore. | def ExistsWithType(self,
urn,
aff4_type=None,
follow_symlinks=True,
age=NEWEST_TIME,
token=None):
"""Checks if an object with a given URN and type exists in the datastore.
Args:
urn: The urn to check.... |
Opens the named object. | def Open(self,
urn,
aff4_type=None,
mode="r",
token=None,
local_cache=None,
age=NEWEST_TIME,
follow_symlinks=True,
transaction=None):
"""Opens the named object.
This instantiates the object from the AFF4 data store.
Not... |
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():
raise NotImplementedError("AFF... |
Opens many URNs and returns handles in the same order. | def MultiOpenOrdered(self, urns, **kwargs):
"""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 sho... |
Returns all the versions of the object as AFF4 objects. | def OpenDiscreteVersions(self,
urn,
mode="r",
token=None,
local_cache=None,
age=ALL_TIMES,
diffs_only=False,
follow_symlinks=True):... |
Returns metadata about all urns. | def Stat(self, urns):
"""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.
"""
if isinstanc... |
Creates the urn if it does not already exist otherwise opens it. | def Create(self,
urn,
aff4_type,
mode="w",
token=None,
age=NEWEST_TIME,
force_new_version=True,
object_exists=False,
mutation_pool=None,
transaction=None):
"""Creates the urn if it does not already e... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.