-
Notifications
You must be signed in to change notification settings - Fork 277
/
mispevent.py
2341 lines (1968 loc) · 97.6 KB
/
mispevent.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
# -*- coding: utf-8 -*-
from datetime import timezone, datetime, date
import copy
import json
import os
import base64
import sys
from io import BytesIO, BufferedIOBase, TextIOBase
from zipfile import ZipFile
import uuid
from uuid import UUID
from collections import defaultdict
import logging
import hashlib
from pathlib import Path
from typing import List, Optional, Union, IO, Dict, Any
from .abstract import AbstractMISP, MISPTag
from .exceptions import UnknownMISPObjectTemplate, InvalidMISPObject, PyMISPError, NewEventError, NewAttributeError, NewEventReportError, NewGalaxyClusterError, NewGalaxyClusterRelationError
logger = logging.getLogger('pymisp')
try:
from dateutil.parser import parse
except ImportError:
logger.exception("Cannot import dateutil")
try:
import jsonschema # type: ignore
except ImportError:
logger.exception("Cannot import jsonschema")
try:
# pyme renamed to gpg the 2016-10-28
import gpg # type: ignore
from gpg.constants.sig import mode # type: ignore
has_pyme = True
except ImportError:
try:
# pyme renamed to gpg the 2016-10-28
import pyme as gpg # type: ignore
from pyme.constants.sig import mode # type: ignore
has_pyme = True
except ImportError:
has_pyme = False
def _make_datetime(value) -> datetime:
if isinstance(value, (int, float)):
# Timestamp
value = datetime.fromtimestamp(value)
elif isinstance(value, str):
if sys.version_info >= (3, 7):
try:
# faster
value = datetime.fromisoformat(value)
except Exception:
value = parse(value)
else:
try:
# faster
if '+' in value or value.find('-', 10) > -1: # date contains `-` char
value = datetime.strptime(value, "%Y-%m-%dT%H:%M:%S.%f%z")
elif '.' in value:
value = datetime.strptime(value, "%Y-%m-%dT%H:%M:%S.%f")
elif 'T' in value:
value = datetime.strptime(value, "%Y-%m-%dT%H:%M:%S")
else:
value = datetime.strptime(value, "%Y-%m-%d")
except Exception:
value = parse(value)
elif isinstance(value, datetime):
pass
elif isinstance(value, date): # NOTE: date has to be *after* datetime, or it will be overwritten
value = datetime.combine(value, datetime.min.time())
else:
raise PyMISPError(f'Invalid format for {value}: {type(value)}.')
if not value.tzinfo:
# set localtimezone if not present
value = value.astimezone()
return value
def make_bool(value: Optional[Union[bool, int, str, dict, list]]) -> bool:
"""Converts the supplied value to a boolean.
:param value: Value to interpret as a boolean. An empty string, dict
or list is False; value None is also False.
"""
if isinstance(value, bool):
return value
if isinstance(value, int):
return bool(value)
if not value: # None, 0, '', {}, []
return False
if isinstance(value, str):
if value == '0':
return False
return True
else:
raise PyMISPError('Unable to convert {} to a boolean.'.format(value))
class MISPOrganisation(AbstractMISP):
_fields_for_feed: set = {'name', 'uuid'}
def __init__(self):
super().__init__()
self.id: int
self.name: str
def from_dict(self, **kwargs):
if 'Organisation' in kwargs:
kwargs = kwargs['Organisation']
super(MISPOrganisation, self).from_dict(**kwargs)
def __repr__(self) -> str:
if hasattr(self, 'name'):
return f'<{self.__class__.__name__}(type={self.name})'
return f'<{self.__class__.__name__}(NotInitialized)'
class MISPSharingGroupOrg(AbstractMISP):
_fields_for_feed: set = {'extend', 'Organisation'}
def __init__(self):
super().__init__()
self.extend: bool
self.Organisation: MISPOrganisation
def from_dict(self, **kwargs):
if 'SharingGroupOrg' in kwargs:
kwargs = kwargs['SharingGroupOrg']
if 'Organisation' in kwargs:
self.Organisation = MISPOrganisation()
self.Organisation.from_dict(**kwargs.pop('Organisation'))
super().from_dict(**kwargs)
def __repr__(self) -> str:
if hasattr(self, 'Organisation') and hasattr(self, 'extend'):
return f'<{self.__class__.__name__}(Org={self.Organisation.name}, extend={self.extend})'
return f'<{self.__class__.__name__}(NotInitialized)'
def _to_feed(self) -> Dict:
to_return = super()._to_feed()
to_return['Organisation'] = self.Organisation._to_feed()
return to_return
class MISPSharingGroup(AbstractMISP):
_fields_for_feed: set = {'uuid', 'name', 'roaming', 'created', 'organisation_uuid', 'Organisation', 'SharingGroupOrg', 'SharingGroupServer'}
def __init__(self):
super().__init__()
self.name: str
self.SharingGroupOrg: List[MISPSharingGroupOrg] = []
@property
def sgorgs(self) -> List[MISPSharingGroupOrg]:
return self.SharingGroupOrg
@sgorgs.setter
def sgorgs(self, sgorgs: List[MISPSharingGroupOrg]):
if all(isinstance(x, MISPSharingGroupOrg) for x in sgorgs):
self.SharingGroupOrg = sgorgs
else:
raise PyMISPError('All the attributes have to be of type MISPSharingGroupOrg.')
def add_sgorg(self, sgorg):
misp_sgorg = MISPSharingGroupOrg()
misp_sgorg.from_dict(**sgorg)
self.SharingGroupOrg.append(misp_sgorg)
return misp_sgorg
def from_dict(self, **kwargs):
if 'SharingGroupOrg' in kwargs:
[self.add_sgorg(sgorg) for sgorg in kwargs.pop('SharingGroupOrg')]
if 'SharingGroup' in kwargs:
kwargs = kwargs['SharingGroup']
super().from_dict(**kwargs)
def __repr__(self) -> str:
if hasattr(self, 'name'):
return f'<{self.__class__.__name__}(name={self.name})>'
return f'<{self.__class__.__name__}(NotInitialized)>'
def _to_feed(self) -> Dict:
to_return = super()._to_feed()
to_return['SharingGroupOrg'] = [sgorg._to_feed() for sgorg in self.SharingGroupOrg]
to_return['Organisation'].pop('id', None)
for server in to_return['SharingGroupServer']:
server.pop('id', None)
server.pop('sharing_group_id', None)
server.pop('server_id', None)
server['Server'].pop('id', None)
return to_return
class MISPShadowAttribute(AbstractMISP):
def __init__(self):
super().__init__()
self.type: str
self.value: str
def from_dict(self, **kwargs):
if 'ShadowAttribute' in kwargs:
kwargs = kwargs['ShadowAttribute']
super().from_dict(**kwargs)
def __repr__(self) -> str:
if hasattr(self, 'value'):
return f'<{self.__class__.__name__}(type={self.type}, value={self.value})'
return f'<{self.__class__.__name__}(NotInitialized)'
class MISPSighting(AbstractMISP):
def __init__(self):
super().__init__()
self.id: int
self.value: str
def from_dict(self, **kwargs):
"""Initialize the MISPSighting from a dictionary
:param value: Value of the attribute the sighting is related too. Pushing this object
will update the sighting count of each attribute with this value on the instance.
:param uuid: UUID of the attribute to update
:param id: ID of the attriute to update
:param source: Source of the sighting
:param type: Type of the sighting
:param timestamp: Timestamp associated to the sighting
"""
if 'Sighting' in kwargs:
kwargs = kwargs['Sighting']
super(MISPSighting, self).from_dict(**kwargs)
def __repr__(self) -> str:
if hasattr(self, 'value'):
return '<{self.__class__.__name__}(value={self.value})'.format(self=self)
if hasattr(self, 'id'):
return '<{self.__class__.__name__}(id={self.id})'.format(self=self)
if hasattr(self, 'uuid'):
return '<{self.__class__.__name__}(uuid={self.uuid})'.format(self=self)
return '<{self.__class__.__name__}(NotInitialized)'.format(self=self)
class MISPAttribute(AbstractMISP):
_fields_for_feed: set = {'uuid', 'value', 'category', 'type', 'comment', 'data',
'deleted', 'timestamp', 'to_ids', 'disable_correlation',
'first_seen', 'last_seen'}
def __init__(self, describe_types: Optional[Dict] = None, strict: bool = False):
"""Represents an Attribute
:param describe_types: Use it if you want to overwrite the default describeTypes.json file (you don't)
:param strict: If false, fallback to sane defaults for the attribute type if the ones passed by the user are incorrect
"""
super().__init__()
if describe_types:
self.describe_types: Dict[str, Any] = describe_types
self.__categories: List[str] = self.describe_types['categories']
self.__category_type_mapping: Dict[str, List[str]] = self.describe_types['category_type_mappings']
self.__sane_default: Dict[str, Dict[str, Union[str, int]]] = self.describe_types['sane_defaults']
self.__strict: bool = strict
self.data: Optional[BytesIO] = None
self.first_seen: datetime
self.last_seen: datetime
self.uuid: str = str(uuid.uuid4())
self.ShadowAttribute: List[MISPShadowAttribute] = []
self.SharingGroup: MISPSharingGroup
self.Sighting: List[MISPSighting] = []
self.Tag: List[MISPTag] = []
# For search
self.Event: MISPEvent
self.RelatedAttribute: List[MISPAttribute]
# For malware sample
self._malware_binary: Optional[BytesIO]
def add_tag(self, tag: Optional[Union[str, MISPTag, Dict]] = None, **kwargs) -> MISPTag:
return super()._add_tag(tag, **kwargs)
@property
def tags(self) -> List[MISPTag]:
"""Returns a list of tags associated to this Attribute"""
return self.Tag
@tags.setter
def tags(self, tags: List[MISPTag]):
"""Set a list of prepared MISPTag."""
super()._set_tags(tags)
def _prepare_data(self, data: Optional[Union[Path, str, bytes, BytesIO]]):
if not data:
super().__setattr__('data', None)
return
if isinstance(data, BytesIO):
super().__setattr__('data', data)
elif isinstance(data, Path):
with data.open('rb') as f_temp:
super().__setattr__('data', BytesIO(f_temp.read()))
elif isinstance(data, (str, bytes)):
super().__setattr__('data', BytesIO(base64.b64decode(data)))
else:
raise PyMISPError(f'Invalid type ({type(data)}) for the data key: {data}')
if self.type == 'malware-sample':
try:
# Ignore type, if data is None -> exception
with ZipFile(self.data) as f: # type: ignore
if not self.__is_misp_encrypted_file(f):
raise PyMISPError('Not an existing malware sample')
for name in f.namelist():
if name.endswith('.filename.txt'):
with f.open(name, pwd=b'infected') as unpacked:
self.malware_filename = unpacked.read().decode().strip()
else:
# decrypting a zipped file is extremely slow. We do it on-demand in self.malware_binary
continue
except Exception:
# not a encrypted zip file, assuming it is a new malware sample
self._prepare_new_malware_sample()
def __setattr__(self, name: str, value: Any):
if name in ['first_seen', 'last_seen']:
_datetime = _make_datetime(value)
# NOTE: the two following should be exceptions, but there are existing events in this state,
# And we cannot dump them if it is there.
if name == 'last_seen' and hasattr(self, 'first_seen') and self.first_seen > _datetime:
logger.warning(f'last_seen ({value}) has to be after first_seen ({self.first_seen})')
if name == 'first_seen' and hasattr(self, 'last_seen') and self.last_seen < _datetime:
logger.warning(f'first_seen ({value}) has to be before last_seen ({self.last_seen})')
super().__setattr__(name, _datetime)
elif name == 'data':
self._prepare_data(value)
else:
super().__setattr__(name, value)
def hash_values(self, algorithm: str = 'sha512') -> List[str]:
"""Compute the hash of every value for fast lookups"""
if algorithm not in hashlib.algorithms_available:
raise PyMISPError('The algorithm {} is not available for hashing.'.format(algorithm))
if '|' in self.type or self.type == 'malware-sample':
hashes = []
for v in self.value.split('|'):
h = hashlib.new(algorithm)
h.update(v.encode("utf-8"))
hashes.append(h.hexdigest())
return hashes
else:
h = hashlib.new(algorithm)
to_encode = self.value
if not isinstance(to_encode, str):
to_encode = str(to_encode)
h.update(to_encode.encode("utf-8"))
return [h.hexdigest()]
def _set_default(self):
if not hasattr(self, 'comment'):
self.comment = ''
if not hasattr(self, 'timestamp'):
self.timestamp = datetime.timestamp(datetime.now())
def _to_feed(self, with_distribution=False) -> Dict:
if with_distribution:
self._fields_for_feed.add('distribution')
to_return = super()._to_feed()
if self.data:
to_return['data'] = base64.b64encode(self.data.getvalue()).decode()
if self.tags:
to_return['Tag'] = list(filter(None, [tag._to_feed() for tag in self.tags]))
if with_distribution:
try:
to_return['SharingGroup'] = self.SharingGroup._to_feed()
except AttributeError:
pass
return to_return
@property
def known_types(self) -> List[str]:
"""Returns a list of all the known MISP attributes types"""
return self.describe_types['types']
@property
def malware_binary(self) -> Optional[BytesIO]:
"""Returns a BytesIO of the malware, if the attribute has one.
Decrypts, unpacks and caches the binary on the first invocation,
which may require some time for large attachments (~1s/MB).
"""
if self.type != 'malware-sample':
# Not a malware sample
return None
if hasattr(self, '_malware_binary'):
# Already unpacked
return self._malware_binary
elif hasattr(self, 'malware_filename'):
# Have a binary, but didn't decrypt it yet
with ZipFile(self.data) as f: # type: ignore
for name in f.namelist():
if not name.endswith('.filename.txt'):
with f.open(name, pwd=b'infected') as unpacked:
self._malware_binary = BytesIO(unpacked.read())
return self._malware_binary
return None
@property
def shadow_attributes(self) -> List[MISPShadowAttribute]:
return self.ShadowAttribute
@shadow_attributes.setter
def shadow_attributes(self, shadow_attributes: List[MISPShadowAttribute]):
"""Set a list of prepared MISPShadowAttribute."""
if all(isinstance(x, MISPShadowAttribute) for x in shadow_attributes):
self.ShadowAttribute = shadow_attributes
else:
raise PyMISPError('All the attributes have to be of type MISPShadowAttribute.')
@property
def sightings(self) -> List[MISPSighting]:
return self.Sighting
@sightings.setter
def sightings(self, sightings: List[MISPSighting]):
"""Set a list of prepared MISPSighting."""
if all(isinstance(x, MISPSighting) for x in sightings):
self.Sighting = sightings
else:
raise PyMISPError('All the attributes have to be of type MISPSighting.')
def delete(self):
"""Mark the attribute as deleted (soft delete)"""
self.deleted = True
def add_proposal(self, shadow_attribute=None, **kwargs) -> MISPShadowAttribute:
"""Alias for add_shadow_attribute"""
return self.add_shadow_attribute(shadow_attribute, **kwargs)
def add_shadow_attribute(self, shadow_attribute: Optional[Union[MISPShadowAttribute, Dict]] = None, **kwargs) -> MISPShadowAttribute:
"""Add a shadow attribute to the attribute (by name or a MISPShadowAttribute object)"""
if isinstance(shadow_attribute, MISPShadowAttribute):
misp_shadow_attribute = shadow_attribute
elif isinstance(shadow_attribute, dict):
misp_shadow_attribute = MISPShadowAttribute()
misp_shadow_attribute.from_dict(**shadow_attribute)
elif kwargs:
misp_shadow_attribute = MISPShadowAttribute()
misp_shadow_attribute.from_dict(**kwargs)
else:
raise PyMISPError("The shadow_attribute is in an invalid format (can be either string, MISPShadowAttribute, or an expanded dict): {}".format(shadow_attribute))
self.shadow_attributes.append(misp_shadow_attribute)
self.edited = True
return misp_shadow_attribute
def add_sighting(self, sighting: Optional[Union[MISPSighting, dict]] = None, **kwargs) -> MISPSighting:
"""Add a sighting to the attribute (by name or a MISPSighting object)"""
if isinstance(sighting, MISPSighting):
misp_sighting = sighting
elif isinstance(sighting, dict):
misp_sighting = MISPSighting()
misp_sighting.from_dict(**sighting)
elif kwargs:
misp_sighting = MISPSighting()
misp_sighting.from_dict(**kwargs)
else:
raise PyMISPError("The sighting is in an invalid format (can be either string, MISPShadowAttribute, or an expanded dict): {}".format(sighting))
self.sightings.append(misp_sighting)
self.edited = True
return misp_sighting
def from_dict(self, **kwargs):
if 'Attribute' in kwargs:
kwargs = kwargs['Attribute']
if kwargs.get('type') and kwargs.get('category'):
if kwargs['type'] not in self.__category_type_mapping[kwargs['category']]:
if self.__strict:
raise NewAttributeError('{} and {} is an invalid combination, type for this category has to be in {}'.format(
kwargs.get('type'), kwargs.get('category'), (', '.join(self.__category_type_mapping[kwargs['category']]))))
else:
kwargs.pop('category', None)
self.type = kwargs.pop('type', None) # Required
if self.type is None:
raise NewAttributeError('The type of the attribute is required.')
if self.type not in self.known_types:
raise NewAttributeError('{} is invalid, type has to be in {}'.format(self.type, (', '.join(self.known_types))))
type_defaults = self.__sane_default[self.type]
self.value = kwargs.pop('value', None)
if self.value is None:
raise NewAttributeError('The value of the attribute is required.')
if self.type == 'datetime' and isinstance(self.value, str):
try:
# Faster
if sys.version_info >= (3, 7):
self.value = datetime.fromisoformat(self.value)
else:
if '+' in self.value or '-' in self.value:
self.value = datetime.strptime(self.value, "%Y-%m-%dT%H:%M:%S.%f%z")
elif '.' in self.value:
self.value = datetime.strptime(self.value, "%Y-%m-%dT%H:%M:%S.%f")
else:
self.value = datetime.strptime(self.value, "%Y-%m-%dT%H:%M:%S")
except ValueError:
# Slower, but if the other ones fail, that's a good fallback
self.value = parse(self.value)
# Default values
self.category = kwargs.pop('category', type_defaults['default_category'])
if self.category is None:
# In case the category key is passed, but None
self.category = type_defaults['default_category']
if self.category not in self.__categories:
raise NewAttributeError('{} is invalid, category has to be in {}'.format(self.category, (', '.join(self.__categories))))
self.to_ids = kwargs.pop('to_ids', bool(int(type_defaults['to_ids'])))
if self.to_ids is None:
self.to_ids = bool(int(type_defaults['to_ids']))
else:
self.to_ids = make_bool(self.to_ids)
if not isinstance(self.to_ids, bool):
raise NewAttributeError('{} is invalid, to_ids has to be True or False'.format(self.to_ids))
self.distribution = kwargs.pop('distribution', None)
if self.distribution is not None:
self.distribution = int(self.distribution)
if self.distribution not in [0, 1, 2, 3, 4, 5]:
raise NewAttributeError('{} is invalid, the distribution has to be in 0, 1, 2, 3, 4, 5'.format(self.distribution))
# other possible values
if kwargs.get('data'):
self.data = kwargs.pop('data')
if kwargs.get('id'):
self.id = int(kwargs.pop('id'))
if kwargs.get('event_id'):
self.event_id = int(kwargs.pop('event_id'))
if kwargs.get('timestamp'):
ts = kwargs.pop('timestamp')
if isinstance(ts, datetime):
self.timestamp = ts
else:
self.timestamp = datetime.fromtimestamp(int(ts), timezone.utc)
if kwargs.get('first_seen'):
fs = kwargs.pop('first_seen')
try:
# Faster
if sys.version_info >= (3, 7):
self.first_seen = datetime.fromisoformat(fs)
else:
self.first_seen = datetime.strptime(fs, "%Y-%m-%dT%H:%M:%S.%f%z")
except Exception:
# Use __setattr__
self.first_seen = fs
if kwargs.get('last_seen'):
ls = kwargs.pop('last_seen')
try:
# Faster
if sys.version_info >= (3, 7):
self.last_seen = datetime.fromisoformat(ls)
else:
self.last_seen = datetime.strptime(ls, "%Y-%m-%dT%H:%M:%S.%f%z")
except Exception:
# Use __setattr__
self.last_seen = ls
if kwargs.get('sharing_group_id'):
self.sharing_group_id = int(kwargs.pop('sharing_group_id'))
if self.distribution == 4:
# The distribution is set to sharing group, a sharing_group_id is required.
if not hasattr(self, 'sharing_group_id'):
raise NewAttributeError('If the distribution is set to sharing group, a sharing group ID is required.')
elif not self.sharing_group_id:
# Cannot be None or 0 either.
raise NewAttributeError('If the distribution is set to sharing group, a sharing group ID is required (cannot be {}).'.format(self.sharing_group_id))
if kwargs.get('Tag'):
[self.add_tag(tag) for tag in kwargs.pop('Tag')]
if kwargs.get('Sighting'):
[self.add_sighting(sighting) for sighting in kwargs.pop('Sighting')]
if kwargs.get('ShadowAttribute'):
[self.add_shadow_attribute(s_attr) for s_attr in kwargs.pop('ShadowAttribute')]
if kwargs.get('SharingGroup'):
self.SharingGroup = MISPSharingGroup()
self.SharingGroup.from_dict(**kwargs.pop('SharingGroup'))
# If the user wants to disable correlation, let them. Defaults to False.
self.disable_correlation = kwargs.pop("disable_correlation", False)
if self.disable_correlation is None:
self.disable_correlation = False
super().from_dict(**kwargs)
def to_dict(self, json_format: bool = False) -> Dict:
to_return = super().to_dict(json_format)
if self.data:
to_return['data'] = base64.b64encode(self.data.getvalue()).decode()
return to_return
def _prepare_new_malware_sample(self):
if '|' in self.value:
# Get the filename, ignore the md5, because humans.
self.malware_filename, md5 = self.value.split('|')
else:
# Assuming the user only passed the filename
self.malware_filename = self.value
self.value = self.malware_filename
self._malware_binary = self.data
self.encrypt = True
def __is_misp_encrypted_file(self, f) -> bool:
files_list = f.namelist()
if len(files_list) != 2:
return False
md5_from_filename = ''
md5_from_file = ''
for name in files_list:
if name.endswith('.filename.txt'):
md5_from_filename = name.replace('.filename.txt', '')
else:
md5_from_file = name
if not md5_from_filename or not md5_from_file or md5_from_filename != md5_from_file:
return False
return True
def __repr__(self):
if hasattr(self, 'value'):
return '<{self.__class__.__name__}(type={self.type}, value={self.value})'.format(self=self)
return '<{self.__class__.__name__}(NotInitialized)'.format(self=self)
def verify(self, gpg_uid): # pragma: no cover
# Not used
if not has_pyme:
raise PyMISPError('pyme is required, please install: pip install --pre pyme3. You will also need libgpg-error-dev and libgpgme11-dev.')
signed_data = self._serialize()
with gpg.Context() as c:
keys = list(c.keylist(gpg_uid))
try:
c.verify(signed_data, signature=base64.b64decode(self.sig), verify=keys[:1])
return {self.uuid: True}
except Exception:
return {self.uuid: False}
def _serialize(self): # pragma: no cover
# Not used
return '{type}{category}{to_ids}{uuid}{timestamp}{comment}{deleted}{value}'.format(
type=self.type, category=self.category, to_ids=self.to_ids, uuid=self.uuid, timestamp=self.timestamp,
comment=self.comment, deleted=self.deleted, value=self.value).encode()
def sign(self, gpg_uid, passphrase=None): # pragma: no cover
# Not used
if not has_pyme:
raise PyMISPError('pyme is required, please install: pip install --pre pyme3. You will also need libgpg-error-dev and libgpgme11-dev.')
to_sign = self._serialize()
with gpg.Context() as c:
keys = list(c.keylist(gpg_uid))
c.signers = keys[:1]
if passphrase:
c.set_passphrase_cb(lambda *args: passphrase)
signed, _ = c.sign(to_sign, mode=mode.DETACH)
self.sig = base64.b64encode(signed).decode()
class MISPObjectReference(AbstractMISP):
_fields_for_feed: set = {'uuid', 'timestamp', 'relationship_type', 'comment',
'object_uuid', 'referenced_uuid'}
def __init__(self):
super().__init__()
self.uuid = str(uuid.uuid4())
self.object_uuid: str
self.referenced_uuid: str
self.relationship_type: str
def _set_default(self):
if not hasattr(self, 'comment'):
self.comment = ''
if not hasattr(self, 'timestamp'):
self.timestamp = datetime.timestamp(datetime.now())
def from_dict(self, **kwargs):
if 'ObjectReference' in kwargs:
kwargs = kwargs['ObjectReference']
super(MISPObjectReference, self).from_dict(**kwargs)
def __repr__(self) -> str:
if hasattr(self, 'referenced_uuid') and hasattr(self, 'object_uuid'):
return '<{self.__class__.__name__}(object_uuid={self.object_uuid}, referenced_uuid={self.referenced_uuid}, relationship_type={self.relationship_type})'.format(self=self)
return '<{self.__class__.__name__}(NotInitialized)'.format(self=self)
class MISPObject(AbstractMISP):
_fields_for_feed: set = {'name', 'meta-category', 'description', 'template_uuid',
'template_version', 'uuid', 'timestamp', 'comment',
'first_seen', 'last_seen', 'deleted'}
def __init__(self, name: str, strict: bool = False, standalone: bool = True, default_attributes_parameters: Dict = {}, **kwargs):
''' Master class representing a generic MISP object
:param name: Name of the object
:param strict: Enforce validation with the object templates
:param standalone: The object will be pushed as directly on MISP, not as a part of an event.
In this case the ObjectReference needs to be pushed manually and cannot be in the JSON dump.
:param default_attributes_parameters: Used as template for the attributes if they are not overwritten in add_attribute
:param misp_objects_path_custom: Path to custom object templates
:param misp_objects_template_custom: Template of the object. Expects the content (dict, loaded with json.load or json.loads) of a template definition file, see repository MISP/misp-objects.
'''
super().__init__(**kwargs)
self._strict: bool = strict
self.name: str = name
self._known_template: bool = False
self.id: int
self._definition: Optional[Dict]
misp_objects_template_custom = kwargs.pop('misp_objects_template_custom', None)
misp_objects_path_custom = kwargs.pop('misp_objects_path_custom', None)
if misp_objects_template_custom:
self._set_template(misp_objects_template_custom=misp_objects_template_custom)
else:
# Fall back to default path if None
self._set_template(misp_objects_path_custom=misp_objects_path_custom)
self.uuid: str = str(uuid.uuid4())
self.first_seen: datetime
self.last_seen: datetime
self.__fast_attribute_access: dict = defaultdict(list) # Hashtable object_relation: [attributes]
self.ObjectReference: List[MISPObjectReference] = []
self._standalone: bool = False
self.Attribute: List[MISPObjectAttribute] = []
self.SharingGroup: MISPSharingGroup
self._default_attributes_parameters: dict
if isinstance(default_attributes_parameters, MISPAttribute):
# Just make sure we're not modifying an existing MISPAttribute
self._default_attributes_parameters = default_attributes_parameters.to_dict()
else:
self._default_attributes_parameters = copy.copy(default_attributes_parameters)
if self._default_attributes_parameters:
# Let's clean that up
self._default_attributes_parameters.pop('value', None) # duh
self._default_attributes_parameters.pop('uuid', None) # duh
self._default_attributes_parameters.pop('id', None) # duh
self._default_attributes_parameters.pop('object_id', None) # duh
self._default_attributes_parameters.pop('type', None) # depends on the value
self._default_attributes_parameters.pop('object_relation', None) # depends on the value
self._default_attributes_parameters.pop('disable_correlation', None) # depends on the value
self._default_attributes_parameters.pop('to_ids', None) # depends on the value
self._default_attributes_parameters.pop('deleted', None) # doesn't make sense to pre-set it
self._default_attributes_parameters.pop('data', None) # in case the original in a sample or an attachment
# Those values are set for the current object, if they exist, but not pop'd because they are still useful for the attributes
self.distribution: int = self._default_attributes_parameters.get('distribution', 5)
self.sharing_group_id: int = self._default_attributes_parameters.get('sharing_group_id', 0)
else:
self.distribution = 5 # Default to inherit
self.sharing_group_id = 0
self.standalone = standalone
def _load_template_path(self, template_path: Union[Path, str]) -> bool:
template = self._load_json(template_path)
if not template:
self._definition = None
return False
self._load_template(template)
return True
def _load_template(self, template: Dict) -> None:
self._definition = template
setattr(self, 'meta-category', self._definition['meta-category'])
self.template_uuid = self._definition['uuid']
self.description = self._definition['description']
self.template_version = self._definition['version']
def _set_default(self):
if not hasattr(self, 'comment'):
self.comment = ''
if not hasattr(self, 'timestamp'):
self.timestamp = datetime.timestamp(datetime.now())
def _to_feed(self, with_distribution=False) -> Dict:
if with_distribution:
self._fields_for_feed.add('distribution')
to_return = super(MISPObject, self)._to_feed()
if self.references:
to_return['ObjectReference'] = [reference._to_feed() for reference in self.references]
if with_distribution:
try:
to_return['SharingGroup'] = self.SharingGroup._to_feed()
except AttributeError:
pass
return to_return
def __setattr__(self, name, value):
if name in ['first_seen', 'last_seen']:
value = _make_datetime(value)
if name == 'last_seen' and hasattr(self, 'first_seen') and self.first_seen > value:
logger.warning(f'last_seen ({value}) has to be after first_seen ({self.first_seen})')
if name == 'first_seen' and hasattr(self, 'last_seen') and self.last_seen < value:
logger.warning(f'first_seen ({value}) has to be before last_seen ({self.last_seen})')
super().__setattr__(name, value)
def force_misp_objects_path_custom(self, misp_objects_path_custom: Union[Path, str], object_name: Optional[str] = None):
if object_name:
self.name = object_name
self._set_template(misp_objects_path_custom)
def _set_template(self, misp_objects_path_custom: Optional[Union[Path, str]] = None, misp_objects_template_custom: Optional[Dict] = None):
if misp_objects_template_custom:
# A complete template was given to the constructor
self._load_template(misp_objects_template_custom)
self._known_template = True
else:
if misp_objects_path_custom:
# If misp_objects_path_custom is given, and an object with the given name exists, use that.
if isinstance(misp_objects_path_custom, str):
self.misp_objects_path = Path(misp_objects_path_custom)
else:
self.misp_objects_path = misp_objects_path_custom
# Try to get the template
self._known_template = self._load_template_path(self.misp_objects_path / self.name / 'definition.json')
if not self._known_template and self._strict:
raise UnknownMISPObjectTemplate('{} is unknown in the MISP object directory.'.format(self.name))
else:
# Then we have no meta-category, template_uuid, description and template_version
pass
def delete(self):
"""Mark the object as deleted (soft delete)"""
self.deleted = True
@property
def disable_validation(self):
self._strict = False
@property
def attributes(self) -> List['MISPObjectAttribute']:
return self.Attribute
@attributes.setter
def attributes(self, attributes: List['MISPObjectAttribute']):
if all(isinstance(x, MISPObjectAttribute) for x in attributes):
self.Attribute = attributes
self.__fast_attribute_access = defaultdict(list)
else:
raise PyMISPError('All the attributes have to be of type MISPObjectAttribute.')
@property
def references(self) -> List[MISPObjectReference]:
return self.ObjectReference
@references.setter
def references(self, references: List[MISPObjectReference]):
if all(isinstance(x, MISPObjectReference) for x in references):
self.ObjectReference = references
else:
raise PyMISPError('All the attributes have to be of type MISPObjectReference.')
@property
def standalone(self):
return self._standalone
@standalone.setter
def standalone(self, new_standalone: bool):
if self._standalone != new_standalone:
if new_standalone:
self.update_not_jsonable("ObjectReference")
else:
self._remove_from_not_jsonable("ObjectReference")
self._standalone = new_standalone
else:
pass
def from_dict(self, **kwargs):
if 'Object' in kwargs:
kwargs = kwargs['Object']
if self._known_template:
if kwargs.get('template_uuid') and kwargs['template_uuid'] != self.template_uuid:
if self._strict:
raise UnknownMISPObjectTemplate('UUID of the object is different from the one of the template.')
else:
self._known_template = False
if kwargs.get('template_version') and int(kwargs['template_version']) != self.template_version:
if self._strict:
raise UnknownMISPObjectTemplate('Version of the object ({}) is different from the one of the template ({}).'.format(kwargs['template_version'], self.template_version))
else:
self._known_template = False
# depending on how the object is initialized, we may have a few keys to pop
kwargs.pop('misp_objects_template_custom', None)
kwargs.pop('misp_objects_path_custom', None)
if 'distribution' in kwargs and kwargs['distribution'] is not None:
self.distribution = kwargs.pop('distribution')
self.distribution = int(self.distribution)
if self.distribution not in [0, 1, 2, 3, 4, 5]:
raise NewAttributeError('{} is invalid, the distribution has to be in 0, 1, 2, 3, 4, 5'.format(self.distribution))
if kwargs.get('timestamp'):
ts = kwargs.pop('timestamp')
if isinstance(ts, datetime):
self.timestamp = ts
else:
self.timestamp = datetime.fromtimestamp(int(ts), timezone.utc)
if kwargs.get('first_seen'):
fs = kwargs.pop('first_seen')
try:
# Faster
if sys.version_info >= (3, 7):
self.first_seen = datetime.fromisoformat(fs)
else:
self.first_seen = datetime.strptime(fs, "%Y-%m-%dT%H:%M:%S.%f%z")
except Exception:
# Use __setattr__
self.first_seen = fs
if kwargs.get('last_seen'):
ls = kwargs.pop('last_seen')
try:
# Faster
if sys.version_info >= (3, 7):
self.last_seen = datetime.fromisoformat(ls)
else:
self.last_seen = datetime.strptime(ls, "%Y-%m-%dT%H:%M:%S.%f%z")
except Exception:
# Use __setattr__
self.last_seen = ls
if kwargs.get('Attribute'):
[self.add_attribute(**a) for a in kwargs.pop('Attribute')]
if kwargs.get('ObjectReference'):
[self.add_reference(**r) for r in kwargs.pop('ObjectReference')]
if kwargs.get('SharingGroup'):
self.SharingGroup = MISPSharingGroup()
self.SharingGroup.from_dict(**kwargs.pop('SharingGroup'))
# Not supported yet - https://github.com/MISP/PyMISP/issues/168
# if kwargs.get('Tag'):
# for tag in kwargs.pop('Tag'):
# self.add_tag(tag)
super().from_dict(**kwargs)
def add_reference(self, referenced_uuid: Union[AbstractMISP, str], relationship_type: str, comment: Optional[str] = None, **kwargs) -> MISPObjectReference:
"""Add a link (uuid) to another object"""
if isinstance(referenced_uuid, AbstractMISP):
# Allow to pass an object or an attribute instead of its UUID
referenced_uuid = referenced_uuid.uuid
if 'object_uuid' in kwargs and not kwargs.get('object_uuid'):
# Unexplained None in object_uuid key -> https://github.com/MISP/PyMISP/issues/640
kwargs.pop('object_uuid')
object_uuid = self.uuid
elif kwargs.get('object_uuid'):
# Load existing object
object_uuid = kwargs.pop('object_uuid')
else:
# New reference
object_uuid = self.uuid
reference = MISPObjectReference()
reference.from_dict(object_uuid=object_uuid, referenced_uuid=referenced_uuid,
relationship_type=relationship_type, comment=comment, **kwargs)
self.ObjectReference.append(reference)
self.edited = True
return reference
def get_attributes_by_relation(self, object_relation: str) -> List[MISPAttribute]:
'''Returns the list of attributes with the given object relation in the object'''
return self._fast_attribute_access.get(object_relation, [])
@property
def _fast_attribute_access(self) -> Dict:
if not self.__fast_attribute_access:
for a in self.attributes:
self.__fast_attribute_access[a.object_relation].append(a)
return self.__fast_attribute_access
def has_attributes_by_relation(self, list_of_relations: List[str]) -> bool:
'''True if all the relations in the list are defined in the object'''
return all(relation in self._fast_attribute_access for relation in list_of_relations)
def add_attribute(self, object_relation: str, simple_value: Optional[Union[str, int, float]] = None, **value) -> Optional[MISPAttribute]:
"""Add an attribute. object_relation is required and the value key is a
dictionary with all the keys supported by MISPAttribute"""
if simple_value is not None: # /!\ The value *can* be 0