Esempio n. 1
0
    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 = "/"
Esempio n. 2
0
    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)

        # Test Info
        self.test_id = None
        self.test_iteration = None
        self.model_name = None

        # URLs specific to Breaking Point
        self.ports_url = "bps/ports"
        self.reserve_ports_url = "bps/ports/operations/reserve"
        self.unreserve_ports_url = "bps/ports/operations/unreserve"
        self.chassis_config_url = "bps/ports/chassisconfig"
        self.change_card_config_url = "bps/ports/operations/changecardconfig"
        self.reboot_card_url = "bps/ports/operations/rebootcard"
        self.running_tests_url = "bps/tests"
        self.start_test_url = "bps/tests/operations/start"
        self.stop_test_url = "bps/tests/operations/stop"
        self.get_rts_url = "bps/tests/operations/getrts"
        self.result = "bps/tests/operations/getrts"

        # Breaking Point constants
        self.TEST_COMPLETE = 100.0 # 100% complete
        self.BETWEEN_CHECKS = 1 * 60 # period for checking the stats

        self.RAMP_UP = 20.0 # Ramp up
        self.RAMP_DOWN = 80.0 # Ramp down
Esempio n. 3
0
    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'
Esempio n. 4
0
    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 = "/"
Esempio n. 5
0
    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.audit_log_url = "logs/audit"
Esempio n. 6
0
    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"
Esempio n. 7
0
    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 Whitelist
        self.whitelist_url = "accesscontrol/whitelistedips"
        self.export_listed_ip_url = "accesscontrol/export/whitelist"
Esempio n. 8
0
    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}"
Esempio n. 9
0
    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 Jobs API
        self.jobs_url = "jobs/"
Esempio n. 10
0
    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 - Resource Groups
        self.resource_group_url = "infras/resourcegroups"

        # URL separator
        self.sep_url = "/"
Esempio n. 11
0
    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.dataplane_url = "chassis"

        # URL separator
        self.sep_url = "/"
Esempio n. 12
0
    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}"
Esempio n. 13
0
    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.nodes_info_url = "sxquery/_nodes"
        self.multi_search_url = "sxquery/_msearch"

        # Spare separator
        self.sep_url = "/"
Esempio n. 14
0
    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.resource_group_create_url = "infras/resourcegroup"
        self.network_set_create_url = "infras/networkset"
Esempio n. 15
0
    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"
Esempio n. 16
0
    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"
Esempio n. 17
0
    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 = "/"
Esempio n. 18
0
    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"
Esempio n. 19
0
class ResourceGroup(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 - Resource Groups
        self.resource_group_url = "infras/resourcegroups"

        # URL separator
        self.sep_url = "/"

    def list_resource_groups(self):
        # Resource Groups
        resource_groups = None

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

        # Headers
        headers = self.rest_session.headers

        # Get Resource Group 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:
            resource_groups = list(response.json())
        else:
            # Empty list
            pass

        return resource_groups
Esempio n. 20
0
class AuditLog(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.audit_log_url = "logs/audit"

    def get_audit_log(self, query=None):
        # Audit Log
        audit_log = []

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

        # Headers
        headers = self.rest_session.headers

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

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

        return audit_log
Esempio n. 21
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. 22
0
class JobsApis(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 Jobs API
        self.jobs_url = "jobs/"

    def get_jobs(self):
        # Jobs
        jobs = []

        # Craft the URL
        url = self.rest_session.base_url + self.jobs_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
        jobs = list(response.json())

        return jobs

    def get_job_by_id(self, job_id):
        # Job
        job = None

        # Craft the URL
        url = self.rest_session.base_url + self.jobs_url + str(job_id)

        # 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
        job = dict(response.json())

        return job

    def wait_on_job_by_id(self, job_id):
        job_completed = False

        try:
            # Craft the URL
            url = self.rest_session.base_url + self.jobs_url + str(
                job_id) + "/wait"

            # 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:
                job_completed = True
                self.logger.info("Job completed successfully")
            else:
                self.logger.error(response.status_code)
        except Exception as e:
            self.logger.error(e)

        return job_completed

    def get_tasks_by_job_id(self, job_id):
        # Tasks
        tasks = []

        # Craft the URL
        url = self.rest_session.base_url + self.jobs_url + str(
            job_id) + "/tasks"

        # Headers
        headers = self.rest_session.headers

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

        tasks = list(response.json())

        return tasks

    def abort_job_by_id(self, job_id):
        is_job_aborted = False

        try:
            # Craft the URL
            url = self.rest_session.base_url + self.jobs_url + str(
                job_id) + "/abort"

            # Headers
            headers = self.rest_session.headers

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

            if response.status_code == requests.codes.ok:
                is_job_aborted = True
                self.logger.info("Job aborted successfully")
            else:
                self.logger.error(response.status_code)
        except Exception as e:
            self.logger.error(e)

        return is_job_aborted
Esempio n. 23
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. 24
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. 25
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. 26
0
class ElasticSearch(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.nodes_info_url = "sxquery/_nodes"
        self.multi_search_url = "sxquery/_msearch"

        # Spare separator
        self.sep_url = "/"

    def get_nodes_info(self):
        # Nodes Info
        nodes_info = None

        try:
            # Craft the URL
            url = self.rest_session.base_url + self.nodes_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
            nodes_info = response.json()
        except Exception as e:
            self.logger.error(e)

        return nodes_info

    def multi_search_query(self, data):
        # Query result
        query_result = None

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

            # Headers
            headers = self.rest_session.headers

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

            # Convert response to expected data
            query_result = response.json()
        except Exception as e:
            self.logger.error(e)

        return query_result

    def get_ms_timstamp(self):
        return int(round(time.time()) * 1000)
Esempio n. 27
0
class GroupandInsert(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.resource_group_create_url = "infras/resourcegroup"
        self.network_set_create_url = "infras/networkset"

    def rgany_vmname_noinsertion(self, rname, regexpr, descrip):
        rg_created = False
        rgid = None

        payload = [{
            "infraIDs": [0],
            "dynamic": True,
            "id": 0,
            "name": "RG-WL-2",
            "regex": "name='tony-frog-WL-4';",
            "resourceType": "VM",
            "description": "RG-2",
            "purpose": "INSERTION_AND_POLICY"
        }]
        for i in payload:
            if i["infraIDs"] == [0]:
                i["name"] = rname
                i["regex"] = regexpr
                i["description"] = descrip
                data = json.dumps(payload)
                data = str(data)[1:-1]
        try:
            # Craft the URL
            url = self.rest_session.base_url + self.resource_group_create_url

            # Headers
            headers = self.rest_session.headers

            # Call REST - POST
            response = self.rest_call.post_query(url=url,
                                                 headers=headers,
                                                 verify=False,
                                                 data=data)
            if response.status_code == requests.codes.ok:
                rgid = list(response.json())
                rgid = rgid[0]
                rg_created = True
                self.logger.info("New resource group added")
            else:
                self.logger.error(response.status_code)
        except Exception as e:
            self.logger.error(e)

        return rgid

    def nset_create_noinsertion(self, rname, regexpr, descrip):
        ns_created = False
        nsid = None

        payload = [{
            "cloudId": 1,
            "id": 0,
            "name": "NSET-1-PG63-2",
            "regex": "ic='1';.*name='tony-PG63-2';",
            "description": "NSET-1-PG63-2",
            "isExclusion": False
        }]

        for i in payload:
            if i["cloudId"] == 1:
                i["name"] = rname
                i["regex"] = regexpr
                i["description"] = descrip
                data = json.dumps(payload)
                data = str(data)[1:-1]
        try:
            # Craft the URL
            url = self.rest_session.base_url + self.network_set_create_url

            # Headers
            headers = self.rest_session.headers

            # Call REST - POST
            response = self.rest_call.post_query(url=url,
                                                 headers=headers,
                                                 verify=False,
                                                 data=data)
            if response.status_code == requests.codes.ok:
                nsid = list(response.json())
                nsid = nsid[0]
                ns_created = True
                self.logger.info("New network set added")
            else:
                self.logger.error(response.status_code)
        except Exception as e:
            self.logger.error(e)

        return nsid
Esempio n. 28
0
class Whitelist(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 Whitelist
        self.whitelist_url = "accesscontrol/whitelistedips"
        self.export_listed_ip_url = "accesscontrol/export/whitelist"

    def get_ip_whitelist(self):
        # Whitelists
        whitelists = None

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

        # Headers
        headers = self.rest_session.headers

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

        # Sample: {"cidr": 0, "sumtotal": 0, "ipv4": 0, "ipv6": 0}
        whitelists = dict(response.json())

        return whitelists

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

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

        # Headers
        headers = self.rest_session.headers

        # Payload
        data = json.dumps({
            "whitelistPeriod": whitelist_period,
            "iplist": [whitelist]
        })

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

        # 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
        # IP Whitelist
        ip_whitelist = None

        # 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_whitelist = response.text
            is_exported = True
        else:
            is_exported = False

        try:
            if export_file is not None:
                with open(export_file, "w") as txt_file:
                    txt_file.write(ip_whitelist)
            else:
                self.logger.error(
                    "Export file is not specified or export request failed.")
        except Exception as e:
            self.logger.error("Export whitelist failed.")
            self.logger.error(e)

        return is_exported
Esempio n. 29
0
class DeploymentManagement(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.dataplane_url = "chassis"

        # URL separator
        self.sep_url = "/"

    def create_deployment(self, deployment_info):
        # Deployment ID
        deployment_id = None

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

        # Headers
        headers = self.rest_session.headers

        # Data
        data = json.dumps(deployment_info)

        # Create Deployment - 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:
            deployment = dict(response.json())
            deployment_id = deployment["id"]
        else:
            pass

        return deployment_id

    def delete_deployment(self, deployment_id):
        forced = 0

        # Craft the URL
        url = self.rest_session.base_url + self.infras_url + self.sep_url + str(
            deployment_id) + self.sep_url + str(forced)

        # Headers
        headers = self.rest_session.headers

        # Delete Deployment - 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
Esempio n. 30
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