INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Normalize the series to have a fixed period over a fixed time range. Supports two modes, depending on the type of data: NORMALIZE_MODE_GAUGE: support gauge values. If multiple original data points lie within an output interval, the output value is an average of the original data point. if n...
def Normalize(self, period, start_time, stop_time, mode=NORMALIZE_MODE_GAUGE): """Normalize the series to have a fixed period over a fixed time range. Supports two modes, depending on the type of data: NORMALIZE_MODE_GAUGE: support gauge values. If multiple original data points lie within an out...
Makes the time series increasing. Assumes that series is based on a counter which is occasionally reset, and using this assumption converts the sequence to estimate the total number of counts which occurred. NOTE: Could give inacurate numbers in either of the following cases: 1) Multiple resets oc...
def MakeIncreasing(self): """Makes the time series increasing. Assumes that series is based on a counter which is occasionally reset, and using this assumption converts the sequence to estimate the total number of counts which occurred. NOTE: Could give inacurate numbers in either of the following...
Convert the sequence to the sequence of differences between points. The value of each point v[i] is replaced by v[i+1] - v[i], except for the last point which is dropped.
def ToDeltas(self): """Convert the sequence to the sequence of differences between points. The value of each point v[i] is replaced by v[i+1] - v[i], except for the last point which is dropped. """ if len(self.data) < 2: self.data = [] return for i in range(0, len(self.data) - 1): ...
Add other to self pointwise. Requires that both self and other are of the same length, and contain identical timestamps. Typically this means that Normalize has been called on both with identical time parameters. Args: other: The sequence to add to self. Raises: RuntimeError: other do...
def Add(self, other): """Add other to self pointwise. Requires that both self and other are of the same length, and contain identical timestamps. Typically this means that Normalize has been called on both with identical time parameters. Args: other: The sequence to add to self. Raises:...
Return the arithmatic mean of all values.
def Mean(self): """Return the arithmatic mean of all values.""" values = [v for v, _ in self.data if v is not None] if not values: return None # TODO(hanuszczak): Why do we return a floored division result instead of # the exact value? return sum(values) // len(values)
Check the source is well constructed.
def Validate(self): """Check the source is well constructed.""" self._ValidateReturnedTypes() self._ValidatePaths() self._ValidateType() self._ValidateRequiredAttributes() self._ValidateCommandArgs()
Handle dict generation specifically for Artifacts.
def ToPrimitiveDict(self): """Handle dict generation specifically for Artifacts.""" artifact_dict = super(Artifact, self).ToPrimitiveDict() # ArtifactName is not JSON-serializable, so convert name to string. artifact_dict["name"] = utils.SmartStr(self.name) # Convert proto enum to simple strings s...
Verifies this filter set can process the result data.
def Validate(self): """Verifies this filter set can process the result data.""" # All filters can handle the input type. bad_filters = [] for f in self.filters: try: f.Validate() except DefinitionError as e: bad_filters.append("%s: %s" % (f.expression, e)) if bad_filters:...
Take the data and yield results that passed through the filters. The output of each filter is added to a result set. So long as the filter selects, but does not modify, raw data, the result count will remain accurate. Args: raw_data: An iterable series of rdf values. Returns: A list o...
def Parse(self, raw_data): """Take the data and yield results that passed through the filters. The output of each filter is added to a result set. So long as the filter selects, but does not modify, raw data, the result count will remain accurate. Args: raw_data: An iterable series of rdf va...
Take the results and yield results that passed through the filters. The output of each filter is used as the input for successive filters. Args: raw_data: An iterable series of rdf values. Returns: A list of rdf values that matched all filters.
def Parse(self, raw_data): """Take the results and yield results that passed through the filters. The output of each filter is used as the input for successive filters. Args: raw_data: An iterable series of rdf values. Returns: A list of rdf values that matched all filters. """ se...
Return an initialized filter. Only initialize filters once. Args: filter_name: The name of the filter, as a string. Returns: an initialized instance of the filter. Raises: DefinitionError if the type of filter has not been defined.
def GetFilter(cls, filter_name): """Return an initialized filter. Only initialize filters once. Args: filter_name: The name of the filter, as a string. Returns: an initialized instance of the filter. Raises: DefinitionError if the type of filter has not been defined. """ # C...
Recurse down an attribute chain to the actual result data.
def _GetVal(self, obj, key): """Recurse down an attribute chain to the actual result data.""" if "." in key: lhs, rhs = key.split(".", 1) obj2 = getattr(obj, lhs, None) if obj2 is None: return None return self._GetVal(obj2, rhs) else: return getattr(obj, key, None)
Parse one or more objects using an objectfilter expression.
def ParseObjs(self, objs, expression): """Parse one or more objects using an objectfilter expression.""" filt = self._Compile(expression) for result in filt.Filter(objs): yield result
Generate lambdas for uid and gid comparison.
def _Comparator(self, operator): """Generate lambdas for uid and gid comparison.""" if operator == "=": return lambda x, y: x == y elif operator == ">=": return lambda x, y: x >= y elif operator == ">": return lambda x, y: x > y elif operator == "<=": return lambda x, y: x <=...
Initialize the filter configuration from a validated configuration. The configuration is read. Active filters are added to the matcher list, which is used to process the Stat values.
def _Initialize(self): """Initialize the filter configuration from a validated configuration. The configuration is read. Active filters are added to the matcher list, which is used to process the Stat values. """ if self.cfg.mask: self.mask = int(self.cfg.mask[0], 8) else: self.mas...
Parse one or more objects by testing if it has matching stat results. Args: objs: An iterable of objects that should be checked. expression: A StatFilter expression, e.g.: "uid:>0 gid:=0 file_type:link" Yields: matching objects.
def ParseObjs(self, objs, expression): """Parse one or more objects by testing if it has matching stat results. Args: objs: An iterable of objects that should be checked. expression: A StatFilter expression, e.g.: "uid:>0 gid:=0 file_type:link" Yields: matching objects. """ ...
Validates that a parsed rule entry is valid for fschecker. Args: expression: A rule expression. Raises: DefinitionError: If the filter definition could not be validated. Returns: True if the expression validated OK.
def Validate(self, expression): """Validates that a parsed rule entry is valid for fschecker. Args: expression: A rule expression. Raises: DefinitionError: If the filter definition could not be validated. Returns: True if the expression validated OK. """ parsed = self._Load(...
Parse one or more objects by testing if it is a known RDF class.
def ParseObjs(self, objs, type_names): """Parse one or more objects by testing if it is a known RDF class.""" for obj in objs: for type_name in self._RDFTypes(type_names): if isinstance(obj, self._GetClass(type_name)): yield obj
Filtered types need to be RDFValues.
def Validate(self, type_names): """Filtered types need to be RDFValues.""" errs = [n for n in self._RDFTypes(type_names) if not self._GetClass(n)] if errs: raise DefinitionError("Undefined RDF Types: %s" % ",".join(errs))
Main.
def main(argv): """Main.""" del argv # Unused. if flags.FLAGS.version: print("GRR worker {}".format(config_server.VERSION["packageversion"])) return config.CONFIG.AddContext(contexts.WORKER_CONTEXT, "Context applied when running a worker.") # Initialise flows and config_...
A compatibility wrapper for getting object's name. In Python 2 class names are returned as `bytes` (since class names can contain only ASCII characters) whereas in Python 3 they are `unicode` (since class names can contain arbitrary unicode characters). This function makes this behaviour consistent and always...
def GetName(obj): """A compatibility wrapper for getting object's name. In Python 2 class names are returned as `bytes` (since class names can contain only ASCII characters) whereas in Python 3 they are `unicode` (since class names can contain arbitrary unicode characters). This function makes this behaviou...
A compatibility wrapper for setting object's name. See documentation for `GetName` for more information. Args: obj: A type or function object to set the name for. name: A name to set.
def SetName(obj, name): """A compatibility wrapper for setting object's name. See documentation for `GetName` for more information. Args: obj: A type or function object to set the name for. name: A name to set. """ # Not doing type assertion on obj, since it may be a mock object used # in tests. ...
A compatibility wrapper for listing class attributes. This method solves similar Python 2 compatibility issues for `dir` function as `GetName` does for `__name__` invocations. See documentation for `GetName` for more details. Once support for Python 2 is dropped all invocations of this function should be re...
def ListAttrs(cls): """A compatibility wrapper for listing class attributes. This method solves similar Python 2 compatibility issues for `dir` function as `GetName` does for `__name__` invocations. See documentation for `GetName` for more details. Once support for Python 2 is dropped all invocations of thi...
A compatibility wrapper for the `type` built-in function. In Python 2 `type` (used as a type constructor) requires the name argument to be a `bytes` object whereas in Python 3 it is required to be an `unicode` object. Since class name is human readable text rather than arbitrary stream of bytes, the Python 3 b...
def MakeType(name, base_classes, namespace): """A compatibility wrapper for the `type` built-in function. In Python 2 `type` (used as a type constructor) requires the name argument to be a `bytes` object whereas in Python 3 it is required to be an `unicode` object. Since class name is human readab...
A compatibility wrapper for the `strftime` function. It is guaranteed to always take unicode string as an argument and return an unicode string as a result. Args: fmt: A format string specifying formatting of the output. stime: A time representation as returned by `gmtime` or `localtime`. Returns: ...
def FormatTime(fmt, stime = None): """A compatibility wrapper for the `strftime` function. It is guaranteed to always take unicode string as an argument and return an unicode string as a result. Args: fmt: A format string specifying formatting of the output. stime: A time representation as returned by...
A wrapper for `shlex.split` that works with unicode objects. Args: string: A unicode string to split. Returns: A list of unicode strings representing parts of the input string.
def ShlexSplit(string): """A wrapper for `shlex.split` that works with unicode objects. Args: string: A unicode string to split. Returns: A list of unicode strings representing parts of the input string. """ precondition.AssertType(string, Text) if PY2: string = string.encode("utf-8") part...
A wrapper for `os.environ.get` that works the same way in both Pythons. Args: variable: A name of the variable to get the value of. default: A default value to return in case no value for the given variable is set. Returns: An environment value of the given variable.
def Environ(variable, default): """A wrapper for `os.environ.get` that works the same way in both Pythons. Args: variable: A name of the variable to get the value of. default: A default value to return in case no value for the given variable is set. Returns: An environment value of the given v...
Attempt to drop privileges if required.
def DropPrivileges(): """Attempt to drop privileges if required.""" if config.CONFIG["Server.username"]: try: os.setuid(pwd.getpwnam(config.CONFIG["Server.username"]).pw_uid) except (KeyError, OSError): logging.exception("Unable to switch to user %s", config.CONFIG["Serve...
Run all required startup routines and initialization hooks.
def Init(): """Run all required startup routines and initialization hooks.""" global INIT_RAN if INIT_RAN: return # Set up a temporary syslog handler so we have somewhere to log problems # with ConfigInit() which needs to happen before we can start our create our # proper logging setup. syslog_logger...
Returns a path to version.ini.
def VersionPath(): """Returns a path to version.ini.""" # Try to get a version.ini. It should be in the resources if the code # was packed with "pip sdist". It will be 2 levels up from grr_response_core # if the code was installed via "pip install -e". version_ini = ( package.ResourcePath("grr-response...
Return a dict with GRR version information.
def Version(): """Return a dict with GRR version information.""" version_ini = VersionPath() config = configparser.SafeConfigParser() config.read(version_ini) return dict( packageversion=config.get("Version", "packageversion"), major=config.getint("Version", "major"), minor=config.getint("...
Reads at most num_bytes starting from offset <address>.
def ReadBytes(self, address, num_bytes): """Reads at most num_bytes starting from offset <address>.""" pdata = ctypes.c_void_p(0) data_cnt = ctypes.c_uint32(0) ret = libc.mach_vm_read(self.task, ctypes.c_ulonglong(address), ctypes.c_longlong(num_bytes), ctypes.pointer(pdata)...
Iterates over the readable regions for this process. We use mach_vm_region_recurse here to get a fine grained view of the process' memory space. The algorithm is that for some regions, the function returns is_submap=True which means that there are actually subregions that we need to examine by increasi...
def Regions(self, skip_executable_regions=False, skip_shared_regions=False, skip_readonly_regions=False): """Iterates over the readable regions for this process. We use mach_vm_region_recurse here to get a fine grained view of the process' memory space. The algorit...
Converts a binary SID to its string representation. https://msdn.microsoft.com/en-us/library/windows/desktop/aa379597.aspx The byte representation of an SID is as follows: Offset Length Description 00 01 revision 01 01 sub-authority count 02 06 authority (big endian...
def BinarySIDtoStringSID(sid): """Converts a binary SID to its string representation. https://msdn.microsoft.com/en-us/library/windows/desktop/aa379597.aspx The byte representation of an SID is as follows: Offset Length Description 00 01 revision 01 01 sub-authority count 0...
Parse WMI Event Consumers.
def ParseMultiple(self, result_dicts): """Parse WMI Event Consumers.""" for result_dict in result_dicts: wmi_dict = result_dict.ToDict() try: creator_sid_bytes = bytes(wmi_dict["CreatorSID"]) wmi_dict["CreatorSID"] = BinarySIDtoStringSID(creator_sid_bytes) except ValueError: ...
Parse the WMI packages output.
def ParseMultiple(self, result_dicts): """Parse the WMI packages output.""" status = rdf_client.SoftwarePackage.InstallState.INSTALLED packages = [] for result_dict in result_dicts: packages.append( rdf_client.SoftwarePackage( name=result_dict["Name"], descrip...
Take a US format date and return epoch.
def AmericanDateToEpoch(self, date_str): """Take a US format date and return epoch.""" try: epoch = time.strptime(date_str, "%m/%d/%Y") return int(calendar.timegm(epoch)) * 1000000 except ValueError: return 0
Parse the WMI packages output.
def ParseMultiple(self, result_dicts): """Parse the WMI packages output.""" status = rdf_client.SoftwarePackage.InstallState.INSTALLED packages = [] for result_dict in result_dicts: result = result_dict.ToDict() # InstalledOn comes back in a godawful format such as '7/10/2013'. insta...
Parse the WMI Win32_UserAccount output.
def ParseMultiple(self, result_dicts): """Parse the WMI Win32_UserAccount output.""" for result_dict in result_dicts: kb_user = rdf_client.User() for wmi_key, kb_key in iteritems(self.account_mapping): try: kb_user.Set(kb_key, result_dict[wmi_key]) except KeyError: ...
Parse the WMI packages output.
def ParseMultiple(self, result_dicts): """Parse the WMI packages output.""" for result_dict in result_dicts: result = result_dict.ToDict() winvolume = rdf_client_fs.WindowsVolume( drive_letter=result.get("DeviceID"), drive_type=result.get("DriveType")) try: size = ...
Parse the WMI output to get Identifying Number.
def ParseMultiple(self, result_dicts): """Parse the WMI output to get Identifying Number.""" for result_dict in result_dicts: # Currently we are only grabbing the Identifying Number # as the serial number (catches the unique number for VMs). # This could be changed to include more information ...
Return RDFDatetime from string like 20140825162259.000000-420. Args: timestr: WMI time string Returns: rdfvalue.RDFDatetime We have some timezone manipulation work to do here because the UTC offset is in minutes rather than +-HHMM
def WMITimeStrToRDFDatetime(self, timestr): """Return RDFDatetime from string like 20140825162259.000000-420. Args: timestr: WMI time string Returns: rdfvalue.RDFDatetime We have some timezone manipulation work to do here because the UTC offset is in minutes rather than +-HHMM """...
Parse the WMI packages output.
def ParseMultiple(self, result_dicts): """Parse the WMI packages output.""" for result_dict in result_dicts: args = {"ifname": result_dict["Description"]} args["mac_address"] = binascii.unhexlify( result_dict["MACAddress"].replace(":", "")) self._ConvertIPs([("IPAddress", "addresses...
Extracts the client id from a session id.
def _ClientIDFromSessionID(session_id): """Extracts the client id from a session id.""" parts = session_id.Split(4) client_id = parts[0] if re.match(r"C\.[0-9a-f]{16}", client_id): return client_id # Maybe it's a legacy hunt id (aff4:/hunts/<hunt_id>/<client_id>/... client_id = parts[2] if re.match(...
Helper function to convert legacy client replies to flow responses.
def FlowResponseForLegacyResponse(legacy_msg): """Helper function to convert legacy client replies to flow responses.""" if legacy_msg.type == legacy_msg.Type.MESSAGE: response = FlowResponse( client_id=_ClientIDFromSessionID(legacy_msg.session_id), flow_id=legacy_msg.session_id.Basename(), ...
Iterator returning dict for each entry in history.
def Parse(self): """Iterator returning dict for each entry in history.""" for data in self.Query(self.EVENTS_QUERY): (timestamp, agent_bundle_identifier, agent_name, url, sender, sender_address, type_number, title, referrer, referrer_alias) = data yield [ timestamp, "OSX_QUARANTINE"...
Retrieves information for an IP4 address.
def RetrieveIP4Info(self, ip): """Retrieves information for an IP4 address.""" if ip.is_private: return (IPInfo.INTERNAL, "Internal IP address.") try: # It's an external IP, let's try to do a reverse lookup. res = socket.getnameinfo((str(ip), 0), socket.NI_NAMEREQD) return (IPInfo.EX...
Gets a connection. Args: blocking: Whether to block when max_size connections are already in use. If false, may return None. Returns: A connection to the database. Raises: PoolAlreadyClosedError: if close() method was already called on this pool.
def get(self, blocking=True): """Gets a connection. Args: blocking: Whether to block when max_size connections are already in use. If false, may return None. Returns: A connection to the database. Raises: PoolAlreadyClosedError: if close() method was already called on ...
Verify we have at least one template that matches maj.minor version.
def CheckTemplates(self, base_dir, version): """Verify we have at least one template that matches maj.minor version.""" major_minor = ".".join(version.split(".")[0:2]) templates = glob.glob( os.path.join(base_dir, "templates/*%s*.zip" % major_minor)) required_templates = set( [x.replace(...
Does the actual termination.
def _TerminateFlow(rdf_flow, reason=None, flow_state=rdf_flow_objects.Flow.FlowState.ERROR): """Does the actual termination.""" flow_cls = registry.FlowRegistry.FlowClassByName(rdf_flow.flow_class_name) flow_obj = flow_cls(rdf_flow) if not flow_obj.IsRunning(): # Nothi...
Terminates a flow and all of its children. Args: client_id: Client ID of a flow to terminate. flow_id: Flow ID of a flow to terminate. reason: String with a termination reason. flow_state: Flow state to be assigned to a flow after termination. Defaults to FlowState.ERROR.
def TerminateFlow(client_id, flow_id, reason=None, flow_state=rdf_flow_objects.Flow.FlowState.ERROR): """Terminates a flow and all of its children. Args: client_id: Client ID of a flow to terminate. flow_id: Flow ID of a flow to terminate. reason: S...
Decorator that creates AFF4 and RELDB flows from a given mixin.
def DualDBFlow(cls): """Decorator that creates AFF4 and RELDB flows from a given mixin.""" if issubclass(cls, flow.GRRFlow): raise ValueError("Mixin class shouldn't inherit from GRRFlow.") if cls.__name__[-5:] != "Mixin": raise ValueError("Flow mixin should have a name that ends in 'Mixin'.") flow_na...
This method is used to schedule a new state on a different worker. This is basically the same as CallFlow() except we are calling ourselves. The state will be invoked at a later time. Args: next_state: The state in this flow to be invoked. start_time: Start the flow at this time. This delays...
def CallState(self, next_state="", start_time=None): """This method is used to schedule a new state on a different worker. This is basically the same as CallFlow() except we are calling ourselves. The state will be invoked at a later time. Args: next_state: The state in this flow to be invoked....
Calls the client asynchronously. This sends a message to the client to invoke an Action. The run action may send back many responses that will be queued by the framework until a status message is sent by the client. The status message will cause the entire transaction to be committed to the specified s...
def CallClient(self, action_cls, request=None, next_state=None, request_data=None, **kwargs): """Calls the client asynchronously. This sends a message to the client to invoke an Action. The run action may send back many re...
Creates a new flow and send its responses to a state. This creates a new flow. The flow may send back many responses which will be queued by the framework until the flow terminates. The final status message will cause the entire transaction to be committed to the specified state. Args: flow_nam...
def CallFlow(self, flow_name=None, next_state=None, request_data=None, client_id=None, base_session_id=None, **kwargs): """Creates a new flow and send its responses to a state. This creates a new flow. The flow may send b...
Allows this flow to send a message to its parent flow. If this flow does not have a parent, the message is ignored. Args: response: An RDFValue() instance to be sent to the parent. tag: If specified, tag the result with this tag. Raises: ValueError: If responses is not of the correct ty...
def SendReply(self, response, tag=None): """Allows this flow to send a message to its parent flow. If this flow does not have a parent, the message is ignored. Args: response: An RDFValue() instance to be sent to the parent. tag: If specified, tag the result with this tag. Raises: V...
Method to tally resources.
def SaveResourceUsage(self, status): """Method to tally resources.""" user_cpu = status.cpu_time_used.user_cpu_time system_cpu = status.cpu_time_used.system_cpu_time self.rdf_flow.cpu_time_used.user_cpu_time += user_cpu self.rdf_flow.cpu_time_used.system_cpu_time += system_cpu self.rdf_flow.net...
Terminates this flow with an error.
def Error(self, error_message=None, backtrace=None, status=None): """Terminates this flow with an error.""" stats_collector_instance.Get().IncrementCounter( "flow_errors", fields=[compatibility.GetName(self.__class__)]) client_id = self.rdf_flow.client_id flow_id = self.rdf_flow.flow_id lo...
Marks this flow as done.
def MarkDone(self, status=None): """Marks this flow as done.""" stats_collector_instance.Get().IncrementCounter( "flow_completions", fields=[compatibility.GetName(self.__class__)]) # Notify our parent flow or hunt that we are done (if there's a parent flow # or hunt). if self.rdf_flow.paren...
Logs the message using the flow's standard logging. Args: format_str: Format string *args: arguments to the format string
def Log(self, format_str, *args): """Logs the message using the flow's standard logging. Args: format_str: Format string *args: arguments to the format string """ log_entry = rdf_flow_objects.FlowLogEntry( client_id=self.rdf_flow.client_id, flow_id=self.rdf_flow.flow_id, ...
Completes the request by calling the state method. Args: method_name: The name of the state method to call. request: A RequestState protobuf. responses: A list of FlowMessages responding to the request.
def RunStateMethod(self, method_name, request=None, responses=None): """Completes the request by calling the state method. Args: method_name: The name of the state method to call. request: A RequestState protobuf. responses: A list of FlowMessages responding to the request. """ if sel...
Processes all requests that are due to run. Returns: The number of processed requests.
def ProcessAllReadyRequests(self): """Processes all requests that are due to run. Returns: The number of processed requests. """ request_dict = data_store.REL_DB.ReadFlowRequestsReadyForProcessing( self.rdf_flow.client_id, self.rdf_flow.flow_id, next_needed_request=self.rd...
Processes replies with output plugins.
def _ProcessRepliesWithFlowOutputPlugins(self, replies): """Processes replies with output plugins.""" created_output_plugins = [] for index, output_plugin_state in enumerate( self.rdf_flow.output_plugins_states): plugin_descriptor = output_plugin_state.plugin_descriptor output_plugin_cls...
Converts an AFF4 URN for a signed binary to a SignedBinaryID.
def _SignedBinaryIDFromURN(binary_urn ): """Converts an AFF4 URN for a signed binary to a SignedBinaryID.""" if binary_urn.RelativeName(GetAFF4PythonHackRoot()): return rdf_objects.SignedBinaryID( binary_type=rdf_objects.SignedBinaryID.BinaryType.PYTHON_HACK, path=binar...
Converts a SignedBinaryID to the equivalent AFF4 URN.
def _SignedBinaryURNFromID(binary_id ): """Converts a SignedBinaryID to the equivalent AFF4 URN.""" binary_type = binary_id.binary_type if binary_type == rdf_objects.SignedBinaryID.BinaryType.PYTHON_HACK: return GetAFF4PythonHackRoot().Add(binary_id.path) elif binary_type == rdf_ob...
Signs a binary and saves it to the datastore. If a signed binary with the given URN already exists, its contents will get overwritten. Args: binary_urn: URN that should serve as a unique identifier for the binary. binary_content: Contents of the binary, as raw bytes. private_key: Key that should be ...
def WriteSignedBinary(binary_urn, binary_content, private_key, public_key, chunk_size = 1024, token = None): """Signs a binary and saves it to the datastore. If a signed binary with the given URN already e...
Saves signed blobs to the datastore. If a signed binary with the given URN already exists, its contents will get overwritten. Args: binary_urn: RDFURN that should serve as a unique identifier for the binary. blobs: An Iterable of signed blobs to write to the datastore. token: ACL token to use with t...
def WriteSignedBinaryBlobs(binary_urn, blobs, token = None): """Saves signed blobs to the datastore. If a signed binary with the given URN already exists, its contents will get overwritten. Args: binary_urn: RDFURN that should serve as a unique identif...
Deletes the binary with the given urn from the datastore. Args: binary_urn: RDFURN that serves as a unique identifier for the binary. token: ACL token to use with the legacy (non-relational) datastore. Raises: SignedBinaryNotFoundError: If the signed binary does not exist.
def DeleteSignedBinary(binary_urn, token = None): """Deletes the binary with the given urn from the datastore. Args: binary_urn: RDFURN that serves as a unique identifier for the binary. token: ACL token to use with the legacy (non-relational) datastore. Raises: SignedBinaryNo...
Returns URNs for all signed binaries in the datastore. Args: token: ACL token to use with the legacy (non-relational) datastore.
def FetchURNsForAllSignedBinaries(token ): """Returns URNs for all signed binaries in the datastore. Args: token: ACL token to use with the legacy (non-relational) datastore. """ if _ShouldUseLegacyDatastore(): urns = [] aff4_roots = [GetAFF4PythonHackRoot(), GetAFF...
Retrieves blobs for the given binary from the datastore. Args: binary_urn: RDFURN that uniquely identifies the binary. token: ACL token to use with the legacy (non-relational) datastore. Returns: A tuple containing an iterator for all the binary's blobs and an RDFDatetime representing when the bin...
def FetchBlobsForSignedBinary( binary_urn, token = None ): """Retrieves blobs for the given binary from the datastore. Args: binary_urn: RDFURN that uniquely identifies the binary. token: ACL token to use with the legacy (non-relational) datastore. Returns: A tuple containing an iterator for...
Returns the size of the given binary (in bytes). Args: binary_urn: RDFURN that uniquely identifies the binary. token: ACL token to use with the legacy (non-relational) datastore. Raises: SignedBinaryNotFoundError: If no signed binary with the given URN exists.
def FetchSizeOfSignedBinary(binary_urn, token = None ): """Returns the size of the given binary (in bytes). Args: binary_urn: RDFURN that uniquely identifies the binary. token: ACL token to use with the legacy (non-relational) datastore. Raises: ...
Yields the contents of the given binary in chunks of the given size. Args: blob_iterator: An Iterator over all the binary's blobs. chunk_size: Size, in bytes, of the chunks to yield.
def StreamSignedBinaryContents(blob_iterator, chunk_size = 1024 ): """Yields the contents of the given binary in chunks of the given size. Args: blob_iterator: An Iterator over all the binary's blobs. chunk_size: Size, in bytes, of the chunks to ...
Creates or overwrites blobs.
def WriteBlobs(self, blob_id_data_map): """Creates or overwrites blobs.""" urns = {self._BlobUrn(blob_id): blob_id for blob_id in blob_id_data_map} mutation_pool = data_store.DB.GetMutationPool() existing = aff4.FACTORY.MultiOpen( urns, aff4_type=aff4.AFF4MemoryStreamBase, mode="r") for ...
Check if blobs for the given digests already exist.
def CheckBlobsExist(self, blob_ids): """Check if blobs for the given digests already exist.""" res = {blob_id: False for blob_id in blob_ids} urns = {self._BlobUrn(blob_id): blob_id for blob_id in blob_ids} existing = aff4.FACTORY.MultiOpen( urns, aff4_type=aff4.AFF4MemoryStreamBase, mode="r")...
Returns named placeholders from all elements of the given iterable. Use this function for VALUES of MySQL INSERTs. To account for Iterables with undefined order (dicts before Python 3.6), this function sorts column names. Examples: >>> NamedPlaceholders({"password": "foo", "name": "bar"}) u'(%(name)s...
def NamedPlaceholders(iterable): """Returns named placeholders from all elements of the given iterable. Use this function for VALUES of MySQL INSERTs. To account for Iterables with undefined order (dicts before Python 3.6), this function sorts column names. Examples: >>> NamedPlaceholders({"password": ...
Returns a string of column names for MySQL INSERTs. To account for Iterables with undefined order (dicts before Python 3.6), this function sorts column names. Examples: >>> Columns({"password": "foo", "name": "bar"}) u'(`name`, `password`)' Args: iterable: The iterable of strings to be used as co...
def Columns(iterable): """Returns a string of column names for MySQL INSERTs. To account for Iterables with undefined order (dicts before Python 3.6), this function sorts column names. Examples: >>> Columns({"password": "foo", "name": "bar"}) u'(`name`, `password`)' Args: iterable: The iterable...
Converts MySQL `TIMESTAMP(6)` columns to datetime objects.
def TimestampToRDFDatetime(timestamp): """Converts MySQL `TIMESTAMP(6)` columns to datetime objects.""" # TODO(hanuszczak): `timestamp` should be of MySQL type `Decimal`. However, # it is unclear where this type is actually defined and how to import it in # order to have a type assertion. if timestamp is None...
Converts a list of path components to a canonical path representation. Args: components: A sequence of path components. Returns: A canonical MySQL path representation.
def ComponentsToPath(components): """Converts a list of path components to a canonical path representation. Args: components: A sequence of path components. Returns: A canonical MySQL path representation. """ precondition.AssertIterableType(components, Text) for component in components: if not...
Converts a canonical path representation to a list of components. Args: path: A canonical MySQL path representation. Returns: A sequence of path components.
def PathToComponents(path): """Converts a canonical path representation to a list of components. Args: path: A canonical MySQL path representation. Returns: A sequence of path components. """ precondition.AssertType(path, Text) if path and not path.startswith("/"): raise ValueError("Path '{}' ...
Log any invalid run states found.
def _LogInvalidRunLevels(states, valid): """Log any invalid run states found.""" invalid = set() for state in states: if state not in valid: invalid.add(state) if invalid: logging.warning("Invalid init runlevel(s) encountered: %s", ", ".join(invalid))
Accepts a string and returns a list of strings of numeric LSB runlevels.
def GetRunlevelsLSB(states): """Accepts a string and returns a list of strings of numeric LSB runlevels.""" if not states: return set() valid = set(["0", "1", "2", "3", "4", "5", "6"]) _LogInvalidRunLevels(states, valid) return valid.intersection(set(states.split()))
Accepts a string and returns a list of strings of numeric LSB runlevels.
def GetRunlevelsNonLSB(states): """Accepts a string and returns a list of strings of numeric LSB runlevels.""" if not states: return set() convert_table = { "0": "0", "1": "1", "2": "2", "3": "3", "4": "4", "5": "5", "6": "6", # SysV, Gentoo, Solaris, HP-UX all ...
Expand insserv variables.
def _InsservExpander(self, facilities, val): """Expand insserv variables.""" expanded = [] if val.startswith("$"): vals = facilities.get(val, []) for v in vals: expanded.extend(self._InsservExpander(facilities, v)) elif val.startswith("+"): expanded.append(val[1:]) else: ...
/etc/insserv.conf* entries define system facilities. Full format details are in man 8 insserv, but the basic structure is: $variable facility1 facility2 $second_variable facility3 $variable Any init script that specifies Required-Start: $second_variable needs to be expanded to facil...
def _ParseInsserv(self, data): """/etc/insserv.conf* entries define system facilities. Full format details are in man 8 insserv, but the basic structure is: $variable facility1 facility2 $second_variable facility3 $variable Any init script that specifies Required-Start: $second_vari...
Extract entries from the xinetd config files.
def _ProcessEntries(self, fd): """Extract entries from the xinetd config files.""" p = config_file.KeyValueParser(kv_sep="{", term="}", sep=None) data = utils.ReadFileBytesAsUnicode(fd) entries = p.ParseEntries(data) for entry in entries: for section, cfg in iteritems(entry): # The par...
Interpolate configurations with defaults to generate actual configs.
def _GenConfig(self, cfg): """Interpolate configurations with defaults to generate actual configs.""" # Some setting names may have a + or - suffix. These indicate that the # settings modify the default values. merged = self.default.copy() for setting, vals in iteritems(cfg): option, operator ...
Identify the init scripts and the start/stop scripts at each runlevel. Evaluate all the stat entries collected from the system. If the path name matches a runlevel spec, and if the filename matches a sysv init symlink process the link as a service. Args: stats: An iterator of StatEntry rdfs. ...
def ParseMultiple(self, stats, unused_file_obj, unused_kb): """Identify the init scripts and the start/stop scripts at each runlevel. Evaluate all the stat entries collected from the system. If the path name matches a runlevel spec, and if the filename matches a sysv init symlink process the link as a ...
Checks a given client against labels/owners whitelists.
def CheckClientLabels(client_id, labels_whitelist=None, labels_owners_whitelist=None, token=None): """Checks a given client against labels/owners whitelists.""" labels_whitelist = labels_whitelist or [] labels_owners_whitelist = labels_owners_whit...
Returns whether error is likely to be retryable.
def _IsRetryable(error): """Returns whether error is likely to be retryable.""" if not isinstance(error, MySQLdb.OperationalError): return False if not error.args: return False code = error.args[0] return code in _RETRYABLE_ERRORS
Checks MySQL collation and warns if misconfigured.
def _CheckCollation(cursor): """Checks MySQL collation and warns if misconfigured.""" # Do not fail for wrong collation, because changing it is harder than changing # the character set. Some providers only allow changing character set and then # use the default collation. Also, misconfigured collation is not e...
Enforces a sane UTF-8 encoding for the database connection.
def _CheckConnectionEncoding(cursor): """Enforces a sane UTF-8 encoding for the database connection.""" cur_character_set = _ReadVariable("character_set_connection", cursor) if cur_character_set != CHARACTER_SET: raise EncodingEnforcementError( "Require MySQL character_set_connection of {}, got {}.".f...
Enforces a sane UTF-8 encoding for the database.
def _CheckDatabaseEncoding(cursor): """Enforces a sane UTF-8 encoding for the database.""" cur_character_set = _ReadVariable("character_set_database", cursor) if cur_character_set != CHARACTER_SET: raise EncodingEnforcementError( "Require MySQL character_set_database of {}, got {}." " To creat...
Sets max_allowed_packet globally for new connections (not current!).
def _SetPacketSizeForFollowingConnections(cursor): """Sets max_allowed_packet globally for new connections (not current!).""" cur_packet_size = int(_ReadVariable("max_allowed_packet", cursor)) if cur_packet_size < MAX_PACKET_SIZE: logging.warning( "MySQL max_allowed_packet of %d is required, got %d. ...
Checks that MySQL packet size is big enough for expected query size.
def _CheckPacketSize(cursor): """Checks that MySQL packet size is big enough for expected query size.""" cur_packet_size = int(_ReadVariable("max_allowed_packet", cursor)) if cur_packet_size < MAX_PACKET_SIZE: raise Error( "MySQL max_allowed_packet of {0} is required, got {1}. " "Please set ma...
Warns if MySQL log file size is not large enough for blob insertions.
def _CheckLogFileSize(cursor): """Warns if MySQL log file size is not large enough for blob insertions.""" # Do not fail, because users might not be able to change this for their # database. Instead, warn the user about the impacts. innodb_log_file_size = int(_ReadVariable("innodb_log_file_size", cursor)) r...
Checks if we are running against MariaDB.
def _IsMariaDB(cursor): """Checks if we are running against MariaDB.""" for variable in ["version", "version_comment"]: cursor.execute("SHOW VARIABLES LIKE %s;", (variable,)) version = cursor.fetchone() if version and "MariaDB" in version[1]: return True return False
Connect to the given MySQL host and create a utf8mb4_unicode_ci database. Args: host: The hostname to connect to. port: The port to connect to. user: The username to connect as. password: The password to connect with. database: The database name to create. client_key_path: The path of the cli...
def _SetupDatabase(host=None, port=None, user=None, password=None, database=None, client_key_path=None, client_cert_path=None, ca_cert_path=None): """Connect to the given MySQL host and...
Builds connection arguments for MySQLdb.Connect function.
def _GetConnectionArgs(host=None, port=None, user=None, password=None, database=None, client_key_path=None, client_cert_path=None, ca_cert_path=None): """Bui...
Connect to MySQL and check if server fulfills requirements.
def _Connect(host=None, port=None, user=None, password=None, database=None, client_key_path=None, client_cert_path=None, ca_cert_path=None): """Connect to MySQL and check if server fulfills requirements.""" connection_args = ...
Runs function within a transaction. Allocates a connection, begins a transaction on it and passes the connection to function. If function finishes without raising, the transaction is committed. If function raises, the transaction will be rolled back, if a retryable database error is raised, the o...
def _RunInTransaction(self, function, readonly=False): """Runs function within a transaction. Allocates a connection, begins a transaction on it and passes the connection to function. If function finishes without raising, the transaction is committed. If function raises, the transaction will be r...