CB ThreatHunter API¶
This page documents the public interfaces exposed by cbapi when communicating with a Carbon Black Cloud ThreatHunter server.
Main Interface¶
To use cbapi with Carbon Black ThreatHunter, you use CbThreatHunterAPI objects.
These objects expose two main methods to access data on the
ThreatHunter server: select
and create
.
-
class
cbapi.psc.threathunter.rest_api.
CbThreatHunterAPI
(*args, **kwargs)¶ The main entry point into the Carbon Black Cloud ThreatHunter API.
Parameters: profile (str) – (optional) Use the credentials in the named profile when connecting to the Carbon Black server. Uses the profile named ‘default’ when not specified. Usage:
>>> from cbapi.psc.threathunter import CbThreatHunterAPI >>> cb = CbThreatHunterAPI(profile="production")
-
alert_search_suggestions
(query)¶ Returns suggestions for keys and field values that can be used in a search.
Parameters: str (query) – A search query to use. Returns: A list of search suggestions expressed as dict objects.
-
api_json_request
(method, uri, **kwargs)¶ Submit a request to the server.
- Args:
- method (str): HTTP method to use. uri (str): URI to submit the request to. **kwargs (dict): Additional arguments.
- Returns:
- object: Result of the operation.
- Raises:
- ServerError: If there’s an error output from the server.
-
bulk_threat_dismiss
(threat_ids, remediation=None, comment=None)¶ Dismiss the alerts associated with multiple threat IDs. The alerts will be left in a DISMISSED state after this request.
Parameters: - list (threat_ids) – List of string threat IDs.
- str (comment) – The remediation state to set for all alerts.
- str – The comment to set for all alerts.
Returns: The request ID, which may be used to select a WorkflowStatus object.
-
bulk_threat_update
(threat_ids, remediation=None, comment=None)¶ Update the alert status of alerts associated with multiple threat IDs. The alerts will be left in an OPEN state after this request.
Parameters: - list (threat_ids) – List of string threat IDs.
- str (comment) – The remediation state to set for all alerts.
- str – The comment to set for all alerts.
Returns: The request ID, which may be used to select a WorkflowStatus object.
-
convert_query
(query)¶ Converts a legacy CB Response query to a ThreatHunter query.
Parameters: query (str) – the query to convert Returns: the converted query Return type: str
-
create
(cls, data=None)¶ Creates a new model.
>>> feed = cb.create(Feed, feed_data)
Parameters: - cls – The model being created
- data (dict(str, object)) – The data to pre-populate the model with
Returns: an instance of cls
-
custom_severities
¶ Returns a list of active
ReportSeverity
instancesReturn type: list[ ReportSeverity
]
-
delete_object
(uri)¶ Send a DELETE request to the specified URI.
- Args:
- uri (str): The URI to send the DELETE request to.
- Returns:
- object: The return data from the DELETE request.
-
device_background_scan
(device_ids, scan)¶ Set the background scan option for the specified devices.
Parameters: - device_ids (list) – List of IDs of devices to be set.
- scan (boolean) – True to turn background scan on, False to turn it off.
-
device_bypass
(device_ids, enable)¶ Set the bypass option for the specified devices.
Parameters: - device_ids (list) – List of IDs of devices to be set.
- enable (boolean) – True to enable bypass, False to disable it.
-
device_delete_sensor
(device_ids)¶ Delete the specified sensor devices.
Parameters: device_ids (list) – List of IDs of devices to be deleted.
-
device_quarantine
(device_ids, enable)¶ Set the quarantine option for the specified devices.
Parameters: - device_ids (list) – List of IDs of devices to be set.
- enable (boolean) – True to enable quarantine, False to disable it.
-
device_uninstall_sensor
(device_ids)¶ Uninstall the specified sensor devices.
Parameters: device_ids (list) – List of IDs of devices to be uninstalled.
-
device_update_policy
(device_ids, policy_id)¶ Set the current policy for the specified devices.
Parameters: - device_ids (list) – List of IDs of devices to be changed.
- policy_id (int) – ID of the policy to set for the devices.
-
device_update_sensor_version
(device_ids, sensor_version)¶ Update the sensor version for the specified devices.
Parameters: - device_ids (list) – List of IDs of devices to be changed.
- sensor_version (dict) – New version properties for the sensor.
-
get_object
(uri, query_parameters=None, default=None)¶ Submit a GET request to the server and parse the result as JSON before returning.
- Args:
- uri (str): The URI to send the GET request to. query_parameters (object): Parameters for the query. default (object): What gets returned in the event of an empty response.
- Returns:
- object: Result of the GET request.
-
get_raw_data
(uri, query_parameters=None, default=None, **kwargs)¶ Submit a GET request to the server and return the result without parsing it.
- Args:
- uri (str): The URI to send the GET request to. query_parameters (object): Parameters for the query. default (object): What gets returned in the event of an empty response. **kwargs:
- Returns:
- object: Result of the GET request.
-
limits
()¶ Returns a dictionary containing API limiting information.
Example:
>>> cb.limits() {u'status_code': 200, u'time_bounds': {u'upper': 1545335070095, u'lower': 1542779216139}}
Returns: a dict of limiting information Return type: dict(str, str)
-
post_object
(uri, body, **kwargs)¶ Send a POST request to the specified URI.
- Args:
- uri (str): The URI to send the POST request to. body (object): The data to be sent in the body of the POST request. **kwargs:
- Returns:
- object: The return data from the POST request.
-
put_object
(uri, body, **kwargs)¶ Send a PUT request to the specified URI.
- Args:
- uri (str): The URI to send the PUT request to. body (object): The data to be sent in the body of the PUT request. **kwargs:
- Returns:
- object: The return data from the PUT request.
-
queries
()¶ Retrieves a list of queries, active or complete, known by the ThreatHunter server.
Returns: a list of query ids Return type: list(str)
-
raise_unless_json
(ret, expected)¶ Raise a ServerError unless we got back an HTTP 200 response with JSON containing all the expected values.
- Args:
- ret (object): Return value to be checked. expected (dict): Expected keys and values that need to be found in the JSON response.
- Raises:
- ServerError: If the HTTP response is anything but 200, or if the expected values are not found.
-
select
(cls, unique_id=None, *args, **kwargs)¶ Prepare a query against the Carbon Black data store.
- Args:
- cls (class): The Model class (for example, Computer, Process, Binary, FileInstance) to query unique_id (optional): The unique id of the object to retrieve, to retrieve a single object by ID *args: **kwargs:
- Returns:
- object: An instance of the Model class if a unique_id is provided, otherwise a Query object
-
url
¶ Return the connection URL.
- Returns:
- str: The connection URL.
-
validate_query
(query)¶ Validates the given IOC query.
>>> cb.validate_query("process_name:chrome.exe") # True
Parameters: query (str) – the query to validate Returns: whether or not the query is valid Return type: bool
-
Queries¶
The ThreatHunter API uses QueryBuilder instances to construct structured
or unstructured (i.e., raw string) queries. You can either construct these
instances manually, or allow CbThreatHunterAPI.select()
to do it for you:
-
class
cbapi.psc.threathunter.query.
QueryBuilder
(**kwargs)¶ Provides a flexible interface for building prepared queries for the CB ThreatHunter backend.
This object can be instantiated directly, or can be managed implicitly through the
CbThreatHunterAPI.select()
API.Examples:
>>> from cbapi.psc.threathunter import QueryBuilder >>> # build a query with chaining >>> query = QueryBuilder().where(process_name="malicious.exe").and_(device_name="suspect") >>> # start with an initial query, and chain another condition to it >>> query = QueryBuilder(device_os="WINDOWS").or_(process_username="root")
-
and_
(q, **kwargs)¶ Adds a conjunctive filter to a query.
Parameters: - q – string or solrq.Q object
- kwargs – Arguments to construct a solrq.Q with
Returns: QueryBuilder object
Return type:
-
not_
(q, **kwargs)¶ Adds a negative filter to a query.
Parameters: - q – solrq.Q object
- kwargs – Arguments to construct a solrq.Q with
Returns: QueryBuilder object
Return type:
-
or_
(q, **kwargs)¶ Adds a disjunctive filter to a query.
Parameters: - q – solrq.Q object
- kwargs – Arguments to construct a solrq.Q with
Returns: QueryBuilder object
Return type:
-
where
(q, **kwargs)¶ Adds a conjunctive filter to a query.
Parameters: - q – string or solrq.Q object
- kwargs – Arguments to construct a solrq.Q with
Returns: QueryBuilder object
Return type:
-
-
class
cbapi.psc.threathunter.query.
Query
(doc_class, cb)¶ Represents a prepared query to the Cb ThreatHunter backend.
This object is returned as part of a
CbThreatHunterPI.select()
operation on models requested from the Cb ThreatHunter backend. You should not have to create this class yourself.The query is not executed on the server until it’s accessed, either as an iterator (where it will generate values on demand as they’re requested) or as a list (where it will retrieve the entire result set and save to a list). You can also call the Python built-in
len()
on this object to retrieve the total number of items matching the query.Examples:
>>> from cbapi.psc.threathunter import CbThreatHunterAPI,Process >>> cb = CbThreatHunterAPI() >>> query = cb.select(Process) >>> query = query.where(process_name="notepad.exe") >>> # alternatively: >>> query = query.where("process_name:notepad.exe")
- Notes:
- The slicing operator only supports start and end parameters, but not step.
[1:-1]
is legal, but[1:2:-1]
is not. - You can chain where clauses together to create AND queries; only objects that match all
where
clauses will be returned.
- The slicing operator only supports start and end parameters, but not step.
-
and_
(q=None, **kwargs)¶ Add a conjunctive filter to this query.
Parameters: - q – Query string or solrq.Q object
- kwargs – Arguments to construct a solrq.Q with
Returns: Query object
Return type:
-
not_
(q=None, **kwargs)¶ Adds a negated filter to this query.
Parameters: - q – solrq.Q object
- kwargs – Arguments to construct a solrq.Q with
Returns: Query object
Return type:
-
or_
(q=None, **kwargs)¶ Add a disjunctive filter to this query.
Parameters: - q – solrq.Q object
- kwargs – Arguments to construct a solrq.Q with
Returns: Query object
Return type:
-
where
(q=None, **kwargs)¶ Add a filter to this query.
Parameters: - q – Query string,
QueryBuilder
, or solrq.Q object - kwargs – Arguments to construct a solrq.Q with
Returns: Query object
Return type: - q – Query string,
-
class
cbapi.psc.threathunter.models.
AsyncProcessQuery
(doc_class, cb)¶ Represents the query logic for an asychronous Process query.
This class specializes
Query
to handle the particulars of process querying.-
and_
(q=None, **kwargs)¶ Add a conjunctive filter to this query.
Parameters: - q – Query string or solrq.Q object
- kwargs – Arguments to construct a solrq.Q with
Returns: Query object
Return type: Query
-
not_
(q=None, **kwargs)¶ Adds a negated filter to this query.
Parameters: - q – solrq.Q object
- kwargs – Arguments to construct a solrq.Q with
Returns: Query object
Return type: Query
-
or_
(q=None, **kwargs)¶ Add a disjunctive filter to this query.
Parameters: - q – solrq.Q object
- kwargs – Arguments to construct a solrq.Q with
Returns: Query object
Return type: Query
-
sort_by
(key, direction='ASC')¶ Sets the sorting behavior on a query’s results.
Example:
>>> cb.select(Process).where(process_name="cmd.exe").sort_by("device_timestamp")
Parameters: - key – the key in the schema to sort by
- direction – the sort order, either “ASC” or “DESC”
Return type:
-
timeout
(msecs)¶ Sets the timeout on a process query.
Example:
>>> cb.select(Process).where(process_name="foo.exe").timeout(5000)
Param: msecs: the timeout duration, in milliseconds Returns: AsyncProcessQuery object Return type: AsyncProcessQuery
-
where
(q=None, **kwargs)¶ Add a filter to this query.
Parameters: - q – Query string,
QueryBuilder
, or solrq.Q object - kwargs – Arguments to construct a solrq.Q with
Returns: Query object
Return type: Query
- q – Query string,
-
-
class
cbapi.psc.threathunter.query.
FeedQuery
(doc_class, cb)¶ Represents the logic for a
Feed
query.>>> cb.select(Feed) >>> cb.select(Feed, id) >>> cb.select(Feed).where(include_public=True)
-
class
cbapi.psc.threathunter.query.
ReportQuery
(doc_class, cb)¶ Represents the logic for a
Report
query.>>> cb.select(Report).where(feed_id=id)
Note
Only feed reports can be queried. Watchlist reports should be interacted with via
Watchlist.reports()
.
-
class
cbapi.psc.threathunter.query.
WatchlistQuery
(doc_class, cb)¶ Represents the logic for a
Watchlist
query.>>> cb.select(Watchlist)
Models¶
-
class
cbapi.psc.threathunter.models.
Process
(cb, model_unique_id=None, initial_data=None, force_init=False, full_doc=True)¶ Represents a Process object in the Carbon Black server.
-
class
Summary
(cb, model_unique_id)¶ Represents a Summary object in the Carbon Black server.
-
children
¶ Returns a list of child processes for this process.
Returns: Returns a list of process objects Return type: list of Process
-
events
(**kwargs)¶ Returns a query for events associated with this process’s process GUID.
Parameters: kwargs – Arguments to filter the event query with. Returns: Returns a Query object with the appropriate search parameters for events Return type: cbapi.psc.threathunter.query.Query
Example:
>>> [print(event) for event in process.events()] >>> [print(event) for event in process.events(event_type="modload")]
-
parents
¶ Returns a query for parent processes associated with this process.
Returns: Returns a Query object with the appropriate search parameters for parent processes, or None if the process has no recorded parent Return type: cbapi.psc.threathunter.query.AsyncProcessQuery
or None
-
process_md5
¶ Returns a string representation of the MD5 hash for this process.
Returns: A string representation of the process’s MD5. Return type: str
-
process_pids
¶ Returns a list of PIDs associated with this process.
Returns: A list of PIDs Return type: list of ints
-
process_sha256
¶ Returns a string representation of the SHA256 hash for this process.
Returns: A string representation of the process’s SHA256. Return type: str
-
siblings
¶ Returns a list of sibling processes for this process.
Returns: Returns a list of process objects Return type: list of Process
-
summary
¶ Returns organization-specific information about this process.
-
class
-
class
cbapi.psc.threathunter.models.
Event
(cb, model_unique_id=None, initial_data=None, force_init=False, full_doc=True)¶ Represents a Event object in the Carbon Black server.
-
class
cbapi.psc.threathunter.models.
Tree
(cb, model_unique_id=None, initial_data=None, force_init=False, full_doc=True)¶ Represents a Tree object in the Carbon Black server.
-
class
cbapi.psc.threathunter.models.
Feed
(cb, model_unique_id=None, initial_data=None)¶ Represents a Feed object in the Carbon Black server.
Variables: - name – A human-friendly name for this feed
- owner – The feed owner’s connector ID
- provider_url – A URL supplied by the feed’s provider
- summary – A human-friendly summary for the feed
- category – The feed’s category
- source_label – The feed’s source label
- access – The feed’s access (public or private)
- id – The feed’s unique ID
-
append_reports
(reports)¶ Append the given reports to this feed’s current reports.
Parameters: reports (list( Report
)) – the reports to appendRaises: InvalidObjectError – if id is missing
-
delete
()¶ Deletes this feed from the ThreatHunter server.
Raises: InvalidObjectError – if id is missing
-
replace_reports
(reports)¶ Replace this feed’s reports with the given reports.
Parameters: reports (list( Report
)) – the reports to replace withRaises: InvalidObjectError – if id is missing
-
reports
¶ Returns a list of
Report
associated with this feed.Returns: a list of reports Return type: list( Report
)
-
save
(public=False)¶ Saves this feed on the ThreatHunter server.
Parameters: public – Whether to make the feed publicly available Returns: The saved feed Return type: Feed
-
update
(**kwargs)¶ Update this feed’s metadata with the given arguments.
>>> feed.update(access="private")
Parameters: kwargs (dict(str, str)) – The fields to update
Raises: - InvalidObjectError – if id is missing or
validate()
fails - ApiError – if an invalid field is specified
- InvalidObjectError – if id is missing or
-
validate
()¶ Validates this feed’s state.
Raises: InvalidObjectError – if the feed’s state is invalid
-
class
cbapi.psc.threathunter.models.
Report
(cb, model_unique_id=None, initial_data=None, feed_id=None, from_watchlist=False)¶ Represents a Report object in the Carbon Black server.
Variables: - id – The report’s unique ID
- timestamp – When this report was created
- title – A human-friendly title for this report
- description – A human-friendly description for this report
- severity – The severity of the IOCs within this report
- link – A URL for some reference for this report
- tags – A list of tags for this report
- iocs_v2 – A list of IOC_V2 dicts associated with this report
- visibility – The visibility of this report
-
custom_severity
¶ Returns the custom severity for this report.
Returns: The custom severity for this report, if it exists Return type: ReportSeverity
Raises: InvalidObjectError – if id is missing or this report is from a watchlist
-
delete
()¶ Deletes this report from the ThreatHunter server.
>>> report.delete()
Raises: InvalidObjectError – if id is missing, or feed_id is missing and this report is a feed report
-
ignore
()¶ Sets the ignore status on this report.
Only watchlist reports have an ignore status.
Raises: InvalidObjectError – if id is missing or this report is not from a watchlist
-
ignored
¶ Returns the ignore status for this report.
Only watchlist reports have an ignore status.
>>> if report.ignored: ... report.unignore()
Returns: whether or not this report is ignored Return type: bool Raises: InvalidObjectError – if id is missing or this report is not from a watchlist
-
iocs_
¶ Returns a list of
IOC_V2
associated with this report.>>> for ioc in report.iocs_: ... print(ioc.values)
Returns: a list of IOCs Return type: list( IOC_V2
)
-
save_watchlist
()¶ Saves this report as a watchlist report.
Note
This method cannot be used to save a feed report. To save feed reports, create them with cb.create and use
Feed.replace()
.Raises: InvalidObjectError – if validate()
fails
-
unignore
()¶ Removes the ignore status on this report.
Only watchlist reports have an ignore status.
Raises: InvalidObjectError – if id is missing or this report is not from a watchlist
-
update
(**kwargs)¶ Update this report with the given arguments.
Note
The report’s timestamp is always updated, regardless of whether passed explicitly.
>>> report.update(title="My new report title")
Parameters: kwargs (dict(str, str)) – The fields to update Returns: The updated report Return type: Report
Raises: InvalidObjectError – if id is missing, or feed_id is missing and this report is a feed report, or validate()
fails
-
validate
()¶ Validates this report’s state.
Raises: InvalidObjectError – if the report’s state is invalid
-
class
cbapi.psc.threathunter.models.
IOC
(cb, model_unique_id=None, initial_data=None, report_id=None)¶ Represents a IOC object in the Carbon Black server.
Variables: Creates a new IOC instance.
Raises: ApiError – if initial_data is None -
validate
()¶ Validates this IOC structure’s state.
Raises: InvalidObjectError – if the IOC structure’s state is invalid
-
-
class
cbapi.psc.threathunter.models.
IOC_V2
(cb, model_unique_id=None, initial_data=None, report_id=None)¶ Represents a IOC_V2 object in the Carbon Black server.
Variables: - id – The IOC_V2’s unique ID
- match_type – How IOCs in this IOC_V2 are matched
- values – A list of IOCs
- field – The kind of IOCs contained in this IOC_V2
- link – A URL for some reference for this IOC_V2
Creates a new IOC_V2 instance.
Raises: ApiError – if initial_data is None -
ignore
()¶ Sets the ignore status on this IOC.
Only watchlist IOCs have an ignore status.
Raises: InvalidObjectError – if id is missing or this IOC is not from a watchlist
-
ignored
¶ Returns whether or not this IOC is ignored
>>> if ioc.ignored: ... ioc.unignore()
Returns: the ignore status Return type: bool Raises: InvalidObjectError – if this IOC is missing an id or is not a watchlist IOC
-
unignore
()¶ Removes the ignore status on this IOC.
Only watchlist IOCs have an ignore status.
Raises: InvalidObjectError – if id is missing or this IOC is not from a watchlist
-
validate
()¶ Validates this IOC_V2’s state.
Raises: InvalidObjectError – if the IOC_V2’s state is invalid
-
class
cbapi.psc.threathunter.models.
Watchlist
(cb, model_unique_id=None, initial_data=None)¶ Represents a Watchlist object in the Carbon Black server.
Variables: - name – A human-friendly name for the watchlist
- description – A short description of the watchlist
- id – The watchlist’s unique id
- tags_enabled – Whether tags are currently enabled
- alerts_enabled – Whether alerts are currently enabled
- create_timestamp – When this watchlist was created
- last_update_timestamp – Report IDs associated with this watchlist
- report_ids – Report IDs associated with this watchlist
- classifier – A key, value pair specifying an associated feed
-
classifier_
¶ Returns the classifier key and value, if any, for this watchlist.
Return type: tuple(str, str) or None
-
delete
()¶ Deletes this watchlist from the ThreatHunter server.
Raises: InvalidObjectError – if id is missing
-
disable_alerts
()¶ Disable alerts for this watchlist.
Raises: InvalidObjectError – if id is missing
Disable tagging for this watchlist.
Raises: InvalidObjectError – if id is missing
-
enable_alerts
()¶ Enable alerts for this watchlist. Alerts are not retroactive.
Raises: InvalidObjectError – if id is missing
Enable tagging for this watchlist.
Raises: InvalidObjectError – if id is missing
-
feed
¶ Returns the feed linked to this watchlist, if there is one.
Returns: the feed linked to this watchlist, if any Return type: Feed
or None
-
reports
¶ Returns a list of
Report
instances associated with this watchlist.Note
If this watchlist is a classifier (i.e. feed-linked) watchlist, reports will be empty. To get the reports associated with the linked feed, use
feed
like:>>> for report in watchlist.feed.reports: ... print(report.title)
Returns: A list of reports Return type: list( Report
)
-
save
()¶ Saves this watchlist on the ThreatHunter server.
Returns: The saved watchlist Return type: Watchlist
Raises: InvalidObjectError – if validate()
fails
-
update
(**kwargs)¶ Updates this watchlist with the given arguments.
>>> watchlist.update(name="New Name")
Parameters: kwargs (dict(str, str)) – The fields to update
Raises: - InvalidObjectError – if id is missing or
validate()
fails - ApiError – if report_ids is given and is empty
- InvalidObjectError – if id is missing or
-
validate
()¶ Validates this watchlist’s state.
Raises: InvalidObjectError – if the watchlist’s state is invalid
-
class
cbapi.psc.threathunter.models.
ReportSeverity
(cb, initial_data=None)¶ Represents a ReportSeverity object in the Carbon Black server.
Variables: - report_id – The unique ID for the corresponding report
- severity – The severity level
-
class
cbapi.psc.threathunter.models.
Binary
(cb, model_unique_id)¶ Represents a Binary object in the Carbon Black server.
Variables: - sha256 – The SHA-256 hash of the file
- md5 – The MD5 hash of the file
- file_available – If true, the file is available for download
- available_file_size – The size of the file available for download
- file_size – The size of the actual file (represented by the hash)
- os_type – The OS that this file is designed for
- architecture – The set of architectures that this file was compiled for
- lang_id – The Language ID value for the Windows VERSIONINFO resource
- charset_id – The Character set ID value for the Windows VERSIONINFO resource
- internal_name – The internal name from FileVersionInformation
- product_name – The product name from FileVersionInformation
- company_name – The company name from FileVersionInformation
- trademark – The trademark from FileVersionInformation
- file_description – The file description from FileVersionInformation
- file_version – The file version from FileVersionInformation
- comments – Comments from FileVersionInformation
- original_filename – The original filename from FileVersionInformation
- product_description – The product description from FileVersionInformation
- product_version – The product version from FileVersionInformation
- private_build – The private build from FileVersionInformation
- special_build – The special build from FileVersionInformation
-
class
Summary
(cb, model_unique_id)¶ Represents a Summary object in the Carbon Black server.
-
download_url
¶ Returns a URL that can be used to download the file for this binary. Returns None if no download can be found.
Parameters: expiration_seconds – How long the download should be valid for Raises: InvalidObjectError – if URL retrieval should be retried Returns: A pre-signed AWS download URL Return type: str
-
summary
¶ Returns organization-specific information about this binary.
-
class
cbapi.psc.threathunter.models.
Downloads
(cb, shas, expiration_seconds=3600)¶ Represents a Downloads object in the Carbon Black server.
-
class
FoundItem
(cb, item)¶ Represents a FoundItem object in the Carbon Black server.
-
found
¶ Returns a list of
Downloads.FoundItem
, one for each binary found in the binary store.
-
class