Page MenuHomeVyOS Platform

No OneTemporary

Size
188 KB
Referenced Files
None
Subscribers
None
diff --git a/src/conf_mode/interfaces-bonding.py b/src/conf_mode/interfaces-bonding.py
index 6cdfb764c..dcb0b59ed 100755
--- a/src/conf_mode/interfaces-bonding.py
+++ b/src/conf_mode/interfaces-bonding.py
@@ -1,514 +1,514 @@
#!/usr/bin/env python3
#
# Copyright (C) 2019 VyOS maintainers and contributors
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 or later as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
from copy import deepcopy
from sys import exit
from netifaces import interfaces
from vyos.ifconfig import BondIf
from vyos.ifconfig_vlan import apply_vlan_config
from vyos.configdict import list_diff, vlan_to_dict
from vyos.config import Config
from vyos import ConfigError
default_config_data = {
'address': [],
'address_remove': [],
'arp_mon_intvl': 0,
'arp_mon_tgt': [],
'description': '',
'deleted': False,
'dhcp_client_id': '',
'dhcp_hostname': '',
'dhcp_vendor_class_id': '',
'dhcpv6_prm_only': False,
'dhcpv6_temporary': False,
'disable': False,
'disable_link_detect': 1,
'hash_policy': 'layer2',
'ip_arp_cache_tmo': 30,
'ip_disable_arp_filter': 1,
'ip_enable_arp_accept': 0,
'ip_enable_arp_announce': 0,
'ip_enable_arp_ignore': 0,
'ip_proxy_arp': 0,
'ip_proxy_arp_pvlan': 0,
'intf': '',
'mac': '',
'mode': '802.3ad',
'member': [],
'shutdown_required': False,
'mtu': 1500,
'primary': '',
'vif_s': [],
'vif_s_remove': [],
'vif': [],
'vif_remove': []
}
def get_bond_mode(mode):
if mode == 'round-robin':
return 'balance-rr'
elif mode == 'active-backup':
return 'active-backup'
elif mode == 'xor-hash':
return 'balance-xor'
elif mode == 'broadcast':
return 'broadcast'
elif mode == '802.3ad':
return '802.3ad'
elif mode == 'transmit-load-balance':
return 'balance-tlb'
elif mode == 'adaptive-load-balance':
return 'balance-alb'
else:
raise ConfigError('invalid bond mode "{}"'.format(mode))
def get_config():
# initialize kernel module if not loaded
if not os.path.isfile('/sys/class/net/bonding_masters'):
import syslog
syslog.syslog(syslog.LOG_NOTICE, "loading bonding kernel module")
if os.system('modprobe bonding max_bonds=0 miimon=250') != 0:
syslog.syslog(syslog.LOG_NOTICE, "failed loading bonding kernel module")
raise ConfigError("failed loading bonding kernel module")
bond = deepcopy(default_config_data)
conf = Config()
# determine tagNode instance
- try:
- bond['intf'] = os.environ['VYOS_TAGNODE_VALUE']
- except KeyError as E:
- print("Interface not specified")
+ if 'VYOS_TAGNODE_VALUE' not in os.environ:
+ raise ConfigError('Interface (VYOS_TAGNODE_VALUE) not specified')
+
+ bond['intf'] = os.environ['VYOS_TAGNODE_VALUE']
# check if bond has been removed
cfg_base = 'interfaces bonding ' + bond['intf']
if not conf.exists(cfg_base):
bond['deleted'] = True
return bond
# set new configuration level
conf.set_level(cfg_base)
# retrieve configured interface addresses
if conf.exists('address'):
bond['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')
bond['address_remove'] = list_diff(eff_addr, bond['address'])
# ARP link monitoring frequency in milliseconds
if conf.exists('arp-monitor interval'):
bond['arp_mon_intvl'] = int(conf.return_value('arp-monitor interval'))
# IP address to use for ARP monitoring
if conf.exists('arp-monitor target'):
bond['arp_mon_tgt'] = conf.return_values('arp-monitor target')
# retrieve interface description
if conf.exists('description'):
bond['description'] = conf.return_value('description')
# get DHCP client identifier
if conf.exists('dhcp-options client-id'):
bond['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'):
bond['dhcp_hostname'] = conf.return_value('dhcp-options host-name')
# DHCP client vendor identifier
if conf.exists('dhcp-options vendor-class-id'):
bond['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'):
bond['dhcpv6_prm_only'] = True
# DHCPv6 temporary IPv6 address
if conf.exists('dhcpv6-options temporary'):
bond['dhcpv6_temporary'] = True
# ignore link state changes
if conf.exists('disable-link-detect'):
bond['disable_link_detect'] = 2
# disable bond interface
if conf.exists('disable'):
bond['disable'] = True
# Bonding transmit hash policy
if conf.exists('hash-policy'):
bond['hash_policy'] = conf.return_value('hash-policy')
# ARP cache entry timeout in seconds
if conf.exists('ip arp-cache-timeout'):
bond['ip_arp_cache_tmo'] = int(conf.return_value('ip arp-cache-timeout'))
# ARP filter configuration
if conf.exists('ip disable-arp-filter'):
bond['ip_disable_arp_filter'] = 0
# ARP enable accept
if conf.exists('ip enable-arp-accept'):
bond['ip_enable_arp_accept'] = 1
# ARP enable announce
if conf.exists('ip enable-arp-announce'):
bond['ip_enable_arp_announce'] = 1
# ARP enable ignore
if conf.exists('ip enable-arp-ignore'):
bond['ip_enable_arp_ignore'] = 1
# Enable proxy-arp on this interface
if conf.exists('ip enable-proxy-arp'):
bond['ip_proxy_arp'] = 1
# Enable private VLAN proxy ARP on this interface
if conf.exists('ip proxy-arp-pvlan'):
bond['ip_proxy_arp_pvlan'] = 1
# Media Access Control (MAC) address
if conf.exists('mac'):
bond['mac'] = conf.return_value('mac')
# Bonding mode
if conf.exists('mode'):
act_mode = conf.return_value('mode')
eff_mode = conf.return_effective_value('mode')
if not (act_mode == eff_mode):
bond['shutdown_required'] = True
bond['mode'] = get_bond_mode(act_mode)
# Maximum Transmission Unit (MTU)
if conf.exists('mtu'):
bond['mtu'] = int(conf.return_value('mtu'))
# determine bond member interfaces (currently configured)
if conf.exists('member interface'):
bond['member'] = conf.return_values('member interface')
# We can not call conf.return_effective_values() as it would not work
# on reboots. Reboots/First boot will return that running config and
# saved config is the same, thus on a reboot the bond members will
# not be added all (https://phabricator.vyos.net/T2030)
live_members = BondIf(bond['intf']).get_slaves()
if not (bond['member'] == live_members):
bond['shutdown_required'] = True
# Primary device interface
if conf.exists('primary'):
bond['primary'] = conf.return_value('primary')
# 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')
bond['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)
bond['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')
bond['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)
bond['vif'].append(vlan_to_dict(conf))
return bond
def verify(bond):
if len (bond['arp_mon_tgt']) > 16:
raise ConfigError('The maximum number of targets that can be specified is 16')
if bond['primary']:
if bond['mode'] not in ['active-backup', 'balance-tlb', 'balance-alb']:
raise ConfigError('Mode dependency failed, primary not supported ' \
'in this mode.'.format())
if bond['primary'] not in bond['member']:
raise ConfigError('Interface "{}" is not part of the bond' \
.format(bond['primary']))
# DHCPv6 parameters-only and temporary address are mutually exclusive
for vif_s in bond['vif_s']:
if vif_s['dhcpv6_prm_only'] and vif_s['dhcpv6_temporary']:
raise ConfigError('DHCPv6 temporary and parameters-only options are mutually exclusive!')
for vif_c in vif_s['vif_c']:
if vif_c['dhcpv6_prm_only'] and vif_c['dhcpv6_temporary']:
raise ConfigError('DHCPv6 temporary and parameters-only options are mutually exclusive!')
for vif in bond['vif']:
if vif['dhcpv6_prm_only'] and vif['dhcpv6_temporary']:
raise ConfigError('DHCPv6 temporary and parameters-only options are mutually exclusive!')
for vif_s in bond['vif_s']:
for vif in bond['vif']:
if vif['id'] == vif_s['id']:
raise ConfigError('Can not use identical ID on vif and vif-s interface')
conf = Config()
for intf in bond['member']:
# check if member interface is "real"
if intf not in interfaces():
raise ConfigError('interface {} does not exist!'.format(intf))
# a bonding member interface is only allowed to be assigned to one bond!
all_bonds = conf.list_nodes('interfaces bonding')
# We do not need to check our own bond
all_bonds.remove(bond['intf'])
for tmp in all_bonds:
if conf.exists('interfaces bonding ' + tmp + ' member interface ' + intf):
raise ConfigError('can not enslave interface {} which already ' \
'belongs to {}'.format(intf, tmp))
# can not add interfaces with an assigned address to a bond
if conf.exists('interfaces ethernet ' + intf + ' address'):
raise ConfigError('can not enslave interface {} which has an address ' \
'assigned'.format(intf))
# bond members are not allowed to be bridge members, too
for tmp in conf.list_nodes('interfaces bridge'):
if conf.exists('interfaces bridge ' + tmp + ' member interface ' + intf):
raise ConfigError('can not enslave interface {} which belongs to ' \
'bridge {}'.format(intf, tmp))
# bond members are not allowed to be vrrp members, too
for tmp in conf.list_nodes('high-availability vrrp group'):
if conf.exists('high-availability vrrp group ' + tmp + ' interface ' + intf):
raise ConfigError('can not enslave interface {} which belongs to ' \
'VRRP group {}'.format(intf, tmp))
# bond members are not allowed to be underlaying psuedo-ethernet devices
for tmp in conf.list_nodes('interfaces pseudo-ethernet'):
if conf.exists('interfaces pseudo-ethernet ' + tmp + ' link ' + intf):
raise ConfigError('can not enslave interface {} which belongs to ' \
'pseudo-ethernet {}'.format(intf, tmp))
# bond members are not allowed to be underlaying vxlan devices
for tmp in conf.list_nodes('interfaces vxlan'):
if conf.exists('interfaces vxlan ' + tmp + ' link ' + intf):
raise ConfigError('can not enslave interface {} which belongs to ' \
'vxlan {}'.format(intf, tmp))
if bond['primary']:
if bond['primary'] not in bond['member']:
raise ConfigError('primary interface must be a member interface of {}' \
.format(bond['intf']))
if bond['mode'] not in ['active-backup', 'balance-tlb', 'balance-alb']:
raise ConfigError('primary interface only works for mode active-backup, ' \
'transmit-load-balance or adaptive-load-balance')
if bond['arp_mon_intvl'] > 0:
if bond['mode'] in ['802.3ad', 'balance-tlb', 'balance-alb']:
raise ConfigError('ARP link monitoring does not work for mode 802.3ad, ' \
'transmit-load-balance or adaptive-load-balance')
return None
def generate(bond):
return None
def apply(bond):
b = BondIf(bond['intf'])
if bond['deleted']:
# delete interface
b.remove()
else:
# ARP link monitoring frequency, reset miimon when arp-montior is inactive
# this is done inside BondIf automatically
b.set_arp_interval(bond['arp_mon_intvl'])
# ARP monitor targets need to be synchronized between sysfs and CLI.
# Unfortunately an address can't be send twice to sysfs as this will
# result in the following exception: OSError: [Errno 22] Invalid argument.
#
# We remove ALL adresses prior adding new ones, this will remove addresses
# added manually by the user too - but as we are limited to 16 adresses
# from the kernel side this looks valid to me. We won't run into an error
# when a user added manual adresses which would result in having more
# then 16 adresses in total.
arp_tgt_addr = list(map(str, b.get_arp_ip_target().split()))
for addr in arp_tgt_addr:
b.set_arp_ip_target('-' + addr)
# Add configured ARP target addresses
for addr in bond['arp_mon_tgt']:
b.set_arp_ip_target('+' + addr)
# update interface description used e.g. within SNMP
b.set_alias(bond['description'])
# get DHCP config dictionary and update values
opt = b.get_dhcp_options()
if bond['dhcp_client_id']:
opt['client_id'] = bond['dhcp_client_id']
if bond['dhcp_hostname']:
opt['hostname'] = bond['dhcp_hostname']
if bond['dhcp_vendor_class_id']:
opt['vendor_class_id'] = bond['dhcp_vendor_class_id']
# store DHCP config dictionary - used later on when addresses are aquired
b.set_dhcp_options(opt)
# get DHCPv6 config dictionary and update values
opt = b.get_dhcpv6_options()
if bond['dhcpv6_prm_only']:
opt['dhcpv6_prm_only'] = True
if bond['dhcpv6_temporary']:
opt['dhcpv6_temporary'] = True
# store DHCPv6 config dictionary - used later on when addresses are required
b.set_dhcpv6_options(opt)
# ignore link state changes
b.set_link_detect(bond['disable_link_detect'])
# Bonding transmit hash policy
b.set_hash_policy(bond['hash_policy'])
# configure ARP cache timeout in milliseconds
b.set_arp_cache_tmo(bond['ip_arp_cache_tmo'])
# configure ARP filter configuration
b.set_arp_filter(bond['ip_disable_arp_filter'])
# configure ARP accept
b.set_arp_accept(bond['ip_enable_arp_accept'])
# configure ARP announce
b.set_arp_announce(bond['ip_enable_arp_announce'])
# configure ARP ignore
b.set_arp_ignore(bond['ip_enable_arp_ignore'])
# Enable proxy-arp on this interface
b.set_proxy_arp(bond['ip_proxy_arp'])
# Enable private VLAN proxy ARP on this interface
b.set_proxy_arp_pvlan(bond['ip_proxy_arp_pvlan'])
# Change interface MAC address
if bond['mac']:
b.set_mac(bond['mac'])
# Maximum Transmission Unit (MTU)
b.set_mtu(bond['mtu'])
# Primary device interface
if bond['primary']:
b.set_primary(bond['primary'])
# Some parameters can not be changed when the bond is up.
if bond['shutdown_required']:
# Disable bond prior changing of certain properties
b.set_state('down')
# The bonding mode can not be changed when there are interfaces enslaved
# to this bond, thus we will free all interfaces from the bond first!
for intf in b.get_slaves():
b.del_port(intf)
# Bonding policy/mode
b.set_mode(bond['mode'])
# Add (enslave) interfaces to bond
for intf in bond['member']:
b.add_port(intf)
# As the bond interface is always disabled first when changing
# parameters we will only re-enable the interface if it is not
# administratively disabled
if not bond['disable']:
b.set_state('up')
else:
b.set_state('down')
# Configure interface address(es)
# - not longer required addresses get removed first
# - newly addresses will be added second
for addr in bond['address_remove']:
b.del_addr(addr)
for addr in bond['address']:
b.add_addr(addr)
# remove no longer required service VLAN interfaces (vif-s)
for vif_s in bond['vif_s_remove']:
b.del_vlan(vif_s)
# create service VLAN interfaces (vif-s)
for vif_s in bond['vif_s']:
s_vlan = b.add_vlan(vif_s['id'], ethertype=vif_s['ethertype'])
apply_vlan_config(s_vlan, vif_s)
# remove no longer required client VLAN interfaces (vif-c)
# on lower service VLAN interface
for vif_c in vif_s['vif_c_remove']:
s_vlan.del_vlan(vif_c)
# create client VLAN interfaces (vif-c)
# on lower service VLAN interface
for vif_c in vif_s['vif_c']:
c_vlan = s_vlan.add_vlan(vif_c['id'])
apply_vlan_config(c_vlan, vif_c)
# remove no longer required VLAN interfaces (vif)
for vif in bond['vif_remove']:
b.del_vlan(vif)
# create VLAN interfaces (vif)
for vif in bond['vif']:
vlan = b.add_vlan(vif['id'])
apply_vlan_config(vlan, vif)
return None
if __name__ == '__main__':
try:
c = get_config()
verify(c)
generate(c)
apply(c)
except ConfigError as e:
print(e)
exit(1)
diff --git a/src/conf_mode/interfaces-bridge.py b/src/conf_mode/interfaces-bridge.py
index a3213f309..0810d63d6 100755
--- a/src/conf_mode/interfaces-bridge.py
+++ b/src/conf_mode/interfaces-bridge.py
@@ -1,335 +1,335 @@
#!/usr/bin/env python3
#
# Copyright (C) 2019 VyOS maintainers and contributors
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 or later as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
from copy import deepcopy
from sys import exit
from netifaces import interfaces
from vyos.ifconfig import BridgeIf, STPIf
from vyos.configdict import list_diff
from vyos.config import Config
from vyos import ConfigError
default_config_data = {
'address': [],
'address_remove': [],
'aging': 300,
'arp_cache_tmo': 30,
'description': '',
'deleted': False,
'dhcp_client_id': '',
'dhcp_hostname': '',
'dhcp_vendor_class_id': '',
'dhcpv6_prm_only': False,
'dhcpv6_temporary': False,
'disable': False,
'disable_link_detect': 1,
'forwarding_delay': 14,
'hello_time': 2,
'ip_disable_arp_filter': 1,
'ip_enable_arp_accept': 0,
'ip_enable_arp_announce': 0,
'ip_enable_arp_ignore': 0,
'igmp_querier': 0,
'intf': '',
'mac' : '',
'max_age': 20,
'member': [],
'member_remove': [],
'priority': 32768,
'stp': 0
}
def get_config():
bridge = deepcopy(default_config_data)
conf = Config()
# determine tagNode instance
- try:
- bridge['intf'] = os.environ['VYOS_TAGNODE_VALUE']
- except KeyError as E:
- print("Interface not specified")
+ 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
# 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
return bridge
def verify(bridge):
if bridge['dhcpv6_prm_only'] and bridge['dhcpv6_temporary']:
raise ConfigError('DHCPv6 temporary and parameters-only options are mutually exclusive!')
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']))
# 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
def generate(bridge):
return None
def apply(bridge):
br = BridgeIf(bridge['intf'])
if bridge['deleted']:
# delete interface
br.remove()
else:
# enable interface
br.set_state('up')
# set ageing time
br.set_ageing_time(bridge['aging'])
# set bridge forward delay
br.set_forward_delay(bridge['forwarding_delay'])
# set hello time
br.set_hello_time(bridge['hello_time'])
# configure ARP filter configuration
br.set_arp_filter(bridge['ip_disable_arp_filter'])
# configure ARP accept
br.set_arp_accept(bridge['ip_enable_arp_accept'])
# configure ARP announce
br.set_arp_announce(bridge['ip_enable_arp_announce'])
# configure ARP ignore
br.set_arp_ignore(bridge['ip_enable_arp_ignore'])
# set max message age
br.set_max_age(bridge['max_age'])
# set bridge priority
br.set_priority(bridge['priority'])
# turn stp on/off
br.set_stp(bridge['stp'])
# enable or disable IGMP querier
br.set_multicast_querier(bridge['igmp_querier'])
# update interface description used e.g. within SNMP
br.set_alias(bridge['description'])
# get DHCP config dictionary and update values
opt = br.get_dhcp_options()
if bridge['dhcp_client_id']:
opt['client_id'] = bridge['dhcp_client_id']
if bridge['dhcp_hostname']:
opt['hostname'] = bridge['dhcp_hostname']
if bridge['dhcp_vendor_class_id']:
opt['vendor_class_id'] = bridge['dhcp_vendor_class_id']
# store DHCPv6 config dictionary - used later on when addresses are aquired
br.set_dhcp_options(opt)
# get DHCPv6 config dictionary and update values
opt = br.get_dhcpv6_options()
if bridge['dhcpv6_prm_only']:
opt['dhcpv6_prm_only'] = True
if bridge['dhcpv6_temporary']:
opt['dhcpv6_temporary'] = True
# store DHCPv6 config dictionary - used later on when addresses are aquired
br.set_dhcpv6_options(opt)
# Change interface MAC address
if bridge['mac']:
br.set_mac(bridge['mac'])
# remove interface from bridge
for intf in bridge['member_remove']:
br.del_port(intf)
# add interfaces to bridge
for member in bridge['member']:
br.add_port(member['name'])
# up/down interface
if bridge['disable']:
br.set_state('down')
# Configure interface address(es)
# - not longer required addresses get removed first
# - newly addresses will be added second
for addr in bridge['address_remove']:
br.del_addr(addr)
for addr in bridge['address']:
br.add_addr(addr)
# configure additional bridge member options
for member in bridge['member']:
i = STPIf(member['name'])
# configure ARP cache timeout
i.set_arp_cache_tmo(bridge['arp_cache_tmo'])
# ignore link state changes
i.set_link_detect(bridge['disable_link_detect'])
# set bridge port path cost
i.set_path_cost(member['cost'])
# set bridge port path priority
i.set_path_priority(member['priority'])
return None
if __name__ == '__main__':
try:
c = get_config()
verify(c)
generate(c)
apply(c)
except ConfigError as e:
print(e)
exit(1)
diff --git a/src/conf_mode/interfaces-dummy.py b/src/conf_mode/interfaces-dummy.py
index eb0145f65..e79e6222d 100755
--- a/src/conf_mode/interfaces-dummy.py
+++ b/src/conf_mode/interfaces-dummy.py
@@ -1,114 +1,114 @@
#!/usr/bin/env python3
#
# Copyright (C) 2019 VyOS maintainers and contributors
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 or later as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
from copy import deepcopy
from sys import exit
from vyos.ifconfig import DummyIf
from vyos.configdict import list_diff
from vyos.config import Config
from vyos import ConfigError
default_config_data = {
'address': [],
'address_remove': [],
'deleted': False,
'description': '',
'disable': False,
'intf': ''
}
def get_config():
dummy = deepcopy(default_config_data)
conf = Config()
# determine tagNode instance
- try:
- dummy['intf'] = os.environ['VYOS_TAGNODE_VALUE']
- except KeyError as E:
- print("Interface not specified")
+ if 'VYOS_TAGNODE_VALUE' not in os.environ:
+ raise ConfigError('Interface (VYOS_TAGNODE_VALUE) not specified')
+
+ dummy['intf'] = os.environ['VYOS_TAGNODE_VALUE']
# Check if interface has been removed
if not conf.exists('interfaces dummy ' + dummy['intf']):
dummy['deleted'] = True
return dummy
# set new configuration level
conf.set_level('interfaces dummy ' + dummy['intf'])
# retrieve configured interface addresses
if conf.exists('address'):
dummy['address'] = conf.return_values('address')
# retrieve interface description
if conf.exists('description'):
dummy['description'] = conf.return_value('description')
# Disable this interface
if conf.exists('disable'):
dummy['disable'] = True
# 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')
dummy['address_remove'] = list_diff(eff_addr, act_addr)
return dummy
def verify(dummy):
return None
def generate(dummy):
return None
def apply(dummy):
d = DummyIf(dummy['intf'])
# Remove dummy interface
if dummy['deleted']:
d.remove()
else:
# update interface description used e.g. within SNMP
d.set_alias(dummy['description'])
# Configure interface address(es)
# - not longer required addresses get removed first
# - newly addresses will be added second
for addr in dummy['address_remove']:
d.del_addr(addr)
for addr in dummy['address']:
d.add_addr(addr)
# disable interface on demand
if dummy['disable']:
d.set_state('down')
else:
d.set_state('up')
return None
if __name__ == '__main__':
try:
c = get_config()
verify(c)
generate(c)
apply(c)
except ConfigError as e:
print(e)
exit(1)
diff --git a/src/conf_mode/interfaces-ethernet.py b/src/conf_mode/interfaces-ethernet.py
index e4f6e5ff2..43cc22589 100755
--- a/src/conf_mode/interfaces-ethernet.py
+++ b/src/conf_mode/interfaces-ethernet.py
@@ -1,419 +1,419 @@
#!/usr/bin/env python3
#
# Copyright (C) 2019 VyOS maintainers and contributors
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 or later as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
from copy import deepcopy
from sys import exit
from vyos.ifconfig import EthernetIf
from vyos.ifconfig_vlan import apply_vlan_config
from vyos.configdict import list_diff, vlan_to_dict
from vyos.config import Config
from vyos import ConfigError
default_config_data = {
'address': [],
'address_remove': [],
'description': '',
'deleted': False,
'dhcp_client_id': '',
'dhcp_hostname': '',
'dhcp_vendor_class_id': '',
'dhcpv6_prm_only': False,
'dhcpv6_temporary': False,
'disable': False,
'disable_link_detect': 1,
'duplex': 'auto',
'flow_control': 'on',
'hw_id': '',
'ip_arp_cache_tmo': 30,
'ip_disable_arp_filter': 1,
'ip_enable_arp_accept': 0,
'ip_enable_arp_announce': 0,
'ip_enable_arp_ignore': 0,
'ip_proxy_arp': 0,
'ip_proxy_arp_pvlan': 0,
'intf': '',
'mac': '',
'mtu': 1500,
'offload_gro': 'off',
'offload_gso': 'off',
'offload_sg': 'off',
'offload_tso': 'off',
'offload_ufo': 'off',
'speed': 'auto',
'vif_s': [],
'vif_s_remove': [],
'vif': [],
'vif_remove': []
}
def get_config():
eth = deepcopy(default_config_data)
conf = Config()
# determine tagNode instance
- try:
- eth['intf'] = os.environ['VYOS_TAGNODE_VALUE']
- except KeyError as E:
- print("Interface not specified")
+ 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
# 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')
# 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
def verify(eth):
if eth['deleted']:
return None
if eth['speed'] == 'auto':
if eth['duplex'] != 'auto':
raise ConfigError('If speed is hardcoded, duplex must be hardcoded, too')
if eth['duplex'] == 'auto':
if eth['speed'] != 'auto':
raise ConfigError('If duplex is hardcoded, speed must be hardcoded, too')
if eth['dhcpv6_prm_only'] and eth['dhcpv6_temporary']:
raise ConfigError('DHCPv6 temporary and parameters-only options are mutually exclusive!')
conf = Config()
# some options can not be changed when interface is enslaved to a bond
for bond in conf.list_nodes('interfaces bonding'):
if conf.exists('interfaces bonding ' + bond + ' member interface'):
bond_member = conf.return_values('interfaces bonding ' + bond + ' member interface')
if eth['intf'] in bond_member:
if eth['address']:
raise ConfigError('Can not assign address to interface {} which is a member of {}').format(eth['intf'], bond)
# DHCPv6 parameters-only and temporary address are mutually exclusive
for vif_s in eth['vif_s']:
if vif_s['dhcpv6_prm_only'] and vif_s['dhcpv6_temporary']:
raise ConfigError('DHCPv6 temporary and parameters-only options are mutually exclusive!')
for vif_c in vif_s['vif_c']:
if vif_c['dhcpv6_prm_only'] and vif_c['dhcpv6_temporary']:
raise ConfigError('DHCPv6 temporary and parameters-only options are mutually exclusive!')
for vif in eth['vif']:
if vif['dhcpv6_prm_only'] and vif['dhcpv6_temporary']:
raise ConfigError('DHCPv6 temporary and parameters-only options are mutually exclusive!')
return None
def generate(eth):
return None
def apply(eth):
e = EthernetIf(eth['intf'])
if eth['deleted']:
# delete interface
e.remove()
else:
# update interface description used e.g. within SNMP
e.set_alias(eth['description'])
# get DHCP config dictionary and update values
opt = e.get_dhcp_options()
if eth['dhcp_client_id']:
opt['client_id'] = eth['dhcp_client_id']
if eth['dhcp_hostname']:
opt['hostname'] = eth['dhcp_hostname']
if eth['dhcp_vendor_class_id']:
opt['vendor_class_id'] = eth['dhcp_vendor_class_id']
# store DHCP config dictionary - used later on when addresses are aquired
e.set_dhcp_options(opt)
# get DHCPv6 config dictionary and update values
opt = e.get_dhcpv6_options()
if eth['dhcpv6_prm_only']:
opt['dhcpv6_prm_only'] = True
if eth['dhcpv6_temporary']:
opt['dhcpv6_temporary'] = True
# store DHCPv6 config dictionary - used later on when addresses are aquired
e.set_dhcpv6_options(opt)
# ignore link state changes
e.set_link_detect(eth['disable_link_detect'])
# disable ethernet flow control (pause frames)
e.set_flow_control(eth['flow_control'])
# configure ARP cache timeout in milliseconds
e.set_arp_cache_tmo(eth['ip_arp_cache_tmo'])
# configure ARP filter configuration
e.set_arp_filter(eth['ip_disable_arp_filter'])
# configure ARP accept
e.set_arp_accept(eth['ip_enable_arp_accept'])
# configure ARP announce
e.set_arp_announce(eth['ip_enable_arp_announce'])
# configure ARP ignore
e.set_arp_ignore(eth['ip_enable_arp_ignore'])
# Enable proxy-arp on this interface
e.set_proxy_arp(eth['ip_proxy_arp'])
# Enable private VLAN proxy ARP on this interface
e.set_proxy_arp_pvlan(eth['ip_proxy_arp_pvlan'])
# Change interface MAC address - re-set to real hardware address (hw-id)
# if custom mac is removed
if eth['mac']:
e.set_mac(eth['mac'])
else:
e.set_mac(eth['hw_id'])
# Maximum Transmission Unit (MTU)
e.set_mtu(eth['mtu'])
# GRO (generic receive offload)
e.set_gro(eth['offload_gro'])
# GSO (generic segmentation offload)
e.set_gso(eth['offload_gso'])
# scatter-gather option
e.set_sg(eth['offload_sg'])
# TSO (TCP segmentation offloading)
e.set_tso(eth['offload_tso'])
# UDP fragmentation offloading
e.set_ufo(eth['offload_ufo'])
# Set physical interface speed and duplex
e.set_speed_duplex(eth['speed'], eth['duplex'])
# Enable/Disable interface
if eth['disable']:
e.set_state('down')
else:
e.set_state('up')
# Configure interface address(es)
# - not longer required addresses get removed first
# - newly addresses will be added second
for addr in eth['address_remove']:
e.del_addr(addr)
for addr in eth['address']:
e.add_addr(addr)
# remove no longer required service VLAN interfaces (vif-s)
for vif_s in eth['vif_s_remove']:
e.del_vlan(vif_s)
# create service VLAN interfaces (vif-s)
for vif_s in eth['vif_s']:
s_vlan = e.add_vlan(vif_s['id'], ethertype=vif_s['ethertype'])
apply_vlan_config(s_vlan, vif_s)
# remove no longer required client VLAN interfaces (vif-c)
# on lower service VLAN interface
for vif_c in vif_s['vif_c_remove']:
s_vlan.del_vlan(vif_c)
# create client VLAN interfaces (vif-c)
# on lower service VLAN interface
for vif_c in vif_s['vif_c']:
c_vlan = s_vlan.add_vlan(vif_c['id'])
apply_vlan_config(c_vlan, vif_c)
# remove no longer required VLAN interfaces (vif)
for vif in eth['vif_remove']:
e.del_vlan(vif)
# create VLAN interfaces (vif)
for vif in eth['vif']:
# QoS priority mapping can only be set during interface creation
# so we delete the interface first if required.
if vif['egress_qos_changed'] or vif['ingress_qos_changed']:
try:
# on system bootup the above condition is true but the interface
# does not exists, which throws an exception, but that's legal
e.del_vlan(vif['id'])
except:
pass
vlan = e.add_vlan(vif['id'], ingress_qos=vif['ingress_qos'], egress_qos=vif['egress_qos'])
apply_vlan_config(vlan, vif)
return None
if __name__ == '__main__':
try:
c = get_config()
verify(c)
generate(c)
apply(c)
except ConfigError as e:
print(e)
exit(1)
diff --git a/src/conf_mode/interfaces-geneve.py b/src/conf_mode/interfaces-geneve.py
index eb18ec7a4..8278b54b0 100755
--- a/src/conf_mode/interfaces-geneve.py
+++ b/src/conf_mode/interfaces-geneve.py
@@ -1,164 +1,164 @@
#!/usr/bin/env python3
#
# Copyright (C) 2019 VyOS maintainers and contributors
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 or later as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
from sys import exit
from copy import deepcopy
from vyos.config import Config
from vyos.ifconfig import GeneveIf, Interface
from vyos import ConfigError
from netifaces import interfaces
default_config_data = {
'address': [],
'deleted': False,
'description': '',
'disable': False,
'intf': '',
'ip_arp_cache_tmo': 30,
'ip_proxy_arp': 0,
'mtu': 1500,
'remote': '',
'vni': ''
}
def get_config():
geneve = deepcopy(default_config_data)
conf = Config()
# determine tagNode instance
- try:
- geneve['intf'] = os.environ['VYOS_TAGNODE_VALUE']
- except KeyError as E:
- print("Interface not specified")
+ 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 verify(geneve):
if geneve['deleted']:
# bail out early
return None
if not geneve['remote']:
raise ConfigError('GENEVE remote must be configured')
if not geneve['vni']:
raise ConfigError('GENEVE VNI must be configured')
return None
def generate(geneve):
return None
def apply(geneve):
# Check if GENEVE interface already exists
if geneve['intf'] in interfaces():
g = GeneveIf(geneve['intf'])
# GENEVE is super picky and the tunnel always needs to be recreated,
# thus we can simply always delete it first.
g.remove()
if not geneve['deleted']:
# GENEVE interface needs to be created on-block
# instead of passing a ton of arguments, I just use a dict
# that is managed by vyos.ifconfig
conf = deepcopy(GeneveIf.get_config())
# Assign GENEVE instance configuration parameters to config dict
conf['vni'] = geneve['vni']
conf['remote'] = geneve['remote']
# Finally create the new interface
g = GeneveIf(geneve['intf'], **conf)
# update interface description used e.g. by SNMP
g.set_alias(geneve['description'])
# Maximum Transfer Unit (MTU)
g.set_mtu(geneve['mtu'])
# configure ARP cache timeout in milliseconds
g.set_arp_cache_tmo(geneve['ip_arp_cache_tmo'])
# Enable proxy-arp on this interface
g.set_proxy_arp(geneve['ip_proxy_arp'])
# Configure interface address(es) - no need to implicitly delete the
# old addresses as they have already been removed by deleting the
# interface above
for addr in geneve['address']:
g.add_addr(addr)
# As the GENEVE interface is always disabled first when changing
# parameters we will only re-enable the interface if it is not
# administratively disabled
if not geneve['disable']:
g.set_state('up')
return None
if __name__ == '__main__':
try:
c = get_config()
verify(c)
generate(c)
apply(c)
except ConfigError as e:
print(e)
exit(1)
diff --git a/src/conf_mode/interfaces-l2tpv3.py b/src/conf_mode/interfaces-l2tpv3.py
index 44fd02654..1b9425f64 100755
--- a/src/conf_mode/interfaces-l2tpv3.py
+++ b/src/conf_mode/interfaces-l2tpv3.py
@@ -1,239 +1,239 @@
#!/usr/bin/env python3
#
# Copyright (C) 2019 VyOS maintainers and contributors
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 or later as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
from sys import exit
from copy import deepcopy
from vyos.config import Config
from vyos.ifconfig import L2TPv3If, Interface
from vyos import ConfigError
from netifaces import interfaces
default_config_data = {
'address': [],
'deleted': False,
'description': '',
'disable': False,
'encapsulation': 'udp',
'local_address': '',
'local_port': 5000,
'intf': '',
'mtu': 1488,
'peer_session_id': '',
'peer_tunnel_id': '',
'remote_address': '',
'remote_port': 5000,
'session_id': '',
'tunnel_id': ''
}
def get_config():
l2tpv3 = deepcopy(default_config_data)
conf = Config()
# determine tagNode instance
- try:
- l2tpv3['intf'] = os.environ['VYOS_TAGNODE_VALUE']
- except KeyError as E:
- print("Interface not specified")
+ if 'VYOS_TAGNODE_VALUE' not in os.environ:
+ raise ConfigError('Interface (VYOS_TAGNODE_VALUE) not specified')
+
+ l2tpv3['intf'] = os.environ['VYOS_TAGNODE_VALUE']
# Check if interface has been removed
if not conf.exists('interfaces l2tpv3 ' + l2tpv3['intf']):
l2tpv3['deleted'] = True
# to delete the l2tpv3 interface we need to current
# tunnel_id and session_id
if conf.exists_effective('interfaces l2tpv3 {} tunnel-id'.format(l2tpv3['intf'])):
l2tpv3['tunnel_id'] = conf.return_effective_value(
'interfaces l2tpv3 {} tunnel-id'.format(l2tpv3['intf']))
if conf.exists_effective('interfaces l2tpv3 {} session-id'.format(l2tpv3['intf'])):
l2tpv3['session_id'] = conf.return_effective_value(
'interfaces l2tpv3 {} session-id'.format(l2tpv3['intf']))
return l2tpv3
# set new configuration level
conf.set_level('interfaces l2tpv3 ' + l2tpv3['intf'])
# retrieve configured interface addresses
if conf.exists('address'):
l2tpv3['address'] = conf.return_values('address')
# retrieve interface description
if conf.exists('description'):
l2tpv3['description'] = conf.return_value('description')
# get tunnel destination port
if conf.exists('destination-port'):
l2tpv3['remote_port'] = int(conf.return_value('destination-port'))
# Disable this interface
if conf.exists('disable'):
l2tpv3['disable'] = True
# get tunnel encapsulation type
if conf.exists('encapsulation'):
l2tpv3['encapsulation'] = conf.return_value('encapsulation')
# get tunnel local ip address
if conf.exists('local-ip'):
l2tpv3['local_address'] = conf.return_value('local-ip')
# Maximum Transmission Unit (MTU)
if conf.exists('mtu'):
l2tpv3['mtu'] = int(conf.return_value('mtu'))
# Remote session id
if conf.exists('peer-session-id'):
l2tpv3['peer_session_id'] = conf.return_value('peer-session-id')
# Remote tunnel id
if conf.exists('peer-tunnel-id'):
l2tpv3['peer_tunnel_id'] = conf.return_value('peer-tunnel-id')
# Remote address of L2TPv3 tunnel
if conf.exists('remote-ip'):
l2tpv3['remote_address'] = conf.return_value('remote-ip')
# Local session id
if conf.exists('session-id'):
l2tpv3['session_id'] = conf.return_value('session-id')
# get local tunnel port
if conf.exists('source-port'):
l2tpv3['local_port'] = conf.return_value('source-port')
# get local tunnel id
if conf.exists('tunnel-id'):
l2tpv3['tunnel_id'] = conf.return_value('tunnel-id')
return l2tpv3
def verify(l2tpv3):
if l2tpv3['deleted']:
# bail out early
return None
if not l2tpv3['local_address']:
raise ConfigError('Must configure the l2tpv3 local-ip for {}'.format(l2tpv3['intf']))
if not l2tpv3['remote_address']:
raise ConfigError('Must configure the l2tpv3 remote-ip for {}'.format(l2tpv3['intf']))
if not l2tpv3['tunnel_id']:
raise ConfigError('Must configure the l2tpv3 tunnel-id for {}'.format(l2tpv3['intf']))
if not l2tpv3['peer_tunnel_id']:
raise ConfigError('Must configure the l2tpv3 peer-tunnel-id for {}'.format(l2tpv3['intf']))
if not l2tpv3['session_id']:
raise ConfigError('Must configure the l2tpv3 session-id for {}'.format(l2tpv3['intf']))
if not l2tpv3['peer_session_id']:
raise ConfigError('Must configure the l2tpv3 peer-session-id for {}'.format(l2tpv3['intf']))
return None
def generate(l2tpv3):
if l2tpv3['deleted']:
# bail out early
return None
# initialize kernel module if not loaded
if not os.path.isdir('/sys/module/l2tp_eth'):
if os.system('modprobe l2tp_eth') != 0:
raise ConfigError("failed loading l2tp_eth kernel module")
if not os.path.isdir('/sys/module/l2tp_netlink'):
if os.system('modprobe l2tp_netlink') != 0:
raise ConfigError("failed loading l2tp_netlink kernel module")
if not os.path.isdir('/sys/module/l2tp_ip'):
if os.system('modprobe l2tp_ip') != 0:
raise ConfigError("failed loading l2tp_ip kernel module")
if l2tpv3['encapsulation'] == 'ip':
if not os.path.isdir('/sys/module/l2tp_ip'):
if os.system('modprobe l2tp_ip') != 0:
raise ConfigError("failed loading l2tp_ip kernel module")
if not os.path.isdir('/sys/module/l2tp_ip6 '):
if os.system('modprobe l2tp_ip6 ') != 0:
raise ConfigError("failed loading l2tp_ip6 kernel module")
return None
def apply(l2tpv3):
# L2TPv3 interface needs to be created/deleted on-block, instead of
# passing a ton of arguments, I just use a dict that is managed by
# vyos.ifconfig
conf = deepcopy(L2TPv3If.get_config())
# Check if L2TPv3 interface already exists
if l2tpv3['intf'] in interfaces():
# L2TPv3 is picky when changing tunnels/sessions, thus we can simply
# always delete it first.
conf['session_id'] = l2tpv3['session_id']
conf['tunnel_id'] = l2tpv3['tunnel_id']
l = L2TPv3If(l2tpv3['intf'], **conf)
l.remove()
if not l2tpv3['deleted']:
conf['peer_tunnel_id'] = l2tpv3['peer_tunnel_id']
conf['local_port'] = l2tpv3['local_port']
conf['remote_port'] = l2tpv3['remote_port']
conf['encapsulation'] = l2tpv3['encapsulation']
conf['local_address'] = l2tpv3['local_address']
conf['remote_address'] = l2tpv3['remote_address']
conf['session_id'] = l2tpv3['session_id']
conf['tunnel_id'] = l2tpv3['tunnel_id']
conf['peer_session_id'] = l2tpv3['peer_session_id']
# Finally create the new interface
l = L2TPv3If(l2tpv3['intf'], **conf)
# update interface description used e.g. by SNMP
l.set_alias(l2tpv3['description'])
# Maximum Transfer Unit (MTU)
l.set_mtu(l2tpv3['mtu'])
# Configure interface address(es) - no need to implicitly delete the
# old addresses as they have already been removed by deleting the
# interface above
for addr in l2tpv3['address']:
l.add_addr(addr)
# As the interface is always disabled first when changing parameters
# we will only re-enable the interface if it is not administratively
# disabled
if not l2tpv3['disable']:
l.set_state('up')
return None
if __name__ == '__main__':
try:
c = get_config()
verify(c)
generate(c)
apply(c)
except ConfigError as e:
print(e)
exit(1)
diff --git a/src/conf_mode/interfaces-loopback.py b/src/conf_mode/interfaces-loopback.py
index 10722d137..ddd18ae24 100755
--- a/src/conf_mode/interfaces-loopback.py
+++ b/src/conf_mode/interfaces-loopback.py
@@ -1,100 +1,100 @@
#!/usr/bin/env python3
#
# Copyright (C) 2019 VyOS maintainers and contributors
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 or later as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
from sys import exit
from copy import deepcopy
from vyos.ifconfig import LoopbackIf
from vyos.configdict import list_diff
from vyos.config import Config
from vyos import ConfigError
default_config_data = {
'address': [],
'address_remove': [],
'deleted': False,
'description': '',
}
def get_config():
loopback = deepcopy(default_config_data)
conf = Config()
# determine tagNode instance
- try:
- loopback['intf'] = os.environ['VYOS_TAGNODE_VALUE']
- except KeyError as E:
- print("Interface not specified")
+ 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
def verify(loopback):
return None
def generate(loopback):
return None
def apply(loopback):
l = LoopbackIf(loopback['intf'])
if loopback['deleted']:
l.remove()
else:
# update interface description used e.g. within SNMP
l.set_alias(loopback['description'])
# Configure interface address(es)
# - not longer required addresses get removed first
# - newly addresses will be added second
for addr in loopback['address_remove']:
l.del_addr(addr)
for addr in loopback['address']:
l.add_addr(addr)
return None
if __name__ == '__main__':
try:
c = get_config()
verify(c)
generate(c)
apply(c)
except ConfigError as e:
print(e)
exit(1)
diff --git a/src/conf_mode/interfaces-openvpn.py b/src/conf_mode/interfaces-openvpn.py
index 622543b58..6b2e3e52e 100755
--- a/src/conf_mode/interfaces-openvpn.py
+++ b/src/conf_mode/interfaces-openvpn.py
@@ -1,1031 +1,1031 @@
#!/usr/bin/env python3
#
# Copyright (C) 2019 VyOS maintainers and contributors
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 or later as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import re
from jinja2 import Template
from copy import deepcopy
from sys import exit
from stat import S_IRUSR,S_IRWXU,S_IRGRP,S_IXGRP,S_IROTH,S_IXOTH
from grp import getgrnam
from ipaddress import ip_address,ip_network,IPv4Interface
from netifaces import interfaces
from psutil import pid_exists
from pwd import getpwnam
from subprocess import Popen, PIPE
from time import sleep
from vyos import ConfigError
from vyos.config import Config
from vyos.ifconfig import Interface
from vyos.validate import is_addr_assigned
user = 'openvpn'
group = 'openvpn'
# Please be careful if you edit the template.
config_tmpl = """
### Autogenerated by interfaces-openvpn.py ###
#
# See https://community.openvpn.net/openvpn/wiki/Openvpn24ManPage
# for individual keyword definition
{% if description %}
# {{ description }}
{% endif %}
verb 3
status /opt/vyatta/etc/openvpn/status/{{ intf }}.status 30
writepid /var/run/openvpn/{{ intf }}.pid
dev-type {{ type }}
dev {{ intf }}
user {{ uid }}
group {{ gid }}
persist-key
iproute /usr/libexec/vyos/system/unpriv-ip
proto {% if 'tcp-active' in protocol -%}tcp-client{% elif 'tcp-passive' in protocol -%}tcp-server{% else %}udp{% endif %}
{%- if local_host %}
local {{ local_host }}
{% endif %}
{%- if local_port %}
lport {{ local_port }}
{% endif %}
{%- if remote_port %}
rport {{ remote_port }}
{% endif %}
{%- if remote_host %}
{% for remote in remote_host -%}
remote {{ remote }}
{% endfor -%}
{% endif %}
{%- if shared_secret_file %}
secret {{ shared_secret_file }}
{% endif %}
{%- if persistent_tunnel %}
persist-tun
{% endif %}
{%- if mode %}
{%- if 'client' in mode %}
#
# OpenVPN Client mode
#
client
nobind
{%- elif 'server' in mode %}
#
# OpenVPN Server mode
#
mode server
tls-server
keepalive {{ ping_interval }} {{ ping_restart }}
management /tmp/openvpn-mgmt-intf unix
{%- if server_topology %}
topology {% if 'point-to-point' in server_topology %}p2p{% else %}subnet{% endif %}
{% endif %}
{% for ns in server_dns_nameserver -%}
push "dhcp-option DNS {{ ns }}"
{% endfor -%}
{% for route in server_push_route -%}
push "route {{ route }}"
{% endfor -%}
{%- if server_domain %}
push "dhcp-option DOMAIN {{ server_domain }}"
{% endif %}
{%- if server_max_conn %}
max-clients {{ server_max_conn }}
{% endif %}
{%- if bridge_member %}
server-bridge nogw
{%- else %}
server {{ server_subnet }}
{% endif %}
{%- if server_reject_unconfigured %}
ccd-exclusive
{% endif %}
{%- else %}
#
# OpenVPN site-2-site mode
#
ping {{ ping_interval }}
ping-restart {{ ping_restart }}
{%- if local_address_subnet %}
ifconfig {{ local_address }} {{ local_address_subnet }}
{% elif remote_address %}
ifconfig {{ local_address }} {{ remote_address }}
{% endif %}
{% endif %}
{% endif %}
{%- if tls_ca_cert %}
ca {{ tls_ca_cert }}
{% endif %}
{%- if tls_cert %}
cert {{ tls_cert }}
{% endif %}
{%- if tls_key %}
key {{ tls_key }}
{% endif %}
{%- if tls_crypt %}
tls-crypt {{ tls_crypt }}
{% endif %}
{%- if tls_crl %}
crl-verify {{ tls_crl }}
{% endif %}
{%- if tls_version_min %}
tls-version-min {{tls_version_min}}
{% endif %}
{%- if tls_dh %}
dh {{ tls_dh }}
{% endif %}
{%- if tls_auth %}
tls-auth {{tls_auth}}
{% endif %}
{%- if 'active' in tls_role %}
tls-client
{%- elif 'passive' in tls_role %}
tls-server
{% endif %}
{%- if redirect_gateway %}
push "redirect-gateway {{ redirect_gateway }}"
{% endif %}
{%- if compress_lzo %}
compress lzo
{% endif %}
{%- if hash %}
auth {{ hash }}
{% endif %}
{%- if encryption %}
{%- if 'des' in encryption %}
cipher des-cbc
{%- elif '3des' in encryption %}
cipher des-ede3-cbc
{%- elif 'bf128' in encryption %}
cipher bf-cbc
keysize 128
{%- elif 'bf256' in encryption %}
cipher bf-cbc
keysize 25
{%- elif 'aes128gcm' in encryption %}
cipher aes-128-gcm
{%- elif 'aes128' in encryption %}
cipher aes-128-cbc
{%- elif 'aes192gcm' in encryption %}
cipher aes-192-gcm
{%- elif 'aes192' in encryption %}
cipher aes-192-cbc
{%- elif 'aes256gcm' in encryption %}
cipher aes-256-gcm
{%- elif 'aes256' in encryption %}
cipher aes-256-cbc
{% endif %}
{% endif %}
{%- if ncp_ciphers %}
ncp-ciphers {{ncp_ciphers}}
{% endif %}
{%- if disable_ncp %}
ncp-disable
{% endif %}
{%- if auth %}
auth-user-pass /tmp/openvpn-{{ intf }}-pw
auth-retry nointeract
{% endif %}
{%- if client %}
client-config-dir /opt/vyatta/etc/openvpn/ccd/{{ intf }}
{% endif %}
# DEPRECATED This option will be removed in OpenVPN 2.5
# Until OpenVPN v2.3 the format of the X.509 Subject fields was formatted like this:
# /C=US/L=Somewhere/CN=John Doe/emailAddress=john@example.com In addition the old
# behaviour was to remap any character other than alphanumeric, underscore ('_'),
# dash ('-'), dot ('.'), and slash ('/') to underscore ('_'). The X.509 Subject
# string as returned by the tls_id environmental variable, could additionally
# contain colon (':') or equal ('='). When using the --compat-names option, this
# old formatting and remapping will be re-enabled again. This is purely implemented
# for compatibility reasons when using older plug-ins or scripts which does not
# handle the new formatting or UTF-8 characters.
#
# See https://phabricator.vyos.net/T1512
compat-names
{% for option in options -%}
{{ option }}
{% endfor -%}
"""
client_tmpl = """
### Autogenerated by interfaces-openvpn.py ###
ifconfig-push {{ ip }} {{ remote_netmask }}
{% for route in push_route -%}
push "route {{ route }}"
{% endfor -%}
{% for net in subnet -%}
iroute {{ net }}
{% endfor -%}
{%- if disable %}
disable
{% endif %}
"""
default_config_data = {
'address': [],
'auth_user': '',
'auth_pass': '',
'auth': False,
'bridge_member': [],
'compress_lzo': False,
'deleted': False,
'description': '',
'disable': False,
'disable_ncp': False,
'encryption': '',
'hash': '',
'intf': '',
'ping_restart': '60',
'ping_interval': '10',
'local_address': '',
'local_address_subnet': '',
'local_host': '',
'local_port': '',
'mode': '',
'ncp_ciphers': '',
'options': [],
'persistent_tunnel': False,
'protocol': '',
'redirect_gateway': '',
'remote_address': '',
'remote_host': [],
'remote_port': '',
'client': [],
'server_domain': '',
'server_max_conn': '',
'server_dns_nameserver': [],
'server_push_route': [],
'server_reject_unconfigured': False,
'server_subnet': '',
'server_topology': '',
'shared_secret_file': '',
'tls': False,
'tls_auth': '',
'tls_ca_cert': '',
'tls_cert': '',
'tls_crl': '',
'tls_dh': '',
'tls_key': '',
'tls_crypt': '',
'tls_role': '',
'tls_version_min': '',
'type': 'tun',
'uid': user,
'gid': group,
}
def subprocess_cmd(command):
p = Popen(command, stdout=PIPE, shell=True)
p.communicate()
def get_config_name(intf):
cfg_file = r'/opt/vyatta/etc/openvpn/openvpn-{}.conf'.format(intf)
return cfg_file
def openvpn_mkdir(directory):
# create directory on demand
if not os.path.exists(directory):
os.mkdir(directory)
# fix permissions - corresponds to mode 755
os.chmod(directory, S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH)
uid = getpwnam(user).pw_uid
gid = getgrnam(group).gr_gid
os.chown(directory, uid, gid)
def fixup_permission(filename, permission=S_IRUSR):
"""
Check if the given file exists and change ownershit to root/vyattacfg
and appripriate file access permissions - default is user and group readable
"""
if os.path.isfile(filename):
os.chmod(filename, permission)
# make file owned by root / vyattacfg
uid = getpwnam('root').pw_uid
gid = getgrnam('vyattacfg').gr_gid
os.chown(filename, uid, gid)
def checkCertHeader(header, filename):
"""
Verify if filename contains specified header.
Returns True on success or on file not found to not trigger the exceptions
"""
if not os.path.isfile(filename):
return False
with open(filename, 'r') as f:
for line in f:
if re.match(header, line):
return True
return True
def get_config():
openvpn = deepcopy(default_config_data)
conf = Config()
# determine tagNode instance
- try:
- openvpn['intf'] = os.environ['VYOS_TAGNODE_VALUE']
- except KeyError as E:
- print("Interface not specified")
+ if 'VYOS_TAGNODE_VALUE' not in os.environ:
+ raise ConfigError('Interface (VYOS_TAGNODE_VALUE) not specified')
+
+ openvpn['intf'] = os.environ['VYOS_TAGNODE_VALUE']
# Check if interface instance has been removed
if not conf.exists('interfaces openvpn ' + openvpn['intf']):
openvpn['deleted'] = True
return openvpn
# Check if we belong to any bridge interface
for bridge in conf.list_nodes('interfaces bridge'):
for intf in conf.list_nodes('interfaces bridge {} member interface'.format(bridge)):
if intf == openvpn['intf']:
openvpn['bridge_member'].append(intf)
# set configuration level
conf.set_level('interfaces openvpn ' + openvpn['intf'])
# retrieve authentication options - username
if conf.exists('authentication username'):
openvpn['auth_user'] = conf.return_value('authentication username')
openvpn['auth'] = True
# retrieve authentication options - username
if conf.exists('authentication password'):
openvpn['auth_pass'] = conf.return_value('authentication password')
openvpn['auth'] = True
# retrieve interface description
if conf.exists('description'):
openvpn['description'] = conf.return_value('description')
# interface device-type
if conf.exists('device-type'):
openvpn['type'] = conf.return_value('device-type')
# disable interface
if conf.exists('disable'):
openvpn['disable'] = True
# data encryption algorithm cipher
if conf.exists('encryption cipher'):
openvpn['encryption'] = conf.return_value('encryption cipher')
# disable ncp-ciphers support
if conf.exists('encryption disable-ncp'):
openvpn['disable_ncp'] = True
# data encryption algorithm ncp-list
if conf.exists('encryption ncp-ciphers'):
_ncp_ciphers = []
for enc in conf.return_values('encryption ncp-ciphers'):
if enc == 'des':
_ncp_ciphers.append('des-cbc')
_ncp_ciphers.append('DES-CBC')
elif enc == '3des':
_ncp_ciphers.append('des-ede3-cbc')
_ncp_ciphers.append('DES-EDE3-CBC')
elif enc == 'aes128':
_ncp_ciphers.append('aes-128-cbc')
_ncp_ciphers.append('AES-128-CBC')
elif enc == 'aes128gcm':
_ncp_ciphers.append('aes-128-gcm')
_ncp_ciphers.append('AES-128-GCM')
elif enc == 'aes192':
_ncp_ciphers.append('aes-192-cbc')
_ncp_ciphers.append('AES-192-CBC')
elif enc == 'aes192gcm':
_ncp_ciphers.append('aes-192-gcm')
_ncp_ciphers.append('AES-192-GCM')
elif enc == 'aes256':
_ncp_ciphers.append('aes-256-cbc')
_ncp_ciphers.append('AES-256-CBC')
elif enc == 'aes256gcm':
_ncp_ciphers.append('aes-256-gcm')
_ncp_ciphers.append('AES-256-GCM')
openvpn['ncp_ciphers'] = ':'.join(_ncp_ciphers)
# hash algorithm
if conf.exists('hash'):
openvpn['hash'] = conf.return_value('hash')
# Maximum number of keepalive packet failures
if conf.exists('keep-alive failure-count') and conf.exists('keep-alive interval'):
fail_count = conf.return_value('keep-alive failure-count')
interval = conf.return_value('keep-alive interval')
openvpn['ping_interval' ] = interval
openvpn['ping_restart' ] = int(interval) * int(fail_count)
# Local IP address of tunnel - even as it is a tag node - we can only work
# on the first address
if conf.exists('local-address'):
openvpn['local_address'] = conf.list_nodes('local-address')[0]
if conf.exists('local-address {} subnet-mask'.format(openvpn['local_address'])):
openvpn['local_address_subnet'] = conf.return_value('local-address {} subnet-mask'.format(openvpn['local_address']))
# Local IP address to accept connections
if conf.exists('local-host'):
openvpn['local_host'] = conf.return_value('local-host')
# Local port number to accept connections
if conf.exists('local-port'):
openvpn['local_port'] = conf.return_value('local-port')
# OpenVPN operation mode
if conf.exists('mode'):
mode = conf.return_value('mode')
openvpn['mode'] = mode
# Additional OpenVPN options
if conf.exists('openvpn-option'):
openvpn['options'] = conf.return_values('openvpn-option')
# Do not close and reopen interface
if conf.exists('persistent-tunnel'):
openvpn['persistent_tunnel'] = True
# Communication protocol
if conf.exists('protocol'):
openvpn['protocol'] = conf.return_value('protocol')
# IP address of remote end of tunnel
if conf.exists('remote-address'):
openvpn['remote_address'] = conf.return_value('remote-address')
# Remote host to connect to (dynamic if not set)
if conf.exists('remote-host'):
openvpn['remote_host'] = conf.return_values('remote-host')
# Remote port number to connect to
if conf.exists('remote-port'):
openvpn['remote_port'] = conf.return_value('remote-port')
# OpenVPN tunnel to be used as the default route
# see https://openvpn.net/community-resources/reference-manual-for-openvpn-2-4/
# redirect-gateway flags
if conf.exists('replace-default-route'):
openvpn['redirect_gateway'] = 'def1'
if conf.exists('replace-default-route local'):
openvpn['redirect_gateway'] = 'local def1'
# Topology for clients
if conf.exists('server topology'):
openvpn['server_topology'] = conf.return_value('server topology')
# Server-mode subnet (from which client IPs are allocated)
if conf.exists('server subnet'):
network = conf.return_value('server subnet')
tmp = IPv4Interface(network).with_netmask
# convert the network in format: "192.0.2.0 255.255.255.0" for later use in template
openvpn['server_subnet'] = tmp.replace(r'/', ' ')
# Client-specific settings
for client in conf.list_nodes('server client'):
# set configuration level
conf.set_level('interfaces openvpn ' + openvpn['intf'] + ' server client ' + client)
data = {
'name': client,
'disable': False,
'ip': '',
'push_route': [],
'subnet': [],
'remote_netmask': ''
}
# note: with "topology subnet", this is "<ip> <netmask>".
# with "topology p2p", this is "<ip> <our_ip>".
if openvpn['server_topology'] == 'subnet':
# we are only interested in the netmask portion of server_subnet
data['remote_netmask'] = openvpn['server_subnet'].split(' ')[1]
else:
# we need the server subnet in format 192.0.2.0/255.255.255.0
subnet = openvpn['server_subnet'].replace(' ', r'/')
# get iterator over the usable hosts in the network
tmp = ip_network(subnet).hosts()
# OpenVPN always uses the subnets first available IP address
data['remote_netmask'] = list(tmp)[0]
# Option to disable client connection
if conf.exists('disable'):
data['disable'] = True
# IP address of the client
if conf.exists('ip'):
data['ip'] = conf.return_value('ip')
# Route to be pushed to the client
for network in conf.return_values('push-route'):
tmp = IPv4Interface(network).with_netmask
data['push_route'].append(tmp.replace(r'/', ' '))
# Subnet belonging to the client
for network in conf.return_values('subnet'):
tmp = IPv4Interface(network).with_netmask
data['subnet'].append(tmp.replace(r'/', ' '))
# Append to global client list
openvpn['client'].append(data)
# re-set configuration level
conf.set_level('interfaces openvpn ' + openvpn['intf'])
# DNS suffix to be pushed to all clients
if conf.exists('server domain-name'):
openvpn['server_domain'] = conf.return_value('server domain-name')
# Number of maximum client connections
if conf.exists('server max-connections'):
openvpn['server_max_conn'] = conf.return_value('server max-connections')
# Domain Name Server (DNS)
if conf.exists('server name-server'):
openvpn['server_dns_nameserver'] = conf.return_values('server name-server')
# Route to be pushed to all clients
if conf.exists('server push-route'):
for network in conf.return_values('server push-route'):
tmp = IPv4Interface(network).with_netmask
openvpn['server_push_route'].append(tmp.replace(r'/', ' '))
# Reject connections from clients that are not explicitly configured
if conf.exists('server reject-unconfigured-clients'):
openvpn['server_reject_unconfigured'] = True
# File containing TLS auth static key
if conf.exists('tls auth-file'):
openvpn['tls_auth'] = conf.return_value('tls auth-file')
openvpn['tls'] = True
# File containing certificate for Certificate Authority (CA)
if conf.exists('tls ca-cert-file'):
openvpn['tls_ca_cert'] = conf.return_value('tls ca-cert-file')
openvpn['tls'] = True
# File containing certificate for this host
if conf.exists('tls cert-file'):
openvpn['tls_cert'] = conf.return_value('tls cert-file')
openvpn['tls'] = True
# File containing certificate revocation list (CRL) for this host
if conf.exists('tls crl-file'):
openvpn['tls_crl'] = conf.return_value('tls crl-file')
openvpn['tls'] = True
# File containing Diffie Hellman parameters (server only)
if conf.exists('tls dh-file'):
openvpn['tls_dh'] = conf.return_value('tls dh-file')
openvpn['tls'] = True
# File containing this host's private key
if conf.exists('tls key-file'):
openvpn['tls_key'] = conf.return_value('tls key-file')
openvpn['tls'] = True
# File containing key to encrypt control channel packets
if conf.exists('tls crypt-file'):
openvpn['tls_crypt'] = conf.return_value('tls crypt-file')
openvpn['tls'] = True
# Role in TLS negotiation
if conf.exists('tls role'):
openvpn['tls_role'] = conf.return_value('tls role')
openvpn['tls'] = True
# Minimum required TLS version
if conf.exists('tls tls-version-min'):
openvpn['tls_version_min'] = conf.return_value('tls tls-version-min')
if conf.exists('shared-secret-key-file'):
openvpn['shared_secret_file'] = conf.return_value('shared-secret-key-file')
if conf.exists('use-lzo-compression'):
openvpn['compress_lzo'] = True
return openvpn
def verify(openvpn):
if openvpn['deleted']:
return None
if not openvpn['mode']:
raise ConfigError('Must specify OpenVPN operation mode')
# Checks which need to be performed on interface rmeoval
if openvpn['deleted']:
# OpenVPN interface can not be deleted if it's still member of a bridge
if openvpn['bridge_member']:
raise ConfigError('Can not delete {} as it is a member interface of bridge {}!'.format(openvpn['intf'], bridge))
# Check if we have disabled ncp and at the same time specified ncp-ciphers
if openvpn['disable_ncp'] and openvpn['ncp_ciphers']:
raise ConfigError('Cannot specify both "encryption disable-ncp" and "encryption ncp-ciphers"')
#
# OpenVPN client mode - VERIFY
#
if openvpn['mode'] == 'client':
if openvpn['local_port']:
raise ConfigError('Cannot specify "local-port" in client mode')
if openvpn['local_host']:
raise ConfigError('Cannot specify "local-host" in client mode')
if openvpn['protocol'] == 'tcp-passive':
raise ConfigError('Protocol "tcp-passive" is not valid in client mode')
if not openvpn['remote_host']:
raise ConfigError('Must specify "remote-host" in client mode')
if openvpn['tls_dh']:
raise ConfigError('Cannot specify "tls dh-file" in client mode')
#
# OpenVPN site-to-site - VERIFY
#
if openvpn['mode'] == 'site-to-site':
if not (openvpn['local_address'] or openvpn['bridge_member']):
raise ConfigError('Must specify "local-address" or "bridge member interface"')
for host in openvpn['remote_host']:
if host == openvpn['remote_address']:
raise ConfigError('"remote-address" cannot be the same as "remote-host"')
if openvpn['type'] == 'tun':
if not openvpn['remote_address']:
raise ConfigError('Must specify "remote-address"')
if openvpn['local_address'] == openvpn['remote_address']:
raise ConfigError('"local-address" and "remote-address" cannot be the same')
if openvpn['local_address'] == openvpn['local_host']:
raise ConfigError('"local-address" cannot be the same as "local-host"')
if openvpn['ncp_ciphers']:
raise ConfigError('encryption ncp-ciphers cannot be specified in site-to-site mode, only server or client')
else:
if openvpn['local_address'] or openvpn['remote_address']:
raise ConfigError('Cannot specify "local-address" or "remote-address" in client-server mode')
elif openvpn['bridge_member']:
raise ConfigError('Cannot specify "local-address" or "remote-address" in bridge mode')
#
# OpenVPN server mode - VERIFY
#
if openvpn['mode'] == 'server':
if openvpn['protocol'] == 'tcp-active':
raise ConfigError('Protocol "tcp-active" is not valid in server mode')
if openvpn['remote_port']:
raise ConfigError('Cannot specify "remote-port" in server mode')
if openvpn['remote_host']:
raise ConfigError('Cannot specify "remote-host" in server mode')
if openvpn['protocol'] == 'tcp-passive' and len(openvpn['remote_host']) > 1:
raise ConfigError('Cannot specify more than 1 "remote-host" with "tcp-passive"')
if not openvpn['tls_dh']:
raise ConfigError('Must specify "tls dh-file" in server mode')
if not openvpn['server_subnet']:
if not openvpn['bridge_member']:
raise ConfigError('Must specify "server subnet" option in server mode')
else:
# checks for both client and site-to-site go here
if openvpn['server_reject_unconfigured']:
raise ConfigError('reject-unconfigured-clients is only supported in OpenVPN server mode')
if openvpn['server_topology']:
raise ConfigError('The "topology" option is only valid in server mode')
if (not openvpn['remote_host']) and openvpn['redirect_gateway']:
raise ConfigError('Cannot set "replace-default-route" without "remote-host"')
#
# OpenVPN common verification section
# not depending on any operation mode
#
# verify specified IP address is present on any interface on this system
if openvpn['local_host']:
if not is_addr_assigned(openvpn['local_host']):
raise ConfigError('No interface on system with specified local-host IP address: {}'.format(openvpn['local_host']))
# TCP active
if openvpn['protocol'] == 'tcp-active':
if openvpn['local_port']:
raise ConfigError('Cannot specify "local-port" with "tcp-active"')
if not openvpn['remote_host']:
raise ConfigError('Must specify "remote-host" with "tcp-active"')
# shared secret and TLS
if not (openvpn['shared_secret_file'] or openvpn['tls']):
raise ConfigError('Must specify one of "shared-secret-key-file" and "tls"')
if openvpn['shared_secret_file'] and openvpn['tls']:
raise ConfigError('Can only specify one of "shared-secret-key-file" and "tls"')
if openvpn['mode'] in ['client', 'server']:
if not openvpn['tls']:
raise ConfigError('Must specify "tls" in client-server mode')
#
# TLS/encryption
#
if openvpn['shared_secret_file']:
if openvpn['encryption'] in ['aes128gcm', 'aes192gcm', 'aes256gcm']:
raise ConfigError('GCM encryption with shared-secret-key-file is not supported')
if not checkCertHeader('-----BEGIN OpenVPN Static key V1-----', openvpn['shared_secret_file']):
raise ConfigError('Specified shared-secret-key-file "{}" is not valid'.format(openvpn['shared_secret_file']))
if openvpn['tls']:
if not openvpn['tls_ca_cert']:
raise ConfigError('Must specify "tls ca-cert-file"')
if not (openvpn['mode'] == 'client' and openvpn['auth']):
if not openvpn['tls_cert']:
raise ConfigError('Must specify "tls cert-file"')
if not openvpn['tls_key']:
raise ConfigError('Must specify "tls key-file"')
if openvpn['tls_auth'] and openvpn['tls_crypt']:
raise ConfigError('TLS auth and crypt are mutually exclusive')
if not checkCertHeader('-----BEGIN CERTIFICATE-----', openvpn['tls_ca_cert']):
raise ConfigError('Specified ca-cert-file "{}" is invalid'.format(openvpn['tls_ca_cert']))
if openvpn['tls_auth']:
if not checkCertHeader('-----BEGIN OpenVPN Static key V1-----', openvpn['tls_auth']):
raise ConfigError('Specified auth-file "{}" is invalid'.format(openvpn['tls_auth']))
if openvpn['tls_cert']:
if not checkCertHeader('-----BEGIN CERTIFICATE-----', openvpn['tls_cert']):
raise ConfigError('Specified cert-file "{}" is invalid'.format(openvpn['tls_cert']))
if openvpn['tls_key']:
if not checkCertHeader('-----BEGIN (?:RSA )?PRIVATE KEY-----', openvpn['tls_key']):
raise ConfigError('Specified key-file "{}" is not valid'.format(openvpn['tls_key']))
if openvpn['tls_crypt']:
if not checkCertHeader('-----BEGIN OpenVPN Static key V1-----', openvpn['tls_crypt']):
raise ConfigError('Specified TLS crypt-file "{}" is invalid'.format(openvpn['tls_crypt']))
if openvpn['tls_crl']:
if not checkCertHeader('-----BEGIN X509 CRL-----', openvpn['tls_crl']):
raise ConfigError('Specified crl-file "{} not valid'.format(openvpn['tls_crl']))
if openvpn['tls_dh']:
if not checkCertHeader('-----BEGIN DH PARAMETERS-----', openvpn['tls_dh']):
raise ConfigError('Specified dh-file "{}" is not valid'.format(openvpn['tls_dh']))
if openvpn['tls_role']:
if openvpn['mode'] in ['client', 'server']:
if not openvpn['tls_auth']:
raise ConfigError('Cannot specify "tls role" in client-server mode')
if openvpn['tls_role'] == 'active':
if openvpn['protocol'] == 'tcp-passive':
raise ConfigError('Cannot specify "tcp-passive" when "tls role" is "active"')
if openvpn['tls_dh']:
raise ConfigError('Cannot specify "tls dh-file" when "tls role" is "active"')
elif openvpn['tls_role'] == 'passive':
if openvpn['protocol'] == 'tcp-active':
raise ConfigError('Cannot specify "tcp-active" when "tls role" is "passive"')
if not openvpn['tls_dh']:
raise ConfigError('Must specify "tls dh-file" when "tls role" is "passive"')
#
# Auth user/pass
#
if openvpn['auth']:
if not openvpn['auth_user']:
raise ConfigError('Username for authentication is missing')
if not openvpn['auth_pass']:
raise ConfigError('Password for authentication is missing')
#
# Client
#
subnet = openvpn['server_subnet'].replace(' ', '/')
for client in openvpn['client']:
if not ip_address(client['ip']) in ip_network(subnet):
raise ConfigError('Client IP "{}" not in server subnet "{}'.format(client['ip'], subnet))
return None
def generate(openvpn):
if openvpn['deleted'] or openvpn['disable']:
return None
interface = openvpn['intf']
directory = os.path.dirname(get_config_name(interface))
# create config directory on demand
openvpn_mkdir(directory)
# create status directory on demand
openvpn_mkdir(directory + '/status')
# create client config dir on demand
openvpn_mkdir(directory + '/ccd')
# crete client config dir per interface on demand
openvpn_mkdir(directory + '/ccd/' + interface)
# Fix file permissons for keys
fixup_permission(openvpn['shared_secret_file'])
fixup_permission(openvpn['tls_key'])
# Generate User/Password authentication file
if openvpn['auth']:
auth_file = '/tmp/openvpn-{}-pw'.format(interface)
with open(auth_file, 'w') as f:
f.write('{}\n{}'.format(openvpn['auth_user'], openvpn['auth_pass']))
fixup_permission(auth_file)
# get numeric uid/gid
uid = getpwnam(user).pw_uid
gid = getgrnam(group).gr_gid
# Generate client specific configuration
for client in openvpn['client']:
client_file = directory + '/ccd/' + interface + '/' + client['name']
tmpl = Template(client_tmpl)
client_text = tmpl.render(client)
with open(client_file, 'w') as f:
f.write(client_text)
os.chown(client_file, uid, gid)
tmpl = Template(config_tmpl)
config_text = tmpl.render(openvpn)
# we need to support quoting of raw parameters from OpenVPN CLI
# see https://phabricator.vyos.net/T1632
config_text = config_text.replace("&quot;",'"')
with open(get_config_name(interface), 'w') as f:
f.write(config_text)
os.chown(get_config_name(interface), uid, gid)
return None
def apply(openvpn):
pid = 0
pidfile = '/var/run/openvpn/{}.pid'.format(openvpn['intf'])
if os.path.isfile(pidfile):
pid = 0
with open(pidfile, 'r') as f:
pid = int(f.read())
# Always stop OpenVPN service. We can not send a SIGUSR1 for restart of the
# service as the configuration is not re-read. Stop daemon only if it's
# running - it could have died or killed by someone evil
if pid_exists(pid):
cmd = 'start-stop-daemon --stop --quiet'
cmd += ' --pidfile ' + pidfile
subprocess_cmd(cmd)
# cleanup old PID file
if os.path.isfile(pidfile):
os.remove(pidfile)
# Do some cleanup when OpenVPN is disabled/deleted
if openvpn['deleted'] or openvpn['disable']:
# cleanup old configuration file
if os.path.isfile(get_config_name(openvpn['intf'])):
os.remove(get_config_name(openvpn['intf']))
# cleanup client config dir
directory = os.path.dirname(get_config_name(openvpn['intf']))
if os.path.isdir(directory + '/ccd/' + openvpn['intf']):
try:
os.remove(directory + '/ccd/' + openvpn['intf'] + '/*')
except:
pass
return None
# On configuration change we need to wait for the 'old' interface to
# vanish from the Kernel, if it is not gone, OpenVPN will report:
# ERROR: Cannot ioctl TUNSETIFF vtun10: Device or resource busy (errno=16)
while openvpn['intf'] in interfaces():
sleep(0.250) # 250ms
# No matching OpenVPN process running - maybe it got killed or none
# existed - nevertheless, spawn new OpenVPN process
cmd = 'start-stop-daemon --start --quiet'
cmd += ' --pidfile ' + pidfile
cmd += ' --exec /usr/sbin/openvpn'
# now pass arguments to openvpn binary
cmd += ' --'
cmd += ' --daemon openvpn-' + openvpn['intf']
cmd += ' --config ' + get_config_name(openvpn['intf'])
# execute assembled command
subprocess_cmd(cmd)
# better late then sorry ... but we can only set interface alias after
# OpenVPN has been launched and created the interface
cnt = 0
while openvpn['intf'] not in interfaces():
# If VPN tunnel can't be established because the peer/server isn't
# (temporarily) available, the vtun interface never becomes registered
# with the kernel, and the commit would hang if there is no bail out
# condition
cnt += 1
if cnt == 50:
break
# sleep 250ms
sleep(0.250)
try:
# we need to catch the exception if the interface is not up due to
# reason stated above
Interface(openvpn['intf']).set_alias(openvpn['description'])
except:
pass
# TAP interface needs to be brought up explicitly
if openvpn['type'] == 'tap':
if not openvpn['disable']:
Interface(openvpn['intf']).set_state('up')
return None
if __name__ == '__main__':
try:
c = get_config()
verify(c)
generate(c)
apply(c)
except ConfigError as e:
print(e)
exit(1)
diff --git a/src/conf_mode/interfaces-pppoe.py b/src/conf_mode/interfaces-pppoe.py
index 8448bc198..8ec78bab3 100755
--- a/src/conf_mode/interfaces-pppoe.py
+++ b/src/conf_mode/interfaces-pppoe.py
@@ -1,294 +1,294 @@
#!/usr/bin/env python3
#
# Copyright (C) 2019 VyOS maintainers and contributors
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 or later as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
from sys import exit
from copy import deepcopy
from jinja2 import Template
from subprocess import Popen, PIPE
from time import sleep
from pwd import getpwnam
from grp import getgrnam
from vyos.config import Config
from vyos.ifconfig import Interface
from vyos import ConfigError
from netifaces import interfaces
# Please be careful if you edit the template.
config_pppoe_tmpl = """
### Autogenerated by interfaces-pppoe.py ###
{% if description %}
# {{ description }}
{% endif %}
# Require peer to provide the local IP address if it is not
# specified explicitly in the config file.
noipdefault
# Don't show the password in logfiles:
hide-password
# Standard Link Control Protocol (LCP) parameters:
lcp-echo-interval 20
lcp-echo-failure 3
# RFC 2516, paragraph 7 mandates that the following options MUST NOT be
# requested and MUST be rejected if requested by the peer:
# Address-and-Control-Field-Compression (ACFC)
noaccomp
# Asynchronous-Control-Character-Map (ACCM)
default-asyncmap
# Override any connect script that may have been set in /etc/ppp/options.
connect /bin/true
# Don't try to authenticate the remote node
noauth
# Don't try to proxy ARP for the remote endpoint. User can set proxy
# arp entries up manually if they wish. More importantly, having
# the "proxyarp" parameter set disables the "defaultroute" option.
noproxyarp
# Unlimited connection attempts
maxfail 0
plugin rp-pppoe.so
{{ source_interface }}
persist
ifname {{ intf }}
ipparam {{ intf }}
debug
logfile {{ logfile }}
{% if 'auto' in default_route -%}
defaultroute
{% elif 'force' in default_route -%}
defaultroute
replacedefaultroute
{% endif %}
mtu {{ mtu }}
mru {{ mtu }}
user "{{ auth_username }}"
password "{{ auth_password }}"
{% if name_server -%}
usepeerdns
{% endif %}
{% if ipv6_enable -%}
+ipv6
{% endif %}
{% if service_name -%}
rp_pppoe_service "{{ service_name }}"
{% endif %}
"""
PPP_LOGFILE = '/var/log/vyatta/ppp_{}.log'
default_config_data = {
'access_concentrator': '',
'auth_username': '',
'auth_password': '',
'on_demand': False,
'default_route': 'auto',
'deleted': False,
'description': '',
'disable': False,
'intf': '',
'idle_timeout': '',
'ipv6_autoconf': False,
'ipv6_enable': False,
'local_address': '',
'logfile': '',
'mtu': '1492',
'name_server': True,
'remote_address': '',
'service_name': '',
'source_interface': ''
}
def subprocess_cmd(command):
p = Popen(command, stdout=PIPE, shell=True)
p.communicate()
def get_config():
pppoe = deepcopy(default_config_data)
conf = Config()
base_path = ['interfaces', 'pppoe']
# determine tagNode instance
- try:
- pppoe['intf'] = os.environ['VYOS_TAGNODE_VALUE']
- pppoe['logfile'] = PPP_LOGFILE.format(pppoe['intf'])
- except KeyError as E:
- print("Interface not specified")
+ if 'VYOS_TAGNODE_VALUE' not in os.environ:
+ raise ConfigError('Interface (VYOS_TAGNODE_VALUE) not specified')
+
+ pppoe['intf'] = os.environ['VYOS_TAGNODE_VALUE']
+ pppoe['logfile'] = PPP_LOGFILE.format(pppoe['intf'])
# Check if interface has been removed
if not conf.exists(base_path + [pppoe['intf']]):
pppoe['deleted'] = True
return pppoe
# set new configuration level
conf.set_level(base_path + [pppoe['intf']])
# Access concentrator name (only connect to this concentrator)
if conf.exists(['access-concentrator']):
pppoe['access_concentrator'] = conf.return_values(['access-concentrator'])
# Authentication name supplied to PPPoE server
if conf.exists(['authentication', 'user']):
pppoe['auth_username'] = conf.return_value(['authentication', 'user'])
# Password for authenticating local machine to PPPoE server
if conf.exists(['authentication', 'password']):
pppoe['auth_password'] = conf.return_value(['authentication', 'password'])
# Access concentrator name (only connect to this concentrator)
if conf.exists(['connect-on-demand']):
pppoe['on_demand'] = True
# Enable/Disable default route to peer when link comes up
if conf.exists(['default-route']):
pppoe['default_route'] = conf.return_value(['default-route'])
# Retrieve interface description
if conf.exists(['description']):
pppoe['description'] = conf.return_value(['description'])
# Disable this interface
if conf.exists(['disable']):
pppoe['disable'] = True
# Delay before disconnecting idle session (in seconds)
if conf.exists(['idle-timeout']):
pppoe['idle_timeout'] = conf.return_value(['idle-timeout'])
# Enable Stateless Address Autoconfiguration (SLAAC)
if conf.exists(['ipv6', 'address', 'autoconf']):
pppoe['ipv6_autoconf'] = True
# Activate IPv6 support on this connection
if conf.exists(['ipv6', 'enable']):
pppoe['ipv6_enable'] = True
# IPv4 address of local end of PPPoE link
if conf.exists(['local-address']):
pppoe['local_address'] = conf.return_value(['local-address'])
# Physical Interface used for this PPPoE session
if conf.exists(['source-interface']):
pppoe['source_interface'] = conf.return_value('source-interface')
# Maximum Transmission Unit (MTU)
if conf.exists(['mtu']):
pppoe['mtu'] = conf.return_value(['mtu'])
# Do not use DNS servers provided by the peer
if conf.exists(['no-peer-dns']):
pppoe['name_server'] = False
# IPv4 address for remote end of PPPoE session
if conf.exists(['remote-address']):
pppoe['remote_address'] = conf.return_value(['remote-address'])
# Service name, only connect to access concentrators advertising this
if conf.exists(['service-name']):
pppoe['service_name'] = conf.return_value(['service-name'])
return pppoe
def verify(pppoe):
if pppoe['deleted']:
# bail out early
return None
if not pppoe['source_interface']:
raise ConfigError('PPPoE source interface is missing')
if pppoe['source_interface'] not in interfaces():
raise ConfigError('PPPoE source interface does not exist')
return None
def generate(pppoe):
config_file_pppoe = '/etc/ppp/peers/{}'.format(pppoe['intf'])
# Always hang-up PPPoE connection prior generating new configuration file
cmd = 'systemctl stop ppp@{}.service'.format(pppoe['intf'])
subprocess_cmd(cmd)
if pppoe['deleted']:
# Delete PPP configuration files
if os.path.exists(config_file_pppoe):
os.unlink(config_file_pppoe)
else:
# Create PPP configuration files
tmpl = Template(config_pppoe_tmpl)
config_text = tmpl.render(pppoe)
with open(config_file_pppoe, 'w') as f:
f.write(config_text)
return None
def apply(pppoe):
if pppoe['deleted']:
# bail out early
return None
if not pppoe['disable']:
# dial PPPoE connection
cmd = 'systemctl start ppp@{}.service'.format(pppoe['intf'])
subprocess_cmd(cmd)
# make logfile owned by root / vyattacfg
if os.path.isfile(pppoe['logfile']):
uid = getpwnam('root').pw_uid
gid = getgrnam('vyattacfg').gr_gid
os.chown(pppoe['logfile'], uid, gid)
# better late then sorry ... but we can only set interface alias after
# pppd has been launched and created the interface
cnt = 0
while pppoe['intf'] not in interfaces():
cnt += 1
if cnt == 50:
break
# sleep 250ms
sleep(0.250)
try:
# we need to catch the exception if the interface is not up due to
# reason stated above
Interface(pppoe['intf']).set_alias(pppoe['description'])
except:
pass
return None
if __name__ == '__main__':
try:
c = get_config()
verify(c)
generate(c)
apply(c)
except ConfigError as e:
print(e)
exit(1)
diff --git a/src/conf_mode/interfaces-pseudo-ethernet.py b/src/conf_mode/interfaces-pseudo-ethernet.py
index 13c809e0d..3d36da226 100755
--- a/src/conf_mode/interfaces-pseudo-ethernet.py
+++ b/src/conf_mode/interfaces-pseudo-ethernet.py
@@ -1,317 +1,316 @@
#!/usr/bin/env python3
#
# Copyright (C) 2019 VyOS maintainers and contributors
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 or later as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
from copy import deepcopy
from sys import exit
from netifaces import interfaces
from vyos.ifconfig import MACVLANIf
from vyos.configdict import list_diff
from vyos.config import Config
from vyos import ConfigError
default_config_data = {
'address': [],
'address_remove': [],
'description': '',
'deleted': False,
'dhcp_client_id': '',
'dhcp_hostname': '',
'dhcp_vendor_class_id': '',
'dhcpv6_prm_only': False,
'dhcpv6_temporary': False,
'disable': False,
'disable_link_detect': 1,
'ip_arp_cache_tmo': 30,
'ip_disable_arp_filter': 1,
'ip_enable_arp_accept': 0,
'ip_enable_arp_announce': 0,
'ip_enable_arp_ignore': 0,
'ip_proxy_arp': 0,
'ip_proxy_arp_pvlan': 0,
'intf': '',
'link': '',
'link_changed': False,
'mac': '',
'mode': 'private',
'vif_s': [],
'vif_s_remove': [],
'vif': [],
'vif_remove': []
}
def get_config():
peth = deepcopy(default_config_data)
conf = Config()
# determine tagNode instance
- try:
- peth['intf'] = os.environ['VYOS_TAGNODE_VALUE']
- except KeyError as E:
- print("Interface not specified")
+ 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
# Lower link device
if conf.exists(['link']):
peth['link'] = conf.return_value(['link'])
tmp = conf.return_effective_value(['link'])
if tmp != peth['link']:
peth['link_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'])
# re-set configuration level to parse new nodes
conf.set_level(cfg_base)
# get vif-s interfaces (currently effective) - to determine which vif-s
# interface is no longer present and needs to be removed
eff_intf = conf.list_effective_nodes('vif-s')
act_intf = conf.list_nodes('vif-s')
peth['vif_s_remove'] = list_diff(eff_intf, act_intf)
if conf.exists('vif-s'):
for vif_s in conf.list_nodes('vif-s'):
# set config level to vif-s interface
conf.set_level(cfg_base + ['vif-s', vif_s])
peth['vif_s'].append(vlan_to_dict(conf))
# re-set configuration level to parse new nodes
conf.set_level(cfg_base)
# Determine vif interfaces (currently effective) - to determine which
# vif interface is no longer present and needs to be removed
eff_intf = conf.list_effective_nodes('vif')
act_intf = conf.list_nodes('vif')
peth['vif_remove'] = list_diff(eff_intf, act_intf)
if conf.exists('vif'):
for vif in conf.list_nodes('vif'):
# set config level to vif interface
conf.set_level(cfg_base + ['vif', vif])
peth['vif'].append(vlan_to_dict(conf))
return peth
def verify(peth):
if peth['deleted']:
return None
if not peth['link']:
raise ConfigError('Link device must be set for virtual ethernet {}'.format(peth['intf']))
return None
def generate(peth):
return None
def apply(peth):
p = ''
if peth['deleted']:
# delete interface
p = MACVLANIf(peth['intf'])
p.remove()
return None
elif peth['link_changed']:
# Check if MACVLAN interface already exists. Parameters like the
# underlaying link device can not be changed on the fly and the
# interface needs to be recreated from the bottom.
#
# link_changed also means - the interface was not present in the
# beginning and is newly created
if peth['intf'] in interfaces():
p = MACVLANIf(peth['intf'])
p.remove()
# MACVLAN interface needs to be created on-block instead of passing a ton
# of arguments, I just use a dict that is managed by vyos.ifconfig
conf = deepcopy(MACVLANIf.get_config())
# Assign MACVLAN instance configuration parameters to config dict
conf['link'] = peth['link']
conf['mode'] = peth['mode']
# It is safe to "re-create" the interface always, there is a sanity check
# that the interface will only be create if its non existent
p = MACVLANIf(peth['intf'], **conf)
else:
p = MACVLANIf(peth['intf'])
# update interface description used e.g. within SNMP
p.set_alias(peth['description'])
# get DHCP config dictionary and update values
opt = p.get_dhcp_options()
if peth['dhcp_client_id']:
opt['client_id'] = peth['dhcp_client_id']
if peth['dhcp_hostname']:
opt['hostname'] = peth['dhcp_hostname']
if peth['dhcp_vendor_class_id']:
opt['vendor_class_id'] = peth['dhcp_vendor_class_id']
# store DHCP config dictionary - used later on when addresses are aquired
p.set_dhcp_options(opt)
# get DHCPv6 config dictionary and update values
opt = p.get_dhcpv6_options()
if peth['dhcpv6_prm_only']:
opt['dhcpv6_prm_only'] = True
if peth['dhcpv6_temporary']:
opt['dhcpv6_temporary'] = True
# store DHCPv6 config dictionary - used later on when addresses are aquired
p.set_dhcpv6_options(opt)
# ignore link state changes
p.set_link_detect(peth['disable_link_detect'])
# configure ARP cache timeout in milliseconds
p.set_arp_cache_tmo(peth['ip_arp_cache_tmo'])
# configure ARP filter configuration
p.set_arp_filter(peth['ip_disable_arp_filter'])
# configure ARP accept
p.set_arp_accept(peth['ip_enable_arp_accept'])
# configure ARP announce
p.set_arp_announce(peth['ip_enable_arp_announce'])
# configure ARP ignore
p.set_arp_ignore(peth['ip_enable_arp_ignore'])
# Enable proxy-arp on this interface
p.set_proxy_arp(peth['ip_proxy_arp'])
# Enable private VLAN proxy ARP on this interface
p.set_proxy_arp_pvlan(peth['ip_proxy_arp_pvlan'])
# Change interface MAC address
if peth['mac']:
p.set_mac(peth['mac'])
# Change interface mode
p.set_mode(peth['mode'])
# Enable/Disable interface
if peth['disable']:
p.set_state('down')
else:
p.set_state('up')
# Configure interface address(es)
# - not longer required addresses get removed first
# - newly addresses will be added second
for addr in peth['address_remove']:
p.del_addr(addr)
for addr in peth['address']:
p.add_addr(addr)
return None
if __name__ == '__main__':
try:
c = get_config()
verify(c)
generate(c)
apply(c)
except ConfigError as e:
print(e)
exit(1)
diff --git a/src/conf_mode/interfaces-vxlan.py b/src/conf_mode/interfaces-vxlan.py
index cfddd0bf8..dabfe4836 100755
--- a/src/conf_mode/interfaces-vxlan.py
+++ b/src/conf_mode/interfaces-vxlan.py
@@ -1,225 +1,225 @@
#!/usr/bin/env python3
#
# Copyright (C) 2019 VyOS maintainers and contributors
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 or later as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
from sys import exit
from copy import deepcopy
from vyos.config import Config
from vyos.ifconfig import VXLANIf, Interface
from vyos import ConfigError
from netifaces import interfaces
default_config_data = {
'address': [],
'deleted': False,
'description': '',
'disable': False,
'group': '',
'intf': '',
'ip_arp_cache_tmo': 30,
'ip_disable_arp_filter': 1,
'ip_enable_arp_accept': 0,
'ip_enable_arp_announce': 0,
'ip_enable_arp_ignore': 0,
'ip_proxy_arp': 0,
'link': '',
'mtu': 1450,
'remote': '',
'remote_port': 8472, # The Linux implementation of VXLAN pre-dates
# the IANA's selection of a standard destination port
'vni': ''
}
def get_config():
vxlan = deepcopy(default_config_data)
conf = Config()
# determine tagNode instance
- try:
- vxlan['intf'] = os.environ['VYOS_TAGNODE_VALUE']
- except KeyError as E:
- print("Interface not specified")
+ if 'VYOS_TAGNODE_VALUE' not in os.environ:
+ raise ConfigError('Interface (VYOS_TAGNODE_VALUE) not specified')
+
+ vxlan['intf'] = os.environ['VYOS_TAGNODE_VALUE']
# Check if interface has been removed
if not conf.exists('interfaces vxlan ' + vxlan['intf']):
vxlan['deleted'] = True
return vxlan
# set new configuration level
conf.set_level('interfaces vxlan ' + vxlan['intf'])
# retrieve configured interface addresses
if conf.exists('address'):
vxlan['address'] = conf.return_values('address')
# retrieve interface description
if conf.exists('description'):
vxlan['description'] = conf.return_value('description')
# Disable this interface
if conf.exists('disable'):
vxlan['disable'] = True
# VXLAN multicast grou
if conf.exists('group'):
vxlan['group'] = conf.return_value('group')
# ARP cache entry timeout in seconds
if conf.exists('ip arp-cache-timeout'):
vxlan['ip_arp_cache_tmo'] = int(conf.return_value('ip arp-cache-timeout'))
# ARP filter configuration
if conf.exists('ip disable-arp-filter'):
vxlan['ip_disable_arp_filter'] = 0
# ARP enable accept
if conf.exists('ip enable-arp-accept'):
vxlan['ip_enable_arp_accept'] = 1
# ARP enable announce
if conf.exists('ip enable-arp-announce'):
vxlan['ip_enable_arp_announce'] = 1
# ARP enable ignore
if conf.exists('ip enable-arp-ignore'):
vxlan['ip_enable_arp_ignore'] = 1
# Enable proxy-arp on this interface
if conf.exists('ip enable-proxy-arp'):
vxlan['ip_proxy_arp'] = 1
# VXLAN underlay interface
if conf.exists('link'):
vxlan['link'] = conf.return_value('link')
# Maximum Transmission Unit (MTU)
if conf.exists('mtu'):
vxlan['mtu'] = int(conf.return_value('mtu'))
# Remote address of VXLAN tunnel
if conf.exists('remote'):
vxlan['remote'] = conf.return_value('remote')
# Remote port of VXLAN tunnel
if conf.exists('port'):
vxlan['remote_port'] = int(conf.return_value('port'))
# Virtual Network Identifier
if conf.exists('vni'):
vxlan['vni'] = conf.return_value('vni')
return vxlan
def verify(vxlan):
if vxlan['deleted']:
# bail out early
return None
if vxlan['mtu'] < 1500:
print('WARNING: RFC7348 recommends VXLAN tunnels preserve a 1500 byte MTU')
if vxlan['group'] and not vxlan['link']:
raise ConfigError('Multicast VXLAN requires an underlaying interface ')
if not (vxlan['group'] or vxlan['remote']):
raise ConfigError('Group or remote must be configured')
if not vxlan['vni']:
raise ConfigError('Must configure VNI for VXLAN')
if vxlan['link']:
# VXLAN adds a 50 byte overhead - we need to check the underlaying MTU
# if our configured MTU is at least 50 bytes less
underlay_mtu = int(Interface(vxlan['link']).get_mtu())
if underlay_mtu < (vxlan['mtu'] + 50):
raise ConfigError('VXLAN has a 50 byte overhead, underlaying device ' \
'MTU is to small ({})'.format(underlay_mtu))
return None
def generate(vxlan):
return None
def apply(vxlan):
# Check if the VXLAN interface already exists
if vxlan['intf'] in interfaces():
v = VXLANIf(vxlan['intf'])
# VXLAN is super picky and the tunnel always needs to be recreated,
# thus we can simply always delete it first.
v.remove()
if not vxlan['deleted']:
# VXLAN interface needs to be created on-block
# instead of passing a ton of arguments, I just use a dict
# that is managed by vyos.ifconfig
conf = deepcopy(VXLANIf.get_config())
# Assign VXLAN instance configuration parameters to config dict
conf['vni'] = vxlan['vni']
conf['group'] = vxlan['group']
conf['dev'] = vxlan['link']
conf['remote'] = vxlan['remote']
conf['port'] = vxlan['remote_port']
# Finally create the new interface
v = VXLANIf(vxlan['intf'], **conf)
# update interface description used e.g. by SNMP
v.set_alias(vxlan['description'])
# Maximum Transfer Unit (MTU)
v.set_mtu(vxlan['mtu'])
# configure ARP cache timeout in milliseconds
v.set_arp_cache_tmo(vxlan['ip_arp_cache_tmo'])
# configure ARP filter configuration
v.set_arp_filter(vxlan['ip_disable_arp_filter'])
# configure ARP accept
v.set_arp_accept(vxlan['ip_enable_arp_accept'])
# configure ARP announce
v.set_arp_announce(vxlan['ip_enable_arp_announce'])
# configure ARP ignore
v.set_arp_ignore(vxlan['ip_enable_arp_ignore'])
# Enable proxy-arp on this interface
v.set_proxy_arp(vxlan['ip_proxy_arp'])
# Configure interface address(es) - no need to implicitly delete the
# old addresses as they have already been removed by deleting the
# interface above
for addr in vxlan['address']:
v.add_addr(addr)
# As the bond interface is always disabled first when changing
# parameters we will only re-enable the interface if it is not
# administratively disabled
if not vxlan['disable']:
v.set_state('up')
return None
if __name__ == '__main__':
try:
c = get_config()
verify(c)
generate(c)
apply(c)
except ConfigError as e:
print(e)
exit(1)
diff --git a/src/conf_mode/interfaces-wireguard.py b/src/conf_mode/interfaces-wireguard.py
index ff12a5172..0d6373d89 100755
--- a/src/conf_mode/interfaces-wireguard.py
+++ b/src/conf_mode/interfaces-wireguard.py
@@ -1,285 +1,285 @@
#!/usr/bin/env python3
#
# Copyright (C) 2018 VyOS maintainers and contributors
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 or later as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#
import sys
import os
import re
import subprocess
from copy import deepcopy
from netifaces import interfaces
from vyos import ConfigError
from vyos.config import Config
from vyos.configdict import list_diff
from vyos.ifconfig import WireGuardIf
kdir = r'/config/auth/wireguard'
def _check_kmod():
if not os.path.exists('/sys/module/wireguard'):
if os.system('sudo modprobe wireguard') != 0:
raise ConfigError("modprobe wireguard failed")
def _migrate_default_keys():
if os.path.exists('{}/private.key'.format(kdir)) and not os.path.exists('{}/default/private.key'.format(kdir)):
old_umask = os.umask(0o027)
location = '{}/default'.format(kdir)
subprocess.call(['sudo mkdir -p ' + location], shell=True)
subprocess.call(['sudo chgrp vyattacfg ' + location], shell=True)
subprocess.call(['sudo chmod 750 ' + location], shell=True)
os.rename('{}/private.key'.format(kdir),
'{}/private.key'.format(location))
os.rename('{}/public.key'.format(kdir),
'{}/public.key'.format(location))
os.umask(old_umask)
def get_config():
c = Config()
if not c.exists(['interfaces', 'wireguard']):
return None
+ # determine tagNode instance
+ if 'VYOS_TAGNODE_VALUE' not in os.environ:
+ raise ConfigError('Interface (VYOS_TAGNODE_VALUE) not specified')
+
dflt_cnf = {
'intfc': '',
'addr': [],
'addr_remove': [],
'descr': '',
'lport': None,
'delete': False,
'state': 'up',
'fwmark': 0x00,
'mtu': 1420,
'peer': {},
'peer_remove': [],
'pk': '{}/default/private.key'.format(kdir)
}
- if os.getenv('VYOS_TAGNODE_VALUE'):
- ifname = str(os.environ['VYOS_TAGNODE_VALUE'])
- wg = deepcopy(dflt_cnf)
- wg['intfc'] = ifname
- wg['descr'] = ifname
- else:
- print("ERROR: VYOS_TAGNODE_VALUE undefined")
- sys.exit(1)
+ ifname = str(os.environ['VYOS_TAGNODE_VALUE'])
+ wg = deepcopy(dflt_cnf)
+ wg['intfc'] = ifname
+ wg['descr'] = ifname
c.set_level(['interfaces', 'wireguard'])
# interface removal state
if not c.exists(ifname) and c.exists_effective(ifname):
wg['delete'] = True
if not wg['delete']:
c.set_level(['interfaces', 'wireguard', ifname])
if c.exists(['address']):
wg['addr'] = c.return_values(['address'])
# determine addresses which need to be removed
eff_addr = c.return_effective_values(['address'])
wg['addr_remove'] = list_diff(eff_addr, wg['addr'])
# ifalias description
if c.exists(['description']):
wg['descr'] = c.return_value(['description'])
# link state
if c.exists(['disable']):
wg['state'] = 'down'
# local port to listen on
if c.exists(['port']):
wg['lport'] = c.return_value(['port'])
# fwmark value
if c.exists(['fwmark']):
wg['fwmark'] = c.return_value(['fwmark'])
# mtu
if c.exists('mtu'):
wg['mtu'] = c.return_value('mtu')
# private key
if c.exists(['private-key']):
wg['pk'] = "{0}/{1}/private.key".format(
kdir, c.return_value(['private-key']))
# peer removal, wg identifies peers by its pubkey
peer_eff = c.list_effective_nodes(['peer'])
peer_rem = list_diff(peer_eff, c.list_nodes(['peer']))
for p in peer_rem:
wg['peer_remove'].append(
c.return_effective_value(['peer', p, 'pubkey']))
# peer settings
if c.exists(['peer']):
for p in c.list_nodes(['peer']):
if not c.exists(['peer', p, 'disable']):
wg['peer'].update(
{
p: {
'allowed-ips': [],
'endpoint': '',
'pubkey': ''
}
}
)
# peer allowed-ips
if c.exists(['peer', p, 'allowed-ips']):
wg['peer'][p]['allowed-ips'] = c.return_values(
['peer', p, 'allowed-ips'])
# peer endpoint
if c.exists(['peer', p, 'endpoint']):
wg['peer'][p]['endpoint'] = c.return_value(
['peer', p, 'endpoint'])
# persistent-keepalive
if c.exists(['peer', p, 'persistent-keepalive']):
wg['peer'][p]['persistent-keepalive'] = c.return_value(
['peer', p, 'persistent-keepalive'])
# preshared-key
if c.exists(['peer', p, 'preshared-key']):
wg['peer'][p]['psk'] = c.return_value(
['peer', p, 'preshared-key'])
# peer pubkeys
key_eff = c.return_effective_value(['peer', p, 'pubkey'])
key_cfg = c.return_value(['peer', p, 'pubkey'])
wg['peer'][p]['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
else:
peer_key = c.return_value(['peer', p, 'pubkey'])
wg['peer_remove'].append(peer_key)
return wg
def verify(c):
if not c:
return None
if not os.path.exists(c['pk']):
raise ConfigError(
"No keys found, generate them by executing: \'run generate wireguard [keypair|named-keypairs]\'")
if not c['delete']:
if not c['addr']:
raise ConfigError("ERROR: IP address required")
if not c['peer']:
raise ConfigError("ERROR: peer required")
for p in c['peer']:
if not c['peer'][p]['allowed-ips']:
raise ConfigError("ERROR: allowed-ips required for peer " + p)
if not c['peer'][p]['pubkey']:
raise ConfigError("peer pubkey required for peer " + p)
def apply(c):
# no wg configs left, remove all interface from system
# maybe move it into ifconfig.py
if not c:
net_devs = os.listdir('/sys/class/net/')
for dev in net_devs:
if os.path.isdir('/sys/class/net/' + dev):
buf = open('/sys/class/net/' + dev + '/uevent', 'r').read()
if re.search("DEVTYPE=wireguard", buf, re.I | re.M):
wg_intf = re.sub("INTERFACE=", "", re.search(
"INTERFACE=.*", buf, re.I | re.M).group(0))
subprocess.call(
['ip l d dev ' + wg_intf + ' >/dev/null'], shell=True)
return None
# init wg class
intfc = WireGuardIf(c['intfc'])
# single interface removal
if c['delete']:
intfc.remove()
return None
# remove IP addresses
for ip in c['addr_remove']:
intfc.del_addr(ip)
# add IP addresses
for ip in c['addr']:
intfc.add_addr(ip)
# interface mtu
intfc.set_mtu(int(c['mtu']))
# ifalias for snmp from description
intfc.set_alias(str(c['descr']))
# remove peers
if c['peer_remove']:
for pkey in c['peer_remove']:
intfc.remove_peer(pkey)
# peer pubkey
# setting up the wg interface
intfc.config['private-key'] = c['pk']
for p in c['peer']:
# peer pubkey
intfc.config['pubkey'] = str(c['peer'][p]['pubkey'])
# peer allowed-ips
intfc.config['allowed-ips'] = c['peer'][p]['allowed-ips']
# local listen port
if c['lport']:
intfc.config['port'] = c['lport']
# fwmark
if c['fwmark']:
intfc.config['fwmark'] = c['fwmark']
# endpoint
if c['peer'][p]['endpoint']:
intfc.config['endpoint'] = c['peer'][p]['endpoint']
# persistent-keepalive
if 'persistent-keepalive' in c['peer'][p]:
intfc.config['keepalive'] = c['peer'][p]['persistent-keepalive']
# maybe move it into ifconfig.py
# preshared-key - needs to be read from a file
if 'psk' in c['peer'][p]:
psk_file = '/config/auth/wireguard/psk'
old_umask = os.umask(0o077)
open(psk_file, 'w').write(str(c['peer'][p]['psk']))
os.umask(old_umask)
intfc.config['psk'] = psk_file
intfc.update()
# interface state
intfc.set_state(c['state'])
return None
if __name__ == '__main__':
try:
_check_kmod()
_migrate_default_keys()
c = get_config()
verify(c)
apply(c)
except ConfigError as e:
print(e)
sys.exit(1)
diff --git a/src/conf_mode/interfaces-wireless.py b/src/conf_mode/interfaces-wireless.py
index 098aa8d97..5289208d9 100755
--- a/src/conf_mode/interfaces-wireless.py
+++ b/src/conf_mode/interfaces-wireless.py
@@ -1,1475 +1,1475 @@
#!/usr/bin/env python3
#
# Copyright (C) 2019 VyOS maintainers and contributors
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 or later as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
from jinja2 import Template
from copy import deepcopy
from sys import exit
from stat import S_IRWXU,S_IRGRP,S_IXGRP,S_IROTH,S_IXOTH
from pwd import getpwnam
from grp import getgrnam
from subprocess import Popen, PIPE
from psutil import pid_exists
from vyos.ifconfig import EthernetIf
from vyos.ifconfig_vlan import apply_vlan_config
from vyos.configdict import list_diff, vlan_to_dict
from vyos.config import Config
from vyos import ConfigError
user = 'root'
group = 'vyattacfg'
# Please be careful if you edit the template.
config_hostapd_tmpl = """
### Autogenerated by interfaces-wireless.py ###
{% if description %}
# Description: {{ description }}
# User-friendly description of device; up to 32 octets encoded in UTF-8
device_name={{ description | truncate(32, True) }}
{% endif %}
# AP netdevice name (without 'ap' postfix, i.e., wlan0 uses wlan0ap for
# management frames with the Host AP driver); wlan0 with many nl80211 drivers
# Note: This attribute can be overridden by the values supplied with the '-i'
# command line parameter.
interface={{ intf }}
# Driver interface type (hostap/wired/none/nl80211/bsd);
# default: hostap). nl80211 is used with all Linux mac80211 drivers.
# Use driver=none if building hostapd as a standalone RADIUS server that does
# not control any wireless/wired driver.
driver=nl80211
#
# What about bridge?
# bridge=br0
# wds_sta=1
#
# Levels (minimum value for logged events):
# 0 = verbose debugging
# 1 = debugging
# 2 = informational messages
# 3 = notification
# 4 = warning
logger_syslog=-1
logger_syslog_level=0
logger_stdout=-1
logger_stdout_level=0
{%- if country_code %}
# Country code (ISO/IEC 3166-1). Used to set regulatory domain.
# Set as needed to indicate country in which device is operating.
# This can limit available channels and transmit power.
country_code={{ country_code }}
# Enable IEEE 802.11d. This advertises the country_code and the set of allowed
# channels and transmit power levels based on the regulatory limits. The
# country_code setting must be configured with the correct country for
# IEEE 802.11d functions.
ieee80211d=1
{% endif %}
{%- if ssid %}
# SSID to be used in IEEE 802.11 management frames
ssid={{ ssid }}
{% endif %}
{%- if channel %}
# Channel number (IEEE 802.11)
# (default: 0, i.e., not set)
# Please note that some drivers do not use this value from hostapd and the
# channel will need to be configured separately with iwconfig.
#
# If CONFIG_ACS build option is enabled, the channel can be selected
# automatically at run time by setting channel=acs_survey or channel=0, both of
# which will enable the ACS survey based algorithm.
channel={{ channel }}
{% endif %}
{%- if mode %}
# Operation mode (a = IEEE 802.11a (5 GHz), b = IEEE 802.11b (2.4 GHz),
# g = IEEE 802.11g (2.4 GHz), ad = IEEE 802.11ad (60 GHz); a/g options are used
# with IEEE 802.11n (HT), too, to specify band). For IEEE 802.11ac (VHT), this
# needs to be set to hw_mode=a. For IEEE 802.11ax (HE) on 6 GHz this needs
# to be set to hw_mode=a. When using ACS (see channel parameter), a
# special value "any" can be used to indicate that any support band can be used.
# This special case is currently supported only with drivers with which
# offloaded ACS is used.
{% if 'n' in mode -%}
hw_mode=g
ieee80211n=1
{% elif 'ac' in mode -%}
hw_mode=a
ieee80211h=1
ieee80211ac=1
{% else -%}
hw_mode={{ mode }}
{% endif %}
{% endif %}
# ieee80211w: Whether management frame protection (MFP) is enabled
# 0 = disabled (default)
# 1 = optional
# 2 = required
{% if 'disabled' in mgmt_frame_protection -%}
ieee80211w=0
{% elif 'optional' in mgmt_frame_protection -%}
ieee80211w=1
{% elif 'required' in mgmt_frame_protection -%}
ieee80211w=2
{% endif %}
# ht_capab: HT capabilities (list of flags)
# LDPC coding capability: [LDPC] = supported
# Supported channel width set: [HT40-] = both 20 MHz and 40 MHz with secondary
# channel below the primary channel; [HT40+] = both 20 MHz and 40 MHz
# with secondary channel above the primary channel
# (20 MHz only if neither is set)
# Note: There are limits on which channels can be used with HT40- and
# HT40+. Following table shows the channels that may be available for
# HT40- and HT40+ use per IEEE 802.11n Annex J:
# freq HT40- HT40+
# 2.4 GHz 5-13 1-7 (1-9 in Europe/Japan)
# 5 GHz 40,48,56,64 36,44,52,60
# (depending on the location, not all of these channels may be available
# for use)
# Please note that 40 MHz channels may switch their primary and secondary
# channels if needed or creation of 40 MHz channel maybe rejected based
# on overlapping BSSes. These changes are done automatically when hostapd
# is setting up the 40 MHz channel.
# Spatial Multiplexing (SM) Power Save: [SMPS-STATIC] or [SMPS-DYNAMIC]
# (SMPS disabled if neither is set)
# HT-greenfield: [GF] (disabled if not set)
# Short GI for 20 MHz: [SHORT-GI-20] (disabled if not set)
# Short GI for 40 MHz: [SHORT-GI-40] (disabled if not set)
# Tx STBC: [TX-STBC] (disabled if not set)
# Rx STBC: [RX-STBC1] (one spatial stream), [RX-STBC12] (one or two spatial
# streams), or [RX-STBC123] (one, two, or three spatial streams); Rx STBC
# disabled if none of these set
# HT-delayed Block Ack: [DELAYED-BA] (disabled if not set)
# Maximum A-MSDU length: [MAX-AMSDU-7935] for 7935 octets (3839 octets if not
# set)
# DSSS/CCK Mode in 40 MHz: [DSSS_CCK-40] = allowed (not allowed if not set)
# 40 MHz intolerant [40-INTOLERANT] (not advertised if not set)
# L-SIG TXOP protection support: [LSIG-TXOP-PROT] (disabled if not set)
{% if cap_ht %}
ht_capab=
{%- endif -%}
{%- if cap_ht_40mhz_incapable -%}
[40-INTOLERANT]
{%- endif -%}
{%- if cap_ht_delayed_block_ack -%}
[DELAYED-BA]
{%- endif -%}
{%- if cap_ht_dsss_cck_40 -%}
[DSSS_CCK-40]
{%- endif -%}
{%- if cap_ht_greenfield -%}
[GF]
{%- endif -%}
{%- if cap_ht_ldpc -%}
[LDPC]
{%- endif -%}
{%- if cap_ht_lsig_protection -%}
[LSIG-TXOP-PROT]
{%- endif -%}
{%- if cap_ht_max_amsdu -%}
[MAX-AMSDU-{{ cap_ht_max_amsdu }}]
{%- endif -%}
{%- if cap_ht_smps -%}
[SMPS-{{ cap_ht_smps | upper }}]
{%- endif -%}
{%- if cap_ht_chan_set_width -%}
{%- for csw in cap_ht_chan_set_width -%}
[{{ csw | upper }}]
{%- endfor -%}
{%- endif -%}
{%- if cap_ht_short_gi -%}
{%- for gi in cap_ht_short_gi -%}
[SHORT-GI-{{ gi }}]
{%- endfor -%}
{%- endif -%}
{%- if cap_ht_stbc_tx -%}
[TX-STBC]
{%- endif -%}
{%- if cap_ht_stbc_rx -%}
[RX-STBC{{ cap_ht_stbc_rx }}]
{%- endif %}
# Required for full HT and VHT functionality
wme_enabled=1
{% if cap_ht_powersave -%}
# WMM-PS Unscheduled Automatic Power Save Delivery [U-APSD]
# Enable this flag if U-APSD supported outside hostapd (eg., Firmware/driver)
uapsd_advertisement_enabled=1
{%- endif %}
{% if cap_req_ht -%}
# Require stations to support HT PHY (reject association if they do not)
require_ht=1
{% endif %}
# vht_capab: VHT capabilities (list of flags)
#
# vht_max_mpdu_len: [MAX-MPDU-7991] [MAX-MPDU-11454]
# Indicates maximum MPDU length
# 0 = 3895 octets (default)
# 1 = 7991 octets
# 2 = 11454 octets
# 3 = reserved
#
# supported_chan_width: [VHT160] [VHT160-80PLUS80]
# Indicates supported Channel widths
# 0 = 160 MHz & 80+80 channel widths are not supported (default)
# 1 = 160 MHz channel width is supported
# 2 = 160 MHz & 80+80 channel widths are supported
# 3 = reserved
#
# Rx LDPC coding capability: [RXLDPC]
# Indicates support for receiving LDPC coded pkts
# 0 = Not supported (default)
# 1 = Supported
#
# Short GI for 80 MHz: [SHORT-GI-80]
# Indicates short GI support for reception of packets transmitted with TXVECTOR
# params format equal to VHT and CBW = 80Mhz
# 0 = Not supported (default)
# 1 = Supported
#
# Short GI for 160 MHz: [SHORT-GI-160]
# Indicates short GI support for reception of packets transmitted with TXVECTOR
# params format equal to VHT and CBW = 160Mhz
# 0 = Not supported (default)
# 1 = Supported
#
# Tx STBC: [TX-STBC-2BY1]
# Indicates support for the transmission of at least 2x1 STBC
# 0 = Not supported (default)
# 1 = Supported
#
# Rx STBC: [RX-STBC-1] [RX-STBC-12] [RX-STBC-123] [RX-STBC-1234]
# Indicates support for the reception of PPDUs using STBC
# 0 = Not supported (default)
# 1 = support of one spatial stream
# 2 = support of one and two spatial streams
# 3 = support of one, two and three spatial streams
# 4 = support of one, two, three and four spatial streams
# 5,6,7 = reserved
#
# SU Beamformer Capable: [SU-BEAMFORMER]
# Indicates support for operation as a single user beamformer
# 0 = Not supported (default)
# 1 = Supported
#
# SU Beamformee Capable: [SU-BEAMFORMEE]
# Indicates support for operation as a single user beamformee
# 0 = Not supported (default)
# 1 = Supported
#
# Compressed Steering Number of Beamformer Antennas Supported:
# [BF-ANTENNA-2] [BF-ANTENNA-3] [BF-ANTENNA-4]
# Beamformee's capability indicating the maximum number of beamformer
# antennas the beamformee can support when sending compressed beamforming
# feedback
# If SU beamformer capable, set to maximum value minus 1
# else reserved (default)
#
# Number of Sounding Dimensions:
# [SOUNDING-DIMENSION-2] [SOUNDING-DIMENSION-3] [SOUNDING-DIMENSION-4]
# Beamformer's capability indicating the maximum value of the NUM_STS parameter
# in the TXVECTOR of a VHT NDP
# If SU beamformer capable, set to maximum value minus 1
# else reserved (default)
#
# MU Beamformer Capable: [MU-BEAMFORMER]
# Indicates support for operation as an MU beamformer
# 0 = Not supported or sent by Non-AP STA (default)
# 1 = Supported
#
# VHT TXOP PS: [VHT-TXOP-PS]
# Indicates whether or not the AP supports VHT TXOP Power Save Mode
# or whether or not the STA is in VHT TXOP Power Save mode
# 0 = VHT AP doesn't support VHT TXOP PS mode (OR) VHT STA not in VHT TXOP PS
# mode
# 1 = VHT AP supports VHT TXOP PS mode (OR) VHT STA is in VHT TXOP power save
# mode
#
# +HTC-VHT Capable: [HTC-VHT]
# Indicates whether or not the STA supports receiving a VHT variant HT Control
# field.
# 0 = Not supported (default)
# 1 = supported
#
# Maximum A-MPDU Length Exponent: [MAX-A-MPDU-LEN-EXP0]..[MAX-A-MPDU-LEN-EXP7]
# Indicates the maximum length of A-MPDU pre-EOF padding that the STA can recv
# This field is an integer in the range of 0 to 7.
# The length defined by this field is equal to
# 2 pow(13 + Maximum A-MPDU Length Exponent) -1 octets
#
# VHT Link Adaptation Capable: [VHT-LINK-ADAPT2] [VHT-LINK-ADAPT3]
# Indicates whether or not the STA supports link adaptation using VHT variant
# HT Control field
# If +HTC-VHTcapable is 1
# 0 = (no feedback) if the STA does not provide VHT MFB (default)
# 1 = reserved
# 2 = (Unsolicited) if the STA provides only unsolicited VHT MFB
# 3 = (Both) if the STA can provide VHT MFB in response to VHT MRQ and if the
# STA provides unsolicited VHT MFB
# Reserved if +HTC-VHTcapable is 0
#
# Rx Antenna Pattern Consistency: [RX-ANTENNA-PATTERN]
# Indicates the possibility of Rx antenna pattern change
# 0 = Rx antenna pattern might change during the lifetime of an association
# 1 = Rx antenna pattern does not change during the lifetime of an association
#
# Tx Antenna Pattern Consistency: [TX-ANTENNA-PATTERN]
# Indicates the possibility of Tx antenna pattern change
# 0 = Tx antenna pattern might change during the lifetime of an association
# 1 = Tx antenna pattern does not change during the lifetime of an association
{% if cap_vht %}
vht_capab=
{%- endif -%}
{%- if cap_vht_max_mpdu -%}
[MAX-MPDU-{{ cap_vht_max_mpdu }}]
{%- endif -%}
{%- if cap_vht_max_mpdu_exp -%}
[MAX-A-MPDU-LEN-EXP{{ cap_vht_max_mpdu_exp }}]
{%- endif -%}
{%- if cap_vht_chan_set_width -%}
[MAX-A-MPDU-LEN-EXP{{ cap_vht_max_mpdu_exp }}]
{%- endif -%}
{%- if cap_vht_chan_set_width -%}
{%- if '2' in cap_vht_chan_set_width -%}
[VHT160]
{%- elif '3' in cap_vht_chan_set_width -%}
[VHT160-80PLUS80]
{%- endif -%}
{%- endif -%}
{%- if cap_vht_stbc_tx -%}
[TX-STBC-2BY1]
{%- endif -%}
{%- if cap_vht_stbc_rx -%}
[RX-STBC-{{ cap_vht_stbc_rx }}]
{%- endif -%}
{%- if cap_vht_link_adaptation -%}
{%- if 'unsolicited' in cap_vht_link_adaptation -%}
[VHT-LINK-ADAPT2]
{%- elif 'both' in cap_vht_link_adaptation -%}
[VHT-LINK-ADAPT3]
{%- endif -%}
{%- endif -%}
{%- if cap_vht_short_gi -%}
{%- for gi in cap_vht_short_gi -%}
[SHORT-GI-{{ gi }}]
{%- endfor -%}
{%- endif -%}
{%- if cap_vht_ldpc -%}
[RXLDPC]
{%- endif -%}
{%- if cap_vht_tx_powersave -%}
[VHT-TXOP-PS]
{%- endif -%}
{%- if cap_vht_vht_cf -%}
[HTC-VHT]
{%- endif -%}
{%- if cap_vht_beamform -%}
{%- for beamform in cap_vht_beamform -%}
{%- if 'single-user-beamformer' in beamform -%}
[SU-BEAMFORMER]
{%- elif 'single-user-beamformee' in beamform -%}
[SU-BEAMFORMEE]
{%- elif 'multi-user-beamformer' in beamform -%}
[MU-BEAMFORMER]
{%- elif 'multi-user-beamformee' in beamform -%}
[MU-BEAMFORMEE]
{%- endif -%}
{%- endfor -%}
{%- endif -%}
{%- if cap_vht_antenna_fixed -%}
[RX-ANTENNA-PATTERN][TX-ANTENNA-PATTERN]
{%- endif -%}
{%- if cap_vht_antenna_cnt -%}
{%- for beamform in cap_vht_beamform -%}
{%- if 'single-user-beamformer' in beamform -%}
[BF-ANTENNA-{{ cap_vht_antenna_cnt|int -1 }}][SOUNDING-DIMENSION-{{ cap_vht_antenna_cnt|int -1}}]
{%- else -%}
[BF-ANTENNA-{{ cap_vht_antenna_cnt }}][SOUNDING-DIMENSION-{{ cap_vht_antenna_cnt }}]
{%- endif -%}
{%- endfor -%}
{%- endif %}
# ieee80211n: Whether IEEE 802.11n (HT) is enabled
# 0 = disabled (default)
# 1 = enabled
# Note: You will also need to enable WMM for full HT functionality.
# Note: hw_mode=g (2.4 GHz) and hw_mode=a (5 GHz) is used to specify the band.
{% if cap_req_vht -%}
ieee80211n=0
# Require stations to support VHT PHY (reject association if they do not)
require_vht=1
{% endif %}
{% if cap_vht_center_freq_1 -%}
# center freq = 5 GHz + (5 * index)
# So index 42 gives center freq 5.210 GHz
# which is channel 42 in 5G band
vht_oper_centr_freq_seg0_idx={{ cap_vht_center_freq_1 }}
{% endif %}
{% if cap_vht_center_freq_2 -%}
# center freq = 5 GHz + (5 * index)
# So index 159 gives center freq 5.795 GHz
# which is channel 159 in 5G band
vht_oper_centr_freq_seg1_idx={{ cap_vht_center_freq_2 }}
{% endif %}
{% if disable_broadcast_ssid -%}
# Send empty SSID in beacons and ignore probe request frames that do not
# specify full SSID, i.e., require stations to know SSID.
# default: disabled (0)
# 1 = send empty (length=0) SSID in beacon and ignore probe request for
# broadcast SSID
# 2 = clear SSID (ASCII 0), but keep the original length (this may be required
# with some clients that do not support empty SSID) and ignore probe
# requests for broadcast SSID
ignore_broadcast_ssid=1
{% endif %}
# Station MAC address -based authentication
# Please note that this kind of access control requires a driver that uses
# hostapd to take care of management frame processing and as such, this can be
# used with driver=hostap or driver=nl80211, but not with driver=atheros.
# 0 = accept unless in deny list
# 1 = deny unless in accept list
# 2 = use external RADIUS server (accept/deny lists are searched first)
macaddr_acl=0
{% if max_stations -%}
# Maximum number of stations allowed in station table. New stations will be
# rejected after the station table is full. IEEE 802.11 has a limit of 2007
# different association IDs, so this number should not be larger than that.
# (default: 2007)
max_num_sta={{ max_stations }}
{% endif %}
{% if isolate_stations -%}
# Client isolation can be used to prevent low-level bridging of frames between
# associated stations in the BSS. By default, this bridging is allowed.
ap_isolate=1
{% endif %}
{% if reduce_transmit_power -%}
# Add Power Constraint element to Beacon and Probe Response frames
# This config option adds Power Constraint element when applicable and Country
# element is added. Power Constraint element is required by Transmit Power
# Control. This can be used only with ieee80211d=1.
# Valid values are 0..255.
local_pwr_constraint={{ reduce_transmit_power }}
{% endif %}
{% if expunge_failing_stations -%}
# Disassociate stations based on excessive transmission failures or other
# indications of connection loss. This depends on the driver capabilities and
# may not be available with all drivers.
disassoc_low_ack=1
{% endif %}
{% if sec_wep -%}
# IEEE 802.11 specifies two authentication algorithms. hostapd can be
# configured to allow both of these or only one. Open system authentication
# should be used with IEEE 802.1X.
# Bit fields of allowed authentication algorithms:
# bit 0 = Open System Authentication
# bit 1 = Shared Key Authentication (requires WEP)
auth_algs=2
# WEP rekeying (disabled if key lengths are not set or are set to 0)
# Key lengths for default/broadcast and individual/unicast keys:
# 5 = 40-bit WEP (also known as 64-bit WEP with 40 secret bits)
# 13 = 104-bit WEP (also known as 128-bit WEP with 104 secret bits)
wep_key_len_broadcast=5
wep_key_len_unicast=5
# Static WEP key configuration
#
# The key number to use when transmitting.
# It must be between 0 and 3, and the corresponding key must be set.
# default: not set
wep_default_key=0
# The WEP keys to use.
# A key may be a quoted string or unquoted hexadecimal digits.
# The key length should be 5, 13, or 16 characters, or 10, 26, or 32
# digits, depending on whether 40-bit (64-bit), 104-bit (128-bit), or
# 128-bit (152-bit) WEP is used.
# Only the default key must be supplied; the others are optional.
{% if sec_wep_key -%}
{% for key in sec_wep_key -%}
wep_key{{ loop.index -1 }}={{ key}}
{% endfor %}
{%- endif %}
{% elif sec_wpa -%}
##### WPA/IEEE 802.11i configuration ##########################################
# Enable WPA. Setting this variable configures the AP to require WPA (either
# WPA-PSK or WPA-RADIUS/EAP based on other configuration). For WPA-PSK, either
# wpa_psk or wpa_passphrase must be set and wpa_key_mgmt must include WPA-PSK.
# Instead of wpa_psk / wpa_passphrase, wpa_psk_radius might suffice.
# For WPA-RADIUS/EAP, ieee8021x must be set (but without dynamic WEP keys),
# RADIUS authentication server must be configured, and WPA-EAP must be included
# in wpa_key_mgmt.
# This field is a bit field that can be used to enable WPA (IEEE 802.11i/D3.0)
# and/or WPA2 (full IEEE 802.11i/RSN):
# bit0 = WPA
# bit1 = IEEE 802.11i/RSN (WPA2) (dot11RSNAEnabled)
{% if 'both' in sec_wpa_mode -%}
wpa=3
{%- elif 'wpa2' in sec_wpa_mode -%}
wpa=2
{%- elif 'wpa' in sec_wpa_mode -%}
wpa=1
{%- endif %}
{% if sec_wpa_cipher -%}
# Set of accepted cipher suites (encryption algorithms) for pairwise keys
# (unicast packets). This is a space separated list of algorithms:
# CCMP = AES in Counter mode with CBC-MAC (CCMP-128)
# TKIP = Temporal Key Integrity Protocol
# CCMP-256 = AES in Counter mode with CBC-MAC with 256-bit key
# GCMP = Galois/counter mode protocol (GCMP-128)
# GCMP-256 = Galois/counter mode protocol with 256-bit key
# Group cipher suite (encryption algorithm for broadcast and multicast frames)
# is automatically selected based on this configuration. If only CCMP is
# allowed as the pairwise cipher, group cipher will also be CCMP. Otherwise,
# TKIP will be used as the group cipher. The optional group_cipher parameter can
# be used to override this automatic selection.
{% if 'wpa2' in sec_wpa_mode -%}
# Pairwise cipher for RSN/WPA2 (default: use wpa_pairwise value)
rsn_pairwise={{ sec_wpa_cipher | join(" ") }}
{% else -%}
# Pairwise cipher for WPA (v1) (default: TKIP)
wpa_pairwise={{ sec_wpa_cipher | join(" ") }}
{%- endif -%}
{% endif %}
{% if sec_wpa_passphrase -%}
# IEEE 802.11 specifies two authentication algorithms. hostapd can be
# configured to allow both of these or only one. Open system authentication
# should be used with IEEE 802.1X.
# Bit fields of allowed authentication algorithms:
# bit 0 = Open System Authentication
# bit 1 = Shared Key Authentication (requires WEP)
auth_algs=1
# WPA pre-shared keys for WPA-PSK. This can be either entered as a 256-bit
# secret in hex format (64 hex digits), wpa_psk, or as an ASCII passphrase
# (8..63 characters) that will be converted to PSK. This conversion uses SSID
# so the PSK changes when ASCII passphrase is used and the SSID is changed.
wpa_passphrase={{ sec_wpa_passphrase }}
# Set of accepted key management algorithms (WPA-PSK, WPA-EAP, or both). The
# entries are separated with a space. WPA-PSK-SHA256 and WPA-EAP-SHA256 can be
# added to enable SHA256-based stronger algorithms.
# WPA-PSK = WPA-Personal / WPA2-Personal
# WPA-PSK-SHA256 = WPA2-Personal using SHA256
wpa_key_mgmt=WPA-PSK
{% elif sec_wpa_radius -%}
##### IEEE 802.1X-2004 related configuration ##################################
# Require IEEE 802.1X authorization
ieee8021x=1
# Set of accepted key management algorithms (WPA-PSK, WPA-EAP, or both). The
# entries are separated with a space. WPA-PSK-SHA256 and WPA-EAP-SHA256 can be
# added to enable SHA256-based stronger algorithms.
# WPA-EAP = WPA-Enterprise / WPA2-Enterprise
# WPA-EAP-SHA256 = WPA2-Enterprise using SHA256
wpa_key_mgmt=WPA-EAP
{% if sec_wpa_radius_source -%}
# RADIUS client forced local IP address for the access point
# Normally the local IP address is determined automatically based on configured
# IP addresses, but this field can be used to force a specific address to be
# used, e.g., when the device has multiple IP addresses.
radius_client_addr={{ sec_wpa_radius_source }}
{% endif %}
{% for radius in sec_wpa_radius -%}
# RADIUS authentication server
auth_server_addr={{ radius.server }}
auth_server_port={{ radius.port }}
auth_server_shared_secret={{ radius.key }}
{% if radius.acc_port -%}
# RADIUS accounting server
acct_server_addr={{ radius.server }}
acct_server_port={{ radius.acc_port }}
acct_server_shared_secret={{ radius.key }}
{% endif %}
{% endfor %}
{% endif %}
{% else %}
# Open system
auth_algs=1
{% endif %}
# TX queue parameters (EDCF / bursting)
# tx_queue_<queue name>_<param>
# queues: data0, data1, data2, data3
# (data0 is the highest priority queue)
# parameters:
# aifs: AIFS (default 2)
# cwmin: cwMin (1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191,
# 16383, 32767)
# cwmax: cwMax (same values as cwMin, cwMax >= cwMin)
# burst: maximum length (in milliseconds with precision of up to 0.1 ms) for
# bursting
#
# Default WMM parameters (IEEE 802.11 draft; 11-03-0504-03-000e):
# These parameters are used by the access point when transmitting frames
# to the clients.
#
# Low priority / AC_BK = background
tx_queue_data3_aifs=7
tx_queue_data3_cwmin=15
tx_queue_data3_cwmax=1023
tx_queue_data3_burst=0
# Note: for IEEE 802.11b mode: cWmin=31 cWmax=1023 burst=0
#
# Normal priority / AC_BE = best effort
tx_queue_data2_aifs=3
tx_queue_data2_cwmin=15
tx_queue_data2_cwmax=63
tx_queue_data2_burst=0
# Note: for IEEE 802.11b mode: cWmin=31 cWmax=127 burst=0
#
# High priority / AC_VI = video
tx_queue_data1_aifs=1
tx_queue_data1_cwmin=7
tx_queue_data1_cwmax=15
tx_queue_data1_burst=3.0
# Note: for IEEE 802.11b mode: cWmin=15 cWmax=31 burst=6.0
#
# Highest priority / AC_VO = voice
tx_queue_data0_aifs=1
tx_queue_data0_cwmin=3
tx_queue_data0_cwmax=7
tx_queue_data0_burst=1.5
# Default WMM parameters (IEEE 802.11 draft; 11-03-0504-03-000e):
# for 802.11a or 802.11g networks
# These parameters are sent to WMM clients when they associate.
# The parameters will be used by WMM clients for frames transmitted to the
# access point.
#
# note - txop_limit is in units of 32microseconds
# note - acm is admission control mandatory flag. 0 = admission control not
# required, 1 = mandatory
# note - Here cwMin and cmMax are in exponent form. The actual cw value used
# will be (2^n)-1 where n is the value given here. The allowed range for these
# wmm_ac_??_{cwmin,cwmax} is 0..15 with cwmax >= cwmin.
#
wmm_enabled=1
# Low priority / AC_BK = background
wmm_ac_bk_cwmin=4
wmm_ac_bk_cwmax=10
wmm_ac_bk_aifs=7
wmm_ac_bk_txop_limit=0
wmm_ac_bk_acm=0
# Note: for IEEE 802.11b mode: cWmin=5 cWmax=10
#
# Normal priority / AC_BE = best effort
wmm_ac_be_aifs=3
wmm_ac_be_cwmin=4
wmm_ac_be_cwmax=10
wmm_ac_be_txop_limit=0
wmm_ac_be_acm=0
# Note: for IEEE 802.11b mode: cWmin=5 cWmax=7
#
# High priority / AC_VI = video
wmm_ac_vi_aifs=2
wmm_ac_vi_cwmin=3
wmm_ac_vi_cwmax=4
wmm_ac_vi_txop_limit=94
wmm_ac_vi_acm=0
# Note: for IEEE 802.11b mode: cWmin=4 cWmax=5 txop_limit=188
#
# Highest priority / AC_VO = voice
wmm_ac_vo_aifs=2
wmm_ac_vo_cwmin=2
wmm_ac_vo_cwmax=3
wmm_ac_vo_txop_limit=47
wmm_ac_vo_acm=0
"""
# Please be careful if you edit the template.
config_wpa_suppl_tmpl = """
# WPA supplicant config
network={
ssid="{{ ssid }}"
{%- if sec_wpa_passphrase %}
psk="{{ sec_wpa_passphrase }}"
{% endif %}
}
"""
default_config_data = {
'address': [],
'address_remove': [],
'cap_ht' : False,
'cap_ht_40mhz_incapable' : False,
'cap_ht_powersave' : False,
'cap_ht_chan_set_width' : '',
'cap_ht_delayed_block_ack' : False,
'cap_ht_dsss_cck_40' : False,
'cap_ht_greenfield' : False,
'cap_ht_ldpc' : False,
'cap_ht_lsig_protection' : False,
'cap_ht_max_amsdu' : '',
'cap_ht_short_gi' : [],
'cap_ht_smps' : '',
'cap_ht_stbc_rx' : '',
'cap_ht_stbc_tx' : False,
'cap_req_ht' : False,
'cap_req_vht' : False,
'cap_vht' : False,
'cap_vht_antenna_cnt' : '',
'cap_vht_antenna_fixed' : False,
'cap_vht_beamform' : '',
'cap_vht_center_freq_1' : '',
'cap_vht_center_freq_2' : '',
'cap_vht_chan_set_width' : '',
'cap_vht_ldpc' : False,
'cap_vht_link_adaptation' : False,
'cap_vht_max_mpdu_exp' : '',
'cap_vht_max_mpdu' : '',
'cap_vht_short_gi' : [],
'cap_vht_stbc_rx' : '',
'cap_vht_stbc_tx' : False,
'cap_vht_tx_powersave' : False,
'cap_vht_vht_cf' : False,
'channel': '',
'country_code': '',
'description': '',
'deleted': False,
'dhcp_client_id': '',
'dhcp_hostname': '',
'dhcp_vendor_class_id': '',
'dhcpv6_prm_only': False,
'dhcpv6_temporary': False,
'disable': False,
'disable_broadcast_ssid' : False,
'disable_link_detect' : 1,
'expunge_failing_stations' : False,
'hw_id' : '',
'intf': '',
'isolate_stations' : False,
'ip_disable_arp_filter': 1,
'ip_enable_arp_accept': 0,
'ip_enable_arp_announce': 0,
'ip_enable_arp_ignore': 0,
'mac' : '',
'max_stations' : '',
'mgmt_frame_protection' : 'disabled',
'mode' : 'g',
'phy' : '',
'reduce_transmit_power' : '',
'sec_wep' : False,
'sec_wep_key' : [],
'sec_wpa' : False,
'sec_wpa_cipher' : [],
'sec_wpa_mode' : 'both',
'sec_wpa_passphrase' : '',
'sec_wpa_radius' : [],
'ssid' : '',
'type' : 'monitor',
'vif': [],
'vif_remove': []
}
def get_conf_file(conf_type, intf):
cfg_dir = '/var/run/' + conf_type
# create directory on demand
if not os.path.exists(cfg_dir):
os.mkdir(cfg_dir)
# fix permissions - corresponds to mode 755
os.chmod(cfg_dir, S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH)
uid = getpwnam(user).pw_uid
gid = getgrnam(group).gr_gid
os.chown(cfg_dir, uid, gid)
cfg_file = cfg_dir + r'/{}.cfg'.format(intf)
return cfg_file
def get_pid(conf_type, intf):
cfg_dir = '/var/run/' + conf_type
# create directory on demand
if not os.path.exists(cfg_dir):
os.mkdir(cfg_dir)
# fix permissions - corresponds to mode 755
os.chmod(cfg_dir, S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH)
uid = getpwnam(user).pw_uid
gid = getgrnam(group).gr_gid
os.chown(cfg_dir, uid, gid)
cfg_file = cfg_dir + r'/{}.pid'.format(intf)
return cfg_file
def get_wpa_suppl_config_name(intf):
cfg_dir = '/var/run/wpa_supplicant'
# create directory on demand
if not os.path.exists(cfg_dir):
os.mkdir(cfg_dir)
# fix permissions - corresponds to mode 755
os.chmod(cfg_dir, S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH)
uid = getpwnam(user).pw_uid
gid = getgrnam(group).gr_gid
os.chown(cfg_dir, uid, gid)
cfg_file = cfg_dir + r'/{}.cfg'.format(intf)
return cfg_file
def subprocess_cmd(command):
p = Popen(command, stdout=PIPE, shell=True)
p.communicate()
def get_config():
wifi = deepcopy(default_config_data)
conf = Config()
# determine tagNode instance
- try:
- wifi['intf'] = os.environ['VYOS_TAGNODE_VALUE']
- except KeyError as E:
- print("Interface not specified")
+ 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'] = True
# 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
# ARP enable ignore
if conf.exists('ip enable-arp-ignore'):
wifi['ip_enable_arp_ignore'] = 1
# 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')
# Wireless physical device
if conf.exists('phy'):
wifi['phy'] = conf.return_value('phy')
# 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' : '',
'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
# 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'):
wifi['type'] = conf.return_value('type')
# 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))
# 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
def verify(wifi):
if wifi['deleted']:
return None
if wifi['type'] != 'monitor' and not wifi['ssid']:
raise ConfigError('SSID must be set for {}'.format(wifi['intf']))
if wifi['type'] == 'access-point':
c = Config()
if not c.exists('system wifi-regulatory-domain'):
raise ConfigError('Wireless regulatory domain is mandatory,\n' \
'use "set system wifi-regulatory-domain".')
if not wifi['channel']:
raise ConfigError('Channel must be set for {}'.format(wifi['intf']))
if len(wifi['sec_wep_key']) > 4:
raise ConfigError('No more then 4 WEP keys configurable')
if wifi['cap_vht'] and not wifi['cap_ht']:
raise ConfigError('Specify HT flags if you want to use VHT!')
if wifi['cap_vht_beamform'] and wifi['cap_vht_antenna_cnt'] == 1:
raise ConfigError('Cannot use beam forming with just one antenna!')
if wifi['sec_wep'] and (len(wifi['sec_wep_key']) == 0):
raise ConfigError('Missing WEP keys')
if wifi['sec_wpa'] and not (wifi['sec_wpa_passphrase'] or wifi['sec_wpa_radius']):
raise ConfigError('Misssing WPA key or RADIUS server')
for radius in wifi['sec_wpa_radius']:
if not radius['key']:
raise ConfigError('Misssing RADIUS shared secret key for server: {}'.format(radius['server']))
return None
def generate(wifi):
pid = 0
# always stop hostapd service first before reconfiguring it
pidfile = get_pid('hostapd', wifi['intf'])
if os.path.isfile(pidfile):
pid = 0
with open(pidfile, 'r') as f:
pid = int(f.read())
if pid_exists(pid):
cmd = 'start-stop-daemon --stop --quiet'
cmd += ' --pidfile ' + pidfile
subprocess_cmd(cmd)
# always stop wpa_supplicant service first before reconfiguring it
pidfile = get_pid('wpa_supplicant', wifi['intf'])
if os.path.isfile(pidfile):
pid = 0
with open(pidfile, 'r') as f:
pid = int(f.read())
if pid_exists(pid):
cmd = 'start-stop-daemon --stop --quiet'
cmd += ' --pidfile ' + pidfile
subprocess_cmd(cmd)
# Delete config files if interface is removed
if wifi['deleted']:
if os.path.isfile(get_conf_file('hostapd', wifi['intf'])):
os.unlink(get_conf_file('hostapd', wifi['intf']))
if os.path.isfile(get_conf_file('wpa_supplicant', wifi['intf'])):
os.unlink(get_conf_file('wpa_supplicant', wifi['intf']))
return None
# render appropriate new config files depending on access-point or station mode
if wifi['type'] == 'access-point':
tmpl = Template(config_hostapd_tmpl)
config_text = tmpl.render(wifi)
with open(get_conf_file('hostapd', wifi['intf']), 'w') as f:
f.write(config_text)
elif wifi['type'] == 'station':
tmpl = Template(config_wpa_suppl_tmpl)
config_text = tmpl.render(wifi)
with open(get_conf_file('wpa_supplicant', wifi['intf']), 'w') as f:
f.write(config_text)
return None
def apply(wifi):
w = EthernetIf(wifi['intf'])
if wifi['deleted']:
# delete interface
w.remove()
else:
# Some parts e.g. MAC address can't be changed when interface is up
w.set_state('down')
# update interface description used e.g. within SNMP
w.set_alias(wifi['description'])
# get DHCP config dictionary and update values
opt = w.get_dhcp_options()
if wifi['dhcp_client_id']:
opt['client_id'] = wifi['dhcp_client_id']
if wifi['dhcp_hostname']:
opt['hostname'] = wifi['dhcp_hostname']
if wifi['dhcp_vendor_class_id']:
opt['vendor_class_id'] = wifi['dhcp_vendor_class_id']
# store DHCP config dictionary - used later on when addresses are aquired
w.set_dhcp_options(opt)
# get DHCPv6 config dictionary and update values
opt = w.get_dhcpv6_options()
if wifi['dhcpv6_prm_only']:
opt['dhcpv6_prm_only'] = True
if wifi['dhcpv6_temporary']:
opt['dhcpv6_temporary'] = True
# store DHCPv6 config dictionary - used later on when addresses are aquired
w.set_dhcpv6_options(opt)
# ignore link state changes
w.set_link_detect(wifi['disable_link_detect'])
# Change interface MAC address - re-set to real hardware address (hw-id)
# if custom mac is removed
if wifi['mac']:
w.set_mac(wifi['mac'])
else:
w.set_mac(wifi['hw_id'])
# configure ARP filter configuration
w.set_arp_filter(wifi['ip_disable_arp_filter'])
# configure ARP accept
w.set_arp_accept(wifi['ip_enable_arp_accept'])
# configure ARP announce
w.set_arp_announce(wifi['ip_enable_arp_announce'])
# configure ARP ignore
w.set_arp_ignore(wifi['ip_enable_arp_ignore'])
# enable interface
if not wifi['disable']:
w.set_state('up')
# Configure interface address(es)
# - not longer required addresses get removed first
# - newly addresses will be added second
for addr in wifi['address_remove']:
w.del_addr(addr)
for addr in wifi['address']:
w.add_addr(addr)
# remove no longer required VLAN interfaces (vif)
for vif in wifi['vif_remove']:
e.del_vlan(vif)
# create VLAN interfaces (vif)
for vif in wifi['vif']:
# QoS priority mapping can only be set during interface creation
# so we delete the interface first if required.
if vif['egress_qos_changed'] or vif['ingress_qos_changed']:
try:
# on system bootup the above condition is true but the interface
# does not exists, which throws an exception, but that's legal
e.del_vlan(vif['id'])
except:
pass
vlan = e.add_vlan(vif['id'])
apply_vlan_config(vlan, vif)
# Physical interface is now configured. Proceed by starting hostapd or
# wpa_supplicant daemon. When type is monitor we can just skip this.
if wifi['type'] == 'access-point':
cmd = 'start-stop-daemon --start --quiet'
cmd += ' --exec /usr/sbin/hostapd'
# now pass arguments to hostapd binary
cmd += ' -- -B'
cmd += ' -P {}'.format(get_pid('hostapd', wifi['intf']))
cmd += ' {}'.format(get_conf_file('hostapd', wifi['intf']))
# execute assembled command
subprocess_cmd(cmd)
elif wifi['type'] == 'station':
cmd = 'start-stop-daemon --start --quiet'
cmd += ' --exec /sbin/wpa_supplicant'
# now pass arguments to hostapd binary
cmd += ' -- -s -B -D nl80211'
cmd += ' -P {}'.format(get_pid('wpa_supplicant', wifi['intf']))
cmd += ' -i {}'.format(wifi['intf'])
cmd += ' -c {}'.format(get_conf_file('wpa_supplicant', wifi['intf']))
# execute assembled command
subprocess_cmd(cmd)
return None
if __name__ == '__main__':
try:
c = get_config()
verify(c)
generate(c)
apply(c)
except ConfigError as e:
print(e)
exit(1)

File Metadata

Mime Type
text/x-diff
Expires
Fri, Nov 6, 10:14 AM (1 h, 51 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
4625500
Default Alt Text
(188 KB)

Event Timeline