Code Monkey home page Code Monkey logo

thehive4py's Introduction

TheHive Logo

thehive4py - the de facto Python API client of TheHive

Discord License PyPI CICD

thehive4py

Important

thehive4py v1.x is not maintained anymore as TheHive v3 and v4 are end of life. thehive4py v2.x is a complete rewrite and is not compatible with thehive4py v1.x. The library is still in beta phase.

What's New: This is a rebooted version of thehive4py designed specifically for TheHive 5. Stay tuned, as we have more exciting updates in store!

Welcome to thehive4py, the Python library designed to simplify interactions with TheHive 5.x. Whether you're a cybersecurity enthusiast or a developer looking to integrate TheHive into your Python projects, this library has got you covered.

Feel free to explore the library's capabilities and contribute to its development. We appreciate your support in making TheHive integration in Python more accessible and efficient.

Quickstart

Requirements

thehive4py works with all currently supported python versions, at the time of writing py>=3.8. One can check the official version support and end of life status here.

Installation

The thehive4py can be installed with pip like:

pip install "thehive4py>=2.0.0b"

Warning

Since thehive4py 2.x is still in beta it is necessary to specify the beta version number during pip install, otherwise the latest version of 1.x would be installed.

Create a client

You can create a thehive4py client instance in two different ways, depending on your authentication method:

Method 1: Username/password authentication

If you're using a username and password for authentication, you can create a client like this:

from thehive4py import TheHiveApi

hive = TheHiveApi(
        url="https://thehive.example.com",
        username="[email protected]",
        password="supersecret",
    )

Method 2: Apikey authentication

Alternatively, if you prefer using an API key for authentication, use this method:

from thehive4py import TheHiveApi

hive = TheHiveApi(
        url="https://thehive.example.com",
        apikey="c0ff33nc0d3",
    )

Choose the authentication method that best suits your needs and security requirements.

Create an alert

To create a new alert, you can use the client's alert.create method with the following minimally required fields:

  • type: The type of the alert.
  • source: The source of the alert.
  • sourceRef: A unique reference for the alert.
  • title: A descriptive title for the alert.
  • description: Additional information describing the alert.

Here's an example that demonstrates how to create a new alert with these required fields:

my_alert = hive.alert.create(
    alert={
        "type": "my-alert",
        "source": "my-source",
        "sourceRef": "my-reference",
        "title": "My test alert",
        "description": "Just a description",
    }
)

The above snippet will create a new alert with the minimally required fields and will store the output alert response in the my_alert variable.

Note

Attempting to create another alert with the same values for type, source, and sourceRef will not be accepted by the backend as the combination of the three fields should be unique per alert.

Add alert observables

To make your alerts more informative and actionable, you can add observables to them. Observables are specific pieces of data related to an alert. In this example, we'll enhance the previous alert with two observables: an IP address 93.184.216.34 and a domain example.com.

Method 1: Adding observables individually

You can add observables to an existing alert using the alert.create_observable method as shown below:

hive.alert.create_observable(
    alert_id=my_alert["_id"],
    observable={"dataType": "ip", "data": "93.184.216.34"},
)
hive.alert.create_observable(
    alert_id=my_alert["_id"],
    observable={"dataType": "domain", "data": "example.com"},
)

This method is useful when you want to add observables to an alert after its initial creation.

Method 2: Adding observables during alert creation

Alternatively, if you already know the observables when creating the alert, you can use the observables field within the alert creation method for a more concise approach:

my_alert = hive.alert.create(
    alert={
        "type": "my-alert",
        "source": "my-source",
        "sourceRef": "my-reference",
        "title": "My test alert",
        "description": "Just a description",
        "observables": [
            {"dataType": "ip", "data": "93.184.216.34"},
            {"dataType": "domain", "data": "example.com"},
        ],
    }
)

This method not only saves you from making additional network requests but also reduces the chance of errors, making your code more efficient and reliable.

By incorporating observables into your alerts, you provide valuable context and information for further analysis and incident response.

Update an alert

If you need to add or modify fields in an existing alert, you can easily update it using client's alert.update method. In this example, we'll add a tag my-tag and change the alert's title:

hive.alert.update(
    alert_id=my_alert["_id"],
    fields={
        "title": "My updated alert",
        "tags": ["my-tag"],
    },
)

The code above updates the alert's title and adds a new tag to the alert in TheHive.

It's essential to understand that the my_alert object in your Python code will not automatically reflect these changes. thehive4py doesn't provide object relationship mapping features. To get the latest version of the alert after making modifications, you need to fetch it again:

my_alert = hive.alert.get(alert_id=my_alert["_id"])

After this request, my_alert["title"] will be "My Updated Alert", and my_alert["tags"] will include "my-tag". This ensures that you have the most up-to-date information in your Python code.

Create a case

You have two options to create a case in thehive4py: either promote an existing alert to a case or create a new, empty case.

Method 1: Promote an existing alert to a case

You can convert an existing alert into a case and associate it with that alert using the alert.promote_to_case method:

my_case = hive.alert.promote_to_case(alert_id=my_alert["_id"])

This method will create a case based on the existing alert and automatically assign the alert to the case. Any observables from the alert will also be copied as case observables.

Method 2: Create an empty case

Alternatively, you can create a new, empty case using the case.create method:

my_case = hive.case.create(
    case={"title": "My First Case", "description": "Just a description"}
)

This method creates a fresh case with no alerts or observables attached.

To merge an existing alert into a new case at a later time, use the alert.merge_into_case method:

hive.alert.merge_into_case(alert_id=my_alert["_id"], case_id=my_case["_id"])

By choosing the method that suits your workflow, you can efficiently manage cases and alerts within TheHive using thehive4py.

Query Case Observables

To retrieve observables from a case, you can use the case.find_observables method provided by thehive4py. This method supports various filtering and querying options, allowing you to retrieve specific observables or all observables associated with a case.

Retrieve All Observables of a Case

To retrieve all the observables of a case, use the following code:

case_observables = hive.case.find_observables(case_id=my_case["_id"])

Retrieve Specific Observables of a Case

If you want to retrieve specific observables based on criteria, you can leverage TheHive's powerful query capabilities. You can refer to the official Query API documentation for more details.

Here's an example of how to retrieve IP observables from a case:

ip_observable = hive.case.find_observables(
    case_id=my_case["_id"], filters=Eq("dataType", "ip") & Like("data", "93.184.216.34")
)

In this example, we use the Eq, Like and the & operators filters to specify the criteria for the query. You can also achieve the same result using a dict-based approach for filtering:

ip_observable = hive.case.find_observables(
    case_id=my_case["_id"],
    filters={
        "_and": [
            {"_field": "dataType", "_value": "ip"},
            {"_like": {"_field": "data", "_value": "93.184.216.34"}},
        ]
    }
)

The dict-based approach is possible, but we recommend using the built-in filter classes for building query expressions due to their ease of use.

Currently, the filter classes support the following operators:

  • &: Used for the Query API's _and construct.
  • |: Used for the Query API's _or construct.
  • ~: Used for the Query API's _not construct.

These operators provide a convenient and intuitive way to construct complex queries.

Development

Setting up a virtual environment (optional)

A virtual environment is highly recommended for clean and isolated Python development. It allows you to manage project-specific dependencies and avoid conflicts with other projects. In case you don't know what is/how to use a virtual environment let's find out more here.

Install the package for development

If you are a first time contributor to github projects please make yourself comfortable with the page contributing to projects.

Navigate to the cloned repository's directory and install the package with development extras using pip:

pip install -e .[dev]

This command installs the package in editable mode (-e) and includes additional development dependencies.

Now, you have the thehive4py package installed in your development environment, ready for contributions.

Contributing

To contribute to thehive4py, follow these steps:

  1. Create an issue: Start by creating an issue that describes the problem you want to solve or the feature you want to add. This allows for discussion and coordination with other contributors.

  2. Create a branch: Once you have an issue, create a branch for your work. Use the following naming convention: <issue-no>-title-of-branch. For example, if you're working on issue #1 and updating the readme, name the branch 1-update-readme.

Run CI checks before pushing changes

To ensure the integrity of your changes and maintain code quality, you can run CI checks before pushing your changes to the repository. Use one of the following methods:

Method 1: Manual check

Run the CI checks manually by executing the following command:

python scripts/ci.py 

This command will trigger the CI checks and provide feedback on any issues that need attention.

Method 2: Automatic checks with pre-commit hooks [experimental]

Note

The pre-commit hooks are not thoroughly tested at the moment and probably broken

For a more streamlined workflow, you can install pre-commit hooks provided by the repository. These hooks will automatically execute checks before each commit. To install them, run:

pre-commit install

With pre-commit hooks in place, your changes will be automatically validated for compliance with coding standards and other quality checks each time you commit. This helps catch issues early and ensures a smooth contribution process.

Testing

Note

Since TheHive 5.3 the licensing constraints has been partially lifted therefore a public integrator image is available for running tests both locally and in github.

thehive4py primarily relies on integration tests, which are designed to execute against a live TheHive 5.x instance. These tests ensure that the library functions correctly in an environment closely resembling real-world usage.

Test requirements

Since the test suite relies on the existence of a live TheHive docker container a local docker engine installation is a must. If you are unfamiliar with docker please check out the official documentation.

Test setup

The test suite relies on the official thehive-image to create a container locally with the predefined name thehive4py-integration-tester which will act as a unique id.
The container will expose TheHive on a random port to make sure it causes no conflicts for any other containers which expose ports.
The suite can identify this random port by querying the container info based on the predefined name. Once TheHive is responsive the suite will initialize the instance with a setup required by the tests (e.g.: test users, organisations, etc.).
Please note that due to this initial setup the very first test run will idle for some time to make sure everything is up and running. Any other subsequent runs' statup time should be significantly faster.

Testing locally

To execute the whole test suite locally one can use the scripts/ci.py utility script like:

./scripts/ci.py --test

Note however that the above will execute the entire test suite which can take several minutes to complete. In case one wants to execute only a portion of the test suite then the easiest workaround is to use pytest and pass the path to the specific test module. For example to only execute tests for the alert endpoints one can do:

pytest -v tests/test_alert_endpoint.py

thehive4py's People

Contributors

ater49 avatar black-pearl25 avatar jamesmckibbenathrb avatar kamforka avatar lamachin3 avatar mike1796 avatar nadouani avatar vdebergue avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

thehive4py's Issues

Allow file observable creation from memory

Request Type

Feature Request

Summary

Allow file observable creation from memory

Description

Currently, to create a file observable, it is needed to provide the path to the file to TheHive4py.
It would be nice to allow file observable creation from memory.
Basically, in some case, it is not well-designed to write the file to disk and then delete it "just" for observable creation.

Add an API method to create users

Request Type

Feature Request

Problem Description

Not being able to create users programatically defeats the purpose of the (great) SSO feature already in place in TheHive.

Possible Solution

Add an API method to create users.

Thanks & Keep on Hiving

Adding option for an Internal CA

How to verify certificate signed by internal CA

Hi, my organization wants to explore TheHive however all our internal services use certificates signed by an internal CA. I think there does not seem to be any support for this as of now, wondering if this might be included in the future.

Use basic auth when calling TheHive apis

Request Type

Bug

Work Environment

Question Answer
TheHive 2.10.2
TheHive4py version / git hash 1.1.0

Problem Description

TheHive 2.10.2 introduced a protection against CSRF attacks that requires a CSRF that the backend provides when APIs are called from the TheHive's UI.

This is not valid for API calls made from TheHive4Py that needs to authenticate every API call using Basic Authentication.

Query for creating alert

how can I generate a alert of any email of outlook, with attachment attached in that email, in the hive? , where I have to do changes for creating any alert?

Tasks missing for creating case using a template

Request Type

Bug

Work Environment

Question Answer
OS version (server) Ubuntu,
OS version (client) 10,
TheHive4py version / git hash 1.4.3

Problem Description

There seems to be a problem with creating a case from a template.
If the template contains a task, it does not appear in the created task.

Steps to Reproduce

  1. create a case template containing a task
  2. fetch the case template via
  3. create a new case using the template
  4. check TheHive. Task is missing in the case.

Possible Solutions

    # if self.template.get('tasks', []):
    #     tasks.extend(self.template.get('tasks', []))
    #

in Case class init adds the template tasks.

Add support of custom fields to the case model

Request Type

Feature Request

Problem Description

TheHive added support to case custom fields, but TheHive4Py didn't allow setting this attribute. We need to enhance the Case model class to support providing custom fields

The custom fields should also be available on the CaseTemplate class

Run Cortex analyzer through api

Request Type

Question/Feature Request

Problem Description

Is it possible to run an Cortex analyzer with an given observableID from a python script?

Add a find_alerts method to search for alerts

Request Type

Feature Request

Problem Description

The goal here is to provide a function to search for alerts. This function should accept the following options: query, range and sort like the find_cases function

Add the ability to search for all active observables where ioc:true without knowing caseIds

Request Type

Feature Request

Problem Description

The endpoint /api/_search is not exposed. Current methods to find observables require knowing the caseId. To find all observables which have ioc:true and list which case they are associated with a new function is required.

Possible Solutions

Add the following to api.py

def get_IOCs(self, **attributes):
    """
    :return: list of IOCs
    ;rtype: json
    """

    # If you don't add the nparent parameter, you don't get the 'case' in the json
    req = self.url + "/api/_search?nparent=1"

    # Add range and sort parameters
    params = {
        "range": attributes.get("range", "all"),
        "sort": attributes.get("sort", [])
    }

    # Add body, pulled from gui in Chrome
    data = {
        "query":{"_and":[{"_string":"ioc:true"},{"_string":"!_type:audit AND !_type:data AND !_type:user AND !_type:analyzer AND !_type:alert AND !_type:case_artifact_job_log AND !status:Deleted"}]}
    }
    
    try:
        return requests.post(req, params=params, json=data, proxies=self.proxies, auth=self.auth, verify=self.cert)
    except requests.exceptions.RequestException as e:
        sys.exit("Error: {}".format(e))

Alternatively, exposing the /api/_search endpoint with a similar function that allows for customized queries would achieve the same end result.

Complementary information

Attached is a Python script iocTest.txt to drive this change (rename from .txt to .py)
The script uses username / password but could be easily adapted to use an api-key.

Error creating alert

Request Type

Bug

Problem Description

API doesn't found Alert, AlertArtifacts in model

Steps to Reproduce

If you try to run the sample to create alert, it exits with an error.

image

xsrf-token in theHive4py

Problem Description

Hi !
Is there any solution to get "xserf-token" in theHive4py?

I'm trying to do auto-analyze after the creation of a case

And I wrote a funcion in the "api.py" file

 def do_analyze(self, cortex_id, observable_id, analyzer_id):

        req = self.url + '/api/connector/cortex/job'
        print ("request url: " + req)

        my_job = {
            "cortexId": cortex_id,
            "artifactId": observable_id,
            "analyzerId": analyzer_id
        }

       my_header = {
            "X-XSRF-TOKEN": ''....",
            "Cookie": "...."
       }
        try:
            response = requests.post(req, headers=my_header, data=my_job, proxies=self.proxies, verify=self.cert)
        except Exception as e:
            return e

Now I have to use tools like burp suite to get the "XSRF-TOKEN" and "Cookie" from web interface

It works but not a convenient way

Case model is missing the required `status` attribute

Request Type

Bug

Work Environment

Question Answer
TheHive4py version 1.2.3

Problem Description

As specified in the documentation, the Case model has a required status attribute which can take any value in [Open, Resolved, Deleted] with Open as the default.

The Case model in TheHive4py does not have such attribute. As a consequence, when instantiating a new Case from JSON data as returned by the API, the status attribute is discarded.

Steps to Reproduce

Instantiate a Case object with a case in its JSON form as produced by TheHive API (2.12.1) (thehive.api.models.Case(json=case_as_json)).

Support several small functions in TheHive4py

Request Type

Feature Request

Problem Description

Several small functions are currently not available in TheHive4py.
Some examples, I was confronted with:
-Check for existens of an Tag attribute on a case
-Find all Tasks of a Case
-Get technical ID of UI caseID
-Get UI caseID of technical CaseId
-Iterate over task-log entries within a task.
-Add, removed, Edit a customField

BTW: Better naming would be helpful, because caseId could be interpreted as both. in the documentation and code examples...

Search for cases

Add a method to search for text into cases. Return a list of cases.

Correction in update_case usage

Request Type

Bug

Work Environment

Question Answer
OS version (server) Debian, Ubuntu, CentOS, RedHat, ...
OS version (client) XP, Seven, 10, Ubuntu, ...
TheHive4py version / git hash 1.4.2

Problem Description

Describe the problem/bug as clearly as possible.

The current update_case method take an object which contains case id and other fields that need to be updated.

The line shows that you create a case object which unnecessarily update the defaults of the case.

Steps to Reproduce

try to use the update method to update only a particular field of the case.

Possible Solutions

either change the update_case method parameter to accept case_id and attributes of case to update as **kwargs or create a pojo for the update_case.

Add support to authentication by API key

Request Type

Feature Request

Problem Description

Currently, TheHive4Py allows basic authentication only. And since TheHive 2.13.0 will provide the ability to call the APIs using an API Key, we need to support this type of authentication mechanism to TheHive4Py library, without breaking the basic authentication support that already exists.

Add a query builder capabilities

Request Type

Feature Request

Problem Description

TheHive comes with a query syntax to use to search for any type of data. This query DSL is rich and based on a JSON syntax that some people might find ugly.

The goal of this task is to provide helper function to produce search queries

Unify the naming of statuses and filters

Request Type

Bug

Work Environment

Question Answer
OS version (server) RedHat
OS version (client) Seven
TheHive4py version / git hash 3.0.6

Problem Description

Discrepancy between case statuses and filter status values.

Steps to Reproduce

  1. Open List of Cases
  2. Filter to see closed cases
  3. Filter is named "status=Resolved"

Possible Solutions

Unify the naming convention between filters and case statuses

Error updating case

Have just noticed that in #50 I seem to have broken case creation. The test-case-create.py script fails with:

ko: 400/{"tableName":"case","type":"AttributeCheckingError","errors":[[{"name":"case.updatedAt","value":{"type":"JsonInputValue","value":null},"type":"UnknownAttributeError","message":"Unknown attribute case.updatedAt: {"type":"JsonInputValue","value":null}"},{"name":"case.caseId","value":{"type":"JsonInputValue","value":null},"type":"UnknownAttributeError","message":"Unknown attribute case.caseId: {"type":"JsonInputValue","value":null}"},{"name":"case.id","value":{"type":"JsonInputValue","value":null},"type":"UnknownAttributeError","message":"Unknown attribute case.id: {"type":"JsonInputValue","value":null}"},{"name":"case.createdAt","value":{"type":"JsonInputValue","value":null},"type":"UnknownAttributeError","message":"Unknown attribute case.createdAt: {"type":"JsonInputValue","value":null}"},{"name":"case.createdBy","value":{"type":"JsonInputValue","value":null},"type":"UnknownAttributeError","message":"Unknown attribute case.createdBy: {"type":"JsonInputValue","value":null}"},{"name":"case.updatedBy","value":{"type":"JsonInputValue","value":null},"type":"UnknownAttributeError","message":"Unknown attribute case.updatedBy: {"type":"JsonInputValue","value":null}"}]]}

Sorry @nadouani I didn't run the test scripts before submitting the change.

Rather than setting these attributes to None it may be best to only add the attributes if they exist in the 'json' parameter, or modify create_case to exclude them. I can fix that up.

Add the ability to create a TheHive alert

Request Type

Feature Request

Work Environment

Question Answer
TheHive version 2.11.x

Problem Description

TheHive 2.11.0 will introduce an alerting framework where it exposes an API to create an alert that could be then converted to cases.

Currently TheHive4Py users create case directly without going through the alertstep.

find_cases query on custom field (for template cases)

Is it possible to use the find_cases function to query on template cases regarding the custom fields ?

In case not, is it possible to write my own function to do it using the API ?

I have a crappy solution consisting in querying all the cases and then filter the cases matching to my query but it spend lot of memory.

Feature Request - Task Log Template/Boilerplate Text

When working with Case Templates, a nice feature to have would be the ability to define Task Log Template text for each Case Template Task so that boilerplate verbiage is added to the Task Log upon creation.

The use case for this feature is an environment where varying levels of Analyst will work on a given task and the SOC manager wants to ensure that the tasks contains specific information in a consistent manner.

Request Type

Feature Request

Problem Description

As of right now, a Task Log does not have the ability to have template text and/or boilerplate text. To do something similar, you would have to provide guidance to the Analyst in the Task Description field and the analyst assigned to the Task would have to copy and paste that information into the Task Log.

Steps to Reproduce

N/A

Possible Solutions

Modify case_task so that it has an additional field for storing Task Log templates. A case_task_log assigned to that task, will have the boilerplate added to the message field of the Task Log upon creation.

Complementary information

N/A

Allow specifying range to return > 10 cases, observables, etc.,

Request Type

Feature Request

Problem Description

TheHive returns the 10 first elements (case, task, observable, ...). In the REST API you can specify the number of element you want using the parameter range (eg. "0-40"). Currently, you can't provide this parameter to TheHive4py.

certificate verify option not included in create_case_task

Request Type

Bug

Work Environment

Question Answer
OS version (server) Docker
OS version (client) Ubuntu
TheHive4py version / git hash 512af3a

Problem Description

In line 67 of api.py, the option to specify certificate validation isn't included.

Steps to Reproduce

Attempt to disable certificate validation and then call create_case_task

Possible Solutions

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

Complementary information

N/A

Provide just the template name when creating a case from a template

Request Type

Enhancement

Problem Description

Creating a case from a template requires just to provide the template name, and no longer needs all the details of the template. The backend is responsible of setting the case attributes based on the template definition.

Keep analyzer reports when merging a case

Request Type

Bug

Work Environment

| OS version (server) | Debian
| TheHive4py version | 3.0.9

Problem Description

When I merge a case containing observables and anayzer reports with another case :
The new merged case is created with the observables but I have to run the analyzers again.
That's a problem because if there are a lot of cases that need to be
consecutively merged with the same case, all the analyzers have to be relaunched at each merge instead of keeping the reports of the first case.

2nd typo in setup.py

When installing:

dc@3356cc050db4:~/InTheMiddle/TheHive4py$ sudo python setup.py install
running install
running bdist_egg
running egg_info
creating thehive4py.egg-info
writing requirements to thehive4py.egg-info/requires.txt
writing thehive4py.egg-info/PKG-INFO
writing top-level names to thehive4py.egg-info/top_level.txt
writing dependency_links to thehive4py.egg-info/dependency_links.txt
writing manifest file 'thehive4py.egg-info/SOURCES.txt'
error: package directory 'thehive4py' does not exist

Because line 15 of setup.py is:

packages=['thehive4py']

While the folder is named TheHive4py.

Not sure what's the best practice between renaming the folder or line 15...

Typo in setup.py

When installing, the following error appears:

dc@server:~/InTheMiddle/TheHive4py$ python setup.py install
Traceback (most recent call last):
  File "setup.py", line 9, in <module>
    long_description=open('README.MD').read(),
IOError: [Errno 2] No such file or directory: 'README.MD'

Because line 9 of setup.py is :

long_description=open('README.MD').read(),

While the file is named README.md.

Fixing the typo gets rid of the error.

Searching For Cases

Hello, i am using the test-case-search.py template to search for open/closed cases which happened in the previous 3 days and i was wondering how would i be able to achieve that? Is there any documentation regarding the variables used for the find_cases function?

Thanks

File handle remains open

Problem Description

When creating a file observable the file object remains open, file cannot be deleted.

Steps to Reproduce

  1. Create CaseObservable with type 'file'
  2. Push this observable to TH (TheHiveApi.create_case_observable)
  3. delete file => error, file is used by another process

Make api return dictionaries, not raw responses

Feature Request

I think it would be great to incapsulate responses. Right now API object returns raw responses and responses most of the times contain json. Why not return pretty dictionaries? It would simplify the work with api, when user often has to do json.loads().

Raise custom exceptions from api methods instead of calling sys.exit

Request Type

Enhancement

Problem Description

The methods provided by the thehive4py.TheHiveApi class should throw exceptions instead of exiting the program when an error occur. This will allow developer to handle the exceptions thrown by the library instead of having their programs quit unexpectedly .

Basic auth doesn't work with version 1.3.0

Request Type

Bug

Work Environment

Question Answer
TheHive4py version 1.3.0

Problem Description

error when using thehive4py with login/password HTTP basic authentication.

Possible Solutions

--- a/thehive4py/api.py
+++ b/thehive4py/api.py
@@ -42,8 +42,7 @@ class TheHiveApi:
         self.proxies = proxies
 
         if self.password is not None:
-            self.auth = requests.auth.HTTPBasicAuth(principal=self.principal,
-                                                    password=self.password)
+            self.auth = requests.auth.HTTPBasicAuth(self.principal, self.password)

CustomFields are not updated in update_case

Request Type

Bug

Problem Description

Changes to the customFields attribute of a case are not sent when using api.update_case(case)

Possible Solutions

Add customFields to the following lines,

update_keys = [
'title', 'description', 'severity', 'startDate', 'owner', 'flag', 'tlp', 'tags', 'resolutionStatus',
'impactStatus', 'summary', 'endDate', 'metrics'
]

SSLError

Hello,

I use thehive4py for alerting on thehive from RSA SIEM.

Thehive url is usign ssl, and i have this error :

Create Alert

Traceback (most recent call last):
  File "/usr/local/lib/python3.5/site-packages/urllib3-1.22-py3.5.egg/urllib3/connectionpool.py", line 589, in urlopen
    conn = self._get_conn(timeout=pool_timeout)
  File "/usr/local/lib/python3.5/site-packages/urllib3-1.22-py3.5.egg/urllib3/connectionpool.py", line 251, in _get_conn
    return conn or self._new_conn()
  File "/usr/local/lib/python3.5/site-packages/urllib3-1.22-py3.5.egg/urllib3/connectionpool.py", line 827, in _new_conn
    raise SSLError("Can't connect to HTTPS URL because the SSL "
urllib3.exceptions.SSLError: Can't connect to HTTPS URL because the SSL module is not available.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.5/site-packages/requests-2.18.4-py3.5.egg/requests/adapters.py", line 440, in send
    timeout=timeout
  File "/usr/local/lib/python3.5/site-packages/urllib3-1.22-py3.5.egg/urllib3/connectionpool.py", line 639, in urlopen
    _stacktrace=sys.exc_info()[2])
  File "/usr/local/lib/python3.5/site-packages/urllib3-1.22-py3.5.egg/urllib3/util/retry.py", line 388, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='10.84.10.10', port=443): Max retries exceeded with url: /api/alert (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.",))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.5/site-packages/thehive4py-1.4.3-py3.5.egg/thehive4py/api.py", line 349, in create_alert
  File "/usr/local/lib/python3.5/site-packages/requests-2.18.4-py3.5.egg/requests/api.py", line 112, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "/usr/local/lib/python3.5/site-packages/requests-2.18.4-py3.5.egg/requests/api.py", line 58, in request
    return session.request(method=method, url=url, **kwargs)
  File "/usr/local/lib/python3.5/site-packages/requests-2.18.4-py3.5.egg/requests/sessions.py", line 508, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/local/lib/python3.5/site-packages/requests-2.18.4-py3.5.egg/requests/sessions.py", line 618, in send
    r = adapter.send(request, **kwargs)
  File "/usr/local/lib/python3.5/site-packages/requests-2.18.4-py3.5.egg/requests/adapters.py", line 506, in send
    raise SSLError(e, request=request)
requests.exceptions.SSLError: HTTPSConnectionPool(host='10.80.X.X', port=443): Max retries exceeded with url: /api/alert (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.",))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "test_alerte.py", line 121, in <module>
    thehive()
  File "test_alerte.py", line 109, in thehive
    response = api.create_alert(thehivealert)
  File "/usr/local/lib/python3.5/site-packages/thehive4py-1.4.3-py3.5.egg/thehive4py/api.py", line 351, in create_alert
thehive4py.exceptions.AlertException: Alert create error: HTTPSConnectionPool(host='10.80.X.X', port=443): Max retries exceeded with url: /api/alert (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.",))

How to close a case via API

It may be obvious, but how do I close an existing case via thehive4py (v 1.4.2) please? I tried to update a case with the following fields without success:

api = TheHiveApi(....)

hiveCase = api.case(caseId)

hiveCase.status='Resolved'
hiveCase.resolutionStatus='TruePositive'
hiveCase.impactStatus='NoImpact'
hiveCase.summary='closed by api'
hiveCase.tags=['test']

hiveResponse = api.update_case(hiveCase)

if hiveResponse.status_code == 200:
    logging.warning(json.dumps(hiveResponse.json(), indent=4, sort_keys=True))
else:
    logging.warning('ko: {}/{}'.format(hiveResponse.status_code, hiveResponse.text))

Thanks in advance

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.