thehive4py Python Client

repository·main·Indexed 42 days ago

https://github.com/thehive-project/thehive4py

A Python API client for TheHive 5.x (version 2.1.0) that allows developers to programmatically manage alerts, cases, and observables. It provides functionality for creating, updating, and deleting alerts and cases, as well as querying observables using built-in filter classes and operators.

Tokens
8.7K
Snippets
47
Records
51
Agent score
54%

What's inside thehive4py

  1. Add a comment to a case

    main

    Comments are lightweight entities used to leave feedback or notes for analysts within a case. You can add a comment to a case after it has been created.

    # Note: This example assumes a client and case_id are already initialized
    
    await case.create_comment(
        case_id,
        {
            "content": "This is a sample comment for the case."
        }
    )
  2. Authenticate with an API Key

    main

    You can authenticate with TheHive API using an apikey. This is typically done by passing the key during the client initialization.

    # Example pattern for API key authentication
    from thehive4py.client import TheHiveApi
    
    client = TheHiveApi(url='http://localhost:9000', api_key='YOUR_API_KEY')
  3. Configure SSL Verification

    main

    The client verifies SSL connections by default. You can customize this behavior using the verify argument:

    • Pass a path to a custom certificate bundle or directory.
    • Set verify=False to disable SSL verification (not recommended for security reasons).
    from thehive4py.client import TheHiveApi
    
    # Use a custom certificate bundle
    client = TheHiveApi(url='https://localhost:9000', api_key='YOUR_API_KEY', verify='/path/to/cert_bundle')
    
    # Disable SSL verification (discouraged)
    client = TheHiveApi(url='https://localhost:9000', api_key='YOUR_API_KEY', verify=False)
  4. Add MITRE ATT&CK procedures to a case

    main

    TheHive supports the MITRE ATT&CK framework via 'procedures'. You can enrich an existing case with specific tactics, techniques, and sub-techniques using the case.create_task method.

    When creating a procedure entity, the following fields are required:

    • occurDate: The timestamp of the occurrence.
    • patternId: The MITRE ATT&CK ID (e.g., T1566).

    Optional fields include tactic and description. You can use thehive4py.helpers.now_to_ts to generate valid timestamps for the occurDate field.

    # Note: This example assumes a client and case_id are already initialized
    # The procedure entity requires 'occurDate' and 'patternId'
    
    await case.create_task(
        case_id,
        {
            "type": "procedure",
            "patternId": "T1566.001",
            "occurDate": await helpers.now_to_ts(),
            "description": "Phishing - Spearphishing Attachment"
        }
    )
  5. Switch Organisations during Runtime

    main

    You can change the active organisation without re-instantiating the client by updating the session_organisation property on the TheHiveApi instance.

    !!! warning The session_organisation property is not thread-safe. If you need to work with multiple organisations in parallel, it is recommended to instantiate separate client instances instead.

    from thehive4py.client import TheHiveApi
    
    client = TheHiveApi(url='http://localhost:9000', api_key='YOUR_API_KEY')
    # Switch to a different organisation at runtime
    client.session_organisation = 'other_org'
  6. Promote or merge alerts into a case

    main

    Alerts can be transitioned into cases to organize investigations:

    • Promote to case: Use alert.promote_to_case to create a new case from an existing alert. You can pass a fields argument to customize the properties of the newly created case.
    • Merge into case: Use alert.merge_into_case to add an existing alert to an already established parent case.
    • Bulk merge: Use alert.bulk_merge_into_case to merge multiple alerts into a single parent case in one operation.
    --8<-- "examples/alert/case_promote.py"
    --8<-- "examples/alert/case_merge.py"
  7. Update single or bulk cases

    main

    Update a single case

    Use case.update(case_id, fields) to modify an existing case. The fields argument is a dictionary of the attributes you wish to change (e.g., title, tags).

    Note: thehive4py is a lightweight wrapper and does not perform Object-Relational Mapping (ORM). An existing local object will not automatically reflect updates made via the API; you must call case.get(case_id) to retrieve the updated version.

    Update multiple cases (Bulk)

    To update the same fields with the same values across multiple cases, use case.bulk_update. The fields dictionary must include an additional ids key containing a list of the case IDs to be updated.

    # Bulk update example
    # fields = {'title': 'New Title', 'tags': ['new_tag'], 'ids': ['id1', 'id2']}
    # case.bulk_update(fields)
  8. Add observables to a case

    main

    Unlike the Alert API, observables cannot be added during case creation; they must be added retroactively using case.create_observable.

    Simple and Bulk Observables

    Use the InputObservable type. The data property can accept either a single str or a list[str] for bulk creation.

    Limitation: When creating multiple observables in one call, they must all share the same dataType. If you need to add observables of different types, you must iterate through them and call create_observable individually.

    File-based Observables

    To add a file as an observable:

    1. Set dataType to 'file' in the observable metadata.
    2. Omit the data field.
    3. Provide the local file path in the observable_path argument.
    # File-based observable example
    # case.create_observable(
    #     metadata={'dataType': 'file'},
    #     observable_path='/path/to/file',
    #     data='observable_data'
    # )
  9. Configure Custom Retries

    main

    The client includes a default retry mechanism. You can customize this by passing a max_retries argument, which accepts a urllib3.Retry object. This allows you to define the number of attempts, backoff factors, and specific status codes to retry.

    from thehive4py.client import TheHiveApi
    from urllib3.util import Retry
    
    # Configure a custom retry mechanism
    custom_retry = Retry(total=5, backoff_factor=0.3, status_forcelist=[500])
    client = TheHiveApi(url='http://localhost:9000', api_key='YOUR_API_KEY', max_retries=custom_retry)