Skip to content

Basic Uber Class usage

Joshua Hiller edited this page Mar 23, 2024 · 24 revisions

CrowdStrike Falcon CrowdStrike Subreddit

Using the Uber Class

Documentation Version Page Updated

Both an interface and a derivative class, the Uber Class provides an all-in-one interface to every service collection within the CrowdStrike API.

This documentation reflects functionality available within the latest version of the Uber Class (APIHarnessV2) released in v1.3.2. The legacy version of the Uber Class (APIHarness) is deprecated, does not support Environment Authentication, or several of the methods and properties detailed here.

Import and Authentication

To make use of the Uber Class, you will need to import it, and then construct an instance of the class. During this construction, you will provide API credentials for authentication and specify any additional configuration options required by your environment.

The Uber class leverages three authentication mechanisms, Direct Authentication, Credential Authentication and Environment Authentication. These methods abstract token administration and allow developers to skip the initial authentication step if desired.

You will not authenticate until you request the headers property, or your first request to the API is made. If you check your authentication status, your token or your token_expiration before performing a request, the results will be 0 or None.

Passing credentials

WARNING

client_id and client_secret are keyword arguments that contain your CrowdStrike API credentials. Please note that all examples below do not hard code these values. (These values are ingested as strings.)

CrowdStrike does NOT recommend hard coding API credentials or customer identifiers within source code.

Direct Authentication

Direct Authentication allows you to pass your credentials to the class as keywords when you create it.

from falconpy import APIHarnessV2

auth = APIHarnessV2(client_id=CLIENT_ID, client_secret=CLIENT_SECRET)

# This example also demonstrates Parameter Abstraction
# within the Uber Class, in our next example, we will
# pass the same argument using the parameters dictionary.
result = falcon.command(action="QueryDevicesByFilterScroll", limit=100)

print(result)

# Only logout when you are done interacting with the API
falcon.logout()

For more detail, please review the full Direct Authentication documentation.

Credential Authentication

Credential Authentication allows you to pass your credentials as a dictionary to the class when you create it.

from falconpy import APIHarnessV2

falcon = APIHarnessV2(creds={"client_id": CLIENT_ID, "client_secret": CLIENT_SECRET})

PARAMS = {"limit": 10}

result = falcon.command(action="QueryDevicesByFilterScroll", parameters=PARAMS)

print(result)

# Only logout when you are done interacting with the API
falcon.logout()

For more detail, please review the full Credential Authentication documentation.

Environment Authentication

Starting in v1.3.0, you may now use the Environment Authentication mechanism to authenticate with the Uber Class.

In order for Environment Authentication to be used, you must have the following two variables defined within the environment at runtime.

Name Purpose
FALCON_CLIENT_ID CrowdStrike Falcon API client ID
FALCON_CLIENT_SECRET CrowdStrike Falcon API client secret

Both variables must be defined in the environment before Environment Authentication will be attempted. If both environment variables are present, and only one of these values exist within the creds dictionary, then the missing value will be replaced with the value stored within the environment.

from falconpy import APIHarnessV2

falcon = APIHarnessV2()

hidden_devices = falcon.command("QueryHiddenDevices")

print(hidden_devices)

# Only logout when you are done interacting with the API
falcon.logout()

Legacy Authentication

In order to make use of legacy authentication, you will first need to create an instance of the OAuth2 derivative class in order to generate a token. You may use Direct Authentication, Credential Authentication or Environment Authentication when you create an instance of this class.

from falconpy import OAuth2
from falconpy import APIHarnessV2

authorization = OAuth2(client_id=CLIENT_ID, client_secret=CLIENT_SECRET)

try:
    token = authorization.token()["body"]["access_token"]
    falcon = APIHarnessV2(access_token=token)
except:
    token = False
    # Failure handling here

For more detail, please review the full Legacy Authentication documentation.

Back to Top

For more detail, please review the full Environment Authentication documentation.

Additional attributes

Authorization status and the token are available as properties.

from falconpy import APIHarnessV2
falcon = APIHarnessV2(client_id=CLIENT_ID, client_secret=CLIENT_SECRET)

falcon.login()

if falcon.authenticated:
    print(falcon.token_value)

Example result

$ eyJhbGciOiJSUzI1NiIsImtpZCI6InB1YmxpYzph...really long token string

Aditional configuration options

The Uber Class provides full support for all custom environment configuration options supported by Service Classes.

Back to Top


The command method

The Uber Class leverages a single method to make calls to the CrowdStrike API. This method is called command, and handles all the same payload types that Service Class API operation methods handle.

Allowed arguments and keywords

The command method accepts only one positional argument, which is assumed to be the action keyword and contain the requested Operation ID. Either this argument must be specified, or one of the keywords, action or override, in order to make use of the command method. All other keywords are optional based upon the API operation being performed.

Keyword Description
action Operation ID to perform. Can be omitted if passed as the first argument to the method. If an Operation ID is not provided as an action, the override keyword must be used.
parameters Query string payload, provided as a dictionary (JSON).
body Body payload, provided as a dictionary (JSON) or a binary.
content_type Forces the Content-Type header for the request being performed.
data Data payload, provided as a dictionary (JSON) or a binary.
files File array formatted file data payload.
file_name Name of the file represented within a form or file data payload.
headers Dictionary of additional headers to add to headers provided when performing the request.
ids Comma-delimited string or list of strings containing the IDs necessary for the requested operation. Only required by some API operations. The ids keyword is the only example of Body Payload Abstraction that the Uber Class supports. Values provided to this keyword will be propagated to the payload type required by the specific operation called.
partition Number of the stream partition to refresh. Specific to the Event Streams API service collection.
distinct_field Name of the field to search for distinct references. Specific to the Sensor Update Policy API service collection.
override String representation of the desired API operation's HTTP method and route when the Operation ID is unknown. Should be provided in METHOD,ROUTE format. Route should not contain the base URL. If the override keyword is not provided, the API Operation ID must be specified as the first positional argument or as the action keyword. For more detail regarding the override keyword and it's usage, please review the example below.

Parameter Abstraction

As of the v0.8.0 release, the Uber Class supports Parameter Abstraction. This functionality allows developers to specify query string parameter values using keywords as opposed to crafting a parameters dictionary and passing it to the command method using the parameters keyword.

Example
from falconpy import APIHarnessV2

falcon = APIHarnessV2(client_id=CLIENT_ID, client_secret=CLIENT_SECRET)

result = falcon.command("QueryDevicesByFilterScroll", limit=100, sort="hostname.asc")

print(result)

Specifying route and method manually (Override)

The Uber Class supports specifying an API operation's HTTP method and route via the override keyword. This argument is provided as a string and should follow METHOD,ROUTE format.

Parameter Abstraction functionality is not supported when making use of the override keyword.

Example

The following example performs the same request demonstrated above, but instead calls the endpoint manually using the override keyword.

from falconpy import APIHarnessV2

falcon = APIHarnessV2(client_id=CLIENT_ID, client_secret=CLIENT_SECRET)

# When using the override keyword, parameter abstraction functionality is not supported. Instead,
# we will create a dictionary to hold these values and provide them to the parameters keyword.
PARAMS = {"limit": 100, "sort": "hostname.asc"}

result = falcon.command(override="GET,/devices/queries/devices-scroll/v1", parameters=PARAMS)

print(result)

API responses

Most API response results will be in the form of a JSON formatted dictionary.

Review the Content-Type section within the operation details of the related service collection wiki page to identify operations that produce results that are binary and will require being saved to a file.

Example

{
	"status_code": 200,
	"headers": {
		"Server": "nginx",
		"Date": "Sat, 22 Jul 2023 06:11:11 GMT",
		"Content-Type": "application/json",
		"Content-Length": "512",
		"Connection": "keep-alive",
		"Content-Encoding": "gzip",
		"Strict-Transport-Security": "max-age=15724800; includeSubDomains, max-age=31536000; includeSubDomains",
		"X-Cs-Region": "us-1",
		"X-Cs-Traceid": "a1bcd234-efa5-6b78-9012-3c4d56ef7a8b",
		"X-Ratelimit-Limit": "6000",
		"X-Ratelimit-Remaining": "5999"
	},
	"body": {
		"meta": {
			"query_time": 0.006985558,
			"pagination": {
				"total": 21310,
				"offset": "FQluY2x1ZGVfY29udGV4dF91dWlkDnF1ZXJ5VGhlbkZldGNoAhZHTF80UlNJYlRtbV9VVVB2TDNzeXFRAAAAABOoKoMWM1FBbS1nVEVRc0c0YjBsYWdVNnAzUYXASEb8bXRvSVFSS0VsQ3BLd3lZbmRRAAAAABTHsT4WWW0zSVFoM01UM2lmYWlRUFJwdzFwQQ==",
				"expires_at": 1690006391067438708
			},
			"powered_by": "device-api",
			"trace_id": "a1bcd234-efa5-6b78-9012-3c4d56ef7a8b"
		},
		"resources": ["123abcde45f67890a1234b5c6de789f0", "a1b2cde3fa4567bcd8e9f0a1b2c34d5d", "a1b23c45d67e8901fa2a34b56cd78ef9", "1a2b3cd4ef5a67b8c9012dfe34567890", "1a2bcde34f5a6b789012cd3ef456a7b8"],
		"errors": []
	}
}

Back to Top


Uber Class architecture

The following attributes, methods and properties are available within the Uber Class upon creation.

Documentation regarding specific API operations can be found in the related service collection documentation page.

Attributes

Upon creation, an instance of the Uber Class will contain the following attributes.

Attribute name Data type Default Value Description
commands Dictionary None Complete list of available API operations.

Methods

The following methods are available within any instance of the Uber Class.

Name Purpose
authenticate

DEPRECATED
Legacy handler to authenticate against the CrowdStrike API and generate a bearer token. This method is deprecated, developers should make use of the login method to access this functionality.
authenticated

DEPRECATED
Returns a boolean flag indicating if the current object is successfully authenticated to the CrowdStrike API.
command Performs the specified API operation. If the class is not currently authenticated, an attempt to generate the bearer token will be made.
deauthenticate

DEPRECATED
Legacy handler to revoke the current bearer token. This method is deprecated, developers should make use of the logout method to access this functionality.
headers

DEPRECATED
Legacy method handler for retrieving the current authorization headers. This method is deprecated, developers should instead use the auth_headers property to access this functionality.
login Leverages a private method to perform a request for a bearer token and updates the authentication object's current state.
logout Leverages a private method to revoke the current API bearer token and updates the object's current state.
token

DEPRECATED
Legacy method handler for retrieving the current bearer token value as a string. This method is deprecated, developers should instead use the token_value property to access this functionality.
token_expired

DEPRECATED
Returns a boolean flag indicating if the current bearer token is expired.
valid_cred_format

DEPRECATED
Legacy handler that returns a boolean indicating if the current credentials dictionary is in a valid format. This method is deprecated, developers should make use of the cred_format_valid property instead.

Properties

The following properties are available within any instance of the Uber Class.

Name Purpose Mutable?
auth_headers The authentication headers that are sent along with all requests to the CrowdStrike API. If the FalconInterface object is not currently authenticated, an authentication request will be performed when this property is referenced. No
base_url The base URL for the target CrowdStrike API. This can be the shortname, or the full address. Yes
bearer_token A data class that represents the current CrowdStrike bearer token. Yes
config The InterfaceConfiguration object used for this authentication object. Yes
creds A dictionary containing the client_id and client_secret used to authenticate to the CrowdStrike API. Yes
cred_format_valid A boolean flag indicating if the current format of the creds dictionary is valid. No
debug Boolean flag indicating if the current object has debug mode enabled. No
debug_record_count The maximum number of records per API call performed to be logged in debug logs. Yes
log The logger object used for this object. No
log_facility The attached debug logging facility for this object. No
proxy Proxy dictionary that is leveraged to perform API requests from this object. Yes
pythonic A boolean flag indicating if results returned from the API should be provided as a JSON dictionary or a pythonic object. Yes
renew_window The amount of time in seconds before the token expires and the token is automatically refreshed. Yes
refreshable A boolean flag indicating if the current bearer token can be automatically refreshed. No
sanitize_log A boolean flag indicating if client_id, client_secret, member_cid and bearer token values should be sanitized from debug logs. Yes
ssl_verify The SSL verification setting (boolean or certificate location). Yes
timeout The connect or connect / read timeout for requests made to the CrowdStrike API. Yes
token_status The current API bearer token status. For successful authentication scenarios, this value will be 201. This attribute is populated after calling the authenticate method or after your first usage of the command method. No
token_expiration The remaining time, in seconds, the current bearer token is considered valid. Yes
token_fail_reason API authentication failure reason. No
token_stale Boolean flag indicating if the current token has expired No
token_valid Boolean flag indicating if the current token is valid. No
token_renew_window

DEPRECATED
This property recreates the functionality of a legacy Service Class attribute and is deprecated. Developers should make use of the renew_window property to make changes to the token renewal window. Yes
token_time The timestamp when the current bearer token was generated. Yes
token_value The bearer token value as a string. Yes
user_agent The User-Agent string that is sent as part of the headers for all API requests performed. Yes

Back to Top

CrowdStrike Falcon

Clone this wiki locally