-
Notifications
You must be signed in to change notification settings - Fork 284
/
Copy pathapi.py
4115 lines (3527 loc) · 205 KB
/
api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
from typing import TypeVar, Any, Mapping, Iterable, MutableMapping, Union, List, Dict
from datetime import date, datetime
import csv
from pathlib import Path
import logging
from urllib.parse import urljoin
import requests
from requests.auth import AuthBase
import re
from uuid import UUID
import warnings
import sys
import copy
from io import BytesIO, StringIO
from importlib.metadata import version
try:
# orjson is optional dependency that speedups parsing and encoding JSON
from orjson import loads, dumps # type: ignore
HAS_ORJSON = True
except ImportError:
from json import loads, dumps
HAS_ORJSON = False
from . import __version__, everything_broken
from .exceptions import MISPServerError, PyMISPUnexpectedResponse, PyMISPError, NoURL, NoKey
from .mispevent import MISPEvent, MISPAttribute, MISPSighting, MISPLog, MISPObject, \
MISPUser, MISPOrganisation, MISPShadowAttribute, MISPWarninglist, MISPTaxonomy, \
MISPGalaxy, MISPNoticelist, MISPObjectReference, MISPObjectTemplate, MISPSharingGroup, \
MISPRole, MISPServer, MISPFeed, MISPEventDelegation, MISPCommunity, MISPUserSetting, \
MISPInbox, MISPEventBlocklist, MISPOrganisationBlocklist, MISPEventReport, \
MISPGalaxyCluster, MISPGalaxyClusterRelation, MISPCorrelationExclusion, MISPDecayingModel, \
MISPNote, MISPOpinion, MISPRelationship, MISPAnalystData
from .abstract import pymisp_json_default, MISPTag, AbstractMISP, describe_types
if sys.platform == 'linux':
# Enable TCP keepalive by default on every requests
import socket
from urllib3.connection import HTTPConnection
HTTPConnection.default_socket_options = HTTPConnection.default_socket_options + [
(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1), # enable keepalive
(socket.SOL_TCP, socket.TCP_KEEPIDLE, 30), # Start pinging after 30s of idle time
(socket.SOL_TCP, socket.TCP_KEEPINTVL, 10), # ping every 10s
(socket.SOL_TCP, socket.TCP_KEEPCNT, 6) # kill the connection if 6 ping fail (60s total)
]
try:
# cached_property exists since Python 3.8
from functools import cached_property
except ImportError:
from functools import lru_cache
def cached_property(func): # type: ignore
return property(lru_cache(func))
SearchType = TypeVar('SearchType', str, int)
# str: string to search / list: values to search (OR) / dict: {'OR': [list], 'NOT': [list], 'AND': [list]}
# NOTE: we cannot use new typing here until we drop Python 3.8 and 3.9 support
SearchParameterTypes = TypeVar('SearchParameterTypes', str, List[Union[str, int]], Dict[str, Union[str, int]])
ToIDSType = TypeVar('ToIDSType', str, int, bool)
logger = logging.getLogger('pymisp')
def get_uuid_or_id_from_abstract_misp(obj: AbstractMISP | int | str | UUID | dict[str, Any]) -> str | int:
"""Extract the relevant ID accordingly to the given type passed as parameter"""
if isinstance(obj, UUID):
return str(obj)
if isinstance(obj, (int, str)):
return obj
if isinstance(obj, dict) and len(obj) == 1:
# We have an object in that format: {'Event': {'id': 2, ...}}
# We need to get the content of that dictionary
obj = obj[list(obj.keys())[0]]
if isinstance(obj, MISPShadowAttribute):
# A ShadowAttribute has the same UUID as the related Attribute, we *need* to use the ID
return obj['id']
if isinstance(obj, MISPEventDelegation):
# An EventDelegation doesn't have a uuid, we *need* to use the ID
return obj['id']
# For the blocklists, we want to return a specific key.
if isinstance(obj, MISPEventBlocklist):
return obj.event_uuid
if isinstance(obj, MISPOrganisationBlocklist):
return obj.org_uuid
# at this point, we must have an AbstractMISP
if 'uuid' in obj: # type: ignore
return obj['uuid'] # type: ignore
return obj['id'] # type: ignore
def register_user(misp_url: str, email: str,
organisation: MISPOrganisation | int | str | UUID | None = None,
org_id: str | None = None, org_name: str | None = None,
message: str | None = None, custom_perms: str | None = None,
perm_sync: bool = False, perm_publish: bool = False, perm_admin: bool = False,
verify: bool = True) -> dict[str, Any] | list[dict[str, Any]]:
"""Ask for the creation of an account for the user with the given email address"""
data = copy.deepcopy(locals())
if organisation:
data['org_uuid'] = get_uuid_or_id_from_abstract_misp(data.pop('organisation'))
url = urljoin(data.pop('misp_url'), 'users/register')
user_agent = f'PyMISP {__version__} - no login - Python {".".join(str(x) for x in sys.version_info[:2])}'
headers = {
'Accept': 'application/json',
'content-type': 'application/json',
'User-Agent': user_agent}
r = requests.post(url, json=data, verify=data.pop('verify'), headers=headers)
return r.json()
def brotli_supported() -> bool:
"""
Returns whether Brotli compression is supported
"""
major: int
minor: int
patch: int
# urllib >= 1.25.1 includes brotli support
version_splitted = version('urllib3').split('.') # noqa: F811
if len(version_splitted) == 2:
major, minor = version_splitted # type: ignore
patch = 0
else:
major, minor, patch = version_splitted # type: ignore
major, minor, patch = int(major), int(minor), int(patch)
urllib3_with_brotli = (major == 1 and ((minor == 25 and patch >= 1) or (minor >= 26))) or major >= 2
if not urllib3_with_brotli:
return False
# pybrotli is an extra package required by urllib3 for brotli support
try:
import brotli # type: ignore # noqa
return True
except ImportError:
return False
class PyMISP:
"""Python API for MISP
:param url: URL of the MISP instance you want to connect to
:param key: API key of the user you want to use
:param ssl: can be True or False (to check or to not check the validity of the certificate. Or a CA_BUNDLE in case of self signed or other certificate (the concatenation of all the crt of the chain)
:param debug: Write all the debug information to stderr
:param proxies: Proxy dict, as described here: http://docs.python-requests.org/en/master/user/advanced/#proxies
:param cert: Client certificate, as described here: http://docs.python-requests.org/en/master/user/advanced/#client-side-certificates
:param auth: The auth parameter is passed directly to requests, as described here: http://docs.python-requests.org/en/master/user/authentication/
:param tool: The software using PyMISP (string), used to set a unique user-agent
:param http_headers: Arbitrary headers to pass to all the requests.
:param https_adapter: Arbitrary HTTPS adapter for the requests session.
:param http_auth_header_name: The name of the HTTP header to use for the API key. Can be either "Authorization" or "X-MISP-AUTH".
:param timeout: Timeout, as described here: https://requests.readthedocs.io/en/master/user/advanced/#timeouts
"""
def __init__(self, url: str, key: str, ssl: bool | str = True, debug: bool = False, proxies: MutableMapping[str, str] | None = None,
cert: str | tuple[str, str] | None = None, auth: AuthBase | None = None, tool: str = '',
timeout: float | tuple[float, float] | None = None,
http_headers: dict[str, str] | None = None,
https_adapter: requests.adapters.BaseAdapter | None = None,
http_auth_header_name: str = 'Authorization'
):
if not url:
raise NoURL('Please provide the URL of your MISP instance.')
if not key:
raise NoKey('Please provide your authorization key.')
self.root_url: str = url
self.key: str = key.strip()
self.ssl: bool | str = ssl
self.proxies: MutableMapping[str, str] | None = proxies
self.cert: str | tuple[str, str] | None = cert
self.auth: AuthBase | None = auth
self.timeout: float | tuple[float, float] | None = timeout
self.__session = requests.Session() # use one session to keep connection between requests
if https_adapter is not None:
self.__session.mount('https://', https_adapter)
if brotli_supported():
self.__session.headers['Accept-Encoding'] = ', '.join(('br', 'gzip', 'deflate'))
if http_auth_header_name in ['Authorization', 'X-MISP-AUTH']:
self.__session.headers[http_auth_header_name] = self.key
else:
raise PyMISPError('http_auth_header_name should be either "Authorization" or "X-MISP-AUTH"')
user_agent = f'PyMISP {__version__} - Python {".".join(str(x) for x in sys.version_info[:2])}'
if tool:
user_agent = f'{user_agent} - {tool}'
self.__session.headers['User-Agent'] = user_agent
if http_headers:
self.__session.headers.update(http_headers)
self.global_pythonify = False
self.resources_path = Path(__file__).parent / 'data'
if debug:
logger.setLevel(logging.DEBUG)
logger.info('To configure logging in your script, leave it to None and use the following: import logging; logging.getLogger(\'pymisp\').setLevel(logging.DEBUG)')
try:
# Make sure the MISP instance is working and the URL is valid
response = self.recommended_pymisp_version
if 'errors' in response:
logger.warning(response['errors'][0])
else:
pymisp_version_tup = tuple(int(x) for x in __version__.split('.')[:3])
recommended_version_tup = tuple(int(x) for x in response['version'].split('.')[:3])
if recommended_version_tup < pymisp_version_tup[:3]:
logger.info(f"The version of PyMISP recommended by the MISP instance ({response['version']}) is older than the one you're using now ({__version__}). If you have a problem, please upgrade the MISP instance or use an older PyMISP version.")
elif pymisp_version_tup[:3] < recommended_version_tup:
logger.warning(f"The version of PyMISP recommended by the MISP instance ({response['version']}) is newer than the one you're using now ({__version__}). Please upgrade PyMISP.")
misp_version = self.misp_instance_version
if 'version' in misp_version:
self._misp_version = tuple(int(v) for v in misp_version['version'].split('.'))
# Get the user information
self._current_user: MISPUser
self._current_role: MISPRole
self._current_user_settings: list[MISPUserSetting]
user_infos = self.get_user(pythonify=True, expanded=True)
if isinstance(user_infos, dict):
# There was an error during the get_user call
if e := user_infos.get('errors'):
raise PyMISPError(f'Unable to get the user settings: {e}')
raise PyMISPError(f'Unexpected error when initializing the connection: {user_infos}')
elif isinstance(user_infos, tuple) and len(user_infos) == 3:
self._current_user, self._current_role, self._current_user_settings = user_infos
else:
raise PyMISPError(f'Unexpected error when initializing the connection: {user_infos}')
except PyMISPError as e:
raise e
except Exception as e:
raise PyMISPError(f'Unable to connect to MISP ({self.root_url}). Please make sure the API key and the URL are correct (http/https is required): {e}')
try:
self.describe_types = self.describe_types_remote
except Exception:
self.describe_types = self.describe_types_local
self.categories = self.describe_types['categories']
self.types = self.describe_types['types']
self.category_type_mapping = self.describe_types['category_type_mappings']
self.sane_default = self.describe_types['sane_defaults']
def remote_acl(self, debug_type: str = 'findMissingFunctionNames') -> dict[str, Any] | list[dict[str, Any]]:
"""This should return an empty list, unless the ACL is outdated.
:param debug_type: printAllFunctionNames, findMissingFunctionNames, or printRoleAccess
"""
response = self._prepare_request('GET', f'events/queryACL/{debug_type}')
return self._check_json_response(response)
@property
def describe_types_local(self) -> dict[str, Any] | list[dict[str, Any]]:
'''Returns the content of describe types from the package'''
return describe_types
@property
def describe_types_remote(self) -> dict[str, Any] | list[dict[str, Any]]:
'''Returns the content of describe types from the remote instance'''
response = self._prepare_request('GET', 'attributes/describeTypes.json')
remote_describe_types = self._check_json_response(response)
return remote_describe_types['result']
@property
def recommended_pymisp_version(self) -> dict[str, Any] | list[dict[str, Any]]:
"""Returns the recommended API version from the server"""
# Sine MISP 2.4.146 is recommended PyMISP version included in getVersion call
misp_version = self.misp_instance_version
if "pymisp_recommended_version" in misp_version:
return {"version": misp_version["pymisp_recommended_version"]} # Returns dict to keep BC
response = self._prepare_request('GET', 'servers/getPyMISPVersion.json')
return self._check_json_response(response)
@property
def version(self) -> dict[str, Any] | list[dict[str, Any]]:
"""Returns the version of PyMISP you're currently using"""
return {'version': __version__}
@property
def pymisp_version_master(self) -> dict[str, Any] | list[dict[str, Any]]:
"""PyMISP version as defined in the main repository"""
return self.pymisp_version_main
@property
def pymisp_version_main(self) -> dict[str, Any] | list[dict[str, Any]]:
"""Get the most recent version of PyMISP from github"""
r = requests.get('https://raw.githubusercontent.com/MISP/PyMISP/main/pyproject.toml')
if r.status_code == 200:
version = re.findall('version = "(.*)"', r.text)
return {'version': version[0]}
return {'error': 'Impossible to retrieve the version of the main branch.'}
@cached_property
def misp_instance_version(self) -> dict[str, Any] | list[dict[str, Any]]:
"""Returns the version of the instance."""
response = self._prepare_request('GET', 'servers/getVersion')
return self._check_json_response(response)
@property
def misp_instance_version_master(self) -> dict[str, Any] | list[dict[str, Any]]:
"""Get the most recent version from github"""
r = requests.get('https://raw.githubusercontent.com/MISP/MISP/2.5/VERSION.json')
if r.status_code == 200:
master_version = loads(r.content)
return {'version': '{}.{}.{}'.format(master_version['major'], master_version['minor'], master_version['hotfix'])}
return {'error': 'Impossible to retrieve the version of the master branch.'}
def update_misp(self) -> dict[str, Any] | list[dict[str, Any]]:
"""Trigger a server update"""
response = self._prepare_request('POST', 'servers/update')
return self._check_json_response(response)
def set_server_setting(self, setting: str, value: str | int | bool, force: bool = False) -> dict[str, Any] | list[dict[str, Any]]:
"""Set a setting on the MISP instance
:param setting: server setting name
:param value: value to set
:param force: override value test
"""
data = {'value': value, 'force': force}
response = self._prepare_request('POST', f'servers/serverSettingsEdit/{setting}', data=data)
return self._check_json_response(response)
def get_server_setting(self, setting: str) -> dict[str, Any] | list[dict[str, Any]]:
"""Get a setting from the MISP instance
:param setting: server setting name
"""
response = self._prepare_request('GET', f'servers/getSetting/{setting}')
return self._check_json_response(response)
def server_settings(self) -> dict[str, Any] | list[dict[str, Any]]:
"""Get all the settings from the server"""
response = self._prepare_request('GET', 'servers/serverSettings')
return self._check_json_response(response)
def restart_workers(self) -> dict[str, Any] | list[dict[str, Any]]:
"""Restart all the workers"""
response = self._prepare_request('POST', 'servers/restartWorkers')
return self._check_json_response(response)
def db_schema_diagnostic(self) -> dict[str, Any] | list[dict[str, Any]]:
"""Get the schema diagnostic"""
response = self._prepare_request('GET', 'servers/dbSchemaDiagnostic')
return self._check_json_response(response)
def toggle_global_pythonify(self) -> None:
"""Toggle the pythonify variable for the class"""
self.global_pythonify = not self.global_pythonify
# ## BEGIN Event ##
def events(self, pythonify: bool = False) -> dict[str, Any] | list[MISPEvent] | list[dict[str, Any]]:
"""Get all the events from the MISP instance: https://www.misp-project.org/openapi/#tag/Events/operation/getEvents
:param pythonify: Returns a list of PyMISP Objects instead of the plain json output. Warning: it might use a lot of RAM
"""
r = self._prepare_request('GET', 'events/index')
events_r = self._check_json_response(r)
if not (self.global_pythonify or pythonify) or isinstance(events_r, dict):
return events_r
to_return = []
for event in events_r:
e = MISPEvent()
e.from_dict(**event)
to_return.append(e)
return to_return
def get_event(self, event: MISPEvent | int | str | UUID,
deleted: bool | int | list[int] = False,
extended: bool | int = False,
pythonify: bool = False) -> dict[str, Any] | MISPEvent:
"""Get an event from a MISP instance. Includes collections like
Attribute, EventReport, Feed, Galaxy, Object, Tag, etc. so the
response size may be large : https://www.misp-project.org/openapi/#tag/Events/operation/getEventById
:param event: event to get
:param deleted: whether to include soft-deleted attributes
:param extended: whether to get extended events
:param pythonify: Returns a list of PyMISP Objects instead of the plain json output. Warning: it might use a lot of RAM
"""
event_id = get_uuid_or_id_from_abstract_misp(event)
data = {}
if deleted:
data['deleted'] = deleted
if extended:
data['extended'] = extended
if data:
r = self._prepare_request('POST', f'events/view/{event_id}', data=data)
else:
r = self._prepare_request('GET', f'events/view/{event_id}')
event_r = self._check_json_response(r)
if not (self.global_pythonify or pythonify) or 'errors' in event_r:
return event_r
e = MISPEvent()
e.load(event_r)
return e
def event_exists(self, event: MISPEvent | int | str | UUID) -> bool:
"""Fast check if event exists.
:param event: Event to check
"""
event_id = get_uuid_or_id_from_abstract_misp(event)
r = self._prepare_request('HEAD', f'events/view/{event_id}')
return self._check_head_response(r)
def add_event(self, event: MISPEvent, pythonify: bool = False, metadata: bool = False) -> dict[str, Any] | MISPEvent:
"""Add a new event on a MISP instance: https://www.misp-project.org/openapi/#tag/Events/operation/addEvent
:param event: event to add
:param pythonify: Returns a PyMISP Object instead of the plain json output
:param metadata: Return just event metadata after successful creating
"""
r = self._prepare_request('POST', 'events/add' + ('/metadata:1' if metadata else ''), data=event)
new_event = self._check_json_response(r)
if not (self.global_pythonify or pythonify) or 'errors' in new_event:
return new_event
e = MISPEvent()
e.load(new_event)
return e
def update_event(self, event: MISPEvent, event_id: int | None = None, pythonify: bool = False,
metadata: bool = False) -> dict[str, Any] | MISPEvent:
"""Update an event on a MISP instance: https://www.misp-project.org/openapi/#tag/Events/operation/editEvent
:param event: event to update
:param event_id: ID of event to update
:param pythonify: Returns a PyMISP Object instead of the plain json output
:param metadata: Return just event metadata after successful update
"""
if event_id is None:
eid = get_uuid_or_id_from_abstract_misp(event)
else:
eid = get_uuid_or_id_from_abstract_misp(event_id)
r = self._prepare_request('POST', f'events/edit/{eid}' + ('/metadata:1' if metadata else ''), data=event)
updated_event = self._check_json_response(r)
if not (self.global_pythonify or pythonify) or 'errors' in updated_event:
return updated_event
e = MISPEvent()
e.load(updated_event)
return e
def delete_event(self, event: MISPEvent | int | str | UUID) -> dict[str, Any] | list[dict[str, Any]]:
"""Delete an event from a MISP instance: https://www.misp-project.org/openapi/#tag/Events/operation/deleteEvent
:param event: event to delete
"""
event_id = get_uuid_or_id_from_abstract_misp(event)
response = self._prepare_request('POST', f'events/delete/{event_id}')
return self._check_json_response(response)
def publish(self, event: MISPEvent | int | str | UUID, alert: bool = False) -> dict[str, Any] | list[dict[str, Any]]:
"""Publish the event with one single HTTP POST: https://www.misp-project.org/openapi/#tag/Events/operation/publishEvent
:param event: event to publish
:param alert: whether to send an email. The default is to not send a mail as it is assumed this method is called on update.
"""
event_id = get_uuid_or_id_from_abstract_misp(event)
if alert:
response = self._prepare_request('POST', f'events/alert/{event_id}')
else:
response = self._prepare_request('POST', f'events/publish/{event_id}')
return self._check_json_response(response)
def unpublish(self, event: MISPEvent | int | str | UUID) -> dict[str, Any] | list[dict[str, Any]]:
"""Unpublish the event with one single HTTP POST: https://www.misp-project.org/openapi/#tag/Events/operation/unpublishEvent
:param event: event to unpublish
"""
event_id = get_uuid_or_id_from_abstract_misp(event)
response = self._prepare_request('POST', f'events/unpublish/{event_id}')
return self._check_json_response(response)
def contact_event_reporter(self, event: MISPEvent | int | str | UUID, message: str) -> dict[str, Any] | list[dict[str, Any]]:
"""Send a message to the reporter of an event
:param event: event with reporter to contact
:param message: message to send
"""
event_id = get_uuid_or_id_from_abstract_misp(event)
to_post = {'message': message}
response = self._prepare_request('POST', f'events/contact/{event_id}', data=to_post)
return self._check_json_response(response)
def enrich_event(self, event: MISPEvent | int | str | UUID, enrich_with: str | list[str]) -> dict[str, Any]:
"""Enrich an event with data from one or more module.
:param event: event to enrich
:param enrich_with: module name or list of module names to use for enrichment
"""
event_id = get_uuid_or_id_from_abstract_misp(event)
if isinstance(enrich_with, str):
enrich_with = [enrich_with]
to_post = {module_name: True for module_name in enrich_with}
response = self._prepare_request('POST', f'/events/enrichEvent/{event_id}', data=to_post)
return self._check_json_response(response)
# ## END Event ###
# ## BEGIN Event Report ###
def get_event_report(self, event_report: MISPEventReport | int | str | UUID,
pythonify: bool = False) -> dict[str, Any] | MISPEventReport:
"""Get an event report from a MISP instance
:param event_report: event report to get
:param pythonify: Returns a list of PyMISP Objects instead of the plain json output. Warning: it might use a lot of RAM
"""
event_report_id = get_uuid_or_id_from_abstract_misp(event_report)
r = self._prepare_request('GET', f'eventReports/view/{event_report_id}')
event_report_r = self._check_json_response(r)
if not (self.global_pythonify or pythonify) or 'errors' in event_report_r:
return event_report_r
er = MISPEventReport()
er.from_dict(**event_report_r)
return er
def get_event_reports(self, event_id: int | str,
pythonify: bool = False) -> dict[str, Any] | list[MISPEventReport] | list[dict[str, Any]]:
"""Get event report from a MISP instance that are attached to an event ID
:param event_id: event id to get the event reports for
:param pythonify: Returns a list of PyMISP Objects instead of the plain json output.
"""
r = self._prepare_request('GET', f'eventReports/index/event_id:{event_id}')
event_reports = self._check_json_response(r)
if not (self.global_pythonify or pythonify) or isinstance(event_reports, dict):
return event_reports
to_return = []
for event_report in event_reports:
er = MISPEventReport()
er.from_dict(**event_report)
to_return.append(er)
return to_return
def add_event_report(self, event: MISPEvent | int | str | UUID, event_report: MISPEventReport, pythonify: bool = False) -> dict[str, Any] | MISPEventReport:
"""Add an event report to an existing MISP event
:param event: event to extend
:param event_report: event report to add.
:param pythonify: Returns a PyMISP Object instead of the plain json output
"""
event_id = get_uuid_or_id_from_abstract_misp(event)
r = self._prepare_request('POST', f'eventReports/add/{event_id}', data=event_report)
new_event_report = self._check_json_response(r)
if not (self.global_pythonify or pythonify) or 'errors' in new_event_report:
return new_event_report
er = MISPEventReport()
er.from_dict(**new_event_report)
return er
def update_event_report(self, event_report: MISPEventReport, event_report_id: int | None = None, pythonify: bool = False) -> dict[str, Any] | MISPEventReport:
"""Update an event report on a MISP instance
:param event_report: event report to update
:param event_report_id: event report ID to update
:param pythonify: Returns a PyMISP Object instead of the plain json output
"""
if event_report_id is None:
erid = get_uuid_or_id_from_abstract_misp(event_report)
else:
erid = get_uuid_or_id_from_abstract_misp(event_report_id)
r = self._prepare_request('POST', f'eventReports/edit/{erid}', data=event_report)
updated_event_report = self._check_json_response(r)
if not (self.global_pythonify or pythonify) or 'errors' in updated_event_report:
return updated_event_report
er = MISPEventReport()
er.from_dict(**updated_event_report)
return er
def delete_event_report(self, event_report: MISPEventReport | int | str | UUID, hard: bool = False) -> dict[str, Any] | list[dict[str, Any]]:
"""Delete an event report from a MISP instance
:param event_report: event report to delete
:param hard: flag for hard delete
"""
event_report_id = get_uuid_or_id_from_abstract_misp(event_report)
request_url = f'eventReports/delete/{event_report_id}'
data = {}
if hard:
data['hard'] = 1
r = self._prepare_request('POST', request_url, data=data)
return self._check_json_response(r)
# ## END Event Report ###
# ## BEGIN Galaxy Cluster ###
def attach_galaxy_cluster(self, misp_entity: MISPEvent | MISPAttribute, galaxy_cluster: MISPGalaxyCluster | int | str, local: bool = False, pythonify: bool = False) -> dict[str, Any] | list[dict[str, Any]]:
"""Attach a galaxy cluster to an event or an attribute
:param misp_entity: a MISP Event or a MISP Attribute
:param galaxy_cluster: Galaxy cluster to attach
:param local: whether the object should be attached locally or not to the target
:param pythonify: Returns a PyMISP Object instead of the plain json output
"""
if isinstance(misp_entity, MISPEvent):
attach_target_type = 'event'
elif isinstance(misp_entity, MISPAttribute):
attach_target_type = 'attribute'
else:
raise PyMISPError('The misp_entity must be MISPEvent or MISPAttribute')
attach_target_id = misp_entity.id
local = 1 if local else 0
if isinstance(galaxy_cluster, MISPGalaxyCluster):
cluster_id = galaxy_cluster.id
elif isinstance(galaxy_cluster, (int, str)):
cluster_id = galaxy_cluster
else:
raise PyMISPError('The galaxy_cluster must be MISPGalaxyCluster or the id associated with the cluster (int or str)')
to_post = {'Galaxy': {'target_id': cluster_id}}
url = f'galaxies/attachCluster/{attach_target_id}/{attach_target_type}/local:{local}'
r = self._prepare_request('POST', url, data=to_post)
return self._check_json_response(r)
# ## END Galaxy Cluster ###
# ## BEGIN Analyst Data ###a
def get_analyst_data(self, analyst_data: MISPAnalystData | int | str | UUID,
pythonify: bool = False) -> dict[str, Any] | MISPNote | MISPOpinion | MISPRelationship:
"""Get an analyst data from a MISP instance
:param analyst_data: analyst data to get
:param pythonify: Returns a list of PyMISP Objects instead of the plain json output. Warning: it might use a lot of RAM
"""
if isinstance(analyst_data, MISPAnalystData):
analyst_data_type = analyst_data.analyst_data_object_type
else:
analyst_data_type = 'all'
analyst_data_id = get_uuid_or_id_from_abstract_misp(analyst_data)
r = self._prepare_request('GET', f'analyst_data/view/{analyst_data_type}/{analyst_data_id}')
analyst_data_r = self._check_json_response(r)
if not (self.global_pythonify or pythonify) or 'errors' in analyst_data_r or analyst_data_type == 'all':
return analyst_data_r
er = type(analyst_data)()
er.from_dict(**analyst_data_r)
return er
def add_analyst_data(self, analyst_data: MISPNote | MISPOpinion | MISPRelationship,
pythonify: bool = False) -> dict[str, Any] | MISPNote | MISPOpinion | MISPRelationship:
"""Add an analyst data to an existing MISP element
:param analyst_data: analyst_data to add
:param pythonify: Returns a PyMISP Object instead of the plain json output
"""
object_uuid = analyst_data.object_uuid
object_type = analyst_data.object_type
r = self._prepare_request('POST', f'analyst_data/add/{analyst_data.analyst_data_object_type}/{object_uuid}/{object_type}', data=analyst_data)
new_analyst_data = self._check_json_response(r)
if not (self.global_pythonify or pythonify) or 'errors' in new_analyst_data:
return new_analyst_data
er = type(analyst_data)()
er.from_dict(**new_analyst_data)
return er
def update_analyst_data(self, analyst_data: MISPNote | MISPOpinion | MISPRelationship, analyst_data_id: int | None = None,
pythonify: bool = False) -> dict[str, Any] | MISPNote | MISPOpinion | MISPRelationship:
"""Update an analyst data on a MISP instance
:param analyst_data: analyst data to update
:param analyst_data_id: analyst data ID to update
:param pythonify: Returns a PyMISP Object instead of the plain json output
"""
if isinstance(analyst_data, MISPAnalystData):
analyst_data_type = analyst_data.analyst_data_object_type
else:
analyst_data_type = 'all'
if analyst_data_id is None:
analyst_data_id = get_uuid_or_id_from_abstract_misp(analyst_data)
r = self._prepare_request('POST', f'analyst_data/edit/{analyst_data_type}/{analyst_data_id}', data=analyst_data)
updated_analyst_data = self._check_json_response(r)
if not (self.global_pythonify or pythonify) or 'errors' in updated_analyst_data or analyst_data_type == 'all':
return updated_analyst_data
er = type(analyst_data)()
er.from_dict(**updated_analyst_data)
return er
def delete_analyst_data(self, analyst_data: MISPNote | MISPOpinion | MISPRelationship | int | str | UUID) -> dict[str, Any] | list[dict[str, Any]]:
"""Delete an analyst data from a MISP instance
:param analyst_data: analyst data to delete
"""
if isinstance(analyst_data, MISPAnalystData):
analyst_data_type = analyst_data.analyst_data_object_type
else:
analyst_data_type = 'all'
analyst_data_id = get_uuid_or_id_from_abstract_misp(analyst_data)
request_url = f'analyst_data/delete/{analyst_data_type}/{analyst_data_id}'
r = self._prepare_request('POST', request_url)
return self._check_json_response(r)
# ## END Analyst Data ###
# ## BEGIN Analyst Note ###
def get_note(self, note: MISPNote, pythonify: bool = False) -> dict[str, Any] | MISPNote:
"""Get a note from a MISP instance
:param note: note to get
:param pythonify: Returns a list of PyMISP Objects instead of the plain json output. Warning: it might use a lot of RAM
"""
return self.get_analyst_data(note, pythonify)
def add_note(self, note: MISPNote, pythonify: bool = False) -> dict[str, Any] | MISPNote:
"""Add a note to an existing MISP element
:param note: note to add
:param pythonify: Returns a PyMISP Object instead of the plain json output
"""
return self.add_analyst_data(note, pythonify)
def update_note(self, note: MISPNote, note_id: int | None = None, pythonify: bool = False) -> dict[str, Any] | MISPNote:
"""Update a note on a MISP instance
:param note: note to update
:param note_id: note ID to update
:param pythonify: Returns a PyMISP Object instead of the plain json output
"""
return self.update_analyst_data(note, note_id, pythonify)
def delete_note(self, note: MISPNote | int | str | UUID) -> dict[str, Any] | list[dict[str, Any]]:
"""Delete a note from a MISP instance
:param note: note delete
"""
return self.delete_analyst_data(note)
# ## END Analyst Note ###
# ## BEGIN Analyst Opinion ###
def get_opinion(self, opinion: MISPOpinion, pythonify: bool = False) -> dict[str, Any] | MISPOpinion:
"""Get an opinion from a MISP instance
:param opinion: opinion to get
:param pythonify: Returns a list of PyMISP Objects instead of the plain json output. Warning: it might use a lot of RAM
"""
return self.get_analyst_data(opinion, pythonify)
def add_opinion(self, opinion: MISPOpinion, pythonify: bool = False) -> dict[str, Any] | MISPOpinion:
"""Add an opinion to an existing MISP element
:param opinion: opinion to add
:param pythonify: Returns a PyMISP Object instead of the plain json output
"""
return self.add_analyst_data(opinion, pythonify)
def update_opinion(self, opinion: MISPOpinion, opinion_id: int | None = None, pythonify: bool = False) -> dict[str, Any] | MISPOpinion:
"""Update an opinion on a MISP instance
:param opinion: opinion to update
:param opinion_id: opinion ID to update
:param pythonify: Returns a PyMISP Object instead of the plain json output
"""
return self.update_analyst_data(opinion, opinion_id, pythonify)
def delete_opinion(self, opinion: MISPOpinion | int | str | UUID) -> dict[str, Any] | list[dict[str, Any]]:
"""Delete an opinion from a MISP instance
:param opinion: opinion to delete
"""
return self.delete_analyst_data(opinion)
# ## END Analyst Opinion ###
# ## BEGIN Analyst Relationship ###
def get_relationship(self, relationship: MISPRelationship, pythonify: bool = False) -> dict[str, Any] | MISPRelationship:
"""Get a relationship from a MISP instance
:param relationship: relationship to get
:param pythonify: Returns a list of PyMISP Objects instead of the plain json output. Warning: it might use a lot of RAM
"""
return self.get_analyst_data(relationship, pythonify)
def add_relationship(self, relationship: MISPRelationship, pythonify: bool = False) -> dict[str, Any] | MISPRelationship:
"""Add a relationship to an existing MISP element
:param relationship: relationship to add
:param pythonify: Returns a PyMISP Object instead of the plain json output
"""
return self.add_analyst_data(relationship, pythonify)
def update_relationship(self, relationship: MISPRelationship, relationship_id: int | None = None, pythonify: bool = False) -> dict[str, Any] | MISPRelationship:
"""Update a relationship on a MISP instance
:param relationship: relationship to update
:param relationship_id: relationship ID to update
:param pythonify: Returns a PyMISP Object instead of the plain json output
"""
return self.update_analyst_data(relationship, relationship_id, pythonify)
def delete_relationship(self, relationship: MISPRelationship | int | str | UUID) -> dict[str, Any] | list[dict[str, Any]]:
"""Delete a relationship from a MISP instance
:param relationship: relationship to delete
"""
return self.delete_analyst_data(relationship)
# ## END Analyst Relationship ###
# ## BEGIN Object ###
def get_object(self, misp_object: MISPObject | int | str | UUID, pythonify: bool = False) -> dict[str, Any] | MISPObject:
"""Get an object from the remote MISP instance: https://www.misp-project.org/openapi/#tag/Objects/operation/getObjectById
:param misp_object: object to get
:param pythonify: Returns a PyMISP Object instead of the plain json output
"""
object_id = get_uuid_or_id_from_abstract_misp(misp_object)
r = self._prepare_request('GET', f'objects/view/{object_id}')
misp_object_r = self._check_json_response(r)
if not (self.global_pythonify or pythonify) or 'errors' in misp_object_r:
return misp_object_r
o = MISPObject(misp_object_r['Object']['name'], standalone=False)
o.from_dict(**misp_object_r)
return o
def object_exists(self, misp_object: MISPObject | int | str | UUID) -> bool:
"""Fast check if object exists.
:param misp_object: Attribute to check
"""
object_id = get_uuid_or_id_from_abstract_misp(misp_object)
r = self._prepare_request('HEAD', f'objects/view/{object_id}')
return self._check_head_response(r)
def add_object(self, event: MISPEvent | int | str | UUID, misp_object: MISPObject, pythonify: bool = False, break_on_duplicate: bool = False) -> dict[str, Any] | MISPObject:
"""Add a MISP Object to an existing MISP event: https://www.misp-project.org/openapi/#tag/Objects/operation/addObject
:param event: event to extend
:param misp_object: object to add
:param pythonify: Returns a PyMISP Object instead of the plain json output
:param break_on_duplicate: if True, check and reject if this object's attributes match an existing object's attributes; may require much time
"""
event_id = get_uuid_or_id_from_abstract_misp(event)
params = {'breakOnDuplicate': 1} if break_on_duplicate else {}
r = self._prepare_request('POST', f'objects/add/{event_id}', data=misp_object, kw_params=params)
new_object = self._check_json_response(r)
if not (self.global_pythonify or pythonify) or 'errors' in new_object:
return new_object
o = MISPObject(new_object['Object']['name'], standalone=False)
o.from_dict(**new_object)
return o
def update_object(self, misp_object: MISPObject, object_id: int | None = None, pythonify: bool = False) -> dict[str, Any] | MISPObject:
"""Update an object on a MISP instance
:param misp_object: object to update
:param object_id: ID of object to update
:param pythonify: Returns a PyMISP Object instead of the plain json output
"""
if object_id is None:
oid = get_uuid_or_id_from_abstract_misp(misp_object)
else:
oid = get_uuid_or_id_from_abstract_misp(object_id)
r = self._prepare_request('POST', f'objects/edit/{oid}', data=misp_object)
updated_object = self._check_json_response(r)
if not (self.global_pythonify or pythonify) or 'errors' in updated_object:
return updated_object
o = MISPObject(updated_object['Object']['name'], standalone=False)
o.from_dict(**updated_object)
return o
def delete_object(self, misp_object: MISPObject | int | str | UUID, hard: bool = False) -> dict[str, Any] | list[dict[str, Any]]:
"""Delete an object from a MISP instance: https://www.misp-project.org/openapi/#tag/Objects/operation/deleteObject
:param misp_object: object to delete
:param hard: flag for hard delete
"""
object_id = get_uuid_or_id_from_abstract_misp(misp_object)
data = {}
if hard:
data['hard'] = 1
r = self._prepare_request('POST', f'objects/delete/{object_id}', data=data)
return self._check_json_response(r)
def add_object_reference(self, misp_object_reference: MISPObjectReference, pythonify: bool = False) -> dict[str, Any] | MISPObjectReference:
"""Add a reference to an object
:param misp_object_reference: object reference
:param pythonify: Returns a PyMISP Object instead of the plain json output
"""
r = self._prepare_request('POST', 'objectReferences/add', misp_object_reference)
object_reference = self._check_json_response(r)
if not (self.global_pythonify or pythonify) or 'errors' in object_reference:
return object_reference
ref = MISPObjectReference()
ref.from_dict(**object_reference)
return ref
def delete_object_reference(
self,
object_reference: MISPObjectReference | int | str | UUID,
hard: bool = False,
) -> dict[str, Any] | list[dict[str, Any]]:
"""Delete a reference to an object."""
object_reference_id = get_uuid_or_id_from_abstract_misp(object_reference)
query_url = f"objectReferences/delete/{object_reference_id}"
if hard:
query_url += "/true"
response = self._prepare_request("POST", query_url)
return self._check_json_response(response)
# Object templates
def object_templates(self, pythonify: bool = False) -> dict[str, Any] | list[MISPObjectTemplate] | list[dict[str, Any]]:
"""Get all the object templates
:param pythonify: Returns a list of PyMISP Objects instead of the plain json output. Warning: it might use a lot of RAM
"""
r = self._prepare_request('GET', 'objectTemplates/index')
templates = self._check_json_response(r)
if not (self.global_pythonify or pythonify) or isinstance(templates, dict):
return templates
to_return = []
for object_template in templates:
o = MISPObjectTemplate()
o.from_dict(**object_template)
to_return.append(o)
return to_return
def get_object_template(self, object_template: MISPObjectTemplate | int | str | UUID, pythonify: bool = False) -> dict[str, Any] | MISPObjectTemplate:
"""Gets the full object template
:param object_template: template or ID to get
:param pythonify: Returns a PyMISP Object instead of the plain json output
"""
object_template_id = get_uuid_or_id_from_abstract_misp(object_template)
r = self._prepare_request('GET', f'objectTemplates/view/{object_template_id}')
object_template_r = self._check_json_response(r)
if not (self.global_pythonify or pythonify) or 'errors' in object_template_r:
return object_template_r
t = MISPObjectTemplate()
t.from_dict(**object_template_r)
return t
def get_raw_object_template(self, uuid_or_name: str) -> dict[str, Any] | list[dict[str, Any]]:
"""Get a row template. It needs to be present on disk on the MISP instance you're connected to.
The response of this method can be passed to MISPObject(<name>, misp_objects_template_custom=<response>)
"""
r = self._prepare_request('GET', f'objectTemplates/getRaw/{uuid_or_name}')
return self._check_json_response(r)
def update_object_templates(self) -> dict[str, Any] | list[dict[str, Any]]:
"""Trigger an update of the object templates"""
response = self._prepare_request('POST', 'objectTemplates/update')
return self._check_json_response(response)
# ## END Object ###
# ## BEGIN Attribute ###
def attributes(self, pythonify: bool = False) -> dict[str, Any] | list[MISPAttribute] | list[dict[str, Any]]:
"""Get all the attributes from the MISP instance: https://www.misp-project.org/openapi/#tag/Attributes/operation/getAttributes
:param pythonify: Returns a list of PyMISP Objects instead of the plain json output. Warning: it might use a lot of RAM
"""
r = self._prepare_request('GET', 'attributes/index')
attributes_r = self._check_json_response(r)
if not (self.global_pythonify or pythonify) or isinstance(attributes_r, dict):
return attributes_r
to_return = []
for attribute in attributes_r:
a = MISPAttribute()
a.from_dict(**attribute)
to_return.append(a)
return to_return
def get_attribute(self, attribute: MISPAttribute | int | str | UUID, pythonify: bool = False) -> dict[str, Any] | MISPAttribute:
"""Get an attribute from a MISP instance: https://www.misp-project.org/openapi/#tag/Attributes/operation/getAttributeById
:param attribute: attribute to get
:param pythonify: Returns a PyMISP Object instead of the plain json output
"""
attribute_id = get_uuid_or_id_from_abstract_misp(attribute)
r = self._prepare_request('GET', f'attributes/view/{attribute_id}')
attribute_r = self._check_json_response(r)
if not (self.global_pythonify or pythonify) or 'errors' in attribute_r:
return attribute_r
a = MISPAttribute()