-
-
Notifications
You must be signed in to change notification settings - Fork 462
/
Copy pathmodels.py
226 lines (201 loc) · 7.82 KB
/
models.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
# This file is a part of IntelOwl https://github.com/intelowlproject/IntelOwl
# See the file 'LICENSE' for copying permission.
from logging import getLogger
from typing import Optional
from django.contrib.contenttypes.fields import GenericRelation
from django.core.exceptions import ValidationError
from django.db import models
from api_app.analyzers_manager.constants import (
HashChoices,
ObservableTypes,
TypeChoices,
)
from api_app.analyzers_manager.exceptions import AnalyzerConfigurationException
from api_app.analyzers_manager.queryset import AnalyzerReportQuerySet
from api_app.choices import TLP, PythonModuleBasePaths
from api_app.fields import ChoiceArrayField
from api_app.models import AbstractReport, PythonConfig, PythonModule
logger = getLogger(__name__)
class AnalyzerReport(AbstractReport):
objects = AnalyzerReportQuerySet.as_manager()
config = models.ForeignKey(
"AnalyzerConfig", related_name="reports", null=False, on_delete=models.CASCADE
)
class Meta:
unique_together = [("config", "job")]
indexes = AbstractReport.Meta.indexes
class MimeTypes(models.TextChoices):
# IMPORTANT! in case you update this Enum remember to update also the frontend
WSCRIPT = "application/w-script-file"
JAVASCRIPT1 = "application/javascript"
JAVASCRIPT2 = "application/x-javascript"
JAVASCRIPT3 = "text/javascript"
VB_SCRIPT = "application/x-vbscript"
IQY = "text/x-ms-iqy"
APK = "application/vnd.android.package-archive"
DEX = "application/x-dex"
ONE_NOTE = "application/onenote"
ZIP1 = "application/zip"
ZIP2 = "multipart/x-zip"
JAVA = "application/java-archive"
RTF1 = "text/rtf"
RTF2 = "application/rtf"
SHARED_LIB = "application/x-sharedlib"
EXE = "application/vnd.microsoft.portable-executable"
ELF = "application/x-elf"
OCTET = "application/octet-stream"
PCAP = "application/vnd.tcpdump.pcap"
PDF = "application/pdf"
HTML = "text/html"
PUB = "application/x-mspublisher"
EXCEL_MACRO1 = "application/vnd.ms-excel.addin.macroEnabled"
EXCEL_MACRO2 = "application/vnd.ms-excel.sheet.macroEnabled.12"
EXCEL1 = "application/vnd.ms-excel"
EXCEL2 = "application/excel"
DOC = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
XML1 = "application/xml"
XML2 = "text/xml"
ENCRYPTED = "application/encrypted"
PLAIN = "text/plain"
CSV = "text/csv"
PPTX = "application/vnd.openxmlformats-officedocument.presentationml.presentation"
WORD1 = "application/msword"
WORD2 = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
POWERPOINT = "application/vnd.ms-powerpoint"
OFFICE = "application/vnd.ms-office"
BINARY = "application/x-binary"
MAC1 = "application/x-macbinary"
MAC2 = "application/mac-binary"
MAC3 = "application/x-mach-binary"
COMPRESS1 = "application/x-zip-compressed"
COMPRESS2 = "application/x-compressed"
OUTLOOK = "application/vnd.ms-outlook"
EML = "message/rfc822"
PKCS7 = "application/pkcs7-signature"
XPKCS7 = "application/x-pkcs7-signature"
MIXED = "multipart/mixed"
X_SHELLSCRIPT = "text/x-shellscript"
CRX = "application/x-chrome-extension"
JSON = "application/json"
@classmethod
def _calculate_from_filename(cls, file_name: str) -> Optional["MimeTypes"]:
if file_name.endswith(".js") or file_name.endswith(".jse"):
mimetype = cls.JAVASCRIPT1
elif file_name.endswith(".vbs") or file_name.endswith(".vbe"):
mimetype = cls.VB_SCRIPT
elif file_name.endswith(".iqy"):
mimetype = cls.IQY
elif file_name.endswith(".apk"):
mimetype = cls.APK
elif file_name.endswith(".dex"):
mimetype = cls.DEX
elif file_name.endswith(".one"):
mimetype = cls.ONE_NOTE
else:
return None
return mimetype
@classmethod
def calculate(cls, file_pointer, file_name) -> str:
from magic import from_buffer as magic_from_buffer
mimetype = None
if file_name:
mimetype = cls._calculate_from_filename(file_name)
if mimetype is None:
buffer = file_pointer.read()
mimetype = magic_from_buffer(buffer, mime=True)
logger.debug(f"mimetype is {mimetype}")
try:
mimetype = cls(mimetype)
except ValueError:
logger.info(
f"Unable to valid a {cls.__name__} for mimetype {mimetype}"
f" for file {file_name}"
)
else:
mimetype = mimetype.value
return mimetype
class AnalyzerConfig(PythonConfig):
# generic
type = models.CharField(choices=TypeChoices.choices, null=False, max_length=50)
docker_based = models.BooleanField(null=False, default=False)
maximum_tlp = models.CharField(
null=False, default=TLP.RED, choices=TLP.choices, max_length=50
)
python_module = models.ForeignKey(
PythonModule,
on_delete=models.PROTECT,
related_name="%(class)ss",
limit_choices_to={
"base_path__in": [
PythonModuleBasePaths.FileAnalyzer.value,
PythonModuleBasePaths.ObservableAnalyzer.value,
]
},
)
# obs
observable_supported = ChoiceArrayField(
models.CharField(null=False, choices=ObservableTypes.choices, max_length=30),
default=list,
blank=True,
)
# file
supported_filetypes = ChoiceArrayField(
models.CharField(null=False, max_length=90, choices=MimeTypes.choices),
default=list,
blank=True,
)
run_hash = models.BooleanField(default=False)
run_hash_type = models.CharField(
blank=True, choices=HashChoices.choices, max_length=10
)
not_supported_filetypes = ChoiceArrayField(
models.CharField(null=False, max_length=90, choices=MimeTypes.choices),
default=list,
blank=True,
)
orgs_configuration = GenericRelation(
"api_app.OrganizationPluginConfiguration", related_name="%(class)s"
)
@classmethod
@property
def serializer_class(cls):
from api_app.analyzers_manager.serializers import AnalyzerConfigSerializer
return AnalyzerConfigSerializer
def clean_observable_supported(self):
if self.type == TypeChoices.OBSERVABLE and not self.observable_supported:
raise ValidationError(
"You have to specify at least one type of observable supported"
)
if self.type != TypeChoices.OBSERVABLE and self.observable_supported:
raise ValidationError(
"You can't specify an observable type if you do not support observable"
)
def clean_filetypes(self):
if self.type == TypeChoices.FILE:
if self.supported_filetypes and self.not_supported_filetypes:
raise ValidationError(
"Please specify only one between "
"supported_filetypes and not_supported_filetypes"
)
else:
if self.supported_filetypes or self.not_supported_filetypes:
raise ValidationError(
"You can't specify supported_filetypes or "
"not_supported_filetypes if you do not support files"
)
def clean_run_hash_type(self):
if self.run_hash and not self.run_hash_type:
raise ValidationError("run_hash_type must be populated if run_hash is True")
def clean(self):
super().clean()
self.clean_run_hash_type()
self.clean_observable_supported()
self.clean_filetypes()
@classmethod
@property
def plugin_type(cls) -> str:
return "1"
@classmethod
@property
def config_exception(cls):
return AnalyzerConfigurationException