Beispiel #1
0
def get_config():
    loopback = 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')

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

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

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

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

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

    # 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')
    loopback['address_remove'] = list_diff(eff_addr, act_addr)

    return loopback
Beispiel #2
0
def get_config():
    salt = deepcopy(default_config_data)
    conf = Config()
    base = ['service', 'salt-minion']

    if not conf.exists(base):
        return None
    else:
        conf.set_level(base)

    if conf.exists(['hash']):
        salt['hash'] = conf.return_value(['hash'])

    if conf.exists(['master']):
        salt['master'] = conf.return_values(['master'])

    if conf.exists(['id']):
        salt['salt_id'] = conf.return_value(['id'])

    if conf.exists(['user']):
        salt['user'] = conf.return_value(['user'])

    if conf.exists(['interval']):
        salt['interval'] = conf.return_value(['interval'])

    if conf.exists(['master-key']):
        salt['master_key'] = conf.return_value(['master-key'])
        salt['verify_master_pubkey_sign'] = 'true'

    return salt
def get_config():
    tz = deepcopy(default_config_data)
    conf = Config()
    if conf.exists('system time-zone'):
        tz['name'] = conf.return_value('system time-zone')

    return tz
def get_config():
    conf = Config()
    conf.set_level("service broadcast-relay id")
    relay_id = conf.list_nodes("")
    relays = []

    for id in relay_id:
        interface_list = []
        address = conf.return_value("{0} address".format(id))
        description = conf.return_value("{0} description".format(id))
        port = conf.return_value("{0} port".format(id))

        # split the interface name listing and form a list
        if conf.exists("{0} interface".format(id)):
            intfs_names = conf.return_values("{0} interface".format(id))
            intfs_names = intfs_names.replace("'", "")
            intfs_names = intfs_names.split()
            for name in intfs_names:
                interface_list.append(name)

        relay = {
            "id": id,
            "address": address,
            "description": description,
            "interfaces": interface_list,
            "port": port
        }
        relays.append(relay)

    return relays
Beispiel #5
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
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
def get_config():
    config = Config()
    data = {"install_routes": "yes"}

    if config.exists("vpn ipsec options disable-route-autoinstall"):
        data["install_routes"] = "no"

    if config.exists("vpn ipsec ipsec-interfaces interface"):
        data["ipsec_interfaces"] = config.return_values("vpn ipsec ipsec-interfaces interface")

    # Init config variables
    data["delim_ipsec_l2tp_begin"] = delim_ipsec_l2tp_begin
    data["delim_ipsec_l2tp_end"] = delim_ipsec_l2tp_end
    data["ipsec_ra_conn_file"] = ipsec_ra_conn_file
    data["ra_conn_name"] = ra_conn_name
    # Get l2tp ipsec settings
    data["ipsec_l2tp"] = False
    conf_ipsec_command = "vpn l2tp remote-access ipsec-settings " #last space is useful
    if config.exists(conf_ipsec_command):
        data["ipsec_l2tp"] = True

        # Authentication params
        if config.exists(conf_ipsec_command + "authentication mode"):
            data["ipsec_l2tp_auth_mode"] = config.return_value(conf_ipsec_command + "authentication mode")
        if config.exists(conf_ipsec_command + "authentication pre-shared-secret"):
            data["ipsec_l2tp_secret"] = config.return_value(conf_ipsec_command + "authentication pre-shared-secret")

        # mode x509
        if config.exists(conf_ipsec_command + "authentication x509 ca-cert-file"):
            data["ipsec_l2tp_x509_ca_cert_file"] = config.return_value(conf_ipsec_command + "authentication x509 ca-cert-file")
        if config.exists(conf_ipsec_command + "authentication x509 crl-file"):
            data["ipsec_l2tp_x509_crl_file"] = config.return_value(conf_ipsec_command + "authentication x509 crl-file")
        if config.exists(conf_ipsec_command + "authentication x509 server-cert-file"):
            data["ipsec_l2tp_x509_server_cert_file"] = config.return_value(conf_ipsec_command + "authentication x509 server-cert-file")
            data["server_cert_file_copied"] = server_cert_path+"/"+re.search('\w+(?:\.\w+)*$', config.return_value(conf_ipsec_command + "authentication x509 server-cert-file")).group(0)
        if config.exists(conf_ipsec_command + "authentication x509 server-key-file"):
            data["ipsec_l2tp_x509_server_key_file"] = config.return_value(conf_ipsec_command + "authentication x509 server-key-file")
            data["server_key_file_copied"] = server_key_path+"/"+re.search('\w+(?:\.\w+)*$', config.return_value(conf_ipsec_command + "authentication x509 server-key-file")).group(0)
        if config.exists(conf_ipsec_command + "authentication x509 server-key-password"):
            data["ipsec_l2tp_x509_server_key_password"] = config.return_value(conf_ipsec_command + "authentication x509 server-key-password")

        # Common l2tp ipsec params
        if config.exists(conf_ipsec_command + "ike-lifetime"):
            data["ipsec_l2tp_ike_lifetime"] = config.return_value(conf_ipsec_command + "ike-lifetime")
        else:
            data["ipsec_l2tp_ike_lifetime"] = "3600"

        if config.exists(conf_ipsec_command + "lifetime"):
            data["ipsec_l2tp_lifetime"] = config.return_value(conf_ipsec_command + "lifetime")
        else:
            data["ipsec_l2tp_lifetime"] = "3600"

    if config.exists("vpn l2tp remote-access outside-address"):
        data['outside_addr'] = config.return_value('vpn l2tp remote-access outside-address')

    return data
Beispiel #8
0
def get_config():
    nat = deepcopy(default_config_data)
    conf = Config()

    # read in current nftable (once) for further processing
    tmp = cmd('nft -j list table raw')
    nftable_json = json.loads(tmp)

    # condense the full JSON table into a list with only relevand informations
    pattern = 'nftables[?rule].rule[?expr[].jump].{chain: chain, handle: handle, target: expr[].jump.target | [0]}'
    condensed_json = jmespath.search(pattern, nftable_json)

    if not conf.exists(['nat']):
        nat['helper_functions'] = 'remove'

        # Retrieve current table handler positions
        nat['pre_ct_ignore'] = get_handler(condensed_json, 'PREROUTING',
                                           'VYATTA_CT_HELPER')
        nat['pre_ct_conntrack'] = get_handler(condensed_json, 'PREROUTING',
                                              'NAT_CONNTRACK')
        nat['out_ct_ignore'] = get_handler(condensed_json, 'OUTPUT',
                                           'VYATTA_CT_HELPER')
        nat['out_ct_conntrack'] = get_handler(condensed_json, 'OUTPUT',
                                              'NAT_CONNTRACK')

        nat['deleted'] = True

        return nat

    # check if NAT connection tracking helpers need to be set up - this has to
    # be done only once
    if not get_handler(condensed_json, 'PREROUTING', 'NAT_CONNTRACK'):
        nat['helper_functions'] = 'add'

        # Retrieve current table handler positions
        nat['pre_ct_ignore'] = get_handler(condensed_json, 'PREROUTING',
                                           'VYATTA_CT_IGNORE')
        nat['pre_ct_conntrack'] = get_handler(condensed_json, 'PREROUTING',
                                              'VYATTA_CT_PREROUTING_HOOK')
        nat['out_ct_ignore'] = get_handler(condensed_json, 'OUTPUT',
                                           'VYATTA_CT_IGNORE')
        nat['out_ct_conntrack'] = get_handler(condensed_json, 'OUTPUT',
                                              'VYATTA_CT_OUTPUT_HOOK')

    # set config level for parsing in NAT configuration
    conf.set_level(['nat'])

    # use a common wrapper function to read in the source / destination
    # tree from the config - thus we do not need to replicate almost the
    # same code :-)
    for tgt in ['source', 'destination', 'nptv6']:
        nat[tgt] = parse_source_destination(conf, tgt)

    return nat
def get_config():
    conf = Config()
    options = get_options(conf)
    interface_list = get_interface_list(conf)
    location = get_location(conf)
    lldp = {
        "options": options,
        "interface_list": interface_list,
        "location": location
    }
    return lldp
Beispiel #10
0
def get_config():
    lldp = deepcopy(default_config_data)
    conf = Config()
    if not conf.exists(base):
        return None
    else:
        lldp['options'] = get_options(conf)
        lldp['interface_list'] = get_interface_list(conf)
        lldp['location'] = get_location(conf)

        return lldp
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
def get_config():
    opt = deepcopy(default_config_data)
    conf = Config()
    conf.set_level('system options')
    if conf.exists(''):
        if conf.exists('ctrl-alt-del-action'):
            opt['ctrl_alt_del'] = conf.return_value('ctrl-alt-del-action')

        opt['beep_if_fully_booted'] = conf.exists('beep-if-fully-booted')
        opt['reboot_on_panic'] = conf.exists('reboot-on-panic')

    return opt
Beispiel #13
0
def get_config():
    geneve = 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')

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

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

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

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

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

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

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

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

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

    # Remote address of GENEVE tunnel
    if conf.exists('remote'):
        geneve['remote'] = conf.return_value('remote')

    # Virtual Network Identifier
    if conf.exists('vni'):
        geneve['vni'] = conf.return_value('vni')

    return geneve
def get_config():
    regdom = deepcopy(default_config_data)
    conf = Config()
    base = ['system', 'wifi-regulatory-domain']

    # Check if interface has been removed
    if not conf.exists(base):
        regdom['deleted'] = True
        return regdom
    else:
        regdom['regdom'] = conf.return_value(base)

    return regdom
Beispiel #15
0
def get_config():
    c = Config()
    if not c.exists('protocols static arp'):
        return None

    c.set_level('protocols static')
    config_data = {}

    for ip_addr in c.list_nodes('arp'):
        config_data.update(
            {ip_addr: c.return_value('arp ' + ip_addr + ' hwaddr')})

    return config_data
Beispiel #16
0
def get_config():
    relay = deepcopy(default_config_data)
    conf = Config()
    base = ['service', 'broadcast-relay']

    if not conf.exists(base):
        return None
    else:
        conf.set_level(base)

    # Service can be disabled by user
    if conf.exists('disable'):
        relay['disabled'] = True
        return relay

    # Parse configuration of each individual instance
    if conf.exists('id'):
        for id in conf.list_nodes('id'):
            conf.set_level(base + ['id', id])
            config = {
                'id': id,
                'disabled': False,
                'address': '',
                'description': '',
                'interfaces': [],
                'port': ''
            }

            # Check if individual broadcast relay service is disabled
            if conf.exists(['disable']):
                config['disabled'] = True

            # Source IP of forwarded packets, if empty original senders address is used
            if conf.exists(['address']):
                config['address'] = conf.return_value(['address'])

            # A description for each individual broadcast relay service
            if conf.exists(['description']):
                config['description'] = conf.return_value(['description'])

            # UDP port to listen on for broadcast frames
            if conf.exists(['port']):
                config['port'] = conf.return_value(['port'])

            # Network interfaces to listen on for broadcast frames to be relayed
            if conf.exists(['interface']):
                config['interfaces'] = conf.return_values(['interface'])

            relay['instances'].append(config)

    return relay
def verify(bridge):
    if bridge['dhcpv6_prm_only'] and bridge['dhcpv6_temporary']:
        raise ConfigError(
            'DHCPv6 temporary and parameters-only options are mutually exclusive!'
        )

    vrf_name = bridge['vrf']
    if vrf_name and vrf_name not in interfaces():
        raise ConfigError(f'VRF "{vrf_name}" does not exist')

    conf = Config()
    for intf in bridge['member']:
        # the interface must exist prior adding it to a bridge
        if intf['name'] not in interfaces():
            raise ConfigError(
                (f'Cannot add nonexistent interface "{intf["name"]}" '
                 f'to bridge "{bridge["intf"]}"'))

        if intf['name'] == 'lo':
            raise ConfigError(
                'Loopback interface "lo" can not be added to a bridge')

        # bridge members aren't allowed to be members of another bridge
        for br in conf.list_nodes('interfaces bridge'):
            # it makes no sense to verify ourself in this case
            if br == bridge['intf']:
                continue

            tmp = conf.list_nodes(f'interfaces bridge {br} member interface')
            if intf['name'] in tmp:
                raise ConfigError((
                    f'Cannot add interface "{intf["name"]}" to bridge '
                    f'"{bridge["intf"]}", it is already a member of bridge "{br}"!'
                ))

        # bridge members are not allowed to be bond members
        tmp = is_member(conf, intf['name'], 'bonding')
        if tmp:
            raise ConfigError(
                (f'Cannot add interface "{intf["name"]}" to bridge '
                 f'"{bridge["intf"]}", it is already a member of bond "{tmp}"!'
                 ))

        # bridge members must not have an assigned address
        if has_address_configured(conf, intf['name']):
            raise ConfigError(
                (f'Cannot add interface "{intf["name"]}" to bridge '
                 f'"{bridge["intf"]}", it has an address assigned!'))

    return None
Beispiel #18
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
def get_config():
    opts = copy.deepcopy(default_config_data)
    conf = Config()
    if not conf.exists('firewall options'):
        # bail out early
        return opts
    else:
        conf.set_level('firewall options')

        # Parse configuration of each individual instance
        if conf.exists('interface'):
            for intf in conf.list_nodes('interface'):
                conf.set_level('firewall options interface {0}'.format(intf))
                config = {
                    'intf': intf,
                    'disabled': False,
                    'mss4': '',
                    'mss6': ''
                }

                # Check if individual option is disabled
                if conf.exists('disable'):
                    config['disabled'] = True

                #
                # Get MSS value IPv4
                #
                if conf.exists('adjust-mss'):
                    config['mss4'] = conf.return_value('adjust-mss')

                    # We need a marker that a new iptables chain needs to be generated
                    if not opts['new_chain4']:
                        opts['new_chain4'] = True

                #
                # Get MSS value IPv6
                #
                if conf.exists('adjust-mss6'):
                    config['mss6'] = conf.return_value('adjust-mss6')

                    # We need a marker that a new ip6tables chain needs to be generated
                    if not opts['new_chain6']:
                        opts['new_chain6'] = True

                # Append interface options to global list
                opts['intf_opts'].append(config)

    return opts
Beispiel #20
0
def get_config():
    conf = Config()
    if not conf.exists('service https certificates certbot'):
        return None
    else:
        conf.set_level('service https certificates certbot')

    cert = {}

    if conf.exists('domain-name'):
        cert['domains'] = conf.return_values('domain-name')

    if conf.exists('email'):
        cert['email'] = conf.return_value('email')

    return cert
Beispiel #21
0
def get_config():
    interface_list = []

    conf = Config()
    conf.set_level('service mdns repeater')
    if not conf.exists(''):
        return interface_list

    if conf.exists('interface'):
        intfs_names = []
        intfs_names = conf.return_values('interface')

        for name in intfs_names:
            interface_list.append(name)

    return interface_list
Beispiel #22
0
def get_config():
    vyos_cert = vyos.defaults.vyos_cert_data

    conf = Config()
    if not conf.exists(
            'service https certificates system-generated-certificate'):
        return None
    else:
        conf.set_level(
            'service https certificates system-generated-certificate')

    if conf.exists('lifetime'):
        lifetime = conf.return_value('lifetime')
        vyos_cert['lifetime'] = lifetime

    return vyos_cert
Beispiel #23
0
def show_status():
    # Do nothing if service is not configured
    c = Config()
    if not c.exists_effective('service dns dynamic'):
        print("Dynamic DNS not configured")
        sys.exit(0)

    data = {
        'hosts': []
    }

    with open(cache_file, 'r') as f:
        for line in f:
            if line.startswith('#'):
                continue

            outp = {
                'host': '',
                'ip': '',
                'time': ''
            }

            if 'host=' in line:
                host = line.split('host=')[1]
                if host:
                    outp['host'] = host.split(',')[0]

            if 'ip=' in line:
                ip = line.split('ip=')[1]
                if ip:
                    outp['ip'] = ip.split(',')[0]

            if 'atime=' in line:
                atime = line.split('atime=')[1]
                if atime:
                    tmp = atime.split(',')[0]
                    outp['time'] = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(int(tmp, base=10)))

            if 'status=' in line:
                status = line.split('status=')[1]
                if status:
                    outp['status'] = status.split(',')[0]

            data['hosts'].append(outp)

    tmpl = jinja2.Template(OUT_TMPL_SRC)
    print(tmpl.render(data))
def verify(bridge):
    if bridge['dhcpv6_prm_only'] and bridge['dhcpv6_temporary']:
        raise ConfigError(
            'DHCPv6 temporary and parameters-only options are mutually exclusive!'
        )

    vrf_name = bridge['vrf']
    if vrf_name and vrf_name not in interfaces():
        raise ConfigError(f'VRF "{vrf_name}" does not exist')

    conf = Config()
    for br in conf.list_nodes('interfaces bridge'):
        # it makes no sense to verify ourself in this case
        if br == bridge['intf']:
            continue

        for intf in bridge['member']:
            tmp = conf.list_nodes(
                'interfaces bridge {} member interface'.format(br))
            if intf['name'] in tmp:
                raise ConfigError(
                    'Interface "{}" belongs to bridge "{}" and can not be enslaved.'
                    .format(intf['name'], bridge['intf']))

    # the interface must exist prior adding it to a bridge
    for intf in bridge['member']:
        if intf['name'] not in interfaces():
            raise ConfigError(
                'Can not add non existing interface "{}" to bridge "{}"'.
                format(intf['name'], bridge['intf']))

        if intf['name'] == 'lo':
            raise ConfigError(
                'Loopback interface "lo" can not be added to a bridge')

    # bridge members are not allowed to be bond members, too
    for intf in bridge['member']:
        for bond in conf.list_nodes('interfaces bonding'):
            if conf.exists('interfaces bonding ' + bond + ' member interface'):
                if intf['name'] in conf.return_values('interfaces bonding ' +
                                                      bond +
                                                      ' member interface'):
                    raise ConfigError(
                        'Interface {} belongs to bond {}, can not add it to {}'
                        .format(intf['name'], bond, bridge['intf']))

    return None
Beispiel #25
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
Beispiel #26
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
Beispiel #27
0
def get_config():
    relay = default_config_data
    conf = Config()
    if not conf.exists(['service', 'dhcp-relay']):
        return None
    else:
        conf.set_level(['service', 'dhcp-relay'])

    # Network interfaces to listen on
    if conf.exists(['interface']):
        relay['interface'] = conf.return_values(['interface'])

    # Servers equal to the address of the DHCP server(s)
    if conf.exists(['server']):
        relay['server'] = conf.return_values(['server'])

    conf.set_level(['service', 'dhcp-relay', 'relay-options'])

    if conf.exists(['hop-count']):
        count = '-c ' + conf.return_value(['hop-count'])
        relay['options'].append(count)

    # Specify the maximum packet size to send to a DHCPv4/BOOTP server.
    # This might be done to allow sufficient space for addition of relay agent
    # options while still fitting into the Ethernet MTU size.
    #
    # Available in DHCPv4 mode only:
    if conf.exists(['max-size']):
        size = '-A ' + conf.return_value(['max-size'])
        relay['options'].append(size)

    # Control the handling of incoming DHCPv4 packets which already contain
    # relay agent options. If such a packet does not have giaddr set in its
    # header, the DHCP standard requires that the packet be discarded. However,
    # if giaddr is set, the relay agent may handle the situation in four ways:
    # It may append its own set of relay options to the packet, leaving the
    # supplied option field intact; it may replace the existing agent option
    # field; it may forward the packet unchanged; or, it may discard it.
    #
    # Available in DHCPv4 mode only:
    if conf.exists(['relay-agents-packets']):
        pkt = '-a -m ' + conf.return_value(['relay-agents-packets'])
        relay['options'].append(pkt)

    return relay
Beispiel #28
0
def get_config():
    ip_opt = deepcopy(default_config_data)
    conf = Config()
    conf.set_level('system ip')
    if conf.exists(''):
        if conf.exists('arp table-size'):
            ip_opt['arp_table'] = int(conf.return_value('arp table-size'))

        if conf.exists('disable-forwarding'):
            ip_opt['ipv4_forward'] = '0'

        if conf.exists('multipath ignore-unreachable-nexthops'):
            ip_opt['mp_unreach_nexthop'] = '1'

        if conf.exists('multipath layer4-hashing'):
            ip_opt['mp_layer4_hashing'] = '1'

    return ip_opt
Beispiel #29
0
def get_config():
    """Get configuration"""
    conf = Config()

    hostname = conf.return_value("system host-name")
    domain = conf.return_value("system domain-name")

    # No one likes fixups, but we really don't want VyOS fail to boot
    # if hostname is not in the config
    if not hostname:
        hostname = "vyos"

    if domain:
        fqdn = "{0}.{1}".format(hostname, domain)
    else:
        fqdn = hostname

    return {"hostname": hostname, "domain": domain, "fqdn": fqdn}
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