-
Notifications
You must be signed in to change notification settings - Fork 148
/
Copy pathapi.py
1409 lines (1067 loc) · 53.9 KB
/
api.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 json
import sys
import magic
import os
import warnings
import json
import magic
import requests
from thehive4py.auth import BasicAuth, BearerAuth
from thehive4py.models import CaseHelper, Version
from thehive4py.query import Parent, Id, And, Eq
from thehive4py.exceptions import *
class TheHiveApi:
def __init__(self, url: str, principal: str, password=None, proxies={}, cert=True, organisation=None,
version=Version.THEHIVE_3.value):
"""
Python API client for TheHive.
Arguments:
url (str): URL of Thehive instance, including the port. Ex: `http://myserver:9000`
principal (str): The API key, or the username if basic authentication is used.
password (str): The password for basic authentication or None. Defaults to None
proxies (dict): The proxy configuration, would have `http` and `https` attributes. Defaults to {}
```python
proxies: {
"http: "http://my_proxy:8080"
"https: "http://my_proxy:8080"
}
```
cert (bool): Wether or not to enable SSL certificate validation
organisation (str): The name of the organisation against which api calls will be run. Defaults to None
version (int): The version of TheHive instance. Defaults to 3
??? note "Examples"
=== "Basic"
Example of simple usage: call TheHive APIs using an API key, without proxy, nor organisation
```python
api = TheHiveApi('http://my_thehive:9000', 'my_api_key')
```
=== "Full options"
Example using all the options: call TheHive APIs using an API key, with orgnisation, proxy and sst certificate
```python
proxies = {
"http: "http://my_proxy:8080"
"https: "http://my_proxy:8080"
}
api = TheHiveApi('http://my_thehive:9000',
'my_api_key',
None,
proxies,
True,
'my-org',
version=Version.THEHIVE_3.value
)
```
"""
self.url = url
self.principal = principal
self.password = password
self.proxies = proxies
self.organisation = organisation
if self.password is not None:
self.auth = BasicAuth(self.principal, self.password, self.organisation)
else:
self.auth = BearerAuth(self.principal, self.organisation)
self.cert = cert
self.version = version
# Create a CaseHelper instance
self.case = CaseHelper(self)
def __isVersion(self, version):
return self.version is version
def __find_rows(self, find_url, **attributes):
"""
Private fuction that abstracts the calls to _search API
Arguments:
find_url: URL of the find api
query (dict): A query object, defined in JSON format or using utiliy methods from thehive4py.query module
sort (Array): List of fields to sort the result with. Prefix the field name with `-` for descending order
and `+` for ascending order
range (str): A range describing the number of rows to be returned
Returns:
response (requests.Response): Response object including a JSON array representing the list of searched records.
Raises:
TheHiveException
"""
req = self.url + find_url
# Add range and sort parameters
params = {
"range": attributes.get("range", "all"),
"sort": attributes.get("sort", [])
}
# Add body
data = {
"query": attributes.get("query", {})
}
try:
return requests.post(req, params=params, json=data, proxies=self.proxies, auth=self.auth, verify=self.cert)
except requests.exceptions.RequestException as e:
raise TheHiveException("Error: {}".format(e))
def do_patch(self, api_url, **attributes):
return requests.patch(self.url + api_url, headers={'Content-Type': 'application/json'}, json=attributes,
proxies=self.proxies, auth=self.auth, verify=self.cert)
def health(self):
"""
Method to call the /api/health endpoint
Returns:
Response object resulting from the API call.
Raises:
TheHiveException: Generic exception if an error occurs
"""
req = self.url + "/api/health"
try:
return requests.get(req, proxies=self.proxies, auth=self.auth, verify=self.cert)
except requests.exceptions.RequestException as e:
raise TheHiveException("Error on retrieving health status: {}".format(e))
def get_current_user(self):
"""
Method to call the /api/current endpoint, returning the current authenticated user.
Returns:
response (requests.Response): Response object including a JSON description of the current user
Raises:
TheHiveException: Generic exception if an error occurs
"""
req = self.url + "/api/user/current"
try:
return requests.get(req, proxies=self.proxies, auth=self.auth, verify=self.cert)
except requests.exceptions.RequestException as e:
raise TheHiveException("Error on retrieving current user: {}".format(e))
def create_case(self, case):
"""
Create a case
Arguments:
case (Case): Instance of [Case][thehive4py.models.Case]
Returns:
response (requests.Response): Response object including a JSON description of a case
Raises:
CaseException: An error occured during case creation
"""
req = self.url + "/api/case"
data = case.jsonify(excludes=['id'])
try:
return requests.post(req, headers={'Content-Type': 'application/json'}, data=data, proxies=self.proxies, auth=self.auth, verify=self.cert)
except requests.exceptions.RequestException as e:
raise CaseException("Case create error: {}".format(e))
def update_case(self, case, fields=[]):
"""
Update a case.
Arguments:
case (Case): Instance of [Case][thehive4py.models.Case] to update. The case's `id` determines which case to update.
fields (Array): Optional parameter, an array of fields names, the ones we want to update
Updatable fields are: [`title`, `description`, `severity`, `startDate`, `owner`, `flag`, `tlp`, `pap`, `tags`, `status`,
`resolutionStatus`, `impactStatus`, `summary`, `endDate`, `metrics`, `customFields`]
Returns:
response (requests.Response): Response object including a JSON description of a case
Raises:
CaseException: An error occured during case creation
"""
req = self.url + "/api/case/{}".format(case.id)
# Choose which attributes to send
update_keys = [
'title', 'description', 'severity', 'startDate', 'owner', 'flag', 'tlp', 'pap', 'tags', 'status',
'resolutionStatus', 'impactStatus', 'summary', 'endDate', 'metrics', 'customFields'
]
data = {k: v for k, v in case.__dict__.items() if (len(fields) > 0 and k in fields) or (len(fields) == 0 and k in update_keys)}
try:
return requests.patch(req, headers={'Content-Type': 'application/json'}, json=data, proxies=self.proxies, auth=self.auth, verify=self.cert)
except requests.exceptions.RequestException as e:
raise CaseException("Case update error: {}".format(e))
def create_case_task(self, case_id, case_task):
"""
Create a case task
Arguments:
case_id: Case identifier
case_task: Instance of [CaseTask][thehive4py.models.CaseTask]
Returns:
response (requests.Response): Response object including a JSON description of a case task
Raises:
CaseTaskException: An error occured during case task creation
"""
req = self.url + "/api/case/{}/task".format(case_id)
data = case_task.jsonify(excludes=['id'])
try:
return requests.post(req, headers={'Content-Type': 'application/json'}, data=data, proxies=self.proxies, auth=self.auth, verify=self.cert)
except requests.exceptions.RequestException as e:
raise CaseTaskException("Case task create error: {}".format(e))
def update_case_task(self, task, fields=[]):
"""
Update a case task
Arguments:
task (CaseTask): Instance of [CaseTask][thehive4py.models.CaseTask]
fields (array): Arry of strings representing CaseTask properties to be updated
Updatable fields are: [`title`, `description`, `status`, `order`, `user`, `owner`, `flag`, `endDate`]
Returns:
response (requests.Response): Response object including a JSON description of a case task
Raises:
CaseTaskException: An error occured during case task creation
"""
req = self.url + "/api/case/task/{}".format(task.id)
# Choose which attributes to send
update_keys = [
'title', 'description', 'status', 'order', 'user', 'owner', 'flag', 'endDate'
]
data = {k: v for k, v in task.__dict__.items() if (
len(fields) > 0 and k in fields) or (len(fields) == 0 and k in update_keys)}
try:
return requests.patch(req, headers={'Content-Type': 'application/json'}, json=data,
proxies=self.proxies, auth=self.auth, verify=self.cert)
except requests.exceptions.RequestException as e:
raise CaseTaskException("Case task update error: {}".format(e))
def delete_case_task(self, task_id):
"""
Deletes a TheHive case task.
Arguments:
task_id (str): Id of the task to delete
Returns:
response (requests.Response): Response object including the updated task
Raises:
CaseException: An error occured during case deletion
"""
req = self.url + "/api/case/task/{}".format(task_id)
try:
return requests.patch(req, headers={'Content-Type': 'application/json'}, json={'status': 'Cancel'},
proxies=self.proxies, auth=self.auth, verify=self.cert)
except requests.exceptions.RequestException as e:
raise CaseTaskException("Case task deletion error: {}".format(e))
def create_task_log(self, task_id, case_task_log):
"""
Create a task log either with an attachement or just with a log message.
Arguments:
task_id (str): Task identifier
case_task_log (CaseTaskLocg): Instance of [CaseTaskLog][thehive4py.models.CaseTaskLog]
Returns:
response (requests.Response): Response object including a JSON description of a case
Raises:
CaseException: An error occured during case creation
"""
req = self.url + "/api/case/task/{}/log".format(task_id)
data = {'_json': json.dumps({"message": case_task_log.message})}
if case_task_log.file:
f = case_task_log.attachment
try:
return requests.post(req, data=data, files=f, proxies=self.proxies, auth=self.auth, verify=self.cert)
except requests.exceptions.RequestException as e:
raise CaseTaskException("Case task log create error: {}".format(e))
else:
try:
return requests.post(req, headers={'Content-Type': 'application/json'}, data=json.dumps({'message':case_task_log.message}), proxies=self.proxies, auth=self.auth, verify=self.cert)
except requests.exceptions.RequestException as e:
raise CaseTaskException("Case task log create error: {}".format(e))
def create_case_observable(self, case_id, case_observable):
"""
Create a case observable
Arguments:
case_id (str): Case identifier
case_observable (CaseObservable): Instance of [CaseObservable][thehive4py.models.CaseObservable]
Returns:
response (requests.Response): Response object including a JSON description of a case observable
Raises:
CaseObservableException: An error occured during case observable creation
"""
req = self.url + "/api/case/{}/artifact".format(case_id)
if case_observable.dataType == 'file':
try:
data = {
"dataType": case_observable.dataType,
"message": case_observable.message,
"tlp": case_observable.tlp,
"tags": case_observable.tags,
"ioc": case_observable.ioc,
"sighted": case_observable.sighted,
"ignoreSimilarity": case_observable.ignoreSimilarity
}
# Exclude ignoreSimilarity field for TheHive 3
if self.__isVersion(Version.THEHIVE_3.value):
data.pop('ignoreSimilarity', None)
data = {"_json": json.dumps(data)}
return requests.post(req, data=data, files=case_observable.data[0], proxies=self.proxies, auth=self.auth, verify=self.cert)
except requests.exceptions.RequestException as e:
raise CaseObservableException("Case observable create error: {}".format(e))
else:
try:
to_exclude = ['id']
# Exclude ignoreSimilarity field for TheHive 3
if self.__isVersion(Version.THEHIVE_3.value):
to_exclude.append('ignoreSimilarity')
data = case_observable.jsonify(excludes=to_exclude)
return requests.post(req, headers={'Content-Type': 'application/json'}, data=data, proxies=self.proxies, auth=self.auth, verify=self.cert)
except requests.exceptions.RequestException as e:
raise CaseObservableException("Case observable create error: {}".format(e))
def delete_case_observable(self, observable_id):
"""
Deletes a TheHive case observable.
Arguments:
observable_id (str): Id of the observable to delete
Returns:
response (requests.Response): Response object including true or false based on the action's success
Raises:
CaseObservableException: An error occured during case observable deletion
"""
req = self.url + "/api/case/artifact/{}".format(observable_id)
try:
return requests.delete(req, proxies=self.proxies, auth=self.auth, verify=self.cert)
except requests.exceptions.RequestException as e:
raise CaseObservableException("Case observable deletion error: {}".format(e))
def update_case_observable(self, observable_id, case_observable, fields=[]):
"""
Update an existing case observable
Arguments:
observable_id: Observable identifier
case_observable (CaseObservable): Instance of [CaseObservable][thehive4py.models.CaseObservable]
fields (Array): Optional parameter, an array of fields names, the ones we want to update.
Updatable fields are: [`tlp`, `ioc`, `sighted`, `tags`, `message`, `ignoreSimilarity`]
Returns:
response (requests.Response): Response object including a JSON description of the updated case observable
Raises:
CaseObservableException: An error occured during case observable update
"""
req = self.url + "/api/case/artifact/{}".format(observable_id)
update_keys = ['message', 'tlp', 'tags', 'ioc', 'sighted', 'ignoreSimilarity']
data = {k: v for k, v in case_observable.__dict__.items() if (
len(fields) > 0 and k in fields) or (len(fields) == 0 and k in update_keys)}
# Exclude ignoreSimilarity field for TheHive 3
if self.__isVersion(Version.THEHIVE_3.value):
data.pop('ignoreSimilarity', None)
try:
return requests.patch(req, headers={'Content-Type': 'application/json'}, json=data, proxies=self.proxies, auth=self.auth, verify=self.cert)
except requests.exceptions.RequestException as e:
raise CaseObservableException("Case observable update error: {}".format(e))
def get_case(self, case_id):
"""
Get a case by id
Arguments:
case_id (str): Case identifier
Returns:
response (requests.Response): Response object including a JSON description of the case.
Raises:
CaseException: An error occured during case fetch
"""
req = self.url + "/api/case/{}".format(case_id)
try:
return requests.get(req, proxies=self.proxies, auth=self.auth, verify=self.cert)
except requests.exceptions.RequestException as e:
raise CaseException("Case fetch error: {}".format(e))
def find_cases(self, **attributes):
"""
Find cases using sort, pagination and a query
Arguments:
query (dict): A query object, defined in JSON format or using utiliy methods from thehive4py.query module
sort (Array): List of fields to sort the result with. Prefix the field name with `-` for descending order
and `+` for ascending order
range (str): A range describing the number of rows to be returned
Returns:
response (requests.Response): Response object including a JSON array of cases.
Raises:
CaseException: An error occured during case search
"""
return self.__find_rows("/api/case/_search", **attributes)
def delete_case(self, case_id, force=False):
"""
Deletes a TheHive case. Unless force is set to True the case is 'soft deleted' (status set to deleted).
Arguments:
case_id (str): Id of the case to delete
force (bool): True to physically delete the case, False to mark the case as deleted
Returns:
response (requests.Response): Response object including true or false based on the action's success
Raises:
CaseException: An error occured during case deletion
"""
req = self.url + "/api/case/{}".format(case_id)
if force:
req += '/force'
try:
return requests.delete(req, proxies=self.proxies, auth=self.auth, verify=self.cert)
except requests.exceptions.RequestException as e:
raise CaseException("Case deletion error: {}".format(e))
def find_first(self, **attributes):
"""
Find cases and return just the first record
Arguments:
query (dict): A query object, defined in JSON format or using utiliy methods from thehive4py.query module
sort (Array): List of fields to sort the result with. Prefix the field name with `-` for descending order
and `+` for ascending order
Returns:
response (dict): A dict object describing the first case resulting from the query and sort options.
Raises:
CaseException: An error occured during case search
"""
attributes['range'] = '0-1'
try:
return self.find_cases(**attributes).json()[0]
except requests.exceptions.RequestException as e:
raise CaseObservableException("Case search error: {}".format(e))
def get_case_observable(self, observable_id):
"""
Get a case observable by its id
Arguments:
observable_id (str): Case observable identifier
Returns:
response (requests.Response): Response object including a JSON representation of the case observable
Raises:
CaseObservableException: An error occured during case observable fetch
"""
req = self.url + "/api/case/artifact/{}".format(observable_id)
try:
return requests.get(req, proxies=self.proxies, auth=self.auth, verify=self.cert)
except requests.exceptions.RequestException as e:
raise CaseObservableException("Case observable search error: {}".format(e))
def get_case_observables(self, case_id, **attributes):
"""
Find observables of a given case identified by its id
Arguments:
case_id (str): Id of the case
query (dict): A query object, defined in JSON format or using utiliy methods from thehive4py.query module
sort (Array): List of fields to sort the result with. Prefix the field name with `-` for descending order
and `+` for ascending order
range (str): A range describing the number of rows to be returned
Returns:
response (requests.Response): Response object including a JSON array of case observable.
Raises:
CaseObservableException: An error occured during case observable search
"""
req = self.url + "/api/case/artifact/_search"
# Add range and sort parameters
params = {
"range": attributes.get("range", "all"),
"sort": attributes.get("sort", [])
}
# Add body
parent_criteria = Parent('case', Id(case_id))
# Append the custom query if specified
if "query" in attributes:
criteria = And(parent_criteria, attributes["query"])
else:
criteria = parent_criteria
data = {
"query": criteria
}
try:
return requests.post(req, params=params, json=data, proxies=self.proxies, auth=self.auth, verify=self.cert)
except requests.exceptions.RequestException as e:
raise CaseObservableException("Case observables search error: {}".format(e))
def find_observables(self, **attributes):
"""
Find observables using sort, pagination and a query
Arguments:
query (dict): A query object, defined in JSON format or using utiliy methods from thehive4py.query module
sort (Array): List of fields to sort the result with. Prefix the field name with `-` for descending order
and `+` for ascending order
range (str): A range describing the number of rows to be returned
Returns:
response (requests.Response): Response object including a JSON array of observables.
Raises:
ObservableException: An error occured during observable search
"""
return self.__find_rows("/api/case/artifact/_search", **attributes)
def get_case_tasks(self, case_id, **attributes):
"""
Find tasks of a given case identified by its id
Arguments:
case_id (str): Id of the case
query (dict): A query object, defined in JSON format or using utiliy methods from thehive4py.query module
sort (Array): List of fields to sort the result with. Prefix the field name with `-` for descending order
and `+` for ascending order
range (str): A range describing the number of rows to be returned
Returns:
response (requests.Response): Response object including a JSON array of case task.
Raises:
CaseTaskException: An error occured during case task search
"""
req = self.url + "/api/case/task/_search"
# Add range and sort parameters
params = {
"range": attributes.get("range", "all"),
"sort": attributes.get("sort", [])
}
# Add body
parent_criteria = Parent('case', Id(case_id))
# Append the custom query if specified
if "query" in attributes:
criteria = And(parent_criteria, attributes["query"])
else:
criteria = parent_criteria
data = {
"query": criteria
}
try:
return requests.post(req, params=params, json=data, proxies=self.proxies, auth=self.auth, verify=self.cert)
except requests.exceptions.RequestException as e:
raise CaseTaskException("Case tasks search error: {}".format(e))
def get_linked_cases(self, case_id):
"""
Find related cases of a given case identified by its id
Arguments:
case_id (str): Id of the case
Returns:
response (requests.Response): Response object including a JSON array of related cases.
Raises:
CaseException: An error occured during case links fetch
"""
req = self.url + "/api/case/{}/links".format(case_id)
try:
return requests.get(req, proxies=self.proxies, auth=self.auth, verify=self.cert)
except requests.exceptions.RequestException as e:
raise CaseException("Linked cases fetch error: {}".format(e))
def find_case_templates(self, **attributes):
"""
Find case templates using a query, sort and pagination
Arguments:
query (dict): A query object, defined in JSON format or using utiliy methods from thehive4py.query module
sort (Array): List of fields to sort the result with. Prefix the field name with `-` for descending order
and `+` for ascending order
range (str): A range describing the number of rows to be returned
Returns:
response (requests.Response): Response object including a JSON array of case templates
Raises:
TheHiveException: An error occured during case template search
"""
return self.__find_rows("/api/case/template/_search", **attributes)
def get_case_template(self, name):
"""
Get a case template by its name
Arguments:
name (str): Case template's name
Returns:
response (requests.Response): Response object including a JSON representation of the case template
Raises:
CaseTemplateException: An error occured during case template fetch
"""
req = self.url + "/api/case/template/_search"
if self.__isVersion(Version.THEHIVE_3.value):
query = And(Eq("name", name), Eq("status", "Ok"))
else:
query = Eq("name", name)
data = {
"query": query
}
try:
response = requests.post(req, json=data, proxies=self.proxies, auth=self.auth, verify=self.cert)
json_response = response.json()
if response.status_code == 200 and len(json_response) > 0:
return response.json()[0]
else:
raise CaseTemplateException("Case template fetch error: Unable to find case template {}".format(name))
except requests.exceptions.RequestException as e:
raise CaseTemplateException("Case template fetch error: {}".format(e))
def create_case_template(self, case_template):
"""
Create a case template
Arguments:
case_template (CaseTemplate): Instance of [CaseTemplate][thehive4py.models.CaseTemplate]
Returns:
response (requests.Response): Response object including a JSON representation of the case template
Raises:
CaseTemplateException: An error occured during case template creation
"""
req = self.url + "/api/case/template"
data = case_template.jsonify(excludes=['id'])
try:
return requests.post(req, headers={'Content-Type': 'application/json'}, data=data, proxies=self.proxies, auth=self.auth, verify=self.cert)
except requests.exceptions.RequestException as e:
raise CaseTemplateException("Case template create error: {}".format(e))
def _check_if_custom_field_exists(self, custom_field):
data = {
'key': 'reference',
'value': custom_field.reference
}
req = self.url + "/api/list/custom_fields/_exists"
response = requests.post(req, json=data, proxies=self.proxies, auth=self.auth, verify=self.cert)
return response.json().get('found', 'False')
def create_custom_field(self, custom_field):
"""
Create a custom field
Arguments:
custom_field (CustomField): Instance of [CustomField][thehive4py.models.CustomField]
Returns:
response (requests.Response): Response object including a JSON representation of the case template
Raises:
CustomFieldException: Custom field already exists
CustomFieldException: An error occured during custom field creation
!!! Warning
This function is available only for TheHive 3
"""
if self._check_if_custom_field_exists(custom_field):
raise CustomFieldException('Field with reference "{}" already exists'.format(custom_field.reference))
data = {
"value": {
"name": custom_field.name,
"reference": custom_field.reference,
"description": custom_field.description,
"type": custom_field.type,
"options": custom_field.options,
"mandatory": custom_field.mandatory
}
}
req = self.url + "/api/list/custom_fields"
try:
return requests.post(req, json=data, proxies=self.proxies, auth=self.auth, verify=self.cert)
except requests.exceptions.RequestException as e:
raise CustomFieldException("Custom field create error: {}".format(e))
def get_case_task(self, task_id):
"""
Get a case task by its id
Arguments:
task_id (str): Case task identifier
Returns:
response (requests.Response): Response object including a JSON representation of the case task
Raises:
CaseTaskException: An error occured during case task fetch
"""
req = self.url + "/api/case/task/{}".format(task_id)
try:
return requests.get(req, proxies=self.proxies, auth=self.auth, verify=self.cert)
except requests.exceptions.RequestException as e:
raise CaseTaskException("Case task logs search error: {}".format(e))
def get_task_log(self, log_id):
"""
Get a case task log by its id
Arguments:
log_id (str): Case task log identifier
Returns:
response (requests.Response): Response object including a JSON representation of the case task log
Raises:
CaseTaskException: An error occured during case task log fetch
"""
if self.__isVersion(Version.THEHIVE_3.value):
req = self.url + "/api/case/task/log/{}".format(log_id)
try:
return requests.get(req, proxies=self.proxies, auth=self.auth, verify=self.cert)
except requests.exceptions.RequestException as e:
raise CaseTaskLogException("Case task log fetch error: {}".format(e))
else:
req = self.url + "/api/v1/query"
data = {
"query": [
{"_name": "getLog", "idOrName": log_id}
]
}
try:
return requests.post(req, json=data, proxies=self.proxies, auth=self.auth, verify=self.cert)
except requests.exceptions.RequestException as e:
raise CaseTaskLogException("Case task log fetch error: {}".format(e))
#'{"query": [{"_name": "getLog", "idOrName": "~40976560"}]}'
def get_task_logs(self, task_id, **attributes):
"""
Get logs of a case task by its id
Arguments:
task_id (str): Case task identifier
query (dict): A query object, defined in JSON format or using utiliy methods from thehive4py.query module
sort (Array): List of fields to sort the result with. Prefix the field name with `-` for descending order
and `+` for ascending order
range (str): A range describing the number of rows to be returned
Returns:
response (requests.Response): Response object including a JSON array representing a list of case task logs
Raises:
CaseTaskException: An error occured during case task log search
"""
req = self.url + "/api/case/task/log/_search"
# Add range and sort parameters
params = {
"range": attributes.get("range", "all"),
"sort": attributes.get("sort", [])
}
# Add body
parent_criteria = Parent('case_task', Id(task_id))
# Append the custom query if specified
if "query" in attributes:
criteria = And(parent_criteria, attributes["query"])
else:
criteria = parent_criteria
data = {
"query": criteria
}
return self.find_task_logs(query=criteria, **params)
def create_alert(self, alert):
"""
Create an alert. Supports adding observables and custom fields
Arguments:
alert (Alert): Instance of [Alert][thehive4py.models.Alert]
Returns:
response (requests.Response): Response object including a JSON array representing a list of case task logs
Raises:
AlertException: An error occured during alert creation
"""
req = self.url + "/api/alert"
to_exclude = ['id']
# Exclude PAP field for TheHive 3
if self.__isVersion(Version.THEHIVE_3.value):
to_exclude.append('pap')
to_exclude.append('externalLink')
data = alert.jsonify(excludes=to_exclude)
try:
return requests.post(req, headers={'Content-Type': 'application/json'}, data=data, proxies=self.proxies, auth=self.auth, verify=self.cert)
except requests.exceptions.RequestException as e:
raise AlertException("Alert create error: {}".format(e))
def mark_alert_as_read(self, alert_id):
"""
Mark an alert as read. This sets the status of the alert to `Ignored` if it's not yet promoted to a case.
Arguments:
alert_id (str): Id of the alert
Returns:
response (requests.Response): Response object including a JSON representation of the alert
Raises:
AlertException: An error occured during alert update
"""
req = self.url + "/api/alert/{}/markAsRead".format(alert_id)
try:
return requests.post(req, headers={'Content-Type': 'application/json'}, proxies=self.proxies, auth=self.auth, verify=self.cert)
except requests.exceptions.RequestException as e:
raise AlertException("Mark alert as read error: {}".format(e))
def mark_alert_as_unread(self, alert_id):
"""
Mark an alert as unread. This sets the status of the alert to `New` if it's not yet promoted to a case.
Arguments:
alert_id (str): Id of the alert
Returns:
response (requests.Response): Response object including a JSON representation of the alert
Raises:
AlertException: An error occured during alert update
"""
req = self.url + "/api/alert/{}/markAsUnread".format(alert_id)
try:
return requests.post(req, headers={'Content-Type': 'application/json'}, proxies=self.proxies, auth=self.auth, verify=self.cert)
except requests.exceptions.RequestException as e:
raise AlertException("Mark alert as unread error: {}".format(e))
def merge_alert_into_case(self, alert_id, case_id):
"""
Merge alert into existing case.
:param alert_id: The ID of the alert to merge.
:param case_id: The ID of the case where to merge alert
:return:
"""
req = self.url + "/api/alert/{}/merge/{}".format(alert_id, case_id)
try:
return requests.post(req, headers={'Content-Type': 'application/json'}, json={}, proxies=self.proxies, auth=self.auth, verify=self.cert)
except requests.exceptions.RequestException as e:
raise AlertException("Merge alert to case error: {}".format(e))
def update_alert(self, alert_id, alert, fields=[]):
"""
Update an alert completely or using specified fields
Arguments:
alert_id (str): Id of the alert
alert (Alert): Instance of [Alert][thehive4py.models.Alert]
fields (Array): Optional parameter, an array of field names, the ones we want to update
Updatable fields are: [`tlp`, `severity`, `tags`, `caseTemplate`, `title`, `description`, `customFields`]
Returns:
response (requests.Response): Response object including a JSON representation of the alert
Raises:
AlertException: An error occured during alert update
"""
req = self.url + "/api/alert/{}".format(alert_id)
# update only the alert attributes that are not read-only
update_keys = ['tlp', 'pap', 'severity', 'tags', 'caseTemplate', 'title', 'description', 'customFields',
'artifacts', 'follow']
data = {k: v for k, v in alert.__dict__.items() if (
len(fields) > 0 and k in fields) or (len(fields) == 0 and k in update_keys)}
if 'artifacts' in data:
data['artifacts'] = [a.__dict__ for a in alert.artifacts]
# data['artifacts'] = [{k: v for k, v in a.__dict__.items()} for a in alert.artifacts]
# Exclude PAP field for TheHive 3
if self.__isVersion(Version.THEHIVE_3.value):
data.pop('pap', None)
data.pop('externalLink', None)