示例#1
0
def get_config():
    conf = Config()
    igmp_conf = {'igmp_conf': False, 'old_ifaces': {}, 'ifaces': {}}
    if not (conf.exists('protocols igmp')
            or conf.exists_effective('protocols igmp')):
        return None

    if conf.exists('protocols igmp'):
        igmp_conf['igmp_conf'] = True

    conf.set_level('protocols igmp')

    # # Get interfaces
    for iface in conf.list_effective_nodes('interface'):
        igmp_conf['old_ifaces'].update({
            iface: {
                'version':
                conf.return_effective_value(
                    'interface {0} version'.format(iface)),
                'query_interval':
                conf.return_effective_value(
                    'interface {0} query-interval'.format(iface)),
                'query_max_resp_time':
                conf.return_effective_value(
                    'interface {0} query-max-response-time'.format(iface)),
                'gr_join': {}
            }
        })
        for gr_join in conf.list_effective_nodes(
                'interface {0} join'.format(iface)):
            igmp_conf['old_ifaces'][iface]['gr_join'][
                gr_join] = conf.return_effective_values(
                    'interface {0} join {1} source'.format(iface, gr_join))

    for iface in conf.list_nodes('interface'):
        igmp_conf['ifaces'].update({
            iface: {
                'version':
                conf.return_value('interface {0} version'.format(iface)),
                'query_interval':
                conf.return_value(
                    'interface {0} query-interval'.format(iface)),
                'query_max_resp_time':
                conf.return_value(
                    'interface {0} query-max-response-time'.format(iface)),
                'gr_join': {}
            }
        })
        for gr_join in conf.list_nodes('interface {0} join'.format(iface)):
            igmp_conf['ifaces'][iface]['gr_join'][
                gr_join] = conf.return_values(
                    'interface {0} join {1} source'.format(iface, gr_join))

    return igmp_conf
示例#2
0
def generate(c):
    c_eff = Config()
    c_eff.set_level('protocols static')
    c_eff_cnf = {}
    for ip_addr in c_eff.list_effective_nodes('arp'):
        c_eff_cnf.update({
            ip_addr:
            c_eff.return_effective_value('arp ' + ip_addr + ' hwaddr')
        })

    config_data = {'remove': [], 'update': {}}
    ### removal
    if c == None:
        for ip_addr in c_eff_cnf:
            config_data['remove'].append(ip_addr)
    else:
        for ip_addr in c_eff_cnf:
            if not ip_addr in c or c[ip_addr] == None:
                config_data['remove'].append(ip_addr)

    ### add/update
    if c != None:
        for ip_addr in c:
            if not ip_addr in c_eff_cnf:
                config_data['update'][ip_addr] = c[ip_addr]
            if ip_addr in c_eff_cnf:
                if c[ip_addr] != c_eff_cnf[ip_addr] and c[ip_addr] != None:
                    config_data['update'][ip_addr] = c[ip_addr]

    return config_data
示例#3
0
def show_brief():
    config = Config()
    if len(config.list_effective_nodes('interfaces wireless')) == 0:
        print("No Wireless interfaces configured")
        exit(0)

    interfaces = []
    for intf in config.list_effective_nodes('interfaces wireless'):
        config.set_level('interfaces wireless {}'.format(intf))
        data = {'name': intf, 'type': '', 'ssid': '', 'channel': ''}
        data['type'] = config.return_effective_value('type')
        data['ssid'] = config.return_effective_value('ssid')
        data['channel'] = config.return_effective_value('channel')

        interfaces.append(data)

    return interfaces
def get_config():
    # determine tagNode instance
    if 'VYOS_TAGNODE_VALUE' not in os.environ:
        raise ConfigError('Interface (VYOS_TAGNODE_VALUE) not specified')

    ifname = os.environ['VYOS_TAGNODE_VALUE']
    conf = Config()

    # Check if interface has been removed
    cfg_base = ['interfaces', 'pseudo-ethernet', ifname]
    if not conf.exists(cfg_base):
        peth = deepcopy(default_config_data)
        peth['deleted'] = True
        return peth

    # set new configuration level
    conf.set_level(cfg_base)

    peth, disabled = intf_to_dict(conf, default_config_data)

    # ARP cache entry timeout in seconds
    if conf.exists(['ip', 'arp-cache-timeout']):
        peth['ip_arp_cache_tmo'] = int(
            conf.return_value(['ip', 'arp-cache-timeout']))

    # Enable private VLAN proxy ARP on this interface
    if conf.exists(['ip', 'proxy-arp-pvlan']):
        peth['ip_proxy_arp_pvlan'] = 1

    # Physical interface
    if conf.exists(['source-interface']):
        peth['source_interface'] = conf.return_value(['source-interface'])
        tmp = conf.return_effective_value(['source-interface'])
        if tmp != peth['source_interface']:
            peth['source_interface_changed'] = True

    # MACvlan mode
    if conf.exists(['mode']):
        peth['mode'] = conf.return_value(['mode'])

    add_to_dict(conf, disabled, peth, 'vif', 'vif')
    add_to_dict(conf, disabled, peth, 'vif-s', 'vif_s')

    return peth
示例#5
0
def get_config():
    conf = Config()
    vrf_config = deepcopy(default_config_data)

    cfg_base = ['vrf']
    if not conf.exists(cfg_base):
        # get all currently effetive VRFs and mark them for deletion
        vrf_config['vrf_remove'] = conf.list_effective_nodes(cfg_base +
                                                             ['name'])
    else:
        # set configuration level base
        conf.set_level(cfg_base)

        # Should services be allowed to bind to all VRFs?
        if conf.exists(['bind-to-all']):
            vrf_config['bind_to_all'] = '1'

        # Determine vrf interfaces (currently effective) - to determine which
        # vrf interface is no longer present and needs to be removed
        eff_vrf = conf.list_effective_nodes(['name'])
        act_vrf = conf.list_nodes(['name'])
        vrf_config['vrf_remove'] = list_diff(eff_vrf, act_vrf)

        # read in individual VRF definition and build up
        # configuration
        for name in conf.list_nodes(['name']):
            vrf_inst = {
                'description': '',
                'members': [],
                'name': name,
                'table': '',
                'table_mod': False
            }
            conf.set_level(cfg_base + ['name', name])

            if conf.exists(['table']):
                # VRF table can't be changed on demand, thus we need to read in the
                # current and the effective routing table number
                act_table = conf.return_value(['table'])
                eff_table = conf.return_effective_value(['table'])
                vrf_inst['table'] = act_table
                if eff_table and eff_table != act_table:
                    vrf_inst['table_mod'] = True

            if conf.exists(['description']):
                vrf_inst['description'] = conf.return_value(['description'])

            # append individual VRF configuration to global configuration list
            vrf_config['vrf_add'].append(vrf_inst)

    # set configuration level base
    conf.set_level(cfg_base)

    # check VRFs which need to be removed as they are not allowed to have
    # interfaces attached
    tmp = []
    for name in vrf_config['vrf_remove']:
        vrf_inst = {'interfaces': [], 'name': name, 'routes': []}

        # find member interfaces of this particulat VRF
        vrf_inst['interfaces'] = vrf_interfaces(conf, name)

        # find routing protocols used by this VRF
        vrf_inst['routes'] = vrf_routing(conf, name)

        # append individual VRF configuration to temporary configuration list
        tmp.append(vrf_inst)

    # replace values in vrf_remove with list of dictionaries
    # as we need it in verify() - we can't delete a VRF with members attached
    vrf_config['vrf_remove'] = tmp
    return vrf_config
示例#6
0
def get_config():
    conf = Config()
    pim_conf = {
        'pim_conf': False,
        'old_pim': {
            'ifaces': {},
            'rp': {}
        },
        'pim': {
            'ifaces': {},
            'rp': {}
        }
    }
    if not (conf.exists('protocols pim')
            or conf.exists_effective('protocols pim')):
        return None

    if conf.exists('protocols pim'):
        pim_conf['pim_conf'] = True

    conf.set_level('protocols pim')

    # Get interfaces
    for iface in conf.list_effective_nodes('interface'):
        pim_conf['old_pim']['ifaces'].update({
            iface: {
                'hello':
                conf.return_effective_value(
                    'interface {0} hello'.format(iface)),
                'dr_prio':
                conf.return_effective_value(
                    'interface {0} dr-priority'.format(iface))
            }
        })

    for iface in conf.list_nodes('interface'):
        pim_conf['pim']['ifaces'].update({
            iface: {
                'hello':
                conf.return_value('interface {0} hello'.format(iface)),
                'dr_prio':
                conf.return_value('interface {0} dr-priority'.format(iface)),
            }
        })

    conf.set_level('protocols pim rp')

    # Get RPs addresses
    for rp_addr in conf.list_effective_nodes('address'):
        pim_conf['old_pim']['rp'][rp_addr] = conf.return_effective_values(
            'address {0} group'.format(rp_addr))

    for rp_addr in conf.list_nodes('address'):
        pim_conf['pim']['rp'][rp_addr] = conf.return_values(
            'address {0} group'.format(rp_addr))

    # Get RP keep-alive-timer
    if conf.exists_effective('rp keep-alive-timer'):
        pim_conf['old_pim']['rp_keep_alive'] = conf.return_effective_value(
            'rp keep-alive-timer')
    if conf.exists('rp keep-alive-timer'):
        pim_conf['pim']['rp_keep_alive'] = conf.return_value(
            'rp keep-alive-timer')

    return pim_conf
def get_config():
    l2tpv3 = deepcopy(default_config_data)
    conf = Config()

    # determine tagNode instance
    if 'VYOS_TAGNODE_VALUE' not in os.environ:
        raise ConfigError('Interface (VYOS_TAGNODE_VALUE) not specified')

    l2tpv3['intf'] = os.environ['VYOS_TAGNODE_VALUE']

    # check if interface is member of a bridge
    l2tpv3['is_bridge_member'] = is_member(conf, l2tpv3['intf'], 'bridge')

    # Check if interface has been removed
    if not conf.exists('interfaces l2tpv3 ' + l2tpv3['intf']):
        l2tpv3['deleted'] = True
        interface = l2tpv3['intf']

        # to delete the l2tpv3 interface we need the current tunnel_id and session_id
        if conf.exists_effective(f'interfaces l2tpv3 {interface} tunnel-id'):
            l2tpv3['tunnel_id'] = conf.return_effective_value(
                f'interfaces l2tpv3 {interface} tunnel-id')

        if conf.exists_effective(f'interfaces l2tpv3 {interface} session-id'):
            l2tpv3['session_id'] = conf.return_effective_value(
                f'interfaces l2tpv3 {interface} session-id')

        return l2tpv3

    # set new configuration level
    conf.set_level('interfaces l2tpv3 ' + l2tpv3['intf'])

    # retrieve configured interface addresses
    if conf.exists('address'):
        l2tpv3['address'] = conf.return_values('address')

    # retrieve interface description
    if conf.exists('description'):
        l2tpv3['description'] = conf.return_value('description')

    # get tunnel destination port
    if conf.exists('destination-port'):
        l2tpv3['remote_port'] = int(conf.return_value('destination-port'))

    # Disable this interface
    if conf.exists('disable'):
        l2tpv3['disable'] = True

    # get tunnel encapsulation type
    if conf.exists('encapsulation'):
        l2tpv3['encapsulation'] = conf.return_value('encapsulation')

    # get tunnel local ip address
    if conf.exists('local-ip'):
        l2tpv3['local_address'] = conf.return_value('local-ip')

    # Enable acquisition of IPv6 address using stateless autoconfig (SLAAC)
    if conf.exists('ipv6 address autoconf'):
        l2tpv3['ipv6_autoconf'] = 1

    # Get prefixes for IPv6 addressing based on MAC address (EUI-64)
    if conf.exists('ipv6 address eui64'):
        l2tpv3['ipv6_eui64_prefix'] = conf.return_values('ipv6 address eui64')

    # Remove the default link-local address if set.
    if not (conf.exists('ipv6 address no-default-link-local')
            or l2tpv3['is_bridge_member']):
        # add the link-local by default to make IPv6 work
        l2tpv3['ipv6_eui64_prefix'].append('fe80::/64')

    # Disable IPv6 forwarding on this interface
    if conf.exists('ipv6 disable-forwarding'):
        l2tpv3['ipv6_forwarding'] = 0

    # IPv6 Duplicate Address Detection (DAD) tries
    if conf.exists('ipv6 dup-addr-detect-transmits'):
        l2tpv3['ipv6_dup_addr_detect'] = int(
            conf.return_value('ipv6 dup-addr-detect-transmits'))

    # to make IPv6 SLAAC and DHCPv6 work with forwarding=1,
    # accept_ra must be 2
    if l2tpv3['ipv6_autoconf'] or 'dhcpv6' in l2tpv3['address']:
        l2tpv3['ipv6_accept_ra'] = 2

    # Maximum Transmission Unit (MTU)
    if conf.exists('mtu'):
        l2tpv3['mtu'] = int(conf.return_value('mtu'))

    # Remote session id
    if conf.exists('peer-session-id'):
        l2tpv3['peer_session_id'] = conf.return_value('peer-session-id')

    # Remote tunnel id
    if conf.exists('peer-tunnel-id'):
        l2tpv3['peer_tunnel_id'] = conf.return_value('peer-tunnel-id')

    # Remote address of L2TPv3 tunnel
    if conf.exists('remote-ip'):
        l2tpv3['remote_address'] = conf.return_value('remote-ip')

    # Local session id
    if conf.exists('session-id'):
        l2tpv3['session_id'] = conf.return_value('session-id')

    # get local tunnel port
    if conf.exists('source-port'):
        l2tpv3['local_port'] = conf.return_value('source-port')

    # get local tunnel id
    if conf.exists('tunnel-id'):
        l2tpv3['tunnel_id'] = conf.return_value('tunnel-id')

    return l2tpv3
def get_config():
    l2tpv3 = deepcopy(default_config_data)
    conf = Config()

    # determine tagNode instance
    if 'VYOS_TAGNODE_VALUE' not in os.environ:
        raise ConfigError('Interface (VYOS_TAGNODE_VALUE) not specified')

    l2tpv3['intf'] = os.environ['VYOS_TAGNODE_VALUE']

    # Check if interface has been removed
    if not conf.exists('interfaces l2tpv3 ' + l2tpv3['intf']):
        l2tpv3['deleted'] = True
        # to delete the l2tpv3 interface we need to current
        # tunnel_id and session_id
        if conf.exists_effective('interfaces l2tpv3 {} tunnel-id'.format(
                l2tpv3['intf'])):
            l2tpv3['tunnel_id'] = conf.return_effective_value(
                'interfaces l2tpv3 {} tunnel-id'.format(l2tpv3['intf']))

        if conf.exists_effective('interfaces l2tpv3 {} session-id'.format(
                l2tpv3['intf'])):
            l2tpv3['session_id'] = conf.return_effective_value(
                'interfaces l2tpv3 {} session-id'.format(l2tpv3['intf']))

        return l2tpv3

    # set new configuration level
    conf.set_level('interfaces l2tpv3 ' + l2tpv3['intf'])

    # retrieve configured interface addresses
    if conf.exists('address'):
        l2tpv3['address'] = conf.return_values('address')

    # retrieve interface description
    if conf.exists('description'):
        l2tpv3['description'] = conf.return_value('description')

    # get tunnel destination port
    if conf.exists('destination-port'):
        l2tpv3['remote_port'] = int(conf.return_value('destination-port'))

    # Disable this interface
    if conf.exists('disable'):
        l2tpv3['disable'] = True

    # get tunnel encapsulation type
    if conf.exists('encapsulation'):
        l2tpv3['encapsulation'] = conf.return_value('encapsulation')

    # get tunnel local ip address
    if conf.exists('local-ip'):
        l2tpv3['local_address'] = conf.return_value('local-ip')

    # Enable acquisition of IPv6 address using stateless autoconfig (SLAAC)
    if conf.exists('ipv6 address autoconf'):
        l2tpv3['ipv6_autoconf'] = 1

    # Get prefix for IPv6 addressing based on MAC address (EUI-64)
    if conf.exists('ipv6 address eui64'):
        l2tpv3['ipv6_eui64_prefix'] = conf.return_value('ipv6 address eui64')

    # Disable IPv6 forwarding on this interface
    if conf.exists('ipv6 disable-forwarding'):
        l2tpv3['ipv6_forwarding'] = 0

    # IPv6 Duplicate Address Detection (DAD) tries
    if conf.exists('ipv6 dup-addr-detect-transmits'):
        l2tpv3['ipv6_dup_addr_detect'] = int(
            conf.return_value('ipv6 dup-addr-detect-transmits'))

    # Maximum Transmission Unit (MTU)
    if conf.exists('mtu'):
        l2tpv3['mtu'] = int(conf.return_value('mtu'))

    # Remote session id
    if conf.exists('peer-session-id'):
        l2tpv3['peer_session_id'] = conf.return_value('peer-session-id')

    # Remote tunnel id
    if conf.exists('peer-tunnel-id'):
        l2tpv3['peer_tunnel_id'] = conf.return_value('peer-tunnel-id')

    # Remote address of L2TPv3 tunnel
    if conf.exists('remote-ip'):
        l2tpv3['remote_address'] = conf.return_value('remote-ip')

    # Local session id
    if conf.exists('session-id'):
        l2tpv3['session_id'] = conf.return_value('session-id')

    # get local tunnel port
    if conf.exists('source-port'):
        l2tpv3['local_port'] = conf.return_value('source-port')

    # get local tunnel id
    if conf.exists('tunnel-id'):
        l2tpv3['tunnel_id'] = conf.return_value('tunnel-id')

    return l2tpv3
示例#9
0
def get_bfd_peer_config(peer, conf_mode="proposed"):
    conf = Config()
    conf.set_level('protocols bfd peer {0}'.format(peer))

    bfd_peer = {
        'remote': peer,
        'shutdown': False,
        'src_if': '',
        'src_addr': '',
        'multiplier': '3',
        'rx_interval': '300',
        'tx_interval': '300',
        'multihop': False,
        'echo_interval': '',
        'echo_mode': False,
    }

    # Check if individual peer is disabled
    if conf_mode == "effective" and conf.exists_effective('shutdown'):
        bfd_peer['shutdown'] = True
    if conf_mode == "proposed" and conf.exists('shutdown'):
        bfd_peer['shutdown'] = True

    # Check if peer has a local source interface configured
    if conf_mode == "effective" and conf.exists_effective('source interface'):
        bfd_peer['src_if'] = conf.return_effective_value('source interface')
    if conf_mode == "proposed" and conf.exists('source interface'):
        bfd_peer['src_if'] = conf.return_value('source interface')

    # Check if peer has a local source address configured - this is mandatory for IPv6
    if conf_mode == "effective" and conf.exists_effective('source address'):
        bfd_peer['src_addr'] = conf.return_effective_value('source address')
    if conf_mode == "proposed" and conf.exists('source address'):
        bfd_peer['src_addr'] = conf.return_value('source address')

    # Tell BFD daemon that we should expect packets with TTL less than 254
    # (because it will take more than one hop) and to listen on the multihop
    # port (4784)
    if conf_mode == "effective" and conf.exists_effective('multihop'):
        bfd_peer['multihop'] = True
    if conf_mode == "proposed" and conf.exists('multihop'):
        bfd_peer['multihop'] = True

    # Configures the minimum interval that this system is capable of receiving
    # control packets. The default value is 300 milliseconds.
    if conf_mode == "effective" and conf.exists_effective('interval receive'):
        bfd_peer['rx_interval'] = conf.return_effective_value(
            'interval receive')
    if conf_mode == "proposed" and conf.exists('interval receive'):
        bfd_peer['rx_interval'] = conf.return_value('interval receive')

    # The minimum transmission interval (less jitter) that this system wants
    # to use to send BFD control packets.
    if conf_mode == "effective" and conf.exists_effective('interval transmit'):
        bfd_peer['tx_interval'] = conf.return_effective_value(
            'interval transmit')
    if conf_mode == "proposed" and conf.exists('interval transmit'):
        bfd_peer['tx_interval'] = conf.return_value('interval transmit')

    # Configures the detection multiplier to determine packet loss. The remote
    # transmission interval will be multiplied by this value to determine the
    # connection loss detection timer. The default value is 3.
    if conf_mode == "effective" and conf.exists_effective(
            'interval multiplier'):
        bfd_peer['multiplier'] = conf.return_effective_value(
            'interval multiplier')
    if conf_mode == "proposed" and conf.exists('interval multiplier'):
        bfd_peer['multiplier'] = conf.return_value('interval multiplier')

    # Configures the minimal echo receive transmission interval that this system is capable of handling
    if conf_mode == "effective" and conf.exists_effective(
            'interval echo-interval'):
        bfd_peer['echo_interval'] = conf.return_effective_value(
            'interval echo-interval')
    if conf_mode == "proposed" and conf.exists('interval echo-interval'):
        bfd_peer['echo_interval'] = conf.return_value('interval echo-interval')

    # Enables or disables the echo transmission mode
    if conf_mode == "effective" and conf.exists_effective('echo-mode'):
        bfd_peer['echo_mode'] = True
    if conf_mode == "proposed" and conf.exists('echo-mode'):
        bfd_peer['echo_mode'] = True

    return bfd_peer
示例#10
0
def get_config():
    conf = Config()
    base = ['interfaces', 'wireguard']

    # determine tagNode instance
    if 'VYOS_TAGNODE_VALUE' not in os.environ:
        raise ConfigError('Interface (VYOS_TAGNODE_VALUE) not specified')

    wg = deepcopy(default_config_data)
    wg['intf'] = os.environ['VYOS_TAGNODE_VALUE']

    # check if interface is member if a bridge
    wg['is_bridge_member'] = is_member(conf, wg['intf'], 'bridge')

    # Check if interface has been removed
    if not conf.exists(base + [wg['intf']]):
        wg['deleted'] = True
        return wg

    conf.set_level(base + [wg['intf']])

    # retrieve configured interface addresses
    if conf.exists(['address']):
        wg['address'] = conf.return_values(['address'])

    # get interface addresses (currently effective) - to determine which
    # address is no longer valid and needs to be removed
    eff_addr = conf.return_effective_values(['address'])
    wg['address_remove'] = list_diff(eff_addr, wg['address'])

    # retrieve interface description
    if conf.exists(['description']):
        wg['description'] = conf.return_value(['description'])

    # disable interface
    if conf.exists(['disable']):
        wg['disable'] = True

    # local port to listen on
    if conf.exists(['port']):
        wg['listen_port'] = conf.return_value(['port'])

    # fwmark value
    if conf.exists(['fwmark']):
        wg['fwmark'] = int(conf.return_value(['fwmark']))

    # Maximum Transmission Unit (MTU)
    if conf.exists('mtu'):
        wg['mtu'] = int(conf.return_value(['mtu']))

    # retrieve VRF instance
    if conf.exists('vrf'):
        wg['vrf'] = conf.return_value('vrf')

    # private key
    if conf.exists(['private-key']):
        wg['pk'] = "{0}/{1}/private.key".format(
            kdir, conf.return_value(['private-key']))

    # peer removal, wg identifies peers by its pubkey
    peer_eff = conf.list_effective_nodes(['peer'])
    peer_rem = list_diff(peer_eff, conf.list_nodes(['peer']))
    for peer in peer_rem:
        wg['peer_remove'].append(
            conf.return_effective_value(['peer', peer, 'pubkey']))

    # peer settings
    if conf.exists(['peer']):
        for p in conf.list_nodes(['peer']):
            # set new config level for this peer
            conf.set_level(base + [wg['intf'], 'peer', p])
            peer = {
                'allowed-ips': [],
                'address': '',
                'name': p,
                'persistent_keepalive': '',
                'port': '',
                'psk': '',
                'pubkey': ''
            }

            # peer allowed-ips
            if conf.exists(['allowed-ips']):
                peer['allowed-ips'] = conf.return_values(['allowed-ips'])

            # peer address
            if conf.exists(['address']):
                peer['address'] = conf.return_value(['address'])

            # peer port
            if conf.exists(['port']):
                peer['port'] = conf.return_value(['port'])

            # persistent-keepalive
            if conf.exists(['persistent-keepalive']):
                peer['persistent_keepalive'] = conf.return_value(['persistent-keepalive'])

            # preshared-key
            if conf.exists(['preshared-key']):
                peer['psk'] = conf.return_value(['preshared-key'])

            # peer pubkeys
            if conf.exists(['pubkey']):
                key_eff = conf.return_effective_value(['pubkey'])
                key_cfg = conf.return_value(['pubkey'])
                peer['pubkey'] = key_cfg

                # on a pubkey change we need to remove the pubkey first
                # peers are identified by pubkey, so key update means
                # peer removal and re-add
                if key_eff != key_cfg and key_eff != None:
                    wg['peer_remove'].append(key_cfg)

            # if a peer is disabled, we have to exec a remove for it's pubkey
            if conf.exists(['disable']):
                wg['peer_remove'].append(peer['pubkey'])
            else:
                wg['peer'].append(peer)

    return wg
示例#11
0
def get_config():
    macsec = deepcopy(default_config_data)
    conf = Config()

    # determine tagNode instance
    if 'VYOS_TAGNODE_VALUE' not in os.environ:
        raise ConfigError('Interface (VYOS_TAGNODE_VALUE) not specified')

    macsec['intf'] = os.environ['VYOS_TAGNODE_VALUE']
    base_path = ['interfaces', 'macsec', macsec['intf']]

    # check if we are a member of any bridge
    macsec['is_bridge_member'] = is_member(conf, macsec['intf'], 'bridge')

    # Check if interface has been removed
    if not conf.exists(base_path):
        macsec['deleted'] = True
        # When stopping wpa_supplicant we need to stop it via the physical
        # interface - thus we need to retrieve ir from the effective config
        if conf.exists_effective(base_path + ['source-interface']):
            macsec['source_interface'] = conf.return_effective_value(
                base_path + ['source-interface'])

        return macsec

    # set new configuration level
    conf.set_level(base_path)

    # retrieve configured interface addresses
    if conf.exists(['address']):
        macsec['address'] = conf.return_values(['address'])

    # retrieve interface description
    if conf.exists(['description']):
        macsec['description'] = conf.return_value(['description'])

    # Disable this interface
    if conf.exists(['disable']):
        macsec['disable'] = True

    # retrieve interface cipher
    if conf.exists(['security', 'cipher']):
        macsec['security_cipher'] = conf.return_value(['security', 'cipher'])

    # Enable optional MACsec encryption
    if conf.exists(['security', 'encrypt']):
        macsec['security_encrypt'] = True

    # Secure Connectivity Association Key
    if conf.exists(['security', 'mka', 'cak']):
        macsec['security_mka_cak'] = conf.return_value(
            ['security', 'mka', 'cak'])

    # Secure Connectivity Association Name
    if conf.exists(['security', 'mka', 'ckn']):
        macsec['security_mka_ckn'] = conf.return_value(
            ['security', 'mka', 'ckn'])

    # MACsec Key Agreement protocol (MKA) actor priority
    if conf.exists(['security', 'mka', 'priority']):
        macsec['security_mka_priority'] = conf.return_value(
            ['security', 'mka', 'priority'])

    # IEEE 802.1X/MACsec replay protection
    if conf.exists(['security', 'replay-window']):
        macsec['security_replay_window'] = conf.return_value(
            ['security', 'replay-window'])

    # Physical interface
    if conf.exists(['source-interface']):
        macsec['source_interface'] = conf.return_value(['source-interface'])

    # Determine interface addresses (currently effective) - to determine which
    # address is no longer valid and needs to be removed from the interface
    eff_addr = conf.return_effective_values(['address'])
    act_addr = conf.return_values(['address'])
    macsec['address_remove'] = list_diff(eff_addr, act_addr)

    # retrieve VRF instance
    if conf.exists(['vrf']):
        macsec['vrf'] = conf.return_value(['vrf'])

    return macsec
示例#12
0
    def op_show_interface(self):
        wgdump = self._dump().get(self.config['ifname'], None)

        c = Config()
        c.set_level(["interfaces", "wireguard", self.config['ifname']])
        description = c.return_effective_value(["description"])
        ips = c.return_effective_values(["address"])

        print("interface: {}".format(self.config['ifname']))
        if (description):
            print("  description: {}".format(description))

        if (ips):
            print("  address: {}".format(", ".join(ips)))
        print("  public key: {}".format(wgdump['public_key']))
        print("  private key: (hidden)")
        print("  listening port: {}".format(wgdump['listen_port']))
        print()

        for peer in c.list_effective_nodes(["peer"]):
            if wgdump['peers']:
                pubkey = c.return_effective_value(["peer", peer, "pubkey"])
                if pubkey in wgdump['peers']:
                    wgpeer = wgdump['peers'][pubkey]

                    print("  peer: {}".format(peer))
                    print("    public key: {}".format(pubkey))
                    """ figure out if the tunnel is recently active or not """
                    status = "inactive"
                    if (wgpeer['latest_handshake'] is None):
                        """ no handshake ever """
                        status = "inactive"
                    else:
                        if int(wgpeer['latest_handshake']) > 0:
                            delta = timedelta(
                                seconds=int(time.time() -
                                            wgpeer['latest_handshake']))
                            print("    latest handshake: {}".format(delta))
                            if (time.time() - int(wgpeer['latest_handshake']) <
                                (60 * 5)):
                                """ Five minutes and the tunnel is still active """
                                status = "active"
                            else:
                                """ it's been longer than 5 minutes """
                                status = "inactive"
                        elif int(wgpeer['latest_handshake']) == 0:
                            """ no handshake ever """
                            status = "inactive"
                        print("    status: {}".format(status))

                    if wgpeer['endpoint'] is not None:
                        print("    endpoint: {}".format(wgpeer['endpoint']))

                    if wgpeer['allowed_ips'] is not None:
                        print("    allowed ips: {}".format(",".join(
                            wgpeer['allowed_ips']).replace(",", ", ")))

                    if wgpeer['transfer_rx'] > 0 or wgpeer['transfer_tx'] > 0:
                        rx_size = size(wgpeer['transfer_rx'],
                                       system=alternative)
                        tx_size = size(wgpeer['transfer_tx'],
                                       system=alternative)
                        print("    transfer: {} received, {} sent".format(
                            rx_size, tx_size))

                    if wgpeer['persistent_keepalive'] is not None:
                        print("    persistent keepalive: every {} seconds".
                              format(wgpeer['persistent_keepalive']))
                print()
        super().op_show_interface_stats()
示例#13
0
def get_config():
    conf = Config()
    mpls_conf = {
        'router_id'  : None,
        'mpls_ldp'   : False,
        'old_ldp'    : {
                'interfaces'          : [],
                'neighbors'           : {},
                'd_transp_ipv4'       : None,
                'd_transp_ipv6'       : None
        },
        'ldp'        : {
                'interfaces'          : [],
                'neighbors'           : {},
                'd_transp_ipv4'       : None,
                'd_transp_ipv6'       : None
        }
    }
    if not (conf.exists('protocols mpls') or conf.exists_effective('protocols mpls')):
        return None

    if conf.exists('protocols mpls ldp'):
        mpls_conf['mpls_ldp'] = True

    conf.set_level('protocols mpls ldp')

    # Get router-id
    if conf.exists_effective('router-id'):
        mpls_conf['old_router_id'] = conf.return_effective_value('router-id')
    if conf.exists('router-id'):
        mpls_conf['router_id'] = conf.return_value('router-id')

    # Get discovery transport-ipv4-address
    if conf.exists_effective('discovery transport-ipv4-address'):
        mpls_conf['old_ldp']['d_transp_ipv4'] = conf.return_effective_value('discovery transport-ipv4-address')

    if conf.exists('discovery transport-ipv4-address'):
        mpls_conf['ldp']['d_transp_ipv4'] = conf.return_value('discovery transport-ipv4-address')

    # Get discovery transport-ipv6-address
    if conf.exists_effective('discovery transport-ipv6-address'):
        mpls_conf['old_ldp']['d_transp_ipv6'] = conf.return_effective_value('discovery transport-ipv6-address')

    if conf.exists('discovery transport-ipv6-address'):
        mpls_conf['ldp']['d_transp_ipv6'] = conf.return_value('discovery transport-ipv6-address')

    # Get interfaces
    if conf.exists_effective('interface'):
        mpls_conf['old_ldp']['interfaces'] = conf.return_effective_values('interface')

    if conf.exists('interface'):
        mpls_conf['ldp']['interfaces'] = conf.return_values('interface')

    # Get neighbors
    for neighbor in conf.list_effective_nodes('neighbor'):
        mpls_conf['old_ldp']['neighbors'].update({
            neighbor : {
                'password' : conf.return_effective_value('neighbor {0} password'.format(neighbor))
            }
        })

    for neighbor in conf.list_nodes('neighbor'):
        mpls_conf['ldp']['neighbors'].update({
            neighbor : {
                'password' : conf.return_value('neighbor {0} password'.format(neighbor))
            }
        })

    return mpls_conf
def get_config():
    peth = deepcopy(default_config_data)
    conf = Config()

    # determine tagNode instance
    if 'VYOS_TAGNODE_VALUE' not in os.environ:
        raise ConfigError('Interface (VYOS_TAGNODE_VALUE) not specified')

    peth['intf'] = os.environ['VYOS_TAGNODE_VALUE']
    cfg_base = ['interfaces', 'pseudo-ethernet', peth['intf']]

    # Check if interface has been removed
    if not conf.exists(cfg_base):
        peth['deleted'] = True
        return peth

    # set new configuration level
    conf.set_level(cfg_base)

    # retrieve configured interface addresses
    if conf.exists(['address']):
        peth['address'] = conf.return_values(['address'])

    # get interface addresses (currently effective) - to determine which
    # address is no longer valid and needs to be removed
    eff_addr = conf.return_effective_values(['address'])
    peth['address_remove'] = list_diff(eff_addr, peth['address'])

    # retrieve interface description
    if conf.exists(['description']):
        peth['description'] = conf.return_value(['description'])

    # get DHCP client identifier
    if conf.exists(['dhcp-options', 'client-id']):
        peth['dhcp_client_id'] = conf.return_value(['dhcp-options', 'client-id'])

    # DHCP client host name (overrides the system host name)
    if conf.exists(['dhcp-options', 'host-name']):
        peth['dhcp_hostname'] = conf.return_value(['dhcp-options', 'host-name'])

    # DHCP client vendor identifier
    if conf.exists(['dhcp-options', 'vendor-class-id']):
        peth['dhcp_vendor_class_id'] = conf.return_value(['dhcp-options', 'vendor-class-id'])

    # DHCPv6 only acquire config parameters, no address
    if conf.exists(['dhcpv6-options parameters-only']):
        peth['dhcpv6_prm_only'] = True

    # DHCPv6 temporary IPv6 address
    if conf.exists(['dhcpv6-options temporary']):
        peth['dhcpv6_temporary'] = True

    # disable interface
    if conf.exists(['disable']):
        peth['disable'] = True

    # ignore link state changes
    if conf.exists(['disable-link-detect']):
        peth['disable_link_detect'] = 2

    # ARP cache entry timeout in seconds
    if conf.exists(['ip', 'arp-cache-timeout']):
        peth['ip_arp_cache_tmo'] = int(conf.return_value(['ip', 'arp-cache-timeout']))

    # ARP filter configuration
    if conf.exists(['ip', 'disable-arp-filter']):
        peth['ip_disable_arp_filter'] = 0

    # ARP enable accept
    if conf.exists(['ip', 'enable-arp-accept']):
        peth['ip_enable_arp_accept'] = 1

    # ARP enable announce
    if conf.exists(['ip', 'enable-arp-announce']):
        peth['ip_enable_arp_announce'] = 1

    # ARP enable ignore
    if conf.exists(['ip', 'enable-arp-ignore']):
        peth['ip_enable_arp_ignore'] = 1

    # Enable proxy-arp on this interface
    if conf.exists(['ip', 'enable-proxy-arp']):
        peth['ip_proxy_arp'] = 1

    # Enable private VLAN proxy ARP on this interface
    if conf.exists(['ip', 'proxy-arp-pvlan']):
        peth['ip_proxy_arp_pvlan'] = 1

    # Enable acquisition of IPv6 address using stateless autoconfig (SLAAC)
    if conf.exists('ipv6 address autoconf'):
        peth['ipv6_autoconf'] = 1

    # Get prefix for IPv6 addressing based on MAC address (EUI-64)
    if conf.exists('ipv6 address eui64'):
        peth['ipv6_eui64_prefix'] = conf.return_value('ipv6 address eui64')

    # Disable IPv6 forwarding on this interface
    if conf.exists('ipv6 disable-forwarding'):
        peth['ipv6_forwarding'] = 0

    # IPv6 Duplicate Address Detection (DAD) tries
    if conf.exists('ipv6 dup-addr-detect-transmits'):
        peth['ipv6_dup_addr_detect'] = int(conf.return_value('ipv6 dup-addr-detect-transmits'))

    # Physical interface
    if conf.exists(['source-interface']):
        peth['source_interface'] = conf.return_value(['source-interface'])
        tmp = conf.return_effective_value(['source-interface'])
        if tmp != peth['source_interface']:
            peth['source_interface_changed'] = True

    # Media Access Control (MAC) address
    if conf.exists(['mac']):
        peth['mac'] = conf.return_value(['mac'])

    # MACvlan mode
    if conf.exists(['mode']):
        peth['mode'] = conf.return_value(['mode'])

    # retrieve VRF instance
    if conf.exists('vrf'):
        peth['vrf'] = conf.return_value('vrf')

    # re-set configuration level to parse new nodes
    conf.set_level(cfg_base)
    # get vif-s interfaces (currently effective) - to determine which vif-s
    # interface is no longer present and needs to be removed
    eff_intf = conf.list_effective_nodes('vif-s')
    act_intf = conf.list_nodes('vif-s')
    peth['vif_s_remove'] = list_diff(eff_intf, act_intf)

    if conf.exists('vif-s'):
        for vif_s in conf.list_nodes('vif-s'):
            # set config level to vif-s interface
            conf.set_level(cfg_base + ['vif-s', vif_s])
            peth['vif_s'].append(vlan_to_dict(conf))

    # re-set configuration level to parse new nodes
    conf.set_level(cfg_base)
    # Determine vif interfaces (currently effective) - to determine which
    # vif interface is no longer present and needs to be removed
    eff_intf = conf.list_effective_nodes('vif')
    act_intf = conf.list_nodes('vif')
    peth['vif_remove'] = list_diff(eff_intf, act_intf)

    if conf.exists('vif'):
        for vif in conf.list_nodes('vif'):
            # set config level to vif interface
            conf.set_level(cfg_base + ['vif', vif])
            peth['vif'].append(vlan_to_dict(conf))


    return peth
def get_config():
    # determine tagNode instance
    if 'VYOS_TAGNODE_VALUE' not in os.environ:
        raise ConfigError('Interface (VYOS_TAGNODE_VALUE) not specified')

    ifname = os.environ['VYOS_TAGNODE_VALUE']
    conf = Config()

    # initialize kernel module if not loaded
    if not os.path.isfile('/sys/class/net/bonding_masters'):
        import syslog
        syslog.syslog(syslog.LOG_NOTICE, "loading bonding kernel module")
        if call('modprobe bonding max_bonds=0 miimon=250') != 0:
            syslog.syslog(syslog.LOG_NOTICE,
                          "failed loading bonding kernel module")
            raise ConfigError("failed loading bonding kernel module")

    # check if bond has been removed
    cfg_base = 'interfaces bonding ' + ifname
    if not conf.exists(cfg_base):
        bond = deepcopy(default_config_data)
        bond['intf'] = ifname
        bond['deleted'] = True
        return bond

    # set new configuration level
    conf.set_level(cfg_base)

    bond, disabled = intf_to_dict(conf, default_config_data)

    # ARP link monitoring frequency in milliseconds
    if conf.exists('arp-monitor interval'):
        bond['arp_mon_intvl'] = int(conf.return_value('arp-monitor interval'))

    # IP address to use for ARP monitoring
    if conf.exists('arp-monitor target'):
        bond['arp_mon_tgt'] = conf.return_values('arp-monitor target')

    # Bonding transmit hash policy
    if conf.exists('hash-policy'):
        bond['hash_policy'] = conf.return_value('hash-policy')

    # ARP cache entry timeout in seconds
    if conf.exists('ip arp-cache-timeout'):
        bond['ip_arp_cache_tmo'] = int(
            conf.return_value('ip arp-cache-timeout'))

    # Enable private VLAN proxy ARP on this interface
    if conf.exists('ip proxy-arp-pvlan'):
        bond['ip_proxy_arp_pvlan'] = 1

    # Bonding mode
    if conf.exists('mode'):
        act_mode = conf.return_value('mode')
        eff_mode = conf.return_effective_value('mode')
        if not (act_mode == eff_mode):
            bond['shutdown_required'] = True

        bond['mode'] = get_bond_mode(act_mode)

    # determine bond member interfaces (currently configured)
    bond['member'] = conf.return_values('member interface')

    # We can not call conf.return_effective_values() as it would not work
    # on reboots. Reboots/First boot will return that running config and
    # saved config is the same, thus on a reboot the bond members will
    # not be added all (https://phabricator.vyos.net/T2030)
    live_members = BondIf(bond['intf']).get_slaves()
    if not (bond['member'] == live_members):
        bond['shutdown_required'] = True

    # Primary device interface
    if conf.exists('primary'):
        bond['primary'] = conf.return_value('primary')

    add_to_dict(conf, disabled, bond, 'vif', 'vif')
    add_to_dict(conf, disabled, bond, 'vif-s', 'vif_s')

    return bond
示例#16
0
    data = {
        'group': [],
        'trap': [],
        'user': [],
        'view': []
    }
    
    if c.exists_effective('service snmp v3 group'):
        for g in c.list_effective_nodes('service snmp v3 group'):
            group = {
                'name': g,
                'mode': '',
                'view': ''
            }
            group['mode'] = c.return_effective_value('service snmp v3 group {0} mode'.format(g))
            group['view'] = c.return_effective_value('service snmp v3 group {0} view'.format(g))

            data['group'].append(group)

    if c.exists_effective('service snmp v3 user'):
        for u in c.list_effective_nodes('service snmp v3 user'):
            user = {
                'name' : u,
                'mode' : '',
                'auth' : '',
                'priv' : '',
                'group': ''
            }
            user['mode'] = c.return_effective_value('service snmp v3 user {0} mode'.format(u))
            user['auth'] = c.return_effective_value('service snmp v3 user {0} auth type'.format(u))
示例#17
0
        required=True)

    args = parser.parse_args()

    # Do nothing if service is not configured
    config = Config()
    if len(config.list_effective_nodes('interfaces openvpn')) == 0:
        print("No OpenVPN interfaces configured")
        exit(0)

    # search all OpenVPN interfaces and add those with a matching mode to our
    # interfaces list
    interfaces = []
    for intf in config.list_effective_nodes('interfaces openvpn'):
        # get interface type (server, client, site-to-site)
        mode = config.return_effective_value(
            'interfaces openvpn {} mode'.format(intf))
        if args.mode == mode:
            interfaces.append(intf)

    for intf in interfaces:
        data = get_status(args.mode, intf)
        local_host = config.return_effective_value(
            'interfaces openvpn {} local-host'.format(intf))
        local_port = config.return_effective_value(
            'interfaces openvpn {} local-port'.format(intf))
        if local_host and local_port:
            data['local'] = local_host + ':' + local_port

        if args.mode in ['client', 'site-to-site']:
            for client in data['clients']:
                if config.exists_effective(