-
Notifications
You must be signed in to change notification settings - Fork 277
/
aping.py
2231 lines (1963 loc) · 110 KB
/
aping.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
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
from . import __version__
from .exceptions import MISPServerError, PyMISPUnexpectedResponse, PyMISPNotImplementedYet, PyMISPError, NoURL, NoKey
from .api import everything_broken, PyMISP
from .mispevent import MISPEvent, MISPAttribute, MISPSighting, MISPLog, MISPObject, \
MISPUser, MISPOrganisation, MISPShadowAttribute, MISPWarninglist, MISPTaxonomy, \
MISPGalaxy, MISPNoticelist, MISPObjectReference, MISPObjectTemplate, MISPSharingGroup, \
MISPRole, MISPServer, MISPFeed, MISPEventDelegation, MISPCommunity, MISPUserSetting
from .abstract import pymisp_json_default, MISPTag, AbstractMISP, describe_types
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[SearchType], Dict[str, SearchType])
DateTypes = TypeVar('DateTypes', datetime, date, SearchType, float)
DateInterval = TypeVar('DateInterval', DateTypes, Tuple[DateTypes, DateTypes])
ToIDSType = TypeVar('ToIDSType', str, int, bool)
logger = logging.getLogger('pymisp')
class ExpandedPyMISP(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 ot not the validity of the certificate. Or a CA_BUNDLE in case of self signed certificate (the concatenation of all the *.crt of the chain)
:param debug: Write all the debug information to stderr
:param proxies: Proxy dict as describes here: http://docs.python-requests.org/en/master/user/advanced/#proxies
:param cert: Client certificate, as described there: 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
"""
def __init__(self, url: str, key: str, ssl=True, debug: bool=False, proxies: dict={},
cert: Tuple[str, tuple]=None, auth: AuthBase=None, tool: str=''):
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 = url
self.key = key
self.ssl = ssl
self.proxies = proxies
self.cert = cert
self.auth = auth
self.tool = tool
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 response.get('errors'):
logger.warning(response.get('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, 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'):
"""This should return an empty list, unless the ACL is outdated.
debug_type can only be printAllFunctionNames, findMissingFunctionNames, or printRoleAccess
"""
response = self._prepare_request('GET', f'events/queryACL/{debug_type}')
return self._check_response(response, expect_json=True)
@property
def describe_types_local(self):
'''Returns the content of describe types from the package'''
return describe_types
@property
def describe_types_remote(self):
'''Returns the content of describe types from the remote instance'''
response = self._prepare_request('GET', 'attributes/describeTypes.json')
remote_describe_types = self._check_response(response, expect_json=True)
return remote_describe_types['result']
@property
def recommended_pymisp_version(self):
"""Returns the recommended API version from the server"""
response = self._prepare_request('GET', 'servers/getPyMISPVersion.json')
return self._check_response(response, expect_json=True)
@property
def version(self):
"""Returns the version of PyMISP you're curently using"""
return {'version': __version__}
@property
def pymisp_version_master(self):
"""Get the most recent version of PyMISP from github"""
r = requests.get('https://raw.githubusercontent.com/MISP/PyMISP/master/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 master branch.'}
@property
def misp_instance_version(self):
"""Returns the version of the instance."""
response = self._prepare_request('GET', 'servers/getVersion.json')
return self._check_response(response, expect_json=True)
@property
def misp_instance_version_master(self):
"""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):
response = self._prepare_request('POST', '/servers/update')
if self._old_misp((2, 4, 116), '2020-01-01', sys._getframe().f_code.co_name):
return self._check_response(response, lenient_response_type=True)
return self._check_response(response, expect_json=True)
def set_server_setting(self, setting: str, value: Union[str, int, bool], force: bool=False):
data = {'value': value, 'force': force}
response = self._prepare_request('POST', f'/servers/serverSettingsEdit/{setting}', data=data)
return self._check_response(response, expect_json=True)
def get_server_setting(self, setting: str):
response = self._prepare_request('GET', f'/servers/getSetting/{setting}')
return self._check_response(response, expect_json=True)
def server_settings(self):
response = self._prepare_request('GET', f'/servers/serverSettings')
return self._check_response(response, expect_json=True)
def restart_workers(self):
response = self._prepare_request('POST', f'/servers/restartWorkers')
return self._check_response(response, expect_json=True)
def toggle_global_pythonify(self):
self.global_pythonify = not self.global_pythonify
# ## BEGIN Event ##
def events(self, pythonify: bool=False):
events = self._prepare_request('GET', 'events')
events = self._check_response(events, expect_json=True)
if not (self.global_pythonify or pythonify) or 'errors' in events:
return events
to_return = []
for event in events:
e = MISPEvent()
e.from_dict(**event)
to_return.append(e)
return to_return
def get_event(self, event: Union[MISPEvent, int, str, UUID], deleted: [bool, int, list]=False, pythonify: bool=False):
'''Get an event from a MISP instance'''
event_id = self.__get_uuid_or_id_from_abstract_misp(event)
if deleted:
data = {'deleted': deleted}
event = self._prepare_request('POST', f'events/view/{event_id}', data=data)
else:
event = self._prepare_request('GET', f'events/view/{event_id}')
event = self._check_response(event, expect_json=True)
if not (self.global_pythonify or pythonify) or 'errors' in event:
return event
e = MISPEvent()
e.load(event)
return e
def add_event(self, event: MISPEvent, pythonify: bool=False):
'''Add a new event on a MISP instance'''
new_event = self._prepare_request('POST', 'events', data=event)
new_event = self._check_response(new_event, expect_json=True)
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, pythonify: bool=False):
'''Update an event on a MISP instance'''
if event_id is None:
event_id = self.__get_uuid_or_id_from_abstract_misp(event)
else:
event_id = self.__get_uuid_or_id_from_abstract_misp(event_id)
updated_event = self._prepare_request('POST', f'events/{event_id}', data=event)
updated_event = self._check_response(updated_event, expect_json=True)
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]):
'''Delete an event from a MISP instance'''
event_id = self.__get_uuid_or_id_from_abstract_misp(event)
response = self._prepare_request('DELETE', f'events/delete/{event_id}')
return self._check_response(response, expect_json=True)
def publish(self, event: Union[MISPEvent, int, str, UUID], alert: bool=False):
"""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.
"""
event_id = self.__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_response(response, expect_json=True)
def contact_event_reporter(self, event: Union[MISPEvent, int, str, UUID], message: str):
"""Send a message to the reporter of an event"""
event_id = self.__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_response(response, expect_json=True)
# ## END Event ###
# ## BEGIN Object ###
def get_object(self, misp_object: Union[MISPObject, int, str, UUID], pythonify: bool=False):
'''Get an object from the remote MISP instance'''
object_id = self.__get_uuid_or_id_from_abstract_misp(misp_object)
misp_object = self._prepare_request('GET', f'objects/view/{object_id}')
misp_object = self._check_response(misp_object, expect_json=True)
if not (self.global_pythonify or pythonify) or 'errors' in misp_object:
return misp_object
o = MISPObject(misp_object['Object']['name'])
o.from_dict(**misp_object)
return o
def add_object(self, event: Union[MISPEvent, int, str, UUID], misp_object: MISPObject, pythonify: bool=False):
'''Add a MISP Object to an existing MISP event'''
event_id = self.__get_uuid_or_id_from_abstract_misp(event)
new_object = self._prepare_request('POST', f'objects/add/{event_id}', data=misp_object)
new_object = self._check_response(new_object, expect_json=True)
if not (self.global_pythonify or pythonify) or 'errors' in new_object:
return new_object
o = MISPObject(new_object['Object']['name'])
o.from_dict(**new_object)
return o
def update_object(self, misp_object: MISPObject, object_id: int=None, pythonify: bool=False):
'''Update an object on a MISP instance'''
if object_id is None:
object_id = self.__get_uuid_or_id_from_abstract_misp(misp_object)
else:
object_id = self.__get_uuid_or_id_from_abstract_misp(object_id)
updated_object = self._prepare_request('POST', f'objects/edit/{object_id}', data=misp_object)
updated_object = self._check_response(updated_object, expect_json=True)
if not (self.global_pythonify or pythonify) or 'errors' in updated_object:
return updated_object
o = MISPObject(updated_object['Object']['name'])
o.from_dict(**updated_object)
return o
def delete_object(self, misp_object: Union[MISPObject, int, str, UUID]):
'''Delete an object from a MISP instance'''
object_id = self.__get_uuid_or_id_from_abstract_misp(misp_object)
response = self._prepare_request('POST', f'objects/delete/{object_id}')
return self._check_response(response, expect_json=True)
def add_object_reference(self, misp_object_reference: MISPObjectReference, pythonify: bool=False):
"""Add a reference to an object"""
object_reference = self._prepare_request('POST', 'object_references/add', misp_object_reference)
object_reference = self._check_response(object_reference, expect_json=True)
if not (self.global_pythonify or pythonify) or 'errors' in object_reference:
return object_reference
r = MISPObjectReference()
r.from_dict(**object_reference)
return r
def delete_object_reference(self, object_reference: Union[MISPObjectReference, int, str, UUID]):
"""Delete a reference to an object"""
object_reference_id = self.__get_uuid_or_id_from_abstract_misp(object_reference)
response = self._prepare_request('POST', f'object_references/delete/{object_reference_id}')
return self._check_response(response, expect_json=True)
# Object templates
def object_templates(self, pythonify: bool=False):
"""Get all the object templates."""
object_templates = self._prepare_request('GET', 'objectTemplates')
object_templates = self._check_response(object_templates, expect_json=True)
if not (self.global_pythonify or pythonify) or 'errors' in object_templates:
return object_templates
to_return = []
for object_template in object_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):
"""Gets the full object template corresponting the UUID passed as parameter"""
object_template_id = self.__get_uuid_or_id_from_abstract_misp(object_template)
object_template = self._prepare_request('GET', f'objectTemplates/view/{object_template_id}')
object_template = self._check_response(object_template, expect_json=True)
if not (self.global_pythonify or pythonify) or 'errors' in object_template:
return object_template
t = MISPObjectTemplate()
t.from_dict(**object_template)
return t
def update_object_templates(self):
"""Trigger an update of the object templates"""
response = self._prepare_request('POST', 'objectTemplates/update')
return self._check_response(response, expect_json=True)
# ## END Object ###
# ## BEGIN Attribute ###
def attributes(self, pythonify: bool=False):
attributes = self._prepare_request('GET', f'attributes/index')
attributes = self._check_response(attributes, expect_json=True)
if not (self.global_pythonify or pythonify) or 'errors' in attributes:
return attributes
to_return = []
for attribute in attributes:
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):
'''Get an attribute from a MISP instance'''
attribute_id = self.__get_uuid_or_id_from_abstract_misp(attribute)
attribute = self._prepare_request('GET', f'attributes/view/{attribute_id}')
attribute = self._check_response(attribute, expect_json=True)
if not (self.global_pythonify or pythonify) or 'errors' in attribute:
return attribute
a = MISPAttribute()
a.from_dict(**attribute)
return a
def add_attribute(self, event: Union[MISPEvent, int, str, UUID], attribute: MISPAttribute, pythonify: bool=False):
'''Add an attribute to an existing MISP event
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}}'''
event_id = self.__get_uuid_or_id_from_abstract_misp(event)
new_attribute = self._prepare_request('POST', f'attributes/add/{event_id}', data=attribute)
new_attribute = self._check_response(new_attribute, expect_json=True)
if isinstance(attribute, list):
# Multiple attributes were passed at once, the handling is totally different
if self._old_misp((2, 4, 113), '2020-01-01', sys._getframe().f_code.co_name):
return new_attribute
if not (self.global_pythonify or pythonify):
return new_attribute
to_return = {'attributes': []}
if 'errors' in new_attribute:
to_return['errors'] = new_attribute['errors']
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
return self.add_attribute_proposal(event_id, attribute, pythonify)
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: int=None, pythonify: bool=False):
'''Update an attribute on a MISP instance'''
if attribute_id is None:
attribute_id = self.__get_uuid_or_id_from_abstract_misp(attribute)
else:
attribute_id = self.__get_uuid_or_id_from_abstract_misp(attribute_id)
updated_attribute = self._prepare_request('POST', f'attributes/edit/{attribute_id}', data=attribute)
updated_attribute = self._check_response(updated_attribute, expect_json=True)
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(attribute_id, 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):
'''Delete an attribute from a MISP instance'''
attribute_id = self.__get_uuid_or_id_from_abstract_misp(attribute)
data = {}
if hard:
data['hard'] = 1
response = self._prepare_request('POST', f'attributes/delete/{attribute_id}', data=data)
response = self._check_response(response, expect_json=True)
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
# ## END Attribute ###
# ## BEGIN Attribute Proposal ###
def attribute_proposals(self, event: Union[MISPEvent, int, str, UUID]=None, pythonify: bool=False):
if event:
event_id = self.__get_uuid_or_id_from_abstract_misp(event)
attribute_proposals = self._prepare_request('GET', f'shadow_attributes/index/{event_id}')
else:
attribute_proposals = self._prepare_request('GET', f'shadow_attributes')
attribute_proposals = self._check_response(attribute_proposals, expect_json=True)
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):
proposal_id = self.__get_uuid_or_id_from_abstract_misp(proposal)
attribute_proposal = self._prepare_request('GET', f'shadow_attributes/view/{proposal_id}')
attribute_proposal = self._check_response(attribute_proposal, expect_json=True)
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):
'''Propose a new attribute in an event'''
event_id = self.__get_uuid_or_id_from_abstract_misp(event)
new_attribute_proposal = self._prepare_request('POST', f'shadow_attributes/add/{event_id}', data=attribute)
new_attribute_proposal = self._check_response(new_attribute_proposal, expect_json=True)
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):
'''Propose a change for an attribute'''
initial_attribute_id = self.__get_uuid_or_id_from_abstract_misp(initial_attribute)
if self._old_misp((2, 4, 112), '2020-01-01', sys._getframe().f_code.co_name):
# Inconsistency in MISP: https://github.com/MISP/MISP/issues/4857
# Fix: https://github.com/MISP/MISP/commit/d6a15438f7a53f589ddeabe2b14e65c92baf43d3
attribute = {'ShadowAttribute': attribute}
update_attribute_proposal = self._prepare_request('POST', f'shadow_attributes/edit/{initial_attribute_id}', data=attribute)
update_attribute_proposal = self._check_response(update_attribute_proposal, expect_json=True)
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]):
'''Propose the deletion of an attribute'''
attribute_id = self.__get_uuid_or_id_from_abstract_misp(attribute)
response = self._prepare_request('POST', f'shadow_attributes/delete/{attribute_id}')
return self._check_response(response, expect_json=True)
# NOTE: You cannot modify an existing proposal, only accept/discard
def accept_attribute_proposal(self, proposal: Union[MISPShadowAttribute, int, str, UUID]):
'''Accept a proposal'''
proposal_id = self.__get_uuid_or_id_from_abstract_misp(proposal)
response = self._prepare_request('POST', f'shadow_attributes/accept/{proposal_id}')
return self._check_response(response, expect_json=True)
def discard_attribute_proposal(self, proposal: Union[MISPShadowAttribute, int, str, UUID]):
'''Discard a proposal'''
proposal_id = self.__get_uuid_or_id_from_abstract_misp(proposal)
response = self._prepare_request('POST', f'shadow_attributes/discard/{proposal_id}')
return self._check_response(response, expect_json=True)
# ## END Attribute Proposal ###
# ## BEGIN Sighting ###
def sightings(self, misp_entity: AbstractMISP=None, org: Union[MISPOrganisation, int, str, UUID]=None, pythonify: bool=False):
"""Get the list of sighting related to a MISPEvent or a MISPAttribute (depending on type of misp_entity)"""
if isinstance(misp_entity, MISPEvent):
context = 'event'
elif isinstance(misp_entity, MISPAttribute):
context = 'attribute'
else:
context = None
if org is not None:
org_id = self.__get_uuid_or_id_from_abstract_misp(org)
else:
org_id = None
if self._old_misp((2, 4, 112), '2020-01-01', sys._getframe().f_code.co_name):
url = f'sightings/listSightings/{misp_entity.id}/{context}'
if org_id:
url = f'{url}/{org_id}'
sightings = self._prepare_request('POST', url)
else:
if context is None:
url = 'sightings'
to_post = {}
else:
url = 'sightings/listSightings'
to_post = {'id': misp_entity.id, 'context': context}
if org_id:
to_post['org_id'] = org_id
sightings = self._prepare_request('POST', url, data=to_post)
sightings = self._check_response(sightings, expect_json=True)
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: Union[MISPAttribute, int, str, UUID]=None, pythonify: bool=False):
'''Add a new sighting (globally, or to a specific attribute)'''
if attribute:
attribute_id = self.__get_uuid_or_id_from_abstract_misp(attribute)
new_sighting = 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
new_sighting = self._prepare_request('POST', f'sightings/add', data=sighting)
new_sighting = self._check_response(new_sighting, expect_json=True)
if not (self.global_pythonify or pythonify) or 'errors' in new_sighting:
return new_sighting
s = MISPSighting()
s.from_dict(**new_sighting)
return s
def delete_sighting(self, sighting: Union[MISPSighting, int, str, UUID]):
'''Delete a sighting from a MISP instance'''
sighting_id = self.__get_uuid_or_id_from_abstract_misp(sighting)
response = self._prepare_request('POST', f'sightings/delete/{sighting_id}')
return self._check_response(response, expect_json=True)
# ## END Sighting ###
# ## BEGIN Tags ###
def tags(self, pythonify: bool=False):
"""Get the list of existing tags."""
tags = self._prepare_request('GET', 'tags')
tags = self._check_response(tags, expect_json=True)
if not (self.global_pythonify or pythonify) or 'errors' in tags:
return tags['Tag']
to_return = []
for tag in tags['Tag']:
t = MISPTag()
t.from_dict(**tag)
to_return.append(t)
return to_return
def get_tag(self, tag: Union[MISPTag, int, str, UUID], pythonify: bool=False):
"""Get a tag by id."""
tag_id = self.__get_uuid_or_id_from_abstract_misp(tag)
tag = self._prepare_request('GET', f'tags/view/{tag_id}')
tag = self._check_response(tag, expect_json=True)
if not (self.global_pythonify or pythonify) or 'errors' in tag:
return tag
t = MISPTag()
t.from_dict(**tag)
return t
def add_tag(self, tag: MISPTag, pythonify: bool=False):
'''Add a new tag on a MISP instance'''
new_tag = self._prepare_request('POST', 'tags/add', data=tag)
new_tag = self._check_response(new_tag, expect_json=True)
if not (self.global_pythonify or pythonify) or 'errors' in new_tag:
return new_tag
t = MISPTag()
t.from_dict(**new_tag)
return t
def enable_tag(self, tag: MISPTag, pythonify: bool=False):
"""Enable a tag."""
tag.hide_tag = False
return self.update_tag(tag, pythonify=pythonify)
def disable_tag(self, tag: MISPTag, pythonify: bool=False):
"""Disable a tag."""
tag.hide_tag = True
return self.update_tag(tag, pythonify=pythonify)
def update_tag(self, tag: MISPTag, tag_id: int=None, pythonify: bool=False):
"""Edit only the provided parameters of a tag."""
if tag_id is None:
tag_id = self.__get_uuid_or_id_from_abstract_misp(tag)
else:
tag_id = self.__get_uuid_or_id_from_abstract_misp(tag_id)
if self._old_misp((2, 4, 114), '2020-01-01', sys._getframe().f_code.co_name):
# Inconsistency https://github.com/MISP/MISP/issues/4852
tag = {'Tag': tag}
updated_tag = self._prepare_request('POST', f'tags/edit/{tag_id}', data=tag)
updated_tag = self._check_response(updated_tag, expect_json=True)
if not (self.global_pythonify or pythonify) or 'errors' in updated_tag:
return updated_tag
t = MISPTag()
t.from_dict(**updated_tag)
return t
def delete_tag(self, tag: Union[MISPTag, int, str, UUID]):
'''Delete an attribute from a MISP instance'''
tag_id = self.__get_uuid_or_id_from_abstract_misp(tag)
response = self._prepare_request('POST', f'tags/delete/{tag_id}')
return self._check_response(response, expect_json=True)
# ## END Tags ###
# ## BEGIN Taxonomies ###
def taxonomies(self, pythonify: bool=False):
"""Get all the taxonomies."""
taxonomies = self._prepare_request('GET', 'taxonomies')
taxonomies = self._check_response(taxonomies, expect_json=True)
if not (self.global_pythonify or pythonify) or 'errors' in taxonomies:
return taxonomies
to_return = []
for taxonomy in taxonomies:
t = MISPTaxonomy()
t.from_dict(**taxonomy)
to_return.append(t)
return to_return
def get_taxonomy(self, taxonomy: Union[MISPTaxonomy, int, str, UUID], pythonify: bool=False):
"""Get a taxonomy from a MISP instance."""
taxonomy_id = self.__get_uuid_or_id_from_abstract_misp(taxonomy)
taxonomy = self._prepare_request('GET', f'taxonomies/view/{taxonomy_id}')
taxonomy = self._check_response(taxonomy, expect_json=True)
if not (self.global_pythonify or pythonify) or 'errors' in taxonomy:
return taxonomy
t = MISPTaxonomy()
t.from_dict(**taxonomy)
return t
def enable_taxonomy(self, taxonomy: Union[MISPTaxonomy, int, str, UUID]):
"""Enable a taxonomy."""
taxonomy_id = self.__get_uuid_or_id_from_abstract_misp(taxonomy)
response = self._prepare_request('POST', f'taxonomies/enable/{taxonomy_id}')
return self._check_response(response, expect_json=True)
def disable_taxonomy(self, taxonomy: Union[MISPTaxonomy, int, str, UUID]):
"""Disable a taxonomy."""
taxonomy_id = self.__get_uuid_or_id_from_abstract_misp(taxonomy)
self.disable_taxonomy_tags(taxonomy_id)
response = self._prepare_request('POST', f'taxonomies/disable/{taxonomy_id}')
return self._check_response(response, expect_json=True)
def disable_taxonomy_tags(self, taxonomy: Union[MISPTaxonomy, int, str, UUID]):
"""Disable all the tags of a taxonomy."""
taxonomy_id = self.__get_uuid_or_id_from_abstract_misp(taxonomy)
response = self._prepare_request('POST', f'taxonomies/disableTag/{taxonomy_id}')
return self._check_response(response, expect_json=True)
def enable_taxonomy_tags(self, taxonomy: Union[MISPTaxonomy, int, str, UUID]):
"""Enable all the tags of a taxonomy.
NOTE: this automatically done when you call enable_taxonomy."""
taxonomy_id = self.__get_uuid_or_id_from_abstract_misp(taxonomy)
taxonomy = self.get_taxonomy(taxonomy_id)
if not taxonomy['Taxonomy']['enabled']:
raise PyMISPError(f"The taxonomy {taxonomy['Taxonomy']['name']} is not enabled.")
url = urljoin(self.root_url, 'taxonomies/addTag/{}'.format(taxonomy_id))
response = self._prepare_request('POST', url)
return self._check_response(response, expect_json=True)
def update_taxonomies(self):
"""Update all the taxonomies."""
response = self._prepare_request('POST', 'taxonomies/update')
return self._check_response(response, expect_json=True)
# ## END Taxonomies ###
# ## BEGIN Warninglists ###
def warninglists(self, pythonify: bool=False):
"""Get all the warninglists."""
warninglists = self._prepare_request('GET', 'warninglists')
warninglists = self._check_response(warninglists, expect_json=True)
if not (self.global_pythonify or pythonify) or 'errors' in warninglists:
return warninglists['Warninglists']
to_return = []
for warninglist in warninglists['Warninglists']:
w = MISPWarninglist()
w.from_dict(**warninglist)
to_return.append(w)
return to_return
def get_warninglist(self, warninglist: Union[MISPWarninglist, int, str, UUID], pythonify: bool=False):
"""Get a warninglist."""
warninglist_id = self.__get_uuid_or_id_from_abstract_misp(warninglist)
warninglist = self._prepare_request('GET', f'warninglists/view/{warninglist_id}')
warninglist = self._check_response(warninglist, expect_json=True)
if not (self.global_pythonify or pythonify) or 'errors' in warninglist:
return warninglist
w = MISPWarninglist()
w.from_dict(**warninglist)
return w
def toggle_warninglist(self, warninglist_id: List[int]=None, warninglist_name: List[str]=None,
force_enable: bool=False):
'''Toggle (enable/disable) the status of a warninglist by ID.
:param warninglist_id: ID of the WarningList
:param force_enable: Force the warning list in the enabled state (does nothing is already enabled)
'''
if warninglist_id is None and warninglist_name is None:
raise PyMISPError('Either warninglist_id or warninglist_name is required.')
query = {}
if warninglist_id is not None:
if not isinstance(warninglist_id, list):
warninglist_id = [warninglist_id]
query['id'] = warninglist_id
if warninglist_name is not None:
if not isinstance(warninglist_name, list):
warninglist_name = [warninglist_name]
query['name'] = warninglist_name
if force_enable:
query['enabled'] = force_enable
response = self._prepare_request('POST', 'warninglists/toggleEnable', data=json.dumps(query))
return self._check_response(response, expect_json=True)
def enable_warninglist(self, warninglist: Union[MISPWarninglist, int, str, UUID]):
"""Enable a warninglist."""
warninglist_id = self.__get_uuid_or_id_from_abstract_misp(warninglist)
return self.toggle_warninglist(warninglist_id=warninglist_id, force_enable=True)
def disable_warninglist(self, warninglist: Union[MISPWarninglist, int, str, UUID]):
"""Disable a warninglist."""
warninglist_id = self.__get_uuid_or_id_from_abstract_misp(warninglist)
return self.toggle_warninglist(warninglist_id=warninglist_id, force_enable=False)
def values_in_warninglist(self, value: list):
"""Check if IOC values are in warninglist"""
response = self._prepare_request('POST', 'warninglists/checkValue', data=json.dumps(value))
return self._check_response(response, expect_json=True)
def update_warninglists(self):
"""Update all the warninglists."""
response = self._prepare_request('POST', 'warninglists/update')
return self._check_response(response, expect_json=True)
# ## END Warninglists ###
# ## BEGIN Noticelist ###
def noticelists(self, pythonify: bool=False):
"""Get all the noticelists."""
noticelists = self._prepare_request('GET', 'noticelists')
noticelists = self._check_response(noticelists, expect_json=True)
if not (self.global_pythonify or pythonify) or 'errors' in noticelists:
return noticelists
to_return = []
for noticelist in noticelists:
n = MISPNoticelist()
n.from_dict(**noticelist)
to_return.append(n)
return to_return
def get_noticelist(self, noticelist: Union[MISPNoticelist, int, str, UUID], pythonify: bool=False):
"""Get a noticelist by id."""
noticelist_id = self.__get_uuid_or_id_from_abstract_misp(noticelist)
noticelist = self._prepare_request('GET', f'noticelists/view/{noticelist_id}')
noticelist = self._check_response(noticelist, expect_json=True)
if not (self.global_pythonify or pythonify) or 'errors' in noticelist:
return noticelist
n = MISPNoticelist()
n.from_dict(**noticelist)
return n
def enable_noticelist(self, noticelist: Union[MISPNoticelist, int, str, UUID]):
"""Enable a noticelist by id."""
# FIXME: https://github.com/MISP/MISP/issues/4856
# response = self._prepare_request('POST', f'noticelists/enable/{noticelist_id}')
noticelist_id = self.__get_uuid_or_id_from_abstract_misp(noticelist)
response = self._prepare_request('POST', f'noticelists/enableNoticelist/{noticelist_id}/true')
return self._check_response(response, expect_json=True)
def disable_noticelist(self, noticelist: Union[MISPNoticelist, int, str, UUID]):
"""Disable a noticelist by id."""
# FIXME: https://github.com/MISP/MISP/issues/4856
# response = self._prepare_request('POST', f'noticelists/disable/{noticelist_id}')
noticelist_id = self.__get_uuid_or_id_from_abstract_misp(noticelist)
response = self._prepare_request('POST', f'noticelists/enableNoticelist/{noticelist_id}')
return self._check_response(response, expect_json=True)
def update_noticelists(self):
"""Update all the noticelists."""
response = self._prepare_request('POST', 'noticelists/update')
return self._check_response(response, expect_json=True)
# ## END Noticelist ###
# ## BEGIN Galaxy ###
def galaxies(self, pythonify: bool=False):
"""Get all the galaxies."""
galaxies = self._prepare_request('GET', 'galaxies')
galaxies = self._check_response(galaxies, expect_json=True)
if not (self.global_pythonify or pythonify) or 'errors' in galaxies:
return galaxies
to_return = []
for galaxy in galaxies:
g = MISPGalaxy()
g.from_dict(**galaxy)
to_return.append(g)
return to_return
def get_galaxy(self, galaxy: Union[MISPGalaxy, int, str, UUID], pythonify: bool=False):
"""Get a galaxy by id."""
galaxy_id = self.__get_uuid_or_id_from_abstract_misp(galaxy)
galaxy = self._prepare_request('GET', f'galaxies/view/{galaxy_id}')
galaxy = self._check_response(galaxy, expect_json=True)
if not (self.global_pythonify or pythonify) or 'errors' in galaxy:
return galaxy
g = MISPGalaxy()
g.from_dict(**galaxy)
return g
def update_galaxies(self):
"""Update all the galaxies."""
response = self._prepare_request('POST', 'galaxies/update')
return self._check_response(response, expect_json=True)
# ## END Galaxy ###
# ## BEGIN Feed ###
def feeds(self, pythonify: bool=False):
"""Get the list of existing feeds."""
feeds = self._prepare_request('GET', 'feeds')
feeds = self._check_response(feeds, expect_json=True)
if not (self.global_pythonify or pythonify) or 'errors' in feeds:
return feeds
to_return = []
for feed in feeds:
f = MISPFeed()
f.from_dict(**feed)
to_return.append(f)
return to_return
def get_feed(self, feed: Union[MISPFeed, int, str, UUID], pythonify: bool=False):
"""Get a feed by id."""
feed_id = self.__get_uuid_or_id_from_abstract_misp(feed)
feed = self._prepare_request('GET', f'feeds/view/{feed_id}')
feed = self._check_response(feed, expect_json=True)
if not (self.global_pythonify or pythonify) or 'errors' in feed:
return feed
f = MISPFeed()
f.from_dict(**feed)
return f
def add_feed(self, feed: MISPFeed, pythonify: bool=False):
'''Add a new feed on a MISP instance'''
# FIXME: https://github.com/MISP/MISP/issues/4834
feed = {'Feed': feed}
new_feed = self._prepare_request('POST', 'feeds/add', data=feed)
new_feed = self._check_response(new_feed, expect_json=True)
if not (self.global_pythonify or pythonify) or 'errors' in new_feed:
return new_feed
f = MISPFeed()
f.from_dict(**new_feed)
return f
def enable_feed(self, feed: Union[MISPFeed, int, str, UUID], pythonify: bool=False):
'''Enable a feed (fetching it will create event(s)'''
if not isinstance(feed, MISPFeed):
feed_id = self.__get_uuid_or_id_from_abstract_misp(feed) # In case we have a UUID
feed = MISPFeed()
feed.id = feed_id
feed.enabled = True
return self.update_feed(feed=feed, pythonify=pythonify)
def disable_feed(self, feed: Union[MISPFeed, int, str, UUID], pythonify: bool=False):
'''Disable a feed'''
if not isinstance(feed, MISPFeed):
feed_id = self.__get_uuid_or_id_from_abstract_misp(feed) # In case we have a UUID
feed = MISPFeed()
feed.id = feed_id
feed.enabled = False
return self.update_feed(feed=feed, pythonify=pythonify)
def enable_feed_cache(self, feed: Union[MISPFeed, int, str, UUID], pythonify: bool=False):
'''Enable the caching of a feed'''
if not isinstance(feed, MISPFeed):
feed_id = self.__get_uuid_or_id_from_abstract_misp(feed) # In case we have a UUID
feed = MISPFeed()
feed.id = feed_id
feed.caching_enabled = True
return self.update_feed(feed=feed, pythonify=pythonify)
def disable_feed_cache(self, feed: Union[MISPFeed, int, str, UUID], pythonify: bool=False):
'''Disable the caching of a feed'''
if not isinstance(feed, MISPFeed):
feed_id = self.__get_uuid_or_id_from_abstract_misp(feed) # In case we have a UUID
feed = MISPFeed()
feed.id = feed_id
feed.caching_enabled = False
return self.update_feed(feed=feed, pythonify=pythonify)
def update_feed(self, feed: MISPFeed, feed_id: int=None, pythonify: bool=False):
'''Update a feed on a MISP instance'''
if feed_id is None:
feed_id = self.__get_uuid_or_id_from_abstract_misp(feed)
else:
feed_id = self.__get_uuid_or_id_from_abstract_misp(feed_id)
# FIXME: https://github.com/MISP/MISP/issues/4834
feed = {'Feed': feed}
updated_feed = self._prepare_request('POST', f'feeds/edit/{feed_id}', data=feed)
updated_feed = self._check_response(updated_feed, expect_json=True)
if not (self.global_pythonify or pythonify) or 'errors' in updated_feed:
return updated_feed
f = MISPFeed()
f.from_dict(**updated_feed)
return f
def delete_feed(self, feed: Union[MISPFeed, int, str, UUID]):
'''Delete a feed from a MISP instance'''
feed_id = self.__get_uuid_or_id_from_abstract_misp(feed)
response = self._prepare_request('POST', f'feeds/delete/{feed_id}')
return self._check_response(response, expect_json=True)
def fetch_feed(self, feed: Union[MISPFeed, int, str, UUID]):
"""Fetch one single feed"""
feed_id = self.__get_uuid_or_id_from_abstract_misp(feed)
response = self._prepare_request('GET', f'feeds/fetchFromFeed/{feed_id}')
return self._check_response(response)
def cache_all_feeds(self):
""" Cache all the feeds"""
response = self._prepare_request('GET', 'feeds/cacheFeeds/all')
return self._check_response(response)
def cache_feed(self, feed: Union[MISPFeed, int, str, UUID]):
"""Cache a specific feed"""
feed_id = self.__get_uuid_or_id_from_abstract_misp(feed)
response = self._prepare_request('GET', f'feeds/cacheFeeds/{feed_id}')
return self._check_response(response)
def cache_freetext_feeds(self):
"""Cache all the freetext feeds"""
response = self._prepare_request('GET', 'feeds/cacheFeeds/freetext')
return self._check_response(response)
def cache_misp_feeds(self):