CBC SDK Package

Subpackages

Submodules

Base Module

Models and Queries for the Base Carbon Black Cloud SDK

class ArrayFieldDescriptor(field_name, coerce_to=None, default_value=None)

Bases: FieldDescriptor

Field descriptor for fields of ‘array’ type.

Initialize the FieldDescriptor object.

Parameters:
  • field_name (str) – The name of the field.

  • coerce_to (class) – The type to which the value should be coerced, or None.

  • default_value (Any) – The default value of the field.

class AsyncQueryMixin

Bases: object

A mix-in which provides support for asynchronous queries.

execute_async()

Executes the current query in an asynchronous fashion.

Returns:

A future representing the query and its results.

Return type:

Future

class BaseQuery(query=None)

Bases: object

The base query for finding objects via the API.

Initializes the BaseQuery object.

Parameters:

query (solrq.Q) – The parent query of this one.

class BinaryFieldDescriptor(field_name, coerce_to=None, default_value=None)

Bases: FieldDescriptor

Field descriptor for fields of ‘byte’ type.

Initialize the FieldDescriptor object.

Parameters:
  • field_name (str) – The name of the field.

  • coerce_to (class) – The type to which the value should be coerced, or None.

  • default_value (Any) – The default value of the field.

class CbMetaModel(name, bases, clsdict)

Bases: type

Meta-model for NewBaseModel and its subclasses.

Creates a new instance of a class, setting up the field descriptors based on the metafile.

Parameters:
  • name (str) – The name of the class.

  • bases (list) – Base classes of the class to be created.

  • clsdict (dict) – Elements defined in the new class.

mro()

Return a type’s method resolution order.

class CreatableModelMixin

Bases: object

Mixin for all objects which are creatable.

class CriteriaBuilderSupportMixin

Bases: object

A mixin that supplies wrapper methods to access the criteria.

add_criteria(key, newlist)

Add to the criteria on this query with a custom criteria key.

Will overwrite any existing criteria for the specified key.

Parameters:
  • key (str) – The key for the criteria item to be set.

  • newlist (str or list[str]) – Value or list of values to be set for the criteria item.

Returns:

The query object with specified custom criteria.

Example

>>> query = api.select(Alert).add_criteria("type", ["CB_ANALYTIC", "WATCHLIST"])
>>> query = api.select(Alert).add_criteria("type", "CB_ANALYTIC")
update_criteria(key, newlist)

Update the criteria on this query with a custom criteria key.

Parameters:
  • key (str) – The key for the criteria item to be set.

  • newlist (list) – List of values to be set for the criteria item.

Returns:

The query object with specified custom criteria.

Example

>>> query = api.select(Alert).update_criteria("my.criteria.key", ["criteria_value"])

Note

Use this method if there is no implemented method for your desired criteria.

class EpochDateTimeFieldDescriptor(field_name, multiplier=1.0)

Bases: FieldDescriptor

Field descriptor for fields of ‘epoch-ms-date-time’ type.

Initialize the EpochDateTimeFieldDescriptor object.

Parameters:
  • field_name (str) – The name of the field.

  • multiplier (float) – Unused.

class ExclusionBuilderSupportMixin

Bases: object

A mixin that supplies wrapper methods to access the exclusions.

add_exclusions(key, newlist)

Add to the exclusions on this query with a custom exclusions key.

Will overwrite any existing exclusion for the specified key.

Parameters:
  • key (str) – The key for the exclusion item to be set.

  • newlist (str or list[str]) – Value or list of values to be set for the exclusion item.

Returns:

The query object with specified custom exclusion.

Example

>>> query = api.select(Alert).add_exclusions("type", ["WATCHLIST"])
>>> query = api.select(Alert).add_exclusions("type", "WATCHLIST")
update_exclusions(key, newlist)

Update the exclusion on this query with a custom exclusion key.

Parameters:
  • key (str) – The key for the exclusion item to be set.

  • newlist (list) – List of values to be set for the exclusion item.

Returns:

The query object with specified custom exclusion.

Example

>>> query = api.select(Alert).update_exclusions("my.criteria.key", ["criteria_value"])

Note

Use this method if there is no implemented method for your desired criteria.

class FacetQuery(cls, cb, query=None)

Bases: BaseQuery, AsyncQueryMixin, QueryBuilderSupportMixin, CriteriaBuilderSupportMixin, ExclusionBuilderSupportMixin

Query class for asynchronous Facet API calls.

These API calls return one result, and are not paginated or iterable.

Initialize the FacetQuery object.

add_criteria(key, newlist)

Add to the criteria on this query with a custom criteria key.

Will overwrite any existing criteria for the specified key.

Parameters:
  • key (str) – The key for the criteria item to be set.

  • newlist (str or list[str]) – Value or list of values to be set for the criteria item.

Returns:

The query object with specified custom criteria.

Example

>>> query = api.select(Alert).add_criteria("type", ["CB_ANALYTIC", "WATCHLIST"])
>>> query = api.select(Alert).add_criteria("type", "CB_ANALYTIC")
add_exclusions(key, newlist)

Add to the exclusions on this query with a custom exclusions key.

Will overwrite any existing exclusion for the specified key.

Parameters:
  • key (str) – The key for the exclusion item to be set.

  • newlist (str or list[str]) – Value or list of values to be set for the exclusion item.

Returns:

The query object with specified custom exclusion.

Example

>>> query = api.select(Alert).add_exclusions("type", ["WATCHLIST"])
>>> query = api.select(Alert).add_exclusions("type", "WATCHLIST")
add_facet_field(field)

Sets the facet fields to be received by this query.

Parameters:

field (str or [str]) – Field(s) to be received.

Returns:

The Query object that will receive the specified field(s).

Return type:

Query (AsyncQuery)

Example

>>> cb.select(ProcessFacet).add_facet_field(["process_name", "process_username"])
add_range(range)

Sets the facet ranges to be received by this query.

Parameters:

range (dict or [dict]) – Range(s) to be received.

Returns:

The Query object that will receive the specified range(s).

Return type:

Query (AsyncQuery)

Note

The range parameter must be in this dictionary format:

{

“bucket_size”: “<object>”,

“start”: “<object>”,

“end”: “<object>”,

“field”: “<string>”

},

where “bucket_size”, “start”, and “end” can be numbers or ISO 8601 timestamps.

Examples

>>> cb.select(ProcessFacet).add_range({"bucket_size": 5, "start": 0, "end": 10, "field": "netconn_count"})
>>> cb.select(ProcessFacet).add_range({"bucket_size": "+1DAY", "start": "2020-11-01T00:00:00Z",
... "end": "2020-11-12T00:00:00Z", "field": "backend_timestamp"})
and_(q=None, **kwargs)

Add a conjunctive filter to this query.

Parameters:
  • q (Any) – Query string or solrq.Q object

  • **kwargs (dict) – Arguments to construct a solrq.Q with

Returns:

This Query object.

Return type:

Query

execute_async()

Executes the current query in an asynchronous fashion.

Returns:

A future representing the query and its results.

Return type:

Future

limit(limit)

Sets the maximum number of facets per category (i.e. any Process Search Fields in self._fields).

The default limit for Process Facet searches in the Carbon Black Cloud backend is 100.

Parameters:

limit (int) – Maximum number of facets per category.

Returns:

The Query object with new limit parameter.

Return type:

Query (AsyncQuery)

Example

>>> cb.select(ProcessFacet).where(process_name="foo.exe").limit(50)
not_(q=None, **kwargs)

Adds a negated filter to this query.

Parameters:
  • q (solrq.Q) – Query object.

  • **kwargs (dict) – Arguments to construct a solrq.Q with.

Returns:

This Query object.

Return type:

Query

or_(q=None, **kwargs)

Add a disjunctive filter to this query.

Parameters:
  • q (solrq.Q) – Query object.

  • **kwargs (dict) – Arguments to construct a solrq.Q with.

Returns:

This Query object.

Return type:

Query

property results

Save query results to self._results with self._search() method.

set_rows(rows)

Sets the number of facet results to return with the query.

Parameters:

rows (int) – Number of rows to return.

Returns:

The Query object with the new rows parameter.

Return type:

Query (AsyncQuery)

Example

>>> cb.select(ProcessFacet).set_rows(50)
set_time_range(start=None, end=None, window=None)

Sets the ‘time_range’ query body parameter, determining a time window based on ‘device_timestamp’.

Parameters:
  • start (str in ISO 8601 timestamp) – When to start the result search.

  • end (str in ISO 8601 timestamp) – When to end the result search.

  • window (str) – Time window to execute the result search, ending on the current time.

  • "-2w" (Should be in the form) –

  • y=year (where) –

  • w=week

  • d=day

  • h=hour

  • m=minute

  • s=second.

Note

  • window will take precendent over start and end if provided.

Examples

>>> query = api.select(Process).set_time_range(start="2020-10-20T20:34:07Z").where("query is required")
>>> second_query = api.select(Process).
...     set_time_range(start="2020-10-20T20:34:07Z", end="2020-10-30T20:34:07Z").where("query is required")
>>> third_query = api.select(Process).set_time_range(window='-3d').where("query is required")
timeout(msecs)

Sets the timeout on an AsyncQuery.

Parameters:

msecs (int) – Timeout duration, in milliseconds. This value can never be greater than the configured default timeout. If this is 0, the configured default timeout value is used.

Returns:

The Query object with new milliseconds parameter.

Return type:

Query (AsyncQuery)

Example

>>> cb.select(ProcessFacet).where(process_name="foo.exe").timeout(5000)
update_criteria(key, newlist)

Update the criteria on this query with a custom criteria key.

Parameters:
  • key (str) – The key for the criteria item to be set.

  • newlist (list) – List of values to be set for the criteria item.

Returns:

The query object with specified custom criteria.

Example

>>> query = api.select(Alert).update_criteria("my.criteria.key", ["criteria_value"])

Note

Use this method if there is no implemented method for your desired criteria.

update_exclusions(key, newlist)

Update the exclusion on this query with a custom exclusion key.

Parameters:
  • key (str) – The key for the exclusion item to be set.

  • newlist (list) – List of values to be set for the exclusion item.

Returns:

The query object with specified custom exclusion.

Example

>>> query = api.select(Alert).update_exclusions("my.criteria.key", ["criteria_value"])

Note

Use this method if there is no implemented method for your desired criteria.

where(q=None, **kwargs)

Add a filter to this query.

Parameters:
  • q (Any) – Query string, QueryBuilder, or solrq.Q object

  • **kwargs (dict) – Arguments to construct a solrq.Q with

Returns:

This Query object.

Return type:

Query

class FieldDescriptor(field_name, coerce_to=None, default_value=None)

Bases: object

Object that describes a field within a model instance.

Initialize the FieldDescriptor object.

Parameters:
  • field_name (str) – The name of the field.

  • coerce_to (class) – The type to which the value should be coerced, or None.

  • default_value (Any) – The default value of the field.

class ForeignKeyFieldDescriptor(field_name, join_model, join_field=None)

Bases: FieldDescriptor

Field descriptor for fields that are foreign keys.

Initialize the ForeignKeyFieldDescriptor object.

Parameters:
  • field_name (str) – The name of the field.

  • join_model (class) – The class for which this field value is a foreign key.

  • join_field (str) – The name fo the field in the joined class for which this field value is a foreign key.

class IsoDateTimeFieldDescriptor(field_name)

Bases: FieldDescriptor

Field descriptor for fields of ‘iso-date-time’ type.

Initialize the IsoDateTimeFieldDescriptor object.

Parameters:

field_name (str) – The name of the field.

class IterableQueryMixin

Bases: object

A mix-in to provide iterability to a query.

all()

Returns all the items of a query as a list.

Returns:

List of query items

Return type:

list

first()

Returns the first item that would be returned as the result of a query.

Returns:

First query item

Return type:

obj

one()

Returns the only item that would be returned by a query.

Returns:

Sole query return item

Return type:

obj

Raises:
class MutableBaseModel(cb, model_unique_id=None, initial_data=None, force_init=False, full_doc=False)

Bases: NewBaseModel

Base model for objects that can have properties changed and then saved back to the server.

Initialize the NewBaseModel object.

Parameters:
  • cb (CBCloudAPI) – A reference to the CBCloudAPI object.

  • model_unique_id (Any) – The unique ID for this particular instance of the model object.

  • initial_data (dict) – The data to use when initializing the model object.

  • force_init (bool) – True to force object initialization.

  • full_doc (bool) – True to mark the object as fully initialized.

delete()

Delete this object.

get(attrname, default_val=None)

Return an attribute of this object.

Parameters:
  • attrname (str) – Name of the attribute to be returned.

  • default_val (Any) – Default value to be used if the attribute is not set.

Returns:

The returned attribute value, which may be defaulted.

Return type:

Any

is_dirty()

Returns whether or not any fields of this object have been changed.

Returns:

True if any fields of this object have been changed, False if not.

Return type:

bool

refresh()

Reload this object from the server.

reset()

Undo any changes made to this object’s fields.

save()

Save any changes made to this object’s fields.

Returns:

This object.

Return type:

MutableBaseModel

to_json()

Return a json object of the response.

Returns:

The response dictionary representation.

Return type:

Any

touch(fulltouch=False)

Force this object to be considered as changed.

validate()

Validates this object.

Returns:

True if the object is validated.

Return type:

bool

Raises:

InvalidObjectError – If the object has missing fields.

class NewBaseModel(cb, model_unique_id=None, initial_data=None, force_init=False, full_doc=False)

Bases: object

Base class of all model objects within the Carbon Black Cloud SDK.

Initialize the NewBaseModel object.

Parameters:
  • cb (CBCloudAPI) – A reference to the CBCloudAPI object.

  • model_unique_id (Any) – The unique ID for this particular instance of the model object.

  • initial_data (dict) – The data to use when initializing the model object.

  • force_init (bool) – True to force object initialization.

  • full_doc (bool) – True to mark the object as fully initialized.

get(attrname, default_val=None)

Return an attribute of this object.

Parameters:
  • attrname (str) – Name of the attribute to be returned.

  • default_val (Any) – Default value to be used if the attribute is not set.

Returns:

The returned attribute value, which may be defaulted.

Return type:

Any

refresh()

Reload this object from the server.

to_json()

Return a json object of the response.

Returns:

The response dictionary representation.

Return type:

Any

class ObjectFieldDescriptor(field_name, coerce_to=None, default_value=None)

Bases: FieldDescriptor

Field descriptor for fields of ‘object’ type.

Initialize the FieldDescriptor object.

Parameters:
  • field_name (str) – The name of the field.

  • coerce_to (class) – The type to which the value should be coerced, or None.

  • default_value (Any) – The default value of the field.

class PaginatedQuery(cls, cb, query=None)

Bases: BaseQuery, IterableQueryMixin

A query that returns objects in a paginated fashion.

Initialize the PaginatedQuery object.

Parameters:
  • cls (class) – The class of objects being returned by this query.

  • cb (CBCloudAPI) – Reference to the CBCloudAPI object.

  • query (BaseQuery) – The query that we are paginating.

all()

Returns all the items of a query as a list.

Returns:

List of query items

Return type:

list

batch_size(new_batch_size)

Set the batch size of the paginated query.

Parameters:

new_batch_size (int) – The new batch size.

Returns:

A new query with the updated batch size.

Return type:

PaginatedQuery

first()

Returns the first item that would be returned as the result of a query.

Returns:

First query item

Return type:

obj

one()

Returns the only item that would be returned by a query.

Returns:

Sole query return item

Return type:

obj

Raises:
class Query(doc_class, cb)

Bases: PaginatedQuery, QueryBuilderSupportMixin, IterableQueryMixin, AsyncQueryMixin, CriteriaBuilderSupportMixin, ExclusionBuilderSupportMixin

Represents a prepared query to the Carbon Black Cloud.

This object is returned as part of a CBCCloudAPI.select operation on models requested from the Carbon Black Cloud 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.

>>> from cbc_sdk import CBCloudAPI
>>> from cbc_sdk.enterprise_edr import Report
>>> cb = CBCloudAPI()
>>> query = cb.select(Report)
>>> query = query.where(report_id="ABCDEFG1234")
>>> # alternatively:
>>> query = query.where("report_id:ABCDEFG1234")

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.

Initialize the Query object.

Parameters:
  • doc_class (class) – The class of the model this query returns.

  • cb (CBCloudAPI) – A reference to the CBCloudAPI object.

add_criteria(key, newlist)

Add to the criteria on this query with a custom criteria key.

Will overwrite any existing criteria for the specified key.

Parameters:
  • key (str) – The key for the criteria item to be set.

  • newlist (str or list[str]) – Value or list of values to be set for the criteria item.

Returns:

The query object with specified custom criteria.

Example

>>> query = api.select(Alert).add_criteria("type", ["CB_ANALYTIC", "WATCHLIST"])
>>> query = api.select(Alert).add_criteria("type", "CB_ANALYTIC")
add_exclusions(key, newlist)

Add to the exclusions on this query with a custom exclusions key.

Will overwrite any existing exclusion for the specified key.

Parameters:
  • key (str) – The key for the exclusion item to be set.

  • newlist (str or list[str]) – Value or list of values to be set for the exclusion item.

Returns:

The query object with specified custom exclusion.

Example

>>> query = api.select(Alert).add_exclusions("type", ["WATCHLIST"])
>>> query = api.select(Alert).add_exclusions("type", "WATCHLIST")
all()

Returns all the items of a query as a list.

Returns:

List of query items

Return type:

list

and_(q=None, **kwargs)

Add a conjunctive filter to this query.

Parameters:
  • q (Any) – Query string or solrq.Q object

  • **kwargs (dict) – Arguments to construct a solrq.Q with

Returns:

This Query object.

Return type:

Query

batch_size(new_batch_size)

Set the batch size of the paginated query.

Parameters:

new_batch_size (int) – The new batch size.

Returns:

A new query with the updated batch size.

Return type:

PaginatedQuery

execute_async()

Executes the current query in an asynchronous fashion.

Returns:

A future representing the query and its results.

Return type:

Future

first()

Returns the first item that would be returned as the result of a query.

Returns:

First query item

Return type:

obj

not_(q=None, **kwargs)

Adds a negated filter to this query.

Parameters:
  • q (solrq.Q) – Query object.

  • **kwargs (dict) – Arguments to construct a solrq.Q with.

Returns:

This Query object.

Return type:

Query

one()

Returns the only item that would be returned by a query.

Returns:

Sole query return item

Return type:

obj

Raises:
or_(q=None, **kwargs)

Add a disjunctive filter to this query.

Parameters:
  • q (solrq.Q) – Query object.

  • **kwargs (dict) – Arguments to construct a solrq.Q with.

Returns:

This Query object.

Return type:

Query

set_fields(fields)

Sets the fields to be returned with the response.

Parameters:

fields (str or list[str]) – Field or list of fields to be returned.

set_rows(rows)

Sets the ‘rows’ query body parameter, determining how many rows of results to request.

Parameters:

rows (int) – How many rows to request.

set_start(start)

Sets the ‘start’ query body parameter, determining where to begin retrieving results from.

Parameters:

start (int) – Where to start results from.

set_time_range(start=None, end=None, window=None)

Sets the ‘time_range’ query body parameter, determining a time window based on ‘device_timestamp’.

Parameters:
  • start (str in ISO 8601 timestamp) – When to start the result search.

  • end (str in ISO 8601 timestamp) – When to end the result search.

  • window (str) – Time window to execute the result search, ending on the current time. Should be in the form “-2w”, where y=year, w=week, d=day, h=hour, m=minute, s=second.

Note

  • window will take precendent over start and end if provided.

Examples

>>> query = api.select(Process).set_time_range(start="2020-10-20T20:34:07Z").where("query is required")
>>> second_query = api.select(Process).
...     set_time_range(start="2020-10-20T20:34:07Z", end="2020-10-30T20:34:07Z").where("query is required")
>>> third_query = api.select(Process).set_time_range(window='-3d').where("query is required")
sort_by(key, direction='ASC')

Sets the sorting behavior on a query’s results.

Parameters:
  • key (str) – The key in the schema to sort by.

  • direction (str) – The sort order, either “ASC” or “DESC”.

Returns:

The query with sorting parameters.

Return type:

Query

Example

>>> cb.select(Process).where(process_name="cmd.exe").sort_by("device_timestamp")
update_criteria(key, newlist)

Update the criteria on this query with a custom criteria key.

Parameters:
  • key (str) – The key for the criteria item to be set.

  • newlist (list) – List of values to be set for the criteria item.

Returns:

The query object with specified custom criteria.

Example

>>> query = api.select(Alert).update_criteria("my.criteria.key", ["criteria_value"])

Note

Use this method if there is no implemented method for your desired criteria.

update_exclusions(key, newlist)

Update the exclusion on this query with a custom exclusion key.

Parameters:
  • key (str) – The key for the exclusion item to be set.

  • newlist (list) – List of values to be set for the exclusion item.

Returns:

The query object with specified custom exclusion.

Example

>>> query = api.select(Alert).update_exclusions("my.criteria.key", ["criteria_value"])

Note

Use this method if there is no implemented method for your desired criteria.

where(q=None, **kwargs)

Add a filter to this query.

Parameters:
  • q (Any) – Query string, QueryBuilder, or solrq.Q object

  • **kwargs (dict) – Arguments to construct a solrq.Q with

Returns:

This Query object.

Return type:

Query

class QueryBuilder(**kwargs)

Bases: object

Provides a flexible interface for building prepared queries for the CB Cloud backend.

This object can be instantiated directly, or can be managed implicitly through the CBCloudAPI.select API.

Examples

>>> from cbc_sdk.base 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")

Initialize the QueryBuilder object.

Parameters:

**kwargs (dict) – If present, these are used to construct a Solrq Query.

and_(q, **kwargs)

Adds a conjunctive filter to a QueryBuilder.

Parameters:
  • q (object) – Either a string or solrq.Q object representing the query to be added.

  • **kwargs (dict) – Arguments with which to construct a solrq.Q object.

Returns:

This object.

Return type:

QueryBuilder

Raises:

ApiError – If the q parameter is of an invalid type.

not_(q, **kwargs)

Adds a negative filter to a QueryBuilder.

Parameters:
  • q (object) – Either a string or solrq.Q object representing the query to be added.

  • **kwargs (dict) – Arguments with which to construct a solrq.Q object.

Returns:

This object.

Return type:

QueryBuilder

Raises:

ApiError – If the q parameter is of an invalid type.

or_(q, **kwargs)

Adds a disjunctive filter to a QueryBuilder.

Parameters:
  • q (object) – Either a string or solrq.Q object representing the query to be added.

  • **kwargs (dict) – Arguments with which to construct a solrq.Q object.

Returns:

This object.

Return type:

QueryBuilder

Raises:

ApiError – If the q parameter is of an invalid type.

where(q, **kwargs)

Adds a conjunctive filter to a QueryBuilder.

Parameters:
  • q (object) – Either a string or solrq.Q object representing the query to be added.

  • **kwargs (dict) – Arguments with which to construct a solrq.Q object.

Returns:

This object.

Return type:

QueryBuilder

Raises:

ApiError – If the q parameter is of an invalid type.

class QueryBuilderSupportMixin

Bases: object

A mixin that supplies wrapper methods to access the _query_builder.

and_(q=None, **kwargs)

Add a conjunctive filter to this query.

Parameters:
  • q (Any) – Query string or solrq.Q object

  • **kwargs (dict) – Arguments to construct a solrq.Q with

Returns:

This Query object.

Return type:

Query

not_(q=None, **kwargs)

Adds a negated filter to this query.

Parameters:
  • q (solrq.Q) – Query object.

  • **kwargs (dict) – Arguments to construct a solrq.Q with.

Returns:

This Query object.

Return type:

Query

or_(q=None, **kwargs)

Add a disjunctive filter to this query.

Parameters:
  • q (solrq.Q) – Query object.

  • **kwargs (dict) – Arguments to construct a solrq.Q with.

Returns:

This Query object.

Return type:

Query

where(q=None, **kwargs)

Add a filter to this query.

Parameters:
  • q (Any) – Query string, QueryBuilder, or solrq.Q object

  • **kwargs (dict) – Arguments to construct a solrq.Q with

Returns:

This Query object.

Return type:

Query

class SimpleQuery(cls, cb, urlobject=None, returns_fulldoc=True)

Bases: BaseQuery, IterableQueryMixin

A simple query object.

Initialize the SimpleQuery object.

Parameters:
  • cls (class) – Class of the object to be returned by the query.

  • cb (CBCloudAPI) – Reference to the CBCloudAPI object.

  • urlobject (str) – URL to be used in making the query.

  • returns_fulldoc (bool) – Whether the result of the Query yields objects that have been fully initialized.

all()

Returns all the items of a query as a list.

Returns:

List of query items

Return type:

list

and_(new_query)

Add an additional “where” clause to this query.

Parameters:

new_query (object) – The additional “where” clause, as a string or solrq.Q object.

Returns:

A new query with the extra “where” clause specified.

Return type:

SimpleQuery

first()

Returns the first item that would be returned as the result of a query.

Returns:

First query item

Return type:

obj

one()

Returns the only item that would be returned by a query.

Returns:

Sole query return item

Return type:

obj

Raises:
property results

Collect and return the results of this query.

Returns:

The results of this query.

Return type:

list

sort(new_sort)

Set the sorting for this query.

Parameters:

new_sort (object) – The new sort criteria for this query.

Returns:

A new query with the sort parameter specified.

Return type:

SimpleQuery

where(new_query)

Add a “where” clause to this query.

Parameters:

new_query (object) – The “where” clause, as a string or solrq.Q object.

Returns:

A new query with the “where” clause specified.

Return type:

SimpleQuery

class SwaggerLoader(stream)

Bases: SafeLoader

YAML loader class for loading Swagger metafiles.

Initialize the scanner.

check_state_key(key)

Block special attributes/methods from being set in a newly created object, to prevent user-controlled methods from being called during deserialization

class UnrefreshableModel(cb, model_unique_id=None, initial_data=None, force_init=False, full_doc=False)

Bases: NewBaseModel

Represents a model that can’t be refreshed, i.e. for which reset() is not a valid operation.

Initialize the NewBaseModel object.

Parameters:
  • cb (CBCloudAPI) – A reference to the CBCloudAPI object.

  • model_unique_id (Any) – The unique ID for this particular instance of the model object.

  • initial_data (dict) – The data to use when initializing the model object.

  • force_init (bool) – True to force object initialization.

  • full_doc (bool) – True to mark the object as fully initialized.

get(attrname, default_val=None)

Return an attribute of this object.

Parameters:
  • attrname (str) – Name of the attribute to be returned.

  • default_val (Any) – Default value to be used if the attribute is not set.

Returns:

The returned attribute value, which may be defaulted.

Return type:

Any

refresh()

Reload this object from the server.

to_json()

Return a json object of the response.

Returns:

The response dictionary representation.

Return type:

Any

construct_include(loader, node)

Include the file referenced by the node.

Parameters:
  • loader (yaml.Loader) – YAML loader object.

  • node (yaml.Node) – Current node being loaded.

Returns:

The data to be included in the YAML loader output.

Return type:

Any

log = <Logger cbc_sdk.base (WARNING)>

Base Models

Connection Module

Manages the CBC SDK connection to the server.

class BaseAPI(*args, **kwargs)

Bases: object

The base API object used by all CBC SDK objects to communicate with the server.

This class is not used directly, but most commonly via the CBCloudAPI class.

Initialize the base API information.

Parameters:
  • *args (list) – Unused.

  • **kwargs (dict) – Additional arguments.

Keyword Arguments:
  • credential_file (str) – The name of a credential file to be used by the default credential provider.

  • credential_provider (cbc_sdk.credentials.CredentialProvider) – An alternate credential provider to use to find the credentials to be used when accessing the Carbon Black Cloud.

  • csp_api_token (str) – The CSP API Token for Carbon Black Cloud.

  • csp_oauth_app_id (str) – The CSP OAuth App ID for Carbon Black Cloud.

  • csp_oauth_app_secret (str) – The CSP OAuth App Secret for Carbon Black Cloud.

  • integration_name (str) – The name of the integration using this connection. This should be specified as a string in the format ‘name/version’

  • max_retries (int) – The maximum number of times to retry failing API calls. Default is 5.

  • org_key (str) – The organization key value to use when accessing the Carbon Black Cloud.

  • pool_block (bool) – True if the connection pool should block when no free connections are available. Default is False.

  • pool_connections (int) – Number of HTTP connections to be pooled for this instance. Default is 1.

  • pool_maxsize (int) – Maximum size of the connection pool. Default is 10.

  • profile (str) – Use the credentials in the named profile when connecting to the Carbon Black Cloud server. Uses the profile named ‘default’ when not specified.

  • proxy_session (requests.session.Session) – Proxy session to be used for cookie persistence, connection pooling, and configuration. Default is None (use the standard session).

  • timeout (float) – The timeout to use for API request connections. Default is None (no timeout).

  • token (str) – The API token to use when accessing the Carbon Black Cloud.

  • url (str) – The URL of the Carbon Black Cloud provider to use.

api_json_request(method, uri, **kwargs)

Submit a request to the server.

Normally only used by other SDK objects; used from user code only to submit a request to the server that is not currently implemented in the SDK.

Parameters:
  • method (str) – HTTP method to use.

  • uri (str) – URI to submit the request to.

  • **kwargs (dict) – Additional arguments.

Keyword Arguments:
  • data (object) – Body data to be passed to the request, formatted as JSON.

  • headers (dict) – Header names and values to pass to the request.

Returns:

Result of the operation, as JSON

Return type:

object

Raises:

ServerError – If there’s an error output from the server.

api_request_iterate(method, uri, **kwargs)

Submit a request to the specified URI and iterate over the response as lines of text.

Should only be used for requests that can be expressed as large amounts of text that can be broken into lines.

Normally only used by other SDK objects; used from user code only to submit a request to the server that is not currently implemented in the SDK.

Parameters:
  • method (str) – HTTP method to use.

  • uri (str) – The URI to send the request to.

  • **kwargs (dict) – Additional arguments for the request.

Keyword Arguments:
  • data (object) – Body data to be passed to the request, formatted as JSON.

  • headers (dict) – Header names and values to pass to the request.

Yields:

str – Each line of text in the returned data.

api_request_stream(method, uri, stream_output, **kwargs)

Submit a request to the specified URI and stream the results back into the given stream object.

Normally only used by other SDK objects; used from user code only to submit a request to the server that is not currently implemented in the SDK.

Parameters:
  • method (str) – HTTP method to use.

  • uri (str) – The URI to send the request to.

  • stream_output (RawIOBase) – The output stream to write the data to.

  • **kwargs (dict) – Additional arguments for the request.

Keyword Arguments:
  • data (object) – Body data to be passed to the request, formatted as JSON.

  • headers (dict) – Header names and values to pass to the request.

Returns:

The return data from the request.

Return type:

object

create(cls, data=None)

Create a new object of a Model class.

Parameters:
  • cls (class) – The Model class (only some models can be created, for example, Feed, Notification, …)

  • data (object) – The data used to initialize the new object.

Returns:

An empty instance of the model class.

Return type:

Model

Raises:

ApiError – If the Model cannot be created.

delete_object(uri)

Send a DELETE request to the specified URI.

Normally only used by other SDK objects; used from user code only to submit a request to the server that is not currently implemented in the SDK.

Parameters:

uri (str) – The URI to send the DELETE request to.

Returns:

The return data from the DELETE request, as JSON.

Return type:

object

get_object(uri, query_parameters=None, default=None)

Submit a GET request to the server and parse the result as JSON before returning.

Normally only used by other SDK objects; used from user code only to submit a request to the server that is not currently implemented in the SDK.

Parameters:
  • uri (str) – The URI to send the GET request to.

  • query_parameters (dict) – Parameters for the query.

  • default (object) – What gets returned in the event of an empty response.

Returns:

Result of the GET request, as JSON.

Return type:

object

get_raw_data(uri, query_parameters=None, default=None, **kwargs)

Submit a GET request to the server and return the result without parsing it.

Normally only used by other SDK objects; used from user code only to submit a request to the server that is not currently implemented in the SDK.

Parameters:
  • uri (str) – The URI to send the GET request to.

  • query_parameters (dict) – Parameters for the query.

  • default (object) – What gets returned in the event of an empty response.

  • **kwargs (dict) – Additional arguments.

Keyword Arguments:

headers (dict) – Header names and values to pass to the GET request.

Returns:

Result of the GET request.

Return type:

object

post_multipart(uri, param_table, **kwargs)

Send a POST request to the specified URI, with parameters sent as multipart/form-data.

Normally only used by other SDK objects; used from user code only to submit a request to the server that is not currently implemented in the SDK.

Parameters:
  • uri (str) – The URI to send the POST request to.

  • param_table (dict) – A dict of known parameters to the underlying method, each element of which is a parameter name mapped to a dict, which contains elements ‘filename’ and ‘type’ representing the pseudo-filename to be used for the data and the MIME type of the data.

  • **kwargs (dict) – Arguments to pass to the API. Except for “headers,” these will all be added as parameters to the form data sent.

Keyword Arguments:

headers (dict) – Header names and values to pass to the request.

Returns:

The return data from the POST request.

Return type:

object

post_object(uri, body, **kwargs)

Send a POST request to the specified URI.

Normally only used by other SDK objects; used from user code only to submit a request to the server that is not currently implemented in the SDK.

Parameters:
  • uri (str) – The URI to send the POST request to.

  • body (object) – The data to be sent in the body of the POST request, as JSON.

  • **kwargs (dict) – Additional arguments for the HTTP POST.

Keyword Arguments:

headers (dict) – Header names and values to pass to the request.

Returns:

The return data from the POST request, as JSON.

Return type:

object

put_object(uri, body, **kwargs)

Send a PUT request to the specified URI.

Normally only used by other SDK objects; used from user code only to submit a request to the server that is not currently implemented in the SDK.

Parameters:
  • 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 (dict) – Additional arguments for the HTTP PUT.

Keyword Arguments:

headers (dict) – Header names and values to pass to the request.

Returns:

The return data from the PUT request, as JSON.

Return type:

object

select(cls, unique_id=None, *args, **kwargs)

Prepare a query against the Carbon Black data store.

Most objects returned by the SDK are returned via queries created using this method.

Parameters:
  • cls (class | str) – The Model class (for example, Computer, Process, Binary, FileInstance) to query

  • unique_id (Any) – The unique id of the object to retrieve, to retrieve a single object by ID. Default is None (create a standard query).

  • *args (list) – Additional arguments to pass to a created object.

  • **kwargs (dict) – Additional arguments to pass to a created object or query.

Returns:

An instance of the Model class if a unique_id is provided, otherwise a Query object.

Return type:

object

property url

The connection URL.

class CBCSDKSessionAdapter(verify_hostname=True, force_tls_1_2=False, max_retries=0, **pool_kwargs)

Bases: HTTPAdapter

Adapter object used to handle TLS connections to the CB server.

Initialize the CBCSDKSessionManager.

Parameters:
  • verify_hostname (boolean) – True if we want to verify the hostname.

  • force_tls_1_2 (boolean) – True to force the use of TLS 1.2.

  • max_retries (int) – Maximum number of retries.

  • **pool_kwargs – Additional arguments.

Raises:

ApiError – If the library versions are too old to force the use of TLS 1.2.

add_headers(request, **kwargs)

Add any headers needed by the connection. As of v2.0 this does nothing by default, but is left for overriding by users that subclass the HTTPAdapter.

This should not be called from user code, and is only exposed for use when subclassing the HTTPAdapter.

Parameters:
  • request – The PreparedRequest to add headers to.

  • kwargs – The keyword arguments from the call to send().

build_connection_pool_key_attributes(request, verify, cert=None)

Build the PoolKey attributes used by urllib3 to return a connection.

This looks at the PreparedRequest, the user-specified verify value, and the value of the cert parameter to determine what PoolKey values to use to select a connection from a given urllib3 Connection Pool.

The SSL related pool key arguments are not consistently set. As of this writing, use the following to determine what keys may be in that dictionary:

  • If verify is True, "ssl_context" will be set and will be the default Requests SSL Context

  • If verify is False, "ssl_context" will not be set but "cert_reqs" will be set

  • If verify is a string, (i.e., it is a user-specified trust bundle) "ca_certs" will be set if the string is not a directory recognized by os.path.isdir(), otherwise "ca_certs_dir" will be set.

  • If "cert" is specified, "cert_file" will always be set. If "cert" is a tuple with a second item, "key_file" will also be present

To override these settings, one may subclass this class, call this method and use the above logic to change parameters as desired. For example, if one wishes to use a custom ssl.SSLContext one must both set "ssl_context" and based on what else they require, alter the other keys to ensure the desired behaviour.

Parameters:
  • request (PreparedRequest) – The PreparedReqest being sent over the connection.

  • verify – Either a boolean, in which case it controls whether we verify the server’s TLS certificate, or a string, in which case it must be a path to a CA bundle to use.

  • cert – (optional) Any user-provided SSL certificate for client authentication (a.k.a., mTLS). This may be a string (i.e., just the path to a file which holds both certificate and key) or a tuple of length 2 with the certificate file path and key file path.

Returns:

A tuple of two dictionaries. The first is the “host parameters” portion of the Pool Key including scheme, hostname, and port. The second is a dictionary of SSLContext related parameters.

build_response(req, resp)

Builds a Response object from a urllib3 response. This should not be called from user code, and is only exposed for use when subclassing the HTTPAdapter

Parameters:
  • req – The PreparedRequest used to generate the response.

  • resp – The urllib3 response object.

Return type:

requests.Response

cert_verify(conn, url, verify, cert)

Verify a SSL certificate. This method should not be called from user code, and is only exposed for use when subclassing the HTTPAdapter.

Parameters:
  • conn – The urllib3 connection object associated with the cert.

  • url – The requested URL.

  • verify – Either a boolean, in which case it controls whether we verify the server’s TLS certificate, or a string, in which case it must be a path to a CA bundle to use

  • cert – The SSL certificate to verify.

close()

Disposes of any internal state.

Currently, this closes the PoolManager and any active ProxyManager, which closes any pooled connections.

get_connection(url, proxies=None)

DEPRECATED: Users should move to get_connection_with_tls_context for all subclasses of HTTPAdapter using Requests>=2.32.2.

Returns a urllib3 connection for the given URL. This should not be called from user code, and is only exposed for use when subclassing the HTTPAdapter.

Parameters:
  • url – The URL to connect to.

  • proxies – (optional) A Requests-style dictionary of proxies used on this request.

Return type:

urllib3.ConnectionPool

get_connection_with_tls_context(request, verify, proxies=None, cert=None)

Returns a urllib3 connection for the given request and TLS settings. This should not be called from user code, and is only exposed for use when subclassing the HTTPAdapter.

Parameters:
  • request – The PreparedRequest object to be sent over the connection.

  • verify – Either a boolean, in which case it controls whether we verify the server’s TLS certificate, or a string, in which case it must be a path to a CA bundle to use.

  • proxies – (optional) The proxies dictionary to apply to the request.

  • cert – (optional) Any user-provided SSL certificate to be used for client authentication (a.k.a., mTLS).

Return type:

urllib3.ConnectionPool

init_poolmanager(connections, maxsize, block=False, **pool_kwargs)

Initialize the connection pool manager.

Parameters:
  • connections (int) – Initial number of connections to be used.

  • maxsize (int) – Maximum size of the connection pool.

  • block (object) – Blocking policy.

  • **pool_kwargs – Additional arguments for the connection pool.

Returns:

None

proxy_headers(proxy)

Returns a dictionary of the headers to add to any request sent through a proxy. This works with urllib3 magic to ensure that they are correctly sent to the proxy, rather than in a tunnelled request if CONNECT is being used.

This should not be called from user code, and is only exposed for use when subclassing the HTTPAdapter.

Parameters:

proxy – The url of the proxy being used for this request.

Return type:

dict

proxy_manager_for(proxy, **proxy_kwargs)

Return urllib3 ProxyManager for the given proxy.

This method should not be called from user code, and is only exposed for use when subclassing the HTTPAdapter.

Parameters:
  • proxy – The proxy to return a urllib3 ProxyManager for.

  • proxy_kwargs – Extra keyword arguments used to configure the Proxy Manager.

Returns:

ProxyManager

Return type:

urllib3.ProxyManager

request_url(request, proxies)

Obtain the url to use when making the final request.

If the message is being sent through a HTTP proxy, the full URL has to be used. Otherwise, we should only use the path portion of the URL.

This should not be called from user code, and is only exposed for use when subclassing the HTTPAdapter.

Parameters:
  • request – The PreparedRequest being sent.

  • proxies – A dictionary of schemes or schemes and hosts to proxy URLs.

Return type:

str

send(request, stream=False, timeout=None, verify=True, cert=None, proxies=None)

Sends PreparedRequest object. Returns Response object.

Parameters:
  • request – The PreparedRequest being sent.

  • stream – (optional) Whether to stream the request content.

  • timeout (float or tuple or urllib3 Timeout object) – (optional) How long to wait for the server to send data before giving up, as a float, or a (connect timeout, read timeout) tuple.

  • verify – (optional) Either a boolean, in which case it controls whether we verify the server’s TLS certificate, or a string, in which case it must be a path to a CA bundle to use

  • cert – (optional) Any user-provided SSL certificate to be trusted.

  • proxies – (optional) The proxies dictionary to apply to the request.

Return type:

requests.Response

class Connection(credentials, integration_name=None, timeout=None, max_retries=None, proxy_session=None, **pool_kwargs)

Bases: object

Object that encapsulates the HTTP connection to the CB server.

Initialize the Connection object.

Parameters:
  • credentials (object) – The credentials to use for the connection.

  • integration_name (str) – The integration name being used.

  • timeout (int) – The timeout value to use for HTTP requests on this connection.

  • max_retries (int) – The maximum number of times to retry a request.

  • proxy_session (requests.Session) –

  • **pool_kwargs – Additional arguments to be used to initialize connection pooling.

Raises:
  • ApiError – If there’s an internal error initializing the connection.

  • ConnectionError – If there’s a problem with the credentials.

delete(url, **kwargs)

Submit a DELETE request on this connection.

Parameters:
  • url (str) – The URL to submit the request to.

  • **kwargs – Additional arguments for the request.

Returns:

Result of the HTTP request.

Return type:

object

get(url, **kwargs)

Submit a GET request on this connection.

Parameters:
  • url (str) – The URL to submit the request to.

  • **kwargs – Additional arguments for the request.

Returns:

Result of the HTTP request.

Return type:

object

http_request(method, url, **kwargs)

Submit a HTTP request to the server.

Parameters:
  • method (str) – The method name to use for the HTTP request.

  • url (str) – The URL to submit the request to.

  • **kwargs – Additional arguments for the request.

Returns:

Result of the HTTP request.

Return type:

object

Raises:
  • ApiError – An unknown problem was detected.

  • ClientError – The server returned an error code in the 4xx range, indicating a problem with the request.

  • ConnectionError – A problem was seen with the HTTP connection.

  • ObjectNotFoundError – The specified object was not found on the server.

  • QuerySyntaxError – The query passed in had invalid syntax.

  • ServerError – The server returned an error code in the 5xx range, indicating a problem on the server side.

  • TimeoutError – The HTTP request timed out.

  • UnauthorizedError – The stored credentials do not permit access to the specified request.

post(url, **kwargs)

Submit a POST request on this connection.

Parameters:
  • url (str) – The URL to submit the request to.

  • **kwargs – Additional arguments for the request.

Returns:

Result of the HTTP request.

Return type:

object

put(url, **kwargs)

Submit a PUT request on this connection.

Parameters:
  • url (str) – The URL to submit the request to.

  • **kwargs – Additional arguments for the request.

Returns:

Result of the HTTP request.

Return type:

object

check_python_tls_compatibility()

Verify which level of TLS/SSL that this version of the code is compatible with.

Returns:

The maximum level of TLS/SSL that this version is compatible with.

Return type:

str

select_class_instance(cls: str)

Given a string class name of a model class, returns the corresponding Carbon Black Cloud SDK class.

Parameters:

cls (str) – The class name represented in a string.

Returns:

The class specified by cls.

Return type:

class

Raises:

ModelNotFound – The specified class could not be found.

try_json(resp)

Return a parsed JSON representation of the input.

Parameters:

resp (Response) – Input to be parsed.

Returns:

The parsed JSON result, or an empty dict if the value is not valid JSON.

Return type:

object

Credentials Module

Credentials management for the CBC SDK.

class CredentialProvider

Bases: object

The interface implemented by a credential provider.

get_credentials(section=None)

Return a Credentials object containing the configured credentials.

Parameters:

section (str) – The credential section to retrieve.

Returns:

The credentials retrieved from that source.

Return type:

Credentials

Raises:

CredentialError – If there is any error retrieving the credentials.

class CredentialValue(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: Enum

All possible credential values.

requires_boolean_value()

Return whether or not this credential requires a boolean value.

Returns:

True if the credential requires a Boolean value, False if not.

Return type:

bool

requires_integer_value()

Return whether or not this credential requires an integer value.

Returns:

True if the credential requires an integer value, False if not.

Return type:

bool

class Credentials(values=None)

Bases: object

The object that contains credentials retrieved from the credential provider.

Initialize the Credentials object.

Parameters:

values (dict) – Dictionary containing values to be set in the credentials.

Raises:

CredentialError – If the value is not correct for any credential of boolean type.

get_token()

Get token required to authenticate with VMware Carbon Black Cloud

Returns:

Token string for VMware Carbon Black Cloud

Return type:

str

get_token_type()

Get token type API_KEY or BEARER

Returns:

The token type

Return type:

str

get_value(key)

Get the value of a credential.

Parameters:

key (CredentialValues) – The credential to be retrieved.

Returns:

The credential’s value, or a default value if the value was not explicitly set.

Return type:

object

to_dict()

Serializes the credentials into a dictionary.

Returns:

Dictionary with the credentials.

Return type:

dict

Errors Module

Exceptions that are thrown by CBC SDK operations.

exception ApiError(message=None, original_exception=None)

Bases: Exception

Base class for all CBC SDK errors; also raised for generic internal errors.

Initialize the ApiError.

Parameters:
  • message (str) – The actual error message.

  • original_exception (Exception) – The exception that caused this one to be raised.

add_note()

Exception.add_note(note) – add a note to the exception

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception ClientError(error_code, message, **kwargs)

Bases: ApiError

A ClientError is raised when an HTTP 4xx error code is returned from the Carbon Black server.

Initialize the ClientError.

Parameters:
  • error_code (int) – The error code that was received from the server.

  • message (str) – The actual error message.

  • kwargs (dict) – Additional arguments, which may include ‘result’ (server operation result), ‘original_exception’ (exception causing this one to be raised), and ‘uri’ (URI being accessed when this error was raised).

add_note()

Exception.add_note(note) – add a note to the exception

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception ConnectionError(message=None, original_exception=None)

Bases: ApiError

There was an error in the connection to the server.

Initialize the ApiError.

Parameters:
  • message (str) – The actual error message.

  • original_exception (Exception) – The exception that caused this one to be raised.

add_note()

Exception.add_note(note) – add a note to the exception

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception CredentialError(message=None, original_exception=None)

Bases: ApiError

The credentials had an unspecified error.

Initialize the ApiError.

Parameters:
  • message (str) – The actual error message.

  • original_exception (Exception) – The exception that caused this one to be raised.

add_note()

Exception.add_note(note) – add a note to the exception

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception FunctionalityDecommissioned(functionality_tag, alternate=None)

Bases: ApiError

Raised when a piece of decommissioned functionality is used.

Initialize the FunctionalityDecommissioned exception.

Parameters:
  • functionality_tag (str) – Should indicate which functionality has been decommissioned.

  • alternate (str) – Optional indication of what the replacement for this functionality is.

add_note()

Exception.add_note(note) – add a note to the exception

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception InvalidHashError

Bases: Exception

An invalid hash value was used.

add_note()

Exception.add_note(note) – add a note to the exception

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception InvalidObjectError(message=None, original_exception=None)

Bases: ApiError

An invalid object was received by the server.

Initialize the ApiError.

Parameters:
  • message (str) – The actual error message.

  • original_exception (Exception) – The exception that caused this one to be raised.

add_note()

Exception.add_note(note) – add a note to the exception

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception ModelNotFound

Bases: Exception

Exception for not finding a model while selecting dynamically.

add_note()

Exception.add_note(note) – add a note to the exception

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception MoreThanOneResultError(message=None, original_exception=None, results=None)

Bases: ApiError

Only one object was requested, but multiple matches were found in the Carbon Black datastore.

Initialize the MoreThanOneResultError.

Parameters:
  • message (str) – The actual error message.

  • original_exception (Exception) – The exception that caused this one to be raised.

  • results (list) – List of results returned

add_note()

Exception.add_note(note) – add a note to the exception

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception NSXJobError(message=None, original_exception=None)

Bases: ApiError

NSX remediation jobs were not started

Initialize the ApiError.

Parameters:
  • message (str) – The actual error message.

  • original_exception (Exception) – The exception that caused this one to be raised.

add_note()

Exception.add_note(note) – add a note to the exception

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception NonQueryableModel(message=None, original_exception=None)

Bases: ApiError

A model that attempted to be queried which is not queryable

Initialize the ApiError.

Parameters:
  • message (str) – The actual error message.

  • original_exception (Exception) – The exception that caused this one to be raised.

add_note()

Exception.add_note(note) – add a note to the exception

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception ObjectNotFoundError(uri, message=None, original_exception=None)

Bases: ApiError

The requested object could not be found in the Carbon Black datastore.

Initialize the ObjectNotFoundError.

Parameters:
  • uri (str) – The URI of the action that failed.

  • message (str) – The error message.

  • original_exception (Exception) – The exception that caused this one to be raised.

add_note()

Exception.add_note(note) – add a note to the exception

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception OperationCancelled(message=None, original_exception=None)

Bases: ApiError

An operation in the background was canceled.

Initialize the ApiError.

Parameters:
  • message (str) – The actual error message.

  • original_exception (Exception) – The exception that caused this one to be raised.

add_note()

Exception.add_note(note) – add a note to the exception

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception QuerySyntaxError(uri, message=None, original_exception=None)

Bases: ApiError

The request contains a query with malformed syntax.

Initialize the QuerySyntaxError.

Parameters:
  • uri (str) – The URI of the action that failed.

  • message (str) – The error message.

  • original_exception (Exception) – The exception that caused this one to be raised.

add_note()

Exception.add_note(note) – add a note to the exception

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception ServerError(error_code, message, **kwargs)

Bases: ApiError

A ServerError is raised when an HTTP 5xx error code is returned from the Carbon Black server.

Initialize the ServerError.

Parameters:
  • error_code (int) – The error code that was received from the server.

  • message (str) – The actual error message.

  • kwargs (dict) – Additional arguments, which may include ‘result’ (server operation result), ‘original_exception’ (exception causing this one to be raised), and ‘uri’ (URI being accessed when this error was raised).

add_note()

Exception.add_note(note) – add a note to the exception

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception TimeoutError(uri=None, error_code=None, message=None, original_exception=None)

Bases: ApiError

A requested operation timed out.

Initialize the TimeoutError.

Parameters:
  • uri (str) – The URI of the action that timed out.

  • error_code (int) – The error code that was received from the server.

  • message (str) – The error message.

  • original_exception (Exception) – The exception that caused this one to be raised.

add_note()

Exception.add_note(note) – add a note to the exception

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception UnauthorizedError(uri, message=None, action='read', original_exception=None)

Bases: ApiError

The action that was attempted was not authorized.

Initialize the UnauthorizedError.

Parameters:
  • uri (str) – The URI of the action that was not authorized.

  • message (str) – The error message.

  • action (str) – The action that was being performed that was not authorized.

  • original_exception (Exception) – The exception that caused this one to be raised.

add_note()

Exception.add_note(note) – add a note to the exception

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

Helpers Module

Helper functions which are not strictly part of the SDK API, but which are used by many of the examples.

build_cli_parser(description='Cb Example Script')

Build a basic CLI parser containing the arguments needed to create a CBCloudAPI. Additional arguments may be added.

Parameters:

description (str) – Description of the script, for use in help messages.

Returns:

The new argument parser.

Return type:

ArgumentParser

disable_insecure_warnings()

Disable warnings about insecure URLs.

eprint(*args, **kwargs)

Print to standard error output.

Parameters:
  • *args (list) – Arguments to the print function.

  • **kwargs (dict) – Keyword arguments to the print function.

get_cb_cloud_object(args)

Based on parsed command line arguments, create and return a CBCloudAPI object.

Parameters:

args (Namespace) – Arguments parsed from the command line.

Returns:

The CBCloudAPI object.

Return type:

CBCloudAPI

get_object_by_name_or_id(cb, cls, name_field='name', id=None, name=None)

Locate an object in the API by either ID or name.

Parameters:
  • cb (CBCloudAPI) – Reference to the CBCloudAPI.

  • cls (class) – Class of object to be found.

  • name_field (str) – Name field to search on.

  • id (int) – ID of object to search for. May be None to do name searching.

  • name (str) – Object name to search on.

  • force_init (bool) – True to force a new object found by ID to be initialized.

Returns:

List of objects that match the search criteria.

Return type:

list

read_iocs(cb, file=<_io.TextIOWrapper name='<stdin>' mode='r' encoding='utf-8'>)

Read indicators of compromise from standard input.

Parameters:
  • cb (CBCloudAPI) – Reference to the CBCloudAPI.

  • file – Not used.

Returns:

New report ID to be used. dict: The indicators of compromise that were read in.

Return type:

str

Live Response API Module

The Live Response API and associated objects.

class CbLRManagerBase(cb, timeout=30, keepalive_sessions=False, thread_pool_count=5)

Bases: object

Live Response manager object.

Initialize the CbLRManagerBase object.

Parameters:
  • cb (BaseAPI) – The CBC SDK object reference.

  • timeout (int) – Timeout to use for requests, in seconds.

  • keepalive_sessions (bool) – If True, “ping” sessions occasionally to ensure they stay alive.

  • thread_pool_count (int) – number of workers for async commands (optional)

close_session(device_id, session_id)

Close the specified Live Response session.

Parameters:
  • device_id (int) – ID of the device.

  • session_id (int) – ID of the session.

request_session(device_id, async_mode=False)

Initiate a new Live Response session.

Parameters:

device_id (int) – The device ID to use.

Returns:

The new Live Response session.

Return type:

CbLRSessionBase

stop_keepalive_thread()

Stops the keepalive thread.

submit_job(job, device)

Submit a new job to be executed as a Live Response.

Parameters:
  • job (func) – The job function to be scheduled.

  • device (int) – ID of the device to use for job execution.

Returns:

A reference to the running job.

Return type:

Future

class CbLRSessionBase(cblr_manager, session_id, device_id, session_data=None, thread_pool_count=5)

Bases: object

A Live Response session that interacts with a remote machine.

Initialize the CbLRSessionBase.

Parameters:
  • cblr_manager (CbLRManagerBase) – The Live Response manager governing this session.

  • session_id (str) – The ID of this session.

  • device_id (int) – The ID of the device (remote machine) we’re connected to.

  • session_data (dict) – Additional session data.

  • thread_pool_count (int) – number of workers for async commands (optional)

cancel_command(command_id)

Cancel command if it is in status PENDING.

Parameters:

command_id (int) – command_id

close()

Close the Live Response session.

command_status(command_id)

Check the status of async command

Parameters:

command_id (int) – command_id

Returns:

status of the command

create_directory(dir_name, async_mode=False)

Create a directory on the remote machine.

Parameters:
  • dir_name (str) – The new directory name.

  • async_mode (bool) – Flag showing whether the command should be executed asynchronously

Returns:

command_id, future if ran async

create_process(command_string, wait_for_output=True, remote_output_file_name=None, working_directory=None, wait_timeout=30, wait_for_completion=True, async_mode=False)

Create a new process on the remote machine with the specified command string.

Example

>>> with c.select(Device, 1).lr_session() as lr_session:
...     print(lr_session.create_process(r'cmd.exe /c "ping.exe 192.168.1.1"'))
Pinging 192.168.1.1 with 32 bytes of data:
Reply from 192.168.1.1: bytes=32 time<1ms TTL=64
Parameters:
  • command_string (str) – Command string used for the create process operation.

  • wait_for_output (bool) – True to block on output from the new process (execute in foreground). This will also set wait_for_completion (below).

  • remote_output_file_name (str) – The remote output file name used for process output.

  • working_directory (str) – The working directory of the create process operation.

  • wait_timeout (int) – Timeout used for this command.

  • wait_for_completion (bool) – True to wait until the process is completed before returning.

  • async_mode (bool) – Flag showing whether the command should be executed asynchronously

Returns:

command_id, future if ran async str: The output of the process.

create_registry_key(regkey, async_mode=False)

Create a new registry key on the remote machine.

Parameters:
  • regkey (str) – The registry key to create.

  • async_mode (bool) – Flag showing whether the command should be executed asynchronously

Returns:

command_id, future if ran async

delete_file(filename, async_mode=False)

Delete the specified file name on the remote machine.

Parameters:
  • filename (str) – Name of the file to be deleted.

  • async_mode (bool) – Flag showing whether the command should be executed asynchronously

Returns:

command_id, future if ran async

delete_registry_key(regkey, async_mode=False)

Delete a registry key on the remote machine.

Parameters:
  • regkey (str) – The registry key to delete.

  • async_mode (bool) – Flag showing whether the command should be executed asynchronously

Returns:

command_id, future if ran async

delete_registry_value(regkey, async_mode=False)

Delete a registry value on the remote machine.

Parameters:
  • regkey (str) – The registry value to delete.

  • async_mode (bool) – Flag showing whether the command should be executed asynchronously

Returns:

command_id, future if ran async

get_file(file_name, timeout=None, delay=None, async_mode=False)

Retrieve contents of the specified file on the remote machine.

Parameters:
  • file_name (str) – Name of the file to be retrieved.

  • timeout (int) – Timeout for the operation.

  • delay (float) – Delay in seconds to wait before command complete.

  • async_mode (bool) – Flag showing whether the command should be executed asynchronously

Returns:

command_id, future if ran async str: Contents of the specified file.

get_raw_file(file_name, timeout=None, delay=None, async_mode=False)

Retrieve contents of the specified file on the remote machine.

Parameters:
  • file_name (str) – Name of the file to be retrieved.

  • timeout (int) – Timeout for the operation.

  • delay (float) – Delay in seconds to wait before command complete.

  • async_mode (bool) – Flag showing whether the command should be executed asynchronously

Returns:

command_id, future if ran async or object: Contains the data of the file.

get_registry_value(regkey, async_mode=False)

Return the associated value of the specified registry key on the remote machine.

Example

>>> with c.select(Device, 1).lr_session() as lr_session:
>>>     pprint.pprint(lr_session.
...     get_registry_value('HKLM\\SYSTEM\\CurrentControlSet\\services\\ACPI\\Start'))
{u'value_data': 0, u'value_name': u'Start', u'value_type': u'REG_DWORD'}
Parameters:
  • regkey (str) – The registry key to retrieve.

  • async_mode (bool) – Flag showing whether the command should be executed asynchronously

Returns:

command_id, future if ran async or dict: A dictionary with keys of: value_data, value_name, value_type.

kill_process(pid, async_mode=False)

Terminate a process on the remote machine.

Parameters:
  • pid (int) – Process ID to be terminated.

  • async_mode (bool) – Flag showing whether the command should be executed asynchronously

Returns:

command_id, future if ran async bool: True if success, False if failure.

list_directory(dir_name, async_mode=False)

List the contents of a directory on the remote machine.

Example

>>> with c.select(Device, 1).lr_session() as lr_session:
...     pprint.pprint(lr_session.list_directory('C:\\\\temp\\\\'))
[{u'attributes': [u'DIRECTORY'],
  u'create_time': 1471897244,
  u'filename': u'.',
  u'last_access_time': 1476390670,
  u'last_write_time': 1476390670,
  u'size': 0},
{u’attributes’: [u’DIRECTORY’],

u’create_time’: 1471897244, u’filename’: u’..’, u’last_access_time’: 1476390670, u’last_write_time’: 1476390670, u’size’: 0},

{u’attributes’: [u’ARCHIVE’],

u’create_time’: 1476390668, u’filename’: u’test.txt’, u’last_access_time’: 1476390668, u’last_write_time’: 1476390668, u’size’: 0}]

Parameters:
  • dir_name (str) – Directory to list. This parameter should end with the path separator.

  • async_mode (bool) – Flag showing whether the command should be executed asynchronously

Returns:

command_id, future if ran async or list: A list of dicts, each one describing a directory entry.

list_processes(async_mode=False)

List currently running processes on the remote machine.

Example

>>> with c.select(Device, 1).lr_session() as lr_session:
...     print(lr_session.list_processes()[0])
{u'command_line': u'',
 u'create_time': 1476260500,
 u'parent': 0,
 u'parent_guid': u'00000001-0000-0000-0000-000000000000',
 u'path': u'',
 u'pid': 4,
 u'proc_guid': u'00000001-0000-0004-01d2-2461a85e4546',
 u'sid': u's-1-5-18',
 u'username': u'NT AUTHORITY\\SYSTEM'}
Parameters:

async_mode (bool) – Flag showing whether the command should be executed asynchronously

Returns:

command_id, future if ran async or list: A list of dicts describing the processes.

list_registry_keys_and_values(regkey, async_mode=False)

Enumerate subkeys and values of the specified registry key on the remote machine.

Example

>>> with c.select(Device, 1).lr_session() as lr_session:
>>> pprint.pprint(lr_session.
...     list_registry_keys_and_values('HKLM\\SYSTEM\\CurrentControlSet\\services\\ACPI'))
{'sub_keys': [u'Parameters', u'Enum'],
'values': [{u'value_data': 0,
     u'value_name': u'Start',
     u'value_type': u'REG_DWORD'},
    {u'value_data': 1,
     u'value_name': u'Type',
     u'value_type': u'REG_DWORD'},
    {u'value_data': 3,
     u'value_name': u'ErrorControl',
     u'value_type': u'REG_DWORD'},
    {u'value_data': u'system32\\drivers\\ACPI.sys',
     u'value_name': u'ImagePath',
     u'value_type': u'REG_EXPAND_SZ'},
    {u'value_data': u'Microsoft ACPI Driver',
     u'value_name': u'DisplayName',
     u'value_type': u'REG_SZ'},
    {u'value_data': u'Boot Bus Extender',
     u'value_name': u'Group',
     u'value_type': u'REG_SZ'},
    {u'value_data': u'acpi.inf_x86_neutral_ddd3c514822f1b21',
     u'value_name': u'DriverPackageId',
     u'value_type': u'REG_SZ'},
    {u'value_data': 1,
     u'value_name': u'Tag',
     u'value_type': u'REG_DWORD'}]}
Parameters:
  • regkey (str) – The registry key to enumerate.

  • async_mode (bool) – Flag showing whether the command should be executed asynchronously

Returns:

command_id, future if ran async

or

dict: A dictionary with two keys, ‘sub_keys’ (a list of subkey names) and ‘values’ (a list of dicts containing value data, name, and type).

list_registry_values(regkey, async_mode=False)

Enumerate all registry values from the specified registry key on the remote machine.

Parameters:
  • regkey (str) – The registry key to enumerate.

  • async_mode (bool) – Flag showing whether the command should be executed asynchronously

Returns:

command_id, future if ran async or list: List of values for the registry key.

memdump(local_filename, remote_filename=None, compress=False, async_mode=False)

Perform a memory dump operation on the remote machine.

Parameters:
  • local_filename (str) – Name of the file the memory dump will be transferred to on the local machine.

  • remote_filename (str) – Name of the file the memory dump will be stored in on the remote machine.

  • compress (bool) – True to compress the file on the remote system.

  • async_mode (bool) – Flag showing whether the command should be executed asynchronously

Returns:

command_id, future if ran async

put_file(infp, remote_filename, async_mode=False)

Create a new file on the remote machine with the specified data.

Example

>>> with c.select(Device, 1).lr_session() as lr_session:
...     lr_session.put_file(open("test.txt", "rb"), r"c:\test.txt")
Parameters:
  • infp (object) – Python file-like containing data to upload to the remote endpoint.

  • remote_filename (str) – File name to create on the remote endpoint.

  • async_mode (bool) – Flag showing whether the command should be executed asynchronously

Returns:

command_id, future if ran async

set_registry_value(regkey, value, overwrite=True, value_type=None, async_mode=False)

Set a registry value on the specified registry key on the remote machine.

Example

>>> with c.select(Device, 1).lr_session() as lr_session:
...     lr_session.
...     set_registry_value('HKLM\\\\SYSTEM\\\\CurrentControlSet\\\\services\\\\ACPI\\\\testvalue', 1)
Parameters:
  • regkey (str) – The registry key to set.

  • value (object) – The value data.

  • overwrite (bool) – If True, any existing value will be overwritten.

  • value_type (str) – The type of value. Examples: REG_DWORD, REG_MULTI_SZ, REG_SZ

  • async_mode (bool) – Flag showing whether the command should be executed asynchronously

Returns:

command_id, future if ran async

start_memdump(remote_filename=None, compress=True)

Start a memory dump operation on the remote machine.

Parameters:
  • remote_filename (str) – Name of the file the memory dump will be stored in on the remote machine.

  • compress (bool) – True to compress the file on the remote system.

Returns:

Controlling object for the memory dump operation.

Return type:

LiveResponseMemdump

walk(top, topdown=True, onerror=None, followlinks=False)

Perform a full directory walk with recursion into subdirectories on the remote machine.

Note: walk does not support async_mode due to its behaviour, it can only be invoked synchronously

Example

>>> with c.select(Device, 1).lr_session() as lr_session:
...     for entry in lr_session.walk(directory_name):
...         print(entry)
('C:\\temp\\', [u'dir1', u'dir2'], [u'file1.txt'])
Parameters:
  • top (str) – Directory to recurse on.

  • topdown (bool) – If True, start output from top level directory.

  • onerror (func) – Callback if an error occurs. This function is called with one argument (the exception that occurred).

  • followlinks (bool) – True to follow symbolic links.

Returns:

List of tuples containing directory name, subdirectory names, file names.

Return type:

list

class CompletionNotification(device_id)

Bases: object

The notification that an operation is complete.

Initialize the CompletionNotification.

Parameters:

device_id (int) – The device ID this notification is for.

class GetFileJob(file_name)

Bases: object

Object that retrieves a file via Live Response.

Initialize the GetFileJob.

Parameters:

file_name (str) – The name of the file to be fetched.

run(session)

Execute the file transfer.

Parameters:

session (CbLRSessionBase) – The Live Response session being used.

Returns:

The contents of the file being retrieved.

Return type:

str

class JobWorker(cb, device_id, result_queue)

Bases: Thread

Thread object that executes individual Live Response jobs.

Initialize the JobWorker.

Parameters:
  • cb (BaseAPI) – The CBC SDK object reference.

  • device_id (int) – The ID of the device being used.

  • result_queue (Queue) – The queue where results are placed.

property daemon

A boolean value indicating whether this thread is a daemon thread.

This must be set before start() is called, otherwise RuntimeError is raised. Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default to daemon = False.

The entire Python program exits when only daemon threads are left.

getName()

Return a string used for identification purposes only.

This method is deprecated, use the name attribute instead.

property ident

Thread identifier of this thread or None if it has not been started.

This is a nonzero integer. See the get_ident() function. Thread identifiers may be recycled when a thread exits and another thread is created. The identifier is available even after the thread has exited.

isDaemon()

Return whether this thread is a daemon.

This method is deprecated, use the daemon attribute instead.

is_alive()

Return whether the thread is alive.

This method returns True just before the run() method starts until just after the run() method terminates. See also the module function enumerate().

join(timeout=None)

Wait until the thread terminates.

This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception or until the optional timeout occurs.

When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). As join() always returns None, you must call is_alive() after join() to decide whether a timeout happened – if the thread is still alive, the join() call timed out.

When the timeout argument is not present or None, the operation will block until the thread terminates.

A thread can be join()ed many times.

join() raises a RuntimeError if an attempt is made to join the current thread as that would cause a deadlock. It is also an error to join() a thread before it has been started and attempts to do so raises the same exception.

property name

A string used for identification purposes only.

It has no semantics. Multiple threads may be given the same name. The initial name is set by the constructor.

property native_id

Native integral thread ID of this thread, or None if it has not been started.

This is a non-negative integer. See the get_native_id() function. This represents the Thread ID as reported by the kernel.

run()

Execute the job worker.

run_job(work_item)

Execute an individual WorkItem.

Parameters:

work_item (WorkItem) – The work item to execute.

setDaemon(daemonic)

Set whether this thread is a daemon.

This method is deprecated, use the .daemon property instead.

setName(name)

Set the name string for this thread.

This method is deprecated, use the name attribute instead.

start()

Start the thread’s activity.

It must be called at most once per thread object. It arranges for the object’s run() method to be invoked in a separate thread of control.

This method will raise a RuntimeError if called more than once on the same thread object.

exception LiveResponseError(details)

Bases: Exception

Exception raised for errors with Live Response.

Initialize the LiveResponseError.

Parameters:

details (object) – Details of the specific error.

add_note()

Exception.add_note(note) – add a note to the exception

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class LiveResponseJobScheduler(cb, max_workers=10)

Bases: Thread

Thread that schedules Live Response jobs.

Initialize the LiveResponseJobScheduler.

Parameters:
  • cb (BaseAPI) – The CBC SDK object reference.

  • max_workers (int) – Maximum number of JobWorker threads to use.

getName()

Return a string used for identification purposes only.

This method is deprecated, use the name attribute instead.

property ident

Thread identifier of this thread or None if it has not been started.

This is a nonzero integer. See the get_ident() function. Thread identifiers may be recycled when a thread exits and another thread is created. The identifier is available even after the thread has exited.

isDaemon()

Return whether this thread is a daemon.

This method is deprecated, use the daemon attribute instead.

is_alive()

Return whether the thread is alive.

This method returns True just before the run() method starts until just after the run() method terminates. See also the module function enumerate().

join(timeout=None)

Wait until the thread terminates.

This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception or until the optional timeout occurs.

When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). As join() always returns None, you must call is_alive() after join() to decide whether a timeout happened – if the thread is still alive, the join() call timed out.

When the timeout argument is not present or None, the operation will block until the thread terminates.

A thread can be join()ed many times.

join() raises a RuntimeError if an attempt is made to join the current thread as that would cause a deadlock. It is also an error to join() a thread before it has been started and attempts to do so raises the same exception.

property name

A string used for identification purposes only.

It has no semantics. Multiple threads may be given the same name. The initial name is set by the constructor.

property native_id

Native integral thread ID of this thread, or None if it has not been started.

This is a non-negative integer. See the get_native_id() function. This represents the Thread ID as reported by the kernel.

run()

Execute the job scheduler.

setDaemon(daemonic)

Set whether this thread is a daemon.

This method is deprecated, use the .daemon property instead.

setName(name)

Set the name string for this thread.

This method is deprecated, use the name attribute instead.

start()

Start the thread’s activity.

It must be called at most once per thread object. It arranges for the object’s run() method to be invoked in a separate thread of control.

This method will raise a RuntimeError if called more than once on the same thread object.

submit_job(work_item)

Submit a new job to be processed.

Parameters:

work_item (WorkItem) – New job to be processed.

class LiveResponseMemdump(lr_session, memdump_id, remote_filename)

Bases: object

Object managing a memory dump on a remote machine.

Initialize the LiveResponseMemdump.

Parameters:
  • lr_session (Session) – The Live Response session to the machine doing the memory dump.

  • memdump_id (str) – The ID of the memory dump being performed.

  • remote_filename (str) – The file name the memory dump will be stored in on the remote machine.

delete()

Delete the memory dump file.

get(local_filename)

Retrieve the remote memory dump to a local file.

Parameters:

local_filename (str) – Filename locally that will receive the memory dump.

wait()

Wait for the remote memory dump to complete.

class LiveResponseSession(cblr_manager, session_id, device_id, session_data=None)

Bases: CbLRSessionBase

Public face of the Live Response session object.

Initializes the LiveResponseSession.

Parameters:
  • cblr_manager (LiveResponseSessionManager) – Reference to the session manager.

  • session_id (str) – The ID of this session.

  • device_id (int) – The ID of the device (remote machine) we’re connected to.

  • session_data (dict) – Additional session data.

cancel_command(command_id)

Cancel command if it is in status PENDING.

Parameters:

command_id (int) – command_id

close()

Close the Live Response session.

command_status(command_id)

Check the status of async command

Parameters:

command_id (int) – command_id

Returns:

status of the command

create_directory(dir_name, async_mode=False)

Create a directory on the remote machine.

Parameters:
  • dir_name (str) – The new directory name.

  • async_mode (bool) – Flag showing whether the command should be executed asynchronously

Returns:

command_id, future if ran async

create_process(command_string, wait_for_output=True, remote_output_file_name=None, working_directory=None, wait_timeout=30, wait_for_completion=True, async_mode=False)

Create a new process on the remote machine with the specified command string.

Example

>>> with c.select(Device, 1).lr_session() as lr_session:
...     print(lr_session.create_process(r'cmd.exe /c "ping.exe 192.168.1.1"'))
Pinging 192.168.1.1 with 32 bytes of data:
Reply from 192.168.1.1: bytes=32 time<1ms TTL=64
Parameters:
  • command_string (str) – Command string used for the create process operation.

  • wait_for_output (bool) – True to block on output from the new process (execute in foreground). This will also set wait_for_completion (below).

  • remote_output_file_name (str) – The remote output file name used for process output.

  • working_directory (str) – The working directory of the create process operation.

  • wait_timeout (int) – Timeout used for this command.

  • wait_for_completion (bool) – True to wait until the process is completed before returning.

  • async_mode (bool) – Flag showing whether the command should be executed asynchronously

Returns:

command_id, future if ran async str: The output of the process.

create_registry_key(regkey, async_mode=False)

Create a new registry key on the remote machine.

Parameters:
  • regkey (str) – The registry key to create.

  • async_mode (bool) – Flag showing whether the command should be executed asynchronously

Returns:

command_id, future if ran async

delete_file(filename, async_mode=False)

Delete the specified file name on the remote machine.

Parameters:
  • filename (str) – Name of the file to be deleted.

  • async_mode (bool) – Flag showing whether the command should be executed asynchronously

Returns:

command_id, future if ran async

delete_registry_key(regkey, async_mode=False)

Delete a registry key on the remote machine.

Parameters:
  • regkey (str) – The registry key to delete.

  • async_mode (bool) – Flag showing whether the command should be executed asynchronously

Returns:

command_id, future if ran async

delete_registry_value(regkey, async_mode=False)

Delete a registry value on the remote machine.

Parameters:
  • regkey (str) – The registry value to delete.

  • async_mode (bool) – Flag showing whether the command should be executed asynchronously

Returns:

command_id, future if ran async

get_file(file_name, timeout=None, delay=None, async_mode=False)

Retrieve contents of the specified file on the remote machine.

Parameters:
  • file_name (str) – Name of the file to be retrieved.

  • timeout (int) – Timeout for the operation.

  • delay (float) – Delay in seconds to wait before command complete.

  • async_mode (bool) – Flag showing whether the command should be executed asynchronously

Returns:

command_id, future if ran async str: Contents of the specified file.

get_raw_file(file_name, timeout=None, delay=None, async_mode=False)

Retrieve contents of the specified file on the remote machine.

Parameters:
  • file_name (str) – Name of the file to be retrieved.

  • timeout (int) – Timeout for the operation.

  • delay (float) – Delay in seconds to wait before command complete.

  • async_mode (bool) – Flag showing whether the command should be executed asynchronously

Returns:

command_id, future if ran async or object: Contains the data of the file.

get_registry_value(regkey, async_mode=False)

Return the associated value of the specified registry key on the remote machine.

Example

>>> with c.select(Device, 1).lr_session() as lr_session:
>>>     pprint.pprint(lr_session.
...     get_registry_value('HKLM\\SYSTEM\\CurrentControlSet\\services\\ACPI\\Start'))
{u'value_data': 0, u'value_name': u'Start', u'value_type': u'REG_DWORD'}
Parameters:
  • regkey (str) – The registry key to retrieve.

  • async_mode (bool) – Flag showing whether the command should be executed asynchronously

Returns:

command_id, future if ran async or dict: A dictionary with keys of: value_data, value_name, value_type.

kill_process(pid, async_mode=False)

Terminate a process on the remote machine.

Parameters:
  • pid (int) – Process ID to be terminated.

  • async_mode (bool) – Flag showing whether the command should be executed asynchronously

Returns:

command_id, future if ran async bool: True if success, False if failure.

list_directory(dir_name, async_mode=False)

List the contents of a directory on the remote machine.

Example

>>> with c.select(Device, 1).lr_session() as lr_session:
...     pprint.pprint(lr_session.list_directory('C:\\\\temp\\\\'))
[{u'attributes': [u'DIRECTORY'],
  u'create_time': 1471897244,
  u'filename': u'.',
  u'last_access_time': 1476390670,
  u'last_write_time': 1476390670,
  u'size': 0},
{u’attributes’: [u’DIRECTORY’],

u’create_time’: 1471897244, u’filename’: u’..’, u’last_access_time’: 1476390670, u’last_write_time’: 1476390670, u’size’: 0},

{u’attributes’: [u’ARCHIVE’],

u’create_time’: 1476390668, u’filename’: u’test.txt’, u’last_access_time’: 1476390668, u’last_write_time’: 1476390668, u’size’: 0}]

Parameters:
  • dir_name (str) – Directory to list. This parameter should end with the path separator.

  • async_mode (bool) – Flag showing whether the command should be executed asynchronously

Returns:

command_id, future if ran async or list: A list of dicts, each one describing a directory entry.

list_processes(async_mode=False)

List currently running processes on the remote machine.

Example

>>> with c.select(Device, 1).lr_session() as lr_session:
...     print(lr_session.list_processes()[0])
{u'command_line': u'',
 u'create_time': 1476260500,
 u'parent': 0,
 u'parent_guid': u'00000001-0000-0000-0000-000000000000',
 u'path': u'',
 u'pid': 4,
 u'proc_guid': u'00000001-0000-0004-01d2-2461a85e4546',
 u'sid': u's-1-5-18',
 u'username': u'NT AUTHORITY\\SYSTEM'}
Parameters:

async_mode (bool) – Flag showing whether the command should be executed asynchronously

Returns:

command_id, future if ran async or list: A list of dicts describing the processes.

list_registry_keys_and_values(regkey, async_mode=False)

Enumerate subkeys and values of the specified registry key on the remote machine.

Example

>>> with c.select(Device, 1).lr_session() as lr_session:
>>> pprint.pprint(lr_session.
...     list_registry_keys_and_values('HKLM\\SYSTEM\\CurrentControlSet\\services\\ACPI'))
{'sub_keys': [u'Parameters', u'Enum'],
'values': [{u'value_data': 0,
     u'value_name': u'Start',
     u'value_type': u'REG_DWORD'},
    {u'value_data': 1,
     u'value_name': u'Type',
     u'value_type': u'REG_DWORD'},
    {u'value_data': 3,
     u'value_name': u'ErrorControl',
     u'value_type': u'REG_DWORD'},
    {u'value_data': u'system32\\drivers\\ACPI.sys',
     u'value_name': u'ImagePath',
     u'value_type': u'REG_EXPAND_SZ'},
    {u'value_data': u'Microsoft ACPI Driver',
     u'value_name': u'DisplayName',
     u'value_type': u'REG_SZ'},
    {u'value_data': u'Boot Bus Extender',
     u'value_name': u'Group',
     u'value_type': u'REG_SZ'},
    {u'value_data': u'acpi.inf_x86_neutral_ddd3c514822f1b21',
     u'value_name': u'DriverPackageId',
     u'value_type': u'REG_SZ'},
    {u'value_data': 1,
     u'value_name': u'Tag',
     u'value_type': u'REG_DWORD'}]}
Parameters:
  • regkey (str) – The registry key to enumerate.

  • async_mode (bool) – Flag showing whether the command should be executed asynchronously

Returns:

command_id, future if ran async

or

dict: A dictionary with two keys, ‘sub_keys’ (a list of subkey names) and ‘values’ (a list of dicts containing value data, name, and type).

list_registry_values(regkey, async_mode=False)

Enumerate all registry values from the specified registry key on the remote machine.

Parameters:
  • regkey (str) – The registry key to enumerate.

  • async_mode (bool) – Flag showing whether the command should be executed asynchronously

Returns:

command_id, future if ran async or list: List of values for the registry key.

memdump(local_filename, remote_filename=None, compress=False, async_mode=False)

Perform a memory dump operation on the remote machine.

Parameters:
  • local_filename (str) – Name of the file the memory dump will be transferred to on the local machine.

  • remote_filename (str) – Name of the file the memory dump will be stored in on the remote machine.

  • compress (bool) – True to compress the file on the remote system.

  • async_mode (bool) – Flag showing whether the command should be executed asynchronously

Returns:

command_id, future if ran async

put_file(infp, remote_filename, async_mode=False)

Create a new file on the remote machine with the specified data.

Example

>>> with c.select(Device, 1).lr_session() as lr_session:
...     lr_session.put_file(open("test.txt", "rb"), r"c:\test.txt")
Parameters:
  • infp (object) – Python file-like containing data to upload to the remote endpoint.

  • remote_filename (str) – File name to create on the remote endpoint.

  • async_mode (bool) – Flag showing whether the command should be executed asynchronously

Returns:

command_id, future if ran async

set_registry_value(regkey, value, overwrite=True, value_type=None, async_mode=False)

Set a registry value on the specified registry key on the remote machine.

Example

>>> with c.select(Device, 1).lr_session() as lr_session:
...     lr_session.
...     set_registry_value('HKLM\\\\SYSTEM\\\\CurrentControlSet\\\\services\\\\ACPI\\\\testvalue', 1)
Parameters:
  • regkey (str) – The registry key to set.

  • value (object) – The value data.

  • overwrite (bool) – If True, any existing value will be overwritten.

  • value_type (str) – The type of value. Examples: REG_DWORD, REG_MULTI_SZ, REG_SZ

  • async_mode (bool) – Flag showing whether the command should be executed asynchronously

Returns:

command_id, future if ran async

start_memdump(remote_filename=None, compress=True)

Start a memory dump operation on the remote machine.

Parameters:
  • remote_filename (str) – Name of the file the memory dump will be stored in on the remote machine.

  • compress (bool) – True to compress the file on the remote system.

Returns:

Controlling object for the memory dump operation.

Return type:

LiveResponseMemdump

walk(top, topdown=True, onerror=None, followlinks=False)

Perform a full directory walk with recursion into subdirectories on the remote machine.

Note: walk does not support async_mode due to its behaviour, it can only be invoked synchronously

Example

>>> with c.select(Device, 1).lr_session() as lr_session:
...     for entry in lr_session.walk(directory_name):
...         print(entry)
('C:\\temp\\', [u'dir1', u'dir2'], [u'file1.txt'])
Parameters:
  • top (str) – Directory to recurse on.

  • topdown (bool) – If True, start output from top level directory.

  • onerror (func) – Callback if an error occurs. This function is called with one argument (the exception that occurred).

  • followlinks (bool) – True to follow symbolic links.

Returns:

List of tuples containing directory name, subdirectory names, file names.

Return type:

list

class LiveResponseSessionManager(cb, timeout=30, keepalive_sessions=False)

Bases: CbLRManagerBase

Session manager for Live Response sessions.

Initialize the LiveResponseSessionManager - only needed to format cblr_base

cblr_session_cls

alias of LiveResponseSession

close_session(device_id, session_id)

Close the specified Live Response session.

Parameters:
  • device_id (int) – ID of the device.

  • session_id (int) – ID of the session.

request_session(device_id, async_mode=False)

Initiate a new Live Response session.

Parameters:

device_id (int) – The device ID to use.

Returns:

The new Live Response session.

Return type:

CbLRSessionBase

session_status(session_id)

Check the status of a lr session

Parameters:

session_id (str) – The id of the session.

Returns:

Status of the session

Return type:

str

stop_keepalive_thread()

Stops the keepalive thread.

submit_job(job, device)

Submit a job for execution by the job scheduler.

Parameters:
  • job (func) – The job function to be executed.

  • device (object) – The device ID or Device object the job will be executed on.

Returns:

A Future that will allow waiting until the job is complete.

Return type:

Future

class WorkItem(fn, device_id)

Bases: object

Work item for scheduling.

Initialize the WorkItem.

Parameters:
  • fn (func) – The function to be called to do the actual work.

  • device_id (object) – The device ID or Device object the work item is directed for.

class WorkerStatus(device_id, status='READY', exception=None)

Bases: object

Holds the status of an individual worker.

Initialize the WorkerStatus.

Parameters:
  • device_id (int) – The device ID this status is for.

  • status (str) – The current status value.

  • exception (Exception) – Any exception that happened.

jobrunner(callable, cb, device_id)

Wrap a callable object with a live response session.

Parameters:
  • callable (object) – The object to be wrapped.

  • cb (BaseAPI) – The CBC SDK object reference.

  • device_id (int) – The device ID to use to get the session.

Returns:

The wrapped object.

Return type:

object

poll_status(cb, url, desired_status='COMPLETE', timeout=None, delay=None)

Poll the status of a Live Response query.

Parameters:
  • cb (BaseAPI) – The CBC SDK object reference.

  • url (str) – The URL to poll.

  • desired_status (str) – The status we’re looking for.

  • timeout (int) – The timeout value in seconds.

  • delay (float) – The delay between attempts in seconds.

Returns:

The result of the Live Response query that has the desired status.

Return type:

object

Raises:

LiveResponseError – If an error response was encountered.

Utils Module

Utility functions for use within the CBC SDK.

class BackoffHandler(cb, timeout=0, initial=0.1, multiplier=2.0, threshold=2.0)

Bases: object

Logic for handling exponential backoff of multiple communications requests.

The logic also handles timeouts of operations that go on too long.

Example:

backoff = BackoffHandler(timeout=600000)  # 10 minutes = 600 seconds
with backoff as b:
    while operation_continues():
        b.pause()
        do_operation()

Initialize the BackoffHandler.

Parameters:
  • cb (BaseAPI) – The API object for the operation.

  • timeout (int) – The timeout for the operation, in milliseconds. If this is 0, the default timeout as configured in the credentials will be used. The default is 0.

  • initial (float) – The initial value for the exponential backoff pause, in seconds. The default is 0.1.

  • multiplier (float) – The value by which the exponential backoff pause will be multiplied each time a pause happens. The default is 2.0.

  • threshold (float) – The maximum value for the exponential backoff pause, in seconds. The default is 2.0.

class BackoffOperation(timeout, initial, multiplier, threshold)

Bases: object

Handler for a single operation requiring exponential backoff between communication attempts.

This is returned by BackoffHandler as part of the with operation, and is stored in the variable referred to in its as clause.

Initialize the BackoffOperation.

Parameters:
  • timeout (int) – The timeout for the operation, in milliseconds.

  • initial (float) – The initial value for the exponential backoff pause, in seconds.

  • multiplier (float) – The value by which the exponential backoff pause will be multiplied each time a pause happens.

  • threshold (float) – The maximum value for the exponential backoff pause, in seconds.

pause()

Pauses operation for a determined amount of time.

The method also checks for a timeout and raises TimeoutError if it happens, and computes the amount of time to pause the next time this method is called.

Raises:

TimeoutError – If the timeout value is reached.

reset(full=False)

Resets the state of the operation so that the pause time is reset.

Does not affect the timeout value. This should be used, for instance, after a successful operation to minimize the pause before the next operation is started.

Parameters:

full (bool) – If this is True, the next pause time will be reset to 0. If this is False, the next pause time will be reset to the initial pause time.

property timeout

Returns the current timeout associated with this handler, in milliseconds.

convert_from_cb(s)

Parse a date and time value into a datetime object.

Parameters:

s (str) – The date and time string to parse. If this is None, we use the UNIX epoch timestamp.

Returns:

The parsed date and time.

Return type:

datetime

convert_to_cb(dt)

Convert a date and time to a string in the Carbon Black format.

Parameters:

dt (datetime) – The date and time to be converted.

Returns:

The date and time as a string.

Return type:

str

WinError Module

Error related constants for win32

Generated by h2py from winerror.h

class CommDlgError

Bases: ErrorBaseClass

Collects all the common dialog error codes.

classmethod lookup_error(error_code)

Look up an error code by value.

Parameters:

error_code (int) – The error code to be looked up.

Returns:

The error code name.

Return type:

str

class DirectoryStorageError

Bases: ErrorBaseClass

Collects all the directory storage error codes.

classmethod lookup_error(error_code)

Look up an error code by value.

Parameters:

error_code (int) – The error code to be looked up.

Returns:

The error code name.

Return type:

str

class ErrorBaseClass

Bases: object

Base class for repositories of error codes.

classmethod lookup_error(error_code)

Look up an error code by value.

Parameters:

error_code (int) – The error code to be looked up.

Returns:

The error code name.

Return type:

str

class ErrorMetaClass(name, bases, clsdict)

Bases: type

Metaclass which establishes an easy means of looking up error codes in a collection.

Creates a new instance of a class, setting up the dict to make it easy to look up error codes.

Parameters:
  • name (str) – The name of the class.

  • bases (list) – Base classes of the class to be created.

  • clsdict (dict) – Elements defined in the new class.

mro()

Return a type’s method resolution order.

FAILED(Status)

Return True iff a HRESULT/SCODE status represents failure.

class Facility

Bases: ErrorBaseClass

Collects all known facility codes.

classmethod lookup_error(error_code)

Look up an error code by value.

Parameters:

error_code (int) – The error code to be looked up.

Returns:

The error code name.

Return type:

str

GetScode(hr)

Turn a HRESULT into a SCODE.

HRESULT_CODE(hr)

Return the error code field of a HRESULT.

HRESULT_FACILITY(hr)

Return the facility field of a HRESULT.

HRESULT_FROM_NT(x)

Turn an NT error code into a HRESULT.

HRESULT_FROM_WIN32(scode)

Return the HRESULT corresponding to a Win32 error code.

HRESULT_SEVERITY(hr)

Return the severity field of a HRESULT.

class RawErrorCode

Bases: ErrorBaseClass

Collects all known error codes defined as raw SCODEs (from COM, OLE, etc.)

classmethod lookup_error(error_code)

Look up an error code by value.

Parameters:

error_code (int) – The error code to be looked up.

Returns:

The error code name.

Return type:

str

ResultFromScode(sc)

Turn a SCODE into a HRESULT.

SCODE_CODE(sc)

Return the error code field of a SCODE.

SCODE_FACILITY(sc)

Return the facility field of a SCODE.

SCODE_SEVERITY(sc)

Return the severity field of a SCODE.

SUCCEEDED(Status)

Return True iff a HRESULT/SCODE status represents success.

class Win32Error

Bases: ErrorBaseClass

Collects all the Win32 error codes.

classmethod lookup_error(error_code)

Look up an error code by value.

Parameters:

error_code (int) – The error code to be looked up.

Returns:

The error code name.

Return type:

str

decode_hresult(hresult)

Look up a Win32 error code based on the error code in a HRESULT.