CrowdStrike Falcon CrowdStrike Subreddit

Using Service Classes

Documentation Version Page Updated

A Service Class provides a one-to-one interface to a single CrowdStrike API service collection with methods defined for every operation that exists within that service collection.

Import and Authentication

To make use of a Service Class to communicate with a specific CrowdStrike API service collection, you will need to construct an instance of it. This involves importing the class, and then providing API credentials and any additional configuration options required for your environment.

For more detail regarding additional configuration options not related to authentication, please review the Environment Configuration page.

Service Classes support multiple authentication mechanisms allowing developers to select the solution that best meets their needs.

Passing credentials

:warning: WARNING :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 directly to the class as keywords when you create it.

from falconpy import Hosts

hosts = Hosts(client_id=CLIENT_ID, client_secret=CLIENT_SECRET)

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

Credential Authentication

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

from falconpy import Hosts

hosts = Hosts(creds={"client_id": CLIENT_ID, "client_secret": CLIENT_SECRET})

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

Object Authentication

Object Authentication allows you to create an instance of any Service Class (or the Uber Class), authenticate, and then use this class as the auth_object for additional Service Classes. Either Direct Authentication, Credential Authentication or Environment Authentication may be used to create the instance of the authenticating class.

Object Authentication using keywords

from falconpy import Hosts, OAuth2

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

hosts = Hosts(auth_object=auth)

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

Object Authentication using a credential dictionary

from falconpy import Detects, Hosts

hosts = Hosts(creds={"client_id": CLIENT_ID, "client_secret": CLIENT_SECRET})
# We do not need to use an instance of the OAuth2 Service Class for Object Authentication.
# Any Service Class can share it's auth_object with another.
detects = Detects(auth_object=hosts)

Environment Authentication

Environment Authentication enables the storage of credentials within the running environment. When present, these credentials are leveraged to authentication to the CrowdStrike API if no other credentials are provided. These variables are named FALCON_CLIENT_ID and FALCON_CLIENT_SECRET.

from falconpy import Detects

detects = Detects()

print(detects.query_detects())

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 Hosts

authorization = OAuth2(creds={"client_id": CLIENT_ID, "client_secret": CLIENT_SECRET})

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

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

Back to Top


Performing a request

Once you have provided your API credentials (and any necessary customization options) you are ready to interact with the API service collection. Each Service Class has a method defined for every Operation within the API service collection. You may leverage either PEP8 or Operation ID syntax to perform the operations. Depending on the requirements of the selected operation, different payloads will also need to be specified at the time of the request. More detail regarding the requirements of specific API operations and their payloads are provided in the wiki page for the related API service collection.

This examples leverages the Hosts Service Class to interact with the CrowdStrike API to retrieve the IDs for 5 endpoints.

from falconpy import Hosts

hosts = Hosts(client_id=CLIENT_ID, client_secret=CLIENT_SECRET)

# You can use PEP8 or Operation ID syntax for this call
response = falcon.query_devices_by_filter_scroll(limit=5)
# Show our results
print(response)

API responses

By default, API response results will be in the form of a JSON formatted dictionary or a binary object. Using FalconPy v1.3.0 or greater, developers are also able to construct Service Classes that return results as pythonic objects.

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.

{
	"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


Service Class architecture

Upon creation, Service Classes authenticate the attached auth_object using the specified authentication mechanism. The following default functionality is available in all regular Service Classes.

OAuth2 is a derivative of the FalconInterface class, hence it is considered an auth_object and does not function like regular Service Classes.

Attributes

The following attributes are available in all regular Service Classes regardless of service collection.

NamePurposeData type
auth_objectThe attached FalconInterface object used for authentication and maintaining state.FalconInterface
validate_payloadsFlag indicating if payload contents sent to the API should be validated before being sent. This functionality is only implemented in a limited number of Service Classes at this time.Boolean

Methods

The following methods are available in all Service Classes regardless of service collection. Service Classes will also have methods available specific to the service collection they represent. Documentation regarding specific API operations can be found in the related service collection documentation page.

NamePurposeReturns
authenticated

DEPRECATED
Method handler that returns the current authentication state.Boolean
loginPerforms a request for a bearer token and updates the authentication objects current state.Dictionary
logoutRevokes the current API bearer token and updates the objects current state.Dictionary
token_expired

DEPRECATED
Method handler that returns the current token expiration status.Boolean

Properties

The following properties are available in all regular Service Classes regardless of service collection.

NamePurposeMutable?
base_urlThe base URL address for the target CrowdStrike API. This can be the shortname, or the full address.Yes
ssl_verifyThe SSL verification setting (boolean or certificate location).Yes
logThe logger object for this object. This property can be enabled or disabled per Service Class regardless of the setting specified in the attached auth_object.

When not specifically enabled or disabled, this property is returned from the auth_object attribute.
No
headersThe headers that are sent for all API requests performed. This includes authentication headers that are requested from the attached auth_object and any custom headers provided when the object is created via the ext_headers keyword argument provide upon construction.No
timeoutAmount of time before considering a connection as timed out. When specififying a float for this value, the timeout is used for the entire request. When specified as a tuple this is used for read and connect.Yes
tokenThe current token value as a stringNo
token_statusThe returned status code when the token was generated for this Service Class. For successful authentication scenarios, this value will be 201.No
token_fail_reasonAPI authentication failure reason. This property is only populated upon token generation failure.No
token_staleBoolean flag indicating if the current token has expiredNo
token_validBoolean flag indicating if the current token is valid.No
refreshableBoolean flag indicating if the current bearer token can be automatically refreshed.No
debugBoolean flag indicating if the current object has debug mode enabled. This property can be enabled or disabled per Service Class regardless of the setting specified in the attached auth_object.

When not specifically enabled or disabled, this property is returned from the auth_object attribute.
No
proxyProxy dictionary that is leveraged to perform API requests from this object. This property can be set to a unique value per Service Class regardless of the setting specified in the attached auth_object.

When not specifically set, this property is returned from the auth_object attribute.
Yes
renew_windowThe amount of time in seconds before the token expires and the token is automatically refreshed. This property is returned from the auth_object attribute. Changing this value will impact all classes that leverage this same authentication object.Yes
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
user_agentThe User-Agent string that is sent as part of the headers for all API requests performed. This property can be set to a unique value per Service Class regardless of the setting specified in the attached auth_object.

When not specifically set, this property is returned from the auth_object attribute.
Yes
debug_record_countThe maximum number of records per API call performed to be logged in debug logs. This property can be set to a unique value per Service Class regardless of the setting speficied in the attached auth_object.

When not specificially set, this property is returned from the auth_object attribute.
Yes
sanitize_logBoolean flag indicating if client_id, client_secret, member_cid and bearer token values should be sanitized from debug logs. This property can be enabled or disabled per Service Class regardless of the setting specified in the attached auth_object.

When not specifically enabled or disabled, this property is returned from the auth_object attribute.
Yes
pythonicBoolean flag indicating if results returned from the API should be provided as a JSON dictionary or a pythonic object. This property can be enabled or disabled per Service Class regardless of the setting specified in the attached auth_object.

When not specifically enabled or disabled, this property is returned from the auth_object attribute.
No

Back to Top