text
stringlengths
81
112k
Takes the average of all instantaneous cosfi values Returns ------- float def active_cosfi(self): """ Takes the average of all instantaneous cosfi values Returns ------- float """ inst = self.load_instantaneous() values = [float(...
Parameters ---------- val_id : str Returns ------- requests.Response def on_command_control(self, val_id): """ Parameters ---------- val_id : str Returns ------- requests.Response """ data = "control,contr...
Parameters ---------- val_id : str Returns ------- requests.Response def off_command_control(self, val_id): """ Parameters ---------- val_id : str Returns ------- requests.Response """ data = "control,cont...
Parameters ---------- val_id : str Returns ------- requests.Response def delete_command_control(self, val_id): """ Parameters ---------- val_id : str Returns ------- requests.Response """ data = "delete,c...
Parameters ---------- val_id : str Returns ------- requests.Response def delete_command_control_timers(self, val_id): """ Parameters ---------- val_id : str Returns ------- requests.Response """ data = "de...
Parameters ---------- logfile : str Returns ------- dict def select_logfile(self, logfile): """ Parameters ---------- logfile : str Returns ------- dict """ data = 'logFileSelect,' + logfile r = se...
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 arg...
Automatically fills bLength and bDescriptorType. 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 wast...
Return an OS description header. interface (int) Related interface number. ext_list (list of OSExtCompatDesc or OSExtPropDesc) List of instances of extended descriptors. def getOSDesc(interface, ext_list): """ Return an OS description header. interface (int) Related interfac...
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 functi...
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 ...
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. def getStrings(lang_dict): """ Return a FunctionFS descriptor suitable for serialisation...
structure (ctypes.Structure) The structure to serialise. Returns a ctypes.c_char array. Does not copy memory. def serialise(structure): """ structure (ctypes.Structure) The structure to serialise. Returns a ctypes.c_char array. Does not copy memory. """ return ctypes.c...
Halt current endpoint. 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: ...
Returns the host-visible interface number, or None if there is no such interface. def getRealInterfaceNumber(self, interface): """ Returns the host-visible interface number, or None if there is no such interface. """ try: return self._ioctl(INTERFACE_REVMAP, ...
Returns the currently active endpoint descriptor (depending on current USB speed). def getDescriptor(self): """ Returns the currently active endpoint descriptor (depending on current USB speed). """ result = USBEndpointDescriptor() self._ioctl(ENDPOINT_DESC, resu...
Halt current endpoint. 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._h...
Close all endpoint file descriptors. def close(self): """ Close all endpoint file descriptors. """ ep_list = self._ep_list while ep_list: ep_list.pop().close() self._closed = True
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 e...
Slowly writes to stdout, without emitting a newline so any output buffering (or input for next pipeline command) can be detected. 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....
The configuration containing this function has been enabled by host. Endpoints become working files, so submit some read operations. def onEnable(self): """ The configuration containing this function has been enabled by host. Endpoints become working files, so submit some read operation...
The configuration containing this function has been disabled by host. Endpoint do not work anymore, so cancel AIO operation blocks. def _disable(self): """ The configuration containing this function has been disabled by host. Endpoint do not work anymore, so cancel AIO operation blocks....
Call when eventfd notified events are available. 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...
Queue write in kernel. value (bytes) Value to send. 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.getEndpo...
Return an error message that is easier to read and more useful. May require updating if the schemas change significantly. 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_lo...
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 ob...
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`. def list_json_files(directory, ...
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 ...
Validate files based on command line options. Args: options: An instance of ``ValidationOptions`` containing options for this validation run. def run_validation(options): """Validate files based on command line options. Args: options: An instance of ``ValidationOptions`` conta...
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...
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. def validate(in_, options=None): """ Validate objects from JSON data in a textual stream. :param ...
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 insta...
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 Objec...
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. def load_validator(schema_path, schema): """Create a JSON schema validator f...
Search the `schema_dir` directory for a schema called `obj_type`.json. Return the file path of the first match it finds. 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_file...
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. def load_schema(schema_path): """Load the JSON schema at the given path as a Python object. Args: schema_path: A ...
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 ...
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. def _get_musts(options): """Return the list of 'MUST' validators for the correct version of STIX...
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. def _get_shoulds(options): """Return the list of 'SHOULD' validators for the correct version o...
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 ...
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 valid...
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 def object_result(self): """ Get the object result object, assuming there is only one. Raises ...
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 def object_results(self, object_results): """ Set the results to an iterable of val...
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...
Ensure custom content follows strict naming style conventions. 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), ...
Ensure custom content follows lenient naming style conventions for forward-compatibility. 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), c...
Ensure custom objects follow strict naming style conventions. 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_TYP...
Ensure custom objects follow lenient naming style conventions for forward-compatibility. 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'] n...
Ensure custom properties follow strict naming style conventions. Does not check property names in custom objects. 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 ...
Ensure custom properties follow lenient naming style conventions for forward-compatibility. Does not check property names in custom objects. def custom_property_prefix_lax(instance): """Ensure custom properties follow lenient naming style conventions for forward-compatibility. Does not check prop...
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. def open_vocab_values(instance): """Ensure that the values of all properties which use open vocabularies are in lowercase and use hyphens instead of...
Ensure the `kill_chain_name` and `phase_name` properties of `kill_chain_phase` objects follow naming style conventions. 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['t...
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. def check_vocab(i...
Ensure that the `definition_type` property of `marking-definition` objects is one of the values in the STIX 2.0 specification. 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. """ ...
Ensure that only the relationship types defined in the specification are used. 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'...
Return true if given value is a valid, recommended hash name according to the STIX 2 specification. 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 i...
Ensure objects with 'hashes' properties only use values from the hash-algo-ov vocabulary. 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: ...
Ensure file objects with the windows-pebinary-ext extension have a 'pe-type' property that is from the windows-pebinary-type-ov vocabulary. 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-t...
Ensure a user-account objects' 'account-type' property is from the account-type-ov vocabulary. 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 ob...
Ensure observable-objects keys are non-negative integers. 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...
Ensure custom observable objects follow strict naming style conventions. 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....
Ensure custom observable objects follow naming style conventions. 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 ...
Ensure custom observable object extensions follow strict naming style conventions. 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'...
Ensure custom observable object extensions follow naming style conventions. 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...
Ensure observable object custom properties follow strict naming style conventions. 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 i...
Ensure network-traffic objects contain both src_port and dst_port. 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 (...
Ensure the 'mime_type' property of file objects comes from the Template column in the IANA media type registry. 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|a...
Ensure the 'protocols' property of network-traffic objects contains only values from the IANA Service Name and Transport Protocol Port Number Registry. def protocols(instance): """Ensure the 'protocols' property of network-traffic objects contains only values from the IANA Service Name and Transport Pr...
Ensure the 'ipfix' property of network-traffic objects contains only values from the IANA IP Flow Information Export (IPFIX) Entities Registry. def ipfix(instance): """Ensure the 'ipfix' property of network-traffic objects contains only values from the IANA IP Flow Information Export (IPFIX) Entities Regis...
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 differentia...
Ensure the keys of the 'options' property of the socket-ext extension of network-traffic objects are only valid socket options (SO_*). 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_*). ...
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. 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...
Ensure that the `country` property of `location` objects is a valid ISO 3166-1 ALPHA-2 Code. 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 ...
Ensure the 'priority' property of windows-process-ext ends in '_CLASS'. 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'...
Ensure keys in 'hashes'-type properties are no more than 30 characters long. 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']...
Ensure objects with duplicate IDs have different `modified` timestamps. 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['obje...
Construct the list of 'SHOULD' validators to be run by the validator. 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(CHE...
Ensure timestamps contain sane months, days, hours, minutes, seconds. 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$") ...
`modified` property must be later or equal to `created` property 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...
Ensure that marking definitions do not contain circular references (ie. they do not reference themselves in the `object_marking_refs` property). def object_marking_circular_refs(instance): """Ensure that marking definitions do not contain circular references (ie. they do not reference themselves in the `ob...
Ensure that marking definitions do not contain circular references (ie. they do not reference themselves in the `granular_markings` property). def granular_markings_circular_refs(instance): """Ensure that marking definitions do not contain circular references (ie. they do not reference themselves in the `g...
Ensure selectors in granular markings refer to items which are actually present in the object. 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 lis...
Ensure certain observable object properties reference the correct type of object. 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: ...
Ensure the 'mime_type' property of artifact objects comes from the Template column in the IANA media type registry. 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['...
Ensure certain properties of cyber observable objects come from the IANA Character Set list. 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['o...
Ensure the 'language' property of software objects is a valid ISO 639-2 language code. 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'...
Ensure that no custom object types are used, but only the official ones from the specification. 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 ...
Ensure that no custom properties are used, but only the official ones from the specification. 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 pr...
Ensure that the syntax of the pattern of an indicator is valid, and that objects and properties referenced by the pattern are valid. 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. "...
Construct the list of 'MUST' validators to be run by the validator. 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_re...
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. def media_types(): """Return a list of the IANA Media (MIME) Types, or an empty list if the IANA website is unreachable. Store it ...
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. 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 funct...
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. def protocols(): """Return a list of values from the IANA Service Name and Transport...
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. def ipfix(): """Return a list of values from the list of IANA IP Flow Information Export ...
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: ...
Print fatal errors that occurred during validation runs. 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)
Print JSON Schema validation errors to stdout. Args: results: An instance of ObjectValidationResults. level: The level at which to print the results. def print_schema_results(results, level=0): """Print JSON Schema validation errors to stdout. Args: results: An instance of ObjectV...
Print warning messages found during validation. 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)
Print a header for the results of either a file or an object. 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 = _...
Print the results of validating an object. Args: obj_result: An ObjectValidationResults instance. 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_...