Page Menu
Home
VyOS Platform
Search
Configure Global Search
Log In
Files
F119903987
No One
Temporary
Actions
View File
Edit File
Delete File
View Transforms
Subscribe
Flag For Later
Award Token
Size
47 KB
Referenced Files
None
Subscribers
None
View Options
diff --git a/data/templates/ethernet/wpa_supplicant.conf.tmpl b/data/templates/ethernet/wpa_supplicant.conf.tmpl
index fe518ad45..308d777f1 100644
--- a/data/templates/ethernet/wpa_supplicant.conf.tmpl
+++ b/data/templates/ethernet/wpa_supplicant.conf.tmpl
@@ -1,72 +1,72 @@
### Autogenerated by interfaces-ethernet.py ###
# see full documentation:
# https://w1.fi/cgit/hostap/plain/wpa_supplicant/wpa_supplicant.conf
# For UNIX domain sockets (default on Linux and BSD): This is a directory that
# will be created for UNIX domain sockets for listening to requests from
# external programs (CLI/GUI, etc.) for status information and configuration.
# The socket file will be named based on the interface name, so multiple
# wpa_supplicant processes can be run at the same time if more than one
# interface is used.
# /var/run/wpa_supplicant is the recommended directory for sockets and by
# default, wpa_cli will use it when trying to connect with wpa_supplicant.
ctrl_interface=/run/wpa_supplicant
# IEEE 802.1X/EAPOL version
# wpa_supplicant is implemented based on IEEE Std 802.1X-2004 which defines
# EAPOL version 2. However, there are many APs that do not handle the new
# version number correctly (they seem to drop the frames completely). In order
# to make wpa_supplicant interoperate with these APs, the version number is set
# to 1 by default. This configuration value can be used to set it to the new
# version (2).
# Note: When using MACsec, eapol_version shall be set to 3, which is
# defined in IEEE Std 802.1X-2010.
eapol_version=2
# No need to scan for access points in EAPoL mode
ap_scan=0
# EAP fast re-authentication
fast_reauth=1
network={
{% if eapol is defined and eapol is not none %}
-{% if eapol.ca_cert_file is defined and eapol.ca_cert_file is not none %}
- ca_cert="{{ eapol.ca_cert_file }}"
+{% if eapol.ca_certificate is defined and eapol.ca_certificate is not none %}
+ ca_cert="/run/wpa_supplicant/{{ ifname }}_ca.pem"
{% endif %}
- client_cert="{{ eapol.cert_file }}"
- private_key="{{ eapol.key_file }}"
+ client_cert="/run/wpa_supplicant/{{ ifname }}_cert.pem"
+ private_key="/run/wpa_supplicant/{{ ifname }}_cert.key"
{% endif %}
# list of accepted authenticated key management protocols
key_mgmt=IEEE8021X
eap=TLS
{% if mac is defined and mac is not none %}
identity="{{ mac }}"
{% else %}
identity="{{ hw_id }}"
{% endif %}
# eapol_flags: IEEE 802.1X/EAPOL options (bit field)
# Dynamic WEP key required for non-WPA mode
# bit0 (1): require dynamically generated unicast WEP key
# bit1 (2): require dynamically generated broadcast WEP key
# (3) = require both keys; default)
# Note: When using wired authentication (including MACsec drivers),
# eapol_flags must be set to 0 for the authentication to be completed
# successfully.
eapol_flags=0
# For wired IEEE 802.1X authentication, "allow_canned_success=1" can be
# used to configure a mode that allows EAP-Success (and EAP-Failure) without
# going through authentication step. Some switches use such sequence when
# forcing the port to be authorized/unauthorized or as a fallback option if
# the authentication server is unreachable. By default, wpa_supplicant
# discards such frames to protect against potential attacks by rogue
# devices, but this option can be used to disable that protection for cases
# where the server/authenticator does not need to be authenticated.
phase1="allow_canned_success=1"
}
diff --git a/interface-definitions/include/interface/interface-eapol.xml.i b/interface-definitions/include/interface/interface-eapol.xml.i
index 92b7a3f35..270ec5b13 100644
--- a/interface-definitions/include/interface/interface-eapol.xml.i
+++ b/interface-definitions/include/interface/interface-eapol.xml.i
@@ -1,12 +1,11 @@
<!-- include start from interface/interface-eapol.xml.i -->
<node name="eapol">
<properties>
<help>Extensible Authentication Protocol over Local Area Network</help>
</properties>
<children>
- #include <include/certificate.xml.i>
- #include <include/certificate-ca.xml.i>
- #include <include/certificate-key.xml.i>
+ #include <include/pki/ca-certificate.xml.i>
+ #include <include/pki/certificate-key.xml.i>
</children>
</node>
<!-- include end -->
diff --git a/python/vyos/configverify.py b/python/vyos/configverify.py
index 979e28b11..58028b604 100644
--- a/python/vyos/configverify.py
+++ b/python/vyos/configverify.py
@@ -1,437 +1,466 @@
# Copyright 2020-2021 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/>.
# The sole purpose of this module is to hold common functions used in
# all kinds of implementations to verify the CLI configuration.
# It is started by migrating the interfaces to the new get_config_dict()
# approach which will lead to a lot of code that can be reused.
# NOTE: imports should be as local as possible to the function which
# makes use of it!
from vyos import ConfigError
from vyos.util import dict_search
def verify_mtu(config):
"""
Common helper function used by interface implementations to perform
recurring validation if the specified MTU can be used by the underlaying
hardware.
"""
from vyos.ifconfig import Interface
if 'mtu' in config:
mtu = int(config['mtu'])
tmp = Interface(config['ifname'])
min_mtu = tmp.get_min_mtu()
max_mtu = tmp.get_max_mtu()
if mtu < min_mtu:
raise ConfigError(f'Interface MTU too low, ' \
f'minimum supported MTU is {min_mtu}!')
if mtu > max_mtu:
raise ConfigError(f'Interface MTU too high, ' \
f'maximum supported MTU is {max_mtu}!')
def verify_mtu_parent(config, parent):
if 'mtu' not in config or 'mtu' not in parent:
return
mtu = int(config['mtu'])
parent_mtu = int(parent['mtu'])
if mtu > parent_mtu:
raise ConfigError(f'Interface MTU ({mtu}) too high, ' \
f'parent interface MTU is {parent_mtu}!')
def verify_mtu_ipv6(config):
"""
Common helper function used by interface implementations to perform
recurring validation if the specified MTU can be used when IPv6 is
configured on the interface. IPv6 requires a 1280 bytes MTU.
"""
from vyos.template import is_ipv6
if 'mtu' in config:
# IPv6 minimum required link mtu
min_mtu = 1280
if int(config['mtu']) < min_mtu:
interface = config['ifname']
error_msg = f'IPv6 address will be configured on interface "{interface}" ' \
f'thus the minimum MTU requirement is {min_mtu}!'
for address in (dict_search('address', config) or []):
if address in ['dhcpv6'] or is_ipv6(address):
raise ConfigError(error_msg)
tmp = dict_search('ipv6.address', config)
if tmp and 'no_default_link_local' not in tmp:
raise ConfigError('link-local ' + error_msg)
if tmp and 'autoconf' in tmp:
raise ConfigError(error_msg)
if tmp and 'eui64' in tmp:
raise ConfigError(error_msg)
def verify_vrf(config):
"""
Common helper function used by interface implementations to perform
recurring validation of VRF configuration.
"""
from netifaces import interfaces
if 'vrf' in config and config['vrf'] != 'default':
if config['vrf'] not in interfaces():
raise ConfigError('VRF "{vrf}" does not exist'.format(**config))
if 'is_bridge_member' in config:
raise ConfigError(
'Interface "{ifname}" cannot be both a member of VRF "{vrf}" '
'and bridge "{is_bridge_member}"!'.format(**config))
def verify_tunnel(config):
"""
This helper is used to verify the common part of the tunnel
"""
from vyos.template import is_ipv4
from vyos.template import is_ipv6
if 'encapsulation' not in config:
raise ConfigError('Must configure the tunnel encapsulation for '\
'{ifname}!'.format(**config))
if 'source_address' not in config and 'dhcp_interface' not in config:
raise ConfigError('source-address is mandatory for tunnel')
if 'remote' not in config and config['encapsulation'] != 'gre':
raise ConfigError('remote ip address is mandatory for tunnel')
if {'source_address', 'dhcp_interface'} <= set(config):
raise ConfigError('Can not use both source-address and dhcp-interface')
if config['encapsulation'] in ['ipip6', 'ip6ip6', 'ip6gre', 'ip6gretap', 'ip6erspan']:
error_ipv6 = 'Encapsulation mode requires IPv6'
if 'source_address' in config and not is_ipv6(config['source_address']):
raise ConfigError(f'{error_ipv6} source-address')
if 'remote' in config and not is_ipv6(config['remote']):
raise ConfigError(f'{error_ipv6} remote')
else:
error_ipv4 = 'Encapsulation mode requires IPv4'
if 'source_address' in config and not is_ipv4(config['source_address']):
raise ConfigError(f'{error_ipv4} source-address')
if 'remote' in config and not is_ipv4(config['remote']):
raise ConfigError(f'{error_ipv4} remote address')
if config['encapsulation'] in ['sit', 'gretap', 'ip6gretap']:
if 'source_interface' in config:
encapsulation = config['encapsulation']
raise ConfigError(f'Option source-interface can not be used with ' \
f'encapsulation "{encapsulation}"!')
elif config['encapsulation'] == 'gre':
if 'source_address' in config and is_ipv6(config['source_address']):
raise ConfigError('Can not use local IPv6 address is for mGRE tunnels')
def verify_eapol(config):
"""
Common helper function used by interface implementations to perform
recurring validation of EAPoL configuration.
"""
if 'eapol' in config:
- if not {'cert_file', 'key_file'} <= set(config['eapol']):
- raise ConfigError('Both cert and key-file must be specified '\
- 'when using EAPoL!')
+ if 'certificate' not in config['eapol']:
+ raise ConfigError('Certificate must be specified when using EAPoL!')
+
+ if 'certificate' not in config['pki']:
+ raise ConfigError('Invalid certificate specified for EAPoL')
+
+ cert_name = config['eapol']['certificate']
+
+ if cert_name not in config['pki']['certificate']:
+ raise ConfigError('Invalid certificate specified for EAPoL')
+
+ cert = config['pki']['certificate'][cert_name]
+
+ if 'certificate' not in cert or 'private' not in cert or 'key' not in cert['private']:
+ raise ConfigError('Invalid certificate/private key specified for EAPoL')
+
+ if 'password_protected' in cert['private']:
+ raise ConfigError('Encrypted private key cannot be used for EAPoL')
+
+ if 'ca_certificate' in config['eapol']:
+ if 'ca' not in config['pki']:
+ raise ConfigError('Invalid CA certificate specified for EAPoL')
+
+ ca_cert_name = config['eapol']['ca_certificate']
+
+ if ca_cert_name not in config['pki']['ca']:
+ raise ConfigError('Invalid CA certificate specified for EAPoL')
+
+ ca_cert = config['pki']['ca'][cert_name]
+
+ if 'certificate' not in ca_cert:
+ raise ConfigError('Invalid CA certificate specified for EAPoL')
def verify_mirror(config):
"""
Common helper function used by interface implementations to perform
recurring validation of mirror interface configuration.
It makes no sense to mirror traffic back at yourself!
"""
if 'mirror' in config:
for direction, mirror_interface in config['mirror'].items():
if mirror_interface == config['ifname']:
raise ConfigError(f'Can not mirror "{direction}" traffic back ' \
'the originating interface!')
def verify_authentication(config):
"""
Common helper function used by interface implementations to perform
recurring validation of authentication for either PPPoE or WWAN interfaces.
If authentication CLI option is defined, both username and password must
be set!
"""
if 'authentication' not in config:
return
if not {'user', 'password'} <= set(config['authentication']):
raise ConfigError('Authentication requires both username and ' \
'password to be set!')
def verify_address(config):
"""
Common helper function used by interface implementations to perform
recurring validation of IP address assignment when interface is part
of a bridge or bond.
"""
if {'is_bridge_member', 'address'} <= set(config):
raise ConfigError(
'Cannot assign address to interface "{ifname}" as it is a '
'member of bridge "{is_bridge_member}"!'.format(**config))
def verify_bridge_delete(config):
"""
Common helper function used by interface implementations to
perform recurring validation of IP address assignmenr
when interface also is part of a bridge.
"""
if 'is_bridge_member' in config:
raise ConfigError(
'Interface "{ifname}" cannot be deleted as it is a '
'member of bridge "{is_bridge_member}"!'.format(**config))
def verify_interface_exists(ifname):
"""
Common helper function used by interface implementations to perform
recurring validation if an interface actually exists.
"""
from netifaces import interfaces
if ifname not in interfaces():
raise ConfigError(f'Interface "{ifname}" does not exist!')
def verify_source_interface(config):
"""
Common helper function used by interface implementations to
perform recurring validation of the existence of a source-interface
required by e.g. peth/MACvlan, MACsec ...
"""
from netifaces import interfaces
if 'source_interface' not in config:
raise ConfigError('Physical source-interface required for '
'interface "{ifname}"'.format(**config))
if config['source_interface'] not in interfaces():
raise ConfigError('Specified source-interface {source_interface} does '
'not exist'.format(**config))
if 'source_interface_is_bridge_member' in config:
raise ConfigError('Invalid source-interface {source_interface}. Interface '
'is already a member of bridge '
'{source_interface_is_bridge_member}'.format(**config))
if 'source_interface_is_bond_member' in config:
raise ConfigError('Invalid source-interface {source_interface}. Interface '
'is already a member of bond '
'{source_interface_is_bond_member}'.format(**config))
def verify_dhcpv6(config):
"""
Common helper function used by interface implementations to perform
recurring validation of DHCPv6 options which are mutually exclusive.
"""
if 'dhcpv6_options' in config:
from vyos.util import dict_search
if {'parameters_only', 'temporary'} <= set(config['dhcpv6_options']):
raise ConfigError('DHCPv6 temporary and parameters-only options '
'are mutually exclusive!')
# It is not allowed to have duplicate SLA-IDs as those identify an
# assigned IPv6 subnet from a delegated prefix
for pd in dict_search('dhcpv6_options.pd', config):
sla_ids = []
interfaces = dict_search(f'dhcpv6_options.pd.{pd}.interface', config)
if not interfaces:
raise ConfigError('DHCPv6-PD requires an interface where to assign '
'the delegated prefix!')
for count, interface in enumerate(interfaces):
if 'sla_id' in interfaces[interface]:
sla_ids.append(interfaces[interface]['sla_id'])
else:
sla_ids.append(str(count))
# Check for duplicates
duplicates = [x for n, x in enumerate(sla_ids) if x in sla_ids[:n]]
if duplicates:
raise ConfigError('Site-Level Aggregation Identifier (SLA-ID) '
'must be unique per prefix-delegation!')
def verify_vlan_config(config):
"""
Common helper function used by interface implementations to perform
recurring validation of interface VLANs
"""
# VLAN and Q-in-Q IDs are not allowed to overlap
if 'vif' in config and 'vif_s' in config:
duplicate = list(set(config['vif']) & set(config['vif_s']))
if duplicate:
raise ConfigError(f'Duplicate VLAN id "{duplicate[0]}" used for vif and vif-s interfaces!')
# 802.1q VLANs
for vlan in config.get('vif', {}):
vlan = config['vif'][vlan]
verify_dhcpv6(vlan)
verify_address(vlan)
verify_vrf(vlan)
verify_mtu_parent(vlan, config)
# 802.1ad (Q-in-Q) VLANs
for s_vlan in config.get('vif_s', {}):
s_vlan = config['vif_s'][s_vlan]
verify_dhcpv6(s_vlan)
verify_address(s_vlan)
verify_vrf(s_vlan)
verify_mtu_parent(s_vlan, config)
for c_vlan in s_vlan.get('vif_c', {}):
c_vlan = s_vlan['vif_c'][c_vlan]
verify_dhcpv6(c_vlan)
verify_address(c_vlan)
verify_vrf(c_vlan)
verify_mtu_parent(c_vlan, config)
verify_mtu_parent(c_vlan, s_vlan)
def verify_accel_ppp_base_service(config):
"""
Common helper function which must be used by all Accel-PPP services based
on get_config_dict()
"""
# vertify auth settings
if dict_search('authentication.mode', config) == 'local':
if not dict_search('authentication.local_users', config):
raise ConfigError('PPPoE local auth mode requires local users to be configured!')
for user in dict_search('authentication.local_users.username', config):
user_config = config['authentication']['local_users']['username'][user]
if 'password' not in user_config:
raise ConfigError(f'Password required for local user "{user}"')
if 'rate_limit' in user_config:
# if up/download is set, check that both have a value
if not {'upload', 'download'} <= set(user_config['rate_limit']):
raise ConfigError(f'User "{user}" has rate-limit configured for only one ' \
'direction but both upload and download must be given!')
elif dict_search('authentication.mode', config) == 'radius':
if not dict_search('authentication.radius.server', config):
raise ConfigError('RADIUS authentication requires at least one server')
for server in dict_search('authentication.radius.server', config):
radius_config = config['authentication']['radius']['server'][server]
if 'key' not in radius_config:
raise ConfigError(f'Missing RADIUS secret key for server "{server}"')
if 'gateway_address' not in config:
raise ConfigError('PPPoE server requires gateway-address to be configured!')
if 'name_server_ipv4' in config:
if len(config['name_server_ipv4']) > 2:
raise ConfigError('Not more then two IPv4 DNS name-servers ' \
'can be configured')
if 'name_server_ipv6' in config:
if len(config['name_server_ipv6']) > 3:
raise ConfigError('Not more then three IPv6 DNS name-servers ' \
'can be configured')
if 'client_ipv6_pool' in config:
ipv6_pool = config['client_ipv6_pool']
if 'delegate' in ipv6_pool:
if 'prefix' not in ipv6_pool:
raise ConfigError('IPv6 "delegate" also requires "prefix" to be defined!')
for delegate in ipv6_pool['delegate']:
if 'delegation_prefix' not in ipv6_pool['delegate'][delegate]:
raise ConfigError('delegation-prefix length required!')
def verify_diffie_hellman_length(file, min_keysize):
""" Verify Diffie-Hellamn keypair length given via file. It must be greater
then or equal to min_keysize """
import os
import re
from vyos.util import cmd
try:
keysize = str(min_keysize)
except:
return False
if os.path.exists(file):
out = cmd(f'openssl dhparam -inform PEM -in {file} -text')
prog = re.compile('\d+\s+bit')
if prog.search(out):
bits = prog.search(out)[0].split()[0]
if int(bits) >= int(min_keysize):
return True
return False
def verify_common_route_maps(config):
"""
Common helper function used by routing protocol implementations to perform
recurring validation if the specified route-map for either zebra to kernel
installation exists (this is the top-level route_map key) or when a route
is redistributed with a route-map that it exists!
"""
# XXX: This function is called in combination with a previous call to:
# tmp = conf.get_config_dict(['policy']) - see protocols_ospf.py as example.
# We should NOT call this with the key_mangling option as this would rename
# route-map hypens '-' to underscores '_' and one could no longer distinguish
# what should have been the "proper" route-map name, as foo-bar and foo_bar
# are two entire different route-map instances!
for route_map in ['route-map', 'route_map']:
if route_map not in config:
continue
tmp = config[route_map]
# Check if the specified route-map exists, if not error out
if dict_search(f'policy.route-map.{tmp}', config) == None:
raise ConfigError(f'Specified route-map "{tmp}" does not exist!')
if 'redistribute' in config:
for protocol, protocol_config in config['redistribute'].items():
if 'route_map' in protocol_config:
verify_route_map(protocol_config['route_map'], config)
def verify_route_map(route_map_name, config):
"""
Common helper function used by routing protocol implementations to perform
recurring validation if a specified route-map exists!
"""
# Check if the specified route-map exists, if not error out
if dict_search(f'policy.route-map.{route_map_name}', config) == None:
raise ConfigError(f'Specified route-map "{route_map_name}" does not exist!')
def verify_prefix_list(prefix_list, config, version=''):
"""
Common helper function used by routing protocol implementations to perform
recurring validation if a specified prefix-list exists!
"""
# Check if the specified prefix-list exists, if not error out
if dict_search(f'policy.prefix-list{version}.{prefix_list}', config) == None:
raise ConfigError(f'Specified prefix-list{version} "{prefix_list}" does not exist!')
def verify_access_list(access_list, config, version=''):
"""
Common helper function used by routing protocol implementations to perform
recurring validation if a specified prefix-list exists!
"""
# Check if the specified ACL exists, if not error out
if dict_search(f'policy.access-list{version}.{access_list}', config) == None:
raise ConfigError(f'Specified access-list{version} "{access_list}" does not exist!')
diff --git a/smoketest/scripts/cli/test_interfaces_ethernet.py b/smoketest/scripts/cli/test_interfaces_ethernet.py
index a31d75423..a9cdab16a 100755
--- a/smoketest/scripts/cli/test_interfaces_ethernet.py
+++ b/smoketest/scripts/cli/test_interfaces_ethernet.py
@@ -1,206 +1,193 @@
#!/usr/bin/env python3
#
# Copyright (C) 2020-2021 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
import unittest
from base_interfaces_test import BasicInterfaceTest
from vyos.configsession import ConfigSessionError
from vyos.ifconfig import Section
from vyos.util import cmd
from vyos.util import process_named_running
from vyos.util import read_file
-ca_cert = '/config/auth/eapol_test_ca.pem'
-ssl_cert = '/config/auth/eapol_test_server.pem'
-ssl_key = '/config/auth/eapol_test_server.key'
+pki_path = ['pki']
+cert_data = 'MIICFDCCAbugAwIBAgIUfMbIsB/ozMXijYgUYG80T1ry+mcwCgYIKoZIzj0EAwIwWTELMAkGA1UEBhMCR0IxEzARBgNVBAgMClNvbWUtU3RhdGUxEjAQBgNVBAcMCVNvbWUtQ2l0eTENMAsGA1UECgwEVnlPUzESMBAGA1UEAwwJVnlPUyBUZXN0MB4XDTIxMDcyMDEyNDUxMloXDTI2MDcxOTEyNDUxMlowWTELMAkGA1UEBhMCR0IxEzARBgNVBAgMClNvbWUtU3RhdGUxEjAQBgNVBAcMCVNvbWUtQ2l0eTENMAsGA1UECgwEVnlPUzESMBAGA1UEAwwJVnlPUyBUZXN0MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE01HrLcNttqq4/PtoMua8rMWEkOdBu7vP94xzDO7A8C92ls1v86eePy4QllKCzIw3QxBIoCuH2peGRfWgPRdFsKNhMF8wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAYYwHQYDVR0lBBYwFAYIKwYBBQUHAwIGCCsGAQUFBwMBMB0GA1UdDgQWBBSu+JnU5ZC4mkuEpqg2+Mk4K79oeDAKBggqhkjOPQQDAgNHADBEAiBEFdzQ/Bc3LftzngrY605UhA6UprHhAogKgROv7iR4QgIgEFUxTtW3xXJcnUPWhhUFhyZoqfn8dE93+dm/LDnp7C0='
+key_data = 'MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgPLpD0Ohhoq0g4nhx2KMIuze7ucKUt/lBEB2wc03IxXyhRANCAATTUestw222qrj8+2gy5rysxYSQ50G7u8/3jHMM7sDwL3aWzW/zp54/LhCWUoLMjDdDEEigK4fal4ZF9aA9F0Ww'
def get_wpa_supplicant_value(interface, key):
tmp = read_file(f'/run/wpa_supplicant/{interface}.conf')
tmp = re.findall(r'\n?{}=(.*)'.format(key), tmp)
return tmp[0]
class EthernetInterfaceTest(BasicInterfaceTest.TestCase):
@classmethod
def setUpClass(cls):
cls._test_ip = True
cls._test_ipv6 = True
cls._test_ipv6_pd = True
cls._test_ipv6_dhcpc6 = True
cls._test_mtu = True
cls._test_vlan = True
cls._test_qinq = True
cls._base_path = ['interfaces', 'ethernet']
cls._mirror_interfaces = ['dum21354']
# we need to filter out VLAN interfaces identified by a dot (.)
# in their name - just in case!
if 'TEST_ETH' in os.environ:
tmp = os.environ['TEST_ETH'].split()
cls._interfaces = tmp
else:
for tmp in Section.interfaces('ethernet'):
if not '.' in tmp:
cls._interfaces.append(tmp)
cls._macs = {}
for interface in cls._interfaces:
cls._macs[interface] = read_file(f'/sys/class/net/{interface}/address')
# call base-classes classmethod
super(cls, cls).setUpClass()
def tearDown(self):
+ self.cli_delete(pki_path)
+
for interface in self._interfaces:
# when using a dedicated interface to test via TEST_ETH environment
# variable only this one will be cleared in the end - usable to test
# ethernet interfaces via SSH
self.cli_delete(self._base_path + [interface])
self.cli_set(self._base_path + [interface, 'duplex', 'auto'])
self.cli_set(self._base_path + [interface, 'speed', 'auto'])
self.cli_set(self._base_path + [interface, 'hw-id', self._macs[interface]])
# Tear down mirror interfaces for SPAN (Switch Port Analyzer)
for span in self._mirror_interfaces:
section = Section.section(span)
self.cli_delete(['interfaces', section, span])
self.cli_commit()
def test_dhcp_disable_interface(self):
# When interface is configured as admin down, it must be admin down
# even when dhcpc starts on the given interface
for interface in self._interfaces:
self.cli_set(self._base_path + [interface, 'disable'])
# Also enable DHCP (ISC DHCP always places interface in admin up
# state so we check that we do not start DHCP client.
# https://phabricator.vyos.net/T2767
self.cli_set(self._base_path + [interface, 'address', 'dhcp'])
self.cli_commit()
# Validate interface state
for interface in self._interfaces:
flags = read_file(f'/sys/class/net/{interface}/flags')
self.assertEqual(int(flags, 16) & 1, 0)
def test_offloading_rps(self):
# enable RPS on all available CPUs, RPS works woth a CPU bitmask,
# where each bit represents a CPU (core/thread). The formula below
# expands to rps_cpus = 255 for a 8 core system
rps_cpus = (1 << os.cpu_count()) -1
# XXX: we should probably reserve one core when the system is under
# high preasure so we can still have a core left for housekeeping.
# This is done by masking out the lowst bit so CPU0 is spared from
# receive packet steering.
rps_cpus &= ~1
for interface in self._interfaces:
self.cli_set(self._base_path + [interface, 'offload', 'rps'])
self.cli_commit()
for interface in self._interfaces:
cpus = read_file(f'/sys/class/net/{interface}/queues/rx-0/rps_cpus')
# remove the nasty ',' separation on larger strings
cpus = cpus.replace(',','')
cpus = int(cpus, 16)
self.assertEqual(f'{cpus:x}', f'{rps_cpus:x}')
def test_non_existing_interface(self):
unknonw_interface = self._base_path + ['eth667']
self.cli_set(unknonw_interface)
# check validate() - interface does not exist
with self.assertRaises(ConfigSessionError):
self.cli_commit()
# we need to remove this wrong interface from the configuration
# manually, else tearDown() will have problem in commit()
self.cli_delete(unknonw_interface)
def test_speed_duplex_verify(self):
for interface in self._interfaces:
self.cli_set(self._base_path + [interface, 'speed', '1000'])
# check validate() - if either speed or duplex is not auto, the
# other one must be manually configured, too
with self.assertRaises(ConfigSessionError):
self.cli_commit()
self.cli_set(self._base_path + [interface, 'speed', 'auto'])
self.cli_commit()
def test_eapol_support(self):
+ self.cli_set(pki_path + ['ca', 'eapol', 'certificate', cert_data])
+ self.cli_set(pki_path + ['certificate', 'eapol', 'certificate', cert_data])
+ self.cli_set(pki_path + ['certificate', 'eapol', 'private', 'key', key_data])
+
for interface in self._interfaces:
# Enable EAPoL
- self.cli_set(self._base_path + [interface, 'eapol', 'ca-cert-file', ca_cert])
- self.cli_set(self._base_path + [interface, 'eapol', 'cert-file', ssl_cert])
- self.cli_set(self._base_path + [interface, 'eapol', 'key-file', ssl_key])
+ self.cli_set(self._base_path + [interface, 'eapol', 'ca-certificate', 'eapol'])
+ self.cli_set(self._base_path + [interface, 'eapol', 'certificate', 'eapol'])
self.cli_commit()
# Check for running process
self.assertTrue(process_named_running('wpa_supplicant'))
# Validate interface config
for interface in self._interfaces:
tmp = get_wpa_supplicant_value(interface, 'key_mgmt')
self.assertEqual('IEEE8021X', tmp)
tmp = get_wpa_supplicant_value(interface, 'eap')
self.assertEqual('TLS', tmp)
tmp = get_wpa_supplicant_value(interface, 'eapol_flags')
self.assertEqual('0', tmp)
tmp = get_wpa_supplicant_value(interface, 'ca_cert')
- self.assertEqual(f'"{ca_cert}"', tmp)
+ self.assertEqual(f'"/run/wpa_supplicant/{interface}_ca.pem"', tmp)
tmp = get_wpa_supplicant_value(interface, 'client_cert')
- self.assertEqual(f'"{ssl_cert}"', tmp)
+ self.assertEqual(f'"/run/wpa_supplicant/{interface}_cert.pem"', tmp)
tmp = get_wpa_supplicant_value(interface, 'private_key')
- self.assertEqual(f'"{ssl_key}"', tmp)
+ self.assertEqual(f'"/run/wpa_supplicant/{interface}_cert.key"', tmp)
mac = read_file(f'/sys/class/net/{interface}/address')
tmp = get_wpa_supplicant_value(interface, 'identity')
self.assertEqual(f'"{mac}"', tmp)
if __name__ == '__main__':
- # Our SSL certificates need a subject ...
- subject = '/C=DE/ST=BY/O=VyOS/localityName=Cloud/commonName=vyos/' \
- 'organizationalUnitName=VyOS/emailAddress=maintainers@vyos.io/'
-
- if not (os.path.isfile(ssl_key) and os.path.isfile(ssl_cert)):
- # Generate mandatory SSL certificate
- tmp = f'openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 '\
- f'-keyout {ssl_key} -out {ssl_cert} -subj {subject}'
- cmd(tmp)
-
- if not os.path.isfile(ca_cert):
- # Generate "CA"
- tmp = f'openssl req -new -x509 -key {ssl_key} -out {ca_cert} -subj {subject}'
- cmd(tmp)
-
- for file in [ca_cert, ssl_cert, ssl_key]:
- cmd(f'sudo chown radius_priv_user:vyattacfg {file}')
-
unittest.main(verbosity=2)
diff --git a/src/conf_mode/interfaces-ethernet.py b/src/conf_mode/interfaces-ethernet.py
index 378f400b8..78c24952b 100755
--- a/src/conf_mode/interfaces-ethernet.py
+++ b/src/conf_mode/interfaces-ethernet.py
@@ -1,160 +1,191 @@
#!/usr/bin/env python3
#
# Copyright (C) 2019-2021 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 glob import glob
from sys import exit
from vyos.config import Config
from vyos.configdict import get_interface_dict
from vyos.configverify import verify_address
from vyos.configverify import verify_dhcpv6
from vyos.configverify import verify_eapol
from vyos.configverify import verify_interface_exists
from vyos.configverify import verify_mirror
from vyos.configverify import verify_mtu
from vyos.configverify import verify_mtu_ipv6
from vyos.configverify import verify_vlan_config
from vyos.configverify import verify_vrf
from vyos.ethtool import Ethtool
from vyos.ifconfig import EthernetIf
+from vyos.pki import wrap_certificate
+from vyos.pki import wrap_private_key
from vyos.template import render
from vyos.util import call
from vyos.util import dict_search
from vyos import ConfigError
from vyos import airbag
airbag.enable()
# XXX: wpa_supplicant works on the source interface
+cfg_dir = '/run/wpa_supplicant'
wpa_suppl_conf = '/run/wpa_supplicant/{ifname}.conf'
def get_config(config=None):
"""
Retrive CLI config as dictionary. Dictionary can never be empty, as at least the
interface name will be added or a deleted flag
"""
if config:
conf = config
else:
conf = Config()
base = ['interfaces', 'ethernet']
+
+ tmp_pki = conf.get_config_dict(['pki'], key_mangling=('-', '_'),
+ get_first_key=True, no_tag_node_value_mangle=True)
+
ethernet = get_interface_dict(conf, base)
+ if 'deleted' not in ethernet:
+ ethernet['pki'] = tmp_pki
+
return ethernet
def verify(ethernet):
if 'deleted' in ethernet:
return None
ifname = ethernet['ifname']
verify_interface_exists(ifname)
# No need to check speed and duplex keys as both have default values.
if ((ethernet['speed'] == 'auto' and ethernet['duplex'] != 'auto') or
(ethernet['speed'] != 'auto' and ethernet['duplex'] == 'auto')):
raise ConfigError('Speed/Duplex missmatch. Must be both auto or manually configured')
verify_mtu(ethernet)
verify_mtu_ipv6(ethernet)
verify_dhcpv6(ethernet)
verify_address(ethernet)
verify_vrf(ethernet)
verify_eapol(ethernet)
verify_mirror(ethernet)
# verify offloading capabilities
if dict_search('offload.rps', ethernet) != None:
if not os.path.exists(f'/sys/class/net/{ifname}/queues/rx-0/rps_cpus'):
raise ConfigError('Interface does not suport RPS!')
driver = EthernetIf(ifname).get_driver_name()
# T3342 - Xen driver requires special treatment
if driver == 'vif':
if int(ethernet['mtu']) > 1500 and dict_search('offload.sg', ethernet) == None:
raise ConfigError('Xen netback drivers requires scatter-gatter offloading '\
'for MTU size larger then 1500 bytes')
ethtool = Ethtool(ifname)
if 'ring_buffer' in ethernet:
max_rx = ethtool.get_rx_buffer()
if not max_rx:
raise ConfigError('Driver does not support RX ring-buffer configuration!')
max_tx = ethtool.get_tx_buffer()
if not max_tx:
raise ConfigError('Driver does not support TX ring-buffer configuration!')
rx = dict_search('ring_buffer.rx', ethernet)
if rx and int(rx) > int(max_rx):
raise ConfigError(f'Driver only supports a maximum RX ring-buffer '\
f'size of "{max_rx}" bytes!')
tx = dict_search('ring_buffer.tx', ethernet)
if tx and int(tx) > int(max_tx):
raise ConfigError(f'Driver only supports a maximum TX ring-buffer '\
f'size of "{max_tx}" bytes!')
# XDP requires multiple TX queues
if 'xdp' in ethernet:
queues = glob(f'/sys/class/net/{ifname}/queues/tx-*')
if len(queues) < 2:
raise ConfigError('XDP requires additional TX queues, too few available!')
if {'is_bond_member', 'mac'} <= set(ethernet):
print(f'WARNING: changing mac address "{mac}" will be ignored as "{ifname}" '
f'is a member of bond "{is_bond_member}"'.format(**ethernet))
# use common function to verify VLAN configuration
verify_vlan_config(ethernet)
return None
def generate(ethernet):
if 'eapol' in ethernet:
render(wpa_suppl_conf.format(**ethernet),
'ethernet/wpa_supplicant.conf.tmpl', ethernet)
+
+ ifname = ethernet['ifname']
+ cert_file_path = os.path.join(cfg_dir, f'{ifname}_cert.pem')
+ cert_key_path = os.path.join(cfg_dir, f'{ifname}_cert.key')
+
+ cert_name = ethernet['eapol']['certificate']
+ pki_cert = ethernet['pki']['certificate'][cert_name]
+
+ with open(cert_file_path, 'w') as f:
+ f.write(wrap_certificate(pki_cert['certificate']))
+
+ with open(cert_key_path, 'w') as f:
+ f.write(wrap_private_key(pki_cert['private']['key']))
+
+ if 'ca_certificate' in ethernet['eapol']:
+ ca_cert_file_path = os.path.join(cfg_dir, f'{ifname}_ca.pem')
+ ca_cert_name = ethernet['eapol']['ca_certificate']
+ pki_ca_cert = ethernet['pki']['ca'][cert_name]
+
+ with open(ca_cert_file_path, 'w') as f:
+ f.write(wrap_certificate(pki_ca_cert['certificate']))
else:
# delete configuration on interface removal
if os.path.isfile(wpa_suppl_conf.format(**ethernet)):
os.unlink(wpa_suppl_conf.format(**ethernet))
return None
def apply(ethernet):
ifname = ethernet['ifname']
# take care about EAPoL supplicant daemon
eapol_action='stop'
e = EthernetIf(ifname)
if 'deleted' in ethernet:
# delete interface
e.remove()
else:
e.update(ethernet)
if 'eapol' in ethernet:
eapol_action='restart'
call(f'systemctl {eapol_action} wpa_supplicant-macsec@{ifname}')
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/migration-scripts/interfaces/22-to-23 b/src/migration-scripts/interfaces/22-to-23
index c6dc32baf..3fd5998a0 100755
--- a/src/migration-scripts/interfaces/22-to-23
+++ b/src/migration-scripts/interfaces/22-to-23
@@ -1,64 +1,158 @@
#!/usr/bin/env python3
#
# Copyright (C) 2021 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/>.
# Migrate Wireguard to store keys in CLI
+# Migrate EAPoL to PKI configuration
import os
import sys
from vyos.configtree import ConfigTree
+from vyos.pki import load_certificate
+from vyos.pki import load_private_key
+from vyos.pki import encode_certificate
+from vyos.pki import encode_private_key
-if __name__ == '__main__':
- if (len(sys.argv) < 1):
- print("Must specify file name!")
- sys.exit(1)
+def wrapped_pem_to_config_value(pem):
+ return "".join(pem.strip().split("\n")[1:-1])
- file_name = sys.argv[1]
+if (len(sys.argv) < 1):
+ print("Must specify file name!")
+ sys.exit(1)
- with open(file_name, 'r') as f:
- config_file = f.read()
+file_name = sys.argv[1]
- config = ConfigTree(config_file)
- base = ['interfaces', 'wireguard']
- if not config.exists(base):
- # Nothing to do
- sys.exit(0)
+with open(file_name, 'r') as f:
+ config_file = f.read()
+config = ConfigTree(config_file)
+
+# Wireguard
+base = ['interfaces', 'wireguard']
+
+if config.exists(base):
for interface in config.list_nodes(base):
private_key_path = base + [interface, 'private-key']
key_file = 'default'
if config.exists(private_key_path):
key_file = config.return_value(private_key_path)
full_key_path = f'/config/auth/wireguard/{key_file}/private.key'
if not os.path.exists(full_key_path):
print(f'Could not find wireguard private key for migration on interface "{interface}"')
continue
with open(full_key_path, 'r') as f:
key_data = f.read().strip()
config.set(private_key_path, value=key_data)
for peer in config.list_nodes(base + [interface, 'peer']):
config.rename(base + [interface, 'peer', peer, 'pubkey'], 'public-key')
- try:
- with open(file_name, 'w') as f:
- f.write(config.to_string())
- except OSError as e:
- print("Failed to save the modified config: {}".format(e))
- sys.exit(1)
+# Ethernet EAPoL
+base = ['interfaces', 'ethernet']
+
+if config.exists(base):
+ AUTH_DIR = '/config/auth'
+ pki_base = ['pki']
+
+ for interface in config.list_nodes(base):
+ if not config.exists(base + [interface, 'eapol']):
+ continue
+
+ x509_base = base + [interface, 'eapol']
+ pki_name = f'eapol_{interface}'
+
+ if config.exists(x509_base + ['ca-cert-file']):
+ if not config.exists(pki_base + ['ca']):
+ config.set(pki_base + ['ca'])
+ config.set_tag(pki_base + ['ca'])
+
+ cert_file = config.return_value(x509_base + ['ca-cert-file'])
+ cert_path = os.path.join(AUTH_DIR, cert_file)
+ cert = None
+
+ if os.path.isfile(cert_path):
+ if not os.access(cert_path, os.R_OK):
+ run(f'sudo chmod 644 {cert_path}')
+
+ with open(cert_path, 'r') as f:
+ cert_data = f.read()
+ cert = load_certificate(cert_data, wrap_tags=False)
+
+ if cert:
+ cert_pem = encode_certificate(cert)
+ config.set(pki_base + ['ca', pki_name, 'certificate'], value=wrapped_pem_to_config_value(cert_pem))
+ config.set(x509_base + ['ca-certificate'], value=pki_name)
+ else:
+ print(f'Failed to migrate CA certificate on eapol config for interface {interface}')
+
+ config.delete(x509_base + ['ca-cert-file'])
+
+ if config.exists(x509_base + ['cert-file']):
+ if not config.exists(pki_base + ['certificate']):
+ config.set(pki_base + ['certificate'])
+ config.set_tag(pki_base + ['certificate'])
+
+ cert_file = config.return_value(x509_base + ['cert-file'])
+ cert_path = os.path.join(AUTH_DIR, cert_file)
+ cert = None
+
+ if os.path.isfile(cert_path):
+ if not os.access(cert_path, os.R_OK):
+ run(f'sudo chmod 644 {cert_path}')
+
+ with open(cert_path, 'r') as f:
+ cert_data = f.read()
+ cert = load_certificate(cert_data, wrap_tags=False)
+
+ if cert:
+ cert_pem = encode_certificate(cert)
+ config.set(pki_base + ['certificate', pki_name, 'certificate'], value=wrapped_pem_to_config_value(cert_pem))
+ config.set(x509_base + ['certificate'], value=pki_name)
+ else:
+ print(f'Failed to migrate certificate on eapol config for interface {interface}')
+
+ config.delete(x509_base + ['cert-file'])
+
+ if config.exists(x509_base + ['key-file']):
+ key_file = config.return_value(x509_base + ['key-file'])
+ key_path = os.path.join(AUTH_DIR, key_file)
+ key = None
+
+ if os.path.isfile(key_path):
+ if not os.access(key_path, os.R_OK):
+ run(f'sudo chmod 644 {key_path}')
+
+ with open(key_path, 'r') as f:
+ key_data = f.read()
+ key = load_private_key(key_data, passphrase=None, wrap_tags=False)
+
+ if key:
+ key_pem = encode_private_key(key, passphrase=None)
+ config.set(pki_base + ['certificate', pki_name, 'private', 'key'], value=wrapped_pem_to_config_value(key_pem))
+ else:
+ print(f'Failed to migrate private key on eapol config for interface {interface}')
+
+ config.delete(x509_base + ['key-file'])
+
+try:
+ with open(file_name, 'w') as f:
+ f.write(config.to_string())
+except OSError as e:
+ print("Failed to save the modified config: {}".format(e))
+ sys.exit(1)
File Metadata
Details
Attached
Mime Type
text/x-diff
Expires
Thu, Nov 26, 9:31 PM (6 m, 33 s)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
4987744
Default Alt Text
(47 KB)
Attached To
Mode
rVYOSONEX vyos-1x
Attached
Detach File
Event Timeline
Log In to Comment