Page MenuHomeVyOS Platform

No OneTemporary

Size
65 KB
Referenced Files
None
Subscribers
None
diff --git a/interface-definitions/include/accel-radius-additions-disable-accounting.xlm.in b/interface-definitions/include/accel-radius-additions-disable-accounting.xlm.in
new file mode 100644
index 000000000..026f67453
--- /dev/null
+++ b/interface-definitions/include/accel-radius-additions-disable-accounting.xlm.in
@@ -0,0 +1,7 @@
+<leafNode name="disable-accounting">
+ <properties>
+ <help>Disable accounting</help>
+ <valueless/>
+ </properties>
+</leafNode>
+
diff --git a/interface-definitions/include/accel-radius-additions.xml.i b/interface-definitions/include/accel-radius-additions.xml.i
index 598fb73f8..bf0f0ac94 100644
--- a/interface-definitions/include/accel-radius-additions.xml.i
+++ b/interface-definitions/include/accel-radius-additions.xml.i
@@ -1,152 +1,153 @@
<!-- included start from accel-radius-additions.xml.i -->
<node name="radius">
<children>
<leafNode name="acct-interim-jitter">
<properties>
<help>Maximum jitter value in seconds to be applied to accounting information interval</help>
<valueHelp>
<format>1-60</format>
<description>Maximum jitter value in seconds</description>
</valueHelp>
<constraint>
<validator name="numeric" argument="--range 1-60"/>
</constraint>
<constraintErrorMessage>Jitter value must be between 1 and 60 seconds</constraintErrorMessage>
</properties>
</leafNode>
<tagNode name="server">
<children>
<leafNode name="acct-port">
<properties>
<help>Accounting port</help>
<valueHelp>
<format>1-65535</format>
<description>Numeric IP port (default: 1813)</description>
</valueHelp>
<constraint>
<validator name="numeric" argument="--range 1-65535"/>
</constraint>
</properties>
<defaultValue>1813</defaultValue>
</leafNode>
+ #include <include/accel-radius-additions-disable-accounting.xlm.in>
<leafNode name="fail-time">
<properties>
<help>Mark server unavailable for &lt;n&gt; seconds on failure</help>
<valueHelp>
<format>0-600</format>
<description>Fail time penalty</description>
</valueHelp>
<constraint>
<validator name="numeric" argument="--range 0-600"/>
</constraint>
<constraintErrorMessage>Fail time must be between 0 and 600 seconds</constraintErrorMessage>
</properties>
<defaultValue>0</defaultValue>
</leafNode>
</children>
</tagNode>
<leafNode name="timeout">
<properties>
<help>Timeout in seconds to wait response from RADIUS server</help>
<valueHelp>
<format>1-60</format>
<description>Timeout in seconds</description>
</valueHelp>
<constraint>
<validator name="numeric" argument="--range 1-60"/>
</constraint>
<constraintErrorMessage>Timeout must be between 1 and 60 seconds</constraintErrorMessage>
</properties>
<defaultValue>3</defaultValue>
</leafNode>
<leafNode name="acct-timeout">
<properties>
<help>Timeout for Interim-Update packets, terminate session afterwards (default 3 seconds)</help>
<valueHelp>
<format>0-60</format>
<description>Timeout in seconds, 0 to keep active</description>
</valueHelp>
<constraint>
<validator name="numeric" argument="--range 0-60"/>
</constraint>
<constraintErrorMessage>Timeout must be between 0 and 60 seconds</constraintErrorMessage>
</properties>
<defaultValue>3</defaultValue>
</leafNode>
<leafNode name="max-try">
<properties>
<help>Number of tries to send Access-Request/Accounting-Request queries</help>
<valueHelp>
<format>1-20</format>
<description>Maximum tries</description>
</valueHelp>
<constraint>
<validator name="numeric" argument="--range 1-20"/>
</constraint>
<constraintErrorMessage>Maximum tries must be between 1 and 20</constraintErrorMessage>
</properties>
<defaultValue>3</defaultValue>
</leafNode>
<leafNode name="nas-identifier">
<properties>
<help>NAS-Identifier attribute sent to RADIUS</help>
</properties>
</leafNode>
<leafNode name="nas-ip-address">
<properties>
<help>NAS-IP-Address attribute sent to RADIUS</help>
<constraint>
<validator name="ipv4-address"/>
</constraint>
<valueHelp>
<format>ipv4</format>
<description>NAS-IP-Address attribute</description>
</valueHelp>
</properties>
</leafNode>
<leafNode name="preallocate-vif">
<properties>
<help>Enable attribute NAS-Port-Id in Access-Request</help>
<valueless/>
</properties>
</leafNode>
<node name="dynamic-author">
<properties>
<help>Dynamic Authorization Extension/Change of Authorization server</help>
</properties>
<children>
<leafNode name="server">
<properties>
<help>IP address for Dynamic Authorization Extension server (DM/CoA)</help>
<constraint>
<validator name="ipv4-address"/>
</constraint>
<valueHelp>
<format>ipv4</format>
<description>IPv4 address for aynamic authorization server</description>
</valueHelp>
</properties>
</leafNode>
<leafNode name="port">
<properties>
<help>Port for Dynamic Authorization Extension server (DM/CoA) (default: 1700)</help>
<valueHelp>
<format>number</format>
<description>TCP port</description>
</valueHelp>
<constraint>
<validator name="numeric" argument="--range 1-65535"/>
</constraint>
</properties>
<defaultValue>1700</defaultValue>
</leafNode>
<leafNode name="key">
<properties>
<help>Shared secret for Dynamic Authorization Extension server</help>
</properties>
</leafNode>
</children>
</node>
</children>
</node>
<!-- included end -->
diff --git a/interface-definitions/vpn_l2tp.xml.in b/interface-definitions/vpn_l2tp.xml.in
index 8802c0564..82af86470 100644
--- a/interface-definitions/vpn_l2tp.xml.in
+++ b/interface-definitions/vpn_l2tp.xml.in
@@ -1,326 +1,327 @@
<?xml version="1.0"?>
<interfaceDefinition>
<node name="vpn">
<children>
<node name="l2tp" owner="${vyos_conf_scripts_dir}/vpn_l2tp.py">
<properties>
<help>L2TP Virtual Private Network (VPN)</help>
</properties>
<children>
<node name="remote-access">
<properties>
<help>Remote access L2TP VPN</help>
</properties>
<children>
#include <include/accel-mtu-128-16384.xml.i>
<leafNode name="outside-address">
<properties>
<help>External IP address to which VPN clients will connect</help>
<constraint>
<validator name="ipv4-address"/>
</constraint>
</properties>
</leafNode>
#include <include/accel-gateway-address.xml.i>
#include <include/accel-name-server.xml.i>
<node name="lns">
<properties>
<help>L2TP Network Server (LNS)</help>
</properties>
<children>
<leafNode name="shared-secret">
<properties>
<help>Tunnel password used to authenticate the client (LAC)</help>
</properties>
</leafNode>
</children>
</node>
<leafNode name="ccp-disable">
<properties>
<help>Disable Compression Control Protocol (CCP)</help>
<valueless />
</properties>
</leafNode>
<node name="ipsec-settings">
<properties>
<help>Internet Protocol Security (IPsec) for remote access L2TP VPN</help>
</properties>
<children>
<node name="authentication">
<properties>
<help>IPsec authentication settings</help>
</properties>
<children>
<leafNode name="mode">
<properties>
<help>Authentication mode for IPsec</help>
<valueHelp>
<format>pre-shared-secret</format>
<description>Use pre-shared secret for IPsec authentication</description>
</valueHelp>
<valueHelp>
<format>x509</format>
<description>Use X.509 certificate for IPsec authentication</description>
</valueHelp>
<constraint>
<regex>(pre-shared-secret|x509)</regex>
</constraint>
<completionHelp>
<list>pre-shared-secret x509</list>
</completionHelp>
</properties>
</leafNode>
<leafNode name="pre-shared-secret">
<properties>
<help>Pre-shared secret for IPsec</help>
</properties>
</leafNode>
<node name="x509">
<properties>
<help>X.509 certificate</help>
</properties>
<children>
<leafNode name="ca-cert-file">
<properties>
<help>File containing the X.509 certificate for the Certificate Authority (CA)</help>
<valueHelp>
<format>&lt;text&gt;</format>
<description>File in /config/auth</description>
</valueHelp>
</properties>
</leafNode>
<leafNode name="crl-file">
<properties>
<help>File containing the X.509 Certificate Revocation List (CRL)</help>
<valueHelp>
<format>&lt;text&gt;</format>
<description>File in /config/auth</description>
</valueHelp>
</properties>
</leafNode>
<leafNode name="server-cert-file">
<properties>
<help>File containing the X.509 certificate for the remote access VPN server (this host)</help>
<valueHelp>
<format>&lt;text&gt;</format>
<description>File in /config/auth</description>
</valueHelp>
</properties>
</leafNode>
<leafNode name="server-key-file">
<properties>
<help>File containing the private key for the X.509 certificate for the remote access VPN server (this host)</help>
<valueHelp>
<format>&lt;text&gt;</format>
<description>File in /config/auth</description>
</valueHelp>
</properties>
</leafNode>
<leafNode name="server-key-password">
<properties>
<help>Password that protects the private key</help>
</properties>
</leafNode>
</children>
</node>
</children>
</node>
<leafNode name="ike-lifetime">
<properties>
<help>IKE lifetime</help>
<valueHelp>
<format>&lt;30-86400&gt;</format>
<description>IKE lifetime in seconds (default 3600)</description>
</valueHelp>
<constraint>
<validator name="numeric" argument="--range 30-86400"/>
</constraint>
</properties>
</leafNode>
<leafNode name="lifetime">
<properties>
<help>ESP lifetime</help>
<valueHelp>
<format>&lt;30-86400&gt;</format>
<description>IKE lifetime in seconds (default 3600)</description>
</valueHelp>
<constraint>
<validator name="numeric" argument="--range 30-86400"/>
</constraint>
</properties>
</leafNode>
</children>
</node>
#include <include/accel-wins-server.xml.i>
<node name="client-ip-pool">
<properties>
<help>Pool of client IP addresses (must be within a /24)</help>
</properties>
<children>
#include <include/accel-client-ip-pool-start-stop.xml.i>
#include <include/accel-client-ip-pool-subnet.xml.i>
</children>
</node>
#include <include/accel-client-ipv6-pool.xml.i>
<leafNode name="description">
<properties>
<help>Description for L2TP remote-access settings</help>
</properties>
</leafNode>
<leafNode name="dhcp-interface">
<properties>
<help>DHCP interface to listen on</help>
</properties>
</leafNode>
<leafNode name="idle">
<properties>
<help>PPP idle timeout</help>
<valueHelp>
<format>&lt;30-86400&gt;</format>
<description>PPP idle timeout in seconds (default 1800)</description>
</valueHelp>
<constraint>
<validator name="numeric" argument="--range 30-86400"/>
</constraint>
</properties>
</leafNode>
<node name="authentication">
<properties>
<help>Authentication for remote access L2TP VPN</help>
</properties>
<children>
<leafNode name="require">
<properties>
<help>Authentication protocol for remote access peer L2TP VPN</help>
<valueHelp>
<format>pap</format>
<description>Require the peer to authenticate itself using PAP [Password Authentication Protocol].</description>
</valueHelp>
<valueHelp>
<format>chap</format>
<description>Require the peer to authenticate itself using CHAP [Challenge Handshake Authentication Protocol].</description>
</valueHelp>
<valueHelp>
<format>mschap</format>
<description>Require the peer to authenticate itself using CHAP [Challenge Handshake Authentication Protocol].</description>
</valueHelp>
<valueHelp>
<format>mschap-v2</format>
<description>Require the peer to authenticate itself using MS-CHAPv2 [Microsoft Challenge Handshake Authentication Protocol, Version 2].</description>
</valueHelp>
<constraint>
<regex>(pap|chap|mschap|mschap-v2)</regex>
</constraint>
<completionHelp>
<list>pap chap mschap mschap-v2</list>
</completionHelp>
<multi />
</properties>
</leafNode>
#include <include/accel-ppp-mppe.xml.i>
#include <include/accel-auth-mode.xml.i>
#include <include/accel-auth-local-users.xml.i>
#include <include/radius-server.xml.i>
<node name="radius">
<children>
<tagNode name="server">
<children>
+ #include <include/accel-radius-additions-disable-accounting.xlm.in>
<leafNode name="fail-time">
<properties>
<help>Mark server unavailable for &lt;n&gt; seconds on failure</help>
<valueHelp>
<format>0-600</format>
<description>Fail time penalty</description>
</valueHelp>
<constraint>
<validator name="numeric" argument="--range 0-600"/>
</constraint>
<constraintErrorMessage>Fail time must be between 0 and 600 seconds</constraintErrorMessage>
</properties>
</leafNode>
</children>
</tagNode>
<leafNode name="timeout">
<properties>
<help>Timeout to wait response from server (seconds)</help>
</properties>
</leafNode>
<leafNode name="acct-timeout">
<properties>
<help>Timeout to wait reply for Interim-Update packets. (default 3 seconds)</help>
</properties>
</leafNode>
<leafNode name="max-try">
<properties>
<help>Maximum number of tries to send Access-Request/Accounting-Request queries</help>
</properties>
</leafNode>
<leafNode name="nas-identifier">
<properties>
<help>Value to send to RADIUS server in NAS-Identifier attribute and to be matched in DM/CoA requests.</help>
</properties>
</leafNode>
<node name="dae-server">
<properties>
<help>IPv4 address and port to bind Dynamic Authorization Extension server (DM/CoA)</help>
</properties>
<children>
<leafNode name="ip-address">
<properties>
<help>IP address for Dynamic Authorization Extension server (DM/CoA)</help>
</properties>
</leafNode>
<leafNode name="port">
<properties>
<help>Port for Dynamic Authorization Extension server (DM/CoA)</help>
</properties>
</leafNode>
<leafNode name="secret">
<properties>
<help>Secret for Dynamic Authorization Extension server (DM/CoA)</help>
</properties>
</leafNode>
</children>
</node>
<node name="rate-limit">
<properties>
<help>Upload/Download speed limits</help>
</properties>
<children>
<leafNode name="attribute">
<properties>
<help>Specifies which radius attribute contains rate information. (default is Filter-Id)</help>
</properties>
</leafNode>
<leafNode name="vendor">
<properties>
<help>Specifies the vendor dictionary. (dictionary needs to be in /usr/share/accel-ppp/radius)</help>
</properties>
</leafNode>
<leafNode name="enable">
<properties>
<help>Enables Bandwidth shaping via RADIUS</help>
<valueless />
</properties>
</leafNode>
</children>
</node>
</children>
</node>
</children>
</node>
<node name="ppp-options">
<properties>
<help>Advanced protocol options</help>
</properties>
<children>
#include <include/accel-lcp-echo-interval-failure.xml.i>
</children>
</node>
</children>
</node>
</children>
</node>
</children>
</node>
</interfaceDefinition>
diff --git a/python/vyos/configdict.py b/python/vyos/configdict.py
index 62df3334c..db17c33fc 100644
--- a/python/vyos/configdict.py
+++ b/python/vyos/configdict.py
@@ -1,466 +1,471 @@
# 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/>.
"""
A library for retrieving value dicts from VyOS configs in a declarative fashion.
"""
import os
from vyos.util import vyos_dict_search
from vyos.xml import defaults
from vyos import ConfigError
def retrieve_config(path_hash, base_path, config):
"""
Retrieves a VyOS config as a dict according to a declarative description
The description dict, passed in the first argument, must follow this format:
``field_name : <path, type, [inner_options_dict]>``.
Supported types are: ``str`` (for normal nodes),
``list`` (returns a list of strings, for multi nodes),
``bool`` (returns True if valueless node exists),
``dict`` (for tag nodes, returns a dict indexed by node names,
according to description in the third item of the tuple).
Args:
path_hash (dict): Declarative description of the config to retrieve
base_path (list): A base path to prepend to all option paths
config (vyos.config.Config): A VyOS config object
Returns:
dict: config dict
"""
config_hash = {}
for k in path_hash:
if type(path_hash[k]) != tuple:
raise ValueError("In field {0}: expected a tuple, got a value {1}".format(k, str(path_hash[k])))
if len(path_hash[k]) < 2:
raise ValueError("In field {0}: field description must be a tuple of at least two items, path (list) and type".format(k))
path = path_hash[k][0]
if type(path) != list:
raise ValueError("In field {0}: path must be a list, not a {1}".format(k, type(path)))
typ = path_hash[k][1]
if type(typ) != type:
raise ValueError("In field {0}: type must be a type, not a {1}".format(k, type(typ)))
path = base_path + path
path_str = " ".join(path)
if typ == str:
config_hash[k] = config.return_value(path_str)
elif typ == list:
config_hash[k] = config.return_values(path_str)
elif typ == bool:
config_hash[k] = config.exists(path_str)
elif typ == dict:
try:
inner_hash = path_hash[k][2]
except IndexError:
raise ValueError("The type of the \'{0}\' field is dict, but inner options hash is missing from the tuple".format(k))
config_hash[k] = {}
nodes = config.list_nodes(path_str)
for node in nodes:
config_hash[k][node] = retrieve_config(inner_hash, path + [node], config)
return config_hash
def dict_merge(source, destination):
""" Merge two dictionaries. Only keys which are not present in destination
will be copied from source, anything else will be kept untouched. Function
will return a new dict which has the merged key/value pairs. """
from copy import deepcopy
tmp = deepcopy(destination)
for key, value in source.items():
if key not in tmp:
tmp[key] = value
elif isinstance(source[key], dict):
tmp[key] = dict_merge(source[key], tmp[key])
return tmp
def list_diff(first, second):
""" Diff two dictionaries and return only unique items """
second = set(second)
return [item for item in first if item not in second]
def leaf_node_changed(conf, path):
"""
Check if a leaf node was altered. If it has been altered - values has been
changed, or it was added/removed, we will return a list containing the old
value(s). If nothing has been changed, None is returned
"""
from vyos.configdiff import get_config_diff
D = get_config_diff(conf, key_mangling=('-', '_'))
D.set_level(conf.get_level())
(new, old) = D.get_value_diff(path)
if new != old:
if isinstance(old, str):
return [old]
elif isinstance(old, list):
if isinstance(new, str):
new = [new]
elif isinstance(new, type(None)):
new = []
return list_diff(old, new)
return None
def node_changed(conf, path):
"""
Check if a leaf node was altered. If it has been altered - values has been
changed, or it was added/removed, we will return the old value. If nothing
has been changed, None is returned
"""
from vyos.configdiff import get_config_diff, Diff
D = get_config_diff(conf, key_mangling=('-', '_'))
D.set_level(conf.get_level())
# get_child_nodes() will return dict_keys(), mangle this into a list with PEP448
keys = D.get_child_nodes_diff(path, expand_nodes=Diff.DELETE)['delete'].keys()
return list(keys)
def get_removed_vlans(conf, dict):
"""
Common function to parse a dictionary retrieved via get_config_dict() and
determine any added/removed VLAN interfaces - be it 802.1q or Q-in-Q.
"""
from vyos.configdiff import get_config_diff, Diff
# Check vif, vif-s/vif-c VLAN interfaces for removal
D = get_config_diff(conf, key_mangling=('-', '_'))
D.set_level(conf.get_level())
# get_child_nodes() will return dict_keys(), mangle this into a list with PEP448
keys = D.get_child_nodes_diff(['vif'], expand_nodes=Diff.DELETE)['delete'].keys()
if keys:
dict.update({'vif_remove': [*keys]})
# get_child_nodes() will return dict_keys(), mangle this into a list with PEP448
keys = D.get_child_nodes_diff(['vif-s'], expand_nodes=Diff.DELETE)['delete'].keys()
if keys:
dict.update({'vif_s_remove': [*keys]})
for vif in dict.get('vif_s', {}).keys():
keys = D.get_child_nodes_diff(['vif-s', vif, 'vif-c'], expand_nodes=Diff.DELETE)['delete'].keys()
if keys:
dict.update({'vif_s': { vif : {'vif_c_remove': [*keys]}}})
return dict
def T2665_set_dhcpv6pd_defaults(config_dict):
""" Properly configure DHCPv6 default options in the dictionary. If there is
no DHCPv6 configured at all, it is safe to remove the entire configuration.
"""
# As this is the same for every interface type it is safe to assume this
# for ethernet
pd_defaults = defaults(['interfaces', 'ethernet', 'dhcpv6-options', 'pd'])
# Implant default dictionary for DHCPv6-PD instances
if vyos_dict_search('dhcpv6_options.pd.length', config_dict):
del config_dict['dhcpv6_options']['pd']['length']
for pd in (vyos_dict_search('dhcpv6_options.pd', config_dict) or []):
config_dict['dhcpv6_options']['pd'][pd] = dict_merge(pd_defaults,
config_dict['dhcpv6_options']['pd'][pd])
return config_dict
def is_member(conf, interface, intftype=None):
"""
Checks if passed interface is member of other interface of specified type.
intftype is optional, if not passed it will search all known types
(currently bridge and bonding)
Returns:
None -> Interface is not a member
interface name -> Interface is a member of this interface
False -> interface type cannot have members
"""
ret_val = None
intftypes = ['bonding', 'bridge']
if intftype not in intftypes + [None]:
raise ValueError((
f'unknown interface type "{intftype}" or it cannot '
f'have member interfaces'))
intftype = intftypes if intftype == None else [intftype]
# set config level to root
old_level = conf.get_level()
conf.set_level([])
for iftype in intftype:
base = ['interfaces', iftype]
for intf in conf.list_nodes(base):
member = base + [intf, 'member', 'interface', interface]
if conf.exists(member):
tmp = conf.get_config_dict(member, key_mangling=('-', '_'), get_first_key=True)
ret_val = {intf : tmp}
old_level = conf.set_level(old_level)
return ret_val
def is_source_interface(conf, interface, intftype=None):
"""
Checks if passed interface is configured as source-interface of other
interfaces of specified type. intftype is optional, if not passed it will
search all known types (currently pppoe, macsec, pseudo-ethernet, tunnel
and vxlan)
Returns:
None -> Interface is not a member
interface name -> Interface is a member of this interface
False -> interface type cannot have members
"""
ret_val = None
intftypes = ['macsec', 'pppoe', 'pseudo-ethernet', 'tunnel', 'vxlan']
if intftype not in intftypes + [None]:
raise ValueError(f'unknown interface type "{intftype}" or it can not '
'have a source-interface')
intftype = intftypes if intftype == None else [intftype]
# set config level to root
old_level = conf.get_level()
conf.set_level([])
for it in intftype:
base = ['interfaces', it]
for intf in conf.list_nodes(base):
lower_intf = base + [intf, 'source-interface']
if conf.exists(lower_intf) and interface in conf.return_values(lower_intf):
ret_val = intf
break
old_level = conf.set_level(old_level)
return ret_val
def get_interface_dict(config, base, ifname=''):
"""
Common utility function to retrieve and mangle the interfaces configuration
from the CLI input nodes. All interfaces have a common base where value
retrival is identical. This function must be used whenever possible when
working on the interfaces node!
Return a dictionary with the necessary interface config keys.
"""
if not ifname:
# determine tagNode instance
if 'VYOS_TAGNODE_VALUE' not in os.environ:
raise ConfigError('Interface (VYOS_TAGNODE_VALUE) not specified')
ifname = os.environ['VYOS_TAGNODE_VALUE']
# retrieve interface default values
default_values = defaults(base)
# We take care about VLAN (vif, vif-s, vif-c) default values later on when
# parsing vlans in default dict and merge the "proper" values in correctly,
# see T2665.
for vif in ['vif', 'vif_s']:
if vif in default_values: del default_values[vif]
# setup config level which is extracted in get_removed_vlans()
config.set_level(base + [ifname])
dict = config.get_config_dict([], key_mangling=('-', '_'), get_first_key=True)
# Check if interface has been removed. We must use exists() as get_config_dict()
# will always return {} - even when an empty interface node like
# +macsec macsec1 {
# +}
# exists.
if not config.exists([]):
dict.update({'deleted' : ''})
# Add interface instance name into dictionary
dict.update({'ifname': ifname})
# XXX: T2665: When there is no DHCPv6-PD configuration given, we can safely
# remove the default values from the dict.
if 'dhcpv6_options' not in dict:
if 'dhcpv6_options' in default_values:
del default_values['dhcpv6_options']
# We have gathered the dict representation of the CLI, but there are
# default options which we need to update into the dictionary
# retrived.
dict = dict_merge(default_values, dict)
# XXX: T2665: blend in proper DHCPv6-PD default values
dict = T2665_set_dhcpv6pd_defaults(dict)
# Check if we are a member of a bridge device
bridge = is_member(config, ifname, 'bridge')
if bridge: dict.update({'is_bridge_member' : bridge})
# Check if we are a member of a bond device
bond = is_member(config, ifname, 'bonding')
if bond: dict.update({'is_bond_member' : bond})
# Some interfaces come with a source_interface which must also not be part
# of any other bond or bridge interface as it is exclusivly assigned as the
# Kernels "lower" interface to this new "virtual/upper" interface.
if 'source_interface' in dict:
# Check if source interface is member of another bridge
tmp = is_member(config, dict['source_interface'], 'bridge')
if tmp: dict.update({'source_interface_is_bridge_member' : tmp})
# Check if source interface is member of another bridge
tmp = is_member(config, dict['source_interface'], 'bonding')
if tmp: dict.update({'source_interface_is_bond_member' : tmp})
mac = leaf_node_changed(config, ['mac'])
if mac: dict.update({'mac_old' : mac})
eui64 = leaf_node_changed(config, ['ipv6', 'address', 'eui64'])
if eui64:
tmp = vyos_dict_search('ipv6.address', dict)
if not tmp:
dict.update({'ipv6': {'address': {'eui64_old': eui64}}})
else:
dict['ipv6']['address'].update({'eui64_old': eui64})
# Implant default dictionary in vif/vif-s VLAN interfaces. Values are
# identical for all types of VLAN interfaces as they all include the same
# XML definitions which hold the defaults.
for vif, vif_config in dict.get('vif', {}).items():
default_vif_values = defaults(base + ['vif'])
# XXX: T2665: When there is no DHCPv6-PD configuration given, we can safely
# remove the default values from the dict.
if not 'dhcpv6_options' in vif_config:
del default_vif_values['dhcpv6_options']
dict['vif'][vif] = dict_merge(default_vif_values, vif_config)
# XXX: T2665: blend in proper DHCPv6-PD default values
dict['vif'][vif] = T2665_set_dhcpv6pd_defaults(dict['vif'][vif])
# Check if we are a member of a bridge device
bridge = is_member(config, f'{ifname}.{vif}', 'bridge')
if bridge: dict['vif'][vif].update({'is_bridge_member' : bridge})
for vif_s, vif_s_config in dict.get('vif_s', {}).items():
default_vif_s_values = defaults(base + ['vif-s'])
# XXX: T2665: we only wan't the vif-s defaults - do not care about vif-c
if 'vif_c' in default_vif_s_values: del default_vif_s_values['vif_c']
# XXX: T2665: When there is no DHCPv6-PD configuration given, we can safely
# remove the default values from the dict.
if not 'dhcpv6_options' in vif_s_config:
del default_vif_s_values['dhcpv6_options']
dict['vif_s'][vif_s] = dict_merge(default_vif_s_values, vif_s_config)
# XXX: T2665: blend in proper DHCPv6-PD default values
dict['vif_s'][vif_s] = T2665_set_dhcpv6pd_defaults(
dict['vif_s'][vif_s])
# Check if we are a member of a bridge device
bridge = is_member(config, f'{ifname}.{vif_s}', 'bridge')
if bridge: dict['vif_s'][vif_s].update({'is_bridge_member' : bridge})
for vif_c, vif_c_config in vif_s_config.get('vif_c', {}).items():
default_vif_c_values = defaults(base + ['vif-s', 'vif-c'])
# XXX: T2665: When there is no DHCPv6-PD configuration given, we can safely
# remove the default values from the dict.
if not 'dhcpv6_options' in vif_c_config:
del default_vif_c_values['dhcpv6_options']
dict['vif_s'][vif_s]['vif_c'][vif_c] = dict_merge(
default_vif_c_values, vif_c_config)
# XXX: T2665: blend in proper DHCPv6-PD default values
dict['vif_s'][vif_s]['vif_c'][vif_c] = T2665_set_dhcpv6pd_defaults(
dict['vif_s'][vif_s]['vif_c'][vif_c])
# Check if we are a member of a bridge device
bridge = is_member(config, f'{ifname}.{vif_s}.{vif_c}', 'bridge')
if bridge: dict['vif_s'][vif_s]['vif_c'][vif_c].update(
{'is_bridge_member' : bridge})
# Check vif, vif-s/vif-c VLAN interfaces for removal
dict = get_removed_vlans(config, dict)
return dict
def get_accel_dict(config, base, chap_secrets):
"""
Common utility function to retrieve and mangle the Accel-PPP configuration
from different CLI input nodes. All Accel-PPP services have a common base
where value retrival is identical. This function must be used whenever
possible when working with Accel-PPP services!
Return a dictionary with the necessary interface config keys.
"""
from vyos.util import get_half_cpus
from vyos.validate import is_ipv4
dict = config.get_config_dict(base, key_mangling=('-', '_'), get_first_key=True)
# We have gathered the dict representation of the CLI, but there are default
# options which we need to update into the dictionary retrived.
default_values = defaults(base)
# defaults include RADIUS server specifics per TAG node which need to be
# added to individual RADIUS servers instead - so we can simply delete them
if vyos_dict_search('authentication.radius.server', default_values):
del default_values['authentication']['radius']['server']
# defaults include static-ip address per TAG node which need to be added to
# individual local users instead - so we can simply delete them
if vyos_dict_search('authentication.local_users.username', default_values):
del default_values['authentication']['local_users']['username']
dict = dict_merge(default_values, dict)
# set CPUs cores to process requests
dict.update({'thread_count' : get_half_cpus()})
# we need to store the path to the secrets file
dict.update({'chap_secrets_file' : chap_secrets})
# We can only have two IPv4 and three IPv6 nameservers - also they are
# configured in a different way in the configuration, this is why we split
# the configuration
if 'name_server' in dict:
ns_v4 = []
ns_v6 = []
for ns in dict['name_server']:
if is_ipv4(ns): ns_v4.append(ns)
else: ns_v6.append(ns)
dict.update({'name_server_ipv4' : ns_v4, 'name_server_ipv6' : ns_v6})
del dict['name_server']
# Add individual RADIUS server default values
if vyos_dict_search('authentication.radius.server', dict):
default_values = defaults(base + ['authentication', 'radius', 'server'])
for server in vyos_dict_search('authentication.radius.server', dict):
dict['authentication']['radius']['server'][server] = dict_merge(
default_values, dict['authentication']['radius']['server'][server])
+ # Check option "disable-accounting" per server and replace default value from '1813' to '0'
+ # set vpn sstp authentication radius server x.x.x.x disable-accounting
+ if 'disable_accounting' in dict['authentication']['radius']['server'][server]:
+ dict['authentication']['radius']['server'][server]['acct_port'] = '0'
+
# Add individual local-user default values
if vyos_dict_search('authentication.local_users.username', dict):
default_values = defaults(base + ['authentication', 'local-users', 'username'])
for username in vyos_dict_search('authentication.local_users.username', dict):
dict['authentication']['local_users']['username'][username] = dict_merge(
default_values, dict['authentication']['local_users']['username'][username])
return dict
diff --git a/src/conf_mode/vpn_l2tp.py b/src/conf_mode/vpn_l2tp.py
index 48d887abe..465986d5b 100755
--- a/src/conf_mode/vpn_l2tp.py
+++ b/src/conf_mode/vpn_l2tp.py
@@ -1,389 +1,392 @@
#!/usr/bin/env python3
#
# Copyright (C) 2019-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 re
from copy import deepcopy
from stat import S_IRUSR, S_IWUSR, S_IRGRP
from sys import exit
from time import sleep
from ipaddress import ip_network
from vyos.config import Config
from vyos.util import call, get_half_cpus
from vyos.validate import is_ipv4
from vyos import ConfigError
from vyos.template import render
from vyos import airbag
airbag.enable()
l2tp_conf = '/run/accel-pppd/l2tp.conf'
l2tp_chap_secrets = '/run/accel-pppd/l2tp.chap-secrets'
default_config_data = {
'auth_mode': 'local',
'auth_ppp_mppe': 'prefer',
'auth_proto': ['auth_mschap_v2'],
'chap_secrets_file': l2tp_chap_secrets, # used in Jinja2 template
'client_ip_pool': None,
'client_ip_subnets': [],
'client_ipv6_pool': [],
'client_ipv6_delegate_prefix': [],
'dnsv4': [],
'dnsv6': [],
'gateway_address': '10.255.255.0',
'local_users' : [],
'mtu': '1436',
'outside_addr': '',
'ppp_mppe': 'prefer',
'ppp_echo_failure' : '3',
'ppp_echo_interval' : '30',
'ppp_echo_timeout': '0',
'radius_server': [],
'radius_acct_inter_jitter': '',
'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': '',
'wins': [],
'ip6_column': [],
'thread_cnt': get_half_cpus()
}
def get_config(config=None):
if config:
conf = config
else:
conf = Config()
base_path = ['vpn', 'l2tp', 'remote-access']
if not conf.exists(base_path):
return None
conf.set_level(base_path)
l2tp = deepcopy(default_config_data)
### general options ###
if conf.exists(['name-server']):
for name_server in conf.return_values(['name-server']):
if is_ipv4(name_server):
l2tp['dnsv4'].append(name_server)
else:
l2tp['dnsv6'].append(name_server)
if conf.exists(['wins-server']):
l2tp['wins'] = conf.return_values(['wins-server'])
if conf.exists('outside-address'):
l2tp['outside_addr'] = conf.return_value('outside-address')
if conf.exists(['authentication', 'mode']):
l2tp['auth_mode'] = conf.return_value(['authentication', 'mode'])
if conf.exists(['authentication', 'require']):
l2tp['auth_proto'] = []
auth_mods = {
'pap': 'auth_pap',
'chap': 'auth_chap_md5',
'mschap': 'auth_mschap_v1',
'mschap-v2': 'auth_mschap_v2'
}
for proto in conf.return_values(['authentication', 'require']):
l2tp['auth_proto'].append(auth_mods[proto])
if conf.exists(['authentication', 'mppe']):
l2tp['auth_ppp_mppe'] = conf.return_value(['authentication', 'mppe'])
#
# 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'])
l2tp['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',
'acct_port' : '1813'
}
conf.set_level(base_path + ['authentication', 'radius', 'server', server])
+ if conf.exists(['disable-accounting']):
+ radius['acct_port'] = '0'
+
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(['acct-port']):
radius['acct_port'] = conf.return_value(['acct-port'])
if conf.exists(['key']):
radius['key'] = conf.return_value(['key'])
if not conf.exists(['disable']):
l2tp['radius_server'].append(radius)
#
# advanced radius-setting
conf.set_level(base_path + ['authentication', 'radius'])
if conf.exists(['acct-interim-jitter']):
l2tp['radius_acct_inter_jitter'] = conf.return_value(['acct-interim-jitter'])
if conf.exists(['acct-timeout']):
l2tp['radius_acct_tmo'] = conf.return_value(['acct-timeout'])
if conf.exists(['max-try']):
l2tp['radius_max_try'] = conf.return_value(['max-try'])
if conf.exists(['timeout']):
l2tp['radius_timeout'] = conf.return_value(['timeout'])
if conf.exists(['nas-identifier']):
l2tp['radius_nas_id'] = conf.return_value(['nas-identifier'])
if conf.exists(['nas-ip-address']):
l2tp['radius_nas_ip'] = conf.return_value(['nas-ip-address'])
if conf.exists(['source-address']):
l2tp['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'])
l2tp['radius_dynamic_author'] = dae
if conf.exists(['rate-limit', 'enable']):
l2tp['radius_shaper_attr'] = 'Filter-Id'
c_attr = ['rate-limit', 'enable', 'attribute']
if conf.exists(c_attr):
l2tp['radius_shaper_attr'] = conf.return_value(c_attr)
c_vendor = ['rate-limit', 'enable', 'vendor']
if conf.exists(c_vendor):
l2tp['radius_shaper_vendor'] = conf.return_value(c_vendor)
conf.set_level(base_path)
if conf.exists(['client-ip-pool']):
if conf.exists(['client-ip-pool', 'start']) and conf.exists(['client-ip-pool', 'stop']):
start = conf.return_value(['client-ip-pool', 'start'])
stop = conf.return_value(['client-ip-pool', 'stop'])
l2tp['client_ip_pool'] = start + '-' + re.search('[0-9]+$', stop).group(0)
if conf.exists(['client-ip-pool', 'subnet']):
l2tp['client_ip_subnets'] = conf.return_values(['client-ip-pool', 'subnet'])
if conf.exists(['client-ipv6-pool', 'prefix']):
l2tp['ip6_column'].append('ip6')
for prefix in conf.list_nodes(['client-ipv6-pool', 'prefix']):
tmp = {
'prefix': prefix,
'mask': '64'
}
if conf.exists(['client-ipv6-pool', 'prefix', prefix, 'mask']):
tmp['mask'] = conf.return_value(['client-ipv6-pool', 'prefix', prefix, 'mask'])
l2tp['client_ipv6_pool'].append(tmp)
if conf.exists(['client-ipv6-pool', 'delegate']):
l2tp['ip6_column'].append('ip6-db')
for prefix in conf.list_nodes(['client-ipv6-pool', 'delegate']):
tmp = {
'prefix': prefix,
'mask': ''
}
if conf.exists(['client-ipv6-pool', 'delegate', prefix, 'delegation-prefix']):
tmp['mask'] = conf.return_value(['client-ipv6-pool', 'delegate', prefix, 'delegation-prefix'])
l2tp['client_ipv6_delegate_prefix'].append(tmp)
if conf.exists(['mtu']):
l2tp['mtu'] = conf.return_value(['mtu'])
# gateway address
if conf.exists(['gateway-address']):
l2tp['gateway_address'] = conf.return_value(['gateway-address'])
else:
# calculate gw-ip-address
if conf.exists(['client-ip-pool', 'start']):
# use start ip as gw-ip-address
l2tp['gateway_address'] = conf.return_value(['client-ip-pool', 'start'])
elif conf.exists(['client-ip-pool', 'subnet']):
# use first ip address from first defined pool
subnet = conf.return_values(['client-ip-pool', 'subnet'])[0]
subnet = ip_network(subnet)
l2tp['gateway_address'] = str(list(subnet.hosts())[0])
# LNS secret
if conf.exists(['lns', 'shared-secret']):
l2tp['lns_shared_secret'] = conf.return_value(['lns', 'shared-secret'])
if conf.exists(['ccp-disable']):
l2tp['ccp_disable'] = True
# PPP options
if conf.exists(['idle']):
l2tp['ppp_echo_timeout'] = conf.return_value(['idle'])
if conf.exists(['ppp-options', 'lcp-echo-failure']):
l2tp['ppp_echo_failure'] = conf.return_value(['ppp-options', 'lcp-echo-failure'])
if conf.exists(['ppp-options', 'lcp-echo-interval']):
l2tp['ppp_echo_interval'] = conf.return_value(['ppp-options', 'lcp-echo-interval'])
return l2tp
def verify(l2tp):
if not l2tp:
return None
if l2tp['auth_mode'] == 'local':
if not l2tp['local_users']:
raise ConfigError('L2TP local auth mode requires local users to be configured!')
for user in l2tp['local_users']:
if not user['password']:
raise ConfigError(f"Password required for user {user['name']}")
elif l2tp['auth_mode'] == 'radius':
if len(l2tp['radius_server']) == 0:
raise ConfigError("RADIUS authentication requires at least one server")
for radius in l2tp['radius_server']:
if not radius['key']:
raise ConfigError(f"Missing RADIUS secret for server { radius['key'] }")
# check for the existence of a client ip pool
if not (l2tp['client_ip_pool'] or l2tp['client_ip_subnets']):
raise ConfigError(
"set vpn l2tp remote-access client-ip-pool requires subnet or start/stop IP pool")
# check ipv6
if l2tp['client_ipv6_delegate_prefix'] and not l2tp['client_ipv6_pool']:
raise ConfigError('IPv6 prefix delegation requires client-ipv6-pool prefix')
for prefix in l2tp['client_ipv6_delegate_prefix']:
if not prefix['mask']:
raise ConfigError('Delegation-prefix required for individual delegated networks')
if len(l2tp['wins']) > 2:
raise ConfigError('Not more then two IPv4 WINS name-servers can be configured')
if len(l2tp['dnsv4']) > 2:
raise ConfigError('Not more then two IPv4 DNS name-servers can be configured')
if len(l2tp['dnsv6']) > 3:
raise ConfigError('Not more then three IPv6 DNS name-servers can be configured')
return None
def generate(l2tp):
if not l2tp:
return None
render(l2tp_conf, 'accel-ppp/l2tp.config.tmpl', l2tp, trim_blocks=True)
if l2tp['auth_mode'] == 'local':
render(l2tp_chap_secrets, 'accel-ppp/chap-secrets.tmpl', l2tp)
os.chmod(l2tp_chap_secrets, S_IRUSR | S_IWUSR | S_IRGRP)
else:
if os.path.exists(l2tp_chap_secrets):
os.unlink(l2tp_chap_secrets)
return None
def apply(l2tp):
if not l2tp:
call('systemctl stop accel-ppp@l2tp.service')
for file in [l2tp_chap_secrets, l2tp_conf]:
if os.path.exists(file):
os.unlink(file)
return None
call('systemctl restart accel-ppp@l2tp.service')
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_pptp.py b/src/conf_mode/vpn_pptp.py
index 306d05c60..3125ee9d0 100755
--- a/src/conf_mode/vpn_pptp.py
+++ b/src/conf_mode/vpn_pptp.py
@@ -1,293 +1,296 @@
#!/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 re
from copy import deepcopy
from stat import S_IRUSR, S_IWUSR, S_IRGRP
from sys import exit
from vyos.config import Config
from vyos.template import render
from vyos.util import call, get_half_cpus
from vyos import ConfigError
from vyos import airbag
airbag.enable()
pptp_conf = '/run/accel-pppd/pptp.conf'
pptp_chap_secrets = '/run/accel-pppd/pptp.chap-secrets'
default_pptp = {
'auth_mode' : 'local',
'local_users' : [],
'radius_server' : [],
'radius_acct_inter_jitter': '',
'radius_acct_tmo' : '30',
'radius_max_try' : '3',
'radius_timeout' : '30',
'radius_nas_id' : '',
'radius_nas_ip' : '',
'radius_source_address' : '',
'radius_shaper_attr' : '',
'radius_shaper_vendor': '',
'radius_dynamic_author' : '',
'chap_secrets_file': pptp_chap_secrets, # used in Jinja2 template
'outside_addr': '',
'dnsv4': [],
'wins': [],
'client_ip_pool': '',
'mtu': '1436',
'auth_proto' : ['auth_mschap_v2'],
'ppp_mppe' : 'prefer',
'thread_cnt': get_half_cpus()
}
def get_config(config=None):
if config:
conf = config
else:
conf = Config()
base_path = ['vpn', 'pptp', 'remote-access']
if not conf.exists(base_path):
return None
pptp = deepcopy(default_pptp)
conf.set_level(base_path)
if conf.exists(['name-server']):
pptp['dnsv4'] = conf.return_values(['name-server'])
if conf.exists(['wins-server']):
pptp['wins'] = conf.return_values(['wins-server'])
if conf.exists(['outside-address']):
pptp['outside_addr'] = conf.return_value(['outside-address'])
if conf.exists(['authentication', 'mode']):
pptp['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' : '*',
}
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 not conf.exists(['disable']):
pptp['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',
'acct_port' : '1813'
}
conf.set_level(base_path + ['authentication', 'radius', 'server', server])
+ if conf.exists(['disable-accounting']):
+ radius['acct_port'] = '0'
+
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(['acct-port']):
radius['acct_port'] = conf.return_value(['acct-port'])
if conf.exists(['key']):
radius['key'] = conf.return_value(['key'])
if not conf.exists(['disable']):
pptp['radius_server'].append(radius)
#
# advanced radius-setting
conf.set_level(base_path + ['authentication', 'radius'])
if conf.exists(['acct-interim-jitter']):
pptp['radius_acct_inter_jitter'] = conf.return_value(['acct-interim-jitter'])
if conf.exists(['acct-timeout']):
pptp['radius_acct_tmo'] = conf.return_value(['acct-timeout'])
if conf.exists(['max-try']):
pptp['radius_max_try'] = conf.return_value(['max-try'])
if conf.exists(['timeout']):
pptp['radius_timeout'] = conf.return_value(['timeout'])
if conf.exists(['nas-identifier']):
pptp['radius_nas_id'] = conf.return_value(['nas-identifier'])
if conf.exists(['nas-ip-address']):
pptp['radius_nas_ip'] = conf.return_value(['nas-ip-address'])
if conf.exists(['source-address']):
pptp['radius_source_address'] = conf.return_value(['source-address'])
# Dynamic Authorization Extensions (DOA)/Change Of Authentication (COA)
if conf.exists(['dae-server']):
dae = {
'port' : '',
'server' : '',
'key' : ''
}
if conf.exists(['dynamic-author', 'ip-address']):
dae['server'] = conf.return_value(['dynamic-author', 'ip-address'])
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'])
pptp['radius_dynamic_author'] = dae
if conf.exists(['rate-limit', 'enable']):
pptp['radius_shaper_attr'] = 'Filter-Id'
c_attr = ['rate-limit', 'enable', 'attribute']
if conf.exists(c_attr):
pptp['radius_shaper_attr'] = conf.return_value(c_attr)
c_vendor = ['rate-limit', 'enable', 'vendor']
if conf.exists(c_vendor):
pptp['radius_shaper_vendor'] = conf.return_value(c_vendor)
conf.set_level(base_path)
if conf.exists(['client-ip-pool']):
if conf.exists(['client-ip-pool', 'start']) and conf.exists(['client-ip-pool', 'stop']):
start = conf.return_value(['client-ip-pool', 'start'])
stop = conf.return_value(['client-ip-pool', 'stop'])
pptp['client_ip_pool'] = start + '-' + re.search('[0-9]+$', stop).group(0)
if conf.exists(['mtu']):
pptp['mtu'] = conf.return_value(['mtu'])
# gateway address
if conf.exists(['gateway-address']):
pptp['gw_ip'] = conf.return_value(['gateway-address'])
else:
# calculate gw-ip-address
if conf.exists(['client-ip-pool', 'start']):
# use start ip as gw-ip-address
pptp['gateway_address'] = conf.return_value(['client-ip-pool', 'start'])
if conf.exists(['authentication', 'require']):
# clear default list content, now populate with actual CLI values
pptp['auth_proto'] = []
auth_mods = {
'pap': 'auth_pap',
'chap': 'auth_chap_md5',
'mschap': 'auth_mschap_v1',
'mschap-v2': 'auth_mschap_v2'
}
for proto in conf.return_values(['authentication', 'require']):
pptp['auth_proto'].append(auth_mods[proto])
if conf.exists(['authentication', 'mppe']):
pptp['ppp_mppe'] = conf.return_value(['authentication', 'mppe'])
return pptp
def verify(pptp):
if not pptp:
return None
if pptp['auth_mode'] == 'local':
if not pptp['local_users']:
raise ConfigError('PPTP local auth mode requires local users to be configured!')
for user in pptp['local_users']:
username = user['name']
if not user['password']:
raise ConfigError(f'Password required for local user "{username}"')
elif pptp['auth_mode'] == 'radius':
if len(pptp['radius_server']) == 0:
raise ConfigError('RADIUS authentication requires at least one server')
for radius in pptp['radius_server']:
if not radius['key']:
server = radius['server']
raise ConfigError(f'Missing RADIUS secret key for server "{ server }"')
if len(pptp['dnsv4']) > 2:
raise ConfigError('Not more then two IPv4 DNS name-servers can be configured')
if len(pptp['wins']) > 2:
raise ConfigError('Not more then two IPv4 WINS name-servers can be configured')
def generate(pptp):
if not pptp:
return None
render(pptp_conf, 'accel-ppp/pptp.config.tmpl', pptp, trim_blocks=True)
if pptp['local_users']:
render(pptp_chap_secrets, 'accel-ppp/chap-secrets.tmpl', pptp, trim_blocks=True)
os.chmod(pptp_chap_secrets, S_IRUSR | S_IWUSR | S_IRGRP)
else:
if os.path.exists(pptp_chap_secrets):
os.unlink(pptp_chap_secrets)
def apply(pptp):
if not pptp:
call('systemctl stop accel-ppp@pptp.service')
for file in [pptp_conf, pptp_chap_secrets]:
if os.path.exists(file):
os.unlink(file)
return None
call('systemctl restart accel-ppp@pptp.service')
if __name__ == '__main__':
try:
c = get_config()
verify(c)
generate(c)
apply(c)
except ConfigError as e:
print(e)
exit(1)

File Metadata

Mime Type
text/x-diff
Expires
Fri, Nov 6, 8:42 AM (1 d, 12 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
4641638
Default Alt Text
(65 KB)

Event Timeline