Merge branch 'paalbra-add-missing-whitespace' into main

pull/612/head
Raphaël Vinot 2020-07-29 11:27:39 +02:00
commit a5ff0b850e
19 changed files with 232 additions and 232 deletions

View File

@ -240,7 +240,7 @@ class AbstractMISP(MutableMapping, MISPFileCache, metaclass=ABCMeta):
to_return = _int_to_str(to_return) to_return = _int_to_str(to_return)
return to_return return to_return
def to_json(self, sort_keys: bool=False, indent: Optional[int]=None): def to_json(self, sort_keys: bool = False, indent: Optional[int] = None):
"""Dump recursively any class of type MISPAbstract to a json string""" """Dump recursively any class of type MISPAbstract to a json string"""
return dumps(self, default=pymisp_json_default, sort_keys=sort_keys, indent=indent) return dumps(self, default=pymisp_json_default, sort_keys=sort_keys, indent=indent)
@ -311,7 +311,7 @@ class AbstractMISP(MutableMapping, MISPFileCache, metaclass=ABCMeta):
return int(d) return int(d)
return int(d.timestamp()) return int(d.timestamp())
def _add_tag(self, tag: Optional[Union[str, 'MISPTag', Mapping]]=None, **kwargs): def _add_tag(self, tag: Optional[Union[str, 'MISPTag', Mapping]] = None, **kwargs):
"""Add a tag to the attribute (by name or a MISPTag object)""" """Add a tag to the attribute (by name or a MISPTag object)"""
if isinstance(tag, str): if isinstance(tag, str):
misp_tag = MISPTag() misp_tag = MISPTag()

View File

@ -56,11 +56,11 @@ def get_uuid_or_id_from_abstract_misp(obj: Union[AbstractMISP, int, str, UUID])
def register_user(misp_url: str, email: str, def register_user(misp_url: str, email: str,
organisation: Union[MISPOrganisation, int, str, UUID]=None, organisation: Union[MISPOrganisation, int, str, UUID] = None,
org_id: Optional[str]=None, org_name: Optional[str]=None, org_id: Optional[str] = None, org_name: Optional[str] = None,
message: Optional[str]=None, custom_perms: Optional[str]=None, message: Optional[str] = None, custom_perms: Optional[str] = None,
perm_sync: bool=False, perm_publish: bool=False, perm_admin: bool=False, perm_sync: bool = False, perm_publish: bool = False, perm_admin: bool = False,
verify: bool=True) -> Dict: verify: bool = True) -> Dict:
"""Ask for the creation of an account for the user with the given email address""" """Ask for the creation of an account for the user with the given email address"""
data = copy.deepcopy(locals()) data = copy.deepcopy(locals())
if organisation: if organisation:
@ -90,8 +90,8 @@ class PyMISP:
:param timeout: Timeout as described here: https://requests.readthedocs.io/en/master/user/advanced/#timeouts :param timeout: Timeout as described here: https://requests.readthedocs.io/en/master/user/advanced/#timeouts
""" """
def __init__(self, url: str, key: str, ssl: bool=True, debug: bool=False, proxies: Mapping={}, def __init__(self, url: str, key: str, ssl: bool = True, debug: bool = False, proxies: Mapping = {},
cert: Tuple[str, tuple]=None, auth: AuthBase=None, tool: str='', timeout: Optional[Union[float, Tuple[float, float]]]=None): cert: Tuple[str, tuple] = None, auth: AuthBase = None, tool: str = '', timeout: Optional[Union[float, Tuple[float, float]]] = None):
if not url: if not url:
raise NoURL('Please provide the URL of your MISP instance.') raise NoURL('Please provide the URL of your MISP instance.')
if not key: if not key:
@ -148,7 +148,7 @@ class PyMISP:
self.category_type_mapping = self.describe_types['category_type_mappings'] self.category_type_mapping = self.describe_types['category_type_mappings']
self.sane_default = self.describe_types['sane_defaults'] self.sane_default = self.describe_types['sane_defaults']
def remote_acl(self, debug_type: str='findMissingFunctionNames') -> Dict: def remote_acl(self, debug_type: str = 'findMissingFunctionNames') -> Dict:
"""This should return an empty list, unless the ACL is outdated. """This should return an empty list, unless the ACL is outdated.
debug_type can only be printAllFunctionNames, findMissingFunctionNames, or printRoleAccess debug_type can only be printAllFunctionNames, findMissingFunctionNames, or printRoleAccess
""" """
@ -210,7 +210,7 @@ class PyMISP:
response = self._prepare_request('POST', '/servers/update') response = self._prepare_request('POST', '/servers/update')
return self._check_json_response(response) return self._check_json_response(response)
def set_server_setting(self, setting: str, value: Union[str, int, bool], force: bool=False) -> Dict: def set_server_setting(self, setting: str, value: Union[str, int, bool], force: bool = False) -> Dict:
data = {'value': value, 'force': force} data = {'value': value, 'force': force}
response = self._prepare_request('POST', f'/servers/serverSettingsEdit/{setting}', data=data) response = self._prepare_request('POST', f'/servers/serverSettingsEdit/{setting}', data=data)
return self._check_json_response(response) return self._check_json_response(response)
@ -236,7 +236,7 @@ class PyMISP:
# ## BEGIN Event ## # ## BEGIN Event ##
def events(self, pythonify: bool=False) -> Union[Dict, List[MISPEvent]]: def events(self, pythonify: bool = False) -> Union[Dict, List[MISPEvent]]:
r = self._prepare_request('GET', 'events') r = self._prepare_request('GET', 'events')
events_r = self._check_json_response(r) events_r = self._check_json_response(r)
if not (self.global_pythonify or pythonify) or 'errors' in events_r: if not (self.global_pythonify or pythonify) or 'errors' in events_r:
@ -249,9 +249,9 @@ class PyMISP:
return to_return return to_return
def get_event(self, event: Union[MISPEvent, int, str, UUID], def get_event(self, event: Union[MISPEvent, int, str, UUID],
deleted: Union[bool, int, list]=False, deleted: Union[bool, int, list] = False,
extended: Union[bool, int]=False, extended: Union[bool, int] = False,
pythonify: bool=False) -> Union[Dict, MISPEvent]: pythonify: bool = False) -> Union[Dict, MISPEvent]:
'''Get an event from a MISP instance''' '''Get an event from a MISP instance'''
event_id = get_uuid_or_id_from_abstract_misp(event) event_id = get_uuid_or_id_from_abstract_misp(event)
data = {} data = {}
@ -270,7 +270,7 @@ class PyMISP:
e.load(event_r) e.load(event_r)
return e return e
def add_event(self, event: MISPEvent, pythonify: bool=False) -> Union[Dict, MISPEvent]: def add_event(self, event: MISPEvent, pythonify: bool = False) -> Union[Dict, MISPEvent]:
'''Add a new event on a MISP instance''' '''Add a new event on a MISP instance'''
r = self._prepare_request('POST', 'events', data=event) r = self._prepare_request('POST', 'events', data=event)
new_event = self._check_json_response(r) new_event = self._check_json_response(r)
@ -280,7 +280,7 @@ class PyMISP:
e.load(new_event) e.load(new_event)
return e return e
def update_event(self, event: MISPEvent, event_id: Optional[int]=None, pythonify: bool=False) -> Union[Dict, MISPEvent]: def update_event(self, event: MISPEvent, event_id: Optional[int] = None, pythonify: bool = False) -> Union[Dict, MISPEvent]:
'''Update an event on a MISP instance''' '''Update an event on a MISP instance'''
if event_id is None: if event_id is None:
eid = get_uuid_or_id_from_abstract_misp(event) eid = get_uuid_or_id_from_abstract_misp(event)
@ -300,7 +300,7 @@ class PyMISP:
response = self._prepare_request('DELETE', f'events/delete/{event_id}') response = self._prepare_request('DELETE', f'events/delete/{event_id}')
return self._check_json_response(response) return self._check_json_response(response)
def publish(self, event: Union[MISPEvent, int, str, UUID], alert: bool=False) -> Dict: def publish(self, event: Union[MISPEvent, int, str, UUID], alert: bool = False) -> Dict:
"""Publish the event with one single HTTP POST. """Publish the event with one single HTTP POST.
The default is to not send a mail as it is assumed this method is called on update. The default is to not send a mail as it is assumed this method is called on update.
""" """
@ -322,7 +322,7 @@ class PyMISP:
# ## BEGIN Object ### # ## BEGIN Object ###
def get_object(self, misp_object: Union[MISPObject, int, str, UUID], pythonify: bool=False) -> Union[Dict, MISPObject]: def get_object(self, misp_object: Union[MISPObject, int, str, UUID], pythonify: bool = False) -> Union[Dict, MISPObject]:
'''Get an object from the remote MISP instance''' '''Get an object from the remote MISP instance'''
object_id = get_uuid_or_id_from_abstract_misp(misp_object) object_id = get_uuid_or_id_from_abstract_misp(misp_object)
r = self._prepare_request('GET', f'objects/view/{object_id}') r = self._prepare_request('GET', f'objects/view/{object_id}')
@ -333,7 +333,7 @@ class PyMISP:
o.from_dict(**misp_object_r) o.from_dict(**misp_object_r)
return o return o
def add_object(self, event: Union[MISPEvent, int, str, UUID], misp_object: MISPObject, pythonify: bool=False) -> Union[Dict, MISPObject]: def add_object(self, event: Union[MISPEvent, int, str, UUID], misp_object: MISPObject, pythonify: bool = False) -> Union[Dict, MISPObject]:
'''Add a MISP Object to an existing MISP event''' '''Add a MISP Object to an existing MISP event'''
event_id = get_uuid_or_id_from_abstract_misp(event) event_id = get_uuid_or_id_from_abstract_misp(event)
r = self._prepare_request('POST', f'objects/add/{event_id}', data=misp_object) r = self._prepare_request('POST', f'objects/add/{event_id}', data=misp_object)
@ -344,7 +344,7 @@ class PyMISP:
o.from_dict(**new_object) o.from_dict(**new_object)
return o return o
def update_object(self, misp_object: MISPObject, object_id: Optional[int]=None, pythonify: bool=False) -> Union[Dict, MISPObject]: def update_object(self, misp_object: MISPObject, object_id: Optional[int] = None, pythonify: bool = False) -> Union[Dict, MISPObject]:
'''Update an object on a MISP instance''' '''Update an object on a MISP instance'''
if object_id is None: if object_id is None:
oid = get_uuid_or_id_from_abstract_misp(misp_object) oid = get_uuid_or_id_from_abstract_misp(misp_object)
@ -364,7 +364,7 @@ class PyMISP:
response = self._prepare_request('POST', f'objects/delete/{object_id}') response = self._prepare_request('POST', f'objects/delete/{object_id}')
return self._check_json_response(response) return self._check_json_response(response)
def add_object_reference(self, misp_object_reference: MISPObjectReference, pythonify: bool=False) -> Union[Dict, MISPObjectReference]: def add_object_reference(self, misp_object_reference: MISPObjectReference, pythonify: bool = False) -> Union[Dict, MISPObjectReference]:
"""Add a reference to an object""" """Add a reference to an object"""
r = self._prepare_request('POST', 'object_references/add', misp_object_reference) r = self._prepare_request('POST', 'object_references/add', misp_object_reference)
object_reference = self._check_json_response(r) object_reference = self._check_json_response(r)
@ -382,7 +382,7 @@ class PyMISP:
# Object templates # Object templates
def object_templates(self, pythonify: bool=False) -> Union[Dict, List[MISPObjectTemplate]]: def object_templates(self, pythonify: bool = False) -> Union[Dict, List[MISPObjectTemplate]]:
"""Get all the object templates.""" """Get all the object templates."""
r = self._prepare_request('GET', 'objectTemplates') r = self._prepare_request('GET', 'objectTemplates')
templates = self._check_json_response(r) templates = self._check_json_response(r)
@ -395,7 +395,7 @@ class PyMISP:
to_return.append(o) to_return.append(o)
return to_return return to_return
def get_object_template(self, object_template: Union[MISPObjectTemplate, int, str, UUID], pythonify: bool=False) -> Union[Dict, MISPObjectTemplate]: def get_object_template(self, object_template: Union[MISPObjectTemplate, int, str, UUID], pythonify: bool = False) -> Union[Dict, MISPObjectTemplate]:
"""Gets the full object template corresponting the UUID passed as parameter""" """Gets the full object template corresponting the UUID passed as parameter"""
object_template_id = get_uuid_or_id_from_abstract_misp(object_template) object_template_id = get_uuid_or_id_from_abstract_misp(object_template)
r = self._prepare_request('GET', f'objectTemplates/view/{object_template_id}') r = self._prepare_request('GET', f'objectTemplates/view/{object_template_id}')
@ -415,7 +415,7 @@ class PyMISP:
# ## BEGIN Attribute ### # ## BEGIN Attribute ###
def attributes(self, pythonify: bool=False) -> Union[Dict, List[MISPAttribute]]: def attributes(self, pythonify: bool = False) -> Union[Dict, List[MISPAttribute]]:
r = self._prepare_request('GET', 'attributes/index') r = self._prepare_request('GET', 'attributes/index')
attributes_r = self._check_json_response(r) attributes_r = self._check_json_response(r)
if not (self.global_pythonify or pythonify) or 'errors' in attributes_r: if not (self.global_pythonify or pythonify) or 'errors' in attributes_r:
@ -427,7 +427,7 @@ class PyMISP:
to_return.append(a) to_return.append(a)
return to_return return to_return
def get_attribute(self, attribute: Union[MISPAttribute, int, str, UUID], pythonify: bool=False) -> Union[Dict, MISPAttribute]: def get_attribute(self, attribute: Union[MISPAttribute, int, str, UUID], pythonify: bool = False) -> Union[Dict, MISPAttribute]:
'''Get an attribute from a MISP instance''' '''Get an attribute from a MISP instance'''
attribute_id = get_uuid_or_id_from_abstract_misp(attribute) attribute_id = get_uuid_or_id_from_abstract_misp(attribute)
r = self._prepare_request('GET', f'attributes/view/{attribute_id}') r = self._prepare_request('GET', f'attributes/view/{attribute_id}')
@ -438,7 +438,7 @@ class PyMISP:
a.from_dict(**attribute_r) a.from_dict(**attribute_r)
return a return a
def add_attribute(self, event: Union[MISPEvent, int, str, UUID], attribute: MISPAttribute, pythonify: bool=False) -> Union[Dict, MISPAttribute, MISPShadowAttribute]: def add_attribute(self, event: Union[MISPEvent, int, str, UUID], attribute: MISPAttribute, pythonify: bool = False) -> Union[Dict, MISPAttribute, MISPShadowAttribute]:
'''Add an attribute to an existing MISP event '''Add an attribute to an existing MISP event
NOTE MISP 2.4.113+: you can pass a list of attributes. NOTE MISP 2.4.113+: you can pass a list of attributes.
In that case, the pythonified response is the following: {'attributes': [MISPAttribute], 'errors': {errors by attributes}}''' In that case, the pythonified response is the following: {'attributes': [MISPAttribute], 'errors': {errors by attributes}}'''
@ -470,7 +470,7 @@ class PyMISP:
a.from_dict(**new_attribute) a.from_dict(**new_attribute)
return a return a
def update_attribute(self, attribute: MISPAttribute, attribute_id: Optional[int]=None, pythonify: bool=False) -> Union[Dict, MISPAttribute, MISPShadowAttribute]: def update_attribute(self, attribute: MISPAttribute, attribute_id: Optional[int] = None, pythonify: bool = False) -> Union[Dict, MISPAttribute, MISPShadowAttribute]:
'''Update an attribute on a MISP instance''' '''Update an attribute on a MISP instance'''
if attribute_id is None: if attribute_id is None:
aid = get_uuid_or_id_from_abstract_misp(attribute) aid = get_uuid_or_id_from_abstract_misp(attribute)
@ -490,7 +490,7 @@ class PyMISP:
a.from_dict(**updated_attribute) a.from_dict(**updated_attribute)
return a return a
def delete_attribute(self, attribute: Union[MISPAttribute, int, str, UUID], hard: bool=False) -> Dict: def delete_attribute(self, attribute: Union[MISPAttribute, int, str, UUID], hard: bool = False) -> Dict:
'''Delete an attribute from a MISP instance''' '''Delete an attribute from a MISP instance'''
attribute_id = get_uuid_or_id_from_abstract_misp(attribute) attribute_id = get_uuid_or_id_from_abstract_misp(attribute)
data = {} data = {}
@ -510,7 +510,7 @@ class PyMISP:
# ## BEGIN Attribute Proposal ### # ## BEGIN Attribute Proposal ###
def attribute_proposals(self, event: Optional[Union[MISPEvent, int, str, UUID]]=None, pythonify: bool=False) -> Union[Dict, List[MISPShadowAttribute]]: def attribute_proposals(self, event: Optional[Union[MISPEvent, int, str, UUID]] = None, pythonify: bool = False) -> Union[Dict, List[MISPShadowAttribute]]:
if event: if event:
event_id = get_uuid_or_id_from_abstract_misp(event) event_id = get_uuid_or_id_from_abstract_misp(event)
r = self._prepare_request('GET', f'shadow_attributes/index/{event_id}') r = self._prepare_request('GET', f'shadow_attributes/index/{event_id}')
@ -526,7 +526,7 @@ class PyMISP:
to_return.append(a) to_return.append(a)
return to_return return to_return
def get_attribute_proposal(self, proposal: Union[MISPShadowAttribute, int, str, UUID], pythonify: bool=False) -> Union[Dict, MISPShadowAttribute]: def get_attribute_proposal(self, proposal: Union[MISPShadowAttribute, int, str, UUID], pythonify: bool = False) -> Union[Dict, MISPShadowAttribute]:
proposal_id = get_uuid_or_id_from_abstract_misp(proposal) proposal_id = get_uuid_or_id_from_abstract_misp(proposal)
r = self._prepare_request('GET', f'shadow_attributes/view/{proposal_id}') r = self._prepare_request('GET', f'shadow_attributes/view/{proposal_id}')
attribute_proposal = self._check_json_response(r) attribute_proposal = self._check_json_response(r)
@ -538,7 +538,7 @@ class PyMISP:
# NOTE: the tree following method have a very specific meaning, look at the comments # NOTE: the tree following method have a very specific meaning, look at the comments
def add_attribute_proposal(self, event: Union[MISPEvent, int, str, UUID], attribute: MISPAttribute, pythonify: bool=False) -> Union[Dict, MISPShadowAttribute]: def add_attribute_proposal(self, event: Union[MISPEvent, int, str, UUID], attribute: MISPAttribute, pythonify: bool = False) -> Union[Dict, MISPShadowAttribute]:
'''Propose a new attribute in an event''' '''Propose a new attribute in an event'''
event_id = get_uuid_or_id_from_abstract_misp(event) event_id = get_uuid_or_id_from_abstract_misp(event)
r = self._prepare_request('POST', f'shadow_attributes/add/{event_id}', data=attribute) r = self._prepare_request('POST', f'shadow_attributes/add/{event_id}', data=attribute)
@ -549,7 +549,7 @@ class PyMISP:
a.from_dict(**new_attribute_proposal) a.from_dict(**new_attribute_proposal)
return a return a
def update_attribute_proposal(self, initial_attribute: Union[MISPAttribute, int, str, UUID], attribute: MISPAttribute, pythonify: bool=False) -> Union[Dict, MISPShadowAttribute]: def update_attribute_proposal(self, initial_attribute: Union[MISPAttribute, int, str, UUID], attribute: MISPAttribute, pythonify: bool = False) -> Union[Dict, MISPShadowAttribute]:
'''Propose a change for an attribute''' '''Propose a change for an attribute'''
initial_attribute_id = get_uuid_or_id_from_abstract_misp(initial_attribute) initial_attribute_id = get_uuid_or_id_from_abstract_misp(initial_attribute)
r = self._prepare_request('POST', f'shadow_attributes/edit/{initial_attribute_id}', data=attribute) r = self._prepare_request('POST', f'shadow_attributes/edit/{initial_attribute_id}', data=attribute)
@ -584,9 +584,9 @@ class PyMISP:
# ## BEGIN Sighting ### # ## BEGIN Sighting ###
def sightings(self, misp_entity: Optional[AbstractMISP]=None, def sightings(self, misp_entity: Optional[AbstractMISP] = None,
org: Optional[Union[MISPOrganisation, int, str, UUID]]=None, org: Optional[Union[MISPOrganisation, int, str, UUID]] = None,
pythonify: bool=False) -> Union[Dict, List[MISPSighting]]: pythonify: bool = False) -> Union[Dict, List[MISPSighting]]:
"""Get the list of sighting related to a MISPEvent or a MISPAttribute (depending on type of misp_entity)""" """Get the list of sighting related to a MISPEvent or a MISPAttribute (depending on type of misp_entity)"""
if isinstance(misp_entity, MISPEvent): if isinstance(misp_entity, MISPEvent):
url = 'sightings/listSightings' url = 'sightings/listSightings'
@ -614,8 +614,8 @@ class PyMISP:
return to_return return to_return
def add_sighting(self, sighting: MISPSighting, def add_sighting(self, sighting: MISPSighting,
attribute: Optional[Union[MISPAttribute, int, str, UUID]]=None, attribute: Optional[Union[MISPAttribute, int, str, UUID]] = None,
pythonify: bool=False) -> Union[Dict, MISPSighting]: pythonify: bool = False) -> Union[Dict, MISPSighting]:
'''Add a new sighting (globally, or to a specific attribute)''' '''Add a new sighting (globally, or to a specific attribute)'''
if attribute: if attribute:
attribute_id = get_uuid_or_id_from_abstract_misp(attribute) attribute_id = get_uuid_or_id_from_abstract_misp(attribute)
@ -640,7 +640,7 @@ class PyMISP:
# ## BEGIN Tags ### # ## BEGIN Tags ###
def tags(self, pythonify: bool=False) -> Union[Dict, List[MISPTag]]: def tags(self, pythonify: bool = False) -> Union[Dict, List[MISPTag]]:
"""Get the list of existing tags.""" """Get the list of existing tags."""
r = self._prepare_request('GET', 'tags') r = self._prepare_request('GET', 'tags')
tags = self._check_json_response(r) tags = self._check_json_response(r)
@ -653,7 +653,7 @@ class PyMISP:
to_return.append(t) to_return.append(t)
return to_return return to_return
def get_tag(self, tag: Union[MISPTag, int, str, UUID], pythonify: bool=False) -> Union[Dict, MISPTag]: def get_tag(self, tag: Union[MISPTag, int, str, UUID], pythonify: bool = False) -> Union[Dict, MISPTag]:
"""Get a tag by id.""" """Get a tag by id."""
tag_id = get_uuid_or_id_from_abstract_misp(tag) tag_id = get_uuid_or_id_from_abstract_misp(tag)
r = self._prepare_request('GET', f'tags/view/{tag_id}') r = self._prepare_request('GET', f'tags/view/{tag_id}')
@ -664,7 +664,7 @@ class PyMISP:
t.from_dict(**tag_r) t.from_dict(**tag_r)
return t return t
def add_tag(self, tag: MISPTag, pythonify: bool=False) -> Union[Dict, MISPTag]: def add_tag(self, tag: MISPTag, pythonify: bool = False) -> Union[Dict, MISPTag]:
'''Add a new tag on a MISP instance '''Add a new tag on a MISP instance
Notes: Notes:
* The user calling this method needs the Tag Editor permission * The user calling this method needs the Tag Editor permission
@ -678,17 +678,17 @@ class PyMISP:
t.from_dict(**new_tag) t.from_dict(**new_tag)
return t return t
def enable_tag(self, tag: MISPTag, pythonify: bool=False) -> Union[Dict, MISPTag]: def enable_tag(self, tag: MISPTag, pythonify: bool = False) -> Union[Dict, MISPTag]:
"""Enable a tag.""" """Enable a tag."""
tag.hide_tag = False tag.hide_tag = False
return self.update_tag(tag, pythonify=pythonify) return self.update_tag(tag, pythonify=pythonify)
def disable_tag(self, tag: MISPTag, pythonify: bool=False) -> Union[Dict, MISPTag]: def disable_tag(self, tag: MISPTag, pythonify: bool = False) -> Union[Dict, MISPTag]:
"""Disable a tag.""" """Disable a tag."""
tag.hide_tag = True tag.hide_tag = True
return self.update_tag(tag, pythonify=pythonify) return self.update_tag(tag, pythonify=pythonify)
def update_tag(self, tag: MISPTag, tag_id: Optional[int]=None, pythonify: bool=False) -> Union[Dict, MISPTag]: def update_tag(self, tag: MISPTag, tag_id: Optional[int] = None, pythonify: bool = False) -> Union[Dict, MISPTag]:
"""Edit only the provided parameters of a tag.""" """Edit only the provided parameters of a tag."""
if tag_id is None: if tag_id is None:
tid = get_uuid_or_id_from_abstract_misp(tag) tid = get_uuid_or_id_from_abstract_misp(tag)
@ -712,7 +712,7 @@ class PyMISP:
# ## BEGIN Taxonomies ### # ## BEGIN Taxonomies ###
def taxonomies(self, pythonify: bool=False) -> Union[Dict, List[MISPTaxonomy]]: def taxonomies(self, pythonify: bool = False) -> Union[Dict, List[MISPTaxonomy]]:
"""Get all the taxonomies.""" """Get all the taxonomies."""
r = self._prepare_request('GET', 'taxonomies') r = self._prepare_request('GET', 'taxonomies')
taxonomies = self._check_json_response(r) taxonomies = self._check_json_response(r)
@ -725,7 +725,7 @@ class PyMISP:
to_return.append(t) to_return.append(t)
return to_return return to_return
def get_taxonomy(self, taxonomy: Union[MISPTaxonomy, int, str, UUID], pythonify: bool=False) -> Union[Dict, MISPTaxonomy]: def get_taxonomy(self, taxonomy: Union[MISPTaxonomy, int, str, UUID], pythonify: bool = False) -> Union[Dict, MISPTaxonomy]:
"""Get a taxonomy from a MISP instance.""" """Get a taxonomy from a MISP instance."""
taxonomy_id = get_uuid_or_id_from_abstract_misp(taxonomy) taxonomy_id = get_uuid_or_id_from_abstract_misp(taxonomy)
r = self._prepare_request('GET', f'taxonomies/view/{taxonomy_id}') r = self._prepare_request('GET', f'taxonomies/view/{taxonomy_id}')
@ -775,7 +775,7 @@ class PyMISP:
# ## BEGIN Warninglists ### # ## BEGIN Warninglists ###
def warninglists(self, pythonify: bool=False) -> Union[Dict, List[MISPWarninglist]]: def warninglists(self, pythonify: bool = False) -> Union[Dict, List[MISPWarninglist]]:
"""Get all the warninglists.""" """Get all the warninglists."""
r = self._prepare_request('GET', 'warninglists') r = self._prepare_request('GET', 'warninglists')
warninglists = self._check_json_response(r) warninglists = self._check_json_response(r)
@ -788,7 +788,7 @@ class PyMISP:
to_return.append(w) to_return.append(w)
return to_return return to_return
def get_warninglist(self, warninglist: Union[MISPWarninglist, int, str, UUID], pythonify: bool=False) -> Union[Dict, MISPWarninglist]: def get_warninglist(self, warninglist: Union[MISPWarninglist, int, str, UUID], pythonify: bool = False) -> Union[Dict, MISPWarninglist]:
"""Get a warninglist.""" """Get a warninglist."""
warninglist_id = get_uuid_or_id_from_abstract_misp(warninglist) warninglist_id = get_uuid_or_id_from_abstract_misp(warninglist)
r = self._prepare_request('GET', f'warninglists/view/{warninglist_id}') r = self._prepare_request('GET', f'warninglists/view/{warninglist_id}')
@ -799,7 +799,7 @@ class PyMISP:
w.from_dict(**wl) w.from_dict(**wl)
return w return w
def toggle_warninglist(self, warninglist_id: Optional[Union[str, int, List[int]]]=None, warninglist_name: Optional[Union[str, List[str]]]=None, force_enable: bool=False) -> Dict: def toggle_warninglist(self, warninglist_id: Optional[Union[str, int, List[int]]] = None, warninglist_name: Optional[Union[str, List[str]]] = None, force_enable: bool = False) -> Dict:
'''Toggle (enable/disable) the status of a warninglist by ID. '''Toggle (enable/disable) the status of a warninglist by ID.
:param warninglist_id: ID of the WarningList :param warninglist_id: ID of the WarningList
:param force_enable: Force the warning list in the enabled state (does nothing is already enabled) :param force_enable: Force the warning list in the enabled state (does nothing is already enabled)
@ -846,7 +846,7 @@ class PyMISP:
# ## BEGIN Noticelist ### # ## BEGIN Noticelist ###
def noticelists(self, pythonify: bool=False) -> Union[Dict, List[MISPNoticelist]]: def noticelists(self, pythonify: bool = False) -> Union[Dict, List[MISPNoticelist]]:
"""Get all the noticelists.""" """Get all the noticelists."""
r = self._prepare_request('GET', 'noticelists') r = self._prepare_request('GET', 'noticelists')
noticelists = self._check_json_response(r) noticelists = self._check_json_response(r)
@ -859,7 +859,7 @@ class PyMISP:
to_return.append(n) to_return.append(n)
return to_return return to_return
def get_noticelist(self, noticelist: Union[MISPNoticelist, int, str, UUID], pythonify: bool=False) -> Union[Dict, MISPNoticelist]: def get_noticelist(self, noticelist: Union[MISPNoticelist, int, str, UUID], pythonify: bool = False) -> Union[Dict, MISPNoticelist]:
"""Get a noticelist by id.""" """Get a noticelist by id."""
noticelist_id = get_uuid_or_id_from_abstract_misp(noticelist) noticelist_id = get_uuid_or_id_from_abstract_misp(noticelist)
r = self._prepare_request('GET', f'noticelists/view/{noticelist_id}') r = self._prepare_request('GET', f'noticelists/view/{noticelist_id}')
@ -895,7 +895,7 @@ class PyMISP:
# ## BEGIN Galaxy ### # ## BEGIN Galaxy ###
def galaxies(self, pythonify: bool=False) -> Union[Dict, List[MISPGalaxy]]: def galaxies(self, pythonify: bool = False) -> Union[Dict, List[MISPGalaxy]]:
"""Get all the galaxies.""" """Get all the galaxies."""
r = self._prepare_request('GET', 'galaxies') r = self._prepare_request('GET', 'galaxies')
galaxies = self._check_json_response(r) galaxies = self._check_json_response(r)
@ -908,7 +908,7 @@ class PyMISP:
to_return.append(g) to_return.append(g)
return to_return return to_return
def get_galaxy(self, galaxy: Union[MISPGalaxy, int, str, UUID], pythonify: bool=False) -> Union[Dict, MISPGalaxy]: def get_galaxy(self, galaxy: Union[MISPGalaxy, int, str, UUID], pythonify: bool = False) -> Union[Dict, MISPGalaxy]:
"""Get a galaxy by id.""" """Get a galaxy by id."""
galaxy_id = get_uuid_or_id_from_abstract_misp(galaxy) galaxy_id = get_uuid_or_id_from_abstract_misp(galaxy)
r = self._prepare_request('GET', f'galaxies/view/{galaxy_id}') r = self._prepare_request('GET', f'galaxies/view/{galaxy_id}')
@ -928,7 +928,7 @@ class PyMISP:
# ## BEGIN Feed ### # ## BEGIN Feed ###
def feeds(self, pythonify: bool=False) -> Union[Dict, List[MISPFeed]]: def feeds(self, pythonify: bool = False) -> Union[Dict, List[MISPFeed]]:
"""Get the list of existing feeds.""" """Get the list of existing feeds."""
r = self._prepare_request('GET', 'feeds') r = self._prepare_request('GET', 'feeds')
feeds = self._check_json_response(r) feeds = self._check_json_response(r)
@ -941,7 +941,7 @@ class PyMISP:
to_return.append(f) to_return.append(f)
return to_return return to_return
def get_feed(self, feed: Union[MISPFeed, int, str, UUID], pythonify: bool=False) -> Union[Dict, MISPFeed]: def get_feed(self, feed: Union[MISPFeed, int, str, UUID], pythonify: bool = False) -> Union[Dict, MISPFeed]:
"""Get a feed by id.""" """Get a feed by id."""
feed_id = get_uuid_or_id_from_abstract_misp(feed) feed_id = get_uuid_or_id_from_abstract_misp(feed)
r = self._prepare_request('GET', f'feeds/view/{feed_id}') r = self._prepare_request('GET', f'feeds/view/{feed_id}')
@ -952,7 +952,7 @@ class PyMISP:
f.from_dict(**feed_j) f.from_dict(**feed_j)
return f return f
def add_feed(self, feed: MISPFeed, pythonify: bool=False) -> Union[Dict, MISPFeed]: def add_feed(self, feed: MISPFeed, pythonify: bool = False) -> Union[Dict, MISPFeed]:
'''Add a new feed on a MISP instance''' '''Add a new feed on a MISP instance'''
# FIXME: https://github.com/MISP/MISP/issues/4834 # FIXME: https://github.com/MISP/MISP/issues/4834
r = self._prepare_request('POST', 'feeds/add', data={'Feed': feed}) r = self._prepare_request('POST', 'feeds/add', data={'Feed': feed})
@ -963,7 +963,7 @@ class PyMISP:
f.from_dict(**new_feed) f.from_dict(**new_feed)
return f return f
def enable_feed(self, feed: Union[MISPFeed, int, str, UUID], pythonify: bool=False) -> Union[Dict, MISPFeed]: def enable_feed(self, feed: Union[MISPFeed, int, str, UUID], pythonify: bool = False) -> Union[Dict, MISPFeed]:
'''Enable a feed (fetching it will create event(s)''' '''Enable a feed (fetching it will create event(s)'''
if not isinstance(feed, MISPFeed): if not isinstance(feed, MISPFeed):
feed_id = get_uuid_or_id_from_abstract_misp(feed) # In case we have a UUID feed_id = get_uuid_or_id_from_abstract_misp(feed) # In case we have a UUID
@ -974,7 +974,7 @@ class PyMISP:
f = feed f = feed
return self.update_feed(feed=f, pythonify=pythonify) return self.update_feed(feed=f, pythonify=pythonify)
def disable_feed(self, feed: Union[MISPFeed, int, str, UUID], pythonify: bool=False) -> Union[Dict, MISPFeed]: def disable_feed(self, feed: Union[MISPFeed, int, str, UUID], pythonify: bool = False) -> Union[Dict, MISPFeed]:
'''Disable a feed''' '''Disable a feed'''
if not isinstance(feed, MISPFeed): if not isinstance(feed, MISPFeed):
feed_id = get_uuid_or_id_from_abstract_misp(feed) # In case we have a UUID feed_id = get_uuid_or_id_from_abstract_misp(feed) # In case we have a UUID
@ -985,7 +985,7 @@ class PyMISP:
f = feed f = feed
return self.update_feed(feed=f, pythonify=pythonify) return self.update_feed(feed=f, pythonify=pythonify)
def enable_feed_cache(self, feed: Union[MISPFeed, int, str, UUID], pythonify: bool=False) -> Union[Dict, MISPFeed]: def enable_feed_cache(self, feed: Union[MISPFeed, int, str, UUID], pythonify: bool = False) -> Union[Dict, MISPFeed]:
'''Enable the caching of a feed''' '''Enable the caching of a feed'''
if not isinstance(feed, MISPFeed): if not isinstance(feed, MISPFeed):
feed_id = get_uuid_or_id_from_abstract_misp(feed) # In case we have a UUID feed_id = get_uuid_or_id_from_abstract_misp(feed) # In case we have a UUID
@ -996,7 +996,7 @@ class PyMISP:
f = feed f = feed
return self.update_feed(feed=f, pythonify=pythonify) return self.update_feed(feed=f, pythonify=pythonify)
def disable_feed_cache(self, feed: Union[MISPFeed, int, str, UUID], pythonify: bool=False) -> Union[Dict, MISPFeed]: def disable_feed_cache(self, feed: Union[MISPFeed, int, str, UUID], pythonify: bool = False) -> Union[Dict, MISPFeed]:
'''Disable the caching of a feed''' '''Disable the caching of a feed'''
if not isinstance(feed, MISPFeed): if not isinstance(feed, MISPFeed):
feed_id = get_uuid_or_id_from_abstract_misp(feed) # In case we have a UUID feed_id = get_uuid_or_id_from_abstract_misp(feed) # In case we have a UUID
@ -1007,7 +1007,7 @@ class PyMISP:
f = feed f = feed
return self.update_feed(feed=f, pythonify=pythonify) return self.update_feed(feed=f, pythonify=pythonify)
def update_feed(self, feed: MISPFeed, feed_id: Optional[int]=None, pythonify: bool=False) -> Union[Dict, MISPFeed]: def update_feed(self, feed: MISPFeed, feed_id: Optional[int] = None, pythonify: bool = False) -> Union[Dict, MISPFeed]:
'''Update a feed on a MISP instance''' '''Update a feed on a MISP instance'''
if feed_id is None: if feed_id is None:
fid = get_uuid_or_id_from_abstract_misp(feed) fid = get_uuid_or_id_from_abstract_misp(feed)
@ -1069,7 +1069,7 @@ class PyMISP:
# ## BEGIN Server ### # ## BEGIN Server ###
def servers(self, pythonify: bool=False) -> Union[Dict, List[MISPServer]]: def servers(self, pythonify: bool = False) -> Union[Dict, List[MISPServer]]:
"""Get the existing servers the MISP instance can synchronise with""" """Get the existing servers the MISP instance can synchronise with"""
r = self._prepare_request('GET', 'servers') r = self._prepare_request('GET', 'servers')
servers = self._check_json_response(r) servers = self._check_json_response(r)
@ -1082,7 +1082,7 @@ class PyMISP:
to_return.append(s) to_return.append(s)
return to_return return to_return
def get_sync_config(self, pythonify: bool=False) -> Union[Dict, MISPServer]: def get_sync_config(self, pythonify: bool = False) -> Union[Dict, MISPServer]:
'''WARNING: This method only works if the user calling it is a sync user''' '''WARNING: This method only works if the user calling it is a sync user'''
r = self._prepare_request('GET', 'servers/createSync') r = self._prepare_request('GET', 'servers/createSync')
server = self._check_json_response(r) server = self._check_json_response(r)
@ -1092,7 +1092,7 @@ class PyMISP:
s.from_dict(**server) s.from_dict(**server)
return s return s
def import_server(self, server: MISPServer, pythonify: bool=False) -> Union[Dict, MISPServer]: def import_server(self, server: MISPServer, pythonify: bool = False) -> Union[Dict, MISPServer]:
"""Import a sync server config received from get_sync_config""" """Import a sync server config received from get_sync_config"""
r = self._prepare_request('POST', 'servers/import', data=server) r = self._prepare_request('POST', 'servers/import', data=server)
server_j = self._check_json_response(r) server_j = self._check_json_response(r)
@ -1102,7 +1102,7 @@ class PyMISP:
s.from_dict(**server_j) s.from_dict(**server_j)
return s return s
def add_server(self, server: MISPServer, pythonify: bool=False) -> Union[Dict, MISPServer]: def add_server(self, server: MISPServer, pythonify: bool = False) -> Union[Dict, MISPServer]:
"""Add a server to synchronise with. """Add a server to synchronise with.
Note: You probably want to use ExpandedPyMISP.get_sync_config and ExpandedPyMISP.import_server instead""" Note: You probably want to use ExpandedPyMISP.get_sync_config and ExpandedPyMISP.import_server instead"""
r = self._prepare_request('POST', 'servers/add', data=server) r = self._prepare_request('POST', 'servers/add', data=server)
@ -1113,7 +1113,7 @@ class PyMISP:
s.from_dict(**server_j) s.from_dict(**server_j)
return s return s
def update_server(self, server: MISPServer, server_id: Optional[int]=None, pythonify: bool=False) -> Union[Dict, MISPServer]: def update_server(self, server: MISPServer, server_id: Optional[int] = None, pythonify: bool = False) -> Union[Dict, MISPServer]:
'''Update a server to synchronise with''' '''Update a server to synchronise with'''
if server_id is None: if server_id is None:
sid = get_uuid_or_id_from_abstract_misp(server) sid = get_uuid_or_id_from_abstract_misp(server)
@ -1133,7 +1133,7 @@ class PyMISP:
response = self._prepare_request('POST', f'servers/delete/{server_id}') response = self._prepare_request('POST', f'servers/delete/{server_id}')
return self._check_json_response(response) return self._check_json_response(response)
def server_pull(self, server: Union[MISPServer, int, str, UUID], event: Optional[Union[MISPEvent, int, str, UUID]]=None) -> Dict: def server_pull(self, server: Union[MISPServer, int, str, UUID], event: Optional[Union[MISPEvent, int, str, UUID]] = None) -> Dict:
'''Initialize a pull from a sync server''' '''Initialize a pull from a sync server'''
server_id = get_uuid_or_id_from_abstract_misp(server) server_id = get_uuid_or_id_from_abstract_misp(server)
if event: if event:
@ -1145,7 +1145,7 @@ class PyMISP:
# FIXME: can we pythonify? # FIXME: can we pythonify?
return self._check_json_response(response) return self._check_json_response(response)
def server_push(self, server: Union[MISPServer, int, str, UUID], event: Optional[Union[MISPEvent, int, str, UUID]]=None) -> Dict: def server_push(self, server: Union[MISPServer, int, str, UUID], event: Optional[Union[MISPEvent, int, str, UUID]] = None) -> Dict:
'''Initialize a push to a sync server''' '''Initialize a push to a sync server'''
server_id = get_uuid_or_id_from_abstract_misp(server) server_id = get_uuid_or_id_from_abstract_misp(server)
if event: if event:
@ -1166,7 +1166,7 @@ class PyMISP:
# ## BEGIN Sharing group ### # ## BEGIN Sharing group ###
def sharing_groups(self, pythonify: bool=False) -> Union[Dict, List[MISPSharingGroup]]: def sharing_groups(self, pythonify: bool = False) -> Union[Dict, List[MISPSharingGroup]]:
"""Get the existing sharing groups""" """Get the existing sharing groups"""
r = self._prepare_request('GET', 'sharing_groups') r = self._prepare_request('GET', 'sharing_groups')
sharing_groups = self._check_json_response(r) sharing_groups = self._check_json_response(r)
@ -1179,7 +1179,7 @@ class PyMISP:
to_return.append(s) to_return.append(s)
return to_return return to_return
def add_sharing_group(self, sharing_group: MISPSharingGroup, pythonify: bool=False) -> Union[Dict, MISPSharingGroup]: def add_sharing_group(self, sharing_group: MISPSharingGroup, pythonify: bool = False) -> Union[Dict, MISPSharingGroup]:
"""Add a new sharing group""" """Add a new sharing group"""
r = self._prepare_request('POST', 'sharing_groups/add', data=sharing_group) r = self._prepare_request('POST', 'sharing_groups/add', data=sharing_group)
sharing_group_j = self._check_json_response(r) sharing_group_j = self._check_json_response(r)
@ -1196,7 +1196,7 @@ class PyMISP:
return self._check_json_response(response) return self._check_json_response(response)
def add_org_to_sharing_group(self, sharing_group: Union[MISPSharingGroup, int, str, UUID], def add_org_to_sharing_group(self, sharing_group: Union[MISPSharingGroup, int, str, UUID],
organisation: Union[MISPOrganisation, int, str, UUID], extend: bool=False) -> Dict: organisation: Union[MISPOrganisation, int, str, UUID], extend: bool = False) -> Dict:
'''Add an organisation to a sharing group. '''Add an organisation to a sharing group.
:sharing_group: Sharing group's local instance ID, or Sharing group's global UUID :sharing_group: Sharing group's local instance ID, or Sharing group's global UUID
:organisation: Organisation's local instance ID, or Organisation's global UUID, or Organisation's name as known to the curent instance :organisation: Organisation's local instance ID, or Organisation's global UUID, or Organisation's name as known to the curent instance
@ -1221,7 +1221,7 @@ class PyMISP:
return self._check_json_response(response) return self._check_json_response(response)
def add_server_to_sharing_group(self, sharing_group: Union[MISPSharingGroup, int, str, UUID], def add_server_to_sharing_group(self, sharing_group: Union[MISPSharingGroup, int, str, UUID],
server: Union[MISPServer, int, str, UUID], all_orgs: bool=False) -> Dict: server: Union[MISPServer, int, str, UUID], all_orgs: bool = False) -> Dict:
'''Add a server to a sharing group. '''Add a server to a sharing group.
:sharing_group: Sharing group's local instance ID, or Sharing group's global UUID :sharing_group: Sharing group's local instance ID, or Sharing group's global UUID
:server: Server's local instance ID, or URL of the Server, or Server's name as known to the curent instance :server: Server's local instance ID, or URL of the Server, or Server's name as known to the curent instance
@ -1249,7 +1249,7 @@ class PyMISP:
# ## BEGIN Organisation ### # ## BEGIN Organisation ###
def organisations(self, scope="local", pythonify: bool=False) -> Union[Dict, List[MISPOrganisation]]: def organisations(self, scope="local", pythonify: bool = False) -> Union[Dict, List[MISPOrganisation]]:
"""Get all the organisations.""" """Get all the organisations."""
r = self._prepare_request('GET', f'organisations/index/scope:{scope}') r = self._prepare_request('GET', f'organisations/index/scope:{scope}')
organisations = self._check_json_response(r) organisations = self._check_json_response(r)
@ -1262,7 +1262,7 @@ class PyMISP:
to_return.append(o) to_return.append(o)
return to_return return to_return
def get_organisation(self, organisation: Union[MISPOrganisation, int, str, UUID], pythonify: bool=False) -> Union[Dict, MISPOrganisation]: def get_organisation(self, organisation: Union[MISPOrganisation, int, str, UUID], pythonify: bool = False) -> Union[Dict, MISPOrganisation]:
'''Get an organisation.''' '''Get an organisation.'''
organisation_id = get_uuid_or_id_from_abstract_misp(organisation) organisation_id = get_uuid_or_id_from_abstract_misp(organisation)
r = self._prepare_request('GET', f'organisations/view/{organisation_id}') r = self._prepare_request('GET', f'organisations/view/{organisation_id}')
@ -1273,7 +1273,7 @@ class PyMISP:
o.from_dict(**organisation_j) o.from_dict(**organisation_j)
return o return o
def add_organisation(self, organisation: MISPOrganisation, pythonify: bool=False) -> Union[Dict, MISPOrganisation]: def add_organisation(self, organisation: MISPOrganisation, pythonify: bool = False) -> Union[Dict, MISPOrganisation]:
'''Add an organisation''' '''Add an organisation'''
r = self._prepare_request('POST', 'admin/organisations/add', data=organisation) r = self._prepare_request('POST', 'admin/organisations/add', data=organisation)
new_organisation = self._check_json_response(r) new_organisation = self._check_json_response(r)
@ -1283,7 +1283,7 @@ class PyMISP:
o.from_dict(**new_organisation) o.from_dict(**new_organisation)
return o return o
def update_organisation(self, organisation: MISPOrganisation, organisation_id: Optional[int]=None, pythonify: bool=False) -> Union[Dict, MISPOrganisation]: def update_organisation(self, organisation: MISPOrganisation, organisation_id: Optional[int] = None, pythonify: bool = False) -> Union[Dict, MISPOrganisation]:
'''Update an organisation''' '''Update an organisation'''
if organisation_id is None: if organisation_id is None:
oid = get_uuid_or_id_from_abstract_misp(organisation) oid = get_uuid_or_id_from_abstract_misp(organisation)
@ -1308,7 +1308,7 @@ class PyMISP:
# ## BEGIN User ### # ## BEGIN User ###
def users(self, pythonify: bool=False) -> Union[Dict, List[MISPUser]]: def users(self, pythonify: bool = False) -> Union[Dict, List[MISPUser]]:
"""Get all the users.""" """Get all the users."""
r = self._prepare_request('GET', 'admin/users') r = self._prepare_request('GET', 'admin/users')
users = self._check_json_response(r) users = self._check_json_response(r)
@ -1321,7 +1321,7 @@ class PyMISP:
to_return.append(u) to_return.append(u)
return to_return return to_return
def get_user(self, user: Union[MISPUser, int, str, UUID]='me', pythonify: bool=False, expanded: bool=False) -> Union[Dict, MISPUser, Tuple[MISPUser, MISPRole, List[MISPUserSetting]]]: def get_user(self, user: Union[MISPUser, int, str, UUID] = 'me', pythonify: bool = False, expanded: bool = False) -> Union[Dict, MISPUser, Tuple[MISPUser, MISPRole, List[MISPUserSetting]]]:
'''Get a user. `me` means the owner of the API key doing the query. '''Get a user. `me` means the owner of the API key doing the query.
expanded also returns a MISPRole and a MISPUserSetting''' expanded also returns a MISPRole and a MISPUserSetting'''
user_id = get_uuid_or_id_from_abstract_misp(user) user_id = get_uuid_or_id_from_abstract_misp(user)
@ -1344,7 +1344,7 @@ class PyMISP:
usersettings.append(us) usersettings.append(us)
return u, role, usersettings return u, role, usersettings
def add_user(self, user: MISPUser, pythonify: bool=False) -> Union[Dict, MISPUser]: def add_user(self, user: MISPUser, pythonify: bool = False) -> Union[Dict, MISPUser]:
'''Add a new user''' '''Add a new user'''
r = self._prepare_request('POST', 'admin/users/add', data=user) r = self._prepare_request('POST', 'admin/users/add', data=user)
user_j = self._check_json_response(r) user_j = self._check_json_response(r)
@ -1354,7 +1354,7 @@ class PyMISP:
u.from_dict(**user_j) u.from_dict(**user_j)
return u return u
def update_user(self, user: MISPUser, user_id: Optional[int]=None, pythonify: bool=False) -> Union[Dict, MISPUser]: def update_user(self, user: MISPUser, user_id: Optional[int] = None, pythonify: bool = False) -> Union[Dict, MISPUser]:
'''Update an event on a MISP instance''' '''Update an event on a MISP instance'''
if user_id is None: if user_id is None:
uid = get_uuid_or_id_from_abstract_misp(user) uid = get_uuid_or_id_from_abstract_misp(user)
@ -1383,7 +1383,7 @@ class PyMISP:
response = self._prepare_request('POST', 'users/change_pw', data={'password': new_password}) response = self._prepare_request('POST', 'users/change_pw', data={'password': new_password})
return self._check_json_response(response) return self._check_json_response(response)
def user_registrations(self, pythonify: bool=False) -> Union[Dict, List[MISPInbox]]: def user_registrations(self, pythonify: bool = False) -> Union[Dict, List[MISPInbox]]:
"""Get all the user registrations.""" """Get all the user registrations."""
r = self._prepare_request('GET', 'users/registrations') r = self._prepare_request('GET', 'users/registrations')
registrations = self._check_json_response(r) registrations = self._check_json_response(r)
@ -1397,10 +1397,10 @@ class PyMISP:
return to_return return to_return
def accept_user_registration(self, registration: Union[MISPInbox, int, str, UUID], def accept_user_registration(self, registration: Union[MISPInbox, int, str, UUID],
organisation: Optional[Union[MISPOrganisation, int, str, UUID]]=None, organisation: Optional[Union[MISPOrganisation, int, str, UUID]] = None,
role: Optional[Union[MISPRole, int, str]]=None, role: Optional[Union[MISPRole, int, str]] = None,
perm_sync: bool=False, perm_publish: bool=False, perm_admin: bool=False, perm_sync: bool = False, perm_publish: bool = False, perm_admin: bool = False,
unsafe_fallback: bool=False): unsafe_fallback: bool = False):
registration_id = get_uuid_or_id_from_abstract_misp(registration) registration_id = get_uuid_or_id_from_abstract_misp(registration)
if role: if role:
role_id = role_id = get_uuid_or_id_from_abstract_misp(role) role_id = role_id = get_uuid_or_id_from_abstract_misp(role)
@ -1446,7 +1446,7 @@ class PyMISP:
# ## BEGIN Role ### # ## BEGIN Role ###
def roles(self, pythonify: bool=False) -> Union[Dict, List[MISPRole]]: def roles(self, pythonify: bool = False) -> Union[Dict, List[MISPRole]]:
"""Get the existing roles""" """Get the existing roles"""
r = self._prepare_request('GET', 'roles') r = self._prepare_request('GET', 'roles')
roles = self._check_json_response(r) roles = self._check_json_response(r)
@ -1469,50 +1469,50 @@ class PyMISP:
# ## BEGIN Search methods ### # ## BEGIN Search methods ###
def search(self, controller: str='events', return_format: str='json', def search(self, controller: str = 'events', return_format: str = 'json',
limit: Optional[int]=None, page: Optional[int]=None, limit: Optional[int] = None, page: Optional[int] = None,
value: Optional[SearchParameterTypes]=None, value: Optional[SearchParameterTypes] = None,
type_attribute: Optional[SearchParameterTypes]=None, type_attribute: Optional[SearchParameterTypes] = None,
category: Optional[SearchParameterTypes]=None, category: Optional[SearchParameterTypes] = None,
org: Optional[SearchParameterTypes]=None, org: Optional[SearchParameterTypes] = None,
tags: Optional[SearchParameterTypes]=None, tags: Optional[SearchParameterTypes] = None,
quick_filter: Optional[str]=None, quickFilter: Optional[str]=None, quick_filter: Optional[str] = None, quickFilter: Optional[str] = None,
date_from: Optional[Union[datetime, date, int, str, float, None]]=None, date_from: Optional[Union[datetime, date, int, str, float, None]] = None,
date_to: Optional[Union[datetime, date, int, str, float, None]]=None, date_to: Optional[Union[datetime, date, int, str, float, None]] = None,
eventid: Optional[SearchType]=None, eventid: Optional[SearchType] = None,
with_attachments: Optional[bool]=None, withAttachments: Optional[bool]=None, with_attachments: Optional[bool] = None, withAttachments: Optional[bool] = None,
metadata: Optional[bool]=None, metadata: Optional[bool] = None,
uuid: Optional[str]=None, uuid: Optional[str] = None,
publish_timestamp: Optional[Union[Union[datetime, date, int, str, float, None], publish_timestamp: Optional[Union[Union[datetime, date, int, str, float, None],
Tuple[Union[datetime, date, int, str, float, None], Tuple[Union[datetime, date, int, str, float, None],
Union[datetime, date, int, str, float, None]] Union[datetime, date, int, str, float, None]]
]]=None, ]] = None,
last: Optional[Union[Union[datetime, date, int, str, float, None], last: Optional[Union[Union[datetime, date, int, str, float, None],
Tuple[Union[datetime, date, int, str, float, None], Tuple[Union[datetime, date, int, str, float, None],
Union[datetime, date, int, str, float, None]] Union[datetime, date, int, str, float, None]]
]]=None, ]] = None,
timestamp: Optional[Union[Union[datetime, date, int, str, float, None], timestamp: Optional[Union[Union[datetime, date, int, str, float, None],
Tuple[Union[datetime, date, int, str, float, None], Tuple[Union[datetime, date, int, str, float, None],
Union[datetime, date, int, str, float, None]] Union[datetime, date, int, str, float, None]]
]]=None, ]] = None,
published: Optional[bool]=None, published: Optional[bool] = None,
enforce_warninglist: Optional[bool]=None, enforceWarninglist: Optional[bool]=None, enforce_warninglist: Optional[bool] = None, enforceWarninglist: Optional[bool] = None,
to_ids: Optional[Union[ToIDSType, List[ToIDSType]]]=None, to_ids: Optional[Union[ToIDSType, List[ToIDSType]]] = None,
deleted: Optional[str]=None, deleted: Optional[str] = None,
include_event_uuid: Optional[bool]=None, includeEventUuid: Optional[bool]=None, include_event_uuid: Optional[bool] = None, includeEventUuid: Optional[bool] = None,
include_event_tags: Optional[bool]=None, includeEventTags: Optional[bool]=None, include_event_tags: Optional[bool] = None, includeEventTags: Optional[bool] = None,
event_timestamp: Optional[Union[datetime, date, int, str, float, None]]=None, event_timestamp: Optional[Union[datetime, date, int, str, float, None]] = None,
sg_reference_only: Optional[bool]=None, sg_reference_only: Optional[bool] = None,
eventinfo: Optional[str]=None, eventinfo: Optional[str] = None,
searchall: Optional[bool]=None, searchall: Optional[bool] = None,
requested_attributes: Optional[str]=None, requested_attributes: Optional[str] = None,
include_context: Optional[bool]=None, includeContext: Optional[bool]=None, include_context: Optional[bool] = None, includeContext: Optional[bool] = None,
headerless: Optional[bool]=None, headerless: Optional[bool] = None,
include_sightings: Optional[bool]=None, includeSightings: Optional[bool]=None, include_sightings: Optional[bool] = None, includeSightings: Optional[bool] = None,
include_correlations: Optional[bool]=None, includeCorrelations: Optional[bool]=None, include_correlations: Optional[bool] = None, includeCorrelations: Optional[bool] = None,
include_decay_score: Optional[bool] = None, includeDecayScore: Optional[bool] = None, include_decay_score: Optional[bool] = None, includeDecayScore: Optional[bool] = None,
object_name: Optional[str]=None, object_name: Optional[str] = None,
pythonify: Optional[bool]=False, pythonify: Optional[bool] = False,
**kwargs) -> Union[Dict, str, List[Union[MISPEvent, MISPAttribute, MISPObject]]]: **kwargs) -> Union[Dict, str, List[Union[MISPEvent, MISPAttribute, MISPObject]]]:
'''Search in the MISP instance '''Search in the MISP instance
@ -1714,20 +1714,20 @@ class PyMISP:
return normalized_response return normalized_response
def search_index(self, published: Optional[bool]=None, eventid: Optional[SearchType]=None, def search_index(self, published: Optional[bool] = None, eventid: Optional[SearchType] = None,
tags: Optional[SearchParameterTypes]=None, tags: Optional[SearchParameterTypes] = None,
date_from: Optional[Union[datetime, date, int, str, float, None]]=None, date_from: Optional[Union[datetime, date, int, str, float, None]] = None,
date_to: Optional[Union[datetime, date, int, str, float, None]]=None, date_to: Optional[Union[datetime, date, int, str, float, None]] = None,
eventinfo: Optional[str]=None, eventinfo: Optional[str] = None,
threatlevel: Optional[List[SearchType]]=None, threatlevel: Optional[List[SearchType]] = None,
distribution: Optional[List[SearchType]]=None, distribution: Optional[List[SearchType]] = None,
analysis: Optional[List[SearchType]]=None, analysis: Optional[List[SearchType]] = None,
org: Optional[SearchParameterTypes]=None, org: Optional[SearchParameterTypes] = None,
timestamp: Optional[Union[Union[datetime, date, int, str, float, None], timestamp: Optional[Union[Union[datetime, date, int, str, float, None],
Tuple[Union[datetime, date, int, str, float, None], Tuple[Union[datetime, date, int, str, float, None],
Union[datetime, date, int, str, float, None]] Union[datetime, date, int, str, float, None]]
]]=None, ]] = None,
pythonify: Optional[bool]=None) -> Union[Dict, List[MISPEvent]]: pythonify: Optional[bool] = None) -> Union[Dict, List[MISPEvent]]:
"""Search only at the index level. Using ! in front of a value means NOT (default is OR) """Search only at the index level. Using ! in front of a value means NOT (default is OR)
:param published: Set whether published or unpublished events should be returned. Do not set the parameter if you want both. :param published: Set whether published or unpublished events should be returned. Do not set the parameter if you want both.
@ -1771,24 +1771,24 @@ class PyMISP:
to_return.append(me) to_return.append(me)
return to_return return to_return
def search_sightings(self, context: Optional[str]=None, def search_sightings(self, context: Optional[str] = None,
context_id: Optional[SearchType]=None, context_id: Optional[SearchType] = None,
type_sighting: Optional[str]=None, type_sighting: Optional[str] = None,
date_from: Optional[Union[datetime, date, int, str, float, None]]=None, date_from: Optional[Union[datetime, date, int, str, float, None]] = None,
date_to: Optional[Union[datetime, date, int, str, float, None]]=None, date_to: Optional[Union[datetime, date, int, str, float, None]] = None,
publish_timestamp: Optional[Union[Union[datetime, date, int, str, float, None], publish_timestamp: Optional[Union[Union[datetime, date, int, str, float, None],
Tuple[Union[datetime, date, int, str, float, None], Tuple[Union[datetime, date, int, str, float, None],
Union[datetime, date, int, str, float, None]] Union[datetime, date, int, str, float, None]]
]]=None, ]] = None,
last: Optional[Union[Union[datetime, date, int, str, float, None], last: Optional[Union[Union[datetime, date, int, str, float, None],
Tuple[Union[datetime, date, int, str, float, None], Tuple[Union[datetime, date, int, str, float, None],
Union[datetime, date, int, str, float, None]] Union[datetime, date, int, str, float, None]]
]]=None, ]] = None,
org: Optional[SearchType]=None, org: Optional[SearchType] = None,
source: Optional[str]=None, source: Optional[str] = None,
include_attribute: Optional[bool]=None, include_attribute: Optional[bool] = None,
include_event_meta: Optional[bool]=None, include_event_meta: Optional[bool] = None,
pythonify: Optional[bool]=False pythonify: Optional[bool] = False
) -> Union[Dict, List[Dict[str, Union[MISPEvent, MISPAttribute, MISPSighting]]]]: ) -> Union[Dict, List[Dict[str, Union[MISPEvent, MISPAttribute, MISPSighting]]]]:
'''Search sightings '''Search sightings
@ -1862,13 +1862,13 @@ class PyMISP:
return to_return return to_return
return normalized_response return normalized_response
def search_logs(self, limit: Optional[int]=None, page: Optional[int]=None, def search_logs(self, limit: Optional[int] = None, page: Optional[int] = None,
log_id: Optional[int]=None, title: Optional[str]=None, log_id: Optional[int] = None, title: Optional[str] = None,
created: Optional[Union[datetime, date, int, str, float, None]]=None, model: Optional[str]=None, created: Optional[Union[datetime, date, int, str, float, None]] = None, model: Optional[str] = None,
action: Optional[str]=None, user_id: Optional[int]=None, action: Optional[str] = None, user_id: Optional[int] = None,
change: Optional[str]=None, email: Optional[str]=None, change: Optional[str] = None, email: Optional[str] = None,
org: Optional[str]=None, description: Optional[str]=None, org: Optional[str] = None, description: Optional[str] = None,
ip: Optional[str]=None, pythonify: Optional[bool]=False) -> Union[Dict, List[MISPLog]]: ip: Optional[str] = None, pythonify: Optional[bool] = False) -> Union[Dict, List[MISPLog]]:
'''Search in logs '''Search in logs
Note: to run substring queries simply append/prepend/encapsulate the search term with % Note: to run substring queries simply append/prepend/encapsulate the search term with %
@ -1906,7 +1906,7 @@ class PyMISP:
to_return.append(ml) to_return.append(ml)
return to_return return to_return
def search_feeds(self, value: Optional[SearchParameterTypes]=None, pythonify: Optional[bool]=False) -> Union[Dict, List[MISPFeed]]: def search_feeds(self, value: Optional[SearchParameterTypes] = None, pythonify: Optional[bool] = False) -> Union[Dict, List[MISPFeed]]:
'''Search in the feeds cached on the servers''' '''Search in the feeds cached on the servers'''
response = self._prepare_request('POST', '/feeds/searchCaches', data={'value': value}) response = self._prepare_request('POST', '/feeds/searchCaches', data={'value': value})
normalized_response = self._check_json_response(response) normalized_response = self._check_json_response(response)
@ -1923,7 +1923,7 @@ class PyMISP:
# ## BEGIN Communities ### # ## BEGIN Communities ###
def communities(self, pythonify: bool=False) -> Union[Dict, List[MISPCommunity]]: def communities(self, pythonify: bool = False) -> Union[Dict, List[MISPCommunity]]:
"""Get all the communities.""" """Get all the communities."""
r = self._prepare_request('GET', 'communities') r = self._prepare_request('GET', 'communities')
communities = self._check_json_response(r) communities = self._check_json_response(r)
@ -1936,7 +1936,7 @@ class PyMISP:
to_return.append(c) to_return.append(c)
return to_return return to_return
def get_community(self, community: Union[MISPCommunity, int, str, UUID], pythonify: bool=False) -> Union[Dict, MISPCommunity]: def get_community(self, community: Union[MISPCommunity, int, str, UUID], pythonify: bool = False) -> Union[Dict, MISPCommunity]:
'''Get an community from a MISP instance''' '''Get an community from a MISP instance'''
community_id = get_uuid_or_id_from_abstract_misp(community) community_id = get_uuid_or_id_from_abstract_misp(community)
r = self._prepare_request('GET', f'communities/view/{community_id}') r = self._prepare_request('GET', f'communities/view/{community_id}')
@ -1948,14 +1948,14 @@ class PyMISP:
return c return c
def request_community_access(self, community: Union[MISPCommunity, int, str, UUID], def request_community_access(self, community: Union[MISPCommunity, int, str, UUID],
requestor_email_address: Optional[str]=None, requestor_email_address: Optional[str] = None,
requestor_gpg_key: Optional[str]=None, requestor_gpg_key: Optional[str] = None,
requestor_organisation_name: Optional[str]=None, requestor_organisation_name: Optional[str] = None,
requestor_organisation_uuid: Optional[str]=None, requestor_organisation_uuid: Optional[str] = None,
requestor_organisation_description: Optional[str]=None, requestor_organisation_description: Optional[str] = None,
message: Optional[str]=None, sync: bool=False, message: Optional[str] = None, sync: bool = False,
anonymise_requestor_server: bool=False, anonymise_requestor_server: bool = False,
mock: bool=False) -> Dict: mock: bool = False) -> Dict:
community_id = get_uuid_or_id_from_abstract_misp(community) community_id = get_uuid_or_id_from_abstract_misp(community)
to_post = {'org_name': requestor_organisation_name, to_post = {'org_name': requestor_organisation_name,
'org_uuid': requestor_organisation_uuid, 'org_uuid': requestor_organisation_uuid,
@ -1970,7 +1970,7 @@ class PyMISP:
# ## BEGIN Event Delegation ### # ## BEGIN Event Delegation ###
def event_delegations(self, pythonify: bool=False) -> Union[Dict, List[MISPEventDelegation]]: def event_delegations(self, pythonify: bool = False) -> Union[Dict, List[MISPEventDelegation]]:
"""Get all the event delegations.""" """Get all the event delegations."""
r = self._prepare_request('GET', 'event_delegations') r = self._prepare_request('GET', 'event_delegations')
delegations = self._check_json_response(r) delegations = self._check_json_response(r)
@ -1983,20 +1983,20 @@ class PyMISP:
to_return.append(d) to_return.append(d)
return to_return return to_return
def accept_event_delegation(self, delegation: Union[MISPEventDelegation, int, str], pythonify: bool=False) -> Dict: def accept_event_delegation(self, delegation: Union[MISPEventDelegation, int, str], pythonify: bool = False) -> Dict:
delegation_id = get_uuid_or_id_from_abstract_misp(delegation) delegation_id = get_uuid_or_id_from_abstract_misp(delegation)
r = self._prepare_request('POST', f'event_delegations/acceptDelegation/{delegation_id}') r = self._prepare_request('POST', f'event_delegations/acceptDelegation/{delegation_id}')
return self._check_json_response(r) return self._check_json_response(r)
def discard_event_delegation(self, delegation: Union[MISPEventDelegation, int, str], pythonify: bool=False) -> Dict: def discard_event_delegation(self, delegation: Union[MISPEventDelegation, int, str], pythonify: bool = False) -> Dict:
delegation_id = get_uuid_or_id_from_abstract_misp(delegation) delegation_id = get_uuid_or_id_from_abstract_misp(delegation)
r = self._prepare_request('POST', f'event_delegations/deleteDelegation/{delegation_id}') r = self._prepare_request('POST', f'event_delegations/deleteDelegation/{delegation_id}')
return self._check_json_response(r) return self._check_json_response(r)
def delegate_event(self, event: Optional[Union[MISPEvent, int, str, UUID]]=None, def delegate_event(self, event: Optional[Union[MISPEvent, int, str, UUID]] = None,
organisation: Optional[Union[MISPOrganisation, int, str, UUID]]=None, organisation: Optional[Union[MISPOrganisation, int, str, UUID]] = None,
event_delegation: Optional[MISPEventDelegation]=None, event_delegation: Optional[MISPEventDelegation] = None,
distribution: int=-1, message: str='', pythonify: bool=False) -> Union[Dict, MISPEventDelegation]: distribution: int = -1, message: str = '', pythonify: bool = False) -> Union[Dict, MISPEventDelegation]:
'''Note: distribution == -1 means recipient decides''' '''Note: distribution == -1 means recipient decides'''
if event and organisation: if event and organisation:
event_id = get_uuid_or_id_from_abstract_misp(event) event_id = get_uuid_or_id_from_abstract_misp(event)
@ -2024,7 +2024,7 @@ class PyMISP:
response = self._prepare_request('POST', f'events/pushEventToZMQ/{event_id}.json') response = self._prepare_request('POST', f'events/pushEventToZMQ/{event_id}.json')
return self._check_json_response(response) return self._check_json_response(response)
def direct_call(self, url: str, data: Optional[Dict]=None, params: Mapping={}, kw_params: Mapping={}) -> Any: def direct_call(self, url: str, data: Optional[Dict] = None, params: Mapping = {}, kw_params: Mapping = {}) -> Any:
'''Very lightweight call that posts a data blob (python dictionary or json string) on the URL''' '''Very lightweight call that posts a data blob (python dictionary or json string) on the URL'''
if data is None: if data is None:
response = self._prepare_request('GET', url, params=params, kw_params=kw_params) response = self._prepare_request('GET', url, params=params, kw_params=kw_params)
@ -2032,8 +2032,8 @@ class PyMISP:
response = self._prepare_request('POST', url, data=data, params=params, kw_params=kw_params) response = self._prepare_request('POST', url, data=data, params=params, kw_params=kw_params)
return self._check_response(response, lenient_response_type=True) return self._check_response(response, lenient_response_type=True)
def freetext(self, event: Union[MISPEvent, int, str, UUID], string: str, adhereToWarninglists: Union[bool, str]=False, def freetext(self, event: Union[MISPEvent, int, str, UUID], string: str, adhereToWarninglists: Union[bool, str] = False,
distribution: Optional[int]=None, returnMetaAttributes: bool=False, pythonify: bool=False, **kwargs) -> Union[Dict, List[MISPAttribute]]: distribution: Optional[int] = None, returnMetaAttributes: bool = False, pythonify: bool = False, **kwargs) -> Union[Dict, List[MISPAttribute]]:
"""Pass a text to the freetext importer""" """Pass a text to the freetext importer"""
event_id = get_uuid_or_id_from_abstract_misp(event) event_id = get_uuid_or_id_from_abstract_misp(event)
query: Dict[str, Any] = {"value": string} query: Dict[str, Any] = {"value": string}
@ -2057,7 +2057,7 @@ class PyMISP:
to_return.append(a) to_return.append(a)
return to_return return to_return
def upload_stix(self, path, version: str='2'): def upload_stix(self, path, version: str = '2'):
"""Upload a STIX file to MISP. """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 path: Path to the STIX on the disk (can be a path-like object, or a pseudofile)
:param version: Can be 1 or 2 :param version: Can be 1 or 2
@ -2083,7 +2083,7 @@ class PyMISP:
# ## BEGIN Statistics ### # ## BEGIN Statistics ###
def attributes_statistics(self, context: str='type', percentage: bool=False) -> Dict: def attributes_statistics(self, context: str = 'type', percentage: bool = False) -> Dict:
"""Get attributes statistics from the MISP instance.""" """Get attributes statistics from the MISP instance."""
# FIXME: https://github.com/MISP/MISP/issues/4874 # FIXME: https://github.com/MISP/MISP/issues/4874
if context not in ['type', 'category']: if context not in ['type', 'category']:
@ -2095,7 +2095,7 @@ class PyMISP:
response = self._prepare_request('GET', path) response = self._prepare_request('GET', path)
return self._check_json_response(response) return self._check_json_response(response)
def tags_statistics(self, percentage: bool=False, name_sort: bool=False) -> Dict: def tags_statistics(self, percentage: bool = False, name_sort: bool = False) -> Dict:
"""Get tags statistics from the MISP instance""" """Get tags statistics from the MISP instance"""
# FIXME: https://github.com/MISP/MISP/issues/4874 # FIXME: https://github.com/MISP/MISP/issues/4874
# NOTE: https://github.com/MISP/MISP/issues/4879 # NOTE: https://github.com/MISP/MISP/issues/4879
@ -2110,7 +2110,7 @@ class PyMISP:
response = self._prepare_request('GET', f'tags/tagStatistics/{p}/{ns}') response = self._prepare_request('GET', f'tags/tagStatistics/{p}/{ns}')
return self._check_json_response(response) return self._check_json_response(response)
def users_statistics(self, context: str='data') -> Dict: def users_statistics(self, context: str = 'data') -> Dict:
"""Get users statistics from the MISP instance""" """Get users statistics from the MISP instance"""
availables_contexts = ['data', 'orgs', 'users', 'tags', 'attributehistogram', 'sightings', 'galaxyMatrix'] availables_contexts = ['data', 'orgs', 'users', 'tags', 'attributehistogram', 'sightings', 'galaxyMatrix']
if context not in availables_contexts: if context not in availables_contexts:
@ -2122,7 +2122,7 @@ class PyMISP:
# ## BEGIN User Settings ### # ## BEGIN User Settings ###
def user_settings(self, pythonify: bool=False) -> Union[Dict, List[MISPUserSetting]]: def user_settings(self, pythonify: bool = False) -> Union[Dict, List[MISPUserSetting]]:
"""Get all the user settings.""" """Get all the user settings."""
r = self._prepare_request('GET', 'user_settings') r = self._prepare_request('GET', 'user_settings')
user_settings = self._check_json_response(r) user_settings = self._check_json_response(r)
@ -2135,8 +2135,8 @@ class PyMISP:
to_return.append(u) to_return.append(u)
return to_return return to_return
def get_user_setting(self, user_setting: str, user: Optional[Union[MISPUser, int, str, UUID]]=None, def get_user_setting(self, user_setting: str, user: Optional[Union[MISPUser, int, str, UUID]] = None,
pythonify: bool=False) -> Union[Dict, MISPUserSetting]: pythonify: bool = False) -> Union[Dict, MISPUserSetting]:
'''Get an user setting''' '''Get an user setting'''
query: Dict[str, Any] = {'setting': user_setting} query: Dict[str, Any] = {'setting': user_setting}
if user: if user:
@ -2149,8 +2149,8 @@ class PyMISP:
u.from_dict(**user_setting_j) u.from_dict(**user_setting_j)
return u return u
def set_user_setting(self, user_setting: str, value: Union[str, dict], user: Optional[Union[MISPUser, int, str, UUID]]=None, def set_user_setting(self, user_setting: str, value: Union[str, dict], user: Optional[Union[MISPUser, int, str, UUID]] = None,
pythonify: bool=False) -> Union[Dict, MISPUserSetting]: pythonify: bool = False) -> Union[Dict, MISPUserSetting]:
'''Get an user setting''' '''Get an user setting'''
query: Dict[str, Any] = {'setting': user_setting} query: Dict[str, Any] = {'setting': user_setting}
if isinstance(value, dict): if isinstance(value, dict):
@ -2166,7 +2166,7 @@ class PyMISP:
u.from_dict(**user_setting_j) u.from_dict(**user_setting_j)
return u return u
def delete_user_setting(self, user_setting: str, user: Optional[Union[MISPUser, int, str, UUID]]=None) -> Dict: def delete_user_setting(self, user_setting: str, user: Optional[Union[MISPUser, int, str, UUID]] = None) -> Dict:
'''Delete a user setting''' '''Delete a user setting'''
query: Dict[str, Any] = {'setting': user_setting} query: Dict[str, Any] = {'setting': user_setting}
if user: if user:
@ -2178,7 +2178,7 @@ class PyMISP:
# ## BEGIN Global helpers ### # ## BEGIN Global helpers ###
def change_sharing_group_on_entity(self, misp_entity: Union[MISPEvent, MISPAttribute, MISPObject], sharing_group_id, pythonify: bool=False) -> Union[Dict, MISPEvent, MISPObject, MISPAttribute, MISPShadowAttribute]: def change_sharing_group_on_entity(self, misp_entity: Union[MISPEvent, MISPAttribute, MISPObject], sharing_group_id, pythonify: bool = False) -> Union[Dict, MISPEvent, MISPObject, MISPAttribute, MISPShadowAttribute]:
"""Change the sharing group of an event, an attribute, or an object""" """Change the sharing group of an event, an attribute, or an object"""
misp_entity.distribution = 4 # Needs to be 'Sharing group' misp_entity.distribution = 4 # Needs to be 'Sharing group'
if 'SharingGroup' in misp_entity: # Delete former SharingGroup information if 'SharingGroup' in misp_entity: # Delete former SharingGroup information
@ -2195,7 +2195,7 @@ class PyMISP:
raise PyMISPError('The misp_entity must be MISPEvent, MISPObject or MISPAttribute') raise PyMISPError('The misp_entity must be MISPEvent, MISPObject or MISPAttribute')
def tag(self, misp_entity: Union[AbstractMISP, str, dict], tag: Union[MISPTag, str], local: bool=False) -> Dict: def tag(self, misp_entity: Union[AbstractMISP, str, dict], tag: Union[MISPTag, str], local: bool = False) -> Dict:
"""Tag an event or an attribute. misp_entity can be a MISPEvent, a MISP Attribute, or a UUID""" """Tag an event or an attribute. misp_entity can be a MISPEvent, a MISP Attribute, or a UUID"""
if isinstance(misp_entity, AbstractMISP) and 'uuid' in misp_entity: if isinstance(misp_entity, AbstractMISP) and 'uuid' in misp_entity:
uuid = misp_entity.uuid uuid = misp_entity.uuid
@ -2226,9 +2226,9 @@ class PyMISP:
response = self._prepare_request('POST', 'tags/removeTagFromObject', data=to_post) response = self._prepare_request('POST', 'tags/removeTagFromObject', data=to_post)
return self._check_json_response(response) return self._check_json_response(response)
def build_complex_query(self, or_parameters: Optional[List[SearchType]]=None, def build_complex_query(self, or_parameters: Optional[List[SearchType]] = None,
and_parameters: Optional[List[SearchType]]=None, and_parameters: Optional[List[SearchType]] = None,
not_parameters: Optional[List[SearchType]]=None) -> Dict[str, List[SearchType]]: not_parameters: Optional[List[SearchType]] = None) -> Dict[str, List[SearchType]]:
'''Build a complex search query. MISP expects a dictionary with AND, OR and NOT keys.''' '''Build a complex search query. MISP expects a dictionary with AND, OR and NOT keys.'''
to_return = {} to_return = {}
if and_parameters: if and_parameters:
@ -2243,7 +2243,7 @@ class PyMISP:
# ## Internal methods ### # ## Internal methods ###
def _old_misp(self, minimal_version_required: tuple, removal_date: Union[str, date, datetime], method: Optional[str]=None, message: Optional[str]=None) -> bool: def _old_misp(self, minimal_version_required: tuple, removal_date: Union[str, date, datetime], method: Optional[str] = None, message: Optional[str] = None) -> bool:
if self._misp_version >= minimal_version_required: if self._misp_version >= minimal_version_required:
return False return False
if isinstance(removal_date, (datetime, date)): if isinstance(removal_date, (datetime, date)):
@ -2254,7 +2254,7 @@ class PyMISP:
warnings.warn(to_print, DeprecationWarning) warnings.warn(to_print, DeprecationWarning)
return True return True
def _make_misp_bool(self, parameter: Optional[Union[bool, str]]=None) -> int: def _make_misp_bool(self, parameter: Optional[Union[bool, str]] = None) -> int:
'''MISP wants 0 or 1 for bool, so we avoid True/False '0', '1' ''' '''MISP wants 0 or 1 for bool, so we avoid True/False '0', '1' '''
if parameter is None: if parameter is None:
return 0 return 0
@ -2287,7 +2287,7 @@ class PyMISP:
return r return r
# Else: an exception was raised anyway # Else: an exception was raised anyway
def _check_response(self, response: requests.Response, lenient_response_type: bool=False, expect_json: bool=False) -> Union[Dict, str]: def _check_response(self, response: requests.Response, lenient_response_type: bool = False, expect_json: bool = False) -> Union[Dict, str]:
"""Check if the response from the server is not an unexpected error""" """Check if the response from the server is not an unexpected error"""
if response.status_code >= 500: if response.status_code >= 500:
logger.critical(everything_broken.format(response.request.headers, response.request.body, response.text)) logger.critical(everything_broken.format(response.request.headers, response.request.body, response.text))
@ -2327,8 +2327,8 @@ class PyMISP:
def __repr__(self): def __repr__(self):
return f'<{self.__class__.__name__}(url={self.root_url})' return f'<{self.__class__.__name__}(url={self.root_url})'
def _prepare_request(self, request_type: str, url: str, data: Union[str, Iterator, Mapping, AbstractMISP]={}, params: Mapping={}, def _prepare_request(self, request_type: str, url: str, data: Union[str, Iterator, Mapping, AbstractMISP] = {}, params: Mapping = {},
kw_params: Mapping={}, output_type: str='json') -> requests.Response: kw_params: Mapping = {}, output_type: str = 'json') -> requests.Response:
'''Prepare a request for python-requests''' '''Prepare a request for python-requests'''
url = urljoin(self.root_url, url) url = urljoin(self.root_url, url)
if data == {} or isinstance(data, str): if data == {} or isinstance(data, str):

View File

@ -174,7 +174,7 @@ class MISPAttribute(AbstractMISP):
'deleted', 'timestamp', 'to_ids', 'disable_correlation', 'deleted', 'timestamp', 'to_ids', 'disable_correlation',
'first_seen', 'last_seen'} 'first_seen', 'last_seen'}
def __init__(self, describe_types: Optional[Dict]=None, strict: bool=False): def __init__(self, describe_types: Optional[Dict] = None, strict: bool = False):
"""Represents an Attribute """Represents an Attribute
:describe_type: Use it is you want to overwrite the defualt describeTypes.json file (you don't) :describe_type: Use it is you want to overwrite the defualt describeTypes.json file (you don't)
:strict: If false, fallback to sane defaults for the attribute type if the ones passed by the user are incorrect :strict: If false, fallback to sane defaults for the attribute type if the ones passed by the user are incorrect
@ -199,7 +199,7 @@ class MISPAttribute(AbstractMISP):
self.Event: MISPEvent self.Event: MISPEvent
self.RelatedAttribute: List[MISPAttribute] self.RelatedAttribute: List[MISPAttribute]
def add_tag(self, tag: Optional[Union[str, MISPTag, Dict]]=None, **kwargs) -> MISPTag: def add_tag(self, tag: Optional[Union[str, MISPTag, Dict]] = None, **kwargs) -> MISPTag:
return super()._add_tag(tag, **kwargs) return super()._add_tag(tag, **kwargs)
@property @property
@ -258,7 +258,7 @@ class MISPAttribute(AbstractMISP):
else: else:
super().__setattr__(name, value) super().__setattr__(name, value)
def hash_values(self, algorithm: str='sha512') -> List[str]: def hash_values(self, algorithm: str = 'sha512') -> List[str]:
"""Compute the hash of every values for fast lookups""" """Compute the hash of every values for fast lookups"""
if algorithm not in hashlib.algorithms_available: if algorithm not in hashlib.algorithms_available:
raise PyMISPError('The algorithm {} is not available for hashing.'.format(algorithm)) raise PyMISPError('The algorithm {} is not available for hashing.'.format(algorithm))
@ -335,7 +335,7 @@ class MISPAttribute(AbstractMISP):
"""Alias for add_shadow_attribute""" """Alias for add_shadow_attribute"""
return self.add_shadow_attribute(shadow_attribute, **kwargs) return self.add_shadow_attribute(shadow_attribute, **kwargs)
def add_shadow_attribute(self, shadow_attribute: Optional[Union[MISPShadowAttribute, Dict]]=None, **kwargs) -> MISPShadowAttribute: def add_shadow_attribute(self, shadow_attribute: Optional[Union[MISPShadowAttribute, Dict]] = None, **kwargs) -> MISPShadowAttribute:
"""Add a shadow attribute to the attribute (by name or a MISPShadowAttribute object)""" """Add a shadow attribute to the attribute (by name or a MISPShadowAttribute object)"""
if isinstance(shadow_attribute, MISPShadowAttribute): if isinstance(shadow_attribute, MISPShadowAttribute):
misp_shadow_attribute = shadow_attribute misp_shadow_attribute = shadow_attribute
@ -351,7 +351,7 @@ class MISPAttribute(AbstractMISP):
self.edited = True self.edited = True
return misp_shadow_attribute return misp_shadow_attribute
def add_sighting(self, sighting: Optional[Union[MISPSighting, dict]]=None, **kwargs) -> MISPSighting: def add_sighting(self, sighting: Optional[Union[MISPSighting, dict]] = None, **kwargs) -> MISPSighting:
"""Add a sighting to the attribute (by name or a MISPSighting object)""" """Add a sighting to the attribute (by name or a MISPSighting object)"""
if isinstance(sighting, MISPSighting): if isinstance(sighting, MISPSighting):
misp_sighting = sighting misp_sighting = sighting
@ -603,7 +603,7 @@ class MISPObject(AbstractMISP):
'sharing_group_id', 'comment', 'first_seen', 'last_seen', 'sharing_group_id', 'comment', 'first_seen', 'last_seen',
'deleted'} 'deleted'}
def __init__(self, name: str, strict: bool=False, standalone: bool=True, default_attributes_parameters: dict={}, **kwargs): def __init__(self, name: str, strict: bool = False, standalone: bool = True, default_attributes_parameters: dict = {}, **kwargs):
''' Master class representing a generic MISP object ''' Master class representing a generic MISP object
:name: Name of the object :name: Name of the object
@ -691,12 +691,12 @@ class MISPObject(AbstractMISP):
raise PyMISPError('first_seen ({value}) has to be before last_seen ({self.last_seen})') raise PyMISPError('first_seen ({value}) has to be before last_seen ({self.last_seen})')
super().__setattr__(name, value) super().__setattr__(name, value)
def force_misp_objects_path_custom(self, misp_objects_path_custom: Union[Path, str], object_name: Optional[str]=None): def force_misp_objects_path_custom(self, misp_objects_path_custom: Union[Path, str], object_name: Optional[str] = None):
if object_name: if object_name:
self.name = object_name self.name = object_name
self._set_template(misp_objects_path_custom) self._set_template(misp_objects_path_custom)
def _set_template(self, misp_objects_path_custom: Optional[Union[Path, str]]=None): def _set_template(self, misp_objects_path_custom: Optional[Union[Path, str]] = None):
if misp_objects_path_custom: if misp_objects_path_custom:
# If misp_objects_path_custom is given, and an object with the given name exists, use that. # If misp_objects_path_custom is given, and an object with the given name exists, use that.
if isinstance(misp_objects_path_custom, str): if isinstance(misp_objects_path_custom, str):
@ -822,7 +822,7 @@ class MISPObject(AbstractMISP):
super().from_dict(**kwargs) super().from_dict(**kwargs)
def add_reference(self, referenced_uuid: Union[AbstractMISP, str], relationship_type: str, comment: Optional[str]=None, **kwargs) -> MISPObjectReference: def add_reference(self, referenced_uuid: Union[AbstractMISP, str], relationship_type: str, comment: Optional[str] = None, **kwargs) -> MISPObjectReference:
"""Add a link (uuid) to an other object""" """Add a link (uuid) to an other object"""
if isinstance(referenced_uuid, AbstractMISP): if isinstance(referenced_uuid, AbstractMISP):
# Allow to pass an object or an attribute instead of its UUID # Allow to pass an object or an attribute instead of its UUID
@ -855,7 +855,7 @@ class MISPObject(AbstractMISP):
'''True if all the relations in the list are defined in the object''' '''True if all the relations in the list are defined in the object'''
return all(relation in self._fast_attribute_access for relation in list_of_relations) return all(relation in self._fast_attribute_access for relation in list_of_relations)
def add_attribute(self, object_relation: str, simple_value: Optional[Union[str, int, float]]=None, **value) -> Optional[MISPAttribute]: def add_attribute(self, object_relation: str, simple_value: Optional[Union[str, int, float]] = None, **value) -> Optional[MISPAttribute]:
"""Add an attribute. object_relation is required and the value key is a """Add an attribute. object_relation is required and the value key is a
dictionary with all the keys supported by MISPAttribute""" dictionary with all the keys supported by MISPAttribute"""
if simple_value is not None: # /!\ The value *can* be 0 if simple_value is not None: # /!\ The value *can* be 0
@ -902,12 +902,12 @@ class MISPObject(AbstractMISP):
to_return.append(a) to_return.append(a)
return to_return return to_return
def to_dict(self, strict: bool=False) -> Dict: def to_dict(self, strict: bool = False) -> Dict:
if strict or self._strict and self._known_template: if strict or self._strict and self._known_template:
self._validate() self._validate()
return super(MISPObject, self).to_dict() return super(MISPObject, self).to_dict()
def to_json(self, sort_keys: bool=False, indent: Optional[int]=None, strict: bool=False): def to_json(self, sort_keys: bool = False, indent: Optional[int] = None, strict: bool = False):
if strict or self._strict and self._known_template: if strict or self._strict and self._known_template:
self._validate() self._validate()
return super(MISPObject, self).to_json(sort_keys=sort_keys, indent=indent) return super(MISPObject, self).to_json(sort_keys=sort_keys, indent=indent)
@ -944,7 +944,7 @@ class MISPEvent(AbstractMISP):
_fields_for_feed: set = {'uuid', 'info', 'threat_level_id', 'analysis', 'timestamp', _fields_for_feed: set = {'uuid', 'info', 'threat_level_id', 'analysis', 'timestamp',
'publish_timestamp', 'published', 'date', 'extends_uuid'} 'publish_timestamp', 'published', 'date', 'extends_uuid'}
def __init__(self, describe_types: Optional[Dict]=None, strict_validation: bool=False, **kwargs): def __init__(self, describe_types: Optional[Dict] = None, strict_validation: bool = False, **kwargs):
super().__init__(**kwargs) super().__init__(**kwargs)
if strict_validation: if strict_validation:
schema_file = 'schema.json' schema_file = 'schema.json'
@ -964,7 +964,7 @@ class MISPEvent(AbstractMISP):
self.SharingGroup: MISPSharingGroup self.SharingGroup: MISPSharingGroup
self.Tag: List[MISPTag] = [] self.Tag: List[MISPTag] = []
def add_tag(self, tag: Optional[Union[str, MISPTag, dict]]=None, **kwargs) -> MISPTag: def add_tag(self, tag: Optional[Union[str, MISPTag, dict]] = None, **kwargs) -> MISPTag:
return super()._add_tag(tag, **kwargs) return super()._add_tag(tag, **kwargs)
@property @property
@ -1019,7 +1019,7 @@ class MISPEvent(AbstractMISP):
} }
} }
def attributes_hashes(self, algorithm: str='sha512') -> List[str]: def attributes_hashes(self, algorithm: str = 'sha512') -> List[str]:
to_return: List[str] = [] to_return: List[str] = []
for attribute in self.attributes: for attribute in self.attributes:
to_return += attribute.hash_values(algorithm) to_return += attribute.hash_values(algorithm)
@ -1028,7 +1028,7 @@ class MISPEvent(AbstractMISP):
to_return += attribute.hash_values(algorithm) to_return += attribute.hash_values(algorithm)
return to_return return to_return
def to_feed(self, valid_distributions: List[int]=[0, 1, 2, 3, 4, 5], with_meta: bool=False) -> Dict: def to_feed(self, valid_distributions: List[int] = [0, 1, 2, 3, 4, 5], with_meta: bool = False) -> Dict:
""" Generate a json output for MISP Feed. """ Generate a json output for MISP Feed.
Notes: Notes:
* valid_distributions only makes sense if the distribution key is set (i.e. the event is exported from a MISP instance) * valid_distributions only makes sense if the distribution key is set (i.e. the event is exported from a MISP instance)
@ -1132,14 +1132,14 @@ class MISPEvent(AbstractMISP):
else: else:
raise PyMISPError('All the attributes have to be of type MISPObject.') raise PyMISPError('All the attributes have to be of type MISPObject.')
def load_file(self, event_path: Union[Path, str], validate: bool=False, metadata_only: bool=False): def load_file(self, event_path: Union[Path, str], validate: bool = False, metadata_only: bool = False):
"""Load a JSON dump from a file on the disk""" """Load a JSON dump from a file on the disk"""
if not os.path.exists(event_path): if not os.path.exists(event_path):
raise PyMISPError('Invalid path, unable to load the event.') raise PyMISPError('Invalid path, unable to load the event.')
with open(event_path, 'rb') as f: with open(event_path, 'rb') as f:
self.load(f, validate, metadata_only) self.load(f, validate, metadata_only)
def load(self, json_event: Union[IO, str, bytes, dict], validate: bool=False, metadata_only: bool=False): def load(self, json_event: Union[IO, str, bytes, dict], validate: bool = False, metadata_only: bool = False):
"""Load a JSON dump from a pseudo file or a JSON string""" """Load a JSON dump from a pseudo file or a JSON string"""
if isinstance(json_event, IOBase): if isinstance(json_event, IOBase):
# python2 and python3 compatible to find if we have a file # python2 and python3 compatible to find if we have a file
@ -1181,7 +1181,7 @@ class MISPEvent(AbstractMISP):
raise NewEventError(f'Invalid format for the date: {type(value)} - {value}') raise NewEventError(f'Invalid format for the date: {type(value)} - {value}')
super().__setattr__(name, value) super().__setattr__(name, value)
def set_date(self, d: Optional[Union[str, int, float, datetime, date]]=None, ignore_invalid: bool=False): def set_date(self, d: Optional[Union[str, int, float, datetime, date]] = None, ignore_invalid: bool = False):
"""Set a date for the event (string, datetime, or date object)""" """Set a date for the event (string, datetime, or date object)"""
if isinstance(d, (str, int, float, datetime, date)): if isinstance(d, (str, int, float, datetime, date)):
self.date = d # type: ignore self.date = d # type: ignore
@ -1382,7 +1382,7 @@ class MISPEvent(AbstractMISP):
objects.append(obj) objects.append(obj)
return objects return objects
def add_object(self, obj: Union[MISPObject, dict, None]=None, **kwargs) -> MISPObject: def add_object(self, obj: Union[MISPObject, dict, None] = None, **kwargs) -> MISPObject:
"""Add an object to the Event, either by passing a MISPObject, or a dictionary""" """Add an object to the Event, either by passing a MISPObject, or a dictionary"""
if isinstance(obj, MISPObject): if isinstance(obj, MISPObject):
misp_obj = obj misp_obj = obj

View File

@ -21,7 +21,7 @@ class AbstractMISPObjectGenerator(MISPObject):
except ValueError: except ValueError:
return False return False
def _sanitize_timestamp(self, timestamp: Optional[Union[datetime, date, dict, str, int, float]]=None) -> datetime: def _sanitize_timestamp(self, timestamp: Optional[Union[datetime, date, dict, str, int, float]] = None) -> datetime:
if not timestamp: if not timestamp:
return datetime.now() return datetime.now()

View File

@ -9,7 +9,7 @@ logger = logging.getLogger('pymisp')
class ASNObject(AbstractMISPObjectGenerator): class ASNObject(AbstractMISPObjectGenerator):
def __init__(self, parameters: dict, strict: bool=True, **kwargs): def __init__(self, parameters: dict, strict: bool = True, **kwargs):
super(ASNObject, self).__init__('asn', strict=strict, **kwargs) super(ASNObject, self).__init__('asn', strict=strict, **kwargs)
self._parameters = parameters self._parameters = parameters
self.generate_attributes() self.generate_attributes()

View File

@ -29,7 +29,7 @@ class FileTypeNotImplemented(MISPObjectException):
pass pass
def make_binary_objects(filepath: Optional[str]=None, pseudofile: Optional[BytesIO]=None, filename: Optional[str]=None, standalone: bool=True, default_attributes_parameters: dict={}): def make_binary_objects(filepath: Optional[str] = None, pseudofile: Optional[BytesIO] = None, filename: Optional[str] = None, standalone: bool = True, default_attributes_parameters: dict = {}):
misp_file = FileObject(filepath=filepath, pseudofile=pseudofile, filename=filename, misp_file = FileObject(filepath=filepath, pseudofile=pseudofile, filename=filename,
standalone=standalone, default_attributes_parameters=default_attributes_parameters) standalone=standalone, default_attributes_parameters=default_attributes_parameters)
if HAS_LIEF and (filepath or (pseudofile and filename)): if HAS_LIEF and (filepath or (pseudofile and filename)):

View File

@ -8,8 +8,8 @@ from pymisp import MISPObject
class CSVLoader(): class CSVLoader():
def __init__(self, template_name: str, csv_path: Path, fieldnames: list=[], has_fieldnames=False, def __init__(self, template_name: str, csv_path: Path, fieldnames: list = [], has_fieldnames=False,
delimiter: str=',', quotechar: str='"'): delimiter: str = ',', quotechar: str = '"'):
self.template_name = template_name self.template_name = template_name
self.delimiter = delimiter self.delimiter = delimiter
self.quotechar = quotechar self.quotechar = quotechar

View File

@ -9,7 +9,7 @@ logger = logging.getLogger('pymisp')
class DomainIPObject(AbstractMISPObjectGenerator): class DomainIPObject(AbstractMISPObjectGenerator):
def __init__(self, parameters: dict, strict: bool=True, **kwargs): def __init__(self, parameters: dict, strict: bool = True, **kwargs):
super(DomainIPObject, self).__init__('domain-ip', strict=strict, **kwargs) super(DomainIPObject, self).__init__('domain-ip', strict=strict, **kwargs)
self._parameters = parameters self._parameters = parameters
self.generate_attributes() self.generate_attributes()

View File

@ -21,7 +21,7 @@ except ImportError:
logger = logging.getLogger('pymisp') logger = logging.getLogger('pymisp')
def make_elf_objects(lief_parsed: lief.Binary, misp_file: FileObject, standalone: bool=True, default_attributes_parameters: dict={}): def make_elf_objects(lief_parsed: lief.Binary, misp_file: FileObject, standalone: bool = True, default_attributes_parameters: dict = {}):
elf_object = ELFObject(parsed=lief_parsed, standalone=standalone, default_attributes_parameters=default_attributes_parameters) elf_object = ELFObject(parsed=lief_parsed, standalone=standalone, default_attributes_parameters=default_attributes_parameters)
misp_file.add_reference(elf_object.uuid, 'includes', 'ELF indicators') misp_file.add_reference(elf_object.uuid, 'includes', 'ELF indicators')
elf_sections = [] elf_sections = []
@ -32,7 +32,7 @@ def make_elf_objects(lief_parsed: lief.Binary, misp_file: FileObject, standalone
class ELFObject(AbstractMISPObjectGenerator): class ELFObject(AbstractMISPObjectGenerator):
def __init__(self, parsed: lief.ELF.Binary=None, filepath: Union[Path, str]=None, pseudofile: Union[BytesIO, bytes]=None, **kwargs): def __init__(self, parsed: lief.ELF.Binary = None, filepath: Union[Path, str] = None, pseudofile: Union[BytesIO, bytes] = None, **kwargs):
super(ELFObject, self).__init__('elf', **kwargs) super(ELFObject, self).__init__('elf', **kwargs)
if not HAS_PYDEEP: if not HAS_PYDEEP:
logger.warning("Please install pydeep: pip install git+https://github.com/kbandla/pydeep.git") logger.warning("Please install pydeep: pip install git+https://github.com/kbandla/pydeep.git")

View File

@ -14,7 +14,7 @@ logger = logging.getLogger('pymisp')
class EMailObject(AbstractMISPObjectGenerator): class EMailObject(AbstractMISPObjectGenerator):
def __init__(self, filepath: Union[Path, str]=None, pseudofile: BytesIO=None, attach_original_email: bool=True, **kwargs): def __init__(self, filepath: Union[Path, str] = None, pseudofile: BytesIO = None, attach_original_email: bool = True, **kwargs):
# PY3 way: # PY3 way:
# super().__init__('file') # super().__init__('file')
super(EMailObject, self).__init__('email', **kwargs) super(EMailObject, self).__init__('email', **kwargs)

View File

@ -9,7 +9,7 @@ logger = logging.getLogger('pymisp')
class Fail2BanObject(AbstractMISPObjectGenerator): class Fail2BanObject(AbstractMISPObjectGenerator):
def __init__(self, parameters: dict, strict: bool=True, **kwargs): def __init__(self, parameters: dict, strict: bool = True, **kwargs):
super(Fail2BanObject, self).__init__('fail2ban', strict=strict, **kwargs) super(Fail2BanObject, self).__init__('fail2ban', strict=strict, **kwargs)
self._parameters = parameters self._parameters = parameters
self.generate_attributes() self.generate_attributes()

View File

@ -30,7 +30,7 @@ except ImportError:
class FileObject(AbstractMISPObjectGenerator): class FileObject(AbstractMISPObjectGenerator):
def __init__(self, filepath: Union[Path, str]=None, pseudofile: BytesIO=None, filename: str=None, **kwargs): def __init__(self, filepath: Union[Path, str] = None, pseudofile: BytesIO = None, filename: str = None, **kwargs):
# PY3 way: # PY3 way:
# super().__init__('file') # super().__init__('file')
super(FileObject, self).__init__('file', **kwargs) super(FileObject, self).__init__('file', **kwargs)

View File

@ -9,7 +9,7 @@ logger = logging.getLogger('pymisp')
class GeolocationObject(AbstractMISPObjectGenerator): class GeolocationObject(AbstractMISPObjectGenerator):
def __init__(self, parameters: dict, strict: bool=True, **kwargs): def __init__(self, parameters: dict, strict: bool = True, **kwargs):
super(GeolocationObject, self).__init__('asn', strict=strict, **kwargs) super(GeolocationObject, self).__init__('asn', strict=strict, **kwargs)
self._parameters = parameters self._parameters = parameters
self.generate_attributes() self.generate_attributes()

View File

@ -9,7 +9,7 @@ logger = logging.getLogger('pymisp')
class GitVulnFinderObject(AbstractMISPObjectGenerator): class GitVulnFinderObject(AbstractMISPObjectGenerator):
def __init__(self, parameters: dict, strict: bool=True, **kwargs): def __init__(self, parameters: dict, strict: bool = True, **kwargs):
super(GitVulnFinderObject, self).__init__('git-vuln-finder', strict=strict, **kwargs) super(GitVulnFinderObject, self).__init__('git-vuln-finder', strict=strict, **kwargs)
self._parameters = parameters self._parameters = parameters
self.generate_attributes() self.generate_attributes()

View File

@ -21,7 +21,7 @@ except ImportError:
logger = logging.getLogger('pymisp') logger = logging.getLogger('pymisp')
def make_macho_objects(lief_parsed: lief.Binary, misp_file: FileObject, standalone: bool=True, default_attributes_parameters: dict={}): def make_macho_objects(lief_parsed: lief.Binary, misp_file: FileObject, standalone: bool = True, default_attributes_parameters: dict = {}):
macho_object = MachOObject(parsed=lief_parsed, standalone=standalone, default_attributes_parameters=default_attributes_parameters) macho_object = MachOObject(parsed=lief_parsed, standalone=standalone, default_attributes_parameters=default_attributes_parameters)
misp_file.add_reference(macho_object.uuid, 'includes', 'MachO indicators') misp_file.add_reference(macho_object.uuid, 'includes', 'MachO indicators')
macho_sections = [] macho_sections = []
@ -32,7 +32,7 @@ def make_macho_objects(lief_parsed: lief.Binary, misp_file: FileObject, standalo
class MachOObject(AbstractMISPObjectGenerator): class MachOObject(AbstractMISPObjectGenerator):
def __init__(self, parsed: Optional[lief.MachO.Binary]=None, filepath: Optional[Union[Path, str]]=None, pseudofile: Optional[BytesIO]=None, **kwargs): def __init__(self, parsed: Optional[lief.MachO.Binary] = None, filepath: Optional[Union[Path, str]] = None, pseudofile: Optional[BytesIO] = None, **kwargs):
# Python3 way # Python3 way
# super().__init__('elf') # super().__init__('elf')
super(MachOObject, self).__init__('macho', **kwargs) super(MachOObject, self).__init__('macho', **kwargs)

View File

@ -23,7 +23,7 @@ except ImportError:
logger = logging.getLogger('pymisp') logger = logging.getLogger('pymisp')
def make_pe_objects(lief_parsed: lief.Binary, misp_file: FileObject, standalone: bool=True, default_attributes_parameters: dict={}): def make_pe_objects(lief_parsed: lief.Binary, misp_file: FileObject, standalone: bool = True, default_attributes_parameters: dict = {}):
pe_object = PEObject(parsed=lief_parsed, standalone=standalone, default_attributes_parameters=default_attributes_parameters) pe_object = PEObject(parsed=lief_parsed, standalone=standalone, default_attributes_parameters=default_attributes_parameters)
misp_file.add_reference(pe_object.uuid, 'includes', 'PE indicators') misp_file.add_reference(pe_object.uuid, 'includes', 'PE indicators')
pe_sections = [] pe_sections = []
@ -34,7 +34,7 @@ def make_pe_objects(lief_parsed: lief.Binary, misp_file: FileObject, standalone:
class PEObject(AbstractMISPObjectGenerator): class PEObject(AbstractMISPObjectGenerator):
def __init__(self, parsed: Optional[lief.PE.Binary]=None, filepath: Optional[Union[Path, str]]=None, pseudofile: Optional[BytesIO]=None, **kwargs): def __init__(self, parsed: Optional[lief.PE.Binary] = None, filepath: Optional[Union[Path, str]] = None, pseudofile: Optional[BytesIO] = None, **kwargs):
# Python3 way # Python3 way
# super().__init__('pe') # super().__init__('pe')
super(PEObject, self).__init__('pe', **kwargs) super(PEObject, self).__init__('pe', **kwargs)

View File

@ -13,7 +13,7 @@ logger = logging.getLogger('pymisp')
class SSHAuthorizedKeysObject(AbstractMISPObjectGenerator): class SSHAuthorizedKeysObject(AbstractMISPObjectGenerator):
def __init__(self, authorized_keys_path: Optional[Union[Path, str]]=None, authorized_keys_pseudofile: Optional[StringIO]=None, **kwargs): def __init__(self, authorized_keys_path: Optional[Union[Path, str]] = None, authorized_keys_pseudofile: Optional[StringIO] = None, **kwargs):
# PY3 way: # PY3 way:
# super().__init__('file') # super().__init__('file')
super(SSHAuthorizedKeysObject, self).__init__('ssh-authorized-keys', **kwargs) super(SSHAuthorizedKeysObject, self).__init__('ssh-authorized-keys', **kwargs)

View File

@ -9,7 +9,7 @@ except ImportError:
has_misp_stix_converter = False has_misp_stix_converter = False
def load_stix(stix, distribution: int=3, threat_level_id: int=2, analysis: int=0): def load_stix(stix, distribution: int = 3, threat_level_id: int = 2, analysis: int = 0):
'''Returns a MISPEvent object from a STIX package''' '''Returns a MISPEvent object from a STIX package'''
if not has_misp_stix_converter: if not has_misp_stix_converter:
raise Exception('You need to install misp_stix_converter: pip install git+https://github.com/MISP/MISP-STIX-Converter.git') raise Exception('You need to install misp_stix_converter: pip install git+https://github.com/MISP/MISP-STIX-Converter.git')
@ -18,7 +18,7 @@ def load_stix(stix, distribution: int=3, threat_level_id: int=2, analysis: int=0
threat_level_id=threat_level_id, analysis=analysis) threat_level_id=threat_level_id, analysis=analysis)
def make_stix_package(misp_event, to_json: bool=False, to_xml: bool=False): def make_stix_package(misp_event, to_json: bool = False, to_xml: bool = False):
'''Returns a STIXPackage from a MISPEvent. '''Returns a STIXPackage from a MISPEvent.
Optionally can return the package in json or xml. Optionally can return the package in json or xml.

View File

@ -24,7 +24,7 @@ class VTReportObject(AbstractMISPObjectGenerator):
:indicator: IOC to search VirusTotal for :indicator: IOC to search VirusTotal for
''' '''
def __init__(self, apikey: str, indicator: str, vt_proxies: Optional[dict]=None, **kwargs): def __init__(self, apikey: str, indicator: str, vt_proxies: Optional[dict] = None, **kwargs):
# PY3 way: # PY3 way:
# super().__init__("virustotal-report") # super().__init__("virustotal-report")
super(VTReportObject, self).__init__("virustotal-report", **kwargs) super(VTReportObject, self).__init__("virustotal-report", **kwargs)