-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathopencti_course_of_action.py
More file actions
693 lines (670 loc) · 25.2 KB
/
opencti_course_of_action.py
File metadata and controls
693 lines (670 loc) · 25.2 KB
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
# coding: utf-8
import json
import uuid
from stix2.canonicalization.Canonicalize import canonicalize
class CourseOfAction:
"""Main CourseOfAction class for OpenCTI
Manages courses of action (mitigations) in the OpenCTI platform.
:param opencti: instance of :py:class:`~pycti.api.opencti_api_client.OpenCTIApiClient`
:type opencti: OpenCTIApiClient
"""
def __init__(self, opencti):
"""Initialize the CourseOfAction instance.
:param opencti: OpenCTI API client instance
:type opencti: OpenCTIApiClient
"""
self.opencti = opencti
self.properties = """
id
standard_id
entity_type
parent_types
spec_version
created_at
updated_at
status {
id
template {
id
name
color
}
}
createdBy {
... on Identity {
id
standard_id
entity_type
parent_types
spec_version
identity_class
name
description
roles
contact_information
x_opencti_aliases
created
modified
objectLabel {
id
value
color
}
}
... on Organization {
x_opencti_organization_type
x_opencti_reliability
}
... on Individual {
x_opencti_firstname
x_opencti_lastname
}
}
objectOrganization {
id
standard_id
name
}
objectMarking {
id
standard_id
entity_type
definition_type
definition
created
modified
x_opencti_order
x_opencti_color
}
objectLabel {
id
value
color
}
externalReferences {
edges {
node {
id
standard_id
entity_type
source_name
description
url
hash
external_id
created
modified
}
}
}
revoked
confidence
created
modified
name
description
x_opencti_aliases
x_mitre_id
"""
self.properties_with_files = """
id
standard_id
entity_type
parent_types
spec_version
created_at
updated_at
status {
id
template {
id
name
color
}
}
createdBy {
... on Identity {
id
standard_id
entity_type
parent_types
spec_version
identity_class
name
description
roles
contact_information
x_opencti_aliases
created
modified
objectLabel {
id
value
color
}
}
... on Organization {
x_opencti_organization_type
x_opencti_reliability
}
... on Individual {
x_opencti_firstname
x_opencti_lastname
}
}
objectOrganization {
id
standard_id
name
}
objectMarking {
id
standard_id
entity_type
definition_type
definition
created
modified
x_opencti_order
x_opencti_color
}
objectLabel {
id
value
color
}
externalReferences {
edges {
node {
id
standard_id
entity_type
source_name
description
url
hash
external_id
created
modified
importFiles {
edges {
node {
id
name
size
metaData {
mimetype
version
}
}
}
}
}
}
}
revoked
confidence
created
modified
name
description
x_opencti_aliases
x_mitre_id
importFiles {
edges {
node {
id
name
size
metaData {
mimetype
version
}
objectMarking {
id
standard_id
entity_type
definition_type
definition
created
modified
x_opencti_order
x_opencti_color
}
}
}
}
"""
@staticmethod
def generate_id(name, x_mitre_id=None):
"""Generate a STIX ID for a Course of Action.
:param name: The name of the course of action
:type name: str
:param x_mitre_id: Optional MITRE ATT&CK ID
:type x_mitre_id: str or None
:return: STIX ID for the course of action
:rtype: str
"""
if x_mitre_id is not None:
data = {"x_mitre_id": x_mitre_id.strip()}
else:
data = {"name": name.lower().strip()}
data = canonicalize(data, utf8=False)
id = str(uuid.uuid5(uuid.UUID("00abedb4-aa42-466c-9c01-fed23315a9b7"), data))
return "course-of-action--" + id
@staticmethod
def generate_id_from_data(data):
"""Generate a STIX ID from course of action data.
:param data: Dictionary containing 'name' and optionally 'x_mitre_id' keys
:type data: dict
:return: STIX ID for the course of action
:rtype: str
"""
return CourseOfAction.generate_id(data.get("name"), data.get("x_mitre_id"))
def list(self, **kwargs):
"""List Course of Action objects.
:param filters: the filters to apply
:type filters: dict
:param search: the search keyword
:type search: str
:param first: return the first n rows from the after ID (or the beginning if not set)
:type first: int
:param after: ID of the first row for pagination
:type after: str
:param orderBy: field to order results by
:type orderBy: str
:param orderMode: ordering mode (asc/desc)
:type orderMode: str
:param customAttributes: custom attributes to return
:type customAttributes: str
:param getAll: whether to retrieve all results
:type getAll: bool
:param withPagination: whether to include pagination info
:type withPagination: bool
:param withFiles: whether to include files
:type withFiles: bool
:return: List of Course of Action objects
:rtype: list
"""
filters = kwargs.get("filters", None)
search = kwargs.get("search", None)
first = kwargs.get("first", 500)
after = kwargs.get("after", None)
order_by = kwargs.get("orderBy", None)
order_mode = kwargs.get("orderMode", None)
custom_attributes = kwargs.get("customAttributes", None)
get_all = kwargs.get("getAll", False)
with_pagination = kwargs.get("withPagination", False)
with_files = kwargs.get("withFiles", False)
self.opencti.app_logger.info(
"Listing Courses-Of-Action with filters", {"filters": json.dumps(filters)}
)
query = (
"""
query CoursesOfAction($filters: FilterGroup, $search: String, $first: Int, $after: ID, $orderBy: CoursesOfActionOrdering, $orderMode: OrderingMode) {
coursesOfAction(filters: $filters, search: $search, first: $first, after: $after, orderBy: $orderBy, orderMode: $orderMode) {
edges {
node {
"""
+ (
custom_attributes
if custom_attributes is not None
else (self.properties_with_files if with_files else self.properties)
)
+ """
}
}
pageInfo {
startCursor
endCursor
hasNextPage
hasPreviousPage
globalCount
}
}
}
"""
)
result = self.opencti.query(
query,
{
"filters": filters,
"search": search,
"first": first,
"after": after,
"orderBy": order_by,
"orderMode": order_mode,
},
)
if get_all:
final_data = []
data = self.opencti.process_multiple(result["data"]["coursesOfAction"])
final_data = final_data + data
while result["data"]["coursesOfAction"]["pageInfo"]["hasNextPage"]:
after = result["data"]["coursesOfAction"]["pageInfo"]["endCursor"]
self.opencti.app_logger.info(
"Listing Courses-Of-Action", {"after": after}
)
result = self.opencti.query(
query,
{
"filters": filters,
"search": search,
"first": first,
"after": after,
"orderBy": order_by,
"orderMode": order_mode,
},
)
data = self.opencti.process_multiple(result["data"]["coursesOfAction"])
final_data = final_data + data
return final_data
else:
return self.opencti.process_multiple(
result["data"]["coursesOfAction"], with_pagination
)
def read(self, **kwargs):
"""Read a Course of Action object.
:param id: the id of the Course of Action
:type id: str
:param filters: the filters to apply if no id provided
:type filters: dict
:param customAttributes: custom attributes to return
:type customAttributes: str
:param withFiles: whether to include files
:type withFiles: bool
:return: Course of Action object
:rtype: dict or None
"""
id = kwargs.get("id", None)
filters = kwargs.get("filters", None)
custom_attributes = kwargs.get("customAttributes", None)
with_files = kwargs.get("withFiles", False)
if id is not None:
self.opencti.app_logger.info("Reading Course-Of-Action", {"id": id})
query = (
"""
query CourseOfAction($id: String!) {
courseOfAction(id: $id) {
"""
+ (
custom_attributes
if custom_attributes is not None
else (self.properties_with_files if with_files else self.properties)
)
+ """
}
}
"""
)
result = self.opencti.query(query, {"id": id})
return self.opencti.process_multiple_fields(
result["data"]["courseOfAction"]
)
elif filters is not None:
result = self.list(filters=filters)
if len(result) > 0:
return result[0]
else:
return None
else:
self.opencti.app_logger.error(
"[opencti_course_of_action] Missing parameters: id or filters"
)
return None
def create(self, **kwargs):
"""Create a Course of Action object.
:param name: the name of the Course of Action (required)
:type name: str
:param stix_id: (optional) the STIX ID
:type stix_id: str
:param createdBy: (optional) the author ID
:type createdBy: str
:param objectMarking: (optional) list of marking definition IDs
:type objectMarking: list
:param objectLabel: (optional) list of label IDs
:type objectLabel: list
:param externalReferences: (optional) list of external reference IDs
:type externalReferences: list
:param revoked: (optional) whether the course of action is revoked
:type revoked: bool
:param confidence: (optional) confidence level (0-100)
:type confidence: int
:param lang: (optional) language
:type lang: str
:param created: (optional) creation date
:type created: str
:param modified: (optional) modification date
:type modified: str
:param description: (optional) description
:type description: str
:param x_opencti_aliases: (optional) list of aliases
:type x_opencti_aliases: list
:param x_mitre_id: (optional) MITRE ATT&CK ID
:type x_mitre_id: str
:param x_opencti_stix_ids: (optional) list of additional STIX IDs
:type x_opencti_stix_ids: list
:param objectOrganization: (optional) list of organization IDs
:type objectOrganization: list
:param x_opencti_workflow_id: (optional) workflow ID
:type x_opencti_workflow_id: str
:param x_opencti_modified_at: (optional) custom modification date
:type x_opencti_modified_at: str
:param update: (optional) whether to update if exists (default: False)
:type update: bool
:param files: (optional) list of File objects to attach
:type files: list
:param filesMarkings: (optional) list of lists of marking definition IDs for each file
:type filesMarkings: list
:return: Course of Action object
:rtype: dict or None
"""
stix_id = kwargs.get("stix_id", None)
created_by = kwargs.get("createdBy", None)
object_marking = kwargs.get("objectMarking", None)
object_label = kwargs.get("objectLabel", None)
external_references = kwargs.get("externalReferences", None)
revoked = kwargs.get("revoked", None)
confidence = kwargs.get("confidence", None)
lang = kwargs.get("lang", None)
created = kwargs.get("created", None)
modified = kwargs.get("modified", None)
name = kwargs.get("name", None)
description = kwargs.get("description", None)
x_opencti_aliases = kwargs.get("x_opencti_aliases", None)
x_opencti_stix_ids = kwargs.get("x_opencti_stix_ids", None)
x_mitre_id = kwargs.get("x_mitre_id", None)
granted_refs = kwargs.get("objectOrganization", None)
x_opencti_workflow_id = kwargs.get("x_opencti_workflow_id", None)
x_opencti_modified_at = kwargs.get("x_opencti_modified_at", None)
update = kwargs.get("update", False)
files = kwargs.get("files", None)
files_markings = kwargs.get("filesMarkings", None)
files_versions = kwargs.get("filesVersions", None)
no_trigger_import = kwargs.get("noTriggerImport", None)
embedded = kwargs.get("embedded", None)
upsert_operations = kwargs.get("upsert_operations", None)
if name is not None:
self.opencti.app_logger.info("Creating Course Of Action", {"name": name})
query = """
mutation CourseOfActionAdd($input: CourseOfActionAddInput!) {
courseOfActionAdd(input: $input) {
id
standard_id
entity_type
parent_types
}
}
"""
result = self.opencti.query(
query,
{
"input": {
"stix_id": stix_id,
"createdBy": created_by,
"objectMarking": object_marking,
"objectLabel": object_label,
"objectOrganization": granted_refs,
"externalReferences": external_references,
"revoked": revoked,
"confidence": confidence,
"lang": lang,
"created": created,
"modified": modified,
"name": name,
"description": description,
"x_opencti_aliases": x_opencti_aliases,
"x_opencti_stix_ids": x_opencti_stix_ids,
"x_mitre_id": x_mitre_id,
"x_opencti_workflow_id": x_opencti_workflow_id,
"x_opencti_modified_at": x_opencti_modified_at,
"update": update,
"files": files,
"filesMarkings": files_markings,
"filesVersions": files_versions,
"noTriggerImport": no_trigger_import,
"embedded": embedded,
"upsertOperations": upsert_operations,
}
},
)
return self.opencti.process_multiple_fields(
result["data"]["courseOfActionAdd"]
)
else:
self.opencti.app_logger.error(
"[opencti_course_of_action] Missing parameters: name"
)
return None
def import_from_stix2(self, **kwargs):
"""Import a Course of Action object from a STIX2 object.
:param stixObject: the STIX2 Course of Action object
:type stixObject: dict
:param extras: extra parameters including created_by_id, object_marking_ids, etc.
:type extras: dict
:param update: whether to update if the entity already exists
:type update: bool
:return: Course of Action object
:rtype: dict or None
"""
stix_object = kwargs.get("stixObject", None)
extras = kwargs.get("extras", {})
update = kwargs.get("update", False)
if stix_object is not None:
# Extract external ID
x_mitre_id = None
if "x_mitre_id" in stix_object:
x_mitre_id = stix_object["x_mitre_id"]
elif (
self.opencti.get_attribute_in_mitre_extension("id", stix_object)
is not None
):
x_mitre_id = self.opencti.get_attribute_in_mitre_extension(
"id", stix_object
)
elif "external_references" in stix_object:
for external_reference in stix_object["external_references"]:
if (
external_reference["source_name"] == "mitre-attack"
or external_reference["source_name"] == "mitre-pre-attack"
or external_reference["source_name"] == "mitre-mobile-attack"
or external_reference["source_name"] == "amitt-attack"
):
x_mitre_id = external_reference.get("external_id", None)
# Search in extensions
if "x_opencti_aliases" not in stix_object:
stix_object["x_opencti_aliases"] = (
self.opencti.get_attribute_in_extension("aliases", stix_object)
)
if "x_opencti_stix_ids" not in stix_object:
stix_object["x_opencti_stix_ids"] = (
self.opencti.get_attribute_in_extension("stix_ids", stix_object)
)
if "x_opencti_granted_refs" not in stix_object:
stix_object["x_opencti_granted_refs"] = (
self.opencti.get_attribute_in_extension("granted_refs", stix_object)
)
if "x_opencti_workflow_id" not in stix_object:
stix_object["x_opencti_workflow_id"] = (
self.opencti.get_attribute_in_extension("workflow_id", stix_object)
)
if "x_opencti_modified_at" not in stix_object:
stix_object["x_opencti_modified_at"] = (
self.opencti.get_attribute_in_extension("modified_at", stix_object)
)
if "opencti_upsert_operations" not in stix_object:
stix_object["opencti_upsert_operations"] = (
self.opencti.get_attribute_in_extension(
"opencti_upsert_operations", stix_object
)
)
return self.create(
stix_id=stix_object["id"],
createdBy=(
extras["created_by_id"] if "created_by_id" in extras else None
),
objectMarking=(
extras["object_marking_ids"]
if "object_marking_ids" in extras
else None
),
objectLabel=(
extras["object_label_ids"] if "object_label_ids" in extras else None
),
externalReferences=(
extras["external_references_ids"]
if "external_references_ids" in extras
else None
),
revoked=stix_object["revoked"] if "revoked" in stix_object else None,
confidence=(
stix_object["confidence"] if "confidence" in stix_object else None
),
lang=stix_object["lang"] if "lang" in stix_object else None,
created=stix_object["created"] if "created" in stix_object else None,
modified=stix_object["modified"] if "modified" in stix_object else None,
name=stix_object["name"],
description=(
self.opencti.stix2.convert_markdown(stix_object["description"])
if "description" in stix_object
else None
),
x_opencti_stix_ids=(
stix_object["x_opencti_stix_ids"]
if "x_opencti_stix_ids" in stix_object
else None
),
x_opencti_aliases=self.opencti.stix2.pick_aliases(stix_object),
x_mitre_id=x_mitre_id,
objectOrganization=(
stix_object["x_opencti_granted_refs"]
if "x_opencti_granted_refs" in stix_object
else None
),
x_opencti_workflow_id=(
stix_object["x_opencti_workflow_id"]
if "x_opencti_workflow_id" in stix_object
else None
),
x_opencti_modified_at=(
stix_object["x_opencti_modified_at"]
if "x_opencti_modified_at" in stix_object
else None
),
update=update,
files=extras.get("files"),
filesMarkings=extras.get("filesMarkings"),
filesVersions=extras.get("filesVersions"),
noTriggerImport=extras.get("noTriggerImport", None),
embedded=extras.get("embedded", None),
upsert_operations=(
stix_object["opencti_upsert_operations"]
if "opencti_upsert_operations" in stix_object
else None
),
)
else:
self.opencti.app_logger.error(
"[opencti_course_of_action] Missing parameters: stixObject"
)
return None