Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Version 1.0.6 - Dashed base_url specifiers, Uber class 401 failure headers, TokenFailReason enum #584

Merged
merged 16 commits into from
Mar 10, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/wordlist.txt
Original file line number Diff line number Diff line change
Expand Up @@ -701,3 +701,4 @@ getroles
mwb
uber
masse
PyCQA
2 changes: 1 addition & 1 deletion .github/workflows/bandit.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ jobs:
- name: Install dependencies
run: |
python -m pip install --upgrade pip
python -m pip install bandit==1.7.2
python -m pip install bandit
pip install -r requirements.txt
- name: Analyze package with bandit
run: |
Expand Down
20 changes: 20 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,23 @@
# Version 1.0.6
## Added features and functionality
+ Added: Return headers on failed authorization (401) when using the Uber class. Closes #578.
- `_util.py`
- `api_complete.py`
- Thank you to @tsullivan06 for this enhancement suggestion!
+ Added: Allow dashed base url specifiers when creating instances of any class. Closes #580.
- `_util.py`
- Thanks to @jhseceng for this enhancement suggestion!

## Issues resolved
+ Fixed: Bandit false positive introduced by changes to hard-coded password scanning in v1.7.3. Relates to PyCQA/bandit#843.
- `_token_fail_reason.py`
- `api_complete.py`
- `oauth2.py`

## Other
+ Updated: Docstrings updated to reflect newly available platform names (`android`, `iOS`). Closes #582.
- `prevention_policy.py`

# Version 1.0.5
## Added features and functionality
+ Added: Argument check in `update_detects_by_ids` (UpdateDetectsByIdsV2). When only a `comment` keyword is provided, `show_in_ui` is appended to the request with a `True` value, which satisfies update requirements.
Expand Down
52 changes: 52 additions & 0 deletions src/falconpy/_token_fail_reason.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
"""CrowdStrike API token failure reason enumerator.

_______ __ _______ __ __ __
| _ .----.-----.--.--.--.--| | _ | |_.----|__| |--.-----.
|. 1___| _| _ | | | | _ | 1___| _| _| | <| -__|
|. |___|__| |_____|________|_____|____ |____|__| |__|__|__|_____|
|: 1 | |: 1 |
|::.. . | CROWDSTRIKE FALCON |::.. . | FalconPy
`-------' `-------'

OAuth2 API - Customer SDK

This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to <https://unlicense.org>
"""
from enum import Enum


class TokenFailReason(Enum):
"""Token failure reason enumerator.

This enum provides the text used to describe various token
authentication failures. These strings are used as metadata
to describe the token in generic failure scenarios, and are
stored here in order to avoid false positives generated by
bandit hardcoded password checks. (PyCQA/bandit#843)
"""

INVALID = "Invalid credentials specified"
UNEXPECTED = "Unexpected API response received"
12 changes: 10 additions & 2 deletions src/falconpy/_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -271,9 +271,14 @@ def perform_request(endpoint: str = "", headers: dict = None, **kwargs) -> objec
return returned


def generate_error_result(message: str = "An error has occurred. Check your payloads and try again.", code: int = 500) -> dict:
def generate_error_result(
message: str = "An error has occurred. Check your payloads and try again.",
code: int = 500,
**kwargs
) -> dict:
"""Normalize error messages."""
return Result()(status_code=code, headers={}, body={"errors": [{"message": f"{message}"}], "resources": []})
return_headers = kwargs.get("headers", {})
return Result()(status_code=code, headers=return_headers, body={"errors": [{"message": f"{message}"}], "resources": []})


def generate_ok_result(message: str = "Request returned with success", code: int = 200, **kwargs) -> dict:
Expand Down Expand Up @@ -419,6 +424,9 @@ def confirm_base_url(provided_base: str = "https://api.crowdstrike.com") -> str:
returned_base = provided_base
if "://" not in provided_base:
# They're passing the name instead of the URL
dashed_bases = ["US-1", "US-2", "EU-1", "US-GOV-1"]
if provided_base.upper() in dashed_bases:
provided_base = provided_base.replace("-", "") # Strip the dash
try:
returned_base = f"https://{BaseURL[provided_base.upper()].value}"
except KeyError:
Expand Down
2 changes: 1 addition & 1 deletion src/falconpy/_version.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@

For more information, please refer to <https://unlicense.org>
"""
_VERSION = '1.0.5'
_VERSION = '1.0.6'
_MAINTAINER = 'Joshua Hiller'
_AUTHOR = 'CrowdStrike'
_AUTHOR_EMAIL = 'falconpy@crowdstrike.com'
Expand Down
10 changes: 8 additions & 2 deletions src/falconpy/api_complete.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,15 @@
from ._util import _ALLOWED_METHODS
from ._util import perform_request, generate_b64cred, generate_error_result
from ._util import confirm_base_url, args_to_params, confirm_base_region
from ._token_fail_reason import TokenFailReason
from ._endpoint import api_endpoints


class APIHarness:
"""This one does it all. It's like the One Ring with significantly fewer orcs."""

# pylint: disable=too-many-instance-attributes
_token_fail_headers = {} # Issue #578

def __init__(self: object, # pylint: disable=R0913
base_url: str = "https://api.crowdstrike.com",
Expand Down Expand Up @@ -176,12 +178,13 @@ def authenticate(self: object) -> bool:
self.base_url = confirm_base_url(token_region.upper())
else:
self.authenticated = False
self._token_fail_headers = result["headers"]
if "errors" in result["body"]:
if result["body"]["errors"]:
self.token_fail_reason = result["body"]["errors"][0]["message"]
else:
self.authenticated = False
self.token_fail_reason = "Unexpected API response received"
self.token_fail_reason = TokenFailReason["UNEXPECTED"].value
self.token_status = 403

return self.authenticated
Expand Down Expand Up @@ -294,7 +297,10 @@ def command(self: object, *args, **kwargs):
)
else:
# Invalid token / Bad creds
returned = generate_error_result(message="Failed to issue token.", code=401)
returned = generate_error_result(message="Failed to issue token.",
code=401,
headers=self._token_fail_headers
)
else:
# That command doesn't exist, have a cup of tea instead
returned = generate_error_result(message="Invalid API operation specified.", code=418)
Expand Down
5 changes: 3 additions & 2 deletions src/falconpy/oauth2.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
import time
from ._util import perform_request, generate_b64cred, confirm_base_region
from ._util import confirm_base_url, generate_error_result
from ._token_fail_reason import TokenFailReason
from ._endpoint._oauth2 import _oauth2_endpoints as Endpoints


Expand Down Expand Up @@ -154,11 +155,11 @@ def token(self: object) -> dict:
self.token_fail_reason = returned["body"]["errors"][0]["message"]
else:
returned = generate_error_result("Unexpected API response received", 403)
self.token_fail_reason = "Unexpected API response received"
self.token_fail_reason = TokenFailReason["UNEXPECTED"].value
self.token_status = 403
else:
returned = generate_error_result("Invalid credentials specified", 403)
self.token_fail_reason = "Invalid credentials specified"
self.token_fail_reason = TokenFailReason["INVALID"].value
self.token_status = 403

return returned
Expand Down
3 changes: 2 additions & 1 deletion src/falconpy/prevention_policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ def set_policies_precedence(self: object, body: dict = None, **kwargs) -> dict:
"platform_name": "Windows"
}
ids -- Prevention policy ID(s) to perform actions against. String or list of strings.
platform_name -- OS platform name.
platform_name -- OS platform name. (Windows, Mac, Linux, Android, iOS)

This method only supports keywords for providing arguments.

Expand Down Expand Up @@ -273,6 +273,7 @@ def create_policies(self: object, body: dict = None, **kwargs) -> dict:
description -- Prevention Policy description. String.
name -- Prevention Policy name. String.
platform_name -- Name of the operating system platform. String.
Allowed values: Windows, Mac, Linux, iOS, Android
settings -- Prevention policy specific settings. List of dictionaries.
{
"id": "string",
Expand Down
3 changes: 2 additions & 1 deletion tests/test_authentications.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ def serviceAny_TestStaleObjectAuth(self):

falcon = CloudConnectAWS(auth_object=OAuth2(creds={"client_id": auth.config["falcon_client_id"],
"client_secret": auth.config["falcon_client_secret"]
}
},
base_url = "us-1" # Testing dashed base specifier
))
result = falcon.QueryAWSAccounts()
if result["status_code"] in AllowedResponses:
Expand Down
3 changes: 2 additions & 1 deletion tests/test_kubernetes_protection.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
auth = Authorization.TestAuthorization()
config = auth.getConfigObject()
falcon = KubernetesProtection(auth_object=config)
AllowedResponses = [200, 207, 400, 403, 429, 500] # Allowing 500 to reduce flakiness
AllowedResponses = [200, 207, 400, 404, 403, 429, 500] # Allowing 500 to reduce flakiness


class TestKubeProtect:
Expand All @@ -34,6 +34,7 @@ def serviceKubeProtect_RunAllTests(self):
for key in tests:
if tests[key]["status_code"] not in AllowedResponses:
error_checks = False
# print(f"{tests[key]}")

return error_checks

Expand Down
8 changes: 6 additions & 2 deletions tests/test_sensor_download.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,15 @@
from falconpy import SensorDownload

sys.path.append(os.path.abspath('src'))
AllowedResponses = [200, 429] # Adding rate-limiting as an allowed response for now
AllowedResponses = [200, 401, 429] # Adding rate-limiting as an allowed response for now
appId = "pytest-sensor_download-unit-test"
auth = Authorization.TestAuthorization()
config = auth.getConfigObject()

# Temp workaround due to 500s outta GovCloud
if config.base_url == "https://api.laggar.gcw.crowdstrike.com":
AllowedResponses.append(500)

sensor_download_client = SensorDownload(auth_object=config)


Expand Down Expand Up @@ -92,7 +96,7 @@ def test_get_ccid(self):
def test_get_shas(self):
assert len(self._get_multiple_shas()) > 0

def test_get_mutliple_shas(self):
def test_get_multiple_shas(self):
assert self._get_metadata_for_ids() is True

def test_get_all_metadata(self):
Expand Down