def serviceAny_TestBadObjectAuth(self):
     # Should also test bad direct auth in the authentication class
     falcon = CloudConnectAWS(auth_object=OAuth2())
     result = falcon.QueryAWSAccounts()
     if result["status_code"] in AllowedResponses:
         return True
     else:
         return False
 def serviceCCAWS_AuthWithObject(self):
     falconWithObject = CloudConnectAWS(auth_object=FalconAuth.OAuth2(creds={
         'client_id': auth.config["falcon_client_id"],
         'client_secret': auth.config["falcon_client_secret"]
     }, base_url=auth.config["falcon_base_url"]))
     check = falconWithObject.auth_object.token()
     if check["status_code"] == 429:
         pytest.skip("Rate limit hit")
     return falconWithObject.authenticated()
    def serviceAny_TestStaleObjectAuth(self):

        falcon = CloudConnectAWS(auth_object=OAuth2(creds={"client_id": auth.config["falcon_client_id"],
                                                           "client_secret": auth.config["falcon_client_secret"]
                                                           }
                                                    ))
        result = falcon.QueryAWSAccounts()
        if result["status_code"] in AllowedResponses:
            return True
        else:
            return False
 def serviceAny_TestObjectAuth(self):
     # Should also test direct auth in the authentication class
     auth_obj = OAuth2(client_id=auth.config["falcon_client_id"],
                       client_secret=auth.config["falcon_client_secret"]
                       )
     auth_obj.token()
     # While we're at it, test user_agent override
     falcon = CloudConnectAWS(auth_object=auth_obj, user_agent=f"{_TITLE}/{str(_VERSION)}")
     result = falcon.QueryAWSAccounts()
     if result["status_code"] in AllowedResponses:
         return True
     else:
         return False
 def serviceAny_forceGovCloudAutoSelectFailure(self):
     falcon = OAuth2(client_id=os.environ["CROSS_DEBUG_KEY"],
                     client_secret=os.environ["CROSS_DEBUG_SECRET"],
                     base_url="usgov1"
                     )
     result = falcon.token()
     if result["status_code"] == 201:
         falcon = APIHarness(client_id=os.environ["CROSS_DEBUG_KEY"],
                             client_secret=os.environ["CROSS_DEBUG_SECRET"],
                             base_url="usgov1"
                             )
         t_creds = {
             "client_id": os.environ["CROSS_DEBUG_KEY"],
             "client_secret": os.environ["CROSS_DEBUG_SECRET"],
         }
         result = falcon.command("oauth2AccessToken", data=t_creds, base_url="usgov1")
         if result["status_code"] == 201:
             falcon = CloudConnectAWS(client_id=os.environ["CROSS_DEBUG_KEY"],
                                      client_secret=os.environ["CROSS_DEBUG_SECRET"],
                                      base_url="usgov1"
                                      )
             result = falcon.auth_object.token()
             if result["status_code"] == 429:
                 pytest.skip("Rate limit hit")
             if result["status_code"] == 201:
                 return True
             else:
                 return False
         else:
             return False
     else:
         return False
Example #6
0
 def timeout_test(self):
     falcon = CloudConnectAWS(creds={
         'client_id':
         auth.config["falcon_client_id"],
         'client_secret':
         auth.config["falcon_client_secret"]
     },
                              base_url=auth.config["falcon_base_url"])
     success = False
     result = falcon.QueryAWSAccounts()
     if result['status_code'] in AllowedResponses:
         success = True
     else:
         if auth.authorization.base_url == "https://api.laggar.gcw.crowdstrike.com":
             pytest.skip("GovCloud rate limit met")
     return success
    def serviceCCAWS_RefreshToken(self):
        falconWithObject = CloudConnectAWS(auth_object=FalconAuth.OAuth2(creds={
            'client_id': auth.config["falcon_client_id"],
            'client_secret': auth.config["falcon_client_secret"]
        }, base_url=auth.config["falcon_base_url"]))
        check = falconWithObject.auth_object.token()
        if check["status_code"] == 429:
            pytest.skip("Rate limit hit")

        if not falconWithObject.token_expired():
            falconWithObject.auth_object.token_expiration = 0  # Forcibly expire the current token
            if falconWithObject.QueryAWSAccounts(parameters={"limit": 1})["status_code"] in AllowedResponses:
                return True
            else:
                return False
        else:
            return False
Example #8
0
    def timeout_standard(self):
        falconStandardFail = CloudConnectAWS(
            creds={
                'client_id': auth.config["falcon_client_id"],
                'client_secret': auth.config["falcon_client_secret"]
            },
            timeout=.001,
            base_url=auth.config["falcon_base_url"])
        success = False
        result = falconStandardFail.QueryAWSAccounts()
        if result["status_code"] == 429:
            pytest.skip("Rate limit hit")
        if result['status_code'] in AllowedResponses:
            if "connect timeout" in result["body"]["errors"][0]["message"]:
                success = True
            else:
                if auth.authorization.base_url == "https://api.laggar.gcw.crowdstrike.com":
                    pytest.skip("GovCloud rate limit met")

        return success
    def serviceCCAWS_InvalidPayloads(self):
        result = True
        falconWithObject = CloudConnectAWS(auth_object=FalconAuth.OAuth2(creds={
            'client_id': auth.config["falcon_client_id"],
            'client_secret': auth.config["falcon_client_secret"]
        }, base_url=auth.config["falcon_base_url"]))
        check = falconWithObject.auth_object.token()
        if check["status_code"] == 429:
            pytest.skip("Rate limit hit")
        
        if not falconWithObject.QueryAWSAccounts(parameters={"limite": 1})["status_code"] in AllowedResponses:
            result = False

        if not falconWithObject.QueryAWSAccounts(parameters={"limit": "1"})["status_code"] in AllowedResponses:
            result = False

        if falconWithObject.UpdateAWSAccounts(body={"resource": "I'm gonna go Boom!"})["status_code"] != 400:
            result = False

        if falconWithObject.UpdateAWSAccounts(body={"resources": {"id": "I'm gonna go Boom!"}})["status_code"] != 400:
            result = False

        return result
Example #10
0
def lambda_handler(event, context):
    try:
        response_data = {}
        logger.info('Event = {}'.format(event))
        FalconClientId = event['ResourceProperties']['FalconClientId']
        FalconSecret = event['ResouceProperties']['FalconSecret']
        falcon = CloudConnectAWS(
            client_id=FalconClientId,
            client_secret=FalconSecret,
            base_url=CrowdStrikeCloud  # Only necessary for GovCloud
        )
        if event['RequestType'] in ['Create']:
            external_id = event['ResourceProperties']['ExternalID']
            api_message = format_notification_message(external_id)
            try:
                delay = float(delay_timer)
            except Exception as e:
                logger.info('cant convert delay_timer type {} error {}'.format(
                    type(delay_timer), e))
                delay = 60

            logger.info(
                'Got ARN of Role Pausing for {} seconds for role setup'.format(
                    delay))
            time.sleep(delay)
            register_result = register_falcon_discover_account(
                api_message, falcon)
            logger.info(
                'Account registration result: {}'.format(register_result))
            if register_result:
                cfnresponse_send(event, context, SUCCESS, register_result,
                                 "CustomResourcePhysicalID")
            else:
                cfnresponse_send(event, context, FAILED, register_result,
                                 "CustomResourcePhysicalID")

        elif event['RequestType'] in ['Update']:
            logger.info('Event = ' + event['RequestType'])
            external_id = event['ResourceProperties']['ExternalID']
            api_message = format_notification_message(external_id)
            register_result = update_falcon_discover_account(
                api_message, falcon)
            logger.info('Account update result: {}'.format(register_result))
            if register_result:
                cfnresponse_send(event, context, SUCCESS,
                                 "CustomResourcePhysicalID")
            else:
                cfnresponse_send(event, context, FAILED,
                                 "CustomResourcePhysicalID")

            logger.info('Event = ' + event['RequestType'])

            cfnresponse_send(event, context, 'SUCCESS',
                             "CustomResourcePhysicalID")

        elif event['RequestType'] in ['Delete']:
            logger.info('Event = ' + event['RequestType'])
            external_id = event['ResourceProperties']['ExternalID']
            api_message = format_notification_message(external_id)
            result = delete_falcon_discover_account(api_message, falcon)
            if result:
                logger.info(
                    'Successfully deleted account in Falcon Discover portal')
            else:
                logger.info(
                    'Failed to delete account in Falcon Discover portal')
            response_data["Status"] = "Success"
            cfnresponse_send(event, context, 'SUCCESS', response_data,
                             "CustomResourcePhysicalID")

    except Exception as e:
        logger.error(e)
        response_data = {}
        response_data["Status"] = str(e)
        cfnresponse_send(event, context, 'FAILED', response_data,
                         "CustomResourcePhysicalID")
import sys
import pytest
# Authentication via the test_authorization.py
from tests import test_authorization as Authorization

# Import our sibling src folder into the path
sys.path.append(os.path.abspath('src'))
# Classes to test - manually imported from sibling folder
from falconpy import CloudConnectAWS
from falconpy import oauth2 as FalconAuth
from falconpy._util import service_request

auth = Authorization.TestAuthorization()

config = auth.getConfigObject()
falcon = CloudConnectAWS(auth_object=config)
AllowedResponses = [200, 201, 404, 429]  # Adding rate-limiting as an allowed response for now
accountPayload = {
        "resources": [
            {
                "rate_limit_reqs": 0,
                "rate_limit_time": 0
            }
        ]
    }
falconWithCreds = None
falconWithObject = None


class TestCloudConnectAWS:
    def serviceCCAWS_AuthWithCreds(self):
Example #12
0
    parser.error(f"The {command} command is not recognized.")
# These globals exist for all requests
falcon_client_id = args.falcon_client_id
falcon_client_secret = args.falcon_client_secret
log_enabled = args.log_enabled
if args.query_limit is None:
    QUERY_LIMIT = 100
else:
    QUERY_LIMIT = args.query_limit

# =============== MAIN ROUTINE
# Authenticate using our provided falcon client_id and client_secret

auth = OAuth2(client_id=falcon_client_id, client_secret=falcon_client_secret)

# Connect using our token and return an instance of the API gateway object
falcon_discover = CloudConnectAWS(auth_object=auth)
try:
    # Execute the requested command
    if command.lower() == "delete":
        delete_account()
    elif command.lower() == "register":
        register_account()
    elif command.lower() == "update":
        update_account()
    else:
        check_account()
except Exception as e:
    # Handle any previously unhandled errors
    print("Command failed with error: {}.".format(str(e)))
    falcon_client_secret = args.falcon_client_secret
    if not args.crowdstrike_cloud:
        CLOUD_URL = "US1"
    else:
        CLOUD_URL = args.crowdstrike_cloud
    log_enabled = args.log_enabled
    if not args.query_limit:
        QUERY_LIMIT = 100
    else:
        QUERY_LIMIT = args.query_limit

    # ############## MAIN ROUTINE
    # Connect to the API using our provided falcon client_id and client_secret
    try:
        falcon = CloudConnectAWS(client_id=falcon_client_id,
                                 client_secret=falcon_client_secret,
                                 base_url=CLOUD_URL)
    except Exception as err:  # noqa: E722  pylint: disable=W0703
        # We can't communicate with the endpoint
        print(f"Unable to communicate with API: {str(err)}")
    # Authenticate
    if falcon.auth_object.token()["status_code"] == 201:
        try:
            # Execute the command by calling the named function
            if command.lower() == "check":
                check_account()
            if command.lower() == "update":
                update_account()
            if command.lower() == "register":
                register_account()
            if command.lower() == "delete":