-
Notifications
You must be signed in to change notification settings - Fork 277
/
api.py
3716 lines (3191 loc) · 182 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from typing import TypeVar, Optional, Tuple, List, Dict, Union, Any, Mapping, Iterable, MutableMapping
from datetime import date, datetime
import csv
from pathlib import Path
import logging
from urllib.parse import urljoin
import json
import requests
from requests.auth import AuthBase
import re
from uuid import UUID
import warnings
import sys
import copy
import urllib3 # type: ignore
from io import BytesIO, StringIO
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
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 # type: ignore
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]}
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: Union[AbstractMISP, int, str, UUID, dict]) -> Union[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.keys()) == 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: Optional[Union[MISPOrganisation, int, str, UUID]] = None,
org_id: Optional[str] = None, org_name: Optional[str] = None,
message: Optional[str] = None, custom_perms: Optional[str] = None,
perm_sync: bool = False, perm_publish: bool = False, perm_admin: bool = False,
verify: bool = True) -> Dict:
"""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 = urllib3.__version__.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) # type: ignore
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 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: Optional[MutableMapping[str, str]] = None,
cert: Optional[Union[str, Tuple[str, str]]] = None, auth: Optional[AuthBase] = None, tool: str = '',
timeout: Optional[Union[float, Tuple[float, float]]] = None,
http_headers: Optional[Dict[str, str]]=None
):
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
self.ssl: bool = ssl
self.proxies: Optional[MutableMapping[str, str]] = proxies
self.cert: Optional[Union[str, Tuple[str, str]]] = cert
self.auth: Optional[AuthBase] = auth
self.tool: str = tool
self.timeout: Optional[Union[float, Tuple[float, float]]] = timeout
self.__session = requests.Session() # use one session to keep connection between requests
if brotli_supported():
self.__session.headers['Accept-Encoding'] = ', '.join(('br', 'gzip', 'deflate'))
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('.'))
recommended_version_tup = tuple(int(x) for x in response['version'].split('.'))
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]
self._current_user, self._current_role, self._current_user_settings = self.get_user(pythonify=True, expanded=True)
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:
"""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:
'''Returns the content of describe types from the package'''
return describe_types
@property
def describe_types_remote(self) -> Dict:
'''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:
"""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:
"""Returns the version of PyMISP you're currently using"""
return {'version': __version__}
@property
def pymisp_version_master(self) -> Dict:
"""PyMISP version as defined in the main repository"""
return self.pymisp_version_main
@property
def pymisp_version_main(self) -> Dict:
"""Get the most recent version of PyMISP from github"""
r = requests.get('https://raw.githubusercontent.com/MISP/PyMISP/main/pymisp/__init__.py')
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:
"""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:
"""Get the most recent version from github"""
r = requests.get('https://raw.githubusercontent.com/MISP/MISP/2.4/VERSION.json')
if r.status_code == 200:
master_version = json.loads(r.text)
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:
"""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: Union[str, int, bool], force: bool = False) -> Dict:
"""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:
"""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:
"""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:
"""Restart all the workers"""
response = self._prepare_request('POST', 'servers/restartWorkers')
return self._check_json_response(response)
def db_schema_diagnostic(self) -> Dict:
"""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) -> Union[Dict, List[MISPEvent]]:
"""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 'errors' in events_r:
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: Union[MISPEvent, int, str, UUID],
deleted: Union[bool, int, list] = False,
extended: Union[bool, int] = False,
pythonify: bool = False) -> Union[Dict, 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: Union[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) -> Union[Dict, 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: Optional[int] = None, pythonify: bool = False,
metadata: bool = False) -> Union[Dict, 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: Union[MISPEvent, int, str, UUID]) -> Dict:
"""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: Union[MISPEvent, int, str, UUID], alert: bool = False) -> Dict:
"""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: Union[MISPEvent, int, str, UUID]) -> Dict:
"""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/publish/{event_id}')
return self._check_json_response(response)
def contact_event_reporter(self, event: Union[MISPEvent, int, str, UUID], message: str) -> Dict:
"""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)
# ## END Event ###
# ## BEGIN Event Report ###
def get_event_report(self, event_report: Union[MISPEventReport, int, str, UUID],
pythonify: bool = False) -> Union[Dict, 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: Union[int, str],
pythonify: bool = False) -> Union[Dict, List[MISPEventReport]]:
"""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 'errors' in event_reports:
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: Union[MISPEvent, int, str, UUID], event_report: MISPEventReport, pythonify: bool = False) -> Union[Dict, 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: Optional[int] = None, pythonify: bool = False) -> Union[Dict, 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: Union[MISPEventReport, int, str, UUID], hard: bool = False) -> Dict:
"""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 Object ###
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: 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: Union[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: Union[MISPEvent, int, str, UUID], misp_object: MISPObject, pythonify: bool = False, break_on_duplicate: bool = False) -> Union[Dict, 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': True} 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: Optional[int] = None, pythonify: bool = False) -> Union[Dict, 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: Union[MISPObject, int, str, UUID], hard: bool = False) -> Dict:
"""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) -> Union[Dict, 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: Union[MISPObjectReference, int, str, UUID]) -> Dict:
"""Delete a reference to an object
:param object_reference: object reference
"""
object_reference_id = get_uuid_or_id_from_abstract_misp(object_reference)
response = self._prepare_request('POST', f'objectReferences/delete/{object_reference_id}')
return self._check_json_response(response)
# Object templates
def object_templates(self, pythonify: bool = False) -> Union[Dict, List[MISPObjectTemplate]]:
"""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 'errors' in templates:
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: Union[MISPObjectTemplate, int, str, UUID], pythonify: bool = False) -> Union[Dict, 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:
"""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:
"""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) -> Union[Dict, List[MISPAttribute]]:
"""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 'errors' in attributes_r:
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: Union[MISPAttribute, int, str, UUID], pythonify: bool = False) -> Union[Dict, 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()
a.from_dict(**attribute_r)
return a
def attribute_exists(self, attribute: Union[MISPAttribute, int, str, UUID]) -> bool:
"""Fast check if attribute exists.
:param attribute: Attribute to check
"""
attribute_id = get_uuid_or_id_from_abstract_misp(attribute)
r = self._prepare_request('HEAD', f'attributes/view/{attribute_id}')
return self._check_head_response(r)
def add_attribute(self, event: Union[MISPEvent, int, str, UUID], attribute: Union[MISPAttribute, Iterable], pythonify: bool = False) -> Union[Dict, MISPAttribute, MISPShadowAttribute]:
"""Add an attribute to an existing MISP event: https://www.misp-project.org/openapi/#tag/Attributes/operation/addAttribute
:param event: event to extend
:param attribute: attribute or (MISP version 2.4.113+) list of attributes to add.
If a list is passed, the pythonified response is a dict with the following structure:
{'attributes': [MISPAttribute], 'errors': {errors by attributes}}
: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'attributes/add/{event_id}', data=attribute)
new_attribute = self._check_json_response(r)
if isinstance(attribute, list):
# Multiple attributes were passed at once, the handling is totally different
if not (self.global_pythonify or pythonify):
return new_attribute
to_return: Dict[str, List[MISPAttribute]] = {'attributes': []}
if 'errors' in new_attribute:
to_return['errors'] = new_attribute['errors']
if len(attribute) == 1:
# input list size 1 yields dict, not list of size 1
if 'Attribute' in new_attribute:
a = MISPAttribute()
a.from_dict(**new_attribute['Attribute'])
to_return['attributes'].append(a)
else:
for new_attr in new_attribute['Attribute']:
a = MISPAttribute()
a.from_dict(**new_attr)
to_return['attributes'].append(a)
return to_return
if ('errors' in new_attribute and new_attribute['errors'][0] == 403
and new_attribute['errors'][1]['message'] == 'You do not have permission to do that.'):
# At this point, we assume the user tried to add an attribute on an event they don't own
# Re-try with a proposal
if isinstance(attribute, (MISPAttribute, dict)):
return self.add_attribute_proposal(event_id, attribute, pythonify) # type: ignore
if not (self.global_pythonify or pythonify) or 'errors' in new_attribute:
return new_attribute
a = MISPAttribute()
a.from_dict(**new_attribute)
return a
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: https://www.misp-project.org/openapi/#tag/Attributes/operation/editAttribute
:param attribute: attribute to update
:param attribute_id: attribute ID to update
:param pythonify: Returns a PyMISP Object instead of the plain json output
"""
if attribute_id is None:
aid = get_uuid_or_id_from_abstract_misp(attribute)
else:
aid = get_uuid_or_id_from_abstract_misp(attribute_id)
r = self._prepare_request('POST', f'attributes/edit/{aid}', data=attribute)
updated_attribute = self._check_json_response(r)
if 'errors' in updated_attribute:
if (updated_attribute['errors'][0] == 403
and updated_attribute['errors'][1]['message'] == 'You do not have permission to do that.'):
# At this point, we assume the user tried to update an attribute on an event they don't own
# Re-try with a proposal
return self.update_attribute_proposal(aid, attribute, pythonify)
if not (self.global_pythonify or pythonify) or 'errors' in updated_attribute:
return updated_attribute
a = MISPAttribute()
a.from_dict(**updated_attribute)
return a
def delete_attribute(self, attribute: Union[MISPAttribute, int, str, UUID], hard: bool = False) -> Dict:
"""Delete an attribute from a MISP instance: https://www.misp-project.org/openapi/#tag/Attributes/operation/deleteAttribute
:param attribute: attribute to delete
:param hard: flag for hard delete
"""
attribute_id = get_uuid_or_id_from_abstract_misp(attribute)
data = {}
if hard:
data['hard'] = 1
r = self._prepare_request('POST', f'attributes/delete/{attribute_id}', data=data)
response = self._check_json_response(r)
if ('errors' in response and response['errors'][0] == 403
and response['errors'][1]['message'] == 'You do not have permission to do that.'):
# FIXME: https://github.com/MISP/MISP/issues/4913
# At this point, we assume the user tried to delete an attribute on an event they don't own
# Re-try with a proposal
return self.delete_attribute_proposal(attribute_id)
return response
def restore_attribute(self, attribute: Union[MISPAttribute, int, str, UUID], pythonify: bool = False) -> Union[Dict, MISPAttribute]:
"""Restore a soft deleted attribute from a MISP instance: https://www.misp-project.org/openapi/#tag/Attributes/operation/restoreAttribute
:param attribute: attribute to restore
"""
attribute_id = get_uuid_or_id_from_abstract_misp(attribute)
r = self._prepare_request('POST', f'attributes/restore/{attribute_id}')
response = self._check_json_response(r)
if not (self.global_pythonify or pythonify) or 'errors' in response:
return response
a = MISPAttribute()
a.from_dict(**response)
return a
# ## END Attribute ###
# ## BEGIN Attribute Proposal ###
def attribute_proposals(self, event: Optional[Union[MISPEvent, int, str, UUID]] = None, pythonify: bool = False) -> Union[Dict, List[MISPShadowAttribute]]:
"""Get all the attribute proposals
:param event: event
:param pythonify: Returns a list of PyMISP Objects instead of the plain json output. Warning: it might use a lot of RAM
"""
if event:
event_id = get_uuid_or_id_from_abstract_misp(event)
r = self._prepare_request('GET', f'shadowAttributes/index/{event_id}')
else:
r = self._prepare_request('GET', 'shadowAttributes/index')
attribute_proposals = self._check_json_response(r)
if not (self.global_pythonify or pythonify) or 'errors' in attribute_proposals:
return attribute_proposals
to_return = []
for attribute_proposal in attribute_proposals:
a = MISPShadowAttribute()
a.from_dict(**attribute_proposal)
to_return.append(a)
return to_return
def get_attribute_proposal(self, proposal: Union[MISPShadowAttribute, int, str, UUID], pythonify: bool = False) -> Union[Dict, MISPShadowAttribute]:
"""Get an attribute proposal
:param proposal: proposal to get
:param pythonify: Returns a PyMISP Object instead of the plain json output
"""
proposal_id = get_uuid_or_id_from_abstract_misp(proposal)
r = self._prepare_request('GET', f'shadowAttributes/view/{proposal_id}')
attribute_proposal = self._check_json_response(r)
if not (self.global_pythonify or pythonify) or 'errors' in attribute_proposal:
return attribute_proposal
a = MISPShadowAttribute()
a.from_dict(**attribute_proposal)
return a
# 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]:
"""Propose a new attribute in an event
:param event: event to receive new attribute
:param attribute: attribute to propose
: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'shadowAttributes/add/{event_id}', data=attribute)
new_attribute_proposal = self._check_json_response(r)
if not (self.global_pythonify or pythonify) or 'errors' in new_attribute_proposal:
return new_attribute_proposal
a = MISPShadowAttribute()
a.from_dict(**new_attribute_proposal)
return a
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
:param initial_attribute: attribute to change
:param attribute: attribute to propose
:param pythonify: Returns a PyMISP Object instead of the plain json output
"""
initial_attribute_id = get_uuid_or_id_from_abstract_misp(initial_attribute)
r = self._prepare_request('POST', f'shadowAttributes/edit/{initial_attribute_id}', data=attribute)
update_attribute_proposal = self._check_json_response(r)
if not (self.global_pythonify or pythonify) or 'errors' in update_attribute_proposal:
return update_attribute_proposal
a = MISPShadowAttribute()
a.from_dict(**update_attribute_proposal)
return a
def delete_attribute_proposal(self, attribute: Union[MISPAttribute, int, str, UUID]) -> Dict:
"""Propose the deletion of an attribute
:param attribute: attribute to delete
"""
attribute_id = get_uuid_or_id_from_abstract_misp(attribute)
response = self._prepare_request('POST', f'shadowAttributes/delete/{attribute_id}')
return self._check_json_response(response)
def accept_attribute_proposal(self, proposal: Union[MISPShadowAttribute, int, str, UUID]) -> Dict:
"""Accept a proposal. You cannot modify an existing proposal, only accept/discard
:param proposal: attribute proposal to accept
"""
proposal_id = get_uuid_or_id_from_abstract_misp(proposal)
response = self._prepare_request('POST', f'shadowAttributes/accept/{proposal_id}')
return self._check_json_response(response)
def discard_attribute_proposal(self, proposal: Union[MISPShadowAttribute, int, str, UUID]) -> Dict:
"""Discard a proposal. You cannot modify an existing proposal, only accept/discard
:param proposal: attribute proposal to discard
"""
proposal_id = get_uuid_or_id_from_abstract_misp(proposal)
response = self._prepare_request('POST', f'shadowAttributes/discard/{proposal_id}')
return self._check_json_response(response)
# ## END Attribute Proposal ###
# ## BEGIN Sighting ###
def sightings(self, misp_entity: Optional[AbstractMISP] = None,
org: Optional[Union[MISPOrganisation, int, str, UUID]] = None,
pythonify: bool = False) -> Union[Dict, List[MISPSighting]]:
"""Get the list of sightings related to a MISPEvent or a MISPAttribute (depending on type of misp_entity): https://www.misp-project.org/openapi/#tag/Sightings/operation/getSightingsByEventId
:param misp_entity: MISP entity
:param org: MISP organization
:param pythonify: Returns a list of PyMISP Objects instead of the plain json output. Warning: it might use a lot of RAM
"""
if isinstance(misp_entity, MISPEvent):
url = 'sightings/listSightings'
to_post = {'context': 'event', 'id': misp_entity.id}
elif isinstance(misp_entity, MISPAttribute):
url = 'sightings/listSightings'
to_post = {'context': 'attribute', 'id': misp_entity.id}
else:
url = 'sightings/index'
to_post = {}
if org is not None:
org_id = get_uuid_or_id_from_abstract_misp(org)
to_post['org_id'] = org_id
r = self._prepare_request('POST', url, data=to_post)
sightings = self._check_json_response(r)
if not (self.global_pythonify or pythonify) or 'errors' in sightings:
return sightings
to_return = []
for sighting in sightings:
s = MISPSighting()
s.from_dict(**sighting)
to_return.append(s)
return to_return
def add_sighting(self, sighting: MISPSighting,
attribute: Optional[Union[MISPAttribute, int, str, UUID]] = None,
pythonify: bool = False) -> Union[Dict, MISPSighting]:
"""Add a new sighting (globally, or to a specific attribute): https://www.misp-project.org/openapi/#tag/Sightings/operation/addSighting and https://www.misp-project.org/openapi/#tag/Sightings/operation/getSightingsByEventId
:param sighting: sighting to add
:param attribute: specific attribute to modify with the sighting
:param pythonify: Returns a PyMISP Object instead of the plain json output
"""
if attribute:
attribute_id = get_uuid_or_id_from_abstract_misp(attribute)
r = self._prepare_request('POST', f'sightings/add/{attribute_id}', data=sighting)
else:
# Either the ID/UUID is in the sighting, or we want to add a sighting on all the attributes with the given value