INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Called when at a leaf value. Should yield a value.
def _AtLeaf(self, attr_value): """Called when at a leaf value. Should yield a value.""" if isinstance(attr_value, collections.Mapping): # If the result is a dict, return each key/value pair as a new dict. for k, v in iteritems(attr_value): yield {k: v} else: yield attr_value
Called when at a non - leaf value. Should recurse and yield values.
def _AtNonLeaf(self, attr_value, path): """Called when at a non-leaf value. Should recurse and yield values.""" try: if isinstance(attr_value, collections.Mapping): # If it's dictionary-like, treat the dict key as the attribute.. sub_obj = attr_value.get(path[1]) if len(path) > 2: ...
Compile the binary expression into a filter object.
def Compile(self, filter_implemention): """Compile the binary expression into a filter object.""" operator = self.operator.lower() if operator == "and" or operator == "&&": method = "AndFilter" elif operator == "or" or operator == "||": method = "OrFilter" else: raise ParseError("I...
Insert an arg to the current expression.
def InsertArg(self, string="", **_): """Insert an arg to the current expression.""" if self.state == "LIST_ARG": self.list_args.append(string) elif self.current_expression.AddArg(string): # This expression is complete self.stack.append(self.current_expression) self.current_expression...
Inserts a Float argument.
def InsertFloatArg(self, string="", **_): """Inserts a Float argument.""" try: float_value = float(string) return self.InsertArg(float_value) except (TypeError, ValueError): raise ParseError("%s is not a valid float." % string)
Inserts an Integer in base16 argument.
def InsertInt16Arg(self, string="", **_): """Inserts an Integer in base16 argument.""" try: int_value = int(string, 16) return self.InsertArg(int_value) except (TypeError, ValueError): raise ParseError("%s is not a valid base16 integer." % string)
Escape backslashes found inside a string quote.
def StringEscape(self, string, match, **_): """Escape backslashes found inside a string quote. Backslashes followed by anything other than [\'"rnbt] will raise an Error. Args: string: The string that matched. match: The match object (m.group(1) is the escaped code) Raises: ParseErro...
Converts a hex escaped string.
def HexEscape(self, string, match, **_): """Converts a hex escaped string.""" hex_string = match.group(1) try: self.string += binascii.unhexlify(hex_string).decode("utf-8") # TODO: In Python 2 `binascii` throws `TypeError` for invalid # input values (for whathever reason). This behaviour is fi...
Generates a CSRF token based on a secret key id and time.
def GenerateCSRFToken(user_id, time): """Generates a CSRF token based on a secret key, id and time.""" precondition.AssertType(user_id, Text) precondition.AssertOptionalType(time, int) time = time or rdfvalue.RDFDatetime.Now().AsMicrosecondsSinceEpoch() secret = config.CONFIG.Get("AdminUI.csrf_secret_key", ...
Decorator for WSGI handler that inserts CSRF cookie into response.
def StoreCSRFCookie(user, response): """Decorator for WSGI handler that inserts CSRF cookie into response.""" csrf_token = GenerateCSRFToken(user, None) response.set_cookie( "csrftoken", csrf_token, max_age=CSRF_TOKEN_DURATION.seconds)
Decorator for WSGI handler that checks CSRF cookie against the request.
def ValidateCSRFTokenOrRaise(request): """Decorator for WSGI handler that checks CSRF cookie against the request.""" # CSRF check doesn't make sense for GET/HEAD methods, because they can # (and are) used when downloading files through <a href> links - and # there's no way to set X-CSRFToken header in this cas...
Decorator that ensures that HTTP access is logged.
def LogAccessWrapper(func): """Decorator that ensures that HTTP access is logged.""" def Wrapper(request, *args, **kwargs): """Wrapping function.""" try: response = func(request, *args, **kwargs) server_logging.LOGGER.LogHttpAdminUIAccess(request, response) except Exception: # pylint: disa...
Build an ACLToken from the request.
def _BuildToken(self, request, execution_time): """Build an ACLToken from the request.""" token = access_control.ACLToken( username=request.user, reason=request.args.get("reason", ""), process="GRRAdminUI", expiry=rdfvalue.RDFDatetime.Now() + execution_time) for field in ["R...
Renders GRR home page by rendering base. html Jinja template.
def _HandleHomepage(self, request): """Renders GRR home page by rendering base.html Jinja template.""" _ = request env = jinja2.Environment( loader=jinja2.FileSystemLoader(config.CONFIG["AdminUI.template_root"]), autoescape=True) create_time = psutil.Process(os.getpid()).create_time()...
Handles API requests.
def _HandleApi(self, request): """Handles API requests.""" # Checks CSRF token. CSRF token cookie is updated when homepage is visited # or via GetPendingUserNotificationsCount API call. ValidateCSRFTokenOrRaise(request) response = http_api.RenderHttpResponse(request) # GetPendingUserNotificati...
Redirect to GitHub - hosted documentation.
def _RedirectToRemoteHelp(self, path): """Redirect to GitHub-hosted documentation.""" allowed_chars = set(string.ascii_letters + string.digits + "._-/") if not set(path) <= allowed_chars: raise RuntimeError("Unusual chars in path %r - " "possible exploit attempt." % path) ...
Handles help requests.
def _HandleHelp(self, request): """Handles help requests.""" help_path = request.path.split("/", 2)[-1] if not help_path: raise werkzeug_exceptions.Forbidden("Error: Invalid help path.") # Proxy remote documentation. return self._RedirectToRemoteHelp(help_path)
Returns GRR s WSGI handler.
def WSGIHandler(self): """Returns GRR's WSGI handler.""" sdm = werkzeug_wsgi.SharedDataMiddleware(self, { "/": config.CONFIG["AdminUI.document_root"], }) # Use DispatcherMiddleware to make sure that SharedDataMiddleware is not # used at all if the URL path doesn't start with "/static". This ...
Import the plugins once only.
def RunOnce(self): """Import the plugins once only.""" # pylint: disable=unused-variable,g-import-not-at-top from grr_response_server.gui import gui_plugins # pylint: enable=unused-variable,g-import-not-at-top if config.CONFIG.Get("AdminUI.django_secret_key", None): logging.warning( ...
Lists all registered Grr binaries.
def ListGrrBinaries(context=None): """Lists all registered Grr binaries.""" items = context.SendIteratorRequest("ListGrrBinaries", None) return utils.MapItemsIterator( lambda data: GrrBinary(data=data, context=context), items)
This function parses the RDFValue from the server.
def Execute(self, message): """This function parses the RDFValue from the server. The Run method will be called with the specified RDFValue. Args: message: The GrrMessage that we are called to process. Returns: Upon return a callback will be called on the server to register th...
Set a status to report back to the server.
def SetStatus(self, status, message="", backtrace=None): """Set a status to report back to the server.""" self.status.status = status self.status.error_message = utils.SmartUnicode(message) if backtrace: self.status.backtrace = utils.SmartUnicode(backtrace)
Send response back to the server.
def SendReply(self, rdf_value=None, session_id=None, message_type=rdf_flows.GrrMessage.Type.MESSAGE): """Send response back to the server.""" # TODO(hanuszczak): This is pretty bad. Here we assume that if the session # id is not none we are "replying" to a wel...
Indicate progress of the client action.
def Progress(self): """Indicate progress of the client action. This function should be called periodically during client actions that do not finish instantly. It will notify the nanny that the action is not stuck and avoid the timeout and it will also check if the action has reached its cpu limit. ...
Writes the provided graphs to the DB with the given client label.
def WriteClientGraphSeries( self, graph_series, client_label, timestamp, cursor=None, ): """Writes the provided graphs to the DB with the given client label.""" args = { "client_label": client_label, "report_type": graph_series.report_type.SerializeToDataStore(), ...
Reads graph series for the given label and report - type from the DB.
def ReadAllClientGraphSeries( self, client_label, report_type, time_range = None, cursor=None): """Reads graph series for the given label and report-type from the DB.""" query = """ SELECT UNIX_TIMESTAMP(timestamp), graph_series FROM client_report_graphs WHERE cli...
Fetches the latest graph series for a client - label from the DB.
def ReadMostRecentClientGraphSeries( self, client_label, report_type, cursor=None): """Fetches the latest graph series for a client-label from the DB.""" query = """ SELECT graph_series FROM client_report_graphs WHERE client_label = %s AND report_type = %s ORDER B...
Converts given RDFValue to an RDFURN of a file to be downloaded.
def CollectionItemToAff4Path(item, client_id=None): """Converts given RDFValue to an RDFURN of a file to be downloaded.""" if isinstance(item, rdf_flows.GrrMessage): client_id = item.source item = item.payload elif isinstance(item, rdf_flow_objects.FlowResult): client_id = item.client_id item = it...
Converts given RDFValue to a ClientPath of a file to be downloaded.
def CollectionItemToClientPath(item, client_id=None): """Converts given RDFValue to a ClientPath of a file to be downloaded.""" if isinstance(item, rdf_flows.GrrMessage): client_id = item.source item = item.payload elif isinstance(item, rdf_flow_objects.FlowResult): client_id = item.client_id item...
Returns a knowledgebase from an rdf client object.
def GetKnowledgeBase(rdf_client_obj, allow_uninitialized=False): """Returns a knowledgebase from an rdf client object.""" if not allow_uninitialized: if rdf_client_obj is None: raise artifact_utils.KnowledgeBaseUninitializedError( "No client snapshot given.") if rdf_client_obj.knowledge_base...
This generates an artifact knowledge base from a GRR client.
def GetArtifactKnowledgeBase(client_obj, allow_uninitialized=False): """This generates an artifact knowledge base from a GRR client. Args: client_obj: A GRRClient object which is opened for reading. allow_uninitialized: If True we accept an uninitialized knowledge_base. Returns: A KnowledgeBase sema...
Set core values from GRR into the knowledgebase.
def SetCoreGRRKnowledgeBaseValues(kb, client_obj): """Set core values from GRR into the knowledgebase.""" client_schema = client_obj.Schema kb.fqdn = utils.SmartUnicode(client_obj.Get(client_schema.FQDN, "")) if not kb.fqdn: kb.fqdn = utils.SmartUnicode(client_obj.Get(client_schema.HOSTNAME, "")) versions...
Parse responses with applicable parsers.
def ApplyParsersToResponses(parser_factory, responses, flow_obj): """Parse responses with applicable parsers. Args: parser_factory: A parser factory for specific artifact. responses: A list of responses from the client. flow_obj: An artifact collection flow. Returns: A list of (possibly parsed) ...
Upload a yaml or json file as an artifact to the datastore.
def UploadArtifactYamlFile(file_content, overwrite=True, overwrite_system_artifacts=False): """Upload a yaml or json file as an artifact to the datastore.""" loaded_artifacts = [] registry_obj = artifact_registry.REGISTRY # Make sure all artifacts are loaded...
Decorator to log and account for a DB call.
def CallLoggedAndAccounted(f): """Decorator to log and account for a DB call.""" @functools.wraps(f) def Decorator(*args, **kwargs): try: start_time = time.time() result = f(*args, **kwargs) latency = time.time() - start_time stats_collector_instance.Get().RecordEvent( "db_...
Escapes wildcard characters for strings intended to be used with LIKE.
def EscapeWildcards(string): """Escapes wildcard characters for strings intended to be used with `LIKE`. Databases don't automatically escape wildcard characters ('%', '_'), so any non-literal string that is passed to `LIKE` and is expected to match literally has to be manually escaped. Args: string: A ...
Convert hunt id string to an integer.
def HuntIDToInt(hunt_id): """Convert hunt id string to an integer.""" # TODO(user): This code is only needed for a brief period of time when we # allow running new rel-db flows with old aff4-based hunts. In this scenario # parent_hunt_id is effectively not used, but it has to be an # integer. Stripping "H:" f...
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): """Reads ClientMetadata records for a list of clients.""" res = {} for client_id in client_ids: md = self.metadatas.get(client_id, None) if md is None: continue res[client_id] = rdf_objects.ClientMetadata( certificate=md.get...
Writes new client snapshot.
def WriteClientSnapshot(self, snapshot): """Writes new client snapshot.""" client_id = snapshot.client_id if client_id not in self.metadatas: raise db.UnknownClientError(client_id) startup_info = snapshot.startup_info snapshot.startup_info = None ts = rdfvalue.RDFDatetime.Now() hist...
Reads the latest client snapshots for a list of clients.
def MultiReadClientSnapshot(self, client_ids): """Reads the latest client snapshots for a list of clients.""" res = {} for client_id in client_ids: history = self.clients.get(client_id, None) if not history: res[client_id] = None continue last_timestamp = max(history) ...
Reads full client information for a list of clients.
def MultiReadClientFullInfo(self, client_ids, min_last_ping=None): """Reads full client information for a list of clients.""" res = {} for client_id in client_ids: try: md = self.ReadClientMetadata(client_id) except db.UnknownClientError: continue if md and min_last_ping a...
Reads last - ping timestamps for clients in the DB.
def ReadClientLastPings(self, min_last_ping=None, max_last_ping=None, fleetspeak_enabled=None): """Reads last-ping timestamps for clients in the DB.""" last_pings = {} for client_id, metadata in iteritems(self.metadatas): la...
Writes the full history for a particular client.
def WriteClientSnapshotHistory(self, clients): """Writes the full history for a particular client.""" if clients[0].client_id not in self.metadatas: raise db.UnknownClientError(clients[0].client_id) for client in clients: startup_info = client.startup_info client.startup_info = None ...
Reads the full history for a particular client.
def ReadClientSnapshotHistory(self, client_id, timerange=None): """Reads the full history for a particular client.""" from_time, to_time = self._ParseTimeRange(timerange) history = self.clients.get(client_id) if not history: return [] res = [] for ts in sorted(history, reverse=True): ...
Associates the provided keywords with the client.
def AddClientKeywords(self, client_id, keywords): """Associates the provided keywords with the client.""" if client_id not in self.metadatas: raise db.UnknownClientError(client_id) for kw in keywords: self.keywords.setdefault(kw, {}) self.keywords[kw][client_id] = rdfvalue.RDFDatetime.Now...
Lists the clients associated with keywords.
def ListClientsForKeywords(self, keywords, start_time=None): """Lists the clients associated with keywords.""" res = {kw: [] for kw in keywords} for kw in keywords: for client_id, timestamp in iteritems(self.keywords.get(kw, {})): if start_time is not None and timestamp < start_time: ...
Removes the association of a particular client to a keyword.
def RemoveClientKeyword(self, client_id, keyword): """Removes the association of a particular client to a keyword.""" if keyword in self.keywords and client_id in self.keywords[keyword]: del self.keywords[keyword][client_id]
Attaches a user label to a client.
def AddClientLabels(self, client_id, owner, labels): """Attaches a user label to a client.""" if client_id not in self.metadatas: raise db.UnknownClientError(client_id) labelset = self.labels.setdefault(client_id, {}).setdefault(owner, set()) for l in labels: labelset.add(utils.SmartUnicode...
Reads the user labels for a list of clients.
def MultiReadClientLabels(self, client_ids): """Reads the user labels for a list of clients.""" res = {} for client_id in client_ids: res[client_id] = [] owner_dict = self.labels.get(client_id, {}) for owner, labels in iteritems(owner_dict): for l in labels: res[client_id...
Removes a list of user labels from a given client.
def RemoveClientLabels(self, client_id, owner, labels): """Removes a list of user labels from a given client.""" labelset = self.labels.setdefault(client_id, {}).setdefault(owner, set()) for l in labels: labelset.discard(utils.SmartUnicode(l))
Lists all client labels known to the system.
def ReadAllClientLabels(self): """Lists all client labels known to the system.""" result = set() for labels_dict in itervalues(self.labels): for owner, names in iteritems(labels_dict): for name in names: result.add(rdf_objects.ClientLabel(owner=owner, name=name)) return list(res...
Writes a new client startup record.
def WriteClientStartupInfo(self, client_id, startup_info): """Writes a new client startup record.""" if client_id not in self.metadatas: raise db.UnknownClientError(client_id) ts = rdfvalue.RDFDatetime.Now() self.metadatas[client_id]["startup_info_timestamp"] = ts history = self.startup_histo...
Reads the latest client startup record for a single client.
def ReadClientStartupInfo(self, client_id): """Reads the latest client startup record for a single client.""" history = self.startup_history.get(client_id, None) if not history: return None ts = max(history) res = rdf_client.StartupInfo.FromSerializedString(history[ts]) res.timestamp = ts...
Reads the full startup history for a particular client.
def ReadClientStartupInfoHistory(self, client_id, timerange=None): """Reads the full startup history for a particular client.""" from_time, to_time = self._ParseTimeRange(timerange) history = self.startup_history.get(client_id) if not history: return [] res = [] for ts in sorted(history, ...
Writes a new client crash record.
def WriteClientCrashInfo(self, client_id, crash_info): """Writes a new client crash record.""" if client_id not in self.metadatas: raise db.UnknownClientError(client_id) ts = rdfvalue.RDFDatetime.Now() self.metadatas[client_id]["last_crash_timestamp"] = ts history = self.crash_history.setdefa...
Reads the latest client crash record for a single client.
def ReadClientCrashInfo(self, client_id): """Reads the latest client crash record for a single client.""" history = self.crash_history.get(client_id, None) if not history: return None ts = max(history) res = rdf_client.ClientCrash.FromSerializedString(history[ts]) res.timestamp = ts r...
Reads the full crash history for a particular client.
def ReadClientCrashInfoHistory(self, client_id): """Reads the full crash history for a particular client.""" history = self.crash_history.get(client_id) if not history: return [] res = [] for ts in sorted(history, reverse=True): client_data = rdf_client.ClientCrash.FromSerializedString(h...
Stores a ClientStats instance.
def WriteClientStats(self, client_id, stats): """Stores a ClientStats instance.""" if client_id not in self.ReadAllClientIDs(): raise db.UnknownClientError(client_id) self.client_stats[client_id][rdfvalue.RDFDatetime.Now()] = stats
Reads ClientStats for a given client and time range.
def ReadClientStats(self, client_id, min_timestamp, max_timestamp ): """Reads ClientStats for a given client and time range.""" results = [] for timestamp, stats in iteritems(self.client_stats[client_id]): if min_timestamp <= timestamp <...
Deletes ClientStats older than a given timestamp.
def DeleteOldClientStats(self, yield_after_count, retention_time ): """Deletes ClientStats older than a given timestamp.""" deleted_count = 0 yielded = False for stats_dict in itervalues(self.client_stats): for timestamp in list(stats_dict.keys...
Computes client - activity stats for all GRR versions in the DB.
def CountClientVersionStringsByLabel(self, day_buckets): """Computes client-activity stats for all GRR versions in the DB.""" def ExtractVersion(client_info): return client_info.last_snapshot.GetGRRVersionString() return self._CountClientStatisticByLabel(day_buckets, ExtractVersion)
Computes client - activity stats for all client platforms in the DB.
def CountClientPlatformsByLabel(self, day_buckets): """Computes client-activity stats for all client platforms in the DB.""" def ExtractPlatform(client_info): return client_info.last_snapshot.knowledge_base.os return self._CountClientStatisticByLabel(day_buckets, ExtractPlatform)
Computes client - activity stats for OS - release strings in the DB.
def CountClientPlatformReleasesByLabel(self, day_buckets): """Computes client-activity stats for OS-release strings in the DB.""" return self._CountClientStatisticByLabel( day_buckets, lambda client_info: client_info.last_snapshot.Uname())
Returns client - activity metrics for a particular statistic.
def _CountClientStatisticByLabel(self, day_buckets, extract_statistic_fn): """Returns client-activity metrics for a particular statistic. Args: day_buckets: A set of n-day-active buckets. extract_statistic_fn: A function that extracts the statistic's value from a ClientFullInfo object. ...
Start frontend http server.
def CreateServer(frontend=None): """Start frontend http server.""" max_port = config.CONFIG.Get("Frontend.port_max", config.CONFIG["Frontend.bind_port"]) for port in range(config.CONFIG["Frontend.bind_port"], max_port + 1): server_address = (config.CONFIG["Frontend.bind_addres...
Main.
def main(argv): """Main.""" del argv # Unused. if flags.FLAGS.version: print("GRR frontend {}".format(config_server.VERSION["packageversion"])) return config.CONFIG.AddContext("HTTPServer Context") server_startup.Init() httpd = CreateServer() server_startup.DropPrivileges() try: httpd...
Sends a response to the client.
def Send(self, data, status=200, ctype="application/octet-stream", additional_headers=None, last_modified=0): """Sends a response to the client.""" if additional_headers: additional_header_strings = [ "%s: %s\r\n" % (name, val) for...
Serve the server pem with GET requests.
def do_GET(self): # pylint: disable=g-bad-name """Serve the server pem with GET requests.""" self._IncrementActiveCount() try: if self.path.startswith("/server.pem"): stats_collector_instance.Get().IncrementCounter( "frontend_http_requests", fields=["cert", "http"]) self.S...
Generates data for a single chunk.
def _GenerateChunk(self, length): """Generates data for a single chunk.""" while 1: to_read = min(length, self.RECV_BLOCK_SIZE) if to_read == 0: return data = self.rfile.read(to_read) if not data: return yield data length -= len(data)
Generates the file data for a chunk encoded file.
def GenerateFileData(self): """Generates the file data for a chunk encoded file.""" # Handle chunked encoding: # https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6.1 while 1: line = self.rfile.readline() # We do not support chunked extensions, just ignore them. chunk_size = ...
Process encrypted message bundles.
def do_POST(self): # pylint: disable=g-bad-name """Process encrypted message bundles.""" self._IncrementActiveCount() try: if self.path.startswith("/upload"): stats_collector_instance.Get().IncrementCounter( "frontend_http_requests", fields=["upload", "http"]) logging.err...
Handle POSTS.
def Control(self): """Handle POSTS.""" # Get the api version try: api_version = int(urlparse.parse_qs(self.path.split("?")[1])["api"][0]) except (ValueError, KeyError, IndexError): # The oldest api version we support if not specified. api_version = 3 try: content_length = se...
Initializes the Fleetspeak connector.
def Init(service_client=None): """Initializes the Fleetspeak connector.""" global CONN global label_map global unknown_label if service_client is None: service_client_cls = fs_client.InsecureGRPCServiceClient fleetspeak_message_listen_address = ( config.CONFIG["Server.fleetspeak_message_list...
Writes blob references for a signed binary to the DB.
def WriteSignedBinaryReferences(self, binary_id, references, cursor=None): """Writes blob references for a signed binary to the DB.""" args = { "binary_type": binary_id.binary_type.Serialize...
Reads blob references for the signed binary with the given id.
def ReadSignedBinaryReferences( self, binary_id, cursor=None): """Reads blob references for the signed binary with the given id.""" cursor.execute( """ SELECT blob_references, UNIX_TIMESTAMP(timestamp) FROM signed_binary_references WHERE binary_type = %s AND binary_path_has...
Returns ids for all signed binaries in the DB.
def ReadIDsForAllSignedBinaries(self, cursor=None ): """Returns ids for all signed binaries in the DB.""" cursor.execute( "SELECT binary_type, binary_path FROM signed_binary_references") return [ rdf_objects.SignedBinaryID(binary_type=binary_type, path=binary...
Deletes blob references for the given signed binary from the DB.
def DeleteSignedBinaryReferences(self, binary_id, cursor=None): """Deletes blob references for the given signed binary from the DB.""" cursor.execute( """ DELETE FROM signed_binary_references WHERE binary_type = %s AND bin...
Query the client for available Volume Shadow Copies using a WMI query.
def Start(self): """Query the client for available Volume Shadow Copies using a WMI query.""" self.state.shadows = [] self.state.raw_device = None self.CallClient( server_stubs.WmiQuery, query="SELECT * FROM Win32_ShadowCopy", next_state="ListDeviceDirectories")
Processes the results of the ListDirectory client action.
def ProcessListDirectory(self, responses): """Processes the results of the ListDirectory client action. Args: responses: a flow Responses object. """ if not responses.success: raise flow.FlowError("Unable to list directory.") with data_store.DB.GetMutationPool() as pool: for resp...
Parse the found release files.
def ParseMultiple(self, stats, file_objects, knowledge_base): """Parse the found release files.""" _ = knowledge_base # Collate files into path: contents dictionary. found_files = self._Combine(stats, file_objects) # Determine collected files and apply weighting. weights = [w for w in self.WEI...
Verifies the certificate using the given key.
def Verify(self, public_key): """Verifies the certificate using the given key. Args: public_key: The public key to use. Returns: True: Everything went well. Raises: VerificationError: The certificate did not verify. """ # TODO(amoser): We have to do this manually for now sin...
Creates a new cert for the given common name.
def ClientCertFromCSR(cls, csr): """Creates a new cert for the given common name. Args: csr: A CertificateSigningRequest. Returns: The signed cert. """ builder = x509.CertificateBuilder() # Use the client CN for a cert serial_id. This will ensure we do # not have clashing cert ...
Verifies a given message.
def Verify(self, message, signature, hash_algorithm=None): """Verifies a given message.""" # This method accepts both PSS and PKCS1v15 padding. PSS is preferred but # old clients only support PKCS1v15. if hash_algorithm is None: hash_algorithm = hashes.SHA256() last_e = None for padding_...
Sign a given message.
def Sign(self, message, use_pss=False): """Sign a given message.""" precondition.AssertType(message, bytes) # TODO(amoser): This should use PSS by default at some point. if not use_pss: padding_algorithm = padding.PKCS1v15() else: padding_algorithm = padding.PSS( mgf=padding.M...
Verify the data in this blob.
def Verify(self, public_key): """Verify the data in this blob. Args: public_key: The public key to use for verification. Returns: True when verification succeeds. Raises: rdfvalue.DecodeError if the data is not suitable verified. """ if self.digest_type != self.HashType.SHA2...
Use the data to sign this blob.
def Sign(self, data, signing_key, verify_key=None): """Use the data to sign this blob. Args: data: String containing the blob data. signing_key: The key to sign with. verify_key: Key to verify with. If None we assume the signing key also contains the public key. Returns: se...
A convenience method which pads and encrypts at once.
def Encrypt(self, data): """A convenience method which pads and encrypts at once.""" encryptor = self.GetEncryptor() padded_data = self.Pad(data) try: return encryptor.update(padded_data) + encryptor.finalize() except ValueError as e: raise CipherError(e)
A convenience method which pads and decrypts at once.
def Decrypt(self, data): """A convenience method which pads and decrypts at once.""" decryptor = self.GetDecryptor() try: padded_data = decryptor.update(data) + decryptor.finalize() return self.UnPad(padded_data) except ValueError as e: raise CipherError(e)
Calculates the HMAC for a given message.
def HMAC(self, message, use_sha256=False): """Calculates the HMAC for a given message.""" h = self._NewHMAC(use_sha256=use_sha256) h.update(message) return h.finalize()
Verifies the signature for a given message.
def Verify(self, message, signature): """Verifies the signature for a given message.""" siglen = len(signature) if siglen == 20: hash_algorithm = hashes.SHA1() elif siglen == 32: hash_algorithm = hashes.SHA256() else: raise VerificationError("Invalid signature length %d." % siglen)...
Converts collection items to aff4 urns suitable for downloading.
def _ItemsToUrns(self, items): """Converts collection items to aff4 urns suitable for downloading.""" for item in items: try: yield flow_export.CollectionItemToAff4Path(item, self.client_id) except flow_export.ItemNotExportableError: pass
Generates archive from a given collection.
def Generate(self, items, token=None): """Generates archive from a given collection. Iterates the collection and generates an archive by yielding contents of every referenced AFF4Stream. Args: items: Iterable with items that point to aff4 paths. token: User's ACLToken. Yields: B...
Get available artifact information for rendering.
def Handle(self, args, token=None): """Get available artifact information for rendering.""" # Get all artifacts that aren't Bootstrap and aren't the base class. artifacts_list = sorted( artifact_registry.REGISTRY.GetArtifacts( reload_datastore_artifacts=True), key=lambda art: ar...
Insert a single component at index.
def Insert(self, index, rdfpathspec=None, **kwarg): """Insert a single component at index.""" if rdfpathspec is None: rdfpathspec = self.__class__(**kwarg) if index == 0: # Copy ourselves to a temp copy. nested_proto = self.__class__() nested_proto.SetRawData(self.GetRawData()) ...
Append a new pathspec component to this pathspec.
def Append(self, component=None, **kwarg): """Append a new pathspec component to this pathspec.""" if component is None: component = self.__class__(**kwarg) if self.HasField("pathtype"): self.last.nested_path = component else: for k, v in iteritems(kwarg): setattr(self, k, v) ...
Removes and returns the pathspec at the specified index.
def Pop(self, index=0): """Removes and returns the pathspec at the specified index.""" if index < 0: index += len(self) if index == 0: result = self.__class__() result.SetRawData(self.GetRawData()) self.SetRawData(self.nested_path.GetRawData()) else: # Get the raw protob...
Get a new copied object with only the directory path.
def Dirname(self): """Get a new copied object with only the directory path.""" result = self.Copy() while 1: last_directory = posixpath.dirname(result.last.path) if last_directory != "/" or len(result) <= 1: result.last.path = last_directory # Make sure to clear the inode inform...
Returns the AFF4 URN this pathspec will be stored under.
def AFF4Path(self, client_urn): """Returns the AFF4 URN this pathspec will be stored under. Args: client_urn: A ClientURN. Returns: A urn that corresponds to this pathspec. Raises: ValueError: If pathspec is not of the correct type. """ # If the first level is OS and the sec...
GlobExpression is valid.
def Validate(self): """GlobExpression is valid.""" if len(self.RECURSION_REGEX.findall(self._value)) > 1: raise ValueError("Only one ** is permitted per path: %s." % self._value)