Basic Service Class usage - CrowdStrike/falconpy GitHub Wiki
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.
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.
- Direct Authentication
- Credential Authentication
- Object Authentication
- Environment Authentication
- Context Authentication
- Legacy Authentication
⚠️ WARNING⚠️
client_id
andclient_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 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 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 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.
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.
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 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())
Context Authentication enables the retrieval of the bearer token from the current running context. When present, this token is leveraged for all requests to the API. This authentication mechanism is primarily used in Fusion workflow actions. FalconPy service classes that have authenticated using Context Authentication do not have access to API credentials and cannot automatically renew the bearer token.
You must be running FalconPy v1.4.3 or greater in order to take advantage of Context Authentication.
from falconpy import Alerts
from crowdstrike.foundry.function import Function, Response
func = Function.instance()
@func.handler(method='POST', path='/data')
def on_query(request, config: Union[Dict[str, any], None]) -> Response:
with Alerts() as alerts:
result = alerts.query_alerts_v2()
return Response(body=result["body"], code=result["status_code"])
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.
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)
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": []
}
}
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 anauth_object
and does not function like regular Service Classes.
The following attributes are available in all regular Service Classes regardless of service collection.
Name | Purpose | Data type |
---|---|---|
auth_object |
The attached FalconInterface object used for authentication and maintaining state. |
|
validate_payloads |
Flag 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. |
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.
Name | Purpose | Returns |
---|---|---|
authenticated |
Method handler that returns the current authentication state. | |
login |
Performs a request for a bearer token and updates the authentication objects current state. | |
logout |
Revokes the current API bearer token and updates the objects current state. | |
token_expired |
Method handler that returns the current token expiration status. |
The following properties are available in all regular Service Classes regardless of service collection.
Name | Purpose | Mutable? |
---|---|---|
base_url |
The base URL address for the target CrowdStrike API. This can be the shortname, or the full address. | |
ssl_verify |
The SSL verification setting (boolean or certificate location). | |
log |
The 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. |
|
headers |
The 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. |
|
timeout |
Amount 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 . |
|
token |
The current token value as a string | |
token_status |
The returned status code when the token was generated for this Service Class. For successful authentication scenarios, this value will be 201 . |
|
token_fail_reason |
API authentication failure reason. This property is only populated upon token generation failure. | |
token_stale |
Boolean flag indicating if the current token has expired | |
token_valid |
Boolean flag indicating if the current token is valid. | |
refreshable |
Boolean flag indicating if the current bearer token can be automatically refreshed. | |
debug |
Boolean 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. |
|
proxy |
Proxy 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. |
|
renew_window |
The 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. |
|
token_renew_window |
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. |
|
user_agent |
The 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. |
|
debug_record_count |
The 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. |
|
sanitize_log |
Boolean 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. |
|
pythonic |
Boolean 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. |