INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
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_loc = '' if error.path: while len(error.path) > 0: path_elem = error.path.popleft() if type(...
Perform additional validation not possible merely with JSON schemas.
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 t...
Return a list of file paths for JSON files within directory.
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 dire...
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.
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 ``tru...
Validate files based on command line options.
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 [FileVa...
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.
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 ...
Validate objects from JSON data in a textual stream.
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_pars...
Validate the input document fn according to the options passed in.
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 ``Validat...
Validate the input string according to the options passed in.
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 ``V...
Create a JSON schema validator for the given schema.
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...
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_filename = obj_type + '.json' for root, dirnames, filenames in os.walk(schema_dir): if schema_filename in filenames: ...
Load the JSON schema at the given path as a Python object.
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.loa...
Get a generator for validating against the schema for the given object type.
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 pat...
Return the list of MUST validators for the correct version of STIX.
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_...
Return the list of SHOULD validators for the correct version of STIX.
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...
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.
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 ...
Perform STIX JSON Schema validation against STIX input.
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. ...
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 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) ...
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 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_no...
A dictionary representation of the: class:. ObjectValidationResults instance.
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 representatio...
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), custom_observable_object_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), custom_property_prefix_lax(instance), custom_observable_object_prefix_lax...
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_TYPE_PREFIX_RE.match(instance['type'])): yield JSONError("...
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'] not in enums.RESERVED_OBJECTS and not CUSTOM_TYPE_LAX_PREFIX_RE.match(instance['typ...
Ensure custom properties follow strict naming style conventions.
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[...
Ensure custom properties follow lenient naming style conventions for forward - compatibility.
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_n...
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 spaces or underscores as word separators. """ if instance['type'] not in enums.VOCAB_PROPERTIES: return properties = enums.VOCAB_PROPERTIE...
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['type'] in enums.KILL_CHAIN_PHASE_USES and 'kill_chain_phases' in instance: for phase in instance['kill_chain_phases']:...
Ensure that the open vocabulary specified by vocab is used properly.
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 propert...
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. """ if (instance['type'] == 'marking-definition' and 'definition_type' in instance and not instance['definitio...
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'] != 'relationship' or instance['type'] not in enums.TYPES): ret...
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 in enums.HASH_ALGO_OV or custom_hash_prefix_re.match(hashname): return True else: retu...
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: continue if obj['type'] == 'file': try: hashes = 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-type-ov vocabulary. """ for key, obj in instance['objects'].items(): if 'type' in obj and obj['type'] == 'file': try: ...
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 obj and obj['type'] == 'user-account': try: acct_type = obj['account_type'...
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 a good key value. Observable Objects " ...
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.OBSERVABLE_TYPES and obj['type'] not in enums.OBSERVABLE_R...
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 and obj['type'] not in enums.OBSERVABLE_RESERVED_OB...
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' in obj and 'type' in obj and obj['type'] in enums.OBSERVABLE_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' in obj and obj['type'] in enums.OBSERVABLE_EXTENSIONS): ...
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 in obj: continue type_ = obj['type'] for prop in obj: ...
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 ('src_port' not in obj or 'dst_port' not in obj)): yield ...
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|audio|font|image|message|model' '|multipart|text|video)/[a-zA-Z0-9.+_-]+') for key, ...
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 Protocol Port Number Registry. """ for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'network-traffic' and ...
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 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['...
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...
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/mes...
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_*). """ for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'network-traffic'): try: ...
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 Information Dictionary Keys. """ for key, obj in instance['objects'].items(): if ('type' in obj and obj['type'] == 'file'): try...
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 instance['country'].upper() in enums.COUNTRY_CODES): return JSONError("Location `country`...
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' in obj and obj['type'] == 'process': try: pr...
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'] == 'file': try: hashes = obj['hashes'] ...
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['objects']: if 'id' not in obj or 'modified' not in obj: c...
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(CHECKS['all']) return validator_list # --disable # Add SH...
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$") timestamp_props = ['created', 'modified'] if instance['type'] i...
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' (%s) must be later or equal to 'created' (%s)" return JS...
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 `object_marking_refs` property). """ if instance['type'] != 'marking-definition': return if 'object_marking_refs' in instance: ...
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 `granular_markings` property). """ if instance['type'] != 'marking-definition': return if 'granular_markings' in instance: ...
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 list_index_re = re.compile(r"\[(\d+)\]") for marking in instance['granular_markings']: if '...
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: continue elif obj['type'] not in enums.OBSERVABLE_PROP_REFS: con...
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['objects'].items(): if ('type' in obj and obj['type'] == 'artifact' and 'mime_type' in obj): if enums....
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['objects'].items(): if ('type' in obj and obj['type'] == 'directory' and 'path_enc' in obj):...
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'] == 'software' and 'languages' in obj): for lang in obj['langua...
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 type '%s' is not one of those defined in the" " specification." % instance['t...
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 properties for official objects defined_props = enums.PROPERTIES.get(instance['type'], []) f...
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. """ if instance['type'] != 'indicator' or 'pattern' not in instance: return pattern = instance['pattern'] if not isins...
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_refs, marking_selector_syntax, observable_object_refere...
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 as a function attribute so that we only build the list once. """ if not hasattr(media_types, 'typelist'): tlist = [] categories = [ 'applicati...
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 function attribute so that we only build the list once. """ if not hasattr(char_sets, 'setlist'): clist = [] try: data = requests.get('http://w...
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 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 ...
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 (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: ...
Print a formatted message to stdout prepended by spaces. Useful for printing hierarchical information like bullet lists.
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 ...
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.
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...
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 = _GREEN + "[+]" verdict = "Valid" log_func = logg...
Print the results of validating an object.
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_re...
Print the results of validating a file.
def print_file_results(file_result): """Print the results of validating a file. Args: file_result: A FileValidationResults instance. """ print_results_header(file_result.filepath, file_result.is_valid) for object_result in file_result.object_results: if object_result.warnings: ...
Print results ( the results of validation ) to stdout.
def print_results(results): """Print `results` (the results of validation) to stdout. Args: results: A list of FileValidationResults or ObjectValidationResults instances. """ if not isinstance(results, list): results = [results] for r in results: try: ...
Ensure file objects encryption_algorithm property is from the encryption - algo - ov vocabulary.
def vocab_encryption_algo(instance): """Ensure file objects' 'encryption_algorithm' property is from the encryption-algo-ov vocabulary. """ for key, obj in instance['objects'].items(): if 'type' in obj and obj['type'] == 'file': try: enc_algo = obj['encryption_algorit...
Ensures that all SDOs being referenced by the SRO are contained within the same bundle
def enforce_relationship_refs(instance): """Ensures that all SDOs being referenced by the SRO are contained within the same bundle""" if instance['type'] != 'bundle' or 'objects' not in instance: return rel_references = set() """Find and store all ids""" for obj in instance['objects']:...
Ensure timestamp properties with a comparison requirement are valid.
def timestamp_compare(instance): """Ensure timestamp properties with a comparison requirement are valid. E.g. `modified` must be later or equal to `created`. """ compares = [('modified', 'ge', 'created')] additional_compares = enums.TIMESTAMP_COMPARE.get(instance.get('type', ''), []) compares.e...
Ensure cyber observable timestamp properties with a comparison requirement are valid.
def observable_timestamp_compare(instance): """Ensure cyber observable timestamp properties with a comparison requirement are valid. """ for key, obj in instance['objects'].items(): compares = enums.TIMESTAMP_COMPARE_OBSERVABLE.get(obj.get('type', ''), []) print(compares) for fir...
Ensure keys in Language Content s contents dictionary are valid language codes and that the keys in the sub - dictionaries match the rules for object property names.
def language_contents(instance): """Ensure keys in Language Content's 'contents' dictionary are valid language codes, and that the keys in the sub-dictionaries match the rules for object property names. """ if instance['type'] != 'language-content' or 'contents' not in instance: return ...
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, timestamp_compare, observable_timestamp_compare, object_marking_circular_refs, granular_markings_circular_refs, marking_selector_s...
Determines the exit status code to be returned from a script by inspecting the results returned from validating file ( s ). Status codes are binary OR d together so exit codes can communicate multiple error conditions.
def get_code(results): """Determines the exit status code to be returned from a script by inspecting the results returned from validating file(s). Status codes are binary OR'd together, so exit codes can communicate multiple error conditions. """ status = EXIT_SUCCESS for file_result in re...
Parses a list of command line arguments into a ValidationOptions object.
def parse_args(cmd_args, is_script=False): """Parses a list of command line arguments into a ValidationOptions object. Args: cmd_args (list of str): The list of command line arguments to be parsed. is_script: Whether the arguments are intended for use in a stand-alone script or impo...
Decorator for functions that require cyber observable data.
def cyber_observable_check(original_function): """Decorator for functions that require cyber observable data. """ def new_function(*args, **kwargs): if not has_cyber_observable_data(args[0]): return func = original_function(*args, **kwargs) if isinstance(func, Iterable): ...
Initializes a cache which the requests library will consult for responses before making network requests.
def init_requests_cache(refresh_cache=False): """ Initializes a cache which the ``requests`` library will consult for responses, before making network requests. :param refresh_cache: Whether the cache should be cleared out """ # Cache data from external sources; used in some checks dirs = A...
render content with active urls logic
def render_tag(self, context, kwargs, nodelist): '''render content with "active" urls logic''' # load configuration from passed options self.load_configuration(**kwargs) # get request from context request = context['request'] # get full path from request self.fu...
parse content of extension
def parse(self, parser): '''parse content of extension''' # line number of token that started the tag lineno = next(parser.stream).lineno # template context context = nodes.ContextReference() # parse keyword arguments kwargs = [] while parser.stream.loo...
render content with active urls logic
def render_tag(self, context, caller, **kwargs): '''render content with "active" urls logic''' # load configuration from passed options self.load_configuration(**kwargs) # get request from context request = context['request'] # get full path from request self.fu...
generate cache key
def get_cache_key(content, **kwargs): '''generate cache key''' cache_key = '' for key in sorted(kwargs.keys()): cache_key = '{cache_key}.{key}:{value}'.format( cache_key=cache_key, key=key, value=kwargs[key], ) cache_key = '{content}{cache_key}'.forma...
Return True/ False from yes/ no.
def yesno_to_bool(value, varname): """Return True/False from "yes"/"no". :param value: template keyword argument value :type value: string :param varname: name of the variable, for use on exception raising :type varname: string :raises: :exc:`ImproperlyConfigured` Django > 1.5 template boo...
check active url apply css_class
def check_active(url, element, **kwargs): '''check "active" url, apply css_class''' menu = yesno_to_bool(kwargs['menu'], 'menu') ignore_params = yesno_to_bool(kwargs['ignore_params'], 'ignore_params') # check missing href parameter if not url.attrib.get('href', None) is None: # get href att...
check content for active urls
def check_content(content, **kwargs): '''check content for "active" urls''' # valid html root tag try: # render elements tree from content tree = fragment_fromstring(content) # flag for prevent content rerendering, when no "active" urls found processed = False # djang...
check content for active urls store results to django cache
def render_content(content, **kwargs): '''check content for "active" urls, store results to django cache''' # try to take pre rendered content from django cache, if caching is enabled if settings.ACTIVE_URL_CACHE: cache_key = get_cache_key(content, **kwargs) # get cached content from django...
load configuration merge with default settings
def load_configuration(self, **kwargs): '''load configuration, merge with default settings''' # update passed arguments with default values for key in settings.ACTIVE_URL_KWARGS: kwargs.setdefault(key, settings.ACTIVE_URL_KWARGS[key]) # "active" html tag css class se...
Parse a Marathon response into an object or list of objects.
def _parse_response(response, clazz, is_list=False, resource_name=None): """Parse a Marathon response into an object or list of objects.""" target = response.json()[ resource_name] if resource_name else response.json() if is_list: return [clazz.from_json(resource) for res...
Query Marathon server.
def _do_request(self, method, path, params=None, data=None): """Query Marathon server.""" headers = { 'Content-Type': 'application/json', 'Accept': 'application/json'} if self.auth_token: headers['Authorization'] = "token={}".format(self.auth_token) response = N...
Query Marathon server for events.
def _do_sse_request(self, path, params=None): """Query Marathon server for events.""" urls = [''.join([server.rstrip('/'), path]) for server in self.servers] while urls: url = urls.pop() try: # Requests does not set the original Authorization header on cro...