sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def pub(self, topic=b'', embed_topic=False): """ Returns a callable that can be used to transmit a message, with a given ``topic``, in a publisher-subscriber fashion. Note that the sender function has a ``print`` like signature, with an infinite number of arguments. Each one being a part of the complete message. By default, no topic will be included into published messages. Being up to developers to include the topic, at the beginning of the first part (i.e. frame) of every published message, so that subscribers are able to receive them. For a different behaviour, check the embed_topic argument. :param topic: the topic that will be published to (default=b'') :type topic: bytes :param embed_topic: set for the topic to be automatically sent as the first part (i.e. frame) of every published message (default=False) :type embed_topic bool :rtype: function """ if not isinstance(topic, bytes): error = 'Topic must be bytes' log.error(error) raise TypeError(error) sock = self.__sock(zmq.PUB) return self.__send_function(sock, topic, embed_topic)
Returns a callable that can be used to transmit a message, with a given ``topic``, in a publisher-subscriber fashion. Note that the sender function has a ``print`` like signature, with an infinite number of arguments. Each one being a part of the complete message. By default, no topic will be included into published messages. Being up to developers to include the topic, at the beginning of the first part (i.e. frame) of every published message, so that subscribers are able to receive them. For a different behaviour, check the embed_topic argument. :param topic: the topic that will be published to (default=b'') :type topic: bytes :param embed_topic: set for the topic to be automatically sent as the first part (i.e. frame) of every published message (default=False) :type embed_topic bool :rtype: function
entailment
def sub(self, topics=(b'',)): """ Returns an iterable that can be used to iterate over incoming messages, that were published with one of the topics specified in ``topics``. Note that the iterable returns as many parts as sent by subscribed publishers. :param topics: a list of topics to subscribe to (default=b'') :type topics: list of bytes :rtype: generator """ sock = self.__sock(zmq.SUB) for topic in topics: if not isinstance(topic, bytes): error = 'Topics must be a list of bytes' log.error(error) raise TypeError(error) sock.setsockopt(zmq.SUBSCRIBE, topic) return self.__recv_generator(sock)
Returns an iterable that can be used to iterate over incoming messages, that were published with one of the topics specified in ``topics``. Note that the iterable returns as many parts as sent by subscribed publishers. :param topics: a list of topics to subscribe to (default=b'') :type topics: list of bytes :rtype: generator
entailment
def push(self): """ Returns a callable that can be used to transmit a message in a push-pull fashion. Note that the sender function has a ``print`` like signature, with an infinite number of arguments. Each one being a part of the complete message. :rtype: function """ sock = self.__sock(zmq.PUSH) return self.__send_function(sock)
Returns a callable that can be used to transmit a message in a push-pull fashion. Note that the sender function has a ``print`` like signature, with an infinite number of arguments. Each one being a part of the complete message. :rtype: function
entailment
def pull(self): """ Returns an iterable that can be used to iterate over incoming messages, that were pushed by a push socket. Note that the iterable returns as many parts as sent by pushers. :rtype: generator """ sock = self.__sock(zmq.PULL) return self.__recv_generator(sock)
Returns an iterable that can be used to iterate over incoming messages, that were pushed by a push socket. Note that the iterable returns as many parts as sent by pushers. :rtype: generator
entailment
def request(self): """ Returns a callable and an iterable respectively. Those can be used to both transmit a message and/or iterate over incoming messages, that were replied by a reply socket. Note that the iterable returns as many parts as sent by repliers. Also, the sender function has a ``print`` like signature, with an infinite number of arguments. Each one being a part of the complete message. :rtype: (function, generator) """ sock = self.__sock(zmq.REQ) return self.__send_function(sock), self.__recv_generator(sock)
Returns a callable and an iterable respectively. Those can be used to both transmit a message and/or iterate over incoming messages, that were replied by a reply socket. Note that the iterable returns as many parts as sent by repliers. Also, the sender function has a ``print`` like signature, with an infinite number of arguments. Each one being a part of the complete message. :rtype: (function, generator)
entailment
def reply(self): """ Returns a callable and an iterable respectively. Those can be used to both transmit a message and/or iterate over incoming messages, that were requested by a request socket. Note that the iterable returns as many parts as sent by requesters. Also, the sender function has a ``print`` like signature, with an infinite number of arguments. Each one being a part of the complete message. :rtype: (function, generator) """ sock = self.__sock(zmq.REP) return self.__send_function(sock), self.__recv_generator(sock)
Returns a callable and an iterable respectively. Those can be used to both transmit a message and/or iterate over incoming messages, that were requested by a request socket. Note that the iterable returns as many parts as sent by requesters. Also, the sender function has a ``print`` like signature, with an infinite number of arguments. Each one being a part of the complete message. :rtype: (function, generator)
entailment
def pair(self): """ Returns a callable and an iterable respectively. Those can be used to both transmit a message and/or iterate over incoming messages, that were sent by a pair socket. Note that the iterable returns as many parts as sent by a pair. Also, the sender function has a ``print`` like signature, with an infinite number of arguments. Each one being a part of the complete message. :rtype: (function, generator) """ sock = self.__sock(zmq.PAIR) return self.__send_function(sock), self.__recv_generator(sock)
Returns a callable and an iterable respectively. Those can be used to both transmit a message and/or iterate over incoming messages, that were sent by a pair socket. Note that the iterable returns as many parts as sent by a pair. Also, the sender function has a ``print`` like signature, with an infinite number of arguments. Each one being a part of the complete message. :rtype: (function, generator)
entailment
def connect(self, ip, port): """ Connects to a server at the specified ip and port. :param ip: an IP address :type ip: str or unicode :param port: port number from 1024 up to 65535 :type port: int :rtype: self """ _check_valid_port_range(port) address = (ip, port) if address in self._addresses: error = 'Already connected to {0} on port {1}'.format(ip, port) log.exception(error) raise ValueError(error) self._addresses.append(address) if self._is_ready: _check_valid_num_connections(self._sock.socket_type, len(self._addresses)) _connect_zmq_sock(self._sock, ip, port) return self
Connects to a server at the specified ip and port. :param ip: an IP address :type ip: str or unicode :param port: port number from 1024 up to 65535 :type port: int :rtype: self
entailment
def disconnect(self, ip, port): """ Disconnects from a server at the specified ip and port. :param ip: an IP address :type ip: str or unicode :param port: port number from 1024 up to 65535 :type port: int :rtype: self """ _check_valid_port_range(port) address = (ip, port) try: self._addresses.remove(address) except ValueError: error = 'There was no connection to {0} on port {1}'.format(ip, port) log.exception(error) raise ValueError(error) if self._is_ready: _disconnect_zmq_sock(self._sock, ip, port) return self
Disconnects from a server at the specified ip and port. :param ip: an IP address :type ip: str or unicode :param port: port number from 1024 up to 65535 :type port: int :rtype: self
entailment
def disconnect_all(self): """ Disconnects from all connected servers. :rtype: self """ addresses = deepcopy(self._addresses) for ip, port in addresses: self.disconnect(ip, port) return self
Disconnects from all connected servers. :rtype: self
entailment
def remove_exponent(d): """Remove exponent.""" return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
Remove exponent.
entailment
def millify(n, precision=0, drop_nulls=True, prefixes=[]): """Humanize number.""" millnames = ['', 'k', 'M', 'B', 'T', 'P', 'E', 'Z', 'Y'] if prefixes: millnames = [''] millnames.extend(prefixes) n = float(n) millidx = max(0, min(len(millnames) - 1, int(math.floor(0 if n == 0 else math.log10(abs(n)) / 3)))) result = '{:.{precision}f}'.format(n / 10**(3 * millidx), precision=precision) if drop_nulls: result = remove_exponent(Decimal(result)) return '{0}{dx}'.format(result, dx=millnames[millidx])
Humanize number.
entailment
def prettify(amount, separator=','): """Separate with predefined separator.""" orig = str(amount) new = re.sub("^(-?\d+)(\d{3})", "\g<1>{0}\g<2>".format(separator), str(amount)) if orig == new: return new else: return prettify(new)
Separate with predefined separator.
entailment
def load_json(json_data, decoder=None): """ Load data from json string :param json_data: Stringified json object :type json_data: str | unicode :param decoder: Use custom json decoder :type decoder: T <= DateTimeDecoder :return: Json data :rtype: None | int | float | str | list | dict """ if decoder is None: decoder = DateTimeDecoder return json.loads(json_data, object_hook=decoder.decode)
Load data from json string :param json_data: Stringified json object :type json_data: str | unicode :param decoder: Use custom json decoder :type decoder: T <= DateTimeDecoder :return: Json data :rtype: None | int | float | str | list | dict
entailment
def load_json_file(file, decoder=None): """ Load data from json file :param file: Readable object or path to file :type file: FileIO | str :param decoder: Use custom json decoder :type decoder: T <= DateTimeDecoder :return: Json data :rtype: None | int | float | str | list | dict """ if decoder is None: decoder = DateTimeDecoder if not hasattr(file, "read"): with io.open(file, "r", encoding="utf-8") as f: return json.load(f, object_hook=decoder.decode) return json.load(file, object_hook=decoder.decode)
Load data from json file :param file: Readable object or path to file :type file: FileIO | str :param decoder: Use custom json decoder :type decoder: T <= DateTimeDecoder :return: Json data :rtype: None | int | float | str | list | dict
entailment
def save_json(val, pretty=False, sort=True, encoder=None): """ Save data to json string :param val: Value or struct to save :type val: None | int | float | str | list | dict :param pretty: Format data to be readable (default: False) otherwise going to be compact :type pretty: bool :param sort: Sort keys (default: True) :type sort: bool :param encoder: Use custom json encoder :type encoder: T <= DateTimeEncoder :return: The jsonified string :rtype: str | unicode """ if encoder is None: encoder = DateTimeEncoder if pretty: data = json.dumps( val, indent=4, separators=(',', ': '), sort_keys=sort, cls=encoder ) else: data = json.dumps( val, separators=(',', ':'), sort_keys=sort, cls=encoder ) if not sys.version_info > (3, 0) and isinstance(data, str): data = data.decode("utf-8") return data
Save data to json string :param val: Value or struct to save :type val: None | int | float | str | list | dict :param pretty: Format data to be readable (default: False) otherwise going to be compact :type pretty: bool :param sort: Sort keys (default: True) :type sort: bool :param encoder: Use custom json encoder :type encoder: T <= DateTimeEncoder :return: The jsonified string :rtype: str | unicode
entailment
def save_json_file( file, val, pretty=False, compact=True, sort=True, encoder=None ): """ Save data to json file :param file: Writable object or path to file :type file: FileIO | str | unicode :param val: Value or struct to save :type val: None | int | float | str | list | dict :param pretty: Format data to be readable (default: False) :type pretty: bool :param compact: Format data to be compact (default: True) :type compact: bool :param sort: Sort keys (default: True) :type sort: bool :param encoder: Use custom json encoder :type encoder: T <= DateTimeEncoder :rtype: None """ # TODO: make pretty/compact into one bool? if encoder is None: encoder = DateTimeEncoder opened = False if not hasattr(file, "write"): file = io.open(file, "w", encoding="utf-8") opened = True try: if pretty: data = json.dumps( val, indent=4, separators=(',', ': '), sort_keys=sort, cls=encoder ) elif compact: data = json.dumps( val, separators=(',', ':'), sort_keys=sort, cls=encoder ) else: data = json.dumps(val, sort_keys=sort, cls=encoder) if not sys.version_info > (3, 0) and isinstance(data, str): data = data.decode("utf-8") file.write(data) finally: if opened: file.close()
Save data to json file :param file: Writable object or path to file :type file: FileIO | str | unicode :param val: Value or struct to save :type val: None | int | float | str | list | dict :param pretty: Format data to be readable (default: False) :type pretty: bool :param compact: Format data to be compact (default: True) :type compact: bool :param sort: Sort keys (default: True) :type sort: bool :param encoder: Use custom json encoder :type encoder: T <= DateTimeEncoder :rtype: None
entailment
def load_yaml_file(file): """ Load data from yaml file :param file: Readable object or path to file :type file: FileIO | str | unicode :return: Yaml data :rtype: None | int | float | str | unicode | list | dict """ if not hasattr(file, "read"): with io.open(file, "r", encoding="utf-8") as f: return yaml.load(f, yaml.FullLoader) return yaml.load(file, yaml.FullLoader)
Load data from yaml file :param file: Readable object or path to file :type file: FileIO | str | unicode :return: Yaml data :rtype: None | int | float | str | unicode | list | dict
entailment
def save_yaml_file(file, val): """ Save data to yaml file :param file: Writable object or path to file :type file: FileIO | str | unicode :param val: Value or struct to save :type val: None | int | float | str | unicode | list | dict """ opened = False if not hasattr(file, "write"): file = io.open(file, "w", encoding="utf-8") opened = True try: yaml.dump(val, file) finally: if opened: file.close()
Save data to yaml file :param file: Writable object or path to file :type file: FileIO | str | unicode :param val: Value or struct to save :type val: None | int | float | str | unicode | list | dict
entailment
def load_file(path): """ Load file :param path: Path to file :type path: str | unicode :return: Loaded data :rtype: None | int | float | str | unicode | list | dict :raises IOError: If file not found or error accessing file """ res = {} if not path: IOError("No path specified to save") if not os.path.isfile(path): raise IOError("File not found {}".format(path)) try: with io.open(path, "r", encoding="utf-8") as f: if path.endswith(".json"): res = load_json_file(f) elif path.endswith(".yaml") or path.endswith(".yml"): res = load_yaml_file(f) except IOError: raise except Exception as e: raise IOError(e) return res
Load file :param path: Path to file :type path: str | unicode :return: Loaded data :rtype: None | int | float | str | unicode | list | dict :raises IOError: If file not found or error accessing file
entailment
def save_file(path, data, readable=False): """ Save to file :param path: File path to save :type path: str | unicode :param data: Data to save :type data: None | int | float | str | unicode | list | dict :param readable: Format file to be human readable (default: False) :type readable: bool :rtype: None :raises IOError: If empty path or error writing file """ if not path: IOError("No path specified to save") try: with io.open(path, "w", encoding="utf-8") as f: if path.endswith(".json"): save_json_file( f, data, pretty=readable, compact=(not readable), sort=True ) elif path.endswith(".yaml") or path.endswith(".yml"): save_yaml_file(f, data) except IOError: raise except Exception as e: raise IOError(e)
Save to file :param path: File path to save :type path: str | unicode :param data: Data to save :type data: None | int | float | str | unicode | list | dict :param readable: Format file to be human readable (default: False) :type readable: bool :rtype: None :raises IOError: If empty path or error writing file
entailment
def join_path_prefix(path, pre_path=None): """ If path set and not absolute, append it to pre path (if used) :param path: path to append :type path: str | None :param pre_path: Base path to append to (default: None) :type pre_path: None | str :return: Path or appended path :rtype: str | None """ if not path: return path if pre_path and not os.path.isabs(path): return os.path.join(pre_path, path) return path
If path set and not absolute, append it to pre path (if used) :param path: path to append :type path: str | None :param pre_path: Base path to append to (default: None) :type pre_path: None | str :return: Path or appended path :rtype: str | None
entailment
def _load_json_file(self, file, decoder=None): """ Load data from json file :param file: Readable file or path to file :type file: FileIO | str | unicode :param decoder: Use custom json decoder :type decoder: T <= flotils.loadable.DateTimeDecoder :return: Json data :rtype: None | int | float | str | list | dict :raises IOError: Failed to load """ try: res = load_json_file(file, decoder=decoder) except ValueError as e: if "{}".format(e) == "No JSON object could be decoded": raise IOError("Decoding JSON failed") self.exception("Failed to load from {}".format(file)) raise IOError("Loading file failed") except: self.exception("Failed to load from {}".format(file)) raise IOError("Loading file failed") return res
Load data from json file :param file: Readable file or path to file :type file: FileIO | str | unicode :param decoder: Use custom json decoder :type decoder: T <= flotils.loadable.DateTimeDecoder :return: Json data :rtype: None | int | float | str | list | dict :raises IOError: Failed to load
entailment
def _save_json_file( self, file, val, pretty=False, compact=True, sort=True, encoder=None ): """ Save data to json file :param file: Writable file or path to file :type file: FileIO | str | unicode :param val: Value or struct to save :type val: None | int | float | str | list | dict :param pretty: Format data to be readable (default: False) :type pretty: bool :param compact: Format data to be compact (default: True) :type compact: bool :param sort: Sort keys (default: True) :type sort: bool :param encoder: Use custom json encoder :type encoder: T <= flotils.loadable.DateTimeEncoder :rtype: None :raises IOError: Failed to save """ try: save_json_file(file, val, pretty, compact, sort, encoder) except: self.exception("Failed to save to {}".format(file)) raise IOError("Saving file failed")
Save data to json file :param file: Writable file or path to file :type file: FileIO | str | unicode :param val: Value or struct to save :type val: None | int | float | str | list | dict :param pretty: Format data to be readable (default: False) :type pretty: bool :param compact: Format data to be compact (default: True) :type compact: bool :param sort: Sort keys (default: True) :type sort: bool :param encoder: Use custom json encoder :type encoder: T <= flotils.loadable.DateTimeEncoder :rtype: None :raises IOError: Failed to save
entailment
def _load_yaml_file(self, file): """ Load data from yaml file :param file: Readable object or path to file :type file: FileIO | str | unicode :return: Yaml data :rtype: None | int | float | str | unicode | list | dict :raises IOError: Failed to load """ try: res = load_yaml_file(file) except: self.exception("Failed to load from {}".format(file)) raise IOError("Loading file failed") return res
Load data from yaml file :param file: Readable object or path to file :type file: FileIO | str | unicode :return: Yaml data :rtype: None | int | float | str | unicode | list | dict :raises IOError: Failed to load
entailment
def _save_yaml_file(self, file, val): """ Save data to yaml file :param file: Writable object or path to file :type file: FileIO | str | unicode :param val: Value or struct to save :type val: None | int | float | str | unicode | list | dict :raises IOError: Failed to save """ try: save_yaml_file(file, val) except: self.exception("Failed to save to {}".format(file)) raise IOError("Saving file failed")
Save data to yaml file :param file: Writable object or path to file :type file: FileIO | str | unicode :param val: Value or struct to save :type val: None | int | float | str | unicode | list | dict :raises IOError: Failed to save
entailment
def load_settings(self, path): """ Load settings dict :param path: Path to settings file :type path: str | unicode :return: Loaded settings :rtype: dict :raises IOError: If file not found or error accessing file :raises TypeError: Settings file does not contain dict """ res = self.load_file(path) if not isinstance(res, dict): raise TypeError("Expected settings to be dict") return res
Load settings dict :param path: Path to settings file :type path: str | unicode :return: Loaded settings :rtype: dict :raises IOError: If file not found or error accessing file :raises TypeError: Settings file does not contain dict
entailment
def save_settings(self, path, settings, readable=False): """ Save settings to file :param path: File path to save :type path: str | unicode :param settings: Settings to save :type settings: dict :param readable: Format file to be human readable (default: False) :type readable: bool :rtype: None :raises IOError: If empty path or error writing file :raises TypeError: Settings is not a dict """ if not isinstance(settings, dict): raise TypeError("Expected settings to be dict") return self.save_file(path, settings, readable)
Save settings to file :param path: File path to save :type path: str | unicode :param settings: Settings to save :type settings: dict :param readable: Format file to be human readable (default: False) :type readable: bool :rtype: None :raises IOError: If empty path or error writing file :raises TypeError: Settings is not a dict
entailment
def load_file(self, path): """ Load file :param path: Path to file :type path: str | unicode :return: Loaded settings :rtype: None | str | unicode | int | list | dict :raises IOError: If file not found or error accessing file """ res = None if not path: IOError("No path specified to save") if not os.path.isfile(path): raise IOError("File not found {}".format(path)) try: with io.open(path, "r", encoding="utf-8") as f: if path.endswith(".json"): res = self._load_json_file(f) elif path.endswith(".yaml") or path.endswith(".yml"): res = self._load_yaml_file(f) except IOError: raise except Exception as e: self.exception("Failed reading {}".format(path)) raise IOError(e) return res
Load file :param path: Path to file :type path: str | unicode :return: Loaded settings :rtype: None | str | unicode | int | list | dict :raises IOError: If file not found or error accessing file
entailment
def save_file(self, path, data, readable=False): """ Save to file :param path: File path to save :type path: str | unicode :param data: To save :type data: None | str | unicode | int | list | dict :param readable: Format file to be human readable (default: False) :type readable: bool :rtype: None :raises IOError: If empty path or error writing file """ if not path: IOError("No path specified to save") try: with io.open(path, "w", encoding="utf-8") as f: if path.endswith(".json"): self._save_json_file( f, data, pretty=readable, compact=(not readable), sort=True ) elif path.endswith(".yaml") or path.endswith(".yml"): self._save_yaml_file(f, data) except IOError: raise except Exception as e: self.exception("Failed writing {}".format(path)) raise IOError(e)
Save to file :param path: File path to save :type path: str | unicode :param data: To save :type data: None | str | unicode | int | list | dict :param readable: Format file to be human readable (default: False) :type readable: bool :rtype: None :raises IOError: If empty path or error writing file
entailment
def name(self): """ Get the module name :return: Module name :rtype: str | unicode """ res = type(self).__name__ if self._id: res += ".{}".format(self._id) return res
Get the module name :return: Module name :rtype: str | unicode
entailment
def _get_function_name(self): """ Get function name of calling method :return: The name of the calling function (expected to be called in self.error/debug/..) :rtype: str | unicode """ fname = inspect.getframeinfo(inspect.stack()[2][0]).function if fname == "<module>": return "" else: return fname
Get function name of calling method :return: The name of the calling function (expected to be called in self.error/debug/..) :rtype: str | unicode
entailment
def start(self, blocking=False): """ Start the interface :param blocking: Should the call block until stop() is called (default: False) :type blocking: bool :rtype: None """ super(StartStopable, self).start() self._is_running = True # blocking try: while blocking and self._is_running: time.sleep(self._start_block_timeout) except IOError as e: if not str(e).lower().startswith("[errno 4]"): raise
Start the interface :param blocking: Should the call block until stop() is called (default: False) :type blocking: bool :rtype: None
entailment
def get_embedded_yara(self, iocid): """ Extract YARA signatures embedded in Yara/Yara indicatorItem nodes. This is done regardless of logic structure in the OpenIOC. """ ioc_obj = self.iocs[iocid] ids_to_process = set([]) signatures = '' for elem in ioc_obj.top_level_indicator.xpath('.//IndicatorItem[Context/@search = "Yara/Yara"]'): signature = elem.findtext('Content') signatures = signatures + '\n' + signature if signatures: signatures += '\n' return signatures
Extract YARA signatures embedded in Yara/Yara indicatorItem nodes. This is done regardless of logic structure in the OpenIOC.
entailment
def get_yara_condition_string(self, indicator_node, parameters_node, ids_to_process, condition_string='', joining_value='or'): """ get_yara_condition_string input indicator_node: this is the node we walk down parameters_node: this contains all the parameters in the ioc, so we can look up parameters nodes as we walk them. ids_to_process: set of ids to upgrade condition_string: This represnts the yara condition string. This string grows as we walk nodes. return returns True upon completion may raise ValueError """ indicator_node_id = str(indicator_node.get('id')) if indicator_node_id not in ids_to_process: msg = 'Entered into get_yara_condition_string with a invalid node to walk [[}]'.format(indicator_node_id) raise YaraConversionError(msg) expected_tag = 'Indicator' if indicator_node.tag != expected_tag: raise YaraConversionError('indicator_node expected tag is [%s]' % expected_tag) is_set = None # print 'indicator node id [%s]' % str(indicator_node_id) for param in parameters_node.xpath('.//param[@ref-id="{}"]'.format(indicator_node_id)): if param.attrib['name'] == 'yara/set': is_set = True set_count = param.findtext('value', None) try: temp = int(set_count) if temp < 1: raise YaraConversionError('yara/set parameter value was less than 1') if temp > len(indicator_node.getchildren()): msg = 'yara/set value is greater than the number of children' \ ' of Indicator node [%s]' % str(indicator_node_id) raise YaraConversionError(msg) except ValueError: raise YaraConversionError('yara/set parameter was not a integer') set_dict = {'set_count': set_count, 'set_ids': []} for node in indicator_node.getchildren(): node_id = node.get('id') # XXX strip out '-' characters from the ids. If a guid is used as # the id, this will cause processing errors safe_node_id = node_id.replace('-', '') if node_id not in ids_to_process: continue if node.tag == 'IndicatorItem': # print 'handling indicatoritem: [%s]' % node_id if is_set: set_dict['set_ids'].append('$' + safe_node_id) else: # Default mapping mapping = {'prefix': '$', 'identifier': safe_node_id, 'condition': '', 'postfix': ''} # XXX: Alot of this could raise ValueError use_condition_template = False negation = node.get('negate') condition = node.get('condition') search = node.xpath('Context/@search')[0] content = node.findtext('Content') yara_condition = self.condition_to_yara_map[condition] if not yara_condition: msg = 'Invalid IndicatorItem condition encountered [%s][%s]' % (str(node_id), str(condition)) raise YaraConversionError(msg) if negation.lower() == 'true': negation = True else: negation = False # parameters cannot modifier the condition of FileSize or Rule if search == 'Yara/FileSize': mapping['prefix'] = '' mapping['identifier'] = 'filesize' mapping['postfix'] = ' ' + content mapping['condition'] = yara_condition use_condition_template = True elif search == 'Yara/RuleName': if content not in self.ioc_names_set: if mangle_name(content) in self.ioc_names_mangled_set: msg = 'Yara/RuleName is present as a mangled name.[{}][{}]'.format(mangle_name(content), node_id) log.warning(msg) content = mangle_name(content) else: log.warning('Yara/RuleName points to a name [{}] that is not in the set of IOCs being' ' processed [{}]'.format(content, node_id)) if mangle_name(content) != content: msg = 'Yara/RuleName contains characters which would cause libyara errors' \ ' [{}]'.format(node_id) raise YaraConversionError(msg) mapping['prefix'] = '' mapping['identifier'] = content # handle parameters else: xp = './/param[@ref-id="{}" and (@name="yara/count" or @name="yara/offset/at" or' \ ' @name="yara/offset/in")]'.format(node_id) params = parameters_node.xpath(xp) if len(params) > 1: msg = 'More than one condition parameters assigned to IndicatorItem [{}]'.format(node_id) raise YaraConversionError(msg) for param in params: param_name = param.get('name', None) if param_name == 'yara/count': log.debug('Found [%s] attached to [%s]' % (param.attrib['name'], node_id)) mapping['prefix'] = '#' mapping['postfix'] = ' ' + param.findtext('value') mapping['condition'] = yara_condition use_condition_template = True break elif param_name == 'yara/offset/at': log.debug('Found [%s] attached to [%s]' % (param.attrib['name'], node_id)) mapping['condition'] = 'at' mapping['postfix'] = ' ' + param.findtext('value') use_condition_template = True break elif param_name == 'yara/offset/in': log.debug('Found [%s] attached to [%s]' % (param.attrib['name'], node_id)) mapping['condition'] = 'in' mapping['postfix'] = ' ' + param.findtext('value') use_condition_template = True break if use_condition_template: temp_string = self.yara_II_condition_template % mapping else: temp_string = self.yara_II_template % mapping if condition_string == '': condition_string = temp_string else: condition_string = ' '.join([condition_string, joining_value, temp_string]) # print condition_string elif node.tag == 'Indicator': if is_set: raise YaraConversionError('Cannot have Indicator nodes underneath a Indicator node with yara/set') operator = node.get('operator').lower() if operator not in ['or', 'and']: raise YaraConversionError('Indicator@operator is not and/or. [%s] has [%s]' % (id, operator)) # handle parameters # XXX Temp POC recursed_condition = self.get_yara_condition_string(node, parameters_node, ids_to_process, '', operator) xp = './/param[@ref-id="{}" and @name="yara/set"]'.format(node_id) if (not parameters_node.xpath(xp)) and has_siblings(node): recursed_condition = '(%s)' % recursed_condition if condition_string == '': condition_string = recursed_condition else: condition_string = ' '.join([condition_string, joining_value, recursed_condition]) # print 'recursed got: [%s]' % condition_string else: # should never get here raise YaraConversionError('node.tag is not a Indicator/IndicatorItem [%s]' % str(id)) if is_set: log.debug('Building set expression for [%s]' % indicator_node_id) if len(set_dict['set_ids']) == 0: raise YaraConversionError('yara/set processing did not yield any set ids') elif len(set_dict['set_ids']) == 1: log.warning('yara/set with 1 id found for node [%s]' % node_id) set_ids = ''.join(set_dict['set_ids']) else: set_ids = ','.join(set_dict['set_ids']) set_dict['set_ids'] = set_ids temp_set_string = self.yara_set_string_template % set_dict # print temp_set_string if condition_string == '': condition_string = temp_set_string else: condition_string = ' '.join( [condition_string, indicator_node.getparent().get('operator').lower(), temp_set_string]) return condition_string
get_yara_condition_string input indicator_node: this is the node we walk down parameters_node: this contains all the parameters in the ioc, so we can look up parameters nodes as we walk them. ids_to_process: set of ids to upgrade condition_string: This represnts the yara condition string. This string grows as we walk nodes. return returns True upon completion may raise ValueError
entailment
def write_yara(self, output_file): """ Write out yara signatures to a file. """ fout = open(output_file, 'wb') fout.write('\n') for iocid in self.yara_signatures: signature = self.yara_signatures[iocid] fout.write(signature) fout.write('\n') fout.close() return True
Write out yara signatures to a file.
entailment
def safe_makedirs(fdir): """ Make an arbitrary directory. This is safe to call for Python 2 users. :param fdir: Directory path to make. :return: """ if os.path.isdir(fdir): pass # print 'dir already exists: %s' % str(dir) else: try: os.makedirs(fdir) except WindowsError as e: if 'Cannot create a file when that file already exists' in e: log.debug('relevant dir already exists') else: raise WindowsError(e) return True
Make an arbitrary directory. This is safe to call for Python 2 users. :param fdir: Directory path to make. :return:
entailment
def convert_to_10(self): """ converts the iocs in self.iocs from openioc 1.1 to openioc 1.0 format. the converted iocs are stored in the dictionary self.iocs_10 :return: A list of iocid values which had errors downgrading. """ if len(self) < 1: log.error('no iocs available to modify') return False log.info('Converting IOCs from 1.1 to 1.0.') errors = [] for iocid in self.iocs: pruned = False ioc_obj_11 = self.iocs[iocid] metadata = ioc_obj_11.metadata # record metadata name_11 = metadata.findtext('.//short_description') keywords_11 = metadata.findtext('.//keywords') description_11 = metadata.findtext('.//description') author_11 = metadata.findtext('.//authored_by') created_date_11 = metadata.findtext('.//authored_date') last_modified_date_11 = ioc_obj_11.root.get('last-modified') links_11 = [] for link in metadata.xpath('//link'): link_rel = link.get('rel') link_text = link.text links_11.append((link_rel, None, link_text)) # get ioc_logic try: ioc_logic = ioc_obj_11.root.xpath('.//criteria')[0] except IndexError: log.exception( 'Could not find criteria nodes for IOC [{}]. Did you attempt to convert OpenIOC 1.0 iocs?'.format( iocid)) errors.append(iocid) continue try: tlo_11 = ioc_logic.getchildren()[0] except IndexError: log.exception( 'Could not find children for the top level criteria/children nodes for IOC [{}]'.format(iocid)) errors.append(iocid) continue tlo_id = tlo_11.get('id') # record comment parameters comment_dict = {} for param in ioc_obj_11.parameters.xpath('//param[@name="comment"]'): param_id = param.get('ref-id') param_text = param.findtext('value') comment_dict[param_id] = param_text # create a 1.1 indicator and populate it with the metadata from the existing 1.1 # we will then modify this new IOC to conform to 1.1 schema ioc_obj_10 = ioc_api.IOC(name=name_11, description=description_11, author=author_11, links=links_11, keywords=keywords_11, iocid=iocid) ioc_obj_10.root.attrib['last-modified'] = last_modified_date_11 authored_date_node = ioc_obj_10.metadata.find('authored_date') authored_date_node.text = created_date_11 # convert 1.1 ioc object to 1.0 # change xmlns ioc_obj_10.root.attrib['xmlns'] = 'http://schemas.mandiant.com/2010/ioc' # remove published data del ioc_obj_10.root.attrib['published-date'] # remove parameters node ioc_obj_10.root.remove(ioc_obj_10.parameters) # change root tag ioc_obj_10.root.tag = 'ioc' # metadata underneath the root node metadata_node = ioc_obj_10.metadata criteria_node = ioc_obj_10.top_level_indicator.getparent() metadata_dictionary = {} for child in metadata_node: metadata_dictionary[child.tag] = child for tag in METADATA_REQUIRED_10: if tag not in metadata_dictionary: msg = 'IOC {} is missing required metadata: [{}]'.format(iocid, tag) raise DowngradeError(msg) for tag in METADATA_ORDER_10: if tag in metadata_dictionary: ioc_obj_10.root.append(metadata_dictionary.get(tag)) ioc_obj_10.root.remove(metadata_node) ioc_obj_10.root.remove(criteria_node) criteria_node.tag = 'definition' ioc_obj_10.root.append(criteria_node) ioc_obj_10.top_level_indicator.attrib['id'] = tlo_id # identify indicator items with 1.1 specific operators # we will skip them when converting IOC from 1.1 to 1.0. ids_to_skip = set() indicatoritems_to_remove = set() for condition_type in self.openioc_11_only_conditions: for elem in ioc_logic.xpath('//IndicatorItem[@condition="%s"]' % condition_type): pruned = True indicatoritems_to_remove.add(elem) for elem in ioc_logic.xpath('//IndicatorItem[@preserve-case="true"]'): pruned = True indicatoritems_to_remove.add(elem) # walk up from each indicatoritem # to build set of ids to skip when downconverting for elem in indicatoritems_to_remove: nid = None current = elem while nid != tlo_id: parent = current.getparent() nid = parent.get('id') if nid == tlo_id: current_id = current.get('id') ids_to_skip.add(current_id) else: current = parent # walk the 1.1 IOC to convert it into a 1.0 IOC # noinspection PyBroadException try: self.convert_branch(tlo_11, ioc_obj_10.top_level_indicator, ids_to_skip, comment_dict) except DowngradeError: log.exception('Problem converting IOC [{}]'.format(iocid)) errors.append(iocid) continue except Exception: log.exception('Unknown error occured while converting [{}]'.format(iocid)) errors.append(iocid) continue # bucket pruned iocs / null iocs if not ioc_obj_10.top_level_indicator.getchildren(): self.null_pruned_iocs.add(iocid) elif pruned is True: self.pruned_11_iocs.add(iocid) # Check the original to see if there was a comment prior to the root node, and if so, copy it's content comment_node = ioc_obj_11.root.getprevious() while comment_node is not None: log.debug('found a comment node') c = et.Comment(comment_node.text) ioc_obj_10.root.addprevious(c) comment_node = comment_node.getprevious() # Record the IOC # ioc_10 = et.ElementTree(root_10) self.iocs_10[iocid] = ioc_obj_10 return errors
converts the iocs in self.iocs from openioc 1.1 to openioc 1.0 format. the converted iocs are stored in the dictionary self.iocs_10 :return: A list of iocid values which had errors downgrading.
entailment
def convert_branch(self, old_node, new_node, ids_to_skip, comment_dict=None): """ Recursively walk a indicator logic tree, starting from a Indicator node. Converts OpenIOC 1.1 Indicator/IndicatorItems to Openioc 1.0 and preserves order. :param old_node: An Indicator node, which we walk down to convert :param new_node: An Indicator node, which we add new IndicatorItem and Indicator nodes too :param ids_to_skip: set of node @id values not to convert :param comment_dict: maps ids to comment values. only applied to IndicatorItem nodes :return: returns True upon completion. :raises: DowngradeError if there is a problem during the conversion. """ expected_tag = 'Indicator' if old_node.tag != expected_tag: raise DowngradeError('old_node expected tag is [%s]' % expected_tag) if not comment_dict: comment_dict = {} for node in old_node.getchildren(): node_id = node.get('id') if node_id in ids_to_skip: continue if node.tag == 'IndicatorItem': negation = node.get('negate') condition = node.get('condition') if 'true' in negation.lower(): new_condition = condition + 'not' else: new_condition = condition document = node.xpath('Context/@document')[0] search = node.xpath('Context/@search')[0] content_type = node.xpath('Content/@type')[0] content = node.findtext('Content') context_type = node.xpath('Context/@type')[0] new_ii_node = ioc_api.make_indicatoritem_node(condition=condition, document=document, search=search, content_type=content_type, content=content, context_type=context_type, nid=node_id) # set condition new_ii_node.attrib['condition'] = new_condition # set comment if node_id in comment_dict: comment = comment_dict[node_id] comment_node = et.Element('Comment') comment_node.text = comment new_ii_node.append(comment_node) # remove preserver-case and negate del new_ii_node.attrib['negate'] del new_ii_node.attrib['preserve-case'] new_node.append(new_ii_node) elif node.tag == 'Indicator': operator = node.get('operator') if operator.upper() not in ['OR', 'AND']: raise DowngradeError('Indicator@operator is not AND/OR. [%s] has [%s]' % (node_id, operator)) new_i_node = ioc_api.make_indicator_node(operator, node_id) new_node.append(new_i_node) self.convert_branch(node, new_i_node, ids_to_skip, comment_dict) else: # should never get here raise DowngradeError('node is not a Indicator/IndicatorItem') return True
Recursively walk a indicator logic tree, starting from a Indicator node. Converts OpenIOC 1.1 Indicator/IndicatorItems to Openioc 1.0 and preserves order. :param old_node: An Indicator node, which we walk down to convert :param new_node: An Indicator node, which we add new IndicatorItem and Indicator nodes too :param ids_to_skip: set of node @id values not to convert :param comment_dict: maps ids to comment values. only applied to IndicatorItem nodes :return: returns True upon completion. :raises: DowngradeError if there is a problem during the conversion.
entailment
def write_iocs(self, directory=None, source=None): """ Serializes IOCs to a directory. :param directory: Directory to write IOCs to. If not provided, the current working directory is used. :param source: Dictionary contianing iocid -> IOC mapping. Defaults to self.iocs_10. This is not normally modifed by a user for this class. :return: """ """ if directory is None, write the iocs to the current working directory source: allows specifying a different dictionry of elmentTree ioc objects """ if not source: source = self.iocs_10 if len(source) < 1: log.error('no iocs available to write out') return False if not directory: directory = os.getcwd() if os.path.isfile(directory): log.error('cannot writes iocs to a directory') return False source_iocs = set(source.keys()) source_iocs = source_iocs.difference(self.pruned_11_iocs) source_iocs = source_iocs.difference(self.null_pruned_iocs) if not source_iocs: log.error('no iocs available to write out after removing pruned/null iocs') return False utils.safe_makedirs(directory) output_dir = os.path.abspath(directory) log.info('Writing IOCs to %s' % (str(output_dir))) # serialize the iocs for iocid in source_iocs: ioc_obj = source[iocid] ioc_obj.write_ioc_to_file(output_dir=output_dir, force=True) return True
Serializes IOCs to a directory. :param directory: Directory to write IOCs to. If not provided, the current working directory is used. :param source: Dictionary contianing iocid -> IOC mapping. Defaults to self.iocs_10. This is not normally modifed by a user for this class. :return:
entailment
def write_pruned_iocs(self, directory=None, pruned_source=None): """ Writes IOCs to a directory that have been pruned of some or all IOCs. :param directory: Directory to write IOCs to. If not provided, the current working directory is used. :param pruned_source: Iterable containing a set of iocids. Defaults to self.iocs_10. :return: """ """ write_pruned_iocs to a directory if directory is None, write the iocs to the current working directory """ if pruned_source is None: pruned_source = self.pruned_11_iocs if len(pruned_source) < 1: log.error('no iocs available to write out') return False if not directory: directory = os.getcwd() if os.path.isfile(directory): log.error('cannot writes iocs to a directory') return False utils.safe_makedirs(directory) output_dir = os.path.abspath(directory) # serialize the iocs for iocid in pruned_source: ioc_obj = self.iocs_10[iocid] ioc_obj.write_ioc_to_file(output_dir=output_dir, force=True) return True
Writes IOCs to a directory that have been pruned of some or all IOCs. :param directory: Directory to write IOCs to. If not provided, the current working directory is used. :param pruned_source: Iterable containing a set of iocids. Defaults to self.iocs_10. :return:
entailment
def make_dnsentryitem_recordname(dns_name, condition='contains', negate=False, preserve_case=False): """ Create a node for DnsEntryItem/RecordName :return: A IndicatorItem represented as an Element node """ document = 'DnsEntryItem' search = 'DnsEntryItem/RecordName' content_type = 'string' content = dns_name ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for DnsEntryItem/RecordName :return: A IndicatorItem represented as an Element node
entailment
def make_driveritem_deviceitem_devicename(device_name, condition='is', negate=False, preserve_case=False): """ Create a node for DriverItem/DeviceItem/DeviceName :return: A IndicatorItem represented as an Element node """ document = 'DriverItem' search = 'DriverItem/DeviceItem/DeviceName' content_type = 'string' content = device_name ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for DriverItem/DeviceItem/DeviceName :return: A IndicatorItem represented as an Element node
entailment
def make_driveritem_drivername(driver_name, condition='contains', negate=False, preserve_case=False): """ Create a node for DriverItem/DriverName :return: A IndicatorItem represented as an Element node """ document = 'DriverItem' search = 'DriverItem/DriverName' content_type = 'string' content = driver_name ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for DriverItem/DriverName :return: A IndicatorItem represented as an Element node
entailment
def make_eventlogitem_eid(eid, condition='is', negate=False): """ Create a node for EventLogItem/EID :return: A IndicatorItem represented as an Element node """ document = 'EventLogItem' search = 'EventLogItem/EID' content_type = 'int' content = eid ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate) return ii_node
Create a node for EventLogItem/EID :return: A IndicatorItem represented as an Element node
entailment
def make_eventlogitem_log(log, condition='is', negate=False, preserve_case=False): """ Create a node for EventLogItem/log :return: A IndicatorItem represented as an Element node """ document = 'EventLogItem' search = 'EventLogItem/log' content_type = 'string' content = log ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for EventLogItem/log :return: A IndicatorItem represented as an Element node
entailment
def make_eventlogitem_message(message, condition='contains', negate=False, preserve_case=False): """ Create a node for EventLogItem/message :return: A IndicatorItem represented as an Element node """ document = 'EventLogItem' search = 'EventLogItem/message' content_type = 'string' content = message ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for EventLogItem/message :return: A IndicatorItem represented as an Element node
entailment
def make_fileitem_fileattributes(attributes, condition='contains', negate=False, preserve_case=False): """ Create a node for FileItem/FileAttributes :return: A IndicatorItem represented as an Element node """ document = 'FileItem' search = 'FileItem/FileAttributes' content_type = 'string' content = attributes ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for FileItem/FileAttributes :return: A IndicatorItem represented as an Element node
entailment
def make_fileitem_fileextension(extension, condition='is', negate=False, preserve_case=False): """ Create a node for FileItem/FileExtension :return: A IndicatorItem represented as an Element node """ document = 'FileItem' search = 'FileItem/FileExtension' content_type = 'string' content = extension ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for FileItem/FileExtension :return: A IndicatorItem represented as an Element node
entailment
def make_fileitem_filename(filename, condition='is', negate=False, preserve_case=False): """ Create a node for FileItem/FileName :return: A IndicatorItem represented as an Element node """ document = 'FileItem' search = 'FileItem/FileName' content_type = 'string' content = filename ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for FileItem/FileName :return: A IndicatorItem represented as an Element node
entailment
def make_fileitem_filepath(filepath, condition='contains', negate=False, preserve_case=False): """ Create a node for FileItem/FilePath :return: A IndicatorItem represented as an Element node """ document = 'FileItem' search = 'FileItem/FilePath' content_type = 'string' content = filepath ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for FileItem/FilePath :return: A IndicatorItem represented as an Element node
entailment
def make_fileitem_fullpath(fullpath, condition='contains', negate=False, preserve_case=False): """ Create a node for FileItem/FullPath :return: A IndicatorItem represented as an Element node """ document = 'FileItem' search = 'FileItem/FullPath' content_type = 'string' content = fullpath ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for FileItem/FullPath :return: A IndicatorItem represented as an Element node
entailment
def make_fileitem_md5sum(md5, condition='is', negate=False): """ Create a node for FileItem/Md5sum :return: A IndicatorItem represented as an Element node """ document = 'FileItem' search = 'FileItem/Md5sum' content_type = 'md5' content = md5 ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate) return ii_node
Create a node for FileItem/Md5sum :return: A IndicatorItem represented as an Element node
entailment
def make_fileitem_peinfo_detectedanomalies_string(anomaly, condition='is', negate=False, preserve_case=False): """ Create a node for FileItem/PEInfo/DetectedAnomalies/string :return: A IndicatorItem represented as an Element node """ document = 'FileItem' search = 'FileItem/PEInfo/DetectedAnomalies/string' content_type = 'string' content = anomaly ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for FileItem/PEInfo/DetectedAnomalies/string :return: A IndicatorItem represented as an Element node
entailment
def make_fileitem_peinfo_detectedentrypointsignature_name(entrypoint_name, condition='is', negate=False, preserve_case=False): """ Create a node for FileItem/PEInfo/DetectedEntryPointSignature/Name :return: A IndicatorItem represented as an Element node """ document = 'FileItem' search = 'FileItem/PEInfo/DetectedEntryPointSignature/Name' content_type = 'string' content = entrypoint_name ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for FileItem/PEInfo/DetectedEntryPointSignature/Name :return: A IndicatorItem represented as an Element node
entailment
def make_fileitem_peinfo_digitalsignature_signatureexists(sig_exists, condition='is', negate=False): """ Create a node for FileItem/PEInfo/DigitalSignature/SignatureExists :return: A IndicatorItem represented as an Element node """ document = 'FileItem' search = 'FileItem/PEInfo/DigitalSignature/SignatureExists' content_type = 'bool' content = sig_exists ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate) return ii_node
Create a node for FileItem/PEInfo/DigitalSignature/SignatureExists :return: A IndicatorItem represented as an Element node
entailment
def make_fileitem_peinfo_digitalsignature_signatureverified(sig_verified, condition='is', negate=False): """ Create a node for FileItem/PEInfo/DigitalSignature/SignatureVerified :return: A IndicatorItem represented as an Element node """ document = 'FileItem' search = 'FileItem/PEInfo/DigitalSignature/SignatureVerified' content_type = 'bool' content = sig_verified ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate) return ii_node
Create a node for FileItem/PEInfo/DigitalSignature/SignatureVerified :return: A IndicatorItem represented as an Element node
entailment
def make_fileitem_peinfo_exports_dllname(dll_name, condition='is', negate=False, preserve_case=False): """ Create a node for FileItem/PEInfo/Exports/DllName :return: A IndicatorItem represented as an Element node """ document = 'FileItem' search = 'FileItem/PEInfo/Exports/DllName' content_type = 'string' content = dll_name ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for FileItem/PEInfo/Exports/DllName :return: A IndicatorItem represented as an Element node
entailment
def make_fileitem_peinfo_exports_numberoffunctions(function_count, condition='is', negate=False): """ Create a node for FileItem/PEInfo/Exports/NumberOfFunctions :return: A IndicatorItem represented as an Element node """ document = 'FileItem' search = 'FileItem/PEInfo/Exports/NumberOfFunctions' content_type = 'int' content = function_count ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate) return ii_node
Create a node for FileItem/PEInfo/Exports/NumberOfFunctions :return: A IndicatorItem represented as an Element node
entailment
def make_fileitem_peinfo_importedmodules_module_importedfunctions_string(imported_function, condition='is', negate=False, preserve_case=False): """ Create a node for FileItem/PEInfo/ImportedModules/Module/ImportedFunctions/string :return: A IndicatorItem represented as an Element node """ document = 'FileItem' search = 'FileItem/PEInfo/ImportedModules/Module/ImportedFunctions/string' content_type = 'string' content = imported_function ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for FileItem/PEInfo/ImportedModules/Module/ImportedFunctions/string :return: A IndicatorItem represented as an Element node
entailment
def make_fileitem_peinfo_importedmodules_module_name(imported_module, condition='is', negate=False, preserve_case=False): """ Create a node for FileItem/PEInfo/ImportedModules/Module/Name :return: A IndicatorItem represented as an Element node """ document = 'FileItem' search = 'FileItem/PEInfo/ImportedModules/Module/Name' content_type = 'string' content = imported_module ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for FileItem/PEInfo/ImportedModules/Module/Name :return: A IndicatorItem represented as an Element node
entailment
def make_fileitem_peinfo_petimestamp(compile_time, condition='is', negate=False): """ Create a node for FileItem/PEInfo/PETimeStamp :return: A IndicatorItem represented as an Element node """ document = 'FileItem' search = 'FileItem/PEInfo/PETimeStamp' content_type = 'date' content = compile_time ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate) return ii_node
Create a node for FileItem/PEInfo/PETimeStamp :return: A IndicatorItem represented as an Element node
entailment
def make_fileitem_peinfo_resourceinfolist_resourceinfoitem_name(resource_name, condition='is', negate=False, preserve_case=False): """ Create a node for FileItem/PEInfo/ResourceInfoList/ResourceInfoItem/Name :return: A IndicatorItem represented as an Element node """ document = 'FileItem' search = 'FileItem/PEInfo/ResourceInfoList/ResourceInfoItem/Name' content_type = 'string' content = resource_name ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for FileItem/PEInfo/ResourceInfoList/ResourceInfoItem/Name :return: A IndicatorItem represented as an Element node
entailment
def make_fileitem_peinfo_type(petype, condition='is', negate=False, preserve_case=False): """ Create a node for FileItem/PEInfo/Type :return: A IndicatorItem represented as an Element node """ document = 'FileItem' search = 'FileItem/PEInfo/Type' content_type = 'string' content = petype ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for FileItem/PEInfo/Type :return: A IndicatorItem represented as an Element node
entailment
def make_fileitem_sizeinbytes(filesize, condition='is', negate=False): """ Create a node for FileItem/SizeInBytes :return: A IndicatorItem represented as an Element node """ document = 'FileItem' search = 'FileItem/SizeInBytes' content_type = 'int' content = filesize ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate) return ii_node
Create a node for FileItem/SizeInBytes :return: A IndicatorItem represented as an Element node
entailment
def make_fileitem_streamlist_stream_name(stream_name, condition='is', negate=False, preserve_case=False): """ Create a node for FileItem/StreamList/Stream/Name :return: A IndicatorItem represented as an Element node """ document = 'FileItem' search = 'FileItem/StreamList/Stream/Name' content_type = 'string' content = stream_name ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for FileItem/StreamList/Stream/Name :return: A IndicatorItem represented as an Element node
entailment
def make_fileitem_stringlist_string(file_string, condition='contains', negate=False, preserve_case=False): """ Create a node for FileItem/StringList/string :return: A IndicatorItem represented as an Element node """ document = 'FileItem' search = 'FileItem/StringList/string' content_type = 'string' content = file_string ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for FileItem/StringList/string :return: A IndicatorItem represented as an Element node
entailment
def make_fileitem_username(file_owner, condition='is', negate=False, preserve_case=False): """ Create a node for FileItem/Username :return: A IndicatorItem represented as an Element node """ document = 'FileItem' search = 'FileItem/Username' content_type = 'string' content = file_owner ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for FileItem/Username :return: A IndicatorItem represented as an Element node
entailment
def make_hookitem_hookedfunction(hooked_function, condition='is', negate=False, preserve_case=False): """ Create a node for HookItem/HookedFunction :return: A IndicatorItem represented as an Element node """ document = 'HookItem' search = 'HookItem/HookedFunction' content_type = 'string' content = hooked_function ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for HookItem/HookedFunction :return: A IndicatorItem represented as an Element node
entailment
def make_hookitem_hookingmodule(hooking_module, condition='contains', negate=False, preserve_case=False): """ Create a node for HookItem/HookingModule :return: A IndicatorItem represented as an Element node """ document = 'HookItem' search = 'HookItem/HookingModule' content_type = 'string' content = hooking_module ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for HookItem/HookingModule :return: A IndicatorItem represented as an Element node
entailment
def make_portitem_remoteport(remote_port, condition='is', negate=False): """ Create a node for PortItem/remotePort :return: A IndicatorItem represented as an Element node """ document = 'PortItem' search = 'PortItem/remotePort' content_type = 'int' content = remote_port ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate) return ii_node
Create a node for PortItem/remotePort :return: A IndicatorItem represented as an Element node
entailment
def make_prefetchitem_accessedfilelist_accessedfile(accessed_file, condition='contains', negate=False, preserve_case=False): """ Create a node for PrefetchItem/AccessedFileList/AccessedFile :return: A IndicatorItem represented as an Element node """ document = 'PrefetchItem' search = 'PrefetchItem/AccessedFileList/AccessedFile' content_type = 'string' content = accessed_file ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for PrefetchItem/AccessedFileList/AccessedFile :return: A IndicatorItem represented as an Element node
entailment
def make_prefetchitem_applicationfilename(application_filename, condition='is', negate=False, preserve_case=False): """ Create a node for PrefetchItem/ApplicationFileName :return: A IndicatorItem represented as an Element node """ document = 'PrefetchItem' search = 'PrefetchItem/ApplicationFileName' content_type = 'string' content = application_filename ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for PrefetchItem/ApplicationFileName :return: A IndicatorItem represented as an Element node
entailment
def make_prefetchitem_applicationfullpath(application_fullpath, condition='contains', negate=False, preserve_case=False): """ Create a node for PrefetchItem/ApplicationFullPath :return: A IndicatorItem represented as an Element node """ document = 'PrefetchItem' search = 'PrefetchItem/ApplicationFullPath' content_type = 'string' content = application_fullpath ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for PrefetchItem/ApplicationFullPath :return: A IndicatorItem represented as an Element node
entailment
def make_processitem_handlelist_handle_name(handle_name, condition='contains', negate=False, preserve_case=False): """ Create a node for ProcessItem/HandleList/Handle/Name :return: A IndicatorItem represented as an Element node """ document = 'ProcessItem' search = 'ProcessItem/HandleList/Handle/Name' content_type = 'string' content = handle_name ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for ProcessItem/HandleList/Handle/Name :return: A IndicatorItem represented as an Element node
entailment
def make_processitem_portlist_portitem_remoteip(remote_ip, condition='is', negate=False): """ Create a node for ProcessItem/PortList/PortItem/remoteIP :return: A IndicatorItem represented as an Element node """ document = 'ProcessItem' search = 'ProcessItem/PortList/PortItem/remoteIP' content_type = 'IP' content = remote_ip ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate) return ii_node
Create a node for ProcessItem/PortList/PortItem/remoteIP :return: A IndicatorItem represented as an Element node
entailment
def make_processitem_sectionlist_memorysection_name(section_name, condition='contains', negate=False, preserve_case=False): """ Create a node for ProcessItem/SectionList/MemorySection/Name :return: A IndicatorItem represented as an Element node """ document = 'ProcessItem' search = 'ProcessItem/SectionList/MemorySection/Name' content_type = 'string' content = section_name ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for ProcessItem/SectionList/MemorySection/Name :return: A IndicatorItem represented as an Element node
entailment
def make_processitem_sectionlist_memorysection_peinfo_exports_exportedfunctions_string(export_function, condition='is', negate=False, preserve_case=False): """ Create a node for ProcessItem/SectionList/MemorySection/PEInfo/Exports/ExportedFunctions/string :return: A IndicatorItem represented as an Element node """ document = 'ProcessItem' search = 'ProcessItem/SectionList/MemorySection/PEInfo/Exports/ExportedFunctions/string' content_type = 'string' content = export_function ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for ProcessItem/SectionList/MemorySection/PEInfo/Exports/ExportedFunctions/string :return: A IndicatorItem represented as an Element node
entailment
def make_processitem_stringlist_string(string, condition='contains', negate=False, preserve_case=False): """ Create a node for ProcessItem/StringList/string :return: A IndicatorItem represented as an Element node """ document = 'ProcessItem' search = 'ProcessItem/StringList/string' content_type = 'string' content = string ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for ProcessItem/StringList/string :return: A IndicatorItem represented as an Element node
entailment
def make_processitem_username(username, condition='contains', negate=False, preserve_case=False): """ Create a node for ProcessItem/Username :return: A IndicatorItem represented as an Element node """ document = 'ProcessItem' search = 'ProcessItem/Username' content_type = 'string' content = username ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for ProcessItem/Username :return: A IndicatorItem represented as an Element node
entailment
def make_processitem_arguments(arguments, condition='contains', negate=False, preserve_case=False): """ Create a node for ProcessItem/arguments :return: A IndicatorItem represented as an Element node """ document = 'ProcessItem' search = 'ProcessItem/arguments' content_type = 'string' content = arguments ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for ProcessItem/arguments :return: A IndicatorItem represented as an Element node
entailment
def make_processitem_path(path, condition='contains', negate=False, preserve_case=False): """ Create a node for ProcessItem/path :return: A IndicatorItem represented as an Element node """ document = 'ProcessItem' search = 'ProcessItem/path' content_type = 'string' content = path ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for ProcessItem/path :return: A IndicatorItem represented as an Element node
entailment
def make_registryitem_keypath(keypath, condition='contains', negate=False, preserve_case=False): """ Create a node for RegistryItem/KeyPath :return: A IndicatorItem represented as an Element node """ document = 'RegistryItem' search = 'RegistryItem/KeyPath' content_type = 'string' content = keypath ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for RegistryItem/KeyPath :return: A IndicatorItem represented as an Element node
entailment
def make_registryitem_text(text, condition='contains', negate=False, preserve_case=False): """ Create a node for RegistryItem/Text :return: A IndicatorItem represented as an Element node """ document = 'RegistryItem' search = 'RegistryItem/Text' content_type = 'string' content = text ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for RegistryItem/Text :return: A IndicatorItem represented as an Element node
entailment
def make_registryitem_valuename(valuename, condition='is', negate=False, preserve_case=False): """ Create a node for RegistryItem/ValueName :return: A IndicatorItem represented as an Element node """ document = 'RegistryItem' search = 'RegistryItem/ValueName' content_type = 'string' content = valuename ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for RegistryItem/ValueName :return: A IndicatorItem represented as an Element node
entailment
def make_serviceitem_description(description, condition='contains', negate=False, preserve_case=False): """ Create a node for ServiceItem/description :return: A IndicatorItem represented as an Element node """ document = 'ServiceItem' search = 'ServiceItem/description' content_type = 'string' content = description ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for ServiceItem/description :return: A IndicatorItem represented as an Element node
entailment
def make_serviceitem_descriptivename(descriptive_name, condition='is', negate=False, preserve_case=False): """ Create a node for ServiceItem/descriptiveName :return: A IndicatorItem represented as an Element node """ document = 'ServiceItem' search = 'ServiceItem/descriptiveName' content_type = 'string' content = descriptive_name ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for ServiceItem/descriptiveName :return: A IndicatorItem represented as an Element node
entailment
def make_serviceitem_name(name, condition='is', negate=False, preserve_case=False): """ Create a node for ServiceItem/name :return: A IndicatorItem represented as an Element node """ document = 'ServiceItem' search = 'ServiceItem/name' content_type = 'string' content = name ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for ServiceItem/name :return: A IndicatorItem represented as an Element node
entailment
def make_serviceitem_pathmd5sum(path_md5, condition='is', negate=False): """ Create a node for ServiceItem/pathmd5sum :return: A IndicatorItem represented as an Element node """ document = 'ServiceItem' search = 'ServiceItem/pathmd5sum' content_type = 'md5' content = path_md5 ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate) return ii_node
Create a node for ServiceItem/pathmd5sum :return: A IndicatorItem represented as an Element node
entailment
def make_serviceitem_servicedll(servicedll, condition='contains', negate=False, preserve_case=False): """ Create a node for ServiceItem/serviceDLL :return: A IndicatorItem represented as an Element node """ document = 'ServiceItem' search = 'ServiceItem/serviceDLL' content_type = 'string' content = servicedll ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for ServiceItem/serviceDLL :return: A IndicatorItem represented as an Element node
entailment
def make_serviceitem_servicedllsignatureexists(dll_sig_exists, condition='is', negate=False): """ Create a node for ServiceItem/serviceDLLSignatureExists :return: A IndicatorItem represented as an Element node """ document = 'ServiceItem' search = 'ServiceItem/serviceDLLSignatureExists' content_type = 'bool' content = dll_sig_exists ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate) return ii_node
Create a node for ServiceItem/serviceDLLSignatureExists :return: A IndicatorItem represented as an Element node
entailment
def make_serviceitem_servicedllsignatureverified(dll_sig_verified, condition='is', negate=False): """ Create a node for ServiceItem/serviceDLLSignatureVerified :return: A IndicatorItem represented as an Element node """ document = 'ServiceItem' search = 'ServiceItem/serviceDLLSignatureVerified' content_type = 'bool' content = dll_sig_verified ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate) return ii_node
Create a node for ServiceItem/serviceDLLSignatureVerified :return: A IndicatorItem represented as an Element node
entailment
def make_serviceitem_servicedllmd5sum(servicedll_md5, condition='is', negate=False): """ Create a node for ServiceItem/serviceDLLmd5sum :return: A IndicatorItem represented as an Element node """ document = 'ServiceItem' search = 'ServiceItem/serviceDLLmd5sum' content_type = 'md5' content = servicedll_md5 ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate) return ii_node
Create a node for ServiceItem/serviceDLLmd5sum :return: A IndicatorItem represented as an Element node
entailment
def make_systeminfoitem_hostname(hostname, condition='contains', negate=False, preserve_case=False): """ Create a node for SystemInfoItem/hostname :return: A IndicatorItem represented as an Element node """ document = 'SystemInfoItem' search = 'SystemInfoItem/hostname' content_type = 'string' content = hostname ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for SystemInfoItem/hostname :return: A IndicatorItem represented as an Element node
entailment
def make_systemrestoreitem_originalfilename(original_filename, condition='contains', negate=False, preserve_case=False): """ Create a node for SystemRestoreItem/OriginalFileName :return: A IndicatorItem represented as an Element node """ document = 'SystemRestoreItem' search = 'SystemRestoreItem/OriginalFileName' content_type = 'string' content = original_filename ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for SystemRestoreItem/OriginalFileName :return: A IndicatorItem represented as an Element node
entailment
def make_fileitem_peinfo_versioninfoitem(key, value, condition='is', negate=False, preserve_case=False): """ Create a node for FileItem/PEInfo/VersionInfoList/VersionInfoItem/ + key name No validation of the key is performed. :return: A IndicatorItem represented as an Element node """ document = 'FileItem' search = 'FileItem/PEInfo/VersionInfoList/VersionInfoItem/' + key # XXX: No validation of key done. content_type = 'string' content = value ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
Create a node for FileItem/PEInfo/VersionInfoList/VersionInfoItem/ + key name No validation of the key is performed. :return: A IndicatorItem represented as an Element node
entailment
def fix_schema_node_ordering(parent): """ Fix the ordering of children under the criteria node to ensure that IndicatorItem/Indicator order is preserved, as per XML Schema. :return: """ children = parent.getchildren() i_nodes = [node for node in children if node.tag == 'IndicatorItem'] ii_nodes = [node for node in children if node.tag == 'Indicator'] if not ii_nodes: return # Remove all the children for node in children: parent.remove(node) # Add the Indicator nodes back for node in i_nodes: parent.append(node) # Now add the IndicatorItem nodes back for node in ii_nodes: parent.append(node) # Now recurse for node in ii_nodes: fix_schema_node_ordering(node)
Fix the ordering of children under the criteria node to ensure that IndicatorItem/Indicator order is preserved, as per XML Schema. :return:
entailment
def make_indicator_node(operator, nid=None): """ This makes a Indicator node element. These allow the construction of a logic tree within the IOC. :param operator: String 'AND' or 'OR'. The constants ioc_api.OR and ioc_api.AND may be used as well. :param nid: This is used to provide a GUID for the Indicator. The ID should NOT be specified under normal circumstances. :return: elementTree element """ if operator.upper() not in VALID_INDICATOR_OPERATORS: raise ValueError('Indicator operator must be in [{}].'.format(VALID_INDICATOR_OPERATORS)) i_node = et.Element('Indicator') if nid: i_node.attrib['id'] = nid else: i_node.attrib['id'] = ioc_et.get_guid() i_node.attrib['operator'] = operator.upper() return i_node
This makes a Indicator node element. These allow the construction of a logic tree within the IOC. :param operator: String 'AND' or 'OR'. The constants ioc_api.OR and ioc_api.AND may be used as well. :param nid: This is used to provide a GUID for the Indicator. The ID should NOT be specified under normal circumstances. :return: elementTree element
entailment
def make_indicatoritem_node(condition, document, search, content_type, content, preserve_case=False, negate=False, context_type='mir', nid=None): """ This makes a IndicatorItem element. This contains the actual threat intelligence in the IOC. :param condition: This is the condition of the item ('is', 'contains', 'matches', etc). The following contants in ioc_api may be used: ==================== ===================================================== Constant Meaning ==================== ===================================================== ioc_api.IS Exact String match. ioc_api.CONTAINS Substring match. ioc_api.MATCHES Regex match. ioc_api.STARTS_WITH String match at the beginning of a string. ioc_api.ENDS_WITH String match at the end of a string. ioc_api.GREATER_THAN Integer match indicating a greater than (>) operation. ioc_api.LESS_THAN Integer match indicator a less than (<) operation. ==================== ===================================================== :param document: Denotes the type of document to look for the encoded artifact in. :param search: Specifies what attribute of the document type the encoded value is. :param content_type: This is the display type of the item. This is normally derived from the iocterm for the search value. :param content: The threat intelligence that is being encoded. :param preserve_case: Specifiy that the content should be treated in a case sensitive manner. :param negate: Specifify that the condition is negated. An example of this is: @condition = 'is' & @negate = 'true' would be equal to the @condition = 'isnot' in OpenIOC 1.0. :param context_type: Gives context to the document/search information. :param nid: This is used to provide a GUID for the IndicatorItem. The ID should NOT be specified under normal circumstances. :return: an elementTree Element item """ # validate condition if condition not in VALID_INDICATORITEM_CONDITIONS: raise ValueError('Invalid IndicatorItem condition [{}]'.format(condition)) ii_node = et.Element('IndicatorItem') if nid: ii_node.attrib['id'] = nid else: ii_node.attrib['id'] = ioc_et.get_guid() ii_node.attrib['condition'] = condition if preserve_case: ii_node.attrib['preserve-case'] = 'true' else: ii_node.attrib['preserve-case'] = 'false' if negate: ii_node.attrib['negate'] = 'true' else: ii_node.attrib['negate'] = 'false' context_node = ioc_et.make_context_node(document, search, context_type) content_node = ioc_et.make_content_node(content_type, content) ii_node.append(context_node) ii_node.append(content_node) return ii_node
This makes a IndicatorItem element. This contains the actual threat intelligence in the IOC. :param condition: This is the condition of the item ('is', 'contains', 'matches', etc). The following contants in ioc_api may be used: ==================== ===================================================== Constant Meaning ==================== ===================================================== ioc_api.IS Exact String match. ioc_api.CONTAINS Substring match. ioc_api.MATCHES Regex match. ioc_api.STARTS_WITH String match at the beginning of a string. ioc_api.ENDS_WITH String match at the end of a string. ioc_api.GREATER_THAN Integer match indicating a greater than (>) operation. ioc_api.LESS_THAN Integer match indicator a less than (<) operation. ==================== ===================================================== :param document: Denotes the type of document to look for the encoded artifact in. :param search: Specifies what attribute of the document type the encoded value is. :param content_type: This is the display type of the item. This is normally derived from the iocterm for the search value. :param content: The threat intelligence that is being encoded. :param preserve_case: Specifiy that the content should be treated in a case sensitive manner. :param negate: Specifify that the condition is negated. An example of this is: @condition = 'is' & @negate = 'true' would be equal to the @condition = 'isnot' in OpenIOC 1.0. :param context_type: Gives context to the document/search information. :param nid: This is used to provide a GUID for the IndicatorItem. The ID should NOT be specified under normal circumstances. :return: an elementTree Element item
entailment
def get_top_level_indicator_node(root_node): """ This returns the first top level Indicator node under the criteria node. :param root_node: Root node of an etree. :return: an elementTree Element item, or None if no item is found. """ if root_node.tag != 'OpenIOC': raise IOCParseError('Root tag is not "OpenIOC" [{}].'.format(root_node.tag)) elems = root_node.xpath('criteria/Indicator') if len(elems) == 0: log.warning('No top level Indicator node found.') return None elif len(elems) > 1: log.warning('Multiple top level Indicator nodes found. This is not a valid MIR IOC.') return None else: top_level_indicator_node = elems[0] if top_level_indicator_node.get('operator').lower() != 'or': log.warning('Top level Indicator/@operator attribute is not "OR". This is not a valid MIR IOC.') return top_level_indicator_node
This returns the first top level Indicator node under the criteria node. :param root_node: Root node of an etree. :return: an elementTree Element item, or None if no item is found.
entailment