def __init__(self, pattern=None, **_): try: SigmaCollectionParser(self.pattern) except (yaml.parser.ParserError, yaml.scanner.ScannerError) as e: raise ValidationError('{0:s} is not a valid YAML markup: {1!s}'.format(pattern, e)) except (SigmaParseError, SigmaCollectionParseError) as e: raise ValidationError('{0:s} is not a valid Sigma rule: {1!s}'.format(pattern, e))
def is_valid(self): try: self.normalize() except Exception as e: # pylint: disable=broad-except ValidationError('Invalid {0:s} value: {1!r} ({2!r})'.format( self.__class__.__name__, self.value, e)) if not self.validate_string(self.value): raise ValidationError('Invalid {0:s} value: {1!r}'.format( self.__class__.__name__, self.value))
def is_valid(self): Indicator.is_valid(self) if not isinstance(self.pattern, str): raise ValidationError('.pattern must be str') try: re.compile(self.pattern) except re.error as err: raise ValidationError( 'Could not compile regular expression: {0:s}'.format(str(err))) return True
def is_valid(self): Indicator.is_valid(self) if not isinstance(self.pattern, str): raise ValidationError('.pattern must be str') try: yara.compile(source=self.pattern) except (yara.SyntaxError, yara.Error) as err: raise ValidationError( 'Could not compile yara rule: {0:s}'.format(str(err))) return True
def _load_yeti(cls, args): """Translate information from the backend into a valid Yeti object. Will instantiate a Yeti object from that definition. Args: args: The dictionary to use to create the Yeti object. Returns: The corresponding Yeti objet. Raises: ValidationError: If a Yeti object could not be instantiated from the serialized data. """ if isinstance(args, list): return [cls._load_yeti(item) for item in args] subclass = cls.get_final_datatype(args) db_id = args.pop('_id', None) args.pop('_rev', None) if 'stix_id' in args: args['id'] = args.pop('stix_id') elif '_key' in args: args['id'] = int(args.pop('_key')) args.pop('_key', None) try: obj = subclass(**args) if db_id: obj._arango_id = db_id # pylint: disable=protected-access return obj except Exception as err: raise ValidationError(str(err))
def normalize(self): initial = self.name self.name = re.sub(r'[^a-z0-9\-_ ]', '', self.name.lower()) self.name = re.sub(' ', '_', self.name) if not self.name: raise ValidationError( 'Tag name "{0:s}" is invalid'.format(initial))
def load_stix(cls, args): """Translate information from the backend into a valid STIX definition. Will instantiate a STIX object from that definition. Args: args: The dictionary to use to create the STIX object. strict: Unused, kept to be consistent with overriden method Returns: The corresponding STIX objet. Raises: ValidationError: If a STIX object could not be instantiated from the serialized data. """ if isinstance(args, list): return [cls.load_stix(item) for item in args] subclass = cls.get_final_datatype(args['attributes']) db_id = args.pop('_id', None) db_from = args.pop('_from') db_to = args.pop('_to') args.pop('_rev', None) stix_rel = args['attributes'] try: obj = subclass(db_from, db_to, stix_rel) if db_id: obj._arango_id = db_id # pylint: disable=protected-access except Exception as err: raise ValidationError(str(err)) return obj
def __init__(self, **kwargs): self.id = kwargs.pop('id', None) if not self.validate_string(kwargs['value']): raise ValidationError( '{0:s} is not a valid string for {1:s}'.format( kwargs['value'], self.type)) super().__init__(**kwargs) self.normalize()
def handle_error(self, exc, data): """Log and raise our custom exception when (de)serialization fails.""" error_dict = exc.messages if '_schema' in error_dict: error_dict = {} for idx, error in enumerate(exc.messages['_schema']): error_dict[error] = data[idx] raise ValidationError(exc.messages)
def get_final_datatype(cls, args): subclass = cls if 'type' in args: if args['type'] not in cls.datatypes: raise ValidationError( '"{0:s}" not in acceptable datatypes ({1!r})'.format( args['type'], cls.datatypes)) subclass = cls.datatypes[args['type']] return subclass
def load(cls, args, strict=False): """Loads data from a dictionary into the corresponding YetiObject. Args: args: key:value dictionary with which to populate fields in the YetiObject """ try: if isinstance(args, list): return [cls.load(doc, strict=strict) for doc in args] return cls.load_object_from_type(args, strict=strict) except MarshmallowValidationError as e: raise ValidationError(e.messages)
def _stix_parse(self, stix_dict): """Parses a dictionary into an actual STIX2 SDO. Args: stix_dict: The dictionary to use to create the STIX obejct. Raises: ValidationError: If the dictionary does not comply with the STIX2 standard. """ if 'type' not in stix_dict: stix_dict['type'] = self.type try: self._stix_object = parse(stix_dict, allow_custom=True) except (MissingPropertiesError, ParseError) as err: raise ValidationError(str(err))
def _stix_parse(self, stix_dict): """Parses a dictionary into an actual STIX2 object. Args: stix_dict: The STIX dictionary to use to create the STIX obejct. Raises: ValidationError: If the dictionary does not comply with the STIX2 standard. """ if 'type' not in stix_dict: stix_dict['type'] = self.type try: self._stix_object = parse_observable(stix_dict) except (exceptions.MissingPropertiesError, exceptions.ParseError, exceptions.ExtraPropertiesError) as err: raise ValidationError(str(err))
def get_realschema(cls, obj): subtype = obj.get('type') if cls.datatypes and subtype not in cls.datatypes: raise ValidationError('{0:s} is not a valid type for {1:s}'.format( subtype, cls.__name__)) return cls.datatypes.get(obj.get('type'), cls).schema
def is_valid(self): if not isinstance(self.name, str): raise ValidationError('.name must be a string.') return True
def is_valid(self): Entity.is_valid(self) if not isinstance(self.family, list): raise ValidationError('.family must be a list of strings.') return True
def __init__(self, pattern=None, **_): try: re.compile(pattern) except re.error as e: raise ValidationError('{0:s} is not a valid regular expression:' ' {1:s}'.format(pattern, str(e)))
def handle_args(err): raise ValidationError(err.messages)
def handle_args(err, response, schema, error_status_code, error_headers): raise ValidationError(err.messages)
def is_valid(self): if not self.name or not isinstance(self.name, str): msg = 'Invalid \'name\' parameter (provided {0:s})'.format( repr(self.name)) raise ValidationError(msg) return True
def __init__(self, pattern=None, **_): try: yara.compile(source=pattern) except (yara.SyntaxError, yara.Error) as e: raise ValidationError('{0:s} is not a valid Yara rule: {1!s}'.format(pattern, e))
def handle_args(err, unused_response, unused_schema): raise ValidationError(err.messages)