repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
EnergieID/smappy
smappy/smappy.py
LocalSmappee.active_cosfi
def active_cosfi(self): """ Takes the average of all instantaneous cosfi values Returns ------- float """ inst = self.load_instantaneous() values = [float(i['value']) for i in inst if i['key'].endswith('Cosfi')] return sum(values) / len(values)
python
def active_cosfi(self): """ Takes the average of all instantaneous cosfi values Returns ------- float """ inst = self.load_instantaneous() values = [float(i['value']) for i in inst if i['key'].endswith('Cosfi')] return sum(values) / len(values)
[ "def", "active_cosfi", "(", "self", ")", ":", "inst", "=", "self", ".", "load_instantaneous", "(", ")", "values", "=", "[", "float", "(", "i", "[", "'value'", "]", ")", "for", "i", "in", "inst", "if", "i", "[", "'key'", "]", ".", "endswith", "(", "'Cosfi'", ")", "]", "return", "sum", "(", "values", ")", "/", "len", "(", "values", ")" ]
Takes the average of all instantaneous cosfi values Returns ------- float
[ "Takes", "the", "average", "of", "all", "instantaneous", "cosfi", "values" ]
1ada3abc9a51c76205c072369258f6f4f4e8fd0f
https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L586-L596
train
EnergieID/smappy
smappy/smappy.py
LocalSmappee.on_command_control
def on_command_control(self, val_id): """ Parameters ---------- val_id : str Returns ------- requests.Response """ data = "control,controlId=1|" + val_id return self._basic_post(url='commandControlPublic', data=data)
python
def on_command_control(self, val_id): """ Parameters ---------- val_id : str Returns ------- requests.Response """ data = "control,controlId=1|" + val_id return self._basic_post(url='commandControlPublic', data=data)
[ "def", "on_command_control", "(", "self", ",", "val_id", ")", ":", "data", "=", "\"control,controlId=1|\"", "+", "val_id", "return", "self", ".", "_basic_post", "(", "url", "=", "'commandControlPublic'", ",", "data", "=", "data", ")" ]
Parameters ---------- val_id : str Returns ------- requests.Response
[ "Parameters", "----------", "val_id", ":", "str" ]
1ada3abc9a51c76205c072369258f6f4f4e8fd0f
https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L697-L708
train
EnergieID/smappy
smappy/smappy.py
LocalSmappee.off_command_control
def off_command_control(self, val_id): """ Parameters ---------- val_id : str Returns ------- requests.Response """ data = "control,controlId=0|" + val_id return self._basic_post(url='commandControlPublic', data=data)
python
def off_command_control(self, val_id): """ Parameters ---------- val_id : str Returns ------- requests.Response """ data = "control,controlId=0|" + val_id return self._basic_post(url='commandControlPublic', data=data)
[ "def", "off_command_control", "(", "self", ",", "val_id", ")", ":", "data", "=", "\"control,controlId=0|\"", "+", "val_id", "return", "self", ".", "_basic_post", "(", "url", "=", "'commandControlPublic'", ",", "data", "=", "data", ")" ]
Parameters ---------- val_id : str Returns ------- requests.Response
[ "Parameters", "----------", "val_id", ":", "str" ]
1ada3abc9a51c76205c072369258f6f4f4e8fd0f
https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L710-L721
train
EnergieID/smappy
smappy/smappy.py
LocalSmappee.delete_command_control
def delete_command_control(self, val_id): """ Parameters ---------- val_id : str Returns ------- requests.Response """ data = "delete,controlId=" + val_id return self._basic_post(url='commandControlPublic', data=data)
python
def delete_command_control(self, val_id): """ Parameters ---------- val_id : str Returns ------- requests.Response """ data = "delete,controlId=" + val_id return self._basic_post(url='commandControlPublic', data=data)
[ "def", "delete_command_control", "(", "self", ",", "val_id", ")", ":", "data", "=", "\"delete,controlId=\"", "+", "val_id", "return", "self", ".", "_basic_post", "(", "url", "=", "'commandControlPublic'", ",", "data", "=", "data", ")" ]
Parameters ---------- val_id : str Returns ------- requests.Response
[ "Parameters", "----------", "val_id", ":", "str" ]
1ada3abc9a51c76205c072369258f6f4f4e8fd0f
https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L739-L751
train
EnergieID/smappy
smappy/smappy.py
LocalSmappee.delete_command_control_timers
def delete_command_control_timers(self, val_id): """ Parameters ---------- val_id : str Returns ------- requests.Response """ data = "deleteTimers,controlId=" + val_id return self._basic_post(url='commandControlPublic', data=data)
python
def delete_command_control_timers(self, val_id): """ Parameters ---------- val_id : str Returns ------- requests.Response """ data = "deleteTimers,controlId=" + val_id return self._basic_post(url='commandControlPublic', data=data)
[ "def", "delete_command_control_timers", "(", "self", ",", "val_id", ")", ":", "data", "=", "\"deleteTimers,controlId=\"", "+", "val_id", "return", "self", ".", "_basic_post", "(", "url", "=", "'commandControlPublic'", ",", "data", "=", "data", ")" ]
Parameters ---------- val_id : str Returns ------- requests.Response
[ "Parameters", "----------", "val_id", ":", "str" ]
1ada3abc9a51c76205c072369258f6f4f4e8fd0f
https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L753-L764
train
EnergieID/smappy
smappy/smappy.py
LocalSmappee.select_logfile
def select_logfile(self, logfile): """ Parameters ---------- logfile : str Returns ------- dict """ data = 'logFileSelect,' + logfile r = self._basic_post(url='logBrowser', data=data) return r.json()
python
def select_logfile(self, logfile): """ Parameters ---------- logfile : str Returns ------- dict """ data = 'logFileSelect,' + logfile r = self._basic_post(url='logBrowser', data=data) return r.json()
[ "def", "select_logfile", "(", "self", ",", "logfile", ")", ":", "data", "=", "'logFileSelect,'", "+", "logfile", "r", "=", "self", ".", "_basic_post", "(", "url", "=", "'logBrowser'", ",", "data", "=", "data", ")", "return", "r", ".", "json", "(", ")" ]
Parameters ---------- logfile : str Returns ------- dict
[ "Parameters", "----------", "logfile", ":", "str" ]
1ada3abc9a51c76205c072369258f6f4f4e8fd0f
https://github.com/EnergieID/smappy/blob/1ada3abc9a51c76205c072369258f6f4f4e8fd0f/smappy/smappy.py#L791-L803
train
vpelletier/python-functionfs
functionfs/__init__.py
getInterfaceInAllSpeeds
def getInterfaceInAllSpeeds(interface, endpoint_list, class_descriptor_list=()): """ Produce similar fs, hs and ss interface and endpoints descriptors. Should be useful for devices desiring to work in all 3 speeds with maximum endpoint wMaxPacketSize. Reduces data duplication from descriptor declarations. Not intended to cover fancy combinations. interface (dict): Keyword arguments for getDescriptor(USBInterfaceDescriptor, ...) in all speeds. bNumEndpoints must not be provided. endpoint_list (list of dicts) Each dict represents an endpoint, and may contain the following items: - "endpoint": required, contains keyword arguments for getDescriptor(USBEndpointDescriptorNoAudio, ...) or getDescriptor(USBEndpointDescriptor, ...) The with-audio variant is picked when its extra fields are assigned a value. wMaxPacketSize may be missing, in which case it will be set to the maximum size for given speed and endpoint type. bmAttributes must be provided. If bEndpointAddress is zero (excluding direction bit) on the first endpoint, endpoints will be assigned their rank in this list, starting at 1. Their direction bit is preserved. If bInterval is present on a INT or ISO endpoint, it must be in millisecond units (but may not be an integer), and will be converted to the nearest integer millisecond for full-speed descriptor, and nearest possible interval for high- and super-speed descriptors. If bInterval is present on a BULK endpoint, it is set to zero on full-speed descriptor and used as provided on high- and super-speed descriptors. - "superspeed": optional, contains keyword arguments for getDescriptor(USBSSEPCompDescriptor, ...) - "superspeed_iso": optional, contains keyword arguments for getDescriptor(USBSSPIsocEndpointDescriptor, ...) Must be provided and non-empty only when endpoint is isochronous and "superspeed" dict has "bmAttributes" bit 7 set. class_descriptor (list of descriptors of any type) Descriptors to insert in all speeds between the interface descriptor and endpoint descriptors. Returns a 3-tuple of lists: - fs descriptors - hs descriptors - ss descriptors """ interface = getDescriptor( USBInterfaceDescriptor, bNumEndpoints=len(endpoint_list), **interface ) class_descriptor_list = list(class_descriptor_list) fs_list = [interface] + class_descriptor_list hs_list = [interface] + class_descriptor_list ss_list = [interface] + class_descriptor_list need_address = ( endpoint_list[0]['endpoint'].get( 'bEndpointAddress', 0, ) & ~ch9.USB_DIR_IN == 0 ) for index, endpoint in enumerate(endpoint_list, 1): endpoint_kw = endpoint['endpoint'].copy() transfer_type = endpoint_kw[ 'bmAttributes' ] & ch9.USB_ENDPOINT_XFERTYPE_MASK fs_max, hs_max, ss_max = _MAX_PACKET_SIZE_DICT[transfer_type] if need_address: endpoint_kw['bEndpointAddress'] = index | ( endpoint_kw.get('bEndpointAddress', 0) & ch9.USB_DIR_IN ) klass = ( USBEndpointDescriptor if 'bRefresh' in endpoint_kw or 'bSynchAddress' in endpoint_kw else USBEndpointDescriptorNoAudio ) interval = endpoint_kw.pop('bInterval', _MARKER) if interval is _MARKER: fs_interval = hs_interval = 0 else: if transfer_type == ch9.USB_ENDPOINT_XFER_BULK: fs_interval = 0 hs_interval = interval else: # USB_ENDPOINT_XFER_ISOC or USB_ENDPOINT_XFER_INT fs_interval = max(1, min(255, round(interval))) # 8 is the number of microframes in a millisecond hs_interval = max( 1, min(16, int(round(1 + math.log(interval * 8, 2)))), ) packet_size = endpoint_kw.pop('wMaxPacketSize', _MARKER) if packet_size is _MARKER: fs_packet_size = fs_max hs_packet_size = hs_max ss_packet_size = ss_max else: fs_packet_size = min(fs_max, packet_size) hs_packet_size = min(hs_max, packet_size) ss_packet_size = min(ss_max, packet_size) fs_list.append(getDescriptor( klass, wMaxPacketSize=fs_max, bInterval=fs_interval, **endpoint_kw )) hs_list.append(getDescriptor( klass, wMaxPacketSize=hs_max, bInterval=hs_interval, **endpoint_kw )) ss_list.append(getDescriptor( klass, wMaxPacketSize=ss_max, bInterval=hs_interval, **endpoint_kw )) ss_companion_kw = endpoint.get('superspeed', _EMPTY_DICT) ss_list.append(getDescriptor( USBSSEPCompDescriptor, **ss_companion_kw )) ssp_iso_kw = endpoint.get('superspeed_iso', _EMPTY_DICT) if bool(ssp_iso_kw) != ( endpoint_kw.get('bmAttributes', 0) & ch9.USB_ENDPOINT_XFERTYPE_MASK == ch9.USB_ENDPOINT_XFER_ISOC and bool(ch9.USB_SS_SSP_ISOC_COMP( ss_companion_kw.get('bmAttributes', 0), )) ): raise ValueError('Inconsistent isochronous companion') if ssp_iso_kw: ss_list.append(getDescriptor( USBSSPIsocEndpointDescriptor, **ssp_iso_kw )) return (fs_list, hs_list, ss_list)
python
def getInterfaceInAllSpeeds(interface, endpoint_list, class_descriptor_list=()): """ Produce similar fs, hs and ss interface and endpoints descriptors. Should be useful for devices desiring to work in all 3 speeds with maximum endpoint wMaxPacketSize. Reduces data duplication from descriptor declarations. Not intended to cover fancy combinations. interface (dict): Keyword arguments for getDescriptor(USBInterfaceDescriptor, ...) in all speeds. bNumEndpoints must not be provided. endpoint_list (list of dicts) Each dict represents an endpoint, and may contain the following items: - "endpoint": required, contains keyword arguments for getDescriptor(USBEndpointDescriptorNoAudio, ...) or getDescriptor(USBEndpointDescriptor, ...) The with-audio variant is picked when its extra fields are assigned a value. wMaxPacketSize may be missing, in which case it will be set to the maximum size for given speed and endpoint type. bmAttributes must be provided. If bEndpointAddress is zero (excluding direction bit) on the first endpoint, endpoints will be assigned their rank in this list, starting at 1. Their direction bit is preserved. If bInterval is present on a INT or ISO endpoint, it must be in millisecond units (but may not be an integer), and will be converted to the nearest integer millisecond for full-speed descriptor, and nearest possible interval for high- and super-speed descriptors. If bInterval is present on a BULK endpoint, it is set to zero on full-speed descriptor and used as provided on high- and super-speed descriptors. - "superspeed": optional, contains keyword arguments for getDescriptor(USBSSEPCompDescriptor, ...) - "superspeed_iso": optional, contains keyword arguments for getDescriptor(USBSSPIsocEndpointDescriptor, ...) Must be provided and non-empty only when endpoint is isochronous and "superspeed" dict has "bmAttributes" bit 7 set. class_descriptor (list of descriptors of any type) Descriptors to insert in all speeds between the interface descriptor and endpoint descriptors. Returns a 3-tuple of lists: - fs descriptors - hs descriptors - ss descriptors """ interface = getDescriptor( USBInterfaceDescriptor, bNumEndpoints=len(endpoint_list), **interface ) class_descriptor_list = list(class_descriptor_list) fs_list = [interface] + class_descriptor_list hs_list = [interface] + class_descriptor_list ss_list = [interface] + class_descriptor_list need_address = ( endpoint_list[0]['endpoint'].get( 'bEndpointAddress', 0, ) & ~ch9.USB_DIR_IN == 0 ) for index, endpoint in enumerate(endpoint_list, 1): endpoint_kw = endpoint['endpoint'].copy() transfer_type = endpoint_kw[ 'bmAttributes' ] & ch9.USB_ENDPOINT_XFERTYPE_MASK fs_max, hs_max, ss_max = _MAX_PACKET_SIZE_DICT[transfer_type] if need_address: endpoint_kw['bEndpointAddress'] = index | ( endpoint_kw.get('bEndpointAddress', 0) & ch9.USB_DIR_IN ) klass = ( USBEndpointDescriptor if 'bRefresh' in endpoint_kw or 'bSynchAddress' in endpoint_kw else USBEndpointDescriptorNoAudio ) interval = endpoint_kw.pop('bInterval', _MARKER) if interval is _MARKER: fs_interval = hs_interval = 0 else: if transfer_type == ch9.USB_ENDPOINT_XFER_BULK: fs_interval = 0 hs_interval = interval else: # USB_ENDPOINT_XFER_ISOC or USB_ENDPOINT_XFER_INT fs_interval = max(1, min(255, round(interval))) # 8 is the number of microframes in a millisecond hs_interval = max( 1, min(16, int(round(1 + math.log(interval * 8, 2)))), ) packet_size = endpoint_kw.pop('wMaxPacketSize', _MARKER) if packet_size is _MARKER: fs_packet_size = fs_max hs_packet_size = hs_max ss_packet_size = ss_max else: fs_packet_size = min(fs_max, packet_size) hs_packet_size = min(hs_max, packet_size) ss_packet_size = min(ss_max, packet_size) fs_list.append(getDescriptor( klass, wMaxPacketSize=fs_max, bInterval=fs_interval, **endpoint_kw )) hs_list.append(getDescriptor( klass, wMaxPacketSize=hs_max, bInterval=hs_interval, **endpoint_kw )) ss_list.append(getDescriptor( klass, wMaxPacketSize=ss_max, bInterval=hs_interval, **endpoint_kw )) ss_companion_kw = endpoint.get('superspeed', _EMPTY_DICT) ss_list.append(getDescriptor( USBSSEPCompDescriptor, **ss_companion_kw )) ssp_iso_kw = endpoint.get('superspeed_iso', _EMPTY_DICT) if bool(ssp_iso_kw) != ( endpoint_kw.get('bmAttributes', 0) & ch9.USB_ENDPOINT_XFERTYPE_MASK == ch9.USB_ENDPOINT_XFER_ISOC and bool(ch9.USB_SS_SSP_ISOC_COMP( ss_companion_kw.get('bmAttributes', 0), )) ): raise ValueError('Inconsistent isochronous companion') if ssp_iso_kw: ss_list.append(getDescriptor( USBSSPIsocEndpointDescriptor, **ssp_iso_kw )) return (fs_list, hs_list, ss_list)
[ "def", "getInterfaceInAllSpeeds", "(", "interface", ",", "endpoint_list", ",", "class_descriptor_list", "=", "(", ")", ")", ":", "interface", "=", "getDescriptor", "(", "USBInterfaceDescriptor", ",", "bNumEndpoints", "=", "len", "(", "endpoint_list", ")", ",", "*", "*", "interface", ")", "class_descriptor_list", "=", "list", "(", "class_descriptor_list", ")", "fs_list", "=", "[", "interface", "]", "+", "class_descriptor_list", "hs_list", "=", "[", "interface", "]", "+", "class_descriptor_list", "ss_list", "=", "[", "interface", "]", "+", "class_descriptor_list", "need_address", "=", "(", "endpoint_list", "[", "0", "]", "[", "'endpoint'", "]", ".", "get", "(", "'bEndpointAddress'", ",", "0", ",", ")", "&", "~", "ch9", ".", "USB_DIR_IN", "==", "0", ")", "for", "index", ",", "endpoint", "in", "enumerate", "(", "endpoint_list", ",", "1", ")", ":", "endpoint_kw", "=", "endpoint", "[", "'endpoint'", "]", ".", "copy", "(", ")", "transfer_type", "=", "endpoint_kw", "[", "'bmAttributes'", "]", "&", "ch9", ".", "USB_ENDPOINT_XFERTYPE_MASK", "fs_max", ",", "hs_max", ",", "ss_max", "=", "_MAX_PACKET_SIZE_DICT", "[", "transfer_type", "]", "if", "need_address", ":", "endpoint_kw", "[", "'bEndpointAddress'", "]", "=", "index", "|", "(", "endpoint_kw", ".", "get", "(", "'bEndpointAddress'", ",", "0", ")", "&", "ch9", ".", "USB_DIR_IN", ")", "klass", "=", "(", "USBEndpointDescriptor", "if", "'bRefresh'", "in", "endpoint_kw", "or", "'bSynchAddress'", "in", "endpoint_kw", "else", "USBEndpointDescriptorNoAudio", ")", "interval", "=", "endpoint_kw", ".", "pop", "(", "'bInterval'", ",", "_MARKER", ")", "if", "interval", "is", "_MARKER", ":", "fs_interval", "=", "hs_interval", "=", "0", "else", ":", "if", "transfer_type", "==", "ch9", ".", "USB_ENDPOINT_XFER_BULK", ":", "fs_interval", "=", "0", "hs_interval", "=", "interval", "else", ":", "# USB_ENDPOINT_XFER_ISOC or USB_ENDPOINT_XFER_INT", "fs_interval", "=", "max", "(", "1", ",", "min", "(", "255", ",", "round", "(", "interval", ")", ")", ")", "# 8 is the number of microframes in a millisecond", "hs_interval", "=", "max", "(", "1", ",", "min", "(", "16", ",", "int", "(", "round", "(", "1", "+", "math", ".", "log", "(", "interval", "*", "8", ",", "2", ")", ")", ")", ")", ",", ")", "packet_size", "=", "endpoint_kw", ".", "pop", "(", "'wMaxPacketSize'", ",", "_MARKER", ")", "if", "packet_size", "is", "_MARKER", ":", "fs_packet_size", "=", "fs_max", "hs_packet_size", "=", "hs_max", "ss_packet_size", "=", "ss_max", "else", ":", "fs_packet_size", "=", "min", "(", "fs_max", ",", "packet_size", ")", "hs_packet_size", "=", "min", "(", "hs_max", ",", "packet_size", ")", "ss_packet_size", "=", "min", "(", "ss_max", ",", "packet_size", ")", "fs_list", ".", "append", "(", "getDescriptor", "(", "klass", ",", "wMaxPacketSize", "=", "fs_max", ",", "bInterval", "=", "fs_interval", ",", "*", "*", "endpoint_kw", ")", ")", "hs_list", ".", "append", "(", "getDescriptor", "(", "klass", ",", "wMaxPacketSize", "=", "hs_max", ",", "bInterval", "=", "hs_interval", ",", "*", "*", "endpoint_kw", ")", ")", "ss_list", ".", "append", "(", "getDescriptor", "(", "klass", ",", "wMaxPacketSize", "=", "ss_max", ",", "bInterval", "=", "hs_interval", ",", "*", "*", "endpoint_kw", ")", ")", "ss_companion_kw", "=", "endpoint", ".", "get", "(", "'superspeed'", ",", "_EMPTY_DICT", ")", "ss_list", ".", "append", "(", "getDescriptor", "(", "USBSSEPCompDescriptor", ",", "*", "*", "ss_companion_kw", ")", ")", "ssp_iso_kw", "=", "endpoint", ".", "get", "(", "'superspeed_iso'", ",", "_EMPTY_DICT", ")", "if", "bool", "(", "ssp_iso_kw", ")", "!=", "(", "endpoint_kw", ".", "get", "(", "'bmAttributes'", ",", "0", ")", "&", "ch9", ".", "USB_ENDPOINT_XFERTYPE_MASK", "==", "ch9", ".", "USB_ENDPOINT_XFER_ISOC", "and", "bool", "(", "ch9", ".", "USB_SS_SSP_ISOC_COMP", "(", "ss_companion_kw", ".", "get", "(", "'bmAttributes'", ",", "0", ")", ",", ")", ")", ")", ":", "raise", "ValueError", "(", "'Inconsistent isochronous companion'", ")", "if", "ssp_iso_kw", ":", "ss_list", ".", "append", "(", "getDescriptor", "(", "USBSSPIsocEndpointDescriptor", ",", "*", "*", "ssp_iso_kw", ")", ")", "return", "(", "fs_list", ",", "hs_list", ",", "ss_list", ")" ]
Produce similar fs, hs and ss interface and endpoints descriptors. Should be useful for devices desiring to work in all 3 speeds with maximum endpoint wMaxPacketSize. Reduces data duplication from descriptor declarations. Not intended to cover fancy combinations. interface (dict): Keyword arguments for getDescriptor(USBInterfaceDescriptor, ...) in all speeds. bNumEndpoints must not be provided. endpoint_list (list of dicts) Each dict represents an endpoint, and may contain the following items: - "endpoint": required, contains keyword arguments for getDescriptor(USBEndpointDescriptorNoAudio, ...) or getDescriptor(USBEndpointDescriptor, ...) The with-audio variant is picked when its extra fields are assigned a value. wMaxPacketSize may be missing, in which case it will be set to the maximum size for given speed and endpoint type. bmAttributes must be provided. If bEndpointAddress is zero (excluding direction bit) on the first endpoint, endpoints will be assigned their rank in this list, starting at 1. Their direction bit is preserved. If bInterval is present on a INT or ISO endpoint, it must be in millisecond units (but may not be an integer), and will be converted to the nearest integer millisecond for full-speed descriptor, and nearest possible interval for high- and super-speed descriptors. If bInterval is present on a BULK endpoint, it is set to zero on full-speed descriptor and used as provided on high- and super-speed descriptors. - "superspeed": optional, contains keyword arguments for getDescriptor(USBSSEPCompDescriptor, ...) - "superspeed_iso": optional, contains keyword arguments for getDescriptor(USBSSPIsocEndpointDescriptor, ...) Must be provided and non-empty only when endpoint is isochronous and "superspeed" dict has "bmAttributes" bit 7 set. class_descriptor (list of descriptors of any type) Descriptors to insert in all speeds between the interface descriptor and endpoint descriptors. Returns a 3-tuple of lists: - fs descriptors - hs descriptors - ss descriptors
[ "Produce", "similar", "fs", "hs", "and", "ss", "interface", "and", "endpoints", "descriptors", ".", "Should", "be", "useful", "for", "devices", "desiring", "to", "work", "in", "all", "3", "speeds", "with", "maximum", "endpoint", "wMaxPacketSize", ".", "Reduces", "data", "duplication", "from", "descriptor", "declarations", ".", "Not", "intended", "to", "cover", "fancy", "combinations", "." ]
e19f729bb47a7d1edd2488531af24551bb86726f
https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L120-L260
train
vpelletier/python-functionfs
functionfs/__init__.py
getDescriptor
def getDescriptor(klass, **kw): """ Automatically fills bLength and bDescriptorType. """ # XXX: ctypes Structure.__init__ ignores arguments which do not exist # as structure fields. So check it. # This is annoying, but not doing it is a huge waste of time for the # developer. empty = klass() assert hasattr(empty, 'bLength') assert hasattr(empty, 'bDescriptorType') unknown = [x for x in kw if not hasattr(empty, x)] if unknown: raise TypeError('Unknown fields %r' % (unknown, )) # XXX: not very pythonic... return klass( bLength=ctypes.sizeof(klass), # pylint: disable=protected-access bDescriptorType=klass._bDescriptorType, # pylint: enable=protected-access **kw )
python
def getDescriptor(klass, **kw): """ Automatically fills bLength and bDescriptorType. """ # XXX: ctypes Structure.__init__ ignores arguments which do not exist # as structure fields. So check it. # This is annoying, but not doing it is a huge waste of time for the # developer. empty = klass() assert hasattr(empty, 'bLength') assert hasattr(empty, 'bDescriptorType') unknown = [x for x in kw if not hasattr(empty, x)] if unknown: raise TypeError('Unknown fields %r' % (unknown, )) # XXX: not very pythonic... return klass( bLength=ctypes.sizeof(klass), # pylint: disable=protected-access bDescriptorType=klass._bDescriptorType, # pylint: enable=protected-access **kw )
[ "def", "getDescriptor", "(", "klass", ",", "*", "*", "kw", ")", ":", "# XXX: ctypes Structure.__init__ ignores arguments which do not exist", "# as structure fields. So check it.", "# This is annoying, but not doing it is a huge waste of time for the", "# developer.", "empty", "=", "klass", "(", ")", "assert", "hasattr", "(", "empty", ",", "'bLength'", ")", "assert", "hasattr", "(", "empty", ",", "'bDescriptorType'", ")", "unknown", "=", "[", "x", "for", "x", "in", "kw", "if", "not", "hasattr", "(", "empty", ",", "x", ")", "]", "if", "unknown", ":", "raise", "TypeError", "(", "'Unknown fields %r'", "%", "(", "unknown", ",", ")", ")", "# XXX: not very pythonic...", "return", "klass", "(", "bLength", "=", "ctypes", ".", "sizeof", "(", "klass", ")", ",", "# pylint: disable=protected-access", "bDescriptorType", "=", "klass", ".", "_bDescriptorType", ",", "# pylint: enable=protected-access", "*", "*", "kw", ")" ]
Automatically fills bLength and bDescriptorType.
[ "Automatically", "fills", "bLength", "and", "bDescriptorType", "." ]
e19f729bb47a7d1edd2488531af24551bb86726f
https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L262-L283
train
vpelletier/python-functionfs
functionfs/__init__.py
getOSDesc
def getOSDesc(interface, ext_list): """ Return an OS description header. interface (int) Related interface number. ext_list (list of OSExtCompatDesc or OSExtPropDesc) List of instances of extended descriptors. """ try: ext_type, = {type(x) for x in ext_list} except ValueError: raise TypeError('Extensions of a single type are required.') if issubclass(ext_type, OSExtCompatDesc): wIndex = 4 kw = { 'b': OSDescHeaderBCount( bCount=len(ext_list), Reserved=0, ), } elif issubclass(ext_type, OSExtPropDescHead): wIndex = 5 kw = { 'wCount': len(ext_list), } else: raise TypeError('Extensions of unexpected type') ext_list_type = ext_type * len(ext_list) klass = type( 'OSDesc', (OSDescHeader, ), { '_fields_': [ ('ext_list', ext_list_type), ], }, ) return klass( interface=interface, dwLength=ctypes.sizeof(klass), bcdVersion=1, wIndex=wIndex, ext_list=ext_list_type(*ext_list), **kw )
python
def getOSDesc(interface, ext_list): """ Return an OS description header. interface (int) Related interface number. ext_list (list of OSExtCompatDesc or OSExtPropDesc) List of instances of extended descriptors. """ try: ext_type, = {type(x) for x in ext_list} except ValueError: raise TypeError('Extensions of a single type are required.') if issubclass(ext_type, OSExtCompatDesc): wIndex = 4 kw = { 'b': OSDescHeaderBCount( bCount=len(ext_list), Reserved=0, ), } elif issubclass(ext_type, OSExtPropDescHead): wIndex = 5 kw = { 'wCount': len(ext_list), } else: raise TypeError('Extensions of unexpected type') ext_list_type = ext_type * len(ext_list) klass = type( 'OSDesc', (OSDescHeader, ), { '_fields_': [ ('ext_list', ext_list_type), ], }, ) return klass( interface=interface, dwLength=ctypes.sizeof(klass), bcdVersion=1, wIndex=wIndex, ext_list=ext_list_type(*ext_list), **kw )
[ "def", "getOSDesc", "(", "interface", ",", "ext_list", ")", ":", "try", ":", "ext_type", ",", "=", "{", "type", "(", "x", ")", "for", "x", "in", "ext_list", "}", "except", "ValueError", ":", "raise", "TypeError", "(", "'Extensions of a single type are required.'", ")", "if", "issubclass", "(", "ext_type", ",", "OSExtCompatDesc", ")", ":", "wIndex", "=", "4", "kw", "=", "{", "'b'", ":", "OSDescHeaderBCount", "(", "bCount", "=", "len", "(", "ext_list", ")", ",", "Reserved", "=", "0", ",", ")", ",", "}", "elif", "issubclass", "(", "ext_type", ",", "OSExtPropDescHead", ")", ":", "wIndex", "=", "5", "kw", "=", "{", "'wCount'", ":", "len", "(", "ext_list", ")", ",", "}", "else", ":", "raise", "TypeError", "(", "'Extensions of unexpected type'", ")", "ext_list_type", "=", "ext_type", "*", "len", "(", "ext_list", ")", "klass", "=", "type", "(", "'OSDesc'", ",", "(", "OSDescHeader", ",", ")", ",", "{", "'_fields_'", ":", "[", "(", "'ext_list'", ",", "ext_list_type", ")", ",", "]", ",", "}", ",", ")", "return", "klass", "(", "interface", "=", "interface", ",", "dwLength", "=", "ctypes", ".", "sizeof", "(", "klass", ")", ",", "bcdVersion", "=", "1", ",", "wIndex", "=", "wIndex", ",", "ext_list", "=", "ext_list_type", "(", "*", "ext_list", ")", ",", "*", "*", "kw", ")" ]
Return an OS description header. interface (int) Related interface number. ext_list (list of OSExtCompatDesc or OSExtPropDesc) List of instances of extended descriptors.
[ "Return", "an", "OS", "description", "header", ".", "interface", "(", "int", ")", "Related", "interface", "number", ".", "ext_list", "(", "list", "of", "OSExtCompatDesc", "or", "OSExtPropDesc", ")", "List", "of", "instances", "of", "extended", "descriptors", "." ]
e19f729bb47a7d1edd2488531af24551bb86726f
https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L285-L329
train
vpelletier/python-functionfs
functionfs/__init__.py
getOSExtPropDesc
def getOSExtPropDesc(data_type, name, value): """ Returns an OS extension property descriptor. data_type (int) See wPropertyDataType documentation. name (string) See PropertyName documentation. value (string) See PropertyData documentation. NULL chars must be explicitely included in the value when needed, this function does not add any terminating NULL for example. """ klass = type( 'OSExtPropDesc', (OSExtPropDescHead, ), { '_fields_': [ ('bPropertyName', ctypes.c_char * len(name)), ('dwPropertyDataLength', le32), ('bProperty', ctypes.c_char * len(value)), ], } ) return klass( dwSize=ctypes.sizeof(klass), dwPropertyDataType=data_type, wPropertyNameLength=len(name), bPropertyName=name, dwPropertyDataLength=len(value), bProperty=value, )
python
def getOSExtPropDesc(data_type, name, value): """ Returns an OS extension property descriptor. data_type (int) See wPropertyDataType documentation. name (string) See PropertyName documentation. value (string) See PropertyData documentation. NULL chars must be explicitely included in the value when needed, this function does not add any terminating NULL for example. """ klass = type( 'OSExtPropDesc', (OSExtPropDescHead, ), { '_fields_': [ ('bPropertyName', ctypes.c_char * len(name)), ('dwPropertyDataLength', le32), ('bProperty', ctypes.c_char * len(value)), ], } ) return klass( dwSize=ctypes.sizeof(klass), dwPropertyDataType=data_type, wPropertyNameLength=len(name), bPropertyName=name, dwPropertyDataLength=len(value), bProperty=value, )
[ "def", "getOSExtPropDesc", "(", "data_type", ",", "name", ",", "value", ")", ":", "klass", "=", "type", "(", "'OSExtPropDesc'", ",", "(", "OSExtPropDescHead", ",", ")", ",", "{", "'_fields_'", ":", "[", "(", "'bPropertyName'", ",", "ctypes", ".", "c_char", "*", "len", "(", "name", ")", ")", ",", "(", "'dwPropertyDataLength'", ",", "le32", ")", ",", "(", "'bProperty'", ",", "ctypes", ".", "c_char", "*", "len", "(", "value", ")", ")", ",", "]", ",", "}", ")", "return", "klass", "(", "dwSize", "=", "ctypes", ".", "sizeof", "(", "klass", ")", ",", "dwPropertyDataType", "=", "data_type", ",", "wPropertyNameLength", "=", "len", "(", "name", ")", ",", "bPropertyName", "=", "name", ",", "dwPropertyDataLength", "=", "len", "(", "value", ")", ",", "bProperty", "=", "value", ",", ")" ]
Returns an OS extension property descriptor. data_type (int) See wPropertyDataType documentation. name (string) See PropertyName documentation. value (string) See PropertyData documentation. NULL chars must be explicitely included in the value when needed, this function does not add any terminating NULL for example.
[ "Returns", "an", "OS", "extension", "property", "descriptor", ".", "data_type", "(", "int", ")", "See", "wPropertyDataType", "documentation", ".", "name", "(", "string", ")", "See", "PropertyName", "documentation", ".", "value", "(", "string", ")", "See", "PropertyData", "documentation", ".", "NULL", "chars", "must", "be", "explicitely", "included", "in", "the", "value", "when", "needed", "this", "function", "does", "not", "add", "any", "terminating", "NULL", "for", "example", "." ]
e19f729bb47a7d1edd2488531af24551bb86726f
https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L331-L361
train
vpelletier/python-functionfs
functionfs/__init__.py
getDescsV2
def getDescsV2(flags, fs_list=(), hs_list=(), ss_list=(), os_list=()): """ Return a FunctionFS descriptor suitable for serialisation. flags (int) Any combination of VIRTUAL_ADDR, EVENTFD, ALL_CTRL_RECIP, CONFIG0_SETUP. {fs,hs,ss,os}_list (list of descriptors) Instances of the following classes: {fs,hs,ss}_list: USBInterfaceDescriptor USBEndpointDescriptorNoAudio USBEndpointDescriptor USBSSEPCompDescriptor USBSSPIsocEndpointDescriptor USBOTGDescriptor USBOTG20Descriptor USBInterfaceAssocDescriptor TODO: HID All (non-empty) lists must define the same number of interfaces and endpoints, and endpoint descriptors must be given in the same order, bEndpointAddress-wise. os_list: OSDesc """ count_field_list = [] descr_field_list = [] kw = {} for descriptor_list, flag, prefix, allowed_descriptor_klass in ( (fs_list, HAS_FS_DESC, 'fs', USBDescriptorHeader), (hs_list, HAS_HS_DESC, 'hs', USBDescriptorHeader), (ss_list, HAS_SS_DESC, 'ss', USBDescriptorHeader), (os_list, HAS_MS_OS_DESC, 'os', OSDescHeader), ): if descriptor_list: for index, descriptor in enumerate(descriptor_list): if not isinstance(descriptor, allowed_descriptor_klass): raise TypeError( 'Descriptor %r of unexpected type: %r' % ( index, type(descriptor), ), ) descriptor_map = [ ('desc_%i' % x, y) for x, y in enumerate(descriptor_list) ] flags |= flag count_name = prefix + 'count' descr_name = prefix + 'descr' count_field_list.append((count_name, le32)) descr_type = type( 't_' + descr_name, (ctypes.LittleEndianStructure, ), { '_pack_': 1, '_fields_': [ (x, type(y)) for x, y in descriptor_map ], } ) descr_field_list.append((descr_name, descr_type)) kw[count_name] = len(descriptor_map) kw[descr_name] = descr_type(**dict(descriptor_map)) elif flags & flag: raise ValueError( 'Flag %r set but descriptor list empty, cannot generate type.' % ( FLAGS.get(flag), ) ) klass = type( 'DescsV2_0x%02x' % ( flags & ( HAS_FS_DESC | HAS_HS_DESC | HAS_SS_DESC | HAS_MS_OS_DESC ), # XXX: include contained descriptors type information ? (and name ?) ), (DescsHeadV2, ), { '_fields_': count_field_list + descr_field_list, }, ) return klass( magic=DESCRIPTORS_MAGIC_V2, length=ctypes.sizeof(klass), flags=flags, **kw )
python
def getDescsV2(flags, fs_list=(), hs_list=(), ss_list=(), os_list=()): """ Return a FunctionFS descriptor suitable for serialisation. flags (int) Any combination of VIRTUAL_ADDR, EVENTFD, ALL_CTRL_RECIP, CONFIG0_SETUP. {fs,hs,ss,os}_list (list of descriptors) Instances of the following classes: {fs,hs,ss}_list: USBInterfaceDescriptor USBEndpointDescriptorNoAudio USBEndpointDescriptor USBSSEPCompDescriptor USBSSPIsocEndpointDescriptor USBOTGDescriptor USBOTG20Descriptor USBInterfaceAssocDescriptor TODO: HID All (non-empty) lists must define the same number of interfaces and endpoints, and endpoint descriptors must be given in the same order, bEndpointAddress-wise. os_list: OSDesc """ count_field_list = [] descr_field_list = [] kw = {} for descriptor_list, flag, prefix, allowed_descriptor_klass in ( (fs_list, HAS_FS_DESC, 'fs', USBDescriptorHeader), (hs_list, HAS_HS_DESC, 'hs', USBDescriptorHeader), (ss_list, HAS_SS_DESC, 'ss', USBDescriptorHeader), (os_list, HAS_MS_OS_DESC, 'os', OSDescHeader), ): if descriptor_list: for index, descriptor in enumerate(descriptor_list): if not isinstance(descriptor, allowed_descriptor_klass): raise TypeError( 'Descriptor %r of unexpected type: %r' % ( index, type(descriptor), ), ) descriptor_map = [ ('desc_%i' % x, y) for x, y in enumerate(descriptor_list) ] flags |= flag count_name = prefix + 'count' descr_name = prefix + 'descr' count_field_list.append((count_name, le32)) descr_type = type( 't_' + descr_name, (ctypes.LittleEndianStructure, ), { '_pack_': 1, '_fields_': [ (x, type(y)) for x, y in descriptor_map ], } ) descr_field_list.append((descr_name, descr_type)) kw[count_name] = len(descriptor_map) kw[descr_name] = descr_type(**dict(descriptor_map)) elif flags & flag: raise ValueError( 'Flag %r set but descriptor list empty, cannot generate type.' % ( FLAGS.get(flag), ) ) klass = type( 'DescsV2_0x%02x' % ( flags & ( HAS_FS_DESC | HAS_HS_DESC | HAS_SS_DESC | HAS_MS_OS_DESC ), # XXX: include contained descriptors type information ? (and name ?) ), (DescsHeadV2, ), { '_fields_': count_field_list + descr_field_list, }, ) return klass( magic=DESCRIPTORS_MAGIC_V2, length=ctypes.sizeof(klass), flags=flags, **kw )
[ "def", "getDescsV2", "(", "flags", ",", "fs_list", "=", "(", ")", ",", "hs_list", "=", "(", ")", ",", "ss_list", "=", "(", ")", ",", "os_list", "=", "(", ")", ")", ":", "count_field_list", "=", "[", "]", "descr_field_list", "=", "[", "]", "kw", "=", "{", "}", "for", "descriptor_list", ",", "flag", ",", "prefix", ",", "allowed_descriptor_klass", "in", "(", "(", "fs_list", ",", "HAS_FS_DESC", ",", "'fs'", ",", "USBDescriptorHeader", ")", ",", "(", "hs_list", ",", "HAS_HS_DESC", ",", "'hs'", ",", "USBDescriptorHeader", ")", ",", "(", "ss_list", ",", "HAS_SS_DESC", ",", "'ss'", ",", "USBDescriptorHeader", ")", ",", "(", "os_list", ",", "HAS_MS_OS_DESC", ",", "'os'", ",", "OSDescHeader", ")", ",", ")", ":", "if", "descriptor_list", ":", "for", "index", ",", "descriptor", "in", "enumerate", "(", "descriptor_list", ")", ":", "if", "not", "isinstance", "(", "descriptor", ",", "allowed_descriptor_klass", ")", ":", "raise", "TypeError", "(", "'Descriptor %r of unexpected type: %r'", "%", "(", "index", ",", "type", "(", "descriptor", ")", ",", ")", ",", ")", "descriptor_map", "=", "[", "(", "'desc_%i'", "%", "x", ",", "y", ")", "for", "x", ",", "y", "in", "enumerate", "(", "descriptor_list", ")", "]", "flags", "|=", "flag", "count_name", "=", "prefix", "+", "'count'", "descr_name", "=", "prefix", "+", "'descr'", "count_field_list", ".", "append", "(", "(", "count_name", ",", "le32", ")", ")", "descr_type", "=", "type", "(", "'t_'", "+", "descr_name", ",", "(", "ctypes", ".", "LittleEndianStructure", ",", ")", ",", "{", "'_pack_'", ":", "1", ",", "'_fields_'", ":", "[", "(", "x", ",", "type", "(", "y", ")", ")", "for", "x", ",", "y", "in", "descriptor_map", "]", ",", "}", ")", "descr_field_list", ".", "append", "(", "(", "descr_name", ",", "descr_type", ")", ")", "kw", "[", "count_name", "]", "=", "len", "(", "descriptor_map", ")", "kw", "[", "descr_name", "]", "=", "descr_type", "(", "*", "*", "dict", "(", "descriptor_map", ")", ")", "elif", "flags", "&", "flag", ":", "raise", "ValueError", "(", "'Flag %r set but descriptor list empty, cannot generate type.'", "%", "(", "FLAGS", ".", "get", "(", "flag", ")", ",", ")", ")", "klass", "=", "type", "(", "'DescsV2_0x%02x'", "%", "(", "flags", "&", "(", "HAS_FS_DESC", "|", "HAS_HS_DESC", "|", "HAS_SS_DESC", "|", "HAS_MS_OS_DESC", ")", ",", "# XXX: include contained descriptors type information ? (and name ?)", ")", ",", "(", "DescsHeadV2", ",", ")", ",", "{", "'_fields_'", ":", "count_field_list", "+", "descr_field_list", ",", "}", ",", ")", "return", "klass", "(", "magic", "=", "DESCRIPTORS_MAGIC_V2", ",", "length", "=", "ctypes", ".", "sizeof", "(", "klass", ")", ",", "flags", "=", "flags", ",", "*", "*", "kw", ")" ]
Return a FunctionFS descriptor suitable for serialisation. flags (int) Any combination of VIRTUAL_ADDR, EVENTFD, ALL_CTRL_RECIP, CONFIG0_SETUP. {fs,hs,ss,os}_list (list of descriptors) Instances of the following classes: {fs,hs,ss}_list: USBInterfaceDescriptor USBEndpointDescriptorNoAudio USBEndpointDescriptor USBSSEPCompDescriptor USBSSPIsocEndpointDescriptor USBOTGDescriptor USBOTG20Descriptor USBInterfaceAssocDescriptor TODO: HID All (non-empty) lists must define the same number of interfaces and endpoints, and endpoint descriptors must be given in the same order, bEndpointAddress-wise. os_list: OSDesc
[ "Return", "a", "FunctionFS", "descriptor", "suitable", "for", "serialisation", "." ]
e19f729bb47a7d1edd2488531af24551bb86726f
https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L389-L480
train
vpelletier/python-functionfs
functionfs/__init__.py
getStrings
def getStrings(lang_dict): """ Return a FunctionFS descriptor suitable for serialisation. lang_dict (dict) Key: language ID (ex: 0x0409 for en-us) Value: list of unicode objects All values must have the same number of items. """ field_list = [] kw = {} try: str_count = len(next(iter(lang_dict.values()))) except StopIteration: str_count = 0 else: for lang, string_list in lang_dict.items(): if len(string_list) != str_count: raise ValueError('All values must have the same string count.') field_id = 'strings_%04x' % lang strings = b'\x00'.join(x.encode('utf-8') for x in string_list) + b'\x00' field_type = type( 'String', (StringBase, ), { '_fields_': [ ('strings', ctypes.c_char * len(strings)), ], }, ) field_list.append((field_id, field_type)) kw[field_id] = field_type( lang=lang, strings=strings, ) klass = type( 'Strings', (StringsHead, ), { '_fields_': field_list, }, ) return klass( magic=STRINGS_MAGIC, length=ctypes.sizeof(klass), str_count=str_count, lang_count=len(lang_dict), **kw )
python
def getStrings(lang_dict): """ Return a FunctionFS descriptor suitable for serialisation. lang_dict (dict) Key: language ID (ex: 0x0409 for en-us) Value: list of unicode objects All values must have the same number of items. """ field_list = [] kw = {} try: str_count = len(next(iter(lang_dict.values()))) except StopIteration: str_count = 0 else: for lang, string_list in lang_dict.items(): if len(string_list) != str_count: raise ValueError('All values must have the same string count.') field_id = 'strings_%04x' % lang strings = b'\x00'.join(x.encode('utf-8') for x in string_list) + b'\x00' field_type = type( 'String', (StringBase, ), { '_fields_': [ ('strings', ctypes.c_char * len(strings)), ], }, ) field_list.append((field_id, field_type)) kw[field_id] = field_type( lang=lang, strings=strings, ) klass = type( 'Strings', (StringsHead, ), { '_fields_': field_list, }, ) return klass( magic=STRINGS_MAGIC, length=ctypes.sizeof(klass), str_count=str_count, lang_count=len(lang_dict), **kw )
[ "def", "getStrings", "(", "lang_dict", ")", ":", "field_list", "=", "[", "]", "kw", "=", "{", "}", "try", ":", "str_count", "=", "len", "(", "next", "(", "iter", "(", "lang_dict", ".", "values", "(", ")", ")", ")", ")", "except", "StopIteration", ":", "str_count", "=", "0", "else", ":", "for", "lang", ",", "string_list", "in", "lang_dict", ".", "items", "(", ")", ":", "if", "len", "(", "string_list", ")", "!=", "str_count", ":", "raise", "ValueError", "(", "'All values must have the same string count.'", ")", "field_id", "=", "'strings_%04x'", "%", "lang", "strings", "=", "b'\\x00'", ".", "join", "(", "x", ".", "encode", "(", "'utf-8'", ")", "for", "x", "in", "string_list", ")", "+", "b'\\x00'", "field_type", "=", "type", "(", "'String'", ",", "(", "StringBase", ",", ")", ",", "{", "'_fields_'", ":", "[", "(", "'strings'", ",", "ctypes", ".", "c_char", "*", "len", "(", "strings", ")", ")", ",", "]", ",", "}", ",", ")", "field_list", ".", "append", "(", "(", "field_id", ",", "field_type", ")", ")", "kw", "[", "field_id", "]", "=", "field_type", "(", "lang", "=", "lang", ",", "strings", "=", "strings", ",", ")", "klass", "=", "type", "(", "'Strings'", ",", "(", "StringsHead", ",", ")", ",", "{", "'_fields_'", ":", "field_list", ",", "}", ",", ")", "return", "klass", "(", "magic", "=", "STRINGS_MAGIC", ",", "length", "=", "ctypes", ".", "sizeof", "(", "klass", ")", ",", "str_count", "=", "str_count", ",", "lang_count", "=", "len", "(", "lang_dict", ")", ",", "*", "*", "kw", ")" ]
Return a FunctionFS descriptor suitable for serialisation. lang_dict (dict) Key: language ID (ex: 0x0409 for en-us) Value: list of unicode objects All values must have the same number of items.
[ "Return", "a", "FunctionFS", "descriptor", "suitable", "for", "serialisation", "." ]
e19f729bb47a7d1edd2488531af24551bb86726f
https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L482-L530
train
vpelletier/python-functionfs
functionfs/__init__.py
serialise
def serialise(structure): """ structure (ctypes.Structure) The structure to serialise. Returns a ctypes.c_char array. Does not copy memory. """ return ctypes.cast( ctypes.pointer(structure), ctypes.POINTER(ctypes.c_char * ctypes.sizeof(structure)), ).contents
python
def serialise(structure): """ structure (ctypes.Structure) The structure to serialise. Returns a ctypes.c_char array. Does not copy memory. """ return ctypes.cast( ctypes.pointer(structure), ctypes.POINTER(ctypes.c_char * ctypes.sizeof(structure)), ).contents
[ "def", "serialise", "(", "structure", ")", ":", "return", "ctypes", ".", "cast", "(", "ctypes", ".", "pointer", "(", "structure", ")", ",", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_char", "*", "ctypes", ".", "sizeof", "(", "structure", ")", ")", ",", ")", ".", "contents" ]
structure (ctypes.Structure) The structure to serialise. Returns a ctypes.c_char array. Does not copy memory.
[ "structure", "(", "ctypes", ".", "Structure", ")", "The", "structure", "to", "serialise", "." ]
e19f729bb47a7d1edd2488531af24551bb86726f
https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L532-L543
train
vpelletier/python-functionfs
functionfs/__init__.py
Endpoint0File.halt
def halt(self, request_type): """ Halt current endpoint. """ try: if request_type & ch9.USB_DIR_IN: self.read(0) else: self.write(b'') except IOError as exc: if exc.errno != errno.EL2HLT: raise else: raise ValueError('halt did not return EL2HLT ?')
python
def halt(self, request_type): """ Halt current endpoint. """ try: if request_type & ch9.USB_DIR_IN: self.read(0) else: self.write(b'') except IOError as exc: if exc.errno != errno.EL2HLT: raise else: raise ValueError('halt did not return EL2HLT ?')
[ "def", "halt", "(", "self", ",", "request_type", ")", ":", "try", ":", "if", "request_type", "&", "ch9", ".", "USB_DIR_IN", ":", "self", ".", "read", "(", "0", ")", "else", ":", "self", ".", "write", "(", "b''", ")", "except", "IOError", "as", "exc", ":", "if", "exc", ".", "errno", "!=", "errno", ".", "EL2HLT", ":", "raise", "else", ":", "raise", "ValueError", "(", "'halt did not return EL2HLT ?'", ")" ]
Halt current endpoint.
[ "Halt", "current", "endpoint", "." ]
e19f729bb47a7d1edd2488531af24551bb86726f
https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L559-L572
train
vpelletier/python-functionfs
functionfs/__init__.py
Endpoint0File.getRealInterfaceNumber
def getRealInterfaceNumber(self, interface): """ Returns the host-visible interface number, or None if there is no such interface. """ try: return self._ioctl(INTERFACE_REVMAP, interface) except IOError as exc: if exc.errno == errno.EDOM: return None raise
python
def getRealInterfaceNumber(self, interface): """ Returns the host-visible interface number, or None if there is no such interface. """ try: return self._ioctl(INTERFACE_REVMAP, interface) except IOError as exc: if exc.errno == errno.EDOM: return None raise
[ "def", "getRealInterfaceNumber", "(", "self", ",", "interface", ")", ":", "try", ":", "return", "self", ".", "_ioctl", "(", "INTERFACE_REVMAP", ",", "interface", ")", "except", "IOError", "as", "exc", ":", "if", "exc", ".", "errno", "==", "errno", ".", "EDOM", ":", "return", "None", "raise" ]
Returns the host-visible interface number, or None if there is no such interface.
[ "Returns", "the", "host", "-", "visible", "interface", "number", "or", "None", "if", "there", "is", "no", "such", "interface", "." ]
e19f729bb47a7d1edd2488531af24551bb86726f
https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L574-L584
train
vpelletier/python-functionfs
functionfs/__init__.py
EndpointFile.getDescriptor
def getDescriptor(self): """ Returns the currently active endpoint descriptor (depending on current USB speed). """ result = USBEndpointDescriptor() self._ioctl(ENDPOINT_DESC, result, True) return result
python
def getDescriptor(self): """ Returns the currently active endpoint descriptor (depending on current USB speed). """ result = USBEndpointDescriptor() self._ioctl(ENDPOINT_DESC, result, True) return result
[ "def", "getDescriptor", "(", "self", ")", ":", "result", "=", "USBEndpointDescriptor", "(", ")", "self", ".", "_ioctl", "(", "ENDPOINT_DESC", ",", "result", ",", "True", ")", "return", "result" ]
Returns the currently active endpoint descriptor (depending on current USB speed).
[ "Returns", "the", "currently", "active", "endpoint", "descriptor", "(", "depending", "on", "current", "USB", "speed", ")", "." ]
e19f729bb47a7d1edd2488531af24551bb86726f
https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L621-L628
train
vpelletier/python-functionfs
functionfs/__init__.py
EndpointFile.halt
def halt(self): """ Halt current endpoint. """ try: self._halt() except IOError as exc: if exc.errno != errno.EBADMSG: raise else: raise ValueError('halt did not return EBADMSG ?') self._halted = True
python
def halt(self): """ Halt current endpoint. """ try: self._halt() except IOError as exc: if exc.errno != errno.EBADMSG: raise else: raise ValueError('halt did not return EBADMSG ?') self._halted = True
[ "def", "halt", "(", "self", ")", ":", "try", ":", "self", ".", "_halt", "(", ")", "except", "IOError", "as", "exc", ":", "if", "exc", ".", "errno", "!=", "errno", ".", "EBADMSG", ":", "raise", "else", ":", "raise", "ValueError", "(", "'halt did not return EBADMSG ?'", ")", "self", ".", "_halted", "=", "True" ]
Halt current endpoint.
[ "Halt", "current", "endpoint", "." ]
e19f729bb47a7d1edd2488531af24551bb86726f
https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L633-L644
train
vpelletier/python-functionfs
functionfs/__init__.py
Function.close
def close(self): """ Close all endpoint file descriptors. """ ep_list = self._ep_list while ep_list: ep_list.pop().close() self._closed = True
python
def close(self): """ Close all endpoint file descriptors. """ ep_list = self._ep_list while ep_list: ep_list.pop().close() self._closed = True
[ "def", "close", "(", "self", ")", ":", "ep_list", "=", "self", ".", "_ep_list", "while", "ep_list", ":", "ep_list", ".", "pop", "(", ")", ".", "close", "(", ")", "self", ".", "_closed", "=", "True" ]
Close all endpoint file descriptors.
[ "Close", "all", "endpoint", "file", "descriptors", "." ]
e19f729bb47a7d1edd2488531af24551bb86726f
https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L800-L807
train
vpelletier/python-functionfs
functionfs/__init__.py
Function.onSetup
def onSetup(self, request_type, request, value, index, length): """ Called when a setup USB transaction was received. Default implementation: - handles USB_REQ_GET_STATUS on interface and endpoints - handles USB_REQ_CLEAR_FEATURE(USB_ENDPOINT_HALT) on endpoints - handles USB_REQ_SET_FEATURE(USB_ENDPOINT_HALT) on endpoints - halts on everything else If this method raises anything, endpoint 0 is halted by its caller and exception is let through. May be overridden in subclass. """ if (request_type & ch9.USB_TYPE_MASK) == ch9.USB_TYPE_STANDARD: recipient = request_type & ch9.USB_RECIP_MASK is_in = (request_type & ch9.USB_DIR_IN) == ch9.USB_DIR_IN if request == ch9.USB_REQ_GET_STATUS: if is_in and length == 2: if recipient == ch9.USB_RECIP_INTERFACE: if value == 0: status = 0 if index == 0: if self.function_remote_wakeup_capable: status |= 1 << 0 if self.function_remote_wakeup: status |= 1 << 1 self.ep0.write(struct.pack('<H', status)[:length]) return elif recipient == ch9.USB_RECIP_ENDPOINT: if value == 0: try: endpoint = self.getEndpoint(index) except IndexError: pass else: status = 0 if endpoint.isHalted(): status |= 1 << 0 self.ep0.write( struct.pack('<H', status)[:length], ) return elif request == ch9.USB_REQ_CLEAR_FEATURE: if not is_in and length == 0: if recipient == ch9.USB_RECIP_ENDPOINT: if value == ch9.USB_ENDPOINT_HALT: try: endpoint = self.getEndpoint(index) except IndexError: pass else: endpoint.clearHalt() self.ep0.read(0) return elif recipient == ch9.USB_RECIP_INTERFACE: if value == ch9.USB_INTRF_FUNC_SUSPEND: if self.function_remote_wakeup_capable: self.disableRemoteWakeup() self.ep0.read(0) return elif request == ch9.USB_REQ_SET_FEATURE: if not is_in and length == 0: if recipient == ch9.USB_RECIP_ENDPOINT: if value == ch9.USB_ENDPOINT_HALT: try: endpoint = self.getEndpoint(index) except IndexError: pass else: endpoint.halt() self.ep0.read(0) return elif recipient == ch9.USB_RECIP_INTERFACE: if value == ch9.USB_INTRF_FUNC_SUSPEND: if self.function_remote_wakeup_capable: self.enableRemoteWakeup() self.ep0.read(0) return self.ep0.halt(request_type)
python
def onSetup(self, request_type, request, value, index, length): """ Called when a setup USB transaction was received. Default implementation: - handles USB_REQ_GET_STATUS on interface and endpoints - handles USB_REQ_CLEAR_FEATURE(USB_ENDPOINT_HALT) on endpoints - handles USB_REQ_SET_FEATURE(USB_ENDPOINT_HALT) on endpoints - halts on everything else If this method raises anything, endpoint 0 is halted by its caller and exception is let through. May be overridden in subclass. """ if (request_type & ch9.USB_TYPE_MASK) == ch9.USB_TYPE_STANDARD: recipient = request_type & ch9.USB_RECIP_MASK is_in = (request_type & ch9.USB_DIR_IN) == ch9.USB_DIR_IN if request == ch9.USB_REQ_GET_STATUS: if is_in and length == 2: if recipient == ch9.USB_RECIP_INTERFACE: if value == 0: status = 0 if index == 0: if self.function_remote_wakeup_capable: status |= 1 << 0 if self.function_remote_wakeup: status |= 1 << 1 self.ep0.write(struct.pack('<H', status)[:length]) return elif recipient == ch9.USB_RECIP_ENDPOINT: if value == 0: try: endpoint = self.getEndpoint(index) except IndexError: pass else: status = 0 if endpoint.isHalted(): status |= 1 << 0 self.ep0.write( struct.pack('<H', status)[:length], ) return elif request == ch9.USB_REQ_CLEAR_FEATURE: if not is_in and length == 0: if recipient == ch9.USB_RECIP_ENDPOINT: if value == ch9.USB_ENDPOINT_HALT: try: endpoint = self.getEndpoint(index) except IndexError: pass else: endpoint.clearHalt() self.ep0.read(0) return elif recipient == ch9.USB_RECIP_INTERFACE: if value == ch9.USB_INTRF_FUNC_SUSPEND: if self.function_remote_wakeup_capable: self.disableRemoteWakeup() self.ep0.read(0) return elif request == ch9.USB_REQ_SET_FEATURE: if not is_in and length == 0: if recipient == ch9.USB_RECIP_ENDPOINT: if value == ch9.USB_ENDPOINT_HALT: try: endpoint = self.getEndpoint(index) except IndexError: pass else: endpoint.halt() self.ep0.read(0) return elif recipient == ch9.USB_RECIP_INTERFACE: if value == ch9.USB_INTRF_FUNC_SUSPEND: if self.function_remote_wakeup_capable: self.enableRemoteWakeup() self.ep0.read(0) return self.ep0.halt(request_type)
[ "def", "onSetup", "(", "self", ",", "request_type", ",", "request", ",", "value", ",", "index", ",", "length", ")", ":", "if", "(", "request_type", "&", "ch9", ".", "USB_TYPE_MASK", ")", "==", "ch9", ".", "USB_TYPE_STANDARD", ":", "recipient", "=", "request_type", "&", "ch9", ".", "USB_RECIP_MASK", "is_in", "=", "(", "request_type", "&", "ch9", ".", "USB_DIR_IN", ")", "==", "ch9", ".", "USB_DIR_IN", "if", "request", "==", "ch9", ".", "USB_REQ_GET_STATUS", ":", "if", "is_in", "and", "length", "==", "2", ":", "if", "recipient", "==", "ch9", ".", "USB_RECIP_INTERFACE", ":", "if", "value", "==", "0", ":", "status", "=", "0", "if", "index", "==", "0", ":", "if", "self", ".", "function_remote_wakeup_capable", ":", "status", "|=", "1", "<<", "0", "if", "self", ".", "function_remote_wakeup", ":", "status", "|=", "1", "<<", "1", "self", ".", "ep0", ".", "write", "(", "struct", ".", "pack", "(", "'<H'", ",", "status", ")", "[", ":", "length", "]", ")", "return", "elif", "recipient", "==", "ch9", ".", "USB_RECIP_ENDPOINT", ":", "if", "value", "==", "0", ":", "try", ":", "endpoint", "=", "self", ".", "getEndpoint", "(", "index", ")", "except", "IndexError", ":", "pass", "else", ":", "status", "=", "0", "if", "endpoint", ".", "isHalted", "(", ")", ":", "status", "|=", "1", "<<", "0", "self", ".", "ep0", ".", "write", "(", "struct", ".", "pack", "(", "'<H'", ",", "status", ")", "[", ":", "length", "]", ",", ")", "return", "elif", "request", "==", "ch9", ".", "USB_REQ_CLEAR_FEATURE", ":", "if", "not", "is_in", "and", "length", "==", "0", ":", "if", "recipient", "==", "ch9", ".", "USB_RECIP_ENDPOINT", ":", "if", "value", "==", "ch9", ".", "USB_ENDPOINT_HALT", ":", "try", ":", "endpoint", "=", "self", ".", "getEndpoint", "(", "index", ")", "except", "IndexError", ":", "pass", "else", ":", "endpoint", ".", "clearHalt", "(", ")", "self", ".", "ep0", ".", "read", "(", "0", ")", "return", "elif", "recipient", "==", "ch9", ".", "USB_RECIP_INTERFACE", ":", "if", "value", "==", "ch9", ".", "USB_INTRF_FUNC_SUSPEND", ":", "if", "self", ".", "function_remote_wakeup_capable", ":", "self", ".", "disableRemoteWakeup", "(", ")", "self", ".", "ep0", ".", "read", "(", "0", ")", "return", "elif", "request", "==", "ch9", ".", "USB_REQ_SET_FEATURE", ":", "if", "not", "is_in", "and", "length", "==", "0", ":", "if", "recipient", "==", "ch9", ".", "USB_RECIP_ENDPOINT", ":", "if", "value", "==", "ch9", ".", "USB_ENDPOINT_HALT", ":", "try", ":", "endpoint", "=", "self", ".", "getEndpoint", "(", "index", ")", "except", "IndexError", ":", "pass", "else", ":", "endpoint", ".", "halt", "(", ")", "self", ".", "ep0", ".", "read", "(", "0", ")", "return", "elif", "recipient", "==", "ch9", ".", "USB_RECIP_INTERFACE", ":", "if", "value", "==", "ch9", ".", "USB_INTRF_FUNC_SUSPEND", ":", "if", "self", ".", "function_remote_wakeup_capable", ":", "self", ".", "enableRemoteWakeup", "(", ")", "self", ".", "ep0", ".", "read", "(", "0", ")", "return", "self", ".", "ep0", ".", "halt", "(", "request_type", ")" ]
Called when a setup USB transaction was received. Default implementation: - handles USB_REQ_GET_STATUS on interface and endpoints - handles USB_REQ_CLEAR_FEATURE(USB_ENDPOINT_HALT) on endpoints - handles USB_REQ_SET_FEATURE(USB_ENDPOINT_HALT) on endpoints - halts on everything else If this method raises anything, endpoint 0 is halted by its caller and exception is let through. May be overridden in subclass.
[ "Called", "when", "a", "setup", "USB", "transaction", "was", "received", "." ]
e19f729bb47a7d1edd2488531af24551bb86726f
https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/functionfs/__init__.py#L956-L1036
train
vpelletier/python-functionfs
examples/usbcat/slowprinter.py
main
def main(): """ Slowly writes to stdout, without emitting a newline so any output buffering (or input for next pipeline command) can be detected. """ now = datetime.datetime.now try: while True: sys.stdout.write(str(now()) + ' ') time.sleep(1) except KeyboardInterrupt: pass except IOError as exc: if exc.errno != errno.EPIPE: raise
python
def main(): """ Slowly writes to stdout, without emitting a newline so any output buffering (or input for next pipeline command) can be detected. """ now = datetime.datetime.now try: while True: sys.stdout.write(str(now()) + ' ') time.sleep(1) except KeyboardInterrupt: pass except IOError as exc: if exc.errno != errno.EPIPE: raise
[ "def", "main", "(", ")", ":", "now", "=", "datetime", ".", "datetime", ".", "now", "try", ":", "while", "True", ":", "sys", ".", "stdout", ".", "write", "(", "str", "(", "now", "(", ")", ")", "+", "' '", ")", "time", ".", "sleep", "(", "1", ")", "except", "KeyboardInterrupt", ":", "pass", "except", "IOError", "as", "exc", ":", "if", "exc", ".", "errno", "!=", "errno", ".", "EPIPE", ":", "raise" ]
Slowly writes to stdout, without emitting a newline so any output buffering (or input for next pipeline command) can be detected.
[ "Slowly", "writes", "to", "stdout", "without", "emitting", "a", "newline", "so", "any", "output", "buffering", "(", "or", "input", "for", "next", "pipeline", "command", ")", "can", "be", "detected", "." ]
e19f729bb47a7d1edd2488531af24551bb86726f
https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/examples/usbcat/slowprinter.py#L22-L36
train
vpelletier/python-functionfs
examples/usbcat/device.py
USBCat.onEnable
def onEnable(self): """ The configuration containing this function has been enabled by host. Endpoints become working files, so submit some read operations. """ trace('onEnable') self._disable() self._aio_context.submit(self._aio_recv_block_list) self._real_onCanSend() self._enabled = True
python
def onEnable(self): """ The configuration containing this function has been enabled by host. Endpoints become working files, so submit some read operations. """ trace('onEnable') self._disable() self._aio_context.submit(self._aio_recv_block_list) self._real_onCanSend() self._enabled = True
[ "def", "onEnable", "(", "self", ")", ":", "trace", "(", "'onEnable'", ")", "self", ".", "_disable", "(", ")", "self", ".", "_aio_context", ".", "submit", "(", "self", ".", "_aio_recv_block_list", ")", "self", ".", "_real_onCanSend", "(", ")", "self", ".", "_enabled", "=", "True" ]
The configuration containing this function has been enabled by host. Endpoints become working files, so submit some read operations.
[ "The", "configuration", "containing", "this", "function", "has", "been", "enabled", "by", "host", ".", "Endpoints", "become", "working", "files", "so", "submit", "some", "read", "operations", "." ]
e19f729bb47a7d1edd2488531af24551bb86726f
https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/examples/usbcat/device.py#L121-L130
train
vpelletier/python-functionfs
examples/usbcat/device.py
USBCat._disable
def _disable(self): """ The configuration containing this function has been disabled by host. Endpoint do not work anymore, so cancel AIO operation blocks. """ if self._enabled: self._real_onCannotSend() has_cancelled = 0 for block in self._aio_recv_block_list + self._aio_send_block_list: try: self._aio_context.cancel(block) except OSError as exc: trace( 'cancelling %r raised: %s' % (block, exc), ) else: has_cancelled += 1 if has_cancelled: noIntr(functools.partial(self._aio_context.getEvents, min_nr=None)) self._enabled = False
python
def _disable(self): """ The configuration containing this function has been disabled by host. Endpoint do not work anymore, so cancel AIO operation blocks. """ if self._enabled: self._real_onCannotSend() has_cancelled = 0 for block in self._aio_recv_block_list + self._aio_send_block_list: try: self._aio_context.cancel(block) except OSError as exc: trace( 'cancelling %r raised: %s' % (block, exc), ) else: has_cancelled += 1 if has_cancelled: noIntr(functools.partial(self._aio_context.getEvents, min_nr=None)) self._enabled = False
[ "def", "_disable", "(", "self", ")", ":", "if", "self", ".", "_enabled", ":", "self", ".", "_real_onCannotSend", "(", ")", "has_cancelled", "=", "0", "for", "block", "in", "self", ".", "_aio_recv_block_list", "+", "self", ".", "_aio_send_block_list", ":", "try", ":", "self", ".", "_aio_context", ".", "cancel", "(", "block", ")", "except", "OSError", "as", "exc", ":", "trace", "(", "'cancelling %r raised: %s'", "%", "(", "block", ",", "exc", ")", ",", ")", "else", ":", "has_cancelled", "+=", "1", "if", "has_cancelled", ":", "noIntr", "(", "functools", ".", "partial", "(", "self", ".", "_aio_context", ".", "getEvents", ",", "min_nr", "=", "None", ")", ")", "self", ".", "_enabled", "=", "False" ]
The configuration containing this function has been disabled by host. Endpoint do not work anymore, so cancel AIO operation blocks.
[ "The", "configuration", "containing", "this", "function", "has", "been", "disabled", "by", "host", ".", "Endpoint", "do", "not", "work", "anymore", "so", "cancel", "AIO", "operation", "blocks", "." ]
e19f729bb47a7d1edd2488531af24551bb86726f
https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/examples/usbcat/device.py#L136-L155
train
vpelletier/python-functionfs
examples/usbcat/device.py
USBCat.onAIOCompletion
def onAIOCompletion(self): """ Call when eventfd notified events are available. """ event_count = self.eventfd.read() trace('eventfd reports %i events' % event_count) # Even though eventfd signaled activity, even though it may give us # some number of pending events, some events seem to have been already # processed (maybe during io_cancel call ?). # So do not trust eventfd value, and do not even trust that there must # be even one event to process. self._aio_context.getEvents(0)
python
def onAIOCompletion(self): """ Call when eventfd notified events are available. """ event_count = self.eventfd.read() trace('eventfd reports %i events' % event_count) # Even though eventfd signaled activity, even though it may give us # some number of pending events, some events seem to have been already # processed (maybe during io_cancel call ?). # So do not trust eventfd value, and do not even trust that there must # be even one event to process. self._aio_context.getEvents(0)
[ "def", "onAIOCompletion", "(", "self", ")", ":", "event_count", "=", "self", ".", "eventfd", ".", "read", "(", ")", "trace", "(", "'eventfd reports %i events'", "%", "event_count", ")", "# Even though eventfd signaled activity, even though it may give us", "# some number of pending events, some events seem to have been already", "# processed (maybe during io_cancel call ?).", "# So do not trust eventfd value, and do not even trust that there must", "# be even one event to process.", "self", ".", "_aio_context", ".", "getEvents", "(", "0", ")" ]
Call when eventfd notified events are available.
[ "Call", "when", "eventfd", "notified", "events", "are", "available", "." ]
e19f729bb47a7d1edd2488531af24551bb86726f
https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/examples/usbcat/device.py#L157-L168
train
vpelletier/python-functionfs
examples/usbcat/device.py
USBCat.write
def write(self, value): """ Queue write in kernel. value (bytes) Value to send. """ aio_block = libaio.AIOBlock( mode=libaio.AIOBLOCK_MODE_WRITE, target_file=self.getEndpoint(1), buffer_list=[bytearray(value)], offset=0, eventfd=self.eventfd, onCompletion=self._onCanSend, ) self._aio_send_block_list.append(aio_block) self._aio_context.submit([aio_block]) if len(self._aio_send_block_list) == MAX_PENDING_WRITE_COUNT: self._onCannotSend()
python
def write(self, value): """ Queue write in kernel. value (bytes) Value to send. """ aio_block = libaio.AIOBlock( mode=libaio.AIOBLOCK_MODE_WRITE, target_file=self.getEndpoint(1), buffer_list=[bytearray(value)], offset=0, eventfd=self.eventfd, onCompletion=self._onCanSend, ) self._aio_send_block_list.append(aio_block) self._aio_context.submit([aio_block]) if len(self._aio_send_block_list) == MAX_PENDING_WRITE_COUNT: self._onCannotSend()
[ "def", "write", "(", "self", ",", "value", ")", ":", "aio_block", "=", "libaio", ".", "AIOBlock", "(", "mode", "=", "libaio", ".", "AIOBLOCK_MODE_WRITE", ",", "target_file", "=", "self", ".", "getEndpoint", "(", "1", ")", ",", "buffer_list", "=", "[", "bytearray", "(", "value", ")", "]", ",", "offset", "=", "0", ",", "eventfd", "=", "self", ".", "eventfd", ",", "onCompletion", "=", "self", ".", "_onCanSend", ",", ")", "self", ".", "_aio_send_block_list", ".", "append", "(", "aio_block", ")", "self", ".", "_aio_context", ".", "submit", "(", "[", "aio_block", "]", ")", "if", "len", "(", "self", ".", "_aio_send_block_list", ")", "==", "MAX_PENDING_WRITE_COUNT", ":", "self", ".", "_onCannotSend", "(", ")" ]
Queue write in kernel. value (bytes) Value to send.
[ "Queue", "write", "in", "kernel", ".", "value", "(", "bytes", ")", "Value", "to", "send", "." ]
e19f729bb47a7d1edd2488531af24551bb86726f
https://github.com/vpelletier/python-functionfs/blob/e19f729bb47a7d1edd2488531af24551bb86726f/examples/usbcat/device.py#L196-L213
train
oasis-open/cti-stix-validator
stix2validator/errors.py
pretty_error
def pretty_error(error, verbose=False): """Return an error message that is easier to read and more useful. May require updating if the schemas change significantly. """ error_loc = '' if error.path: while len(error.path) > 0: path_elem = error.path.popleft() if type(path_elem) is not int: if error_loc: error_loc += '.' error_loc += path_elem # elif len(error.path) > 0: else: error_loc += '[' + text_type(path_elem) + ']' error_loc += ': ' # Get error message and remove ugly u'' prefixes if verbose: msg = remove_u(text_type(error)) else: msg = remove_u(error.message) # Don't reword error messages from our validators, # only the default error messages from the jsonschema library if repr(error.schema) == '<unset>': try: return error_loc + msg except UnicodeDecodeError: return error_loc + msg.decode('utf-8') # Reword error messages containing regexes if error.validator == 'pattern' and 'title' in error.schema: if error.schema['title'] == 'type': msg = re.sub(r"match '.+'$", 'match the \'type\' field format ' '(lowercase ASCII a-z, 0-9, and hypens only - and no ' 'two hyphens in a row)', msg) elif error.schema['title'] == 'identifier': msg = re.sub(r"match '.+'$", 'match the id format ' '([object-type]--[UUIDv4])', msg) elif error.schema['title'] == 'id': msg = re.sub(r"match '.+'$", 'start with \'' + error.validator_value[1:-2] + '--\'', msg) elif error.schema['title'] == 'timestamp': msg = re.sub(r"match '.+'$", 'match the timestamp format ' 'YYYY-MM-DDTHH:mm:ss[.s+]Z', msg) elif error.schema['title'] == 'timestamp_millis': msg = re.sub(r"match '.+'$", 'match the timestamp format ' 'YYYY-MM-DDTHH:mm:ss.sssZ (must be precise to the ' 'millisecond)', msg) elif error.schema['title'] == 'relationship_type': msg = re.sub(r"does not match '.+'$", 'contains invalid ' 'characters', msg) elif error.schema['title'] == 'url-regex': msg = re.sub(r'match ".+"$', 'match the format ' 'of a URL', msg) elif error.schema['title'] == 'binary': msg = re.sub(r"does not.+'$", 'must be a base64-encoded string', msg) elif error.validator == 'pattern' and 'observed_data_refs' in error.schema_path: msg = "'observed_data_refs' must refer to Observed Data Objects" elif error.validator == 'pattern' and 'where_sighted_refs' in error.schema_path: msg = "'where_sighted_refs' must refer to Identity Objects" # Reword empty array errors elif type(error.instance) is list and len(error.instance) == 0: msg = re.sub(r"\[\] is not valid .+$", 'empty arrays are not allowed', msg) # Reword custom property errors elif 'title' in error.schema and error.schema['title'] == 'core': if error.validator == 'additionalProperties': msg = re.sub(r"Additional .+$", 'Custom properties must match the ' 'proper format (lowercase ASCII a-z, 0-9, and ' 'underscores; 3-250 characters)', msg) elif error.validator == 'not' and 'anyOf' in error.validator_value: reserved_properties = [y for x in error.validator_value['anyOf'] for y in x['required']] msg = re.sub(r".+", "Contains a reserved property ('%s')" % "', '".join(reserved_properties), msg) elif 'title' in error.schema and error.schema['title'] == 'cyber-observable-core': if error.validator == 'additionalProperties': msg = re.sub(r"Additional .+$", 'Custom observable properties must' ' match the proper format (lowercase ASCII a-z, 0-9, ' 'and underscores; 3-250 characters)', msg) elif error.validator == 'additionalProperties': if 'extensions' in error.schema_path: msg = re.sub(r"Additional .+$", 'Custom extension keys may only ' 'contain alphanumeric characters, dashes, and ' 'underscores; 3-256 characters', msg) # Reword 'is valid under each of' errors elif error.validator == 'oneOf': try: if 'external_references' in error.schema_path: msg = "If the external reference is a CVE, 'source_name' must be" \ " 'cve' and 'external_id' must be in the CVE format " \ "(CVE-YYYY-NNNN+). If the external reference is a CAPEC, " \ "'source_name' must be 'capec' and 'external_id' must be " \ "in the CAPEC format (CAPEC-N+). If the external reference "\ "is neither, it must contain the 'source_name' property and"\ " at least one of the 'external_id', 'url', or "\ "'description' properties." elif 'type' in error.instance and error.instance['type'] == 'email-message': if 'is_multipart' not in error.instance: msg = "'is_multipart' is a required property" elif error.instance['is_multipart'] is True: msg = "Since 'is_multipart' is true, 'body_multipart' must "\ "contain valid 'mime-part-type' objects and the 'body' "\ "property must not be present. " elif error.instance['is_multipart'] is False: msg = "Since 'is_multipart' is false, 'body' must be a string"\ " and the 'body_multipart' property must not be present." elif 'type' in error.instance and error.instance['type'] == 'artifact': if 'payload_bin' in error.instance and 'url' in error.instance: msg = "'artifact' object must contain either 'payload_bin' "\ "or 'url' but not both" elif 'payload_bin' in error.instance: msg = "'payload_bin' must be base64 encoded and 'hashes', if "\ "present, must contain a valid dictionary of hashes" elif 'url' in error.instance: msg = "'url' must be a valid url and 'hashes', which must be "\ "present, must contain a valid hash dictionary" else: msg = "'artifact' object must contain either 'payload_bin' "\ "or 'url'" elif 'type' in error.instance and error.instance['type'] == 'marking-definition': msg = "'definition' must contain a valid statement, TLP, or "\ "custom marking definition" elif 'type' in error.instance and error.instance['type'] == 'file': if (('is_encrypted' not in error.instance or error.instance['is_encrypted'] is False) and ('encryption_algorithm' in error.instance or 'decryption_key' in error.instance)): msg = "'file' objects may only contain 'encryption_algorithm'"\ " or 'decryption_key' when 'is_encrypted' is true" elif 'type' in error.instance and error.instance['type'] == 'network-traffic': if ('is_active' in error.instance and error.instance['is_active'] is True and 'end' in error.instance): msg = "If the 'is_active' property is true, then the "\ "'end' property must not be included." else: raise TypeError except TypeError: msg = msg + ':\n' + remove_u(text_type(error.schema)) # reword forbidden property or value errors elif error.validator == 'not': if 'enum' in error.validator_value: msg = re.sub(r"\{.+\} is not allowed for '(.+)'$", r"'\g<1>' is " "not an allowed value", msg) elif ('target_ref' in error.schema_path or 'source_ref' in error.schema_path): msg = "Relationships cannot link bundles, marking definitions"\ ", sightings, or other relationships. This field must "\ "contain the id of an SDO." elif 'sighting_of_ref' in error.schema_path: msg = "'sighting_of_ref' must refer to a STIX Domain Object or "\ "Custom Object" # Reword 'is not valid under any of the given schemas' errors elif error.validator == 'anyOf': try: if error.instance == {}: msg = "must contain at least one property from this type." elif error.instance is None: msg = "null properties are not allowed in STIX." elif 'type' in error.instance and error.instance['type'] == 'network-traffic': if ('src_ref' not in error.instance and 'dst_ref' not in error.instance): msg = "'network-traffic' objects must contain at least "\ "one of 'src_ref' or 'dst_ref'" elif 'type' in error.instance and error.instance['type'] in ['process', 'x509-certificate']: if error.instance.keys() == ['type']: msg = "must contain at least one property (other than `type`) from this object." else: raise TypeError except TypeError: msg = msg + ':\n' + remove_u(text_type(error.schema)) return error_loc + msg
python
def pretty_error(error, verbose=False): """Return an error message that is easier to read and more useful. May require updating if the schemas change significantly. """ error_loc = '' if error.path: while len(error.path) > 0: path_elem = error.path.popleft() if type(path_elem) is not int: if error_loc: error_loc += '.' error_loc += path_elem # elif len(error.path) > 0: else: error_loc += '[' + text_type(path_elem) + ']' error_loc += ': ' # Get error message and remove ugly u'' prefixes if verbose: msg = remove_u(text_type(error)) else: msg = remove_u(error.message) # Don't reword error messages from our validators, # only the default error messages from the jsonschema library if repr(error.schema) == '<unset>': try: return error_loc + msg except UnicodeDecodeError: return error_loc + msg.decode('utf-8') # Reword error messages containing regexes if error.validator == 'pattern' and 'title' in error.schema: if error.schema['title'] == 'type': msg = re.sub(r"match '.+'$", 'match the \'type\' field format ' '(lowercase ASCII a-z, 0-9, and hypens only - and no ' 'two hyphens in a row)', msg) elif error.schema['title'] == 'identifier': msg = re.sub(r"match '.+'$", 'match the id format ' '([object-type]--[UUIDv4])', msg) elif error.schema['title'] == 'id': msg = re.sub(r"match '.+'$", 'start with \'' + error.validator_value[1:-2] + '--\'', msg) elif error.schema['title'] == 'timestamp': msg = re.sub(r"match '.+'$", 'match the timestamp format ' 'YYYY-MM-DDTHH:mm:ss[.s+]Z', msg) elif error.schema['title'] == 'timestamp_millis': msg = re.sub(r"match '.+'$", 'match the timestamp format ' 'YYYY-MM-DDTHH:mm:ss.sssZ (must be precise to the ' 'millisecond)', msg) elif error.schema['title'] == 'relationship_type': msg = re.sub(r"does not match '.+'$", 'contains invalid ' 'characters', msg) elif error.schema['title'] == 'url-regex': msg = re.sub(r'match ".+"$', 'match the format ' 'of a URL', msg) elif error.schema['title'] == 'binary': msg = re.sub(r"does not.+'$", 'must be a base64-encoded string', msg) elif error.validator == 'pattern' and 'observed_data_refs' in error.schema_path: msg = "'observed_data_refs' must refer to Observed Data Objects" elif error.validator == 'pattern' and 'where_sighted_refs' in error.schema_path: msg = "'where_sighted_refs' must refer to Identity Objects" # Reword empty array errors elif type(error.instance) is list and len(error.instance) == 0: msg = re.sub(r"\[\] is not valid .+$", 'empty arrays are not allowed', msg) # Reword custom property errors elif 'title' in error.schema and error.schema['title'] == 'core': if error.validator == 'additionalProperties': msg = re.sub(r"Additional .+$", 'Custom properties must match the ' 'proper format (lowercase ASCII a-z, 0-9, and ' 'underscores; 3-250 characters)', msg) elif error.validator == 'not' and 'anyOf' in error.validator_value: reserved_properties = [y for x in error.validator_value['anyOf'] for y in x['required']] msg = re.sub(r".+", "Contains a reserved property ('%s')" % "', '".join(reserved_properties), msg) elif 'title' in error.schema and error.schema['title'] == 'cyber-observable-core': if error.validator == 'additionalProperties': msg = re.sub(r"Additional .+$", 'Custom observable properties must' ' match the proper format (lowercase ASCII a-z, 0-9, ' 'and underscores; 3-250 characters)', msg) elif error.validator == 'additionalProperties': if 'extensions' in error.schema_path: msg = re.sub(r"Additional .+$", 'Custom extension keys may only ' 'contain alphanumeric characters, dashes, and ' 'underscores; 3-256 characters', msg) # Reword 'is valid under each of' errors elif error.validator == 'oneOf': try: if 'external_references' in error.schema_path: msg = "If the external reference is a CVE, 'source_name' must be" \ " 'cve' and 'external_id' must be in the CVE format " \ "(CVE-YYYY-NNNN+). If the external reference is a CAPEC, " \ "'source_name' must be 'capec' and 'external_id' must be " \ "in the CAPEC format (CAPEC-N+). If the external reference "\ "is neither, it must contain the 'source_name' property and"\ " at least one of the 'external_id', 'url', or "\ "'description' properties." elif 'type' in error.instance and error.instance['type'] == 'email-message': if 'is_multipart' not in error.instance: msg = "'is_multipart' is a required property" elif error.instance['is_multipart'] is True: msg = "Since 'is_multipart' is true, 'body_multipart' must "\ "contain valid 'mime-part-type' objects and the 'body' "\ "property must not be present. " elif error.instance['is_multipart'] is False: msg = "Since 'is_multipart' is false, 'body' must be a string"\ " and the 'body_multipart' property must not be present." elif 'type' in error.instance and error.instance['type'] == 'artifact': if 'payload_bin' in error.instance and 'url' in error.instance: msg = "'artifact' object must contain either 'payload_bin' "\ "or 'url' but not both" elif 'payload_bin' in error.instance: msg = "'payload_bin' must be base64 encoded and 'hashes', if "\ "present, must contain a valid dictionary of hashes" elif 'url' in error.instance: msg = "'url' must be a valid url and 'hashes', which must be "\ "present, must contain a valid hash dictionary" else: msg = "'artifact' object must contain either 'payload_bin' "\ "or 'url'" elif 'type' in error.instance and error.instance['type'] == 'marking-definition': msg = "'definition' must contain a valid statement, TLP, or "\ "custom marking definition" elif 'type' in error.instance and error.instance['type'] == 'file': if (('is_encrypted' not in error.instance or error.instance['is_encrypted'] is False) and ('encryption_algorithm' in error.instance or 'decryption_key' in error.instance)): msg = "'file' objects may only contain 'encryption_algorithm'"\ " or 'decryption_key' when 'is_encrypted' is true" elif 'type' in error.instance and error.instance['type'] == 'network-traffic': if ('is_active' in error.instance and error.instance['is_active'] is True and 'end' in error.instance): msg = "If the 'is_active' property is true, then the "\ "'end' property must not be included." else: raise TypeError except TypeError: msg = msg + ':\n' + remove_u(text_type(error.schema)) # reword forbidden property or value errors elif error.validator == 'not': if 'enum' in error.validator_value: msg = re.sub(r"\{.+\} is not allowed for '(.+)'$", r"'\g<1>' is " "not an allowed value", msg) elif ('target_ref' in error.schema_path or 'source_ref' in error.schema_path): msg = "Relationships cannot link bundles, marking definitions"\ ", sightings, or other relationships. This field must "\ "contain the id of an SDO." elif 'sighting_of_ref' in error.schema_path: msg = "'sighting_of_ref' must refer to a STIX Domain Object or "\ "Custom Object" # Reword 'is not valid under any of the given schemas' errors elif error.validator == 'anyOf': try: if error.instance == {}: msg = "must contain at least one property from this type." elif error.instance is None: msg = "null properties are not allowed in STIX." elif 'type' in error.instance and error.instance['type'] == 'network-traffic': if ('src_ref' not in error.instance and 'dst_ref' not in error.instance): msg = "'network-traffic' objects must contain at least "\ "one of 'src_ref' or 'dst_ref'" elif 'type' in error.instance and error.instance['type'] in ['process', 'x509-certificate']: if error.instance.keys() == ['type']: msg = "must contain at least one property (other than `type`) from this object." else: raise TypeError except TypeError: msg = msg + ':\n' + remove_u(text_type(error.schema)) return error_loc + msg
[ "def", "pretty_error", "(", "error", ",", "verbose", "=", "False", ")", ":", "error_loc", "=", "''", "if", "error", ".", "path", ":", "while", "len", "(", "error", ".", "path", ")", ">", "0", ":", "path_elem", "=", "error", ".", "path", ".", "popleft", "(", ")", "if", "type", "(", "path_elem", ")", "is", "not", "int", ":", "if", "error_loc", ":", "error_loc", "+=", "'.'", "error_loc", "+=", "path_elem", "# elif len(error.path) > 0:", "else", ":", "error_loc", "+=", "'['", "+", "text_type", "(", "path_elem", ")", "+", "']'", "error_loc", "+=", "': '", "# Get error message and remove ugly u'' prefixes", "if", "verbose", ":", "msg", "=", "remove_u", "(", "text_type", "(", "error", ")", ")", "else", ":", "msg", "=", "remove_u", "(", "error", ".", "message", ")", "# Don't reword error messages from our validators,", "# only the default error messages from the jsonschema library", "if", "repr", "(", "error", ".", "schema", ")", "==", "'<unset>'", ":", "try", ":", "return", "error_loc", "+", "msg", "except", "UnicodeDecodeError", ":", "return", "error_loc", "+", "msg", ".", "decode", "(", "'utf-8'", ")", "# Reword error messages containing regexes", "if", "error", ".", "validator", "==", "'pattern'", "and", "'title'", "in", "error", ".", "schema", ":", "if", "error", ".", "schema", "[", "'title'", "]", "==", "'type'", ":", "msg", "=", "re", ".", "sub", "(", "r\"match '.+'$\"", ",", "'match the \\'type\\' field format '", "'(lowercase ASCII a-z, 0-9, and hypens only - and no '", "'two hyphens in a row)'", ",", "msg", ")", "elif", "error", ".", "schema", "[", "'title'", "]", "==", "'identifier'", ":", "msg", "=", "re", ".", "sub", "(", "r\"match '.+'$\"", ",", "'match the id format '", "'([object-type]--[UUIDv4])'", ",", "msg", ")", "elif", "error", ".", "schema", "[", "'title'", "]", "==", "'id'", ":", "msg", "=", "re", ".", "sub", "(", "r\"match '.+'$\"", ",", "'start with \\''", "+", "error", ".", "validator_value", "[", "1", ":", "-", "2", "]", "+", "'--\\''", ",", "msg", ")", "elif", "error", ".", "schema", "[", "'title'", "]", "==", "'timestamp'", ":", "msg", "=", "re", ".", "sub", "(", "r\"match '.+'$\"", ",", "'match the timestamp format '", "'YYYY-MM-DDTHH:mm:ss[.s+]Z'", ",", "msg", ")", "elif", "error", ".", "schema", "[", "'title'", "]", "==", "'timestamp_millis'", ":", "msg", "=", "re", ".", "sub", "(", "r\"match '.+'$\"", ",", "'match the timestamp format '", "'YYYY-MM-DDTHH:mm:ss.sssZ (must be precise to the '", "'millisecond)'", ",", "msg", ")", "elif", "error", ".", "schema", "[", "'title'", "]", "==", "'relationship_type'", ":", "msg", "=", "re", ".", "sub", "(", "r\"does not match '.+'$\"", ",", "'contains invalid '", "'characters'", ",", "msg", ")", "elif", "error", ".", "schema", "[", "'title'", "]", "==", "'url-regex'", ":", "msg", "=", "re", ".", "sub", "(", "r'match \".+\"$'", ",", "'match the format '", "'of a URL'", ",", "msg", ")", "elif", "error", ".", "schema", "[", "'title'", "]", "==", "'binary'", ":", "msg", "=", "re", ".", "sub", "(", "r\"does not.+'$\"", ",", "'must be a base64-encoded string'", ",", "msg", ")", "elif", "error", ".", "validator", "==", "'pattern'", "and", "'observed_data_refs'", "in", "error", ".", "schema_path", ":", "msg", "=", "\"'observed_data_refs' must refer to Observed Data Objects\"", "elif", "error", ".", "validator", "==", "'pattern'", "and", "'where_sighted_refs'", "in", "error", ".", "schema_path", ":", "msg", "=", "\"'where_sighted_refs' must refer to Identity Objects\"", "# Reword empty array errors", "elif", "type", "(", "error", ".", "instance", ")", "is", "list", "and", "len", "(", "error", ".", "instance", ")", "==", "0", ":", "msg", "=", "re", ".", "sub", "(", "r\"\\[\\] is not valid .+$\"", ",", "'empty arrays are not allowed'", ",", "msg", ")", "# Reword custom property errors", "elif", "'title'", "in", "error", ".", "schema", "and", "error", ".", "schema", "[", "'title'", "]", "==", "'core'", ":", "if", "error", ".", "validator", "==", "'additionalProperties'", ":", "msg", "=", "re", ".", "sub", "(", "r\"Additional .+$\"", ",", "'Custom properties must match the '", "'proper format (lowercase ASCII a-z, 0-9, and '", "'underscores; 3-250 characters)'", ",", "msg", ")", "elif", "error", ".", "validator", "==", "'not'", "and", "'anyOf'", "in", "error", ".", "validator_value", ":", "reserved_properties", "=", "[", "y", "for", "x", "in", "error", ".", "validator_value", "[", "'anyOf'", "]", "for", "y", "in", "x", "[", "'required'", "]", "]", "msg", "=", "re", ".", "sub", "(", "r\".+\"", ",", "\"Contains a reserved property ('%s')\"", "%", "\"', '\"", ".", "join", "(", "reserved_properties", ")", ",", "msg", ")", "elif", "'title'", "in", "error", ".", "schema", "and", "error", ".", "schema", "[", "'title'", "]", "==", "'cyber-observable-core'", ":", "if", "error", ".", "validator", "==", "'additionalProperties'", ":", "msg", "=", "re", ".", "sub", "(", "r\"Additional .+$\"", ",", "'Custom observable properties must'", "' match the proper format (lowercase ASCII a-z, 0-9, '", "'and underscores; 3-250 characters)'", ",", "msg", ")", "elif", "error", ".", "validator", "==", "'additionalProperties'", ":", "if", "'extensions'", "in", "error", ".", "schema_path", ":", "msg", "=", "re", ".", "sub", "(", "r\"Additional .+$\"", ",", "'Custom extension keys may only '", "'contain alphanumeric characters, dashes, and '", "'underscores; 3-256 characters'", ",", "msg", ")", "# Reword 'is valid under each of' errors", "elif", "error", ".", "validator", "==", "'oneOf'", ":", "try", ":", "if", "'external_references'", "in", "error", ".", "schema_path", ":", "msg", "=", "\"If the external reference is a CVE, 'source_name' must be\"", "\" 'cve' and 'external_id' must be in the CVE format \"", "\"(CVE-YYYY-NNNN+). If the external reference is a CAPEC, \"", "\"'source_name' must be 'capec' and 'external_id' must be \"", "\"in the CAPEC format (CAPEC-N+). If the external reference \"", "\"is neither, it must contain the 'source_name' property and\"", "\" at least one of the 'external_id', 'url', or \"", "\"'description' properties.\"", "elif", "'type'", "in", "error", ".", "instance", "and", "error", ".", "instance", "[", "'type'", "]", "==", "'email-message'", ":", "if", "'is_multipart'", "not", "in", "error", ".", "instance", ":", "msg", "=", "\"'is_multipart' is a required property\"", "elif", "error", ".", "instance", "[", "'is_multipart'", "]", "is", "True", ":", "msg", "=", "\"Since 'is_multipart' is true, 'body_multipart' must \"", "\"contain valid 'mime-part-type' objects and the 'body' \"", "\"property must not be present. \"", "elif", "error", ".", "instance", "[", "'is_multipart'", "]", "is", "False", ":", "msg", "=", "\"Since 'is_multipart' is false, 'body' must be a string\"", "\" and the 'body_multipart' property must not be present.\"", "elif", "'type'", "in", "error", ".", "instance", "and", "error", ".", "instance", "[", "'type'", "]", "==", "'artifact'", ":", "if", "'payload_bin'", "in", "error", ".", "instance", "and", "'url'", "in", "error", ".", "instance", ":", "msg", "=", "\"'artifact' object must contain either 'payload_bin' \"", "\"or 'url' but not both\"", "elif", "'payload_bin'", "in", "error", ".", "instance", ":", "msg", "=", "\"'payload_bin' must be base64 encoded and 'hashes', if \"", "\"present, must contain a valid dictionary of hashes\"", "elif", "'url'", "in", "error", ".", "instance", ":", "msg", "=", "\"'url' must be a valid url and 'hashes', which must be \"", "\"present, must contain a valid hash dictionary\"", "else", ":", "msg", "=", "\"'artifact' object must contain either 'payload_bin' \"", "\"or 'url'\"", "elif", "'type'", "in", "error", ".", "instance", "and", "error", ".", "instance", "[", "'type'", "]", "==", "'marking-definition'", ":", "msg", "=", "\"'definition' must contain a valid statement, TLP, or \"", "\"custom marking definition\"", "elif", "'type'", "in", "error", ".", "instance", "and", "error", ".", "instance", "[", "'type'", "]", "==", "'file'", ":", "if", "(", "(", "'is_encrypted'", "not", "in", "error", ".", "instance", "or", "error", ".", "instance", "[", "'is_encrypted'", "]", "is", "False", ")", "and", "(", "'encryption_algorithm'", "in", "error", ".", "instance", "or", "'decryption_key'", "in", "error", ".", "instance", ")", ")", ":", "msg", "=", "\"'file' objects may only contain 'encryption_algorithm'\"", "\" or 'decryption_key' when 'is_encrypted' is true\"", "elif", "'type'", "in", "error", ".", "instance", "and", "error", ".", "instance", "[", "'type'", "]", "==", "'network-traffic'", ":", "if", "(", "'is_active'", "in", "error", ".", "instance", "and", "error", ".", "instance", "[", "'is_active'", "]", "is", "True", "and", "'end'", "in", "error", ".", "instance", ")", ":", "msg", "=", "\"If the 'is_active' property is true, then the \"", "\"'end' property must not be included.\"", "else", ":", "raise", "TypeError", "except", "TypeError", ":", "msg", "=", "msg", "+", "':\\n'", "+", "remove_u", "(", "text_type", "(", "error", ".", "schema", ")", ")", "# reword forbidden property or value errors", "elif", "error", ".", "validator", "==", "'not'", ":", "if", "'enum'", "in", "error", ".", "validator_value", ":", "msg", "=", "re", ".", "sub", "(", "r\"\\{.+\\} is not allowed for '(.+)'$\"", ",", "r\"'\\g<1>' is \"", "\"not an allowed value\"", ",", "msg", ")", "elif", "(", "'target_ref'", "in", "error", ".", "schema_path", "or", "'source_ref'", "in", "error", ".", "schema_path", ")", ":", "msg", "=", "\"Relationships cannot link bundles, marking definitions\"", "\", sightings, or other relationships. This field must \"", "\"contain the id of an SDO.\"", "elif", "'sighting_of_ref'", "in", "error", ".", "schema_path", ":", "msg", "=", "\"'sighting_of_ref' must refer to a STIX Domain Object or \"", "\"Custom Object\"", "# Reword 'is not valid under any of the given schemas' errors", "elif", "error", ".", "validator", "==", "'anyOf'", ":", "try", ":", "if", "error", ".", "instance", "==", "{", "}", ":", "msg", "=", "\"must contain at least one property from this type.\"", "elif", "error", ".", "instance", "is", "None", ":", "msg", "=", "\"null properties are not allowed in STIX.\"", "elif", "'type'", "in", "error", ".", "instance", "and", "error", ".", "instance", "[", "'type'", "]", "==", "'network-traffic'", ":", "if", "(", "'src_ref'", "not", "in", "error", ".", "instance", "and", "'dst_ref'", "not", "in", "error", ".", "instance", ")", ":", "msg", "=", "\"'network-traffic' objects must contain at least \"", "\"one of 'src_ref' or 'dst_ref'\"", "elif", "'type'", "in", "error", ".", "instance", "and", "error", ".", "instance", "[", "'type'", "]", "in", "[", "'process'", ",", "'x509-certificate'", "]", ":", "if", "error", ".", "instance", ".", "keys", "(", ")", "==", "[", "'type'", "]", ":", "msg", "=", "\"must contain at least one property (other than `type`) from this object.\"", "else", ":", "raise", "TypeError", "except", "TypeError", ":", "msg", "=", "msg", "+", "':\\n'", "+", "remove_u", "(", "text_type", "(", "error", ".", "schema", ")", ")", "return", "error_loc", "+", "msg" ]
Return an error message that is easier to read and more useful. May require updating if the schemas change significantly.
[ "Return", "an", "error", "message", "that", "is", "easier", "to", "read", "and", "more", "useful", ".", "May", "require", "updating", "if", "the", "schemas", "change", "significantly", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/errors.py#L71-L252
train
oasis-open/cti-stix-validator
stix2validator/validator.py
_iter_errors_custom
def _iter_errors_custom(instance, checks, options): """Perform additional validation not possible merely with JSON schemas. Args: instance: The STIX object to be validated. checks: A sequence of callables which do the checks. Each callable may be written to accept 1 arg, which is the object to check, or 2 args, which are the object and a ValidationOptions instance. options: ValidationOptions instance with settings affecting how validation should be done. """ # Perform validation for v_function in checks: try: result = v_function(instance) except TypeError: result = v_function(instance, options) if isinstance(result, Iterable): for x in result: yield x elif result is not None: yield result # Validate any child STIX objects for field in instance: if type(instance[field]) is list: for obj in instance[field]: if _is_stix_obj(obj): for err in _iter_errors_custom(obj, checks, options): yield err
python
def _iter_errors_custom(instance, checks, options): """Perform additional validation not possible merely with JSON schemas. Args: instance: The STIX object to be validated. checks: A sequence of callables which do the checks. Each callable may be written to accept 1 arg, which is the object to check, or 2 args, which are the object and a ValidationOptions instance. options: ValidationOptions instance with settings affecting how validation should be done. """ # Perform validation for v_function in checks: try: result = v_function(instance) except TypeError: result = v_function(instance, options) if isinstance(result, Iterable): for x in result: yield x elif result is not None: yield result # Validate any child STIX objects for field in instance: if type(instance[field]) is list: for obj in instance[field]: if _is_stix_obj(obj): for err in _iter_errors_custom(obj, checks, options): yield err
[ "def", "_iter_errors_custom", "(", "instance", ",", "checks", ",", "options", ")", ":", "# Perform validation", "for", "v_function", "in", "checks", ":", "try", ":", "result", "=", "v_function", "(", "instance", ")", "except", "TypeError", ":", "result", "=", "v_function", "(", "instance", ",", "options", ")", "if", "isinstance", "(", "result", ",", "Iterable", ")", ":", "for", "x", "in", "result", ":", "yield", "x", "elif", "result", "is", "not", "None", ":", "yield", "result", "# Validate any child STIX objects", "for", "field", "in", "instance", ":", "if", "type", "(", "instance", "[", "field", "]", ")", "is", "list", ":", "for", "obj", "in", "instance", "[", "field", "]", ":", "if", "_is_stix_obj", "(", "obj", ")", ":", "for", "err", "in", "_iter_errors_custom", "(", "obj", ",", "checks", ",", "options", ")", ":", "yield", "err" ]
Perform additional validation not possible merely with JSON schemas. Args: instance: The STIX object to be validated. checks: A sequence of callables which do the checks. Each callable may be written to accept 1 arg, which is the object to check, or 2 args, which are the object and a ValidationOptions instance. options: ValidationOptions instance with settings affecting how validation should be done.
[ "Perform", "additional", "validation", "not", "possible", "merely", "with", "JSON", "schemas", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/validator.py#L34-L63
train
oasis-open/cti-stix-validator
stix2validator/validator.py
list_json_files
def list_json_files(directory, recursive=False): """Return a list of file paths for JSON files within `directory`. Args: directory: A path to a directory. recursive: If ``True``, this function will descend into all subdirectories. Returns: A list of JSON file paths directly under `directory`. """ json_files = [] for top, dirs, files in os.walk(directory): dirs.sort() # Get paths to each file in `files` paths = (os.path.join(top, f) for f in sorted(files)) # Add all the .json files to our return collection json_files.extend(x for x in paths if is_json(x)) if not recursive: break return json_files
python
def list_json_files(directory, recursive=False): """Return a list of file paths for JSON files within `directory`. Args: directory: A path to a directory. recursive: If ``True``, this function will descend into all subdirectories. Returns: A list of JSON file paths directly under `directory`. """ json_files = [] for top, dirs, files in os.walk(directory): dirs.sort() # Get paths to each file in `files` paths = (os.path.join(top, f) for f in sorted(files)) # Add all the .json files to our return collection json_files.extend(x for x in paths if is_json(x)) if not recursive: break return json_files
[ "def", "list_json_files", "(", "directory", ",", "recursive", "=", "False", ")", ":", "json_files", "=", "[", "]", "for", "top", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "directory", ")", ":", "dirs", ".", "sort", "(", ")", "# Get paths to each file in `files`", "paths", "=", "(", "os", ".", "path", ".", "join", "(", "top", ",", "f", ")", "for", "f", "in", "sorted", "(", "files", ")", ")", "# Add all the .json files to our return collection", "json_files", ".", "extend", "(", "x", "for", "x", "in", "paths", "if", "is_json", "(", "x", ")", ")", "if", "not", "recursive", ":", "break", "return", "json_files" ]
Return a list of file paths for JSON files within `directory`. Args: directory: A path to a directory. recursive: If ``True``, this function will descend into all subdirectories. Returns: A list of JSON file paths directly under `directory`.
[ "Return", "a", "list", "of", "file", "paths", "for", "JSON", "files", "within", "directory", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/validator.py#L281-L306
train
oasis-open/cti-stix-validator
stix2validator/validator.py
get_json_files
def get_json_files(files, recursive=False): """Return a list of files to validate from `files`. If a member of `files` is a directory, its children with a ``.json`` extension will be added to the return value. Args: files: A list of file paths and/or directory paths. recursive: If ``true``, this will descend into any subdirectories of input directories. Returns: A list of file paths to validate. """ json_files = [] if not files: return json_files for fn in files: if os.path.isdir(fn): children = list_json_files(fn, recursive) json_files.extend(children) elif is_json(fn): json_files.append(fn) else: continue if not json_files: raise NoJSONFileFoundError("No JSON files found!") return json_files
python
def get_json_files(files, recursive=False): """Return a list of files to validate from `files`. If a member of `files` is a directory, its children with a ``.json`` extension will be added to the return value. Args: files: A list of file paths and/or directory paths. recursive: If ``true``, this will descend into any subdirectories of input directories. Returns: A list of file paths to validate. """ json_files = [] if not files: return json_files for fn in files: if os.path.isdir(fn): children = list_json_files(fn, recursive) json_files.extend(children) elif is_json(fn): json_files.append(fn) else: continue if not json_files: raise NoJSONFileFoundError("No JSON files found!") return json_files
[ "def", "get_json_files", "(", "files", ",", "recursive", "=", "False", ")", ":", "json_files", "=", "[", "]", "if", "not", "files", ":", "return", "json_files", "for", "fn", "in", "files", ":", "if", "os", ".", "path", ".", "isdir", "(", "fn", ")", ":", "children", "=", "list_json_files", "(", "fn", ",", "recursive", ")", "json_files", ".", "extend", "(", "children", ")", "elif", "is_json", "(", "fn", ")", ":", "json_files", ".", "append", "(", "fn", ")", "else", ":", "continue", "if", "not", "json_files", ":", "raise", "NoJSONFileFoundError", "(", "\"No JSON files found!\"", ")", "return", "json_files" ]
Return a list of files to validate from `files`. If a member of `files` is a directory, its children with a ``.json`` extension will be added to the return value. Args: files: A list of file paths and/or directory paths. recursive: If ``true``, this will descend into any subdirectories of input directories. Returns: A list of file paths to validate.
[ "Return", "a", "list", "of", "files", "to", "validate", "from", "files", ".", "If", "a", "member", "of", "files", "is", "a", "directory", "its", "children", "with", "a", ".", "json", "extension", "will", "be", "added", "to", "the", "return", "value", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/validator.py#L309-L339
train
oasis-open/cti-stix-validator
stix2validator/validator.py
run_validation
def run_validation(options): """Validate files based on command line options. Args: options: An instance of ``ValidationOptions`` containing options for this validation run. """ if options.files == sys.stdin: results = validate(options.files, options) return [FileValidationResults(is_valid=results.is_valid, filepath='stdin', object_results=results)] files = get_json_files(options.files, options.recursive) results = [validate_file(fn, options) for fn in files] return results
python
def run_validation(options): """Validate files based on command line options. Args: options: An instance of ``ValidationOptions`` containing options for this validation run. """ if options.files == sys.stdin: results = validate(options.files, options) return [FileValidationResults(is_valid=results.is_valid, filepath='stdin', object_results=results)] files = get_json_files(options.files, options.recursive) results = [validate_file(fn, options) for fn in files] return results
[ "def", "run_validation", "(", "options", ")", ":", "if", "options", ".", "files", "==", "sys", ".", "stdin", ":", "results", "=", "validate", "(", "options", ".", "files", ",", "options", ")", "return", "[", "FileValidationResults", "(", "is_valid", "=", "results", ".", "is_valid", ",", "filepath", "=", "'stdin'", ",", "object_results", "=", "results", ")", "]", "files", "=", "get_json_files", "(", "options", ".", "files", ",", "options", ".", "recursive", ")", "results", "=", "[", "validate_file", "(", "fn", ",", "options", ")", "for", "fn", "in", "files", "]", "return", "results" ]
Validate files based on command line options. Args: options: An instance of ``ValidationOptions`` containing options for this validation run.
[ "Validate", "files", "based", "on", "command", "line", "options", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/validator.py#L342-L360
train
oasis-open/cti-stix-validator
stix2validator/validator.py
validate_parsed_json
def validate_parsed_json(obj_json, options=None): """ Validate objects from parsed JSON. This supports a single object, or a list of objects. If a single object is given, a single result is returned. Otherwise, a list of results is returned. If an error occurs, a ValidationErrorResults instance or list which includes one of these instances, is returned. :param obj_json: The parsed json :param options: Validation options :return: An ObjectValidationResults instance, or a list of such. """ validating_list = isinstance(obj_json, list) if not options: options = ValidationOptions() if not options.no_cache: init_requests_cache(options.refresh_cache) results = None if validating_list: results = [] for obj in obj_json: try: results.append(validate_instance(obj, options)) except SchemaInvalidError as ex: error_result = ObjectValidationResults(is_valid=False, object_id=obj.get('id', ''), errors=[str(ex)]) results.append(error_result) else: try: results = validate_instance(obj_json, options) except SchemaInvalidError as ex: error_result = ObjectValidationResults(is_valid=False, object_id=obj_json.get('id', ''), errors=[str(ex)]) results = error_result if not options.no_cache and options.clear_cache: clear_requests_cache() return results
python
def validate_parsed_json(obj_json, options=None): """ Validate objects from parsed JSON. This supports a single object, or a list of objects. If a single object is given, a single result is returned. Otherwise, a list of results is returned. If an error occurs, a ValidationErrorResults instance or list which includes one of these instances, is returned. :param obj_json: The parsed json :param options: Validation options :return: An ObjectValidationResults instance, or a list of such. """ validating_list = isinstance(obj_json, list) if not options: options = ValidationOptions() if not options.no_cache: init_requests_cache(options.refresh_cache) results = None if validating_list: results = [] for obj in obj_json: try: results.append(validate_instance(obj, options)) except SchemaInvalidError as ex: error_result = ObjectValidationResults(is_valid=False, object_id=obj.get('id', ''), errors=[str(ex)]) results.append(error_result) else: try: results = validate_instance(obj_json, options) except SchemaInvalidError as ex: error_result = ObjectValidationResults(is_valid=False, object_id=obj_json.get('id', ''), errors=[str(ex)]) results = error_result if not options.no_cache and options.clear_cache: clear_requests_cache() return results
[ "def", "validate_parsed_json", "(", "obj_json", ",", "options", "=", "None", ")", ":", "validating_list", "=", "isinstance", "(", "obj_json", ",", "list", ")", "if", "not", "options", ":", "options", "=", "ValidationOptions", "(", ")", "if", "not", "options", ".", "no_cache", ":", "init_requests_cache", "(", "options", ".", "refresh_cache", ")", "results", "=", "None", "if", "validating_list", ":", "results", "=", "[", "]", "for", "obj", "in", "obj_json", ":", "try", ":", "results", ".", "append", "(", "validate_instance", "(", "obj", ",", "options", ")", ")", "except", "SchemaInvalidError", "as", "ex", ":", "error_result", "=", "ObjectValidationResults", "(", "is_valid", "=", "False", ",", "object_id", "=", "obj", ".", "get", "(", "'id'", ",", "''", ")", ",", "errors", "=", "[", "str", "(", "ex", ")", "]", ")", "results", ".", "append", "(", "error_result", ")", "else", ":", "try", ":", "results", "=", "validate_instance", "(", "obj_json", ",", "options", ")", "except", "SchemaInvalidError", "as", "ex", ":", "error_result", "=", "ObjectValidationResults", "(", "is_valid", "=", "False", ",", "object_id", "=", "obj_json", ".", "get", "(", "'id'", ",", "''", ")", ",", "errors", "=", "[", "str", "(", "ex", ")", "]", ")", "results", "=", "error_result", "if", "not", "options", ".", "no_cache", "and", "options", ".", "clear_cache", ":", "clear_requests_cache", "(", ")", "return", "results" ]
Validate objects from parsed JSON. This supports a single object, or a list of objects. If a single object is given, a single result is returned. Otherwise, a list of results is returned. If an error occurs, a ValidationErrorResults instance or list which includes one of these instances, is returned. :param obj_json: The parsed json :param options: Validation options :return: An ObjectValidationResults instance, or a list of such.
[ "Validate", "objects", "from", "parsed", "JSON", ".", "This", "supports", "a", "single", "object", "or", "a", "list", "of", "objects", ".", "If", "a", "single", "object", "is", "given", "a", "single", "result", "is", "returned", ".", "Otherwise", "a", "list", "of", "results", "is", "returned", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/validator.py#L363-L408
train
oasis-open/cti-stix-validator
stix2validator/validator.py
validate
def validate(in_, options=None): """ Validate objects from JSON data in a textual stream. :param in_: A textual stream of JSON data. :param options: Validation options :return: An ObjectValidationResults instance, or a list of such. """ obj_json = json.load(in_) results = validate_parsed_json(obj_json, options) return results
python
def validate(in_, options=None): """ Validate objects from JSON data in a textual stream. :param in_: A textual stream of JSON data. :param options: Validation options :return: An ObjectValidationResults instance, or a list of such. """ obj_json = json.load(in_) results = validate_parsed_json(obj_json, options) return results
[ "def", "validate", "(", "in_", ",", "options", "=", "None", ")", ":", "obj_json", "=", "json", ".", "load", "(", "in_", ")", "results", "=", "validate_parsed_json", "(", "obj_json", ",", "options", ")", "return", "results" ]
Validate objects from JSON data in a textual stream. :param in_: A textual stream of JSON data. :param options: Validation options :return: An ObjectValidationResults instance, or a list of such.
[ "Validate", "objects", "from", "JSON", "data", "in", "a", "textual", "stream", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/validator.py#L411-L423
train
oasis-open/cti-stix-validator
stix2validator/validator.py
validate_file
def validate_file(fn, options=None): """Validate the input document `fn` according to the options passed in. If any exceptions are raised during validation, no further validation will take place. Args: fn: The filename of the JSON file to be validated. options: An instance of ``ValidationOptions``. Returns: An instance of FileValidationResults. """ file_results = FileValidationResults(filepath=fn) output.info("Performing JSON schema validation on %s" % fn) if not options: options = ValidationOptions(files=fn) try: with open(fn) as instance_file: file_results.object_results = validate(instance_file, options) except Exception as ex: if 'Expecting value' in str(ex): line_no = str(ex).split()[3] file_results.fatal = ValidationErrorResults( 'Invalid JSON input on line %s' % line_no ) else: file_results.fatal = ValidationErrorResults(ex) msg = ("Unexpected error occurred with file '{fn}'. No further " "validation will be performed: {error}") output.info(msg.format(fn=fn, error=str(ex))) file_results.is_valid = (all(object_result.is_valid for object_result in file_results.object_results) and not file_results.fatal) return file_results
python
def validate_file(fn, options=None): """Validate the input document `fn` according to the options passed in. If any exceptions are raised during validation, no further validation will take place. Args: fn: The filename of the JSON file to be validated. options: An instance of ``ValidationOptions``. Returns: An instance of FileValidationResults. """ file_results = FileValidationResults(filepath=fn) output.info("Performing JSON schema validation on %s" % fn) if not options: options = ValidationOptions(files=fn) try: with open(fn) as instance_file: file_results.object_results = validate(instance_file, options) except Exception as ex: if 'Expecting value' in str(ex): line_no = str(ex).split()[3] file_results.fatal = ValidationErrorResults( 'Invalid JSON input on line %s' % line_no ) else: file_results.fatal = ValidationErrorResults(ex) msg = ("Unexpected error occurred with file '{fn}'. No further " "validation will be performed: {error}") output.info(msg.format(fn=fn, error=str(ex))) file_results.is_valid = (all(object_result.is_valid for object_result in file_results.object_results) and not file_results.fatal) return file_results
[ "def", "validate_file", "(", "fn", ",", "options", "=", "None", ")", ":", "file_results", "=", "FileValidationResults", "(", "filepath", "=", "fn", ")", "output", ".", "info", "(", "\"Performing JSON schema validation on %s\"", "%", "fn", ")", "if", "not", "options", ":", "options", "=", "ValidationOptions", "(", "files", "=", "fn", ")", "try", ":", "with", "open", "(", "fn", ")", "as", "instance_file", ":", "file_results", ".", "object_results", "=", "validate", "(", "instance_file", ",", "options", ")", "except", "Exception", "as", "ex", ":", "if", "'Expecting value'", "in", "str", "(", "ex", ")", ":", "line_no", "=", "str", "(", "ex", ")", ".", "split", "(", ")", "[", "3", "]", "file_results", ".", "fatal", "=", "ValidationErrorResults", "(", "'Invalid JSON input on line %s'", "%", "line_no", ")", "else", ":", "file_results", ".", "fatal", "=", "ValidationErrorResults", "(", "ex", ")", "msg", "=", "(", "\"Unexpected error occurred with file '{fn}'. No further \"", "\"validation will be performed: {error}\"", ")", "output", ".", "info", "(", "msg", ".", "format", "(", "fn", "=", "fn", ",", "error", "=", "str", "(", "ex", ")", ")", ")", "file_results", ".", "is_valid", "=", "(", "all", "(", "object_result", ".", "is_valid", "for", "object_result", "in", "file_results", ".", "object_results", ")", "and", "not", "file_results", ".", "fatal", ")", "return", "file_results" ]
Validate the input document `fn` according to the options passed in. If any exceptions are raised during validation, no further validation will take place. Args: fn: The filename of the JSON file to be validated. options: An instance of ``ValidationOptions``. Returns: An instance of FileValidationResults.
[ "Validate", "the", "input", "document", "fn", "according", "to", "the", "options", "passed", "in", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/validator.py#L426-L467
train
oasis-open/cti-stix-validator
stix2validator/validator.py
validate_string
def validate_string(string, options=None): """Validate the input `string` according to the options passed in. If any exceptions are raised during validation, no further validation will take place. Args: string: The string containing the JSON to be validated. options: An instance of ``ValidationOptions``. Returns: An ObjectValidationResults instance, or a list of such. """ output.info("Performing JSON schema validation on input string: " + string) stream = io.StringIO(string) return validate(stream, options)
python
def validate_string(string, options=None): """Validate the input `string` according to the options passed in. If any exceptions are raised during validation, no further validation will take place. Args: string: The string containing the JSON to be validated. options: An instance of ``ValidationOptions``. Returns: An ObjectValidationResults instance, or a list of such. """ output.info("Performing JSON schema validation on input string: " + string) stream = io.StringIO(string) return validate(stream, options)
[ "def", "validate_string", "(", "string", ",", "options", "=", "None", ")", ":", "output", ".", "info", "(", "\"Performing JSON schema validation on input string: \"", "+", "string", ")", "stream", "=", "io", ".", "StringIO", "(", "string", ")", "return", "validate", "(", "stream", ",", "options", ")" ]
Validate the input `string` according to the options passed in. If any exceptions are raised during validation, no further validation will take place. Args: string: The string containing the JSON to be validated. options: An instance of ``ValidationOptions``. Returns: An ObjectValidationResults instance, or a list of such.
[ "Validate", "the", "input", "string", "according", "to", "the", "options", "passed", "in", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/validator.py#L470-L486
train
oasis-open/cti-stix-validator
stix2validator/validator.py
load_validator
def load_validator(schema_path, schema): """Create a JSON schema validator for the given schema. Args: schema_path: The filename of the JSON schema. schema: A Python object representation of the same schema. Returns: An instance of Draft4Validator. """ # Get correct prefix based on OS if os.name == 'nt': file_prefix = 'file:///' else: file_prefix = 'file:' resolver = RefResolver(file_prefix + schema_path.replace("\\", "/"), schema) validator = Draft4Validator(schema, resolver=resolver) return validator
python
def load_validator(schema_path, schema): """Create a JSON schema validator for the given schema. Args: schema_path: The filename of the JSON schema. schema: A Python object representation of the same schema. Returns: An instance of Draft4Validator. """ # Get correct prefix based on OS if os.name == 'nt': file_prefix = 'file:///' else: file_prefix = 'file:' resolver = RefResolver(file_prefix + schema_path.replace("\\", "/"), schema) validator = Draft4Validator(schema, resolver=resolver) return validator
[ "def", "load_validator", "(", "schema_path", ",", "schema", ")", ":", "# Get correct prefix based on OS", "if", "os", ".", "name", "==", "'nt'", ":", "file_prefix", "=", "'file:///'", "else", ":", "file_prefix", "=", "'file:'", "resolver", "=", "RefResolver", "(", "file_prefix", "+", "schema_path", ".", "replace", "(", "\"\\\\\"", ",", "\"/\"", ")", ",", "schema", ")", "validator", "=", "Draft4Validator", "(", "schema", ",", "resolver", "=", "resolver", ")", "return", "validator" ]
Create a JSON schema validator for the given schema. Args: schema_path: The filename of the JSON schema. schema: A Python object representation of the same schema. Returns: An instance of Draft4Validator.
[ "Create", "a", "JSON", "schema", "validator", "for", "the", "given", "schema", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/validator.py#L489-L509
train
oasis-open/cti-stix-validator
stix2validator/validator.py
find_schema
def find_schema(schema_dir, obj_type): """Search the `schema_dir` directory for a schema called `obj_type`.json. Return the file path of the first match it finds. """ schema_filename = obj_type + '.json' for root, dirnames, filenames in os.walk(schema_dir): if schema_filename in filenames: return os.path.join(root, schema_filename)
python
def find_schema(schema_dir, obj_type): """Search the `schema_dir` directory for a schema called `obj_type`.json. Return the file path of the first match it finds. """ schema_filename = obj_type + '.json' for root, dirnames, filenames in os.walk(schema_dir): if schema_filename in filenames: return os.path.join(root, schema_filename)
[ "def", "find_schema", "(", "schema_dir", ",", "obj_type", ")", ":", "schema_filename", "=", "obj_type", "+", "'.json'", "for", "root", ",", "dirnames", ",", "filenames", "in", "os", ".", "walk", "(", "schema_dir", ")", ":", "if", "schema_filename", "in", "filenames", ":", "return", "os", ".", "path", ".", "join", "(", "root", ",", "schema_filename", ")" ]
Search the `schema_dir` directory for a schema called `obj_type`.json. Return the file path of the first match it finds.
[ "Search", "the", "schema_dir", "directory", "for", "a", "schema", "called", "obj_type", ".", "json", ".", "Return", "the", "file", "path", "of", "the", "first", "match", "it", "finds", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/validator.py#L512-L520
train
oasis-open/cti-stix-validator
stix2validator/validator.py
load_schema
def load_schema(schema_path): """Load the JSON schema at the given path as a Python object. Args: schema_path: A filename for a JSON schema. Returns: A Python object representation of the schema. """ try: with open(schema_path) as schema_file: schema = json.load(schema_file) except ValueError as e: raise SchemaInvalidError('Invalid JSON in schema or included schema: ' '%s\n%s' % (schema_file.name, str(e))) return schema
python
def load_schema(schema_path): """Load the JSON schema at the given path as a Python object. Args: schema_path: A filename for a JSON schema. Returns: A Python object representation of the schema. """ try: with open(schema_path) as schema_file: schema = json.load(schema_file) except ValueError as e: raise SchemaInvalidError('Invalid JSON in schema or included schema: ' '%s\n%s' % (schema_file.name, str(e))) return schema
[ "def", "load_schema", "(", "schema_path", ")", ":", "try", ":", "with", "open", "(", "schema_path", ")", "as", "schema_file", ":", "schema", "=", "json", ".", "load", "(", "schema_file", ")", "except", "ValueError", "as", "e", ":", "raise", "SchemaInvalidError", "(", "'Invalid JSON in schema or included schema: '", "'%s\\n%s'", "%", "(", "schema_file", ".", "name", ",", "str", "(", "e", ")", ")", ")", "return", "schema" ]
Load the JSON schema at the given path as a Python object. Args: schema_path: A filename for a JSON schema. Returns: A Python object representation of the schema.
[ "Load", "the", "JSON", "schema", "at", "the", "given", "path", "as", "a", "Python", "object", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/validator.py#L523-L540
train
oasis-open/cti-stix-validator
stix2validator/validator.py
_get_error_generator
def _get_error_generator(type, obj, schema_dir=None, version=DEFAULT_VER, default='core'): """Get a generator for validating against the schema for the given object type. Args: type (str): The object type to find the schema for. obj: The object to be validated. schema_dir (str): The path in which to search for schemas. version (str): The version of the STIX specification to validate against. Only used to find base schemas when schema_dir is None. default (str): If the schema for the given type cannot be found, use the one with this name instead. Returns: A generator for errors found when validating the object against the appropriate schema, or None if schema_dir is None and the schema cannot be found. """ # If no schema directory given, use default for the given STIX version, # which comes bundled with this package if schema_dir is None: schema_dir = os.path.abspath(os.path.dirname(__file__) + '/schemas-' + version + '/') try: schema_path = find_schema(schema_dir, type) schema = load_schema(schema_path) except (KeyError, TypeError): # Assume a custom object with no schema try: schema_path = find_schema(schema_dir, default) schema = load_schema(schema_path) except (KeyError, TypeError): # Only raise an error when checking against default schemas, not custom if schema_dir is not None: return None raise SchemaInvalidError("Cannot locate a schema for the object's " "type, nor the base schema ({}.json).".format(default)) if type == 'observed-data' and schema_dir is None: # Validate against schemas for specific observed data object types later. # If schema_dir is not None the schema is custom and won't need to be modified. schema['allOf'][1]['properties']['objects'] = { "objects": { "type": "object", "minProperties": 1 } } # Don't use custom validator; only check schemas, no additional checks validator = load_validator(schema_path, schema) try: error_gen = validator.iter_errors(obj) except schema_exceptions.RefResolutionError: raise SchemaInvalidError('Invalid JSON schema: a JSON ' 'reference failed to resolve') return error_gen
python
def _get_error_generator(type, obj, schema_dir=None, version=DEFAULT_VER, default='core'): """Get a generator for validating against the schema for the given object type. Args: type (str): The object type to find the schema for. obj: The object to be validated. schema_dir (str): The path in which to search for schemas. version (str): The version of the STIX specification to validate against. Only used to find base schemas when schema_dir is None. default (str): If the schema for the given type cannot be found, use the one with this name instead. Returns: A generator for errors found when validating the object against the appropriate schema, or None if schema_dir is None and the schema cannot be found. """ # If no schema directory given, use default for the given STIX version, # which comes bundled with this package if schema_dir is None: schema_dir = os.path.abspath(os.path.dirname(__file__) + '/schemas-' + version + '/') try: schema_path = find_schema(schema_dir, type) schema = load_schema(schema_path) except (KeyError, TypeError): # Assume a custom object with no schema try: schema_path = find_schema(schema_dir, default) schema = load_schema(schema_path) except (KeyError, TypeError): # Only raise an error when checking against default schemas, not custom if schema_dir is not None: return None raise SchemaInvalidError("Cannot locate a schema for the object's " "type, nor the base schema ({}.json).".format(default)) if type == 'observed-data' and schema_dir is None: # Validate against schemas for specific observed data object types later. # If schema_dir is not None the schema is custom and won't need to be modified. schema['allOf'][1]['properties']['objects'] = { "objects": { "type": "object", "minProperties": 1 } } # Don't use custom validator; only check schemas, no additional checks validator = load_validator(schema_path, schema) try: error_gen = validator.iter_errors(obj) except schema_exceptions.RefResolutionError: raise SchemaInvalidError('Invalid JSON schema: a JSON ' 'reference failed to resolve') return error_gen
[ "def", "_get_error_generator", "(", "type", ",", "obj", ",", "schema_dir", "=", "None", ",", "version", "=", "DEFAULT_VER", ",", "default", "=", "'core'", ")", ":", "# If no schema directory given, use default for the given STIX version,", "# which comes bundled with this package", "if", "schema_dir", "is", "None", ":", "schema_dir", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", "+", "'/schemas-'", "+", "version", "+", "'/'", ")", "try", ":", "schema_path", "=", "find_schema", "(", "schema_dir", ",", "type", ")", "schema", "=", "load_schema", "(", "schema_path", ")", "except", "(", "KeyError", ",", "TypeError", ")", ":", "# Assume a custom object with no schema", "try", ":", "schema_path", "=", "find_schema", "(", "schema_dir", ",", "default", ")", "schema", "=", "load_schema", "(", "schema_path", ")", "except", "(", "KeyError", ",", "TypeError", ")", ":", "# Only raise an error when checking against default schemas, not custom", "if", "schema_dir", "is", "not", "None", ":", "return", "None", "raise", "SchemaInvalidError", "(", "\"Cannot locate a schema for the object's \"", "\"type, nor the base schema ({}.json).\"", ".", "format", "(", "default", ")", ")", "if", "type", "==", "'observed-data'", "and", "schema_dir", "is", "None", ":", "# Validate against schemas for specific observed data object types later.", "# If schema_dir is not None the schema is custom and won't need to be modified.", "schema", "[", "'allOf'", "]", "[", "1", "]", "[", "'properties'", "]", "[", "'objects'", "]", "=", "{", "\"objects\"", ":", "{", "\"type\"", ":", "\"object\"", ",", "\"minProperties\"", ":", "1", "}", "}", "# Don't use custom validator; only check schemas, no additional checks", "validator", "=", "load_validator", "(", "schema_path", ",", "schema", ")", "try", ":", "error_gen", "=", "validator", ".", "iter_errors", "(", "obj", ")", "except", "schema_exceptions", ".", "RefResolutionError", ":", "raise", "SchemaInvalidError", "(", "'Invalid JSON schema: a JSON '", "'reference failed to resolve'", ")", "return", "error_gen" ]
Get a generator for validating against the schema for the given object type. Args: type (str): The object type to find the schema for. obj: The object to be validated. schema_dir (str): The path in which to search for schemas. version (str): The version of the STIX specification to validate against. Only used to find base schemas when schema_dir is None. default (str): If the schema for the given type cannot be found, use the one with this name instead. Returns: A generator for errors found when validating the object against the appropriate schema, or None if schema_dir is None and the schema cannot be found.
[ "Get", "a", "generator", "for", "validating", "against", "the", "schema", "for", "the", "given", "object", "type", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/validator.py#L543-L598
train
oasis-open/cti-stix-validator
stix2validator/validator.py
_get_musts
def _get_musts(options): """Return the list of 'MUST' validators for the correct version of STIX. Args: options: ValidationOptions instance with validation options for this validation run, including the STIX spec version. """ if options.version == '2.0': return musts20.list_musts(options) else: return musts21.list_musts(options)
python
def _get_musts(options): """Return the list of 'MUST' validators for the correct version of STIX. Args: options: ValidationOptions instance with validation options for this validation run, including the STIX spec version. """ if options.version == '2.0': return musts20.list_musts(options) else: return musts21.list_musts(options)
[ "def", "_get_musts", "(", "options", ")", ":", "if", "options", ".", "version", "==", "'2.0'", ":", "return", "musts20", ".", "list_musts", "(", "options", ")", "else", ":", "return", "musts21", ".", "list_musts", "(", "options", ")" ]
Return the list of 'MUST' validators for the correct version of STIX. Args: options: ValidationOptions instance with validation options for this validation run, including the STIX spec version.
[ "Return", "the", "list", "of", "MUST", "validators", "for", "the", "correct", "version", "of", "STIX", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/validator.py#L601-L611
train
oasis-open/cti-stix-validator
stix2validator/validator.py
_get_shoulds
def _get_shoulds(options): """Return the list of 'SHOULD' validators for the correct version of STIX. Args: options: ValidationOptions instance with validation options for this validation run, including the STIX spec version. """ if options.version == '2.0': return shoulds20.list_shoulds(options) else: return shoulds21.list_shoulds(options)
python
def _get_shoulds(options): """Return the list of 'SHOULD' validators for the correct version of STIX. Args: options: ValidationOptions instance with validation options for this validation run, including the STIX spec version. """ if options.version == '2.0': return shoulds20.list_shoulds(options) else: return shoulds21.list_shoulds(options)
[ "def", "_get_shoulds", "(", "options", ")", ":", "if", "options", ".", "version", "==", "'2.0'", ":", "return", "shoulds20", ".", "list_shoulds", "(", "options", ")", "else", ":", "return", "shoulds21", ".", "list_shoulds", "(", "options", ")" ]
Return the list of 'SHOULD' validators for the correct version of STIX. Args: options: ValidationOptions instance with validation options for this validation run, including the STIX spec version.
[ "Return", "the", "list", "of", "SHOULD", "validators", "for", "the", "correct", "version", "of", "STIX", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/validator.py#L614-L624
train
oasis-open/cti-stix-validator
stix2validator/validator.py
_schema_validate
def _schema_validate(sdo, options): """Set up validation of a single STIX object against its type's schema. This does no actual validation; it just returns generators which must be iterated to trigger the actual generation. This function first creates generators for the built-in schemas, then adds generators for additional schemas from the options, if specified. Do not call this function directly; use validate_instance() instead, as it calls this one. This function does not perform any custom checks. """ error_gens = [] if 'id' in sdo: try: error_prefix = sdo['id'] + ": " except TypeError: error_prefix = 'unidentifiable object: ' else: error_prefix = '' # Get validator for built-in schema base_sdo_errors = _get_error_generator(sdo['type'], sdo, version=options.version) if base_sdo_errors: error_gens.append((base_sdo_errors, error_prefix)) # Get validator for any user-supplied schema if options.schema_dir: custom_sdo_errors = _get_error_generator(sdo['type'], sdo, options.schema_dir) if custom_sdo_errors: error_gens.append((custom_sdo_errors, error_prefix)) # Validate each cyber observable object separately if sdo['type'] == 'observed-data' and 'objects' in sdo: # Check if observed data property is in dictionary format if not isinstance(sdo['objects'], dict): error_gens.append(([schema_exceptions.ValidationError("Observed Data objects must be in dict format.", error_prefix)], error_prefix)) return error_gens for key, obj in iteritems(sdo['objects']): if 'type' not in obj: error_gens.append(([schema_exceptions.ValidationError("Observable object must contain a 'type' property.", error_prefix)], error_prefix + 'object \'' + key + '\': ')) continue # Get validator for built-in schemas base_obs_errors = _get_error_generator(obj['type'], obj, None, options.version, 'cyber-observable-core') if base_obs_errors: error_gens.append((base_obs_errors, error_prefix + 'object \'' + key + '\': ')) # Get validator for any user-supplied schema custom_obs_errors = _get_error_generator(obj['type'], obj, options.schema_dir, options.version, 'cyber-observable-core') if custom_obs_errors: error_gens.append((custom_obs_errors, error_prefix + 'object \'' + key + '\': ')) return error_gens
python
def _schema_validate(sdo, options): """Set up validation of a single STIX object against its type's schema. This does no actual validation; it just returns generators which must be iterated to trigger the actual generation. This function first creates generators for the built-in schemas, then adds generators for additional schemas from the options, if specified. Do not call this function directly; use validate_instance() instead, as it calls this one. This function does not perform any custom checks. """ error_gens = [] if 'id' in sdo: try: error_prefix = sdo['id'] + ": " except TypeError: error_prefix = 'unidentifiable object: ' else: error_prefix = '' # Get validator for built-in schema base_sdo_errors = _get_error_generator(sdo['type'], sdo, version=options.version) if base_sdo_errors: error_gens.append((base_sdo_errors, error_prefix)) # Get validator for any user-supplied schema if options.schema_dir: custom_sdo_errors = _get_error_generator(sdo['type'], sdo, options.schema_dir) if custom_sdo_errors: error_gens.append((custom_sdo_errors, error_prefix)) # Validate each cyber observable object separately if sdo['type'] == 'observed-data' and 'objects' in sdo: # Check if observed data property is in dictionary format if not isinstance(sdo['objects'], dict): error_gens.append(([schema_exceptions.ValidationError("Observed Data objects must be in dict format.", error_prefix)], error_prefix)) return error_gens for key, obj in iteritems(sdo['objects']): if 'type' not in obj: error_gens.append(([schema_exceptions.ValidationError("Observable object must contain a 'type' property.", error_prefix)], error_prefix + 'object \'' + key + '\': ')) continue # Get validator for built-in schemas base_obs_errors = _get_error_generator(obj['type'], obj, None, options.version, 'cyber-observable-core') if base_obs_errors: error_gens.append((base_obs_errors, error_prefix + 'object \'' + key + '\': ')) # Get validator for any user-supplied schema custom_obs_errors = _get_error_generator(obj['type'], obj, options.schema_dir, options.version, 'cyber-observable-core') if custom_obs_errors: error_gens.append((custom_obs_errors, error_prefix + 'object \'' + key + '\': ')) return error_gens
[ "def", "_schema_validate", "(", "sdo", ",", "options", ")", ":", "error_gens", "=", "[", "]", "if", "'id'", "in", "sdo", ":", "try", ":", "error_prefix", "=", "sdo", "[", "'id'", "]", "+", "\": \"", "except", "TypeError", ":", "error_prefix", "=", "'unidentifiable object: '", "else", ":", "error_prefix", "=", "''", "# Get validator for built-in schema", "base_sdo_errors", "=", "_get_error_generator", "(", "sdo", "[", "'type'", "]", ",", "sdo", ",", "version", "=", "options", ".", "version", ")", "if", "base_sdo_errors", ":", "error_gens", ".", "append", "(", "(", "base_sdo_errors", ",", "error_prefix", ")", ")", "# Get validator for any user-supplied schema", "if", "options", ".", "schema_dir", ":", "custom_sdo_errors", "=", "_get_error_generator", "(", "sdo", "[", "'type'", "]", ",", "sdo", ",", "options", ".", "schema_dir", ")", "if", "custom_sdo_errors", ":", "error_gens", ".", "append", "(", "(", "custom_sdo_errors", ",", "error_prefix", ")", ")", "# Validate each cyber observable object separately", "if", "sdo", "[", "'type'", "]", "==", "'observed-data'", "and", "'objects'", "in", "sdo", ":", "# Check if observed data property is in dictionary format", "if", "not", "isinstance", "(", "sdo", "[", "'objects'", "]", ",", "dict", ")", ":", "error_gens", ".", "append", "(", "(", "[", "schema_exceptions", ".", "ValidationError", "(", "\"Observed Data objects must be in dict format.\"", ",", "error_prefix", ")", "]", ",", "error_prefix", ")", ")", "return", "error_gens", "for", "key", ",", "obj", "in", "iteritems", "(", "sdo", "[", "'objects'", "]", ")", ":", "if", "'type'", "not", "in", "obj", ":", "error_gens", ".", "append", "(", "(", "[", "schema_exceptions", ".", "ValidationError", "(", "\"Observable object must contain a 'type' property.\"", ",", "error_prefix", ")", "]", ",", "error_prefix", "+", "'object \\''", "+", "key", "+", "'\\': '", ")", ")", "continue", "# Get validator for built-in schemas", "base_obs_errors", "=", "_get_error_generator", "(", "obj", "[", "'type'", "]", ",", "obj", ",", "None", ",", "options", ".", "version", ",", "'cyber-observable-core'", ")", "if", "base_obs_errors", ":", "error_gens", ".", "append", "(", "(", "base_obs_errors", ",", "error_prefix", "+", "'object \\''", "+", "key", "+", "'\\': '", ")", ")", "# Get validator for any user-supplied schema", "custom_obs_errors", "=", "_get_error_generator", "(", "obj", "[", "'type'", "]", ",", "obj", ",", "options", ".", "schema_dir", ",", "options", ".", "version", ",", "'cyber-observable-core'", ")", "if", "custom_obs_errors", ":", "error_gens", ".", "append", "(", "(", "custom_obs_errors", ",", "error_prefix", "+", "'object \\''", "+", "key", "+", "'\\': '", ")", ")", "return", "error_gens" ]
Set up validation of a single STIX object against its type's schema. This does no actual validation; it just returns generators which must be iterated to trigger the actual generation. This function first creates generators for the built-in schemas, then adds generators for additional schemas from the options, if specified. Do not call this function directly; use validate_instance() instead, as it calls this one. This function does not perform any custom checks.
[ "Set", "up", "validation", "of", "a", "single", "STIX", "object", "against", "its", "type", "s", "schema", ".", "This", "does", "no", "actual", "validation", ";", "it", "just", "returns", "generators", "which", "must", "be", "iterated", "to", "trigger", "the", "actual", "generation", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/validator.py#L627-L692
train
oasis-open/cti-stix-validator
stix2validator/validator.py
validate_instance
def validate_instance(instance, options=None): """Perform STIX JSON Schema validation against STIX input. Find the correct schema by looking at the 'type' property of the `instance` JSON object. Args: instance: A Python dictionary representing a STIX object with a 'type' property. options: ValidationOptions instance with validation options for this validation run. Returns: A dictionary of validation results """ if 'type' not in instance: raise ValidationError("Input must be an object with a 'type' property.") if not options: options = ValidationOptions() error_gens = [] # Schema validation if instance['type'] == 'bundle' and 'objects' in instance: # Validate each object in a bundle separately for sdo in instance['objects']: if 'type' not in sdo: raise ValidationError("Each object in bundle must have a 'type' property.") error_gens += _schema_validate(sdo, options) else: error_gens += _schema_validate(instance, options) # Custom validation must_checks = _get_musts(options) should_checks = _get_shoulds(options) output.info("Running the following additional checks: %s." % ", ".join(x.__name__ for x in chain(must_checks, should_checks))) try: errors = _iter_errors_custom(instance, must_checks, options) warnings = _iter_errors_custom(instance, should_checks, options) if options.strict: chained_errors = chain(errors, warnings) warnings = [] else: chained_errors = errors warnings = [pretty_error(x, options.verbose) for x in warnings] except schema_exceptions.RefResolutionError: raise SchemaInvalidError('Invalid JSON schema: a JSON reference ' 'failed to resolve') # List of error generators and message prefixes (to denote which object the # error comes from) error_gens += [(chained_errors, '')] # Prepare the list of errors (this actually triggers the custom validation # functions). error_list = [] for gen, prefix in error_gens: for error in gen: msg = prefix + pretty_error(error, options.verbose) error_list.append(SchemaError(msg)) if error_list: valid = False else: valid = True return ObjectValidationResults(is_valid=valid, object_id=instance.get('id', ''), errors=error_list, warnings=warnings)
python
def validate_instance(instance, options=None): """Perform STIX JSON Schema validation against STIX input. Find the correct schema by looking at the 'type' property of the `instance` JSON object. Args: instance: A Python dictionary representing a STIX object with a 'type' property. options: ValidationOptions instance with validation options for this validation run. Returns: A dictionary of validation results """ if 'type' not in instance: raise ValidationError("Input must be an object with a 'type' property.") if not options: options = ValidationOptions() error_gens = [] # Schema validation if instance['type'] == 'bundle' and 'objects' in instance: # Validate each object in a bundle separately for sdo in instance['objects']: if 'type' not in sdo: raise ValidationError("Each object in bundle must have a 'type' property.") error_gens += _schema_validate(sdo, options) else: error_gens += _schema_validate(instance, options) # Custom validation must_checks = _get_musts(options) should_checks = _get_shoulds(options) output.info("Running the following additional checks: %s." % ", ".join(x.__name__ for x in chain(must_checks, should_checks))) try: errors = _iter_errors_custom(instance, must_checks, options) warnings = _iter_errors_custom(instance, should_checks, options) if options.strict: chained_errors = chain(errors, warnings) warnings = [] else: chained_errors = errors warnings = [pretty_error(x, options.verbose) for x in warnings] except schema_exceptions.RefResolutionError: raise SchemaInvalidError('Invalid JSON schema: a JSON reference ' 'failed to resolve') # List of error generators and message prefixes (to denote which object the # error comes from) error_gens += [(chained_errors, '')] # Prepare the list of errors (this actually triggers the custom validation # functions). error_list = [] for gen, prefix in error_gens: for error in gen: msg = prefix + pretty_error(error, options.verbose) error_list.append(SchemaError(msg)) if error_list: valid = False else: valid = True return ObjectValidationResults(is_valid=valid, object_id=instance.get('id', ''), errors=error_list, warnings=warnings)
[ "def", "validate_instance", "(", "instance", ",", "options", "=", "None", ")", ":", "if", "'type'", "not", "in", "instance", ":", "raise", "ValidationError", "(", "\"Input must be an object with a 'type' property.\"", ")", "if", "not", "options", ":", "options", "=", "ValidationOptions", "(", ")", "error_gens", "=", "[", "]", "# Schema validation", "if", "instance", "[", "'type'", "]", "==", "'bundle'", "and", "'objects'", "in", "instance", ":", "# Validate each object in a bundle separately", "for", "sdo", "in", "instance", "[", "'objects'", "]", ":", "if", "'type'", "not", "in", "sdo", ":", "raise", "ValidationError", "(", "\"Each object in bundle must have a 'type' property.\"", ")", "error_gens", "+=", "_schema_validate", "(", "sdo", ",", "options", ")", "else", ":", "error_gens", "+=", "_schema_validate", "(", "instance", ",", "options", ")", "# Custom validation", "must_checks", "=", "_get_musts", "(", "options", ")", "should_checks", "=", "_get_shoulds", "(", "options", ")", "output", ".", "info", "(", "\"Running the following additional checks: %s.\"", "%", "\", \"", ".", "join", "(", "x", ".", "__name__", "for", "x", "in", "chain", "(", "must_checks", ",", "should_checks", ")", ")", ")", "try", ":", "errors", "=", "_iter_errors_custom", "(", "instance", ",", "must_checks", ",", "options", ")", "warnings", "=", "_iter_errors_custom", "(", "instance", ",", "should_checks", ",", "options", ")", "if", "options", ".", "strict", ":", "chained_errors", "=", "chain", "(", "errors", ",", "warnings", ")", "warnings", "=", "[", "]", "else", ":", "chained_errors", "=", "errors", "warnings", "=", "[", "pretty_error", "(", "x", ",", "options", ".", "verbose", ")", "for", "x", "in", "warnings", "]", "except", "schema_exceptions", ".", "RefResolutionError", ":", "raise", "SchemaInvalidError", "(", "'Invalid JSON schema: a JSON reference '", "'failed to resolve'", ")", "# List of error generators and message prefixes (to denote which object the", "# error comes from)", "error_gens", "+=", "[", "(", "chained_errors", ",", "''", ")", "]", "# Prepare the list of errors (this actually triggers the custom validation", "# functions).", "error_list", "=", "[", "]", "for", "gen", ",", "prefix", "in", "error_gens", ":", "for", "error", "in", "gen", ":", "msg", "=", "prefix", "+", "pretty_error", "(", "error", ",", "options", ".", "verbose", ")", "error_list", ".", "append", "(", "SchemaError", "(", "msg", ")", ")", "if", "error_list", ":", "valid", "=", "False", "else", ":", "valid", "=", "True", "return", "ObjectValidationResults", "(", "is_valid", "=", "valid", ",", "object_id", "=", "instance", ".", "get", "(", "'id'", ",", "''", ")", ",", "errors", "=", "error_list", ",", "warnings", "=", "warnings", ")" ]
Perform STIX JSON Schema validation against STIX input. Find the correct schema by looking at the 'type' property of the `instance` JSON object. Args: instance: A Python dictionary representing a STIX object with a 'type' property. options: ValidationOptions instance with validation options for this validation run. Returns: A dictionary of validation results
[ "Perform", "STIX", "JSON", "Schema", "validation", "against", "STIX", "input", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/validator.py#L695-L766
train
oasis-open/cti-stix-validator
stix2validator/validator.py
FileValidationResults.object_result
def object_result(self): """ Get the object result object, assuming there is only one. Raises an error if there is more than one. :return: The result object :raises ValueError: If there is more than one result """ num_obj_results = len(self._object_results) if num_obj_results < 1: return None elif num_obj_results < 2: return self._object_results[0] else: raise ValueError("There is more than one result; use 'object_results'")
python
def object_result(self): """ Get the object result object, assuming there is only one. Raises an error if there is more than one. :return: The result object :raises ValueError: If there is more than one result """ num_obj_results = len(self._object_results) if num_obj_results < 1: return None elif num_obj_results < 2: return self._object_results[0] else: raise ValueError("There is more than one result; use 'object_results'")
[ "def", "object_result", "(", "self", ")", ":", "num_obj_results", "=", "len", "(", "self", ".", "_object_results", ")", "if", "num_obj_results", "<", "1", ":", "return", "None", "elif", "num_obj_results", "<", "2", ":", "return", "self", ".", "_object_results", "[", "0", "]", "else", ":", "raise", "ValueError", "(", "\"There is more than one result; use 'object_results'\"", ")" ]
Get the object result object, assuming there is only one. Raises an error if there is more than one. :return: The result object :raises ValueError: If there is more than one result
[ "Get", "the", "object", "result", "object", "assuming", "there", "is", "only", "one", ".", "Raises", "an", "error", "if", "there", "is", "more", "than", "one", ".", ":", "return", ":", "The", "result", "object", ":", "raises", "ValueError", ":", "If", "there", "is", "more", "than", "one", "result" ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/validator.py#L129-L143
train
oasis-open/cti-stix-validator
stix2validator/validator.py
FileValidationResults.object_results
def object_results(self, object_results): """ Set the results to an iterable of values. The values will be collected into a list. A single value is allowed; it will be converted to a length 1 list. :param object_results: The results to set """ if _is_iterable_non_string(object_results): self._object_results = list(object_results) elif object_results is None: self._object_results = [] else: self._object_results = [object_results]
python
def object_results(self, object_results): """ Set the results to an iterable of values. The values will be collected into a list. A single value is allowed; it will be converted to a length 1 list. :param object_results: The results to set """ if _is_iterable_non_string(object_results): self._object_results = list(object_results) elif object_results is None: self._object_results = [] else: self._object_results = [object_results]
[ "def", "object_results", "(", "self", ",", "object_results", ")", ":", "if", "_is_iterable_non_string", "(", "object_results", ")", ":", "self", ".", "_object_results", "=", "list", "(", "object_results", ")", "elif", "object_results", "is", "None", ":", "self", ".", "_object_results", "=", "[", "]", "else", ":", "self", ".", "_object_results", "=", "[", "object_results", "]" ]
Set the results to an iterable of values. The values will be collected into a list. A single value is allowed; it will be converted to a length 1 list. :param object_results: The results to set
[ "Set", "the", "results", "to", "an", "iterable", "of", "values", ".", "The", "values", "will", "be", "collected", "into", "a", "list", ".", "A", "single", "value", "is", "allowed", ";", "it", "will", "be", "converted", "to", "a", "length", "1", "list", ".", ":", "param", "object_results", ":", "The", "results", "to", "set" ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/validator.py#L167-L179
train
oasis-open/cti-stix-validator
stix2validator/validator.py
ObjectValidationResults.as_dict
def as_dict(self): """A dictionary representation of the :class:`.ObjectValidationResults` instance. Keys: * ``'result'``: The validation results (``True`` or ``False``) * ``'errors'``: A list of validation errors. Returns: A dictionary representation of an instance of this class. """ d = super(ObjectValidationResults, self).as_dict() if self.errors: d['errors'] = [x.as_dict() for x in self.errors] return d
python
def as_dict(self): """A dictionary representation of the :class:`.ObjectValidationResults` instance. Keys: * ``'result'``: The validation results (``True`` or ``False``) * ``'errors'``: A list of validation errors. Returns: A dictionary representation of an instance of this class. """ d = super(ObjectValidationResults, self).as_dict() if self.errors: d['errors'] = [x.as_dict() for x in self.errors] return d
[ "def", "as_dict", "(", "self", ")", ":", "d", "=", "super", "(", "ObjectValidationResults", ",", "self", ")", ".", "as_dict", "(", ")", "if", "self", ".", "errors", ":", "d", "[", "'errors'", "]", "=", "[", "x", ".", "as_dict", "(", ")", "for", "x", "in", "self", ".", "errors", "]", "return", "d" ]
A dictionary representation of the :class:`.ObjectValidationResults` instance. Keys: * ``'result'``: The validation results (``True`` or ``False``) * ``'errors'``: A list of validation errors. Returns: A dictionary representation of an instance of this class.
[ "A", "dictionary", "representation", "of", "the", ":", "class", ":", ".", "ObjectValidationResults", "instance", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/validator.py#L226-L243
train
oasis-open/cti-stix-validator
stix2validator/v21/shoulds.py
custom_prefix_strict
def custom_prefix_strict(instance): """Ensure custom content follows strict naming style conventions. """ for error in chain(custom_object_prefix_strict(instance), custom_property_prefix_strict(instance), custom_observable_object_prefix_strict(instance), custom_object_extension_prefix_strict(instance), custom_observable_properties_prefix_strict(instance)): yield error
python
def custom_prefix_strict(instance): """Ensure custom content follows strict naming style conventions. """ for error in chain(custom_object_prefix_strict(instance), custom_property_prefix_strict(instance), custom_observable_object_prefix_strict(instance), custom_object_extension_prefix_strict(instance), custom_observable_properties_prefix_strict(instance)): yield error
[ "def", "custom_prefix_strict", "(", "instance", ")", ":", "for", "error", "in", "chain", "(", "custom_object_prefix_strict", "(", "instance", ")", ",", "custom_property_prefix_strict", "(", "instance", ")", ",", "custom_observable_object_prefix_strict", "(", "instance", ")", ",", "custom_object_extension_prefix_strict", "(", "instance", ")", ",", "custom_observable_properties_prefix_strict", "(", "instance", ")", ")", ":", "yield", "error" ]
Ensure custom content follows strict naming style conventions.
[ "Ensure", "custom", "content", "follows", "strict", "naming", "style", "conventions", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L32-L40
train
oasis-open/cti-stix-validator
stix2validator/v21/shoulds.py
custom_prefix_lax
def custom_prefix_lax(instance): """Ensure custom content follows lenient naming style conventions for forward-compatibility. """ for error in chain(custom_object_prefix_lax(instance), custom_property_prefix_lax(instance), custom_observable_object_prefix_lax(instance), custom_object_extension_prefix_lax(instance), custom_observable_properties_prefix_lax(instance)): yield error
python
def custom_prefix_lax(instance): """Ensure custom content follows lenient naming style conventions for forward-compatibility. """ for error in chain(custom_object_prefix_lax(instance), custom_property_prefix_lax(instance), custom_observable_object_prefix_lax(instance), custom_object_extension_prefix_lax(instance), custom_observable_properties_prefix_lax(instance)): yield error
[ "def", "custom_prefix_lax", "(", "instance", ")", ":", "for", "error", "in", "chain", "(", "custom_object_prefix_lax", "(", "instance", ")", ",", "custom_property_prefix_lax", "(", "instance", ")", ",", "custom_observable_object_prefix_lax", "(", "instance", ")", ",", "custom_object_extension_prefix_lax", "(", "instance", ")", ",", "custom_observable_properties_prefix_lax", "(", "instance", ")", ")", ":", "yield", "error" ]
Ensure custom content follows lenient naming style conventions for forward-compatibility.
[ "Ensure", "custom", "content", "follows", "lenient", "naming", "style", "conventions", "for", "forward", "-", "compatibility", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L43-L52
train
oasis-open/cti-stix-validator
stix2validator/v21/shoulds.py
custom_object_prefix_strict
def custom_object_prefix_strict(instance): """Ensure custom objects follow strict naming style conventions. """ if (instance['type'] not in enums.TYPES and instance['type'] not in enums.RESERVED_OBJECTS and not CUSTOM_TYPE_PREFIX_RE.match(instance['type'])): yield JSONError("Custom object type '%s' should start with 'x-' " "followed by a source unique identifier (like a " "domain name with dots replaced by hyphens), a hyphen " "and then the name." % instance['type'], instance['id'], 'custom-prefix')
python
def custom_object_prefix_strict(instance): """Ensure custom objects follow strict naming style conventions. """ if (instance['type'] not in enums.TYPES and instance['type'] not in enums.RESERVED_OBJECTS and not CUSTOM_TYPE_PREFIX_RE.match(instance['type'])): yield JSONError("Custom object type '%s' should start with 'x-' " "followed by a source unique identifier (like a " "domain name with dots replaced by hyphens), a hyphen " "and then the name." % instance['type'], instance['id'], 'custom-prefix')
[ "def", "custom_object_prefix_strict", "(", "instance", ")", ":", "if", "(", "instance", "[", "'type'", "]", "not", "in", "enums", ".", "TYPES", "and", "instance", "[", "'type'", "]", "not", "in", "enums", ".", "RESERVED_OBJECTS", "and", "not", "CUSTOM_TYPE_PREFIX_RE", ".", "match", "(", "instance", "[", "'type'", "]", ")", ")", ":", "yield", "JSONError", "(", "\"Custom object type '%s' should start with 'x-' \"", "\"followed by a source unique identifier (like a \"", "\"domain name with dots replaced by hyphens), a hyphen \"", "\"and then the name.\"", "%", "instance", "[", "'type'", "]", ",", "instance", "[", "'id'", "]", ",", "'custom-prefix'", ")" ]
Ensure custom objects follow strict naming style conventions.
[ "Ensure", "custom", "objects", "follow", "strict", "naming", "style", "conventions", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L55-L65
train
oasis-open/cti-stix-validator
stix2validator/v21/shoulds.py
custom_object_prefix_lax
def custom_object_prefix_lax(instance): """Ensure custom objects follow lenient naming style conventions for forward-compatibility. """ if (instance['type'] not in enums.TYPES and instance['type'] not in enums.RESERVED_OBJECTS and not CUSTOM_TYPE_LAX_PREFIX_RE.match(instance['type'])): yield JSONError("Custom object type '%s' should start with 'x-' in " "order to be compatible with future versions of the " "STIX 2 specification." % instance['type'], instance['id'], 'custom-prefix-lax')
python
def custom_object_prefix_lax(instance): """Ensure custom objects follow lenient naming style conventions for forward-compatibility. """ if (instance['type'] not in enums.TYPES and instance['type'] not in enums.RESERVED_OBJECTS and not CUSTOM_TYPE_LAX_PREFIX_RE.match(instance['type'])): yield JSONError("Custom object type '%s' should start with 'x-' in " "order to be compatible with future versions of the " "STIX 2 specification." % instance['type'], instance['id'], 'custom-prefix-lax')
[ "def", "custom_object_prefix_lax", "(", "instance", ")", ":", "if", "(", "instance", "[", "'type'", "]", "not", "in", "enums", ".", "TYPES", "and", "instance", "[", "'type'", "]", "not", "in", "enums", ".", "RESERVED_OBJECTS", "and", "not", "CUSTOM_TYPE_LAX_PREFIX_RE", ".", "match", "(", "instance", "[", "'type'", "]", ")", ")", ":", "yield", "JSONError", "(", "\"Custom object type '%s' should start with 'x-' in \"", "\"order to be compatible with future versions of the \"", "\"STIX 2 specification.\"", "%", "instance", "[", "'type'", "]", ",", "instance", "[", "'id'", "]", ",", "'custom-prefix-lax'", ")" ]
Ensure custom objects follow lenient naming style conventions for forward-compatibility.
[ "Ensure", "custom", "objects", "follow", "lenient", "naming", "style", "conventions", "for", "forward", "-", "compatibility", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L68-L78
train
oasis-open/cti-stix-validator
stix2validator/v21/shoulds.py
custom_property_prefix_strict
def custom_property_prefix_strict(instance): """Ensure custom properties follow strict naming style conventions. Does not check property names in custom objects. """ for prop_name in instance.keys(): if (instance['type'] in enums.PROPERTIES and prop_name not in enums.PROPERTIES[instance['type']] and prop_name not in enums.RESERVED_PROPERTIES and not CUSTOM_PROPERTY_PREFIX_RE.match(prop_name)): yield JSONError("Custom property '%s' should have a type that " "starts with 'x_' followed by a source unique " "identifier (like a domain name with dots " "replaced by hyphen), a hyphen and then the name." % prop_name, instance['id'], 'custom-prefix')
python
def custom_property_prefix_strict(instance): """Ensure custom properties follow strict naming style conventions. Does not check property names in custom objects. """ for prop_name in instance.keys(): if (instance['type'] in enums.PROPERTIES and prop_name not in enums.PROPERTIES[instance['type']] and prop_name not in enums.RESERVED_PROPERTIES and not CUSTOM_PROPERTY_PREFIX_RE.match(prop_name)): yield JSONError("Custom property '%s' should have a type that " "starts with 'x_' followed by a source unique " "identifier (like a domain name with dots " "replaced by hyphen), a hyphen and then the name." % prop_name, instance['id'], 'custom-prefix')
[ "def", "custom_property_prefix_strict", "(", "instance", ")", ":", "for", "prop_name", "in", "instance", ".", "keys", "(", ")", ":", "if", "(", "instance", "[", "'type'", "]", "in", "enums", ".", "PROPERTIES", "and", "prop_name", "not", "in", "enums", ".", "PROPERTIES", "[", "instance", "[", "'type'", "]", "]", "and", "prop_name", "not", "in", "enums", ".", "RESERVED_PROPERTIES", "and", "not", "CUSTOM_PROPERTY_PREFIX_RE", ".", "match", "(", "prop_name", ")", ")", ":", "yield", "JSONError", "(", "\"Custom property '%s' should have a type that \"", "\"starts with 'x_' followed by a source unique \"", "\"identifier (like a domain name with dots \"", "\"replaced by hyphen), a hyphen and then the name.\"", "%", "prop_name", ",", "instance", "[", "'id'", "]", ",", "'custom-prefix'", ")" ]
Ensure custom properties follow strict naming style conventions. Does not check property names in custom objects.
[ "Ensure", "custom", "properties", "follow", "strict", "naming", "style", "conventions", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L81-L97
train
oasis-open/cti-stix-validator
stix2validator/v21/shoulds.py
custom_property_prefix_lax
def custom_property_prefix_lax(instance): """Ensure custom properties follow lenient naming style conventions for forward-compatibility. Does not check property names in custom objects. """ for prop_name in instance.keys(): if (instance['type'] in enums.PROPERTIES and prop_name not in enums.PROPERTIES[instance['type']] and prop_name not in enums.RESERVED_PROPERTIES and not CUSTOM_PROPERTY_LAX_PREFIX_RE.match(prop_name)): yield JSONError("Custom property '%s' should have a type that " "starts with 'x_' in order to be compatible with " "future versions of the STIX 2 specification." % prop_name, instance['id'], 'custom-prefix-lax')
python
def custom_property_prefix_lax(instance): """Ensure custom properties follow lenient naming style conventions for forward-compatibility. Does not check property names in custom objects. """ for prop_name in instance.keys(): if (instance['type'] in enums.PROPERTIES and prop_name not in enums.PROPERTIES[instance['type']] and prop_name not in enums.RESERVED_PROPERTIES and not CUSTOM_PROPERTY_LAX_PREFIX_RE.match(prop_name)): yield JSONError("Custom property '%s' should have a type that " "starts with 'x_' in order to be compatible with " "future versions of the STIX 2 specification." % prop_name, instance['id'], 'custom-prefix-lax')
[ "def", "custom_property_prefix_lax", "(", "instance", ")", ":", "for", "prop_name", "in", "instance", ".", "keys", "(", ")", ":", "if", "(", "instance", "[", "'type'", "]", "in", "enums", ".", "PROPERTIES", "and", "prop_name", "not", "in", "enums", ".", "PROPERTIES", "[", "instance", "[", "'type'", "]", "]", "and", "prop_name", "not", "in", "enums", ".", "RESERVED_PROPERTIES", "and", "not", "CUSTOM_PROPERTY_LAX_PREFIX_RE", ".", "match", "(", "prop_name", ")", ")", ":", "yield", "JSONError", "(", "\"Custom property '%s' should have a type that \"", "\"starts with 'x_' in order to be compatible with \"", "\"future versions of the STIX 2 specification.\"", "%", "prop_name", ",", "instance", "[", "'id'", "]", ",", "'custom-prefix-lax'", ")" ]
Ensure custom properties follow lenient naming style conventions for forward-compatibility. Does not check property names in custom objects.
[ "Ensure", "custom", "properties", "follow", "lenient", "naming", "style", "conventions", "for", "forward", "-", "compatibility", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L100-L116
train
oasis-open/cti-stix-validator
stix2validator/v21/shoulds.py
open_vocab_values
def open_vocab_values(instance): """Ensure that the values of all properties which use open vocabularies are in lowercase and use hyphens instead of spaces or underscores as word separators. """ if instance['type'] not in enums.VOCAB_PROPERTIES: return properties = enums.VOCAB_PROPERTIES[instance['type']] for prop in properties: if prop in instance: if type(instance[prop]) is list: values = instance[prop] else: values = [instance[prop]] for v in values: if not v.islower() or '_' in v or ' ' in v: yield JSONError("Open vocabulary value '%s' should be all" " lowercase and use hyphens instead of" " spaces or underscores as word" " separators." % v, instance['id'], 'open-vocab-format')
python
def open_vocab_values(instance): """Ensure that the values of all properties which use open vocabularies are in lowercase and use hyphens instead of spaces or underscores as word separators. """ if instance['type'] not in enums.VOCAB_PROPERTIES: return properties = enums.VOCAB_PROPERTIES[instance['type']] for prop in properties: if prop in instance: if type(instance[prop]) is list: values = instance[prop] else: values = [instance[prop]] for v in values: if not v.islower() or '_' in v or ' ' in v: yield JSONError("Open vocabulary value '%s' should be all" " lowercase and use hyphens instead of" " spaces or underscores as word" " separators." % v, instance['id'], 'open-vocab-format')
[ "def", "open_vocab_values", "(", "instance", ")", ":", "if", "instance", "[", "'type'", "]", "not", "in", "enums", ".", "VOCAB_PROPERTIES", ":", "return", "properties", "=", "enums", ".", "VOCAB_PROPERTIES", "[", "instance", "[", "'type'", "]", "]", "for", "prop", "in", "properties", ":", "if", "prop", "in", "instance", ":", "if", "type", "(", "instance", "[", "prop", "]", ")", "is", "list", ":", "values", "=", "instance", "[", "prop", "]", "else", ":", "values", "=", "[", "instance", "[", "prop", "]", "]", "for", "v", "in", "values", ":", "if", "not", "v", ".", "islower", "(", ")", "or", "'_'", "in", "v", "or", "' '", "in", "v", ":", "yield", "JSONError", "(", "\"Open vocabulary value '%s' should be all\"", "\" lowercase and use hyphens instead of\"", "\" spaces or underscores as word\"", "\" separators.\"", "%", "v", ",", "instance", "[", "'id'", "]", ",", "'open-vocab-format'", ")" ]
Ensure that the values of all properties which use open vocabularies are in lowercase and use hyphens instead of spaces or underscores as word separators.
[ "Ensure", "that", "the", "values", "of", "all", "properties", "which", "use", "open", "vocabularies", "are", "in", "lowercase", "and", "use", "hyphens", "instead", "of", "spaces", "or", "underscores", "as", "word", "separators", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L119-L142
train
oasis-open/cti-stix-validator
stix2validator/v21/shoulds.py
kill_chain_phase_names
def kill_chain_phase_names(instance): """Ensure the `kill_chain_name` and `phase_name` properties of `kill_chain_phase` objects follow naming style conventions. """ if instance['type'] in enums.KILL_CHAIN_PHASE_USES and 'kill_chain_phases' in instance: for phase in instance['kill_chain_phases']: if 'kill_chain_name' not in phase: # Since this field is required, schemas will already catch the error return chain_name = phase['kill_chain_name'] if not chain_name.islower() or '_' in chain_name or ' ' in chain_name: yield JSONError("kill_chain_name '%s' should be all lowercase" " and use hyphens instead of spaces or " "underscores as word separators." % chain_name, instance['id'], 'kill-chain-names') phase_name = phase['phase_name'] if not phase_name.islower() or '_' in phase_name or ' ' in phase_name: yield JSONError("phase_name '%s' should be all lowercase and " "use hyphens instead of spaces or underscores " "as word separators." % phase_name, instance['id'], 'kill-chain-names')
python
def kill_chain_phase_names(instance): """Ensure the `kill_chain_name` and `phase_name` properties of `kill_chain_phase` objects follow naming style conventions. """ if instance['type'] in enums.KILL_CHAIN_PHASE_USES and 'kill_chain_phases' in instance: for phase in instance['kill_chain_phases']: if 'kill_chain_name' not in phase: # Since this field is required, schemas will already catch the error return chain_name = phase['kill_chain_name'] if not chain_name.islower() or '_' in chain_name or ' ' in chain_name: yield JSONError("kill_chain_name '%s' should be all lowercase" " and use hyphens instead of spaces or " "underscores as word separators." % chain_name, instance['id'], 'kill-chain-names') phase_name = phase['phase_name'] if not phase_name.islower() or '_' in phase_name or ' ' in phase_name: yield JSONError("phase_name '%s' should be all lowercase and " "use hyphens instead of spaces or underscores " "as word separators." % phase_name, instance['id'], 'kill-chain-names')
[ "def", "kill_chain_phase_names", "(", "instance", ")", ":", "if", "instance", "[", "'type'", "]", "in", "enums", ".", "KILL_CHAIN_PHASE_USES", "and", "'kill_chain_phases'", "in", "instance", ":", "for", "phase", "in", "instance", "[", "'kill_chain_phases'", "]", ":", "if", "'kill_chain_name'", "not", "in", "phase", ":", "# Since this field is required, schemas will already catch the error", "return", "chain_name", "=", "phase", "[", "'kill_chain_name'", "]", "if", "not", "chain_name", ".", "islower", "(", ")", "or", "'_'", "in", "chain_name", "or", "' '", "in", "chain_name", ":", "yield", "JSONError", "(", "\"kill_chain_name '%s' should be all lowercase\"", "\" and use hyphens instead of spaces or \"", "\"underscores as word separators.\"", "%", "chain_name", ",", "instance", "[", "'id'", "]", ",", "'kill-chain-names'", ")", "phase_name", "=", "phase", "[", "'phase_name'", "]", "if", "not", "phase_name", ".", "islower", "(", ")", "or", "'_'", "in", "phase_name", "or", "' '", "in", "phase_name", ":", "yield", "JSONError", "(", "\"phase_name '%s' should be all lowercase and \"", "\"use hyphens instead of spaces or underscores \"", "\"as word separators.\"", "%", "phase_name", ",", "instance", "[", "'id'", "]", ",", "'kill-chain-names'", ")" ]
Ensure the `kill_chain_name` and `phase_name` properties of `kill_chain_phase` objects follow naming style conventions.
[ "Ensure", "the", "kill_chain_name", "and", "phase_name", "properties", "of", "kill_chain_phase", "objects", "follow", "naming", "style", "conventions", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L145-L168
train
oasis-open/cti-stix-validator
stix2validator/v21/shoulds.py
check_vocab
def check_vocab(instance, vocab, code): """Ensure that the open vocabulary specified by `vocab` is used properly. This checks properties of objects specified in the appropriate `_USES` dictionary to determine which properties SHOULD use the given vocabulary, then checks that the values in those properties are from the vocabulary. """ vocab_uses = getattr(enums, vocab + "_USES") for k in vocab_uses.keys(): if instance['type'] == k: for prop in vocab_uses[k]: if prop not in instance: continue vocab_ov = getattr(enums, vocab + "_OV") if type(instance[prop]) is list: is_in = set(instance[prop]).issubset(set(vocab_ov)) else: is_in = instance[prop] in vocab_ov if not is_in: vocab_name = vocab.replace('_', '-').lower() yield JSONError("%s contains a value not in the %s-ov " "vocabulary." % (prop, vocab_name), instance['id'], code)
python
def check_vocab(instance, vocab, code): """Ensure that the open vocabulary specified by `vocab` is used properly. This checks properties of objects specified in the appropriate `_USES` dictionary to determine which properties SHOULD use the given vocabulary, then checks that the values in those properties are from the vocabulary. """ vocab_uses = getattr(enums, vocab + "_USES") for k in vocab_uses.keys(): if instance['type'] == k: for prop in vocab_uses[k]: if prop not in instance: continue vocab_ov = getattr(enums, vocab + "_OV") if type(instance[prop]) is list: is_in = set(instance[prop]).issubset(set(vocab_ov)) else: is_in = instance[prop] in vocab_ov if not is_in: vocab_name = vocab.replace('_', '-').lower() yield JSONError("%s contains a value not in the %s-ov " "vocabulary." % (prop, vocab_name), instance['id'], code)
[ "def", "check_vocab", "(", "instance", ",", "vocab", ",", "code", ")", ":", "vocab_uses", "=", "getattr", "(", "enums", ",", "vocab", "+", "\"_USES\"", ")", "for", "k", "in", "vocab_uses", ".", "keys", "(", ")", ":", "if", "instance", "[", "'type'", "]", "==", "k", ":", "for", "prop", "in", "vocab_uses", "[", "k", "]", ":", "if", "prop", "not", "in", "instance", ":", "continue", "vocab_ov", "=", "getattr", "(", "enums", ",", "vocab", "+", "\"_OV\"", ")", "if", "type", "(", "instance", "[", "prop", "]", ")", "is", "list", ":", "is_in", "=", "set", "(", "instance", "[", "prop", "]", ")", ".", "issubset", "(", "set", "(", "vocab_ov", ")", ")", "else", ":", "is_in", "=", "instance", "[", "prop", "]", "in", "vocab_ov", "if", "not", "is_in", ":", "vocab_name", "=", "vocab", ".", "replace", "(", "'_'", ",", "'-'", ")", ".", "lower", "(", ")", "yield", "JSONError", "(", "\"%s contains a value not in the %s-ov \"", "\"vocabulary.\"", "%", "(", "prop", ",", "vocab_name", ")", ",", "instance", "[", "'id'", "]", ",", "code", ")" ]
Ensure that the open vocabulary specified by `vocab` is used properly. This checks properties of objects specified in the appropriate `_USES` dictionary to determine which properties SHOULD use the given vocabulary, then checks that the values in those properties are from the vocabulary.
[ "Ensure", "that", "the", "open", "vocabulary", "specified", "by", "vocab", "is", "used", "properly", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L171-L195
train
oasis-open/cti-stix-validator
stix2validator/v21/shoulds.py
vocab_marking_definition
def vocab_marking_definition(instance): """Ensure that the `definition_type` property of `marking-definition` objects is one of the values in the STIX 2.0 specification. """ if (instance['type'] == 'marking-definition' and 'definition_type' in instance and not instance['definition_type'] in enums.MARKING_DEFINITION_TYPES): return JSONError("Marking definition `definition_type` should be one " "of: %s." % ', '.join(enums.MARKING_DEFINITION_TYPES), instance['id'], 'marking-definition-type')
python
def vocab_marking_definition(instance): """Ensure that the `definition_type` property of `marking-definition` objects is one of the values in the STIX 2.0 specification. """ if (instance['type'] == 'marking-definition' and 'definition_type' in instance and not instance['definition_type'] in enums.MARKING_DEFINITION_TYPES): return JSONError("Marking definition `definition_type` should be one " "of: %s." % ', '.join(enums.MARKING_DEFINITION_TYPES), instance['id'], 'marking-definition-type')
[ "def", "vocab_marking_definition", "(", "instance", ")", ":", "if", "(", "instance", "[", "'type'", "]", "==", "'marking-definition'", "and", "'definition_type'", "in", "instance", "and", "not", "instance", "[", "'definition_type'", "]", "in", "enums", ".", "MARKING_DEFINITION_TYPES", ")", ":", "return", "JSONError", "(", "\"Marking definition `definition_type` should be one \"", "\"of: %s.\"", "%", "', '", ".", "join", "(", "enums", ".", "MARKING_DEFINITION_TYPES", ")", ",", "instance", "[", "'id'", "]", ",", "'marking-definition-type'", ")" ]
Ensure that the `definition_type` property of `marking-definition` objects is one of the values in the STIX 2.0 specification.
[ "Ensure", "that", "the", "definition_type", "property", "of", "marking", "-", "definition", "objects", "is", "one", "of", "the", "values", "in", "the", "STIX", "2", ".", "0", "specification", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L258-L268
train
oasis-open/cti-stix-validator
stix2validator/v21/shoulds.py
relationships_strict
def relationships_strict(instance): """Ensure that only the relationship types defined in the specification are used. """ # Don't check objects that aren't relationships or that are custom objects if (instance['type'] != 'relationship' or instance['type'] not in enums.TYPES): return if ('relationship_type' not in instance or 'source_ref' not in instance or 'target_ref' not in instance): # Since these fields are required, schemas will already catch the error return r_type = instance['relationship_type'] try: r_source = re.search(r"(.+)\-\-", instance['source_ref']).group(1) r_target = re.search(r"(.+)\-\-", instance['target_ref']).group(1) except (AttributeError, TypeError): # Schemas already catch errors of these properties not being strings or # not containing the string '--'. return if (r_type in enums.COMMON_RELATIONSHIPS or r_source in enums.NON_SDOS or r_target in enums.NON_SDOS): # If all objects can have this relationship type, no more checks needed # Schemas already catch if source/target type cannot have relationship return if r_source not in enums.RELATIONSHIPS: return JSONError("'%s' is not a suggested relationship source object " "for the '%s' relationship." % (r_source, r_type), instance['id'], 'relationship-types') if r_type not in enums.RELATIONSHIPS[r_source]: return JSONError("'%s' is not a suggested relationship type for '%s' " "objects." % (r_type, r_source), instance['id'], 'relationship-types') if r_target not in enums.RELATIONSHIPS[r_source][r_type]: return JSONError("'%s' is not a suggested relationship target object " "for '%s' objects with the '%s' relationship." % (r_target, r_source, r_type), instance['id'], 'relationship-types')
python
def relationships_strict(instance): """Ensure that only the relationship types defined in the specification are used. """ # Don't check objects that aren't relationships or that are custom objects if (instance['type'] != 'relationship' or instance['type'] not in enums.TYPES): return if ('relationship_type' not in instance or 'source_ref' not in instance or 'target_ref' not in instance): # Since these fields are required, schemas will already catch the error return r_type = instance['relationship_type'] try: r_source = re.search(r"(.+)\-\-", instance['source_ref']).group(1) r_target = re.search(r"(.+)\-\-", instance['target_ref']).group(1) except (AttributeError, TypeError): # Schemas already catch errors of these properties not being strings or # not containing the string '--'. return if (r_type in enums.COMMON_RELATIONSHIPS or r_source in enums.NON_SDOS or r_target in enums.NON_SDOS): # If all objects can have this relationship type, no more checks needed # Schemas already catch if source/target type cannot have relationship return if r_source not in enums.RELATIONSHIPS: return JSONError("'%s' is not a suggested relationship source object " "for the '%s' relationship." % (r_source, r_type), instance['id'], 'relationship-types') if r_type not in enums.RELATIONSHIPS[r_source]: return JSONError("'%s' is not a suggested relationship type for '%s' " "objects." % (r_type, r_source), instance['id'], 'relationship-types') if r_target not in enums.RELATIONSHIPS[r_source][r_type]: return JSONError("'%s' is not a suggested relationship target object " "for '%s' objects with the '%s' relationship." % (r_target, r_source, r_type), instance['id'], 'relationship-types')
[ "def", "relationships_strict", "(", "instance", ")", ":", "# Don't check objects that aren't relationships or that are custom objects", "if", "(", "instance", "[", "'type'", "]", "!=", "'relationship'", "or", "instance", "[", "'type'", "]", "not", "in", "enums", ".", "TYPES", ")", ":", "return", "if", "(", "'relationship_type'", "not", "in", "instance", "or", "'source_ref'", "not", "in", "instance", "or", "'target_ref'", "not", "in", "instance", ")", ":", "# Since these fields are required, schemas will already catch the error", "return", "r_type", "=", "instance", "[", "'relationship_type'", "]", "try", ":", "r_source", "=", "re", ".", "search", "(", "r\"(.+)\\-\\-\"", ",", "instance", "[", "'source_ref'", "]", ")", ".", "group", "(", "1", ")", "r_target", "=", "re", ".", "search", "(", "r\"(.+)\\-\\-\"", ",", "instance", "[", "'target_ref'", "]", ")", ".", "group", "(", "1", ")", "except", "(", "AttributeError", ",", "TypeError", ")", ":", "# Schemas already catch errors of these properties not being strings or", "# not containing the string '--'.", "return", "if", "(", "r_type", "in", "enums", ".", "COMMON_RELATIONSHIPS", "or", "r_source", "in", "enums", ".", "NON_SDOS", "or", "r_target", "in", "enums", ".", "NON_SDOS", ")", ":", "# If all objects can have this relationship type, no more checks needed", "# Schemas already catch if source/target type cannot have relationship", "return", "if", "r_source", "not", "in", "enums", ".", "RELATIONSHIPS", ":", "return", "JSONError", "(", "\"'%s' is not a suggested relationship source object \"", "\"for the '%s' relationship.\"", "%", "(", "r_source", ",", "r_type", ")", ",", "instance", "[", "'id'", "]", ",", "'relationship-types'", ")", "if", "r_type", "not", "in", "enums", ".", "RELATIONSHIPS", "[", "r_source", "]", ":", "return", "JSONError", "(", "\"'%s' is not a suggested relationship type for '%s' \"", "\"objects.\"", "%", "(", "r_type", ",", "r_source", ")", ",", "instance", "[", "'id'", "]", ",", "'relationship-types'", ")", "if", "r_target", "not", "in", "enums", ".", "RELATIONSHIPS", "[", "r_source", "]", "[", "r_type", "]", ":", "return", "JSONError", "(", "\"'%s' is not a suggested relationship target object \"", "\"for '%s' objects with the '%s' relationship.\"", "%", "(", "r_target", ",", "r_source", ",", "r_type", ")", ",", "instance", "[", "'id'", "]", ",", "'relationship-types'", ")" ]
Ensure that only the relationship types defined in the specification are used.
[ "Ensure", "that", "only", "the", "relationship", "types", "defined", "in", "the", "specification", "are", "used", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L271-L315
train
oasis-open/cti-stix-validator
stix2validator/v21/shoulds.py
valid_hash_value
def valid_hash_value(hashname): """Return true if given value is a valid, recommended hash name according to the STIX 2 specification. """ custom_hash_prefix_re = re.compile(r"^x_") if hashname in enums.HASH_ALGO_OV or custom_hash_prefix_re.match(hashname): return True else: return False
python
def valid_hash_value(hashname): """Return true if given value is a valid, recommended hash name according to the STIX 2 specification. """ custom_hash_prefix_re = re.compile(r"^x_") if hashname in enums.HASH_ALGO_OV or custom_hash_prefix_re.match(hashname): return True else: return False
[ "def", "valid_hash_value", "(", "hashname", ")", ":", "custom_hash_prefix_re", "=", "re", ".", "compile", "(", "r\"^x_\"", ")", "if", "hashname", "in", "enums", ".", "HASH_ALGO_OV", "or", "custom_hash_prefix_re", ".", "match", "(", "hashname", ")", ":", "return", "True", "else", ":", "return", "False" ]
Return true if given value is a valid, recommended hash name according to the STIX 2 specification.
[ "Return", "true", "if", "given", "value", "is", "a", "valid", "recommended", "hash", "name", "according", "to", "the", "STIX", "2", "specification", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L318-L326
train
oasis-open/cti-stix-validator
stix2validator/v21/shoulds.py
vocab_hash_algo
def vocab_hash_algo(instance): """Ensure objects with 'hashes' properties only use values from the hash-algo-ov vocabulary. """ for key, obj in instance['objects'].items(): if 'type' not in obj: continue if obj['type'] == 'file': try: hashes = obj['hashes'] except KeyError: pass else: for h in hashes: if not (valid_hash_value(h)): yield JSONError("Object '%s' has a 'hashes' dictionary" " with a hash of type '%s', which is not a " "value in the hash-algo-ov vocabulary nor a " "custom value prepended with 'x_'." % (key, h), instance['id'], 'hash-algo') try: ads = obj['extensions']['ntfs-ext']['alternate_data_streams'] except KeyError: pass else: for datastream in ads: if 'hashes' not in datastream: continue for h in datastream['hashes']: if not (valid_hash_value(h)): yield JSONError("Object '%s' has an NTFS extension" " with an alternate data stream that has a" " 'hashes' dictionary with a hash of type " "'%s', which is not a value in the " "hash-algo-ov vocabulary nor a custom " "value prepended with 'x_'." % (key, h), instance['id'], 'hash-algo') try: head_hashes = obj['extensions']['windows-pebinary-ext']['file_header_hashes'] except KeyError: pass else: for h in head_hashes: if not (valid_hash_value(h)): yield JSONError("Object '%s' has a Windows PE Binary " "File extension with a file header hash of " "'%s', which is not a value in the " "hash-algo-ov vocabulary nor a custom value " "prepended with 'x_'." % (key, h), instance['id'], 'hash-algo') try: hashes = obj['extensions']['windows-pebinary-ext']['optional_header']['hashes'] except KeyError: pass else: for h in hashes: if not (valid_hash_value(h)): yield JSONError("Object '%s' has a Windows PE Binary " "File extension with an optional header that " "has a hash of '%s', which is not a value in " "the hash-algo-ov vocabulary nor a custom " "value prepended with 'x_'." % (key, h), instance['id'], 'hash-algo') try: sections = obj['extensions']['windows-pebinary-ext']['sections'] except KeyError: pass else: for s in sections: if 'hashes' not in s: continue for h in s['hashes']: if not (valid_hash_value(h)): yield JSONError("Object '%s' has a Windows PE " "Binary File extension with a section that" " has a hash of '%s', which is not a value" " in the hash-algo-ov vocabulary nor a " "custom value prepended with 'x_'." % (key, h), instance['id'], 'hash-algo') elif obj['type'] == 'artifact' or obj['type'] == 'x509-certificate': try: hashes = obj['hashes'] except KeyError: pass else: for h in hashes: if not (valid_hash_value(h)): yield JSONError("Object '%s' has a 'hashes' dictionary" " with a hash of type '%s', which is not a " "value in the hash-algo-ov vocabulary nor a " "custom value prepended with 'x_'." % (key, h), instance['id'], 'hash-algo')
python
def vocab_hash_algo(instance): """Ensure objects with 'hashes' properties only use values from the hash-algo-ov vocabulary. """ for key, obj in instance['objects'].items(): if 'type' not in obj: continue if obj['type'] == 'file': try: hashes = obj['hashes'] except KeyError: pass else: for h in hashes: if not (valid_hash_value(h)): yield JSONError("Object '%s' has a 'hashes' dictionary" " with a hash of type '%s', which is not a " "value in the hash-algo-ov vocabulary nor a " "custom value prepended with 'x_'." % (key, h), instance['id'], 'hash-algo') try: ads = obj['extensions']['ntfs-ext']['alternate_data_streams'] except KeyError: pass else: for datastream in ads: if 'hashes' not in datastream: continue for h in datastream['hashes']: if not (valid_hash_value(h)): yield JSONError("Object '%s' has an NTFS extension" " with an alternate data stream that has a" " 'hashes' dictionary with a hash of type " "'%s', which is not a value in the " "hash-algo-ov vocabulary nor a custom " "value prepended with 'x_'." % (key, h), instance['id'], 'hash-algo') try: head_hashes = obj['extensions']['windows-pebinary-ext']['file_header_hashes'] except KeyError: pass else: for h in head_hashes: if not (valid_hash_value(h)): yield JSONError("Object '%s' has a Windows PE Binary " "File extension with a file header hash of " "'%s', which is not a value in the " "hash-algo-ov vocabulary nor a custom value " "prepended with 'x_'." % (key, h), instance['id'], 'hash-algo') try: hashes = obj['extensions']['windows-pebinary-ext']['optional_header']['hashes'] except KeyError: pass else: for h in hashes: if not (valid_hash_value(h)): yield JSONError("Object '%s' has a Windows PE Binary " "File extension with an optional header that " "has a hash of '%s', which is not a value in " "the hash-algo-ov vocabulary nor a custom " "value prepended with 'x_'." % (key, h), instance['id'], 'hash-algo') try: sections = obj['extensions']['windows-pebinary-ext']['sections'] except KeyError: pass else: for s in sections: if 'hashes' not in s: continue for h in s['hashes']: if not (valid_hash_value(h)): yield JSONError("Object '%s' has a Windows PE " "Binary File extension with a section that" " has a hash of '%s', which is not a value" " in the hash-algo-ov vocabulary nor a " "custom value prepended with 'x_'." % (key, h), instance['id'], 'hash-algo') elif obj['type'] == 'artifact' or obj['type'] == 'x509-certificate': try: hashes = obj['hashes'] except KeyError: pass else: for h in hashes: if not (valid_hash_value(h)): yield JSONError("Object '%s' has a 'hashes' dictionary" " with a hash of type '%s', which is not a " "value in the hash-algo-ov vocabulary nor a " "custom value prepended with 'x_'." % (key, h), instance['id'], 'hash-algo')
[ "def", "vocab_hash_algo", "(", "instance", ")", ":", "for", "key", ",", "obj", "in", "instance", "[", "'objects'", "]", ".", "items", "(", ")", ":", "if", "'type'", "not", "in", "obj", ":", "continue", "if", "obj", "[", "'type'", "]", "==", "'file'", ":", "try", ":", "hashes", "=", "obj", "[", "'hashes'", "]", "except", "KeyError", ":", "pass", "else", ":", "for", "h", "in", "hashes", ":", "if", "not", "(", "valid_hash_value", "(", "h", ")", ")", ":", "yield", "JSONError", "(", "\"Object '%s' has a 'hashes' dictionary\"", "\" with a hash of type '%s', which is not a \"", "\"value in the hash-algo-ov vocabulary nor a \"", "\"custom value prepended with 'x_'.\"", "%", "(", "key", ",", "h", ")", ",", "instance", "[", "'id'", "]", ",", "'hash-algo'", ")", "try", ":", "ads", "=", "obj", "[", "'extensions'", "]", "[", "'ntfs-ext'", "]", "[", "'alternate_data_streams'", "]", "except", "KeyError", ":", "pass", "else", ":", "for", "datastream", "in", "ads", ":", "if", "'hashes'", "not", "in", "datastream", ":", "continue", "for", "h", "in", "datastream", "[", "'hashes'", "]", ":", "if", "not", "(", "valid_hash_value", "(", "h", ")", ")", ":", "yield", "JSONError", "(", "\"Object '%s' has an NTFS extension\"", "\" with an alternate data stream that has a\"", "\" 'hashes' dictionary with a hash of type \"", "\"'%s', which is not a value in the \"", "\"hash-algo-ov vocabulary nor a custom \"", "\"value prepended with 'x_'.\"", "%", "(", "key", ",", "h", ")", ",", "instance", "[", "'id'", "]", ",", "'hash-algo'", ")", "try", ":", "head_hashes", "=", "obj", "[", "'extensions'", "]", "[", "'windows-pebinary-ext'", "]", "[", "'file_header_hashes'", "]", "except", "KeyError", ":", "pass", "else", ":", "for", "h", "in", "head_hashes", ":", "if", "not", "(", "valid_hash_value", "(", "h", ")", ")", ":", "yield", "JSONError", "(", "\"Object '%s' has a Windows PE Binary \"", "\"File extension with a file header hash of \"", "\"'%s', which is not a value in the \"", "\"hash-algo-ov vocabulary nor a custom value \"", "\"prepended with 'x_'.\"", "%", "(", "key", ",", "h", ")", ",", "instance", "[", "'id'", "]", ",", "'hash-algo'", ")", "try", ":", "hashes", "=", "obj", "[", "'extensions'", "]", "[", "'windows-pebinary-ext'", "]", "[", "'optional_header'", "]", "[", "'hashes'", "]", "except", "KeyError", ":", "pass", "else", ":", "for", "h", "in", "hashes", ":", "if", "not", "(", "valid_hash_value", "(", "h", ")", ")", ":", "yield", "JSONError", "(", "\"Object '%s' has a Windows PE Binary \"", "\"File extension with an optional header that \"", "\"has a hash of '%s', which is not a value in \"", "\"the hash-algo-ov vocabulary nor a custom \"", "\"value prepended with 'x_'.\"", "%", "(", "key", ",", "h", ")", ",", "instance", "[", "'id'", "]", ",", "'hash-algo'", ")", "try", ":", "sections", "=", "obj", "[", "'extensions'", "]", "[", "'windows-pebinary-ext'", "]", "[", "'sections'", "]", "except", "KeyError", ":", "pass", "else", ":", "for", "s", "in", "sections", ":", "if", "'hashes'", "not", "in", "s", ":", "continue", "for", "h", "in", "s", "[", "'hashes'", "]", ":", "if", "not", "(", "valid_hash_value", "(", "h", ")", ")", ":", "yield", "JSONError", "(", "\"Object '%s' has a Windows PE \"", "\"Binary File extension with a section that\"", "\" has a hash of '%s', which is not a value\"", "\" in the hash-algo-ov vocabulary nor a \"", "\"custom value prepended with 'x_'.\"", "%", "(", "key", ",", "h", ")", ",", "instance", "[", "'id'", "]", ",", "'hash-algo'", ")", "elif", "obj", "[", "'type'", "]", "==", "'artifact'", "or", "obj", "[", "'type'", "]", "==", "'x509-certificate'", ":", "try", ":", "hashes", "=", "obj", "[", "'hashes'", "]", "except", "KeyError", ":", "pass", "else", ":", "for", "h", "in", "hashes", ":", "if", "not", "(", "valid_hash_value", "(", "h", ")", ")", ":", "yield", "JSONError", "(", "\"Object '%s' has a 'hashes' dictionary\"", "\" with a hash of type '%s', which is not a \"", "\"value in the hash-algo-ov vocabulary nor a \"", "\"custom value prepended with 'x_'.\"", "%", "(", "key", ",", "h", ")", ",", "instance", "[", "'id'", "]", ",", "'hash-algo'", ")" ]
Ensure objects with 'hashes' properties only use values from the hash-algo-ov vocabulary.
[ "Ensure", "objects", "with", "hashes", "properties", "only", "use", "values", "from", "the", "hash", "-", "algo", "-", "ov", "vocabulary", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L330-L427
train
oasis-open/cti-stix-validator
stix2validator/v21/shoulds.py
vocab_windows_pebinary_type
def vocab_windows_pebinary_type(instance): """Ensure file objects with the windows-pebinary-ext extension have a 'pe-type' property that is from the windows-pebinary-type-ov vocabulary. """ for key, obj in instance['objects'].items(): if 'type' in obj and obj['type'] == 'file': try: pe_type = obj['extensions']['windows-pebinary-ext']['pe_type'] except KeyError: continue if pe_type not in enums.WINDOWS_PEBINARY_TYPE_OV: yield JSONError("Object '%s' has a Windows PE Binary File " "extension with a 'pe_type' of '%s', which is not a " "value in the windows-pebinary-type-ov vocabulary." % (key, pe_type), instance['id'], 'windows-pebinary-type')
python
def vocab_windows_pebinary_type(instance): """Ensure file objects with the windows-pebinary-ext extension have a 'pe-type' property that is from the windows-pebinary-type-ov vocabulary. """ for key, obj in instance['objects'].items(): if 'type' in obj and obj['type'] == 'file': try: pe_type = obj['extensions']['windows-pebinary-ext']['pe_type'] except KeyError: continue if pe_type not in enums.WINDOWS_PEBINARY_TYPE_OV: yield JSONError("Object '%s' has a Windows PE Binary File " "extension with a 'pe_type' of '%s', which is not a " "value in the windows-pebinary-type-ov vocabulary." % (key, pe_type), instance['id'], 'windows-pebinary-type')
[ "def", "vocab_windows_pebinary_type", "(", "instance", ")", ":", "for", "key", ",", "obj", "in", "instance", "[", "'objects'", "]", ".", "items", "(", ")", ":", "if", "'type'", "in", "obj", "and", "obj", "[", "'type'", "]", "==", "'file'", ":", "try", ":", "pe_type", "=", "obj", "[", "'extensions'", "]", "[", "'windows-pebinary-ext'", "]", "[", "'pe_type'", "]", "except", "KeyError", ":", "continue", "if", "pe_type", "not", "in", "enums", ".", "WINDOWS_PEBINARY_TYPE_OV", ":", "yield", "JSONError", "(", "\"Object '%s' has a Windows PE Binary File \"", "\"extension with a 'pe_type' of '%s', which is not a \"", "\"value in the windows-pebinary-type-ov vocabulary.\"", "%", "(", "key", ",", "pe_type", ")", ",", "instance", "[", "'id'", "]", ",", "'windows-pebinary-type'", ")" ]
Ensure file objects with the windows-pebinary-ext extension have a 'pe-type' property that is from the windows-pebinary-type-ov vocabulary.
[ "Ensure", "file", "objects", "with", "the", "windows", "-", "pebinary", "-", "ext", "extension", "have", "a", "pe", "-", "type", "property", "that", "is", "from", "the", "windows", "-", "pebinary", "-", "type", "-", "ov", "vocabulary", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L431-L446
train
oasis-open/cti-stix-validator
stix2validator/v21/shoulds.py
vocab_account_type
def vocab_account_type(instance): """Ensure a user-account objects' 'account-type' property is from the account-type-ov vocabulary. """ for key, obj in instance['objects'].items(): if 'type' in obj and obj['type'] == 'user-account': try: acct_type = obj['account_type'] except KeyError: continue if acct_type not in enums.ACCOUNT_TYPE_OV: yield JSONError("Object '%s' is a User Account Object " "with an 'account_type' of '%s', which is not a " "value in the account-type-ov vocabulary." % (key, acct_type), instance['id'], 'account-type')
python
def vocab_account_type(instance): """Ensure a user-account objects' 'account-type' property is from the account-type-ov vocabulary. """ for key, obj in instance['objects'].items(): if 'type' in obj and obj['type'] == 'user-account': try: acct_type = obj['account_type'] except KeyError: continue if acct_type not in enums.ACCOUNT_TYPE_OV: yield JSONError("Object '%s' is a User Account Object " "with an 'account_type' of '%s', which is not a " "value in the account-type-ov vocabulary." % (key, acct_type), instance['id'], 'account-type')
[ "def", "vocab_account_type", "(", "instance", ")", ":", "for", "key", ",", "obj", "in", "instance", "[", "'objects'", "]", ".", "items", "(", ")", ":", "if", "'type'", "in", "obj", "and", "obj", "[", "'type'", "]", "==", "'user-account'", ":", "try", ":", "acct_type", "=", "obj", "[", "'account_type'", "]", "except", "KeyError", ":", "continue", "if", "acct_type", "not", "in", "enums", ".", "ACCOUNT_TYPE_OV", ":", "yield", "JSONError", "(", "\"Object '%s' is a User Account Object \"", "\"with an 'account_type' of '%s', which is not a \"", "\"value in the account-type-ov vocabulary.\"", "%", "(", "key", ",", "acct_type", ")", ",", "instance", "[", "'id'", "]", ",", "'account-type'", ")" ]
Ensure a user-account objects' 'account-type' property is from the account-type-ov vocabulary.
[ "Ensure", "a", "user", "-", "account", "objects", "account", "-", "type", "property", "is", "from", "the", "account", "-", "type", "-", "ov", "vocabulary", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L450-L464
train
oasis-open/cti-stix-validator
stix2validator/v21/shoulds.py
observable_object_keys
def observable_object_keys(instance): """Ensure observable-objects keys are non-negative integers. """ digits_re = re.compile(r"^\d+$") for key in instance['objects']: if not digits_re.match(key): yield JSONError("'%s' is not a good key value. Observable Objects " "should use non-negative integers for their keys." % key, instance['id'], 'observable-object-keys')
python
def observable_object_keys(instance): """Ensure observable-objects keys are non-negative integers. """ digits_re = re.compile(r"^\d+$") for key in instance['objects']: if not digits_re.match(key): yield JSONError("'%s' is not a good key value. Observable Objects " "should use non-negative integers for their keys." % key, instance['id'], 'observable-object-keys')
[ "def", "observable_object_keys", "(", "instance", ")", ":", "digits_re", "=", "re", ".", "compile", "(", "r\"^\\d+$\"", ")", "for", "key", "in", "instance", "[", "'objects'", "]", ":", "if", "not", "digits_re", ".", "match", "(", "key", ")", ":", "yield", "JSONError", "(", "\"'%s' is not a good key value. Observable Objects \"", "\"should use non-negative integers for their keys.\"", "%", "key", ",", "instance", "[", "'id'", "]", ",", "'observable-object-keys'", ")" ]
Ensure observable-objects keys are non-negative integers.
[ "Ensure", "observable", "-", "objects", "keys", "are", "non", "-", "negative", "integers", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L468-L476
train
oasis-open/cti-stix-validator
stix2validator/v21/shoulds.py
custom_observable_object_prefix_strict
def custom_observable_object_prefix_strict(instance): """Ensure custom observable objects follow strict naming style conventions. """ for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] not in enums.OBSERVABLE_TYPES and obj['type'] not in enums.OBSERVABLE_RESERVED_OBJECTS and not CUSTOM_TYPE_PREFIX_RE.match(obj['type'])): yield JSONError("Custom Observable Object type '%s' should start " "with 'x-' followed by a source unique identifier " "(like a domain name with dots replaced by " "hyphens), a hyphen and then the name." % obj['type'], instance['id'], 'custom-prefix')
python
def custom_observable_object_prefix_strict(instance): """Ensure custom observable objects follow strict naming style conventions. """ for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] not in enums.OBSERVABLE_TYPES and obj['type'] not in enums.OBSERVABLE_RESERVED_OBJECTS and not CUSTOM_TYPE_PREFIX_RE.match(obj['type'])): yield JSONError("Custom Observable Object type '%s' should start " "with 'x-' followed by a source unique identifier " "(like a domain name with dots replaced by " "hyphens), a hyphen and then the name." % obj['type'], instance['id'], 'custom-prefix')
[ "def", "custom_observable_object_prefix_strict", "(", "instance", ")", ":", "for", "key", ",", "obj", "in", "instance", "[", "'objects'", "]", ".", "items", "(", ")", ":", "if", "(", "'type'", "in", "obj", "and", "obj", "[", "'type'", "]", "not", "in", "enums", ".", "OBSERVABLE_TYPES", "and", "obj", "[", "'type'", "]", "not", "in", "enums", ".", "OBSERVABLE_RESERVED_OBJECTS", "and", "not", "CUSTOM_TYPE_PREFIX_RE", ".", "match", "(", "obj", "[", "'type'", "]", ")", ")", ":", "yield", "JSONError", "(", "\"Custom Observable Object type '%s' should start \"", "\"with 'x-' followed by a source unique identifier \"", "\"(like a domain name with dots replaced by \"", "\"hyphens), a hyphen and then the name.\"", "%", "obj", "[", "'type'", "]", ",", "instance", "[", "'id'", "]", ",", "'custom-prefix'", ")" ]
Ensure custom observable objects follow strict naming style conventions.
[ "Ensure", "custom", "observable", "objects", "follow", "strict", "naming", "style", "conventions", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L504-L516
train
oasis-open/cti-stix-validator
stix2validator/v21/shoulds.py
custom_observable_object_prefix_lax
def custom_observable_object_prefix_lax(instance): """Ensure custom observable objects follow naming style conventions. """ for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] not in enums.OBSERVABLE_TYPES and obj['type'] not in enums.OBSERVABLE_RESERVED_OBJECTS and not CUSTOM_TYPE_LAX_PREFIX_RE.match(obj['type'])): yield JSONError("Custom Observable Object type '%s' should start " "with 'x-'." % obj['type'], instance['id'], 'custom-prefix-lax')
python
def custom_observable_object_prefix_lax(instance): """Ensure custom observable objects follow naming style conventions. """ for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] not in enums.OBSERVABLE_TYPES and obj['type'] not in enums.OBSERVABLE_RESERVED_OBJECTS and not CUSTOM_TYPE_LAX_PREFIX_RE.match(obj['type'])): yield JSONError("Custom Observable Object type '%s' should start " "with 'x-'." % obj['type'], instance['id'], 'custom-prefix-lax')
[ "def", "custom_observable_object_prefix_lax", "(", "instance", ")", ":", "for", "key", ",", "obj", "in", "instance", "[", "'objects'", "]", ".", "items", "(", ")", ":", "if", "(", "'type'", "in", "obj", "and", "obj", "[", "'type'", "]", "not", "in", "enums", ".", "OBSERVABLE_TYPES", "and", "obj", "[", "'type'", "]", "not", "in", "enums", ".", "OBSERVABLE_RESERVED_OBJECTS", "and", "not", "CUSTOM_TYPE_LAX_PREFIX_RE", ".", "match", "(", "obj", "[", "'type'", "]", ")", ")", ":", "yield", "JSONError", "(", "\"Custom Observable Object type '%s' should start \"", "\"with 'x-'.\"", "%", "obj", "[", "'type'", "]", ",", "instance", "[", "'id'", "]", ",", "'custom-prefix-lax'", ")" ]
Ensure custom observable objects follow naming style conventions.
[ "Ensure", "custom", "observable", "objects", "follow", "naming", "style", "conventions", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L520-L530
train
oasis-open/cti-stix-validator
stix2validator/v21/shoulds.py
custom_object_extension_prefix_strict
def custom_object_extension_prefix_strict(instance): """Ensure custom observable object extensions follow strict naming style conventions. """ for key, obj in instance['objects'].items(): if not ('extensions' in obj and 'type' in obj and obj['type'] in enums.OBSERVABLE_EXTENSIONS): continue for ext_key in obj['extensions']: if (ext_key not in enums.OBSERVABLE_EXTENSIONS[obj['type']] and not CUSTOM_TYPE_PREFIX_RE.match(ext_key)): yield JSONError("Custom Cyber Observable Object extension type" " '%s' should start with 'x-' followed by a source " "unique identifier (like a domain name with dots " "replaced by hyphens), a hyphen and then the name." % ext_key, instance['id'], 'custom-prefix')
python
def custom_object_extension_prefix_strict(instance): """Ensure custom observable object extensions follow strict naming style conventions. """ for key, obj in instance['objects'].items(): if not ('extensions' in obj and 'type' in obj and obj['type'] in enums.OBSERVABLE_EXTENSIONS): continue for ext_key in obj['extensions']: if (ext_key not in enums.OBSERVABLE_EXTENSIONS[obj['type']] and not CUSTOM_TYPE_PREFIX_RE.match(ext_key)): yield JSONError("Custom Cyber Observable Object extension type" " '%s' should start with 'x-' followed by a source " "unique identifier (like a domain name with dots " "replaced by hyphens), a hyphen and then the name." % ext_key, instance['id'], 'custom-prefix')
[ "def", "custom_object_extension_prefix_strict", "(", "instance", ")", ":", "for", "key", ",", "obj", "in", "instance", "[", "'objects'", "]", ".", "items", "(", ")", ":", "if", "not", "(", "'extensions'", "in", "obj", "and", "'type'", "in", "obj", "and", "obj", "[", "'type'", "]", "in", "enums", ".", "OBSERVABLE_EXTENSIONS", ")", ":", "continue", "for", "ext_key", "in", "obj", "[", "'extensions'", "]", ":", "if", "(", "ext_key", "not", "in", "enums", ".", "OBSERVABLE_EXTENSIONS", "[", "obj", "[", "'type'", "]", "]", "and", "not", "CUSTOM_TYPE_PREFIX_RE", ".", "match", "(", "ext_key", ")", ")", ":", "yield", "JSONError", "(", "\"Custom Cyber Observable Object extension type\"", "\" '%s' should start with 'x-' followed by a source \"", "\"unique identifier (like a domain name with dots \"", "\"replaced by hyphens), a hyphen and then the name.\"", "%", "ext_key", ",", "instance", "[", "'id'", "]", ",", "'custom-prefix'", ")" ]
Ensure custom observable object extensions follow strict naming style conventions.
[ "Ensure", "custom", "observable", "object", "extensions", "follow", "strict", "naming", "style", "conventions", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L534-L550
train
oasis-open/cti-stix-validator
stix2validator/v21/shoulds.py
custom_object_extension_prefix_lax
def custom_object_extension_prefix_lax(instance): """Ensure custom observable object extensions follow naming style conventions. """ for key, obj in instance['objects'].items(): if not ('extensions' in obj and 'type' in obj and obj['type'] in enums.OBSERVABLE_EXTENSIONS): continue for ext_key in obj['extensions']: if (ext_key not in enums.OBSERVABLE_EXTENSIONS[obj['type']] and not CUSTOM_TYPE_LAX_PREFIX_RE.match(ext_key)): yield JSONError("Custom Cyber Observable Object extension type" " '%s' should start with 'x-'." % ext_key, instance['id'], 'custom-prefix-lax')
python
def custom_object_extension_prefix_lax(instance): """Ensure custom observable object extensions follow naming style conventions. """ for key, obj in instance['objects'].items(): if not ('extensions' in obj and 'type' in obj and obj['type'] in enums.OBSERVABLE_EXTENSIONS): continue for ext_key in obj['extensions']: if (ext_key not in enums.OBSERVABLE_EXTENSIONS[obj['type']] and not CUSTOM_TYPE_LAX_PREFIX_RE.match(ext_key)): yield JSONError("Custom Cyber Observable Object extension type" " '%s' should start with 'x-'." % ext_key, instance['id'], 'custom-prefix-lax')
[ "def", "custom_object_extension_prefix_lax", "(", "instance", ")", ":", "for", "key", ",", "obj", "in", "instance", "[", "'objects'", "]", ".", "items", "(", ")", ":", "if", "not", "(", "'extensions'", "in", "obj", "and", "'type'", "in", "obj", "and", "obj", "[", "'type'", "]", "in", "enums", ".", "OBSERVABLE_EXTENSIONS", ")", ":", "continue", "for", "ext_key", "in", "obj", "[", "'extensions'", "]", ":", "if", "(", "ext_key", "not", "in", "enums", ".", "OBSERVABLE_EXTENSIONS", "[", "obj", "[", "'type'", "]", "]", "and", "not", "CUSTOM_TYPE_LAX_PREFIX_RE", ".", "match", "(", "ext_key", ")", ")", ":", "yield", "JSONError", "(", "\"Custom Cyber Observable Object extension type\"", "\" '%s' should start with 'x-'.\"", "%", "ext_key", ",", "instance", "[", "'id'", "]", ",", "'custom-prefix-lax'", ")" ]
Ensure custom observable object extensions follow naming style conventions.
[ "Ensure", "custom", "observable", "object", "extensions", "follow", "naming", "style", "conventions", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L554-L568
train
oasis-open/cti-stix-validator
stix2validator/v21/shoulds.py
custom_observable_properties_prefix_strict
def custom_observable_properties_prefix_strict(instance): """Ensure observable object custom properties follow strict naming style conventions. """ for key, obj in instance['objects'].items(): if 'type' not in obj: continue type_ = obj['type'] for prop in obj: # Check objects' properties if (type_ in enums.OBSERVABLE_PROPERTIES and prop not in enums.OBSERVABLE_PROPERTIES[type_] and not CUSTOM_PROPERTY_PREFIX_RE.match(prop)): yield JSONError("Cyber Observable Object custom property '%s' " "should start with 'x_' followed by a source " "unique identifier (like a domain name with " "dots replaced by hyphens), a hyphen and then the" " name." % prop, instance['id'], 'custom-prefix') # Check properties of embedded cyber observable types if (type_ in enums.OBSERVABLE_EMBEDDED_PROPERTIES and prop in enums.OBSERVABLE_EMBEDDED_PROPERTIES[type_]): for embed_prop in obj[prop]: if isinstance(embed_prop, dict): for embedded in embed_prop: if (embedded not in enums.OBSERVABLE_EMBEDDED_PROPERTIES[type_][prop] and not CUSTOM_PROPERTY_PREFIX_RE.match(embedded)): yield JSONError("Cyber Observable Object custom " "property '%s' in the %s property of " "%s object should start with 'x_' " "followed by a source unique " "identifier (like a domain name with " "dots replaced by hyphens), a hyphen and " "then the name." % (embedded, prop, type_), instance['id'], 'custom-prefix') elif (embed_prop not in enums.OBSERVABLE_EMBEDDED_PROPERTIES[type_][prop] and not CUSTOM_PROPERTY_PREFIX_RE.match(embed_prop)): yield JSONError("Cyber Observable Object custom " "property '%s' in the %s property of " "%s object should start with 'x_' " "followed by a source unique " "identifier (like a domain name with " "dots replaced by hyphens), a hyphen and " "then the name." % (embed_prop, prop, type_), instance['id'], 'custom-prefix') # Check object extensions' properties if (type_ in enums.OBSERVABLE_EXTENSIONS and 'extensions' in obj): for ext_key in obj['extensions']: if ext_key in enums.OBSERVABLE_EXTENSIONS[type_]: for ext_prop in obj['extensions'][ext_key]: if (ext_prop not in enums.OBSERVABLE_EXTENSION_PROPERTIES[ext_key] and not CUSTOM_PROPERTY_PREFIX_RE.match(ext_prop)): yield JSONError("Cyber Observable Object custom " "property '%s' in the %s extension " "should start with 'x_' followed by a " "source unique identifier (like a " "domain name with dots replaced by " "hyphens), a hyphen and then the name." % (ext_prop, ext_key), instance['id'], 'custom-prefix') if ext_key in enums.OBSERVABLE_EXTENSIONS[type_]: for ext_prop in obj['extensions'][ext_key]: if (ext_key in enums.OBSERVABLE_EXTENSION_EMBEDDED_PROPERTIES and ext_prop in enums.OBSERVABLE_EXTENSION_EMBEDDED_PROPERTIES[ext_key]): for embed_prop in obj['extensions'][ext_key][ext_prop]: if not (isinstance(embed_prop, Iterable) and not isinstance(embed_prop, string_types)): embed_prop = [embed_prop] for p in embed_prop: if (p not in enums.OBSERVABLE_EXTENSION_EMBEDDED_PROPERTIES[ext_key][ext_prop] and not CUSTOM_PROPERTY_PREFIX_RE.match(p)): yield JSONError("Cyber Observable Object " "custom property '%s' in the %s " "property of the %s extension should " "start with 'x_' followed by a source " "unique identifier (like a domain name" " with dots replaced by hyphens), a " "hyphen and then the name." % (p, ext_prop, ext_key), instance['id'], 'custom-prefix')
python
def custom_observable_properties_prefix_strict(instance): """Ensure observable object custom properties follow strict naming style conventions. """ for key, obj in instance['objects'].items(): if 'type' not in obj: continue type_ = obj['type'] for prop in obj: # Check objects' properties if (type_ in enums.OBSERVABLE_PROPERTIES and prop not in enums.OBSERVABLE_PROPERTIES[type_] and not CUSTOM_PROPERTY_PREFIX_RE.match(prop)): yield JSONError("Cyber Observable Object custom property '%s' " "should start with 'x_' followed by a source " "unique identifier (like a domain name with " "dots replaced by hyphens), a hyphen and then the" " name." % prop, instance['id'], 'custom-prefix') # Check properties of embedded cyber observable types if (type_ in enums.OBSERVABLE_EMBEDDED_PROPERTIES and prop in enums.OBSERVABLE_EMBEDDED_PROPERTIES[type_]): for embed_prop in obj[prop]: if isinstance(embed_prop, dict): for embedded in embed_prop: if (embedded not in enums.OBSERVABLE_EMBEDDED_PROPERTIES[type_][prop] and not CUSTOM_PROPERTY_PREFIX_RE.match(embedded)): yield JSONError("Cyber Observable Object custom " "property '%s' in the %s property of " "%s object should start with 'x_' " "followed by a source unique " "identifier (like a domain name with " "dots replaced by hyphens), a hyphen and " "then the name." % (embedded, prop, type_), instance['id'], 'custom-prefix') elif (embed_prop not in enums.OBSERVABLE_EMBEDDED_PROPERTIES[type_][prop] and not CUSTOM_PROPERTY_PREFIX_RE.match(embed_prop)): yield JSONError("Cyber Observable Object custom " "property '%s' in the %s property of " "%s object should start with 'x_' " "followed by a source unique " "identifier (like a domain name with " "dots replaced by hyphens), a hyphen and " "then the name." % (embed_prop, prop, type_), instance['id'], 'custom-prefix') # Check object extensions' properties if (type_ in enums.OBSERVABLE_EXTENSIONS and 'extensions' in obj): for ext_key in obj['extensions']: if ext_key in enums.OBSERVABLE_EXTENSIONS[type_]: for ext_prop in obj['extensions'][ext_key]: if (ext_prop not in enums.OBSERVABLE_EXTENSION_PROPERTIES[ext_key] and not CUSTOM_PROPERTY_PREFIX_RE.match(ext_prop)): yield JSONError("Cyber Observable Object custom " "property '%s' in the %s extension " "should start with 'x_' followed by a " "source unique identifier (like a " "domain name with dots replaced by " "hyphens), a hyphen and then the name." % (ext_prop, ext_key), instance['id'], 'custom-prefix') if ext_key in enums.OBSERVABLE_EXTENSIONS[type_]: for ext_prop in obj['extensions'][ext_key]: if (ext_key in enums.OBSERVABLE_EXTENSION_EMBEDDED_PROPERTIES and ext_prop in enums.OBSERVABLE_EXTENSION_EMBEDDED_PROPERTIES[ext_key]): for embed_prop in obj['extensions'][ext_key][ext_prop]: if not (isinstance(embed_prop, Iterable) and not isinstance(embed_prop, string_types)): embed_prop = [embed_prop] for p in embed_prop: if (p not in enums.OBSERVABLE_EXTENSION_EMBEDDED_PROPERTIES[ext_key][ext_prop] and not CUSTOM_PROPERTY_PREFIX_RE.match(p)): yield JSONError("Cyber Observable Object " "custom property '%s' in the %s " "property of the %s extension should " "start with 'x_' followed by a source " "unique identifier (like a domain name" " with dots replaced by hyphens), a " "hyphen and then the name." % (p, ext_prop, ext_key), instance['id'], 'custom-prefix')
[ "def", "custom_observable_properties_prefix_strict", "(", "instance", ")", ":", "for", "key", ",", "obj", "in", "instance", "[", "'objects'", "]", ".", "items", "(", ")", ":", "if", "'type'", "not", "in", "obj", ":", "continue", "type_", "=", "obj", "[", "'type'", "]", "for", "prop", "in", "obj", ":", "# Check objects' properties", "if", "(", "type_", "in", "enums", ".", "OBSERVABLE_PROPERTIES", "and", "prop", "not", "in", "enums", ".", "OBSERVABLE_PROPERTIES", "[", "type_", "]", "and", "not", "CUSTOM_PROPERTY_PREFIX_RE", ".", "match", "(", "prop", ")", ")", ":", "yield", "JSONError", "(", "\"Cyber Observable Object custom property '%s' \"", "\"should start with 'x_' followed by a source \"", "\"unique identifier (like a domain name with \"", "\"dots replaced by hyphens), a hyphen and then the\"", "\" name.\"", "%", "prop", ",", "instance", "[", "'id'", "]", ",", "'custom-prefix'", ")", "# Check properties of embedded cyber observable types", "if", "(", "type_", "in", "enums", ".", "OBSERVABLE_EMBEDDED_PROPERTIES", "and", "prop", "in", "enums", ".", "OBSERVABLE_EMBEDDED_PROPERTIES", "[", "type_", "]", ")", ":", "for", "embed_prop", "in", "obj", "[", "prop", "]", ":", "if", "isinstance", "(", "embed_prop", ",", "dict", ")", ":", "for", "embedded", "in", "embed_prop", ":", "if", "(", "embedded", "not", "in", "enums", ".", "OBSERVABLE_EMBEDDED_PROPERTIES", "[", "type_", "]", "[", "prop", "]", "and", "not", "CUSTOM_PROPERTY_PREFIX_RE", ".", "match", "(", "embedded", ")", ")", ":", "yield", "JSONError", "(", "\"Cyber Observable Object custom \"", "\"property '%s' in the %s property of \"", "\"%s object should start with 'x_' \"", "\"followed by a source unique \"", "\"identifier (like a domain name with \"", "\"dots replaced by hyphens), a hyphen and \"", "\"then the name.\"", "%", "(", "embedded", ",", "prop", ",", "type_", ")", ",", "instance", "[", "'id'", "]", ",", "'custom-prefix'", ")", "elif", "(", "embed_prop", "not", "in", "enums", ".", "OBSERVABLE_EMBEDDED_PROPERTIES", "[", "type_", "]", "[", "prop", "]", "and", "not", "CUSTOM_PROPERTY_PREFIX_RE", ".", "match", "(", "embed_prop", ")", ")", ":", "yield", "JSONError", "(", "\"Cyber Observable Object custom \"", "\"property '%s' in the %s property of \"", "\"%s object should start with 'x_' \"", "\"followed by a source unique \"", "\"identifier (like a domain name with \"", "\"dots replaced by hyphens), a hyphen and \"", "\"then the name.\"", "%", "(", "embed_prop", ",", "prop", ",", "type_", ")", ",", "instance", "[", "'id'", "]", ",", "'custom-prefix'", ")", "# Check object extensions' properties", "if", "(", "type_", "in", "enums", ".", "OBSERVABLE_EXTENSIONS", "and", "'extensions'", "in", "obj", ")", ":", "for", "ext_key", "in", "obj", "[", "'extensions'", "]", ":", "if", "ext_key", "in", "enums", ".", "OBSERVABLE_EXTENSIONS", "[", "type_", "]", ":", "for", "ext_prop", "in", "obj", "[", "'extensions'", "]", "[", "ext_key", "]", ":", "if", "(", "ext_prop", "not", "in", "enums", ".", "OBSERVABLE_EXTENSION_PROPERTIES", "[", "ext_key", "]", "and", "not", "CUSTOM_PROPERTY_PREFIX_RE", ".", "match", "(", "ext_prop", ")", ")", ":", "yield", "JSONError", "(", "\"Cyber Observable Object custom \"", "\"property '%s' in the %s extension \"", "\"should start with 'x_' followed by a \"", "\"source unique identifier (like a \"", "\"domain name with dots replaced by \"", "\"hyphens), a hyphen and then the name.\"", "%", "(", "ext_prop", ",", "ext_key", ")", ",", "instance", "[", "'id'", "]", ",", "'custom-prefix'", ")", "if", "ext_key", "in", "enums", ".", "OBSERVABLE_EXTENSIONS", "[", "type_", "]", ":", "for", "ext_prop", "in", "obj", "[", "'extensions'", "]", "[", "ext_key", "]", ":", "if", "(", "ext_key", "in", "enums", ".", "OBSERVABLE_EXTENSION_EMBEDDED_PROPERTIES", "and", "ext_prop", "in", "enums", ".", "OBSERVABLE_EXTENSION_EMBEDDED_PROPERTIES", "[", "ext_key", "]", ")", ":", "for", "embed_prop", "in", "obj", "[", "'extensions'", "]", "[", "ext_key", "]", "[", "ext_prop", "]", ":", "if", "not", "(", "isinstance", "(", "embed_prop", ",", "Iterable", ")", "and", "not", "isinstance", "(", "embed_prop", ",", "string_types", ")", ")", ":", "embed_prop", "=", "[", "embed_prop", "]", "for", "p", "in", "embed_prop", ":", "if", "(", "p", "not", "in", "enums", ".", "OBSERVABLE_EXTENSION_EMBEDDED_PROPERTIES", "[", "ext_key", "]", "[", "ext_prop", "]", "and", "not", "CUSTOM_PROPERTY_PREFIX_RE", ".", "match", "(", "p", ")", ")", ":", "yield", "JSONError", "(", "\"Cyber Observable Object \"", "\"custom property '%s' in the %s \"", "\"property of the %s extension should \"", "\"start with 'x_' followed by a source \"", "\"unique identifier (like a domain name\"", "\" with dots replaced by hyphens), a \"", "\"hyphen and then the name.\"", "%", "(", "p", ",", "ext_prop", ",", "ext_key", ")", ",", "instance", "[", "'id'", "]", ",", "'custom-prefix'", ")" ]
Ensure observable object custom properties follow strict naming style conventions.
[ "Ensure", "observable", "object", "custom", "properties", "follow", "strict", "naming", "style", "conventions", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L572-L657
train
oasis-open/cti-stix-validator
stix2validator/v21/shoulds.py
network_traffic_ports
def network_traffic_ports(instance): """Ensure network-traffic objects contain both src_port and dst_port. """ for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'network-traffic' and ('src_port' not in obj or 'dst_port' not in obj)): yield JSONError("The Network Traffic object '%s' should contain " "both the 'src_port' and 'dst_port' properties." % key, instance['id'], 'network-traffic-ports')
python
def network_traffic_ports(instance): """Ensure network-traffic objects contain both src_port and dst_port. """ for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'network-traffic' and ('src_port' not in obj or 'dst_port' not in obj)): yield JSONError("The Network Traffic object '%s' should contain " "both the 'src_port' and 'dst_port' properties." % key, instance['id'], 'network-traffic-ports')
[ "def", "network_traffic_ports", "(", "instance", ")", ":", "for", "key", ",", "obj", "in", "instance", "[", "'objects'", "]", ".", "items", "(", ")", ":", "if", "(", "'type'", "in", "obj", "and", "obj", "[", "'type'", "]", "==", "'network-traffic'", "and", "(", "'src_port'", "not", "in", "obj", "or", "'dst_port'", "not", "in", "obj", ")", ")", ":", "yield", "JSONError", "(", "\"The Network Traffic object '%s' should contain \"", "\"both the 'src_port' and 'dst_port' properties.\"", "%", "key", ",", "instance", "[", "'id'", "]", ",", "'network-traffic-ports'", ")" ]
Ensure network-traffic objects contain both src_port and dst_port.
[ "Ensure", "network", "-", "traffic", "objects", "contain", "both", "src_port", "and", "dst_port", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L733-L741
train
oasis-open/cti-stix-validator
stix2validator/v21/shoulds.py
mime_type
def mime_type(instance): """Ensure the 'mime_type' property of file objects comes from the Template column in the IANA media type registry. """ mime_pattern = re.compile(r'^(application|audio|font|image|message|model' '|multipart|text|video)/[a-zA-Z0-9.+_-]+') for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'file' and 'mime_type' in obj): if enums.media_types(): if obj['mime_type'] not in enums.media_types(): yield JSONError("The 'mime_type' property of object '%s' " "('%s') should be an IANA registered MIME " "Type of the form 'type/subtype'." % (key, obj['mime_type']), instance['id'], 'mime-type') else: info("Can't reach IANA website; using regex for mime types.") if not mime_pattern.match(obj['mime_type']): yield JSONError("The 'mime_type' property of object '%s' " "('%s') should be an IANA MIME Type of the" " form 'type/subtype'." % (key, obj['mime_type']), instance['id'], 'mime-type')
python
def mime_type(instance): """Ensure the 'mime_type' property of file objects comes from the Template column in the IANA media type registry. """ mime_pattern = re.compile(r'^(application|audio|font|image|message|model' '|multipart|text|video)/[a-zA-Z0-9.+_-]+') for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'file' and 'mime_type' in obj): if enums.media_types(): if obj['mime_type'] not in enums.media_types(): yield JSONError("The 'mime_type' property of object '%s' " "('%s') should be an IANA registered MIME " "Type of the form 'type/subtype'." % (key, obj['mime_type']), instance['id'], 'mime-type') else: info("Can't reach IANA website; using regex for mime types.") if not mime_pattern.match(obj['mime_type']): yield JSONError("The 'mime_type' property of object '%s' " "('%s') should be an IANA MIME Type of the" " form 'type/subtype'." % (key, obj['mime_type']), instance['id'], 'mime-type')
[ "def", "mime_type", "(", "instance", ")", ":", "mime_pattern", "=", "re", ".", "compile", "(", "r'^(application|audio|font|image|message|model'", "'|multipart|text|video)/[a-zA-Z0-9.+_-]+'", ")", "for", "key", ",", "obj", "in", "instance", "[", "'objects'", "]", ".", "items", "(", ")", ":", "if", "(", "'type'", "in", "obj", "and", "obj", "[", "'type'", "]", "==", "'file'", "and", "'mime_type'", "in", "obj", ")", ":", "if", "enums", ".", "media_types", "(", ")", ":", "if", "obj", "[", "'mime_type'", "]", "not", "in", "enums", ".", "media_types", "(", ")", ":", "yield", "JSONError", "(", "\"The 'mime_type' property of object '%s' \"", "\"('%s') should be an IANA registered MIME \"", "\"Type of the form 'type/subtype'.\"", "%", "(", "key", ",", "obj", "[", "'mime_type'", "]", ")", ",", "instance", "[", "'id'", "]", ",", "'mime-type'", ")", "else", ":", "info", "(", "\"Can't reach IANA website; using regex for mime types.\"", ")", "if", "not", "mime_pattern", ".", "match", "(", "obj", "[", "'mime_type'", "]", ")", ":", "yield", "JSONError", "(", "\"The 'mime_type' property of object '%s' \"", "\"('%s') should be an IANA MIME Type of the\"", "\" form 'type/subtype'.\"", "%", "(", "key", ",", "obj", "[", "'mime_type'", "]", ")", ",", "instance", "[", "'id'", "]", ",", "'mime-type'", ")" ]
Ensure the 'mime_type' property of file objects comes from the Template column in the IANA media type registry.
[ "Ensure", "the", "mime_type", "property", "of", "file", "objects", "comes", "from", "the", "Template", "column", "in", "the", "IANA", "media", "type", "registry", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L745-L767
train
oasis-open/cti-stix-validator
stix2validator/v21/shoulds.py
protocols
def protocols(instance): """Ensure the 'protocols' property of network-traffic objects contains only values from the IANA Service Name and Transport Protocol Port Number Registry. """ for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'network-traffic' and 'protocols' in obj): for prot in obj['protocols']: if enums.protocols(): if prot not in enums.protocols(): yield JSONError("The 'protocols' property of object " "'%s' contains a value ('%s') not in " "IANA Service Name and Transport " "Protocol Port Number Registry." % (key, prot), instance['id'], 'protocols') else: info("Can't reach IANA website; using regex for protocols.") if not PROTOCOL_RE.match(prot): yield JSONError("The 'protocols' property of object " "'%s' contains a value ('%s') not in " "IANA Service Name and Transport " "Protocol Port Number Registry." % (key, prot), instance['id'], 'protocols')
python
def protocols(instance): """Ensure the 'protocols' property of network-traffic objects contains only values from the IANA Service Name and Transport Protocol Port Number Registry. """ for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'network-traffic' and 'protocols' in obj): for prot in obj['protocols']: if enums.protocols(): if prot not in enums.protocols(): yield JSONError("The 'protocols' property of object " "'%s' contains a value ('%s') not in " "IANA Service Name and Transport " "Protocol Port Number Registry." % (key, prot), instance['id'], 'protocols') else: info("Can't reach IANA website; using regex for protocols.") if not PROTOCOL_RE.match(prot): yield JSONError("The 'protocols' property of object " "'%s' contains a value ('%s') not in " "IANA Service Name and Transport " "Protocol Port Number Registry." % (key, prot), instance['id'], 'protocols')
[ "def", "protocols", "(", "instance", ")", ":", "for", "key", ",", "obj", "in", "instance", "[", "'objects'", "]", ".", "items", "(", ")", ":", "if", "(", "'type'", "in", "obj", "and", "obj", "[", "'type'", "]", "==", "'network-traffic'", "and", "'protocols'", "in", "obj", ")", ":", "for", "prot", "in", "obj", "[", "'protocols'", "]", ":", "if", "enums", ".", "protocols", "(", ")", ":", "if", "prot", "not", "in", "enums", ".", "protocols", "(", ")", ":", "yield", "JSONError", "(", "\"The 'protocols' property of object \"", "\"'%s' contains a value ('%s') not in \"", "\"IANA Service Name and Transport \"", "\"Protocol Port Number Registry.\"", "%", "(", "key", ",", "prot", ")", ",", "instance", "[", "'id'", "]", ",", "'protocols'", ")", "else", ":", "info", "(", "\"Can't reach IANA website; using regex for protocols.\"", ")", "if", "not", "PROTOCOL_RE", ".", "match", "(", "prot", ")", ":", "yield", "JSONError", "(", "\"The 'protocols' property of object \"", "\"'%s' contains a value ('%s') not in \"", "\"IANA Service Name and Transport \"", "\"Protocol Port Number Registry.\"", "%", "(", "key", ",", "prot", ")", ",", "instance", "[", "'id'", "]", ",", "'protocols'", ")" ]
Ensure the 'protocols' property of network-traffic objects contains only values from the IANA Service Name and Transport Protocol Port Number Registry.
[ "Ensure", "the", "protocols", "property", "of", "network", "-", "traffic", "objects", "contains", "only", "values", "from", "the", "IANA", "Service", "Name", "and", "Transport", "Protocol", "Port", "Number", "Registry", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L771-L796
train
oasis-open/cti-stix-validator
stix2validator/v21/shoulds.py
ipfix
def ipfix(instance): """Ensure the 'ipfix' property of network-traffic objects contains only values from the IANA IP Flow Information Export (IPFIX) Entities Registry. """ ipf_pattern = re.compile(r'^[a-z][a-zA-Z0-9]+') for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'network-traffic' and 'ipfix' in obj): for ipf in obj['ipfix']: if enums.ipfix(): if ipf not in enums.ipfix(): yield JSONError("The 'ipfix' property of object " "'%s' contains a key ('%s') not in " "IANA IP Flow Information Export " "(IPFIX) Entities Registry." % (key, ipf), instance['id'], 'ipfix') else: info("Can't reach IANA website; using regex for ipfix.") if not ipf_pattern.match(ipf): yield JSONError("The 'ipfix' property of object " "'%s' contains a key ('%s') not in " "IANA IP Flow Information Export " "(IPFIX) Entities Registry." % (key, ipf), instance['id'], 'ipfix')
python
def ipfix(instance): """Ensure the 'ipfix' property of network-traffic objects contains only values from the IANA IP Flow Information Export (IPFIX) Entities Registry. """ ipf_pattern = re.compile(r'^[a-z][a-zA-Z0-9]+') for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'network-traffic' and 'ipfix' in obj): for ipf in obj['ipfix']: if enums.ipfix(): if ipf not in enums.ipfix(): yield JSONError("The 'ipfix' property of object " "'%s' contains a key ('%s') not in " "IANA IP Flow Information Export " "(IPFIX) Entities Registry." % (key, ipf), instance['id'], 'ipfix') else: info("Can't reach IANA website; using regex for ipfix.") if not ipf_pattern.match(ipf): yield JSONError("The 'ipfix' property of object " "'%s' contains a key ('%s') not in " "IANA IP Flow Information Export " "(IPFIX) Entities Registry." % (key, ipf), instance['id'], 'ipfix')
[ "def", "ipfix", "(", "instance", ")", ":", "ipf_pattern", "=", "re", ".", "compile", "(", "r'^[a-z][a-zA-Z0-9]+'", ")", "for", "key", ",", "obj", "in", "instance", "[", "'objects'", "]", ".", "items", "(", ")", ":", "if", "(", "'type'", "in", "obj", "and", "obj", "[", "'type'", "]", "==", "'network-traffic'", "and", "'ipfix'", "in", "obj", ")", ":", "for", "ipf", "in", "obj", "[", "'ipfix'", "]", ":", "if", "enums", ".", "ipfix", "(", ")", ":", "if", "ipf", "not", "in", "enums", ".", "ipfix", "(", ")", ":", "yield", "JSONError", "(", "\"The 'ipfix' property of object \"", "\"'%s' contains a key ('%s') not in \"", "\"IANA IP Flow Information Export \"", "\"(IPFIX) Entities Registry.\"", "%", "(", "key", ",", "ipf", ")", ",", "instance", "[", "'id'", "]", ",", "'ipfix'", ")", "else", ":", "info", "(", "\"Can't reach IANA website; using regex for ipfix.\"", ")", "if", "not", "ipf_pattern", ".", "match", "(", "ipf", ")", ":", "yield", "JSONError", "(", "\"The 'ipfix' property of object \"", "\"'%s' contains a key ('%s') not in \"", "\"IANA IP Flow Information Export \"", "\"(IPFIX) Entities Registry.\"", "%", "(", "key", ",", "ipf", ")", ",", "instance", "[", "'id'", "]", ",", "'ipfix'", ")" ]
Ensure the 'ipfix' property of network-traffic objects contains only values from the IANA IP Flow Information Export (IPFIX) Entities Registry.
[ "Ensure", "the", "ipfix", "property", "of", "network", "-", "traffic", "objects", "contains", "only", "values", "from", "the", "IANA", "IP", "Flow", "Information", "Export", "(", "IPFIX", ")", "Entities", "Registry", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L800-L825
train
oasis-open/cti-stix-validator
stix2validator/v21/shoulds.py
http_request_headers
def http_request_headers(instance): """Ensure the keys of the 'request_headers' property of the http-request- ext extension of network-traffic objects conform to the format for HTTP request headers. Use a regex because there isn't a definitive source. https://www.iana.org/assignments/message-headers/message-headers.xhtml does not differentiate between request and response headers, and leaves out several common non-standard request fields listed elsewhere. """ for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'network-traffic'): try: headers = obj['extensions']['http-request-ext']['request_header'] except KeyError: continue for hdr in headers: if hdr not in enums.HTTP_REQUEST_HEADERS: yield JSONError("The 'request_header' property of object " "'%s' contains an invalid HTTP request " "header ('%s')." % (key, hdr), instance['id'], 'http-request-headers')
python
def http_request_headers(instance): """Ensure the keys of the 'request_headers' property of the http-request- ext extension of network-traffic objects conform to the format for HTTP request headers. Use a regex because there isn't a definitive source. https://www.iana.org/assignments/message-headers/message-headers.xhtml does not differentiate between request and response headers, and leaves out several common non-standard request fields listed elsewhere. """ for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'network-traffic'): try: headers = obj['extensions']['http-request-ext']['request_header'] except KeyError: continue for hdr in headers: if hdr not in enums.HTTP_REQUEST_HEADERS: yield JSONError("The 'request_header' property of object " "'%s' contains an invalid HTTP request " "header ('%s')." % (key, hdr), instance['id'], 'http-request-headers')
[ "def", "http_request_headers", "(", "instance", ")", ":", "for", "key", ",", "obj", "in", "instance", "[", "'objects'", "]", ".", "items", "(", ")", ":", "if", "(", "'type'", "in", "obj", "and", "obj", "[", "'type'", "]", "==", "'network-traffic'", ")", ":", "try", ":", "headers", "=", "obj", "[", "'extensions'", "]", "[", "'http-request-ext'", "]", "[", "'request_header'", "]", "except", "KeyError", ":", "continue", "for", "hdr", "in", "headers", ":", "if", "hdr", "not", "in", "enums", ".", "HTTP_REQUEST_HEADERS", ":", "yield", "JSONError", "(", "\"The 'request_header' property of object \"", "\"'%s' contains an invalid HTTP request \"", "\"header ('%s').\"", "%", "(", "key", ",", "hdr", ")", ",", "instance", "[", "'id'", "]", ",", "'http-request-headers'", ")" ]
Ensure the keys of the 'request_headers' property of the http-request- ext extension of network-traffic objects conform to the format for HTTP request headers. Use a regex because there isn't a definitive source. https://www.iana.org/assignments/message-headers/message-headers.xhtml does not differentiate between request and response headers, and leaves out several common non-standard request fields listed elsewhere.
[ "Ensure", "the", "keys", "of", "the", "request_headers", "property", "of", "the", "http", "-", "request", "-", "ext", "extension", "of", "network", "-", "traffic", "objects", "conform", "to", "the", "format", "for", "HTTP", "request", "headers", ".", "Use", "a", "regex", "because", "there", "isn", "t", "a", "definitive", "source", ".", "https", ":", "//", "www", ".", "iana", ".", "org", "/", "assignments", "/", "message", "-", "headers", "/", "message", "-", "headers", ".", "xhtml", "does", "not", "differentiate", "between", "request", "and", "response", "headers", "and", "leaves", "out", "several", "common", "non", "-", "standard", "request", "fields", "listed", "elsewhere", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L829-L850
train
oasis-open/cti-stix-validator
stix2validator/v21/shoulds.py
socket_options
def socket_options(instance): """Ensure the keys of the 'options' property of the socket-ext extension of network-traffic objects are only valid socket options (SO_*). """ for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'network-traffic'): try: options = obj['extensions']['socket-ext']['options'] except KeyError: continue for opt in options: if opt not in enums.SOCKET_OPTIONS: yield JSONError("The 'options' property of object '%s' " "contains a key ('%s') that is not a valid" " socket option (SO_*)." % (key, opt), instance['id'], 'socket-options')
python
def socket_options(instance): """Ensure the keys of the 'options' property of the socket-ext extension of network-traffic objects are only valid socket options (SO_*). """ for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'network-traffic'): try: options = obj['extensions']['socket-ext']['options'] except KeyError: continue for opt in options: if opt not in enums.SOCKET_OPTIONS: yield JSONError("The 'options' property of object '%s' " "contains a key ('%s') that is not a valid" " socket option (SO_*)." % (key, opt), instance['id'], 'socket-options')
[ "def", "socket_options", "(", "instance", ")", ":", "for", "key", ",", "obj", "in", "instance", "[", "'objects'", "]", ".", "items", "(", ")", ":", "if", "(", "'type'", "in", "obj", "and", "obj", "[", "'type'", "]", "==", "'network-traffic'", ")", ":", "try", ":", "options", "=", "obj", "[", "'extensions'", "]", "[", "'socket-ext'", "]", "[", "'options'", "]", "except", "KeyError", ":", "continue", "for", "opt", "in", "options", ":", "if", "opt", "not", "in", "enums", ".", "SOCKET_OPTIONS", ":", "yield", "JSONError", "(", "\"The 'options' property of object '%s' \"", "\"contains a key ('%s') that is not a valid\"", "\" socket option (SO_*).\"", "%", "(", "key", ",", "opt", ")", ",", "instance", "[", "'id'", "]", ",", "'socket-options'", ")" ]
Ensure the keys of the 'options' property of the socket-ext extension of network-traffic objects are only valid socket options (SO_*).
[ "Ensure", "the", "keys", "of", "the", "options", "property", "of", "the", "socket", "-", "ext", "extension", "of", "network", "-", "traffic", "objects", "are", "only", "valid", "socket", "options", "(", "SO_", "*", ")", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L854-L870
train
oasis-open/cti-stix-validator
stix2validator/v21/shoulds.py
pdf_doc_info
def pdf_doc_info(instance): """Ensure the keys of the 'document_info_dict' property of the pdf-ext extension of file objects are only valid PDF Document Information Dictionary Keys. """ for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'file'): try: did = obj['extensions']['pdf-ext']['document_info_dict'] except KeyError: continue for elem in did: if elem not in enums.PDF_DID: yield JSONError("The 'document_info_dict' property of " "object '%s' contains a key ('%s') that is" " not a valid PDF Document Information " "Dictionary key." % (key, elem), instance['id'], 'pdf-doc-info')
python
def pdf_doc_info(instance): """Ensure the keys of the 'document_info_dict' property of the pdf-ext extension of file objects are only valid PDF Document Information Dictionary Keys. """ for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'file'): try: did = obj['extensions']['pdf-ext']['document_info_dict'] except KeyError: continue for elem in did: if elem not in enums.PDF_DID: yield JSONError("The 'document_info_dict' property of " "object '%s' contains a key ('%s') that is" " not a valid PDF Document Information " "Dictionary key." % (key, elem), instance['id'], 'pdf-doc-info')
[ "def", "pdf_doc_info", "(", "instance", ")", ":", "for", "key", ",", "obj", "in", "instance", "[", "'objects'", "]", ".", "items", "(", ")", ":", "if", "(", "'type'", "in", "obj", "and", "obj", "[", "'type'", "]", "==", "'file'", ")", ":", "try", ":", "did", "=", "obj", "[", "'extensions'", "]", "[", "'pdf-ext'", "]", "[", "'document_info_dict'", "]", "except", "KeyError", ":", "continue", "for", "elem", "in", "did", ":", "if", "elem", "not", "in", "enums", ".", "PDF_DID", ":", "yield", "JSONError", "(", "\"The 'document_info_dict' property of \"", "\"object '%s' contains a key ('%s') that is\"", "\" not a valid PDF Document Information \"", "\"Dictionary key.\"", "%", "(", "key", ",", "elem", ")", ",", "instance", "[", "'id'", "]", ",", "'pdf-doc-info'", ")" ]
Ensure the keys of the 'document_info_dict' property of the pdf-ext extension of file objects are only valid PDF Document Information Dictionary Keys.
[ "Ensure", "the", "keys", "of", "the", "document_info_dict", "property", "of", "the", "pdf", "-", "ext", "extension", "of", "file", "objects", "are", "only", "valid", "PDF", "Document", "Information", "Dictionary", "Keys", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L874-L893
train
oasis-open/cti-stix-validator
stix2validator/v21/shoulds.py
countries
def countries(instance): """Ensure that the `country` property of `location` objects is a valid ISO 3166-1 ALPHA-2 Code. """ if (instance['type'] == 'location' and 'country' in instance and not instance['country'].upper() in enums.COUNTRY_CODES): return JSONError("Location `country` should be a valid ISO 3166-1 " "ALPHA-2 Code.", instance['id'], 'marking-definition-type')
python
def countries(instance): """Ensure that the `country` property of `location` objects is a valid ISO 3166-1 ALPHA-2 Code. """ if (instance['type'] == 'location' and 'country' in instance and not instance['country'].upper() in enums.COUNTRY_CODES): return JSONError("Location `country` should be a valid ISO 3166-1 " "ALPHA-2 Code.", instance['id'], 'marking-definition-type')
[ "def", "countries", "(", "instance", ")", ":", "if", "(", "instance", "[", "'type'", "]", "==", "'location'", "and", "'country'", "in", "instance", "and", "not", "instance", "[", "'country'", "]", ".", "upper", "(", ")", "in", "enums", ".", "COUNTRY_CODES", ")", ":", "return", "JSONError", "(", "\"Location `country` should be a valid ISO 3166-1 \"", "\"ALPHA-2 Code.\"", ",", "instance", "[", "'id'", "]", ",", "'marking-definition-type'", ")" ]
Ensure that the `country` property of `location` objects is a valid ISO 3166-1 ALPHA-2 Code.
[ "Ensure", "that", "the", "country", "property", "of", "location", "objects", "is", "a", "valid", "ISO", "3166", "-", "1", "ALPHA", "-", "2", "Code", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L896-L905
train
oasis-open/cti-stix-validator
stix2validator/v21/shoulds.py
windows_process_priority_format
def windows_process_priority_format(instance): """Ensure the 'priority' property of windows-process-ext ends in '_CLASS'. """ class_suffix_re = re.compile(r'.+_CLASS$') for key, obj in instance['objects'].items(): if 'type' in obj and obj['type'] == 'process': try: priority = obj['extensions']['windows-process-ext']['priority'] except KeyError: continue if not class_suffix_re.match(priority): yield JSONError("The 'priority' property of object '%s' should" " end in '_CLASS'." % key, instance['id'], 'windows-process-priority-format')
python
def windows_process_priority_format(instance): """Ensure the 'priority' property of windows-process-ext ends in '_CLASS'. """ class_suffix_re = re.compile(r'.+_CLASS$') for key, obj in instance['objects'].items(): if 'type' in obj and obj['type'] == 'process': try: priority = obj['extensions']['windows-process-ext']['priority'] except KeyError: continue if not class_suffix_re.match(priority): yield JSONError("The 'priority' property of object '%s' should" " end in '_CLASS'." % key, instance['id'], 'windows-process-priority-format')
[ "def", "windows_process_priority_format", "(", "instance", ")", ":", "class_suffix_re", "=", "re", ".", "compile", "(", "r'.+_CLASS$'", ")", "for", "key", ",", "obj", "in", "instance", "[", "'objects'", "]", ".", "items", "(", ")", ":", "if", "'type'", "in", "obj", "and", "obj", "[", "'type'", "]", "==", "'process'", ":", "try", ":", "priority", "=", "obj", "[", "'extensions'", "]", "[", "'windows-process-ext'", "]", "[", "'priority'", "]", "except", "KeyError", ":", "continue", "if", "not", "class_suffix_re", ".", "match", "(", "priority", ")", ":", "yield", "JSONError", "(", "\"The 'priority' property of object '%s' should\"", "\" end in '_CLASS'.\"", "%", "key", ",", "instance", "[", "'id'", "]", ",", "'windows-process-priority-format'", ")" ]
Ensure the 'priority' property of windows-process-ext ends in '_CLASS'.
[ "Ensure", "the", "priority", "property", "of", "windows", "-", "process", "-", "ext", "ends", "in", "_CLASS", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L909-L922
train
oasis-open/cti-stix-validator
stix2validator/v21/shoulds.py
hash_length
def hash_length(instance): """Ensure keys in 'hashes'-type properties are no more than 30 characters long. """ for key, obj in instance['objects'].items(): if 'type' not in obj: continue if obj['type'] == 'file': try: hashes = obj['hashes'] except KeyError: pass else: for h in hashes: if (len(h) > 30): yield JSONError("Object '%s' has a 'hashes' dictionary" " with a hash of type '%s', which is " "longer than 30 characters." % (key, h), instance['id'], 'hash-algo') try: ads = obj['extensions']['ntfs-ext']['alternate_data_streams'] except KeyError: pass else: for datastream in ads: if 'hashes' not in datastream: continue for h in datastream['hashes']: if (len(h) > 30): yield JSONError("Object '%s' has an NTFS extension" " with an alternate data stream that has a" " 'hashes' dictionary with a hash of type " "'%s', which is longer than 30 " "characters." % (key, h), instance['id'], 'hash-algo') try: head_hashes = obj['extensions']['windows-pebinary-ext']['file_header_hashes'] except KeyError: pass else: for h in head_hashes: if (len(h) > 30): yield JSONError("Object '%s' has a Windows PE Binary " "File extension with a file header hash of " "'%s', which is longer than 30 " "characters." % (key, h), instance['id'], 'hash-algo') try: hashes = obj['extensions']['windows-pebinary-ext']['optional_header']['hashes'] except KeyError: pass else: for h in hashes: if (len(h) > 30): yield JSONError("Object '%s' has a Windows PE Binary " "File extension with an optional header that " "has a hash of '%s', which is longer " "than 30 characters." % (key, h), instance['id'], 'hash-algo') try: sections = obj['extensions']['windows-pebinary-ext']['sections'] except KeyError: pass else: for s in sections: if 'hashes' not in s: continue for h in s['hashes']: if (len(h) > 30): yield JSONError("Object '%s' has a Windows PE " "Binary File extension with a section that" " has a hash of '%s', which is " "longer than 30 characters." % (key, h), instance['id'], 'hash-algo') elif obj['type'] == 'artifact' or obj['type'] == 'x509-certificate': try: hashes = obj['hashes'] except KeyError: pass else: for h in hashes: if (len(h) > 30): yield JSONError("Object '%s' has a 'hashes' dictionary" " with a hash of type '%s', which is " "longer than 30 characters." % (key, h), instance['id'], 'hash-algo')
python
def hash_length(instance): """Ensure keys in 'hashes'-type properties are no more than 30 characters long. """ for key, obj in instance['objects'].items(): if 'type' not in obj: continue if obj['type'] == 'file': try: hashes = obj['hashes'] except KeyError: pass else: for h in hashes: if (len(h) > 30): yield JSONError("Object '%s' has a 'hashes' dictionary" " with a hash of type '%s', which is " "longer than 30 characters." % (key, h), instance['id'], 'hash-algo') try: ads = obj['extensions']['ntfs-ext']['alternate_data_streams'] except KeyError: pass else: for datastream in ads: if 'hashes' not in datastream: continue for h in datastream['hashes']: if (len(h) > 30): yield JSONError("Object '%s' has an NTFS extension" " with an alternate data stream that has a" " 'hashes' dictionary with a hash of type " "'%s', which is longer than 30 " "characters." % (key, h), instance['id'], 'hash-algo') try: head_hashes = obj['extensions']['windows-pebinary-ext']['file_header_hashes'] except KeyError: pass else: for h in head_hashes: if (len(h) > 30): yield JSONError("Object '%s' has a Windows PE Binary " "File extension with a file header hash of " "'%s', which is longer than 30 " "characters." % (key, h), instance['id'], 'hash-algo') try: hashes = obj['extensions']['windows-pebinary-ext']['optional_header']['hashes'] except KeyError: pass else: for h in hashes: if (len(h) > 30): yield JSONError("Object '%s' has a Windows PE Binary " "File extension with an optional header that " "has a hash of '%s', which is longer " "than 30 characters." % (key, h), instance['id'], 'hash-algo') try: sections = obj['extensions']['windows-pebinary-ext']['sections'] except KeyError: pass else: for s in sections: if 'hashes' not in s: continue for h in s['hashes']: if (len(h) > 30): yield JSONError("Object '%s' has a Windows PE " "Binary File extension with a section that" " has a hash of '%s', which is " "longer than 30 characters." % (key, h), instance['id'], 'hash-algo') elif obj['type'] == 'artifact' or obj['type'] == 'x509-certificate': try: hashes = obj['hashes'] except KeyError: pass else: for h in hashes: if (len(h) > 30): yield JSONError("Object '%s' has a 'hashes' dictionary" " with a hash of type '%s', which is " "longer than 30 characters." % (key, h), instance['id'], 'hash-algo')
[ "def", "hash_length", "(", "instance", ")", ":", "for", "key", ",", "obj", "in", "instance", "[", "'objects'", "]", ".", "items", "(", ")", ":", "if", "'type'", "not", "in", "obj", ":", "continue", "if", "obj", "[", "'type'", "]", "==", "'file'", ":", "try", ":", "hashes", "=", "obj", "[", "'hashes'", "]", "except", "KeyError", ":", "pass", "else", ":", "for", "h", "in", "hashes", ":", "if", "(", "len", "(", "h", ")", ">", "30", ")", ":", "yield", "JSONError", "(", "\"Object '%s' has a 'hashes' dictionary\"", "\" with a hash of type '%s', which is \"", "\"longer than 30 characters.\"", "%", "(", "key", ",", "h", ")", ",", "instance", "[", "'id'", "]", ",", "'hash-algo'", ")", "try", ":", "ads", "=", "obj", "[", "'extensions'", "]", "[", "'ntfs-ext'", "]", "[", "'alternate_data_streams'", "]", "except", "KeyError", ":", "pass", "else", ":", "for", "datastream", "in", "ads", ":", "if", "'hashes'", "not", "in", "datastream", ":", "continue", "for", "h", "in", "datastream", "[", "'hashes'", "]", ":", "if", "(", "len", "(", "h", ")", ">", "30", ")", ":", "yield", "JSONError", "(", "\"Object '%s' has an NTFS extension\"", "\" with an alternate data stream that has a\"", "\" 'hashes' dictionary with a hash of type \"", "\"'%s', which is longer than 30 \"", "\"characters.\"", "%", "(", "key", ",", "h", ")", ",", "instance", "[", "'id'", "]", ",", "'hash-algo'", ")", "try", ":", "head_hashes", "=", "obj", "[", "'extensions'", "]", "[", "'windows-pebinary-ext'", "]", "[", "'file_header_hashes'", "]", "except", "KeyError", ":", "pass", "else", ":", "for", "h", "in", "head_hashes", ":", "if", "(", "len", "(", "h", ")", ">", "30", ")", ":", "yield", "JSONError", "(", "\"Object '%s' has a Windows PE Binary \"", "\"File extension with a file header hash of \"", "\"'%s', which is longer than 30 \"", "\"characters.\"", "%", "(", "key", ",", "h", ")", ",", "instance", "[", "'id'", "]", ",", "'hash-algo'", ")", "try", ":", "hashes", "=", "obj", "[", "'extensions'", "]", "[", "'windows-pebinary-ext'", "]", "[", "'optional_header'", "]", "[", "'hashes'", "]", "except", "KeyError", ":", "pass", "else", ":", "for", "h", "in", "hashes", ":", "if", "(", "len", "(", "h", ")", ">", "30", ")", ":", "yield", "JSONError", "(", "\"Object '%s' has a Windows PE Binary \"", "\"File extension with an optional header that \"", "\"has a hash of '%s', which is longer \"", "\"than 30 characters.\"", "%", "(", "key", ",", "h", ")", ",", "instance", "[", "'id'", "]", ",", "'hash-algo'", ")", "try", ":", "sections", "=", "obj", "[", "'extensions'", "]", "[", "'windows-pebinary-ext'", "]", "[", "'sections'", "]", "except", "KeyError", ":", "pass", "else", ":", "for", "s", "in", "sections", ":", "if", "'hashes'", "not", "in", "s", ":", "continue", "for", "h", "in", "s", "[", "'hashes'", "]", ":", "if", "(", "len", "(", "h", ")", ">", "30", ")", ":", "yield", "JSONError", "(", "\"Object '%s' has a Windows PE \"", "\"Binary File extension with a section that\"", "\" has a hash of '%s', which is \"", "\"longer than 30 characters.\"", "%", "(", "key", ",", "h", ")", ",", "instance", "[", "'id'", "]", ",", "'hash-algo'", ")", "elif", "obj", "[", "'type'", "]", "==", "'artifact'", "or", "obj", "[", "'type'", "]", "==", "'x509-certificate'", ":", "try", ":", "hashes", "=", "obj", "[", "'hashes'", "]", "except", "KeyError", ":", "pass", "else", ":", "for", "h", "in", "hashes", ":", "if", "(", "len", "(", "h", ")", ">", "30", ")", ":", "yield", "JSONError", "(", "\"Object '%s' has a 'hashes' dictionary\"", "\" with a hash of type '%s', which is \"", "\"longer than 30 characters.\"", "%", "(", "key", ",", "h", ")", ",", "instance", "[", "'id'", "]", ",", "'hash-algo'", ")" ]
Ensure keys in 'hashes'-type properties are no more than 30 characters long.
[ "Ensure", "keys", "in", "hashes", "-", "type", "properties", "are", "no", "more", "than", "30", "characters", "long", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L926-L1016
train
oasis-open/cti-stix-validator
stix2validator/v21/shoulds.py
duplicate_ids
def duplicate_ids(instance): """Ensure objects with duplicate IDs have different `modified` timestamps. """ if instance['type'] != 'bundle' or 'objects' not in instance: return unique_ids = {} for obj in instance['objects']: if 'id' not in obj or 'modified' not in obj: continue elif obj['id'] not in unique_ids: unique_ids[obj['id']] = obj['modified'] elif obj['modified'] == unique_ids[obj['id']]: yield JSONError("Duplicate ID '%s' has identical `modified` timestamp." " If they are different versions of the same object, " "they should have different `modified` properties." % obj['id'], instance['id'], 'duplicate-ids')
python
def duplicate_ids(instance): """Ensure objects with duplicate IDs have different `modified` timestamps. """ if instance['type'] != 'bundle' or 'objects' not in instance: return unique_ids = {} for obj in instance['objects']: if 'id' not in obj or 'modified' not in obj: continue elif obj['id'] not in unique_ids: unique_ids[obj['id']] = obj['modified'] elif obj['modified'] == unique_ids[obj['id']]: yield JSONError("Duplicate ID '%s' has identical `modified` timestamp." " If they are different versions of the same object, " "they should have different `modified` properties." % obj['id'], instance['id'], 'duplicate-ids')
[ "def", "duplicate_ids", "(", "instance", ")", ":", "if", "instance", "[", "'type'", "]", "!=", "'bundle'", "or", "'objects'", "not", "in", "instance", ":", "return", "unique_ids", "=", "{", "}", "for", "obj", "in", "instance", "[", "'objects'", "]", ":", "if", "'id'", "not", "in", "obj", "or", "'modified'", "not", "in", "obj", ":", "continue", "elif", "obj", "[", "'id'", "]", "not", "in", "unique_ids", ":", "unique_ids", "[", "obj", "[", "'id'", "]", "]", "=", "obj", "[", "'modified'", "]", "elif", "obj", "[", "'modified'", "]", "==", "unique_ids", "[", "obj", "[", "'id'", "]", "]", ":", "yield", "JSONError", "(", "\"Duplicate ID '%s' has identical `modified` timestamp.\"", "\" If they are different versions of the same object, \"", "\"they should have different `modified` properties.\"", "%", "obj", "[", "'id'", "]", ",", "instance", "[", "'id'", "]", ",", "'duplicate-ids'", ")" ]
Ensure objects with duplicate IDs have different `modified` timestamps.
[ "Ensure", "objects", "with", "duplicate", "IDs", "have", "different", "modified", "timestamps", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L1028-L1044
train
oasis-open/cti-stix-validator
stix2validator/v21/shoulds.py
list_shoulds
def list_shoulds(options): """Construct the list of 'SHOULD' validators to be run by the validator. """ validator_list = [] # Default: enable all if not options.disabled and not options.enabled: validator_list.extend(CHECKS['all']) return validator_list # --disable # Add SHOULD requirements to the list unless disabled if options.disabled: if 'all' not in options.disabled: if 'format-checks' not in options.disabled: if 'custom-prefix' not in options.disabled: validator_list.append(CHECKS['custom-prefix']) elif 'custom-prefix-lax' not in options.disabled: validator_list.append(CHECKS['custom-prefix-lax']) if 'open-vocab-format' not in options.disabled: validator_list.append(CHECKS['open-vocab-format']) if 'kill-chain-names' not in options.disabled: validator_list.append(CHECKS['kill-chain-names']) if 'observable-object-keys' not in options.disabled: validator_list.append(CHECKS['observable-object-keys']) if 'observable-dictionary-keys' not in options.disabled: validator_list.append(CHECKS['observable-dictionary-keys']) if 'windows-process-priority-format' not in options.disabled: validator_list.append(CHECKS['windows-process-priority-format']) if 'hash-length' not in options.disabled: validator_list.append(CHECKS['hash-length']) if 'approved-values' not in options.disabled: if 'marking-definition-type' not in options.disabled: validator_list.append(CHECKS['marking-definition-type']) if 'relationship-types' not in options.disabled: validator_list.append(CHECKS['relationship-types']) if 'duplicate-ids' not in options.disabled: validator_list.append(CHECKS['duplicate-ids']) if 'all-vocabs' not in options.disabled: if 'attack-motivation' not in options.disabled: validator_list.append(CHECKS['attack-motivation']) if 'attack-resource-level' not in options.disabled: validator_list.append(CHECKS['attack-resource-level']) if 'identity-class' not in options.disabled: validator_list.append(CHECKS['identity-class']) if 'indicator-types' not in options.disabled: validator_list.append(CHECKS['indicator-types']) if 'industry-sector' not in options.disabled: validator_list.append(CHECKS['industry-sector']) if 'malware-types' not in options.disabled: validator_list.append(CHECKS['malware-types']) if 'report-types' not in options.disabled: validator_list.append(CHECKS['report-types']) if 'threat-actor-types' not in options.disabled: validator_list.append(CHECKS['threat-actor-types']) if 'threat-actor-role' not in options.disabled: validator_list.append(CHECKS['threat-actor-role']) if 'threat-actor-sophistication' not in options.disabled: validator_list.append(CHECKS['threat-actor-sophistication']) if 'tool-types' not in options.disabled: validator_list.append(CHECKS['tool-types']) if 'region' not in options.disabled: validator_list.append(CHECKS['region']) if 'hash-algo' not in options.disabled: validator_list.append(CHECKS['hash-algo']) if 'windows-pebinary-type' not in options.disabled: validator_list.append(CHECKS['windows-pebinary-type']) if 'account-type' not in options.disabled: validator_list.append(CHECKS['account-type']) if 'all-external-sources' not in options.disabled: if 'mime-type' not in options.disabled: validator_list.append(CHECKS['mime-type']) if 'protocols' not in options.disabled: validator_list.append(CHECKS['protocols']) if 'ipfix' not in options.disabled: validator_list.append(CHECKS['ipfix']) if 'http-request-headers' not in options.disabled: validator_list.append(CHECKS['http-request-headers']) if 'socket-options' not in options.disabled: validator_list.append(CHECKS['socket-options']) if 'pdf-doc-info' not in options.disabled: validator_list.append(CHECKS['pdf-doc-info']) if 'countries' not in options.disabled: validator_list.append(CHECKS['countries']) if 'network-traffic-ports' not in options.disabled: validator_list.append(CHECKS['network-traffic-ports']) if 'extref-hashes' not in options.disabled: validator_list.append(CHECKS['extref-hashes']) # --enable if options.enabled: for check in options.enabled: try: if CHECKS[check] in validator_list: continue if type(CHECKS[check]) is list: validator_list.extend(CHECKS[check]) else: validator_list.append(CHECKS[check]) except KeyError: raise JSONError("%s is not a valid check!" % check) return validator_list
python
def list_shoulds(options): """Construct the list of 'SHOULD' validators to be run by the validator. """ validator_list = [] # Default: enable all if not options.disabled and not options.enabled: validator_list.extend(CHECKS['all']) return validator_list # --disable # Add SHOULD requirements to the list unless disabled if options.disabled: if 'all' not in options.disabled: if 'format-checks' not in options.disabled: if 'custom-prefix' not in options.disabled: validator_list.append(CHECKS['custom-prefix']) elif 'custom-prefix-lax' not in options.disabled: validator_list.append(CHECKS['custom-prefix-lax']) if 'open-vocab-format' not in options.disabled: validator_list.append(CHECKS['open-vocab-format']) if 'kill-chain-names' not in options.disabled: validator_list.append(CHECKS['kill-chain-names']) if 'observable-object-keys' not in options.disabled: validator_list.append(CHECKS['observable-object-keys']) if 'observable-dictionary-keys' not in options.disabled: validator_list.append(CHECKS['observable-dictionary-keys']) if 'windows-process-priority-format' not in options.disabled: validator_list.append(CHECKS['windows-process-priority-format']) if 'hash-length' not in options.disabled: validator_list.append(CHECKS['hash-length']) if 'approved-values' not in options.disabled: if 'marking-definition-type' not in options.disabled: validator_list.append(CHECKS['marking-definition-type']) if 'relationship-types' not in options.disabled: validator_list.append(CHECKS['relationship-types']) if 'duplicate-ids' not in options.disabled: validator_list.append(CHECKS['duplicate-ids']) if 'all-vocabs' not in options.disabled: if 'attack-motivation' not in options.disabled: validator_list.append(CHECKS['attack-motivation']) if 'attack-resource-level' not in options.disabled: validator_list.append(CHECKS['attack-resource-level']) if 'identity-class' not in options.disabled: validator_list.append(CHECKS['identity-class']) if 'indicator-types' not in options.disabled: validator_list.append(CHECKS['indicator-types']) if 'industry-sector' not in options.disabled: validator_list.append(CHECKS['industry-sector']) if 'malware-types' not in options.disabled: validator_list.append(CHECKS['malware-types']) if 'report-types' not in options.disabled: validator_list.append(CHECKS['report-types']) if 'threat-actor-types' not in options.disabled: validator_list.append(CHECKS['threat-actor-types']) if 'threat-actor-role' not in options.disabled: validator_list.append(CHECKS['threat-actor-role']) if 'threat-actor-sophistication' not in options.disabled: validator_list.append(CHECKS['threat-actor-sophistication']) if 'tool-types' not in options.disabled: validator_list.append(CHECKS['tool-types']) if 'region' not in options.disabled: validator_list.append(CHECKS['region']) if 'hash-algo' not in options.disabled: validator_list.append(CHECKS['hash-algo']) if 'windows-pebinary-type' not in options.disabled: validator_list.append(CHECKS['windows-pebinary-type']) if 'account-type' not in options.disabled: validator_list.append(CHECKS['account-type']) if 'all-external-sources' not in options.disabled: if 'mime-type' not in options.disabled: validator_list.append(CHECKS['mime-type']) if 'protocols' not in options.disabled: validator_list.append(CHECKS['protocols']) if 'ipfix' not in options.disabled: validator_list.append(CHECKS['ipfix']) if 'http-request-headers' not in options.disabled: validator_list.append(CHECKS['http-request-headers']) if 'socket-options' not in options.disabled: validator_list.append(CHECKS['socket-options']) if 'pdf-doc-info' not in options.disabled: validator_list.append(CHECKS['pdf-doc-info']) if 'countries' not in options.disabled: validator_list.append(CHECKS['countries']) if 'network-traffic-ports' not in options.disabled: validator_list.append(CHECKS['network-traffic-ports']) if 'extref-hashes' not in options.disabled: validator_list.append(CHECKS['extref-hashes']) # --enable if options.enabled: for check in options.enabled: try: if CHECKS[check] in validator_list: continue if type(CHECKS[check]) is list: validator_list.extend(CHECKS[check]) else: validator_list.append(CHECKS[check]) except KeyError: raise JSONError("%s is not a valid check!" % check) return validator_list
[ "def", "list_shoulds", "(", "options", ")", ":", "validator_list", "=", "[", "]", "# Default: enable all", "if", "not", "options", ".", "disabled", "and", "not", "options", ".", "enabled", ":", "validator_list", ".", "extend", "(", "CHECKS", "[", "'all'", "]", ")", "return", "validator_list", "# --disable", "# Add SHOULD requirements to the list unless disabled", "if", "options", ".", "disabled", ":", "if", "'all'", "not", "in", "options", ".", "disabled", ":", "if", "'format-checks'", "not", "in", "options", ".", "disabled", ":", "if", "'custom-prefix'", "not", "in", "options", ".", "disabled", ":", "validator_list", ".", "append", "(", "CHECKS", "[", "'custom-prefix'", "]", ")", "elif", "'custom-prefix-lax'", "not", "in", "options", ".", "disabled", ":", "validator_list", ".", "append", "(", "CHECKS", "[", "'custom-prefix-lax'", "]", ")", "if", "'open-vocab-format'", "not", "in", "options", ".", "disabled", ":", "validator_list", ".", "append", "(", "CHECKS", "[", "'open-vocab-format'", "]", ")", "if", "'kill-chain-names'", "not", "in", "options", ".", "disabled", ":", "validator_list", ".", "append", "(", "CHECKS", "[", "'kill-chain-names'", "]", ")", "if", "'observable-object-keys'", "not", "in", "options", ".", "disabled", ":", "validator_list", ".", "append", "(", "CHECKS", "[", "'observable-object-keys'", "]", ")", "if", "'observable-dictionary-keys'", "not", "in", "options", ".", "disabled", ":", "validator_list", ".", "append", "(", "CHECKS", "[", "'observable-dictionary-keys'", "]", ")", "if", "'windows-process-priority-format'", "not", "in", "options", ".", "disabled", ":", "validator_list", ".", "append", "(", "CHECKS", "[", "'windows-process-priority-format'", "]", ")", "if", "'hash-length'", "not", "in", "options", ".", "disabled", ":", "validator_list", ".", "append", "(", "CHECKS", "[", "'hash-length'", "]", ")", "if", "'approved-values'", "not", "in", "options", ".", "disabled", ":", "if", "'marking-definition-type'", "not", "in", "options", ".", "disabled", ":", "validator_list", ".", "append", "(", "CHECKS", "[", "'marking-definition-type'", "]", ")", "if", "'relationship-types'", "not", "in", "options", ".", "disabled", ":", "validator_list", ".", "append", "(", "CHECKS", "[", "'relationship-types'", "]", ")", "if", "'duplicate-ids'", "not", "in", "options", ".", "disabled", ":", "validator_list", ".", "append", "(", "CHECKS", "[", "'duplicate-ids'", "]", ")", "if", "'all-vocabs'", "not", "in", "options", ".", "disabled", ":", "if", "'attack-motivation'", "not", "in", "options", ".", "disabled", ":", "validator_list", ".", "append", "(", "CHECKS", "[", "'attack-motivation'", "]", ")", "if", "'attack-resource-level'", "not", "in", "options", ".", "disabled", ":", "validator_list", ".", "append", "(", "CHECKS", "[", "'attack-resource-level'", "]", ")", "if", "'identity-class'", "not", "in", "options", ".", "disabled", ":", "validator_list", ".", "append", "(", "CHECKS", "[", "'identity-class'", "]", ")", "if", "'indicator-types'", "not", "in", "options", ".", "disabled", ":", "validator_list", ".", "append", "(", "CHECKS", "[", "'indicator-types'", "]", ")", "if", "'industry-sector'", "not", "in", "options", ".", "disabled", ":", "validator_list", ".", "append", "(", "CHECKS", "[", "'industry-sector'", "]", ")", "if", "'malware-types'", "not", "in", "options", ".", "disabled", ":", "validator_list", ".", "append", "(", "CHECKS", "[", "'malware-types'", "]", ")", "if", "'report-types'", "not", "in", "options", ".", "disabled", ":", "validator_list", ".", "append", "(", "CHECKS", "[", "'report-types'", "]", ")", "if", "'threat-actor-types'", "not", "in", "options", ".", "disabled", ":", "validator_list", ".", "append", "(", "CHECKS", "[", "'threat-actor-types'", "]", ")", "if", "'threat-actor-role'", "not", "in", "options", ".", "disabled", ":", "validator_list", ".", "append", "(", "CHECKS", "[", "'threat-actor-role'", "]", ")", "if", "'threat-actor-sophistication'", "not", "in", "options", ".", "disabled", ":", "validator_list", ".", "append", "(", "CHECKS", "[", "'threat-actor-sophistication'", "]", ")", "if", "'tool-types'", "not", "in", "options", ".", "disabled", ":", "validator_list", ".", "append", "(", "CHECKS", "[", "'tool-types'", "]", ")", "if", "'region'", "not", "in", "options", ".", "disabled", ":", "validator_list", ".", "append", "(", "CHECKS", "[", "'region'", "]", ")", "if", "'hash-algo'", "not", "in", "options", ".", "disabled", ":", "validator_list", ".", "append", "(", "CHECKS", "[", "'hash-algo'", "]", ")", "if", "'windows-pebinary-type'", "not", "in", "options", ".", "disabled", ":", "validator_list", ".", "append", "(", "CHECKS", "[", "'windows-pebinary-type'", "]", ")", "if", "'account-type'", "not", "in", "options", ".", "disabled", ":", "validator_list", ".", "append", "(", "CHECKS", "[", "'account-type'", "]", ")", "if", "'all-external-sources'", "not", "in", "options", ".", "disabled", ":", "if", "'mime-type'", "not", "in", "options", ".", "disabled", ":", "validator_list", ".", "append", "(", "CHECKS", "[", "'mime-type'", "]", ")", "if", "'protocols'", "not", "in", "options", ".", "disabled", ":", "validator_list", ".", "append", "(", "CHECKS", "[", "'protocols'", "]", ")", "if", "'ipfix'", "not", "in", "options", ".", "disabled", ":", "validator_list", ".", "append", "(", "CHECKS", "[", "'ipfix'", "]", ")", "if", "'http-request-headers'", "not", "in", "options", ".", "disabled", ":", "validator_list", ".", "append", "(", "CHECKS", "[", "'http-request-headers'", "]", ")", "if", "'socket-options'", "not", "in", "options", ".", "disabled", ":", "validator_list", ".", "append", "(", "CHECKS", "[", "'socket-options'", "]", ")", "if", "'pdf-doc-info'", "not", "in", "options", ".", "disabled", ":", "validator_list", ".", "append", "(", "CHECKS", "[", "'pdf-doc-info'", "]", ")", "if", "'countries'", "not", "in", "options", ".", "disabled", ":", "validator_list", ".", "append", "(", "CHECKS", "[", "'countries'", "]", ")", "if", "'network-traffic-ports'", "not", "in", "options", ".", "disabled", ":", "validator_list", ".", "append", "(", "CHECKS", "[", "'network-traffic-ports'", "]", ")", "if", "'extref-hashes'", "not", "in", "options", ".", "disabled", ":", "validator_list", ".", "append", "(", "CHECKS", "[", "'extref-hashes'", "]", ")", "# --enable", "if", "options", ".", "enabled", ":", "for", "check", "in", "options", ".", "enabled", ":", "try", ":", "if", "CHECKS", "[", "check", "]", "in", "validator_list", ":", "continue", "if", "type", "(", "CHECKS", "[", "check", "]", ")", "is", "list", ":", "validator_list", ".", "extend", "(", "CHECKS", "[", "check", "]", ")", "else", ":", "validator_list", ".", "append", "(", "CHECKS", "[", "check", "]", ")", "except", "KeyError", ":", "raise", "JSONError", "(", "\"%s is not a valid check!\"", "%", "check", ")", "return", "validator_list" ]
Construct the list of 'SHOULD' validators to be run by the validator.
[ "Construct", "the", "list", "of", "SHOULD", "validators", "to", "be", "run", "by", "the", "validator", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/shoulds.py#L1193-L1298
train
oasis-open/cti-stix-validator
stix2validator/v20/musts.py
timestamp
def timestamp(instance): """Ensure timestamps contain sane months, days, hours, minutes, seconds. """ ts_re = re.compile(r"^[0-9]{4}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60)(\.[0-9]+)?Z$") timestamp_props = ['created', 'modified'] if instance['type'] in enums.TIMESTAMP_PROPERTIES: timestamp_props += enums.TIMESTAMP_PROPERTIES[instance['type']] for tprop in timestamp_props: if tprop in instance and ts_re.match(instance[tprop]): # Don't raise an error if schemas will catch it try: parser.parse(instance[tprop]) except ValueError as e: yield JSONError("'%s': '%s' is not a valid timestamp: %s" % (tprop, instance[tprop], str(e)), instance['id']) if has_cyber_observable_data(instance): for key, obj in instance['objects'].items(): if 'type' not in obj: continue if obj['type'] in enums.TIMESTAMP_OBSERVABLE_PROPERTIES: for tprop in enums.TIMESTAMP_OBSERVABLE_PROPERTIES[obj['type']]: if tprop in obj and ts_re.match(obj[tprop]): # Don't raise an error if schemas will catch it try: parser.parse(obj[tprop]) except ValueError as e: yield JSONError("'%s': '%s': '%s' is not a valid timestamp: %s" % (obj['type'], tprop, obj[tprop], str(e)), instance['id']) if obj['type'] in enums.TIMESTAMP_EMBEDDED_PROPERTIES: for embed in enums.TIMESTAMP_EMBEDDED_PROPERTIES[obj['type']]: if embed in obj: for tprop in enums.TIMESTAMP_EMBEDDED_PROPERTIES[obj['type']][embed]: if embed == 'extensions': for ext in obj[embed]: if tprop in obj[embed][ext] and ts_re.match(obj[embed][ext][tprop]): try: parser.parse(obj[embed][ext][tprop]) except ValueError as e: yield JSONError("'%s': '%s': '%s': '%s' is not a valid timestamp: %s" % (obj['type'], ext, tprop, obj[embed][ext][tprop], str(e)), instance['id']) elif tprop in obj[embed] and ts_re.match(obj[embed][tprop]): try: parser.parse(obj[embed][tprop]) except ValueError as e: yield JSONError("'%s': '%s': '%s' is not a valid timestamp: %s" % (obj['type'], tprop, obj[embed][tprop], str(e)), instance['id'])
python
def timestamp(instance): """Ensure timestamps contain sane months, days, hours, minutes, seconds. """ ts_re = re.compile(r"^[0-9]{4}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60)(\.[0-9]+)?Z$") timestamp_props = ['created', 'modified'] if instance['type'] in enums.TIMESTAMP_PROPERTIES: timestamp_props += enums.TIMESTAMP_PROPERTIES[instance['type']] for tprop in timestamp_props: if tprop in instance and ts_re.match(instance[tprop]): # Don't raise an error if schemas will catch it try: parser.parse(instance[tprop]) except ValueError as e: yield JSONError("'%s': '%s' is not a valid timestamp: %s" % (tprop, instance[tprop], str(e)), instance['id']) if has_cyber_observable_data(instance): for key, obj in instance['objects'].items(): if 'type' not in obj: continue if obj['type'] in enums.TIMESTAMP_OBSERVABLE_PROPERTIES: for tprop in enums.TIMESTAMP_OBSERVABLE_PROPERTIES[obj['type']]: if tprop in obj and ts_re.match(obj[tprop]): # Don't raise an error if schemas will catch it try: parser.parse(obj[tprop]) except ValueError as e: yield JSONError("'%s': '%s': '%s' is not a valid timestamp: %s" % (obj['type'], tprop, obj[tprop], str(e)), instance['id']) if obj['type'] in enums.TIMESTAMP_EMBEDDED_PROPERTIES: for embed in enums.TIMESTAMP_EMBEDDED_PROPERTIES[obj['type']]: if embed in obj: for tprop in enums.TIMESTAMP_EMBEDDED_PROPERTIES[obj['type']][embed]: if embed == 'extensions': for ext in obj[embed]: if tprop in obj[embed][ext] and ts_re.match(obj[embed][ext][tprop]): try: parser.parse(obj[embed][ext][tprop]) except ValueError as e: yield JSONError("'%s': '%s': '%s': '%s' is not a valid timestamp: %s" % (obj['type'], ext, tprop, obj[embed][ext][tprop], str(e)), instance['id']) elif tprop in obj[embed] and ts_re.match(obj[embed][tprop]): try: parser.parse(obj[embed][tprop]) except ValueError as e: yield JSONError("'%s': '%s': '%s' is not a valid timestamp: %s" % (obj['type'], tprop, obj[embed][tprop], str(e)), instance['id'])
[ "def", "timestamp", "(", "instance", ")", ":", "ts_re", "=", "re", ".", "compile", "(", "r\"^[0-9]{4}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60)(\\.[0-9]+)?Z$\"", ")", "timestamp_props", "=", "[", "'created'", ",", "'modified'", "]", "if", "instance", "[", "'type'", "]", "in", "enums", ".", "TIMESTAMP_PROPERTIES", ":", "timestamp_props", "+=", "enums", ".", "TIMESTAMP_PROPERTIES", "[", "instance", "[", "'type'", "]", "]", "for", "tprop", "in", "timestamp_props", ":", "if", "tprop", "in", "instance", "and", "ts_re", ".", "match", "(", "instance", "[", "tprop", "]", ")", ":", "# Don't raise an error if schemas will catch it", "try", ":", "parser", ".", "parse", "(", "instance", "[", "tprop", "]", ")", "except", "ValueError", "as", "e", ":", "yield", "JSONError", "(", "\"'%s': '%s' is not a valid timestamp: %s\"", "%", "(", "tprop", ",", "instance", "[", "tprop", "]", ",", "str", "(", "e", ")", ")", ",", "instance", "[", "'id'", "]", ")", "if", "has_cyber_observable_data", "(", "instance", ")", ":", "for", "key", ",", "obj", "in", "instance", "[", "'objects'", "]", ".", "items", "(", ")", ":", "if", "'type'", "not", "in", "obj", ":", "continue", "if", "obj", "[", "'type'", "]", "in", "enums", ".", "TIMESTAMP_OBSERVABLE_PROPERTIES", ":", "for", "tprop", "in", "enums", ".", "TIMESTAMP_OBSERVABLE_PROPERTIES", "[", "obj", "[", "'type'", "]", "]", ":", "if", "tprop", "in", "obj", "and", "ts_re", ".", "match", "(", "obj", "[", "tprop", "]", ")", ":", "# Don't raise an error if schemas will catch it", "try", ":", "parser", ".", "parse", "(", "obj", "[", "tprop", "]", ")", "except", "ValueError", "as", "e", ":", "yield", "JSONError", "(", "\"'%s': '%s': '%s' is not a valid timestamp: %s\"", "%", "(", "obj", "[", "'type'", "]", ",", "tprop", ",", "obj", "[", "tprop", "]", ",", "str", "(", "e", ")", ")", ",", "instance", "[", "'id'", "]", ")", "if", "obj", "[", "'type'", "]", "in", "enums", ".", "TIMESTAMP_EMBEDDED_PROPERTIES", ":", "for", "embed", "in", "enums", ".", "TIMESTAMP_EMBEDDED_PROPERTIES", "[", "obj", "[", "'type'", "]", "]", ":", "if", "embed", "in", "obj", ":", "for", "tprop", "in", "enums", ".", "TIMESTAMP_EMBEDDED_PROPERTIES", "[", "obj", "[", "'type'", "]", "]", "[", "embed", "]", ":", "if", "embed", "==", "'extensions'", ":", "for", "ext", "in", "obj", "[", "embed", "]", ":", "if", "tprop", "in", "obj", "[", "embed", "]", "[", "ext", "]", "and", "ts_re", ".", "match", "(", "obj", "[", "embed", "]", "[", "ext", "]", "[", "tprop", "]", ")", ":", "try", ":", "parser", ".", "parse", "(", "obj", "[", "embed", "]", "[", "ext", "]", "[", "tprop", "]", ")", "except", "ValueError", "as", "e", ":", "yield", "JSONError", "(", "\"'%s': '%s': '%s': '%s' is not a valid timestamp: %s\"", "%", "(", "obj", "[", "'type'", "]", ",", "ext", ",", "tprop", ",", "obj", "[", "embed", "]", "[", "ext", "]", "[", "tprop", "]", ",", "str", "(", "e", ")", ")", ",", "instance", "[", "'id'", "]", ")", "elif", "tprop", "in", "obj", "[", "embed", "]", "and", "ts_re", ".", "match", "(", "obj", "[", "embed", "]", "[", "tprop", "]", ")", ":", "try", ":", "parser", ".", "parse", "(", "obj", "[", "embed", "]", "[", "tprop", "]", ")", "except", "ValueError", "as", "e", ":", "yield", "JSONError", "(", "\"'%s': '%s': '%s' is not a valid timestamp: %s\"", "%", "(", "obj", "[", "'type'", "]", ",", "tprop", ",", "obj", "[", "embed", "]", "[", "tprop", "]", ",", "str", "(", "e", ")", ")", ",", "instance", "[", "'id'", "]", ")" ]
Ensure timestamps contain sane months, days, hours, minutes, seconds.
[ "Ensure", "timestamps", "contain", "sane", "months", "days", "hours", "minutes", "seconds", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v20/musts.py#L23-L70
train
oasis-open/cti-stix-validator
stix2validator/v20/musts.py
modified_created
def modified_created(instance): """`modified` property must be later or equal to `created` property """ if 'modified' in instance and 'created' in instance and \ instance['modified'] < instance['created']: msg = "'modified' (%s) must be later or equal to 'created' (%s)" return JSONError(msg % (instance['modified'], instance['created']), instance['id'])
python
def modified_created(instance): """`modified` property must be later or equal to `created` property """ if 'modified' in instance and 'created' in instance and \ instance['modified'] < instance['created']: msg = "'modified' (%s) must be later or equal to 'created' (%s)" return JSONError(msg % (instance['modified'], instance['created']), instance['id'])
[ "def", "modified_created", "(", "instance", ")", ":", "if", "'modified'", "in", "instance", "and", "'created'", "in", "instance", "and", "instance", "[", "'modified'", "]", "<", "instance", "[", "'created'", "]", ":", "msg", "=", "\"'modified' (%s) must be later or equal to 'created' (%s)\"", "return", "JSONError", "(", "msg", "%", "(", "instance", "[", "'modified'", "]", ",", "instance", "[", "'created'", "]", ")", ",", "instance", "[", "'id'", "]", ")" ]
`modified` property must be later or equal to `created` property
[ "modified", "property", "must", "be", "later", "or", "equal", "to", "created", "property" ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v20/musts.py#L73-L80
train
oasis-open/cti-stix-validator
stix2validator/v20/musts.py
object_marking_circular_refs
def object_marking_circular_refs(instance): """Ensure that marking definitions do not contain circular references (ie. they do not reference themselves in the `object_marking_refs` property). """ if instance['type'] != 'marking-definition': return if 'object_marking_refs' in instance: for ref in instance['object_marking_refs']: if ref == instance['id']: yield JSONError("`object_marking_refs` cannot contain any " "references to this marking definition object" " (no circular references).", instance['id'])
python
def object_marking_circular_refs(instance): """Ensure that marking definitions do not contain circular references (ie. they do not reference themselves in the `object_marking_refs` property). """ if instance['type'] != 'marking-definition': return if 'object_marking_refs' in instance: for ref in instance['object_marking_refs']: if ref == instance['id']: yield JSONError("`object_marking_refs` cannot contain any " "references to this marking definition object" " (no circular references).", instance['id'])
[ "def", "object_marking_circular_refs", "(", "instance", ")", ":", "if", "instance", "[", "'type'", "]", "!=", "'marking-definition'", ":", "return", "if", "'object_marking_refs'", "in", "instance", ":", "for", "ref", "in", "instance", "[", "'object_marking_refs'", "]", ":", "if", "ref", "==", "instance", "[", "'id'", "]", ":", "yield", "JSONError", "(", "\"`object_marking_refs` cannot contain any \"", "\"references to this marking definition object\"", "\" (no circular references).\"", ",", "instance", "[", "'id'", "]", ")" ]
Ensure that marking definitions do not contain circular references (ie. they do not reference themselves in the `object_marking_refs` property).
[ "Ensure", "that", "marking", "definitions", "do", "not", "contain", "circular", "references", "(", "ie", ".", "they", "do", "not", "reference", "themselves", "in", "the", "object_marking_refs", "property", ")", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v20/musts.py#L83-L95
train
oasis-open/cti-stix-validator
stix2validator/v20/musts.py
granular_markings_circular_refs
def granular_markings_circular_refs(instance): """Ensure that marking definitions do not contain circular references (ie. they do not reference themselves in the `granular_markings` property). """ if instance['type'] != 'marking-definition': return if 'granular_markings' in instance: for marking in instance['granular_markings']: if 'marking_ref' in marking and marking['marking_ref'] == instance['id']: yield JSONError("`granular_markings` cannot contain any " "references to this marking definition object" " (no circular references).", instance['id'])
python
def granular_markings_circular_refs(instance): """Ensure that marking definitions do not contain circular references (ie. they do not reference themselves in the `granular_markings` property). """ if instance['type'] != 'marking-definition': return if 'granular_markings' in instance: for marking in instance['granular_markings']: if 'marking_ref' in marking and marking['marking_ref'] == instance['id']: yield JSONError("`granular_markings` cannot contain any " "references to this marking definition object" " (no circular references).", instance['id'])
[ "def", "granular_markings_circular_refs", "(", "instance", ")", ":", "if", "instance", "[", "'type'", "]", "!=", "'marking-definition'", ":", "return", "if", "'granular_markings'", "in", "instance", ":", "for", "marking", "in", "instance", "[", "'granular_markings'", "]", ":", "if", "'marking_ref'", "in", "marking", "and", "marking", "[", "'marking_ref'", "]", "==", "instance", "[", "'id'", "]", ":", "yield", "JSONError", "(", "\"`granular_markings` cannot contain any \"", "\"references to this marking definition object\"", "\" (no circular references).\"", ",", "instance", "[", "'id'", "]", ")" ]
Ensure that marking definitions do not contain circular references (ie. they do not reference themselves in the `granular_markings` property).
[ "Ensure", "that", "marking", "definitions", "do", "not", "contain", "circular", "references", "(", "ie", ".", "they", "do", "not", "reference", "themselves", "in", "the", "granular_markings", "property", ")", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v20/musts.py#L98-L110
train
oasis-open/cti-stix-validator
stix2validator/v20/musts.py
marking_selector_syntax
def marking_selector_syntax(instance): """Ensure selectors in granular markings refer to items which are actually present in the object. """ if 'granular_markings' not in instance: return list_index_re = re.compile(r"\[(\d+)\]") for marking in instance['granular_markings']: if 'selectors' not in marking: continue selectors = marking['selectors'] for selector in selectors: segments = selector.split('.') obj = instance prev_segmt = None for segmt in segments: index_match = list_index_re.match(segmt) if index_match: try: idx = int(index_match.group(1)) obj = obj[idx] except IndexError: yield JSONError("'%s' is not a valid selector because" " %s is not a valid index." % (selector, idx), instance['id']) except KeyError: yield JSONError("'%s' is not a valid selector because" " '%s' is not a list." % (selector, prev_segmt), instance['id']) else: try: obj = obj[segmt] except KeyError as e: yield JSONError("'%s' is not a valid selector because" " %s is not a property." % (selector, e), instance['id']) except TypeError: yield JSONError("'%s' is not a valid selector because" " '%s' is not a property." % (selector, segmt), instance['id']) prev_segmt = segmt
python
def marking_selector_syntax(instance): """Ensure selectors in granular markings refer to items which are actually present in the object. """ if 'granular_markings' not in instance: return list_index_re = re.compile(r"\[(\d+)\]") for marking in instance['granular_markings']: if 'selectors' not in marking: continue selectors = marking['selectors'] for selector in selectors: segments = selector.split('.') obj = instance prev_segmt = None for segmt in segments: index_match = list_index_re.match(segmt) if index_match: try: idx = int(index_match.group(1)) obj = obj[idx] except IndexError: yield JSONError("'%s' is not a valid selector because" " %s is not a valid index." % (selector, idx), instance['id']) except KeyError: yield JSONError("'%s' is not a valid selector because" " '%s' is not a list." % (selector, prev_segmt), instance['id']) else: try: obj = obj[segmt] except KeyError as e: yield JSONError("'%s' is not a valid selector because" " %s is not a property." % (selector, e), instance['id']) except TypeError: yield JSONError("'%s' is not a valid selector because" " '%s' is not a property." % (selector, segmt), instance['id']) prev_segmt = segmt
[ "def", "marking_selector_syntax", "(", "instance", ")", ":", "if", "'granular_markings'", "not", "in", "instance", ":", "return", "list_index_re", "=", "re", ".", "compile", "(", "r\"\\[(\\d+)\\]\"", ")", "for", "marking", "in", "instance", "[", "'granular_markings'", "]", ":", "if", "'selectors'", "not", "in", "marking", ":", "continue", "selectors", "=", "marking", "[", "'selectors'", "]", "for", "selector", "in", "selectors", ":", "segments", "=", "selector", ".", "split", "(", "'.'", ")", "obj", "=", "instance", "prev_segmt", "=", "None", "for", "segmt", "in", "segments", ":", "index_match", "=", "list_index_re", ".", "match", "(", "segmt", ")", "if", "index_match", ":", "try", ":", "idx", "=", "int", "(", "index_match", ".", "group", "(", "1", ")", ")", "obj", "=", "obj", "[", "idx", "]", "except", "IndexError", ":", "yield", "JSONError", "(", "\"'%s' is not a valid selector because\"", "\" %s is not a valid index.\"", "%", "(", "selector", ",", "idx", ")", ",", "instance", "[", "'id'", "]", ")", "except", "KeyError", ":", "yield", "JSONError", "(", "\"'%s' is not a valid selector because\"", "\" '%s' is not a list.\"", "%", "(", "selector", ",", "prev_segmt", ")", ",", "instance", "[", "'id'", "]", ")", "else", ":", "try", ":", "obj", "=", "obj", "[", "segmt", "]", "except", "KeyError", "as", "e", ":", "yield", "JSONError", "(", "\"'%s' is not a valid selector because\"", "\" %s is not a property.\"", "%", "(", "selector", ",", "e", ")", ",", "instance", "[", "'id'", "]", ")", "except", "TypeError", ":", "yield", "JSONError", "(", "\"'%s' is not a valid selector because\"", "\" '%s' is not a property.\"", "%", "(", "selector", ",", "segmt", ")", ",", "instance", "[", "'id'", "]", ")", "prev_segmt", "=", "segmt" ]
Ensure selectors in granular markings refer to items which are actually present in the object.
[ "Ensure", "selectors", "in", "granular", "markings", "refer", "to", "items", "which", "are", "actually", "present", "in", "the", "object", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v20/musts.py#L113-L156
train
oasis-open/cti-stix-validator
stix2validator/v20/musts.py
observable_object_references
def observable_object_references(instance): """Ensure certain observable object properties reference the correct type of object. """ for key, obj in instance['objects'].items(): if 'type' not in obj: continue elif obj['type'] not in enums.OBSERVABLE_PROP_REFS: continue obj_type = obj['type'] for obj_prop in enums.OBSERVABLE_PROP_REFS[obj_type]: if obj_prop not in obj: continue enum_prop = enums.OBSERVABLE_PROP_REFS[obj_type][obj_prop] if isinstance(enum_prop, list): refs = obj[obj_prop] enum_vals = enum_prop for x in check_observable_refs(refs, obj_prop, enum_prop, '', enum_vals, key, instance): yield x elif isinstance(enum_prop, dict): for embedded_prop in enum_prop: if isinstance(obj[obj_prop], dict): if embedded_prop not in obj[obj_prop]: continue embedded_obj = obj[obj_prop][embedded_prop] for embed_obj_prop in embedded_obj: if embed_obj_prop not in enum_prop[embedded_prop]: continue refs = embedded_obj[embed_obj_prop] enum_vals = enum_prop[embedded_prop][embed_obj_prop] for x in check_observable_refs(refs, obj_prop, enum_prop, embed_obj_prop, enum_vals, key, instance): yield x elif isinstance(obj[obj_prop], list): for embedded_list_obj in obj[obj_prop]: if embedded_prop not in embedded_list_obj: continue embedded_obj = embedded_list_obj[embedded_prop] refs = embedded_obj enum_vals = enum_prop[embedded_prop] for x in check_observable_refs(refs, obj_prop, enum_prop, embedded_prop, enum_vals, key, instance): yield x
python
def observable_object_references(instance): """Ensure certain observable object properties reference the correct type of object. """ for key, obj in instance['objects'].items(): if 'type' not in obj: continue elif obj['type'] not in enums.OBSERVABLE_PROP_REFS: continue obj_type = obj['type'] for obj_prop in enums.OBSERVABLE_PROP_REFS[obj_type]: if obj_prop not in obj: continue enum_prop = enums.OBSERVABLE_PROP_REFS[obj_type][obj_prop] if isinstance(enum_prop, list): refs = obj[obj_prop] enum_vals = enum_prop for x in check_observable_refs(refs, obj_prop, enum_prop, '', enum_vals, key, instance): yield x elif isinstance(enum_prop, dict): for embedded_prop in enum_prop: if isinstance(obj[obj_prop], dict): if embedded_prop not in obj[obj_prop]: continue embedded_obj = obj[obj_prop][embedded_prop] for embed_obj_prop in embedded_obj: if embed_obj_prop not in enum_prop[embedded_prop]: continue refs = embedded_obj[embed_obj_prop] enum_vals = enum_prop[embedded_prop][embed_obj_prop] for x in check_observable_refs(refs, obj_prop, enum_prop, embed_obj_prop, enum_vals, key, instance): yield x elif isinstance(obj[obj_prop], list): for embedded_list_obj in obj[obj_prop]: if embedded_prop not in embedded_list_obj: continue embedded_obj = embedded_list_obj[embedded_prop] refs = embedded_obj enum_vals = enum_prop[embedded_prop] for x in check_observable_refs(refs, obj_prop, enum_prop, embedded_prop, enum_vals, key, instance): yield x
[ "def", "observable_object_references", "(", "instance", ")", ":", "for", "key", ",", "obj", "in", "instance", "[", "'objects'", "]", ".", "items", "(", ")", ":", "if", "'type'", "not", "in", "obj", ":", "continue", "elif", "obj", "[", "'type'", "]", "not", "in", "enums", ".", "OBSERVABLE_PROP_REFS", ":", "continue", "obj_type", "=", "obj", "[", "'type'", "]", "for", "obj_prop", "in", "enums", ".", "OBSERVABLE_PROP_REFS", "[", "obj_type", "]", ":", "if", "obj_prop", "not", "in", "obj", ":", "continue", "enum_prop", "=", "enums", ".", "OBSERVABLE_PROP_REFS", "[", "obj_type", "]", "[", "obj_prop", "]", "if", "isinstance", "(", "enum_prop", ",", "list", ")", ":", "refs", "=", "obj", "[", "obj_prop", "]", "enum_vals", "=", "enum_prop", "for", "x", "in", "check_observable_refs", "(", "refs", ",", "obj_prop", ",", "enum_prop", ",", "''", ",", "enum_vals", ",", "key", ",", "instance", ")", ":", "yield", "x", "elif", "isinstance", "(", "enum_prop", ",", "dict", ")", ":", "for", "embedded_prop", "in", "enum_prop", ":", "if", "isinstance", "(", "obj", "[", "obj_prop", "]", ",", "dict", ")", ":", "if", "embedded_prop", "not", "in", "obj", "[", "obj_prop", "]", ":", "continue", "embedded_obj", "=", "obj", "[", "obj_prop", "]", "[", "embedded_prop", "]", "for", "embed_obj_prop", "in", "embedded_obj", ":", "if", "embed_obj_prop", "not", "in", "enum_prop", "[", "embedded_prop", "]", ":", "continue", "refs", "=", "embedded_obj", "[", "embed_obj_prop", "]", "enum_vals", "=", "enum_prop", "[", "embedded_prop", "]", "[", "embed_obj_prop", "]", "for", "x", "in", "check_observable_refs", "(", "refs", ",", "obj_prop", ",", "enum_prop", ",", "embed_obj_prop", ",", "enum_vals", ",", "key", ",", "instance", ")", ":", "yield", "x", "elif", "isinstance", "(", "obj", "[", "obj_prop", "]", ",", "list", ")", ":", "for", "embedded_list_obj", "in", "obj", "[", "obj_prop", "]", ":", "if", "embedded_prop", "not", "in", "embedded_list_obj", ":", "continue", "embedded_obj", "=", "embedded_list_obj", "[", "embedded_prop", "]", "refs", "=", "embedded_obj", "enum_vals", "=", "enum_prop", "[", "embedded_prop", "]", "for", "x", "in", "check_observable_refs", "(", "refs", ",", "obj_prop", ",", "enum_prop", ",", "embedded_prop", ",", "enum_vals", ",", "key", ",", "instance", ")", ":", "yield", "x" ]
Ensure certain observable object properties reference the correct type of object.
[ "Ensure", "certain", "observable", "object", "properties", "reference", "the", "correct", "type", "of", "object", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v20/musts.py#L191-L240
train
oasis-open/cti-stix-validator
stix2validator/v20/musts.py
artifact_mime_type
def artifact_mime_type(instance): """Ensure the 'mime_type' property of artifact objects comes from the Template column in the IANA media type registry. """ for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'artifact' and 'mime_type' in obj): if enums.media_types(): if obj['mime_type'] not in enums.media_types(): yield JSONError("The 'mime_type' property of object '%s' " "('%s') must be an IANA registered MIME " "Type of the form 'type/subtype'." % (key, obj['mime_type']), instance['id']) else: info("Can't reach IANA website; using regex for mime types.") mime_re = re.compile(r'^(application|audio|font|image|message|model' '|multipart|text|video)/[a-zA-Z0-9.+_-]+') if not mime_re.match(obj['mime_type']): yield JSONError("The 'mime_type' property of object '%s' " "('%s') should be an IANA MIME Type of the" " form 'type/subtype'." % (key, obj['mime_type']), instance['id'])
python
def artifact_mime_type(instance): """Ensure the 'mime_type' property of artifact objects comes from the Template column in the IANA media type registry. """ for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'artifact' and 'mime_type' in obj): if enums.media_types(): if obj['mime_type'] not in enums.media_types(): yield JSONError("The 'mime_type' property of object '%s' " "('%s') must be an IANA registered MIME " "Type of the form 'type/subtype'." % (key, obj['mime_type']), instance['id']) else: info("Can't reach IANA website; using regex for mime types.") mime_re = re.compile(r'^(application|audio|font|image|message|model' '|multipart|text|video)/[a-zA-Z0-9.+_-]+') if not mime_re.match(obj['mime_type']): yield JSONError("The 'mime_type' property of object '%s' " "('%s') should be an IANA MIME Type of the" " form 'type/subtype'." % (key, obj['mime_type']), instance['id'])
[ "def", "artifact_mime_type", "(", "instance", ")", ":", "for", "key", ",", "obj", "in", "instance", "[", "'objects'", "]", ".", "items", "(", ")", ":", "if", "(", "'type'", "in", "obj", "and", "obj", "[", "'type'", "]", "==", "'artifact'", "and", "'mime_type'", "in", "obj", ")", ":", "if", "enums", ".", "media_types", "(", ")", ":", "if", "obj", "[", "'mime_type'", "]", "not", "in", "enums", ".", "media_types", "(", ")", ":", "yield", "JSONError", "(", "\"The 'mime_type' property of object '%s' \"", "\"('%s') must be an IANA registered MIME \"", "\"Type of the form 'type/subtype'.\"", "%", "(", "key", ",", "obj", "[", "'mime_type'", "]", ")", ",", "instance", "[", "'id'", "]", ")", "else", ":", "info", "(", "\"Can't reach IANA website; using regex for mime types.\"", ")", "mime_re", "=", "re", ".", "compile", "(", "r'^(application|audio|font|image|message|model'", "'|multipart|text|video)/[a-zA-Z0-9.+_-]+'", ")", "if", "not", "mime_re", ".", "match", "(", "obj", "[", "'mime_type'", "]", ")", ":", "yield", "JSONError", "(", "\"The 'mime_type' property of object '%s' \"", "\"('%s') should be an IANA MIME Type of the\"", "\" form 'type/subtype'.\"", "%", "(", "key", ",", "obj", "[", "'mime_type'", "]", ")", ",", "instance", "[", "'id'", "]", ")" ]
Ensure the 'mime_type' property of artifact objects comes from the Template column in the IANA media type registry.
[ "Ensure", "the", "mime_type", "property", "of", "artifact", "objects", "comes", "from", "the", "Template", "column", "in", "the", "IANA", "media", "type", "registry", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v20/musts.py#L244-L265
train
oasis-open/cti-stix-validator
stix2validator/v20/musts.py
character_set
def character_set(instance): """Ensure certain properties of cyber observable objects come from the IANA Character Set list. """ char_re = re.compile(r'^[a-zA-Z0-9_\(\)-]+$') for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'directory' and 'path_enc' in obj): if enums.char_sets(): if obj['path_enc'] not in enums.char_sets(): yield JSONError("The 'path_enc' property of object '%s' " "('%s') must be an IANA registered " "character set." % (key, obj['path_enc']), instance['id']) else: info("Can't reach IANA website; using regex for character_set.") if not char_re.match(obj['path_enc']): yield JSONError("The 'path_enc' property of object '%s' " "('%s') must be an IANA registered " "character set." % (key, obj['path_enc']), instance['id']) if ('type' in obj and obj['type'] == 'file' and 'name_enc' in obj): if enums.char_sets(): if obj['name_enc'] not in enums.char_sets(): yield JSONError("The 'name_enc' property of object '%s' " "('%s') must be an IANA registered " "character set." % (key, obj['name_enc']), instance['id']) else: info("Can't reach IANA website; using regex for character_set.") if not char_re.match(obj['name_enc']): yield JSONError("The 'name_enc' property of object '%s' " "('%s') must be an IANA registered " "character set." % (key, obj['name_enc']), instance['id'])
python
def character_set(instance): """Ensure certain properties of cyber observable objects come from the IANA Character Set list. """ char_re = re.compile(r'^[a-zA-Z0-9_\(\)-]+$') for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'directory' and 'path_enc' in obj): if enums.char_sets(): if obj['path_enc'] not in enums.char_sets(): yield JSONError("The 'path_enc' property of object '%s' " "('%s') must be an IANA registered " "character set." % (key, obj['path_enc']), instance['id']) else: info("Can't reach IANA website; using regex for character_set.") if not char_re.match(obj['path_enc']): yield JSONError("The 'path_enc' property of object '%s' " "('%s') must be an IANA registered " "character set." % (key, obj['path_enc']), instance['id']) if ('type' in obj and obj['type'] == 'file' and 'name_enc' in obj): if enums.char_sets(): if obj['name_enc'] not in enums.char_sets(): yield JSONError("The 'name_enc' property of object '%s' " "('%s') must be an IANA registered " "character set." % (key, obj['name_enc']), instance['id']) else: info("Can't reach IANA website; using regex for character_set.") if not char_re.match(obj['name_enc']): yield JSONError("The 'name_enc' property of object '%s' " "('%s') must be an IANA registered " "character set." % (key, obj['name_enc']), instance['id'])
[ "def", "character_set", "(", "instance", ")", ":", "char_re", "=", "re", ".", "compile", "(", "r'^[a-zA-Z0-9_\\(\\)-]+$'", ")", "for", "key", ",", "obj", "in", "instance", "[", "'objects'", "]", ".", "items", "(", ")", ":", "if", "(", "'type'", "in", "obj", "and", "obj", "[", "'type'", "]", "==", "'directory'", "and", "'path_enc'", "in", "obj", ")", ":", "if", "enums", ".", "char_sets", "(", ")", ":", "if", "obj", "[", "'path_enc'", "]", "not", "in", "enums", ".", "char_sets", "(", ")", ":", "yield", "JSONError", "(", "\"The 'path_enc' property of object '%s' \"", "\"('%s') must be an IANA registered \"", "\"character set.\"", "%", "(", "key", ",", "obj", "[", "'path_enc'", "]", ")", ",", "instance", "[", "'id'", "]", ")", "else", ":", "info", "(", "\"Can't reach IANA website; using regex for character_set.\"", ")", "if", "not", "char_re", ".", "match", "(", "obj", "[", "'path_enc'", "]", ")", ":", "yield", "JSONError", "(", "\"The 'path_enc' property of object '%s' \"", "\"('%s') must be an IANA registered \"", "\"character set.\"", "%", "(", "key", ",", "obj", "[", "'path_enc'", "]", ")", ",", "instance", "[", "'id'", "]", ")", "if", "(", "'type'", "in", "obj", "and", "obj", "[", "'type'", "]", "==", "'file'", "and", "'name_enc'", "in", "obj", ")", ":", "if", "enums", ".", "char_sets", "(", ")", ":", "if", "obj", "[", "'name_enc'", "]", "not", "in", "enums", ".", "char_sets", "(", ")", ":", "yield", "JSONError", "(", "\"The 'name_enc' property of object '%s' \"", "\"('%s') must be an IANA registered \"", "\"character set.\"", "%", "(", "key", ",", "obj", "[", "'name_enc'", "]", ")", ",", "instance", "[", "'id'", "]", ")", "else", ":", "info", "(", "\"Can't reach IANA website; using regex for character_set.\"", ")", "if", "not", "char_re", ".", "match", "(", "obj", "[", "'name_enc'", "]", ")", ":", "yield", "JSONError", "(", "\"The 'name_enc' property of object '%s' \"", "\"('%s') must be an IANA registered \"", "\"character set.\"", "%", "(", "key", ",", "obj", "[", "'name_enc'", "]", ")", ",", "instance", "[", "'id'", "]", ")" ]
Ensure certain properties of cyber observable objects come from the IANA Character Set list.
[ "Ensure", "certain", "properties", "of", "cyber", "observable", "objects", "come", "from", "the", "IANA", "Character", "Set", "list", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v20/musts.py#L269-L303
train
oasis-open/cti-stix-validator
stix2validator/v20/musts.py
software_language
def software_language(instance): """Ensure the 'language' property of software objects is a valid ISO 639-2 language code. """ for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'software' and 'languages' in obj): for lang in obj['languages']: if lang not in enums.SOFTWARE_LANG_CODES: yield JSONError("The 'languages' property of object '%s' " "contains an invalid ISO 639-2 language " " code ('%s')." % (key, lang), instance['id'])
python
def software_language(instance): """Ensure the 'language' property of software objects is a valid ISO 639-2 language code. """ for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'software' and 'languages' in obj): for lang in obj['languages']: if lang not in enums.SOFTWARE_LANG_CODES: yield JSONError("The 'languages' property of object '%s' " "contains an invalid ISO 639-2 language " " code ('%s')." % (key, lang), instance['id'])
[ "def", "software_language", "(", "instance", ")", ":", "for", "key", ",", "obj", "in", "instance", "[", "'objects'", "]", ".", "items", "(", ")", ":", "if", "(", "'type'", "in", "obj", "and", "obj", "[", "'type'", "]", "==", "'software'", "and", "'languages'", "in", "obj", ")", ":", "for", "lang", "in", "obj", "[", "'languages'", "]", ":", "if", "lang", "not", "in", "enums", ".", "SOFTWARE_LANG_CODES", ":", "yield", "JSONError", "(", "\"The 'languages' property of object '%s' \"", "\"contains an invalid ISO 639-2 language \"", "\" code ('%s').\"", "%", "(", "key", ",", "lang", ")", ",", "instance", "[", "'id'", "]", ")" ]
Ensure the 'language' property of software objects is a valid ISO 639-2 language code.
[ "Ensure", "the", "language", "property", "of", "software", "objects", "is", "a", "valid", "ISO", "639", "-", "2", "language", "code", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v20/musts.py#L307-L319
train
oasis-open/cti-stix-validator
stix2validator/v20/musts.py
types_strict
def types_strict(instance): """Ensure that no custom object types are used, but only the official ones from the specification. """ if instance['type'] not in enums.TYPES: yield JSONError("Object type '%s' is not one of those defined in the" " specification." % instance['type'], instance['id']) if has_cyber_observable_data(instance): for key, obj in instance['objects'].items(): if 'type' in obj and obj['type'] not in enums.OBSERVABLE_TYPES: yield JSONError("Observable object %s is type '%s' which is " "not one of those defined in the " "specification." % (key, obj['type']), instance['id'])
python
def types_strict(instance): """Ensure that no custom object types are used, but only the official ones from the specification. """ if instance['type'] not in enums.TYPES: yield JSONError("Object type '%s' is not one of those defined in the" " specification." % instance['type'], instance['id']) if has_cyber_observable_data(instance): for key, obj in instance['objects'].items(): if 'type' in obj and obj['type'] not in enums.OBSERVABLE_TYPES: yield JSONError("Observable object %s is type '%s' which is " "not one of those defined in the " "specification." % (key, obj['type']), instance['id'])
[ "def", "types_strict", "(", "instance", ")", ":", "if", "instance", "[", "'type'", "]", "not", "in", "enums", ".", "TYPES", ":", "yield", "JSONError", "(", "\"Object type '%s' is not one of those defined in the\"", "\" specification.\"", "%", "instance", "[", "'type'", "]", ",", "instance", "[", "'id'", "]", ")", "if", "has_cyber_observable_data", "(", "instance", ")", ":", "for", "key", ",", "obj", "in", "instance", "[", "'objects'", "]", ".", "items", "(", ")", ":", "if", "'type'", "in", "obj", "and", "obj", "[", "'type'", "]", "not", "in", "enums", ".", "OBSERVABLE_TYPES", ":", "yield", "JSONError", "(", "\"Observable object %s is type '%s' which is \"", "\"not one of those defined in the \"", "\"specification.\"", "%", "(", "key", ",", "obj", "[", "'type'", "]", ")", ",", "instance", "[", "'id'", "]", ")" ]
Ensure that no custom object types are used, but only the official ones from the specification.
[ "Ensure", "that", "no", "custom", "object", "types", "are", "used", "but", "only", "the", "official", "ones", "from", "the", "specification", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v20/musts.py#L322-L336
train
oasis-open/cti-stix-validator
stix2validator/v20/musts.py
properties_strict
def properties_strict(instance): """Ensure that no custom properties are used, but only the official ones from the specification. """ if instance['type'] not in enums.TYPES: return # only check properties for official objects defined_props = enums.PROPERTIES.get(instance['type'], []) for prop in instance.keys(): if prop not in defined_props: yield JSONError("Property '%s' is not one of those defined in the" " specification." % prop, instance['id']) if has_cyber_observable_data(instance): for key, obj in instance['objects'].items(): type_ = obj.get('type', '') if type_ not in enums.OBSERVABLE_PROPERTIES: continue # custom observable types handled outside this function observable_props = enums.OBSERVABLE_PROPERTIES.get(type_, []) embedded_props = enums.OBSERVABLE_EMBEDDED_PROPERTIES.get(type_, {}) extensions = enums.OBSERVABLE_EXTENSIONS.get(type_, []) for prop in obj.keys(): if prop not in observable_props: yield JSONError("Property '%s' is not one of those defined in the" " specification for %s objects." % (prop, type_), instance['id']) # Check properties of embedded cyber observable types elif prop in embedded_props: embedded_prop_keys = embedded_props.get(prop, []) for embedded_key in obj[prop]: if isinstance(embedded_key, dict): for embedded in embedded_key: if embedded not in embedded_prop_keys: yield JSONError("Property '%s' is not one of those defined in the" " specification for the %s property in %s objects." % (embedded, prop, type_), instance['id']) elif embedded_key not in embedded_prop_keys: yield JSONError("Property '%s' is not one of those defined in the" " specification for the %s property in %s objects." % (embedded_key, prop, type_), instance['id']) # Check properties of embedded cyber observable types for ext_key in obj.get('extensions', {}): if ext_key not in extensions: continue # don't check custom extensions extension_props = enums.OBSERVABLE_EXTENSION_PROPERTIES[ext_key] for ext_prop in obj['extensions'][ext_key]: if ext_prop not in extension_props: yield JSONError("Property '%s' is not one of those defined in the" " specification for the %s extension in %s objects." % (ext_prop, ext_key, type_), instance['id']) embedded_ext_props = enums.OBSERVABLE_EXTENSION_EMBEDDED_PROPERTIES.get(ext_key, {}).get(ext_prop, []) if embedded_ext_props: for embed_ext_prop in obj['extensions'][ext_key].get(ext_prop, []): if embed_ext_prop not in embedded_ext_props: yield JSONError("Property '%s' in the %s property of the %s extension " "is not one of those defined in the specification." % (embed_ext_prop, ext_prop, ext_key), instance['id'])
python
def properties_strict(instance): """Ensure that no custom properties are used, but only the official ones from the specification. """ if instance['type'] not in enums.TYPES: return # only check properties for official objects defined_props = enums.PROPERTIES.get(instance['type'], []) for prop in instance.keys(): if prop not in defined_props: yield JSONError("Property '%s' is not one of those defined in the" " specification." % prop, instance['id']) if has_cyber_observable_data(instance): for key, obj in instance['objects'].items(): type_ = obj.get('type', '') if type_ not in enums.OBSERVABLE_PROPERTIES: continue # custom observable types handled outside this function observable_props = enums.OBSERVABLE_PROPERTIES.get(type_, []) embedded_props = enums.OBSERVABLE_EMBEDDED_PROPERTIES.get(type_, {}) extensions = enums.OBSERVABLE_EXTENSIONS.get(type_, []) for prop in obj.keys(): if prop not in observable_props: yield JSONError("Property '%s' is not one of those defined in the" " specification for %s objects." % (prop, type_), instance['id']) # Check properties of embedded cyber observable types elif prop in embedded_props: embedded_prop_keys = embedded_props.get(prop, []) for embedded_key in obj[prop]: if isinstance(embedded_key, dict): for embedded in embedded_key: if embedded not in embedded_prop_keys: yield JSONError("Property '%s' is not one of those defined in the" " specification for the %s property in %s objects." % (embedded, prop, type_), instance['id']) elif embedded_key not in embedded_prop_keys: yield JSONError("Property '%s' is not one of those defined in the" " specification for the %s property in %s objects." % (embedded_key, prop, type_), instance['id']) # Check properties of embedded cyber observable types for ext_key in obj.get('extensions', {}): if ext_key not in extensions: continue # don't check custom extensions extension_props = enums.OBSERVABLE_EXTENSION_PROPERTIES[ext_key] for ext_prop in obj['extensions'][ext_key]: if ext_prop not in extension_props: yield JSONError("Property '%s' is not one of those defined in the" " specification for the %s extension in %s objects." % (ext_prop, ext_key, type_), instance['id']) embedded_ext_props = enums.OBSERVABLE_EXTENSION_EMBEDDED_PROPERTIES.get(ext_key, {}).get(ext_prop, []) if embedded_ext_props: for embed_ext_prop in obj['extensions'][ext_key].get(ext_prop, []): if embed_ext_prop not in embedded_ext_props: yield JSONError("Property '%s' in the %s property of the %s extension " "is not one of those defined in the specification." % (embed_ext_prop, ext_prop, ext_key), instance['id'])
[ "def", "properties_strict", "(", "instance", ")", ":", "if", "instance", "[", "'type'", "]", "not", "in", "enums", ".", "TYPES", ":", "return", "# only check properties for official objects", "defined_props", "=", "enums", ".", "PROPERTIES", ".", "get", "(", "instance", "[", "'type'", "]", ",", "[", "]", ")", "for", "prop", "in", "instance", ".", "keys", "(", ")", ":", "if", "prop", "not", "in", "defined_props", ":", "yield", "JSONError", "(", "\"Property '%s' is not one of those defined in the\"", "\" specification.\"", "%", "prop", ",", "instance", "[", "'id'", "]", ")", "if", "has_cyber_observable_data", "(", "instance", ")", ":", "for", "key", ",", "obj", "in", "instance", "[", "'objects'", "]", ".", "items", "(", ")", ":", "type_", "=", "obj", ".", "get", "(", "'type'", ",", "''", ")", "if", "type_", "not", "in", "enums", ".", "OBSERVABLE_PROPERTIES", ":", "continue", "# custom observable types handled outside this function", "observable_props", "=", "enums", ".", "OBSERVABLE_PROPERTIES", ".", "get", "(", "type_", ",", "[", "]", ")", "embedded_props", "=", "enums", ".", "OBSERVABLE_EMBEDDED_PROPERTIES", ".", "get", "(", "type_", ",", "{", "}", ")", "extensions", "=", "enums", ".", "OBSERVABLE_EXTENSIONS", ".", "get", "(", "type_", ",", "[", "]", ")", "for", "prop", "in", "obj", ".", "keys", "(", ")", ":", "if", "prop", "not", "in", "observable_props", ":", "yield", "JSONError", "(", "\"Property '%s' is not one of those defined in the\"", "\" specification for %s objects.\"", "%", "(", "prop", ",", "type_", ")", ",", "instance", "[", "'id'", "]", ")", "# Check properties of embedded cyber observable types", "elif", "prop", "in", "embedded_props", ":", "embedded_prop_keys", "=", "embedded_props", ".", "get", "(", "prop", ",", "[", "]", ")", "for", "embedded_key", "in", "obj", "[", "prop", "]", ":", "if", "isinstance", "(", "embedded_key", ",", "dict", ")", ":", "for", "embedded", "in", "embedded_key", ":", "if", "embedded", "not", "in", "embedded_prop_keys", ":", "yield", "JSONError", "(", "\"Property '%s' is not one of those defined in the\"", "\" specification for the %s property in %s objects.\"", "%", "(", "embedded", ",", "prop", ",", "type_", ")", ",", "instance", "[", "'id'", "]", ")", "elif", "embedded_key", "not", "in", "embedded_prop_keys", ":", "yield", "JSONError", "(", "\"Property '%s' is not one of those defined in the\"", "\" specification for the %s property in %s objects.\"", "%", "(", "embedded_key", ",", "prop", ",", "type_", ")", ",", "instance", "[", "'id'", "]", ")", "# Check properties of embedded cyber observable types", "for", "ext_key", "in", "obj", ".", "get", "(", "'extensions'", ",", "{", "}", ")", ":", "if", "ext_key", "not", "in", "extensions", ":", "continue", "# don't check custom extensions", "extension_props", "=", "enums", ".", "OBSERVABLE_EXTENSION_PROPERTIES", "[", "ext_key", "]", "for", "ext_prop", "in", "obj", "[", "'extensions'", "]", "[", "ext_key", "]", ":", "if", "ext_prop", "not", "in", "extension_props", ":", "yield", "JSONError", "(", "\"Property '%s' is not one of those defined in the\"", "\" specification for the %s extension in %s objects.\"", "%", "(", "ext_prop", ",", "ext_key", ",", "type_", ")", ",", "instance", "[", "'id'", "]", ")", "embedded_ext_props", "=", "enums", ".", "OBSERVABLE_EXTENSION_EMBEDDED_PROPERTIES", ".", "get", "(", "ext_key", ",", "{", "}", ")", ".", "get", "(", "ext_prop", ",", "[", "]", ")", "if", "embedded_ext_props", ":", "for", "embed_ext_prop", "in", "obj", "[", "'extensions'", "]", "[", "ext_key", "]", ".", "get", "(", "ext_prop", ",", "[", "]", ")", ":", "if", "embed_ext_prop", "not", "in", "embedded_ext_props", ":", "yield", "JSONError", "(", "\"Property '%s' in the %s property of the %s extension \"", "\"is not one of those defined in the specification.\"", "%", "(", "embed_ext_prop", ",", "ext_prop", ",", "ext_key", ")", ",", "instance", "[", "'id'", "]", ")" ]
Ensure that no custom properties are used, but only the official ones from the specification.
[ "Ensure", "that", "no", "custom", "properties", "are", "used", "but", "only", "the", "official", "ones", "from", "the", "specification", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v20/musts.py#L339-L396
train
oasis-open/cti-stix-validator
stix2validator/v20/musts.py
patterns
def patterns(instance, options): """Ensure that the syntax of the pattern of an indicator is valid, and that objects and properties referenced by the pattern are valid. """ if instance['type'] != 'indicator' or 'pattern' not in instance: return pattern = instance['pattern'] if not isinstance(pattern, string_types): return # This error already caught by schemas errors = pattern_validator(pattern) # Check pattern syntax if errors: for e in errors: yield PatternError(str(e), instance['id']) return type_format_re = re.compile(r'^\-?[a-z0-9]+(-[a-z0-9]+)*\-?$') property_format_re = re.compile(r'^[a-z0-9_]{3,250}$') p = Pattern(pattern) inspection = p.inspect().comparisons for objtype in inspection: # Check observable object types if objtype in enums.OBSERVABLE_TYPES: pass elif options.strict_types: yield PatternError("'%s' is not a valid STIX observable type" % objtype, instance['id']) elif (not type_format_re.match(objtype) or len(objtype) < 3 or len(objtype) > 250): yield PatternError("'%s' is not a valid observable type name" % objtype, instance['id']) elif (all(x not in options.disabled for x in ['all', 'format-checks', 'custom-prefix']) and not CUSTOM_TYPE_PREFIX_RE.match(objtype)): yield PatternError("Custom Observable Object type '%s' should start " "with 'x-' followed by a source unique identifier " "(like a domain name with dots replaced by " "hyphens), a hyphen and then the name" % objtype, instance['id']) elif (all(x not in options.disabled for x in ['all', 'format-checks', 'custom-prefix-lax']) and not CUSTOM_TYPE_LAX_PREFIX_RE.match(objtype)): yield PatternError("Custom Observable Object type '%s' should start " "with 'x-'" % objtype, instance['id']) # Check observable object properties expression_list = inspection[objtype] for exp in expression_list: path = exp[0] # Get the property name without list index, dictionary key, or referenced object property prop = path[0] if objtype in enums.OBSERVABLE_PROPERTIES and prop in enums.OBSERVABLE_PROPERTIES[objtype]: continue elif options.strict_properties: yield PatternError("'%s' is not a valid property for '%s' objects" % (prop, objtype), instance['id']) elif not property_format_re.match(prop): yield PatternError("'%s' is not a valid observable property name" % prop, instance['id']) elif (all(x not in options.disabled for x in ['all', 'format-checks', 'custom-prefix']) and not CUSTOM_PROPERTY_PREFIX_RE.match(prop)): yield PatternError("Cyber Observable Object custom property '%s' " "should start with 'x_' followed by a source " "unique identifier (like a domain name with " "dots replaced by underscores), an " "underscore and then the name" % prop, instance['id']) elif (all(x not in options.disabled for x in ['all', 'format-checks', 'custom-prefix-lax']) and not CUSTOM_PROPERTY_LAX_PREFIX_RE.match(prop)): yield PatternError("Cyber Observable Object custom property '%s' " "should start with 'x_'" % prop, instance['id'])
python
def patterns(instance, options): """Ensure that the syntax of the pattern of an indicator is valid, and that objects and properties referenced by the pattern are valid. """ if instance['type'] != 'indicator' or 'pattern' not in instance: return pattern = instance['pattern'] if not isinstance(pattern, string_types): return # This error already caught by schemas errors = pattern_validator(pattern) # Check pattern syntax if errors: for e in errors: yield PatternError(str(e), instance['id']) return type_format_re = re.compile(r'^\-?[a-z0-9]+(-[a-z0-9]+)*\-?$') property_format_re = re.compile(r'^[a-z0-9_]{3,250}$') p = Pattern(pattern) inspection = p.inspect().comparisons for objtype in inspection: # Check observable object types if objtype in enums.OBSERVABLE_TYPES: pass elif options.strict_types: yield PatternError("'%s' is not a valid STIX observable type" % objtype, instance['id']) elif (not type_format_re.match(objtype) or len(objtype) < 3 or len(objtype) > 250): yield PatternError("'%s' is not a valid observable type name" % objtype, instance['id']) elif (all(x not in options.disabled for x in ['all', 'format-checks', 'custom-prefix']) and not CUSTOM_TYPE_PREFIX_RE.match(objtype)): yield PatternError("Custom Observable Object type '%s' should start " "with 'x-' followed by a source unique identifier " "(like a domain name with dots replaced by " "hyphens), a hyphen and then the name" % objtype, instance['id']) elif (all(x not in options.disabled for x in ['all', 'format-checks', 'custom-prefix-lax']) and not CUSTOM_TYPE_LAX_PREFIX_RE.match(objtype)): yield PatternError("Custom Observable Object type '%s' should start " "with 'x-'" % objtype, instance['id']) # Check observable object properties expression_list = inspection[objtype] for exp in expression_list: path = exp[0] # Get the property name without list index, dictionary key, or referenced object property prop = path[0] if objtype in enums.OBSERVABLE_PROPERTIES and prop in enums.OBSERVABLE_PROPERTIES[objtype]: continue elif options.strict_properties: yield PatternError("'%s' is not a valid property for '%s' objects" % (prop, objtype), instance['id']) elif not property_format_re.match(prop): yield PatternError("'%s' is not a valid observable property name" % prop, instance['id']) elif (all(x not in options.disabled for x in ['all', 'format-checks', 'custom-prefix']) and not CUSTOM_PROPERTY_PREFIX_RE.match(prop)): yield PatternError("Cyber Observable Object custom property '%s' " "should start with 'x_' followed by a source " "unique identifier (like a domain name with " "dots replaced by underscores), an " "underscore and then the name" % prop, instance['id']) elif (all(x not in options.disabled for x in ['all', 'format-checks', 'custom-prefix-lax']) and not CUSTOM_PROPERTY_LAX_PREFIX_RE.match(prop)): yield PatternError("Cyber Observable Object custom property '%s' " "should start with 'x_'" % prop, instance['id'])
[ "def", "patterns", "(", "instance", ",", "options", ")", ":", "if", "instance", "[", "'type'", "]", "!=", "'indicator'", "or", "'pattern'", "not", "in", "instance", ":", "return", "pattern", "=", "instance", "[", "'pattern'", "]", "if", "not", "isinstance", "(", "pattern", ",", "string_types", ")", ":", "return", "# This error already caught by schemas", "errors", "=", "pattern_validator", "(", "pattern", ")", "# Check pattern syntax", "if", "errors", ":", "for", "e", "in", "errors", ":", "yield", "PatternError", "(", "str", "(", "e", ")", ",", "instance", "[", "'id'", "]", ")", "return", "type_format_re", "=", "re", ".", "compile", "(", "r'^\\-?[a-z0-9]+(-[a-z0-9]+)*\\-?$'", ")", "property_format_re", "=", "re", ".", "compile", "(", "r'^[a-z0-9_]{3,250}$'", ")", "p", "=", "Pattern", "(", "pattern", ")", "inspection", "=", "p", ".", "inspect", "(", ")", ".", "comparisons", "for", "objtype", "in", "inspection", ":", "# Check observable object types", "if", "objtype", "in", "enums", ".", "OBSERVABLE_TYPES", ":", "pass", "elif", "options", ".", "strict_types", ":", "yield", "PatternError", "(", "\"'%s' is not a valid STIX observable type\"", "%", "objtype", ",", "instance", "[", "'id'", "]", ")", "elif", "(", "not", "type_format_re", ".", "match", "(", "objtype", ")", "or", "len", "(", "objtype", ")", "<", "3", "or", "len", "(", "objtype", ")", ">", "250", ")", ":", "yield", "PatternError", "(", "\"'%s' is not a valid observable type name\"", "%", "objtype", ",", "instance", "[", "'id'", "]", ")", "elif", "(", "all", "(", "x", "not", "in", "options", ".", "disabled", "for", "x", "in", "[", "'all'", ",", "'format-checks'", ",", "'custom-prefix'", "]", ")", "and", "not", "CUSTOM_TYPE_PREFIX_RE", ".", "match", "(", "objtype", ")", ")", ":", "yield", "PatternError", "(", "\"Custom Observable Object type '%s' should start \"", "\"with 'x-' followed by a source unique identifier \"", "\"(like a domain name with dots replaced by \"", "\"hyphens), a hyphen and then the name\"", "%", "objtype", ",", "instance", "[", "'id'", "]", ")", "elif", "(", "all", "(", "x", "not", "in", "options", ".", "disabled", "for", "x", "in", "[", "'all'", ",", "'format-checks'", ",", "'custom-prefix-lax'", "]", ")", "and", "not", "CUSTOM_TYPE_LAX_PREFIX_RE", ".", "match", "(", "objtype", ")", ")", ":", "yield", "PatternError", "(", "\"Custom Observable Object type '%s' should start \"", "\"with 'x-'\"", "%", "objtype", ",", "instance", "[", "'id'", "]", ")", "# Check observable object properties", "expression_list", "=", "inspection", "[", "objtype", "]", "for", "exp", "in", "expression_list", ":", "path", "=", "exp", "[", "0", "]", "# Get the property name without list index, dictionary key, or referenced object property", "prop", "=", "path", "[", "0", "]", "if", "objtype", "in", "enums", ".", "OBSERVABLE_PROPERTIES", "and", "prop", "in", "enums", ".", "OBSERVABLE_PROPERTIES", "[", "objtype", "]", ":", "continue", "elif", "options", ".", "strict_properties", ":", "yield", "PatternError", "(", "\"'%s' is not a valid property for '%s' objects\"", "%", "(", "prop", ",", "objtype", ")", ",", "instance", "[", "'id'", "]", ")", "elif", "not", "property_format_re", ".", "match", "(", "prop", ")", ":", "yield", "PatternError", "(", "\"'%s' is not a valid observable property name\"", "%", "prop", ",", "instance", "[", "'id'", "]", ")", "elif", "(", "all", "(", "x", "not", "in", "options", ".", "disabled", "for", "x", "in", "[", "'all'", ",", "'format-checks'", ",", "'custom-prefix'", "]", ")", "and", "not", "CUSTOM_PROPERTY_PREFIX_RE", ".", "match", "(", "prop", ")", ")", ":", "yield", "PatternError", "(", "\"Cyber Observable Object custom property '%s' \"", "\"should start with 'x_' followed by a source \"", "\"unique identifier (like a domain name with \"", "\"dots replaced by underscores), an \"", "\"underscore and then the name\"", "%", "prop", ",", "instance", "[", "'id'", "]", ")", "elif", "(", "all", "(", "x", "not", "in", "options", ".", "disabled", "for", "x", "in", "[", "'all'", ",", "'format-checks'", ",", "'custom-prefix-lax'", "]", ")", "and", "not", "CUSTOM_PROPERTY_LAX_PREFIX_RE", ".", "match", "(", "prop", ")", ")", ":", "yield", "PatternError", "(", "\"Cyber Observable Object custom property '%s' \"", "\"should start with 'x_'\"", "%", "prop", ",", "instance", "[", "'id'", "]", ")" ]
Ensure that the syntax of the pattern of an indicator is valid, and that objects and properties referenced by the pattern are valid.
[ "Ensure", "that", "the", "syntax", "of", "the", "pattern", "of", "an", "indicator", "is", "valid", "and", "that", "objects", "and", "properties", "referenced", "by", "the", "pattern", "are", "valid", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v20/musts.py#L399-L470
train
oasis-open/cti-stix-validator
stix2validator/v20/musts.py
list_musts
def list_musts(options): """Construct the list of 'MUST' validators to be run by the validator. """ validator_list = [ timestamp, modified_created, object_marking_circular_refs, granular_markings_circular_refs, marking_selector_syntax, observable_object_references, artifact_mime_type, character_set, software_language, patterns ] # --strict-types if options.strict_types: validator_list.append(types_strict) # --strict-properties if options.strict_properties: validator_list.append(properties_strict) return validator_list
python
def list_musts(options): """Construct the list of 'MUST' validators to be run by the validator. """ validator_list = [ timestamp, modified_created, object_marking_circular_refs, granular_markings_circular_refs, marking_selector_syntax, observable_object_references, artifact_mime_type, character_set, software_language, patterns ] # --strict-types if options.strict_types: validator_list.append(types_strict) # --strict-properties if options.strict_properties: validator_list.append(properties_strict) return validator_list
[ "def", "list_musts", "(", "options", ")", ":", "validator_list", "=", "[", "timestamp", ",", "modified_created", ",", "object_marking_circular_refs", ",", "granular_markings_circular_refs", ",", "marking_selector_syntax", ",", "observable_object_references", ",", "artifact_mime_type", ",", "character_set", ",", "software_language", ",", "patterns", "]", "# --strict-types", "if", "options", ".", "strict_types", ":", "validator_list", ".", "append", "(", "types_strict", ")", "# --strict-properties", "if", "options", ".", "strict_properties", ":", "validator_list", ".", "append", "(", "properties_strict", ")", "return", "validator_list" ]
Construct the list of 'MUST' validators to be run by the validator.
[ "Construct", "the", "list", "of", "MUST", "validators", "to", "be", "run", "by", "the", "validator", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v20/musts.py#L473-L497
train
oasis-open/cti-stix-validator
stix2validator/v21/enums.py
media_types
def media_types(): """Return a list of the IANA Media (MIME) Types, or an empty list if the IANA website is unreachable. Store it as a function attribute so that we only build the list once. """ if not hasattr(media_types, 'typelist'): tlist = [] categories = [ 'application', 'audio', 'font', 'image', 'message', 'model', 'multipart', 'text', 'video' ] for cat in categories: try: data = requests.get('http://www.iana.org/assignments/' 'media-types/%s.csv' % cat) except requests.exceptions.RequestException: return [] types = [] for line in data.iter_lines(): if line: line = line.decode("utf-8") if line.count(',') > 0: reg_template = line.split(',')[1] if reg_template: types.append(reg_template) else: types.append(cat + '/' + line.split(',')[0]) tlist.extend(types) media_types.typelist = tlist return media_types.typelist
python
def media_types(): """Return a list of the IANA Media (MIME) Types, or an empty list if the IANA website is unreachable. Store it as a function attribute so that we only build the list once. """ if not hasattr(media_types, 'typelist'): tlist = [] categories = [ 'application', 'audio', 'font', 'image', 'message', 'model', 'multipart', 'text', 'video' ] for cat in categories: try: data = requests.get('http://www.iana.org/assignments/' 'media-types/%s.csv' % cat) except requests.exceptions.RequestException: return [] types = [] for line in data.iter_lines(): if line: line = line.decode("utf-8") if line.count(',') > 0: reg_template = line.split(',')[1] if reg_template: types.append(reg_template) else: types.append(cat + '/' + line.split(',')[0]) tlist.extend(types) media_types.typelist = tlist return media_types.typelist
[ "def", "media_types", "(", ")", ":", "if", "not", "hasattr", "(", "media_types", ",", "'typelist'", ")", ":", "tlist", "=", "[", "]", "categories", "=", "[", "'application'", ",", "'audio'", ",", "'font'", ",", "'image'", ",", "'message'", ",", "'model'", ",", "'multipart'", ",", "'text'", ",", "'video'", "]", "for", "cat", "in", "categories", ":", "try", ":", "data", "=", "requests", ".", "get", "(", "'http://www.iana.org/assignments/'", "'media-types/%s.csv'", "%", "cat", ")", "except", "requests", ".", "exceptions", ".", "RequestException", ":", "return", "[", "]", "types", "=", "[", "]", "for", "line", "in", "data", ".", "iter_lines", "(", ")", ":", "if", "line", ":", "line", "=", "line", ".", "decode", "(", "\"utf-8\"", ")", "if", "line", ".", "count", "(", "','", ")", ">", "0", ":", "reg_template", "=", "line", ".", "split", "(", "','", ")", "[", "1", "]", "if", "reg_template", ":", "types", ".", "append", "(", "reg_template", ")", "else", ":", "types", ".", "append", "(", "cat", "+", "'/'", "+", "line", ".", "split", "(", "','", ")", "[", "0", "]", ")", "tlist", ".", "extend", "(", "types", ")", "media_types", ".", "typelist", "=", "tlist", "return", "media_types", ".", "typelist" ]
Return a list of the IANA Media (MIME) Types, or an empty list if the IANA website is unreachable. Store it as a function attribute so that we only build the list once.
[ "Return", "a", "list", "of", "the", "IANA", "Media", "(", "MIME", ")", "Types", "or", "an", "empty", "list", "if", "the", "IANA", "website", "is", "unreachable", ".", "Store", "it", "as", "a", "function", "attribute", "so", "that", "we", "only", "build", "the", "list", "once", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/enums.py#L1618-L1656
train
oasis-open/cti-stix-validator
stix2validator/v21/enums.py
char_sets
def char_sets(): """Return a list of the IANA Character Sets, or an empty list if the IANA website is unreachable. Store it as a function attribute so that we only build the list once. """ if not hasattr(char_sets, 'setlist'): clist = [] try: data = requests.get('http://www.iana.org/assignments/character-' 'sets/character-sets-1.csv') except requests.exceptions.RequestException: return [] for line in data.iter_lines(): if line: line = line.decode("utf-8") if line.count(',') > 0: vals = line.split(',') if vals[0]: clist.append(vals[0]) else: clist.append(vals[1]) char_sets.setlist = clist return char_sets.setlist
python
def char_sets(): """Return a list of the IANA Character Sets, or an empty list if the IANA website is unreachable. Store it as a function attribute so that we only build the list once. """ if not hasattr(char_sets, 'setlist'): clist = [] try: data = requests.get('http://www.iana.org/assignments/character-' 'sets/character-sets-1.csv') except requests.exceptions.RequestException: return [] for line in data.iter_lines(): if line: line = line.decode("utf-8") if line.count(',') > 0: vals = line.split(',') if vals[0]: clist.append(vals[0]) else: clist.append(vals[1]) char_sets.setlist = clist return char_sets.setlist
[ "def", "char_sets", "(", ")", ":", "if", "not", "hasattr", "(", "char_sets", ",", "'setlist'", ")", ":", "clist", "=", "[", "]", "try", ":", "data", "=", "requests", ".", "get", "(", "'http://www.iana.org/assignments/character-'", "'sets/character-sets-1.csv'", ")", "except", "requests", ".", "exceptions", ".", "RequestException", ":", "return", "[", "]", "for", "line", "in", "data", ".", "iter_lines", "(", ")", ":", "if", "line", ":", "line", "=", "line", ".", "decode", "(", "\"utf-8\"", ")", "if", "line", ".", "count", "(", "','", ")", ">", "0", ":", "vals", "=", "line", ".", "split", "(", "','", ")", "if", "vals", "[", "0", "]", ":", "clist", ".", "append", "(", "vals", "[", "0", "]", ")", "else", ":", "clist", ".", "append", "(", "vals", "[", "1", "]", ")", "char_sets", ".", "setlist", "=", "clist", "return", "char_sets", ".", "setlist" ]
Return a list of the IANA Character Sets, or an empty list if the IANA website is unreachable. Store it as a function attribute so that we only build the list once.
[ "Return", "a", "list", "of", "the", "IANA", "Character", "Sets", "or", "an", "empty", "list", "if", "the", "IANA", "website", "is", "unreachable", ".", "Store", "it", "as", "a", "function", "attribute", "so", "that", "we", "only", "build", "the", "list", "once", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/enums.py#L1659-L1683
train
oasis-open/cti-stix-validator
stix2validator/v21/enums.py
protocols
def protocols(): """Return a list of values from the IANA Service Name and Transport Protocol Port Number Registry, or an empty list if the IANA website is unreachable. Store it as a function attribute so that we only build the list once. """ if not hasattr(protocols, 'protlist'): plist = [] try: data = requests.get('http://www.iana.org/assignments/service-names' '-port-numbers/service-names-port-numbers.csv') except requests.exceptions.RequestException: return [] for line in data.iter_lines(): if line: line = line.decode("utf-8") if line.count(',') > 0: vals = line.split(',') if vals[0]: plist.append(vals[0]) if len(vals) > 2 and vals[2] and vals[2] not in plist: plist.append(vals[2]) plist.append('ipv4') plist.append('ipv6') plist.append('ssl') plist.append('tls') plist.append('dns') protocols.protlist = plist return protocols.protlist
python
def protocols(): """Return a list of values from the IANA Service Name and Transport Protocol Port Number Registry, or an empty list if the IANA website is unreachable. Store it as a function attribute so that we only build the list once. """ if not hasattr(protocols, 'protlist'): plist = [] try: data = requests.get('http://www.iana.org/assignments/service-names' '-port-numbers/service-names-port-numbers.csv') except requests.exceptions.RequestException: return [] for line in data.iter_lines(): if line: line = line.decode("utf-8") if line.count(',') > 0: vals = line.split(',') if vals[0]: plist.append(vals[0]) if len(vals) > 2 and vals[2] and vals[2] not in plist: plist.append(vals[2]) plist.append('ipv4') plist.append('ipv6') plist.append('ssl') plist.append('tls') plist.append('dns') protocols.protlist = plist return protocols.protlist
[ "def", "protocols", "(", ")", ":", "if", "not", "hasattr", "(", "protocols", ",", "'protlist'", ")", ":", "plist", "=", "[", "]", "try", ":", "data", "=", "requests", ".", "get", "(", "'http://www.iana.org/assignments/service-names'", "'-port-numbers/service-names-port-numbers.csv'", ")", "except", "requests", ".", "exceptions", ".", "RequestException", ":", "return", "[", "]", "for", "line", "in", "data", ".", "iter_lines", "(", ")", ":", "if", "line", ":", "line", "=", "line", ".", "decode", "(", "\"utf-8\"", ")", "if", "line", ".", "count", "(", "','", ")", ">", "0", ":", "vals", "=", "line", ".", "split", "(", "','", ")", "if", "vals", "[", "0", "]", ":", "plist", ".", "append", "(", "vals", "[", "0", "]", ")", "if", "len", "(", "vals", ")", ">", "2", "and", "vals", "[", "2", "]", "and", "vals", "[", "2", "]", "not", "in", "plist", ":", "plist", ".", "append", "(", "vals", "[", "2", "]", ")", "plist", ".", "append", "(", "'ipv4'", ")", "plist", ".", "append", "(", "'ipv6'", ")", "plist", ".", "append", "(", "'ssl'", ")", "plist", ".", "append", "(", "'tls'", ")", "plist", ".", "append", "(", "'dns'", ")", "protocols", ".", "protlist", "=", "plist", "return", "protocols", ".", "protlist" ]
Return a list of values from the IANA Service Name and Transport Protocol Port Number Registry, or an empty list if the IANA website is unreachable. Store it as a function attribute so that we only build the list once.
[ "Return", "a", "list", "of", "values", "from", "the", "IANA", "Service", "Name", "and", "Transport", "Protocol", "Port", "Number", "Registry", "or", "an", "empty", "list", "if", "the", "IANA", "website", "is", "unreachable", ".", "Store", "it", "as", "a", "function", "attribute", "so", "that", "we", "only", "build", "the", "list", "once", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/enums.py#L1686-L1716
train
oasis-open/cti-stix-validator
stix2validator/v21/enums.py
ipfix
def ipfix(): """Return a list of values from the list of IANA IP Flow Information Export (IPFIX) Entities, or an empty list if the IANA website is unreachable. Store it as a function attribute so that we only build the list once. """ if not hasattr(ipfix, 'ipflist'): ilist = [] try: data = requests.get('http://www.iana.org/assignments/ipfix/ipfix-' 'information-elements.csv') except requests.exceptions.RequestException: return [] for line in data.iter_lines(): if line: line = line.decode("utf-8") if re.match(r'^\d+(,[a-zA-Z0-9]+){2},', line): vals = line.split(',') if vals[1]: ilist.append(vals[1]) ipfix.ipflist = ilist return ipfix.ipflist
python
def ipfix(): """Return a list of values from the list of IANA IP Flow Information Export (IPFIX) Entities, or an empty list if the IANA website is unreachable. Store it as a function attribute so that we only build the list once. """ if not hasattr(ipfix, 'ipflist'): ilist = [] try: data = requests.get('http://www.iana.org/assignments/ipfix/ipfix-' 'information-elements.csv') except requests.exceptions.RequestException: return [] for line in data.iter_lines(): if line: line = line.decode("utf-8") if re.match(r'^\d+(,[a-zA-Z0-9]+){2},', line): vals = line.split(',') if vals[1]: ilist.append(vals[1]) ipfix.ipflist = ilist return ipfix.ipflist
[ "def", "ipfix", "(", ")", ":", "if", "not", "hasattr", "(", "ipfix", ",", "'ipflist'", ")", ":", "ilist", "=", "[", "]", "try", ":", "data", "=", "requests", ".", "get", "(", "'http://www.iana.org/assignments/ipfix/ipfix-'", "'information-elements.csv'", ")", "except", "requests", ".", "exceptions", ".", "RequestException", ":", "return", "[", "]", "for", "line", "in", "data", ".", "iter_lines", "(", ")", ":", "if", "line", ":", "line", "=", "line", ".", "decode", "(", "\"utf-8\"", ")", "if", "re", ".", "match", "(", "r'^\\d+(,[a-zA-Z0-9]+){2},'", ",", "line", ")", ":", "vals", "=", "line", ".", "split", "(", "','", ")", "if", "vals", "[", "1", "]", ":", "ilist", ".", "append", "(", "vals", "[", "1", "]", ")", "ipfix", ".", "ipflist", "=", "ilist", "return", "ipfix", ".", "ipflist" ]
Return a list of values from the list of IANA IP Flow Information Export (IPFIX) Entities, or an empty list if the IANA website is unreachable. Store it as a function attribute so that we only build the list once.
[ "Return", "a", "list", "of", "values", "from", "the", "list", "of", "IANA", "IP", "Flow", "Information", "Export", "(", "IPFIX", ")", "Entities", "or", "an", "empty", "list", "if", "the", "IANA", "website", "is", "unreachable", ".", "Store", "it", "as", "a", "function", "attribute", "so", "that", "we", "only", "build", "the", "list", "once", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/v21/enums.py#L1719-L1741
train
oasis-open/cti-stix-validator
stix2validator/output.py
print_level
def print_level(log_function, fmt, level, *args): """Print a formatted message to stdout prepended by spaces. Useful for printing hierarchical information, like bullet lists. Note: If the application is running in "Silent Mode" (i.e., ``_SILENT == True``), this function will return immediately and no message will be printed. Args: log_function: The function that will be called to output the formatted message. fmt (str): A Python formatted string. level (int): Used to determing how many spaces to print. The formula is ``' ' * level ``. *args: Variable length list of arguments. Values are plugged into the format string. Examples: >>> print_level("%s %d", 0, "TEST", 0) TEST 0 >>> print_level("%s %d", 1, "TEST", 1) TEST 1 >>> print_level("%s %d", 2, "TEST", 2) TEST 2 """ if _SILENT: return msg = fmt % args spaces = ' ' * level log_function("%s%s" % (spaces, msg))
python
def print_level(log_function, fmt, level, *args): """Print a formatted message to stdout prepended by spaces. Useful for printing hierarchical information, like bullet lists. Note: If the application is running in "Silent Mode" (i.e., ``_SILENT == True``), this function will return immediately and no message will be printed. Args: log_function: The function that will be called to output the formatted message. fmt (str): A Python formatted string. level (int): Used to determing how many spaces to print. The formula is ``' ' * level ``. *args: Variable length list of arguments. Values are plugged into the format string. Examples: >>> print_level("%s %d", 0, "TEST", 0) TEST 0 >>> print_level("%s %d", 1, "TEST", 1) TEST 1 >>> print_level("%s %d", 2, "TEST", 2) TEST 2 """ if _SILENT: return msg = fmt % args spaces = ' ' * level log_function("%s%s" % (spaces, msg))
[ "def", "print_level", "(", "log_function", ",", "fmt", ",", "level", ",", "*", "args", ")", ":", "if", "_SILENT", ":", "return", "msg", "=", "fmt", "%", "args", "spaces", "=", "' '", "*", "level", "log_function", "(", "\"%s%s\"", "%", "(", "spaces", ",", "msg", ")", ")" ]
Print a formatted message to stdout prepended by spaces. Useful for printing hierarchical information, like bullet lists. Note: If the application is running in "Silent Mode" (i.e., ``_SILENT == True``), this function will return immediately and no message will be printed. Args: log_function: The function that will be called to output the formatted message. fmt (str): A Python formatted string. level (int): Used to determing how many spaces to print. The formula is ``' ' * level ``. *args: Variable length list of arguments. Values are plugged into the format string. Examples: >>> print_level("%s %d", 0, "TEST", 0) TEST 0 >>> print_level("%s %d", 1, "TEST", 1) TEST 1 >>> print_level("%s %d", 2, "TEST", 2) TEST 2
[ "Print", "a", "formatted", "message", "to", "stdout", "prepended", "by", "spaces", ".", "Useful", "for", "printing", "hierarchical", "information", "like", "bullet", "lists", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/output.py#L62-L94
train
oasis-open/cti-stix-validator
stix2validator/output.py
print_fatal_results
def print_fatal_results(results, level=0): """Print fatal errors that occurred during validation runs. """ print_level(logger.critical, _RED + "[X] Fatal Error: %s", level, results.error)
python
def print_fatal_results(results, level=0): """Print fatal errors that occurred during validation runs. """ print_level(logger.critical, _RED + "[X] Fatal Error: %s", level, results.error)
[ "def", "print_fatal_results", "(", "results", ",", "level", "=", "0", ")", ":", "print_level", "(", "logger", ".", "critical", ",", "_RED", "+", "\"[X] Fatal Error: %s\"", ",", "level", ",", "results", ".", "error", ")" ]
Print fatal errors that occurred during validation runs.
[ "Print", "fatal", "errors", "that", "occurred", "during", "validation", "runs", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/output.py#L97-L100
train
oasis-open/cti-stix-validator
stix2validator/output.py
print_schema_results
def print_schema_results(results, level=0): """Print JSON Schema validation errors to stdout. Args: results: An instance of ObjectValidationResults. level: The level at which to print the results. """ for error in results.errors: print_level(logger.error, _RED + "[X] %s", level, error)
python
def print_schema_results(results, level=0): """Print JSON Schema validation errors to stdout. Args: results: An instance of ObjectValidationResults. level: The level at which to print the results. """ for error in results.errors: print_level(logger.error, _RED + "[X] %s", level, error)
[ "def", "print_schema_results", "(", "results", ",", "level", "=", "0", ")", ":", "for", "error", "in", "results", ".", "errors", ":", "print_level", "(", "logger", ".", "error", ",", "_RED", "+", "\"[X] %s\"", ",", "level", ",", "error", ")" ]
Print JSON Schema validation errors to stdout. Args: results: An instance of ObjectValidationResults. level: The level at which to print the results.
[ "Print", "JSON", "Schema", "validation", "errors", "to", "stdout", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/output.py#L103-L112
train
oasis-open/cti-stix-validator
stix2validator/output.py
print_warning_results
def print_warning_results(results, level=0): """Print warning messages found during validation. """ marker = _YELLOW + "[!] " for warning in results.warnings: print_level(logger.warning, marker + "Warning: %s", level, warning)
python
def print_warning_results(results, level=0): """Print warning messages found during validation. """ marker = _YELLOW + "[!] " for warning in results.warnings: print_level(logger.warning, marker + "Warning: %s", level, warning)
[ "def", "print_warning_results", "(", "results", ",", "level", "=", "0", ")", ":", "marker", "=", "_YELLOW", "+", "\"[!] \"", "for", "warning", "in", "results", ".", "warnings", ":", "print_level", "(", "logger", ".", "warning", ",", "marker", "+", "\"Warning: %s\"", ",", "level", ",", "warning", ")" ]
Print warning messages found during validation.
[ "Print", "warning", "messages", "found", "during", "validation", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/output.py#L115-L121
train
oasis-open/cti-stix-validator
stix2validator/output.py
print_results_header
def print_results_header(identifier, is_valid): """Print a header for the results of either a file or an object. """ print_horizontal_rule() print_level(logger.info, "[-] Results for: %s", 0, identifier) if is_valid: marker = _GREEN + "[+]" verdict = "Valid" log_func = logger.info else: marker = _RED + "[X]" verdict = "Invalid" log_func = logger.error print_level(log_func, "%s STIX JSON: %s", 0, marker, verdict)
python
def print_results_header(identifier, is_valid): """Print a header for the results of either a file or an object. """ print_horizontal_rule() print_level(logger.info, "[-] Results for: %s", 0, identifier) if is_valid: marker = _GREEN + "[+]" verdict = "Valid" log_func = logger.info else: marker = _RED + "[X]" verdict = "Invalid" log_func = logger.error print_level(log_func, "%s STIX JSON: %s", 0, marker, verdict)
[ "def", "print_results_header", "(", "identifier", ",", "is_valid", ")", ":", "print_horizontal_rule", "(", ")", "print_level", "(", "logger", ".", "info", ",", "\"[-] Results for: %s\"", ",", "0", ",", "identifier", ")", "if", "is_valid", ":", "marker", "=", "_GREEN", "+", "\"[+]\"", "verdict", "=", "\"Valid\"", "log_func", "=", "logger", ".", "info", "else", ":", "marker", "=", "_RED", "+", "\"[X]\"", "verdict", "=", "\"Invalid\"", "log_func", "=", "logger", ".", "error", "print_level", "(", "log_func", ",", "\"%s STIX JSON: %s\"", ",", "0", ",", "marker", ",", "verdict", ")" ]
Print a header for the results of either a file or an object.
[ "Print", "a", "header", "for", "the", "results", "of", "either", "a", "file", "or", "an", "object", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/output.py#L139-L154
train
oasis-open/cti-stix-validator
stix2validator/output.py
print_object_results
def print_object_results(obj_result): """Print the results of validating an object. Args: obj_result: An ObjectValidationResults instance. """ print_results_header(obj_result.object_id, obj_result.is_valid) if obj_result.warnings: print_warning_results(obj_result, 1) if obj_result.errors: print_schema_results(obj_result, 1)
python
def print_object_results(obj_result): """Print the results of validating an object. Args: obj_result: An ObjectValidationResults instance. """ print_results_header(obj_result.object_id, obj_result.is_valid) if obj_result.warnings: print_warning_results(obj_result, 1) if obj_result.errors: print_schema_results(obj_result, 1)
[ "def", "print_object_results", "(", "obj_result", ")", ":", "print_results_header", "(", "obj_result", ".", "object_id", ",", "obj_result", ".", "is_valid", ")", "if", "obj_result", ".", "warnings", ":", "print_warning_results", "(", "obj_result", ",", "1", ")", "if", "obj_result", ".", "errors", ":", "print_schema_results", "(", "obj_result", ",", "1", ")" ]
Print the results of validating an object. Args: obj_result: An ObjectValidationResults instance.
[ "Print", "the", "results", "of", "validating", "an", "object", "." ]
a607014e3fa500a7678f8b61b278456ca581f9d0
https://github.com/oasis-open/cti-stix-validator/blob/a607014e3fa500a7678f8b61b278456ca581f9d0/stix2validator/output.py#L157-L169
train