forked from dod-cyber-crime-center/DC3-MWCP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmetadata.py
2928 lines (2429 loc) · 98.4 KB
/
metadata.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
"""
Schema for reportable metadata.
- Using attrs for easy of use and validation.
"""
import base64
import binascii
import hashlib
import inspect
import io
import json
import logging
import pathlib
import re
import textwrap
import warnings
import ntpath
from enum import IntEnum
import uuid
import typing
from typing import Any, Union, List, Optional, TypeVar, Type, Dict
from stix2 import v21 as stix
import attr
from bitarray import bitarray
import cattr
from defusedxml import ElementTree
import jsonschema_extractor
from pyasn1.codec.der import decoder as asn1_decoder
from pyasn1_modules import rfc2437, rfc2459, pem
from pyasn1.error import PyAsn1Error
import mwcp
from mwcp.exceptions import ValidationError
from mwcp.utils import construct
from mwcp.stix import extensions as stix_extensions
from mwcp.stix.objects import STIXResult
logger = logging.getLogger(__name__)
cattr = cattr.GenConverter()
# Register support for pathlib.
cattr.register_structure_hook(pathlib.Path, lambda d, t: pathlib.Path(d))
cattr.register_unstructure_hook(pathlib.Path, str)
# Register support for enums.
cattr.register_structure_hook(IntEnum, lambda d, t: t[d.upper()] if isinstance(d, str) else t(d))
cattr.register_unstructure_hook(IntEnum, lambda d: None if d is None else d.name)
T = TypeVar("T")
def _cast(value: Any, type_: Type[T]) -> T:
"""
Casts given value to the given type.
Usually uses cattr.structure()
:param value: Value to cast.
:param type_: Type to cast to.
(For things like Union, it will try each type listed
within, until one works.)
:return: Converted value.
"""
# Convert bytes to string, Python 2 style!
if type_ is str and isinstance(value, bytes):
return value.decode("latin1")
# Prevent accidentally casting an integer to bytes.
# Since bytes(some_int) will cause it to create a zero byte string with that many bytes,
# this can stall or crash the process if the integer is large enough.
if type_ is bytes and isinstance(value, int):
raise ValueError("Cannot convert int to bytes.")
if typing.get_origin(type_) is dict:
key_type, value_type = typing.get_args(type_)
return {_cast(key, key_type): _cast(value, value_type) for key, value in value.items()}
# cattr doesn't handle Unions very nicely, so we'll recursively
# handle the innards of Union types instead.
# NOTE: Based on documentation, the cattr devs will eventually provide
# better support for Unions in the future.
if typing.get_origin(type_) is Union:
# First see if value is already one of the types.
if type(value) in type_.__args__:
return value
# Otherwise, attempt to case using types in order they are found in the Union.
for sub_type in type_.__args__:
try:
return _cast(value, sub_type)
except Exception:
continue
raise ValueError("No subtypes matched.")
# Otherwise use cattr
return cattr.structure(value, type_)
def _auto_convert(cls, fields):
"""
Automatically applies type coercion to all fields.
(This also acts as validation)
"""
def converter(field_type):
def _wrapper(v):
if v is None:
return v
try:
return _cast(v, field_type)
except Exception as e:
raise ValidationError(f"Failed to cast {v!r} to {field_type} with error: {e}")
return _wrapper
new_fields = []
for field in fields:
if field.converter is None and field.type:
field = field.evolve(converter=converter(field.type))
new_fields.append(field)
return new_fields
def _camel_to_snake(name):
name = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name)
return re.sub("([a-z0-9])([A-Z])", r"\1_\2", name).lower()
def _strip_null(d: dict) -> dict:
"""
Strips away any entries that have the value None.
"""
new_dict = {}
for key, value in d.items():
if isinstance(value, dict):
value = _strip_null(value)
if value is not None:
new_dict[key] = value
return new_dict
def _flatten_dict(dict_: dict) -> dict:
"""
Flattens given element dictionary into a single level of key/value pairs.
Combines tags into one.
"""
new_dict = {}
for key, value in dict_.items():
if isinstance(value, dict):
value.pop("type", None)
tags = value.pop("tags", None)
value = {
f"{key}.{_key}" if _key in dict_ else _key: _value
for _key, _value in _flatten_dict(value).items()
}
new_dict.update(value)
# Consolidate tags into main dictionary.
if tags:
try:
new_dict["tags"].extend(tags)
except KeyError:
new_dict["tags"] = tags
else:
new_dict[key] = value
# Pop off type.
new_dict.pop("type", None)
return new_dict
# Global configuration for all elements.
config = dict(auto_attribs=True, field_transformer=_auto_convert)
@attr.s(**config)
class Element:
"""
Base class for handling reporting elements.
These should be created using attr for convenience.
"""
tags: List[str] = attr.ib(init=False, factory=list)
_registry = {}
_STIX_NAMESPACE = uuid.UUID("27b16a6a-0f3e-44e2-af1f-4b1c590278f4")
def __init_subclass__(cls, **kwargs):
"""
Registers all subclasses of Element.
"""
typ = cls._type()
if not typ.startswith("_") and typ != "metadata":
if typ in cls._registry:
raise ValueError(f"Metadata element of type {typ} already exists.")
cls._registry[typ] = cls
super().__init_subclass__(**kwargs)
@classmethod
def _all_subclasses(cls):
"""
Returns all registered subclasses of the class, sorted by type.
"""
return [
subclass
for _, subclass in sorted(cls._registry.items())
if issubclass(subclass, cls) and subclass != cls
]
@classmethod
def _get_subclass(cls, type_name: str) -> Optional[Type["Element"]]:
"""
Obtains subclass from given type.
"""
try:
subclass = cls._registry[type_name]
if issubclass(subclass, cls) and subclass != cls:
return subclass
except KeyError:
return
@classmethod
def _type(cls):
"""This function is used to determine name identifier for the """
# By default, type is determined by class name.
return _camel_to_snake(cls.__name__)
@classmethod
def _structure(cls, value: dict) -> "Element":
"""
cattr hook for structuring Element class.
"""
# Determine class to use based on "type" field.
# Then call that class's _structure() function.
type_ = value.pop("type", None)
if type_ and type_ != cls._type():
klass = cls._get_subclass(type_)
if not klass:
raise ValueError(f"Invalid type name: {type_}")
return klass._structure(value)
# Remove None values from dictionary, since that seems to be causing
# cattr (or our autocasting) to convert them to the string "None"
# TODO: Remove when github.com/python-attrs/cattrs/issues/53 is solved.
value = _strip_null(value)
# cattrs doesn't support init=False values, so we need to remove tags and
# then re-add them.
tags = value.pop("tags", [])
ret = cattr.structure_attrs_fromdict(value, cls)
ret.tags = tags
return ret
def _unstructure(self) -> dict:
# Add "type" field to help with serialization.
return {"type": self._type(), **cattr.unstructure_attrs_asdict(self)}
@classmethod
def fields(cls):
return attr.fields(cls)
@classmethod
def _schema(cls, extractor):
"""
Generates schema for this particular Element class.
"""
# First get the short description by looking for the first complete sentence.
description = []
for line in inspect.getdoc(cls).splitlines():
# Stop when we hit an empty line or see variable statements.
if not line or line.startswith(":"):
break
description.append(line.strip())
description = " ".join(description)
schema = {
"title": cls.__name__.strip("_").rstrip("2"),
"description": description,
"type": "object",
"properties": {
# Include the "type" property that gets added dynamically during serialization.
"type": {
"const": cls._type(),
}
},
"additionalProperties": False,
"required": ["type"],
}
for field in cls.fields():
is_required = field.default is not None
# Allow customization within attr metadata field for corner cases.
if "jsonschema" in field.metadata:
sub_schema = field.metadata["jsonschema"]
else:
sub_schema = extractor.extract(field.type)
# Anything not required is nullable.
if not is_required:
if list(sub_schema.keys()) == ["type"]:
if isinstance(sub_schema["type"], list):
if "null" not in sub_schema["type"]:
sub_schema["type"].append("null")
elif sub_schema["type"] != "null":
sub_schema["type"] = [sub_schema["type"], "null"]
elif list(sub_schema.keys()) == ["anyOf"]:
if {"type": "null"} not in sub_schema["anyOf"]:
sub_schema["anyOf"].append({"type": "null"})
else:
sub_schema = {"anyOf": [sub_schema, {"type": "null"}]}
schema["properties"][field.name] = sub_schema
if is_required:
schema["required"].append(field.name)
return schema
@classmethod
def schema(cls) -> dict:
"""
Generates a JSONSchema from the given element.
:return: Dictionary representing the schema.
"""
typing_extractor = jsonschema_extractor.TypingExtractor()
typing_extractor.register(Element, lambda extractor, typ: typ._schema(extractor))
typing_extractor.register(bytes, lambda extractor, typ: {
"type": "string",
"contentEncoding": "base64",
})
# IntEnums are converted to their names before serialization by cattr.
typing_extractor.register(IntEnum, lambda extractor, typ: {
"enum": [c.name for c in typ]
})
extractor = jsonschema_extractor.SchemaExtractorSet([typing_extractor])
return extractor.extract(cls)
@classmethod
def from_dict(cls, obj: dict) -> "Element":
return cattr.structure(obj.copy(), cls)
def as_dict(self, flat=False) -> dict:
ret = cattr.unstructure(self)
if flat:
ret = _flatten_dict(ret)
return ret
def _format_value(self, value):
# Convert bytes to a string representation.
if isinstance(value, bytes):
value = str(value)
if isinstance(value, list):
value = list(map(self._format_value, value))
# Recursively handle nested elements.
if isinstance(value, Element):
value = value.as_formatted_dict()
return value
def as_formatted_dict(self, flat=False) -> dict:
"""
Converts metadata element into a well formatted dictionary usually
used for presenting metadata elements as tabular data.
"""
ret = {}
for field in self.fields():
name = field.name
value = getattr(self, name)
ret[name] = self._format_value(value)
if flat:
ret = _flatten_dict(ret)
return ret
def as_json(self) -> str:
class _JSONEncoder(json.JSONEncoder):
def default(self, o):
# Encode Collection objects using as_dict()
if isinstance(o, Element):
return o.as_dict()
# Encode bytes as base64
if isinstance(o, bytes):
return base64.b64encode(o).decode()
# Convert sets to list
if isinstance(o, set):
return sorted(o)
# Convert UUID
if isinstance(o, uuid.UUID):
return str(o)
return super().default(o)
return json.dumps(self, cls=_JSONEncoder, indent=4)
def as_json_dict(self) -> dict:
"""
Jsonifies the element and then loads it back as a dictionary.
NOTE: This is different from .as_dict() because things like bytes
will be converted to a base64 encoded string.
"""
return json.loads(self.as_json())
def validate(self):
attr.validate(self)
def elements(self) -> List["Element"]:
"""
All elements contained within the given element. (including self)
"""
elements = [self]
for field in self.fields():
value = getattr(self, field.name)
if isinstance(value, Element):
elements.extend(value.elements())
elif isinstance(value, list):
for sub_value in value:
if isinstance(sub_value, Element):
elements.extend(sub_value.elements())
return elements
def post_processing(self, report):
"""
Performs and adds extra additions to the Report when the Element gets created.
:param report: mwcp Report used to add metadata.
"""
def add_tag(self, *tags: str) -> "Element":
"""
Adds a tag for the given metadata.
:param tags: One or more tags to add to the metadata.
:returns: self to make this function chainable.
"""
for tag in tags:
if tag not in self.tags:
self.tags.append(tag)
# Ensure we keep the tags sorted.
self.tags = sorted(self.tags)
return self
# Value may be partially converted
# github.com/python-attrs/cattrs/issues/78
cattr.register_structure_hook(
Element,
lambda value, cls: value if hasattr(value, "__attrs_attrs__") else cls._structure(dict(value))
)
# obj may be None because we don't use Optional in our Typing.
cattr.register_unstructure_hook(Element, lambda obj: None if obj is None else obj._unstructure())
class Metadata(Element):
"""
Represents a collection of reportable metadata attributes that together represent an idea.
This class can be subclassed to create your own reportable metadata element.
"""
@classmethod
def _schema(cls, extractor):
# If we are typing the base Metadata class, this means we want to represent
# all subclasses instead.
if cls == Metadata:
return {"anyOf": [
extractor.extract(subclass) for subclass in Metadata._all_subclasses()
]}
else:
return super()._schema(extractor)
def as_stix(self, base_object, fixed_timestamp=None) -> STIXResult:
"""
Returns STIX content for a class. All metadata objects should implement this, but if one does not a warning will be supplied.
"""
warnings.warn(
"as_stix is not implmeneted by " + type(self).__name__ + " so data may be missing from the result",
UserWarning
)
return STIXResult()
def as_stix_tags(self, parent, fixed_timestamp=None):
"""
Returns an object containing tag information for a given parent assuming there is content
"""
if self.tags:
return stix.Note(
labels=self.tags,
content=f"MWCP Tags: {', '.join(self.tags)}",
object_refs=[parent.id],
created=fixed_timestamp,
modified=fixed_timestamp,
allow_custom=True
)
@attr.s(**config)
class Path2(Metadata):
r"""
Filesystem path used by malware.
Current directory (".") represents the directory of the malware sample that produced this metadata.
e.g.
Path2(r"C:\windows\temp\1\log\keydb.txt", is_dir=False) # pass full path
Path2(r"C:\foo\logs", is_dir=True)
Path2("bar.exe", is_dir=False) # Represents a file name with unknown location
Path2(".\bar.exe", is_dir=False) # Represents a file path within the same directory as the source malware sample.
"""
path: str
is_dir: bool = None
posix: bool = None
file_system: str = None # NTFS, ext4, etc.
def __attrs_post_init__(self):
# If posix wasn't provided, determine this based on presence of drive letter or separator.
if self.posix is None and (self.path.count("\\") or self.path.count("/")):
self.posix = not (re.match("^[A-Z]:\\\\", self.path) or self.path.count("\\") > self.path.count("/"))
@classmethod
def _type(cls):
return "path"
@classmethod
def from_segments(cls, *segments: str, is_dir: bool = None, posix: bool = False, file_system: str = None):
"""
Provides ability to construct a Path from segments.
NOTE: Path is assumed to be Windows if posix flag is not provided.
e.g.
Path2.from_segments("C:", "windows", "temp", "1", "log", "keydb.txt", posix=False, is_dir=False)
"""
if not segments:
raise ValidationError(f"from_segments() requires at least one segment.")
if len(segments) == 1:
return Path2(segments[0], is_dir=is_dir, posix=posix, file_system=file_system)
# Ensure we do not have secondary segments starting with a slash.
# This would cause pathlib's constructor to just take the last absolute path ignored the ones before it.
# Which is something we don't want in this context.
slash = "/" if posix else "\\"
segments = [segments[0], *(segment.lstrip(slash) for segment in segments[1:])]
if posix:
path = pathlib.PurePosixPath(*segments)
else:
segments = list(segments)
# If first segment is a drive, we need to include the \ in order for pathlib to see it as such.
if segments[0].endswith(":"):
segments[0] += "\\"
path = pathlib.PureWindowsPath(*segments)
return cls.from_pathlib_path(path, is_dir=is_dir, file_system=file_system)
@classmethod
def from_pathlib_path(cls, path: pathlib.PurePath, is_dir: bool = None, file_system: str = None):
"""
Generate Path from pathlib.PurePath instance.
"""
return Path2(str(path), is_dir=is_dir, posix=isinstance(path, pathlib.PurePosixPath), file_system=file_system)
@property
def _pathlib_path(self) -> Optional[pathlib.PurePath]:
if self.posix is None:
return None
elif self.posix:
return pathlib.PurePosixPath(self.path)
else:
return pathlib.PureWindowsPath(self.path)
@property
def directory_path(self) -> Optional[str]:
if self.is_dir:
return self.path
else:
path = self._pathlib_path
if path:
return str(path.parent)
else:
return None
@property
def name(self) -> str:
path = self._pathlib_path
if path:
return path.name
else:
return self.path
def as_stix(self, base_object, fixed_timestamp=None) -> STIXResult:
result = STIXResult(fixed_timestamp=fixed_timestamp)
if self.is_dir:
result.add_linked(stix.Directory(path=self.path))
else:
file_data = {}
if self.directory_path:
cur_dir = stix.Directory(path=self.directory_path)
result.add_unlinked(cur_dir)
file_data["parent_directory_ref"] = cur_dir.id
if self.name:
file_data["name"] = self.name
result.add_linked(stix.File(**file_data))
result.create_tag_note(self, result.linked_stix[-1])
return result
def Path(
path: str = None,
directory_path: str = None,
name: str = None,
is_dir: bool = None,
file_system: str = None
) -> Path2:
warnings.warn(
"Path has been renamed to Path2 during a transitional period to a new version of Path "
"with a new signature. "
"Please update to use Path2 which explicitly expects a path string with no directory/name separation."
"NOTE: In a future version, once this function is deprecated, Path2 will be renamed back to Path "
"using the new signature.",
DeprecationWarning
)
# Replicating original logic. (existence of directory_path and name overwrite path)
if directory_path and name:
path = ntpath.join(directory_path, name)
# If a directory_path was provided without a name, overwrite is_dir.
elif directory_path and not name:
path = directory_path
is_dir = True
elif name and not directory_path:
path = name
is_dir = False
return Path2(path, is_dir=is_dir, file_system=file_system)
def Directory(path: str, posix: bool = None) -> Path2:
return Path2(path, posix=posix, is_dir=True)
def FilePath(path: str, posix: bool = None) -> Path2:
return Path2(path, posix=posix, is_dir=False)
def FileName(name: str) -> Path2:
return Path2(name, is_dir=False)
@attr.s(**config)
class Alphabet(Metadata):
"""
Generic baseXX alphabet
"""
alphabet: str = attr.ib()
base: int = attr.ib()
@alphabet.validator
def _validate_alphabet(self, attribute, value):
alphabet = value
base = self.base
if alphabet and base:
if len(alphabet) not in (base, base + 1):
raise ValidationError(
"Invalid alphabet provided: "
"Length of alphabet must be size of base or base + 1 (if including the pad character)."
)
# TODO: Determine if this is a valid.
# if len(alphabet) != len(set(alphabet)):
# raise ValidationError('mapping must be unique')
def as_stix(self, base_object, fixed_timestamp=None) -> STIXResult:
content = f"Alphabet: {self.alphabet}\nAlphabet Base: {self.base}"
if self.tags:
content += f"\n Alphabet Tags: {', '.join(self.tags)}"
return STIXResult(content)
def Base16Alphabet(alphabet: str) -> Alphabet:
"""
Base16 alphabet
e.g.
Base16Alphabet("0123456789ABCDEF")
"""
return Alphabet(alphabet=alphabet, base=16)
def Base32Alphabet(alphabet: str) -> Alphabet:
"""
Base32 alphabet
e.g.
Base32Alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=")
"""
return Alphabet(alphabet=alphabet, base=32)
def Base64Alphabet(alphabet: str) -> Alphabet:
"""
Base64 alphabet
e.g.
Base64Alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=")
"""
return Alphabet(alphabet=alphabet, base=64)
@attr.s(**config)
class Command(Metadata):
"""
Shell command
:var value: The shell command itself.
:var cwd: Working directory where the command would get run (if known).
e.g.
Command("calc.exe")
Command("calc.exe", cwd=r"C:\Windows\System32")
"""
value: str
cwd: str = None
def as_stix(self, base_object, fixed_timestamp=None) -> STIXResult:
# Process generally uses a UUIDv4 but we want to deduplicate when the same command is used so we will use a v5
identifier = "process--" + str(uuid.uuid5(self._STIX_NAMESPACE, f"{self.value}/{self.cwd}"))
result = STIXResult(fixed_timestamp=fixed_timestamp)
result.add_linked(stix.Process(command_line=self.value, cwd=self.cwd, id=identifier))
result.create_tag_note(self, result.linked_stix[-1])
return result
def as_formatted_dict(self, flat=False) -> dict:
return {
"tags": self.tags,
"command": self.value,
"working_directory": self.cwd,
}
@attr.s(**config)
class Credential(Metadata):
"""
Collection of username and password used as credentials.
e.g.
Credential(username="admin", password="123456")
"""
username: str = None
password: str = None
def as_stix(self, base_object, fixed_timestamp=None) -> STIXResult:
result = STIXResult(fixed_timestamp=fixed_timestamp)
params = {}
if self.username:
params["account_login"] = self.username
if self.password:
params["credential"] = self.password
# the default UUIDv5 generation scheme for user-account does not factor in credentials so it is possible
# to overwrite the same username with separate creds
# since we do not want this with MWCP if a password is present will generate the ID in our own deterministic manner
params["id"] = "user-account--" + str(uuid.uuid5(self._STIX_NAMESPACE, f"{self.username}//{self.password}"))
result.add_linked(stix.UserAccount(**params))
result.create_tag_note(self, result.linked_stix[-1])
return result
def Password(password: str) -> Credential:
return Credential(password=password)
def Username(username: str) -> Credential:
return Credential(username=username)
@attr.s(**config)
class CryptoAddress(Metadata):
"""
A cryptocurrency address and its symbol.
:param address: The address or unique identifier of the crypto wallet.
:param symbol: A unique symbol for the cryptocurrency platform.
This is usually the ticker symbol like "BTC", but can be something else more appropriate.
e.g.
# Sample address pulled from bitcoinwiki.org/wiki/Bitcoin_address
CryptoAddress("14qViLJfdGaP4EeHnDyJbEGQysnCpwk3gd", "BTC")
"""
address: str
symbol: str = None
def as_stix(self, base_object, fixed_timestamp=None) -> STIXResult:
result = STIXResult(fixed_timestamp=fixed_timestamp)
params = {
"address": self.address
}
if self.symbol:
params["currency_type"] = self.symbol.lower().replace(" ", "-")
result.add_linked(stix_extensions.CryptoCurrencyAddress(**params))
result.create_tag_note(self, result.linked_stix[-1])
return result
_ActionType = Union[Command, str]
_ActionType = Union[List[_ActionType], _ActionType]
def _action_converter(actions):
# Convenience to allow users to pass in strings or a single command not in a list.
if actions is not None:
if not isinstance(actions, list):
actions = [actions]
actions = [
Command(command) if isinstance(command, str) else command
for command in actions
]
return actions
@attr.s(**config)
class ScheduledTask(Metadata):
"""
A Windows Scheduled task
NOTE: This is currently only covers basic registration info and commands that get run.
Other information such as trigger information is currently not captured.
Please use 'Other' to store other information if desired.
e.g.
ScheduledTask("calc.exe", name="ActiveXServer")
ScheduleTask([Command("calc.exe", cwd=r"C:\Temp"), Command("notepad.exe")], name="LegitWindowsTask")
"""
# TODO: for now we are only accounting for command (Exec) actions.
# Add support for COM, email, and message types.
actions: _ActionType = attr.ib(
default=None,
converter=_action_converter,
metadata={"jsonschema": {
"type": "array",
"items": Command.schema(),
}}
)
name: str = None
description: str = None
author: str = None
credentials: Credential = None
@classmethod
def from_xml(cls, xml_data: str) -> "ScheduledTask":
"""
Creates a ScheduledTask from exported xml file.
Based on https://learn.microsoft.com/en-us/windows/win32/taskschd/task-scheduler-schema
"""
xml_data = xml_data.strip()
# Remove namespace because it makes parsing complex.
xml_data = re.sub(' xmlns="[^"]+"', '', xml_data, count=1)
try:
root = ElementTree.fromstring(xml_data)
except ElementTree.ParseError as e:
raise ValueError(f"Failed to parse XML data: {e}")
if root.tag != "Task":
raise ValueError(f"Expected root tag to be 'Task', got '{root.tag}'")
# Parse registration info
# NOTE: Must check with 'is None' because truthiness is still False with .find() for some reason.
description = None
author = None
if (registration := root.find("RegistrationInfo")) is not None:
if (description := registration.find("Description")) is not None:
description = description.text
if (author := registration.find("Author")) is not None:
author = author.text
# Parse commands.
actions_meta = []
if (actions := root.find("Actions")) is not None:
for action in actions.findall("Exec"):
command = action.find("Command")
if command is None:
raise ValueError(f"Expected 'Command' tag.")
command = command.text
if (arguments := action.find("Arguments")) is not None:
command += " " + arguments.text
if (cwd := action.find("WorkingDirectory")) is not None:
cwd = cwd.text
actions_meta.append(Command(command, cwd=cwd))
return cls(actions_meta, description=description, author=author)
def as_formatted_dict(self, flat=False) -> dict:
"""
Formatting in order to collapse the actions.
TODO: Look into doing this generically for list fields.
"""
tags = list(self.tags)
if self.credentials:
tags.extend(self.credentials.tags)
actions = []
for action in self.actions or []:
tags.extend(action.tags)
if action.cwd:
actions.append(f"{action.cwd}> {action.value}")
else:
actions.append(action.value)
return {
"tags": sorted(set(tags)),
"actions": "\n".join(actions),
"name": self.name,
"description": self.description,
"author": self.author,
"username": self.credentials.username if self.credentials else None,
"password": self.credentials.password if self.credentials else None,
}
def as_stix(self, base_object, fixed_timestamp=None) -> STIXResult:
result = STIXResult(fixed_timestamp=fixed_timestamp)
params = {}
if self.name:
params["name"] = self.name
if self.description:
params["description"] = self.description
if self.author:
params["author"] = self.author
if self.credentials:
credentials = self.credentials.as_stix(base_object)
result.merge_ref(credentials)
params["user_account_ref"] = credentials.linked_stix[-1].id
scheduled_task = stix_extensions.ScheduledTask(**params)
result.add_linked(scheduled_task)
result.create_tag_note(self, scheduled_task)
for action in self.actions or []:
action_obj = action.as_stix(base_object)
result.merge(action_obj)
result.add_unlinked(stix.Relationship(
relationship_type="contained",
source_ref=scheduled_task.id,
target_ref=action_obj.linked_stix[-1].id,
created=fixed_timestamp,
modified=fixed_timestamp,
allow_custom=True,
))
return result
@attr.s(**config)
class Socket2(Metadata):
"""
A collection of address, port, and protocol used together to make a socket
connection.
e.g.
Socket(address="bad.com", port=21, protocol="tcp")
"""
_VALID_PROTOCOLS = {"tcp", "udp", "icmp"}
address: str = None # ip address or domain # TODO: should this be split up?
port: int = attr.ib(
default=None,
metadata={"jsonschema": {
"type": "integer",
"minimum": 0,
"maximum": 65535,
}}
)
network_protocol: str = attr.ib(
default=None,
converter=lambda v: str(v).lower() if v is not None else v,
metadata={"jsonschema": {
"enum": sorted(_VALID_PROTOCOLS),
}}
)
listen: bool = None
@classmethod
def _type(cls):
return "socket"
def __attrs_post_init__(self):
# Add the _from_port attribute, used internally for backwards compatibility support.
self._from_port = False
@port.validator
def _validate_port(self, attribute, value):
if value is not None and not 0 <= value <= 65535:
raise ValidationError(f"port must be between 0 and 65535. Got {value}")
@network_protocol.validator
def _validate_protocol(self, attribute, value):
if value is not None and value not in self._VALID_PROTOCOLS: