INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
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. Args: private_key: The private key to use. common_name: Name for cert. issuer_cn: Name for issuer. issuer_c: Country for issuer. Returns: The 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. Args: graph_series: A series of rdf_stats.Graphs containing aggregated data for a particular report-type. label: Client label by which data in the graph_series was aggregated. token: ACL token to use for writing to the legacy (non-relatio...
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. Args: label: Client label to fetch data for. report_type: rdf_stats.ClientGraphSeries.ReportType to fetch data for. period: rdfvalue.Duration specifying how far back in time to fetch data. If not provided, all data for the given ...
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. Args: label: Client label to fetch data for. report_type: rdf_stats.ClientGraphSeries.ReportType to fetch data for. token: ACL token to use for reading from the legacy (non-relational) datastore. Raises: AFF4AttributeTypeError: ...
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. Args: label: Client label to fetch data for. report_type: rdf_stats.ClientGraphSeries.ReportType to fetch data for. token: ACL token to use for reading from the DB. Raises: AFF4AttributeTypeError: If an unexpected report-data t...
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. Args: client_path_blob_refs: A dictionary mapping `db.ClientPath` instances to lists of blob references. use_external_stores: A flag indicating if the files should also be added to external file stores. Returns: A dictionary mapping `db.C...
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. 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.
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. 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 specified, will simply open the latest version. Re...
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. 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 equal or lower than max_timestamp. If not specified, will simply open ...
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. Args: hash_id_metadatas: A dictionary mapping hash ids to file metadata (a tuple of hash client path and blob references).
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. 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 stream. If it is `None` then the whole file is uploaded. ...
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. 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 `None` then the whole file is uploaded. Retur...
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. Args: chunk: A chunk to upload. Returns: A `BlobImageChunkDescriptor` object.
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. 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 (, +Inf)] produce the following buckets: Bucket "0.0" : -Inf <= val...
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...
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_...
Opens the named object. This instantiates the object from the AFF4 data store. Note that the root aff4:/ object is a container for all other objects. Opening it for reading will instantiate a AFF4Volume instance, even if the row does not exist. The mode parameter specifies, how the object should b...
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...
Recursively lists bunch of directories. Args: urns: List of urns to list children. limit: Max number of children to list (NOTE: this is per urn). age: The age of the items to retrieve. Should be one of ALL_TIMES, NEWEST_TIME or a range. Yields: (subject<->children urns) tuples...
def RecursiveMultiListChildren(self, urns, limit=None, age=NEWEST_TIME): """Recursively lists bunch of directories. Args: urns: List of urns to list children. limit: Max number of children to list (NOTE: this is per urn). age: The age of the items to retrieve. Should be one of ALL_TIMES, ...
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....
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...
Log an http based api call. Args: request: A WSGI request object. response: A WSGI response object.
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...
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 not exist or some unexpected ...
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 ...
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.
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...
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 strings which are the external config references found...
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...
Update the child indexes. This function maintains the index for direct child relations. When we set an AFF4 path, we always add an attribute like index:dir/%(childname)s to its parent. This is written asynchronously to its parent. In order to query for all direct children of an AFF4 object, we the...
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...
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(...
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. Optional.
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...
Check that the value is of the expected type. Args: attribute: An instance of Attribute(). value: An instance of RDFValue. Raises: ValueError: when the value is not of the expected type. AttributeError: When the attribute is not of type Attribute().
def _CheckAttribute(self, attribute, value): """Check that the value is of the expected type. Args: attribute: An instance of Attribute(). value: An instance of RDFValue. Raises: ValueError: when the value is not of the expected type. AttributeError: When the attribute is not o...
Lists bunch of directories efficiently. Args: urns: List of urns to list children. limit: Max number of children to list (NOTE: this is per urn). age: The age of the items to retrieve. Should be one of ALL_TIMES, NEWEST_TIME or a range. Yields: Tuples of Subjects and a list of...
def MultiListChildren(self, urns, limit=None, age=NEWEST_TIME): """Lists bunch of directories efficiently. Args: urns: List of urns to list children. limit: Max number of children to list (NOTE: this is per urn). age: The age of the items to retrieve. Should be one of ALL_TIMES, NEWES...
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_...
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...
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, ...
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.
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 ...
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_GENERIC_READ", "FILE_GENERIC_WRITE"] user: usernam...
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...
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, ...
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 no effect. Returns: `Stat` object corre...
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...
Returns an invariant key for an AFF4 object. The object will be cached based on this key. This function is specifically extracted to ensure that we encapsulate all security critical aspects of the AFF4 object so that objects do not leak across security boundaries. Args: urn: The urn of the obje...
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...
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...
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...
Gets all the subfields indicated by field_names. This resolves specifications like "Users.special_folders.app_data" where for each entry in the Users protobuf the corresponding app_data folder entry should be returned. Args: fd: The base RDFValue or Array. field_names: A list of strings in...
def GetSubFields(self, fd, field_names): """Gets all the subfields indicated by field_names. This resolves specifications like "Users.special_folders.app_data" where for each entry in the Users protobuf the corresponding app_data folder entry should be returned. Args: fd: The base RDFValue o...
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...
Lists bunch of directories efficiently. Args: urn: Urn to list children. limit: Max number of children to list. age: The age of the items to retrieve. Should be one of ALL_TIMES, NEWEST_TIME or a range. Returns: RDFURNs instances of each child.
def ListChildren(self, urn, limit=None, age=NEWEST_TIME): """Lists bunch of directories efficiently. Args: urn: Urn to list children. limit: Max number of children to list. age: The age of the items to retrieve. Should be one of ALL_TIMES, NEWEST_TIME or a range. Returns: R...
Returns this attribute's RDFValue class.
def GetRDFValueType(self): """Returns this attribute's RDFValue class.""" result = self.attribute_type for field_name in self.field_names: # Support the new semantic protobufs. try: result = result.type_infos.get(field_name).type except AttributeError: raise AttributeError(...
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...
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...
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. Canonical paths on windows have: -...
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. ...
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...
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...
Sync the new attributes to the synced attribute cache. This maintains object validity.
def _SyncAttributes(self): """Sync the new attributes to the synced attribute cache. This maintains object validity. """ # This effectively moves all the values from the new_attributes to the # synced_attributes caches. for attribute, value_array in iteritems(self.new_attributes): if not ...
Opens the named object. DeletionPool will only open the object if it's not in the pool already. Otherwise it will just return the cached version. Objects are cached based on their urn and mode. I.e. same object opened with mode="r" and mode="rw" will be actually opened two times and cached separately. ...
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...
Returns all the versions of the object as AFF4 objects. This iterates through versions of an object, returning the newest version first, then each older version until the beginning of time. Note that versions are defined by changes to the TYPE attribute, and this takes the version between two TYPE att...
def OpenDiscreteVersions(self, urn, mode="r", token=None, local_cache=None, age=ALL_TIMES, diffs_only=False, follow_symlinks=True):...
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.
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...
Upgrades this object to the type specified. AFF4 Objects can be upgraded on the fly to other type - As long as the new type is derived from the current type. This feature allows creation of placeholder objects which can later be upgraded to the fully featured object. Note: It is not allowed to dow...
def Upgrade(self, aff4_class): """Upgrades this object to the type specified. AFF4 Objects can be upgraded on the fly to other type - As long as the new type is derived from the current type. This feature allows creation of placeholder objects which can later be upgraded to the fully featured objec...
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...
Returns a default attribute if it is not set.
def GetDefault(self, fd=None, default=None): """Returns a default attribute if it is not set.""" if callable(self.default): return self.default(fd) if self.default is not None: # We can't return mutable objects here or the default might change for all # objects of this class. if isi...
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...
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 []
Return a copy without registering in the attribute registry.
def Copy(self): """Return a copy without registering in the attribute registry.""" return Attribute( self.predicate, self.attribute_type, self.description, self.name, _copy=True)
Gets the attribute from this object.
def Get(self, attribute, default=None): """Gets the attribute from this object.""" if attribute is None: return default # Allow the user to specify the attribute by name. elif isinstance(attribute, str): attribute = Attribute.GetAttributeByName(attribute) # We can't read attributes fro...
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", ...
Returns metadata about all urns. Currently the metadata include type, and last update time. Args: urns: The urns of the objects to open. Yields: A dict of metadata. Raises: ValueError: A string was passed instead of an iterable.
def Stat(self, urns): """Returns metadata about 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...
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())
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 ...
Checks if an object with a given URN and type exists in the datastore. Args: urn: The urn to check. aff4_type: Expected object type. follow_symlinks: If object opened is a symlink, follow it. age: The age policy used to check this object. Should be either NEWEST_TIME or a time range...
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....
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 parts with matching content.
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...
Close and destroy the object. This is similar to Flush, but does not maintain object validity. Hence the object should not be interacted with after Close(). Raises: LockError: The lease for this object has expired.
def Close(self): """Close and destroy the object. This is similar to Flush, but does not maintain object validity. Hence the object should not be interacted with after Close(). Raises: LockError: The lease for this object has expired. """ if self.locked and self.CheckLease() == 0: ...
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( ...
Add an additional attribute to this object. If value is None, attribute is expected to be already initialized with a value. For example: fd.AddAttribute(fd.Schema.CONTAINS("some data")) Args: attribute: The attribute name or an RDFValue derived from the attribute. value: The value the a...
def AddAttribute(self, attribute, value=None, age=None): """Add an additional attribute to this object. If value is None, attribute is expected to be already initialized with a value. For example: fd.AddAttribute(fd.Schema.CONTAINS("some data")) Args: attribute: The attribute name or an RD...
Returns a list of values from this attribute.
def GetValuesForAttribute(self, attribute, only_one=False): """Returns a list of values from this attribute.""" if not only_one and self.age_policy == NEWEST_TIME: raise ValueError("Attempting to read all attribute versions for an " "object opened for NEWEST_TIME. This is probably "...
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...
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...
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 has no effect. Returns: Stat instance, with...
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...
Creates a new object and locks it. Similar to OpenWithLock below, this creates a locked object. The difference is that when you call CreateWithLock, the object does not yet have to exist in the data store. Args: urn: The object to create. aff4_type: The desired type for this object. ...
def CreateWithLock(self, urn, aff4_type, token=None, age=NEWEST_TIME, force_new_version=True, blocking=True, blocking_lock_timeout=10, blocking_sleep_in...
Given a serialized value, decode the attribute. Only attributes which have been previously defined are permitted. Args: attribute_name: The string name of the attribute. value: The serialized attribute value. ts: The timestamp of this attribute.
def DecodeValueFromAttribute(self, attribute_name, value, ts): """Given a serialized value, decode the attribute. Only attributes which have been previously defined are permitted. Args: attribute_name: The string name of the attribute. value: The serialized attribute value. ts: The ti...
Write the dirty attributes to the data store.
def _WriteAttributes(self): """Write the dirty attributes to the data store.""" # If the object is not opened for writing we do not need to flush it to the # data_store. if "w" not in self.mode: return if self.urn is None: raise ValueError("Storing of anonymous AFF4 objects not supporte...
Remove specified labels from the AFF4Object.
def RemoveLabels(self, labels_names, owner=None): """Remove specified labels from the AFF4Object.""" if owner is None and not self.token: raise ValueError("Can't remove label: No owner specified and " "no access token available.") if isinstance(labels_names, string_types): ...
Opens many URNs and returns handles in the same order. `MultiOpen` can return file handles in arbitrary order. This makes it more efficient and in most cases the order does not matter. However, there are cases where order is important and this function should be used instead. Args: urns: A list ...
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...
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 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...
Creates the urn if it does not already exist, otherwise opens it. If the urn exists and is of a different type, this will also promote it to the specified type. Args: urn: The object to create. aff4_type: The desired type for this object. mode: The desired mode for this object. tok...
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...
Syncs this object with the data store, maintaining object validity.
def Flush(self): """Syncs this object with the data store, maintaining object validity.""" if self.locked and self.CheckLease() == 0: self._RaiseLockError("Flush") self._WriteAttributes() self._SyncAttributes() if self.parent: self.parent.Flush()
Add labels to the AFF4Object.
def AddLabels(self, labels_names, owner=None): """Add labels to the AFF4Object.""" if owner is None and not self.token: raise ValueError("Can't set label: No owner specified and " "no access token available.") if isinstance(labels_names, string_types): raise ValueError("La...
Gets the kernel version as string, eg. "5.1.2600". Returns: The kernel version, or "unknown" in the case of failure.
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...