-
Notifications
You must be signed in to change notification settings - Fork 20
/
test_stix1_export.py
4282 lines (3696 loc) · 196 KB
/
test_stix1_export.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 python
# -*- coding: utf-8 -*-
import re
import unittest
from base64 import b64encode
from datetime import datetime, timezone
from misp_stix_converter import (MISPtoSTIX1EventsParser, misp_attribute_collection_to_stix1,
misp_event_collection_to_stix1, misp_to_stix1)
from pymisp import MISPEvent
from uuid import uuid5, UUID
from .test_events import *
from ._test_stix import TestSTIX
from ._test_stix_export import TestCollectionSTIX1Export
_DEFAULT_NAMESPACE = 'https://github.com/MISP/MISP'
_DEFAULT_ORGNAME = 'MISP-Project'
_ORGNAME_ID = re.sub('[\W]+', '', _DEFAULT_ORGNAME.replace(' ', '_'))
misp_reghive = {
"HKEY_CLASSES_ROOT": "HKEY_CLASSES_ROOT",
"HKCR": "HKEY_CLASSES_ROOT",
"HKEY_CURRENT_CONFIG": "HKEY_CURRENT_CONFIG",
"HKCC": "HKEY_CURRENT_CONFIG",
"HKEY_CURRENT_USER": "HKEY_CURRENT_USER",
"HKCU": "HKEY_CURRENT_USER",
"HKEY_LOCAL_MACHINE": "HKEY_LOCAL_MACHINE",
"HKLM": "HKEY_LOCAL_MACHINE",
"HKEY_USERS": "HKEY_USERS",
"HKU": "HKEY_USERS",
"HKEY_CURRENT_USER_LOCAL_SETTINGS": "HKEY_CURRENT_USER_LOCAL_SETTINGS",
"HKCULS": "HKEY_CURRENT_USER_LOCAL_SETTINGS",
"HKEY_PERFORMANCE_DATA": "HKEY_PERFORMANCE_DATA",
"HKPD": "HKEY_PERFORMANCE_DATA",
"HKEY_PERFORMANCE_NLSTEXT": "HKEY_PERFORMANCE_NLSTEXT",
"HKPN": "HKEY_PERFORMANCE_NLSTEXT",
"HKEY_PERFORMANCE_TEXT": "HKEY_PERFORMANCE_TEXT",
"HKPT": "HKEY_PERFORMANCE_TEXT",
}
class TestStix1Export(TestSTIX):
################################################################################
# UTILITY FUNCTIONS. #
################################################################################
@staticmethod
def _add_ids_flag(event):
for misp_object in event['Object']:
misp_object['Attribute'][0]['to_ids'] = True
def _check_asn_properties(self, properties, attributes):
asn, description, subnet1, subnet2 = attributes
self.assertEqual(properties.handle.value, asn['value'])
self.assertEqual(properties.name.value, description['value'])
custom_properties = properties.custom_properties
self.assertEqual(len(custom_properties), 2)
for attribute, custom in zip((subnet1, subnet2), custom_properties):
self.assertEqual(custom.name, attribute['object_relation'])
self.assertEqual(custom.value, attribute['value'])
def _check_attachment_properties(self, observable, attribute):
self.assertEqual(observable.title, attribute['value'])
properties = self._check_observable_features(observable, attribute, 'Artifact')
data = attribute['data']
if not isinstance(data, str):
data = b64encode(data.getvalue()).decode()
self.assertEqual(properties.raw_artifact.value, data)
def _check_credential_properties(self, properties, attributes):
text, username, password, _type, origin, _format, notification = attributes
self.assertEqual(properties.description.value, text['value'])
self.assertEqual(properties.username.value, username['value'])
self.assertEqual(len(properties.authentication), 1)
authentication = properties.authentication[0]
self.assertEqual(authentication.authentication_type.value, _type['value'])
self.assertEqual(authentication.authentication_data.value, password['value'])
struct_auth_meca = authentication.structured_authentication_mechanism
self.assertEqual(struct_auth_meca.description.value, _format['value'])
custom_properties = properties.custom_properties
self._check_custom_properties((origin, notification), custom_properties)
def _check_coa_taken(self, coa_taken, uuid, timestamp=None):
self.assertEqual(coa_taken.course_of_action.idref, f'{_ORGNAME_ID}:CourseOfAction-{uuid}')
if timestamp is not None:
if isinstance(timestamp, str):
self.assertEqual(
coa_taken.course_of_action.timestamp,
datetime.fromtimestamp(
int(timestamp), timezone.utc
)
)
else:
self.assertEqual(coa_taken.course_of_action.timestamp, timestamp)
def _check_course_of_action_fields(self, course_of_action, misp_object):
self.assertEqual(course_of_action.id_, f"{_ORGNAME_ID}:CourseOfAction-{misp_object['uuid']}")
name, description, type_, objective, stage, cost, impact, efficacy = misp_object['Attribute']
self.assertEqual(course_of_action.title, name['value'])
self.assertEqual(course_of_action.description.value, description['value'])
self.assertEqual(course_of_action.type_.value, type_['value'])
self.assertEqual(course_of_action.objective.description.value, objective['value'])
self.assertEqual(course_of_action.stage.value, stage['value'])
self.assertEqual(course_of_action.cost.value, cost['value'])
self.assertEqual(course_of_action.impact.value, impact['value'])
self.assertEqual(course_of_action.efficacy.value, efficacy['value'])
def _check_custom_properties(self, attributes, custom_properties):
self.assertEqual(len(custom_properties), len(attributes))
for attribute, custom in zip(attributes, custom_properties):
self.assertEqual(custom.name, attribute['object_relation'])
value = attribute['value']
if isinstance(value, datetime):
self.assertEqual(
self._datetime_from_str(custom.value).timestamp(),
value.timestamp()
)
continue
self.assertEqual(custom.value, value)
def _check_custom_property(self, attribute, custom_properties):
self.assertEqual(custom_properties.name, attribute['type'])
value = attribute['value']
if isinstance(value, datetime):
self.assertEqual(
self._datetime_from_str(custom_properties.value).timestamp(),
value.timestamp()
)
else:
self.assertEqual(custom_properties.value, value)
def _check_destination_address(self, properties, category='ipv4-addr'):
self.assertEqual(properties.category, category)
self.assertFalse(properties.is_source)
self.assertTrue(properties.is_destination)
def _check_domain_ip_observables(self, observables, attributes):
self.assertEqual(len(observables), len(attributes))
domain, ip = attributes
domain_observable, ip_observable = observables
domain_properties = self._check_observable_features(domain_observable, domain, "DomainName")
self.assertEqual(domain_properties.value.value, domain['value'])
ip_properties = self._check_observable_features(ip_observable, ip, 'Address')
self.assertEqual(ip_properties.address_value.value, ip['value'])
def _check_email_properties(self, properties, related_objects, attributes):
from_, from_dn, to_, to_dn, cc1, cc1_dn, cc2, cc2_dn, bcc, bcc_dn, reply_to, subject, attachment1, attachment2, x_mailer, user_agent, boundary, message_id = attributes
header = properties.header
self.assertEqual(header.from_.address_value.value, from_['value'])
self.assertEqual(len(header.to), 1)
self.assertEqual(header.to[0].address_value.value, to_['value'])
self.assertEqual(len(header.cc), 2)
self.assertEqual(header.cc[0].address_value.value, cc1['value'])
self.assertEqual(header.cc[1].address_value.value, cc2['value'])
self.assertEqual(len(header.bcc), 1)
self.assertEqual(header.bcc[0].address_value.value, bcc['value'])
self.assertEqual(header.reply_to.address_value.value, reply_to['value'])
self.assertEqual(header.subject.value, subject['value'])
self.assertEqual(header.x_mailer.value, x_mailer['value'])
self.assertEqual(header.user_agent.value, user_agent['value'])
self.assertEqual(header.boundary.value, boundary['value'])
self.assertEqual(header.message_id.value, message_id['value'])
attachments = properties.attachments
self.assertEqual(len(attachments), 2)
self.assertEqual(len(related_objects), 2)
for attachment, related_object, attribute in zip(attachments, related_objects, (attachment1, attachment2)):
self.assertEqual(attachment.object_reference, related_object.id_)
self.assertEqual(related_object.relationship, 'Contains')
self.assertEqual(related_object.properties.file_name.value, attribute['value'])
self._check_custom_properties(
(from_dn, to_dn, cc1_dn, cc2_dn, bcc_dn),
properties.custom_properties
)
def _check_embedded_features(self, embedded_object, cluster, name, feature='title'):
self.assertEqual(embedded_object.id_, f"{_ORGNAME_ID}:{name}-{cluster['uuid']}")
self.assertEqual(getattr(embedded_object, feature), cluster['value'])
self.assertEqual(embedded_object.description.value, cluster['description'])
def _check_file_and_pe_properties(self, properties, file_object, pe_object, section_object):
filename, md5, sha1, sha256, size, entropy = file_object['Attribute']
self.assertEqual(properties.file_name.value, filename['value'])
self.assertEqual(properties.size_in_bytes.value, int(size['value']))
self.assertEqual(properties.peak_entropy.value, float(entropy['value']))
self.assertEqual(len(properties.hashes), 3)
for hash_property, attribute in zip(properties.hashes, (md5, sha1, sha256)):
self._check_simple_hash_property(hash_property, attribute['value'], attribute['type'].upper())
self._check_pe_and_section_properties(properties, pe_object, section_object)
def _check_file_observables(self, observables, misp_object):
self.assertEqual(len(observables), 3)
attributes = misp_object['Attribute']
attachment = attributes.pop(6)
malware_sample = attributes.pop(0)
malware_sample_observable, attachment_observable, file_observable = observables
self._check_malware_sample_properties(malware_sample_observable, malware_sample)
self._check_attachment_properties(attachment_observable, attachment)
file_properties = self._check_observable_features(file_observable, misp_object, 'File')
self._check_file_properties(file_properties, attributes, with_artifact=True)
def _check_file_properties(self, properties, attributes, with_artifact=False):
custom_properties = properties.custom_properties
if with_artifact:
filename, md5, sha1, sha256, size, path, encoding, creation, modification = attributes
self._check_custom_properties([encoding], custom_properties)
else:
malware_sample, filename, md5, sha1, sha256, size, attachment, path, encoding, creation, modification = attributes
self._check_custom_properties((malware_sample, attachment, encoding), custom_properties)
self.assertEqual(properties.file_name.value, filename['value'])
self.assertEqual(properties.file_path.value, path['value'])
self.assertEqual(properties.size_in_bytes.value, int(size['value']))
creation_time = creation['value']
if isinstance(creation_time, str):
creation_time = self._datetime_from_str(creation_time)
self.assertEqual(properties.created_time.value, creation_time)
modification_time = modification['value']
if isinstance(modification_time, str):
modification_time = self._datetime_from_str(modification_time)
self.assertEqual(properties.modified_time.value, modification_time)
hashes = properties.hashes
self.assertEqual(len(hashes), 3)
for hash_property, attribute in zip(hashes, (md5, sha1, sha256)):
self._check_simple_hash_property(hash_property, attribute['value'], attribute['type'].upper())
def _check_fuzzy_hash_property(self, hash_property, value, hash_type):
self.assertEqual(hash_property.type_.value, hash_type)
self.assertEqual(hash_property.fuzzy_hash_value.value, value)
def _check_identity_features(self, identity, attribute):
self.assertEqual(identity.id_, f"{_ORGNAME_ID}:Identity-{attribute['uuid']}")
self.assertEqual(identity.name, f"{attribute['category']}: {attribute['value']} (MISP Attribute)")
def _check_indicator_attribute_features(self, related_indicator, attribute, orgc):
self.assertEqual(related_indicator.relationship, attribute['category'])
indicator = related_indicator.item
self.assertEqual(indicator.id_, f"{_ORGNAME_ID}:Indicator-{attribute['uuid']}")
self.assertEqual(indicator.title, f"{attribute['category']}: {attribute['value']} (MISP Attribute)")
self.assertEqual(indicator.description.value, attribute['comment'])
timestamp = attribute['timestamp']
if isinstance(timestamp, str):
self.assertEqual(
self._get_utc_timestamp(indicator.timestamp),
int(timestamp)
)
else:
self.assertEqual(indicator.timestamp, timestamp)
self.assertEqual(indicator.producer.identity.name, orgc)
return indicator
def _check_indicator_object_features(self, related_indicator, misp_object, orgc):
self.assertEqual(related_indicator.relationship, misp_object['meta-category'])
indicator = related_indicator.item
self.assertEqual(indicator.id_, f"{_ORGNAME_ID}:Indicator-{misp_object['uuid']}")
self.assertEqual(indicator.title, f"{misp_object['meta-category']}: {misp_object['name']} (MISP Object)")
self.assertEqual(indicator.description.value, misp_object['description'])
timestamp = misp_object['timestamp']
if isinstance(timestamp, str):
self.assertEqual(
self._get_utc_timestamp(indicator.timestamp),
int(timestamp)
)
else:
self.assertEqual(indicator.timestamp, timestamp)
self.assertEqual(indicator.producer.identity.name, orgc)
return indicator
def _check_ip_port_observables(self, observables, misp_object):
attributes = misp_object['Attribute']
self.assertEqual(len(observables), len(attributes) - 1)
ip, port, domain, _ = attributes
ip_observable, port_observable, domain_observable = observables
ip_properties = self._check_observable_features(ip_observable, ip, 'Address')
self.assertEqual(ip_properties.address_value.value, ip['value'])
self.assertEqual(port_observable.id_, f"{_ORGNAME_ID}:Observable-{port['uuid']}")
port_object = port_observable.object_
self.assertEqual(port_object.id_, f"{_ORGNAME_ID}:dstPort-{port['uuid']}")
port_properties = port_object.properties
self.assertEqual(port_properties._XSI_TYPE, 'PortObjectType')
self.assertEqual(port_properties.port_value.value, int(port['value']))
domain_properties = self._check_observable_features(domain_observable, domain, "DomainName")
self.assertEqual(domain_properties.value.value, domain['value'])
def _check_malware_sample_properties(self, observable, attribute):
filename, md5 = attribute['value'].split('|')
self.assertEqual(observable.title, filename)
properties = self._check_observable_features(observable, attribute, 'Artifact')
data = attribute['data']
if not isinstance(data, str):
data = b64encode(data.getvalue()).decode()
self.assertEqual(properties.raw_artifact.value, data)
self._check_simple_hash_property(properties.hashes[0], md5, 'MD5')
def _check_mutex_properties(self, properties, attributes):
name, *custom_attributes = attributes
self.assertEqual(properties.name, name['value'])
self._check_custom_properties(custom_attributes, properties.custom_properties)
def _check_network_connection_properties(self, properties, attributes):
ip_src, ip_dst, src_port, dst_port, hostname, layer3, layer4, layer7 = attributes
src_socket = properties.source_socket_address
self.assertEqual(src_socket.ip_address.address_value.value, ip_src['value'])
self.assertEqual(src_socket.port.port_value.value, int(src_port['value']))
dst_socket = properties.destination_socket_address
self.assertEqual(dst_socket.ip_address.address_value.value, ip_dst['value'])
self.assertEqual(dst_socket.hostname.hostname_value.value, hostname['value'])
self.assertEqual(dst_socket.port.port_value.value, int(dst_port['value']))
self.assertEqual(properties.layer3_protocol.value, layer3['value'])
self.assertEqual(properties.layer4_protocol.value, layer4['value'])
self.assertEqual(properties.layer7_protocol.value, layer7['value'])
def _check_network_socket_properties(self, properties, attributes):
ip_src, ip_dst, src_port, dst_port, hostname, address, domain, type_, state, protocol = attributes
src_socket = properties.local_address
self.assertEqual(src_socket.ip_address.address_value.value, ip_src['value'])
self.assertEqual(src_socket.port.port_value.value, int(src_port['value']))
dst_socket = properties.remote_address
self.assertEqual(dst_socket.ip_address.address_value.value, ip_dst['value'])
self.assertEqual(dst_socket.hostname.hostname_value.value, hostname['value'])
self.assertEqual(dst_socket.port.port_value.value, int(dst_port['value']))
self.assertEqual(properties.address_family.value, address['value'])
self.assertEqual(properties.domain.value, domain['value'])
self.assertEqual(properties.type_.value, type_['value'])
self.assertEqual(properties.protocol.value, protocol['value'])
self.assertEqual(getattr(properties, f"is_{state['value']}"), True)
def _check_observable_features(self, observable, attribute, name):
self.assertEqual(observable.id_, f"{_ORGNAME_ID}:Observable-{attribute['uuid']}")
observable_object = observable.object_
try:
self.assertEqual(
observable_object.id_,
f"{_ORGNAME_ID}:{name}-{attribute['uuid']}"
)
self.assertEqual(
observable_object.properties._XSI_TYPE,
f'{name}ObjectType'
)
except AssertionError:
self.assertEqual(
observable_object.id_,
f"{_ORGNAME_ID}:Custom-{attribute['uuid']}"
)
self.assertEqual(
observable_object.properties._XSI_TYPE,
'CustomObjectType'
)
return observable_object.properties
def _check_pe_and_section_properties(self, properties, pe_object, section_object):
type_, compilation, entrypoint, original, internal, description, fileversion, langid, productname, productversion, companyname, copyright, sections, imphash, impfuzzy = pe_object['Attribute']
self.assertEqual(properties.type_.value, type_['value'])
headers = properties.headers
self.assertEqual(headers.optional_header.address_of_entry_point.value, entrypoint['value'])
file_header = headers.file_header
self.assertEqual(file_header.number_of_sections.value, int(sections['value']))
self.assertEqual(len(file_header.hashes), 2)
for hash_property, attribute in zip(file_header.hashes, (imphash, impfuzzy)):
self.assertEqual(hash_property.simple_hash_value.value, attribute['value'])
resource = properties.resources[0]
self.assertEqual(resource.companyname.value, companyname['value'])
self.assertEqual(resource.filedescription.value, description['value'])
self.assertEqual(resource.fileversion.value, fileversion['value'])
self.assertEqual(resource.internalname.value, internal['value'])
self.assertEqual(resource.langid.value, langid['value'])
self.assertEqual(resource.legalcopyright.value, copyright['value'])
self.assertEqual(resource.originalfilename.value, original['value'])
self.assertEqual(resource.productname.value, productname['value'])
self.assertEqual(resource.productversion.value, productversion['value'])
self._check_custom_properties([compilation], properties.custom_properties)
name, size, entropy, md5, sha1, sha256, sha512, ssdeep = section_object['Attribute']
self.assertEqual(len(properties.sections), 1)
section = properties.sections[0]
self.assertEqual(section.entropy.value, float(entropy['value']))
section_header = section.section_header
self.assertEqual(section_header.name.value, name['value'])
self.assertEqual(section_header.size_of_raw_data.value, size['value'])
hashes = section.data_hashes
attributes = (md5, sha1, sha256, sha512)
md5_hash, sha1_hash, sha256_hash, sha512_hash, ssdeep_hash = hashes
hashes = (md5_hash, sha1_hash, sha256_hash, sha512_hash)
for hash_property, attribute in zip(hashes, attributes):
self._check_simple_hash_property(hash_property, attribute['value'], attribute['type'].upper())
self._check_fuzzy_hash_property(ssdeep_hash, ssdeep['value'], ssdeep['type'].upper())
def _check_process_properties(self, properties, attributes):
pid, child, parent, name, image, parent_image, port, _ = attributes
self.assertEqual(properties.pid.value, int(pid['value']))
self.assertEqual(properties.parent_pid.value, int(parent['value']))
self.assertEqual(properties.name.value, name['value'])
self.assertEqual(len(properties.child_pid_list), 1)
self.assertEqual(properties.child_pid_list[0].value, int(child['value']))
self.assertEqual(properties.image_info.file_name.value, image['value'])
self.assertEqual(len(properties.port_list), 1)
self.assertEqual(properties.port_list[0].port_value.value, int(port['value']))
self.assertEqual(properties.is_hidden, True)
self._check_custom_properties([parent_image], properties.custom_properties)
def _check_registry_key_properties(self, properties, attributes):
regkey, hive, name, data, datatype, modified = attributes
self.assertEqual(properties.key.value, regkey['value'])
self.assertEqual(properties.hive.value, misp_reghive[hive['value'].lstrip('\\').upper()])
values = properties.values
self.assertEqual(len(values), 1)
key_value = values.value[0]
self.assertEqual(key_value.name.value, name['value'])
self.assertEqual(key_value.data.value, data['value'])
self.assertEqual(key_value.datatype.value, datatype['value'])
modified_value = modified['value']
if isinstance(modified_value, str):
modified_value = self._datetime_from_str(modified_value)
self.assertEqual(properties.modified_time.value, modified_value)
def _check_related_object(self, related_ttp, galaxy_name, cluster_uuid, timestamp=None, object_type='TTP'):
self.assertEqual(related_ttp.relationship.value, galaxy_name)
self.assertEqual(related_ttp.item.idref, f"{_ORGNAME_ID}:{object_type}-{cluster_uuid}")
if timestamp is not None:
if isinstance(timestamp, str):
self.assertEqual(
related_ttp.item.timestamp,
datetime.fromtimestamp(
int(timestamp), timezone.utc
)
)
else:
self.assertEqual(related_ttp.item.timestamp, timestamp)
def _check_simple_hash_property(self, hash_property, value, hash_type):
self.assertEqual(hash_property.type_.value, hash_type)
self.assertEqual(hash_property.simple_hash_value.value, value)
def _check_source_address(self, properties, category='ipv4-addr'):
self.assertEqual(properties.category, category)
self.assertTrue(properties.is_source)
self.assertFalse(properties.is_destination)
def _check_ttp_fields(self, ttp, uuid, identifier, object_type, timestamp=None):
self.assertEqual(ttp.id_, f"{_ORGNAME_ID}:TTP-{uuid}")
self.assertEqual(ttp.title, f"{identifier} (MISP {object_type})")
if timestamp is not None:
if isinstance(timestamp, str):
self.assertEqual(
ttp.timestamp,
datetime.fromtimestamp(
int(timestamp), timezone.utc
)
)
else:
self.assertEqual(ttp.timestamp, timestamp)
def _check_ttp_fields_from_attribute(self, stix_package, attribute):
ttp = self._check_ttp_length(stix_package, 1)[0]
self._check_ttp_fields(
ttp,
attribute['uuid'],
f"{attribute['category']}: {attribute['value']}",
'Attribute',
timestamp=attribute['timestamp']
)
return ttp
def _check_ttp_fields_from_galaxy(self, stix_package, cluster_uuid, galaxy_name):
ttp = self._check_ttp_length(stix_package, 1)[0]
self._check_ttp_fields(ttp, cluster_uuid, galaxy_name, 'Galaxy')
return ttp
def _check_ttp_fields_from_object(self, stix_package, misp_object):
ttp = self._check_ttp_length(stix_package, 1)[0]
self._check_ttp_fields(
ttp,
misp_object['uuid'],
f"{misp_object['meta-category']}: {misp_object['name']}",
'Object',
timestamp=misp_object['timestamp']
)
return ttp
def _check_ttp_length(self, stix_package, length):
self.assertEqual(len(stix_package.ttps.ttp), length)
return stix_package.ttps.ttp
def _check_ttps_from_galaxies(self, stix_package, uuids, names):
ttps = self._check_ttp_length(stix_package, len(uuids))
for ttp, uuid, name in zip(ttps, uuids, names):
self._check_ttp_fields(ttp, uuid, name, 'Galaxy')
return ttps
def _check_url_observables(self, observables, misp_object):
attributes = misp_object['Attribute']
self.assertEqual(len(observables), len(attributes))
url, domain, hostname, ip, port = attributes
url_observable, domain_observable, hostname_observable, ip_observable, port_observable = observables
url_properties = self._check_observable_features(url_observable, url, 'URI')
self.assertEqual(url_properties.value.value, url['value'])
domain_properties = self._check_observable_features(domain_observable, domain, 'DomainName')
self.assertEqual(domain_properties.value.value, domain['value'])
hostname_properties = self._check_observable_features(hostname_observable, hostname, 'Hostname')
self.assertEqual(hostname_properties.hostname_value.value, hostname['value'])
ip_properties = self._check_observable_features(ip_observable, ip, 'Address')
self.assertEqual(ip_properties.address_value.value, ip['value'])
port_properties = self._check_observable_features(port_observable, port, 'Port')
self.assertEqual(port_properties.port_value.value, int(port['value']))
def _check_unix_user_account_properties(self, properties, attributes):
username, user_id, display_name, password, group1, group2, group_id, home_dir, avatar, _ = attributes
self.assertEqual(properties.username.value, username['value'])
self.assertEqual(properties.full_name.value, display_name['value'])
self.assertEqual(len(properties.authentication), 1)
authentication = properties.authentication[0]
self.assertEqual(authentication.authentication_type.value, 'password')
self.assertEqual(authentication.authentication_data.value, password['value'])
self.assertEqual(properties.group_id.value, int(group_id['value']))
self.assertEqual(properties.home_directory.value, home_dir['value'])
self._check_custom_properties(
(avatar, user_id, group1, group2),
properties.custom_properties
)
def _check_user_account_properties(self, properties, attributes):
username, user_id, display_name, password, group1, group2, group_id, home_dir, avatar = attributes
self.assertEqual(properties.username.value, username['value'])
self.assertEqual(properties.full_name.value, display_name['value'])
self.assertEqual(len(properties.authentication), 1)
authentication = properties.authentication[0]
self.assertEqual(authentication.authentication_type.value, 'password')
self.assertEqual(authentication.authentication_data.value, password['value'])
self.assertEqual(properties.home_directory.value, home_dir['value'])
self._check_custom_properties(
(user_id, group1, group2, group_id, avatar),
properties.custom_properties
)
def _check_windows_user_account_properties(self, properties, attributes):
username, user_id, display_name, password, group1, group2, group_id, home_dir, avatar, account_type = attributes
self.assertEqual(properties.username.value, username['value'])
self.assertEqual(properties.security_id.value, user_id['value'])
self.assertEqual(properties.full_name.value, display_name['value'])
self.assertEqual(len(properties.authentication), 1)
authentication = properties.authentication[0]
self.assertEqual(authentication.authentication_type.value, 'password')
self.assertEqual(authentication.authentication_data.value, password['value'])
self.assertEqual(properties.home_directory.value, home_dir['value'])
group_list = properties.group_list
self.assertEqual(len(group_list), 2)
group1_properties, group2_properties = group_list
self.assertEqual(group1_properties.name.value, group1['value'])
self.assertEqual(group2_properties.name.value, group2['value'])
self._check_custom_properties(
(group_id, avatar, account_type),
properties.custom_properties
)
def _check_whois_properties(self, properties, attributes):
registrar, email, org, name, phone, creation, modification, expiration, domain, nameserver, ip = attributes
self.assertEqual(properties.registrar_info.name.value, registrar['value'])
registrants = properties.registrants
self.assertEqual(len(registrants), 1)
registrant = registrants[0]
self.assertEqual(registrant.email_address.address_value.value, email['value'])
self.assertEqual(registrant.organization.value, org['value'])
self.assertEqual(registrant.name.value, name['value'])
self.assertEqual(registrant.phone_number.value, phone['value'])
creation_value = creation['value']
if isinstance(creation_value, str):
creation_value = self._datetime_from_str(creation_value)
self.assertEqual(properties.creation_date.value, creation_value.date())
modification_value = modification['value']
if isinstance(modification_value, str):
modification_value = self._datetime_from_str(modification_value)
self.assertEqual(properties.updated_date.value, modification_value.date())
expiration_value = expiration['value']
if isinstance(expiration_value, str):
expiration_value = self._datetime_from_str(expiration_value)
self.assertEqual(properties.expiration_date.value, expiration_value.date())
self.assertEqual(properties.domain_name.value.value, domain['value'])
nameservers = properties.nameservers
self.assertEqual(len(nameservers), 1)
self.assertEqual(nameservers[0].value.value, nameserver['value'])
self.assertEqual(properties.ip_address.address_value.value, ip['value'])
def _check_x509_properties(self, properties, attributes):
issuer, pem, pubkey_algo, exponent, modulus, serial, signature_algo, subject, before, after, version, md5, sha1 = attributes
certificate = properties.certificate
self.assertEqual(certificate.issuer.value, issuer['value'])
self.assertEqual(certificate.serial_number.value, serial['value'])
self.assertEqual(certificate.signature_algorithm.value, signature_algo['value'])
self.assertEqual(certificate.subject.value, subject['value'])
self.assertEqual(certificate.version.value, int(version['value']))
validity = certificate.validity
before_value = before['value']
if isinstance(before_value, str):
before_value = self._datetime_from_str(before_value)
self.assertEqual(validity.not_before.value, before_value)
after_value = after['value']
if isinstance(after_value, str):
after_value = self._datetime_from_str(after_value)
self.assertEqual(validity.not_after.value, after_value)
pubkey = certificate.subject_public_key
self.assertEqual(pubkey.public_key_algorithm.value, pubkey_algo['value'])
rsa_pubkey = pubkey.rsa_public_key
self.assertEqual(rsa_pubkey.exponent.value, int(exponent['value']))
self.assertEqual(rsa_pubkey.modulus.value, modulus['value'])
self.assertEqual(properties.raw_certificate.value, pem['value'])
signature = properties.certificate_signature
self.assertEqual(signature.signature_algorithm.value, 'SHA1')
self.assertEqual(signature.signature.value, sha1['value'])
self._check_custom_properties([md5], properties.custom_properties)
@staticmethod
def _date_to_str(date_value):
return datetime.strftime(date_value, '%Y-%m-%d')
@staticmethod
def _get_marking_value(marking):
if marking._XSI_TYPE == 'tlpMarking:TLPMarkingStructureType':
return marking.color
return marking.statement
@staticmethod
def _get_test_printing(stix_object):
return stix_object.to_xml(include_namespaces=False).decode().replace('"', '\"').encode()
@staticmethod
def _get_utc_timestamp(dtime):
return int(dtime.replace(tzinfo=timezone.utc).timestamp())
@staticmethod
def _parse_tag(tag_name):
if tag_name.startswith('tlp:'):
return tag_name.split(':')[1].upper()
return tag_name
@staticmethod
def _remove_ids_flags(event):
for misp_object in event['Object']:
for attribute in misp_object['Attribute']:
attribute['to_ids'] = False
def _run_composition_from_indicator_object_tests(self, event):
self._add_ids_flag(event)
misp_object = deepcopy(event['Object'][0])
orgc = event['Orgc']['name']
self.parser.parse_misp_event(event)
incident = self.parser.stix_package.incidents[0]
related_indicator = incident.related_indicators.indicator[0]
indicator = self._check_indicator_object_features(related_indicator, misp_object, orgc)
observables = indicator.observable.observable_composition.observables
return observables, misp_object
def _run_composition_from_observable_object_tests(self, event):
self._remove_ids_flags(event)
misp_object = deepcopy(event['Object'][0])
self.parser.parse_misp_event(event)
incident = self.parser.stix_package.incidents[0]
observable = incident.related_observables.observable[0]
prefix = f"{_ORGNAME_ID}:{misp_object['name']}"
self.assertEqual(
observable.item.id_,
f"{prefix}_ObservableComposition-{misp_object['uuid']}"
)
observables = observable.item.observable_composition.observables
return observables, misp_object
def _run_indicator_from_object_tests(self, event, object_type):
self._add_ids_flag(event)
misp_object = deepcopy(event['Object'][0])
orgc = event['Orgc']['name']
self.parser.parse_misp_event(event)
incident = self.parser.stix_package.incidents[0]
related_indicator = incident.related_indicators.indicator[0]
indicator = self._check_indicator_object_features(
related_indicator,
misp_object,
orgc
)
properties = self._check_observable_features(
indicator.observable,
misp_object,
object_type
)
return properties, misp_object['Attribute']
def _run_indicator_from_objects_tests(self, event, object_type):
self._add_ids_flag(event)
misp_objects = deepcopy(event['Object'])
orgc = event['Orgc']['name']
self.parser.parse_misp_event(event)
incident = self.parser.stix_package.incidents[0]
related_indicator = incident.related_indicators.indicator[0]
indicator = self._check_indicator_object_features(
related_indicator,
misp_objects[0],
orgc
)
properties = self._check_observable_features(
indicator.observable,
misp_objects[0],
object_type
)
return properties, misp_objects
def _run_indicator_tests(self, event, object_type):
attribute = event['Attribute'][0]
orgc = event['Orgc']['name']
self.parser.parse_misp_event(event)
incident = self.parser.stix_package.incidents[0]
related_indicator = incident.related_indicators.indicator[0]
indicator = self._check_indicator_attribute_features(
related_indicator,
attribute,
orgc
)
properties = self._check_observable_features(
indicator.observable,
attribute,
object_type
)
return properties, attribute
def _run_indicators_tests(self, event, object_type):
attributes = event['Attribute']
orgc = event['Orgc']['name']
self.parser.parse_misp_event(event)
incident = self.parser.stix_package.incidents[0]
related_indicators = incident.related_indicators.indicator
properties = []
for related, attribute in zip(related_indicators, attributes):
indicator = self._check_indicator_attribute_features(
related,
attribute,
orgc
)
properties.append(
self._check_observable_features(
indicator.observable,
attribute,
object_type
)
)
return properties, attributes
def _run_observable_from_object_tests(self, event, object_type):
self._remove_ids_flags(event)
misp_object = deepcopy(event['Object'][0])
self.parser.parse_misp_event(event)
incident = self.parser.stix_package.incidents[0]
observable = incident.related_observables.observable[0]
self.assertEqual(observable.relationship, misp_object['meta-category'])
properties = self._check_observable_features(
observable.item,
misp_object,
object_type
)
return properties, misp_object['Attribute']
def _run_observable_from_objects_tests(self, event, object_type):
self._remove_ids_flags(event)
misp_objects = deepcopy(event['Object'])
self.parser.parse_misp_event(event)
incident = self.parser.stix_package.incidents[0]
observable = incident.related_observables.observable[0]
self.assertEqual(observable.relationship, misp_objects[0]['meta-category'])
properties = self._check_observable_features(
observable.item,
misp_objects[0],
object_type
)
return properties, misp_objects
def _run_observable_tests(self, event, object_type):
attribute = event['Attribute'][0]
self.parser.parse_misp_event(event)
incident = self.parser.stix_package.incidents[0]
observable = incident.related_observables.observable[0]
self.assertEqual(observable.relationship, attribute['category'])
properties = self._check_observable_features(
observable.item,
attribute,
object_type
)
return properties, attribute
def _run_observables_tests(self, event, object_type):
attributes = event['Attribute']
self.parser.parse_misp_event(event)
incident = self.parser.stix_package.incidents[0]
related_observables = incident.related_observables.observable
properties = []
for related, attribute in zip(related_observables, attributes):
self.assertEqual(related.relationship, attribute['category'])
properties.append(
self._check_observable_features(related.item, attribute, object_type)
)
return properties, attributes
################################################################################
# EVENT FIELDS TESTS #
################################################################################
def _test_base_event(self, version, event):
uuid = event['uuid']
info = event['info']
self.parser.parse_misp_event(event)
stix_package = self.parser.stix_package
self.assertEqual(stix_package.id_, f"{_ORGNAME_ID}:STIXPackage-{uuid}")
timestamp = event['timestamp']
if isinstance(timestamp, str):
self.assertEqual(
self._get_utc_timestamp(stix_package.timestamp),
int(event['timestamp'])
)
else:
self.assertEqual(stix_package.timestamp, timestamp)
self.assertEqual(stix_package.version, version)
self.assertEqual(stix_package.stix_header.title, f"Export from {_DEFAULT_ORGNAME}'s MISP")
incident = stix_package.incidents[0]
self.assertEqual(incident.id_, f"{_ORGNAME_ID}:Incident-{uuid}")
self.assertEqual(incident.title, info)
self.assertEqual(incident.information_source.identity.name, _DEFAULT_ORGNAME)
self.assertEqual(incident.reporter.identity.name, _DEFAULT_ORGNAME)
def _test_event_with_attribute_confidence_tags(self, event):
domain, campaign_name, vulnerability, _ = event['Attribute']
self.parser.parse_misp_event(event)
incident = self.parser.stix_package.incidents[0]
self.assertEqual(incident.confidence.value, 'Medium')
marking = incident.handling[0]
self.assertEqual(len(marking.marking_structures), 3)
self.assertEqual(
tuple(self._parse_tag(tag['name']) for tag in event['Tag']),
tuple(self._get_marking_value(marking) for marking in marking.marking_structures)
)
campaign = self.parser.stix_package.campaigns[0]
self.assertEqual(campaign.confidence.value, 'Medium')
campaign_marking = campaign.handling[0]
self.assertEqual(len(campaign_marking.marking_structures), 3)
self.assertEqual(
tuple(self._parse_tag(tag['name']) for tag in campaign_name['Tag']),
tuple(self._get_marking_value(marking) for marking in campaign_marking.marking_structures)
)
indicator = incident.related_indicators.indicator[0].item
self.assertEqual(indicator.confidence.value, 'Medium')
indicator_marking = indicator.handling[0]
self.assertEqual(len(indicator_marking.marking_structures), 3)
self.assertEqual(
tuple(self._parse_tag(tag['name']) for tag in domain['Tag']),
tuple(self._get_marking_value(marking) for marking in indicator_marking.marking_structures)
)
observable = incident.related_observables.observable[0].item
self.assertFalse(hasattr(observable, 'confidence'))
self.assertFalse(hasattr(observable, 'handling'))
ttp = self.parser.stix_package.ttps.ttp[0]
self.assertFalse(hasattr(ttp, 'confidence'))
vulnerability_marking = ttp.handling[0]
self.assertEqual(len(vulnerability_marking.marking_structures), 3)
self.assertEqual(
tuple(self._parse_tag(tag['name']) for tag in vulnerability['Tag']),
tuple(self._get_marking_value(marking) for marking in vulnerability_marking.marking_structures)
)
def _test_event_with_object_confidence_tags(self, event):
ip_port, course_of_action, _ = event['Object']
self.parser.parse_misp_event(event)
incident = self.parser.stix_package.incidents[0]
self.assertEqual(incident.confidence.value, 'High')
marking = incident.handling[0]
self.assertEqual(len(marking.marking_structures), 3)
self.assertEqual(
tuple(self._parse_tag(tag['name']) for tag in event['Tag']),
tuple(self._get_marking_value(marking) for marking in marking.marking_structures)
)
indicator = incident.related_indicators.indicator[0].item
self.assertEqual(indicator.confidence.value, 'High')
indicator_marking = indicator.handling[0]
self.assertEqual(len(indicator_marking.marking_structures), 3)
self.assertEqual(
set(self._parse_tag(attr['Tag'][0]['name']) for attr in ip_port['Attribute'][:3]),
set(self._get_marking_value(marking) for marking in indicator_marking.marking_structures)
)
coa = self.parser.stix_package.courses_of_action[0]
self.assertFalse(hasattr(coa, 'confidence'))
coa_marking = coa.handling[0]
self.assertEqual(len(coa_marking.marking_structures), 3)
self.assertEqual(
set(self._parse_tag(attr['Tag'][0]['name']) for attr in course_of_action['Attribute'][:3]),
set(self._get_marking_value(marking) for marking in coa_marking.marking_structures)
)
observable = incident.related_observables.observable[0].item
self.assertFalse(hasattr(observable, 'confidence'))
self.assertFalse(hasattr(observable, 'handling'))
def _test_event_with_tags(self, event):
self.parser.parse_misp_event(event)
marking = self.parser.stix_package.incidents[0].handling[0]
self.assertEqual(len(marking.marking_structures), 3)
markings = tuple(self._get_marking_value(marking) for marking in marking.marking_structures)
self.assertIn('WHITE', markings)
self.assertIn('misp:tool="misp2stix"', markings)
self.assertIn('misp-galaxy:mitre-attack-pattern="Code Signing - T1116"', markings)
def _test_published_event(self, event):
self.parser.parse_misp_event(event)
incident = self.parser.stix_package.incidents[0]
timestamp = event['timestamp']
if isinstance(timestamp, str):
self.assertEqual(
self._get_utc_timestamp(incident.timestamp),
int(timestamp)
)
else:
self.assertEqual(incident.timestamp, timestamp)
date_value = event['date']
if not isinstance(date_value, str):
date_value = self._date_to_str(date_value)
self.assertEqual(
incident.time.incident_discovery.value.strftime("%Y-%m-%d"),
date_value
)
publish_timestamp = event['publish_timestamp']
if isinstance(publish_timestamp, str):
self.assertEqual(
self._get_utc_timestamp(incident.time.incident_reported.value),
int(publish_timestamp)
)
else:
self.assertEqual(incident.time.incident_reported.value, publish_timestamp)
################################################################################
# SINGLE ATTRIBUTES EXPORT TESTS #
################################################################################
def _test_embedded_indicator_attribute_galaxy(self, event):
attribute = event['Attribute'][0]
ap_galaxy, coa_galaxy, _ = attribute['Galaxy']
ap_cluster = ap_galaxy['GalaxyCluster'][0]
coa_cluster = coa_galaxy['GalaxyCluster'][0]
galaxy = event['Galaxy'][0]
cluster = galaxy['GalaxyCluster'][0]
self.parser.parse_misp_event(event)
stix_package = self.parser.stix_package
malware_ttp, attack_pattern_ttp = self._check_ttps_from_galaxies(
stix_package,
(cluster['uuid'], ap_cluster['uuid']),
(galaxy['name'], ap_galaxy['name'])
)
attack_pattern = attack_pattern_ttp.behavior.attack_patterns[0]
self._check_embedded_features(attack_pattern, ap_cluster, 'AttackPattern')
malware = malware_ttp.behavior.malware_instances[0]
self._check_embedded_features(malware, cluster, 'MalwareInstance')
course_of_action = stix_package.courses_of_action[0]
self._check_embedded_features(course_of_action, coa_cluster, 'CourseOfAction')
incident = stix_package.incidents[0]
self._check_related_object(incident.leveraged_ttps.ttp[0], galaxy['name'], cluster['uuid'])
indicator = incident.related_indicators.indicator[0].item
self._check_related_object(
indicator.indicated_ttps[0],
ap_galaxy['name'],
ap_cluster['uuid']
)
self._check_related_object(
indicator.suggested_coas[0],
coa_galaxy['name'],
coa_cluster['uuid'],
object_type='CourseOfAction'
)
def _test_embedded_non_indicator_attribute_galaxy(self, event):
attribute = event['Attribute'][0]
attribute_galaxy = attribute['Galaxy'][0]
attribute_cluster = attribute_galaxy['GalaxyCluster'][0]
coa_galaxy, malware_galaxy = event['Galaxy']
coa_cluster = coa_galaxy['GalaxyCluster'][0]
malware_cluster = malware_galaxy['GalaxyCluster'][0]
self.parser.parse_misp_event(event)
stix_package = self.parser.stix_package
malware_ttp, attack_pattern_ttp, vulnerability_ttp = self._check_ttp_length(
stix_package,
3
)
self._check_ttp_fields(
attack_pattern_ttp,
attribute_cluster['uuid'],
attribute_galaxy['name'],
'Galaxy'
)
self._check_ttp_fields(
malware_ttp,
malware_cluster['uuid'],
malware_galaxy['name'],
'Galaxy'
)
self._check_ttp_fields(
vulnerability_ttp,
attribute['uuid'],
f"{attribute['category']}: {attribute['value']}",
'Attribute',
timestamp=attribute['timestamp']
)
attack_pattern = attack_pattern_ttp.behavior.attack_patterns[0]