Exemple #1
0
    def va_unconfig_deceptionserver(self, server=None, commit=None):
        """
            API to unconfig  darknet policy
            param    :
                pname : darknet policy name
                pcommit : commit flag set
            example  : va_unconfig_darknet('darknet1')
            return   : True/False
        """
        logger.info("We are in ::" + sys._getframe().f_code.co_name)
        if not server:
            raise ValueError(" Policy name is mandatory for setting policy")
        cmd = []
        cmd.append('unset deception server %s' % (server))
        logger.info('Unconfiguring the darknet policy' + str(cmd))
        if commit:
            cmd.append('commit')
        logger.info("Now commiting the configs")

        logger.info('Unconfiguring the deception server' + str(cmd))
        config_status, output = self._access.va_config(cmd)
        logger.info("the commit status :" + str(config_status) + str(output))
        cmd = 'show running | grep \"deception server\"'
        logger.info("Executing show command" + str(cmd))
        cmdkey = 'set deception server ' + str(server)
        routput = self._access.va_cli(cmd)
        logger.info("the execution status :" + str(routput))
        logger.debug('Command key to check in running config' + cmdkey)
        if str(cmdkey) in routput:
            logger.error('The config not removed from running configs' +
                         str(cmd))
            return False, routput
        logger.debug(
            'The given deception server is removed from running configs')
        return config_status, output
Exemple #2
0
    def va_clear_session(self):
        """
        API to clear session
        param      : None
        example    : va_clear_session()
        returns:
            :True|False (bool): True if success else False
        """
        logger.info("\nIn subroutine: " + sys._getframe().f_code.co_name)
        times = 1
        sleeptime = 2
        self._access.va_cli('clear session')
        session = self.va_get_session('is_fail')
        pattern = re.compile(r'((\d+\.){3}\d+)')
        while pattern.search(session) is not None and times <= 6:
            time.sleep(sleeptime)
            logger.debug('Retry {} times to clear session'.format(times))
            self._access.va_cli('clear session')
            session = self.va_get_session('is_fail')
            times += 1

        if pattern.search(session) is not None:
            logger.error("Session can't be cleared")
            return False

        logger.info('Session are cleared')
        return True
Exemple #3
0
    def va_check_session_packets_increment(self, session_before, session_after, 
        *args, **kwargs):
        """
        API to check if packets counter of data session increase
        param     : 'session_before', should be single data session before increment
                    'session_after', should be single data session after increment
                }    
        example :
                    va_check_session_packets_increment(session_before, session_after)
        returns:
            :True|False (bool): True on success, False on failure
        """
        logger.info("\nIn subroutine: " + sys._getframe().f_code.co_name)
        in_packets_before  = int(session_before.get('in_packets'))
        in_packets_after   = int(session_after.get('in_packets'))
        out_packets_before = int(session_before.get('out_packets'))
        out_packets_after  = int(session_after.get('out_packets'))
        if in_packets_before > in_packets_after or \
            out_packets_before > out_packets_after:
            logger.debug('In_packets:  {}, {}'.format(in_packets_before, in_packets_after))
            logger.debug('Out_packets: {}, {}'.format(out_packets_before, out_packets_after))
            logger.error('Packet counter of data session is not increasing!')
            return False

        logger.info('Packet counter of data session is increasing.')
        return True
Exemple #4
0
    def _va_parse_app_profile(self, output=None):
        """
        Parse the Output of show policy and check the given app profile
        is associated with policy

        :param output:

        :return:
        """
        logger.info("We are in ::" + sys._getframe().f_code.co_name)
        if not output:
            logger.error(" The output is empty string and \
            nothing to verify")
            return False
        logger.debug(" The output :")
        parsed = list()

        for line in output.splitlines()[1:]:
            line = line.strip()
            if not line.startswith('index') and \
                    not line.startswith('=') and \
                    not line.startswith('Total'):
                parsed.append(line.split())
        logger.info(parsed)
        return parsed
Exemple #5
0
    def va_unconfig_global_applog(self, application=None, port=None,
                               commit=None):
        '''
        API to configure global applog

        :param application:
        :param port:
        :param commit:
        :return:
        '''
        logger.info('We are in ::' + sys._getframe().f_code.co_name)
        if not application:
            return False, 'Application name is mandotory'
        if port:
            cmd = 'unset system app-log %s port %s' %(application, port)
        else:
            cmd = 'unset system app-log %s' %(application)
        if commit :
            cmd.append('commit')
        config_status, output = self._access.va_config(cmd)
        logger.debug('UnConfiguration of Global APPLOG : ' + str(config_status) + str(output))

        if config_status is False:
            logger.error('Global APPLOG Configuration/commit FAILED')
            return False, output
        else:
            logger.info('Global APPLOG Configuration/commit is successful')
            print('Configuration of GLOBAL APPLOG: ', config_status, output)
            return True, output
Exemple #6
0
    def va_install_image(self, image, **kwargs ):
        """
        Install image

        Arguments:
            :image (str): Software image name
            :kwargs (dict) :
                'install_os'    :  primary/secondary
                'install_delay' : time of install image
        returns:
            :False: Failed to install image.
            :True: Succeed to install image.

        Examples:
            va_install_image('image-file.tar')
            va_install_image('image-file.tar',\
                {'install_os':'primary','install_delay':200})
        """
        if not 'install_os' in kwargs:
            install_os = 'primary'
        else :
            install_os = kwargs['install_os']

        if not 'install_delay' in kwargs:
            install_delay = 300
        else :
            install_delay = kwargs['install_delay']

        if not 'reboot_delay' in kwargs:
            reboot_delay = 120
        else:
            reboot_delay = kwargs['reboot_delay']

        logger.info('install delay is {}'.format(install_delay))
        self._access.va_cli("request install software {} {}"\
                            .format(image, install_os),install_delay)

        #check the status of install firmeare
        if not self.va_check_install_status_for_ep_or_cp():
            return False

        if not self.va_check_install_status_for_epi() :
            return False

        logger.debug("Change boot-sector to %s" % install_os)
        self._access.va_cli("request system boot-sector {}" .format(install_os))
        time.sleep(30)

        logger.info("**************Completed install image to all devices************")
        return True
Exemple #7
0
    def _va_parse_show_session(self, output=None):
        """
        Parse the Output of show policy and check the given
        app profile is associated with policy

        :param output:

        :return:
        """
        logger.info("We are in ::" + sys._getframe().f_code.co_name)
        if not output:
            logger.error(" The output is empty string and \
            nothing to verify")
            return False
        logger.debug(" The \"show session\" output :")
Exemple #8
0
    def va_deceptionserver_enabled(self, server=None):
        """
            API to check given Deception server enabled?

        """
        logger.info("We are in ::" + sys._getframe().f_code.co_name)
        if not server:
            raise ValueError(" Deception server name is\
             mandatory for setting policy")
        cmd = "show deception server {}".format(server)
        logger.info("Executing show command ->" + str(cmd))
        cstatus = self._access.va_cli(cmd)
        logger.info("the execution status :" + str(cstatus))
        if 'enable' in str(cstatus):
            logger.debug('The given Deception Server is enabled')
            return True, cstatus
        else:
            logger.error('Given Deception Server  is NOT enabled')
            return False, cstatus
Exemple #9
0
    def va_globalapplog_conf_in_running(self, config=None):
        """

        :param config:
        :return:   True if it is enabled
                   False if not
        """
        logger.info("We are in ::" + sys._getframe().f_code.co_name)
        if not config:
            raise ValueError(" Policy name is mandatory for setting policy")
        cmd = 'show running | grep \"set system app-log\" '
        logger.info("Executing show command : " + str(cmd))
        routput = self._access.va_cli(cmd)
        logger.info("the execution status : " + str(routput))
        for i in config:
            if i not in routput:
                logger.error('The command is not in running configs: ' + i)
                return False, routput
        logger.debug('The command is available in running configs :' + i)
        return True, routput
Exemple #10
0
    def va_disable_deceptionserver(self, server=None, commit=None):
        '''
        API to disable the deception server
        In this case the policy will not be deleted, just disabled state
        :param data:
        :param args:
        :param kwargs:
        :return:
        '''
        logger.info("We are in ::" + sys._getframe().f_code.co_name)

        if not server:
            raise ValueError(" Policy name is mandatory for setting policy")

        logger.debug('data1........ in darknet,' + str(data1))
        cmds = []

        cmds.append('set deception server %s disable' % data1['name'])
        if commit:
            cmds.append('commit')
        logger.info('Darknet command :' + str(cmds))

        config_status, output = self._access.va_config(cmds)
        logger.debug('Configuration of Deception disable: {} :: \
                {} '.format(config_status, output))

        if config_status is False:
            logger.error('Configuration/commit FAILED')
            return False, output
        else:
            logger.info('Configuration and commit is successful')
            logger.debug('Configuration of DARKNET: {} \
            :: {} '.format(config_status, output))
            return True, output
Exemple #11
0
 def va_darknet_enabled(self, pname=None):
     """
         API to check given darknet policy enabled?
         param    :
             pname : darknet policy name
             Check given policy is enabled or not.
         example  : va_darknet_enabled('darknet1')
         return   : True if it is enabled
                    False if not
     """
     logger.info("We are in ::" + sys._getframe().f_code.co_name)
     if not pname:
         raise ValueError(" Policy name is mandatory for setting policy")
     cmd = "show deception dark-net {}".format(pname)
     logger.info("Executing show command" + str(cmd))
     cstatus = self._access.va_cli(cmd)
     logger.info("the execution status :" + str(cstatus))
     if 'enable' in str(cstatus):
         logger.debug('The given DARKNET policy is enabled')
         return True, cstatus
     else:
         logger.error('Given DARKNET policy is NOT enabled')
         return False, cstatus
Exemple #12
0
 def va_deceptionserver_in_running(self, config=None):
     """
         API to check given darknet policy available in running configs
         param    :
             pname : darknet policy name
             Check given policy is available in running conf or not.
         example  : va_darknetconf_in_running('darknet1')
         return   : True if it is enabled
                    False if not
     """
     logger.info("We are in ::" + sys._getframe().f_code.co_name)
     if not config:
         raise ValueError(" Policy name is mandatory for setting policy")
     cmd = 'show running | grep deception server'
     logger.info("Executing show command" + str(cmd))
     output = self._access.va_cli(cmd)
     logger.info("the execution status :" + str(output))
     for i in config:
         if i not in output:
             logger.error('The command is not in running configs' + i)
             return False, output
     logger.debug('The given policy is available in running configs')
     return True, output
Exemple #13
0
    def va_unset_applog_profile(self, app_log_name=None,
                           app_log_commit=None):
        '''

        :param app_log_name:
        :param app_log_commit:
        :return:
                   complete command if commit is not passed
            Else : True  on success of configuration on DUT

        Raises:
            :AddressValueError: if invalid address is provided
            :NetmaskValueError: if invalid mask is provided
            :ParamRequired: if interface is not provided
        '''

        logger.info("We are in ::" + sys._getframe().f_code.co_name)

        mandatory = [app_log_name]

        for param in mandatory:
            if not param:
                pass
                # TODO: raise ValueError
                raise ValueError(" The app profile parameter is not provided, \
                    This is mandetory Argument\n")
        cmd = []
        cmd.append('unset profile app-log {} '.format(app_log_name))
        logger.debug('APPLOG command :' + str(cmd))

        if app_log_commit:
            cmd.append('commit')

        config_status, output = self._access.va_config(cmd)
        logger.debug('commit status' + str(config_status) + str(output))
        return config_status, output
Exemple #14
0
    def va_disable_darknet(self, data, *args, **kwargs):
        '''
        API to disable the darknet policy
        In this case the policy will not be deleted, just disabled state
        :param data:
         Where Data is the dictionary with darknet policy details as 
         shown below:
           data = {
                 'name': 'darknet policy name',
                  'iscommit': ' commit it or not'
           }
        :param args:
        :param kwargs:
        :return:
        '''
        logger.info("We are in ::" + sys._getframe().f_code.co_name)

        data1 = copy.deepcopy(data)

        if 'name' not in data1:
            data1['name'] = 'darknet_new1'
        if 'iscommit' not in data1:
            data1['iscommit'] = 'ON'

        logger.debug('data1........ in darknet,' + str(data1))
        cmds = []

        cmds.append('unset deception dark-net %s enable' % data1['name'])
        if data1['iscommit'] == 'ON':
            cmds.append('commit')
        logger.info('Darknet command :' + str(cmds))

        config_status, output = self._access.va_config(cmds)
        logger.debug('Configuration of DARKNET: {} :: {} '.format(
            config_status, output))

        if config_status is False:
            logger.error('Configuration/commit FAILED')
            return False, output
        else:
            logger.info('Configuration and commit is successful')
            logger.debug('Configuration of DARKNET: {} :: {} '.format(
                config_status, output))
            return True, output
Exemple #15
0
    def va_set_applog_profile(self, app_log_name=None, app_log_rule=None,
                           app_log_application=None, app_log_context=None,
                           app_log_filter=None, app_log_modifier=None,
                           app_log_commit=None):
        """
        :param app_log_name: Profile name
        :param app_log_rule: Matching rule name
        :param app_log_application: Supported Application name
        :param app_log_context: Attribute for provided application
        :param app_log_filter: String to match the context
        :param app_log_modifier: Modifier string (Optional)
        :param app_log_commit: string, will configure on DUT if it is passed

        :return:  complete command if commit is not passed
                  Else : True  on success of configuration on DUT

        Raises:
            :AddressValueError: if invalid address is provided
            :NetmaskValueError: if invalid mask is provided
            :ParamRequired: if interface is not provided
        """
        logger.info("We are in ::" + sys._getframe().f_code.co_name)

        mandatory = [app_log_name, app_log_rule, app_log_application,
                     app_log_context, app_log_filter]

        for param in mandatory:
            if not param:
                pass
                # TODO: raise ValueError
                raise ValueError(" The app profile parameter is not provided, \
                    This is mandetory Argument\n")
        cmd = []
        if app_log_modifier:
            cmd.append('set profile app-log {} rule {} application {} context {}  '
                       'filter {} modifier {}'.format(app_log_name, app_log_rule,
                                                 app_log_application,
                                                 app_log_context,
                                                 app_log_filter,
                                                 app_log_modifier))
            logger.debug('APPLOG command :' + str(cmd))
        else:
            cmd.append('set profile app-log {} rule {} application {} context {} '
                       'filter {} '.format(app_log_name, app_log_rule, app_log_application,
                               app_log_context, app_log_filter))
            logger.debug('APPLOG command :' + str(cmd))

        if app_log_commit:
            cmd.append('commit')

        config_status, output = self._access.va_config(cmd)
        logger.debug('commit status' + str(config_status) + str(output))
        gcmd = 'show running | grep \"set profile app-log\" '
        logger.info("Executing show command : " + str(gcmd))
        routput = self._access.va_cli(gcmd)
        logger.info("the execution status : " + str(routput))
        for i in cmd:
            if i not in routput:
                logger.error('The command is not in running configs: ' + i)
                return False, routput
        logger.debug('The command is available in running configs :' + i)
        return config_status, output
Exemple #16
0
    def va_verify_app_log(self, policy_name=None, app_log_profile_name=None,
                       policy_template=None):
        """

        :param policy_name:
        :param app_log_profile_name:
        :param policy_template:

        :return: True if app-log profile is associated with policy else False
        """
        logger.info("We are in ::" + sys._getframe().f_code.co_name)

        mandatory = [app_log_profile_name]

        if not policy_template:
            policy_template = "policy_template"

        for param in mandatory:
            if not param:
                # TODO: raise ValueError
                raise ValueError(" The app profile parameter is not provided, \
                 This is mandetory Argument\n")

        if policy_name:
            cmd = "show policy name {}".format(policy_name)
        else:
            cmd = "show policy"

        output = self._access.exec_command(cmd)

        logger.info("TextFSM parsing POC")
        policy_template = open(policy_template)
        policy_table = jtextfsm.TextFSM(policy_template)

        logger.debug("CLI OUTPUT :\n" + output + "\n\n\n\n")
        policy_fsm_results = policy_table.ParseText(output)

        # Results will be writen to output file
        outputfile_name = open("show_policy_output.csv", "w+")
        outfile = outputfile_name

        for s in policy_table.header:
            outfile.write("%s;" % s)
        outfile.write("\n")

        # Iterate for all the rows
        logger.info(" Here is the result parsed using TextFSM:")
        counter = 0
        for row in policy_fsm_results:
            logger.info(" Row :" + str(counter) + " columns :" + str(row))
            for s in row:
                outfile.write("%s;" % s)
            outfile.write("\n")
            counter += 1
        logger.info(" Number of records:" + str(counter))
        exit()

        # below code will do regular pattern matching
        parsed = self._va_parse_app_profile(output)
        logger.debug(parsed)
        for line in parsed:
            app_log_profile_name = app_log_profile_name
            if line[1] == policy_name and app_log_profile_name in line[8]:
                logger.info(" The profile is associated with policy")
                return True
            else:
                logger.error(" The app profile is not \
                associated with policy")
                return False
Exemple #17
0
    def va_get_active_device(self):
        """
        get the number of active devices of director and CP/EP

        kwargs: None

        returns:
            dict : {'active_devices': The number of active devices except EPI,
                    'active_epis': The number of active EPIs
                    }
        Examples:
            va_get_active_device()
        """
        count_dev = 0
        count_epis = 0
        return_value = {}

        chassis_info = self.controller.va_show_chassis()
        dev_status = chassis_info.get('devices status')
        total_dev_counts = dev_status.get('total devices connected')
        inactive_devs = dev_status.get('inactive devices')

        match_tol_act_devs = re.search(r'^(\d+)\s+\(',total_dev_counts, re.I | re.M)
        if match_tol_act_devs is not None:
            total_dev_count = match_tol_act_devs.group(1)
            if int(total_dev_count) != 0:
                logger.debug("The number of devices are %s" % total_dev_count)
            else:
                logger.warn("The number of total connected devices is incorrect")
        else:
            logger.error("Failed to get 'total devices connected' \
        information via 'show chassis'")

        match_rt = re.search(r'(\d+)\s+\(', inactive_devs, re.I|re.M)
        if match_rt is not None:
            inactive_dev_count = match_rt.group(1)
            if int(inactive_dev_count) == 0:
                logger.debug("No inactivate devices")
            else:
                logger.warn("The number of inactive device are %s" % inactive_dev_count)
        else:
            logger.error("Failed to get information of inactive device")

        #number of activate devices except EPI.
        count_dev = int(total_dev_count) - int(inactive_dev_count)
        return_value['active_devices'] = count_dev

        #get number of activate EPIs
        rt = self._access.va_cli('show chassis epi')
        match_rt = re.search(r'Total active EPIs:\s+(\d+)', rt, re.I | re.M)
        if match_rt is not None:
            count_epis = match_rt.group(1)
            if count_epis != 0:
                logger.debug("The number of EPIs are %s" % count_epis)
            else:
                logger.debug("No activate EPIs")
        else:
            logger.error("Failed to get information of EPIs")
        return_value['active_epis'] = count_epis

        return return_value
Exemple #18
0
    def va_config_darknet(self, data, *args, **kwargs):
        """
            API to config darknet policy
            param    :
                data1 = {
                     'name'       : 'Darknet policy name'
                     'epi'        : 'EPI UUID' or by default it is all
                     'segment'    : 'segment ID' or by default it is all
                     'from2address': pair address from and to
                     'isenable'   : 'enable' or by default yes
                     'is_commit"  : Commit pending configuration
            example  : va_config_darknet(data1)
            return   : True/False
        """
        logger.info("We are in ::" + sys._getframe().f_code.co_name)

        data1 = copy.deepcopy(data)

        if 'name' not in data1:
            data1['name'] = 'darknet_new1'
        if 'iscommit' not in data1:
            data1['iscommit'] = 'ON'
        if 'isenable' not in data1:
            data1['isenable'] = 'enable'
        if 'epi' not in data1:
            data1['epi'] = 'all'
        if 'segment' not in data1:
            data1['segment'] = 'all'

        logger.debug('data1........ in darknet,' + str(data1))
        cmds = []

        cmds.append('set deception dark-net %s epi %s segment %s' %
                    (data1['name'], data1['epi'], data1['segment']))

        darknetaddresses = data1['from2address']
        print('Length of from2address list :', len(data1['from2address']),
              darknetaddresses, darknetaddresses[0])
        if type(darknetaddresses) == str:
            cmds.append('set deception dark-net %s address %s to %s' %
                        (data1['name'], darknetaddresses, darknetaddresses))
        elif len(darknetaddresses) == 2 and type(darknetaddresses[0]) == str:
            cmds.append(
                'set deception dark-net %s address %s to %s' %
                (data1['name'], darknetaddresses[0], darknetaddresses[1]))
        else:
            logger.debug('THIS IS FOR MORE THAN ONE LIST')
            for e in darknetaddresses:
                print(' each element in darknet', e)
                if len(e) == 1:
                    cmds.append('set deception dark-net %s address %s to %s' %
                                (data1['name'], e[0], e[0]))
                else:
                    cmds.append('set deception dark-net %s address %s to %s' %
                                (data1['name'], e[0], e[1]))

        cmds.append('set deception dark-net %s %s' %
                    (data1['name'], data1['isenable']))
        logger.info('Darknet command :' + str(cmds))

        config_status, output = self._access.va_config(cmds)
        print('Configuration of DARKNET: ', config_status, output)

        if config_status is False:
            logger.error('Configuration/commit FAILED')
            return False, output
        else:
            logger.info('Configuration and commit is successful')
            print('Configuration of DARKNET: ', config_status, output)
            rstatus, output = self.va_darknetconf_in_running(cmds)
            return True, output
Exemple #19
0
    def va_get_data_session(self, *args, **kwargs):
        """
        API to get data session, not support multiple session at same time
    
        param     : kwargs : dict
            kwargs = {
                    'session' : session_val,
                    'proto'   : 'icmp' | 'ftp',
                    'policy'  : 'pol_test',
                    more parameters refer to _va_check_single_session,
                }    
        example :
                    va_get_session_id(**kwargs)
        return: a dict of session like this
        {'app': '--',
         'in_dst_ip': '5.5.5.3',
         'out_dst_ip': '5.5.5.3',
         'in_dst_port': '17436',
         'out_dst_port': '17436',
         'flag': '0x21c004a4',
         'id': '0x6020000000007c0',
         'in_intf': '603',
         'out_intf': '603',
         'in_micro_vlan': '1',
         'out_micro_vlan': '2',
         'in_packets': '1',
         'out_packets': '1',
         'policy': 'p1',
         'proto': '1',
         'segment': '20',
         'in_src_ip': '5.5.5.2',
         'out_src_ip': '5.5.5.2',
         'in_src_port': '61',
         'out_src_port': '61',
         'state': '-1--1',
         'time': '1',
         'vsys_id': '1',
        }
        """
        logger.info("\nIn subroutine: " + sys._getframe().f_code.co_name)

        if not 'session' in kwargs:
            session = self.va_get_session()
        else:
            session = kwargs.pop('session')

        if not 'proto' in kwargs:
            proto_name = 'ftp'
        else:
            proto_name = kwargs.pop('proto').split('-')[0]

        if proto_name in ['ftp', 'tftp']:
            f = lambda x,y:x!=y
        else:
            f = lambda x,y:x==y

        if not 'policy' in kwargs:
            kwargs['policy'] = "pol_test"

        port  = port_map.get(proto_name)
        kwargs['proto'] = proto_map.get(proto_name)
        session_stats = self._va_parse_session(session)

        data_session = dict()
        for device in session_stats:
            for active_sessions in session_stats.get(device):
                for session in active_sessions.get('sessions'):
                    match, no_matches, failed = self._va_check_single_session(kwargs, session)
                    in_dst_port = int(session.get('in_dst_port'))
                    logger.debug('Session    : \n{}'.format(session))
                    logger.debug('Matched    : {}'.format(match))
                    logger.debug('Not Matched: {}'.format(no_matches))
                    logger.debug('Failed     : {}'.format(failed))
                    if len(failed) != 0:
                        match = True
                        for name in failed:
                            failed_name  = str(kwargs.get(name))
                            session_name = session.values()
                            if failed_name not in session_name:
                                match = False
                        if not match:
                            logger.error('Not matched: {}, {}'.format(failed_name, session_name))
                    if match:
                        if f(in_dst_port, port):
                            data_session = session
                            break
                    else:
                        continue
        
        logger.info('Data session: {}'.format(data_session))
        return data_session
Exemple #20
0
    def va_verify_interface(self, *args, **kwargs):
        """
            Verify interface info,the API can supports physical interface and logical interfaces
            example is a part of parameter,the method supports verify the following:
                'packets sent','Interface index','Local address','Link address',
                'Security token','packets received',Vrouter','Logical interface',
                'bytes received',bytes sent','ospf','flags','Security zone',
                'Logical interface counters','Vrouter','MTU','Allowed in-bound traffic'
                'collisions','frame alignment errors','packets dropped by TX',
                'Current address','transmit errors','Link-level type',Link-mode,
                'Speed','Auto-negotiation','packets with RX overrun','Physical interface',
                'Native vlan id','Physical interface counters','packets with RX overrun',
                'CRC errors','packets dropped by RX','receive errors'

            Param   : kwargs : dict
                     kwargs = {
                                'name' (str)                 : expected to check interface name
                                'packets sent'(str)               : interface packets sent
                                'Interface index'(str)           : interface Interface index
                                'Local address'(str)              : interface local address
                                'Link address'(str)               : interface link address
                                'Security token'(str)             : interface security token
                                'packets received'(str)           : interface packets received
                                'Vrouter'(str)                    : interface vrouter
                                'Logical interface'(str)          : logical interface
                                'bytes received'(str)             : interface bytes received
                                'bytes sent'(str)                 : interface bytes sent
                                'ospf'(str)                       : interface ospf
                                'flags'(str)                      : interface flags
                                'Security zone'(str)              : security zone
                                'Logical interface counters'(str) : logical interface counters
                                'MTU'(str)                        : interface MTU
                                'Allowed in-bound traffic'(str)   : allowed in-bound traffic                                
                            }

            Return  : boolean
                True
                False

            Example     : va_verify_interface(**kwargs)
                         kwargs = {
                                    'name':'xe-3/0/1.1',
                                    'Local address': '10.11.120.46/24',
                                    'Allowed in-bound traffic': '',
                                    'packets sent': '0',
                                    'packets received': '0',
                                    'Security token': '0x000000',
                                    'MTU': '1500',
                                    'flags': '0x0',
                                    'Security zone': 'Null',
                                    'ospf': 'OSPF is not configured',
                                    'bytes received': '0',
                                    'Vrouter': 'vr-default',
                                    'Interface index': '0x801001',
                                    'Logical interface counters': '',
                                    'bytes sent': '0',
                                    'Link address': '0.0.0.0/0',
                                    'Logical interface': 'xe-3/0/1.1, Enabled, Physical link is Up'
                                }
        """
        logger.info("\nIn subroutine: " + sys._getframe().f_code.co_name)

        interface_info_dict = {}
        error_value = []

        if 'name' not in kwargs:
            raise ValueError("name is mandatory parameter!\n")

        name = kwargs['name']
        interface_info_dict = self.va_show_interface(interface=name)
        interface_key_dict = interface_info_dict.keys()
        logger.debug("Actual interface info for {} : {} ".format(
            name, interface_info_dict))

        for expected_key in kwargs.keys():
            if expected_key == 'name':
                continue
            if expected_key not in interface_key_dict:
                error_value.append("{} is not exist".format(expected_key))
                continue
            if kwargs[expected_key] != interface_info_dict[expected_key]:
                error_value.append(expected_key + "is not right")
                logger.error("Fail,expected {} is {} the actual {} is {}"\
                .format(expected_key,kwargs[expected_key],expected_key,interface_info_dict[expected_key]))

        if len(error_value) > 0:
            logger.error(str(error_value))
            return False
        else:
            logger.info("Succeed to varify interface info")
            return True
Exemple #21
0
    def va_check_epi_forwarding_table(self, *args, **kwargs):
        """
        check epi forwarding table if it is correct according to the value of epi,vm-mac, micro-vlan and seg-id
         or option parameter (epi-mac, epi-ip and flag)
        param   : kwargs : dict
            kwargs = {
                    'epi' : uuid or hostname of the epi. eg: 2-6 or epi6
                    'fw_data' :[
                       {
                            'EPI-MAC': the value of epi-mac[option],
                            'EPI-IP': the value of epi ip[Option]
                            'SEG-ID': 'the value of seg id
                            'MICRO-VLAN': the value of micor vlan
                            'VM-MAC': the value of vm mac
                            'FLAG': the value of flag[option]}
                        }
                    ],
                    'Total remote entries' : option,
                    'Total local entries': option
            }
        return: bool
            Success: return True
            Failure: return False
        example :
             va_check_epi_forwarding_table(**kwargs)
             kwargs = {
                'epi': '2-6',
                'fw_data': [
                    {
                        'EPI-MAC': 'local',
                        'EPI-IP': 'local',
                        'SEG-ID': '3000',
                        'MICRO-VLAN': '2002',
                        'VM-MAC': '0:c:29:51:77:f8',
                        'FLAG': '111'
                     },
                     {'SEG-ID': '3000', 'MICRO-VLAN': '2003', 'VM-MAC': '0:50:56:8e:ed:8'}],
                     'Total local entries' : 2,
                     'Total remote entries': 0

            }
        """
        logger.info("\nIn subroutine: " + sys._getframe().f_code.co_name)
        if not 'epi' in kwargs:
            raise ValueError(
                "uuid of hostname of epi is mandatory parameter!\n")

        if not 'fw_data' in kwargs:
            raise ValueError("fw_table is mandatory parameter!\n")

        result, forwarding_info = self.va_get_epi_forwarding_table(
            **{'epi': kwargs.get('epi')})

        if result == False:
            return False

        expect_fw_data = kwargs.get('fw_data')

        if 'Total remote entries' in kwargs:
            expect_val = int(kwargs.get('Total remote entries'))
            actual_val = int(forwarding_info.get('Total remote entries'))
            if actual_val != expect_val:
                logger.error('The value of total remove entries is incorrect')
                logger.debug(
                    'Expect value of total remove entries is {}'.format(
                        expect_val))
                logger.debug(
                    'Actual value of total remove entries is {}'.format(
                        actual_val))
                return False

        if 'Total local entries' in kwargs:
            expect_val = int(kwargs.get('Total local entries'))
            actual_val = int(forwarding_info.get('Total local entries'))
            if actual_val != expect_val:
                logger.error('The value of Total local entries is incorrect')
                logger.debug(
                    'Expect value of Total local entries is {}'.format(
                        expect_val))
                logger.debug(
                    'Actual value of Total local entries is {}'.format(
                        actual_val))
                return False

        for each_fw_info in expect_fw_data:
            vm_mac = each_fw_info.get('VM-MAC')
            micro_vlan = each_fw_info.get('MICRO-VLAN')
            seg_id = each_fw_info.get('SEG-ID')
            if not vm_mac.strip() in forwarding_info:
                logger.error(
                    'Not found vm_mac {} in forwarding table'.format(vm_mac))
                return False

            actual_fw = forwarding_info.get(vm_mac.strip())
            if vm_mac.strip() != actual_fw.get('VM-MAC') or \
                micro_vlan.strip() != actual_fw.get('MICRO-VLAN') or \
                seg_id.strip() != actual_fw.get('SEG-ID') :
                logger.error('Verification failure!!!')
                logger.debug('Expect value are:vm_mac:{},micro_vlan:{},\
                seg_id:{}'.format(vm_mac, micro_vlan, seg_id))
                logger.debug('Acutal values are:vm_mac:{},micro_vlan:{},\
                seg_id:{}'.format(actual_fw.get('VM-MAC'),
                                  actual_fw.get('MICRO-VLAN'),
                                  actual_fw.get('SEG-ID')))
                return False

            if 'EPI-MAC' in each_fw_info:
                epi_mac = each_fw_info.get('EPI-MAC')
                if epi_mac != actual_fw.get('EPI-MAC'):
                    logger.error(
                        'Verification failure for EPI-MAC. expect value:{}, \
                    actual value:{}'.format(actual_fw.get('EPI-MAC'), epi_mac))
                    return False

            if 'EPI-IP' in each_fw_info:
                epi_ip = each_fw_info.get('EPI-IP')
                if epi_ip != actual_fw.get('EPI-IP'):
                    logger.error(
                        'Verification failure for EPI-IP. expect value:{}, \
                                actual value:{}'.format(
                            actual_fw.get('EPI-IP'), epi_ip))
                    return False

            if 'FLAG' in each_fw_info:
                flag = each_fw_info.get('FLAG')
                if flag != actual_fw.get('FLAG'):
                    logger.error(
                        'Verification failure for FLAG. expect value:{}, \
                                actual value:{}'.format(
                            actual_fw.get('FLAG'), flag))
                    return False
            logger.info(
                'Succeed to check forwaring for vm_mac {}'.format(vm_mac))

        logger.info('Succeed to check forwarding for epi {}'.format(
            kwargs.get('epi')))
        return True
Exemple #22
0
    def va_config_deceptionserver(self, data, *args, **kwargs):
        """
            API to config deception server policy
            Here user credential are optional, it will be configure
            if user provide the details
            param    :
                data = {
                     'server'       : 'Deception server name'
                     'endpoint-ip'   : 'Server end point IP'
                           - Note that DNS name is not supported
                     'username'   : 'UserID to connect server'
                     'passphrase'  : 'password'
                     'encrypted'  : True/False, by default it is False
                            provided password is encrypted?
                     'is_commit"  : Commit pending configuration
            example  : va_config_deception_server(data)
            return   : tuple with True/False and log output
        """
        logger.info("We are in ::" + sys._getframe().f_code.co_name)

        data1 = copy.deepcopy(data)

        if 'server' not in data1:
            logger.error('Missing the mandotory argument: Server')
            raise ValueError('Missing the mandotory argument: Server')
        if 'endpoint-ip' not in data1:
            logger.error('Missing the mandotory argument: {}'.format(
                data1['server']))
            raise ValueError('Missing the mandotory argument: \
            {}'.format(data1['server']))
        if 'iscommit' not in data1:
            data1['iscommit'] = 'ON'
        if 'username' in data1:
            if 'passphrase' not in data:
                logger.error('passphrase required for user {}'.format(
                    data['username']))
                raise ValueError('passphrase required for \
                user {}'.format(data['username']))
        if 'encrypted' not in data1:
            data1['encrypted'] = False

        logger.debug('data1........ in darknet,' + str(data1))
        cmds = []

        cmds.append('set deception server %s endpoint-ip %s' %
                    (data1['server'], data1['endpoint-ip']))
        if 'username' in data1:
            cmds.append('set deception server %s username %s' %
                        (data1['server'], data1['username']))
            if data1['encrypted'] is True:
                cmds.append(
                    'set deception server %s passphrase encrypted-password %s'
                    % (data1['server'], data1['passphrase']))
                logger.info('Deception Server command :' + str(cmds))
                config_status, output = self._access.va_config(cmds)
                logger.info('Configuration of DECEPTION: {} : {} '.format(
                    config_status, output))
            else:
                #TODO NEED TO CHECK HOW INTERACTIVE COMMAND EXECUTED IN CLI
                # replace below code with commented one
                logger.info('Deception Server command :' + str(cmds))
                config_status, output = self._access.va_config(cmds)
                logger.info('Configuration of DECEPTION: {} : {} '.format(
                    config_status, output))
                '''
                cmds.append('set deception server %s passphrase ' % (data1['server']))
                config_status, output = self._access.va_config(cmds)
                logger.info('Configuration of DECEPTION: {} : {} '.format(config_status, output))
                #cmds.append( data1['passphrase'])
                #cmds.append( data1['passphrase'])
                config_status, output = self._access.va_cli(data1['passphrase'])
                config_status, output = self._access.va_cli(data1['passphrase'])
                '''
        else:
            logger.info('Deception Server command :' + str(cmds))
            config_status, output = self._access.va_config(cmds)
            logger.info('Configuration of DECEPTION: {} : {} '.format(
                config_status, output))
        '''logger.info('Deception Server command :' + str(cmds))

        config_status, output = self._access.va_config(cmds)
        print('Configuration of DARKNET: ', config_status, output)
        '''
        if config_status is False:
            logger.error('Configuration/commit FAILED')
            return False, output
        else:
            if 'username' in data1:
                logger.info('Configuration and commit is successful')
                print('Configuration of DECEPTION: ', config_status, output)
                if data1['encrypted'] is True:
                    cmds.pop()
                else:
                    #TODO THESE required when interactive cli is available
                    #cmds.pop()
                    cmds.pop()
            rstatus, output = self.va_deceptionserver_in_running(cmds)
            return True, output
Exemple #23
0
    def va_check_session(self, data=None, *args):
        """
        method to match a bunch of keyswords related to session output. The
        session output is part of the data. Look at the following data dict
        for the valid keywords. data should have a mandatory key - session,
        which is the session output. other keywords are optional.

        {
            'app': '--',
            'flag': '0x00c00004',
            'id': '0x5000100000008',
            'in_dst_ip': '152.32.13.174',
            'in_dst_port': '10001',
            'in_intf': 'reth0',
            'in_micro_vlan': '1',
            'in_packets': '213',
            'in_phy_intf': '(xe-2/0/2)',
            'in_src_ip': '152.16.13.174',
            'in_src_port': '1087',
            'out_dst_ip': '152.16.13.174',
            'out_dst_port': '1087',
            'out_intf': 'reth1',
            'out_micro_vlan': '1',
            'out_packets': '0',
            'out_phy_intf': '(xe-2/0/3)',
            'out_src_ip': '152.32.13.174',
            'out_src_port': '10001',
            'policy': 'Any',
            'proto': '17',
            'state': '-1--1',
            'time': '1769',
            'vsys_id': '1'
        }

        raises:
            :ValueError: if data does not have session defined

        returns:
            :True|False (bool): True if match succeeds else False
        """
        found_match = False
        match_counter = 0
        most_match_session = dict()
        failed_in_most_match = None

        output = data.get('session')
        if not output:
            raise ValueError

        data.pop('session')

        session_stats = self._va_parse_session(output)

        if 'data_session' in args:
            in_ip = data.pop('in_dst_ip')
            out_ip = data.pop('out_dst_ip')
            data['in_dst_ip'] = data.pop('in_src_ip')
            data['in_src_ip'] = in_ip
            data['out_dst_ip'] = data.pop('out_src_ip')
            data['out_src_ip'] = out_ip

        for device in session_stats:
            if found_match:
                break
            for active_sessions in session_stats.get(device):
                if found_match:
                    break
                for session in active_sessions.get('sessions'):
                    match, no_matches, failed = self._va_check_single_session(
                                            data, session
                                        )

                    if no_matches > match_counter:
                        match_counter = no_matches
                        most_match_session = session
                        failed_in_most_match = failed

                    if match:
                        found_match = True
                        break
                    else:
                        continue

        if not found_match:
            logger.debug('Expected match session info:\n%s' % data)
            logger.debug("failed keywords: {}".format(failed_in_most_match))
            logger.debug("session with most matches: {}"
                        .format(most_match_session))
            logger.error("session match failed!")

        logger.info("session match succeed!")
        return found_match
Exemple #24
0
    def va_get_epi_forwarding_table(self, *args, **kwargs):
        """
        get epi forwarding table according to uuid or hostname of epi
        param   : kwargs : dict
            kwargs = {
                    'epi' : uuid or hostname of the epi. eg: 2-6 or epi6
            }
        return: tuple
            Success: True,
                : {'0:50:56:8e:ed:8': {
                            'EPI-MAC': 'local',
                            'EPI-IP': 'local',
                            'SEG-ID': '3000',
                            'MICRO-VLAN': '2003',
                            'VM-MAC': '0:50:56:8e:ed:8',
                            'FLAG': '110'},
                   'Total remote entries': '0',
                   'Total local entries': '2',
                   '0:c:29:51:77:f8': {
                         'EPI-MAC': 'local',
                         'EPI-IP': 'local',
                         'SEG-ID': '3000',
                         'MICRO-VLAN': '2002',
                         'VM-MAC': '0:c:29:51:77:f8',
                         'FLAG': '110'
                         }
                   }
            Failure: False,{}
        example : va_get_epi_forwarding_table(**kwargs)

        """
        logger.info("\nIn subroutine: " + sys._getframe().f_code.co_name)
        return_data = {}
        if not 'epi' in kwargs:
            raise ValueError(
                "uuid of hostname of epi is mandatory parameter!\n")

        cmd = 'show chassis epi {} forwarding'.format(kwargs.get('epi'))
        output = self._access.va_cli(cmd)
        if re.search(r'Fail to find EPI', output, re.M | re.I) is not None:
            logger.error('Failed to find EPI {}'.format(kwargs.get('epi')))
            return False, return_data

        output = output.split('\n')
        output.pop(0)
        last_index = len(output) - 1
        output.pop(int(last_index))
        output.pop(1)

        #address the number of tatal local/remove entries
        for i in range(1, 3):
            total_line = output.pop(-1).split(':')
            return_data[total_line[0].strip()] = total_line[1].strip()

        #get key name
        key_name = output.pop(0)
        key_name = key_name.split()

        #get forwarding information for each vm-mac
        for fw_in in output:
            fw_in_l = fw_in.split()
            num = len(fw_in_l)
            vm_mac = fw_in_l[0]
            return_data[vm_mac] = {}
            for i in range(0, num):
                fw_in_e_v = fw_in_l[i].strip()
                fw_in_e_k = key_name[i].strip()
                return_data[vm_mac][fw_in_e_k] = fw_in_e_v
        logger.debug('forwaing table of {} epi is {}\n'.format(
            kwargs.get('epi'), return_data))
        return True, return_data