text
stringlengths
81
112k
Run all the actions specified in the rule. Args: rule: Rule which actions are to be executed. client_id: Id of a client where rule's actions are to be executed. Returns: Number of actions started. def _RunActions(self, rule, client_id): """Run all the actions specified in the rule. ...
Examines our rules and starts up flows based on the client. Args: client_id: Client id of the client for tasks to be assigned. Returns: Number of assigned tasks. def AssignTasksToClient(self, client_id): """Examines our rules and starts up flows based on the client. Args: client_id...
Open the delegate object. def Initialize(self): """Open the delegate object.""" if "r" in self.mode: delegate = self.Get(self.Schema.DELEGATE) if delegate: self.delegate = aff4.FACTORY.Open( delegate, mode=self.mode, token=self.token, age=self.age_policy)
Effectively streams data from multiple opened BlobImage objects. Args: fds: A list of opened AFF4Stream (or AFF4Stream descendants) objects. Yields: Tuples (chunk, fd, exception) where chunk is a binary blob of data and fd is an object from the fds argument. If one or more chunks are ...
Retrieve the relevant blob from the AFF4 data store or cache. def _GetChunkForReading(self, chunk): """Retrieve the relevant blob from the AFF4 data store or cache.""" offset = chunk * self._HASH_SIZE self.index.seek(offset) chunk_name = self.index.read(self._HASH_SIZE) try: return self.chu...
Create new blob hashes and append to BlobImage. We don't support writing at arbitrary file offsets, but this method provides a convenient way to add blobs for a new file, or append content to an existing one. Args: src_fd: source file handle open for read Raises: IOError: if blob has ...
Add another blob to this image using its hash. Once a blob is added that is smaller than the chunksize we finalize the file, since handling adding more blobs makes the code much more complex. Args: blob_id: rdf_objects.BlobID object. length: int length of blob Raises: IOError: if bl...
Alternate constructor for GRRSignedBlob. Creates a GRRSignedBlob from a content string by chunking it and signing each chunk. Args: content: The data to stored in the GRRSignedBlob. urn: The AFF4 URN to create. chunk_size: Data will be chunked into this size (each chunk is indiv...
Formats given pattern with this substitution environment. A pattern can contain placeholders for variables (`%%foo%%`) and scopes (`%%bar.baz%%`) that are replaced with concrete values in this substiution environment (specified in the constructor). Args: pattern: A pattern with placeholders to s...
Associates a value with given variable. This can be called multiple times to associate multiple values. Args: var_id: A variable id to bind the values to. value: A value to bind to the specified variable. Raises: KeyError: If given variable is not specified in the pattern. def BindVar(...
Associates given values with given scope. This can be called multiple times to associate multiple values. Args: scope_id: A scope id to bind the values to. values: A mapping from scope variable ids to values to bind in scope. Raises: KeyError: If given scope or scope variable is not spe...
Interpolates the pattern. Yields: All possible interpolation results. def Interpolate(self): """Interpolates the pattern. Yields: All possible interpolation results. """ for var_config in collection.DictProduct(self._var_bindings): for scope_config in collection.DictProduct(self...
Registers a report plugin for use in the GRR UI. def RegisterPlugin(self, report_plugin_cls): """Registers a report plugin for use in the GRR UI.""" name = report_plugin_cls.__name__ if name in self.plugins: raise RuntimeError("Can't register two report plugins with the same " ...
Create the executable template. def MakeExecutableTemplate(self, output_file=None): """Create the executable template.""" super(DarwinClientBuilder, self).MakeExecutableTemplate(output_file=output_file) self.SetBuildVars() self.MakeBuildDirectory() self.BuildWithPyInstaller() self.Cop...
Add a zip to the end of the .xar containing build.yaml. The build.yaml is already inside the .xar file, but we can't easily open this on linux. To make repacking easier we add a zip to the end of the .xar and add in the build.yaml. The repack step will then look at the build.yaml and insert the config....
Builds a package (.pkg) using PackageMaker. def BuildInstallerPkg(self, output_file): """Builds a package (.pkg) using PackageMaker.""" self.CreateInstallDirs() self.InterpolateFiles() self.RenameGRRPyinstallerBinaries() self.SignGRRPyinstallerBinaries() self.WriteClientConfig() self.Set755...
Returns a path-like String of client_path with optional prefix. def _ClientPathToString(client_path, prefix=""): """Returns a path-like String of client_path with optional prefix.""" return os.path.join(prefix, client_path.client_id, client_path.vfs_path)
Generates description into a MANIFEST file in the archive. def _GenerateDescription(self): """Generates description into a MANIFEST file in the archive.""" manifest = { "description": self.description, "processed_files": len(self.processed_files), "archived_files": len(self.archived_fi...
Yields chucks of archive information for given client. def _GenerateClientInfo(self, client_id, client_fd): """Yields chucks of archive information for given client.""" summary_dict = client_fd.ToPrimitiveDict(stringify_leaf_fields=True) summary = yaml.Dump(summary_dict).encode("utf-8") client_info_pa...
Generates archive from a given collection. Iterates the collection and generates an archive by yielding contents of every referenced AFF4Stream. Args: items: Iterable of rdf_client_fs.StatEntry objects token: User's ACLToken. Yields: Binary chunks comprising the generated archive. ...
Yields binary chunks, respecting archive file headers and footers. Args: chunk: the StreamedFileChunk to be written def _WriteFileChunk(self, chunk): """Yields binary chunks, respecting archive file headers and footers. Args: chunk: the StreamedFileChunk to be written """ if chunk.chu...
Add type info definitions from an existing protobuf. We support building this class by copying definitions from an annotated protobuf using the semantic protobuf. This is ideal for interoperability with other languages and non-semantic protobuf implementations. In that case it might be easier to simply annotat...
Sets up all the component in their own threads. def main(argv): """Sets up all the component in their own threads.""" if flags.FLAGS.version: print("GRR server {}".format(config_server.VERSION["packageversion"])) return # We use .startswith so that multiple copies of services can easily be # created ...
Whether x is fully contained in y. def Operation(self, x, y): """Whether x is fully contained in y.""" if x in y: return True # x might be an iterable # first we need to skip strings or we'll do silly things if isinstance(x, string_types) or isinstance(x, bytes): return False try:...
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): ...
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.. ...
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 == "||": me...
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...
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. 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: ParseError: For strings other than those used to define a re...
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 whathev...
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...
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 h...
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(requ...
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() + ...
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...
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) # G...
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 - " ...
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'...
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): ...
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. 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 the end of the function and pass back...
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(backtra...
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 ...
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. Raises: CPUExcee...
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, ...
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(tim...
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...
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...
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, ...
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 sn...
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 semantic value. Raises: ArtifactProcessingError: If called when the kno...
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(clie...
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) responses. def ApplyParsersToResponses(parser_factory, responses, flow...
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 = arti...
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_collect...
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 string to escape. Returns: ...
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...
Write metadata about the client. def WriteClientMetadata(self, client_id, certificate=None, fleetspeak_enabled=None, first_seen=None, last_ping=None, last_clock=No...
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...
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 = rdfval...
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 ...
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.UnknownClientEr...
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_...
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.s...
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 = [] ...
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...
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 n...
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: ...
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): ...
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...
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"] ...
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.Startup...
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: ...
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 h...
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.Fro...
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): clie...
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_st...
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_...
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._CountClie...
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._CountClie...
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. 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. def _CountClientStatisticByLabel(self, day_buckets, extract_statistic_fn): """Ret...
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...
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: ...
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...
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"...
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...
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 chunke...
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=["up...
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: cont...
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...
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 = { "bi...
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_bi...