def getConfigExtended(self):
        if "FALCONPY_DEBUG_TOKEN" in os.environ:
            self.token = os.getenv("FALCONPY_DEBUG_TOKEN")
            self.config = {}
            self.config["falcon_client_id"] = os.environ[
                "FALCONPY_DEBUG_CLIENT_ID"]
            self.config["falcon_client_secret"] = os.environ[
                "FALCONPY_DEBUG_CLIENT_SECRET"]
            if "DEBUG_API_BASE_URL" in os.environ:
                self.config["falcon_base_url"] = os.getenv(
                    "DEBUG_API_BASE_URL")
            else:
                self.config["falcon_base_url"] = "https://api.crowdstrike.com"
        else:
            status = self.getConfig()
            if status:
                os.environ["FALCONPY_DEBUG_CLIENT_ID"] = self.config[
                    "falcon_client_id"]
                os.environ["FALCONPY_DEBUG_CLIENT_SECRET"] = self.config[
                    "falcon_client_secret"]
                self.authorization = OAuth2(
                    creds={
                        "client_id": self.config["falcon_client_id"],
                        "client_secret": self.config["falcon_client_secret"]
                    },
                    base_url=self.config["falcon_base_url"])
            try:
                self.token = self.authorization.token()['body']['access_token']
                os.environ["FALCONPY_DEBUG_TOKEN"] = self.token
            except KeyError:
                self.token = False

        return self.token
Exemple #2
0
def load_api_config():
    """Grab our config parameters from our provided config file (JSON format)."""
    with open(Config.config_file, 'r', encoding="utf-8") as file_config:
        conf = json.loads(file_config.read())

    return OAuth2(client_id=conf["falcon_client_id"],
                  client_secret=conf["falcon_client_secret"])
 def serviceAny_TestBadCredRevoke(self):
     bad_falcon = OAuth2()
     result = bad_falcon.revoke("Will generate a 403")
     if result["status_code"] in AllowedResponses:
         return True
     else:
         return False
    def serviceAuth(self):
        status = self.getConfig()
        if status:
            self.authorization = OAuth2(
                creds={
                    'client_id': self.config["falcon_client_id"],
                    'client_secret': self.config["falcon_client_secret"]
                },
                base_url=self.config["falcon_base_url"])

            try:
                check = self.authorization.token()
                if check["status_code"] == 429:
                    pytest.skip("Rate limit hit")
                self.token = check['body']['access_token']
                # Force a token authentication
                _ = Hosts(access_token=self.token)
            except KeyError:
                self.token = False

            if self.token:
                return True
            else:
                return False
        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
 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 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_checkRegionNameLookups(self):
     falcon = OAuth2(client_id=auth.config["falcon_client_id"],
                     client_secret=auth.config["falcon_client_secret"],
                     base_url="usgov1"
                     )
     result = falcon.token()
     if result["status_code"] == 400:
         return True
     elif result["status_code"] == 429:
         pytest.skip("Rate limit hit")
     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 serviceMSSPAuth(self):
        status = self.getConfig()
        result = False
        if status:
            authorization = OAuth2(
                client_id=self.config["falcon_client_id"],
                client_secret=self.config["falcon_client_secret"],
                member_cid='1234567890ABCDEFG')
            try:
                req = authorization.token()
                if req["status_code"] in [
                        201, 403
                ]:  # Prolly an invalid MSSP cred, 403 is correct
                    result = True
            except KeyError:
                pass

        return result
def get_install_params(events, context):
    """Retrieve necessary installation detail from CrowdStrike cloud."""
    api_base_url, api_client_id, api_client_secret = get_ssm_params(events)

    try:
        auth = OAuth2(client_id=api_client_id,
                      client_secret=api_client_secret,
                      base_url=api_base_url
                      )
    except Exception as err:
        raise ValueError(f"Failure while interacting with CrowdStrike backend. Error: {err}") from err

    try:
        print('Requesting Customer ID from CrowdStrike backend.')
        sensor = SensorDownload(auth_object=auth)
        get_ccid = sensor.get_sensor_installer_ccid()
        if get_ccid["status_code"] != 200:
            error_detail = get_ccid['body']['errors'][0]
            code = error_detail["code"]
            msg = error_detail["message"]
            raise ValueError(f"Received non success response {code}. Error: {msg}")
        customer_ccid = get_ccid['body']['resources'][0]
        print('Successfully received Customer ID.')
    except Exception as err:
        raise ValueError(f"Failure while interacting with CrowdStrike backend. Error {err}") from err

    try:
        hosts = Hosts(auth_object=auth)

        id_to_retrieve = events["InstanceIds"][0]
        host_aid = hosts.query_devices_by_filter(filter=f"instance_id:'{id_to_retrieve}'")

        skip_install = "NO"
        if host_aid["status_code"] == 200:
            if host_aid["body"]["resources"]:
                skip_install = "YES"
        print('Checked for a skipped install')

        return {
            'CCID': customer_ccid,
            'SkipInstall': skip_install
            }
    except Exception as err:
        raise ValueError(f"Failure while interacting with CrowdStrike backend. Error {err}") from err
Exemple #12
0
    def timeout_legacy_auth(self):
        falconLegacyFail = OAuth2(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 = falconLegacyFail.token()
        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 serviceAny_forceCrossCloudResponseFailure(self):
     falcon = OAuth2(client_id=os.environ["CROSS_DEBUG_KEY"],
                     client_secret="will_not_work",
                     base_url="us1"
                     )
     result = falcon.token()
     if result["status_code"] == 403:
         falcon = APIHarness(client_id=os.environ["CROSS_DEBUG_KEY"],
                             client_secret="will_not_work",
                             base_url="us1"
                             )
         t_creds = {
             "client_id": os.environ["CROSS_DEBUG_KEY"],
             "client_secret": "shouldn't work",
         }
         result = falcon.command("oauth2AccessToken", data=t_creds, base_url="us1")
         if result["status_code"] in [401, 403]:
             return True
         else:
             return False
     else:
         return False
    def getConfigObject(self):
        status = self.getConfig()
        if status:
            os.environ["FALCONPY_DEBUG_CLIENT_ID"] = self.config[
                "falcon_client_id"]
            os.environ["FALCONPY_DEBUG_CLIENT_SECRET"] = self.config[
                "falcon_client_secret"]
            self.authorization = OAuth2(
                creds={
                    "client_id": self.config["falcon_client_id"],
                    "client_secret": self.config["falcon_client_secret"]
                },
                base_url=self.config["falcon_base_url"])
        try:
            global shared_token
            if not shared_token:
                shared_token = self.authorization.token(
                )['body']['access_token']
        except KeyError:
            shared_token = False

        return self.authorization
Exemple #15
0
        WithDecryption=True)
    client_id = ssm_response['Parameters'][0]['Value']
    client_secret = ssm_response['Parameters'][1]['Value']

except IndexError as no_creds:
    raise SystemExit(
        "Unable to retrieve CrowdStrike Falcon API credentials.") from no_creds

except KeyError as bad_creds:
    raise SystemExit("Unable to retrieve CrowdStrike Falcon API credentials."
                     ) from bad_creds

# Authenticate to the CrowdStrike Falcon API
auth = OAuth2(creds={
    "client_id": client_id,
    "client_secret": client_secret
},
              base_url=BASE_URL)

# Connect to the Samples Sandbox API
Samples = SampleUploads(auth_object=auth)
# Connect to the Quick Scan API
Scanner = QuickScan(auth_object=auth)


# Main routine
def lambda_handler(event, _):  # pylint: disable=R0912,R0914,R0915
    """Lambda execution entry point."""
    bucket_name = event['Records'][0]['s3']['bucket']['name']
    bucket = s3.Bucket(bucket_name)
    key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'],
Exemple #16
0
            local_account = args.local_account
else:
    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
Exemple #17
0
def load_api_config():
    """Return an instance of the authentication class using our provided credentials."""
    return OAuth2(client_id=Config.falcon_client_id,
                  client_secret=Config.falcon_client_secret)
Exemple #18
0
HOSTNAME = "HOSTNAME_HERE"

mssp = FlightControl(client_id=args.client_id,
                     client_secret=args.client_secret,
                     base_url=BASE)

children = mssp.query_children()
if children["status_code"] == 200:
    if children["body"]["resources"]:
        CIDS = children["body"]["resources"]
        AUTH = []
        for cid in CIDS:
            AUTH.append(
                OAuth2(client_id=args.client_id,
                       client_secret=args.client_secret,
                       base_url=BASE,
                       member_cid=cid))
        for auth in AUTH:
            hosts = Hosts(auth_object=auth)
            lookup = hosts.query_devices_by_filter(
                filter=f"hostname:'{HOSTNAME}'")
            if lookup["body"]["resources"]:
                for host in lookup["body"]["resources"]:
                    detail = hosts.get_device_details(ids=host)
                    host_cid = detail["body"]["resources"][0]["cid"]
                    print(f"Host identified on CID: {host_cid}")
    else:
        print("No children identified.")
else:
    print("No children identified, check permissions.")
if args.sort:
    sort_types = [
        "cve", "score", "severity", "cve_description", "created_on",
        "updated_on", "hostname", "local_ip", "os_version", "service_provider",
        "remediation"
    ]
    sort_type = args.sort.strip().lower()
    if sort_type in sort_types:
        SORT = sort_type

SORT_REVERSE = args.reverse
PROGRESS = args.show_progress

# Connect to the API and create instances of the SpotlightVulnerabilities and Hosts Service Classes
auth = OAuth2(client_id=args.client_id,
              client_secret=args.client_secret,
              base_url=BASE)
spotlight = SpotlightVulnerabilities(auth_object=auth)
hosts = Hosts(auth_object=auth)

# Headers used for our results display
HEADERS = {
    "cve": "CVE",
    "score": "Score",
    "severity": "Severity",
    "cve_description": "Description",
    "created_on": "Created",
    "updated_on": "Updated",
    "hostname": "Host",
    "local_ip": "IP Address",
    "os_version": "Operating System",
        # User submitted name matches an accepted type
        if env.name == SANDBOX_ENV:
            MATCHED = True
    if not MATCHED:
        # We only accept the environments defined in our Enum above
        raise SystemExit("Invalid sandbox environment specified.")

if not os.path.isfile(args.file):
    # We were not provided a valid filename
    raise SystemExit("Invalid filename specified.")

# Announce progress
inform(f"[   Init   ] {running_time(start_time)}")
# Create an instance of our authentication object
# and provide our API credentials for authorization
auth = OAuth2(client_id=args.key, client_secret=args.secret)
# Connect to Sample Uploads
samples = SampleUploads(auth_object=auth)
# Connect to Falcon X Sandbox
sandbox = FalconXSandbox(auth_object=auth)

# Announce progress
inform(f"[  Upload  ] {running_time(start_time)}")

# Upload our test file
response = upload_file(args.file,
                       f"FalconX File Analysis: {time.strftime('%V %r %Z')}",
                       "Falcon X upload and scan example",
                       confidential=False)

# Retrieve the SHA of our upload file
 def test_fail_base_url_lookup(self):
     _ = self.getConfig()
     test_falcon = OAuth2(client_id=self.config["falcon_client_id"],
                          client_secret=self.config["falcon_client_secret"],
                          base_url="nowhere")
     assert bool(test_falcon.token()["status_code"] != 201)
Exemple #22
0
parser.add_argument(  # CrowdStrike API Client ID
    '-k',
    '--key',
    help='Your CrowdStrike API key ID\n'
    '     Required Scopes\n'
    '     Hosts:     READ\n'
    '     RTR:       WRITE\n'
    '     RTR Admin: WRITE',
    required=True)
parser.add_argument(  # CrowdStrike API Client secret
    '-s',
    '--secret',
    help='Your CrowdStrike API key secret',
    required=True)
args = parser.parse_args()  # Retrieve our provided command line arguments
hostname = args.target  # Grab the hostname of our target from the user
falcon_auth = OAuth2(  # Create an instance of our authentication class
    client_id=args.key,  # and authenticate to the API
    client_secret=args.secret,
)
falcon_hosts = Hosts(
    auth_object=falcon_auth)  # Connect to the Hosts API using our auth object
falcon_rtr = RealTimeResponse(
    auth_object=falcon_auth)  # Connect to the RTR API using our auth object
falcon_rtra = RealTimeResponseAdmin(
    auth_object=falcon_auth
)  # Connect to the RTR Admin API using our auth object

if __name__ == "__main__":
    main()