Esempio n. 1
0
class PolicyGen(object):
    def __init__(self, rest_session):

        self.test_aws_flow_connection = 'appconfig/testawss3connection'
        self.post_aws_flow_log = 'appconfig/flowlogsstorageconfig'
        self.get_all_cloud_listing = 'infras'
        self.app_instance = 'applications/instances'
        self.sequence_apps = 'applications/sequence'
        self.logger = CustomLogger().get_logger()
        # REST Session
        self.rest_session = rest_session

        # Common REST Calls
        self.rest_call = RestCall(rest_session)
        self.acl_caller = AccessControl(rest_session)

        self.new_acl_count = "applications/statistics"
        self.forward_test = "applications/forwardtest"
        self.get_forward_time = "applications/forwardtest/starttime"
        self.implement_all_CS = "applications/services/implement"
        self.purge_data = "appconfig/purgedata"
        self.implement_all = "applications/instances/implement"
        self.summary_apps = "applications/summarydetails"
        self.delete_apps = "applications/instances"
        self.filter_config = 'appconfig/filterconfig'
        self.get_networks = 'infras/networkset'
        self.deny_policy = 'applications/lasthitaclrule'
        self.last_hit_rule = 'applications/lasthitaclrule'
        self.get_violations_api = 'policy/accesscontrolpolicy/rulehits/'
        self.create_acl_rule = 'policy/accesscontrolpolicy/rule'
        self.proposed_acl = 'applications/aclrules/propose'
        self.acl_policy = 'policy/accesscontrolpolicy'
        self.resource_group = 'applications/resourcegroups'

    def get_acl_connections(self):
        url = self.rest_session.base_url + self.new_acl_count
        headers = self.rest_session.headers
        response = self.rest_call.get_query(url=url,
                                            headers=headers,
                                            verify=False)
        resp = json.loads(response.content)
        return resp

    def start_forward_testing(self):
        url = self.rest_session.base_url + self.forward_test
        headers = self.rest_session.headers
        response = self.rest_call.put_query(url=url,
                                            headers=headers,
                                            verify=False)
        ts = datetime.now()
        time_started = datetime.timestamp(ts)
        status = response.status_code
        return status, time_started

    def get_forward_testing_time(self):
        url = self.rest_session.base_url + self.get_forward_time
        headers = self.rest_session.headers
        response = self.rest_call.get_query(url=url,
                                            headers=headers,
                                            verify=False)
        timestamp = json.loads(response.content)
        forward_testing_time = datetime.fromtimestamp(timestamp /
                                                      1000).strftime('%c')
        return forward_testing_time, timestamp

    def implement_all_commonservices(self):
        url = self.rest_session.base_url + self.implement_all_CS
        headers = self.rest_session.headers
        response = self.rest_call.post_query(url=url,
                                             headers=headers,
                                             verify=False)
        status = response.status_code
        if status == requests.codes.ok:
            return status
        else:
            return response.content

    def purge_data_gm(self):
        url = self.rest_session.base_url + self.purge_data
        headers = self.rest_session.headers
        response = self.rest_call.put_query(url=url,
                                            headers=headers,
                                            verify=False)
        status = response.status_code
        if status == requests.codes.ok:
            return status

    def app_summary(self):
        url = self.rest_session.base_url + self.summary_apps
        headers = self.rest_session.headers
        response = self.rest_call.get_query(url=url,
                                            headers=headers,
                                            verify=False)
        status = response.status_code
        if status == requests.codes.ok:
            content2 = json.loads(response.content)
            apps_summary = content2["All Applications"]
            return apps_summary, content2

    def implement_all_apps(self):
        url = self.rest_session.base_url + self.implement_all
        headers = self.rest_session.headers
        data, content = self.app_summary()
        final_data = content["All Applications"]
        print(final_data)
        data = json.dumps(final_data)
        response = self.rest_call.post_query(url=url,
                                             headers=headers,
                                             data=data,
                                             timeout=400,
                                             verify=False)
        status = response.status_code
        if status == requests.codes.ok:
            return status
        else:
            return response.content

    def get_total_acl_proposed(self):
        url = self.rest_session.base_url + self.proposed_acl
        headers = self.rest_session.headers
        response = self.rest_call.get_query(url=url,
                                            headers=headers,
                                            timeout=100,
                                            verify=False)
        status = response.status_code
        if status == requests.codes.ok:
            content2 = response.content
            acl_rules = json.loads(content2)
            rule_num = len(acl_rules)
            return status, rule_num

        else:
            return status, response.content

    def get_acl_rules_policy(self):
        url = self.rest_session.base_url + self.acl_policy
        headers = self.rest_session.headers
        response = self.rest_call.get_query(url=url,
                                            headers=headers,
                                            timeout=10,
                                            verify=False)
        status = response.status_code
        if status == requests.codes.ok:
            content = response.content
            content2 = json.loads(content)
            for i in content2:
                if i["name"] == "Default ACL Policy":
                    rule2 = len(i["aclRules"])
                    return status, rule2
        else:
            return status, response.content

    def delete_all(self):
        url = self.rest_session.base_url + self.delete_apps
        headers = self.rest_session.headers
        response = self.rest_call.delete_query(url=url,
                                               headers=headers,
                                               timeout=400,
                                               verify=False)
        status = response.status_code
        if status == requests.codes.ok:
            return status
        else:
            return response.content

    def get_filter_config(self):
        url = self.rest_session.base_url + self.filter_config
        headers = self.rest_session.headers
        response = self.rest_call.get_query(url=url,
                                            headers=headers,
                                            verify=False)
        payload = response.content
        status = response.status_code
        if status == requests.codes.ok:
            return status, payload
        else:
            return response.content

    def get_network_sets(self):
        networksetListing = []
        url = self.rest_session.base_url + self.get_networks
        headers = self.rest_session.headers
        response = self.rest_call.get_query(url=url,
                                            headers=headers,
                                            verify=False)
        status = response.status_code
        if status == requests.codes.ok:
            payload = json.loads(response.content)
            for i in payload:
                networksetListing.append(i["id"])
            return status, networksetListing
        else:
            return response.content

    def set_filter_config(self):
        status, payload = self.get_filter_config()
        status, networksets = self.get_network_sets()

        if status == requests.codes.ok:
            resp = json.loads(payload)
            print(resp.keys())
            if "configMap" in resp.keys():
                for i in networksets:
                    nscreation = {"enabled": True, "networkSetId": i}
                    resp["configMap"]["1"]["networkSetFilter"].append(
                        nscreation)
                    resp["configMap"]["1"]["enabled"] = True

            if "advancedConfig" in resp.keys():
                resp["advancedConfig"]["processingCycleTime"] = 15

            data = json.dumps(resp, indent=4)
            url = self.rest_session.base_url + self.filter_config
            headers = self.rest_session.headers
            response = self.rest_call.post_query(url=url,
                                                 headers=headers,
                                                 data=data,
                                                 verify=False)
            if status == requests.codes.ok:
                return status
            else:
                return response.content

    def set_deny_policy(self):
        url = self.rest_session.base_url + self.deny_policy
        headers = self.rest_session.headers
        parameters = {"action": "DENY"}
        response = self.rest_call.put_query(url=url,
                                            headers=headers,
                                            params=parameters,
                                            verify=False)
        status = response.status_code
        return status

    def set_permit_policy(self):
        url = self.rest_session.base_url + self.deny_policy
        headers = self.rest_session.headers
        parameters = {"action": "PERMIT"}
        response = self.rest_call.put_query(url=url,
                                            headers=headers,
                                            params=parameters,
                                            verify=False)
        status = response.status_code
        return status

    def get_sequence_application_instance(self):
        url = self.rest_session.base_url + self.sequence_apps
        headers = self.rest_session.headers
        response = self.rest_call.get_query(url=url,
                                            headers=headers,
                                            verify=False)
        status = response.status_code
        if status == requests.codes.ok:
            payload = json.loads(response.content)
            return payload, status

    def get_individual_application_instance(self, appId):
        url = self.rest_session.base_url + self.app_instance + "/" + str(appId)
        headers = self.rest_session.headers
        response = self.rest_call.get_query(url=url,
                                            headers=headers,
                                            verify=False)
        status = response.status_code
        if status == requests.codes.ok:
            payload = json.loads(response.content)
            return payload, status
        else:
            return response.content

    # Function is retriving the sequence IDs and then implementing them
    def implement_individual_applications(self):
        apps_done = []
        headers = self.rest_session.headers
        sequence, status = self.get_sequence_application_instance()
        if status == requests.codes.ok:
            sequence2 = sequence
            print(sequence2)
            if not sequence2:
                return False, "No Apps to implement"
        else:
            return False, "Unable to get sequence"
        for i in sequence2:
            app, status = self.get_individual_application_instance(i)
            url = self.rest_session.base_url + self.app_instance + "/" + str(
                i) + "/" + "implement"
            data2 = app
            data2["status"] = "VERIFIED"
            # Testing notifs
            data = json.dumps(data2, indent=4)
            print(data)
            response = self.rest_call.post_query(url=url,
                                                 headers=headers,
                                                 data=data,
                                                 verify=False)
            status = response.status_code
            if status == requests.codes.ok:
                print(response.content)
                print("Application ID that is implemented: %d", i)
                apps_done.append(i)
            else:
                print(response.content)
                print(response.status_code)
                print("Application that failed to be implemented is %d", i)
                if apps_done:
                    print("Applications that are implemented are %s" %
                          apps_done)
                return response.status_code
        acl_proposed = self.get_total_acl_proposed()
        acl_policy = self.get_acl_rules_policy()
        if acl_policy == acl_proposed:
            return status, "Applications are implemented %s" % apps_done
        else:
            return status, "ACL numbers are not matching check back again"

    def get_last_hit_acl_rule(self):
        url = self.rest_session.base_url + self.last_hit_rule
        headers = self.rest_session.headers
        response = self.rest_call.get_query(url=url,
                                            headers=headers,
                                            verify=False)
        lasthitrule = json.loads(response.content)
        return lasthitrule

    def get_violations(self):
        starttime_human, timestamp = self.get_forward_testing_time()
        ruleid = self.get_last_hit_acl_rule()
        url = self.rest_session.base_url + self.get_violations_api + "/" + str(
            ruleid) + "/" + str(timestamp)
        headers = self.rest_session.headers
        response = self.rest_call.get_query(url=url,
                                            headers=headers,
                                            verify=False)
        violations = json.loads(response.content)
        if response.status_code == requests.codes.ok:
            return response.status_code, violations
        else:
            return response.status_code, response.content

    def add_all_violations_aclPolicy(self):
        status_code, all_violations = self.get_violations()
        if status_code == requests.codes.ok:
            print(all_violations)
            for i in all_violations:
                rig = {}
                if i['srcRG'] == 0:
                    i["srcRGName"] = 'ANY'
                if i['destRG'] == 0:
                    i["destRGName"] = 'ANY'
                # rule = self.acl_caller.get_aclrule_ruleid(str(i["ruleId"]))
                # rule = json.loads(rule)
                rig["action"] = "PERMIT"

                rig["name"] = str(i["srcRGName"]) + str(i["destRGName"]) + str(
                    i["protocolName"]) + str(i["destPort"])
                rig["destinationResourceGroupList"] = [str(i["destRG"])]
                rig["sourceResourceGroupList"] = [str(i["srcRG"])]
                rig["destinationPortRanges"] = i["destPort"]
                rig["destinationProtocol"] = i["protocolName"]
                rig["enabled"] = True
                rig["orderNum"] = 1
                data = [rig]
                data = json.dumps(data, indent=4)
                params = {"aclPolicyId": i["aclPolicyId"]}
                print(data)
                url = self.rest_session.base_url + self.create_acl_rule
                headers = self.rest_session.headers
                response = self.rest_call.put_query(url=url,
                                                    headers=headers,
                                                    data=data,
                                                    verify=False,
                                                    params=params)
                print(response.status_code)
                print(response.content)
                # if response.status_code == requests.codes.ok:
                #   print(response.status_code)
                # else:
                #    print(response.status_code, response.content)
        return response.status_code

    def get_cloud_id(self):
        url = self.rest_session.base_url + self.get_all_cloud_listing
        headers = self.rest_session.headers
        response = self.rest_call.get_query(url=url,
                                            headers=headers,
                                            verify=False)
        clouds = json.loads(response.content)
        return clouds

    def set_flow_logs(self, prereq):
        with open(prereq) as f:
            prereq = yaml.safe_load(f)

        if 'AWS' in prereq.keys():
            for i in prereq["AWS"]:
                cloudname = i["InfraName"]
                listing = self.get_cloud_id()
                for clouds in listing:
                    if clouds["name"] == cloudname:
                        cloudid = clouds["id"]
                        flow_aws = {
                            "accessKey": i["AccessKey"],
                            "region": i["Region"],
                            "s3BucketName": i["s3BucketName"],
                            "secretKey": i["SecretKey"]
                        }
                        payload = {
                            "aws": flow_aws,
                            "eventsFileEnabled": True,
                            "infraId": cloudid,
                            "startTime": int(time.time())
                        }
                        data = json.dumps(payload)
                        url = self.rest_session.base_url + self.post_aws_flow_log
                        headers = self.rest_session.headers
                        response = self.rest_call.post_query(url=url,
                                                             headers=headers,
                                                             data=data,
                                                             timeout=400,
                                                             verify=False)
                        status = response.status_code
                        if status == requests.codes.ok:
                            url = self.rest_session.base_url + self.test_aws_flow_connection
                            response = self.rest_call.post_query(
                                url=url,
                                headers=headers,
                                data=flow_aws,
                                timeout=400,
                                verify=False)
                            status = response.status_code
                            if status == requests.codes.ok:
                                return status
                            else:
                                return response.content
                        else:

                            return response.content

    def applications_resource_group(self):
        url = self.rest_session.base_url + self.resource_group
        headers = self.rest_session.headers
        response = self.rest_call.get_query(url=url,
                                            headers=headers,
                                            timeout=10,
                                            verify=False)
        status = response.status_code
        if status == requests.codes.ok:
            resource_groups = response.content
            return status, resource_groups
        else:
            return status, response.content

    def get_application_vuln(self):
        headers = self.rest_session.headers
        sequence2 = []
        summary, detailed_summary = self.app_summary()
        detailed_summary2 = detailed_summary["All Applications"]
        for i in detailed_summary2:
            sequence2.append(i["id"])
        for i in sequence2:
            url = self.rest_session.base_url + "applications/instance/" + str(
                i) + "/vulndetails"
            response = self.rest_call.get_query(url=url,
                                                headers=headers,
                                                timeout=10,
                                                verify=False)
            status = response.status_code
            if status == requests.codes.ok:
                content2 = response.content
                content = json.loads(content2)
                if content:
                    counter_critical = 0
                    counter_high = 0
                    vuln_seen_critical = []
                    vuln_seen_high = []
                    for tt in content:
                        if tt["severity"] == "Critical":
                            counter_critical += 1
                            print(tt["name"])
                            vuln_seen_critical.append(tt["name"])
                        if tt["severity"] == "High":
                            counter_high += 1
                            print(tt["name"])
                            vuln_seen_high.append(tt["name"])
                    for jk in detailed_summary2:
                        if jk["id"] == i:
                            if "Critical" in jk[
                                    "vulnerabilitySeverityMap"].keys():
                                if jk["vulnerabilitySeverityMap"][
                                        "Critical"] == counter_critical:
                                    print("Critical number checked against GM")
                                    print("%s critical vuln found " %
                                          counter_critical)
                                else:
                                    return False, "Critical number of apps not matching on application - %s" % jk[
                                        "applicationName"]
                            if "High" in jk["vulnerabilitySeverityMap"].keys():
                                if jk["vulnerabilitySeverityMap"][
                                        "High"] == counter_high:
                                    print("Critical number checked against GM")
                                    print("%s high vuln found " % counter_high)
                                else:
                                    return False, "Critical number of apps not matching on application - %s" % jk[
                                        "applicationName"]
                else:
                    print("App has no known vulnerabilities")
            else:
                return status, response.content

        return status, "All Apps vuln checked"
Esempio n. 2
0
class SystemManagement(object):
    def __init__(self, rest_session):
        # singleton logger
        self.logger = CustomLogger().get_logger()

        # REST Session
        self.rest_session = rest_session

        # Common REST Calls
        self.rest_call = RestCall(rest_session)

        # URL specific to this Module
        self.license_url = "manage/license"
        self.activate_license_url = "manage/license/activate"
        self.system_info_url = "manage/systeminfo"
        self.staged_software_url = "manage/software/stagedversion"
        self.deployed_software_url = "manage/software/deployed"
        self.latest_software_url = "manage/software/latest"
        self.update_content_url = "manage/updatecontent"
        self.update_software_url = "manage/software/update"
        self.update_hotfix_url = "manage/software/update/hotfix"
        self.file_based_update_content_url = "manage/filebasedupdatecontent"
        self.users_url = "manage/users"

        # URL separator
        self.sep_url = "/"

    def get_system_info(self):
        # System Info
        system_info = {}

        # This is a special variable, license,  showing the license used for this library
        # self.logger.info("Test Infra License: {}".format(license))

        # Craft the URL
        url = self.rest_session.base_url + self.system_info_url

        # Headers
        headers = self.rest_session.headers

        # Call REST - GET
        response = self.rest_call.get_query(url=url,
                                            verify=False,
                                            headers=headers)

        # Convert response to expected data
        system_info = dict(response.json())

        return system_info

    def set_license(self, license=None):
        # Action
        is_license_set = False

        # No license to activate
        if license == None:
            # No-op, just get out
            return is_license_set
        else:
            # Proceed in activating license
            pass

        # Craft the URL
        url = self.rest_session.base_url + self.activate_license_url

        # Headers
        headers = self.rest_session.headers

        # Call REST - POST
        response = self.rest_call.post_query(url=url,
                                             verify=False,
                                             headers=headers,
                                             data=license)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            is_license_set = True
        else:
            is_license_set = False

        return is_license_set

    def get_license(self, license=None):
        # License Info
        license_info = {}

        # Craft the URL
        if license == None:
            # Get whatever license is currently applied
            url = self.rest_session.base_url + self.license_url + self.sep_url + "dummy"
        else:
            # Get the specific license applied
            url = self.rest_session.base_url + self.license_url + self.sep_url + license

        # Headers
        headers = self.rest_session.headers

        # Call REST - GET
        response = self.rest_call.get_query(url=url,
                                            verify=False,
                                            headers=headers)

        # Convert response to expected data
        license_info = dict(response.json())

        self.logger.info("License: {}".format(license_info))

        return license_info

    def create_user(self, user_info):
        is_user_created = False

        # Craft the URL
        url = self.rest_session.base_url + self.users_url

        # Headers
        headers = self.rest_session.headers

        # Craft the payload
        data = json.dumps(user_info)

        # Call REST - POST
        response = self.rest_call.post_query(url=url,
                                             headers=headers,
                                             verify=False,
                                             data=data)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            is_user_created = True
        else:
            is_user_created = False

        return is_user_created

    def update_user(self, user_info):
        is_user_updated = False

        # Craft the URL
        url = self.rest_session.base_url + self.users_url

        # Headers
        headers = self.rest_session.headers

        # Craft the payload
        data = json.dumps(user_info)

        # Call REST - PUT
        response = self.rest_call.put_query(url=url,
                                            headers=headers,
                                            verify=False,
                                            data=data)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            is_user_updated = True
        else:
            is_user_updated = False

        return is_user_updated

    def get_user(self, user_login):
        # Info for specific user
        user_info = {}

        # Craft the URL
        url = self.rest_session.base_url + self.users_url + self.sep_url + user_login

        # Headers
        headers = self.rest_session.headers

        # Call REST - GET
        response = self.rest_call.get_query(url=url,
                                            verify=False,
                                            headers=headers)

        # Convert response to expected data
        user_info = dict(response.json())

        return user_info

    def get_users(self):
        # List of users
        users = {}

        # Craft the URL
        url = self.rest_session.base_url + self.users_url

        # Headers
        headers = self.rest_session.headers

        # Call REST - GET
        response = self.rest_call.get_query(url=url,
                                            verify=False,
                                            headers=headers)

        # Convert response to expected data
        users = list(response.json())

        return users

    def delete_user(self, user_login):
        # Action
        is_user_deleted = False

        # Craft the URL
        url = self.rest_session.base_url + self.users_url + self.sep_url + user_login

        # Headers
        headers = self.rest_session.headers

        # Call REST - DELETE
        response = self.rest_call.delete_query(url=url,
                                               verify=False,
                                               headers=headers)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            is_user_deleted = True
        else:
            is_user_deleted = False

        return is_user_deleted

    def update_content(self):
        # Action
        is_content_update_initiated = False

        # Craft the URL
        url = self.rest_session.base_url + self.update_content_url

        # Headers
        headers = self.rest_session.headers

        # Call REST - GET
        response = self.rest_call.get_query(url=url,
                                            verify=False,
                                            headers=headers)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            is_content_update_initiated = True
        else:
            is_content_update_initiated = False

        return is_content_update_initiated

    def file_based_update_content(self, filename):
        # Action
        is_content_update_initiated = False

        try:
            # Craft the URL
            url = self.rest_session.base_url + self.file_based_update_content_url

            # File to import
            files = {
                "file": (filename, open(filename,
                                        "rb"), "application/x-compressed")
            }

            # Customize header, remove "content-type".
            headers = dict(**self.rest_session.headers)
            headers.pop("content-type")

            # Call REST - POST
            response = self.rest_call.post_query(url=url,
                                                 files=files,
                                                 verify=False,
                                                 headers=headers)

            # Convert response to expected data
            if response.status_code == requests.codes.ok:
                is_content_update_initiated = True
            else:
                pass

        except Exception as e:
            self.logger.error(e)

        return is_content_update_initiated

    def update_hotfix(self, microservice, swversion, hotfix):
        # Action
        is_update_initiated = False

        try:
            # Craft the URL
            url = self.rest_session.base_url + self.update_hotfix_url

            # Payload
            data = {
                "microservice": microservice,
                "swversion": swversion,
                "hotfixbuild": hotfix
            }

            # Headers
            headers = self.rest_session.headers

            # Call REST - POST
            response = self.rest_call.post_query(url=url,
                                                 data=data,
                                                 verify=False,
                                                 headers=headers)

            # Convert response to expected data
            if response.status_code == requests.codes.ok:
                is_update_initiated = True
            else:
                pass

        except Exception as e:
            self.logger.error(e)

        return is_update_initiated

    def get_staged_version(self):
        # Staged Version
        staged_version = []

        # Craft the URL
        url = self.rest_session.base_url + self.staged_software_url

        # Headers
        headers = self.rest_session.headers

        # Call REST - GET
        response = self.rest_call.get_query(url=url,
                                            verify=False,
                                            headers=headers)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            staged_version = list(response.json())
        else:
            pass

        return staged_version

    def get_latest_version(self):
        # Latest Version
        latest_version = []

        # Craft the URL
        url = self.rest_session.base_url + self.latest_software_url

        # Headers
        headers = self.rest_session.headers

        # Call REST - GET
        response = self.rest_call.get_query(url=url,
                                            verify=False,
                                            headers=headers)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            latest_version = list(response.json())
        else:
            pass

        return latest_version

    def apply_staged_software(self):
        # Staged Version
        is_update_initiated = False

        # Craft the URL
        url = self.rest_session.base_url + self.update_software_url

        # Headers
        headers = self.rest_session.headers

        # Call REST - GET
        response = self.rest_call.get_query(url=url,
                                            verify=False,
                                            headers=headers)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            is_update_initiated = True
        else:
            pass

        return is_update_initiated
Esempio n. 3
0
class ThreatPrevention(object):
    def __init__(self, rest_session):
        # singleton logger
        self.logger = CustomLogger().get_logger()

        # REST Session
        self.rest_session = rest_session

        # Common REST Calls
        self.rest_call = RestCall(rest_session)

        # URLs - ACL
        self.access_control_policy_url = "policy/accesscontrolpolicy"

        # URLs - Threat Prevention Policy (TPP)
        self.content_attribute_url = "policy/threatpreventionpolicy/contentattr"
        self.protection_type_url = "policy/threatpreventionpolicy/protectiontype"
        self.tpp_url = "policy/threatpreventionpolicy"
        self.tpp_by_id_url = "policy/threatpreventionpolicy/{policy_id}"
        self.threats_by_policy_id_url = "policy/{policy_id}/threats"
        self.threat_responses_by_policy_id_url = "policy/{policy_id}/threatresponses"
        self.apps_by_policy_id_url = "policy/{policy_id}/apps"
        self.clone_tpp_responses_url = "policy/{from_policy_id}/{to_policy_id}/clonethreatresponses"
        self.bulk_update_response_url = "policy/threatresponses"

        # URLs - Threat Encyclopedia
        self.threat_encyclopedia_url = "policy/threatencyclopedia"
        self.threat_severity_url = "policy/severity"

        # URLs - URL Filtering Policy
        self.url_filtering_policy_url = "policy/urlfilteringpolicy"

        # URL separator
        self.sep_url = "/"

    def get_access_control_policy(self):
        # Access Control Policy List
        access_control_policy_list = None

        # Craft the URL
        url = self.rest_session.base_url + self.access_control_policy_url

        # Headers
        headers = self.rest_session.headers

        # Get Access Control Policy List - GET
        response = self.rest_call.get_query(url=url,
                                            headers=headers,
                                            verify=False)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            access_control_policy_list = list(response.json())
        else:
            # Empty list
            pass

        return access_control_policy_list

    def get_content_attributes(self):
        # Content Attribute
        content_attributes = None

        # Craft the URL
        url = self.rest_session.base_url + self.content_attribute_url

        # Headers
        headers = self.rest_session.headers

        # Get Content Attribute - GET
        response = self.rest_call.get_query(url=url,
                                            headers=headers,
                                            verify=False)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            content_attributes = list(response.json())
        else:
            # Empty list
            pass

        return content_attributes

    def get_threat_severities(self):
        # Threat Severities
        threat_severities = None

        # Craft the URL
        url = self.rest_session.base_url + self.threat_severity_url

        # Headers
        headers = self.rest_session.headers

        # Get Threat Severities - GET
        response = self.rest_call.get_query(url=url,
                                            headers=headers,
                                            verify=False)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            threat_severities = list(response.json())
        else:
            # Empty list
            pass

        return threat_severities

    def get_protection_types(self):
        # Protection Types
        protection_types = None

        # Craft the URL
        url = self.rest_session.base_url + self.protection_type_url

        # Headers
        headers = self.rest_session.headers

        # Get Protection Types - GET
        response = self.rest_call.get_query(url=url,
                                            headers=headers,
                                            verify=False)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            protection_types = list(response.json())
        else:
            # Empty list
            pass

        return protection_types

    def create_threat_prevention_policy(self, policy):
        # Action
        policy_id = 0

        # Craft the URL
        url = self.rest_session.base_url + self.tpp_url

        # Headers
        headers = self.rest_session.headers

        # Payload
        data = json.dumps(policy)

        # Create TPP - POST
        response = self.rest_call.post_query(url=url,
                                             headers=headers,
                                             data=data,
                                             verify=False)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            policy_id = int(response.text)
        else:
            pass

        return policy_id

    def clone_threat_prevention_policy_responses(self,
                                                 from_policy_id,
                                                 to_policy_id,
                                                 response_action=None):
        # Action
        is_cloned = False

        # Craft the URL
        url = self.rest_session.base_url + \
              self.clone_tpp_responses_url.format(
                  from_policy_id=from_policy_id,
                  to_policy_id=to_policy_id
              )

        # Headers
        headers = self.rest_session.headers

        # Payload
        data = json.dumps(response_action)

        # Clone TPP - PUT
        response = self.rest_call.put_query(url=url,
                                            headers=headers,
                                            data=data,
                                            verify=False)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            is_cloned = True
        else:
            pass

        return is_cloned

    def bulk_update_threat_responses(self, response_action=None):
        # Action
        bulk_edit_success = False

        # Craft the URL
        url = self.rest_session.base_url + self.bulk_update_response_url

        # Headers
        headers = self.rest_session.headers

        # Payload
        data = json.dumps(response_action)

        # Bulk Edit TPP Response Action - PUT
        response = self.rest_call.put_query(url=url,
                                            headers=headers,
                                            data=data,
                                            verify=False)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            bulk_edit_success = True
        else:
            pass

        return bulk_edit_success

    def get_threat_prevention_policy_list(self):
        # Threat Prevention Policy List
        tpp_list = []

        # Craft the URL
        url = self.rest_session.base_url + self.tpp_url

        # Headers
        headers = self.rest_session.headers

        # Get Threat Prevention Policy List - GET
        response = self.rest_call.get_query(url=url,
                                            headers=headers,
                                            verify=False)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            tpp_list = list(response.json())
        else:
            # Empty list
            pass

        return tpp_list

    def get_threat_prevention_policy_by_id(self, policy_id):
        # Threat Prevention Policy
        tpp = None

        # Craft the URL
        url = self.rest_session.base_url + self.tpp_by_id_url.format(
            policy_id=policy_id)

        # Headers
        headers = self.rest_session.headers

        # Get Threat Prevention Policy by ID - GET
        response = self.rest_call.get_query(url=url,
                                            headers=headers,
                                            verify=False)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            tpp = dict(response.json())
        else:
            # Empty list
            pass

        return tpp

    def get_threat_prevention_policy_by_name(self, policy_name):
        # Threat Prevention Policy
        tpp = None

        # Get TPP List
        tpp_list = self.get_threat_prevention_policy_list()

        # Find the index of the TPP
        tpp_names = [tpp["name"] for tpp in tpp_list]

        if policy_name in tpp_names:
            index = tpp_names.index(policy_name)
            tpp = tpp_list[index]
        else:
            # TPP not found
            pass

        return tpp

    def delete_threat_prevention_policy_by_id(self, policy_id):
        # Action
        is_deleted = False

        # Craft the URL
        url = self.rest_session.base_url + self.tpp_by_id_url.format(
            policy_id=policy_id)

        # Headers
        headers = self.rest_session.headers

        # Delete Threat Prevention Policy by ID
        response = self.rest_call.delete_query(url=url,
                                               headers=headers,
                                               verify=False)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            is_deleted = True
        else:
            # Empty list
            pass

        return is_deleted

    def get_threats_by_policy_id(self, policy_id):
        # Threats List
        threats = []

        # Craft the URL
        url = self.rest_session.base_url + self.threats_by_policy_id_url.format(
            policy_id=policy_id)

        # Headers
        headers = self.rest_session.headers

        # Get Threats - GET
        response = self.rest_call.get_query(url=url,
                                            headers=headers,
                                            verify=False)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            threats = list(response.json())
        else:
            # Empty list
            pass

        return threats

    def get_threat_responses_by_policy_id(self, policy_id):
        # Threat Responses List
        threat_responses = []

        # Craft the URL
        url = self.rest_session.base_url + self.threat_responses_by_policy_id_url.format(
            policy_id=policy_id)

        # Headers
        headers = self.rest_session.headers

        # Get Threat Responses - GET
        response = self.rest_call.get_query(url=url,
                                            headers=headers,
                                            verify=False)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            threat_responses = list(response.json())
        else:
            # Empty list
            pass

        return threat_responses

    def get_apps_by_policy_id(self, policy_id):
        # Apps List
        apps = []

        # Craft the URL
        url = self.rest_session.base_url + self.apps_by_policy_id_url.format(
            policy_id=policy_id)

        # Headers
        headers = self.rest_session.headers

        # Get Threats - GET
        response = self.rest_call.get_query(url=url,
                                            headers=headers,
                                            verify=False)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            apps = list(response.json())
        else:
            # Empty list
            pass

        return apps

    def get_threat_encyclopedia(self, pm_id, rule_id):
        # Threat Info
        threat_info = {}

        # Craft the URL
        url = self.rest_session.base_url + self.threat_encyclopedia_url + self.sep_url + rule_id + self.sep_url + pm_id

        # Headers
        headers = self.rest_session.headers

        # Call REST - GET
        response = self.rest_call.get_query(url=url,
                                            headers=headers,
                                            verify=False)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            threat_info = dict(response.json())
        else:
            # Empty dictionary
            pass

        return threat_info

    def get_url_filtering_policy(self):
        # Policy List
        url_filter_policies = None

        # Craft the URL
        url = self.rest_session.base_url + self.url_filtering_policy_url

        # Headers
        headers = self.rest_session.headers

        # Get URL Filtering Policies - GET
        response = self.rest_call.get_query(url=url,
                                            headers=headers,
                                            verify=False)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            url_filter_policies = list(response.json())
        else:
            # Empty list
            pass

        return url_filter_policies
Esempio n. 4
0
class AccessControl(object):
    def __init__(self, rest_session):
        # singleton logger
        self.logger = CustomLogger().get_logger()

        # REST Session
        self.rest_session = rest_session

        # Common REST Calls
        self.rest_call = RestCall(rest_session)

        # URLs - Access Control
        self.acl_url = "policy/accesscontrolpolicy"
        self.acl_by_id_url = "policy/accesscontrolpolicy/{acl_id}"
        self.acl_by_infra_url = "policy/accesscontrolpolicy/infra/{infra_id}"
        self.acl_by_tenant_url = "policy/accesscontrolpolicy/tenant/{tenant_id}"
        self.acl_by_dataplane_url = "policy/accesscontrolpolicy/chassis/{dp_id}"

    def get_acl_policies(self):
        # ACL Policies
        acl_list = None

        # Craft the URL
        url = self.rest_session.base_url + self.acl_url

        # Headers
        headers = self.rest_session.headers

        # Get ACL Policies - GET (List)
        response = self.rest_call.get_query(url=url,
                                            headers=headers,
                                            verify=False)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            acl_list = list(response.json())
        else:
            pass

        return acl_list

    def get_acl_by_name(self, acl_name):
        # ACL Policy
        acl_policy = None
        index = -1

        # Get ACL Policies
        acl_list = self.get_acl_policies()

        # Find the index of the ACL
        acl_names = [acl["name"] for acl in acl_list]
        index = acl_names.index(acl_name)

        # Get specific ACL based on index
        if index >= 0:
            acl_policy = acl_list[index]
        else:
            pass

        return acl_policy

    def get_acl_by_id(self, acl_id):
        # ACL Policy
        acl_policy = None
        index = -1

        # Get ACL Policies
        acl_list = self.get_acl_policies()

        # Find the index of the ACL
        acl_ids = [acl["id"] for acl in acl_list]
        index = acl_names.ids(acl_id)

        # Get specific ACL based on index
        if index >= 0:
            acl_policy = acl_list[index]
        else:
            pass

        return acl_policy

    def update_acl(self, acl_policy):
        # Action
        is_updated = False

        # Craft the URL
        url = self.rest_session.base_url + self.acl_url

        # Headers
        headers = self.rest_session.headers

        # Payload
        data = json.dumps(acl_policy)

        # Update ACL - PUT
        response = self.rest_call.put_query(url=url,
                                            headers=headers,
                                            data=data,
                                            verify=False)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            is_updated = True
        else:
            pass

        return is_updated

    def delete_acl(self, acl_id):
        # Action
        is_deleted = False

        # Craft the URL
        url = self.rest_session.base_url + self.acl_by_id_url.format(
            acl_id=acl_id)

        # Headers
        headers = self.rest_session.headers

        # Payload
        data = json.dumps(acl_policy)

        # Delete ACL - DELETE
        response = self.rest_call.delete_query(url=url,
                                               headers=headers,
                                               verify=False)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            is_deleted = True
        else:
            pass

        return is_deleted
Esempio n. 5
0
class Blacklist(object):
    def __init__(self, rest_session):
        # singleton logger
        self.logger = CustomLogger().get_logger()

        # REST Session
        self.rest_session = rest_session

        # Common REST Calls
        self.rest_call = RestCall(rest_session)

        # URLs specific to IP Blacklist
        self.blacklist_url = "accesscontrol/ipblacklist"
        self.disable_blacklist_url = "accesscontrol/ipblacklist/disable"
        self.import_by_file_url = "accesscontrol/importlistedip"
        self.import_by_feed_url = "accesscontrol/urlfeed/blacklistedips"
        self.export_listed_ip_url = "accesscontrol/export/blacklist"
        self.response_action_url = "accesscontrol/ipblacklist/action"
        self.global_settings_url = "accesscontrol/ipblacklist/globalsettings"

    def get_ip_blacklist(self):
        # Blacklists
        blacklists = None

        # Craft the URL
        url = self.rest_session.base_url + self.blacklist_url

        # Headers
        headers = self.rest_session.headers

        # Call REST - GET
        response = self.rest_call.get_query(
                       url = url,
                       verify = False,
                       headers = headers
                   )

        # Convert response to expected data
        blacklists = list(response.json())

        return blacklists

    def disable_ip_blacklist(self):
        # Action
        is_disabled = False

        # Craft the URL
        url = self.rest_session.base_url + self.disable_blacklist_url

        # Headers
        headers = self.rest_session.headers

        # Call REST - DELETE
        response = self.rest_call.delete_query(
                       url = url,
                       verify = False,
                       headers = headers
                   )

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            is_disabled = True
        else:
            is_disabled = False

        return is_disabled

    def import_listed_ip(self, filename):
        # Action
        is_imported = False

        try:
            # Craft the URL
            url = self.rest_session.base_url + self.import_by_file_url

            # File to import, opened
            files = {"file": (filename, open(filename), "text/plain")}

            # Use file name and exclude full path
            _, file_name = os.path.split(filename)

            # Customize header, remove "content-type".
            headers = dict(**self.rest_session.headers)
            headers.pop("content-type")

            # "param" is the name of the imported file
            data = {
                "param": file_name,
            }

            # Call REST - POST
            response = self.rest_call.post_query(
                           url = url,
                           files = files,
                           headers = headers,
                           verify = False,
                           data = data
                       )
        except Exception as e:
            self.logger.error(e)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            is_imported = True
        else:
            is_imported = False

        return is_imported

    def import_listed_feed(self, urlfeed):
        # Action
        is_imported = False

        try:
            # Craft the URL
            url = self.rest_session.base_url + self.import_by_feed_url

            # Fetch the resource name
            feed_name = urlfeed.split("/")[-1]

            # Payload
            data = json.dumps({
                "enable" : "false",
                "tenantId" : 1,
                "tenants" : [{"id": 1, "name": "default-tenant"}],
                "name" : feed_name,
                "type" : "2",
                "url" : urlfeed,
                "urlmd5" : ""
            })

            # Headers
            headers = self.rest_session.headers

            # Call REST - POST
            response = self.rest_call.post_query(
                           url = url,
                           headers = headers,
                           verify = False,
                           data = data
                       )
        except Exception as e:
            self.logger.error(e)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            is_imported = True
        else:
            is_imported = False

        return is_imported

    def export_listed_ip(self, export_file = None):
        # Action
        is_exported = False

        # Blacklist
        ip_blacklist = None

        try:
            # Craft the URL
            url = self.rest_session.base_url + self.export_listed_ip_url

            # Headers
            headers = self.rest_session.headers

            # Call REST - GET
            response = self.rest_call.get_query(
                           url = url,
                           verify = False,
                           headers = headers
                       )

            # Convert response to expected data
            if response.status_code == requests.codes.ok:
                # IP Blacklist Count
                self.logger.info("IP Blacklist Count: {}".format(len(response.text.split())))

                ip_blacklist = response.text
                is_exported = True
            else:
                self.logger.error(response.status_code)
                self.logger.error(response.content)
        except Exception as e:
            self.logger.error(e)

        try:
            if export_file is not None:
                with open(export_file, "w") as txt_file:
                    txt_file.write(ip_blacklist)
            else:
                pass
        except Exception as e:
            self.logger.error(e)

        return is_exported

    def get_ip_blacklist_global_settings(self):
        # Global settings
        ip_blacklist_globalsettings = {}

        try:
            # Craft the URL
            url = self.rest_session.base_url + self.global_settings_url

            # Headers
            headers = self.rest_session.headers

            # Call REST - GET
            response = self.rest_call.get_query(
                           url = url,
                           verify = False,
                           headers = headers
                       )

            # Convert response to expected data
            if response.status_code == requests.codes.ok:
                ip_blacklist_globalsettings = dict(response.json())
            else:
                self.logger.error(response.status_code)
        except Exception as e:
            self.logger.error(e)

        return ip_blacklist_globalsettings

    def set_ip_blacklist_action(self, action, frequency=30):
        # Action
        is_action_set = False

        # Blacklist - Response Action
        #     1 - Alert Only
        #     2 - Block and Alert
        # Blacklist - Frequency
        #     Currently not used
        data = json.dumps({
                   "action" : action,
                   "frequency" : frequency
               })

        try:
            # Craft the URL
            url = self.rest_session.base_url + self.response_action_url

            # Headers
            headers = self.rest_session.headers

            # Call REST - PUT
            response = self.rest_call.put_query(
                           url = url,
                           headers = headers,
                           verify = False,
                           data = data
                       )

            # Convert response to expected data
            if response.status_code == requests.codes.ok:
                is_action_set = True
                self.logger.info("Blacklist Action Set.")
            else:
                self.logger.error(response.status_code)
        except Exception as e:
            self.logger.error(e)

        return is_action_set
Esempio n. 6
0
class AccessControl(object):
    def __init__(self, rest_session):
        # singleton logger
        self.logger = CustomLogger().get_logger()

        # fetched data
        self.data = None

        # REST Session
        self.rest_session = rest_session

        # Common REST Calls
        self.rest_call = RestCall(rest_session)

        # URLs specific to ACL's
        self.accesscontrol_policy_url = "policy/accesscontrolpolicy"
        self.accesscontrol_policy_ruleadd = "policy/accesscontrolpolicy"
        self.accesscontrol_policy_nondefaultacl = "policy/accesscontrolpolicy"
        self.accesscontrol_policy_nondefaultacl_del = "policy/accesscontrolpolicy/"
        self.accesscontrol_policy_byruleid = "policy/accesscontrolpolicy/rules/"
        self.accesscontrol_policy_bychassisid = "policy/accesscontrolpolicy/chassis/"
        self.accesscontrol_policy_byinfraid = "policy/accesscontrolpolicy/infra/"
        self.accesscontrol_policy_byaclid = "policy/accesscontrolpolicy/"
        self.accesscontrol_policy_bytenantid = "policy/accesscontrolpolicy/tenant/"
        self.accesscontrol_policy_ruleadd_policyid = "policy/accesscontrolpolicy/rule"

    def get_access_controllist(self):
        accesscontrol = None

        # Craft the URL
        url = self.rest_session.base_url + self.accesscontrol_policy_url

        # Headers
        headers = self.rest_session.headers

        # Call REST - GET
        response = self.rest_call.get_query(
            url = url,
            verify=False,
            headers = headers
        )
        accesscontrol = list(response.json())
        return accesscontrol

    def add_access_control_rule(self):
        rule_added = False

        # Craft the URL
        url = self.rest_session.base_url + self.accesscontrol_policy_url

        # Headers
        headers = self.rest_session.headers

        # Call REST - GET
        response = self.rest_call.get_query(
            url = url,
            verify=False,
            headers = headers
        )
        accesscontrollist = list(response.json())
        for aid in accesscontrollist:
            if aid["name"] == 'Default ACL Policy':
                aclpolicyid = int(aid['id'])
                break

        data = json.dumps({
            "id": aclpolicyid,
            "name": "Default ACL Policy",
            "tenantId": None,
            "aclRules": [
                {
                    "action": "PERMIT",
                    "description": "",
                    "destinationApps": "",
                    "destinationCidrs": "",
                    "destinationPortRanges": "",
                    "name": "rule-51",
                    "destinationResourceGroupList": [

                    ],
                    "enableTLSInspection": False,
                    "enabled": True,
                    "orderNum": 1,
                    "resourcegroupNames": [

                    ],
                    "sourceResourceGroupList": [

                    ],
                    "destinationProtocol": None,
                    "spsId": 5,
                    "tcpSessionTimeout": 1800,
                    "hitStats": None,
                    "tlsInspection": "DISABLED",
                    "serviceList": [

                    ]
                },
                {
                    "id": 4,
                    "name": "Default",
                    "description": None,
                    "orderNum": 2,
                    "enabled": True,
                    "destinationResourceGroupList": [

                    ],
                    "sourceResourceGroupList": [

                    ],
                    "serviceList": [

                    ],
                    "destinationApps": "",
                    "syslog": False,
                    "tcpSessionTimeout": 1800,
                    "tlsInspection": "DISABLED",
                    "packetCapture": "DISABLED",
                    "spsId": 5,
                    "action": "PERMIT",
                    "destinationProtocol": None,
                    "destinationPortRanges": None,
                    "userType": "HUMAN",
                    "user": "******",
                    "mapOfChangeLogPerTS": None,
                    "gmId": None
                }
            ],
            "infraMap": {
                "2": "tonyinf"
            },
            "rgNameMap": None,
            "spsNameMap": None,
            "serviceNameMap": None
        })
        try:
            # Craft the URL
            url = self.rest_session.base_url + self.accesscontrol_policy_ruleadd

            # Headers
            headers = self.rest_session.headers

            # Call REST - PUT
            response = self.rest_call.put_query(
            url=url,
            headers=headers,
            verify=False,
            data=data
        )
            if response.status_code == requests.codes.ok:
                rule_added = True
                self.logger.info("New rule added to Default ACL.")
            else:
                self.logger.error(response.status_code)
        except Exception as e:
            self.logger.error(e)

        return rule_added

    def add_srcdst_access_control_rule(self, dstrg_id, srcrg_id, rule_nm):
        rules_added = False
        # Craft the URL
        url = self.rest_session.base_url + self.accesscontrol_policy_url

        # Headers
        headers = self.rest_session.headers

        # Call REST - GET
        response = self.rest_call.get_query(
            url = url,
            verify=False,
            headers = headers
        )
        accesscontrollist = list(response.json())
        for aid in accesscontrollist:
            if aid["name"] == 'Default ACL Policy':
                aclpolicyid = int(aid['id'])
                break

        group_handle = GroupandInsert(self.rest_session)
        rgid1 = str(dstrg_id)
        rgid2 = str(srcrg_id)

        newacl_add = [{
            "id": aclpolicyid,
            "name": "Default ACL Policy",
            "tenantId": None,
            "aclRules": [
                {
                    "action": "PERMIT",
                    "description": "",
                    "destinationApps": "",
                    "destinationCidrs": "",
                    "destinationPortRanges": "",
                    "name": "RG-1 to RG-2",
                    "destinationResourceGroupList": [
                        15
                    ],
                    "enableTLSInspection": False,
                    "enabled": True,
                    "orderNum": 1,
                    "resourcegroupNames": [

                    ],
                    "sourceResourceGroupList": [
                        14
                    ],
                    "destinationProtocol": None,
                    "spsId": 5,
                    "tcpSessionTimeout": 1800,
                    "hitStats": None,
                    "tlsInspection": "DISABLED",
                    "serviceList": [
                        215
                    ]
                },
                {
                    "id": 4,
                    "name": "Default",
                    "description": None,
                    "orderNum": 2,
                    "enabled": True,
                    "destinationResourceGroupList": [

                    ],
                    "sourceResourceGroupList": [

                    ],
                    "serviceList": [

                    ],
                    "destinationApps": "",
                    "syslog": False,
                    "tcpSessionTimeout": 1800,
                    "tlsInspection": "DISABLED",
                    "packetCapture": "DISABLED",
                    "spsId": 5,
                    "action": "PERMIT",
                    "destinationProtocol": None,
                    "destinationPortRanges": None,
                    "userType": "HUMAN",
                    "user": "******",
                    "mapOfChangeLogPerTS": None,
                    "gmId": None
                }
            ],
            "infraMap": {
                "2": "tonyinf-test2"
            },
            "rgNameMap": None,
            "spsNameMap": None,
            "serviceNameMap": None
        }]

        for srcdstid in newacl_add:
            if srcdstid["name"] == "Default ACL Policy":
                srcdstid["aclRules"][0]["name"] = rule_nm
                srcdstid["aclRules"][0]["destinationResourceGroupList"] = [rgid1]
                srcdstid["aclRules"][0]["sourceResourceGroupList"] = [rgid2]

        data = json.dumps(newacl_add)
        data = str(data)[1:-1]

        try:
            # Craft the URL
            url = self.rest_session.base_url + self.accesscontrol_policy_ruleadd

            # Headers
            headers = self.rest_session.headers

            # Call REST - PUT
            response = self.rest_call.put_query(
            url=url,
            headers=headers,
            verify=False,
            data=data
        )
            if response.status_code == requests.codes.ok:
                rules_added = True
                self.logger.info("New rules added with src and dst.")
            else:
                self.logger.error(response.status_code)
        except Exception as e:
            self.logger.error(e)

        return rules_added

    def add_nondefault_acl_policy(self):

            # Craft the URL
            url = self.rest_session.base_url + self.accesscontrol_policy_nondefaultacl

            # Headers
            headers = self.rest_session.headers

            # Payload-1
            data1 = json.dumps({
                "id": 0,
                "name": "nondefault_acl_policy",
                "tenantId": 1,
                "aclRules": [
                    {
                        "action": "PERMIT",
                        "description": "Default rule",
                        "destinationApps": "",
                        "destinationCidrs": "",
                        "destinationPortRanges": "",
                        "name": "Default",
                        "destinationResourceGroupList": [

                        ],
                        "enableTLSInspection": False,
                        "enabled": True,
                        "id": 0,
                        "orderNum": 1,
                        "resourcegroupNames": [

                        ],
                        "sourceResourceGroupList": [

                        ],
                        "destinationProtocol": None,
                        "spsId": 5,
                        "tcpSessionTimeout": 1800,
                        "hitStats": None,
                        "tlsInspection": "DISABLED"
                    }
                ]
            })

            # Call REST - POST
            response = self.rest_call.post_query(
                           url = url,
                           headers = headers,
                           verify=False,
                           data = data1
                       )
            nondefault_acl_id = int(response.json())

            # Payload-2
            payload = [{
                "id": 0,
                "name": "nondefault_acl_policy",
                "tenantId": 1,
                "aclRules": [
                    {
                        "id": 0,
                        "name": "Default",
                        "description": "Default rule",
                        "orderNum": 1,
                        "enabled": True,
                        "destinationResourceGroupList": [

                        ],
                        "sourceResourceGroupList": [

                        ],
                        "serviceList": [

                        ],
                        "destinationApps": "",
                        "syslog": False,
                        "tcpSessionTimeout": 1800,
                        "tlsInspection": "DISABLED",
                        "packetCapture": None,
                        "spsId": 5,
                        "action": "PERMIT",
                        "destinationProtocol": None,
                        "destinationPortRanges": "",
                        "userType": "HUMAN",
                        "user": None,
                        "mapOfChangeLogPerTS": None,
                        "gmId": None
                    }
                ],
                "infraMap": {

                },
                "rgNameMap": None,
                "spsNameMap": None,
                "serviceNameMap": None
            }]
            for aid in payload:
                if aid["id"] == 0:
                    aid["id"] = nondefault_acl_id
                    aid["aclRules"][0]["id"] = nondefault_acl_id+1
            data2 = json.dumps(payload)
            data2 = str(data2)[1:-1]

            # Call REST - PUT
            response = self.rest_call.put_query(
            url=url,
            headers=headers,
            verify=False,
            data=data2
        )
            if response.status_code == requests.codes.ok:
                print("Non Default ACL policy created successfully")
            else:
                print("Non default ACL creation not successful")

                return nondefault_acl_id

    def add_tls_rule(self):
        tls_rule_added = False

        # Craft the URL
        url = self.rest_session.base_url + self.accesscontrol_policy_url

        # Headers
        headers = self.rest_session.headers

        # Call REST - GET
        response = self.rest_call.get_query(
            url = url,
            verify=False,
            headers = headers
        )
        accesscontrollist = list(response.json())
        for aid in accesscontrollist:
            if aid["name"] == 'Default ACL Policy':
                aclpolicyid = int(aid['id'])
                break

        data = json.dumps({
            "id": aclpolicyid,
            "name": "Default ACL Policy",
            "tenantId": None,
            "aclRules": [
                {
                    "action": "PERMIT",
                    "description": "",
                    "destinationApps": "",
                    "destinationCidrs": "",
                    "destinationPortRanges": "",
                    "name": "Enable_TLS",
                    "destinationResourceGroupList": [

                    ],
                    "enableTLSInspection": True,
                    "enabled": True,
                    "orderNum": 1,
                    "resourcegroupNames": [

                    ],
                    "sourceResourceGroupList": [

                    ],
                    "destinationProtocol": None,
                    "spsId": 5,
                    "tcpSessionTimeout": 1800,
                    "hitStats": None,
                    "tlsInspection": "INBOUND",
                    "serviceList": [
                        92
                    ],
                    "syslog": False,
                    "packetCapture": "DISABLED"
                },
                {
                    "id": 4,
                    "name": "Default",
                    "description": None,
                    "orderNum": 2,
                    "enabled": True,
                    "destinationResourceGroupList": [

                    ],
                    "sourceResourceGroupList": [

                    ],
                    "serviceList": [

                    ],
                    "destinationApps": "",
                    "syslog": False,
                    "tcpSessionTimeout": 1800,
                    "tlsInspection": "DISABLED",
                    "packetCapture": "DISABLED",
                    "spsId": 5,
                    "action": "PERMIT",
                    "destinationProtocol": None,
                    "destinationPortRanges": None,
                    "userType": "HUMAN",
                    "user": "******",
                    "mapOfChangeLogPerTS": None,
                    "gmId": None
                }
            ],
            "infraMap": {
                "2": "tonyinf"
            },
            "rgNameMap": None,
            "spsNameMap": None,
            "serviceNameMap": None
        })

        try:
            # Craft the URL
            url = self.rest_session.base_url + self.accesscontrol_policy_ruleadd

            # Headers
            headers = self.rest_session.headers

            # Call REST - PUT
            response = self.rest_call.put_query(
            url=url,
            headers=headers,
            verify=False,
            data=data
        )
            if response.status_code == requests.codes.ok:
                tls_rule_added = True
                self.logger.info("TLS policy enabled successfully.")
            else:
                self.logger.error(response.status_code)
        except Exception as e:
            self.logger.error(e)

        return tls_rule_added

    def add_multirule_httpping_service(self):
        multi_rule_added = False

        # Craft the URL
        url = self.rest_session.base_url + self.accesscontrol_policy_url

        # Headers
        headers = self.rest_session.headers

        # Call REST - GET
        response = self.rest_call.get_query(
            url = url,
            verify=False,
            headers = headers
        )
        accesscontrollist = list(response.json())
        for aid in accesscontrollist:
            if aid["name"] == 'Default ACL Policy':
                aclpolicyid = int(aid['id'])
                break

        data = json.dumps({
            "id": aclpolicyid,
            "name": "Default ACL Policy",
            "tenantId": None,
            "aclRules": [
                {
                    "action": "DENY",
                    "description": "",
                    "destinationApps": "",
                    "destinationCidrs": "",
                    "destinationPortRanges": "",
                    "name": "rule-2",
                    "destinationResourceGroupList": [

                    ],
                    "enableTLSInspection": False,
                    "enabled": True,
                    "orderNum": 1,
                    "resourcegroupNames": [

                    ],
                    "sourceResourceGroupList": [

                    ],
                    "destinationProtocol": None,
                    "spsId": 5,
                    "tcpSessionTimeout": 1800,
                    "hitStats": None,
                    "tlsInspection": "DISABLED",
                    "serviceList": [
                        215
                    ]
                },
                {
                    "id": 165,
                    "name": "rule-1",
                    "description": "",
                    "orderNum": 2,
                    "enabled": True,
                    "destinationResourceGroupList": [

                    ],
                    "sourceResourceGroupList": [

                    ],
                    "serviceList": [
                        25
                    ],
                    "destinationApps": "",
                    "syslog": False,
                    "tcpSessionTimeout": 1800,
                    "tlsInspection": "DISABLED",
                    "packetCapture": None,
                    "spsId": 5,
                    "action": "PERMIT",
                    "hitStats": {
                        "ruleId": 165,
                        "hitCount": 0
                    },
                    "destinationProtocol": None,
                    "destinationPortRanges": "",
                    "userType": "HUMAN",
                    "user": None,
                    "mapOfChangeLogPerTS": None,
                    "gmId": None,
                    "enableTLSInspection": True
                },
                {
                    "id": 4,
                    "name": "Default",
                    "description": None,
                    "orderNum": 3,
                    "enabled": True,
                    "destinationResourceGroupList": [

                    ],
                    "sourceResourceGroupList": [

                    ],
                    "serviceList": [

                    ],
                    "destinationApps": "",
                    "syslog": False,
                    "tcpSessionTimeout": 1800,
                    "tlsInspection": "DISABLED",
                    "packetCapture": "DISABLED",
                    "spsId": 5,
                    "action": "PERMIT",
                    "destinationProtocol": None,
                    "destinationPortRanges": None,
                    "userType": "HUMAN",
                    "user": "******",
                    "mapOfChangeLogPerTS": None,
                    "gmId": None
                }
            ],
            "infraMap": {
                "2": "tonyinf"
            },
            "rgNameMap": None,
            "spsNameMap": None,
            "serviceNameMap": None
        })

        try:
            # Craft the URL
            url = self.rest_session.base_url + self.accesscontrol_policy_ruleadd

            # Headers
            headers = self.rest_session.headers

            # Call REST - PUT
            response = self.rest_call.put_query(
            url=url,
            headers=headers,
            verify=False,
            data=data
        )
            if response.status_code == requests.codes.ok:
                multi_rule_added = True
                self.logger.info("ACL rules with HTTP and Ping services added")
            else:
                self.logger.error(response.status_code)
        except Exception as e:
            self.logger.error(e)
        return multi_rule_added

    def del_all_defaultacl_rules(self):
        all_rule_del = False

        # Craft the URL
        url = self.rest_session.base_url + self.accesscontrol_policy_url

        # Headers
        headers = self.rest_session.headers

        # Call REST - GET
        response = self.rest_call.get_query(
            url = url,
            verify=False,
            headers = headers
        )
        accesscontrollist = list(response.json())
        for aid in accesscontrollist:
            if aid["name"] == 'Default ACL Policy':
                aclpolicyid = int(aid['id'])
                break

        data = json.dumps({
            "id": aclpolicyid,
            "name": "Default ACL Policy",
            "tenantId": None,
            "aclRules": [
                {
                    "id": 4,
                    "name": "Default",
                    "description": None,
                    "orderNum": 1,
                    "enabled": True,
                    "destinationResourceGroupList": [

                    ],
                    "sourceResourceGroupList": [

                    ],
                    "serviceList": [

                    ],
                    "destinationApps": "",
                    "syslog": False,
                    "tcpSessionTimeout": 1800,
                    "tlsInspection": "DISABLED",
                    "packetCapture": "DISABLED",
                    "spsId": 5,
                    "action": "PERMIT",
                    "destinationProtocol": None,
                    "destinationPortRanges": None,
                    "userType": "HUMAN",
                    "user": "******",
                    "mapOfChangeLogPerTS": None,
                    "gmId": None
                }
            ],
            "infraMap": {
                "2": "tonyinf"
            },
            "rgNameMap": None,
            "spsNameMap": None,
            "serviceNameMap": None
        })

        try:
            # Craft the URL
            url = self.rest_session.base_url + self.accesscontrol_policy_ruleadd

            # Headers
            headers = self.rest_session.headers

            # Call REST - PUT
            response = self.rest_call.put_query(
            url=url,
            headers=headers,
            verify=False,
            data=data
        )
            if response.status_code == requests.codes.ok:
                all_rule_del = True
                self.logger.info("All rules deleted from the default ACL policy")
            else:
                self.logger.error(response.status_code)
        except Exception as e:
            self.logger.error(e)
        return all_rule_del

    def del_nondefaultacl_policy(self):
        del_nondefault_acl = False

        # Craft the URL
        url = self.rest_session.base_url + self.accesscontrol_policy_url

        # Headers
        headers = self.rest_session.headers

        # Call REST - GET
        response = self.rest_call.get_query(
            url = url,
            verify=False,
            headers = headers
        )
        accesscontrollist = list(response.json())
        for aid in accesscontrollist:
            if aid["name"] == 'nondefault_acl_policy':
                aclpolicyid = str(aid['id'])
                break

        # Craft the URL
        url = self.rest_session.base_url + self.accesscontrol_policy_nondefaultacl_del + aclpolicyid

        # Headers
        headers = self.rest_session.headers

        # Call REST - DELETE
        response = self.rest_call.delete_query(
                       url = url,
                       verify=False,
                       headers = headers
                   )

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            del_nondefault_acl = True
        else:
            del_nondefault_acl = False

        return del_nondefault_acl

    def del_aclpolicy_aclid(self,acl_policy_id):
        del_aclpolicy_aclid = False

        aclid_policy = str(acl_policy_id)

        # Craft the URL
        url = self.rest_session.base_url + self.accesscontrol_policy_byaclid + aclid_policy

        # Headers
        headers = self.rest_session.headers

        # Call REST - DELETE
        response = self.rest_call.delete_query(
                       url = url,
                       verify=False,
                       headers = headers
                   )

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            del_aclpolicy_aclid = True
        else:
            del_aclpolicy_aclid = False

        return del_aclpolicy_aclid

    def get_aclrule_ruleid(self,aclruleid):
        obtain_aclrule_byid = False

        aclruleid = str(aclruleid)

        # Craft the URL
        url = self.rest_session.base_url + self.accesscontrol_policy_byruleid + aclruleid

        # Headers
        headers = self.rest_session.headers

        # Call REST - GET
        response = self.rest_call.get_query(
            url = url,
            verify=False,
            headers = headers
        )
        if response.status_code == requests.codes.ok:
            accesscontrollist = response.content
            obtain_aclrule_byid = True
        else:
            obtain_aclrule_byid = False

        return accesscontrollist

    def get_aclpolicy_chassisid(self,aclpolicychassisid):
        obtain_aclpolicy_bychassisid = False

        aclpolicychassisid = str(aclpolicychassisid)

        # Craft the URL
        url = self.rest_session.base_url + self.accesscontrol_policy_bychassisid + aclpolicychassisid

        # Headers
        headers = self.rest_session.headers

        # Call REST - GET
        response = self.rest_call.get_query(
            url = url,
            verify=False,
            headers = headers
        )
        if response.status_code == requests.codes.ok:
            accesscontrol_list = response.content
            obtain_aclpolicy_bychassisid = True
        else:
            obtain_aclpolicy_bychassisid = False

        return accesscontrol_list

    def get_aclpolicy_infraid(self,aclpolicyinfraid):
        obtain_aclpolicy_byinfraid = False

        aclpolicyinfraid = str(aclpolicyinfraid)

        # Craft the URL
        url = self.rest_session.base_url + self.accesscontrol_policy_byinfraid + aclpolicyinfraid

        # Headers
        headers = self.rest_session.headers

        # Call REST - GET
        response = self.rest_call.get_query(
            url = url,
            verify=False,
            headers = headers
        )
        if response.status_code == requests.codes.ok:
            ac_list = response.content
            obtain_aclpolicy_byinfraid = True
        else:
            obtain_aclpolicy_byinfraid = False

        return ac_list

    def get_aclpolicy_aclid(self,aclpolicyid):
        obtain_aclpolicy_byaclid = False

        aclpolicyid = str(aclpolicyid)

        # Craft the URL
        url = self.rest_session.base_url + self.accesscontrol_policy_byaclid + aclpolicyid

        # Headers
        headers = self.rest_session.headers

        # Call REST - GET
        response = self.rest_call.get_query(
            url = url,
            verify=False,
            headers = headers
        )
        if response.status_code == requests.codes.ok:
            accesscontrolpolicy = response.content
            obtain_aclpolicy_byaclid = True
        else:
            obtain_aclpolicy_byaclid = False

        return accesscontrolpolicy

    def get_aclpolicy_tenantid(self,aclpolicytenantid):
        obtain_aclpolicy_bytenantid = False

        aclpolicytenantid = str(aclpolicytenantid)

        # Craft the URL
        url = self.rest_session.base_url + self.accesscontrol_policy_bytenantid + aclpolicytenantid

        # Headers
        headers = self.rest_session.headers

        # Call REST - GET
        response = self.rest_call.get_query(
            url = url,
            verify=False,
            headers = headers
        )
        if response.status_code == requests.codes.ok:
            accesscontrol_policy = response.content
            obtain_aclpolicy_bytenantid = True
        else:
            obtain_aclpolicy_bytenantid = False

        return accesscontrol_policy

    def add_aclrule_aclpolicyid(self,aclrule,aclpolicy_id):
        aclrule_addbypolicyid = False

        data = json.dumps(aclrule)
        aclpolid = "?aclPolicyId={0}".format(aclpolicy_id)

        # Craft the URL
        url = self.rest_session.base_url + self.accesscontrol_policy_ruleadd_policyid + aclpolid

        # Headers
        headers = self.rest_session.headers

        # Call REST - PUT
        response = self.rest_call.put_query(
            url = url,
            verify=False,
            headers = headers,
            data = data
        )
        if response.status_code == requests.codes.ok:
            aclrule_addbypolicyid = True
        else:
            aclrule_addbypolicyid = False

        return aclrule_addbypolicyid
Esempio n. 7
0
class SecurityPolicySets(object):
    def __init__(self, rest_session):
        # singleton logger
        self.logger = CustomLogger().get_logger()

        # REST Session
        self.rest_session = rest_session

        # Common REST Calls
        self.rest_call = RestCall(rest_session)

        # URLs - Security Policy Set
        self.sps_url = "policy/securitypolicyset"
        self.sps_by_tenant_id_url = "policy/securitypolicyset/tenant/{tenant_id}"
        self.sps_by_id_url = "policy/securitypolicyset/{sps_id}"

    def create_security_policy_set(self, policy):
        # Security Policy Set ID
        policy_id = None

        # Craft the URL
        url = self.rest_session.base_url + self.sps_url

        # Headers
        headers = self.rest_session.headers

        # Payload
        data = json.dumps(policy)

        # Create SPS - POST
        response = self.rest_call.post_query(
                       url = url,
                       headers = headers,
                       data = data,
                       verify = False
                   )

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            policy_id = int(response.text)
        else:
            pass

        return policy_id

    def update_security_policy_set(self, policy):
        # Security Policy Set ID
        policy_id = None

        # Craft the URL
        url = self.rest_session.base_url + self.sps_url

        # Headers
        headers = self.rest_session.headers

        # Payload
        data = json.dumps(policy)

        # Update SPS - PUT
        response = self.rest_call.put_query(
                       url = url,
                       headers = headers,
                       data = data,
                       verify = False
                   )

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            policy_id = int(response.text)
        else:
            pass

        return policy_id

    def get_security_policy_set(self):
        # Security Policy Set List
        sps_list = []

        # Craft the URL
        url = self.rest_session.base_url + self.sps_url

        # Headers
        headers = self.rest_session.headers

        # Get SPS List - GET
        response = self.rest_call.get_query(
                       url = url,
                       headers = headers,
                       verify = False
                   )

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            sps_list = list(response.json())
        else:
            # Empty list
            pass

        return sps_list

    def get_sps_by_id(self, sps_id):
        # Security Policy Set
        sps = None

        # Craft the URL
        url = self.rest_session.base_url + self.sps_by_id_url.format(sps_id=sps_id)

        # Headers
        headers = self.rest_session.headers

        # Get SPS - GET
        response = self.rest_call.get_query(
                       url = url,
                       headers = headers,
                       verify = False
                   )

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            sps = dict(response.json())
        else:
            # Empty list
            pass

        return sps

    def get_sps_by_name(self, sps_name):
        # Security Policy Set
        sps = None

        # Get list of SPS
        sps_list = self.get_security_policy_set()

        # Find the index of the SPS
        sps_names = [sps["name"] for sps in sps_list]

        if sps_name in sps_names:
            index = sps_names.index(sps_name)
            sps = sps_list[index]
        else:
            # SPS not found
            pass

        return sps

    def delete_security_policy_set_by_id(self, sps_id):
        # Action
        is_deleted = False

        # Craft the URL
        url = self.rest_session.base_url + self.sps_by_id_url.format(sps_id=sps_id)

        # Headers
        headers = self.rest_session.headers

        # Delete Security Policy Set by ID
        response = self.rest_call.delete_query(
                       url = url,
                       headers = headers,
                       verify = False
                   )

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            is_deleted = True
        else:
            # Empty list
            pass

        return is_deleted
Esempio n. 8
0
class CloudManagement(object):
    def __init__(self, rest_session):
        # singleton logger
        self.logger = CustomLogger().get_logger()

        # REST Session
        self.rest_session = rest_session

        # Common REST Calls
        self.rest_call = RestCall(rest_session)

        # URL specific to this Module
        self.infras_url = "infras"
        self.resource_group_url = "infras/resourcegroup"
        self.resource_groups_url = "infras/resourcegroups"

        self.ip_pool_url = "ippool"

        # URL separator
        self.sep_url = "/"

    def create_cloud(self, cloud_info):
        # Cloud ID
        cloud_id = None

        # Craft the URL
        url = self.rest_session.base_url + self.infras_url

        # Headers
        headers = self.rest_session.headers

        # Data
        data = json.dumps(cloud_info)

        # Create Infra Connector - POST
        response = self.rest_call.post_query(url=url,
                                             data=data,
                                             verify=False,
                                             headers=headers)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            cloud_id = int(response.json())
        else:
            pass

        return cloud_id

    def delete_cloud(self, cloud_id):
        # Craft the URL
        url = self.rest_session.base_url + self.infras_url + self.sep_url + str(
            cloud_id)

        # Headers
        headers = self.rest_session.headers

        # Delete Infra Connector - DELETE
        response = self.rest_call.delete_query(url=url,
                                               verify=False,
                                               headers=headers)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            return True
        else:
            return False

    def get_cloud_objects(self, cloud_id):
        cloud_objects = None

        # Craft the URL
        url = self.rest_session.base_url + self.infras_url + self.sep_url + str(
            cloud_id) + self.sep_url + "objects"

        # Headers
        headers = self.rest_session.headers

        # Infra Objects - GET
        response = self.rest_call.get_query(url=url,
                                            verify=False,
                                            headers=headers)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            cloud_objects = dict(response.json())
        else:
            return False

        return cloud_objects

    def create_cloud_infra(self, **cloud_info):
        # Infra ID
        infra_id = None

        # Verify necessary info are defined
        try:
            # Verify cloud info is not None
            if not all([
                    cloud_info["cloud_type"],
                    cloud_info["username"],
                    cloud_info["password"],
            ]):
                self.logger.error("One of the cloud info is None.")
                return infra_id
            else:
                # Proceed with cloud infra creation
                pass
        except KeyError as e:
            self.logger.error("Missing necessary cloud information.")
            return infra_id

        # Verify cloud information
        if cloud_info["cloud_type"] == "VMWARE":
            self.logger.info("Cloud Type: {}".format(cloud_info["cloud_type"]))
        elif cloud_info["cloud_type"] == "AWS":
            self.logger.info("Cloud Type: {}".format(cloud_info["cloud_type"]))
        elif cloud_info["cloud_type"] == "MS Azure":
            self.logger.info("Cloud Type: {}".format(cloud_info["cloud_type"]))
        else:
            self.logger.error("Cloud Type: {}".format(
                cloud_info["cloud_type"]))

        # Craft the URL
        url = self.rest_session.base_url + self.infras_url

        # Headers
        headers = self.rest_session.headers

        # Create Infra Connector - POST

        # Convert response to expected data

        return infra_id

    def get_cloud_infra(self):
        # Cloud list
        cloud_list = None

        # Craft the URL
        url = self.rest_session.base_url + self.infras_url

        # Headers
        headers = self.rest_session.headers

        # Get Cloud Infras - GET
        response = self.rest_call.get_query(url=url,
                                            verify=False,
                                            headers=headers)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            cloud_list = list(response.json())
        else:
            pass

        return cloud_list

    def get_cloud_infra_by_name(self, cloud_name):
        # Cloud (Infra Connectors)
        cloud_list = self.get_cloud_infra()

        for cloud in cloud_list:
            if cloud_name == cloud["name"]:
                return cloud

        return None

    def update_cloud_infra(self, cloud_info):
        is_updated = False

        # Craft the URL
        url = self.rest_session.base_url + self.infras_url

        # Payload
        data = json.dumps(cloud_info)

        # Headers
        headers = self.rest_session.headers

        # Update Cloud Infra - PUT
        response = self.rest_call.put_query(url=url,
                                            data=data,
                                            verify=False,
                                            headers=headers)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            is_updated = True
        else:
            pass

        return is_updated

    def create_resource_group(self, resource_group):
        rg_id = None

        # Craft the URL
        url = self.rest_session.base_url + self.resource_group_url

        # Headers
        headers = self.rest_session.headers

        # Payload
        data = json.dumps(resource_group)

        # Create Resource Group - POST
        response = self.rest_call.post_query(url=url,
                                             headers=headers,
                                             data=data,
                                             verify=False)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            rg_id, _ = list(response.json())
        else:
            pass

        return rg_id

    def get_resource_groups(self):
        resource_groups = []

        # Craft the URL
        url = self.rest_session.base_url + self.resource_groups_url

        # Headers
        headers = self.rest_session.headers

        # Get Resource Groups - GET
        response = self.rest_call.get_query(url=url,
                                            headers=headers,
                                            verify=False)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            resource_groups = list(response.json())
        else:
            pass

        return resource_groups

    def get_resource_group_by_name(self, rg_name):
        resource_group = None

        # Craft the URL
        url = self.rest_session.base_url + self.resource_groups_url

        # Headers
        headers = self.rest_session.headers

        # Get Resource Groups - GET
        response = self.rest_call.get_query(url=url,
                                            headers=headers,
                                            verify=False)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            for rg in list(response.json()):
                if rg["name"] == rg_name:
                    resource_group = rg
                    break
        else:
            pass

        return resource_group

    def remove_resource_group_by_name(self, rg_name):
        is_deleted = False

        rg = self.get_resource_group_by_name(rg_name)

        if rg is not None:
            # Craft the URL
            url = self.rest_session.base_url + self.resource_group_url + self.sep_url + str(
                rg["id"])

            # Headers
            headers = self.rest_session.headers

            # Delete Resource Groups - DELETE
            response = self.rest_call.delete_query(url=url,
                                                   headers=headers,
                                                   verify=False)

            # Convert response to expected data
            if response.status_code == requests.codes.ok:
                is_deleted = True
            else:
                pass
        else:
            pass

        return is_deleted

    def create_ip_pool(self, ip_pool):
        ip_pool_id = None

        # Craft the URL
        url = self.rest_session.base_url + self.ip_pool_url

        # Data
        data = json.dumps(ip_pool)

        # Headers
        headers = self.rest_session.headers

        # Create IP Pool - POST
        response = self.rest_call.post_query(url=url,
                                             headers=headers,
                                             data=data,
                                             verify=False)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            ip_pool_id = int(response.text)
        else:
            pass

        return ip_pool_id

    def get_ip_pools(self, infra_id):
        ip_pools = []

        # Craft the URL
        url = self.rest_session.base_url + str(
            infra_id) + self.sep_url + self.ip_pool_url

        # Headers
        headers = self.rest_session.headers

        # Get IP Pools - GET
        response = self.rest_call.get_query(url=url,
                                            headers=headers,
                                            verify=False)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            ip_pools = list(response.json())
        else:
            pass

        return ip_pools

    def get_ip_pool_by_name(self, infra_id, ip_pool_name):
        ip_pools = self.get_ip_pools(infra_id)

        for ip_pool in ip_pools:
            if ip_pool["name"] == ip_pool_name:
                return ip_pool
            else:
                continue

        return None

    def delete_ip_pool_by_name(self, infra_id, ip_pool_name):
        is_deleted = False

        ip_pools = self.get_ip_pools(infra_id)

        ip_pool_id = None

        for ip_pool in ip_pools:
            if ip_pool["name"] == ip_pool_name:
                ip_pool_id = ip_pool["id"]
                break
            else:
                continue

        if ip_pool_id is not None:
            # Craft URL
            url = self.rest_session.base_url + self.ip_pool_url + self.sep_url + str(
                ip_pool_id)

            # Headers
            headers = self.rest_session.headers

            # Delete IP Pool - DELETE
            response = self.rest_call.delete_query(url=url,
                                                   headers=headers,
                                                   verify=False)
            # Convert response to expected data
            if response.status_code == requests.codes.ok:
                is_deleted = True
            else:
                pass
        else:
            # NOOP
            pass

        return is_deleted
Esempio n. 9
0
class Malware(object):
    def __init__(self, rest_session):
        # singleton logger
        self.logger = CustomLogger().get_logger()

        # REST Session
        self.rest_session = rest_session

        # Common REST Calls
        self.rest_call = RestCall(rest_session)

        # URLs - Malware
        self.malware_url = "policy/malwarepolicy"
        self.malware_engines_config_url = "manage/malwareenginesconfig"

    def get_policies(self):
        # Malware Policies
        policies = None

        # Craft the URL
        url = self.rest_session.base_url + self.malware_url

        # Headers
        headers = self.rest_session.headers

        # List Policies - GET
        response = self.rest_call.get_query(url=url,
                                            headers=headers,
                                            verify=False)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            policies = list(response.json())
        else:
            pass

        return policies

    def get_policy_by_name(self, policy_name):
        # Malware Policy
        malware_policy = None

        # Craft the URL
        url = self.rest_session.base_url + self.malware_url

        # Headers
        headers = self.rest_session.headers

        # List Policies - GET
        response = self.rest_call.get_query(url=url,
                                            headers=headers,
                                            verify=False)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            policies = list(response.json())

            for policy in policies:
                if policy_name == policy["name"]:
                    malware_policy = policy
                    break
                else:
                    continue
        else:
            pass

        return malware_policy

    def get_policy_by_id(self, policy_id):
        # Malware Policy
        malware_policy = None

        # Craft the URL
        url = self.rest_session.base_url + self.malware_url

        # Headers
        headers = self.rest_session.headers

        # List Policies - GET
        response = self.rest_call.get_query(url=url,
                                            headers=headers,
                                            verify=False)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            policies = list(response.json())

            for policy in policies:
                if policy_id == policy["id"]:
                    malware_policy = policy
                    break
                else:
                    continue
        else:
            pass

        return malware_policy

    def set_malware_config(self, malware_config):
        # Action
        is_updated = False

        # Craft the URL
        url = self.rest_session.base_url + self.malware_engines_config_url

        # Headers
        headers = self.rest_session.headers

        # Payload
        data = json.dumps(malware_config)

        # Update ACL - PUT
        response = self.rest_call.put_query(url=url,
                                            headers=headers,
                                            data=data,
                                            verify=False)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            is_updated = True
        else:
            pass

        return is_updated

    def create_policy(self, policy):
        # Policy ID
        policy_id = 0

        # Craft the URL
        url = self.rest_session.base_url + self.malware_url

        # Headers
        headers = self.rest_session.headers

        # Data
        data = json.dumps(policy)

        # Create malware policy - POST
        response = self.rest_call.post_query(url=url,
                                             headers=headers,
                                             data=data,
                                             verify=False)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            policy_id = int(response.json())
        else:
            pass

        return policy_id

    def update_policy(self, policy):
        # Policy ID
        policy_id = 0

        # Craft the URL
        url = self.rest_session.base_url + self.malware_url

        # Headers
        headers = self.rest_session.headers

        # Data
        data = json.dumps(policy)

        # Update malware policy - PUT
        response = self.rest_call.put_query(url=url,
                                            headers=headers,
                                            data=data,
                                            verify=False)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            policy_id = int(response.json())
        else:
            pass

        return policy_id

    def delete_policy(self, policy_id):
        # Action
        is_deleted = False

        # Craft the URL
        url = self.rest_session.base_url + self.malware_url + "/" + str(
            policy_id)

        # Headers
        headers = self.rest_session.headers

        # Delete malware policy - DELETE
        response = self.rest_call.delete_query(url=url,
                                               headers=headers,
                                               verify=False)

        # Convert response to expected data
        if response.status_code == requests.codes.ok:
            is_deleted = True
        else:
            pass

        return is_deleted
Esempio n. 10
0
class DataplaneManagement(object):
    def __init__(self, rest_session):
        # singleton logger
        self.logger = CustomLogger().get_logger()

        # fetched data
        self.data = None

        # REST Session
        self.rest_session = rest_session

        # Common REST Calls
        self.rest_call = RestCall(rest_session)

        # URLs specific to Resource group and Network set
        self.chassis_list_url = "chassislist"
        self.chassis_redeploy_id = "chassis/"
        self.network_set_insertionstaging_elements = "chassis/insertionstagingelements"
        self.network_set_chassis_bulkinsertion = "chassisbulkinsertion"

    def get_chassis_list(self):
        dp_list = None

        # Craft the URL
        url = self.rest_session.base_url + self.chassis_list_url

        # Headers
        headers = self.rest_session.headers

        # Call REST - GET
        response = self.rest_call.get_query(url=url,
                                            verify=False,
                                            headers=headers)
        dp_list = list(response.json())
        return dp_list

    def get_redeploy_chassisid(self, dp_id):
        job_id = None

        chassisid = str(dp_id)

        # Craft the URL
        url = self.rest_session.base_url + self.chassis_redeploy_id + chassisid + "/redeploy"

        # Headers
        headers = self.rest_session.headers

        # Call REST - GET
        response = self.rest_call.get_query(url=url,
                                            verify=False,
                                            headers=headers)
        job_id = response.json()
        return job_id

    def ns_insertionstaging_elements(self, ns_id, nsname, chassis_id,
                                     insertion_type):
        ns_staged = False
        insert_type = insertion_type.upper()

        payload = [{
            "id": 19,
            "name": "NSET-1-PG63-200",
            "infraId": 1,
            "type": "NETWORK_SET",
            "chassisSubscriptionMap": {
                "2": {
                    "subscription": {
                        "chassisId": 2,
                        "insertable": True,
                        "insertionType": "SEGMENTATION",
                        "markForDeletion": False,
                        "precedence": 1,
                        "resourceGroupId": 19
                    }
                }
            },
            "status": "STAGING",
            "action": "EDIT"
        }]

        for i in payload:
            if i["type"] == "NETWORK_SET":
                i["id"] = ns_id
                i["name"] = nsname
                i["chassisSubscriptionMap"]["2"]["subscription"][
                    "chassisId"] = chassis_id
                i["chassisSubscriptionMap"]["2"]["subscription"][
                    "insertionType"] = insert_type
                i["chassisSubscriptionMap"]["2"]["subscription"][
                    "resourceGroupId"] = ns_id
                data = json.dumps(payload)

        try:
            # Craft the URL
            url = self.rest_session.base_url + self.network_set_insertionstaging_elements

            # Headers
            headers = self.rest_session.headers

            # Call REST - PUT
            response = self.rest_call.put_query(url=url,
                                                headers=headers,
                                                verify=False,
                                                data=data)

            if response.status_code == requests.codes.ok:
                ns_staged = True
                self.logger.info("New network set staged for insertion")
            else:
                self.logger.error(response.status_code)
        except Exception as e:
            self.logger.error(e)
        return ns_staged

    def ns_chassis_bulkinsertion(self, ns_id, chassis_id, insertion_type):
        ns_insert = False
        insert_type = insertion_type.upper()

        payload = [{
            "id": 22,
            "action": "EDIT",
            "infraId": 1,
            "status": "STAGING",
            "type": "NETWORK_SET",
            "chassisSubscriptionMap": {
                "2": {
                    "subscription": {
                        "chassisId": 2,
                        "insertable": True,
                        "insertionType": "SEGMENTATION",
                        "markForDeletion": False,
                        "precedence": 1,
                        "resourceGroupId": 22
                    }
                }
            }
        }]

        for i in payload:
            if i["type"] == "NETWORK_SET":
                i["id"] = ns_id
                i["chassisSubscriptionMap"]["2"]["subscription"][
                    "chassisId"] = chassis_id
                i["chassisSubscriptionMap"]["2"]["subscription"][
                    "insertionType"] = insert_type
                i["chassisSubscriptionMap"]["2"]["subscription"][
                    "resourceGroupId"] = ns_id
                data = json.dumps(payload)
        try:
            # Craft the URL
            url = self.rest_session.base_url + self.network_set_chassis_bulkinsertion

            # Headers
            headers = self.rest_session.headers

            # Call REST - PUT
            response = self.rest_call.put_query(url=url,
                                                headers=headers,
                                                verify=False,
                                                data=data)

            if response.status_code == requests.codes.ok:
                ns_insert = True
                self.logger.info("New network set submitted for insertion")
                ns_jid = list(response.json())
                for nsjid in ns_jid:
                    if nsjid["type"] == 'NETWORK_SET':
                        ns_jobid = int(
                            nsjid["chassisSubscriptionMap"]["2"]["jobId"])
            else:
                self.logger.error(response.status_code)
        except Exception as e:
            self.logger.error(e)

        return ns_jobid