Esempio n. 1
0
    def removeDiagnosticFile(self):
        fields = self.request().fields()
        if 'removeFiles' in fields and 'dir' in fields:
            directory = fields['dir']
            if directory not in allowedDirs:
                raise OSError, "'%s' is not a permitted system file category." % directory

            path = basicPathName + directory
            for systemFile in FormUtils.getPrefixedFieldNames('ck_', fields):
                self.sendAction('/file/delete_diagnostic',
                                ('local_dir', 'string', path),
                                ('local_filename', 'string', systemFile))
Esempio n. 2
0
    def tcpDumps(self):
        # dump capture files table on top
        if 'removeFiles' in self.fields:
            self.removeDiagnosticFile()

        # running tcp dumps table below:
        elif 'addTcpDump' in self.fields:
            ifaces = FormUtils.getPrefixedFieldNames('iface_', self.fields)

            # We need to handle RiOS interfaces and host interfaces (BOB boxes).
            riosIfaces = []
            hostIfaces = []
            for iface in ifaces:
                if iface == 'All':
                    pass
                elif iface.startswith('host_'):
                    hostIfaces.append(iface[5:])
                else:
                    riosIfaces.append(iface)

            name = self.fields.get('addDump_captureName', '').strip()
            bufferSize = self.fields.get('addDump_bufferSize')
            snapLength = self.fields.get('addDump_snapLength')
            rotateCount = self.fields.get('addDump_rotation', '0')
            fileSize = self.fields.get('addDump_captureMax', '0')
            duration = self.fields.get('addDump_captureDuration', '0')
            flags = self.fields.get('addDump_flags', '')
            vlan = self.fields.get('addDump_vlanEnable')

            # for the ip and port fields, parse the comma-delimited list
            # return an empty list for the default cases
            def listOrEmpty(name):
                val = self.fields.get(name, '').strip().lower()
                if val in ('', 'all', '0.0.0.0', '0'):
                    return []
                return map(str.strip, val.split(','))

            sched = self.fields.get('addDump_schedule')

            args = [('rotate_count', 'uint32', rotateCount),
                    ('custom', 'string', flags)] + \
                   [('sip', 'ipv4addr', si) for si in listOrEmpty('addDump_srcIps')] + \
                   [('sport', 'uint16', sp) for sp in listOrEmpty('addDump_srcPorts')] + \
                   [('dip', 'ipv4addr', di) for di in listOrEmpty('addDump_dstIps')] + \
                   [('dport', 'uint16', dp) for dp in listOrEmpty('addDump_dstPorts')]

            if '0' != duration:
                args.append(('duration', 'duration_sec', duration))

            if '0' != fileSize:
                args.append(('file_size', 'uint32', fileSize))

            if bufferSize:
                args.append(('buffer_size', 'uint32', bufferSize))

            if snapLength:
                args.append(('snap_len', 'uint32', snapLength))

            if name:
                args.append(('cap_name', 'string', name))

            if 'true' == vlan:
                args.append(('dot1q', 'bool', 'true'))

            if 'true' == sched:
                schedDate = self.fields.get('addDump_scheduleDate', '')
                schedTime = self.fields.get('addDump_scheduleTime', '')
                args.append(('sched_date', 'date', schedDate))
                args.append(('sched_time', 'time_sec', schedTime))

            if riosIfaces:
                riosArgs = list(args)
                riosArgs += [('interface', 'string', iface) for iface in riosIfaces]
                self.sendAction('/rbt/tcpdump/action/start', *riosArgs)

            if hostIfaces:
                hostArgs = list(args)
                hostArgs += [('interface', 'string', iface) for iface in hostIfaces]
                self.sendAction('/host/tcpdump/action/start', *hostArgs)

            if not riosIfaces and not hostIfaces:
                self.setFormError('An interface must be selected.')

        elif 'removeTcpCaptures':
            captures = FormUtils.getPrefixedFieldNames('select_', self.fields)
            riosCaptures = Nodes.getMgmtLocalChildrenNames(self.mgmt, '/rbt/tcpdump/state/capture')
            if RVBDUtils.isBOB():
                hostCaptures = Nodes.getMgmtLocalChildrenNames(self.mgmt, '/host/tcpdump/state/capture')

            for capture in captures:
                name, runningOn = capture.split('/')

                # it could have finished while the user was admiring the page
                if runningOn == 'RiOS' and name in riosCaptures:
                    self.sendAction('/rbt/tcpdump/action/stop',
                                    ('cap_name', 'string', name))
                elif runningOn == 'Hypervisor' and name in hostCaptures:
                    self.sendAction('/host/tcpdump/action/stop',
                                    ('cap_name', 'string', name))
    def snmpAction(self):
        base = self.cmcPolicyRetarget('/snmp/trapsink/sink')
        userBase = self.cmcPolicyRetarget('/snmp/usm/users')
        nameBase = self.cmcPolicyRetarget('/snmp/vacm/sec_names')
        groupBase = self.cmcPolicyRetarget('/snmp/vacm/groups')
        groupSpec = {'sec_name': 'string',
                     'sec_model': 'string'}
        aclBase = self.cmcPolicyRetarget('/snmp/vacm/acls')
        aclSpec = {'group_name': 'string',
                   'sec_level': 'string',
                   'read_view': 'string'}

        id, val = FormUtils.getPrefixedField('controlReceiver_', self.fields)
        if id:
            self.mgmt.set(('%s/%s/enable' % (base, id), 'bool', ('enabled' == val) and 'true' or 'false'))

        if 'addReceiver' in self.fields:
            host = self.fields.get('addReceiver_host')
            port = self.fields.get('addReceiver_port')
            version = self.fields.get('addReceiver_version')
            enable = self.fields.get('addReceiver_enable', 'false')

            pre = '%s/%s' % (base, host)
            nodes = [(pre + '/type', 'string', version),
                     (pre + '/enable', 'bool', enable)]

            if port:
                nodes += [(pre + '/port', 'uint16', port)]
            if 'trap-v3' != version:
                # version 1, version 2
                community = self.fields.get('addReceiver_community', '')
                nodes += [(pre + '/community', 'string', community)]
            else:
                # version 3
                user = self.fields.get('addReceiver_user')
                mode = self.fields.get('addReceiver_mode')
                protocol = self.fields.get('addReceiver_protocol')
                auth = self.fields.get('addReceiver_auth')

                # key from the user, or derrived from the password
                if 'password'== mode:
                    password = self.fields.get('addReceiver_password')
                    key = self.sendAction('/snmp/usm/actions/generate_auth_key',
                                          ('password', 'string', password),
                                          ('hash_function', 'string', protocol))
                    key = key.get('auth_key', '')
                else:
                    key = self.fields.get('addReceiver_key')
                nodes += [(pre + '/username', 'string', user),
                          (pre + '/hash_function', 'string', protocol),
                          (pre + '/auth_key', 'string', key),
                          (pre + '/sec_level', 'string', auth)]
                # AuthPriv option of Security Level
                if 'authpriv'== auth:
                    privacyMode = self.fields.get('addReceiver_privacyMode')
                    if 'authPrivacy'== privacyMode:
                       # Use the same key generated from authentication password or entered for authentication
                        privacyKey = key
                    elif 'password'== privacyMode:
                       # Generate key from privacy password entered by user
                        privacyPassword = self.fields.get('addReceiver_privacyPassword')
                        privacyKey = self.sendAction('/snmp/usm/actions/generate_auth_key',
                                                    ('password', 'string', privacyPassword),
                                                    ('hash_function', 'string', protocol))
                        privacyKey = privacyKey.get('auth_key', '')
                    elif 'key'== privacyMode:
                       # Use privacy key provided by the user
                        privacyKey = self.fields.get('addReceiver_privacyKey')
                    privacyProtocol = self.fields.get('addReceiver_privacyProtocol')
                    nodes += [(pre + '/privacy_protocol', 'string', privacyProtocol),
                              (pre + '/privacy_key', 'string', privacyKey)]
            self.setNodes(*nodes)

        elif 'removeReceivers' in self.fields:
            FormUtils.deleteNodesFromConfigForm(self.mgmt, base, 'ck_', self.fields)

        elif 'addSnmpUser' in self.fields:
            name = self.fields.get('addSnmpUser_name')
            protocol = self.fields.get('addSnmpUser_protocol')
            if 'password'== self.fields.get('addSnmpUser_mode'):
                password = self.fields.get('addSnmpUser_password')
                key = self.sendAction('/snmp/usm/actions/generate_auth_key',
                                      ('password', 'string', password),
                                      ('hash_function', 'string', protocol))
                key = key.get('auth_key', '')
            else:
                key = self.fields.get('addSnmpUser_key', '')
            nodes = [('%s/%s' % (userBase, name), 'string', name),
                    ('%s/%s/auth_key' % (userBase, name), 'string', key),
                    ('%s/%s/hash_function' % (userBase, name), 'string', protocol)]
            privacyOption = self.fields.get('addSnmpUser_privacyOption', 'false')
            if 'true' == privacyOption:
                # The user wishes to use the privacy feature, therefore checkbox is checked.
                privacyProtocol = self.fields.get('addSnmpUser_privacyProtocol')
                privacyMode = self.fields.get('addSnmpUser_privacyMode')
                if 'authPrivacy' == privacyMode:
                    # Use the same key generated from authentication or entered for authentication
                    privacyKey = key
                elif 'password' == privacyMode:
                    # Generate key from password entered for privacy
                    privacyPassword = self.fields.get('addSnmpUser_privacyPassword')
                    privacyKey = self.sendAction('/snmp/usm/actions/generate_auth_key',
                                      ('password', 'string', privacyPassword),
                                      ('hash_function', 'string', protocol))
                    privacyKey = privacyKey.get('auth_key', '')
                elif 'key' == privacyMode:
                    # Use the privacy key provided by the user
                    privacyKey = self.fields.get('addSnmpUser_privacyKey')
            elif 'false' == privacyOption:
                # Privacy feature not to be used. Clear the privacy_key and privacy_protocol nodes
                privacyKey = ''
                privacyProtocol = ''
            nodes += [('%s/%s/privacy_protocol' % (userBase, name), 'string', privacyProtocol),
                      ('%s/%s/privacy_key' % (userBase, name), 'string', privacyKey)]
            self.setNodes(*nodes)

        elif 'removeSnmpUsers' in self.fields:
            FormUtils.deleteNodesFromConfigForm(
                self.mgmt, userBase, 'snmpUser_', self.fields)
        elif 'addSecurityName' in self.fields:
            name = self.fields.get('addSecurityName_name')
            community = self.fields.get('addSecurityName_community')
            ipBits = self.fields.get('addSecurityName_ip', ':')
            if '/' not in ipBits:
                return
            ip, maskBits = ipBits.split('/')
            self.setNodes(
                ('%s/%s' % (nameBase, name), 'string', name),
                ('%s/%s/community' % (nameBase, name), 'string', community),
                ('%s/%s/src/ip' % (nameBase, name), 'ipv6addr', ip),
                ('%s/%s/src/mask_len' % (nameBase, name), 'uint8', maskBits))
        elif 'removeSecurityNames' in self.fields:
            FormUtils.deleteNodesFromConfigForm(
                self.mgmt, nameBase, 'secName_', self.fields)
        elif 'addGroup' in self.fields:
            name = self.fields.get('addGroup_name')
            i = 0
            while True:
                model = self.fields.get('addSnmpGroup_secModel_%d' % i)
                if 'editPolicy' in self.fields:
                    if model == 'usm':
                        user = self.fields.get('addSnmpGroupUsm_secName_%d' % i)
                    else:
                        user = self.fields.get('addSnmpGroup_secName_%d' % i)
                else:
                    user = self.fields.get('addSnmpGroup_secName_%d' % i)
                if not (user and model):
                    break
                path = '%s/%s/grp_entry' % (groupBase, name)
                Nodes.editNodeSequence(self.mgmt, path, groupSpec, 'add', -1,
                                      {'sec_name': user,
                                       'sec_model': model})
                i += 1
        elif 'removeGroups' in self.fields:
            FormUtils.deleteNodesFromConfigForm(self.mgmt,
                                                groupBase,
                                                'group_',
                                                self.fields)
        elif 'addView' in self.fields:
            name = self.fields.get('addView_name')
            incField = self.fields.get('addView_includes')
            # If the addView_includes/_excludes field is blank, then we want a blank list.
            includes = incField and [inc.strip() for inc in incField.split('\n') if inc.strip() != ''] or []
            excField = self.fields.get('addView_excludes')
            excludes = excField and [exc.strip() for exc in excField.split('\n') if exc.strip() != ''] or []
            viewBase = self.cmcPolicyRetarget('/snmp/vacm/views/%s' % name)
            # Note: Because we don't call Nodes.deleteChildNodes here, adding a view with the
            # same name as an existing view will append those OIDs, rather than overwriting
            # the whole list of OIDs.
            nodes = [(viewBase, 'string', name)] + \
                    [('%s/included/%s' % (viewBase, inc), 'string', inc) for inc in includes] + \
                    [('%s/excluded/%s' % (viewBase, exc), 'string', exc) for exc in excludes]
            self.setNodes(*nodes)

        elif 'editView' in self.fields:
            name = self.fields.get('editView_name')
            incField = self.fields.get('editView_includes')
            # If the editView_includes/_excludes field is blank, then we want a blank list.
            includes = incField and [inc.strip() for inc in incField.split('\n') if inc.strip() != ''] or []
            excField = self.fields.get('editView_excludes')
            excludes = excField and [exc.strip() for exc in excField.split('\n') if exc.strip() != ''] or []

            viewBase = self.cmcPolicyRetarget('/snmp/vacm/views/%s' % name)
            Nodes.deleteChildNodes(self.mgmt, viewBase + '/included')
            Nodes.deleteChildNodes(self.mgmt, viewBase + '/excluded')
            nodes = [('%s/included/%s' % (viewBase, inc), 'string', inc) for inc in includes] + \
                    [('%s/excluded/%s' % (viewBase, exc), 'string', exc) for exc in excludes]
            self.setNodes(*nodes)

        elif 'removeViews' in self.fields:
            viewBase = self.cmcPolicyRetarget('/snmp/vacm/views')
            FormUtils.deleteNodesFromConfigForm(self.mgmt,
                                                viewBase,
                                                'view_',
                                                self.fields)
        elif 'addAcl' in self.fields:
            group = self.fields.get('addAcl_group')
            auth = self.fields.get('addAcl_auth')
            readView = self.fields.get('addAcl_readView')

            # group/sec pairs must be unique, so if there's currently
            # a group/sec like this one, we replace it
            acls = Nodes.getMgmtSetEntries(self.mgmt, aclBase)
            for k, v in acls.iteritems():
                if (group == v.get('group_name')) and \
                   (auth == v.get('sec_level')):
                    Nodes.editNodeSequence(self.mgmt, aclBase, aclSpec, 'edit', int(k),
                                          {'group_name': group,
                                           'sec_level': auth,
                                           'read_view': readView})
                    break;
            else:
                Nodes.editNodeSequence(self.mgmt, aclBase, aclSpec, 'add', -1,
                                      {'group_name': group,
                                       'sec_level': auth,
                                       'read_view': readView})
        elif 'removeAcls' in self.fields:
            acls = FormUtils.getPrefixedFieldNames('acl_', self.fields)
            Nodes.editNodeSequence(self.mgmt, aclBase, aclSpec, 'remove', map(int, acls))