def get_config():
    conf = Config()
    mroute = {'old_mroute': {}, 'mroute': {}}

    base_path = "protocols static multicast"

    if not (conf.exists(base_path) or conf.exists_effective(base_path)):
        return None

    conf.set_level(base_path)

    # Get multicast effective routes
    for route in conf.list_effective_nodes('route'):
        mroute['old_mroute'][route] = {}
        for next_hop in conf.list_effective_nodes(
                'route {0} next-hop'.format(route)):
            mroute['old_mroute'][route].update({
                next_hop:
                conf.return_value('route {0} next-hop {1} distance'.format(
                    route, next_hop))
            })

    # Get multicast effective interface-routes
    for route in conf.list_effective_nodes('interface-route'):
        if not route in mroute['old_mroute']:
            mroute['old_mroute'][route] = {}
        for next_hop in conf.list_effective_nodes(
                'interface-route {0} next-hop-interface'.format(route)):
            mroute['old_mroute'][route].update({
                next_hop:
                conf.return_value(
                    'interface-route {0} next-hop-interface {1} distance'.
                    format(route, next_hop))
            })

    # Get multicast routes
    for route in conf.list_nodes('route'):
        mroute['mroute'][route] = {}
        for next_hop in conf.list_nodes('route {0} next-hop'.format(route)):
            mroute['mroute'][route].update({
                next_hop:
                conf.return_value('route {0} next-hop {1} distance'.format(
                    route, next_hop))
            })

    # Get multicast interface-routes
    for route in conf.list_nodes('interface-route'):
        if not route in mroute['mroute']:
            mroute['mroute'][route] = {}
        for next_hop in conf.list_nodes(
                'interface-route {0} next-hop-interface'.format(route)):
            mroute['mroute'][route].update({
                next_hop:
                conf.return_value(
                    'interface-route {0} next-hop-interface {1} distance'.
                    format(route, next_hop))
            })

    return mroute
Esempio n. 2
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
Esempio n. 3
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
Esempio n. 4
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
Esempio n. 5
0
def get_config():
    bfd = deepcopy(default_config_data)
    conf = Config()
    if not (conf.exists('protocols bfd')
            or conf.exists_effective('protocols bfd')):
        return None
    else:
        conf.set_level('protocols bfd')

    # as we have to use vtysh to talk to FRR we also need to know
    # which peers are gone due to a config removal - thus we read in
    # all peers (active or to delete)
    for peer in conf.list_effective_nodes('peer'):
        bfd['old_peers'].append(get_bfd_peer_config(peer, "effective"))

    for peer in conf.list_nodes('peer'):
        bfd['new_peers'].append(get_bfd_peer_config(peer))

    # find deleted peers
    set_new_peers = set(conf.list_nodes('peer'))
    set_old_peers = set(conf.list_effective_nodes('peer'))
    bfd['deleted_peers'] = set_old_peers - set_new_peers

    return bfd
Esempio n. 6
0
def get_config():
    c = Config()
    interfaces = dict()
    for intf in c.list_effective_nodes('interfaces ethernet'):
        # skip interfaces that are disabled or is configured for dhcp
        check_disable = "interfaces ethernet {} disable".format(intf)
        check_dhcp = "interfaces ethernet {} address dhcp".format(intf)
        if c.exists_effective(check_disable):
            continue

        # get addresses configured on the interface
        intf_addresses = c.return_effective_values(
            "interfaces ethernet {} address".format(intf))
        interfaces[intf] = [addr.strip("'") for addr in intf_addresses]
    return interfaces
Esempio n. 7
0
def get_config():
    c = Config()
    if not c.exists_effective('interfaces ethernet'):
        return None

    interfaces = {}
    for intf in c.list_effective_nodes('interfaces ethernet'):
        if not c.exists_effective('interfaces ethernet ' + intf +
                                  ' disable') and c.exists_effective(
                                      'interfaces ethernet ' + intf +
                                      ' address'):
            interfaces[intf] = re.sub(
                "\'", "",
                c.return_effective_values('interfaces ethernet ' + intf +
                                          ' address')).split()

    return interfaces
Esempio n. 8
0
def list_users():
    cfg = Config()
    vyos_users = cfg.list_effective_nodes('system login user')
    users = []
    with open('/var/log/lastlog', 'rb') as lastlog_file:
        for (name, _, uid, _, _, _, _) in pwd.getpwall():
            lastlog_info = decode_lastlog(lastlog_file, uid)
            if lastlog_info is None:
                continue
            user_info = UserInfo(
                uid,
                name,
                user_type='vyos' if name in vyos_users else 'other',
                is_locked=is_locked(name),
                login_time=lastlog_info[0],
                tty=lastlog_info[1],
                host=lastlog_info[2])
            users.append(user_info)
    return users
Esempio n. 9
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():
    wifi = 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')

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

    # check if wireless interface has been removed
    cfg_base = 'interfaces wireless ' + wifi['intf']
    if not conf.exists(cfg_base):
        wifi['deleted'] = True
        # we can not bail out early as wireless interface can not be removed
        # Kernel will complain with: RTNETLINK answers: Operation not supported.
        # Thus we need to remove individual settings
        return wifi

    # set new configuration level
    conf.set_level(cfg_base)

    # retrieve configured interface addresses
    if conf.exists('address'):
        wifi['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')
    wifi['address_remove'] = list_diff(eff_addr, wifi['address'])

    # 40MHz intolerance, use 20MHz only
    if conf.exists('capabilities ht 40mhz-incapable'):
        wifi['cap_ht'] = True
        wifi['cap_ht_40mhz_incapable'] = True

    # WMM-PS Unscheduled Automatic Power Save Delivery [U-APSD]
    if conf.exists('capabilities ht auto-powersave'):
        wifi['cap_ht'] = True
        wifi['cap_ht_powersave'] = True

    # Supported channel set width
    if conf.exists('capabilities ht channel-set-width'):
        wifi['cap_ht'] = True
        wifi['cap_ht_chan_set_width'] = conf.return_values('capabilities ht channel-set-width')

    # HT-delayed Block Ack
    if conf.exists('capabilities ht delayed-block-ack'):
        wifi['cap_ht'] = True
        wifi['cap_ht_delayed_block_ack'] = True

    # DSSS/CCK Mode in 40 MHz
    if conf.exists('capabilities ht dsss-cck-40'):
        wifi['cap_ht'] = True
        wifi['cap_ht_dsss_cck_40'] = True

    # HT-greenfield capability
    if conf.exists('capabilities ht greenfield'):
        wifi['cap_ht'] = True
        wifi['cap_ht_greenfield'] = True

    # LDPC coding capability
    if conf.exists('capabilities ht ldpc'):
        wifi['cap_ht'] = True
        wifi['cap_ht_ldpc'] = True

    # L-SIG TXOP protection capability
    if conf.exists('capabilities ht lsig-protection'):
        wifi['cap_ht'] = True
        wifi['cap_ht_lsig_protection'] = True

    # Set Maximum A-MSDU length
    if conf.exists('capabilities ht max-amsdu'):
        wifi['cap_ht'] = True
        wifi['cap_ht_max_amsdu'] = conf.return_value('capabilities ht max-amsdu')

    # Short GI capabilities
    if conf.exists('capabilities ht short-gi'):
        wifi['cap_ht'] = True
        wifi['cap_ht_short_gi'] = conf.return_values('capabilities ht short-gi')

    # Spatial Multiplexing Power Save (SMPS) settings
    if conf.exists('capabilities ht smps'):
        wifi['cap_ht'] = True
        wifi['cap_ht_smps'] = conf.return_value('capabilities ht smps')

    # Support for receiving PPDU using STBC (Space Time Block Coding)
    if conf.exists('capabilities ht stbc rx'):
        wifi['cap_ht'] = True
        wifi['cap_ht_stbc_rx'] = conf.return_value('capabilities ht stbc rx')

    # Support for sending PPDU using STBC (Space Time Block Coding)
    if conf.exists('capabilities ht stbc tx'):
        wifi['cap_ht'] = True
        wifi['cap_ht_stbc_tx'] = True

    # Require stations to support HT PHY (reject association if they do not)
    if conf.exists('capabilities require-ht'):
        wifi['cap_req_ht'] = True

    # Require stations to support VHT PHY (reject association if they do not)
    if conf.exists('capabilities require-vht'):
        wifi['cap_req_vht'] = True

    # Number of antennas on this card
    if conf.exists('capabilities vht antenna-count'):
        wifi['cap_vht'] = True
        wifi['cap_vht_antenna_cnt'] = conf.return_value('capabilities vht antenna-count')

    # set if antenna pattern does not change during the lifetime of an association
    if conf.exists('capabilities vht antenna-pattern-fixed'):
        wifi['cap_vht'] = True
        wifi['cap_vht_antenna_fixed'] = True

    # Beamforming capabilities
    if conf.exists('capabilities vht beamform'):
        wifi['cap_vht'] = True
        wifi['cap_vht_beamform'] = conf.return_values('capabilities vht beamform')

    # VHT operating channel center frequency - center freq 1 (for use with 80, 80+80 and 160 modes)
    if conf.exists('capabilities vht center-channel-freq freq-1'):
        wifi['cap_vht'] = True
        wifi['cap_vht_center_freq_1'] = conf.return_value('capabilities vht center-channel-freq freq-1')

    # VHT operating channel center frequency - center freq 2 (for use with the 80+80 mode)
    if conf.exists('capabilities vht center-channel-freq freq-2'):
        wifi['cap_vht'] = True
        wifi['cap_vht_center_freq_2'] = conf.return_value('capabilities vht center-channel-freq freq-2')

    # VHT operating Channel width
    if conf.exists('capabilities vht channel-set-width'):
        wifi['cap_vht'] = True
        wifi['cap_vht_chan_set_width'] = conf.return_value('capabilities vht channel-set-width')

    # LDPC coding capability
    if conf.exists('capabilities vht ldpc'):
        wifi['cap_vht'] = True
        wifi['cap_vht_ldpc'] = True

    # VHT link adaptation capabilities
    if conf.exists('capabilities vht link-adaptation'):
        wifi['cap_vht'] = True
        wifi['cap_vht_link_adaptation'] = conf.return_value('capabilities vht link-adaptation')

    # Set the maximum length of A-MPDU pre-EOF padding that the station can receive
    if conf.exists('capabilities vht max-mpdu-exp'):
        wifi['cap_vht'] = True
        wifi['cap_vht_max_mpdu_exp'] = conf.return_value('capabilities vht max-mpdu-exp')

    # Increase Maximum MPDU length
    if conf.exists('capabilities vht max-mpdu'):
        wifi['cap_vht'] = True
        wifi['cap_vht_max_mpdu'] = conf.return_value('capabilities vht max-mpdu')

    # Increase Maximum MPDU length
    if conf.exists('capabilities vht short-gi'):
        wifi['cap_vht'] = True
        wifi['cap_vht_short_gi'] = conf.return_values('capabilities vht short-gi')

    # Support for receiving PPDU using STBC (Space Time Block Coding)
    if conf.exists('capabilities vht stbc rx'):
        wifi['cap_vht'] = True
        wifi['cap_vht_stbc_rx'] = conf.return_value('capabilities vht stbc rx')

    # Support for the transmission of at least 2x1 STBC (Space Time Block Coding)
    if conf.exists('capabilities vht stbc tx'):
        wifi['cap_vht'] = True
        wifi['cap_vht_stbc_tx'] = True

    # Support for VHT TXOP Power Save Mode
    if conf.exists('capabilities vht tx-powersave'):
        wifi['cap_vht'] = True
        wifi['cap_vht_tx_powersave'] = True

    # STA supports receiving a VHT variant HT Control field
    if conf.exists('capabilities vht vht-cf'):
        wifi['cap_vht'] = True
        wifi['cap_vht_vht_cf'] = True

    # Wireless radio channel
    if conf.exists('channel'):
        wifi['channel'] = conf.return_value('channel')

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

    # get DHCP client identifier
    if conf.exists('dhcp-options client-id'):
        wifi['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'):
        wifi['dhcp_hostname'] = conf.return_value('dhcp-options host-name')

    # DHCP client vendor identifier
    if conf.exists('dhcp-options vendor-class-id'):
        wifi['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'):
        wifi['dhcpv6_prm_only'] = conf.return_value('dhcpv6-options parameters-only')

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

    # Disable broadcast of SSID from access-point
    if conf.exists('disable-broadcast-ssid'):
        wifi['disable_broadcast_ssid'] = True

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

    # Disassociate stations based on excessive transmission failures
    if conf.exists('expunge-failing-stations'):
        wifi['expunge_failing_stations'] = True

    # retrieve real hardware address
    if conf.exists('hw-id'):
        wifi['hw_id'] = conf.return_value('hw-id')

    # Isolate stations on the AP so they cannot see each other
    if conf.exists('isolate-stations'):
        wifi['isolate_stations'] = True

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

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

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

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

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

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

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

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

    # Wireless physical device
    if conf.exists('physical-device'):
        wifi['phy'] = conf.return_value('physical-device')

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

    # Maximum number of wireless radio stations
    if conf.exists('max-stations'):
        wifi['max_stations'] = conf.return_value('max-stations')

    # Management Frame Protection (MFP) according to IEEE 802.11w
    if conf.exists('mgmt-frame-protection'):
        wifi['mgmt_frame_protection'] = conf.return_value('mgmt-frame-protection')

    # Wireless radio mode
    if conf.exists('mode'):
        wifi['mode'] = conf.return_value('mode')

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

    # Transmission power reduction in dBm
    if conf.exists('reduce-transmit-power'):
        wifi['reduce_transmit_power'] = conf.return_value('reduce-transmit-power')

    # WEP enabled?
    if conf.exists('security wep'):
        wifi['sec_wep'] = True

    # WEP encryption key(s)
    if conf.exists('security wep key'):
        wifi['sec_wep_key'] = conf.return_values('security wep key')

    # WPA enabled?
    if conf.exists('security wpa'):
        wifi['sec_wpa'] = True

    # WPA Cipher suite
    if conf.exists('security wpa cipher'):
        wifi['sec_wpa_cipher'] = conf.return_values('security wpa cipher')

    # WPA mode
    if conf.exists('security wpa mode'):
        wifi['sec_wpa_mode'] = conf.return_value('security wpa mode')

    # WPA default ciphers depend on WPA mode
    if not wifi['sec_wpa_cipher']:
        if wifi['sec_wpa_mode'] == 'wpa':
            wifi['sec_wpa_cipher'].append('TKIP')
            wifi['sec_wpa_cipher'].append('CCMP')

        elif wifi['sec_wpa_mode'] == 'wpa2':
            wifi['sec_wpa_cipher'].append('CCMP')

        elif wifi['sec_wpa_mode'] == 'both':
            wifi['sec_wpa_cipher'].append('CCMP')
            wifi['sec_wpa_cipher'].append('TKIP')

    # WPA personal shared pass phrase
    if conf.exists('security wpa passphrase'):
        wifi['sec_wpa_passphrase'] = conf.return_value('security wpa passphrase')

    # WPA RADIUS source address
    if conf.exists('security wpa radius source-address'):
        wifi['sec_wpa_radius_source'] = conf.return_value('security wpa radius source-address')

    # WPA RADIUS server
    for server in conf.list_nodes('security wpa radius server'):
        # set new configuration level
        conf.set_level(cfg_base + ' security wpa radius server ' + server)
        radius = {
            'server' : server,
            'acc_port' : '',
            'disabled': False,
            'port' : 1812,
            'key' : ''
        }

        # RADIUS server port
        if conf.exists('port'):
            radius['port'] = int(conf.return_value('port'))

        # receive RADIUS accounting info
        if conf.exists('accounting'):
            radius['acc_port'] = radius['port'] + 1

        # Check if RADIUS server was temporary disabled
        if conf.exists(['disable']):
            radius['disabled'] = True

        # RADIUS server shared-secret
        if conf.exists('key'):
            radius['key'] = conf.return_value('key')

        # append RADIUS server to list of servers
        wifi['sec_wpa_radius'].append(radius)

    # re-set configuration level to parse new nodes
    conf.set_level(cfg_base)

    # Wireless access-point service set identifier (SSID)
    if conf.exists('ssid'):
        wifi['ssid'] = conf.return_value('ssid')

    # Wireless device type for this interface
    if conf.exists('type'):
        tmp = conf.return_value('type')
        if tmp == 'access-point':
            tmp = 'ap'

        wifi['op_mode'] = tmp

    # 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')
    wifi['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)
            wifi['vif'].append(vlan_to_dict(conf))

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

    # retrieve configured regulatory domain
    conf.set_level('system')
    if conf.exists('wifi-regulatory-domain'):
        wifi['country_code'] = conf.return_value('wifi-regulatory-domain')

    return wifi
Esempio n. 11
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
Esempio n. 13
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
def get_config():
    eth = 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')

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

    # check if ethernet interface has been removed
    cfg_base = ['interfaces', 'ethernet', eth['intf']]
    if not conf.exists(cfg_base):
        eth['deleted'] = True
        # we can not bail out early as ethernet interface can not be removed
        # Kernel will complain with: RTNETLINK answers: Operation not supported.
        # Thus we need to remove individual settings
        return eth

    # set new configuration level
    conf.set_level(cfg_base)

    # retrieve configured interface addresses
    if conf.exists('address'):
        eth['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')
    eth['address_remove'] = list_diff(eff_addr, eth['address'])

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

    # get DHCP client identifier
    if conf.exists('dhcp-options client-id'):
        eth['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'):
        eth['dhcp_hostname'] = conf.return_value('dhcp-options host-name')

    # DHCP client vendor identifier
    if conf.exists('dhcp-options vendor-class-id'):
        eth['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'):
        eth['dhcpv6_prm_only'] = True

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

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

    # disable ethernet flow control (pause frames)
    if conf.exists('disable-flow-control'):
        eth['flow_control'] = 'off'

    # retrieve real hardware address
    if conf.exists('hw-id'):
        eth['hw_id'] = conf.return_value('hw-id')

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

    # interface duplex
    if conf.exists('duplex'):
        eth['duplex'] = conf.return_value('duplex')

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

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

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

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

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

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

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

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

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

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

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

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

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

    # GRO (generic receive offload)
    if conf.exists('offload-options generic-receive'):
        eth['offload_gro'] = conf.return_value(
            'offload-options generic-receive')

    # GSO (generic segmentation offload)
    if conf.exists('offload-options generic-segmentation'):
        eth['offload_gso'] = conf.return_value(
            'offload-options generic-segmentation')

    # scatter-gather option
    if conf.exists('offload-options scatter-gather'):
        eth['offload_sg'] = conf.return_value('offload-options scatter-gather')

    # TSO (TCP segmentation offloading)
    if conf.exists('offload-options tcp-segmentation'):
        eth['offload_tso'] = conf.return_value(
            'offload-options tcp-segmentation')

    # UDP fragmentation offloading
    if conf.exists('offload-options udp-fragmentation'):
        eth['offload_ufo'] = conf.return_value(
            'offload-options udp-fragmentation')

    # interface speed
    if conf.exists('speed'):
        eth['speed'] = conf.return_value('speed')

    # retrieve VRF instance
    if conf.exists('vrf'):
        eth['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')
    eth['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])
            eth['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')
    eth['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])
            eth['vif'].append(vlan_to_dict(conf))

    return eth
Esempio n. 15
0
def get_config():
    bridge = 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')

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

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

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

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

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

    # retrieve aging - how long addresses are retained
    if conf.exists('aging'):
        bridge['aging'] = int(conf.return_value('aging'))

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

    # get DHCP client identifier
    if conf.exists('dhcp-options client-id'):
        bridge['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'):
        bridge['dhcp_hostname'] = conf.return_value('dhcp-options host-name')

    # DHCP client vendor identifier
    if conf.exists('dhcp-options vendor-class-id'):
        bridge['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'):
        bridge['dhcpv6_prm_only'] = True

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

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

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

    # Forwarding delay
    if conf.exists('forwarding-delay'):
        bridge['forwarding_delay'] = int(conf.return_value('forwarding-delay'))

    # Hello packet advertisment interval
    if conf.exists('hello-time'):
        bridge['hello_time'] = int(conf.return_value('hello-time'))

    # Enable Internet Group Management Protocol (IGMP) querier
    if conf.exists('igmp querier'):
        bridge['igmp_querier'] = 1

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

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

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

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

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

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

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

    # Determine currently effective EUI64 addresses - to determine which
    # address is no longer valid and needs to be removed
    eff_addr = conf.return_effective_values('ipv6 address eui64')
    bridge['ipv6_eui64_prefix_remove'] = list_diff(eff_addr,
                                                   bridge['ipv6_eui64_prefix'])

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

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

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

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

    # Find out if MAC has changed - if so, we need to delete all IPv6 EUI64 addresses
    # before re-adding them
    if (bridge['mac']
            and bridge['intf'] in Section.interfaces(section='bridge') and
            bridge['mac'] != BridgeIf(bridge['intf'], create=False).get_mac()):
        bridge['ipv6_eui64_prefix_remove'] += bridge['ipv6_eui64_prefix']

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

    # Interval at which neighbor bridges are removed
    if conf.exists('max-age'):
        bridge['max_age'] = int(conf.return_value('max-age'))

    # Determine bridge member interface (currently configured)
    for intf in conf.list_nodes('member interface'):
        # defaults are stored in util.py (they can't be here as all interface
        # scripts use the function)
        memberconf = get_bridge_member_config(conf, bridge['intf'], intf)
        if memberconf:
            memberconf['name'] = intf
            bridge['member'].append(memberconf)

    # Determine bridge member interface (currently effective) - to determine which
    # interfaces is no longer assigend to the bridge and thus can be removed
    eff_intf = conf.list_effective_nodes('member interface')
    act_intf = conf.list_nodes('member interface')
    bridge['member_remove'] = list_diff(eff_intf, act_intf)

    # Priority for this bridge
    if conf.exists('priority'):
        bridge['priority'] = int(conf.return_value('priority'))

    # Enable spanning tree protocol
    if conf.exists('stp'):
        bridge['stp'] = 1

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

    return bridge
Esempio n. 16
0
    c = Config()
    if not c.exists_effective('service dhcpv6-server'):
        print("DHCPv6 service is not configured")
        sys.exit(0)

    # if dhcp server is down, inactive leases may still be shown as active, so warn the user.
    if call('systemctl -q is-active isc-dhcpv6-server.service') != 0:
        print(
            "WARNING: DHCPv6 server is configured but not started. Data may be stale."
        )

    if args.leases:
        leases = get_leases(lease_file, args.state, args.pool, args.sort)

        if args.json:
            print(json.dumps(leases, indent=4))
        else:
            show_leases(leases)
    elif args.statistics:
        print("DHCPv6 statistics option is not available")
    elif args.allowed == 'pool':
        print(' '.join(
            c.list_effective_nodes(
                "service dhcpv6-server shared-network-name")))
    elif args.allowed == 'sort':
        print(' '.join(lease_display_fields.keys()))
    elif args.allowed == 'state':
        print(' '.join(lease_valid_states))
    else:
        parser.print_help()
Esempio n. 17
0
    if args.leases:
        leases = get_leases(lease_file, args.state, args.pool, args.sort)

        if args.json:
            print(json.dumps(leases, indent=4))
        else:
            show_leases(leases)

    elif args.statistics:
        pools = []

        # Get relevant pools
        if args.pool:
            pools = [args.pool]
        else:
            pools = config.list_effective_nodes(
                "service dhcp-server shared-network-name")

        # Get pool usage stats
        stats = []
        for p in pools:
            size = get_pool_size(config, p)
            leases = len(get_leases(lease_file, state='active', pool=p))

            if size != 0:
                use_percentage = round(leases / size * 100)
            else:
                use_percentage = 0

            if args.json:
                pool_stats = {
                    "pool": p,
Esempio n. 18
0
def get_config():
    bridge = 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')

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

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

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

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

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

    # retrieve aging - how long addresses are retained
    if conf.exists('aging'):
        bridge['aging'] = int(conf.return_value('aging'))

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

    # get DHCP client identifier
    if conf.exists('dhcp-options client-id'):
        bridge['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'):
        bridge['dhcp_hostname'] = conf.return_value('dhcp-options host-name')

    # DHCP client vendor identifier
    if conf.exists('dhcp-options vendor-class-id'):
        bridge['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'):
        bridge['dhcpv6_prm_only'] = True

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

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

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

    # Forwarding delay
    if conf.exists('forwarding-delay'):
        bridge['forwarding_delay'] = int(conf.return_value('forwarding-delay'))

    # Hello packet advertisment interval
    if conf.exists('hello-time'):
        bridge['hello_time'] = int(conf.return_value('hello-time'))

    # Enable Internet Group Management Protocol (IGMP) querier
    if conf.exists('igmp querier'):
        bridge['igmp_querier'] = 1

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

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

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

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

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

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

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

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

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

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

    # Interval at which neighbor bridges are removed
    if conf.exists('max-age'):
        bridge['max_age'] = int(conf.return_value('max-age'))

    # Determine bridge member interface (currently configured)
    for intf in conf.list_nodes('member interface'):
        # cost and priority initialized with linux defaults
        # by reading /sys/devices/virtual/net/br0/brif/eth2/{path_cost,priority}
        # after adding interface to bridge after reboot
        iface = {'name': intf, 'cost': 100, 'priority': 32}

        if conf.exists('member interface {} cost'.format(intf)):
            iface['cost'] = int(
                conf.return_value('member interface {} cost'.format(intf)))

        if conf.exists('member interface {} priority'.format(intf)):
            iface['priority'] = int(
                conf.return_value('member interface {} priority'.format(intf)))

        bridge['member'].append(iface)

    # Determine bridge member interface (currently effective) - to determine which
    # interfaces is no longer assigend to the bridge and thus can be removed
    eff_intf = conf.list_effective_nodes('member interface')
    act_intf = conf.list_nodes('member interface')
    bridge['member_remove'] = list_diff(eff_intf, act_intf)

    # Priority for this bridge
    if conf.exists('priority'):
        bridge['priority'] = int(conf.return_value('priority'))

    # Enable spanning tree protocol
    if conf.exists('stp'):
        bridge['stp'] = 1

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

    return bridge
Esempio n. 19
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
Esempio n. 20
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()
Esempio n. 21
0
    # Do nothing if service is not configured
    c = Config()
    if not c.exists_effective('service snmp v3'):
        print("SNMP v3 is not configured")
        sys.exit(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' : '',
Esempio n. 22
0
    return data


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '-m',
        '--mode',
        help='OpenVPN operation mode (server, client, site-2-site)',
        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)