Skip to content

API#

This is the reference of all the methods available on thehive4py.api.TheHiveApi.

TheHiveApi #

__init__(self, url, principal, password=None, proxies={}, cert=True, organisation=None, version=3) special #

Python API client for TheHive.

Parameters:

Name Type Description Default
url str

URL of Thehive instance, including the port. Ex: http://myserver:9000

required
principal str

The API key, or the username if basic authentication is used.

required
password str

The password for basic authentication or None. Defaults to None

None
proxies dict

The proxy configuration, would have http and https attributes. Defaults to {}

proxies: {
    "http: "http://my_proxy:8080"
    "https: "http://my_proxy:8080"
}

{}
cert bool

Wether or not to enable SSL certificate validation

True
organisation str

The name of the organisation against which api calls will be run. Defaults to None

None
version int

The version of TheHive instance. Defaults to 3

3
Examples

Example of simple usage: call TheHive APIs using an API key, without proxy, nor organisation

api = TheHiveApi('http://my_thehive:9000', 'my_api_key')

Example using all the options: call TheHive APIs using an API key, with orgnisation, proxy and sst certificate

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
)
Source code in thehive4py/api.py
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
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)

create_alert(self, alert) #

Create an alert. Supports adding observables and custom fields

Parameters:

Name Type Description Default
alert Alert

Instance of Alert

required

Returns:

Type Description
response (requests.Response)

Response object including a JSON array representing a list of case task logs

Exceptions:

Type Description
AlertException

An error occured during alert creation

Source code in thehive4py/api.py
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
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))

create_alert_artifact(self, alert_id, alert_artifact) #

Create an alert artifact

Parameters:

Name Type Description Default
alert_id str

Alert identifier

required
alert_artifact AlertArtifact

Instance of AlertArtifact

required

Returns:

Type Description
response (requests.Response)

Response object including a JSON description of an alert artifact

Exceptions:

Type Description
AlertArtifactException

An error occured during alert artifact creation

Warning

This function is available in TheHive 4 ONLY

Source code in thehive4py/api.py
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
def create_alert_artifact(self, alert_id, alert_artifact):

    """
    Create an alert artifact

    Arguments:
        alert_id (str): Alert identifier
        alert_artifact (AlertArtifact): Instance of [AlertArtifact][thehive4py.models.AlertArtifact]

    Returns:
        response (requests.Response): Response object including a JSON description of an alert artifact

    Raises:
        AlertArtifactException: An error occured during alert artifact creation

    !!! Warning
        This function is available in TheHive 4 ONLY
    """

    if self.__isVersion(Version.THEHIVE_3.value):
        raise AlertArtifactException("This function is available in TheHive 4 ONLY")

    req = self.url + "/api/alert/{}/artifact".format(alert_id)

    if alert_artifact.dataType == 'file':
        try:
            fields = ["dataType", "message", "tlp", "tags", "ioc", "sighted", "ignoreSimilarity"]
            data = {k: v for k, v in alert_artifact.__dict__.items() if k in fields}

            data = {"_json": json.dumps(data)}
            return requests.post(req, data=data, files=alert_artifact.data, proxies=self.proxies, auth=self.auth, verify=self.cert)
        except requests.exceptions.RequestException as e:
            raise AlertArtifactException("Alert artifact create error: {}".format(e))
    else:
        try:
            data = alert_artifact.jsonify(excludes=['id'])

            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 AlertArtifactException("Alert artifact create error: {}".format(e))

create_case(self, case) #

Create a case

Parameters:

Name Type Description Default
case Case

Instance of Case

required

Returns:

Type Description
response (requests.Response)

Response object including a JSON description of a case

Exceptions:

Type Description
CaseException

An error occured during case creation

Source code in thehive4py/api.py
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
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))

create_case_observable(self, case_id, case_observable) #

Create a case observable

Parameters:

Name Type Description Default
case_id str

Case identifier

required
case_observable CaseObservable

Instance of CaseObservable

required

Returns:

Type Description
response (requests.Response)

Response object including a JSON description of a case observable

Exceptions:

Type Description
CaseObservableException

An error occured during case observable creation

Source code in thehive4py/api.py
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
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))

create_case_task(self, case_id, case_task) #

Create a case task

Parameters:

Name Type Description Default
case_id

Case identifier

required
case_task

Instance of CaseTask

required

Returns:

Type Description
response (requests.Response)

Response object including a JSON description of a case task

Exceptions:

Type Description
CaseTaskException

An error occured during case task creation

Source code in thehive4py/api.py
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
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))

create_case_template(self, case_template) #

Create a case template

Parameters:

Name Type Description Default
case_template CaseTemplate

Instance of CaseTemplate

required

Returns:

Type Description
response (requests.Response)

Response object including a JSON representation of the case template

Exceptions:

Type Description
CaseTemplateException

An error occured during case template creation

Source code in thehive4py/api.py
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
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))

create_custom_field(self, custom_field) #

Create a custom field

Parameters:

Name Type Description Default
custom_field CustomField

Instance of CustomField

required

Returns:

Type Description
response (requests.Response)

Response object including a JSON representation of the case template

Exceptions:

Type Description
CustomFieldException

Custom field already exists

CustomFieldException

An error occured during custom field creation

Warning

This function is available only for TheHive 3

Source code in thehive4py/api.py
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
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))

create_task_log(self, task_id, case_task_log) #

Create a task log either with an attachement or just with a log message.

Parameters:

Name Type Description Default
task_id str

Task identifier

required
case_task_log CaseTaskLocg

Instance of CaseTaskLog

required

Returns:

Type Description
response (requests.Response)

Response object including a JSON description of a case

Exceptions:

Type Description
CaseException

An error occured during case creation

Source code in thehive4py/api.py
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
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))

delete_alert(self, alert_id) #

Deletes a TheHive alert.

Parameters:

Name Type Description Default
alert_id str

Id of the alert to delete

required

Returns:

Type Description
response (requests.Response)

Response object including true or false based on the action's success

Exceptions:

Type Description
AlertException

An error occured during alert deletion

Warning

TheHive 3: Deleting alert requires admin role TheHive 4: Deleting alert requires a role including manageAlert permissing

Source code in thehive4py/api.py
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
def delete_alert(self, alert_id):
    """
    Deletes a TheHive alert.

    Arguments:
        alert_id (str): Id of the alert to delete

    Returns:
        response (requests.Response): Response object including true or false based on the action's success

    Raises:
        AlertException: An error occured during alert deletion

    !!! Warning
        TheHive 3: Deleting alert requires `admin` role
        TheHive 4: Deleting alert requires a role including `manageAlert` permissing
    """

    req = self.url + "/api/alert/{}".format(alert_id)
    params = {
        "force": 1
    }
    try:
        return requests.delete(req, params=params, proxies=self.proxies, auth=self.auth, verify=self.cert)
    except requests.exceptions.RequestException as e:
        raise AlertException("Alert deletion error: {}".format(e))

delete_alert_artifact(self, artifact_id) #

Deletes a TheHive alert artifact.

Parameters:

Name Type Description Default
artifact_id str

Id of the artifact to delete

required

Returns:

Type Description
response (requests.Response)

Response object including true or false based on the action's success

Exceptions:

Type Description
AlertArtifactException

An error occured during alert artifact deletion

Warning

This function is available in TheHive 4 ONLY

Source code in thehive4py/api.py
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
def delete_alert_artifact(self, artifact_id):
    """
    Deletes a TheHive alert artifact.

    Arguments:
        artifact_id (str): Id of the artifact to delete

    Returns:
        response (requests.Response): Response object including true or false based on the action's success

    Raises:
        AlertArtifactException: An error occured during alert artifact deletion

    !!! Warning
        This function is available in TheHive 4 ONLY
    """

    if self.__isVersion(Version.THEHIVE_3.value):
        raise AlertArtifactException("This function is available in TheHive 4 ONLY")

    req = self.url + "/api/alert/artifact/{}".format(artifact_id)

    try:
        return requests.delete(req, proxies=self.proxies, auth=self.auth, verify=self.cert)
    except requests.exceptions.RequestException as e:
        raise AlertArtifactException("Alert artifact deletion error: {}".format(e))

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).

Parameters:

Name Type Description Default
case_id str

Id of the case to delete

required
force bool

True to physically delete the case, False to mark the case as deleted

False

Returns:

Type Description
response (requests.Response)

Response object including true or false based on the action's success

Exceptions:

Type Description
CaseException

An error occured during case deletion

Source code in thehive4py/api.py
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
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))

delete_case_observable(self, observable_id) #

Deletes a TheHive case observable.

Parameters:

Name Type Description Default
observable_id str

Id of the observable to delete

required

Returns:

Type Description
response (requests.Response)

Response object including true or false based on the action's success

Exceptions:

Type Description
CaseObservableException

An error occured during case observable deletion

Source code in thehive4py/api.py
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
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))

delete_case_task(self, task_id) #

Deletes a TheHive case task.

Parameters:

Name Type Description Default
task_id str

Id of the task to delete

required

Returns:

Type Description
response (requests.Response)

Response object including the updated task

Exceptions:

Type Description
CaseException

An error occured during case deletion

Source code in thehive4py/api.py
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
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))

download_attachment(self, attachment_id, filename='attachment', archive=False) #

Get the content of an attachement object by ID

Parameters:

Name Type Description Default
attachment_id

identifier of the attachment object

required
filename str

name of the downloaded file

'attachment'
archive bool

set to True to zip and password protect the downloaded file

False

Returns:

Type Description
response (requests.Response)

Response object including a the attachment content as bytes

Exceptions:

Type Description
TheHiveException

An error occured during the attachment download

Source code in thehive4py/api.py
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
def download_attachment(self, attachment_id, filename="attachment", archive=False):
    """
    Get the content of an attachement object by ID

    Arguments:
        attachment_id: identifier of the attachment object
        filename (str): name of the downloaded file
        archive (bool): set to `True` to zip and password protect the downloaded file

    Returns:
        response (requests.Response): Response object including a the attachment content as bytes

    Raises:
        TheHiveException: An error occured during the attachment download
    """
    if archive is True:
        req = self.url + "/api/datastorezip/{}?name{}".format(attachment_id, filename)
    else:
        req = self.url + "/api/datastore/{}?name={}".format(attachment_id, filename)

    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 attachment {}: {}".format(attachment_id, e))

download_observable_attachment(self, observable_id, archive=True) #

Get the content of the attachement object of a file observable

Parameters:

Name Type Description Default
observable_id

identifier of the case observable object

required
archive bool

set to False to disable zip and password protection of the downloaded file

True

Returns:

Type Description
response (requests.Response)

Response object including a the attachment content as bytes

Exceptions:

Type Description
CaseObservableException

If the observable is not a file

TheHiveException

An error occured during the attachment download

Source code in thehive4py/api.py
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
def download_observable_attachment(self, observable_id, archive=True):
    """
    Get the content of the attachement object of a file observable

    Arguments:
        observable_id: identifier of the case observable object
        archive (bool): set to `False` to disable zip and password protection of the downloaded file

    Returns:
        response (requests.Response): Response object including a the attachment content as bytes

    Raises:
        CaseObservableException: If the observable is not a file
        TheHiveException: An error occured during the attachment download
    """
    try:
        # Get the observable by id
        response = self.get_case_observable(observable_id)

        # Check if it has an attachment
        observable = response.json()

        if 'attachment' in observable:
            attachment = observable['attachment']
            return self.download_attachment(attachment['id'], filename=attachment['name'], archive=True)
        else:
            raise CaseObservableException("Observable {} doesn't have an attachment".format(observable_id))

    except requests.exceptions.RequestException as e:
        raise CaseObservableException("Error on retrieving attachment of case observable {}: {}".format(observable_id, e))

download_task_log_attachment(self, task_log_id, archive=False) #

Get the content of the attachement object of a task log

Parameters:

Name Type Description Default
task_log_id

identifier of the task log object

required
archive bool

set to True to zip and password protect the downloaded file

False

Returns:

Type Description
response (requests.Response)

Response object including a the attachment content as bytes

Exceptions:

Type Description
CaseTaskLogException

If the task log doesn't have an attachment

TheHiveException

An error occured during the attachment download

Source code in thehive4py/api.py
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
def download_task_log_attachment(self, task_log_id, archive=False):
    """
    Get the content of the attachement object of a task log

    Arguments:
        task_log_id: identifier of the task log object
        archive (bool): set to `True` to zip and password protect the downloaded file

    Returns:
        response (requests.Response): Response object including a the attachment content as bytes

    Raises:
        CaseTaskLogException: If the task log doesn't have an attachment
        TheHiveException: An error occured during the attachment download
    """
    try:
        # Get the task log by id
        response = self.get_task_log(task_log_id)

        # Check if it has an attachment
        if self.__isVersion(Version.THEHIVE_3.value):
            log = response.json()
        else:
            log = response.json()[0]

        if 'attachment' in log:
            attachment = log['attachment']
            return self.download_attachment(attachment['id'], filename=attachment['name'], archive=archive)
        else:
            raise CaseTaskLogException("Task log {} doesn't have an attachment".format(task_log_id))

    except requests.exceptions.RequestException as e:
        raise CaseTaskLogException("Error on retrieving attachment of task log {}: {}".format(task_log_id, e))

export_to_misp(self, misp_id, case_id) #

Export selected IOCs of a case as an event to a MISP instance This function triggers the same action triggered when the "Share" button on the TheHive GUI is clicked

Parameters:

Name Type Description Default
misp_id

identifier of the MISP server

required
case_id str

Id of the case

required

Returns:

Type Description
response (requests.Response)

Response object including a JSON representation of the exported event

Exceptions:

Type Description
TheHiveException

An error occured during the export operation

Source code in thehive4py/api.py
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
def export_to_misp(self, misp_id, case_id):
    """
    Export selected IOCs of a case as an event to a MISP instance 
    This function triggers the same action triggered when the "Share" button on the TheHive GUI is clicked

    Arguments:
        misp_id: identifier of the MISP server
        case_id (str): Id of the case

    Returns:
        response (requests.Response): Response object including a JSON representation of the exported event

    Raises:
        TheHiveException: An error occured during the export operation
    """

    req = self.url + "/api/connector/misp/export/{0}/{1}".format(case_id, misp_id)
    try:
        return requests.post(req, headers={'Content-Type': 'application/json'}, proxies=self.proxies,
                             json={}, auth=self.auth, verify=self.cert)
    except requests.exceptions.RequestException as e:
        raise TheHiveException("MISP export error: {}".format(e))

find_alerts(self, **attributes) #

Find alerts using sort, pagination and a query

Parameters:

Name Type Description Default
query dict

A query object, defined in JSON format or using utiliy methods from thehive4py.query module

required
sort Array

List of fields to sort the result with. Prefix the field name with - for descending order and + for ascending order

required
range str

A range describing the number of rows to be returned

required

Returns:

Type Description
response (requests.Response)

Response object including a JSON array of alerts.

Exceptions:

Type Description
AlertException

An error occured during alert search

Source code in thehive4py/api.py
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
def find_alerts(self, **attributes):
    """
    Find alerts 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 alerts.

    Raises:
        AlertException: An error occured during alert search
    """

    return self.__find_rows("/api/alert/_search", **attributes)

find_case_templates(self, **attributes) #

Find case templates using a query, sort and pagination

Parameters:

Name Type Description Default
query dict

A query object, defined in JSON format or using utiliy methods from thehive4py.query module

required
sort Array

List of fields to sort the result with. Prefix the field name with - for descending order and + for ascending order

required
range str

A range describing the number of rows to be returned

required

Returns:

Type Description
response (requests.Response)

Response object including a JSON array of case templates

Exceptions:

Type Description
TheHiveException

An error occured during case template search

Source code in thehive4py/api.py
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
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)

find_cases(self, **attributes) #

Find cases using sort, pagination and a query

Parameters:

Name Type Description Default
query dict

A query object, defined in JSON format or using utiliy methods from thehive4py.query module

required
sort Array

List of fields to sort the result with. Prefix the field name with - for descending order and + for ascending order

required
range str

A range describing the number of rows to be returned

required

Returns:

Type Description
response (requests.Response)

Response object including a JSON array of cases.

Exceptions:

Type Description
CaseException

An error occured during case search

Source code in thehive4py/api.py
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
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)

find_first(self, **attributes) #

Find cases and return just the first record

Parameters:

Name Type Description Default
query dict

A query object, defined in JSON format or using utiliy methods from thehive4py.query module

required
sort Array

List of fields to sort the result with. Prefix the field name with - for descending order and + for ascending order

required

Returns:

Type Description
response (dict)

A dict object describing the first case resulting from the query and sort options.

Exceptions:

Type Description
CaseException

An error occured during case search

Source code in thehive4py/api.py
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
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))

find_observables(self, **attributes) #

Find observables using sort, pagination and a query

Parameters:

Name Type Description Default
query dict

A query object, defined in JSON format or using utiliy methods from thehive4py.query module

required
sort Array

List of fields to sort the result with. Prefix the field name with - for descending order and + for ascending order

required
range str

A range describing the number of rows to be returned

required

Returns:

Type Description
response (requests.Response)

Response object including a JSON array of observables.

Exceptions:

Type Description
ObservableException

An error occured during observable search

Source code in thehive4py/api.py
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
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)

find_task_logs(self, **attributes) #

Find task logs using sort, pagination and a query

Parameters:

Name Type Description Default
query dict

A query object, defined in JSON format or using utiliy methods from thehive4py.query module

required
sort Array

List of fields to sort the result with. Prefix the field name with - for descending order and + for ascending order

required
range str

A range describing the number of rows to be returned

required

Returns:

Type Description
response (requests.Response)

Response object including a JSON array representing a list of case task logs

Exceptions:

Type Description
CaseTaskException

An error occured during case task log search

Source code in thehive4py/api.py
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
def find_task_logs(self, **attributes):
    """
    Find task logs 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 representing a list of case task logs

    Raises:
        CaseTaskException: An error occured during case task log search
    """

    return self.__find_rows("/api/case/task/log/_search", **attributes)

find_tasks(self, **attributes) #

Find case tasks using sort, pagination and a query

Parameters:

Name Type Description Default
query dict

A query object, defined in JSON format or using utiliy methods from thehive4py.query module

required
sort Array

List of fields to sort the result with. Prefix the field name with - for descending order and + for ascending order

required
range str

A range describing the number of rows to be returned

required

Returns:

Type Description
response (requests.Response)

Response object including a JSON array of case tasks.

Exceptions:

Type Description
AlertException

An error occured during case task search

Source code in thehive4py/api.py
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
def find_tasks(self, **attributes):
    """
    Find case tasks 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 case tasks.

    Raises:
        AlertException: An error occured during case task search
    """

    return self.__find_rows("/api/case/task/_search", **attributes)

get_alert(self, alert_id, similar_cases=False) #

Get an alert by its id

Parameters:

Name Type Description Default
alert_id str

Id of the alert

required
similar_cases bool

True if similar cases should be retrieved (Default False)

False

Returns:

Type Description
response (requests.Response)

Response object including a JSON representation of the alert

Exceptions:

Type Description
AlertException

An error occured during alert update

Source code in thehive4py/api.py
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
def get_alert(self, alert_id, similar_cases=False):
    """
    Get an alert by its id

    Arguments:
        alert_id (str): Id of the alert
        similar_cases (bool): True if similar cases should be retrieved (Default False)

    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)

    params = {}

    if similar_cases:
        params = {
            "similarity": int(similar_cases)
        }

    try:
        return requests.get(req, proxies=self.proxies, params=params, auth=self.auth, verify=self.cert)
    except requests.exceptions.RequestException as e:
        raise AlertException("Alert fetch error: {}".format(e))

get_case(self, case_id) #

Get a case by id

Parameters:

Name Type Description Default
case_id str

Case identifier

required

Returns:

Type Description
response (requests.Response)

Response object including a JSON description of the case.

Exceptions:

Type Description
CaseException

An error occured during case fetch

Source code in thehive4py/api.py
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
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))

get_case_observable(self, observable_id) #

Get a case observable by its id

Parameters:

Name Type Description Default
observable_id str

Case observable identifier

required

Returns:

Type Description
response (requests.Response)

Response object including a JSON representation of the case observable

Exceptions:

Type Description
CaseObservableException

An error occured during case observable fetch

Source code in thehive4py/api.py
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
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))

get_case_observables(self, case_id, **attributes) #

Find observables of a given case identified by its id

Parameters:

Name Type Description Default
case_id str

Id of the case

required
query dict

A query object, defined in JSON format or using utiliy methods from thehive4py.query module

required
sort Array

List of fields to sort the result with. Prefix the field name with - for descending order and + for ascending order

required
range str

A range describing the number of rows to be returned

required

Returns:

Type Description
response (requests.Response)

Response object including a JSON array of case observable.

Exceptions:

Type Description
CaseObservableException

An error occured during case observable search

Source code in thehive4py/api.py
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
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))

get_case_task(self, task_id) #

Get a case task by its id

Parameters:

Name Type Description Default
task_id str

Case task identifier

required

Returns:

Type Description
response (requests.Response)

Response object including a JSON representation of the case task

Exceptions:

Type Description
CaseTaskException

An error occured during case task fetch

Source code in thehive4py/api.py
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
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))

get_case_tasks(self, case_id, **attributes) #

Find tasks of a given case identified by its id

Parameters:

Name Type Description Default
case_id str

Id of the case

required
query dict

A query object, defined in JSON format or using utiliy methods from thehive4py.query module

required
sort Array

List of fields to sort the result with. Prefix the field name with - for descending order and + for ascending order

required
range str

A range describing the number of rows to be returned

required

Returns:

Type Description
response (requests.Response)

Response object including a JSON array of case task.

Exceptions:

Type Description
CaseTaskException

An error occured during case task search

Source code in thehive4py/api.py
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
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))

get_case_template(self, name) #

Get a case template by its name

Parameters:

Name Type Description Default
name str

Case template's name

required

Returns:

Type Description
response (requests.Response)

Response object including a JSON representation of the case template

Exceptions:

Type Description
CaseTemplateException

An error occured during case template fetch

Source code in thehive4py/api.py
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
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))

get_current_user(self) #

Method to call the /api/current endpoint, returning the current authenticated user.

Returns:

Type Description
response (requests.Response)

Response object including a JSON description of the current user

Exceptions:

Type Description
TheHiveException

Generic exception if an error occurs

Source code in thehive4py/api.py
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
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))

get_linked_cases(self, case_id) #

Find related cases of a given case identified by its id

Parameters:

Name Type Description Default
case_id str

Id of the case

required

Returns:

Type Description
response (requests.Response)

Response object including a JSON array of related cases.

Exceptions:

Type Description
CaseException

An error occured during case links fetch

Source code in thehive4py/api.py
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
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))

get_task_log(self, log_id) #

Get a case task log by its id

Parameters:

Name Type Description Default
log_id str

Case task log identifier

required

Returns:

Type Description
response (requests.Response)

Response object including a JSON representation of the case task log

Exceptions:

Type Description
CaseTaskException

An error occured during case task log fetch

Source code in thehive4py/api.py
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
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))

get_task_logs(self, task_id, **attributes) #

Get logs of a case task by its id

Parameters:

Name Type Description Default
task_id str

Case task identifier

required
query dict

A query object, defined in JSON format or using utiliy methods from thehive4py.query module

required
sort Array

List of fields to sort the result with. Prefix the field name with - for descending order and + for ascending order

required
range str

A range describing the number of rows to be returned

required

Returns:

Type Description
response (requests.Response)

Response object including a JSON array representing a list of case task logs

Exceptions:

Type Description
CaseTaskException

An error occured during case task log search

Source code in thehive4py/api.py
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
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)

health(self) #

Method to call the /api/health endpoint

Returns:

Type Description

Response object resulting from the API call.

Exceptions:

Type Description
TheHiveException

Generic exception if an error occurs

Source code in thehive4py/api.py
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
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))

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.

Parameters:

Name Type Description Default
alert_id str

Id of the alert

required

Returns:

Type Description
response (requests.Response)

Response object including a JSON representation of the alert

Exceptions:

Type Description
AlertException

An error occured during alert update

Source code in thehive4py/api.py
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
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))

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.

Parameters:

Name Type Description Default
alert_id str

Id of the alert

required

Returns:

Type Description
response (requests.Response)

Response object including a JSON representation of the alert

Exceptions:

Type Description
AlertException

An error occured during alert update

Source code in thehive4py/api.py
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
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))

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:

Source code in thehive4py/api.py
953
954
955
956
957
958
959
960
961
962
963
964
965
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))

promote_alert_to_case(self, alert_id, case_template=None) #

Create a new case from an alert, with an optional case template

Parameters:

Name Type Description Default
alert_id str

Id of the alert

required
case_template str

Case template name to apply when creating the cas

None

Returns:

Type Description
response (requests.Response)

Response object including a JSON representation of the alert

Exceptions:

Type Description
AlertException

An error occured during alert promotion

Source code in thehive4py/api.py
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
def promote_alert_to_case(self, alert_id, case_template=None):
    """
    Create a new case from an alert, with an optional case template

    Arguments:
        alert_id (str): Id of the alert
        case_template (str): Case template name to apply when creating the cas

    Returns:
        response (requests.Response): Response object including a JSON representation of the alert

    Raises:
        AlertException: An error occured during alert promotion
    """

    req = self.url + "/api/alert/{}/createCase".format(alert_id)

    try:
        return requests.post(req, headers={'Content-Type': 'application/json'},
                             proxies=self.proxies, auth=self.auth,
                             verify=self.cert, data=json.dumps({"caseTemplate": case_template}))

    except requests.exceptions.RequestException as the_exception:
        raise AlertException("Couldn't promote alert to case: {}".format(the_exception))

    return None

run_analyzer(self, cortex_id, artifact_id, analyzer_id) #

Create a new case from an alert, with an optional case template

Parameters:

Name Type Description Default
cortex_id

identifier of the Cortex server

required
artifact_id

identifier of the artifact as found with an artifact search

required
analyzer_id

name of the analyzer used by the job

required

Returns:

Type Description
response (requests.Response)

Response object including a JSON representation of the analysis job

Exceptions:

Type Description
TheHiveException

An error occured during job creation

Source code in thehive4py/api.py
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
def run_analyzer(self, cortex_id, artifact_id, analyzer_id):
    """
    Create a new case from an alert, with an optional case template

    Arguments:
        cortex_id: identifier of the Cortex server
        artifact_id: identifier of the artifact as found with an artifact search
        analyzer_id: name of the analyzer used by the job

    Returns:
        response (requests.Response): Response object including a JSON representation of the analysis job

    Raises:
        TheHiveException: An error occured during job creation
    """

    req = self.url + "/api/connector/cortex/job"

    try:
        data = json.dumps({ "cortexId": cortex_id,
            "artifactId": artifact_id,
            "analyzerId": analyzer_id
            })
        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 TheHiveException("Analyzer run error: {}".format(e))

update_alert(self, alert_id, alert, fields=[]) #

Update an alert completely or using specified fields

Parameters:

Name Type Description Default
alert_id str

Id of the alert

required
alert Alert

Instance of Alert

required
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:

Type Description
response (requests.Response)

Response object including a JSON representation of the alert

Exceptions:

Type Description
AlertException

An error occured during alert update

Source code in thehive4py/api.py
 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
1001
1002
1003
1004
1005
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)

    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 AlertException("Alert update error: {}".format(e))

update_alert_artifact(self, artifact_id, alert_artifact, fields=[]) #

Update an existing alert artifact

Parameters:

Name Type Description Default
artifact_id

Artifact identifier

required
alert_artifact AlertArtifact

Instance of AlertArtifact

required
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:

Type Description
response (requests.Response)

Response object including a JSON description of the updated alert artifact

Exceptions:

Type Description
AlertArtifactException

An error occured during alert artifact update

Warning

This function is available in TheHive 4 ONLY

Source code in thehive4py/api.py
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
def update_alert_artifact(self, artifact_id, alert_artifact, fields=[]):

    """
    Update an existing alert artifact

    Arguments:
        artifact_id: Artifact identifier
        alert_artifact (AlertArtifact): Instance of [AlertArtifact][thehive4py.models.AlertArtifact]
        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 alert artifact

    Raises:
        AlertArtifactException: An error occured during alert artifact update

    !!! Warning
        This function is available in TheHive 4 ONLY
    """

    if self.__isVersion(Version.THEHIVE_3.value):
        raise AlertArtifactException("This function is available in TheHive 4 ONLY")

    req = self.url + "/api/alert/artifact/{}".format(artifact_id)

    update_keys = ['message', 'tlp', 'tags', 'ioc', 'sighted', 'ignoreSimilarity']

    data = {k: v for k, v in alert_artifact.__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 CaseObservableException("Case observable update error: {}".format(e))

update_case(self, case, fields=[]) #

Update a case.

Parameters:

Name Type Description Default
case Case

Instance of Case to update. The case's id determines which case to update.

required
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:

Type Description
response (requests.Response)

Response object including a JSON description of a case

Exceptions:

Type Description
CaseException

An error occured during case creation

Source code in thehive4py/api.py
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
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))

update_case_observable(self, observable_id, case_observable, fields=[]) #

Update an existing case observable

Parameters:

Name Type Description Default
observable_id

Observable identifier

required
case_observable CaseObservable

Instance of CaseObservable

required
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:

Type Description
response (requests.Response)

Response object including a JSON description of the updated case observable

Exceptions:

Type Description
CaseObservableException

An error occured during case observable update

Source code in thehive4py/api.py
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
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))

update_case_observables(self, observable, fields=[]) #

[DEPRECATED] Update a case observable

Parameters:

Name Type Description Default
observable CaseObservable

Instance of CaseObservable to update. The observable's id determines which case to update.

required
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:

Type Description
response (requests.Response)

Response object including a JSON description of a case observable

Exceptions:

Type Description
CaseObservableException

An error occured during observable update

Source code in thehive4py/api.py
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
def update_case_observables(self, observable, fields=[]):
    """
    [DEPRECATED] Update a case observable

    Arguments:
        observable (CaseObservable): Instance of [CaseObservable][thehive4py.models.CaseObservable] to update. 
            The observable'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: [`tlp`, `ioc`, `sighted`, `tags`, `message`, `ignoreSimilarity`]

    Returns:
        response (requests.Response): Response object including a JSON description of a case observable

    Raises:
        CaseObservableException: An error occured during observable update
    """
    return self.update_case_observable(observable.id, observable, fields=fields)

update_case_task(self, task, fields=[]) #

Update a case task

Parameters:

Name Type Description Default
task CaseTask

Instance of CaseTask

required
fields array

Arry of strings representing CaseTask properties to be updated

Updatable fields are: [title, description, status, order, user, owner, flag, endDate]

[]

Returns:

Type Description
response (requests.Response)

Response object including a JSON description of a case task

Exceptions:

Type Description
CaseTaskException

An error occured during case task creation

Source code in thehive4py/api.py
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
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))

Last update: June 2, 2020 07:16:07