index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
25,150
pymisp.api
upload_stix
Upload a STIX file to MISP. :param path: Path to the STIX on the disk (can be a path-like object, or a pseudofile) :param data: stix object :param version: Can be 1 or 2
def upload_stix(self, path: str | Path | BytesIO | StringIO | None = None, data: str | bytes | None = None, version: str = '2') -> requests.Response: """Upload a STIX file to MISP. :param path: Path to the STIX on the disk (can be a path-like object, or a pseudofile) :param data: stix object :param version: Can be 1 or 2 """ to_post: str | bytes if path is not None: if isinstance(path, (str, Path)): with open(path, 'rb') as f: to_post = f.read() else: to_post = path.read() elif data is not None: to_post = data else: raise MISPServerError("please fill path or data parameter") if str(version) == '1': url = urljoin(self.root_url, 'events/upload_stix') response = self._prepare_request('POST', url, data=to_post, output_type='xml', content_type='xml') else: url = urljoin(self.root_url, 'events/upload_stix/2') response = self._prepare_request('POST', url, data=to_post) return response
(self, path: Union[str, pathlib.Path, _io.BytesIO, _io.StringIO, NoneType] = None, data: Union[str, bytes, NoneType] = None, version: str = '2') -> requests.models.Response
25,151
pymisp.api
user_registrations
Get all the user registrations :param pythonify: Returns a list of PyMISP Objects instead of the plain json output. Warning: it might use a lot of RAM
def user_registrations(self, pythonify: bool = False) -> dict[str, Any] | list[MISPInbox] | list[dict[str, Any]]: """Get all the user registrations :param pythonify: Returns a list of PyMISP Objects instead of the plain json output. Warning: it might use a lot of RAM """ r = self._prepare_request('GET', 'users/registrations/index') registrations = self._check_json_response(r) if not (self.global_pythonify or pythonify) or isinstance(registrations, dict): return registrations to_return = [] for registration in registrations: i = MISPInbox() i.from_dict(**registration) to_return.append(i) return to_return
(self, pythonify: bool = False) -> dict[str, typing.Any] | list[pymisp.mispevent.MISPInbox] | list[dict[str, typing.Any]]
25,152
pymisp.api
user_settings
Get all the user settings: https://www.misp-project.org/openapi/#tag/UserSettings/operation/getUserSettings :param pythonify: Returns a list of PyMISP Objects instead of the plain json output. Warning: it might use a lot of RAM
def user_settings(self, pythonify: bool = False) -> dict[str, Any] | list[MISPUserSetting] | list[dict[str, Any]]: """Get all the user settings: https://www.misp-project.org/openapi/#tag/UserSettings/operation/getUserSettings :param pythonify: Returns a list of PyMISP Objects instead of the plain json output. Warning: it might use a lot of RAM """ r = self._prepare_request('GET', 'userSettings/index') user_settings = self._check_json_response(r) if not (self.global_pythonify or pythonify) or isinstance(user_settings, dict): return user_settings to_return = [] for user_setting in user_settings: u = MISPUserSetting() u.from_dict(**user_setting) to_return.append(u) return to_return
(self, pythonify: bool = False) -> dict[str, typing.Any] | list[pymisp.mispevent.MISPUserSetting] | list[dict[str, typing.Any]]
25,153
pymisp.api
users
Get all the users, or a filtered set of users: https://www.misp-project.org/openapi/#tag/Users/operation/getUsers :param search: The search to make against the list of users :param organisation: The ID of an organisation to filter against :param pythonify: Returns a list of PyMISP Objects instead of the plain json output. Warning: it might use a lot of RAM
def users(self, search: str | None = None, organisation: int | None = None, pythonify: bool = False) -> dict[str, Any] | list[MISPUser] | list[dict[str, Any]]: """Get all the users, or a filtered set of users: https://www.misp-project.org/openapi/#tag/Users/operation/getUsers :param search: The search to make against the list of users :param organisation: The ID of an organisation to filter against :param pythonify: Returns a list of PyMISP Objects instead of the plain json output. Warning: it might use a lot of RAM """ urlpath = 'admin/users/index' if search: urlpath += f'/value:{search}' if organisation: organisation_id = get_uuid_or_id_from_abstract_misp(organisation) urlpath += f"/searchorg:{organisation_id}" r = self._prepare_request('GET', urlpath) users = self._check_json_response(r) if not (self.global_pythonify or pythonify) or isinstance(users, dict): return users to_return = [] for user in users: u = MISPUser() u.from_dict(**user) to_return.append(u) return to_return
(self, search: Optional[str] = None, organisation: Optional[int] = None, pythonify: bool = False) -> dict[str, typing.Any] | list[pymisp.mispevent.MISPUser] | list[dict[str, typing.Any]]
25,154
pymisp.api
users_statistics
Get user statistics from the MISP instance :param context: one of 'data', 'orgs', 'users', 'tags', 'attributehistogram', 'sightings', 'galaxyMatrix'
def users_statistics(self, context: str = 'data') -> dict[str, Any] | list[dict[str, Any]]: """Get user statistics from the MISP instance :param context: one of 'data', 'orgs', 'users', 'tags', 'attributehistogram', 'sightings', 'galaxyMatrix' """ availables_contexts = ['data', 'orgs', 'users', 'tags', 'attributehistogram', 'sightings', 'galaxyMatrix'] if context not in availables_contexts: raise PyMISPError("context can only be {','.join(availables_contexts)}") response = self._prepare_request('GET', f'users/statistics/{context}') try: return self._check_json_response(response) except PyMISPError: return self._check_json_response(response)
(self, context: str = 'data') -> dict[str, typing.Any] | list[dict[str, typing.Any]]
25,155
pymisp.api
values_in_warninglist
Check if IOC values are in warninglist :param value: iterator with values to check
def values_in_warninglist(self, value: Iterable[str]) -> dict[str, Any] | list[dict[str, Any]]: """Check if IOC values are in warninglist :param value: iterator with values to check """ response = self._prepare_request('POST', 'warninglists/checkValue', data=value) try: return self._check_json_response(response) except PyMISPError: return self._check_json_response(response)
(self, value: Iterable[str]) -> dict[str, typing.Any] | list[dict[str, typing.Any]]
25,156
pymisp.api
warninglists
Get all the warninglists: https://www.misp-project.org/openapi/#tag/Warninglists/operation/getWarninglists :param pythonify: Returns a list of PyMISP Objects instead of the plain json output. Warning: it might use a lot of RAM
def warninglists(self, pythonify: bool = False) -> dict[str, Any] | list[MISPWarninglist]: """Get all the warninglists: https://www.misp-project.org/openapi/#tag/Warninglists/operation/getWarninglists :param pythonify: Returns a list of PyMISP Objects instead of the plain json output. Warning: it might use a lot of RAM """ r = self._prepare_request('GET', 'warninglists/index') warninglists = self._check_json_response(r) if not (self.global_pythonify or pythonify) or 'errors' in warninglists: return warninglists['Warninglists'] to_return = [] for warninglist in warninglists['Warninglists']: w = MISPWarninglist() w.from_dict(**warninglist) to_return.append(w) return to_return
(self, pythonify: bool = False) -> dict[str, typing.Any] | list[pymisp.mispevent.MISPWarninglist]
25,157
pymisp.exceptions
InvalidMISPObject
Exception raised when an object doesn't respect the contrains in the definition
class InvalidMISPObject(MISPObjectException): """Exception raised when an object doesn't respect the contrains in the definition""" pass
(message: 'str') -> 'None'
25,159
pymisp.mispevent
MISPAttribute
null
class MISPAttribute(AbstractMISP): _fields_for_feed: set[str] = {'uuid', 'value', 'category', 'type', 'comment', 'data', 'deleted', 'timestamp', 'to_ids', 'disable_correlation', 'first_seen', 'last_seen'} def __init__(self, describe_types: dict[str, Any] | None = None, strict: bool = False): """Represents an Attribute :param describe_types: Use it if you want to overwrite the default describeTypes.json file (you don't) :param strict: If false, fallback to sane defaults for the attribute type if the ones passed by the user are incorrect """ super().__init__() if describe_types: self.describe_types: dict[str, Any] = describe_types self.__categories: list[str] = self.describe_types['categories'] self.__category_type_mapping: dict[str, list[str]] = self.describe_types['category_type_mappings'] self.__sane_default: dict[str, dict[str, str | int]] = self.describe_types['sane_defaults'] self.__strict: bool = strict self.data: BytesIO | None = None self.first_seen: datetime self.last_seen: datetime self.uuid: str = str(uuid.uuid4()) self.ShadowAttribute: list[MISPShadowAttribute] = [] self.SharingGroup: MISPSharingGroup self.Sighting: list[MISPSighting] = [] self.Tag: list[MISPTag] = [] self.Galaxy: list[MISPGalaxy] = [] self.expand: str self.timestamp: float | int | datetime # For search self.Event: MISPEvent self.RelatedAttribute: list[MISPAttribute] # For malware sample self._malware_binary: BytesIO | None def add_tag(self, tag: str | MISPTag | dict[str, Any] | None = None, **kwargs) -> MISPTag: # type: ignore[no-untyped-def] return super()._add_tag(tag, **kwargs) @property def tags(self) -> list[MISPTag]: """Returns a list of tags associated to this Attribute""" return self.Tag @tags.setter def tags(self, tags: list[MISPTag]) -> None: """Set a list of prepared MISPTag.""" super()._set_tags(tags) def add_galaxy(self, galaxy: MISPGalaxy | dict[str, Any] | None = None, **kwargs) -> MISPGalaxy: # type: ignore[no-untyped-def] """Add a galaxy to the Attribute, either by passing a MISPGalaxy or a dictionary""" if isinstance(galaxy, MISPGalaxy): self.galaxies.append(galaxy) return galaxy if isinstance(galaxy, dict): misp_galaxy = MISPGalaxy() misp_galaxy.from_dict(**galaxy) elif kwargs: misp_galaxy = MISPGalaxy() misp_galaxy.from_dict(**kwargs) else: raise InvalidMISPGalaxy("A Galaxy to add to an existing Attribute needs to be either a MISPGalaxy or a plain python dictionary") self.galaxies.append(misp_galaxy) return misp_galaxy @property def galaxies(self) -> list[MISPGalaxy]: """Returns a list of galaxies associated to this Attribute""" return self.Galaxy def _prepare_data(self, data: Path | str | bytes | BytesIO | None) -> None: if not data: super().__setattr__('data', None) return if isinstance(data, BytesIO): super().__setattr__('data', data) elif isinstance(data, Path): with data.open('rb') as f_temp: super().__setattr__('data', BytesIO(f_temp.read())) elif isinstance(data, (str, bytes)): super().__setattr__('data', BytesIO(base64.b64decode(data))) else: raise PyMISPError(f'Invalid type ({type(data)}) for the data key: {data}') if self.type == 'malware-sample': try: # Ignore type, if data is None -> exception with ZipFile(self.data) as f: # type: ignore if not self.__is_misp_encrypted_file(f): raise PyMISPError('Not an existing malware sample') for name in f.namelist(): if name.endswith('.filename.txt'): with f.open(name, pwd=b'infected') as unpacked: self.malware_filename = unpacked.read().decode().strip() else: # decrypting a zipped file is extremely slow. We do it on-demand in self.malware_binary continue except Exception: # not a encrypted zip file, assuming it is a new malware sample self._prepare_new_malware_sample() def __setattr__(self, name: str, value: Any) -> None: if name in ['first_seen', 'last_seen']: _datetime = _make_datetime(value) # NOTE: the two following should be exceptions, but there are existing events in this state, # And we cannot dump them if it is there. if name == 'last_seen' and hasattr(self, 'first_seen') and self.first_seen > _datetime: logger.warning(f'last_seen ({value}) has to be after first_seen ({self.first_seen})') if name == 'first_seen' and hasattr(self, 'last_seen') and self.last_seen < _datetime: logger.warning(f'first_seen ({value}) has to be before last_seen ({self.last_seen})') super().__setattr__(name, _datetime) elif name == 'data': self._prepare_data(value) else: super().__setattr__(name, value) def hash_values(self, algorithm: str = 'sha512') -> list[str]: """Compute the hash of every value for fast lookups""" if algorithm not in hashlib.algorithms_available: raise PyMISPError(f'The algorithm {algorithm} is not available for hashing.') if '|' in self.type or self.type == 'malware-sample': hashes = [] for v in self.value.split('|'): h = hashlib.new(algorithm) h.update(v.encode("utf-8")) hashes.append(h.hexdigest()) return hashes else: h = hashlib.new(algorithm) to_encode = self.value if not isinstance(to_encode, str): to_encode = str(to_encode) h.update(to_encode.encode("utf-8")) return [h.hexdigest()] def _set_default(self) -> None: if not hasattr(self, 'comment'): self.comment = '' if not hasattr(self, 'timestamp'): self.timestamp = datetime.timestamp(datetime.now()) def _to_feed(self, with_distribution: bool=False) -> dict[str, Any]: if with_distribution: self._fields_for_feed.add('distribution') to_return = super()._to_feed() if self.data: to_return['data'] = base64.b64encode(self.data.getvalue()).decode() if self.tags: to_return['Tag'] = list(filter(None, [tag._to_feed() for tag in self.tags])) if with_distribution: try: to_return['SharingGroup'] = self.SharingGroup._to_feed() except AttributeError: pass return to_return @property def known_types(self) -> list[str]: """Returns a list of all the known MISP attributes types""" return self.describe_types['types'] @property def malware_binary(self) -> BytesIO | None: """Returns a BytesIO of the malware, if the attribute has one. Decrypts, unpacks and caches the binary on the first invocation, which may require some time for large attachments (~1s/MB). """ if self.type != 'malware-sample': # Not a malware sample return None if hasattr(self, '_malware_binary'): # Already unpacked return self._malware_binary elif hasattr(self, 'malware_filename'): # Have a binary, but didn't decrypt it yet with ZipFile(self.data) as f: # type: ignore for name in f.namelist(): if not name.endswith('.filename.txt'): with f.open(name, pwd=b'infected') as unpacked: self._malware_binary = BytesIO(unpacked.read()) return self._malware_binary return None @property def shadow_attributes(self) -> list[MISPShadowAttribute]: return self.ShadowAttribute @shadow_attributes.setter def shadow_attributes(self, shadow_attributes: list[MISPShadowAttribute]) -> None: """Set a list of prepared MISPShadowAttribute.""" if all(isinstance(x, MISPShadowAttribute) for x in shadow_attributes): self.ShadowAttribute = shadow_attributes else: raise PyMISPError('All the attributes have to be of type MISPShadowAttribute.') @property def sightings(self) -> list[MISPSighting]: return self.Sighting @sightings.setter def sightings(self, sightings: list[MISPSighting]) -> None: """Set a list of prepared MISPSighting.""" if all(isinstance(x, MISPSighting) for x in sightings): self.Sighting = sightings else: raise PyMISPError('All the attributes have to be of type MISPSighting.') def delete(self) -> None: """Mark the attribute as deleted (soft delete)""" self.deleted = True def add_proposal(self, shadow_attribute=None, **kwargs) -> MISPShadowAttribute: # type: ignore[no-untyped-def] """Alias for add_shadow_attribute""" return self.add_shadow_attribute(shadow_attribute, **kwargs) def add_shadow_attribute(self, shadow_attribute: MISPShadowAttribute | dict[str, Any] | None = None, **kwargs) -> MISPShadowAttribute: # type: ignore[no-untyped-def] """Add a shadow attribute to the attribute (by name or a MISPShadowAttribute object)""" if isinstance(shadow_attribute, MISPShadowAttribute): misp_shadow_attribute = shadow_attribute elif isinstance(shadow_attribute, dict): misp_shadow_attribute = MISPShadowAttribute() misp_shadow_attribute.from_dict(**shadow_attribute) elif kwargs: misp_shadow_attribute = MISPShadowAttribute() misp_shadow_attribute.from_dict(**kwargs) else: raise PyMISPError(f"The shadow_attribute is in an invalid format (can be either string, MISPShadowAttribute, or an expanded dict[str, Any]): {shadow_attribute}") self.shadow_attributes.append(misp_shadow_attribute) self.edited = True return misp_shadow_attribute def add_sighting(self, sighting: MISPSighting | dict[str, Any] | None = None, **kwargs) -> MISPSighting: # type: ignore[no-untyped-def] """Add a sighting to the attribute (by name or a MISPSighting object)""" if isinstance(sighting, MISPSighting): misp_sighting = sighting elif isinstance(sighting, dict): misp_sighting = MISPSighting() misp_sighting.from_dict(**sighting) elif kwargs: misp_sighting = MISPSighting() misp_sighting.from_dict(**kwargs) else: raise PyMISPError(f"The sighting is in an invalid format (can be either string, MISPShadowAttribute, or an expanded dict[str, Any]): {sighting}") self.sightings.append(misp_sighting) self.edited = True return misp_sighting def from_dict(self, **kwargs) -> None: # type: ignore[no-untyped-def] if 'Attribute' in kwargs: kwargs = kwargs['Attribute'] if kwargs.get('type') and kwargs.get('category'): if kwargs['type'] not in self.__category_type_mapping[kwargs['category']]: if self.__strict: raise NewAttributeError('{} and {} is an invalid combination, type for this category has to be in {}'.format( kwargs.get('type'), kwargs.get('category'), (', '.join(self.__category_type_mapping[kwargs['category']])))) else: kwargs.pop('category', None) self.type = kwargs.pop('type', None) # Required if self.type is None: raise NewAttributeError('The type of the attribute is required.') if self.type not in self.known_types: raise NewAttributeError('{} is invalid, type has to be in {}'.format(self.type, (', '.join(self.known_types)))) type_defaults = self.__sane_default[self.type] self.value = kwargs.pop('value', None) if self.value is None: raise NewAttributeError('The value of the attribute is required.') if self.type == 'datetime' and isinstance(self.value, str): try: # Faster if sys.version_info >= (3, 7): self.value = datetime.fromisoformat(self.value) else: if '+' in self.value or '-' in self.value: self.value = datetime.strptime(self.value, "%Y-%m-%dT%H:%M:%S.%f%z") elif '.' in self.value: self.value = datetime.strptime(self.value, "%Y-%m-%dT%H:%M:%S.%f") else: self.value = datetime.strptime(self.value, "%Y-%m-%dT%H:%M:%S") except ValueError: # Slower, but if the other ones fail, that's a good fallback self.value = parse(self.value) # Default values self.category = kwargs.pop('category', type_defaults['default_category']) if self.category is None: # In case the category key is passed, but None self.category = type_defaults['default_category'] if self.category not in self.__categories: raise NewAttributeError('{} is invalid, category has to be in {}'.format(self.category, (', '.join(self.__categories)))) self.to_ids = kwargs.pop('to_ids', bool(int(type_defaults['to_ids']))) if self.to_ids is None: self.to_ids = bool(int(type_defaults['to_ids'])) else: self.to_ids = make_bool(self.to_ids) if not isinstance(self.to_ids, bool): raise NewAttributeError(f'{self.to_ids} is invalid, to_ids has to be True or False') self.distribution = kwargs.pop('distribution', None) if self.distribution is not None: self.distribution = int(self.distribution) if self.distribution not in [0, 1, 2, 3, 4, 5]: raise NewAttributeError(f'{self.distribution} is invalid, the distribution has to be in 0, 1, 2, 3, 4, 5') # other possible values if kwargs.get('data'): self.data = kwargs.pop('data') if kwargs.get('id'): self.id = int(kwargs.pop('id')) if kwargs.get('event_id'): self.event_id = int(kwargs.pop('event_id')) if kwargs.get('timestamp'): ts = kwargs.pop('timestamp') if isinstance(ts, datetime): self.timestamp = ts else: self.timestamp = datetime.fromtimestamp(int(ts), timezone.utc) if kwargs.get('first_seen'): fs = kwargs.pop('first_seen') try: # Faster self.first_seen = datetime.fromisoformat(fs) except Exception: # Use __setattr__ self.first_seen = fs if kwargs.get('last_seen'): ls = kwargs.pop('last_seen') try: # Faster self.last_seen = datetime.fromisoformat(ls) except Exception: # Use __setattr__ self.last_seen = ls if kwargs.get('sharing_group_id'): self.sharing_group_id = int(kwargs.pop('sharing_group_id')) if self.distribution == 4: # The distribution is set to sharing group, a sharing_group_id is required. if not hasattr(self, 'sharing_group_id'): raise NewAttributeError('If the distribution is set to sharing group, a sharing group ID is required.') elif not self.sharing_group_id: # Cannot be None or 0 either. raise NewAttributeError(f'If the distribution is set to sharing group, a sharing group ID is required (cannot be {self.sharing_group_id}).') if kwargs.get('Tag'): [self.add_tag(tag) for tag in kwargs.pop('Tag')] if kwargs.get('Galaxy'): [self.add_galaxy(galaxy) for galaxy in kwargs.pop('Galaxy')] if kwargs.get('Sighting'): [self.add_sighting(sighting) for sighting in kwargs.pop('Sighting')] if kwargs.get('ShadowAttribute'): [self.add_shadow_attribute(s_attr) for s_attr in kwargs.pop('ShadowAttribute')] if kwargs.get('SharingGroup'): self.SharingGroup = MISPSharingGroup() self.SharingGroup.from_dict(**kwargs.pop('SharingGroup')) # If the user wants to disable correlation, let them. Defaults to False. self.disable_correlation = kwargs.pop("disable_correlation", False) if self.disable_correlation is None: self.disable_correlation = False super().from_dict(**kwargs) def to_dict(self, json_format: bool = False) -> dict[str, Any]: to_return = super().to_dict(json_format) if self.data: to_return['data'] = base64.b64encode(self.data.getvalue()).decode() return to_return def _prepare_new_malware_sample(self) -> None: if '|' in self.value: # Get the filename, ignore the md5, because humans. self.malware_filename, md5 = self.value.rsplit('|', 1) else: # Assuming the user only passed the filename self.malware_filename = self.value self.value = self.malware_filename self._malware_binary = self.data self.encrypt = True def __is_misp_encrypted_file(self, f: ZipFile) -> bool: files_list = f.namelist() if len(files_list) != 2: return False md5_from_filename = '' md5_from_file = '' for name in files_list: if name.endswith('.filename.txt'): md5_from_filename = name.replace('.filename.txt', '') else: md5_from_file = name if not md5_from_filename or not md5_from_file or md5_from_filename != md5_from_file: return False return True def __repr__(self) -> str: if hasattr(self, 'value'): return '<{self.__class__.__name__}(type={self.type}, value={self.value})'.format(self=self) return f'<{self.__class__.__name__}(NotInitialized)'
(describe_types: 'dict[str, Any] | None' = None, strict: 'bool' = False)
25,160
pymisp.mispevent
__is_misp_encrypted_file
null
def __is_misp_encrypted_file(self, f: ZipFile) -> bool: files_list = f.namelist() if len(files_list) != 2: return False md5_from_filename = '' md5_from_file = '' for name in files_list: if name.endswith('.filename.txt'): md5_from_filename = name.replace('.filename.txt', '') else: md5_from_file = name if not md5_from_filename or not md5_from_file or md5_from_filename != md5_from_file: return False return True
(self, f: zipfile.ZipFile) -> bool
25,165
pymisp.mispevent
__init__
Represents an Attribute :param describe_types: Use it if you want to overwrite the default describeTypes.json file (you don't) :param strict: If false, fallback to sane defaults for the attribute type if the ones passed by the user are incorrect
def __init__(self, describe_types: dict[str, Any] | None = None, strict: bool = False): """Represents an Attribute :param describe_types: Use it if you want to overwrite the default describeTypes.json file (you don't) :param strict: If false, fallback to sane defaults for the attribute type if the ones passed by the user are incorrect """ super().__init__() if describe_types: self.describe_types: dict[str, Any] = describe_types self.__categories: list[str] = self.describe_types['categories'] self.__category_type_mapping: dict[str, list[str]] = self.describe_types['category_type_mappings'] self.__sane_default: dict[str, dict[str, str | int]] = self.describe_types['sane_defaults'] self.__strict: bool = strict self.data: BytesIO | None = None self.first_seen: datetime self.last_seen: datetime self.uuid: str = str(uuid.uuid4()) self.ShadowAttribute: list[MISPShadowAttribute] = [] self.SharingGroup: MISPSharingGroup self.Sighting: list[MISPSighting] = [] self.Tag: list[MISPTag] = [] self.Galaxy: list[MISPGalaxy] = [] self.expand: str self.timestamp: float | int | datetime # For search self.Event: MISPEvent self.RelatedAttribute: list[MISPAttribute] # For malware sample self._malware_binary: BytesIO | None
(self, describe_types: Optional[dict[str, Any]] = None, strict: bool = False)
25,168
pymisp.mispevent
__repr__
null
def __repr__(self) -> str: if hasattr(self, 'value'): return '<{self.__class__.__name__}(type={self.type}, value={self.value})'.format(self=self) return f'<{self.__class__.__name__}(NotInitialized)'
(self) -> str
25,169
pymisp.mispevent
__setattr__
null
def __setattr__(self, name: str, value: Any) -> None: if name in ['first_seen', 'last_seen']: _datetime = _make_datetime(value) # NOTE: the two following should be exceptions, but there are existing events in this state, # And we cannot dump them if it is there. if name == 'last_seen' and hasattr(self, 'first_seen') and self.first_seen > _datetime: logger.warning(f'last_seen ({value}) has to be after first_seen ({self.first_seen})') if name == 'first_seen' and hasattr(self, 'last_seen') and self.last_seen < _datetime: logger.warning(f'first_seen ({value}) has to be before last_seen ({self.last_seen})') super().__setattr__(name, _datetime) elif name == 'data': self._prepare_data(value) else: super().__setattr__(name, value)
(self, name: str, value: Any) -> NoneType
25,173
pymisp.mispevent
_prepare_data
null
def _prepare_data(self, data: Path | str | bytes | BytesIO | None) -> None: if not data: super().__setattr__('data', None) return if isinstance(data, BytesIO): super().__setattr__('data', data) elif isinstance(data, Path): with data.open('rb') as f_temp: super().__setattr__('data', BytesIO(f_temp.read())) elif isinstance(data, (str, bytes)): super().__setattr__('data', BytesIO(base64.b64decode(data))) else: raise PyMISPError(f'Invalid type ({type(data)}) for the data key: {data}') if self.type == 'malware-sample': try: # Ignore type, if data is None -> exception with ZipFile(self.data) as f: # type: ignore if not self.__is_misp_encrypted_file(f): raise PyMISPError('Not an existing malware sample') for name in f.namelist(): if name.endswith('.filename.txt'): with f.open(name, pwd=b'infected') as unpacked: self.malware_filename = unpacked.read().decode().strip() else: # decrypting a zipped file is extremely slow. We do it on-demand in self.malware_binary continue except Exception: # not a encrypted zip file, assuming it is a new malware sample self._prepare_new_malware_sample()
(self, data: pathlib.Path | str | bytes | _io.BytesIO | None) -> NoneType
25,174
pymisp.mispevent
_prepare_new_malware_sample
null
def _prepare_new_malware_sample(self) -> None: if '|' in self.value: # Get the filename, ignore the md5, because humans. self.malware_filename, md5 = self.value.rsplit('|', 1) else: # Assuming the user only passed the filename self.malware_filename = self.value self.value = self.malware_filename self._malware_binary = self.data self.encrypt = True
(self) -> NoneType
25,178
pymisp.mispevent
_to_feed
null
def _to_feed(self, with_distribution: bool=False) -> dict[str, Any]: if with_distribution: self._fields_for_feed.add('distribution') to_return = super()._to_feed() if self.data: to_return['data'] = base64.b64encode(self.data.getvalue()).decode() if self.tags: to_return['Tag'] = list(filter(None, [tag._to_feed() for tag in self.tags])) if with_distribution: try: to_return['SharingGroup'] = self.SharingGroup._to_feed() except AttributeError: pass return to_return
(self, with_distribution: bool = False) -> dict[str, typing.Any]
25,179
pymisp.mispevent
add_galaxy
Add a galaxy to the Attribute, either by passing a MISPGalaxy or a dictionary
def add_galaxy(self, galaxy: MISPGalaxy | dict[str, Any] | None = None, **kwargs) -> MISPGalaxy: # type: ignore[no-untyped-def] """Add a galaxy to the Attribute, either by passing a MISPGalaxy or a dictionary""" if isinstance(galaxy, MISPGalaxy): self.galaxies.append(galaxy) return galaxy if isinstance(galaxy, dict): misp_galaxy = MISPGalaxy() misp_galaxy.from_dict(**galaxy) elif kwargs: misp_galaxy = MISPGalaxy() misp_galaxy.from_dict(**kwargs) else: raise InvalidMISPGalaxy("A Galaxy to add to an existing Attribute needs to be either a MISPGalaxy or a plain python dictionary") self.galaxies.append(misp_galaxy) return misp_galaxy
(self, galaxy: Union[pymisp.mispevent.MISPGalaxy, dict[str, Any], NoneType] = None, **kwargs) -> pymisp.mispevent.MISPGalaxy
25,180
pymisp.mispevent
add_proposal
Alias for add_shadow_attribute
def add_proposal(self, shadow_attribute=None, **kwargs) -> MISPShadowAttribute: # type: ignore[no-untyped-def] """Alias for add_shadow_attribute""" return self.add_shadow_attribute(shadow_attribute, **kwargs)
(self, shadow_attribute=None, **kwargs) -> pymisp.mispevent.MISPShadowAttribute
25,181
pymisp.mispevent
add_shadow_attribute
Add a shadow attribute to the attribute (by name or a MISPShadowAttribute object)
def add_shadow_attribute(self, shadow_attribute: MISPShadowAttribute | dict[str, Any] | None = None, **kwargs) -> MISPShadowAttribute: # type: ignore[no-untyped-def] """Add a shadow attribute to the attribute (by name or a MISPShadowAttribute object)""" if isinstance(shadow_attribute, MISPShadowAttribute): misp_shadow_attribute = shadow_attribute elif isinstance(shadow_attribute, dict): misp_shadow_attribute = MISPShadowAttribute() misp_shadow_attribute.from_dict(**shadow_attribute) elif kwargs: misp_shadow_attribute = MISPShadowAttribute() misp_shadow_attribute.from_dict(**kwargs) else: raise PyMISPError(f"The shadow_attribute is in an invalid format (can be either string, MISPShadowAttribute, or an expanded dict[str, Any]): {shadow_attribute}") self.shadow_attributes.append(misp_shadow_attribute) self.edited = True return misp_shadow_attribute
(self, shadow_attribute: Union[pymisp.mispevent.MISPShadowAttribute, dict[str, Any], NoneType] = None, **kwargs) -> pymisp.mispevent.MISPShadowAttribute
25,182
pymisp.mispevent
add_sighting
Add a sighting to the attribute (by name or a MISPSighting object)
def add_sighting(self, sighting: MISPSighting | dict[str, Any] | None = None, **kwargs) -> MISPSighting: # type: ignore[no-untyped-def] """Add a sighting to the attribute (by name or a MISPSighting object)""" if isinstance(sighting, MISPSighting): misp_sighting = sighting elif isinstance(sighting, dict): misp_sighting = MISPSighting() misp_sighting.from_dict(**sighting) elif kwargs: misp_sighting = MISPSighting() misp_sighting.from_dict(**kwargs) else: raise PyMISPError(f"The sighting is in an invalid format (can be either string, MISPShadowAttribute, or an expanded dict[str, Any]): {sighting}") self.sightings.append(misp_sighting) self.edited = True return misp_sighting
(self, sighting: Union[pymisp.mispevent.MISPSighting, dict[str, Any], NoneType] = None, **kwargs) -> pymisp.mispevent.MISPSighting
25,183
pymisp.mispevent
add_tag
null
def add_tag(self, tag: str | MISPTag | dict[str, Any] | None = None, **kwargs) -> MISPTag: # type: ignore[no-untyped-def] return super()._add_tag(tag, **kwargs)
(self, tag: Union[str, pymisp.abstract.MISPTag, dict[str, Any], NoneType] = None, **kwargs) -> pymisp.abstract.MISPTag
25,185
pymisp.mispevent
delete
Mark the attribute as deleted (soft delete)
def delete(self) -> None: """Mark the attribute as deleted (soft delete)""" self.deleted = True
(self) -> NoneType
25,186
pymisp.mispevent
from_dict
null
def from_dict(self, **kwargs) -> None: # type: ignore[no-untyped-def] if 'Attribute' in kwargs: kwargs = kwargs['Attribute'] if kwargs.get('type') and kwargs.get('category'): if kwargs['type'] not in self.__category_type_mapping[kwargs['category']]: if self.__strict: raise NewAttributeError('{} and {} is an invalid combination, type for this category has to be in {}'.format( kwargs.get('type'), kwargs.get('category'), (', '.join(self.__category_type_mapping[kwargs['category']])))) else: kwargs.pop('category', None) self.type = kwargs.pop('type', None) # Required if self.type is None: raise NewAttributeError('The type of the attribute is required.') if self.type not in self.known_types: raise NewAttributeError('{} is invalid, type has to be in {}'.format(self.type, (', '.join(self.known_types)))) type_defaults = self.__sane_default[self.type] self.value = kwargs.pop('value', None) if self.value is None: raise NewAttributeError('The value of the attribute is required.') if self.type == 'datetime' and isinstance(self.value, str): try: # Faster if sys.version_info >= (3, 7): self.value = datetime.fromisoformat(self.value) else: if '+' in self.value or '-' in self.value: self.value = datetime.strptime(self.value, "%Y-%m-%dT%H:%M:%S.%f%z") elif '.' in self.value: self.value = datetime.strptime(self.value, "%Y-%m-%dT%H:%M:%S.%f") else: self.value = datetime.strptime(self.value, "%Y-%m-%dT%H:%M:%S") except ValueError: # Slower, but if the other ones fail, that's a good fallback self.value = parse(self.value) # Default values self.category = kwargs.pop('category', type_defaults['default_category']) if self.category is None: # In case the category key is passed, but None self.category = type_defaults['default_category'] if self.category not in self.__categories: raise NewAttributeError('{} is invalid, category has to be in {}'.format(self.category, (', '.join(self.__categories)))) self.to_ids = kwargs.pop('to_ids', bool(int(type_defaults['to_ids']))) if self.to_ids is None: self.to_ids = bool(int(type_defaults['to_ids'])) else: self.to_ids = make_bool(self.to_ids) if not isinstance(self.to_ids, bool): raise NewAttributeError(f'{self.to_ids} is invalid, to_ids has to be True or False') self.distribution = kwargs.pop('distribution', None) if self.distribution is not None: self.distribution = int(self.distribution) if self.distribution not in [0, 1, 2, 3, 4, 5]: raise NewAttributeError(f'{self.distribution} is invalid, the distribution has to be in 0, 1, 2, 3, 4, 5') # other possible values if kwargs.get('data'): self.data = kwargs.pop('data') if kwargs.get('id'): self.id = int(kwargs.pop('id')) if kwargs.get('event_id'): self.event_id = int(kwargs.pop('event_id')) if kwargs.get('timestamp'): ts = kwargs.pop('timestamp') if isinstance(ts, datetime): self.timestamp = ts else: self.timestamp = datetime.fromtimestamp(int(ts), timezone.utc) if kwargs.get('first_seen'): fs = kwargs.pop('first_seen') try: # Faster self.first_seen = datetime.fromisoformat(fs) except Exception: # Use __setattr__ self.first_seen = fs if kwargs.get('last_seen'): ls = kwargs.pop('last_seen') try: # Faster self.last_seen = datetime.fromisoformat(ls) except Exception: # Use __setattr__ self.last_seen = ls if kwargs.get('sharing_group_id'): self.sharing_group_id = int(kwargs.pop('sharing_group_id')) if self.distribution == 4: # The distribution is set to sharing group, a sharing_group_id is required. if not hasattr(self, 'sharing_group_id'): raise NewAttributeError('If the distribution is set to sharing group, a sharing group ID is required.') elif not self.sharing_group_id: # Cannot be None or 0 either. raise NewAttributeError(f'If the distribution is set to sharing group, a sharing group ID is required (cannot be {self.sharing_group_id}).') if kwargs.get('Tag'): [self.add_tag(tag) for tag in kwargs.pop('Tag')] if kwargs.get('Galaxy'): [self.add_galaxy(galaxy) for galaxy in kwargs.pop('Galaxy')] if kwargs.get('Sighting'): [self.add_sighting(sighting) for sighting in kwargs.pop('Sighting')] if kwargs.get('ShadowAttribute'): [self.add_shadow_attribute(s_attr) for s_attr in kwargs.pop('ShadowAttribute')] if kwargs.get('SharingGroup'): self.SharingGroup = MISPSharingGroup() self.SharingGroup.from_dict(**kwargs.pop('SharingGroup')) # If the user wants to disable correlation, let them. Defaults to False. self.disable_correlation = kwargs.pop("disable_correlation", False) if self.disable_correlation is None: self.disable_correlation = False super().from_dict(**kwargs)
(self, **kwargs) -> NoneType
25,189
pymisp.mispevent
hash_values
Compute the hash of every value for fast lookups
def hash_values(self, algorithm: str = 'sha512') -> list[str]: """Compute the hash of every value for fast lookups""" if algorithm not in hashlib.algorithms_available: raise PyMISPError(f'The algorithm {algorithm} is not available for hashing.') if '|' in self.type or self.type == 'malware-sample': hashes = [] for v in self.value.split('|'): h = hashlib.new(algorithm) h.update(v.encode("utf-8")) hashes.append(h.hexdigest()) return hashes else: h = hashlib.new(algorithm) to_encode = self.value if not isinstance(to_encode, str): to_encode = str(to_encode) h.update(to_encode.encode("utf-8")) return [h.hexdigest()]
(self, algorithm: str = 'sha512') -> list[str]
25,197
pymisp.mispevent
to_dict
null
def to_dict(self, json_format: bool = False) -> dict[str, Any]: to_return = super().to_dict(json_format) if self.data: to_return['data'] = base64.b64encode(self.data.getvalue()).decode() return to_return
(self, json_format: bool = False) -> dict[str, typing.Any]
25,202
pymisp.mispevent
MISPCorrelationExclusion
null
class MISPCorrelationExclusion(AbstractMISP): def from_dict(self, **kwargs) -> None: # type: ignore[no-untyped-def] if 'CorrelationExclusion' in kwargs: kwargs = kwargs['CorrelationExclusion'] super().from_dict(**kwargs)
(**kwargs) -> 'None'
25,219
pymisp.mispevent
from_dict
null
def from_dict(self, **kwargs) -> None: # type: ignore[no-untyped-def] if 'CorrelationExclusion' in kwargs: kwargs = kwargs['CorrelationExclusion'] super().from_dict(**kwargs)
(self, **kwargs) -> NoneType
25,234
pymisp.mispevent
MISPDecayingModel
null
class MISPDecayingModel(AbstractMISP): def __init__(self, **kwargs: dict[str, Any]) -> None: super().__init__(**kwargs) self.uuid: str self.id: int def from_dict(self, **kwargs) -> None: # type: ignore[no-untyped-def] if 'DecayingModel' in kwargs: kwargs = kwargs['DecayingModel'] super().from_dict(**kwargs) def __repr__(self) -> str: return f'<{self.__class__.__name__}(uuid={self.uuid})>'
(**kwargs: 'dict[str, Any]') -> 'None'
25,239
pymisp.mispevent
__init__
null
def __init__(self, **kwargs: dict[str, Any]) -> None: super().__init__(**kwargs) self.uuid: str self.id: int
(self, **kwargs: dict[str, typing.Any]) -> NoneType
25,242
pymisp.mispevent
__repr__
null
def __repr__(self) -> str: return f'<{self.__class__.__name__}(uuid={self.uuid})>'
(self) -> str
25,251
pymisp.mispevent
from_dict
null
def from_dict(self, **kwargs) -> None: # type: ignore[no-untyped-def] if 'DecayingModel' in kwargs: kwargs = kwargs['DecayingModel'] super().from_dict(**kwargs)
(self, **kwargs) -> NoneType
25,266
pymisp.abstract
MISPEncode
null
class MISPEncode(JSONEncoder): def default(self, obj: Any) -> dict[str, Any] | str: if isinstance(obj, AbstractMISP): return obj.jsonable() elif isinstance(obj, (datetime, date)): return obj.isoformat() elif isinstance(obj, Enum): return obj.value elif isinstance(obj, UUID): return str(obj) return JSONEncoder.default(self, obj)
(*args, **kwargs)
25,268
deprecated.classic
wrapped_cls
null
def __call__(self, wrapped): """ Decorate your class or function. :param wrapped: Wrapped class or function. :return: the decorated class or function. .. versionchanged:: 1.2.4 Don't pass arguments to :meth:`object.__new__` (other than *cls*). .. versionchanged:: 1.2.8 The warning filter is not set if the *action* parameter is ``None`` or empty. """ if inspect.isclass(wrapped): old_new1 = wrapped.__new__ def wrapped_cls(cls, *args, **kwargs): msg = self.get_deprecated_msg(wrapped, None) if self.action: with warnings.catch_warnings(): warnings.simplefilter(self.action, self.category) warnings.warn(msg, category=self.category, stacklevel=_class_stacklevel) else: warnings.warn(msg, category=self.category, stacklevel=_class_stacklevel) if old_new1 is object.__new__: return old_new1(cls) # actually, we don't know the real signature of *old_new1* return old_new1(cls, *args, **kwargs) wrapped.__new__ = staticmethod(wrapped_cls) return wrapped
(cls, *args, **kwargs)
25,269
pymisp.abstract
default
null
def default(self, obj: Any) -> dict[str, Any] | str: if isinstance(obj, AbstractMISP): return obj.jsonable() elif isinstance(obj, (datetime, date)): return obj.isoformat() elif isinstance(obj, Enum): return obj.value elif isinstance(obj, UUID): return str(obj) return JSONEncoder.default(self, obj)
(self, obj: Any) -> dict[str, typing.Any] | str
25,272
pymisp.mispevent
MISPEvent
null
class MISPEvent(AbstractMISP): _fields_for_feed: set[str] = {'uuid', 'info', 'threat_level_id', 'analysis', 'timestamp', 'publish_timestamp', 'published', 'date', 'extends_uuid'} def __init__(self, describe_types: dict[str, Any] | None = None, strict_validation: bool = False, **kwargs) -> None: # type: ignore[no-untyped-def] super().__init__(**kwargs) self.__schema_file = 'schema.json' if strict_validation else 'schema-lax.json' if describe_types: # This variable is used in add_attribute in order to avoid duplicating the structure self.describe_types = describe_types self.uuid: str = str(uuid.uuid4()) self.date: date self.Attribute: list[MISPAttribute] = [] self.Object: list[MISPObject] = [] self.RelatedEvent: list[MISPEvent] = [] self.ShadowAttribute: list[MISPShadowAttribute] = [] self.SharingGroup: MISPSharingGroup self.EventReport: list[MISPEventReport] = [] self.Tag: list[MISPTag] = [] self.Galaxy: list[MISPGalaxy] = [] self.publish_timestamp: float | int | datetime self.timestamp: float | int | datetime def add_tag(self, tag: str | MISPTag | dict[str, Any] | None = None, **kwargs) -> MISPTag: # type: ignore[no-untyped-def] return super()._add_tag(tag, **kwargs) @property def tags(self) -> list[MISPTag]: """Returns a list of tags associated to this Event""" return self.Tag @tags.setter def tags(self, tags: list[MISPTag]) -> None: """Set a list of prepared MISPTag.""" super()._set_tags(tags) def _set_default(self) -> None: """There are a few keys that could, or need to be set by default for the feed generator""" if not hasattr(self, 'published'): self.published = True if not hasattr(self, 'uuid'): self.uuid = str(uuid.uuid4()) if not hasattr(self, 'extends_uuid'): self.extends_uuid = '' if not hasattr(self, 'date'): self.set_date(date.today()) if not hasattr(self, 'timestamp'): self.timestamp = datetime.timestamp(datetime.now()) if not hasattr(self, 'publish_timestamp'): self.publish_timestamp = datetime.timestamp(datetime.now()) if not hasattr(self, 'analysis'): # analysis: 0 means initial, 1 ongoing, 2 completed self.analysis = 2 if not hasattr(self, 'threat_level_id'): # threat_level_id 4 means undefined. Tags are recommended. self.threat_level_id = 4 @property def manifest(self) -> dict[str, Any]: required = ['info', 'Orgc'] for r in required: if not hasattr(self, r): raise PyMISPError('The field {} is required to generate the event manifest.') self._set_default() return { self.uuid: { 'Orgc': self.Orgc._to_feed(), 'Tag': list(filter(None, [tag._to_feed() for tag in self.tags])), 'info': self.info, 'date': self.date.isoformat(), 'analysis': self.analysis, 'threat_level_id': self.threat_level_id, 'timestamp': self._datetime_to_timestamp(self.timestamp) } } def attributes_hashes(self, algorithm: str = 'sha512') -> list[str]: to_return: list[str] = [] for attribute in self.attributes: to_return += attribute.hash_values(algorithm) for obj in self.objects: for attribute in obj.attributes: to_return += attribute.hash_values(algorithm) return to_return def to_feed(self, valid_distributions: list[int] = [0, 1, 2, 3, 4, 5], with_meta: bool = False, with_distribution: bool=False, with_local_tags: bool = True, with_event_reports: bool = True) -> dict[str, Any]: """ Generate a json output for MISP Feed. :param valid_distributions: only makes sense if the distribution key is set; i.e., the event is exported from a MISP instance. :param with_distribution: exports distribution and Sharing Group info; otherwise all SharingGroup information is discarded (protecting privacy) :param with_local_tags: tag export includes local exportable tags along with global exportable tags :param with_event_reports: include event reports in the returned MISP event """ required = ['info', 'Orgc'] for r in required: if not hasattr(self, r): raise PyMISPError(f'The field {r} is required to generate the event feed output.') if (hasattr(self, 'distribution') and self.distribution is not None and int(self.distribution) not in valid_distributions): return {} if with_distribution: self._fields_for_feed.add('distribution') to_return = super()._to_feed() if with_meta: to_return['_hashes'] = [] to_return['_manifest'] = self.manifest to_return['Orgc'] = self.Orgc._to_feed() to_return['Tag'] = list(filter(None, [tag._to_feed(with_local_tags) for tag in self.tags])) if self.attributes: to_return['Attribute'] = [] for attribute in self.attributes: if (valid_distributions and attribute.get('distribution') is not None and attribute.distribution not in valid_distributions): continue to_return['Attribute'].append(attribute._to_feed(with_distribution=with_distribution)) if with_meta: to_return['_hashes'] += attribute.hash_values('md5') if self.objects: to_return['Object'] = [] for obj in self.objects: if (valid_distributions and obj.get('distribution') is not None and obj.distribution not in valid_distributions): continue if with_distribution: obj._fields_for_feed.add('distribution') obj_to_attach = obj._to_feed(with_distribution=with_distribution) obj_to_attach['Attribute'] = [] for attribute in obj.attributes: if (valid_distributions and attribute.get('distribution') is not None and attribute.distribution not in valid_distributions): continue obj_to_attach['Attribute'].append(attribute._to_feed(with_distribution=with_distribution)) if with_meta: to_return['_hashes'] += attribute.hash_values('md5') to_return['Object'].append(obj_to_attach) if with_distribution: try: to_return['SharingGroup'] = self.SharingGroup._to_feed() except AttributeError: pass if with_event_reports and self.event_reports: to_return['EventReport'] = [] for event_report in self.event_reports: if (valid_distributions and event_report.get('distribution') is not None and event_report.distribution not in valid_distributions): continue if not with_distribution: event_report.pop('distribution', None) event_report.pop('SharingGroup', None) event_report.pop('sharing_group_id', None) to_return['EventReport'].append(event_report.to_dict()) return {'Event': to_return} @property def known_types(self) -> list[str]: return self.describe_types['types'] @property def org(self) -> MISPOrganisation: return self.Org @property def orgc(self) -> MISPOrganisation: return self.Orgc @orgc.setter def orgc(self, orgc: MISPOrganisation) -> None: if isinstance(orgc, MISPOrganisation): self.Orgc = orgc else: raise PyMISPError('Orgc must be of type MISPOrganisation.') @property def attributes(self) -> list[MISPAttribute]: return self.Attribute @attributes.setter def attributes(self, attributes: list[MISPAttribute]) -> None: if all(isinstance(x, MISPAttribute) for x in attributes): self.Attribute = attributes else: raise PyMISPError('All the attributes have to be of type MISPAttribute.') @property def event_reports(self) -> list[MISPEventReport]: return self.EventReport @property def shadow_attributes(self) -> list[MISPShadowAttribute]: return self.ShadowAttribute @shadow_attributes.setter def shadow_attributes(self, shadow_attributes: list[MISPShadowAttribute]) -> None: if all(isinstance(x, MISPShadowAttribute) for x in shadow_attributes): self.ShadowAttribute = shadow_attributes else: raise PyMISPError('All the attributes have to be of type MISPShadowAttribute.') @property def related_events(self) -> list[MISPEvent]: return self.RelatedEvent @property def galaxies(self) -> list[MISPGalaxy]: return self.Galaxy @galaxies.setter def galaxies(self, galaxies: list[MISPGalaxy]) -> None: if all(isinstance(x, MISPGalaxy) for x in galaxies): self.Galaxy = galaxies else: raise PyMISPError('All the attributes have to be of type MISPGalaxy.') @property def objects(self) -> list[MISPObject]: return self.Object @objects.setter def objects(self, objects: list[MISPObject]) -> None: if all(isinstance(x, MISPObject) for x in objects): self.Object = objects else: raise PyMISPError('All the attributes have to be of type MISPObject.') def load_file(self, event_path: Path | str, validate: bool = False, metadata_only: bool = False) -> None: """Load a JSON dump from a file on the disk""" if not os.path.exists(event_path): raise PyMISPError('Invalid path, unable to load the event.') with open(event_path, 'rb') as f: self.load(f, validate, metadata_only) def load(self, json_event: IO[bytes] | IO[str] | str | bytes | dict[str, Any], validate: bool = False, metadata_only: bool = False) -> None: """Load a JSON dump from a pseudo file or a JSON string""" if isinstance(json_event, (BufferedIOBase, TextIOBase)): json_event = json_event.read() if isinstance(json_event, (str, bytes)): json_event = json.loads(json_event) if isinstance(json_event, dict) and 'response' in json_event and isinstance(json_event['response'], list): event = json_event['response'][0] else: event = json_event if not event: raise PyMISPError('Invalid event') if metadata_only: event.pop('Attribute', None) event.pop('Object', None) self.from_dict(**event) if validate: warnings.warn('The validate parameter is deprecated because PyMISP is more flexible at loading event than the schema') def __setattr__(self, name: str, value: Any) -> None: if name in ['date']: if isinstance(value, date): pass elif isinstance(value, str): try: # faster value = date.fromisoformat(value) except Exception: value = parse(value).date() elif isinstance(value, (int, float)): value = date.fromtimestamp(value) elif isinstance(value, datetime): value = value.date() else: raise NewEventError(f'Invalid format for the date: {type(value)} - {value}') super().__setattr__(name, value) def set_date(self, d: str | int | float | datetime | date | None = None, ignore_invalid: bool = False) -> None: """Set a date for the event :param d: String, datetime, or date object :param ignore_invalid: if True, assigns current date if d is not an expected type """ if isinstance(d, (str, int, float, datetime, date)): self.date = d # type: ignore elif ignore_invalid: self.date = date.today() else: raise NewEventError(f'Invalid format for the date: {type(d)} - {d}') def from_dict(self, **kwargs) -> None: # type: ignore[no-untyped-def] if 'Event' in kwargs: kwargs = kwargs['Event'] # Required value self.info = kwargs.pop('info', None) if self.info is None: raise NewEventError('The info field of the new event is required.') # Default values for a valid event to send to a MISP instance self.distribution = kwargs.pop('distribution', None) if self.distribution is not None: self.distribution = int(self.distribution) if self.distribution not in [0, 1, 2, 3, 4]: raise NewEventError(f'{self.info}: {self.distribution} is invalid, the distribution has to be in 0, 1, 2, 3, 4') if kwargs.get('threat_level_id') is not None: self.threat_level_id = int(kwargs.pop('threat_level_id')) if self.threat_level_id not in [1, 2, 3, 4]: raise NewEventError(f'{self.info}: {self.threat_level_id} is invalid, the threat_level_id has to be in 1, 2, 3, 4') if kwargs.get('analysis') is not None: self.analysis = int(kwargs.pop('analysis')) if self.analysis not in [0, 1, 2]: raise NewEventError(f'{self.info}: {self.analysis} is invalid, the analysis has to be in 0, 1, 2') self.published = kwargs.pop('published', None) if self.published is True: self.publish() else: self.unpublish() if kwargs.get('date'): self.set_date(kwargs.pop('date')) if kwargs.get('Attribute'): [self.add_attribute(**a) for a in kwargs.pop('Attribute')] if kwargs.get('Galaxy'): [self.add_galaxy(**e) for e in kwargs.pop('Galaxy')] if kwargs.get('EventReport'): [self.add_event_report(**e) for e in kwargs.pop('EventReport')] # All other keys if kwargs.get('id'): self.id = int(kwargs.pop('id')) if kwargs.get('orgc_id'): self.orgc_id = int(kwargs.pop('orgc_id')) if kwargs.get('org_id'): self.org_id = int(kwargs.pop('org_id')) if kwargs.get('timestamp'): self.timestamp = datetime.fromtimestamp(int(kwargs.pop('timestamp')), timezone.utc) if kwargs.get('publish_timestamp'): self.publish_timestamp = datetime.fromtimestamp(int(kwargs.pop('publish_timestamp')), timezone.utc) if kwargs.get('sighting_timestamp'): self.sighting_timestamp = datetime.fromtimestamp(int(kwargs.pop('sighting_timestamp')), timezone.utc) if kwargs.get('sharing_group_id'): self.sharing_group_id = int(kwargs.pop('sharing_group_id')) if kwargs.get('RelatedEvent'): for rel_event in kwargs.pop('RelatedEvent'): sub_event = MISPEvent() sub_event.load(rel_event) self.RelatedEvent.append({'Event': sub_event}) # type: ignore[arg-type] if kwargs.get('Tag'): [self.add_tag(tag) for tag in kwargs.pop('Tag')] if kwargs.get('Object'): [self.add_object(obj) for obj in kwargs.pop('Object')] if kwargs.get('Org'): self.Org = MISPOrganisation() self.Org.from_dict(**kwargs.pop('Org')) if kwargs.get('Orgc'): self.Orgc = MISPOrganisation() self.Orgc.from_dict(**kwargs.pop('Orgc')) if kwargs.get('SharingGroup'): self.SharingGroup = MISPSharingGroup() self.SharingGroup.from_dict(**kwargs.pop('SharingGroup')) super().from_dict(**kwargs) def to_dict(self, json_format: bool = False) -> dict[str, Any]: to_return = super().to_dict(json_format) if to_return.get('date'): if isinstance(self.date, datetime): self.date = self.date.date() to_return['date'] = self.date.isoformat() if to_return.get('publish_timestamp'): to_return['publish_timestamp'] = str(self._datetime_to_timestamp(self.publish_timestamp)) if to_return.get('sighting_timestamp'): to_return['sighting_timestamp'] = str(self._datetime_to_timestamp(self.sighting_timestamp)) return to_return def add_proposal(self, shadow_attribute=None, **kwargs) -> MISPShadowAttribute: # type: ignore[no-untyped-def] """Alias for add_shadow_attribute""" return self.add_shadow_attribute(shadow_attribute, **kwargs) def add_shadow_attribute(self, shadow_attribute=None, **kwargs) -> MISPShadowAttribute: # type: ignore[no-untyped-def] """Add a tag to the attribute (by name or a MISPTag object)""" if isinstance(shadow_attribute, MISPShadowAttribute): misp_shadow_attribute = shadow_attribute elif isinstance(shadow_attribute, dict): misp_shadow_attribute = MISPShadowAttribute() misp_shadow_attribute.from_dict(**shadow_attribute) elif kwargs: misp_shadow_attribute = MISPShadowAttribute() misp_shadow_attribute.from_dict(**kwargs) else: raise PyMISPError(f"The shadow_attribute is in an invalid format (can be either string, MISPShadowAttribute, or an expanded dict[str, Any]): {shadow_attribute}") self.shadow_attributes.append(misp_shadow_attribute) self.edited = True return misp_shadow_attribute def get_attribute_tag(self, attribute_identifier: str) -> list[MISPTag]: """Return the tags associated to an attribute or an object attribute. :param attribute_identifier: can be an ID, UUID, or the value. """ tags: list[MISPTag] = [] for a in self.attributes + [attribute for o in self.objects for attribute in o.attributes]: if ((hasattr(a, 'id') and str(a.id) == attribute_identifier) or (hasattr(a, 'uuid') and a.uuid == attribute_identifier) or (hasattr(a, 'value') and attribute_identifier == a.value or (isinstance(a.value, str) and attribute_identifier in a.value.split('|')))): tags += a.tags return tags def add_attribute_tag(self, tag: MISPTag | str, attribute_identifier: str) -> list[MISPAttribute]: """Add a tag to an existing attribute. Raise an Exception if the attribute doesn't exist. :param tag: Tag name as a string, MISPTag instance, or dictionary :param attribute_identifier: can be an ID, UUID, or the value. """ attributes = [] for a in self.attributes + [attribute for o in self.objects for attribute in o.attributes]: if ((hasattr(a, 'id') and str(a.id) == attribute_identifier) or (hasattr(a, 'uuid') and a.uuid == attribute_identifier) or (hasattr(a, 'value') and attribute_identifier == a.value or (isinstance(a.value, str) and attribute_identifier in a.value.split('|')))): a.add_tag(tag) attributes.append(a) if not attributes: raise PyMISPError(f'No attribute with identifier {attribute_identifier} found.') self.edited = True return attributes def publish(self) -> None: """Mark the attribute as published""" self.published = True def unpublish(self) -> None: """Mark the attribute as un-published (set publish flag to false)""" self.published = False def delete_attribute(self, attribute_id: str) -> None: """Delete an attribute :param attribute_id: ID or UUID """ for a in self.attributes: if ((hasattr(a, 'id') and str(a.id) == attribute_id) or (hasattr(a, 'uuid') and a.uuid == attribute_id)): a.delete() break else: raise PyMISPError(f'No attribute with UUID/ID {attribute_id} found.') def add_attribute(self, type: str, value: str | int | float, **kwargs) -> MISPAttribute | list[MISPAttribute]: # type: ignore[no-untyped-def] """Add an attribute. type and value are required but you can pass all other parameters supported by MISPAttribute""" attr_list: list[MISPAttribute] = [] if isinstance(value, list): attr_list = [self.add_attribute(type=type, value=a, **kwargs) for a in value] else: attribute = MISPAttribute(describe_types=self.describe_types) attribute.from_dict(type=type, value=value, **kwargs) self.attributes.append(attribute) self.edited = True if attr_list: return attr_list return attribute def add_event_report(self, name: str, content: str, **kwargs) -> MISPEventReport: # type: ignore[no-untyped-def] """Add an event report. name and value are requred but you can pass all other parameters supported by MISPEventReport""" event_report = MISPEventReport() event_report.from_dict(name=name, content=content, **kwargs) self.event_reports.append(event_report) self.edited = True return event_report def add_galaxy(self, galaxy: MISPGalaxy | dict[str, Any] | None = None, **kwargs) -> MISPGalaxy: # type: ignore[no-untyped-def] """Add a galaxy and sub-clusters into an event, either by passing a MISPGalaxy or a dictionary. Supports all other parameters supported by MISPGalaxy""" if isinstance(galaxy, MISPGalaxy): self.galaxies.append(galaxy) return galaxy if isinstance(galaxy, dict): misp_galaxy = MISPGalaxy() misp_galaxy.from_dict(**galaxy) elif kwargs: misp_galaxy = MISPGalaxy() misp_galaxy.from_dict(**kwargs) else: raise InvalidMISPGalaxy("A Galaxy to add to an existing Event needs to be either a MISPGalaxy or a plain python dictionary") self.galaxies.append(misp_galaxy) return misp_galaxy def get_object_by_id(self, object_id: str | int) -> MISPObject: """Get an object by ID :param object_id: the ID is the one set by the server when creating the new object""" for obj in self.objects: if hasattr(obj, 'id') and int(obj.id) == int(object_id): return obj raise InvalidMISPObject(f'Object with {object_id} does not exist in this event') def get_object_by_uuid(self, object_uuid: str) -> MISPObject: """Get an object by UUID :param object_uuid: the UUID is set by the server when creating the new object""" for obj in self.objects: if hasattr(obj, 'uuid') and obj.uuid == object_uuid: return obj raise InvalidMISPObject(f'Object with {object_uuid} does not exist in this event') def get_objects_by_name(self, object_name: str) -> list[MISPObject]: """Get objects by name :param object_name: name is set by the server when creating the new object""" objects = [] for obj in self.objects: if hasattr(obj, 'uuid') and obj.name == object_name: objects.append(obj) return objects def add_object(self, obj: MISPObject | dict[str, Any] | None = None, **kwargs) -> MISPObject: # type: ignore[no-untyped-def] """Add an object to the Event, either by passing a MISPObject, or a dictionary""" if isinstance(obj, MISPObject): misp_obj = obj elif isinstance(obj, dict): misp_obj = MISPObject(name=obj.pop('name'), strict=obj.pop('strict', False), default_attributes_parameters=obj.pop('default_attributes_parameters', {}), **obj) misp_obj.from_dict(**obj) elif kwargs: misp_obj = MISPObject(name=kwargs.pop('name'), strict=kwargs.pop('strict', False), default_attributes_parameters=kwargs.pop('default_attributes_parameters', {}), **kwargs) misp_obj.from_dict(**kwargs) else: raise InvalidMISPObject("An object to add to an existing Event needs to be either a MISPObject, or a plain python dictionary") misp_obj.standalone = False self.Object.append(misp_obj) self.edited = True return misp_obj def delete_object(self, object_id: str) -> None: """Delete an object :param object_id: ID or UUID """ for o in self.objects: if ((hasattr(o, 'id') and object_id.isdigit() and int(o.id) == int(object_id)) or (hasattr(o, 'uuid') and o.uuid == object_id)): o.delete() break else: raise PyMISPError(f'No object with UUID/ID {object_id} found.') def run_expansions(self) -> None: for index, attribute in enumerate(self.attributes): if 'expand' not in attribute: continue # NOTE: Always make sure the attribute with the expand key is either completely removed, # of the key is deleted to avoid seeing it processed again on MISP side elif attribute.expand == 'binary': try: from .tools import make_binary_objects except ImportError as e: logger.info(f'Unable to load make_binary_objects: {e}') continue file_object, bin_type_object, bin_section_objects = make_binary_objects(pseudofile=attribute.malware_binary, filename=attribute.malware_filename) self.add_object(file_object) if bin_type_object: self.add_object(bin_type_object) if bin_section_objects: for bin_section_object in bin_section_objects: self.add_object(bin_section_object) self.attributes.pop(index) else: logger.warning(f'No expansions for this data type ({attribute.type}). Open an issue if needed.') def __repr__(self) -> str: if hasattr(self, 'info'): return '<{self.__class__.__name__}(info={self.info})'.format(self=self) return f'<{self.__class__.__name__}(NotInitialized)'
(describe_types: 'dict[str, Any] | None' = None, strict_validation: 'bool' = False, **kwargs) -> 'None'
25,277
pymisp.mispevent
__init__
null
def __init__(self, describe_types: dict[str, Any] | None = None, strict_validation: bool = False, **kwargs) -> None: # type: ignore[no-untyped-def] super().__init__(**kwargs) self.__schema_file = 'schema.json' if strict_validation else 'schema-lax.json' if describe_types: # This variable is used in add_attribute in order to avoid duplicating the structure self.describe_types = describe_types self.uuid: str = str(uuid.uuid4()) self.date: date self.Attribute: list[MISPAttribute] = [] self.Object: list[MISPObject] = [] self.RelatedEvent: list[MISPEvent] = [] self.ShadowAttribute: list[MISPShadowAttribute] = [] self.SharingGroup: MISPSharingGroup self.EventReport: list[MISPEventReport] = [] self.Tag: list[MISPTag] = [] self.Galaxy: list[MISPGalaxy] = [] self.publish_timestamp: float | int | datetime self.timestamp: float | int | datetime
(self, describe_types: Optional[dict[str, Any]] = None, strict_validation: bool = False, **kwargs) -> NoneType
25,280
pymisp.mispevent
__repr__
null
def __repr__(self) -> str: if hasattr(self, 'info'): return '<{self.__class__.__name__}(info={self.info})'.format(self=self) return f'<{self.__class__.__name__}(NotInitialized)'
(self) -> str
25,281
pymisp.mispevent
__setattr__
null
def __setattr__(self, name: str, value: Any) -> None: if name in ['date']: if isinstance(value, date): pass elif isinstance(value, str): try: # faster value = date.fromisoformat(value) except Exception: value = parse(value).date() elif isinstance(value, (int, float)): value = date.fromtimestamp(value) elif isinstance(value, datetime): value = value.date() else: raise NewEventError(f'Invalid format for the date: {type(value)} - {value}') super().__setattr__(name, value)
(self, name: str, value: Any) -> NoneType
25,286
pymisp.mispevent
_set_default
There are a few keys that could, or need to be set by default for the feed generator
def _set_default(self) -> None: """There are a few keys that could, or need to be set by default for the feed generator""" if not hasattr(self, 'published'): self.published = True if not hasattr(self, 'uuid'): self.uuid = str(uuid.uuid4()) if not hasattr(self, 'extends_uuid'): self.extends_uuid = '' if not hasattr(self, 'date'): self.set_date(date.today()) if not hasattr(self, 'timestamp'): self.timestamp = datetime.timestamp(datetime.now()) if not hasattr(self, 'publish_timestamp'): self.publish_timestamp = datetime.timestamp(datetime.now()) if not hasattr(self, 'analysis'): # analysis: 0 means initial, 1 ongoing, 2 completed self.analysis = 2 if not hasattr(self, 'threat_level_id'): # threat_level_id 4 means undefined. Tags are recommended. self.threat_level_id = 4
(self) -> NoneType
25,289
pymisp.mispevent
add_attribute
Add an attribute. type and value are required but you can pass all other parameters supported by MISPAttribute
def add_attribute(self, type: str, value: str | int | float, **kwargs) -> MISPAttribute | list[MISPAttribute]: # type: ignore[no-untyped-def] """Add an attribute. type and value are required but you can pass all other parameters supported by MISPAttribute""" attr_list: list[MISPAttribute] = [] if isinstance(value, list): attr_list = [self.add_attribute(type=type, value=a, **kwargs) for a in value] else: attribute = MISPAttribute(describe_types=self.describe_types) attribute.from_dict(type=type, value=value, **kwargs) self.attributes.append(attribute) self.edited = True if attr_list: return attr_list return attribute
(self, type: str, value: str | int | float, **kwargs) -> pymisp.mispevent.MISPAttribute | list[pymisp.mispevent.MISPAttribute]
25,290
pymisp.mispevent
add_attribute_tag
Add a tag to an existing attribute. Raise an Exception if the attribute doesn't exist. :param tag: Tag name as a string, MISPTag instance, or dictionary :param attribute_identifier: can be an ID, UUID, or the value.
def add_attribute_tag(self, tag: MISPTag | str, attribute_identifier: str) -> list[MISPAttribute]: """Add a tag to an existing attribute. Raise an Exception if the attribute doesn't exist. :param tag: Tag name as a string, MISPTag instance, or dictionary :param attribute_identifier: can be an ID, UUID, or the value. """ attributes = [] for a in self.attributes + [attribute for o in self.objects for attribute in o.attributes]: if ((hasattr(a, 'id') and str(a.id) == attribute_identifier) or (hasattr(a, 'uuid') and a.uuid == attribute_identifier) or (hasattr(a, 'value') and attribute_identifier == a.value or (isinstance(a.value, str) and attribute_identifier in a.value.split('|')))): a.add_tag(tag) attributes.append(a) if not attributes: raise PyMISPError(f'No attribute with identifier {attribute_identifier} found.') self.edited = True return attributes
(self, tag: pymisp.abstract.MISPTag | str, attribute_identifier: str) -> list[pymisp.mispevent.MISPAttribute]
25,291
pymisp.mispevent
add_event_report
Add an event report. name and value are requred but you can pass all other parameters supported by MISPEventReport
def add_event_report(self, name: str, content: str, **kwargs) -> MISPEventReport: # type: ignore[no-untyped-def] """Add an event report. name and value are requred but you can pass all other parameters supported by MISPEventReport""" event_report = MISPEventReport() event_report.from_dict(name=name, content=content, **kwargs) self.event_reports.append(event_report) self.edited = True return event_report
(self, name: str, content: str, **kwargs) -> pymisp.mispevent.MISPEventReport
25,292
pymisp.mispevent
add_galaxy
Add a galaxy and sub-clusters into an event, either by passing a MISPGalaxy or a dictionary. Supports all other parameters supported by MISPGalaxy
def add_galaxy(self, galaxy: MISPGalaxy | dict[str, Any] | None = None, **kwargs) -> MISPGalaxy: # type: ignore[no-untyped-def] """Add a galaxy and sub-clusters into an event, either by passing a MISPGalaxy or a dictionary. Supports all other parameters supported by MISPGalaxy""" if isinstance(galaxy, MISPGalaxy): self.galaxies.append(galaxy) return galaxy if isinstance(galaxy, dict): misp_galaxy = MISPGalaxy() misp_galaxy.from_dict(**galaxy) elif kwargs: misp_galaxy = MISPGalaxy() misp_galaxy.from_dict(**kwargs) else: raise InvalidMISPGalaxy("A Galaxy to add to an existing Event needs to be either a MISPGalaxy or a plain python dictionary") self.galaxies.append(misp_galaxy) return misp_galaxy
(self, galaxy: Union[pymisp.mispevent.MISPGalaxy, dict[str, Any], NoneType] = None, **kwargs) -> pymisp.mispevent.MISPGalaxy
25,293
pymisp.mispevent
add_object
Add an object to the Event, either by passing a MISPObject, or a dictionary
def add_object(self, obj: MISPObject | dict[str, Any] | None = None, **kwargs) -> MISPObject: # type: ignore[no-untyped-def] """Add an object to the Event, either by passing a MISPObject, or a dictionary""" if isinstance(obj, MISPObject): misp_obj = obj elif isinstance(obj, dict): misp_obj = MISPObject(name=obj.pop('name'), strict=obj.pop('strict', False), default_attributes_parameters=obj.pop('default_attributes_parameters', {}), **obj) misp_obj.from_dict(**obj) elif kwargs: misp_obj = MISPObject(name=kwargs.pop('name'), strict=kwargs.pop('strict', False), default_attributes_parameters=kwargs.pop('default_attributes_parameters', {}), **kwargs) misp_obj.from_dict(**kwargs) else: raise InvalidMISPObject("An object to add to an existing Event needs to be either a MISPObject, or a plain python dictionary") misp_obj.standalone = False self.Object.append(misp_obj) self.edited = True return misp_obj
(self, obj: Union[pymisp.mispevent.MISPObject, dict[str, Any], NoneType] = None, **kwargs) -> pymisp.mispevent.MISPObject
25,295
pymisp.mispevent
add_shadow_attribute
Add a tag to the attribute (by name or a MISPTag object)
def add_shadow_attribute(self, shadow_attribute=None, **kwargs) -> MISPShadowAttribute: # type: ignore[no-untyped-def] """Add a tag to the attribute (by name or a MISPTag object)""" if isinstance(shadow_attribute, MISPShadowAttribute): misp_shadow_attribute = shadow_attribute elif isinstance(shadow_attribute, dict): misp_shadow_attribute = MISPShadowAttribute() misp_shadow_attribute.from_dict(**shadow_attribute) elif kwargs: misp_shadow_attribute = MISPShadowAttribute() misp_shadow_attribute.from_dict(**kwargs) else: raise PyMISPError(f"The shadow_attribute is in an invalid format (can be either string, MISPShadowAttribute, or an expanded dict[str, Any]): {shadow_attribute}") self.shadow_attributes.append(misp_shadow_attribute) self.edited = True return misp_shadow_attribute
(self, shadow_attribute=None, **kwargs) -> pymisp.mispevent.MISPShadowAttribute
25,297
pymisp.mispevent
attributes_hashes
null
def attributes_hashes(self, algorithm: str = 'sha512') -> list[str]: to_return: list[str] = [] for attribute in self.attributes: to_return += attribute.hash_values(algorithm) for obj in self.objects: for attribute in obj.attributes: to_return += attribute.hash_values(algorithm) return to_return
(self, algorithm: str = 'sha512') -> list[str]
25,299
pymisp.mispevent
delete_attribute
Delete an attribute :param attribute_id: ID or UUID
def delete_attribute(self, attribute_id: str) -> None: """Delete an attribute :param attribute_id: ID or UUID """ for a in self.attributes: if ((hasattr(a, 'id') and str(a.id) == attribute_id) or (hasattr(a, 'uuid') and a.uuid == attribute_id)): a.delete() break else: raise PyMISPError(f'No attribute with UUID/ID {attribute_id} found.')
(self, attribute_id: str) -> NoneType
25,300
pymisp.mispevent
delete_object
Delete an object :param object_id: ID or UUID
def delete_object(self, object_id: str) -> None: """Delete an object :param object_id: ID or UUID """ for o in self.objects: if ((hasattr(o, 'id') and object_id.isdigit() and int(o.id) == int(object_id)) or (hasattr(o, 'uuid') and o.uuid == object_id)): o.delete() break else: raise PyMISPError(f'No object with UUID/ID {object_id} found.')
(self, object_id: str) -> NoneType
25,301
pymisp.mispevent
from_dict
null
def from_dict(self, **kwargs) -> None: # type: ignore[no-untyped-def] if 'Event' in kwargs: kwargs = kwargs['Event'] # Required value self.info = kwargs.pop('info', None) if self.info is None: raise NewEventError('The info field of the new event is required.') # Default values for a valid event to send to a MISP instance self.distribution = kwargs.pop('distribution', None) if self.distribution is not None: self.distribution = int(self.distribution) if self.distribution not in [0, 1, 2, 3, 4]: raise NewEventError(f'{self.info}: {self.distribution} is invalid, the distribution has to be in 0, 1, 2, 3, 4') if kwargs.get('threat_level_id') is not None: self.threat_level_id = int(kwargs.pop('threat_level_id')) if self.threat_level_id not in [1, 2, 3, 4]: raise NewEventError(f'{self.info}: {self.threat_level_id} is invalid, the threat_level_id has to be in 1, 2, 3, 4') if kwargs.get('analysis') is not None: self.analysis = int(kwargs.pop('analysis')) if self.analysis not in [0, 1, 2]: raise NewEventError(f'{self.info}: {self.analysis} is invalid, the analysis has to be in 0, 1, 2') self.published = kwargs.pop('published', None) if self.published is True: self.publish() else: self.unpublish() if kwargs.get('date'): self.set_date(kwargs.pop('date')) if kwargs.get('Attribute'): [self.add_attribute(**a) for a in kwargs.pop('Attribute')] if kwargs.get('Galaxy'): [self.add_galaxy(**e) for e in kwargs.pop('Galaxy')] if kwargs.get('EventReport'): [self.add_event_report(**e) for e in kwargs.pop('EventReport')] # All other keys if kwargs.get('id'): self.id = int(kwargs.pop('id')) if kwargs.get('orgc_id'): self.orgc_id = int(kwargs.pop('orgc_id')) if kwargs.get('org_id'): self.org_id = int(kwargs.pop('org_id')) if kwargs.get('timestamp'): self.timestamp = datetime.fromtimestamp(int(kwargs.pop('timestamp')), timezone.utc) if kwargs.get('publish_timestamp'): self.publish_timestamp = datetime.fromtimestamp(int(kwargs.pop('publish_timestamp')), timezone.utc) if kwargs.get('sighting_timestamp'): self.sighting_timestamp = datetime.fromtimestamp(int(kwargs.pop('sighting_timestamp')), timezone.utc) if kwargs.get('sharing_group_id'): self.sharing_group_id = int(kwargs.pop('sharing_group_id')) if kwargs.get('RelatedEvent'): for rel_event in kwargs.pop('RelatedEvent'): sub_event = MISPEvent() sub_event.load(rel_event) self.RelatedEvent.append({'Event': sub_event}) # type: ignore[arg-type] if kwargs.get('Tag'): [self.add_tag(tag) for tag in kwargs.pop('Tag')] if kwargs.get('Object'): [self.add_object(obj) for obj in kwargs.pop('Object')] if kwargs.get('Org'): self.Org = MISPOrganisation() self.Org.from_dict(**kwargs.pop('Org')) if kwargs.get('Orgc'): self.Orgc = MISPOrganisation() self.Orgc.from_dict(**kwargs.pop('Orgc')) if kwargs.get('SharingGroup'): self.SharingGroup = MISPSharingGroup() self.SharingGroup.from_dict(**kwargs.pop('SharingGroup')) super().from_dict(**kwargs)
(self, **kwargs) -> NoneType
25,304
pymisp.mispevent
get_attribute_tag
Return the tags associated to an attribute or an object attribute. :param attribute_identifier: can be an ID, UUID, or the value.
def get_attribute_tag(self, attribute_identifier: str) -> list[MISPTag]: """Return the tags associated to an attribute or an object attribute. :param attribute_identifier: can be an ID, UUID, or the value. """ tags: list[MISPTag] = [] for a in self.attributes + [attribute for o in self.objects for attribute in o.attributes]: if ((hasattr(a, 'id') and str(a.id) == attribute_identifier) or (hasattr(a, 'uuid') and a.uuid == attribute_identifier) or (hasattr(a, 'value') and attribute_identifier == a.value or (isinstance(a.value, str) and attribute_identifier in a.value.split('|')))): tags += a.tags return tags
(self, attribute_identifier: str) -> list[pymisp.abstract.MISPTag]
25,305
pymisp.mispevent
get_object_by_id
Get an object by ID :param object_id: the ID is the one set by the server when creating the new object
def get_object_by_id(self, object_id: str | int) -> MISPObject: """Get an object by ID :param object_id: the ID is the one set by the server when creating the new object""" for obj in self.objects: if hasattr(obj, 'id') and int(obj.id) == int(object_id): return obj raise InvalidMISPObject(f'Object with {object_id} does not exist in this event')
(self, object_id: str | int) -> pymisp.mispevent.MISPObject
25,306
pymisp.mispevent
get_object_by_uuid
Get an object by UUID :param object_uuid: the UUID is set by the server when creating the new object
def get_object_by_uuid(self, object_uuid: str) -> MISPObject: """Get an object by UUID :param object_uuid: the UUID is set by the server when creating the new object""" for obj in self.objects: if hasattr(obj, 'uuid') and obj.uuid == object_uuid: return obj raise InvalidMISPObject(f'Object with {object_uuid} does not exist in this event')
(self, object_uuid: str) -> pymisp.mispevent.MISPObject
25,307
pymisp.mispevent
get_objects_by_name
Get objects by name :param object_name: name is set by the server when creating the new object
def get_objects_by_name(self, object_name: str) -> list[MISPObject]: """Get objects by name :param object_name: name is set by the server when creating the new object""" objects = [] for obj in self.objects: if hasattr(obj, 'uuid') and obj.name == object_name: objects.append(obj) return objects
(self, object_name: str) -> list[pymisp.mispevent.MISPObject]
25,311
pymisp.mispevent
load
Load a JSON dump from a pseudo file or a JSON string
def load(self, json_event: IO[bytes] | IO[str] | str | bytes | dict[str, Any], validate: bool = False, metadata_only: bool = False) -> None: """Load a JSON dump from a pseudo file or a JSON string""" if isinstance(json_event, (BufferedIOBase, TextIOBase)): json_event = json_event.read() if isinstance(json_event, (str, bytes)): json_event = json.loads(json_event) if isinstance(json_event, dict) and 'response' in json_event and isinstance(json_event['response'], list): event = json_event['response'][0] else: event = json_event if not event: raise PyMISPError('Invalid event') if metadata_only: event.pop('Attribute', None) event.pop('Object', None) self.from_dict(**event) if validate: warnings.warn('The validate parameter is deprecated because PyMISP is more flexible at loading event than the schema')
(self, json_event: Union[IO[bytes], IO[str], str, bytes, dict[str, Any]], validate: bool = False, metadata_only: bool = False) -> NoneType
25,312
pymisp.mispevent
load_file
Load a JSON dump from a file on the disk
def load_file(self, event_path: Path | str, validate: bool = False, metadata_only: bool = False) -> None: """Load a JSON dump from a file on the disk""" if not os.path.exists(event_path): raise PyMISPError('Invalid path, unable to load the event.') with open(event_path, 'rb') as f: self.load(f, validate, metadata_only)
(self, event_path: pathlib.Path | str, validate: bool = False, metadata_only: bool = False) -> NoneType
25,315
pymisp.mispevent
publish
Mark the attribute as published
def publish(self) -> None: """Mark the attribute as published""" self.published = True
(self) -> NoneType
25,316
pymisp.mispevent
run_expansions
null
def run_expansions(self) -> None: for index, attribute in enumerate(self.attributes): if 'expand' not in attribute: continue # NOTE: Always make sure the attribute with the expand key is either completely removed, # of the key is deleted to avoid seeing it processed again on MISP side elif attribute.expand == 'binary': try: from .tools import make_binary_objects except ImportError as e: logger.info(f'Unable to load make_binary_objects: {e}') continue file_object, bin_type_object, bin_section_objects = make_binary_objects(pseudofile=attribute.malware_binary, filename=attribute.malware_filename) self.add_object(file_object) if bin_type_object: self.add_object(bin_type_object) if bin_section_objects: for bin_section_object in bin_section_objects: self.add_object(bin_section_object) self.attributes.pop(index) else: logger.warning(f'No expansions for this data type ({attribute.type}). Open an issue if needed.')
(self) -> NoneType
25,317
pymisp.mispevent
set_date
Set a date for the event :param d: String, datetime, or date object :param ignore_invalid: if True, assigns current date if d is not an expected type
def set_date(self, d: str | int | float | datetime | date | None = None, ignore_invalid: bool = False) -> None: """Set a date for the event :param d: String, datetime, or date object :param ignore_invalid: if True, assigns current date if d is not an expected type """ if isinstance(d, (str, int, float, datetime, date)): self.date = d # type: ignore elif ignore_invalid: self.date = date.today() else: raise NewEventError(f'Invalid format for the date: {type(d)} - {d}')
(self, d: Union[datetime.datetime, datetime.date, int, str, float, NoneType] = None, ignore_invalid: bool = False) -> NoneType
25,320
pymisp.mispevent
to_dict
null
def to_dict(self, json_format: bool = False) -> dict[str, Any]: to_return = super().to_dict(json_format) if to_return.get('date'): if isinstance(self.date, datetime): self.date = self.date.date() to_return['date'] = self.date.isoformat() if to_return.get('publish_timestamp'): to_return['publish_timestamp'] = str(self._datetime_to_timestamp(self.publish_timestamp)) if to_return.get('sighting_timestamp'): to_return['sighting_timestamp'] = str(self._datetime_to_timestamp(self.sighting_timestamp)) return to_return
(self, json_format: bool = False) -> dict[str, typing.Any]
25,321
pymisp.mispevent
to_feed
Generate a json output for MISP Feed. :param valid_distributions: only makes sense if the distribution key is set; i.e., the event is exported from a MISP instance. :param with_distribution: exports distribution and Sharing Group info; otherwise all SharingGroup information is discarded (protecting privacy) :param with_local_tags: tag export includes local exportable tags along with global exportable tags :param with_event_reports: include event reports in the returned MISP event
def to_feed(self, valid_distributions: list[int] = [0, 1, 2, 3, 4, 5], with_meta: bool = False, with_distribution: bool=False, with_local_tags: bool = True, with_event_reports: bool = True) -> dict[str, Any]: """ Generate a json output for MISP Feed. :param valid_distributions: only makes sense if the distribution key is set; i.e., the event is exported from a MISP instance. :param with_distribution: exports distribution and Sharing Group info; otherwise all SharingGroup information is discarded (protecting privacy) :param with_local_tags: tag export includes local exportable tags along with global exportable tags :param with_event_reports: include event reports in the returned MISP event """ required = ['info', 'Orgc'] for r in required: if not hasattr(self, r): raise PyMISPError(f'The field {r} is required to generate the event feed output.') if (hasattr(self, 'distribution') and self.distribution is not None and int(self.distribution) not in valid_distributions): return {} if with_distribution: self._fields_for_feed.add('distribution') to_return = super()._to_feed() if with_meta: to_return['_hashes'] = [] to_return['_manifest'] = self.manifest to_return['Orgc'] = self.Orgc._to_feed() to_return['Tag'] = list(filter(None, [tag._to_feed(with_local_tags) for tag in self.tags])) if self.attributes: to_return['Attribute'] = [] for attribute in self.attributes: if (valid_distributions and attribute.get('distribution') is not None and attribute.distribution not in valid_distributions): continue to_return['Attribute'].append(attribute._to_feed(with_distribution=with_distribution)) if with_meta: to_return['_hashes'] += attribute.hash_values('md5') if self.objects: to_return['Object'] = [] for obj in self.objects: if (valid_distributions and obj.get('distribution') is not None and obj.distribution not in valid_distributions): continue if with_distribution: obj._fields_for_feed.add('distribution') obj_to_attach = obj._to_feed(with_distribution=with_distribution) obj_to_attach['Attribute'] = [] for attribute in obj.attributes: if (valid_distributions and attribute.get('distribution') is not None and attribute.distribution not in valid_distributions): continue obj_to_attach['Attribute'].append(attribute._to_feed(with_distribution=with_distribution)) if with_meta: to_return['_hashes'] += attribute.hash_values('md5') to_return['Object'].append(obj_to_attach) if with_distribution: try: to_return['SharingGroup'] = self.SharingGroup._to_feed() except AttributeError: pass if with_event_reports and self.event_reports: to_return['EventReport'] = [] for event_report in self.event_reports: if (valid_distributions and event_report.get('distribution') is not None and event_report.distribution not in valid_distributions): continue if not with_distribution: event_report.pop('distribution', None) event_report.pop('SharingGroup', None) event_report.pop('sharing_group_id', None) to_return['EventReport'].append(event_report.to_dict()) return {'Event': to_return}
(self, valid_distributions: list[int] = [0, 1, 2, 3, 4, 5], with_meta: bool = False, with_distribution: bool = False, with_local_tags: bool = True, with_event_reports: bool = True) -> dict[str, typing.Any]
25,323
pymisp.mispevent
unpublish
Mark the attribute as un-published (set publish flag to false)
def unpublish(self) -> None: """Mark the attribute as un-published (set publish flag to false)""" self.published = False
(self) -> NoneType
25,327
pymisp.mispevent
MISPEventBlocklist
null
class MISPEventBlocklist(AbstractMISP): def __init__(self, **kwargs: dict[str, Any]) -> None: super().__init__(**kwargs) self.event_uuid: str def from_dict(self, **kwargs) -> None: # type: ignore[no-untyped-def] if 'EventBlocklist' in kwargs: kwargs = kwargs['EventBlocklist'] super().from_dict(**kwargs) def __repr__(self) -> str: return f'<{self.__class__.__name__}(event_uuid={self.event_uuid}'
(**kwargs: 'dict[str, Any]') -> 'None'
25,332
pymisp.mispevent
__init__
null
def __init__(self, **kwargs: dict[str, Any]) -> None: super().__init__(**kwargs) self.event_uuid: str
(self, **kwargs: dict[str, typing.Any]) -> NoneType
25,335
pymisp.mispevent
__repr__
null
def __repr__(self) -> str: return f'<{self.__class__.__name__}(event_uuid={self.event_uuid}'
(self) -> str
25,344
pymisp.mispevent
from_dict
null
def from_dict(self, **kwargs) -> None: # type: ignore[no-untyped-def] if 'EventBlocklist' in kwargs: kwargs = kwargs['EventBlocklist'] super().from_dict(**kwargs)
(self, **kwargs) -> NoneType
25,359
pymisp.mispevent
MISPEventDelegation
null
class MISPEventDelegation(AbstractMISP): def __init__(self, **kwargs: dict[str, Any]) -> None: super().__init__(**kwargs) self.org_id: int self.requester_org_id: int self.event_id: int def from_dict(self, **kwargs) -> None: # type: ignore[no-untyped-def] if 'EventDelegation' in kwargs: kwargs = kwargs['EventDelegation'] super().from_dict(**kwargs) def __repr__(self) -> str: return '<{self.__class__.__name__}(org_id={self.org_id}, requester_org_id={self.requester_org_id}, {self.event_id})'.format(self=self)
(**kwargs: 'dict[str, Any]') -> 'None'
25,364
pymisp.mispevent
__init__
null
def __init__(self, **kwargs: dict[str, Any]) -> None: super().__init__(**kwargs) self.org_id: int self.requester_org_id: int self.event_id: int
(self, **kwargs: dict[str, typing.Any]) -> NoneType
25,367
pymisp.mispevent
__repr__
null
def __repr__(self) -> str: return '<{self.__class__.__name__}(org_id={self.org_id}, requester_org_id={self.requester_org_id}, {self.event_id})'.format(self=self)
(self) -> str
25,376
pymisp.mispevent
from_dict
null
def from_dict(self, **kwargs) -> None: # type: ignore[no-untyped-def] if 'EventDelegation' in kwargs: kwargs = kwargs['EventDelegation'] super().from_dict(**kwargs)
(self, **kwargs) -> NoneType
25,391
pymisp.mispevent
MISPEventReport
null
class MISPEventReport(AbstractMISP): _fields_for_feed: set[str] = {'uuid', 'name', 'content', 'timestamp', 'deleted'} timestamp: float | int | datetime def from_dict(self, **kwargs) -> None: # type: ignore[no-untyped-def] if 'EventReport' in kwargs: kwargs = kwargs['EventReport'] self.distribution = kwargs.pop('distribution', None) if self.distribution is not None: self.distribution = int(self.distribution) if self.distribution not in [0, 1, 2, 3, 4, 5]: raise NewEventReportError(f'{self.distribution} is invalid, the distribution has to be in 0, 1, 2, 3, 4, 5') if kwargs.get('sharing_group_id'): self.sharing_group_id = int(kwargs.pop('sharing_group_id')) if self.distribution == 4: # The distribution is set to sharing group, a sharing_group_id is required. if not hasattr(self, 'sharing_group_id'): raise NewEventReportError('If the distribution is set to sharing group, a sharing group ID is required.') elif not self.sharing_group_id: # Cannot be None or 0 either. raise NewEventReportError(f'If the distribution is set to sharing group, a sharing group ID is required (cannot be {self.sharing_group_id}).') self.name = kwargs.pop('name', None) if self.name is None: raise NewEventReportError('The name of the event report is required.') self.content = kwargs.pop('content', None) if self.content is None: raise NewAttributeError('The content of the event report is required.') if kwargs.get('id'): self.id = int(kwargs.pop('id')) if kwargs.get('event_id'): self.event_id = int(kwargs.pop('event_id')) if kwargs.get('timestamp'): ts = kwargs.pop('timestamp') if isinstance(ts, datetime): self.timestamp = ts else: self.timestamp = datetime.fromtimestamp(int(ts), timezone.utc) if kwargs.get('deleted'): self.deleted = kwargs.pop('deleted') super().from_dict(**kwargs) def __repr__(self) -> str: if hasattr(self, 'name'): return '<{self.__class__.__name__}(name={self.name})'.format(self=self) return f'<{self.__class__.__name__}(NotInitialized)' def _set_default(self) -> None: if not hasattr(self, 'timestamp'): self.timestamp = datetime.timestamp(datetime.now()) if not hasattr(self, 'name'): self.name = '' if not hasattr(self, 'content'): self.content = ''
(**kwargs) -> 'None'
25,405
pymisp.mispevent
_set_default
null
def _set_default(self) -> None: if not hasattr(self, 'timestamp'): self.timestamp = datetime.timestamp(datetime.now()) if not hasattr(self, 'name'): self.name = '' if not hasattr(self, 'content'): self.content = ''
(self) -> NoneType
25,409
pymisp.mispevent
from_dict
null
def from_dict(self, **kwargs) -> None: # type: ignore[no-untyped-def] if 'EventReport' in kwargs: kwargs = kwargs['EventReport'] self.distribution = kwargs.pop('distribution', None) if self.distribution is not None: self.distribution = int(self.distribution) if self.distribution not in [0, 1, 2, 3, 4, 5]: raise NewEventReportError(f'{self.distribution} is invalid, the distribution has to be in 0, 1, 2, 3, 4, 5') if kwargs.get('sharing_group_id'): self.sharing_group_id = int(kwargs.pop('sharing_group_id')) if self.distribution == 4: # The distribution is set to sharing group, a sharing_group_id is required. if not hasattr(self, 'sharing_group_id'): raise NewEventReportError('If the distribution is set to sharing group, a sharing group ID is required.') elif not self.sharing_group_id: # Cannot be None or 0 either. raise NewEventReportError(f'If the distribution is set to sharing group, a sharing group ID is required (cannot be {self.sharing_group_id}).') self.name = kwargs.pop('name', None) if self.name is None: raise NewEventReportError('The name of the event report is required.') self.content = kwargs.pop('content', None) if self.content is None: raise NewAttributeError('The content of the event report is required.') if kwargs.get('id'): self.id = int(kwargs.pop('id')) if kwargs.get('event_id'): self.event_id = int(kwargs.pop('event_id')) if kwargs.get('timestamp'): ts = kwargs.pop('timestamp') if isinstance(ts, datetime): self.timestamp = ts else: self.timestamp = datetime.fromtimestamp(int(ts), timezone.utc) if kwargs.get('deleted'): self.deleted = kwargs.pop('deleted') super().from_dict(**kwargs)
(self, **kwargs) -> NoneType
25,424
pymisp.mispevent
MISPFeed
null
class MISPFeed(AbstractMISP): settings: str def from_dict(self, **kwargs) -> None: # type: ignore[no-untyped-def] if 'Feed' in kwargs: kwargs = kwargs['Feed'] super().from_dict(**kwargs) if hasattr(self, 'settings'): try: self.settings = json.loads(self.settings) except json.decoder.JSONDecodeError as e: logger.error(f"Failed to parse feed settings: {self.settings}") raise e
(**kwargs) -> 'None'
25,441
pymisp.mispevent
from_dict
null
def from_dict(self, **kwargs) -> None: # type: ignore[no-untyped-def] if 'Feed' in kwargs: kwargs = kwargs['Feed'] super().from_dict(**kwargs) if hasattr(self, 'settings'): try: self.settings = json.loads(self.settings) except json.decoder.JSONDecodeError as e: logger.error(f"Failed to parse feed settings: {self.settings}") raise e
(self, **kwargs) -> NoneType
25,456
pymisp.mispevent
MISPGalaxy
Galaxy class, used to view a galaxy and respective clusters
class MISPGalaxy(AbstractMISP): """Galaxy class, used to view a galaxy and respective clusters""" id: str | None def __init__(self) -> None: super().__init__() self.GalaxyCluster: list[MISPGalaxyCluster] = [] self.name: str def from_dict(self, **kwargs) -> None: # type: ignore[no-untyped-def] """Galaxy could be in one of the following formats: {'Galaxy': {}, 'GalaxyCluster': []} {'Galaxy': {'GalaxyCluster': []}} """ if 'GalaxyCluster' in kwargs and kwargs.get("withCluster", True): # Parse the cluster from the kwargs [self.add_galaxy_cluster(**e) for e in kwargs.pop('GalaxyCluster')] if 'Galaxy' in kwargs: kwargs = kwargs['Galaxy'] super().from_dict(**kwargs) @property def clusters(self) -> list[MISPGalaxyCluster]: return self.GalaxyCluster def add_galaxy_cluster(self, **kwargs) -> MISPGalaxyCluster: # type: ignore[no-untyped-def] """Add a MISP galaxy cluster into a MISPGalaxy. Supports all other parameters supported by MISPGalaxyCluster""" galaxy_cluster = MISPGalaxyCluster() galaxy_cluster.from_dict(**kwargs) self.clusters.append(galaxy_cluster) return galaxy_cluster def __repr__(self) -> str: if hasattr(self, 'name'): return '<{self.__class__.__name__}(name={self.name})'.format(self=self) return f'<{self.__class__.__name__}(NotInitialized)'
() -> 'None'
25,461
pymisp.mispevent
__init__
null
def __init__(self) -> None: super().__init__() self.GalaxyCluster: list[MISPGalaxyCluster] = [] self.name: str
(self) -> NoneType
25,472
pymisp.mispevent
add_galaxy_cluster
Add a MISP galaxy cluster into a MISPGalaxy. Supports all other parameters supported by MISPGalaxyCluster
def add_galaxy_cluster(self, **kwargs) -> MISPGalaxyCluster: # type: ignore[no-untyped-def] """Add a MISP galaxy cluster into a MISPGalaxy. Supports all other parameters supported by MISPGalaxyCluster""" galaxy_cluster = MISPGalaxyCluster() galaxy_cluster.from_dict(**kwargs) self.clusters.append(galaxy_cluster) return galaxy_cluster
(self, **kwargs) -> pymisp.mispevent.MISPGalaxyCluster
25,474
pymisp.mispevent
from_dict
Galaxy could be in one of the following formats: {'Galaxy': {}, 'GalaxyCluster': []} {'Galaxy': {'GalaxyCluster': []}}
def from_dict(self, **kwargs) -> None: # type: ignore[no-untyped-def] """Galaxy could be in one of the following formats: {'Galaxy': {}, 'GalaxyCluster': []} {'Galaxy': {'GalaxyCluster': []}} """ if 'GalaxyCluster' in kwargs and kwargs.get("withCluster", True): # Parse the cluster from the kwargs [self.add_galaxy_cluster(**e) for e in kwargs.pop('GalaxyCluster')] if 'Galaxy' in kwargs: kwargs = kwargs['Galaxy'] super().from_dict(**kwargs)
(self, **kwargs) -> NoneType
25,489
pymisp.mispevent
MISPGalaxyCluster
A MISP galaxy cluster, storing respective galaxy elements and relations. Used to view default galaxy clusters and add/edit/update/delete Galaxy 2.0 clusters Creating a new galaxy cluster can take the following parameters :param value: The value of the galaxy cluster :type value: str :param description: The description of the galaxy cluster :type description: str :param distribution: The distribution type, one of 0, 1, 2, 3, 4 :type distribution: int :param sharing_group_id: The sharing group ID, if distribution is set to 4 :type sharing_group_id: int, optional :param authors: A list of authors of the galaxy cluster :type authors: list[str], optional :param cluster_elements: List of MISPGalaxyClusterElement :type cluster_elements: list[MISPGalaxyClusterElement], optional :param cluster_relations: List of MISPGalaxyClusterRelation :type cluster_relations: list[MISPGalaxyClusterRelation], optional
class MISPGalaxyCluster(AbstractMISP): """A MISP galaxy cluster, storing respective galaxy elements and relations. Used to view default galaxy clusters and add/edit/update/delete Galaxy 2.0 clusters Creating a new galaxy cluster can take the following parameters :param value: The value of the galaxy cluster :type value: str :param description: The description of the galaxy cluster :type description: str :param distribution: The distribution type, one of 0, 1, 2, 3, 4 :type distribution: int :param sharing_group_id: The sharing group ID, if distribution is set to 4 :type sharing_group_id: int, optional :param authors: A list of authors of the galaxy cluster :type authors: list[str], optional :param cluster_elements: List of MISPGalaxyClusterElement :type cluster_elements: list[MISPGalaxyClusterElement], optional :param cluster_relations: List of MISPGalaxyClusterRelation :type cluster_relations: list[MISPGalaxyClusterRelation], optional """ id: int | str | None tag_name: str galaxy_id: str | None def __init__(self) -> None: super().__init__() self.Galaxy: MISPGalaxy self.GalaxyElement: list[MISPGalaxyClusterElement] = [] self.meta: dict[str, Any] = {} self.GalaxyClusterRelation: list[MISPGalaxyClusterRelation] = [] self.Org: MISPOrganisation self.Orgc: MISPOrganisation self.SharingGroup: MISPSharingGroup self.value: str # Set any inititialized cluster to be False self.default = False @property def cluster_elements(self) -> list[MISPGalaxyClusterElement]: return self.GalaxyElement @cluster_elements.setter def cluster_elements(self, cluster_elements: list[MISPGalaxyClusterElement]) -> None: self.GalaxyElement = cluster_elements @property def cluster_relations(self) -> list[MISPGalaxyClusterRelation]: return self.GalaxyClusterRelation @cluster_relations.setter def cluster_relations(self, cluster_relations: list[MISPGalaxyClusterRelation]) -> None: self.GalaxyClusterRelation = cluster_relations def parse_meta_as_elements(self) -> None: """Function to parse the meta field into GalaxyClusterElements""" # Parse the cluster elements from the kwargs meta fields for key, value in self.meta.items(): # The meta will merge fields together, i.e. Two 'countries' will be a list, so split these up if not isinstance(value, list): value = [value] for v in value: self.add_cluster_element(key=key, value=v) @property def elements_meta(self) -> dict[str, Any]: """Function to return the galaxy cluster elements as a dictionary structure of lists that comes from a MISPGalaxy within a MISPEvent. Lossy, you lose the element ID """ response = defaultdict(list) for element in self.cluster_elements: response[element.key].append(element.value) return dict(response) def from_dict(self, **kwargs) -> None: # type: ignore[no-untyped-def] if 'GalaxyCluster' in kwargs: kwargs = kwargs['GalaxyCluster'] self.default = kwargs.pop('default', False) # If the default field is set, we shouldn't have distribution or sharing group ID set if self.default: blocked_fields = ["distribution" "sharing_group_id"] for field in blocked_fields: if kwargs.get(field, None): raise NewGalaxyClusterError( f"The field '{field}' cannot be set on a default galaxy cluster" ) self.distribution = int(kwargs.pop('distribution', 0)) if self.distribution not in [0, 1, 2, 3, 4]: raise NewGalaxyClusterError(f'{self.distribution} is invalid, the distribution has to be in 0, 1, 2, 3, 4') if kwargs.get('sharing_group_id'): self.sharing_group_id = int(kwargs.pop('sharing_group_id')) if self.distribution == 4: # The distribution is set to sharing group, a sharing_group_id is required. if not hasattr(self, 'sharing_group_id'): raise NewGalaxyClusterError('If the distribution is set to sharing group, a sharing group ID is required.') elif not self.sharing_group_id: # Cannot be None or 0 either. raise NewGalaxyClusterError(f'If the distribution is set to sharing group, a sharing group ID is required (cannot be {self.sharing_group_id}).') if 'uuid' in kwargs: self.uuid = kwargs.pop('uuid') if 'meta' in kwargs: self.meta = kwargs.pop('meta') if 'Galaxy' in kwargs: self.Galaxy = MISPGalaxy() self.Galaxy.from_dict(**kwargs.pop('Galaxy')) if 'GalaxyElement' in kwargs: [self.add_cluster_element(**e) for e in kwargs.pop('GalaxyElement')] if 'Org' in kwargs: self.Org = MISPOrganisation() self.Org.from_dict(**kwargs.pop('Org')) if 'Orgc' in kwargs: self.Orgc = MISPOrganisation() self.Orgc.from_dict(**kwargs.pop('Orgc')) if 'GalaxyClusterRelation' in kwargs: [self.add_cluster_relation(**r) for r in kwargs.pop('GalaxyClusterRelation')] if 'SharingGroup' in kwargs: self.SharingGroup = MISPSharingGroup() self.SharingGroup.from_dict(**kwargs.pop('SharingGroup')) super().from_dict(**kwargs) def add_cluster_element(self, key: str, value: str, **kwargs) -> MISPGalaxyClusterElement: # type: ignore[no-untyped-def] """Add a cluster relation to a MISPGalaxyCluster, key and value are required :param key: The key name of the element :type key: str :param value: The value of the element :type value: str """ cluster_element = MISPGalaxyClusterElement() cluster_element.from_dict(key=key, value=value, **kwargs) self.cluster_elements.append(cluster_element) return cluster_element def add_cluster_relation(self, referenced_galaxy_cluster_uuid: MISPGalaxyCluster | str | UUID, referenced_galaxy_cluster_type: str, galaxy_cluster_uuid: str | None = None, **kwargs: dict[str, Any]) -> MISPGalaxyClusterRelation: """Add a cluster relation to a MISPGalaxyCluster. :param referenced_galaxy_cluster_uuid: UUID of the related cluster :type referenced_galaxy_cluster_uuid: uuid :param referenced_galaxy_cluster_type: Relation type :type referenced_galaxy_cluster_type: uuid :param galaxy_cluster_uuid: UUID of this cluster, leave blank to use the stored UUID :param galaxy_cluster_uuid: uuid, Optional """ if not getattr(self, "uuid", None): raise PyMISPError("The cluster does not have a UUID, make sure it is a valid galaxy cluster") cluster_relation = MISPGalaxyClusterRelation() if isinstance(referenced_galaxy_cluster_uuid, MISPGalaxyCluster): referenced_galaxy_cluster_uuid = referenced_galaxy_cluster_uuid.uuid cluster_relation.from_dict( referenced_galaxy_cluster_uuid=referenced_galaxy_cluster_uuid, referenced_galaxy_cluster_type=referenced_galaxy_cluster_type, galaxy_cluster_uuid=galaxy_cluster_uuid or self.uuid, **kwargs ) self.cluster_relations.append(cluster_relation) return cluster_relation def __repr__(self) -> str: if hasattr(self, 'value'): return '<{self.__class__.__name__}(value={self.value})'.format(self=self) return f'<{self.__class__.__name__}(NotInitialized)'
() -> 'None'
25,494
pymisp.mispevent
__init__
null
def __init__(self) -> None: super().__init__() self.Galaxy: MISPGalaxy self.GalaxyElement: list[MISPGalaxyClusterElement] = [] self.meta: dict[str, Any] = {} self.GalaxyClusterRelation: list[MISPGalaxyClusterRelation] = [] self.Org: MISPOrganisation self.Orgc: MISPOrganisation self.SharingGroup: MISPSharingGroup self.value: str # Set any inititialized cluster to be False self.default = False
(self) -> NoneType
25,497
pymisp.mispevent
__repr__
null
def __repr__(self) -> str: if hasattr(self, 'value'): return '<{self.__class__.__name__}(value={self.value})'.format(self=self) return f'<{self.__class__.__name__}(NotInitialized)'
(self) -> str
25,505
pymisp.mispevent
add_cluster_element
Add a cluster relation to a MISPGalaxyCluster, key and value are required :param key: The key name of the element :type key: str :param value: The value of the element :type value: str
def add_cluster_element(self, key: str, value: str, **kwargs) -> MISPGalaxyClusterElement: # type: ignore[no-untyped-def] """Add a cluster relation to a MISPGalaxyCluster, key and value are required :param key: The key name of the element :type key: str :param value: The value of the element :type value: str """ cluster_element = MISPGalaxyClusterElement() cluster_element.from_dict(key=key, value=value, **kwargs) self.cluster_elements.append(cluster_element) return cluster_element
(self, key: str, value: str, **kwargs) -> pymisp.mispevent.MISPGalaxyClusterElement
25,506
pymisp.mispevent
add_cluster_relation
Add a cluster relation to a MISPGalaxyCluster. :param referenced_galaxy_cluster_uuid: UUID of the related cluster :type referenced_galaxy_cluster_uuid: uuid :param referenced_galaxy_cluster_type: Relation type :type referenced_galaxy_cluster_type: uuid :param galaxy_cluster_uuid: UUID of this cluster, leave blank to use the stored UUID :param galaxy_cluster_uuid: uuid, Optional
def add_cluster_relation(self, referenced_galaxy_cluster_uuid: MISPGalaxyCluster | str | UUID, referenced_galaxy_cluster_type: str, galaxy_cluster_uuid: str | None = None, **kwargs: dict[str, Any]) -> MISPGalaxyClusterRelation: """Add a cluster relation to a MISPGalaxyCluster. :param referenced_galaxy_cluster_uuid: UUID of the related cluster :type referenced_galaxy_cluster_uuid: uuid :param referenced_galaxy_cluster_type: Relation type :type referenced_galaxy_cluster_type: uuid :param galaxy_cluster_uuid: UUID of this cluster, leave blank to use the stored UUID :param galaxy_cluster_uuid: uuid, Optional """ if not getattr(self, "uuid", None): raise PyMISPError("The cluster does not have a UUID, make sure it is a valid galaxy cluster") cluster_relation = MISPGalaxyClusterRelation() if isinstance(referenced_galaxy_cluster_uuid, MISPGalaxyCluster): referenced_galaxy_cluster_uuid = referenced_galaxy_cluster_uuid.uuid cluster_relation.from_dict( referenced_galaxy_cluster_uuid=referenced_galaxy_cluster_uuid, referenced_galaxy_cluster_type=referenced_galaxy_cluster_type, galaxy_cluster_uuid=galaxy_cluster_uuid or self.uuid, **kwargs ) self.cluster_relations.append(cluster_relation) return cluster_relation
(self, referenced_galaxy_cluster_uuid: pymisp.mispevent.MISPGalaxyCluster | str | uuid.UUID, referenced_galaxy_cluster_type: str, galaxy_cluster_uuid: Optional[str] = None, **kwargs: dict[str, typing.Any]) -> pymisp.mispevent.MISPGalaxyClusterRelation
25,508
pymisp.mispevent
from_dict
null
def from_dict(self, **kwargs) -> None: # type: ignore[no-untyped-def] if 'GalaxyCluster' in kwargs: kwargs = kwargs['GalaxyCluster'] self.default = kwargs.pop('default', False) # If the default field is set, we shouldn't have distribution or sharing group ID set if self.default: blocked_fields = ["distribution" "sharing_group_id"] for field in blocked_fields: if kwargs.get(field, None): raise NewGalaxyClusterError( f"The field '{field}' cannot be set on a default galaxy cluster" ) self.distribution = int(kwargs.pop('distribution', 0)) if self.distribution not in [0, 1, 2, 3, 4]: raise NewGalaxyClusterError(f'{self.distribution} is invalid, the distribution has to be in 0, 1, 2, 3, 4') if kwargs.get('sharing_group_id'): self.sharing_group_id = int(kwargs.pop('sharing_group_id')) if self.distribution == 4: # The distribution is set to sharing group, a sharing_group_id is required. if not hasattr(self, 'sharing_group_id'): raise NewGalaxyClusterError('If the distribution is set to sharing group, a sharing group ID is required.') elif not self.sharing_group_id: # Cannot be None or 0 either. raise NewGalaxyClusterError(f'If the distribution is set to sharing group, a sharing group ID is required (cannot be {self.sharing_group_id}).') if 'uuid' in kwargs: self.uuid = kwargs.pop('uuid') if 'meta' in kwargs: self.meta = kwargs.pop('meta') if 'Galaxy' in kwargs: self.Galaxy = MISPGalaxy() self.Galaxy.from_dict(**kwargs.pop('Galaxy')) if 'GalaxyElement' in kwargs: [self.add_cluster_element(**e) for e in kwargs.pop('GalaxyElement')] if 'Org' in kwargs: self.Org = MISPOrganisation() self.Org.from_dict(**kwargs.pop('Org')) if 'Orgc' in kwargs: self.Orgc = MISPOrganisation() self.Orgc.from_dict(**kwargs.pop('Orgc')) if 'GalaxyClusterRelation' in kwargs: [self.add_cluster_relation(**r) for r in kwargs.pop('GalaxyClusterRelation')] if 'SharingGroup' in kwargs: self.SharingGroup = MISPSharingGroup() self.SharingGroup.from_dict(**kwargs.pop('SharingGroup')) super().from_dict(**kwargs)
(self, **kwargs) -> NoneType
25,514
pymisp.mispevent
parse_meta_as_elements
Function to parse the meta field into GalaxyClusterElements
def parse_meta_as_elements(self) -> None: """Function to parse the meta field into GalaxyClusterElements""" # Parse the cluster elements from the kwargs meta fields for key, value in self.meta.items(): # The meta will merge fields together, i.e. Two 'countries' will be a list, so split these up if not isinstance(value, list): value = [value] for v in value: self.add_cluster_element(key=key, value=v)
(self) -> NoneType
25,524
pymisp.mispevent
MISPGalaxyClusterElement
A MISP Galaxy cluster element, providing further info on a cluster Creating a new galaxy cluster element can take the following parameters :param key: The key/identifier of the element :type key: str :param value: The value of the element :type value: str
class MISPGalaxyClusterElement(AbstractMISP): """A MISP Galaxy cluster element, providing further info on a cluster Creating a new galaxy cluster element can take the following parameters :param key: The key/identifier of the element :type key: str :param value: The value of the element :type value: str """ key: str value: str def __repr__(self) -> str: if hasattr(self, 'key') and hasattr(self, 'value'): return '<{self.__class__.__name__}(key={self.key}, value={self.value})'.format(self=self) return f'<{self.__class__.__name__}(NotInitialized)' def __setattr__(self, key: str, value: Any) -> None: if key == "value" and isinstance(value, list): raise PyMISPError("You tried to set a list to a cluster element's value. " "Instead, create seperate elements for each value") super().__setattr__(key, value) def from_dict(self, **kwargs) -> None: # type: ignore[no-untyped-def] if kwargs.get('id'): self.id = int(kwargs.pop('id')) if kwargs.get('galaxy_cluster_id'): self.galaxy_cluster_id = int(kwargs.pop('galaxy_cluster_id')) super().from_dict(**kwargs)
(**kwargs) -> 'None'
25,532
pymisp.mispevent
__repr__
null
def __repr__(self) -> str: if hasattr(self, 'key') and hasattr(self, 'value'): return '<{self.__class__.__name__}(key={self.key}, value={self.value})'.format(self=self) return f'<{self.__class__.__name__}(NotInitialized)'
(self) -> str
25,533
pymisp.mispevent
__setattr__
null
def __setattr__(self, key: str, value: Any) -> None: if key == "value" and isinstance(value, list): raise PyMISPError("You tried to set a list to a cluster element's value. " "Instead, create seperate elements for each value") super().__setattr__(key, value)
(self, key: str, value: Any) -> NoneType
25,541
pymisp.mispevent
from_dict
null
def from_dict(self, **kwargs) -> None: # type: ignore[no-untyped-def] if kwargs.get('id'): self.id = int(kwargs.pop('id')) if kwargs.get('galaxy_cluster_id'): self.galaxy_cluster_id = int(kwargs.pop('galaxy_cluster_id')) super().from_dict(**kwargs)
(self, **kwargs) -> NoneType
25,556
pymisp.mispevent
MISPGalaxyClusterRelation
A MISP Galaxy cluster relation, linking one cluster to another Creating a new galaxy cluster can take the following parameters :param galaxy_cluster_uuid: The UUID of the galaxy the relation links to :param referenced_galaxy_cluster_type: The relation type, e.g. dropped-by :param referenced_galaxy_cluster_uuid: The UUID of the related galaxy :param distribution: The distribution of the relation, one of 0, 1, 2, 3, 4, default 0 :param sharing_group_id: The sharing group of the relation, only when distribution is 4
class MISPGalaxyClusterRelation(AbstractMISP): """A MISP Galaxy cluster relation, linking one cluster to another Creating a new galaxy cluster can take the following parameters :param galaxy_cluster_uuid: The UUID of the galaxy the relation links to :param referenced_galaxy_cluster_type: The relation type, e.g. dropped-by :param referenced_galaxy_cluster_uuid: The UUID of the related galaxy :param distribution: The distribution of the relation, one of 0, 1, 2, 3, 4, default 0 :param sharing_group_id: The sharing group of the relation, only when distribution is 4 """ def __repr__(self) -> str: if hasattr(self, "referenced_galaxy_cluster_type"): return '<{self.__class__.__name__}(referenced_galaxy_cluster_type={self.referenced_galaxy_cluster_type})'.format(self=self) return f'<{self.__class__.__name__}(NotInitialized)' def __init__(self) -> None: super().__init__() self.galaxy_cluster_uuid: str self.referenced_galaxy_cluster_uuid: str self.distribution: int = 0 self.referenced_galaxy_cluster_type: str self.Tag: list[MISPTag] = [] def from_dict(self, **kwargs) -> None: # type: ignore[no-untyped-def] # Default values for a valid event to send to a MISP instance self.distribution = int(kwargs.pop('distribution', 0)) if self.distribution not in [0, 1, 2, 3, 4, 5]: raise NewGalaxyClusterRelationError(f'{self.distribution} is invalid, the distribution has to be in 0, 1, 2, 3, 4') if kwargs.get('sharing_group_id'): self.sharing_group_id = int(kwargs.pop('sharing_group_id')) if self.distribution == 4: # The distribution is set to sharing group, a sharing_group_id is required. if not hasattr(self, 'sharing_group_id'): raise NewGalaxyClusterRelationError('If the distribution is set to sharing group, a sharing group ID is required.') elif not self.sharing_group_id: # Cannot be None or 0 either. raise NewGalaxyClusterRelationError(f'If the distribution is set to sharing group, a sharing group ID is required (cannot be {self.sharing_group_id}).') if kwargs.get('id'): self.id = int(kwargs.pop('id')) if kwargs.get('orgc_id'): self.orgc_id = int(kwargs.pop('orgc_id')) if kwargs.get('org_id'): self.org_id = int(kwargs.pop('org_id')) if kwargs.get('galaxy_id'): self.galaxy_id = int(kwargs.pop('galaxy_id')) if kwargs.get('tag_id'): self.tag_id = int(kwargs.pop('tag_id')) if kwargs.get('sharing_group_id'): self.sharing_group_id = int(kwargs.pop('sharing_group_id')) if kwargs.get('Tag'): [self.add_tag(**t) for t in kwargs.pop('Tag')] if kwargs.get('SharingGroup'): self.SharingGroup = MISPSharingGroup() self.SharingGroup.from_dict(**kwargs.pop('SharingGroup')) super().from_dict(**kwargs) def add_tag(self, tag: str | MISPTag | dict[str, Any] | None = None, **kwargs) -> MISPTag: # type: ignore[no-untyped-def] return super()._add_tag(tag, **kwargs) @property def tags(self) -> list[MISPTag]: """Returns a list of tags associated to this Attribute""" return self.Tag @tags.setter def tags(self, tags: list[MISPTag]) -> None: """Set a list of prepared MISPTag.""" super()._set_tags(tags)
() -> 'None'
25,561
pymisp.mispevent
__init__
null
def __init__(self) -> None: super().__init__() self.galaxy_cluster_uuid: str self.referenced_galaxy_cluster_uuid: str self.distribution: int = 0 self.referenced_galaxy_cluster_type: str self.Tag: list[MISPTag] = []
(self) -> NoneType
25,564
pymisp.mispevent
__repr__
null
def __repr__(self) -> str: if hasattr(self, "referenced_galaxy_cluster_type"): return '<{self.__class__.__name__}(referenced_galaxy_cluster_type={self.referenced_galaxy_cluster_type})'.format(self=self) return f'<{self.__class__.__name__}(NotInitialized)'
(self) -> str
25,574
pymisp.mispevent
from_dict
null
def from_dict(self, **kwargs) -> None: # type: ignore[no-untyped-def] # Default values for a valid event to send to a MISP instance self.distribution = int(kwargs.pop('distribution', 0)) if self.distribution not in [0, 1, 2, 3, 4, 5]: raise NewGalaxyClusterRelationError(f'{self.distribution} is invalid, the distribution has to be in 0, 1, 2, 3, 4') if kwargs.get('sharing_group_id'): self.sharing_group_id = int(kwargs.pop('sharing_group_id')) if self.distribution == 4: # The distribution is set to sharing group, a sharing_group_id is required. if not hasattr(self, 'sharing_group_id'): raise NewGalaxyClusterRelationError('If the distribution is set to sharing group, a sharing group ID is required.') elif not self.sharing_group_id: # Cannot be None or 0 either. raise NewGalaxyClusterRelationError(f'If the distribution is set to sharing group, a sharing group ID is required (cannot be {self.sharing_group_id}).') if kwargs.get('id'): self.id = int(kwargs.pop('id')) if kwargs.get('orgc_id'): self.orgc_id = int(kwargs.pop('orgc_id')) if kwargs.get('org_id'): self.org_id = int(kwargs.pop('org_id')) if kwargs.get('galaxy_id'): self.galaxy_id = int(kwargs.pop('galaxy_id')) if kwargs.get('tag_id'): self.tag_id = int(kwargs.pop('tag_id')) if kwargs.get('sharing_group_id'): self.sharing_group_id = int(kwargs.pop('sharing_group_id')) if kwargs.get('Tag'): [self.add_tag(**t) for t in kwargs.pop('Tag')] if kwargs.get('SharingGroup'): self.SharingGroup = MISPSharingGroup() self.SharingGroup.from_dict(**kwargs.pop('SharingGroup')) super().from_dict(**kwargs)
(self, **kwargs) -> NoneType
25,589
pymisp.mispevent
MISPInbox
null
class MISPInbox(AbstractMISP): def __init__(self, **kwargs: dict[str, Any]) -> None: super().__init__(**kwargs) self.data: dict[str, Any] self.type: str def from_dict(self, **kwargs) -> None: # type: ignore[no-untyped-def] if 'Inbox' in kwargs: kwargs = kwargs['Inbox'] super().from_dict(**kwargs) def __repr__(self) -> str: return f'<{self.__class__.__name__}(name={self.type})>'
(**kwargs: 'dict[str, Any]') -> 'None'
25,594
pymisp.mispevent
__init__
null
def __init__(self, **kwargs: dict[str, Any]) -> None: super().__init__(**kwargs) self.data: dict[str, Any] self.type: str
(self, **kwargs: dict[str, typing.Any]) -> NoneType
25,597
pymisp.mispevent
__repr__
null
def __repr__(self) -> str: return f'<{self.__class__.__name__}(name={self.type})>'
(self) -> str
25,606
pymisp.mispevent
from_dict
null
def from_dict(self, **kwargs) -> None: # type: ignore[no-untyped-def] if 'Inbox' in kwargs: kwargs = kwargs['Inbox'] super().from_dict(**kwargs)
(self, **kwargs) -> NoneType
25,621
pymisp.mispevent
MISPLog
null
class MISPLog(AbstractMISP): def __init__(self, **kwargs: dict[str, Any]) -> None: super().__init__(**kwargs) self.model: str self.action: str self.title: str def from_dict(self, **kwargs) -> None: # type: ignore[no-untyped-def] if 'Log' in kwargs: kwargs = kwargs['Log'] super().from_dict(**kwargs) def __repr__(self) -> str: return '<{self.__class__.__name__}({self.model}, {self.action}, {self.title})'.format(self=self)
(**kwargs: 'dict[str, Any]') -> 'None'
25,626
pymisp.mispevent
__init__
null
def __init__(self, **kwargs: dict[str, Any]) -> None: super().__init__(**kwargs) self.model: str self.action: str self.title: str
(self, **kwargs: dict[str, typing.Any]) -> NoneType
25,629
pymisp.mispevent
__repr__
null
def __repr__(self) -> str: return '<{self.__class__.__name__}({self.model}, {self.action}, {self.title})'.format(self=self)
(self) -> str