text
stringlengths
81
112k
Expand artifact by extending its sources. This method takes as input an rdf artifact object and returns a rdf expanded artifact. It iterates through the list of sources processing them by type. Each source of the original artifact can lead to one or more (in case of artifact groups and files where the ...
Recursively expands an artifact group source. def _ExpandArtifactGroupSource(self, source, requested): """Recursively expands an artifact group source.""" artifact_list = [] if "names" in source.attributes: artifact_list = source.attributes["names"] for artifact_name in artifact_list: if ar...
Recursively expands an artifact files source. def _ExpandArtifactFilesSource(self, source, requested): """Recursively expands an artifact files source.""" expanded_source = rdf_artifacts.ExpandedSource(base_source=source) sub_sources = [] artifact_list = [] if "artifact_list" in source.attributes: ...
Creates the nodes and directed edges of the dependency graph. Args: os_name: String specifying the OS name. artifact_list: List of requested artifact names. def _InitializeGraph(self, os_name, artifact_list): """Creates the nodes and directed edges of the dependency graph. Args: os_name...
Add the attribute nodes to the graph. For every attribute that is required for the collection of requested artifacts, add a node to the dependency graph. An attribute node will have incoming edges from the artifacts that provide this attribute and outgoing edges to the artifacts that depend on it. ...
Add the artifact nodes to the graph. For every artifact that has to be collected, add a node to the dependency graph. The edges represent the dependencies. An artifact has outgoing edges to the attributes it provides and incoming edges from attributes it depends on. Initially, only artifacts witho...
Add an edge for every dependency of the given artifact. This method gets the attribute names for a given artifact and for every attribute it adds a directed edge from the attribute node to the artifact node. If an artifact does not have any dependencies it is added to the set of reachable nodes. A...
Add an edge for every attribute the given artifact provides. This method adds a directed edge from the artifact node to every attribute this artifact provides. Args: rdf_artifact: The artifact object. def _AddProvidesEdges(self, rdf_artifact): """Add an edge for every attribute the given artifa...
Add a directed edge to the graph. Add the end to the list of outgoing nodes of the start and the start to the list of incoming nodes of the end node. Args: start_node: name of the start node end_node: name of the end node def _AddEdge(self, start_node, end_node): """Add a directed edge to...
Bring the artifacts in a linear order that resolves dependencies. This method obtains a linear ordering of the nodes and then returns the list of artifact names. Returns: A list of `ArtifactName` instances such that if they are collected in the given order their dependencies are resolved. def...
Consumes an entire range, or part thereof. If the finger has no ranges left, or the curent range start is higher than the end of the consumed block, nothing happens. Otherwise, the current range is adjusted for the consumed block, or removed, if the entire block is consumed. For things to work, the con...
Returns the next Range of the file that is to be hashed. For all fingers, inspect their next expected range, and return the lowest uninterrupted range of interest. If the range is larger than BLOCK_SIZE, truncate it. Returns: Next range of interest in a Range namedtuple. def _GetNextInterval(se...
_HashBlock feeds data blocks into the hashers of fingers. This function must be called before adjusting fingers for next interval, otherwise the lack of remaining ranges will cause the block not to be hashed for a specific finger. Start and end are used to validate the expected ranges, to catch un...
Finalizing function for the Fingerprint class. This method applies all the different hash functions over the previously specified different ranges of the input file, and computes the resulting hashes. After calling HashIt, the state of the object is reset to its initial state, with no fingers defi...
Causes the entire file to be hashed by the given hash functions. This sets up a 'finger' for fingerprinting, where the entire file is passed through a pre-defined (or user defined) set of hash functions. Args: hashers: An iterable of hash classes (e.g. out of hashlib) which will be in...
Parses PECOFF headers. Reads header magic and some data structures in a file to determine if it is a valid PECOFF header, and figure out the offsets at which relevant data is stored. While this code contains multiple seeks and small reads, that is compensated by the underlying libc buffering mechan...
Extracts signedData blob from PECOFF binary and parses first layer. def _CollectSignedData(self, extent): """Extracts signedData blob from PECOFF binary and parses first layer.""" start, length = extent self.file.seek(start, os.SEEK_SET) buf = self.file.read(length) signed_data = [] # This loo...
If the file is a PE/COFF file, computes authenticode hashes on it. This checks if the input file is a valid PE/COFF image file (e.g. a Windows binary, driver, or DLL) and if yes, sets up a 'finger' for fingerprinting in Authenticode style. If available, the 'SignedData' section of the image file is ret...
Parse the History file. def Parse(self, stat, file_object, knowledge_base): """Parse the History file.""" _, _ = stat, knowledge_base # TODO(user): Convert this to use the far more intelligent plaso parser. ff = Firefox3History(file_object) for timestamp, unused_entry_type, url, title in ff.Parse()...
Iterator returning dict for each entry in history. def Parse(self): """Iterator returning dict for each entry in history.""" for timestamp, url, title in self.Query(self.VISITS_QUERY): if not isinstance(timestamp, (long, int)): timestamp = 0 yield [timestamp, "FIREFOX3_VISIT", url, title]
Read a tag from the buffer, and return a (tag_bytes, new_pos) tuple. def ReadTag(buf, pos): """Read a tag from the buffer, and return a (tag_bytes, new_pos) tuple.""" try: start = pos while ORD_MAP_AND_0X80[buf[pos]]: pos += 1 pos += 1 return (buf[start:pos], pos) except IndexError: rai...
Convert an integer to a varint and write it using the write function. def VarintEncode(value): """Convert an integer to a varint and write it using the write function.""" result = b"" if value < 0: raise ValueError("Varint can not encode a negative number.") bits = value & 0x7f value >>= 7 while valu...
Encode a signed integer as a zigzag encoded signed integer. def SignedVarintEncode(value): """Encode a signed integer as a zigzag encoded signed integer.""" result = b"" if value < 0: value += (1 << 64) bits = value & 0x7f value >>= 7 while value: result += HIGH_CHR_MAP[bits] bits = value & 0x...
A 64 bit decoder from google.protobuf.internal.decoder. def VarintReader(buf, pos=0): """A 64 bit decoder from google.protobuf.internal.decoder.""" result = 0 shift = 0 while 1: b = buf[pos] result |= (ORD_MAP_AND_0X7F[b] << shift) pos += 1 if not ORD_MAP_AND_0X80[b]: return (result, pos...
Parses the buffer as a prototypes. Args: buff: The buffer to parse. index: The position to start parsing. length: Optional length to parse until. Yields: Splits the buffer into tuples of strings: (encoded_tag, encoded_length, wire_format). def SplitBuffer(buff, index=0, length=None): ""...
Gets entries of `RDFProtoStruct` in a well-defined order. Args: data: A raw data dictionary of `RDFProtoStruct`. Yields: Entries of the structured in a well-defined order. def _GetOrderedEntries(data): """Gets entries of `RDFProtoStruct` in a well-defined order. Args: data: A raw data dictionary...
Serializes given triplets of python and wire values and a descriptor. def _SerializeEntries(entries): """Serializes given triplets of python and wire values and a descriptor.""" output = [] for python_format, wire_format, type_descriptor in entries: if wire_format is None or (python_format and ...
Reads all tags until the next end group and store in the value_obj. def ReadIntoObject(buff, index, value_obj, length=0): """Reads all tags until the next end group and store in the value_obj.""" raw_data = value_obj.GetRawData() count = 0 # Split the buffer into tags and wire_format representations, then col...
Validates a python format representation of the value. def Validate(self, value, **_): """Validates a python format representation of the value.""" if isinstance(value, rdfvalue.RDFString): # TODO(hanuszczak): Use `str` here. return Text(value) if isinstance(value, Text): return value ...
Internally strings are utf8 encoded. def ConvertToWireFormat(self, value): """Internally strings are utf8 encoded.""" value = value.encode("utf8") return (self.encoded_tag, VarintEncode(len(value)), value)
Check that value is a valid enum. def Validate(self, value, **_): """Check that value is a valid enum.""" # None is a valid value - it means the field is not set. if value is None: return # If the value is a string we need to try to convert it to an integer. checked_value = value if isin...
Return a string with the definition of this field. def Definition(self): """Return a string with the definition of this field.""" result = self._FormatDescriptionComment() result += " enum %s {\n" % self.enum_name for k, v in sorted(iteritems(self.reverse_enum)): result += " %s = %s;\n" % (v...
Return boolean value. def GetDefault(self, container=None): """Return boolean value.""" return rdfvalue.RDFBool( super(ProtoBoolean, self).GetDefault(container=container))
Check that value is a valid enum. def Validate(self, value, **_): """Check that value is a valid enum.""" if value is None: return return rdfvalue.RDFBool(super(ProtoBoolean, self).Validate(value))
The wire format is simply a string. def ConvertFromWireFormat(self, value, container=None): """The wire format is simply a string.""" result = self.type() ReadIntoObject(value[2], 0, result) return result
Encode the nested protobuf into wire format. def ConvertToWireFormat(self, value): """Encode the nested protobuf into wire format.""" output = _SerializeEntries(_GetOrderedEntries(value.GetRawData())) return (self.encoded_tag, VarintEncode(len(output)), output)
Late binding callback. This method is called on this field descriptor when the target RDFValue class is finally defined. It gives the field descriptor an opportunity to initialize after the point of definition. Args: target: The target nested class. Raises: TypeError: If the target cl...
Return and clear the dirty state of the python object. def IsDirty(self, proto): """Return and clear the dirty state of the python object.""" if proto.dirty: return True for python_format, _, type_descriptor in itervalues(proto.GetRawData()): if python_format is not None and type_descriptor.Is...
Encode the nested protobuf into wire format. def ConvertToWireFormat(self, value): """Encode the nested protobuf into wire format.""" data = value.SerializeToString() return (self.encoded_tag, VarintEncode(len(data)), data)
The wire format is an AnyValue message. def ConvertFromWireFormat(self, value, container=None): """The wire format is an AnyValue message.""" result = AnyValue() ReadIntoObject(value[2], 0, result) if self._type is not None: converted_value = self._type(container) else: converted_value ...
Encode the nested protobuf into wire format. def ConvertToWireFormat(self, value): """Encode the nested protobuf into wire format.""" # Is it a protobuf-based value? if hasattr(value.__class__, "protobuf"): if value.__class__.protobuf: type_name = ("type.googleapis.com/%s" % ...
Check that value is a list of the required type. def Validate(self, value, **_): """Check that value is a list of the required type.""" # Assigning from same kind can allow us to skip verification since all # elements in a RepeatedFieldHelper already are coerced to the delegate # type. In that case we ...
Convert to the wire format. Args: value: is of type RepeatedFieldHelper. Returns: A wire format representation of the value. def ConvertToWireFormat(self, value): """Convert to the wire format. Args: value: is of type RepeatedFieldHelper. Returns: A wire format represent...
This method will be called by our delegate during late binding. def AddDescriptor(self, field_desc): """This method will be called by our delegate during late binding.""" # Just relay it up to our owner. self.late_bound = False self.delegate = field_desc self.wire_type = self.delegate.wire_type ...
Bind the field descriptor to the owner once the target is defined. def LateBind(self, target=None): """Bind the field descriptor to the owner once the target is defined.""" self.type = target self._GetPrimitiveEncoder() # Now re-add the descriptor to the owner protobuf. self.late_bound = False ...
Finds the primitive encoder according to the type's data_store_type. def _GetPrimitiveEncoder(self): """Finds the primitive encoder according to the type's data_store_type.""" # Decide what should the primitive type be for packing the target rdfvalue # into the protobuf and create a delegate descriptor to ...
Returns descriptor copy, optionally changing field number. def Copy(self, field_number=None): """Returns descriptor copy, optionally changing field number.""" new_args = self._kwargs.copy() if field_number is not None: new_args["field_number"] = field_number return ProtoRDFValue( rdf_typ...
Return an old style protocol buffer object. def AsPrimitiveProto(self): """Return an old style protocol buffer object.""" if self.protobuf: result = self.protobuf() result.ParseFromString(self.SerializeToString()) return result
Initializes itself from a given dictionary. def FromDict(self, dictionary): """Initializes itself from a given dictionary.""" dynamic_fields = [] for key, value in iteritems(dictionary): field_type_info = self.type_infos.get(key) if isinstance(field_type_info, ProtoEmbedded): nested_va...
Emits .proto file definitions. def EmitProto(cls): """Emits .proto file definitions.""" result = "message %s {\n" % cls.__name__ for _, desc in sorted(iteritems(cls.type_infos_by_field_number)): result += desc.Definition() result += "}\n" return result
Parse this object from a text representation. def FromTextFormat(cls, text): """Parse this object from a text representation.""" tmp = cls.protobuf() # pylint: disable=not-callable text_format.Merge(text, tmp) return cls.FromSerializedString(tmp.SerializeToString())
Register this descriptor with the Proto Struct. def AddDescriptor(cls, field_desc): """Register this descriptor with the Proto Struct.""" if not isinstance(field_desc, ProtoType): raise type_info.TypeValueError( "%s field '%s' should be of type ProtoType" % (cls.__name__, field_desc.n...
Run all registered installers. Run all the current installers and then exit the process. def RunInstaller(): """Run all registered installers. Run all the current installers and then exit the process. """ try: os.makedirs(os.path.dirname(config.CONFIG["Installer.logfile"])) except OSError: pass ...
Maps ItemsIterator via given function. def MapItemsIterator(function, items): """Maps ItemsIterator via given function.""" return ItemsIterator( items=map(function, items), total_count=items.total_count)
Periodically calls generator function until a condition is satisfied. def Poll(generator=None, condition=None, interval=None, timeout=None): """Periodically calls generator function until a condition is satisfied.""" if not generator: raise ValueError("generator has to be a lambda") if not condition: r...
Converts given URN string to a client id string. def UrnStringToClientId(urn): """Converts given URN string to a client id string.""" if urn.startswith(AFF4_PREFIX): urn = urn[len(AFF4_PREFIX):] components = urn.split("/") return components[0]
Converts given URN string to a flow id string. def UrnStringToHuntId(urn): """Converts given URN string to a flow id string.""" if urn.startswith(AFF4_PREFIX): urn = urn[len(AFF4_PREFIX):] components = urn.split("/") if len(components) != 2 or components[0] != "hunts": raise ValueError("Invalid hunt U...
Returns a message instance corresponding to a given type URL. def TypeUrlToMessage(type_url): """Returns a message instance corresponding to a given type URL.""" if not type_url.startswith(TYPE_URL_PREFIX): raise ValueError("Type URL has to start with a prefix %s: %s" % (TYPE_URL_PREFIX, ...
Registers all API-releated descriptors in a given symbol DB. def RegisterProtoDescriptors(db, *additional_descriptors): """Registers all API-releated descriptors in a given symbol DB.""" db.RegisterFileDescriptor(artifact_pb2.DESCRIPTOR) db.RegisterFileDescriptor(client_pb2.DESCRIPTOR) db.RegisterFileDescripto...
Converts python datetime to epoch microseconds. def _DateToEpoch(date): """Converts python datetime to epoch microseconds.""" tz_zero = datetime.datetime.utcfromtimestamp(0) diff_sec = int((date - tz_zero).total_seconds()) return diff_sec * 1000000
Parse the StatEntry objects. def ParseMultiple(self, stat_entries, knowledge_base): """Parse the StatEntry objects.""" _ = knowledge_base for stat_entry in stat_entries: # TODO: `st_mode` has to be an `int`, not `StatMode`. if stat.S_ISDIR(int(stat_entry.st_mode)): homedir = stat_entry...
Parse the system profiler output. We get it in the form of a plist. def Parse(self, cmd, args, stdout, stderr, return_val, time_taken, knowledge_base): """Parse the system profiler output. We get it in the form of a plist.""" _ = stderr, time_taken, args, knowledge_base # Unused self.CheckRetu...
Parse the Plist file. def Parse(self, statentry, file_object, knowledge_base): """Parse the Plist file.""" _ = knowledge_base kwargs = {} try: kwargs["aff4path"] = file_object.urn except AttributeError: pass direct_copy_items = [ "Label", "Disabled", "UserName", "GroupName"...
Parse the Plist file. def Parse(self, statentry, file_object, knowledge_base): """Parse the Plist file.""" plist = biplist.readPlist(file_object) if not isinstance(plist, list): raise parser.ParseError( "InstallHistory plist is a '%s', expecting a list" % type(plist)) packages = [] ...
Add the running contexts to the config system. def SetPlatformArchContext(): """Add the running contexts to the config system.""" # Initialize the running platform context: _CONFIG.AddContext("Platform:%s" % platform.system().title()) machine = platform.uname()[4] if machine in ["x86_64", "AMD64", "i686"]:...
Parses given YAML file. def _ParseYamlFromFile(filedesc): """Parses given YAML file.""" content = filedesc.read() return yaml.Parse(content) or collections.OrderedDict()
A helper for defining choice string options. def DEFINE_choice(name, default, choices, help): """A helper for defining choice string options.""" _CONFIG.DEFINE_choice(name, default, choices, help)
Choose multiple options from a list. def DEFINE_multichoice(name, default, choices, help): """Choose multiple options from a list.""" _CONFIG.DEFINE_multichoice(name, default, choices, help)
Initialize a ConfigManager with the specified options. Args: config_obj: The ConfigManager object to use and update. If None, one will be created. config_file: Filename to read the config from. config_fd: A file-like object to read config data from. secondary_configs: A list of secondary config...
Parse all the command line options which control the config system. def ParseConfigCommandLine(): """Parse all the command line options which control the config system.""" # The user may specify the primary config file on the command line. if flags.FLAGS.config: _CONFIG.Initialize(filename=flags.FLAGS.config...
Use pkg_resources to find the path to the required resource. def Filter(self, filename_spec): """Use pkg_resources to find the path to the required resource.""" if "@" in filename_spec: file_path, package_name = filename_spec.split("@") else: file_path, package_name = filename_spec, Resource.de...
Merge the raw data with the config file and store it. def SaveDataToFD(self, raw_data, fd): """Merge the raw data with the config file and store it.""" for key, value in iteritems(raw_data): # TODO(hanuszczak): Incorrect type specification for `set`. # pytype: disable=wrong-arg-types self.set...
Store the raw data as our configuration. def SaveData(self, raw_data): """Store the raw data as our configuration.""" if self.filename is None: raise IOError("Unknown filename") logging.info("Writing back configuration to file %s", self.filename) # Ensure intermediate directories exist try: ...
Merge the raw data with the config file and store it. def SaveDataToFD(self, raw_data, fd): """Merge the raw data with the config file and store it.""" fd.write(yaml.Dump(raw_data).encode("utf-8"))
Convert data to common format. Configuration options are normally grouped by the functional component which define it (e.g. Logging.path is the path parameter for the logging subsystem). However, sometimes it is more intuitive to write the config as a flat string (e.g. Logging.path). In this case we gr...
Support standard string escaping. def Escape(self, string="", **_): """Support standard string escaping.""" # Translate special escapes: self.stack[-1] += self.STRING_ESCAPES.get(string, string)
Filter the current expression. def Filter(self, match=None, **_): """Filter the current expression.""" arg = self.stack.pop(-1) # Filters can be specified as a comma separated list. for filter_name in match.group(1).split(","): filter_object = ConfigFilter.classes_by_name.get(filter_name) ...
Expand the args as a section.parameter from the config. def ExpandArg(self, **_): """Expand the args as a section.parameter from the config.""" # This function is called when we see close ) and the stack depth has to # exactly match the number of (. if len(self.stack) <= 1: raise lexer.ParseError...
Creates a new configuration option based on this one. Note that it is not normally possible to just instantiate the config object because it will have an empty set of type descriptors (i.e. no config options will be defined). Config options are normally defined at import time, and then they get add...
Make a complete new copy of the current config. This includes all options as they currently are. If you want a base config with defaults use MakeNewConfig. Returns: A new config object with the same data as self. def CopyConfig(self): """Make a complete new copy of the current config. This...
Sets the config file which will receive any modifications. The main config file can be made writable, but directing all Set() operations into a secondary location. This secondary location will receive any updates and will override the options for this file. Args: filename: A filename which will ...
Validate sections or individual parameters. The GRR configuration file contains several sections, used by different components. Many of these components don't care about other sections. This method allows a component to declare in advance what sections and parameters it cares about, and have these vali...
Adds a context string to the global configuration. The context conveys information about the caller of the config system and allows the configuration to have specialized results for different callers. Note that the configuration file may specify conflicting options for different contexts. In this case...
Set the raw string without verification or escaping. def SetRaw(self, name, value): """Set the raw string without verification or escaping.""" if self.writeback is None: logging.warning("Attempting to modify a read only config object.") if name in self.constants: raise ConstModificationError( ...
Update the configuration option with a new value. Note that this forces the value to be set for all contexts. The value is written to the writeback location if Save() is later called. Args: name: The name of the parameter to set. value: The value to set it to. The value will be validated again...
Write out the updated configuration to the fd. def Write(self): """Write out the updated configuration to the fd.""" if self.writeback: self.writeback.SaveData(self.writeback_data) else: raise RuntimeError("Attempting to write a configuration without a " "writeback loca...
Write out the updated configuration to the fd. def WriteToFD(self, fd): """Write out the updated configuration to the fd.""" if self.writeback: self.writeback.SaveDataToFD(self.writeback_data, fd) else: raise RuntimeError("Attempting to write a configuration without a " ...
Stores <config_option> in the writeback. def Persist(self, config_option): """Stores <config_option> in the writeback.""" if not self.writeback: raise RuntimeError("Attempting to write a configuration without a " "writeback location.") writeback_raw_value = dict(self.writeba...
Registers an option with the configuration system. Args: descriptor: A TypeInfoObject instance describing the option. constant: If this is set, the option is treated as a constant - it can be read at any time (before parsing the configuration) and it's an error to try to override it in ...
Merges data read from a config file into the current config. def MergeData(self, merge_data, raw_data=None): """Merges data read from a config file into the current config.""" self.FlushCache() if raw_data is None: raw_data = self.raw_data for k, v in iteritems(merge_data): # A context cla...
Returns the appropriate parser class from the filename. def GetParserFromFilename(self, path): """Returns the appropriate parser class from the filename.""" # Find the configuration parser. handler_name = path.split("://")[0] for parser_cls in itervalues(GRRConfigParser.classes): if parser_cls.na...
Loads an additional configuration file. The configuration system has the concept of a single Primary configuration file, and multiple secondary files. The primary configuration file is the main file that is used by the program. Any writebacks will only be made to the primary configuration file. Seconda...
Initializes the config manager. This method is used to add more config options to the manager. The config can be given as one of the parameters as described in the Args section. Args: filename: The name of the configuration file to use. data: The configuration given directly as a long string o...
Get the raw value without interpolations. def GetRaw(self, name, context=None, default=utils.NotAValue): """Get the raw value without interpolations.""" if context is None: context = self.context # Getting a raw value is pretty cheap so we wont bother with the cache here. _, value = self._GetVal...
Get the value contained by the named parameter. This method applies interpolation/escaping of the named parameter and retrieves the interpolated value. Args: name: The name of the parameter to retrieve. This should be in the format of "Section.name" default: If retrieving the value re...
Returns the config options active under this context. def _ResolveContext(self, context, name, raw_data, path=None): """Returns the config options active under this context.""" if path is None: path = [] for element in context: if element not in self.valid_contexts: raise InvalidContex...
Search for the value based on the context. def _GetValue(self, name, context, default=utils.NotAValue): """Search for the value based on the context.""" container = self.defaults # The caller provided a default value. if default is not utils.NotAValue: value = default # Take the default fro...
Search for a type_info instance which describes this key. def FindTypeInfo(self, name): """Search for a type_info instance which describes this key.""" result = self.type_infos.get(name) if result is None: # Not found, assume string. result = type_info.String(name=name, default="") return ...
Interpolate the value and parse it with the appropriate type. def InterpolateValue(self, value, type_info_obj=type_info.String(), default_section=None, context=None): """Interpolate the value and parse it with the appropria...
Return true if target_platforms matches the supplied parameters. Used by buildanddeploy to determine what clients need to be built. Args: target_os: which os we are building for in this run (linux, windows, darwin) target_arch: which arch we are building for in this run (i386, amd64) ...