Page Menu
Home
VyOS Platform
Search
Configure Global Search
Log In
Files
F119063912
No One
Temporary
Actions
View File
Edit File
Delete File
View Transforms
Subscribe
Flag For Later
Award Token
Size
154 KB
Referenced Files
None
Subscribers
None
View Options
diff --git a/python/vyos/ifconfig/ethernet.py b/python/vyos/ifconfig/ethernet.py
index 8b6b6d9db..30e3a3bef 100644
--- a/python/vyos/ifconfig/ethernet.py
+++ b/python/vyos/ifconfig/ethernet.py
@@ -1,231 +1,231 @@
# Copyright 2019 VyOS maintainers and contributors <maintainers@vyos.io>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library. If not, see <http://www.gnu.org/licenses/>.
import os
import re
from vyos.ifconfig.vlan import VLANIf
from vyos.validate import *
class EthernetIf(VLANIf):
"""
Abstraction of a Linux Ethernet Interface
"""
_command_set = {**VLANIf._command_set, **{
'gro': {
'validate': lambda v: assert_list(v, ['on', 'off']),
'shellcmd': '/sbin/ethtool -K {ifname} gro {value}',
},
'gso': {
'validate': lambda v: assert_list(v, ['on', 'off']),
'shellcmd': '/sbin/ethtool -K {ifname} gso {value}',
},
'sg': {
'validate': lambda v: assert_list(v, ['on', 'off']),
'shellcmd': '/sbin/ethtool -K {ifname} sg {value}',
},
'tso': {
'validate': lambda v: assert_list(v, ['on', 'off']),
'shellcmd': '/sbin/ethtool -K {ifname} tso {value}',
},
'ufo': {
'validate': lambda v: assert_list(v, ['on', 'off']),
'shellcmd': '/sbin/ethtool -K {ifname} ufo {value}',
},
}}
default = {
'type': 'ethernet',
}
def _delete(self):
# Ethernet interfaces can not be removed
pass
def get_driver_name(self):
"""
Return the driver name used by NIC. Some NICs don't support all
features e.g. changing link-speed, duplex
Example:
>>> from vyos.ifconfig import EthernetIf
>>> i = EthernetIf('eth0')
>>> i.get_driver_name()
'vmxnet3'
"""
sysfs_file = '/sys/class/net/{}/device/driver/module'.format(
self.config['ifname'])
if os.path.exists(sysfs_file):
link = os.readlink(sysfs_file)
return os.path.basename(link)
else:
return None
def set_flow_control(self, enable):
"""
Changes the pause parameters of the specified Ethernet device.
@param enable: true -> enable pause frames, false -> disable pause frames
Example:
>>> from vyos.ifconfig import EthernetIf
>>> i = EthernetIf('eth0')
>>> i.set_flow_control(True)
"""
if enable not in ['on', 'off']:
raise ValueError("Value out of range")
if self.get_driver_name() in ['vmxnet3', 'virtio_net']:
self._debug_msg('{} driver does not support changing flow control settings!'
.format(self.get_driver_name()))
return
# Get current flow control settings:
cmd = '/sbin/ethtool --show-pause {0}'.format(self.config['ifname'])
tmp = self._cmd(cmd)
# The above command returns - with tabs:
#
# Pause parameters for eth0:
# Autonegotiate: on
# RX: off
# TX: off
if re.search("Autonegotiate:\ton", tmp):
if enable == "on":
# flowcontrol is already enabled - no need to re-enable it again
# this will prevent the interface from flapping as applying the
# flow-control settings will take the interface down and bring
# it back up every time.
return
# Assemble command executed on system. Unfortunately there is no way
# to change this setting via sysfs
cmd = '/sbin/ethtool --pause {0} autoneg {1} tx {1} rx {1}'.format(
self.config['ifname'], enable)
try:
# An exception will be thrown if the settings are not changed
return self._cmd(cmd)
- except CalledProcessError:
+ except RuntimeError:
pass
def set_speed_duplex(self, speed, duplex):
"""
Set link speed in Mbit/s and duplex.
@speed can be any link speed in MBit/s, e.g. 10, 100, 1000 auto
@duplex can be half, full, auto
Example:
>>> from vyos.ifconfig import EthernetIf
>>> i = EthernetIf('eth0')
>>> i.set_speed_duplex('auto', 'auto')
"""
if speed not in ['auto', '10', '100', '1000', '2500', '5000', '10000', '25000', '40000', '50000', '100000', '400000']:
raise ValueError("Value out of range (speed)")
if duplex not in ['auto', 'full', 'half']:
raise ValueError("Value out of range (duplex)")
if self.get_driver_name() in ['vmxnet3', 'virtio_net']:
self._debug_msg('{} driver does not support changing speed/duplex settings!'
.format(self.get_driver_name()))
return
# Get current speed and duplex settings:
cmd = '/sbin/ethtool {0}'.format(self.config['ifname'])
tmp = self._cmd(cmd)
if re.search("\tAuto-negotiation: on", tmp):
if speed == 'auto' and duplex == 'auto':
# bail out early as nothing is to change
return
else:
# read in current speed and duplex settings
cur_speed = 0
cur_duplex = ''
for line in tmp.splitlines():
if line.lstrip().startswith("Speed:"):
non_decimal = re.compile(r'[^\d.]+')
cur_speed = non_decimal.sub('', line)
continue
if line.lstrip().startswith("Duplex:"):
cur_duplex = line.split()[-1].lower()
break
if (cur_speed == speed) and (cur_duplex == duplex):
# bail out early as nothing is to change
return
cmd = '/sbin/ethtool -s {}'.format(self.config['ifname'])
if speed == 'auto' or duplex == 'auto':
cmd += ' autoneg on'
else:
cmd += ' speed {} duplex {} autoneg off'.format(speed, duplex)
return self._cmd(cmd)
def set_gro(self, state):
"""
Example:
>>> from vyos.ifconfig import EthernetIf
>>> i = EthernetIf('eth0')
>>> i.set_gro('on')
"""
return self.set_interface('gro', state)
def set_gso(self, state):
"""
Example:
>>> from vyos.ifconfig import EthernetIf
>>> i = EthernetIf('eth0')
>>> i.set_gso('on')
"""
return self.set_interface('gso', state)
def set_sg(self, state):
"""
Example:
>>> from vyos.ifconfig import EthernetIf
>>> i = EthernetIf('eth0')
>>> i.set_sg('on')
"""
return self.set_interface('sg', state)
def set_tso(self, state):
"""
Example:
>>> from vyos.ifconfig import EthernetIf
>>> i = EthernetIf('eth0')
>>> i.set_tso('on')
"""
return self.set_interface('tso', state)
def set_ufo(self, state):
"""
Example:
>>> from vyos.ifconfig import EthernetIf
>>> i = EthernetIf('eth0')
>>> i.set_udp_offload('on')
"""
if state not in ['on', 'off']:
raise ValueError('state must be "on" or "off"')
cmd = '/sbin/ethtool -K {} ufo {}'.format(self.config['ifname'], state)
return self._cmd(cmd)
diff --git a/python/vyos/ifconfig/interface.py b/python/vyos/ifconfig/interface.py
index 18256cf99..4f72271c9 100644
--- a/python/vyos/ifconfig/interface.py
+++ b/python/vyos/ifconfig/interface.py
@@ -1,849 +1,859 @@
# Copyright 2019 VyOS maintainers and contributors <maintainers@vyos.io>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library. If not, see <http://www.gnu.org/licenses/>.
import os
import re
import jinja2
import json
import glob
import time
from copy import deepcopy
import vyos.interfaces
from vyos.validate import * # should not * include
from vyos.config import Config # not used anymore
from vyos import ConfigError
from ipaddress import IPv4Network, IPv6Address
from netifaces import ifaddresses, AF_INET, AF_INET6
from time import sleep
from os.path import isfile
from tabulate import tabulate
from hurry.filesize import size,alternative
from datetime import timedelta
from vyos.ifconfig.control import Control
dhclient_base = r'/var/lib/dhcp/dhclient_'
dhcp_cfg = """
# generated by ifconfig.py
option rfc3442-classless-static-routes code 121 = array of unsigned integer 8;
timeout 60;
retry 300;
interface "{{ intf }}" {
send host-name "{{ hostname }}";
{% if client_id -%}
send dhcp-client-identifier "{{ client_id }}";
{% endif -%}
{% if vendor_class_id -%}
send vendor-class-identifier "{{ vendor_class_id }}";
{% endif -%}
request subnet-mask, broadcast-address, routers, domain-name-servers,
rfc3442-classless-static-routes, domain-name, interface-mtu;
require subnet-mask;
}
"""
dhcpv6_cfg = """
# generated by ifconfig.py
interface "{{ intf }}" {
request routers, domain-name-servers, domain-name;
}
"""
class Interface(Control):
options = []
required = []
default = {
'type': '',
}
_command_set = {
'state': {
'validate': lambda v: assert_list(v, ['up', 'down']),
'shellcmd': 'ip link set dev {ifname} {value}',
},
'mac': {
'validate': assert_mac,
'shellcmd': 'ip link set dev {ifname} address {value}',
},
'vrf': {
'force': True,
'convert': lambda v: f'master {v}' if v else 'nomaster',
'shellcmd': 'ip link set dev {ifname} {value}',
},
}
_sysfs_get = {
'mac': {
'location': '/sys/class/net/{ifname}/address',
},
'mtu': {
'location': '/sys/class/net/{ifname}/mtu',
},
}
_sysfs_set = {
'alias': {
'convert': lambda name: name if name else '\0',
'location': '/sys/class/net/{ifname}/ifalias',
},
'mtu': {
'validate': assert_mtu,
'location': '/sys/class/net/{ifname}/mtu',
},
'arp_cache_tmo': {
'convert': lambda tmo: (int(tmo) * 1000),
'location': '/proc/sys/net/ipv4/neigh/{ifname}/base_reachable_time_ms',
},
'arp_filter': {
'validate': assert_boolean,
'location': '/proc/sys/net/ipv4/conf/{ifname}/arp_filter',
},
'arp_accept': {
'validate': lambda arp: assert_range(arp,0,2),
'location': '/proc/sys/net/ipv4/conf/{ifname}/arp_accept',
},
'arp_announce': {
'validate': assert_boolean,
'location': '/proc/sys/net/ipv4/conf/{ifname}/arp_announce',
},
'arp_ignore': {
'validate': assert_boolean,
'location': '/proc/sys/net/ipv4/conf/{ifname}/arp_ignore',
},
'proxy_arp': {
'validate': assert_boolean,
'location': '/proc/sys/net/ipv4/conf/{ifname}/proxy_arp',
},
'proxy_arp_pvlan': {
'validate': assert_boolean,
'location': '/proc/sys/net/ipv4/conf/{ifname}/proxy_arp_pvlan',
},
# link_detect vs link_filter name weirdness
'link_detect': {
'validate': lambda link: assert_range(link,0,3),
'location': '/proc/sys/net/ipv4/conf/{ifname}/link_filter',
},
}
def __init__(self, ifname, **kargs):
"""
This is the base interface class which supports basic IP/MAC address
operations as well as DHCP(v6). Other interface which represent e.g.
and ethernet bridge are implemented as derived classes adding all
additional functionality.
For creation you will need to provide the interface type, otherwise
the existing interface is used
DEBUG:
This class has embedded debugging (print) which can be enabled by
creating the following file:
vyos@vyos# touch /tmp/vyos.ifconfig.debug
Example:
>>> from vyos.ifconfig import Interface
>>> i = Interface('eth0')
"""
self.config = deepcopy(self.default)
self.config['ifname'] = ifname
for k in self.options:
if k in kargs:
self.config[k] = kargs[k]
if not os.path.exists('/sys/class/net/{}'.format(self.config['ifname'])):
if not self.config['type']:
raise Exception('interface "{}" not found'.format(self.config['ifname']))
for k in self.required:
if k not in kargs:
name = self.default['type']
raise ConfigError(f'missing required option {k} for {name} {ifname} creation')
self._create()
# per interface DHCP config files
self._dhcp_cfg_file = dhclient_base + self.config['ifname'] + '.conf'
self._dhcp_pid_file = dhclient_base + self.config['ifname'] + '.pid'
self._dhcp_lease_file = dhclient_base + self.config['ifname'] + '.leases'
# per interface DHCPv6 config files
self._dhcpv6_cfg_file = dhclient_base + self.config['ifname'] + '.v6conf'
self._dhcpv6_pid_file = dhclient_base + self.config['ifname'] + '.v6pid'
self._dhcpv6_lease_file = dhclient_base + self.config['ifname'] + '.v6leases'
# DHCP options
self._dhcp_options = {
'intf' : self.config['ifname'],
'hostname' : '',
'client_id' : '',
'vendor_class_id' : ''
}
# DHCPv6 options
self._dhcpv6_options = {
'intf' : self.config['ifname'],
'dhcpv6_prm_only' : False,
'dhcpv6_temporary' : False
}
# list of assigned IP addresses
self._addr = []
def _create(self):
cmd = 'ip link add dev {ifname} type {type}'.format(**self.config)
self._cmd(cmd)
def remove(self):
"""
Remove interface from operating system. Removing the interface
deconfigures all assigned IP addresses and clear possible DHCP(v6)
client processes.
Example:
>>> from vyos.ifconfig import Interface
>>> i = Interface('eth0')
>>> i.remove()
"""
# stop DHCP(v6) if running
self._del_dhcp()
self._del_dhcpv6()
# remove all assigned IP addresses from interface - this is a bit redundant
# as the kernel will remove all addresses on interface deletion, but we
# can not delete ALL interfaces, see below
for addr in self.get_addr():
self.del_addr(addr)
# ---------------------------------------------------------------------
# A code refactoring is required as this type check is present as
# Interface implement behaviour for one of it's sub-class.
# It is required as the current pattern for vlan is:
# Interface('name').remove() to delete an interface
# The code should be modified to have a class method called connect and
# have Interface.connect('name').remove()
# each subclass should register within Interface the pattern for that
# interface ie: (ethX, etc.) and use this to create an instance of
# the right class (EthernetIf, ...)
# Ethernet interfaces can not be removed
# Commented out as nowhere in the code do we call Interface()
# This would also cause an import loop
# if self.__class__ == EthernetIf:
# return
# ---------------------------------------------------------------------
self._delete()
def _delete(self):
# NOTE (Improvement):
# after interface removal no other commands should be allowed
# to be called and instead should raise an Exception:
cmd = 'ip link del dev {}'.format(self.config['ifname'])
return self._cmd(cmd)
def get_mtu(self):
"""
Get/set interface mtu in bytes.
Example:
>>> from vyos.ifconfig import Interface
>>> Interface('eth0').get_mtu()
'1500'
"""
return self.get_interface('mtu')
def set_mtu(self, mtu):
"""
Get/set interface mtu in bytes.
Example:
>>> from vyos.ifconfig import Interface
>>> Interface('eth0').set_mtu(1400)
>>> Interface('eth0').get_mtu()
'1400'
"""
return self.set_interface('mtu', mtu)
def get_mac(self):
"""
Get current interface MAC (Media Access Contrl) address used.
Example:
>>> from vyos.ifconfig import Interface
>>> Interface('eth0').get_mac()
'00:50:ab:cd:ef:00'
"""
self.get_interface('mac')
def set_mac(self, mac):
"""
Set interface MAC (Media Access Contrl) address to given value.
Example:
>>> from vyos.ifconfig import Interface
>>> Interface('eth0').set_mac('00:50:ab:cd:ef:01')
"""
# If MAC is unchanged, bail out early
if mac == self.get_mac():
return None
# MAC address can only be changed if interface is in 'down' state
prev_state = self.get_state()
if prev_state == 'up':
self.set_state('down')
self.set_interface('mac', mac)
def set_vrf(self, vrf=''):
"""
Add/Remove interface from given VRF instance.
Example:
>>> from vyos.ifconfig import Interface
>>> Interface('eth0').set_vrf('foo')
>>> Interface('eth0').set_vrf()
"""
self.set_interface('vrf', vrf)
def set_arp_cache_tmo(self, tmo):
"""
Set ARP cache timeout value in seconds. Internal Kernel representation
is in milliseconds.
Example:
>>> from vyos.ifconfig import Interface
>>> Interface('eth0').set_arp_cache_tmo(40)
"""
return self.set_interface('arp_cache_tmo', tmo)
def set_arp_filter(self, arp_filter):
"""
Filter ARP requests
1 - Allows you to have multiple network interfaces on the same
subnet, and have the ARPs for each interface be answered
based on whether or not the kernel would route a packet from
the ARP'd IP out that interface (therefore you must use source
based routing for this to work). In other words it allows control
of which cards (usually 1) will respond to an arp request.
0 - (default) The kernel can respond to arp requests with addresses
from other interfaces. This may seem wrong but it usually makes
sense, because it increases the chance of successful communication.
IP addresses are owned by the complete host on Linux, not by
particular interfaces. Only for more complex setups like load-
balancing, does this behaviour cause problems.
"""
return self.set_interface('arp_filter', arp_filter)
def set_arp_accept(self, arp_accept):
"""
Define behavior for gratuitous ARP frames who's IP is not
already present in the ARP table:
0 - don't create new entries in the ARP table
1 - create new entries in the ARP table
Both replies and requests type gratuitous arp will trigger the
ARP table to be updated, if this setting is on.
If the ARP table already contains the IP address of the
gratuitous arp frame, the arp table will be updated regardless
if this setting is on or off.
"""
return self.set_interface('arp_accept', arp_accept)
def set_arp_announce(self, arp_announce):
"""
Define different restriction levels for announcing the local
source IP address from IP packets in ARP requests sent on
interface:
0 - (default) Use any local address, configured on any interface
1 - Try to avoid local addresses that are not in the target's
subnet for this interface. This mode is useful when target
hosts reachable via this interface require the source IP
address in ARP requests to be part of their logical network
configured on the receiving interface. When we generate the
request we will check all our subnets that include the
target IP and will preserve the source address if it is from
such subnet.
Increasing the restriction level gives more chance for
receiving answer from the resolved target while decreasing
the level announces more valid sender's information.
"""
return self.set_interface('arp_announce', arp_announce)
def set_arp_ignore(self, arp_ignore):
"""
Define different modes for sending replies in response to received ARP
requests that resolve local target IP addresses:
0 - (default): reply for any local target IP address, configured
on any interface
1 - reply only if the target IP address is local address
configured on the incoming interface
"""
return self.set_interface('arp_ignore', arp_ignore)
def set_link_detect(self, link_filter):
"""
Configure kernel response in packets received on interfaces that are 'down'
0 - Allow packets to be received for the address on this interface
even if interface is disabled or no carrier.
1 - Ignore packets received if interface associated with the incoming
address is down.
2 - Ignore packets received if interface associated with the incoming
address is down or has no carrier.
Default value is 0. Note that some distributions enable it in startup
scripts.
Example:
>>> from vyos.ifconfig import Interface
>>> Interface('eth0').set_link_detect(1)
"""
return self.set_interface('link_detect', link_filter)
def set_alias(self, ifalias=''):
"""
Set interface alias name used by e.g. SNMP
Example:
>>> from vyos.ifconfig import Interface
>>> Interface('eth0').set_alias('VyOS upstream interface')
to clear alias e.g. delete it use:
>>> Interface('eth0').set_ifalias('')
"""
self.set_interface('alias', ifalias)
def get_state(self):
"""
Get interface administrative state. Function will return 'up' or 'down'
Example:
>>> from vyos.ifconfig import Interface
>>> Interface('eth0').get_state()
'up'
"""
cmd = 'ip -json link show dev {}'.format(self.config['ifname'])
tmp = self._cmd(cmd)
out = json.loads(tmp)
state = 'down'
if 'UP' in out[0]['flags']:
state = 'up'
return state
def set_state(self, state):
"""
Set interface administrative state to be 'up' or 'down'
Example:
>>> from vyos.ifconfig import Interface
>>> Interface('eth0').set_state('down')
>>> Interface('eth0').get_state()
'down'
"""
return self.set_interface('state', state)
def set_proxy_arp(self, enable):
"""
Set per interface proxy ARP configuration
Example:
>>> from vyos.ifconfig import Interface
>>> Interface('eth0').set_proxy_arp(1)
"""
self.set_interface('proxy_arp', enable)
def set_proxy_arp_pvlan(self, enable):
"""
Private VLAN proxy arp.
Basically allow proxy arp replies back to the same interface
(from which the ARP request/solicitation was received).
This is done to support (ethernet) switch features, like RFC
3069, where the individual ports are NOT allowed to
communicate with each other, but they are allowed to talk to
the upstream router. As described in RFC 3069, it is possible
to allow these hosts to communicate through the upstream
router by proxy_arp'ing. Don't need to be used together with
proxy_arp.
This technology is known by different names:
In RFC 3069 it is called VLAN Aggregation.
Cisco and Allied Telesyn call it Private VLAN.
Hewlett-Packard call it Source-Port filtering or port-isolation.
Ericsson call it MAC-Forced Forwarding (RFC Draft).
Example:
>>> from vyos.ifconfig import Interface
>>> Interface('eth0').set_proxy_arp_pvlan(1)
"""
self.set_interface('proxy_arp_pvlan', enable)
def get_addr(self):
"""
Retrieve assigned IPv4 and IPv6 addresses from given interface.
This is done using the netifaces and ipaddress python modules.
Example:
>>> from vyos.ifconfig import Interface
>>> Interface('eth0').get_addrs()
['172.16.33.30/24', 'fe80::20c:29ff:fe11:a174/64']
"""
ipv4 = []
ipv6 = []
if AF_INET in ifaddresses(self.config['ifname']).keys():
for v4_addr in ifaddresses(self.config['ifname'])[AF_INET]:
# we need to manually assemble a list of IPv4 address/prefix
prefix = '/' + \
str(IPv4Network('0.0.0.0/' + v4_addr['netmask']).prefixlen)
ipv4.append(v4_addr['addr'] + prefix)
if AF_INET6 in ifaddresses(self.config['ifname']).keys():
for v6_addr in ifaddresses(self.config['ifname'])[AF_INET6]:
# Note that currently expanded netmasks are not supported. That means
# 2001:db00::0/24 is a valid argument while 2001:db00::0/ffff:ff00:: not.
# see https://docs.python.org/3/library/ipaddress.html
bits = bin(
int(v6_addr['netmask'].replace(':', ''), 16)).count('1')
prefix = '/' + str(bits)
# we alsoneed to remove the interface suffix on link local
# addresses
v6_addr['addr'] = v6_addr['addr'].split('%')[0]
ipv6.append(v6_addr['addr'] + prefix)
return ipv4 + ipv6
def add_addr(self, addr):
"""
Add IP(v6) address to interface. Address is only added if it is not
already assigned to that interface.
addr: can be an IPv4 address, IPv6 address, dhcp or dhcpv6!
IPv4: add IPv4 address to interface
IPv6: add IPv6 address to interface
dhcp: start dhclient (IPv4) on interface
dhcpv6: start dhclient (IPv6) on interface
Example:
>>> from vyos.ifconfig import Interface
>>> j = Interface('eth0')
>>> j.add_addr('192.0.2.1/24')
>>> j.add_addr('2001:db8::ffff/64')
>>> j.get_addr()
['192.0.2.1/24', '2001:db8::ffff/64']
"""
# cache new IP address which is assigned to interface
self._addr.append(addr)
# we can not have both DHCP and static IPv4 addresses assigned to an interface
if 'dhcp' in self._addr:
for addr in self._addr:
# do not change below 'if' ordering esle you will get an exception as:
# ValueError: 'dhcp' does not appear to be an IPv4 or IPv6 address
if addr != 'dhcp' and is_ipv4(addr):
raise ConfigError("Can't configure both static IPv4 and DHCP address on the same interface")
if addr == 'dhcp':
self._set_dhcp()
elif addr == 'dhcpv6':
self._set_dhcpv6()
else:
if not is_intf_addr_assigned(self.config['ifname'], addr):
cmd = 'ip addr add "{}" dev "{}"'.format(addr, self.config['ifname'])
return self._cmd(cmd)
def del_addr(self, addr):
"""
Delete IP(v6) address to interface. Address is only added if it is
assigned to that interface.
addr: can be an IPv4 address, IPv6 address, dhcp or dhcpv6!
IPv4: delete IPv4 address from interface
IPv6: delete IPv6 address from interface
dhcp: stop dhclient (IPv4) on interface
dhcpv6: stop dhclient (IPv6) on interface
Example:
>>> from vyos.ifconfig import Interface
>>> j = Interface('eth0')
>>> j.add_addr('2001:db8::ffff/64')
>>> j.add_addr('192.0.2.1/24')
>>> j.get_addr()
['192.0.2.1/24', '2001:db8::ffff/64']
>>> j.del_addr('192.0.2.1/24')
>>> j.get_addr()
['2001:db8::ffff/64']
"""
if addr == 'dhcp':
self._del_dhcp()
elif addr == 'dhcpv6':
self._del_dhcpv6()
else:
if is_intf_addr_assigned(self.config['ifname'], addr):
cmd = 'ip addr del "{}" dev "{}"'.format(addr, self.config['ifname'])
return self._cmd(cmd)
def get_dhcp_options(self):
"""
Return dictionary with supported DHCP options.
Dictionary should be altered and send back via set_dhcp_options()
so those options are applied when DHCP is run.
"""
return self._dhcp_options
def set_dhcp_options(self, options):
"""
Store new DHCP options used by next run of DHCP client.
"""
self._dhcp_options = options
def get_dhcpv6_options(self):
"""
Return dictionary with supported DHCPv6 options.
Dictionary should be altered and send back via set_dhcp_options()
so those options are applied when DHCP is run.
"""
return self._dhcpv6_options
def set_dhcpv6_options(self, options):
"""
Store new DHCP options used by next run of DHCP client.
"""
self._dhcpv6_options = options
# replace dhcpv4/v6 with systemd.networkd?
def _set_dhcp(self):
"""
Configure interface as DHCP client. The dhclient binary is automatically
started in background!
Example:
>>> from vyos.ifconfig import Interface
>>> j = Interface('eth0')
>>> j.set_dhcp()
"""
dhcp = self.get_dhcp_options()
if not dhcp['hostname']:
# read configured system hostname.
# maybe change to vyos hostd client ???
with open('/etc/hostname', 'r') as f:
dhcp['hostname'] = f.read().rstrip('\n')
# render DHCP configuration
tmpl = jinja2.Template(dhcp_cfg)
dhcp_text = tmpl.render(dhcp)
with open(self._dhcp_cfg_file, 'w') as f:
f.write(dhcp_text)
- cmd = 'start-stop-daemon --start --quiet --pidfile ' + \
- self._dhcp_pid_file
+ cmd = 'start-stop-daemon'
+ cmd += ' --start '
+ cmd += ' --quiet'
+ cmd += ' --oknodo'
+ cmd += ' --pidfile ' + self._dhcp_pid_file
cmd += ' --exec /sbin/dhclient --'
# now pass arguments to dhclient binary
cmd += ' -4 -nw -cf {} -pf {} -lf {} {}'.format(
self._dhcp_cfg_file, self._dhcp_pid_file, self._dhcp_lease_file, self.config['ifname'])
return self._cmd(cmd)
def _del_dhcp(self):
"""
De-configure interface as DHCP clinet. All auto generated files like
pid, config and lease will be removed.
Example:
>>> from vyos.ifconfig import Interface
>>> j = Interface('eth0')
>>> j.del_dhcp()
"""
pid = 0
if os.path.isfile(self._dhcp_pid_file):
with open(self._dhcp_pid_file, 'r') as f:
pid = int(f.read())
else:
self._debug_msg('No DHCP client PID found')
return None
# stop dhclient, we need to call dhclient and tell it should release the
# aquired IP address. tcpdump tells me:
# 172.16.35.103.68 > 172.16.35.254.67: [bad udp cksum 0xa0cb -> 0xb943!] BOOTP/DHCP, Request from 00:50:56:9d:11:df, length 300, xid 0x620e6946, Flags [none] (0x0000)
# Client-IP 172.16.35.103
# Client-Ethernet-Address 00:50:56:9d:11:df
# Vendor-rfc1048 Extensions
# Magic Cookie 0x63825363
# DHCP-Message Option 53, length 1: Release
# Server-ID Option 54, length 4: 172.16.35.254
# Hostname Option 12, length 10: "vyos"
#
cmd = '/sbin/dhclient -cf {} -pf {} -lf {} -r {}'.format(
self._dhcp_cfg_file, self._dhcp_pid_file, self._dhcp_lease_file, self.config['ifname'])
self._cmd(cmd)
# cleanup old config file
if os.path.isfile(self._dhcp_cfg_file):
os.remove(self._dhcp_cfg_file)
# cleanup old pid file
if os.path.isfile(self._dhcp_pid_file):
os.remove(self._dhcp_pid_file)
# cleanup old lease file
if os.path.isfile(self._dhcp_lease_file):
os.remove(self._dhcp_lease_file)
def _set_dhcpv6(self):
"""
Configure interface as DHCPv6 client. The dhclient binary is automatically
started in background!
Example:
>>> from vyos.ifconfig import Interface
>>> j = Interface('eth0')
>>> j.set_dhcpv6()
"""
dhcpv6 = self.get_dhcpv6_options()
# better save then sorry .. should be checked in interface script
# but if you missed it we are safe!
if dhcpv6['dhcpv6_prm_only'] and dhcpv6['dhcpv6_temporary']:
raise Exception('DHCPv6 temporary and parameters-only options are mutually exclusive!')
# render DHCP configuration
tmpl = jinja2.Template(dhcpv6_cfg)
dhcpv6_text = tmpl.render(dhcpv6)
with open(self._dhcpv6_cfg_file, 'w') as f:
f.write(dhcpv6_text)
# no longer accept router announcements on this interface
self._write_sysfs('/proc/sys/net/ipv6/conf/{}/accept_ra'
.format(self.config['ifname']), 0)
# assemble command-line to start DHCPv6 client (dhclient)
- cmd = 'start-stop-daemon --start --quiet --pidfile ' + \
- self._dhcpv6_pid_file
+ cmd = 'start-stop-daemon'
+ cmd += ' --start '
+ cmd += ' --quiet'
+ cmd += ' --oknodo'
+ cmd += ' --pidfile ' + self._dhcpv6_pid_file
cmd += ' --exec /sbin/dhclient --'
# now pass arguments to dhclient binary
cmd += ' -6 -nw -cf {} -pf {} -lf {}'.format(
self._dhcpv6_cfg_file, self._dhcpv6_pid_file, self._dhcpv6_lease_file)
# add optional arguments
if dhcpv6['dhcpv6_prm_only']:
cmd += ' -S'
if dhcpv6['dhcpv6_temporary']:
cmd += ' -T'
cmd += ' {}'.format(self.config['ifname'])
return self._cmd(cmd)
def _del_dhcpv6(self):
"""
De-configure interface as DHCPv6 clinet. All auto generated files like
pid, config and lease will be removed.
Example:
>>> from vyos.ifconfig import Interface
>>> j = Interface('eth0')
>>> j.del_dhcpv6()
"""
pid = 0
if os.path.isfile(self._dhcpv6_pid_file):
with open(self._dhcpv6_pid_file, 'r') as f:
pid = int(f.read())
else:
self._debug_msg('No DHCPv6 client PID found')
return None
# stop dhclient
- cmd = 'start-stop-daemon --stop --quiet --pidfile {}'.format(self._dhcpv6_pid_file)
+ cmd = 'start-stop-daemon'
+ cmd += ' --stop'
+ cmd += ' --oknodo'
+ cmd += ' --quiet'
+ cmd += ' --pidfile ' + self._dhcpv6_pid_file
self._cmd(cmd)
# accept router announcements on this interface
self._write_sysfs('/proc/sys/net/ipv6/conf/{}/accept_ra'
.format(self.config['ifname']), 1)
# cleanup old config file
if os.path.isfile(self._dhcpv6_cfg_file):
os.remove(self._dhcpv6_cfg_file)
# cleanup old pid file
if os.path.isfile(self._dhcpv6_pid_file):
os.remove(self._dhcpv6_pid_file)
# cleanup old lease file
if os.path.isfile(self._dhcpv6_lease_file):
os.remove(self._dhcpv6_lease_file)
def op_show_interface_stats(self):
stats = self.get_interface_stats()
rx = [['bytes','packets','errors','dropped','overrun','mcast'],[stats['rx_bytes'],stats['rx_packets'],stats['rx_errors'],stats['rx_dropped'],stats['rx_over_errors'],stats['multicast']]]
tx = [['bytes','packets','errors','dropped','carrier','collisions'],[stats['tx_bytes'],stats['tx_packets'],stats['tx_errors'],stats['tx_dropped'],stats['tx_carrier_errors'],stats['collisions']]]
output = "RX: \n"
output += tabulate(rx,headers="firstrow",numalign="right",tablefmt="plain")
output += "\n\nTX: \n"
output += tabulate(tx,headers="firstrow",numalign="right",tablefmt="plain")
print(' '.join(('\n'+output.lstrip()).splitlines(True)))
def get_interface_stats(self):
interface_stats = dict()
devices = [f for f in glob.glob("/sys/class/net/**/statistics")]
for dev_path in devices:
metrics = [f for f in glob.glob(dev_path +"/**")]
dev = re.findall(r"/sys/class/net/(.*)/statistics",dev_path)[0]
dev_dict = dict()
for metric_path in metrics:
metric = metric_path.replace(dev_path+"/","")
if isfile(metric_path):
data = open(metric_path, 'r').read()[:-1]
dev_dict[metric] = int(data)
interface_stats[dev] = dev_dict
return interface_stats[self.config['ifname']]
diff --git a/src/conf_mode/interfaces-openvpn.py b/src/conf_mode/interfaces-openvpn.py
index 463ae9fd7..3a3c69e37 100755
--- a/src/conf_mode/interfaces-openvpn.py
+++ b/src/conf_mode/interfaces-openvpn.py
@@ -1,1042 +1,1048 @@
#!/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 if match is found, False if no match or file is not found
"""
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 False
def get_config():
openvpn = deepcopy(default_config_data)
conf = Config()
# determine tagNode instance
if 'VYOS_TAGNODE_VALUE' not in os.environ:
raise ConfigError('Interface (VYOS_TAGNODE_VALUE) not specified')
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
# Special case when using EC certificates:
# if key-file is EC and dh-file is unset, set tls_dh to 'none'
if not openvpn['tls_dh'] and openvpn['tls_key'] and checkCertHeader('-----BEGIN EC PRIVATE KEY-----', openvpn['tls_key']):
openvpn['tls_dh'] = 'none'
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'] and openvpn['tls_dh'] != 'none':
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'] and not checkCertHeader('-----BEGIN EC PRIVATE KEY-----', openvpn['tls_key']):
raise ConfigError('Must specify "tls dh-file" when not using EC keys 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 |EC )?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'] and openvpn['tls_dh'] != 'none':
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'] and openvpn['tls_dh'] != 'none':
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"')
if openvpn['tls_key'] and checkCertHeader('-----BEGIN EC PRIVATE KEY-----', openvpn['tls_key']):
if openvpn['tls_dh'] and openvpn['tls_dh'] != 'none':
print('Warning: using dh-file and EC keys simultaneously will lead to DH ciphers being used instead of ECDH')
else:
print('Diffie-Hellman prime file is unspecified, assuming ECDH')
#
# 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(""",'"')
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 = 'start-stop-daemon'
+ cmd += ' --stop '
+ cmd += ' --quiet'
+ cmd += ' --oknodo'
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 = 'start-stop-daemon'
+ cmd += ' --start '
+ cmd += ' --quiet'
+ cmd += ' --oknodo'
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-wireless.py b/src/conf_mode/interfaces-wireless.py
index 54299b609..43455196c 100755
--- a/src/conf_mode/interfaces-wireless.py
+++ b/src/conf_mode/interfaces-wireless.py
@@ -1,1563 +1,1569 @@
#!/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 re import findall
from subprocess import Popen, PIPE
from psutil import pid_exists
from netifaces import interfaces
from netaddr import *
from vyos.ifconfig import WiFiIf
from vyos.ifconfig_vlan import apply_vlan_config, verify_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
# 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 }}
# The own IP address of the access point (used as NAS-IP-Address)
own_ip_addr={{ sec_wpa_radius_source }}
{% else %}
# The own IP address of the access point (used as NAS-IP-Address)
own_ip_addr=127.0.0.1
{% endif %}
{% for radius in sec_wpa_radius -%}
{%- if not radius.disabled -%}
# 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 %}
{% 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 }}"
{% else %}
key_mgmt=NONE
{% 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' : '',
'op_mode' : 'monitor',
'vif': [],
'vif_remove': [],
'vrf': ''
}
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
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
# Wireless physical device
if conf.exists('physical-device'):
wifi['phy'] = conf.return_value('physical-device')
# Media Access Control (MAC) address
if conf.exists('mac'):
wifi['mac'] = conf.return_value('mac')
# Maximum number of wireless radio stations
if conf.exists('max-stations'):
wifi['max_stations'] = conf.return_value('max-stations')
# Management Frame Protection (MFP) according to IEEE 802.11w
if conf.exists('mgmt-frame-protection'):
wifi['mgmt_frame_protection'] = conf.return_value('mgmt-frame-protection')
# Wireless radio mode
if conf.exists('mode'):
wifi['mode'] = conf.return_value('mode')
# retrieve VRF instance
if conf.exists('vrf'):
wifi['vrf'] = conf.return_value('vrf')
# Transmission power reduction in dBm
if conf.exists('reduce-transmit-power'):
wifi['reduce_transmit_power'] = conf.return_value('reduce-transmit-power')
# WEP enabled?
if conf.exists('security wep'):
wifi['sec_wep'] = True
# WEP encryption key(s)
if conf.exists('security wep key'):
wifi['sec_wep_key'] = conf.return_values('security wep key')
# WPA enabled?
if conf.exists('security wpa'):
wifi['sec_wpa'] = True
# WPA Cipher suite
if conf.exists('security wpa cipher'):
wifi['sec_wpa_cipher'] = conf.return_values('security wpa cipher')
# WPA mode
if conf.exists('security wpa mode'):
wifi['sec_wpa_mode'] = conf.return_value('security wpa mode')
# WPA default ciphers depend on WPA mode
if not wifi['sec_wpa_cipher']:
if wifi['sec_wpa_mode'] == 'wpa':
wifi['sec_wpa_cipher'].append('TKIP')
wifi['sec_wpa_cipher'].append('CCMP')
elif wifi['sec_wpa_mode'] == 'wpa2':
wifi['sec_wpa_cipher'].append('CCMP')
elif wifi['sec_wpa_mode'] == 'both':
wifi['sec_wpa_cipher'].append('CCMP')
wifi['sec_wpa_cipher'].append('TKIP')
# WPA personal shared pass phrase
if conf.exists('security wpa passphrase'):
wifi['sec_wpa_passphrase'] = conf.return_value('security wpa passphrase')
# WPA RADIUS source address
if conf.exists('security wpa radius source-address'):
wifi['sec_wpa_radius_source'] = conf.return_value('security wpa radius source-address')
# WPA RADIUS server
for server in conf.list_nodes('security wpa radius server'):
# set new configuration level
conf.set_level(cfg_base + ' security wpa radius server ' + server)
radius = {
'server' : server,
'acc_port' : '',
'disabled': False,
'port' : 1812,
'key' : ''
}
# RADIUS server port
if conf.exists('port'):
radius['port'] = int(conf.return_value('port'))
# receive RADIUS accounting info
if conf.exists('accounting'):
radius['acc_port'] = radius['port'] + 1
# Check if RADIUS server was temporary disabled
if conf.exists(['disable']):
radius['disabled'] = True
# RADIUS server shared-secret
if conf.exists('key'):
radius['key'] = conf.return_value('key')
# append RADIUS server to list of servers
wifi['sec_wpa_radius'].append(radius)
# re-set configuration level to parse new nodes
conf.set_level(cfg_base)
# Wireless access-point service set identifier (SSID)
if conf.exists('ssid'):
wifi['ssid'] = conf.return_value('ssid')
# Wireless device type for this interface
if conf.exists('type'):
tmp = conf.return_value('type')
if tmp == 'access-point':
tmp = 'ap'
wifi['op_mode'] = tmp
# re-set configuration level to parse new nodes
conf.set_level(cfg_base)
# Determine vif interfaces (currently effective) - to determine which
# vif interface is no longer present and needs to be removed
eff_intf = conf.list_effective_nodes('vif')
act_intf = conf.list_nodes('vif')
wifi['vif_remove'] = list_diff(eff_intf, act_intf)
if conf.exists('vif'):
for vif in conf.list_nodes('vif'):
# set config level to vif interface
conf.set_level(cfg_base + ' vif ' + vif)
wifi['vif'].append(vlan_to_dict(conf))
# disable interface
if conf.exists('disable'):
wifi['disable'] = True
# retrieve configured regulatory domain
conf.set_level('system')
if conf.exists('wifi-regulatory-domain'):
wifi['country_code'] = conf.return_value('wifi-regulatory-domain')
return wifi
def verify(wifi):
if wifi['deleted']:
return None
if wifi['op_mode'] != 'monitor' and not wifi['ssid']:
raise ConfigError('SSID must be set for {}'.format(wifi['intf']))
if not wifi['phy']:
raise ConfigError('You must specify physical-device')
if wifi['op_mode'] == 'ap':
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']))
vrf_name = wifi['vrf']
if vrf_name and vrf_name not in interfaces():
raise ConfigError(f'VRF "{vrf_name}" does not exist')
# use common function to verify VLAN configuration
verify_vlan_config(wifi)
conf = Config()
# Only one wireless interface per phy can be in station mode
base = ['interfaces', 'wireless']
for phy in os.listdir('/sys/class/ieee80211'):
stations = []
for wlan in conf.list_nodes(base):
# the following node is mandatory
if conf.exists(base + [wlan, 'physical-device', phy]):
tmp = conf.return_value(base + [wlan, 'type'])
if tmp == 'station':
stations.append(wlan)
if len(stations) > 1:
raise ConfigError('Only one station per wireless physical interface possible!')
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 = 'start-stop-daemon'
+ cmd += ' --stop '
+ cmd += ' --quiet'
+ cmd += ' --oknodo'
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 = 'start-stop-daemon'
+ cmd += ' --stop '
+ cmd += ' --quiet'
+ cmd += ' --oknodo'
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
if not wifi['mac']:
# http://wiki.stocksy.co.uk/wiki/Multiple_SSIDs_with_hostapd
# generate locally administered MAC address from used phy interface
with open('/sys/class/ieee80211/{}/addresses'.format(wifi['phy']), 'r') as f:
tmp = EUI(f.read().rstrip()).value
# mask last nibble from the MAC address
tmp &= 0xfffffffffff0
# set locally administered bit in MAC address
tmp |= 0x020000000000
# we now need to add an offset to our MAC address indicating this
# subinterfaces index
tmp += int(findall(r'\d+', wifi['intf'])[0])
# convert integer to "real" MAC address representation
mac = EUI(hex(tmp).split('x')[-1])
# change dialect to use : as delimiter instead of -
mac.dialect = mac_unix_expanded
wifi['mac'] = str(mac)
# render appropriate new config files depending on access-point or station mode
if wifi['op_mode'] == 'ap':
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['op_mode'] == '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):
if wifi['deleted']:
w = WiFiIf(wifi['intf'])
# delete interface
w.remove()
else:
# WiFi interface needs to be created on-block (e.g. mode or physical
# interface) instead of passing a ton of arguments, I just use a dict
# that is managed by vyos.ifconfig
conf = deepcopy(WiFiIf.get_config())
# Assign WiFi instance configuration parameters to config dict
conf['phy'] = wifi['phy']
# Finally create the new interface
w = WiFiIf(wifi['intf'], **conf)
# assign/remove VRF
w.set_vrf(wifi['vrf'])
# 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'])
# 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)
# Enable/Disable interface - interface is always placed in
# administrative down state in WiFiIf class
if not wifi['disable']:
w.set_state('up')
# Physical interface is now configured. Proceed by starting hostapd or
# wpa_supplicant daemon. When type is monitor we can just skip this.
if wifi['op_mode'] == 'ap':
cmd = 'start-stop-daemon'
cmd += ' --start '
cmd += ' --quiet'
cmd += ' --oknodo'
cmd += ' --pidfile ' + get_pid('hostapd', wifi['intf'])
cmd += ' --exec /usr/sbin/hostapd'
# now pass arguments to hostapd binary
cmd += ' -- '
cmd += ' -B'
cmd += ' -P ' + get_pid('hostapd', wifi['intf'])
cmd += ' ' + get_conf_file('hostapd', wifi['intf'])
# execute assembled command
subprocess_cmd(cmd)
elif wifi['op_mode'] == 'station':
cmd = 'start-stop-daemon'
cmd += ' --start '
cmd += ' --quiet'
cmd += ' --oknodo'
cmd += ' --pidfile ' + get_pid('hostapd', wifi['intf'])
cmd += ' --exec /sbin/wpa_supplicant'
# now pass arguments to hostapd binary
cmd += ' -- '
cmd += ' -s -B -D nl80211'
cmd += ' -P ' + get_pid('wpa_supplicant', wifi['intf'])
cmd += ' -i ' + wifi['intf']
cmd += ' -c ' + 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)
diff --git a/src/conf_mode/vpn_sstp.py b/src/conf_mode/vpn_sstp.py
index 8583ece74..8e5c7587c 100755
--- a/src/conf_mode/vpn_sstp.py
+++ b/src/conf_mode/vpn_sstp.py
@@ -1,537 +1,543 @@
#!/usr/bin/env python3
#
# Copyright (C) 2018-2020 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 jinja2
from time import sleep
from sys import exit
from subprocess import Popen, PIPE, check_output
from socket import socket, AF_INET, SOCK_STREAM
from copy import deepcopy
from stat import S_IRUSR, S_IWUSR, S_IRGRP
from psutil import pid_exists
from vyos.config import Config
from vyos import ConfigError
pidfile = r'/var/run/accel_sstp.pid'
sstp_cnf_dir = r'/etc/accel-ppp/sstp'
chap_secrets = sstp_cnf_dir + '/chap-secrets'
sstp_conf = sstp_cnf_dir + '/sstp.config'
# config path creation
if not os.path.exists(sstp_cnf_dir):
os.makedirs(sstp_cnf_dir)
sstp_config = """### generated by vpn_sstp.py ###
[modules]
log_syslog
sstp
shaper
{% if auth_mode == 'local' %}
chap-secrets
{% elif auth_mode == 'radius' %}
radius
{% endif -%}
ippool
{% for proto in auth_proto %}
{{proto}}
{% endfor %}
[core]
thread-count={{thread_cnt}}
[common]
single-session=replace
[log]
syslog=accel-sstp,daemon
copy=1
level=5
[client-ip-range]
disable
[sstp]
verbose=1
accept=ssl
ssl-ca-file={{ ssl_ca }}
ssl-pemfile={{ ssl_cert }}
ssl-keyfile={{ ssl_key }}
{% if client_ip_pool %}
[ip-pool]
gw-ip-address={{ client_gateway }}
{% for subnet in client_ip_pool %}
{{ subnet }}
{% endfor %}
{% endif %}
{% if dnsv4 %}
[dns]
{% for dns in dnsv4 -%}
dns{{ loop.index }}={{ dns }}
{% endfor -%}
{% endif %}
{% if auth_mode == 'local' %}
[chap-secrets]
chap-secrets=/etc/accel-ppp/sstp/chap-secrets
{% elif auth_mode == 'radius' %}
[radius]
verbose=1
{% for r in radius_server %}
server={{ r.server }},{{ r.key }},auth-port={{ r.port }},req-limit=0,fail-time={{ r.fail_time }}
{% endfor -%}
acct-timeout={{ radius_acct_tmo }}
timeout={{ radius_timeout }}
max-try={{ radius_max_try }}
{% if radius_nas_id %}
nas-identifier={{ radius_nas_id }}
{% endif -%}
{% if radius_nas_ip %}
nas-ip-address={{ radius_nas_ip }}
{% endif -%}
{% if radius_source_address %}
bind={{ radius_source_address }}
{% endif -%}
{% if radius_dynamic_author %}
dae-server={{ radius_dynamic_author.server }}:{{ radius_dynamic_author.port }},{{ radius_dynamic_author.key }}
{% endif -%}
{% endif %}
[ppp]
verbose=1
check-ip=1
{% if mtu %}
mtu={{ mtu }}
{% endif -%}
{% if ppp_mppe %}
mppe={{ ppp_mppe }}
{% endif -%}
{% if ppp_echo_interval %}
lcp-echo-interval={{ ppp_echo_interval }}
{% endif -%}
{% if ppp_echo_failure %}
lcp-echo-failure={{ ppp_echo_failure }}
{% endif -%}
{% if ppp_echo_timeout %}
lcp-echo-timeout={{ ppp_echo_timeout }}
{% endif %}
{% if radius_shaper_attr %}
[shaper]
verbose=1
attr={{ radius_shaper_attr }}
{% if radius_shaper_vendor %}
vendor={{ radius_shaper_vendor }}
{% endif -%}
{% endif %}
[cli]
tcp=127.0.0.1:2005
"""
# sstp chap secrets
chap_secrets_conf = """
# username server password acceptable local IP addresses shaper
{% for user in local_users %}
{% if user.state == 'enabled' %}
{% if user.upload and user.download %}
{{ "%-12s" | format(user.name) }} * {{ "%-16s" | format(user.password) }} {{ "%-16s" | format(user.ip) }} {{ user.download }} / {{ user.upload }}
{% else %}
{{ "%-12s" | format(user.name) }} * {{ "%-16s" | format(user.password) }} {{ "%-16s" | format(user.ip) }}
{% endif %}
{% endif %}
{% endfor %}
"""
def subprocess_cmd(command):
p = Popen(command, stdout=PIPE, shell=True)
p.communicate()
def chk_con():
cnt = 0
s = socket(AF_INET, SOCK_STREAM)
while True:
try:
s.connect(("127.0.0.1", 2005))
s.close()
break
except ConnectionRefusedError:
sleep(0.5)
cnt += 1
if cnt == 100:
raise("failed to start sstp server")
break
def accel_cmd(cmd):
if not cmd:
return None
try:
ret = check_output(['/usr/bin/accel-cmd', '-p', '2005', cmd])
return ret.decode().strip()
except:
return 1
default_config_data = {
'local_users' : [],
'auth_mode' : 'local',
'auth_proto' : [],
'radius_server' : [],
'radius_acct_tmo' : '3',
'radius_max_try' : '3',
'radius_timeout' : '3',
'radius_nas_id' : '',
'radius_nas_ip' : '',
'radius_source_address' : '',
'radius_shaper_attr' : '',
'radius_shaper_vendor': '',
'radius_dynamic_author' : '',
'ssl_ca' : '',
'ssl_cert' : '',
'ssl_key' : '',
'client_ip_pool' : [],
'dnsv4' : [],
'mtu' : '',
'ppp_mppe' : '',
'ppp_echo_failure' : '',
'ppp_echo_interval' : '',
'ppp_echo_timeout' : '',
'thread_cnt' : ''
}
def get_config():
sstp = deepcopy(default_config_data)
base_path = ['vpn', 'sstp']
conf = Config()
if not conf.exists(base_path):
return None
conf.set_level(base_path)
cpu = int(os.cpu_count()/2)
if cpu < 1:
cpu = 1
sstp['thread_cnt'] = cpu
if conf.exists(['authentication', 'mode']):
sstp['auth_mode'] = conf.return_value(['authentication', 'mode'])
#
# local auth
if conf.exists(['authentication', 'local-users']):
for username in conf.list_nodes(['authentication', 'local-users', 'username']):
user = {
'name' : username,
'password' : '',
'state' : 'enabled',
'ip' : '*',
'upload' : None,
'download' : None
}
conf.set_level(base_path + ['authentication', 'local-users', 'username', username])
if conf.exists(['password']):
user['password'] = conf.return_value(['password'])
if conf.exists(['disable']):
user['state'] = 'disable'
if conf.exists(['static-ip']):
user['ip'] = conf.return_value(['static-ip'])
if conf.exists(['rate-limit', 'download']):
user['download'] = conf.return_value(['rate-limit', 'download'])
if conf.exists(['rate-limit', 'upload']):
user['upload'] = conf.return_value(['rate-limit', 'upload'])
sstp['local_users'].append(user)
#
# RADIUS auth and settings
conf.set_level(base_path + ['authentication', 'radius'])
if conf.exists(['server']):
for server in conf.list_nodes(['server']):
radius = {
'server' : server,
'key' : '',
'fail_time' : 0,
'port' : '1812'
}
conf.set_level(base_path + ['authentication', 'radius', 'server', server])
if conf.exists(['fail-time']):
radius['fail-time'] = conf.return_value(['fail-time'])
if conf.exists(['port']):
radius['port'] = conf.return_value(['port'])
if conf.exists(['key']):
radius['key'] = conf.return_value(['key'])
if not conf.exists(['disable']):
sstp['radius_server'].append(radius)
#
# advanced radius-setting
conf.set_level(base_path + ['authentication', 'radius'])
if conf.exists(['acct-timeout']):
sstp['radius_acct_tmo'] = conf.return_value(['acct-timeout'])
if conf.exists(['max-try']):
sstp['radius_max_try'] = conf.return_value(['max-try'])
if conf.exists(['timeout']):
sstp['radius_timeout'] = conf.return_value(['timeout'])
if conf.exists(['nas-identifier']):
sstp['radius_nas_id'] = conf.return_value(['nas-identifier'])
if conf.exists(['nas-ip-address']):
sstp['radius_nas_ip'] = conf.return_value(['nas-ip-address'])
if conf.exists(['source-address']):
sstp['radius_source_address'] = conf.return_value(['source-address'])
# Dynamic Authorization Extensions (DOA)/Change Of Authentication (COA)
if conf.exists(['dynamic-author']):
dae = {
'port' : '',
'server' : '',
'key' : ''
}
if conf.exists(['dynamic-author', 'server']):
dae['server'] = conf.return_value(['dynamic-author', 'server'])
if conf.exists(['dynamic-author', 'port']):
dae['port'] = conf.return_value(['dynamic-author', 'port'])
if conf.exists(['dynamic-author', 'key']):
dae['key'] = conf.return_value(['dynamic-author', 'key'])
sstp['radius_dynamic_author'] = dae
if conf.exists(['rate-limit', 'enable']):
sstp['radius_shaper_attr'] = 'Filter-Id'
c_attr = ['rate-limit', 'enable', 'attribute']
if conf.exists(c_attr):
sstp['radius_shaper_attr'] = conf.return_value(c_attr)
c_vendor = ['rate-limit', 'enable', 'vendor']
if conf.exists(c_vendor):
sstp['radius_shaper_vendor'] = conf.return_value(c_vendor)
#
# authentication protocols
conf.set_level(base_path + ['authentication'])
if conf.exists(['protocols']):
auth_mods = {
'pap': 'auth_pap',
'chap': 'auth_chap_md5',
'mschap': 'auth_mschap_v1',
'mschap-v2': 'auth_mschap_v2'
}
for proto in conf.return_values(['protocols']):
sstp['auth_proto'].append(auth_mods[proto])
else:
sstp['auth_proto'] = ['auth_mschap_v2']
#
# read in SSL certs
conf.set_level(base_path + ['ssl'])
if conf.exists(['ca-cert-file']):
sstp['ssl_ca'] = conf.return_value(['ca-cert-file'])
if conf.exists(['cert-file']):
sstp['ssl_cert'] = conf.return_value(['cert-file'])
if conf.exists(['key-file']):
sstp['ssl_key'] = conf.return_value(['key-file'])
#
# read in client ip pool settings
conf.set_level(base_path + ['network-settings', 'client-ip-settings'])
if conf.exists(['subnet']):
sstp['client_ip_pool'] = conf.return_values(['subnet'])
if conf.exists(['gateway-address']):
sstp['client_gateway'] = conf.return_value(['gateway-address'])
#
# read in network settings
conf.set_level(base_path + ['network-settings'])
if conf.exists(['name-server']):
sstp['dnsv4'] = conf.return_values(['name-server'])
if conf.exists(['mtu']):
sstp['mtu'] = conf.return_value(['mtu'])
#
# read in PPP stuff
conf.set_level(base_path + ['ppp-settings'])
if conf.exists('mppe'):
sstp['ppp_mppe'] = conf.return_value('ppp-settings mppe')
if conf.exists(['lcp-echo-failure']):
sstp['ppp_echo_failure'] = conf.return_value(['lcp-echo-failure'])
if conf.exists(['lcp-echo-interval']):
sstp['ppp_echo_interval'] = conf.return_value(['lcp-echo-interval'])
if conf.exists(['lcp-echo-timeout']):
sstp['ppp_echo_timeout'] = conf.return_value(['lcp-echo-timeout'])
return sstp
def verify(sstp):
if sstp is None:
return None
# vertify auth settings
if sstp['auth_mode'] == 'local':
if not sstp['local_users']:
raise ConfigError('sstp-server authentication local-users required')
for user in sstp['local_users']:
if not user['password']:
raise ConfigError(f"Password required for user {user['name']}")
# if up/download is set, check that both have a value
if user['upload'] and not user['download']:
raise ConfigError(f"Download speed value required for user {user['name']}")
if user['download'] and not user['upload']:
raise ConfigError(f"Upload speed value required for user {user['name']}")
if not sstp['client_ip_pool']:
raise ConfigError("Client IP subnet required")
if not sstp['client_gateway']:
raise ConfigError("Client gateway IP address required")
if len(sstp['dnsv4']) > 2:
raise ConfigError("Only 2 DNS name-servers can be configured")
if not sstp['ssl_ca'] or not sstp['ssl_cert'] or not sstp['ssl_key']:
raise ConfigError('One or more SSL certificates missing')
if not os.path.exists(sstp['ssl_ca']):
raise ConfigError(f"CA cert file {sstp['ssl_ca']} does not exist")
if not os.path.exists(sstp['ssl_cert']):
raise ConfigError(f"SSL cert file {sstp['ssl_cert']} does not exist")
if not os.path.exists(sstp['ssl_key']):
raise ConfigError(f"SSL key file {sstp['ssl_key']} does not exist")
if sstp['auth_mode'] == 'radius':
if len(sstp['radius_server']) == 0:
raise ConfigError("RADIUS authentication requires at least one server")
for radius in sstp['radius_server']:
if not radius['key']:
raise ConfigError(f"Missing RADIUS secret for server {{ radius['key'] }}")
def generate(sstp):
if sstp is None:
return None
# accel-cmd reload doesn't work so any change results in a restart of the daemon
tmpl = jinja2.Template(sstp_config, trim_blocks=True)
config_text = tmpl.render(sstp)
with open(sstp_conf, 'w') as f:
f.write(config_text)
if sstp['local_users']:
tmpl = jinja2.Template(chap_secrets_conf, trim_blocks=True)
config_text = tmpl.render(sstp)
with open(chap_secrets, 'w') as f:
f.write(config_text)
os.chmod(chap_secrets, S_IRUSR | S_IWUSR | S_IRGRP)
else:
if os.path.exists(chap_secrets):
os.unlink(chap_secrets)
return sstp
def apply(sstp):
pid = 0
if os.path.isfile(pidfile):
pid = 0
with open(pidfile, 'r') as f:
pid = int(f.read())
if sstp is None:
if pid_exists(pid):
- cmd = 'start-stop-daemon --stop --quiet'
+ cmd = 'start-stop-daemon'
+ cmd += ' --stop '
+ cmd += ' --quiet'
+ cmd += ' --oknodo'
cmd += ' --pidfile ' + pidfile
subprocess_cmd(cmd)
if os.path.exists(pidfile):
os.remove(pidfile)
return None
if not pid_exists(pid):
if os.path.exists(pidfile):
os.remove(pidfile)
- cmd = 'start-stop-daemon --start --quiet'
+ cmd = 'start-stop-daemon'
+ cmd += ' --start '
+ cmd += ' --quiet'
+ cmd += ' --oknodo'
cmd += ' --pidfile ' + pidfile
cmd += ' --exec /usr/sbin/accel-pppd'
# now pass arguments to accel-pppd binary
cmd += ' --'
cmd += ' -c ' + sstp_conf
cmd += ' -p ' + pidfile
cmd += ' -d'
subprocess_cmd(cmd)
chk_con()
else:
accel_cmd('restart')
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/etc/init.d/isc-dhcpv4-server b/src/etc/init.d/isc-dhcpv4-server
index 377634a13..94a1020ac 100755
--- a/src/etc/init.d/isc-dhcpv4-server
+++ b/src/etc/init.d/isc-dhcpv4-server
@@ -1,113 +1,113 @@
#!/bin/sh
#
#
### BEGIN INIT INFO
# Provides: isc-dhcpv4-server
# Required-Start: $remote_fs $network $syslog
# Required-Stop: $remote_fs $network $syslog
# Should-Start: $local_fs slapd $named
# Should-Stop: $local_fs slapd
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: IPv4 DHCP server
# Description: Dynamic Host Configuration Protocol Server for IPv4
### END INIT INFO
PATH=/sbin:/bin:/usr/sbin:/usr/bin
test -f /usr/sbin/dhcpd || exit 0
DHCPD_DEFAULT="${DHCPD_DEFAULT:-/etc/default/isc-dhcpv4-server}"
# It is not safe to start if we don't have a default configuration...
if [ ! -f "$DHCPD_DEFAULT" ]; then
echo "$DHCPD_DEFAULT does not exist! - Aborting..."
exit 0
fi
. /lib/lsb/init-functions
# Read init script configuration
[ -f "$DHCPD_DEFAULT" ] && . "$DHCPD_DEFAULT"
NAME=dhcpd
DESC="ISC DHCP server"
# fallback to default config file
DHCPD_CONF=${DHCPD_CONF:-/etc/dhcp/dhcpd.conf}
# try to read pid file name from config file, with fallback to /var/run/dhcpd.pid
if [ -z "$DHCPD_PID" ]; then
DHCPD_PID=$(sed -n -e 's/^[ \t]*pid-file-name[ \t]*"(.*)"[ \t]*;.*$/\1/p' < "$DHCPD_CONF" 2>/dev/null | head -n 1)
fi
DHCPD_PID="${DHCPD_PID:-/var/run/dhcpd.pid}"
test_config()
{
if ! /usr/sbin/dhcpd -t $OPTIONS -q -cf "$DHCPD_CONF" > /dev/null 2>&1; then
echo "dhcpd self-test failed. Please fix $DHCPD_CONF."
echo "The error was: "
/usr/sbin/dhcpd -t $OPTIONS -cf "$DHCPD_CONF"
exit 1
fi
touch /var/lib/dhcp/dhcpd.leases
}
# single arg is -v for messages, -q for none
check_status()
{
if [ ! -r "$DHCPD_PID" ]; then
test "$1" != -v || echo "$NAME is not running."
return 3
fi
if read pid < "$DHCPD_PID" && ps -p "$pid" > /dev/null 2>&1; then
test "$1" != -v || echo "$NAME is running."
return 0
else
test "$1" != -v || echo "$NAME is not running but $DHCPD_PID exists."
return 1
fi
}
case "$1" in
start)
test_config
log_daemon_msg "Starting $DESC" "$NAME"
- start-stop-daemon --start --quiet --pidfile "$DHCPD_PID" \
+ start-stop-daemon --start --oknodo --quiet --pidfile "$DHCPD_PID" \
--exec /usr/sbin/dhcpd -- \
-q $OPTIONS -cf "$DHCPD_CONF" -pf "$DHCPD_PID" $INTERFACES
sleep 2
if check_status -q; then
log_end_msg 0
else
log_failure_msg "check syslog for diagnostics."
log_end_msg 1
exit 1
fi
;;
stop)
log_daemon_msg "Stopping $DESC" "$NAME"
- start-stop-daemon --stop --quiet --pidfile "$DHCPD_PID"
+ start-stop-daemon --stop --oknodo --quiet --pidfile "$DHCPD_PID"
log_end_msg $?
rm -f "$DHCPD_PID"
;;
restart | force-reload)
test_config
$0 stop
sleep 2
$0 start
if [ "$?" != "0" ]; then
exit 1
fi
;;
status)
echo -n "Status of $DESC: "
check_status -v
exit "$?"
;;
*)
echo "Usage: $0 {start|stop|restart|force-reload|status}"
exit 1
esac
exit 0
diff --git a/src/etc/init.d/isc-dhcpv6-relay b/src/etc/init.d/isc-dhcpv6-relay
index 5a8ce620c..e553eafd1 100755
--- a/src/etc/init.d/isc-dhcpv6-relay
+++ b/src/etc/init.d/isc-dhcpv6-relay
@@ -1,50 +1,50 @@
#!/bin/sh
#
#
### BEGIN INIT INFO
# Provides: isc-dhcpv6-relay
# Required-Start: $remote_fs $network
# Required-Stop: $remote_fs $network
# Should-Start: $local_fs
# Should-Stop: $local_fs
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: IPv6 DHCP relay
# Description: Dynamic Host Configuration Protocol Relay for IPv6
### END INIT INFO
# It is not safe to start if we don't have a default configuration...
if [ ! -f /etc/default/isc-dhcpv6-relay ]; then
echo "/etc/default/isc-dhcpv6-relay does not exist! - Aborting..."
exit 1
fi
# Source init functions
. /lib/lsb/init-functions
# Read init script configuration (interfaces the daemon should listen on
# and the DHCP server we should forward requests to.)
[ -f /etc/default/isc-dhcpv6-relay ] && . /etc/default/isc-dhcpv6-relay
DHCRELAYPID=/var/run/dhcv6relay.pid
case "$1" in
start)
- start-stop-daemon --start --quiet --pidfile $DHCRELAYPID \
+ start-stop-daemon --start --oknodo --quiet --pidfile $DHCRELAYPID \
--exec /usr/sbin/dhcrelay -- -q $OPTIONS -pf $DHCRELAYPID
;;
stop)
- start-stop-daemon --stop --quiet --pidfile $DHCRELAYPID
+ start-stop-daemon --stop --oknodo --quiet --pidfile $DHCRELAYPID
;;
restart | force-reload)
$0 stop
sleep 2
$0 start
;;
*)
echo "Usage: /etc/init.d/isc-dhcpv6-relay {start|stop|restart|force-reload}"
exit 1
esac
exit 0
diff --git a/src/etc/init.d/isc-dhcpv6-server b/src/etc/init.d/isc-dhcpv6-server
index 55f59b68e..f6b27cb4a 100755
--- a/src/etc/init.d/isc-dhcpv6-server
+++ b/src/etc/init.d/isc-dhcpv6-server
@@ -1,113 +1,113 @@
#!/bin/sh
#
#
### BEGIN INIT INFO
# Provides: isc-dhcpv6-server
# Required-Start: $remote_fs $network $syslog
# Required-Stop: $remote_fs $network $syslog
# Should-Start: $local_fs slapd $named
# Should-Stop: $local_fs slapd
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: IPv6 DHCP server
# Description: Dynamic Host Configuration Protocol Server for IPv6
### END INIT INFO
PATH=/sbin:/bin:/usr/sbin:/usr/bin
test -f /usr/sbin/dhcpd || exit 0
DHCPD_DEFAULT="${DHCPD_DEFAULT:-/etc/default/isc-dhcpv6-server}"
# It is not safe to start if we don't have a default configuration...
if [ ! -f "$DHCPD_DEFAULT" ]; then
echo "$DHCPD_DEFAULT does not exist! - Aborting..."
exit 0
fi
. /lib/lsb/init-functions
# Read init script configuration
[ -f "$DHCPD_DEFAULT" ] && . "$DHCPD_DEFAULT"
NAME=dhcpdv6
DESC="ISC DHCP server IPv6"
# fallback to default config file
DHCPD_CONF=${DHCPD_CONF:-/etc/dhcp/dhcpdv6.conf}
# try to read pid file name from config file, with fallback to /var/run/dhcpdv6.pid
if [ -z "$DHCPD_PID" ]; then
DHCPD_PID=$(sed -n -e 's/^[ \t]*pid-file-name[ \t]*"(.*)"[ \t]*;.*$/\1/p' < "$DHCPD_CONF" 2>/dev/null | head -n 1)
fi
DHCPD_PID="${DHCPD_PID:-/var/run/dhcpdv6.pid}"
test_config()
{
if ! /usr/sbin/dhcpd -t $OPTIONS -q -cf "$DHCPD_CONF" > /dev/null 2>&1; then
echo "dhcpd self-test failed. Please fix $DHCPD_CONF."
echo "The error was: "
/usr/sbin/dhcpd -t $OPTIONS -cf "$DHCPD_CONF"
exit 1
fi
touch /var/lib/dhcp/dhcpdv6.leases
}
# single arg is -v for messages, -q for none
check_status()
{
if [ ! -r "$DHCPD_PID" ]; then
test "$1" != -v || echo "$NAME is not running."
return 3
fi
if read pid < "$DHCPD_PID" && ps -p "$pid" > /dev/null 2>&1; then
test "$1" != -v || echo "$NAME is running."
return 0
else
test "$1" != -v || echo "$NAME is not running but $DHCPD_PID exists."
return 1
fi
}
case "$1" in
start)
test_config
log_daemon_msg "Starting $DESC" "$NAME"
- start-stop-daemon --start --quiet --pidfile "$DHCPD_PID" \
+ start-stop-daemon --start --oknodo --quiet --pidfile "$DHCPD_PID" \
--exec /usr/sbin/dhcpd -- \
-q $OPTIONS -cf "$DHCPD_CONF" -pf "$DHCPD_PID" $INTERFACES
sleep 2
if check_status -q; then
log_end_msg 0
else
log_failure_msg "check syslog for diagnostics."
log_end_msg 1
exit 1
fi
;;
stop)
log_daemon_msg "Stopping $DESC" "$NAME"
- start-stop-daemon --stop --quiet --pidfile "$DHCPD_PID"
+ start-stop-daemon --stop --oknodo --quiet --pidfile "$DHCPD_PID"
log_end_msg $?
rm -f "$DHCPD_PID"
;;
restart | force-reload)
test_config
$0 stop
sleep 2
$0 start
if [ "$?" != "0" ]; then
exit 1
fi
;;
status)
echo -n "Status of $DESC: "
check_status -v
exit "$?"
;;
*)
echo "Usage: $0 {start|stop|restart|force-reload|status}"
exit 1
esac
exit 0
diff --git a/src/op_mode/reset_openvpn.py b/src/op_mode/reset_openvpn.py
index 38eca53cc..176cd51cf 100755
--- a/src/op_mode/reset_openvpn.py
+++ b/src/op_mode/reset_openvpn.py
@@ -1,73 +1,79 @@
#!/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
from psutil import pid_exists
from subprocess import Popen, PIPE
from time import sleep
from netifaces import interfaces
def get_config_name(intf):
cfg_file = r'/opt/vyatta/etc/openvpn/openvpn-{}.conf'.format(intf)
return cfg_file
def get_pid_file(intf):
pid_file = r'/var/run/openvpn/{}.pid'.format(intf)
return pid_file
def subprocess_cmd(command):
p = Popen(command, stdout=PIPE, shell=True)
p.communicate()
if __name__ == '__main__':
if (len(sys.argv) < 1):
print("Must specify OpenVPN interface name!")
sys.exit(1)
interface = sys.argv[1]
if os.path.isfile(get_config_name(interface)):
pidfile = '/var/run/openvpn/{}.pid'.format(interface)
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 = 'start-stop-daemon'
+ cmd += ' --stop'
+ cmd += ' --oknodo'
+ cmd += ' --quiet'
cmd += ' --pidfile ' + pidfile
subprocess_cmd(cmd)
# When stopping OpenVPN 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 interface in interfaces():
sleep(0.250) # 250ms
# re-start OpenVPN process
- cmd = 'start-stop-daemon --start --quiet'
+ cmd = 'start-stop-daemon'
+ cmd += ' --start'
+ cmd += ' --oknodo'
+ cmd += ' --quiet'
cmd += ' --pidfile ' + get_pid_file(interface)
cmd += ' --exec /usr/sbin/openvpn'
# now pass arguments to openvpn binary
cmd += ' --'
cmd += ' --daemon openvpn-' + interface
cmd += ' --config ' + get_config_name(interface)
subprocess_cmd(cmd)
else:
print("OpenVPN interface {} does not exist!".format(interface))
sys.exit(1)
File Metadata
Details
Attached
Mime Type
text/x-diff
Expires
Fri, Nov 6, 9:15 AM (13 h, 59 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
4617889
Default Alt Text
(154 KB)
Attached To
Mode
rVYOSONEX vyos-1x
Attached
Detach File
Event Timeline
Log In to Comment